Skip to content

Commit 03e4f4a

Browse files
committed
Fix for tests
Use HTTPStatus enum for statuses
1 parent 0c6ab9d commit 03e4f4a

35 files changed

+484
-169
lines changed

findthatpostcode/areatypes.py

Lines changed: 210 additions & 28 deletions
Large diffs are not rendered by default.

findthatpostcode/blueprints/addtocsv.py

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import codecs
22
import os
33
import tempfile
4+
from http import HTTPStatus
45
from typing import Annotated
56

67
from fastapi import APIRouter, Form, HTTPException, Request, Response, UploadFile
@@ -67,10 +68,14 @@ def return_csv(
6768

6869
filename = csvfile.filename
6970
if not isinstance(filename, str):
70-
raise HTTPException(status_code=400, detail="No file uploaded.")
71+
raise HTTPException(
72+
status_code=HTTPStatus.BAD_REQUEST, detail="No file uploaded."
73+
)
7174
_, ext = os.path.splitext(filename)
7275
if ext not in [".csv"]:
73-
raise HTTPException(status_code=400, detail="File extension not allowed.")
76+
raise HTTPException(
77+
status_code=HTTPStatus.BAD_REQUEST, detail="File extension not allowed."
78+
)
7479

7580
with tempfile.SpooledTemporaryFile(mode="w+", newline="") as output:
7681
process_csv(

findthatpostcode/blueprints/areas.py

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import csv
22
import io
33
import re
4+
from http import HTTPStatus
45
from typing import Iterator
56

67
from fastapi import APIRouter, Request, Response
@@ -22,7 +23,7 @@ def area_search(request: Request, filetype="json", q: str | None = None) -> Resp
2223
redirect_url = request.url_for("search_index")
2324
if q:
2425
redirect_url = redirect_url.include_query_params(q=q)
25-
return RedirectResponse(redirect_url, status_code=301)
26+
return RedirectResponse(redirect_url, status_code=HTTPStatus.SEE_OTHER)
2627

2728

2829
@bp.get("/names.csv")
@@ -63,7 +64,7 @@ def get_area_boundary(areacodes: str, es: ElasticsearchDep, s3_client: S3Dep):
6364
areacode, es, boundary=True, examples_count=0, s3_client=s3_client
6465
)
6566
status, r = result.geoJSON()
66-
if status == 200 and isinstance(r, dict):
67+
if status == HTTPStatus.OK and isinstance(r, dict):
6768
features.extend(r.get("features", []))
6869
return {"type": "FeatureCollection", "features": features}
6970

@@ -82,14 +83,14 @@ def get_area_children_boundary(
8283
child_area.id, es, boundary=True, examples_count=0, s3_client=s3_client
8384
)
8485
status, r = result.geoJSON()
85-
if status == 200 and isinstance(r, dict):
86+
if status == HTTPStatus.OK and isinstance(r, dict):
8687
features.extend(r.get("features", []))
8788
else:
8889
errors[child_area.id] = r
8990
else:
9091
errors["area"] = f"No children of type {areatype} found for area {areacode}"
9192
if not features:
92-
return JSONResponse(dict(message=errors), status_code=404)
93+
return JSONResponse(dict(message=errors), status_code=HTTPStatus.NOT_FOUND)
9394
return {"type": "FeatureCollection", "features": features}
9495

9596

@@ -114,7 +115,7 @@ def get_area(
114115

115116
if filetype == "geojson":
116117
status, r = result.geoJSON()
117-
if status != 200:
118+
if status != HTTPStatus.OK:
118119
return JSONResponse(content={"message": r}, status_code=status)
119120
return JSONResponse(r)
120121

findthatpostcode/blueprints/areatypes.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
from http import HTTPStatus
2+
13
from fastapi import APIRouter, HTTPException, Request, Response
24

35
from findthatpostcode.blueprints.areas import areas_csv
@@ -44,7 +46,9 @@ def get_areatype(
4446
try:
4547
result = Areatype.get_from_es(areacode, es)
4648
except ValueError:
47-
raise HTTPException(status_code=404, detail="AreaType not found")
49+
raise HTTPException(
50+
status_code=HTTPStatus.NOT_FOUND, detail="AreaType not found"
51+
)
4852
pagination = Pagination(page=p, size=size)
4953
result.get_areas(es, pagination=pagination)
5054

findthatpostcode/blueprints/places.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
from http import HTTPStatus
2+
13
from fastapi import APIRouter, Request, Response
24
from fastapi.responses import JSONResponse, RedirectResponse
35

@@ -15,7 +17,7 @@
1517
def point_redirect(lat: float, lon: float, request: Request) -> Response:
1618
return RedirectResponse(
1719
request.url_for("places.nearest", lat=lat, lon=lon, filetype="html"),
18-
status_code=303,
20+
status_code=HTTPStatus.SEE_OTHER,
1921
)
2022

2123

@@ -35,7 +37,7 @@ def nearest(
3537
data = es.search(
3638
index=PLACENAME_INDEX,
3739
body=query,
38-
ignore=[404], # type: ignore
40+
ignore=[HTTPStatus.NOT_FOUND], # type: ignore
3941
size=10, # type: ignore
4042
_source_excludes=[], # type: ignore
4143
)

findthatpostcode/blueprints/points.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
from http import HTTPStatus
2+
13
from fastapi import APIRouter, Request, Response
24
from fastapi.responses import RedirectResponse
35

@@ -17,7 +19,7 @@ def point_redirect(lat: float, lon: float, request: Request) -> Response:
1719
request.url_for(
1820
"get_point", latlon="{},{}.html".format(lat, lon), filetype="html"
1921
),
20-
status_code=303,
22+
status_code=HTTPStatus.SEE_OTHER,
2123
)
2224

2325

findthatpostcode/blueprints/postcodes.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
from http import HTTPStatus
12
from typing import Annotated
23

34
from dictlib import dig_get
@@ -25,7 +26,7 @@
2526
def postcode_redirect(postcode: str, request: Request) -> Response:
2627
return RedirectResponse(
2728
request.url_for("get_postcode", postcode=postcode, filetype="html"),
28-
status_code=303,
29+
status_code=HTTPStatus.SEE_OTHER,
2930
)
3031

3132

@@ -87,7 +88,8 @@ def get_postcode_by_hash(
8788
for hash_ in hashes:
8889
if len(hash_) < 3:
8990
raise HTTPException(
90-
status_code=400, detail="Hash length must be at least 3 characters"
91+
status_code=HTTPStatus.UNPROCESSABLE_ENTITY,
92+
detail="Hash length must be at least 3 characters",
9193
)
9294
query.append(
9395
{

findthatpostcode/blueprints/process_csv.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
import csv
44
import io
5+
from http import HTTPStatus
56
from typing import Iterable
67

78
from elasticsearch import Elasticsearch
@@ -42,7 +43,7 @@ def process_csv(
4243
index=es_config.es_index,
4344
doc_type=es_config.es_type,
4445
id=postcode,
45-
ignore=[404], # type: ignore
46+
ignore=[HTTPStatus.NOT_FOUND], # type: ignore
4647
)
4748
if pc["found"]:
4849
for i in fields:
@@ -55,7 +56,7 @@ def process_csv(
5556
index=AREA_INDEX,
5657
doc_type=es_config.es_type,
5758
id=code,
58-
ignore=[404], # type: ignore
59+
ignore=[HTTPStatus.NOT_FOUND], # type: ignore
5960
_source_excludes=["boundary"], # type: ignore
6061
)
6162
if area["found"]:

findthatpostcode/blueprints/search.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import re
2+
from http import HTTPStatus
23

34
from fastapi import APIRouter, Request
45
from fastapi.responses import RedirectResponse
@@ -52,13 +53,13 @@ def search_index(
5253
"get_point",
5354
latlon="{},{}.html".format(latlon["lat"], latlon["lon"]), # type: ignore
5455
),
55-
status_code=303,
56+
status_code=HTTPStatus.SEE_OTHER,
5657
)
5758

5859
if is_postcode(q):
5960
return RedirectResponse(
6061
request.url_for("get_postcode", postcode=q, filetype="html"),
61-
status_code=303,
62+
status_code=HTTPStatus.SEE_OTHER,
6263
)
6364

6465
pagination = Pagination(page=p, size=size)

findthatpostcode/blueprints/utils.py

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
from http import HTTPStatus
2+
13
from fastapi import HTTPException, Request, Response
24

35
from findthatpostcode.controllers.controller import Controller
@@ -12,15 +14,18 @@ def return_result(
1214
**kwargs,
1315
) -> Response | dict:
1416
if filetype == "html" and not template:
15-
raise HTTPException(status_code=500, detail="No template provided")
17+
raise HTTPException(
18+
status_code=HTTPStatus.INTERNAL_SERVER_ERROR, detail="No template provided"
19+
)
1620
if template is not None and request is None:
1721
raise HTTPException(
18-
status_code=500, detail="No request provided for HTML response"
22+
status_code=HTTPStatus.INTERNAL_SERVER_ERROR,
23+
detail="No request provided for HTML response",
1924
)
2025

21-
status = 200 if result.found else 404
26+
status = HTTPStatus.OK if result.found else HTTPStatus.NOT_FOUND
2227

23-
if status != 200:
28+
if status != HTTPStatus.OK:
2429
errors = result.get_errors()
2530
if errors and errors[0].get("status"):
2631
status = int(errors[0]["status"])
@@ -45,4 +50,4 @@ def return_result(
4550
media_type="text/html",
4651
)
4752

48-
raise HTTPException(status_code=404, detail="Not found")
53+
raise HTTPException(status_code=HTTPStatus.NOT_FOUND, detail="Not found")

0 commit comments

Comments
 (0)