Skip to content
Open
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
19 changes: 19 additions & 0 deletions doc/howto.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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
-------------------

Expand Down
24 changes: 24 additions & 0 deletions tests/examples/test_howto_json_fallback.py
Original file line number Diff line number Diff line change
@@ -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()
Loading