Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
5 changes: 5 additions & 0 deletions releasenotes/notes/new-expect-method-4f8d071c78c9884b.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
features:
- |
Add a new ``expect`` method to the ``HTTPServer`` object which allows
developers to provide their own request matcher object.
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
Loading