diff --git a/doc/howto.rst b/doc/howto.rst index aac9857..93e47c2 100644 --- a/doc/howto.rst +++ b/doc/howto.rst @@ -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 ------------------------- diff --git a/tests/examples/test_howto_custom_request_matcher.py b/tests/examples/test_howto_custom_request_matcher.py new file mode 100644 index 0000000..ddec11c --- /dev/null +++ b/tests/examples/test_howto_custom_request_matcher.py @@ -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