cheroot.test package


cheroot.test.conftest module

Pytest configuration module.

Contains fixtures, which are tightly bound to the Cheroot framework itself, useless for end-users’ app testing.


Provision a server creator as a fixture.


Create and start an HTTP server bound to bind_addr.


Create a test client out of given HTTP server.


Create a test client out of given WSGI server.

cheroot.test.helper module

A library of helper functions for the Cheroot test suite.

class cheroot.test.helper.CherootWebCase(methodName='runTest')

Bases: cheroot.test.webtest.WebCase

Helper class for a web app test suite.

assertEqualDates(dt1, dt2, seconds=None)

Assert abs(dt1 - dt2) is within Y seconds.

available_servers = {'native': <class 'cheroot.server.HTTPServer'>, 'wsgi': <class 'cheroot.wsgi.Server'>}
date_tolerance = 2
scheme = 'http'
script_name = ''
classmethod setup_class()

Create and run one HTTP server per class.

classmethod start()

Load and start the HTTP server.

classmethod stop()

Terminate HTTP server.

classmethod teardown_class()

Cleanup HTTP server.

class cheroot.test.helper.Controller

Bases: object

WSGI app for tests.

class cheroot.test.helper.Request(environ)

Bases: object

HTTP request container.

class cheroot.test.helper.Response

Bases: object

HTTP response container.


Generate iterable response body object.

cheroot.test.test__compat module

Test suite for cross-python compatibility helpers.


Check that compatibility functions fail loudly for incorrect input.

cheroot.test.test__compat.test_compat_functions_positive(func, inp, out)

Check that compatibility functions work with correct input.

cheroot.test.test__compat.test_extract_bytes(input_argument, expected_result)

Check that legitimate inputs produce bytes.


Ensure that invalid input causes exception to be raised.


Check that ntou supports escape-encoding under Python 2.

cheroot.test.test_conn module

Tests for TCP connection handling, including proper and timely close.

class cheroot.test.test_conn.Controller

Bases: cheroot.test.helper.Controller

Controller for serving WSGI apps.


Render response with status 204.


Render response with status 304.


Render response with status 500.

handlers = {'/custom/204': <function Controller.custom_204>, '/custom/304': <function Controller.custom_304>, '/err_before_read': <function Controller.err_before_read>, '/hello': <function Controller.hello>, '/one_megabyte_of_a': <function Controller.one_megabyte_of_a>, '/page1': <function Controller.pov>, '/page2': <function Controller.pov>, '/page3': <function Controller.pov>, '/pov': <function Controller.pov>, '/stream': <function>, '/upload': <function Controller.upload>, '/wrong_cl_buffered': <function Controller.wrong_cl_buffered>, '/wrong_cl_unbuffered': <function Controller.wrong_cl_unbuffered>}

Render Hello world.


Render 1MB response.


Render pov value.


Render streaming response.


Process file upload and render thank.


Render buffered response with invalid length value.


Render unbuffered response with invalid length value.

cheroot.test.test_conn.header_exists(header_name, headers)

Check that a header is present.

cheroot.test.test_conn.header_has_value(header_name, header_value, headers)

Check that a header with a given value is present.


Test 100-continue header processing.


Test serving large file with a read timeout in place.


Test HTTP uploads with chunked transfer-encoding.


Try a non-chunked request where Content-Length exceeds limit.

(server.max_request_body_size). Assert error before body send.


Test that malicious Content-Length header returns 400.

cheroot.test.test_conn.test_Content_Length_out(test_client, uri, expected_resp_status, expected_resp_body)

Test response with Content-Length less than the response body.

(non-chunked response)

cheroot.test.test_conn.test_HTTP11_Timeout(test_client, timeout_before_headers)

Check timeout without sending any data.

The server will close the connection with a 408.


Check timeout after at least one request has succeeded.

The server should close the connection without 408.


Test persistent HTTP/1.1 connections.


Test HTTP/1.1 pipelining.

