Skip to content

Commit a989d71

Browse files
committed
doc: add howto for the new expect() method
1 parent 87de827 commit a989d71

File tree

2 files changed

+48
-0
lines changed

2 files changed

+48
-0
lines changed

doc/howto.rst

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -238,6 +238,17 @@ these.
238238
the server.
239239

240240

241+
Using custom request matcher
242+
----------------------------
243+
In the case when you want to extend or modify the request matcher in
244+
*pytest-httpserrver*, then you can use your own request matcher.
245+
246+
Example:
247+
248+
.. literalinclude :: ../tests/examples/test_howto_custom_request_matcher.py
249+
:language: python
250+
251+
241252
Customizing host and port
242253
-------------------------
243254

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
import requests
2+
from werkzeug import Request
3+
4+
from pytest_httpserver import HTTPServer
5+
from pytest_httpserver import RequestMatcher
6+
7+
8+
class MyMatcher(RequestMatcher):
9+
def match(self, request: Request) -> bool:
10+
match = super().match(request)
11+
if not match: # existing parameters didn't match -> return with False
12+
return match
13+
14+
# match the json's "value" key: if it is an integer and it is an even
15+
# number, it returns True
16+
json = request.json
17+
if isinstance(json, dict) and isinstance(json.get("value"), int):
18+
return json["value"] % 2 == 0
19+
20+
return False
21+
22+
23+
def test_custom_request_matcher(httpserver: HTTPServer):
24+
httpserver.expect(MyMatcher("/foo")).respond_with_data("OK")
25+
26+
# with even number it matches the request
27+
resp = requests.post(httpserver.url_for("/foo"), json={"value": 42})
28+
resp.raise_for_status()
29+
assert resp.text == "OK"
30+
31+
resp = requests.post(httpserver.url_for("/foo"), json={"value": 198})
32+
resp.raise_for_status()
33+
assert resp.text == "OK"
34+
35+
# with an odd number, it does not match the request
36+
resp = requests.post(httpserver.url_for("/foo"), json={"value": 43})
37+
assert resp.status_code == 500

0 commit comments

Comments
 (0)