|
| 1 | +import requests |
| 2 | + |
| 3 | +from pytest_httpserver import HTTPServer |
| 4 | +from pytest_httpserver import RequestMatcher |
| 5 | + |
| 6 | + |
| 7 | +def test_log_querying_example(httpserver: HTTPServer): |
| 8 | + # set up the handler for the request |
| 9 | + httpserver.expect_request("/foo").respond_with_data("OK") |
| 10 | + |
| 11 | + # make a request matching the handler |
| 12 | + assert requests.get(httpserver.url_for("/foo")).text == "OK", "Response should be 'OK'" |
| 13 | + |
| 14 | + # make another request non-matching and handler |
| 15 | + assert ( |
| 16 | + requests.get(httpserver.url_for("/no_match")).status_code == 500 |
| 17 | + ), "Response code should be 500 for non-matched requests" |
| 18 | + |
| 19 | + # you can query the log directly |
| 20 | + # log will contain all request-response pair, including non-matching |
| 21 | + # requests and their response as well |
| 22 | + assert len(httpserver.log) == 2, "2 request-response pairs should be in the log" |
| 23 | + |
| 24 | + # there are the following methods to query the log |
| 25 | + # |
| 26 | + # each one uses the matcher we created for the handler in the very beginning |
| 27 | + # of this test, RequestMatcher accepts the same parameters what you were |
| 28 | + # specifying to the `expect_request` (and similar) methods. |
| 29 | + |
| 30 | + # 1. get counts |
| 31 | + # (returns 0 for non-matches) |
| 32 | + httpserver.get_matching_requests_count( |
| 33 | + RequestMatcher("/foo") |
| 34 | + ) == 1, "There should be one request matching the the /foo request" |
| 35 | + |
| 36 | + # 2. assert for matching request counts |
| 37 | + # by default it asserts for exactly 1 matches |
| 38 | + # it is roughly the same as: |
| 39 | + # ``` |
| 40 | + # assert httpserver.get_matching_requests_count(...) == 1 |
| 41 | + # ``` |
| 42 | + # assertion text will be a fully-detailed explanation about the error, including |
| 43 | + # the similar handlers (which might have been inproperly configured) |
| 44 | + httpserver.assert_request_made(RequestMatcher("/foo")) |
| 45 | + |
| 46 | + # you can also specify the counts |
| 47 | + # if you want, you can specify 0 to check for non-matching requests |
| 48 | + |
| 49 | + # there should have been 0 requests for /bar |
| 50 | + httpserver.assert_request_made(RequestMatcher("/bar"), count=0) |
| 51 | + |
| 52 | + # 3. iterate over the matching request-response pairs |
| 53 | + # this provides you greater flexibility |
| 54 | + for request, response in httpserver.iter_matching_requests(RequestMatcher("/foo")): |
| 55 | + assert request.url == httpserver.url_for("/foo") |
| 56 | + assert response.get_data() == b"OK" |
0 commit comments