http.client doesn’t support this directly.

cheroot.test.test_conn.test_No_CRLF(test_client, invalid_terminator)

Test HTTP queries with no valid CRLF terminators.


Test HTTP queries with an empty response body.


Get and return a test client out of the given server.

cheroot.test.test_conn.test_keepalive(test_client, http_server_protocol)

Test Keep-Alive enabled connections.


Test management of Keep-Alive connections.

cheroot.test.test_conn.test_readall_or_close(test_client, max_request_body_size)

Test a max_request_body_size of 0 (the default) and 1001.

cheroot.test.test_conn.test_streaming_10(test_client, set_cl)

Test serving of streaming responses with HTTP/1.0 protocol.

cheroot.test.test_conn.test_streaming_11(test_client, set_cl)

Test serving of streaming responses with HTTP/1.1 protocol.


Attach a WSGI app to the given server and preconfigure it.

cheroot.test.test_core module

Tests for managing HTTP issues (malformed requests, etc).

class cheroot.test.test_core.CloseController

Bases: object

Controller for testing the close callback.


Close, writing hello.

class cheroot.test.test_core.CloseResponse(close)

Bases: object

Dummy empty response to trigger the no body status.


Return self to hook the close method.

class cheroot.test.test_core.HelloController

Bases: cheroot.test.helper.Controller

Controller for serving WSGI apps.


Render request method value.


Render Hello world or set 411.

handlers = {'/*': <function HelloController.asterisk>, '/body_required': <function HelloController.body_required>, '/hello': <function HelloController.hello>, '/no_body': <function HelloController.hello>, '/query_string': <function HelloController.query_string>, '/\xa0Ðblah key 0 900 4 data': <function HelloController.hello>, '/ЮÑ\x85Ñ\x85Ñ\x83Ñ\x83Ñ\x83': <function HelloController.hello>, '/пÑ\x80ивÑ\x96Ñ\x82': <function HelloController.hello>}

Render Hello world.


Render QUERY_STRING value.


Get and return a test client out of the given server.


Get and return a test client out of the given server.


Test POST query with body failing because of missing Content-Length.


Test that server sends an error for garbage received over TCP.


Check that CONNECT query results in Method Not Allowed status.


Test GET query with maliciously large Content-Length.


Check that broken HTTP header results in Bad Request.


Test non-uppercase HTTP method.

cheroot.test.test_core.test_malformed_request_line(test_client, request_line, status_code, expected_body)

Test missing or invalid HTTP version in Request-Line.


Test POST query with an empty body being successful.


Check that normal GET query succeeds.

cheroot.test.test_core.test_parse_acceptable_uri(test_client, uri)

Check that server responds with OK to valid GET queries.

cheroot.test.test_core.test_parse_no_leading_slash_invalid(test_client, uri)

Check that server responds with Bad Request to invalid GET queries.

Invalid request line test case: it should have leading slash (be absolute).


Check that server responds with Bad Request to Absolute URI.

Only proxy servers should allow this.


Check that server responds with OK to OPTIONS with “*” Absolute URI.


Check that server responds with Bad Request to URI with fragment.


Check that server responds with Bad Request to invalid GET queries.

Invalid request line test case: it should only contain US-ASCII.


Test that malicious URI does not allow HTTP injection.

This effectively checks that sending GET request with URL


is not converted into

GET / blah key 0 900 4 data HTTP/1.1

which would be a security issue otherwise.


Check that GET param is parsed well.


Check that HTTP request line of exactly 256 chars length is OK.


Test we are actually sending the headers before calling ‘close’.


Attach a WSGI app to the given server and preconfigure it.


Attach a WSGI app to the given server and preconfigure it.


Attach a WSGI app to the given server and preconfigure it.

cheroot.test.test_dispatch module

Tests for the HTTP server.


Dispatch despite lack of SCRIPT_NAME in environ.

cheroot.test.test_dispatch.wsgi_invoke(app, environ)

