API documentation

pytest_httpserver

This is package provides the main API for the pytest_httpserver package.

HTTPServer

class pytest_httpserver.HTTPServer(host='localhost', port=0, ssl_context: Optional[ssl.SSLContext, None] = None, default_waiting_settings: Optional[pytest_httpserver.httpserver.WaitingSettings, None] = None)

Server instance which manages handlers to serve pre-defined requests.

Parameters:
  • host – the host or IP where the server will listen
  • port – the TCP port where the server will listen
  • ssl_context – the ssl context object to use for https connections
  • default_waiting_settings – the waiting settings object to use as default settings for wait() context manager
no_handler_status_code

Attribute containing the http status code (int) which will be the response status when no matcher is found for the request. By default, it is set to 500 but it can be overridden to any valid http status code such as 404 if needed.

add_assertion(obj)

Add a new assertion

Assertions can be added here, and when check_assertions() is called, it will raise AssertionError for pytest with the object specified here.

Parameters:obj – An AssertionError, or an object which will be passed to an AssertionError.
application(request: werkzeug.wrappers.request.Request)

Entry point of werkzeug.

This method is called for each request, and it then calls the undecorated dispatch() method to serve the request.

Parameters:request – the request object from the werkzeug library
Returns:the response object what the dispatch returned
check()

Raises AssertionError or Errors raised in handlers.

Runs both check_assertions() and check_handler_errors()

check_assertions()

Raise AssertionError when at least one assertion added

The first assertion added by add_assertion() will be raised and it will be removed from the list.

This method can be useful to get some insights into the errors happened in the sever, and to have a proper error reporting in pytest.

check_handler_errors()

Re-Raises any errors caused in request handlers

The first error raised by a handler will be re-raised here, and then removed from the list.

clear()

Clears and resets the state attributes of the object.

This method is useful when the object needs to be re-used but stopping the server is not feasible.

clear_all_handlers()

Clears all types of the handlers (ordered, oneshot, permanent)

clear_assertions()

Clears the list of assertions

clear_handler_errors()

Clears the list of collected errors from handler invocations

clear_log()

Clears the list of log entries

create_matcher(*args, **kwargs) → pytest_httpserver.httpserver.RequestMatcher

Creates a RequestMatcher instance with the specified parameters.

This method can be overridden if you want to use your own matcher.

dispatch(request: werkzeug.wrappers.request.Request) → werkzeug.wrappers.response.Response

Dispatch a request to the appropriate request handler.

This method tries to find the request handler whose matcher matches the request, and then calls it in order to serve the request.

First, the request is checked for the ordered matchers. If there’s an ordered matcher, it must match the request, otherwise the server will be put into a permanent failure mode in which it makes all request failed - this is the intended way of working of ordered matchers.

Then oneshot handlers, and the permanent handlers are looked up.

Parameters:request – the request object from the werkzeug library
Returns:the response object what the handler responded, or a response which contains the error
expect_oneshot_request(uri: Union[str, pytest_httpserver.httpserver.URIPattern, Pattern[str]], method: str = '__ALL', data: Union[str, bytes, None] = None, data_encoding: str = 'utf-8', headers: Optional[Mapping[str, str], None] = None, query_string: Union[None, pytest_httpserver.httpserver.QueryMatcher, str, bytes, Mapping] = None, header_value_matcher: Optional[pytest_httpserver.httpserver.HeaderValueMatcher, None] = None, json: Any = <UNDEFINED>) → pytest_httpserver.httpserver.RequestHandler

Create and register a oneshot request handler.

This is a method for convenience. See expect_request() for documentation.

Parameters:
  • uri – URI of the request. This must be an absolute path starting with /, a URIPattern object, or a regular expression compiled by re.compile().
  • method – HTTP method of the request. If not specified (or METHOD_ALL specified), all HTTP requests will match.
  • data – payload of the HTTP request. This could be a string (utf-8 encoded by default, see data_encoding) or a bytes object.
  • data_encoding – the encoding used for data parameter if data is a string.
  • headers – dictionary of the headers of the request to be matched
  • query_string – the http query string, after ?, such as username=user. If string is specified it will be encoded to bytes with the encode method of the string. If dict is specified, it will be matched to the key=value pairs specified in the request. If multiple values specified for a given key, the first value will be used. If multiple values needed to be handled, use MultiDict object from werkzeug.
  • header_value_matcherHeaderValueMatcher that matches values of headers.
  • json – a python object (eg. a dict) whose value will be compared to the request body after it is loaded as json. If load fails, this matcher will be failed also. Content-Type is not checked. If that’s desired, add it to the headers parameter.
