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, default_waiting_settings: Optional[pytest_httpserver.httpserver.WaitingSettings] = 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
log
¶Attribute containing the list of two-element tuples. Each tuple contains
Request
andResponse
object which represents the incoming request and the outgoing response which happened during the lifetime of the server.
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 object which will be passed to 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_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.
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_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, query_string: Union[None, pytest_httpserver.httpserver.QueryMatcher, str, bytes, Mapping[KT, VT_co]] = None, header_value_matcher: Optional[pytest_httpserver.httpserver.HeaderValueMatcher] = None) → 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
/
, aURIPattern
object, or a regular expression compiled byre.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 asusername=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 thekey=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, useMultiDict
object from werkzeug.- header_value_matcher –
HeaderValueMatcher
that matches values of headers.Returns: Created and register
RequestHandler
.
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, query_string: Union[None, pytest_httpserver.httpserver.QueryMatcher, str, bytes, Mapping[KT, VT_co]] = None, header_value_matcher: Optional[pytest_httpserver.httpserver.HeaderValueMatcher] = None) → 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
/
, aURIPattern
object, or a regular expression compiled byre.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 asusername=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 thekey=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, useMultiDict
object from werkzeug.- header_value_matcher –
HeaderValueMatcher
that matches values of headers.Returns: Created and register
RequestHandler
.
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, query_string: Union[None, pytest_httpserver.httpserver.QueryMatcher, str, bytes, Mapping[KT, VT_co]] = None, header_value_matcher: Optional[pytest_httpserver.httpserver.HeaderValueMatcher] = None, handler_type: pytest_httpserver.httpserver.HandlerType = <HandlerType.PERMANENT: 'permanent'>) → 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
/
, aURIPattern
object, or a regular expression compiled byre.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 asusername=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 thekey=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, useMultiDict
object from werkzeug.- header_value_matcher –
HeaderValueMatcher
that matches values of headers.- handler_type – type of handler
Returns: Created and register
RequestHandler
.
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 primairly used when reporting errors.
is_running
() → bool¶Returns True when the server is running, otherwise False.
respond_nohandler
(request: werkzeug.wrappers.request.Request)¶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 thred is stopped.
If the sever is already running
HTTPServerError
will be raised. If you are unsure, callis_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 runnig, :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 overriden 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).
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, stop_on_nohandler: Optional[bool] = None, timeout: Optional[float] = 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))
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[[str, str], bool]]] = 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.
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.
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 request handler 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: Optional[Mapping[str, str]] = None, mimetype: Optional[str] = None, content_type: Optional[str] = None)¶Registers a respond handler function which responds raw data.
For detailed description please see the
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, content_type: str = 'application/json')¶Registers a respond handler function which responds 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)¶Registers a respond handler function which responds the specified response object.
Parameters: response – the response object which will be responded
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, query_string: Union[None, pytest_httpserver.httpserver.QueryMatcher, str, bytes, Mapping[KT, VT_co]] = None, header_value_matcher: Optional[pytest_httpserver.httpserver.HeaderValueMatcher] = None)¶ 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
/
, aURIPattern
object, or a regular expression compiled byre.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 asusername=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 thekey=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, useMultiDict
object from werkzeug.
-
difference
(request: werkzeug.wrappers.request.Request) → list¶ 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.
- uri – URI of the request. This must be an absolute path starting with
-
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.