Skip to content

Commit

Permalink
doc: add howto for the new expect() method
Browse files Browse the repository at this point in the history
  • Loading branch information
csernazs committed Jan 21, 2025
1 parent 87de827 commit a989d71
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 0 deletions.
11 changes: 11 additions & 0 deletions doc/howto.rst
Original file line number Diff line number Diff line change
Expand Up @@ -238,6 +238,17 @@ these.
the server.


Using custom request matcher
----------------------------
In the case when you want to extend or modify the request matcher in
*pytest-httpserrver*, then you can use your own request matcher.

Example:

.. literalinclude :: ../tests/examples/test_howto_custom_request_matcher.py
:language: python
Customizing host and port
-------------------------

Expand Down
37 changes: 37 additions & 0 deletions tests/examples/test_howto_custom_request_matcher.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import requests
from werkzeug import Request

from pytest_httpserver import HTTPServer
from pytest_httpserver import RequestMatcher


class MyMatcher(RequestMatcher):
def match(self, request: Request) -> bool:
match = super().match(request)
if not match: # existing parameters didn't match -> return with False
return match

# match the json's "value" key: if it is an integer and it is an even
# number, it returns True
json = request.json
if isinstance(json, dict) and isinstance(json.get("value"), int):
return json["value"] % 2 == 0

return False


def test_custom_request_matcher(httpserver: HTTPServer):
httpserver.expect(MyMatcher("/foo")).respond_with_data("OK")

# with even number it matches the request
resp = requests.post(httpserver.url_for("/foo"), json={"value": 42})
resp.raise_for_status()
assert resp.text == "OK"

resp = requests.post(httpserver.url_for("/foo"), json={"value": 198})
resp.raise_for_status()
assert resp.text == "OK"

# with an odd number, it does not match the request
resp = requests.post(httpserver.url_for("/foo"), json={"value": 43})
assert resp.status_code == 500

0 comments on commit a989d71

Please sign in to comment.