Returns:

Created and register RequestHandler.

Parameters json and data are mutually exclusive.

expect_ordered_request(uri: Union[str, pytest_httpserver.httpserver.URIPattern, Pattern[str]], method: str = '__ALL', data: Union[str, bytes, None] = None, data_encoding: str = 'utf-8', headers: Optional[Mapping[str, str], None] = None, query_string: Union[None, pytest_httpserver.httpserver.QueryMatcher, str, bytes, Mapping] = None, header_value_matcher: Optional[pytest_httpserver.httpserver.HeaderValueMatcher, None] = None, json: Any = <UNDEFINED>) → pytest_httpserver.httpserver.RequestHandler

Create and register a ordered request handler.

This is a method for convenience. See expect_request() for documentation.

Parameters:
  • uri – URI of the request. This must be an absolute path starting with /, a URIPattern object, or a regular expression compiled by re.compile().
  • method – HTTP method of the request. If not specified (or METHOD_ALL specified), all HTTP requests will match.
  • data – payload of the HTTP request. This could be a string (utf-8 encoded by default, see data_encoding) or a bytes object.
  • data_encoding – the encoding used for data parameter if data is a string.
  • headers – dictionary of the headers of the request to be matched
  • query_string – the http query string, after ?, such as username=user. If string is specified it will be encoded to bytes with the encode method of the string. If dict is specified, it will be matched to the key=value pairs specified in the request. If multiple values specified for a given key, the first value will be used. If multiple values needed to be handled, use MultiDict object from werkzeug.
  • header_value_matcherHeaderValueMatcher that matches values of headers.
  • json – a python object (eg. a dict) whose value will be compared to the request body after it is loaded as json. If load fails, this matcher will be failed also. Content-Type is not checked. If that’s desired, add it to the headers parameter.
Returns:

Created and register RequestHandler.

Parameters json and data are mutually exclusive.

expect_request(uri: Union[str, pytest_httpserver.httpserver.URIPattern, Pattern[str]], method: str = '__ALL', data: Union[str, bytes, None] = None, data_encoding: str = 'utf-8', headers: Optional[Mapping[str, str], None] = None, query_string: Union[None, pytest_httpserver.httpserver.QueryMatcher, str, bytes, Mapping] = None, header_value_matcher: Optional[pytest_httpserver.httpserver.HeaderValueMatcher, None] = None, handler_type: pytest_httpserver.httpserver.HandlerType = <HandlerType.PERMANENT: 'permanent'>, json: Any = <UNDEFINED>) → pytest_httpserver.httpserver.RequestHandler

Create and register a request handler.

If handler_type is HandlerType.PERMANENT a permanent request handler is created. This handler can be used as many times as the request matches it, but ordered handlers have higher priority so if there’s one or more ordered handler registered, those must be used first.

If handler_type is HandlerType.ONESHOT a oneshot request handler is created. This handler can be only used once. Once the server serves a response for this handler, the handler will be dropped.

If handler_type is HandlerType.ORDERED an ordered request handler is created. Comparing to oneshot handler, ordered handler also determines the order of the requests to be served. For example if there are two ordered handlers registered, the first request must hit the first handler, and the second request must hit the second one, and not vice versa. If one or more ordered handler defined, those must be exhausted first.

Parameters:
  • uri – URI of the request. This must be an absolute path starting with /, a URIPattern object, or a regular expression compiled by re.compile().
  • method – HTTP method of the request. If not specified (or METHOD_ALL specified), all HTTP requests will match. Case insensitive.
  • data – payload of the HTTP request. This could be a string (utf-8 encoded by default, see data_encoding) or a bytes object.
  • data_encoding – the encoding used for data parameter if data is a string.
  • headers – dictionary of the headers of the request to be matched
  • query_string – the http query string, after ?, such as username=user. If string is specified it will be encoded to bytes with the encode method of the string. If dict is specified, it will be matched to the key=value pairs specified in the request. If multiple values specified for a given key, the first value will be used. If multiple values needed to be handled, use MultiDict object from werkzeug.
  • header_value_matcherHeaderValueMatcher that matches values of headers.
  • handler_type – type of handler
  • json – a python object (eg. a dict) whose value will be compared to the request body after it is loaded as json. If load fails, this matcher will be failed also. Content-Type is not checked. If that’s desired, add it to the headers parameter.
