cheroot.test package

Submodules

cheroot.test.conftest module

Pytest configuration module.

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

cheroot.test.conftest.http_server()

Provision a server creator as a fixture.

cheroot.test.conftest.make_http_server(bind_addr)

Create and start an HTTP server bound to bind_addr.

cheroot.test.conftest.native_server_client(native_server)

Create a test client out of given HTTP server.

cheroot.test.conftest.wsgi_server_client(wsgi_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.

output()

Generate iterable response body object.

cheroot.test.test__compat module

Test suite for cross-python compatibility helpers.

cheroot.test.test__compat.test_compat_functions_negative_nonnative(func)

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.

cheroot.test.test__compat.test_extract_bytes_invalid()

Ensure that invalid input causes exception to be raised.

cheroot.test.test__compat.test_ntou_escape()

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.

custom_204(resp)

Render response with status 204.

custom_304(resp)

Render response with status 304.

err_before_read(resp)

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 Controller.stream>, '/upload': <function Controller.upload>, '/wrong_cl_buffered': <function Controller.wrong_cl_buffered>, '/wrong_cl_unbuffered': <function Controller.wrong_cl_unbuffered>}
hello(resp)

Render Hello world.

one_megabyte_of_a(resp)

Render 1MB response.

pov(resp)

Render pov value.

stream(resp)

Render streaming response.

upload(resp)

Process file upload and render thank.

wrong_cl_buffered(resp)

Render buffered response with invalid length value.

wrong_cl_unbuffered(resp)

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.

cheroot.test.test_conn.test_100_Continue(test_client)

Test 100-continue header processing.

cheroot.test.test_conn.test_598(test_client)

Test serving large file with a read timeout in place.

cheroot.test.test_conn.test_Chunked_Encoding(test_client)

Test HTTP uploads with chunked transfer-encoding.

cheroot.test.test_conn.test_Content_Length_in(test_client)

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

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

cheroot.test.test_conn.test_Content_Length_not_int(test_client)

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.

cheroot.test.test_conn.test_HTTP11_Timeout_after_request(test_client)

Check timeout after at least one request has succeeded.

The server should close the connection without 408.

cheroot.test.test_conn.test_HTTP11_persistent_connections(test_client)

Test persistent HTTP/1.1 connections.

cheroot.test.test_conn.test_HTTP11_pipelining(test_client)

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.

cheroot.test.test_conn.test_No_Message_Body(test_client)

Test HTTP queries with an empty response body.

cheroot.test.test_conn.test_client(testing_server)

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.

cheroot.test.test_conn.test_keepalive_conn_management(test_client)

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.

cheroot.test.test_conn.testing_server(wsgi_server_client)

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()

Close, writing hello.

class cheroot.test.test_core.CloseResponse(close)

Bases: object

Dummy empty response to trigger the no body status.

output()

Return self to hook the close method.

class cheroot.test.test_core.HelloController

Bases: cheroot.test.helper.Controller

Controller for serving WSGI apps.

asterisk(resp)

Render request method value.

body_required(resp)

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>}
hello(resp)

Render Hello world.

query_string(resp)

Render QUERY_STRING value.

cheroot.test.test_core.test_client(testing_server)

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

cheroot.test.test_core.test_client_with_defaults(testing_server_with_defaults)

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

cheroot.test.test_core.test_content_length_required(test_client)

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

cheroot.test.test_core.test_garbage_in(test_client)

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

cheroot.test.test_core.test_http_connect_request(test_client)

Check that CONNECT query results in Method Not Allowed status.

cheroot.test.test_core.test_large_request(test_client_with_defaults)

Test GET query with maliciously large Content-Length.

cheroot.test.test_core.test_malformed_header(test_client)

Check that broken HTTP header results in Bad Request.

cheroot.test.test_core.test_malformed_http_method(test_client)

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.

cheroot.test.test_core.test_no_content_length(test_client)

Test POST query with an empty body being successful.

cheroot.test.test_core.test_normal_request(test_client)

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).

cheroot.test.test_core.test_parse_uri_absolute_uri(test_client)

Check that server responds with Bad Request to Absolute URI.

Only proxy servers should allow this.

