|
| 1 | +import threading |
| 2 | +from queue import Queue |
| 3 | + |
| 4 | +import pytest |
| 5 | +import requests |
| 6 | + |
| 7 | +from pytest_httpserver import BlockingHTTPServer |
| 8 | + |
| 9 | +# override httpserver fixture |
| 10 | + |
| 11 | + |
| 12 | +@pytest.fixture |
| 13 | +def httpserver(): |
| 14 | + server = BlockingHTTPServer(timeout=1) |
| 15 | + server.start() |
| 16 | + |
| 17 | + yield server |
| 18 | + |
| 19 | + server.clear() |
| 20 | + if server.is_running(): |
| 21 | + server.stop() |
| 22 | + |
| 23 | + |
| 24 | +def test_simplified(httpserver: BlockingHTTPServer): |
| 25 | + def client(response_queue: Queue): |
| 26 | + response = requests.get(httpserver.url_for("/foobar"), timeout=10) |
| 27 | + response_queue.put(response) |
| 28 | + |
| 29 | + # start the client, server is not yet configured |
| 30 | + # it will block until we add a request handler to the server |
| 31 | + # (see the timeout parameter of the http server) |
| 32 | + response_queue: Queue[requests.models.Response] = Queue(maxsize=1) |
| 33 | + thread = threading.Thread(target=client, args=(response_queue,)) |
| 34 | + thread.start() |
| 35 | + |
| 36 | + try: |
| 37 | + # check that the request is for /foobar and it is a GET method |
| 38 | + # if this does not match, it will raise AssertionError and test will fail |
| 39 | + client_connection = httpserver.assert_request(uri="/foobar", method="GET") |
| 40 | + |
| 41 | + # with the received client_connection, we now need to send back the response |
| 42 | + # this makes the request.get() call in client() to return |
| 43 | + client_connection.respond_with_json({"foo": "bar"}) |
| 44 | + |
| 45 | + finally: |
| 46 | + # wait for the client thread to complete |
| 47 | + thread.join(timeout=1) |
| 48 | + assert not thread.is_alive() # check if join() has not timed out |
| 49 | + |
| 50 | + # check the response the client received |
| 51 | + response = response_queue.get(timeout=1) |
| 52 | + assert response.status_code == 200 |
| 53 | + assert response.json() == {"foo": "bar"} |
0 commit comments