Returns:

Created and register RequestHandler.

Parameters json and data are mutually exclusive.

static format_host(host)

Formats a hostname so it can be used in a URL. Notably, this adds brackets around IPV6 addresses when they are missing.

format_matchers() → str

Return a string representation of the matchers

This method returns a human-readable string representation of the matchers registered. You can observe which requests will be served, etc.

This method is primarily used when reporting errors.

is_running() → bool

Returns True when the server is running, otherwise False.

respond_nohandler(request: werkzeug.wrappers.request.Request, extra_message: str = '')

Add a ‘no handler’ assertion.

This method is called when the server wasn’t able to find any handler to serve the request. As the result, there’s an assertion added (which can be raised by check_assertions()).

respond_permanent_failure()

Add a ‘permanent failure’ assertion.

This assertion means that no further requests will be handled. This is the resuld of missing an ordered matcher.

start()

Start the server in a thread.

This method returns immediately (e.g. does not block), and it’s the caller’s responsibility to stop the server (by calling stop()) when it is no longer needed).

If the sever 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 HTTPServerError will be raised. If you are unsure, call is_running() first.

There’s a context interface of this class which stops the server when the context block ends.

stop()

Stop the running server.

Notifies the server thread about the intention of the stopping, and the thread will terminate itself. This needs about 0.5 seconds in worst case.

Only a running server can be stopped. If the sever is not running, :py:class`HTTPServerError` will be raised.

thread_target()

This method serves as a thread target when the server is started.

This should not be called directly, but can be overridden to tailor it to your needs.

url_for(suffix: str)

Return an url for a given suffix.

This basically means that it prepends the string http://$HOST:$PORT/ to the suffix parameter (where $HOST and $PORT are the parameters given to the constructor).

When host is an IPv6 address, the required square brackets will be added to it, forming a valid URL.

When SSL or TLS is in use, the protocol of the returned URL will be https.

Parameters:suffix – the suffix which will be added to the base url. It can start with / (slash) or not, the url will be the same.
Returns:the full url which refers to the server
wait(raise_assertions: Optional[bool, None] = None, stop_on_nohandler: Optional[bool, None] = None, timeout: Optional[float, None] = None)

Context manager to wait until the first of following event occurs: all ordered and oneshot handlers were executed, unexpected request was received (if stop_on_nohandler is set to True), or time was out

Parameters:
  • raise_assertions – whether raise assertions on unexpected request or timeout or not
  • stop_on_nohandler – whether stop on unexpected request or not
  • timeout – time (in seconds) until time is out

Example:

def test_wait(httpserver):
    httpserver.expect_oneshot_request("/").respond_with_data("OK")
    with httpserver.wait(
        raise_assertions=False, stop_on_nohandler=False, timeout=1
    ) as waiting:
        requests.get(httpserver.url_for("/"))
    # `waiting` is :py:class:`Waiting`
    assert waiting.result
    print("Elapsed time: {} sec".format(waiting.elapsed_time))

RequestHandler

class pytest_httpserver.RequestHandler(matcher: pytest_httpserver.httpserver.RequestMatcher)

Represents a response function and a RequestHandler object.

This class connects the matcher object with the function responsible for the response. The respond handler function can be registered with the respond_with_ methods.

Parameters:matcher – the matcher object
respond(request: werkzeug.wrappers.request.Request) → werkzeug.wrappers.response.Response

Calls the request handler registered for this object.

If no response was specified previously, it raises NoHandlerError exception.

Parameters:request – the incoming request object
Returns:the response object
respond_with_data(response_data: Union[str, bytes] = '', status: int = 200, headers: Union[Mapping[str, Union[str, int, Iterable[Union[str, int]]]], Iterable[Tuple[str, Union[str, int]]], None] = None, mimetype: Optional[str, None] = None, content_type: Optional[str, None] = None)

