|
| 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: if it is an integer and it is an even |
| 15 | + # number, it returns True |
| 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 | + # with even number it matches the request |
| 27 | + resp = requests.post(httpserver.url_for("/foo"), json={"value": 42}) |
| 28 | + resp.raise_for_status() |
| 29 | + assert resp.text == "OK" |
| 30 | + |
| 31 | + resp = requests.post(httpserver.url_for("/foo"), json={"value": 198}) |
| 32 | + resp.raise_for_status() |
| 33 | + assert resp.text == "OK" |
| 34 | + |
| 35 | + # with an odd number, it does not match the request |
| 36 | + resp = requests.post(httpserver.url_for("/foo"), json={"value": 43}) |
| 37 | + assert resp.status_code == 500 |
0 commit comments