diff --git a/doc/howto.rst b/doc/howto.rst index d2049a3..af119c4 100644 --- a/doc/howto.rst +++ b/doc/howto.rst @@ -769,6 +769,25 @@ fixture so you can keep the original single-threaded behavior. described above. +Returning JSON for unknown URLs +------------------------------- + +If an API returns JSON for unknown URLs, register a persistent catch-all +handler after the specific persistent handlers: + +.. literalinclude :: ../tests/examples/test_howto_json_fallback.py + :language: python + +Persistent handlers are checked in registration order. Registering the +catch-all last lets the specific handlers respond first. The fallback can +return any JSON body and status code required by your API. + +A request served by this fallback has matched a handler, so +``check_assertions()`` does not report it as an unexpected request. If +unexpected requests should fail the test, omit the catch-all and keep the +normal unmatched-request checks. + + Adding side effects ------------------- diff --git a/tests/examples/test_howto_json_fallback.py b/tests/examples/test_howto_json_fallback.py new file mode 100644 index 0000000..e67bff6 --- /dev/null +++ b/tests/examples/test_howto_json_fallback.py @@ -0,0 +1,24 @@ +import re + +import requests + +from pytest_httpserver import HTTPServer + + +def test_json_fallback(httpserver: HTTPServer) -> None: + httpserver.expect_request("/known").respond_with_json({"message": "found"}) + + # Persistent handlers are checked in registration order: put this last. + httpserver.expect_request(re.compile(".*")).respond_with_json({"error": "not found"}, status=404) + + known = requests.get(httpserver.url_for("/known")) + assert known.status_code == 200 + assert known.json() == {"message": "found"} + + missing = requests.get(httpserver.url_for("/dynamic/missing")) + assert missing.status_code == 404 + assert missing.json() == {"error": "not found"} + assert missing.headers["Content-Type"] == "application/json" + + # The fallback is a matching handler, so these requests are not errors. + httpserver.check_assertions()