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
18 changes: 14 additions & 4 deletions pytest_httpserver/httpserver.py
Original file line number Diff line number Diff line change
Expand Up @@ -598,6 +598,7 @@ class HTTPServerBase(abc.ABC): # pylint: disable=too-many-instance-attributes
:param host: the host or IP where the server will listen
:param port: the TCP port where the server will listen
:param ssl_context: the ssl context object to use for https connections
:param threaded: whether to handle concurrent requests in separate threads

.. py:attribute:: log

Expand All @@ -619,6 +620,8 @@ def __init__(
host: str,
port: int,
ssl_context: SSLContext | None = None,
*,
threaded: bool = False,
):
"""
Initializes the instance.
Expand All @@ -632,6 +635,7 @@ def __init__(
self.handler_errors: list[Exception] = []
self.log: list[tuple[Request, Response]] = []
self.ssl_context = ssl_context
self.threaded = threaded
self.no_handler_status_code = 500

def __repr__(self):
Expand Down Expand Up @@ -730,19 +734,21 @@ def start(self):
This method returns immediately (e.g. does not block), and it's the caller's
responsibility to stop the server (by calling :py:meth:`stop`) when it is no longer needed).

If the sever is not stopped by the caller and execution reaches the end, the
If the server is not stopped by the caller and execution reaches the end, the
program needs to be terminated by Ctrl+C or by signal as it will not terminate until
the thread is stopped.

If the sever is already running :py:class:`HTTPServerError` will be raised. If you are
If the server is already running :py:class:`HTTPServerError` will be raised. If you are
unsure, call :py:meth:`is_running` first.

There's a context interface of this class which stops the server when the context block ends.
"""
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=self.threaded
)
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()
Expand Down Expand Up @@ -900,6 +906,8 @@ class HTTPServer(HTTPServerBase): # pylint: disable=too-many-instance-attribute
:param default_waiting_settings: the waiting settings object to use as default settings for :py:meth:`wait` context
manager

:param threaded: whether to handle concurrent requests in separate threads

.. py:attribute:: no_handler_status_code

Attribute containing the http status code (int) which will be the response
Expand All @@ -916,11 +924,13 @@ def __init__(
port=DEFAULT_LISTEN_PORT,
ssl_context: SSLContext | None = None,
default_waiting_settings: WaitingSettings | None = None,
*,
threaded: bool = False,
):
"""
Initializes the instance.
"""
super().__init__(host, port, ssl_context)
super().__init__(host, port, ssl_context, threaded=threaded)

self.ordered_handlers: list[RequestHandler] = []
self.oneshot_handlers = RequestHandlerList()
Expand Down
1 change: 1 addition & 0 deletions tests/test_release.py
Original file line number Diff line number Diff line change
Expand Up @@ -220,6 +220,7 @@ def test_sdist_contents(build: Build, version: str):
"test_querystring.py",
"test_release.py",
"test_ssl.py",
"test_threaded.py",
"test_urimatch.py",
"test_wait.py",
"test_with_statement.py",
Expand Down
60 changes: 60 additions & 0 deletions tests/test_threaded.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import http.client
import threading
import time
from typing import Iterable

import pytest
from werkzeug.wrappers import Request
from werkzeug.wrappers import Response

from pytest_httpserver import HTTPServer


@pytest.fixture()
def threaded() -> Iterable[HTTPServer]:
server = HTTPServer(threaded=True)
server.start()
yield server
server.clear()
if server.is_running():
server.stop()


def test_threaded(threaded: HTTPServer):
sleep_time = 0.5

def handler(_request: Request):
# allow some time to the client to have multiple pending request
# handlers running in parallel
time.sleep(sleep_time)

# send back thread id
return Response(f"{threading.get_ident()}")

threaded.expect_request("/foo").respond_with_handler(handler)

t_start = time.perf_counter()

number_of_connections = 5
conns = [http.client.HTTPConnection(threaded.host, threaded.port) for _ in range(number_of_connections)]

for conn in conns:
conn.request("GET", "/foo", headers={"Host": threaded.host})

thread_ids: list[int] = []
for conn in conns:
response = conn.getresponse()

assert response.status == 200
thread_ids.append(int(response.read()))

for conn in conns:
conn.close()

t_elapsed = time.perf_counter() - t_start

assert len(thread_ids) == len(set(thread_ids)), "thread ids returned should be unique"

assert (
t_elapsed < number_of_connections * sleep_time * 0.9
), "elapsed time should be less than processing sequential requests"