Prepares a response with raw data.

For detailed description please see the werkzeug.wrappers.Response object as the parameters are analogue.

Parameters:
  • response_data – a string or bytes object representing the body of the response
  • status – the HTTP status of the response
  • headers – the HTTP headers to be sent (excluding the Content-Type header)
  • content_type – the content type header to be sent
  • mimetype – the mime type of the request
respond_with_handler(func: Callable[[werkzeug.wrappers.request.Request], werkzeug.wrappers.response.Response])

Registers the specified function as a responder.

The function will receive the request object and must return with the response object.

respond_with_json(response_json, status: int = 200, headers: Optional[Mapping[str, str], None] = None, content_type: str = 'application/json')

Prepares a response with a serialized JSON object.

Parameters:
  • response_json – a JSON-serializable python object
  • status – the HTTP status of the response
  • headers – the HTTP headers to be sent (excluding the Content-Type header)
  • content_type – the content type header to be sent
respond_with_response(response: werkzeug.wrappers.response.Response)

Prepares a response with the specified response object.

Parameters:response – the response object which will be responded

BlockingHTTPServer

class pytest_httpserver.BlockingHTTPServer(host='localhost', port=0, ssl_context: Optional[ssl.SSLContext, None] = None, timeout: int = 30)

Server instance which enables synchronous matching for incoming requests.

Parameters:
  • host – the host or IP where the server will listen
  • port – the TCP port where the server will listen
  • ssl_context – the ssl context object to use for https connections
  • timeout – waiting time in seconds for matching and responding to an incoming request. manager
no_handler_status_code

Attribute containing the http status code (int) which will be the response status when no matcher is found for the request. By default, it is set to 500 but it can be overridden to any valid http status code such as 404 if needed.

add_assertion(obj)

Add a new assertion

Assertions can be added here, and when check_assertions() is called, it will raise AssertionError for pytest with the object specified here.

Parameters:obj – An AssertionError, or an object which will be passed to an AssertionError.
application(request: werkzeug.wrappers.request.Request)

Entry point of werkzeug.

This method is called for each request, and it then calls the undecorated dispatch() method to serve the request.

Parameters:request – the request object from the werkzeug library
Returns:the response object what the dispatch returned
assert_request(uri: Union[str, pytest_httpserver.httpserver.URIPattern, Pattern[str]], method: str = '__ALL', data: Union[str, bytes, None] = None, data_encoding: str = 'utf-8', headers: Optional[Mapping[str, str], None] = None, query_string: Union[None, pytest_httpserver.httpserver.QueryMatcher, str, bytes, Mapping] = None, header_value_matcher: Optional[pytest_httpserver.httpserver.HeaderValueMatcher, None] = None, json: Any = <UNDEFINED>, timeout: int = 30) → pytest_httpserver.blocking_httpserver.BlockingRequestHandler

Wait for an incoming request and check whether it matches according to the given parameters.

If the incoming request matches, a request handler is created and registered, otherwise assertion error is raised. The request handler can be used once to respond for the request. If no response is performed in the period given in the timeout parameter of the constructor or no request arrives in the timeout period, assertion error is raised.

Parameters:
  • uri – URI of the request. This must be an absolute path starting with /, a URIPattern object, or a regular expression compiled by re.compile().
  • method – HTTP method of the request. If not specified (or METHOD_ALL specified), all HTTP requests will match.
  • data – payload of the HTTP request. This could be a string (utf-8 encoded by default, see data_encoding) or a bytes object.
  • data_encoding – the encoding used for data parameter if data is a string.
  • headers – dictionary of the headers of the request to be matched
  • query_string – the http query string, after ?, such as username=user. If string is specified it will be encoded to bytes with the encode method of the string. If dict is specified, it will be matched to the key=value pairs specified in the request. If multiple values specified for a given key, the first value will be used. If multiple values needed to be handled, use MultiDict object from werkzeug.
  • header_value_matcherHeaderValueMatcher that matches values of headers.
  • json – a python object (eg. a dict) whose value will be compared to the request body after it is loaded as json. If load fails, this matcher will be failed also. Content-Type is not checked. If that’s desired, add it to the headers parameter.
  • timeout – waiting time in seconds for an incoming request.
Returns:

