Skip to content

Commit ce73526

Browse files
author
ada-wh525
committed
Add support for successive responses from an iterable
1 parent b7a8731 commit ce73526

5 files changed

Lines changed: 138 additions & 0 deletions

File tree

‎doc/howto.rst‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -288,6 +288,29 @@ names; a ``defaultdict`` can supply a fallback comparator without caching those
288288
names. Create a new matcher to use a changed mapping. Instances do not read or
289289
modify ``HeaderValueMatcher.DEFAULT_MATCHERS`` and do not share a registry.
290290

291+
Returning successive responses
292+
------------------------------
293+
294+
To simulate retries or a changing endpoint, use
295+
:py:meth:`~pytest_httpserver.RequestHandler.respond_multiple` with
296+
an iterable of Werkzeug ``Response`` objects:
297+
298+
.. literalinclude:: ../tests/test_multiple_responses.py
299+
:language: python
300+
:pyobject: test_multiple_responses
301+
302+
Each matching request consumes the next response. Generators are consumed lazily,
303+
and ``itertools.cycle`` can provide a repeating sequence. When the iterable is
304+
exhausted, further matching requests return HTTP 500 and ``httpserver.check()``
305+
raises an assertion explaining that there are no responses left. An empty
306+
iterable fails on the first matching request. Unused responses are not checked
307+
by ``httpserver.check()``.
308+
309+
Register the sequence with ``expect_request``. Oneshot and ordered handlers
310+
still serve only one request, even when given multiple responses. Existing
311+
handler priorities are unchanged: an exhausted permanent handler remains
312+
registered and does not fall through to another handler.
313+
291314
Using custom request handler
292315
----------------------------
293316
In the case the response is not static, for example it depends on the request,

‎pytest_httpserver/httpserver.py‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -656,6 +656,33 @@ def respond_with_handler(self, func: Callable[[Request], Response]) -> None:
656656
def respond_with_response(self, response: Response) -> None:
657657
self.request_handler = lambda request: response
658658

659+
def respond_multiple(self, responses: Iterable[Response]) -> None:
660+
"""
661+
Respond to successive matching requests with successive responses.
662+
663+
The iterable is consumed lazily, once per matching request. When it is
664+
exhausted, further matching requests fail with an assertion recorded by
665+
:py:meth:`HTTPServer.check`. Responses must be Werkzeug response objects.
666+
667+
Use with :py:meth:`HTTPServer.expect_request` to serve multiple requests.
668+
Oneshot and ordered handlers still handle only one request.
669+
670+
:param responses: an iterable of response objects, possibly infinite
671+
"""
672+
iterator = iter(responses)
673+
674+
def respond(request: Request) -> Response:
675+
try:
676+
response = next(iterator)
677+
except StopIteration:
678+
message = f"No responses left for matching request: {request.method} {request.path}"
679+
raise AssertionError(message) from None
680+
if not isinstance(response, Response):
681+
raise TypeError("respond_multiple expects Werkzeug Response objects")
682+
return response
683+
684+
self.respond_with_handler(respond)
685+
659686
def __repr__(self) -> str:
660687
class_name = self.__class__.__name__
661688
retval = (
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
---
2+
features:
3+
- |
4+
Add ``RequestHandler.respond_multiple`` to serve successive Werkzeug responses
5+
from an iterable for successive matching requests. Supports lazy generators
6+
and infinite iterables; exhausted sequences produce an assertion failure.

‎tests/test_multiple_responses.py‎

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
from itertools import cycle
2+
3+
import pytest
4+
import requests
5+
from werkzeug import Request
6+
from werkzeug import Response
7+
8+
from pytest_httpserver import HTTPServer
9+
10+
11+
def test_multiple_responses(httpserver: HTTPServer):
12+
httpserver.expect_request("/retry").respond_multiple(
13+
[
14+
Response("unavailable", status=503),
15+
Response("OK", headers={"X-Result": "success"}),
16+
]
17+
)
18+
first = requests.get(httpserver.url_for("/retry"))
19+
second = requests.get(httpserver.url_for("/retry"))
20+
assert (first.status_code, first.text) == (503, "unavailable")
21+
assert (second.status_code, second.text) == (200, "OK")
22+
assert second.headers["X-Result"] == "success"
23+
httpserver.check()
24+
25+
26+
@pytest.mark.parametrize("responses", [[], [Response("OK")]])
27+
def test_exhausted_responses(httpserver: HTTPServer, responses):
28+
httpserver.expect_request("/").respond_multiple(responses)
29+
for _ in responses:
30+
assert requests.get(httpserver.url_for("/")).status_code == 200
31+
assert requests.get(httpserver.url_for("/")).status_code == 500
32+
with pytest.raises(AssertionError, match="No responses left for matching request: GET /"):
33+
httpserver.check()
34+
httpserver.check_handler_errors()
35+
36+
37+
def test_lazy_generator_and_matching(httpserver: HTTPServer):
38+
consumed = []
39+
40+
def responses():
41+
for text in ["first", "second"]:
42+
consumed.append(text)
43+
yield Response(text)
44+
45+
httpserver.expect_request("/sequence").respond_multiple(responses())
46+
httpserver.expect_request("/other").respond_with_data("other")
47+
assert consumed == []
48+
requests.get(httpserver.url_for("/other"))
49+
assert consumed == []
50+
assert requests.get(httpserver.url_for("/sequence")).text == "first"
51+
assert consumed == ["first"]
52+
assert requests.get(httpserver.url_for("/sequence")).text == "second"
53+
httpserver.check()
54+
55+
56+
def test_infinite_responses_and_post_hook(httpserver: HTTPServer):
57+
def hook(_request: Request, response: Response) -> Response:
58+
response.headers["X-Hook"] = "called"
59+
return response
60+
61+
httpserver.expect_request("/").with_post_hook(hook).respond_multiple(cycle([Response("a"), Response("b")]))
62+
results = [requests.get(httpserver.url_for("/")) for _ in range(5)]
63+
assert [response.text for response in results] == ["a", "b", "a", "b", "a"]
64+
assert all(response.headers["X-Hook"] == "called" for response in results)
65+
httpserver.check()
66+
67+
68+
def test_invalid_response(httpserver: HTTPServer):
69+
httpserver.expect_request("/").respond_multiple(iter([None])) # type: ignore[arg-type]
70+
assert requests.get(httpserver.url_for("/")).status_code == 500
71+
with pytest.raises(TypeError, match="respond_multiple expects Werkzeug Response objects"):
72+
httpserver.check_handler_errors()
73+
74+
75+
@pytest.mark.parametrize("method", ["expect_oneshot_request", "expect_ordered_request"])
76+
def test_single_use_handlers(httpserver: HTTPServer, method):
77+
getattr(httpserver, method)("/").respond_multiple([Response("first"), Response("second")])
78+
httpserver.expect_request("/").respond_with_data("fallback")
79+
assert requests.get(httpserver.url_for("/")).text == "first"
80+
assert requests.get(httpserver.url_for("/")).text == "fallback"
81+
httpserver.check()

‎tests/test_release.py‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -222,6 +222,7 @@ def test_sdist_contents(build: Build, version: str):
222222
"test_log_leak.py",
223223
"test_log_querying.py",
224224
"test_mixed.py",
225+
"test_multiple_responses.py",
225226
"test_oneshot.py",
226227
"test_ordered.py",
227228
"test_permanent.py",

0 commit comments

Comments
 (0)