Skip to content

Commit b249413

Browse files
committed
doc: add howto for the new expect() method
1 parent d71bba2 commit b249413

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-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: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
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
15+
# if it it can be divided by 2, it returns True, False otherwise
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+
resp = requests.post(httpserver.url_for("/foo"), json={"value": 42})
27+
resp.raise_for_status()
28+
assert resp.text == "OK"
29+
30+
resp = requests.post(httpserver.url_for("/foo"), json={"value": 43})
31+
assert resp.status_code == 500

0 commit comments

Comments
 (0)