Created and registered BlockingRequestHandler.

Parameters json and data are mutually exclusive.

check()

Raises AssertionError or Errors raised in handlers.

Runs both check_assertions() and check_handler_errors()

check_assertions()

Raise AssertionError when at least one assertion added

The first assertion added by add_assertion() will be raised and it will be removed from the list.

This method can be useful to get some insights into the errors happened in the sever, and to have a proper error reporting in pytest.

check_handler_errors()

Re-Raises any errors caused in request handlers

The first error raised by a handler will be re-raised here, and then removed from the list.

clear()

Clears and resets the state attributes of the object.

This method is useful when the object needs to be re-used but stopping the server is not feasible.

clear_assertions()

Clears the list of assertions

clear_handler_errors()

Clears the list of collected errors from handler invocations

clear_log()

Clears the list of log entries

create_matcher(*args, **kwargs) → pytest_httpserver.httpserver.RequestMatcher

Creates a RequestMatcher instance with the specified parameters.

This method can be overridden if you want to use your own matcher.

dispatch(request: werkzeug.wrappers.request.Request) → werkzeug.wrappers.response.Response

Dispatch a request for synchronous matching.

This method queues the request for matching and waits for the request handler. If there was no request handler, error is responded, otherwise it waits for the response of request handler. If no response arrives, assertion error is raised, otherwise the response is returned.

Parameters:request – the request object from the werkzeug library.
Returns:the response object what the handler responded, or a response which contains the error.
static format_host(host)

Formats a hostname so it can be used in a URL. Notably, this adds brackets around IPV6 addresses when they are missing.

is_running() → bool

Returns True when the server is running, otherwise False.

respond_nohandler(request: werkzeug.wrappers.request.Request, extra_message: str = '')

Add a ‘no handler’ assertion.

This method is called when the server wasn’t able to find any handler to serve the request. As the result, there’s an assertion added (which can be raised by check_assertions()).

start()

Start the server in a thread.

This method returns immediately (e.g. does not block), and it’s the caller’s responsibility to stop the server (by calling stop()) when it is no longer needed).

If the sever 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 HTTPServerError will be raised. If you are unsure, call is_running() first.

There’s a context interface of this class which stops the server when the context block ends.

stop()

Stop the running server.

Notifies the server thread about the intention of the stopping, and the thread will terminate itself. This needs about 0.5 seconds in worst case.

Only a running server can be stopped. If the sever is not running, :py:class`HTTPServerError` will be raised.

thread_target()

This method serves as a thread target when the server is started.

This should not be called directly, but can be overridden to tailor it to your needs.

url_for(suffix: str)

Return an url for a given suffix.

This basically means that it prepends the string http://$HOST:$PORT/ to the suffix parameter (where $HOST and $PORT are the parameters given to the constructor).

When host is an IPv6 address, the required square brackets will be added to it, forming a valid URL.

When SSL or TLS is in use, the protocol of the returned URL will be https.

Parameters:suffix – the suffix which will be added to the base url. It can start with / (slash) or not, the url will be the same.
Returns:the full url which refers to the server

BlockingRequestHandler

class pytest_httpserver.BlockingRequestHandler

Provides responding to a request synchronously.

This class should only be instantiated inside the implementation of the BlockingHTTPServer.

respond_with_data(response_data: Union[str, bytes] = '', status: int = 200, headers: Union[Mapping[str, Union[str, int, Iterable[Union[str, int]]]], Iterable[Tuple[str, Union[str, int]]], None] = None, mimetype: Optional[str, None] = None, content_type: Optional[str, None] = None)

Prepares a response with raw data.

For detailed description please see the werkzeug.wrappers.Response object as the parameters are analogue.

Parameters:
  • response_data – a string or bytes object representing the body of the response
  • status – the HTTP status of the response
  • headers – the HTTP headers to be sent (excluding the Content-Type header)
  • content_type – the content type header to be sent
  • mimetype – the mime type of the request
respond_with_json(response_json, status: int = 200, headers: Optional[Mapping[str, str], None] = None, content_type: str = 'application/json')

Prepares a response with a serialized JSON object.

Parameters:
  • response_json – a JSON-serializable python object
  • status – the HTTP status of the response
  • headers – the HTTP headers to be sent (excluding the Content-Type header)
  • content_type – the content type header to be sent
