Skip to content

fix: handle form validation errors more robustly in document number extraction #199

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions doctor/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -435,6 +435,33 @@ def test_get_document_number(self):
self.assertEqual(doc_num, document_number)


class TestDocumentNumberExtraction(unittest.TestCase):
def test_get_document_number_invalid_form(self):
"""Test that we get a proper response when form validation fails"""
# Test with empty request
response = requests.post(
"http://doctor:5050/utils/document-number/pdf/",
)
self.assertEqual(response.status_code, 400, msg="Wrong status code")
self.assertIn(
"File is missing",
response.text,
msg="Wrong validation error message",
)

# Test with non-PDF file
with NamedTemporaryFile(suffix=".txt") as tmp:
tmp.write(b"This is not a PDF file")
tmp.flush()
tmp.seek(0)
files = {"file": (tmp.name, tmp.read())}
response = requests.post(
"http://doctor:5050/utils/document-number/pdf/",
files=files,
)
self.assertEqual(response.status_code, 400, msg="Wrong status code")


class RedactionTest(unittest.TestCase):
def test_xray_no_pdf(self):
"""Are we able to discover bad redacts?"""
Expand Down
17 changes: 13 additions & 4 deletions doctor/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -437,11 +437,20 @@ def get_document_number(request) -> HttpResponse:
:return: PACER document number
"""

form = BaseFileForm(request.GET, request.FILES)
form = BaseFileForm(request.POST, request.FILES)
if not form.is_valid():
validation_message = form.errors.get_json_data()["__all__"][0][
"message"
]
error_data = form.errors.get_json_data()
if "__all__" in error_data:
validation_message = error_data["__all__"][0]["message"]
elif "file" in error_data:
validation_message = error_data["file"][0]["message"]
else:
for field, errors in error_data.items():
if errors and errors[0]:
validation_message = errors[0]["message"]
break
else:
validation_message = "Form validation failed."
return HttpResponse(validation_message, status=BAD_REQUEST)
fp = form.cleaned_data["fp"]
document_number = get_document_number_from_pdf(fp)
Expand Down
Loading