Async support?
aodj opened this issue · 1 comments
Has anyone looked into running the server asynchronously?
I've got client code that runs using aiohttp
and when I'm testing connections that timeout (using httpserver.expect_request(f"/{path}", method="POST").respond_with_handler(timeout)
) it looks like the server hangs during the timeout period leaving the inbound async requests from tests to timeout.
Hi,
That's correct, although the server is running in a different thread, it serves the request in a single-threaded mode (this allows us to write the code for ordered handlers easier, and makes the working simpler). That means that only one request handler can run at each time and while it is serving, no other handlers can be run.
Werkzeug and the underlying library supports threaded handling, but this is not availalbe in the pytest-httpserver's API. However with this modification you can experiment with it:
diff --git a/pytest_httpserver/httpserver.py b/pytest_httpserver/httpserver.py
index 332cd3d..a00ea6d 100644
--- a/pytest_httpserver/httpserver.py
+++ b/pytest_httpserver/httpserver.py
@@ -872,7 +872,7 @@ class HTTPServer: # pylint: disable=too-many-instance-attributes
if self.is_running():
raise HTTPServerError("Server is already running")
- self.server = make_server(self.host, self.port, self.application, ssl_context=self.ssl_context)
+ self.server = make_server(self.host, self.port, self.application, ssl_context=self.ssl_context, threaded=True)
self.port = self.server.port # Update port (needed if `port` was set to 0)
self.server_thread = threading.Thread(target=self.thread_target)
self.server_thread.start()
I have not tried this but this idea comes from https://github.com/pallets/werkzeug/blob/main/src/werkzeug/serving.py#L746.
If it works for you, you can subclass from HTTPServer and override this method.
Asyncio support is not planned to pytest-httpserver, it would need a radical re-write I'm afraid.