respond_with_response(response: werkzeug.wrappers.response.Response)

Prepares a response with the specified response object.

Parameters:response – the response object which will be responded

WaitingSettings

class pytest_httpserver.WaitingSettings(raise_assertions: bool = True, stop_on_nohandler: bool = True, timeout: float = 5)

Class for providing default settings and storing them in HTTPServer

Parameters:
  • raise_assertions – whether raise assertions on unexpected request or timeout or not
  • stop_on_nohandler – whether stop on unexpected request or not
  • timeout – time (in seconds) until time is out

HeaderValueMatcher

class pytest_httpserver.HeaderValueMatcher(matchers: Optional[Mapping[str, Callable[[Optional[str, None], str], bool]], None] = None)

Matcher object for the header value of incoming request.

Parameters:matchers – mapping from header name to comparator function that accepts actual and expected header values and return whether they are equal as bool.

URIPattern

class pytest_httpserver.URIPattern
match(uri: str) → bool

Matches the provided URI.

Parameters:uri – URI of the request. This is an absolute path starting with “/” and does not contain the query part.
Returns:True if there’s a match, False otherwise

HTTPServerError

class pytest_httpserver.HTTPServerError

Raised when there’s a problem with HTTP server.

NoHandlerError

class pytest_httpserver.NoHandlerError

Raised when a RequestHandler has no registered method to serve the request.

pytest_httpserver.httpserver

This module contains some internal classes which are normally not instantiated by the user.

class pytest_httpserver.httpserver.RequestMatcher(uri: Union[str, pytest_httpserver.httpserver.URIPattern, Pattern[str]], method: str = '__ALL', data: Union[str, bytes, None] = None, data_encoding: str = 'utf-8', headers: Optional[Mapping[str, str], None] = None, query_string: Union[None, pytest_httpserver.httpserver.QueryMatcher, str, bytes, Mapping] = None, header_value_matcher: Optional[pytest_httpserver.httpserver.HeaderValueMatcher, None] = None, json: Any = <UNDEFINED>)

Matcher object for the incoming request.

It defines various parameters to match the incoming request.

Parameters:
  • uri – URI of the request. This must be an absolute path starting with /, a URIPattern object, or a regular expression compiled by re.compile().
  • method – HTTP method of the request. If not specified (or METHOD_ALL specified), all HTTP requests will match.
  • data – payload of the HTTP request. This could be a string (utf-8 encoded by default, see data_encoding) or a bytes object.
  • data_encoding – the encoding used for data parameter if data is a string.
  • headers – dictionary of the headers of the request to be matched
  • query_string – the http query string, after ?, such as username=user. If string is specified it will be encoded to bytes with the encode method of the string. If dict is specified, it will be matched to the key=value pairs specified in the request. If multiple values specified for a given key, the first value will be used. If multiple values needed to be handled, use MultiDict object from werkzeug.
difference(request: werkzeug.wrappers.request.Request) → List[Tuple]

Calculates the difference between the matcher and the request.

Returns a list of fields where there’s a difference between the request and the matcher. The returned list may have zero or more elements, each element is a three-element tuple containing the field name, the request value, and the matcher value.

If zero-length list is returned, this means that there’s no difference, so the request matches the fields set in the matcher object.

match(request: werkzeug.wrappers.request.Request) → bool

Returns whether the request matches the parameters set in the matcher object or not. True value is returned when it matches, False otherwise.

match_data(request: werkzeug.wrappers.request.Request) → bool

Matches the data part of the request

Parameters:request – the HTTP request
Returns:True when the data is matched or no matching is required. False otherwise.
match_json(request: werkzeug.wrappers.request.Request) → bool

Matches the request data as json.

Load the request data as json and compare it to self.json which is a json-serializable data structure (eg. a dict or list).

Parameters:request – the HTTP request
Returns:True when the data is matched or no matching is required. False otherwise.
class pytest_httpserver.httpserver.HTTPServerBase(host: str, port: int, ssl_context: Optional[ssl.SSLContext, None] = None)

Abstract HTTP server with error handling.

Parameters:
  • host – the host or IP where the server will listen
  • port – the TCP port where the server will listen
  • ssl_context – the ssl context object to use for https connections
log

