import pytest from django.test import Client from rest_framework import status from rest_framework.test import APIClient class TestUnmatchedApiPaths: @pytest.mark.parametrize("method", ["get", "post", "put", "patch", "delete"]) def test_unmatched_api_path_is_a_json_404( self, rest_api_client: APIClient, method: str, ) -> None: """ GIVEN: - An unauthenticated client WHEN: - Any method is sent to an /api/ URL that no route matches THEN: - The response is a JSON 404, not a redirect to the login page """ response = getattr(rest_api_client, method)("/api/this_does_not_exist/") assert response.status_code == status.HTTP_404_NOT_FOUND assert response["Content-Type"].startswith("application/json") def test_unmatched_api_path_is_a_json_404_when_authenticated( self, admin_client: APIClient, ) -> None: """ GIVEN: - An authenticated client WHEN: - An /api/ URL that no route matches is requested THEN: - The response is a JSON 404, not the frontend page """ response = admin_client.get("/api/this/is/nested/and/missing/") assert response.status_code == status.HTTP_404_NOT_FOUND assert response["Content-Type"].startswith("application/json") def test_other_paths_still_reach_the_frontend_catch_all( self, client: Client, ) -> None: """ GIVEN: - An anonymous browser request WHEN: - A non-API path is requested THEN: - The frontend catch-all still applies, which sends the user to log in """ response = client.get("/documents/") assert response.status_code == status.HTTP_302_FOUND assert "login" in response["Location"] class TestDocumentRouteIds: @pytest.mark.parametrize( "action", [ "download", "history", "metadata", "notes", "preview", "root", "share_links", "suggestions", "thumb", ], ) @pytest.mark.parametrize("pk", ["null", "true", "abc", "0.5", "%20"]) def test_non_numeric_document_id_is_a_json_404( self, admin_client: APIClient, action: str, pk: str, ) -> None: """ GIVEN: - An authenticated client WHEN: - A document sub-route is requested with an id that is not a number THEN: - The response is a JSON 404, not a server error """ response = admin_client.get(f"/api/documents/{pk}/{action}/") assert response.status_code == status.HTTP_404_NOT_FOUND assert response["Content-Type"].startswith("application/json")