cheroot.test.test_core.test_parse_uri_asterisk_uri(test_client)

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

cheroot.test.test_core.test_parse_uri_fragment_uri(test_client)

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

cheroot.test.test_core.test_parse_uri_invalid_uri(test_client)

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

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

cheroot.test.test_core.test_parse_uri_unsafe_uri(test_client)

Test that malicious URI does not allow HTTP injection.

This effectively checks that sending GET request with URL

/%A0%D0blah%20key%200%20900%204%20data

is not converted into

GET / blah key 0 900 4 data HTTP/1.1

which would be a security issue otherwise.

cheroot.test.test_core.test_query_string_request(test_client)

Check that GET param is parsed well.

cheroot.test.test_core.test_request_line_split_issue_1220(test_client)

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

cheroot.test.test_core.test_send_header_before_closing(testing_server_close)

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

cheroot.test.test_core.testing_server(wsgi_server_client)

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

cheroot.test.test_core.testing_server_close(wsgi_server_client)

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

cheroot.test.test_core.testing_server_with_defaults(wsgi_server_client)

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

cheroot.test.test_dispatch module

Tests for the HTTP server.

cheroot.test.test_dispatch.test_dispatch_no_script_name()

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.

recv(size)

Simulate recv for Python 2.

recv_into(buf)

Simulate recv_into for Python 3.

send(val)

Simulate a send.

cheroot.test.test_makefile.test_bytes_read()

Reader should capture bytes read.

cheroot.test.test_makefile.test_bytes_written()

Writer should capture bytes written.

cheroot.test.test_server module

Tests for the HTTP server.

cheroot.test.test_server.peercreds_enabled_server_and_client(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.

cheroot.test.test_server.test_peercreds_unix_sock(peercreds_enabled_server_and_client)

Check that PEERCRED lookup works when enabled.

cheroot.test.test_server.test_peercreds_unix_sock_with_lookup(peercreds_enabled_server_and_client)

Check that PEERCRED resolution works when enabled.

cheroot.test.test_server.test_prepare_makes_server_ready()

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

cheroot.test.test_server.test_stop_interrupts_serve()

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

cheroot.test.test_server.unix_abstract_sock()

Return an abstract UNIX socket address.

cheroot.test.test_server.unix_sock_file(request)

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.server.Gateway

Gateway responding with Hello World to root URI.

respond()

Respond with dummy content via HTTP.

cheroot.test.test_ssl.ca()

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_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.

cheroot.test.test_ssl.tls_ca_certificate_pem_path(ca)

Provide a certificate authority certificate file via fixture.

cheroot.test.test_ssl.tls_certificate(ca)

Provide a leaf certificate via fixture.

cheroot.test.test_ssl.tls_certificate_chain_pem_path(tls_certificate)

Provide a certificate chain PEM file path via fixture.

cheroot.test.test_ssl.tls_certificate_private_key_pem_path(tls_certificate)

Provide a certificate private key PEM file path via fixture.

cheroot.test.test_ssl.tls_http_server(request)

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')

Bases: unittest.case.TestCase

Helper web test suite base.

HOST = '127.0.0.1'
HTTP_CONN

alias of http.client.HTTPConnection

PORT = 8000
PROTOCOL = 'HTTP/1.1'
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().

get_conn(auto_open=False)

Return a connection to our HTTP server.

headers = None
interactive

Non-data property decorator.

interface()

Return an IP address for a client connection.

If the server is listening on ‘0.0.0.0’ (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.

status_matches(expected)

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).

cheroot.test.webtest.getchar()

Get a key press.

cheroot.test.webtest.interface(host)

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

If the server is listening on ‘0.0.0.0’ (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.

cheroot.test.webtest.server_error(exc=None)

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.

cheroot.test.webtest.shb(response)

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

cheroot.test.webtest.strip_netloc(url)

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('https://google.com/foo/bar?bing#baz')
'/foo/bar?bing'
>>> strip_netloc('//google.com/foo/bar?bing#baz')
'/foo/bar?bing'
>>> strip_netloc('/foo/bar?bing#baz')
'/foo/bar?bing'

Module contents

Cheroot test suite.