Attribute containing the list of two-element tuples. Each tuple contains werkzeug.wrappers.Request and werkzeug.wrappers.Response object which represents the incoming request and the outgoing response which happened during the lifetime of the server.

no_handler_status_code

Attribute containing the http status code (int) which will be the response status when no matcher is found for the request. By default, it is set to 500 but it can be overridden to any valid http status code such as 404 if needed.

add_assertion(obj)

Add a new assertion

Assertions can be added here, and when check_assertions() is called, it will raise AssertionError for pytest with the object specified here.

Parameters:obj – An AssertionError, or an object which will be passed to an AssertionError.
application(request: werkzeug.wrappers.request.Request)

Entry point of werkzeug.

This method is called for each request, and it then calls the undecorated dispatch() method to serve the request.

Parameters:request – the request object from the werkzeug library
Returns:the response object what the dispatch returned
check()

Raises AssertionError or Errors raised in handlers.

Runs both check_assertions() and check_handler_errors()

check_assertions()

Raise AssertionError when at least one assertion added

The first assertion added by add_assertion() will be raised and it will be removed from the list.

This method can be useful to get some insights into the errors happened in the sever, and to have a proper error reporting in pytest.

check_handler_errors()

Re-Raises any errors caused in request handlers

The first error raised by a handler will be re-raised here, and then removed from the list.

clear()

Clears and resets the state attributes of the object.

This method is useful when the object needs to be re-used but stopping the server is not feasible.

clear_assertions()

Clears the list of assertions

clear_handler_errors()

Clears the list of collected errors from handler invocations

clear_log()

Clears the list of log entries

create_matcher(*args, **kwargs) → pytest_httpserver.httpserver.RequestMatcher

Creates a RequestMatcher instance with the specified parameters.

This method can be overridden if you want to use your own matcher.

dispatch(request: werkzeug.wrappers.request.Request) → werkzeug.wrappers.response.Response

Dispatch a request to the appropriate request handler.

Parameters:request – the request object from the werkzeug library
Returns:the response object what the handler responded, or a response which contains the error
static format_host(host)

Formats a hostname so it can be used in a URL. Notably, this adds brackets around IPV6 addresses when they are missing.

is_running() → bool

Returns True when the server is running, otherwise False.

respond_nohandler(request: werkzeug.wrappers.request.Request, extra_message: str = '')

Add a ‘no handler’ assertion.

This method is called when the server wasn’t able to find any handler to serve the request. As the result, there’s an assertion added (which can be raised by check_assertions()).

start()

Start the server in a thread.

This method returns immediately (e.g. does not block), and it’s the caller’s responsibility to stop the server (by calling stop()) when it is no longer needed).

If the sever 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 HTTPServerError will be raised. If you are unsure, call is_running() first.

There’s a context interface of this class which stops the server when the context block ends.

stop()

Stop the running server.

Notifies the server thread about the intention of the stopping, and the thread will terminate itself. This needs about 0.5 seconds in worst case.

Only a running server can be stopped. If the sever is not running, :py:class`HTTPServerError` will be raised.

thread_target()

This method serves as a thread target when the server is started.

This should not be called directly, but can be overridden to tailor it to your needs.

url_for(suffix: str)

Return an url for a given suffix.

This basically means that it prepends the string http://$HOST:$PORT/ to the suffix parameter (where $HOST and $PORT are the parameters given to the constructor).

When host is an IPv6 address, the required square brackets will be added to it, forming a valid URL.

When SSL or TLS is in use, the protocol of the returned URL will be https.

Parameters:suffix – the suffix which will be added to the base url. It can start with / (slash) or not, the url will be the same.
Returns:the full url which refers to the server
class pytest_httpserver.httpserver.Error

Base class for all exception defined in this package.

class pytest_httpserver.httpserver.NoHandlerError

Raised when a RequestHandler has no registered method to serve the request.

class pytest_httpserver.httpserver.HTTPServerError

Raised when there’s a problem with HTTP server.

class pytest_httpserver.httpserver.RequestHandlerList

Represents a list of RequestHandler objects.

match(request: werkzeug.wrappers.request.Request) → Optional[pytest_httpserver.httpserver.RequestHandler, None]

Returns the first request handler which matches the specified request. Otherwise, it returns None.