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 5b581ac
Show file tree
Hide file tree
Showing 2 changed files with 42 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
31 changes: 31 additions & 0 deletions tests/examples/test_howto_custom_request_matcher.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
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 it can be divided by 2, it returns True, False otherwise
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")

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": 43})
assert resp.status_code == 500

0 comments on commit 5b581ac

Please sign in to comment.