Serve 1 request from a WSGI application.

cheroot.test.test_errors module

Test suite for cheroot.errors.

cheroot.test.test_errors.test_plat_specific_errors(err_names, err_nums)

Test that plat_specific_errors gets correct error numbers list.

cheroot.test.test_makefile module

Tests for cheroot.makefile.

class cheroot.test.test_makefile.MockSocket

Bases: object

A mock socket.


Simulate recv for Python 2.


Simulate recv_into for Python 3.


Simulate a send.


Reader should capture bytes read.


Writer should capture bytes written.

cheroot.test.test_server module

Tests for the HTTP server.

cheroot.test.test_server.peercreds_enabled_server(http_server, unix_sock_file)

Construct a test server with peercreds_enabled.

cheroot.test.test_server.test_bind_addr_inet(http_server, ip_addr)

Check that bound IP address is stored in server.

cheroot.test.test_server.test_bind_addr_unix(http_server, unix_sock_file)

Check that bound UNIX socket address is stored in server.

cheroot.test.test_server.test_bind_addr_unix_abstract(http_server, unix_abstract_sock)

Check that bound UNIX abstract socket address is stored in server.


Check that PEERCRED lookup works when enabled.


Check that PEERCRED resolution works when enabled.


Check that prepare() makes the server ready, and stop() clears it.


Check that stop() interrupts running of serve().


Return an abstract UNIX socket address.


Yield a unix file socket.


Check that bound UNIX socket address is stored in server.

cheroot.test.test_ssl module

Tests for TLS support.

class cheroot.test.test_ssl.HelloWorldGateway(req)

Bases: cheroot.wsgi.Gateway_10

Gateway responding with Hello World to root URI.


Respond with dummy content via HTTP.

Provide a certificate authority via fixture.

cheroot.test.test_ssl.make_tls_http_server(bind_addr, ssl_adapter, request)

Create and start an HTTP server bound to bind_addr.

cheroot.test.test_ssl.test_http_over_https_error(tls_http_server, adapter_type, ca, ip_addr, tls_certificate, tls_certificate_chain_pem_path, tls_certificate_private_key_pem_path)

Ensure that connecting over HTTP to HTTPS port is handled.

cheroot.test.test_ssl.test_https_over_http_error(http_server, ip_addr)

Ensure that connecting over HTTPS to HTTP port is handled.

cheroot.test.test_ssl.test_ssl_adapters(tls_http_server, adapter_type, tls_certificate, tls_certificate_chain_pem_path, tls_certificate_private_key_pem_path, tls_ca_certificate_pem_path)

Test ability to connect to server via HTTPS using adapters.

cheroot.test.test_ssl.test_ssl_env(mocker, tls_http_server, adapter_type, ca, tls_verify_mode, tls_certificate, tls_certificate_chain_pem_path, tls_certificate_private_key_pem_path, tls_ca_certificate_pem_path, use_client_cert)

Test the SSL environment generated by the SSL adapters.

cheroot.test.test_ssl.test_tls_client_auth(mocker, tls_http_server, adapter_type, ca, tls_certificate, tls_certificate_chain_pem_path, tls_certificate_private_key_pem_path, tls_ca_certificate_pem_path, is_trusted_cert, tls_client_identity, tls_verify_mode)

Verify that client TLS certificate auth works correctly.


Provide a certificate authority certificate file via fixture.


Provide a leaf certificate via fixture.


Provide a certificate chain PEM file path via fixture.


Provide a certificate private key PEM file path via fixture.


Provision a server creator as a fixture.

cheroot.test.webtest module

Extensions to unittest for web frameworks.

Use the WebCase.getPage() method to request a page from your HTTP server.

Framework Integration

If you have control over your server process, you can handle errors in the server-side of the HTTP conversation a bit better. You must run both the client (your WebCase tests) and the server in the same process (but in separate threads, obviously). When an error occurs in the framework, call server_error. It will print the traceback to stdout, and keep any assertions you have from running (the assumption is that, if the server errors, the page output will not be of further significance to your tests).

