API documentation
pytest_httpserver
This is package provides the main API for the pytest_httpserver package.
HTTPServer
- class pytest_httpserver.HTTPServer(host: str = 'localhost', port: int = 0, ssl_context: SSLContext | None = None, default_waiting_settings: WaitingSettings | None = None, *, threaded: bool = False, startup_timeout: float | 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 managerthreaded – whether to handle concurrent requests in separate threads
startup_timeout – maximum time in seconds to wait for server readiness. By default, no readiness check is performed.
- 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: str | AssertionError) None
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: Request) Response
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_made(matcher: RequestMatcher, *, count: int = 1) None
Check the amount of log entries matching for the matcher specified. By default it verifies that exactly one request matching for the matcher specified. The expected count can be customized with the count kwarg (including zero, which asserts that no requests made for the given matcher).
- Parameters:
matcher – the matcher object to match requests
count – the expected number of matches in the log
- Returns:
Noneif the assert succeeded, raisesAssertionErrorif not.
- check() None
Raises AssertionError or Errors raised in handlers.
Runs both
check_assertions()andcheck_handler_errors()
- check_assertions() None
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() None
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() None
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.
- create_matcher(*args: Any, **kwargs: Any) RequestMatcher
Creates a
RequestMatcherinstance with the specified parameters.This method can be overridden if you want to use your own matcher.
- dispatch(request: Request) 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(matcher: RequestMatcher, handler_type: HandlerType = HandlerType.PERMANENT) RequestHandler
Create and register a request handler.
- Parameters:
matcher –
RequestMatcherused to match requests.handler_type – type of handler
- expect_oneshot_request(uri: str | ~pytest_httpserver.httpserver.URIPattern | ~re.Pattern[str], method: str = '__ALL', data: str | bytes | None = None, data_encoding: str = 'utf-8', headers: ~collections.abc.Mapping[str, str] | None = None, query_string: None | ~pytest_httpserver.httpserver.QueryMatcher | str | bytes | ~collections.abc.Mapping[str, str] = None, header_value_matcher: ~collections.abc.Callable[[str, str | None, str], bool] | None = None, json: ~typing.Any = <UNDEFINED>) 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
/, aURIPatternobject, 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=valuepairs 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, useMultiDictobject from werkzeug.header_value_matcher –
HeaderValueMatcherthat matches values of headers, or aCallable[[str, Optional[str], str], bool]receiving the header key (from headers), header value (or None) and the expected value (from headers) and should returnTrueif the header matches,Falseotherwise.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: str | ~pytest_httpserver.httpserver.URIPattern | ~re.Pattern[str], method: str = '__ALL', data: str | bytes | None = None, data_encoding: str = 'utf-8', headers: ~collections.abc.Mapping[str, str] | None = None, query_string: None | ~pytest_httpserver.httpserver.QueryMatcher | str | bytes | ~collections.abc.Mapping[str, str] = None, header_value_matcher: ~collections.abc.Callable[[str, str | None, str], bool] | None = None, json: ~typing.Any = <UNDEFINED>) 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
/, aURIPatternobject, 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=valuepairs 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, useMultiDictobject from werkzeug.header_value_matcher –
HeaderValueMatcherthat matches values of headers, or aCallable[[str, Optional[str], str], bool]receiving the header key (from headers), header value (or None) and the expected value (from headers) and should returnTrueif the header matches,Falseotherwise.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: str | ~pytest_httpserver.httpserver.URIPattern | ~re.Pattern[str], method: str = '__ALL', data: str | bytes | None = None, data_encoding: str = 'utf-8', headers: ~collections.abc.Mapping[str, str] | None = None, query_string: None | ~pytest_httpserver.httpserver.QueryMatcher | str | bytes | ~collections.abc.Mapping[str, str] = None, header_value_matcher: ~collections.abc.Callable[[str, str | None, str], bool] | None = None, handler_type: ~pytest_httpserver.httpserver.HandlerType = HandlerType.PERMANENT, json: ~typing.Any = <UNDEFINED>) 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.
Note
Once this method is called, the response should also be specified by calling one of the respond methods of the returned
RequestHandlerobject, otherwiseNoHandlerErrorwill be raised on an incoming request.
- Parameters:
uri – URI of the request. This must be an absolute path starting with
/, aURIPatternobject, 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. 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 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=valuepairs 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, useMultiDictobject from werkzeug.header_value_matcher –
HeaderValueMatcherthat matches values of headers, or aCallable[[str, Optional[str], str], bool]receiving the header key (from headers), header value (or None) and the expected value (from headers) and should returnTrueif the header matches,Falseotherwise.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: str) str
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.
- get_matching_requests_count(matcher: RequestMatcher) int
Queries the log for matching requests, returning the number of log entries matching for the specified matcher.
- Parameters:
matcher – the matcher object to match requests
- Returns:
the number of log entries matching
- iter_matching_requests(matcher: RequestMatcher) Iterable[tuple[Request, Response]]
Queries log for matching requests.
- Parameters:
matcher – the matcher object to match requests
- Returns:
an iterator with request-response pair from the log
- respond_nohandler(request: Request, extra_message: str = '') Response
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() Response
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() None
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 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 server is already running
HTTPServerErrorwill 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() None
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() None
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) 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: bool | None = None, stop_on_nohandler: bool | None = None, timeout: float | None = None) Generator[Waiting, 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: RequestMatcher)
Represents a response function and a
RequestHandlerobject.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: Request) Response
Calls the request handler registered for this object.
If no response was specified previously, it raises
NoHandlerErrorexception.
- Parameters:
request – the incoming request object
- Returns:
the response object
- respond_with_data(response_data: str | bytes = '', status: int = 200, headers: Mapping[str, str | Iterable[str]] | Iterable[tuple[str, str]] | None = None, mimetype: str | None = None, content_type: str | None = None) None
Prepares a response with raw data.
For detailed description please see the
werkzeug.Responseobject 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[[Request], Response]) None
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: Any, status: int = 200, headers: Mapping[str, str] | None = None, content_type: str = 'application/json') None
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
RequestMatcher
- class pytest_httpserver.RequestMatcher(uri: str | ~pytest_httpserver.httpserver.URIPattern | ~re.Pattern[str], method: str = '__ALL', data: str | bytes | None = None, data_encoding: str = 'utf-8', headers: ~collections.abc.Mapping[str, str] | None = None, query_string: None | ~pytest_httpserver.httpserver.QueryMatcher | str | bytes | ~collections.abc.Mapping[str, str] = None, header_value_matcher: ~collections.abc.Callable[[str, str | None, str], bool] | None = None, json: ~typing.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
/, aURIPatternobject, 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=valuepairs 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, useMultiDictobject from werkzeug.header_value_matcher –
HeaderValueMatcherthat matches values of headers, or aCallable[[str, Optional[str], str], bool]receiving the header key (from headers), header value (or None) and the expected value (from headers) and should returnTrueif the header matches,Falseotherwise.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.
- difference(request: Request) list[tuple[str, str, str | URIPattern]]
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: 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: 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: 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.
BlockingHTTPServer
- class pytest_httpserver.BlockingHTTPServer(host: str = 'localhost', port: int = 0, ssl_context: 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: str | AssertionError) None
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: Request) Response
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: str | URIPattern | Pattern[str], method: str = '__ALL', data: str | bytes | None = None, data_encoding: str = 'utf-8', headers: Mapping[str, str] | None = None, query_string: None | QueryMatcher | str | bytes | Mapping[str, str] = None, header_value_matcher: HeaderValueMatcher | None = None, json: Any = <UNDEFINED>, timeout: int = 30) 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
/, aURIPatternobject, 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=valuepairs 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, useMultiDictobject from werkzeug.header_value_matcher –
HeaderValueMatcherthat 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() None
Raises AssertionError or Errors raised in handlers.
Runs both
check_assertions()andcheck_handler_errors()
- check_assertions() None
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() None
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() None
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.
- create_matcher(*args: Any, **kwargs: Any) RequestMatcher
Creates a
RequestMatcherinstance with the specified parameters.This method can be overridden if you want to use your own matcher.
- dispatch(request: Request) 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: str) str
Formats a hostname so it can be used in a URL. Notably, this adds brackets around IPV6 addresses when they are missing.
- respond_nohandler(request: Request, extra_message: str = '') Response
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() None
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 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 server is already running
HTTPServerErrorwill 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() None
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() None
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) 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: str | bytes = '', status: int = 200, headers: Mapping[str, str | Iterable[str]] | Iterable[tuple[str, str]] | None = None, mimetype: str | None = None, content_type: str | None = None) None
Prepares a response with raw data.
For detailed description please see the
werkzeug.Responseobject 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: Any, status: int = 200, headers: Mapping[str, str] | None = None, content_type: str = 'application/json') None
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
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: Mapping[str, Callable[[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
HTTPServerError
- class pytest_httpserver.HTTPServerError
Raised when there’s a problem with HTTP server.
NoHandlerError
- class pytest_httpserver.NoHandlerError
Raised when a
RequestHandlerhas 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: str | ~pytest_httpserver.httpserver.URIPattern | ~re.Pattern[str], method: str = '__ALL', data: str | bytes | None = None, data_encoding: str = 'utf-8', headers: ~collections.abc.Mapping[str, str] | None = None, query_string: None | ~pytest_httpserver.httpserver.QueryMatcher | str | bytes | ~collections.abc.Mapping[str, str] = None, header_value_matcher: ~collections.abc.Callable[[str, str | None, str], bool] | None = None, json: ~typing.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
/, aURIPatternobject, 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=valuepairs 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, useMultiDictobject from werkzeug.header_value_matcher –
HeaderValueMatcherthat matches values of headers, or aCallable[[str, Optional[str], str], bool]receiving the header key (from headers), header value (or None) and the expected value (from headers) and should returnTrueif the header matches,Falseotherwise.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.
- difference(request: Request) list[tuple[str, str, str | URIPattern]]
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: 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: 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: 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: SSLContext | None = None, *, threaded: bool = False)
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
threaded – whether to handle concurrent requests in separate threads
- log
Attribute containing the list of two-element tuples. Each tuple contains
werkzeug.Requestandwerkzeug.Responseobject 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: str | AssertionError) None
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: Request) Response
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() None
Raises AssertionError or Errors raised in handlers.
Runs both
check_assertions()andcheck_handler_errors()
- check_assertions() None
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() None
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() None
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.
- create_matcher(*args: Any, **kwargs: Any) RequestMatcher
Creates a
RequestMatcherinstance with the specified parameters.This method can be overridden if you want to use your own matcher.
- abstractmethod dispatch(request: Request) 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: str) str
Formats a hostname so it can be used in a URL. Notably, this adds brackets around IPV6 addresses when they are missing.
- respond_nohandler(request: Request, extra_message: str = '') Response
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() None
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 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 server is already running
HTTPServerErrorwill 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() None
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() None
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) 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
RequestHandlerhas 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(iterable=(), /)
Represents a list of
RequestHandlerobjects.- match(request: Request) RequestHandler | None
Returns the first request handler which matches the specified request. Otherwise, it returns None.
pytest_httpserver.hooks
Hooks for pytest-httpserver