class cheroot.test.webtest.NonDataProperty(fget)

Bases: object

Non-data property decorator.

exception cheroot.test.webtest.ServerError

Bases: Exception

Exception for signalling server error.

on = False
class cheroot.test.webtest.WebCase(methodName='runTest')


Helper web test suite base.

HOST = ''

alias of http.client.HTTPConnection

PORT = 8000
assertBody(value, msg=None)

Fail if value != self.body.

assertHeader(key, value=None, msg=None)

Fail if (key, [value]) not in self.headers.

assertHeaderIn(key, values, msg=None)

Fail if header indicated by key doesn’t have one of the values.

assertHeaderItemValue(key, value, msg=None)

Fail if the header does not contain the specified value.

assertInBody(value, msg=None)

Fail if value not in self.body.

assertMatchesBody(pattern, msg=None, flags=0)

Fail if value (a regex pattern) is not in self.body.

assertNoHeader(key, msg=None)

Fail if key in self.headers.

assertNoHeaderItemValue(key, value, msg=None)

Fail if the header contains the specified value.

assertNotInBody(value, msg=None)

Fail if value in self.body.

assertStatus(status, msg=None)

Fail if self.status != status.

status may be integer code, exact string status, or iterable of allowed possibilities.

body = None
console_height = 30
encoding = 'utf-8'
getPage(url, headers=None, method='GET', body=None, protocol=None, raise_subcls=)

Open the url with debugging support. Return status, headers, body.

url should be the identifier passed to the server, typically a server-absolute path and query string (sent between method and protocol), and should only be an absolute URI if proxy support is enabled in the server.

If the application under test generates absolute URIs, be sure to wrap them first with strip_netloc():

>>> class MyAppWebCase(WebCase):
...     def getPage(url, *args, **kwargs):
...         super(MyAppWebCase, self).getPage(
...             cheroot.test.webtest.strip_netloc(url),
...             *args, **kwargs
...         )

raise_subcls is passed through to openURL().


Return a connection to our HTTP server.

headers = None

Non-data property decorator.


Return an IP address for a client connection.

If the server is listening on ‘’ (INADDR_ANY) or ‘::’ (IN6ADDR_ANY), this will return the proper localhost.

property persistent

Presence of the persistent HTTP connection.

scheme = 'http'
set_persistent(on=True, auto_open=False)

Make our HTTP_CONN persistent (or not).

If the ‘on’ argument is True (the default), then self.HTTP_CONN will be set to an instance of HTTP(S)?Connection to persist across requests. As this class only allows for a single open connection, if self already has an open connection, it will be closed.

ssl_context = None
status = None
property status_code

Integer HTTP status code.


Check whether actual status matches expected.

time = None
url = None
cheroot.test.webtest.cleanHeaders(headers, method, body, host, port)

Return request headers, with required headers added (if missing).


Get a key press.


Return an IP address for a client connection given the server host.

If the server is listening on ‘’ (INADDR_ANY) or ‘::’ (IN6ADDR_ANY), this will return the proper localhost.

cheroot.test.webtest.openURL(*args, **kwargs)

Open a URL, retrying when it fails.

Specify raise_subcls (class or tuple of classes) to exclude those socket.error subclasses from being suppressed and retried.


Server debug hook.

Return True if exception handled, False if ignored. You probably want to wrap this, so you can still handle an error using your framework when it’s ignored.


Return status, headers, body the way we like from a response.


Return absolute-URI path from URL.

Strip the scheme and host from the URL, returning the server-absolute portion.

Useful for wrapping an absolute-URI for which only the path is expected (such as in calls to WebCase.getPage()).

>>> strip_netloc('')
>>> strip_netloc('//')
>>> strip_netloc('/foo/bar?bing#baz')

Module contents

Cheroot test suite.