cherrypy.test package

Submodules

cherrypy.test._test_decorators module

Test module for the @-decorator syntax, which is version-specific

class cherrypy.test._test_decorators.ExposeExamples

Bases: object

alias1()
alias2()
alias3()
andrews()
call_alias()
call_empty()
nesbitt()
no_call()
watson()
class cherrypy.test._test_decorators.ToolExamples

Bases: object

blah()

cherrypy.test._test_states_demo module

class cherrypy.test._test_states_demo.Root

Bases: object

exit()
index()
mtimes()
pid()
start()
cherrypy.test._test_states_demo.log_test_case_name()
cherrypy.test._test_states_demo.starterror()
cherrypy.test._test_states_demo.unsub_sig()

cherrypy.test.benchmark module

CherryPy Benchmark Tool

Usage:
benchmark.py [options]

–null: use a null Request object (to bench the HTTP server only) –notests: start the server but do not run the tests; this allows

you to check the tested pages with a browser

–help: show this help message –cpmodpy: run tests via apache on 54583 (with the builtin _cpmodpy) –modpython: run tests via apache on 54583 (with modpython_gateway) –ab=path: Use the ab script/executable at ‘path’ (see below) –apache=path: Use the apache script/exe at ‘path’ (see below)

To run the benchmarks, the Apache Benchmark tool “ab” must either be on your system path, or specified via the –ab=path option.

To run the modpython tests, the “apache” executable or script must be on your system path, or provided via the –apache=path option. On some platforms, “apache” may be called “apachectl” or “apache2ctl”–create a symlink to them if needed.

class cherrypy.test.benchmark.ABSession(path='/cpbench/users/rdelon/apps/blog/hello', requests=1000, concurrency=10)

Bases: object

A session of ‘ab’, the Apache HTTP server benchmarking tool.

Example output from ab:

This is ApacheBench, Version 2.0.40-dev <$Revision: 1.121.2.1 $> apache-2.0 Copyright (c) 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/ Copyright (c) 1998-2002 The Apache Software Foundation, http://www.apache.org/

Benchmarking 127.0.0.1 (be patient) Completed 100 requests Completed 200 requests Completed 300 requests Completed 400 requests Completed 500 requests Completed 600 requests Completed 700 requests Completed 800 requests Completed 900 requests

Server Software: CherryPy/3.1beta Server Hostname: 127.0.0.1 Server Port: 54583

Document Path: /static/index.html Document Length: 14 bytes

Concurrency Level: 10 Time taken for tests: 9.643867 seconds Complete requests: 1000 Failed requests: 0 Write errors: 0 Total transferred: 189000 bytes HTML transferred: 14000 bytes Requests per second: 103.69 [#/sec] (mean) Time per request: 96.439 [ms] (mean) Time per request: 9.644 [ms] (mean, across all concurrent requests) Transfer rate: 19.08 [Kbytes/sec] received

Connection Times (ms)
min mean[+/-sd] median max

Connect: 0 0 2.9 0 10 Processing: 20 94 7.3 90 130 Waiting: 0 43 28.1 40 100 Total: 20 95 7.3 100 130

Percentage of the requests served within a certain time (ms)
50% 100 66% 100 75% 100 80% 100 90% 100 95% 100 98% 100 99% 110

100% 130 (longest request)

Finished 1000 requests

args()
parse_patterns = [('complete_requests', 'Completed', b'^Complete requests:\\s*(\\d+)'), ('failed_requests', 'Failed', b'^Failed requests:\\s*(\\d+)'), ('requests_per_second', 'req/sec', b'^Requests per second:\\s*([0-9.]+)'), ('time_per_request_concurrent', 'msec/req', b'^Time per request:\\s*([0-9.]+).*concurrent requests\\)$'), ('transfer_rate', 'KB/sec', b'^Transfer rate:\\s*([0-9.]+)')]
run()
class cherrypy.test.benchmark.Root

Bases: object

hello()
index()
sizer(size)
cherrypy.test.benchmark.print_report(rows)
cherrypy.test.benchmark.run_standard_benchmarks()
cherrypy.test.benchmark.size_report(sizes=(10, 100, 1000, 10000, 100000, 100000000), concurrency=50)
cherrypy.test.benchmark.thread_report(path='/cpbench/users/rdelon/apps/blog/hello', concurrency=(25, 50, 100, 200, 400))

cherrypy.test.checkerdemo module

Demonstration app for cherrypy.checker.

This application is intentionally broken and badly designed. To demonstrate the output of the CherryPy Checker, simply execute this module.

class cherrypy.test.checkerdemo.Root

Bases: object

cherrypy.test.helper module

A library of helper functions for the CherryPy test suite.

class cherrypy.test.helper.CPProcess(wait=False, daemonize=False, ssl=False, socket_host=None, socket_port=None)

Bases: object

access_log = '/home/docs/checkouts/readthedocs.org/user_builds/cherrypy/checkouts/latest/cherrypy/test/test.access.log'
config_file = '/home/docs/checkouts/readthedocs.org/user_builds/cherrypy/checkouts/latest/cherrypy/test/test.conf'
config_template = "[global]\nserver.socket_host: '%(host)s'\nserver.socket_port: %(port)s\nchecker.on: False\nlog.screen: False\nlog.error_file: r'%(error_log)s'\nlog.access_file: r'%(access_log)s'\n%(ssl)s\n%(extra)s\n"
error_log = '/home/docs/checkouts/readthedocs.org/user_builds/cherrypy/checkouts/latest/cherrypy/test/test.error.log'
get_pid()
join()

Wait for the process to exit.

pid_file = '/home/docs/checkouts/readthedocs.org/user_builds/cherrypy/checkouts/latest/cherrypy/test/test.pid'
start(imports=None)

Start cherryd in a subprocess.

write_conf(extra='')
class cherrypy.test.helper.CPWebCase(methodName='runTest')

Bases: cherrypy.test.webtest.WebCase

assertEqualDates(dt1, dt2, seconds=None)

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

assertErrorPage(status, message=None, pattern='')

Compare the response body with a built in error page.

The function will optionally look for the regexp pattern, within the exception embedded in the error page.

available_servers = {'wsgi': <class 'cherrypy.test.helper.LocalWSGISupervisor'>, 'wsgi_u': <function get_wsgi_u_supervisor at 0x7fb351190ea0>, 'native': <class 'cherrypy.test.helper.NativeServerSupervisor'>, 'modfcgid': <function get_modfcgid_supervisor at 0x7fb351190d90>, 'cpmodpy': <function get_cpmodpy_supervisor at 0x7fb3511907b8>, 'modpygw': <function get_modpygw_supervisor at 0x7fb351190c80>, 'modwsgi': <function get_modwsgi_supervisor at 0x7fb351190d08>, 'modfastcgi': <function get_modfastcgi_supervisor at 0x7fb351190e18>}
base()
date_tolerance = 2
default_server = 'wsgi'
do_gc_test = False
exit()
getPage(url, headers=None, method='GET', body=None, protocol=None, raise_subcls=None)

Open the url. Return status, headers, body.

raise_subcls must be a tuple with the exceptions classes or a single exception class that are not going to be considered a socket.error regardless that they were are subclass of a socket.error and therefore not considered for a connection retry.

prefix()
scheme = 'http'
script_name = ''
classmethod setup_class()
skip(msg='skipped ')
classmethod teardown_class()
test_gc()
class cherrypy.test.helper.LocalSupervisor(**kwargs)

Bases: cherrypy.test.helper.Supervisor

Base class for modeling/controlling servers which run in the same process.

When the server side runs in a different process, start/stop can dump all state between each test module easily. When the server side runs in the same process as the client, however, we have to do a bit more work to ensure config and mounted apps are reset between tests.

start(modulename=None)

Load and start the HTTP server.

stop()
sync_apps()

Tell the server about any apps which the setup functions mounted.

using_apache = False
using_wsgi = False
class cherrypy.test.helper.LocalWSGISupervisor(**kwargs)

Bases: cherrypy.test.helper.LocalSupervisor

Server supervisor for the builtin WSGI server.

get_app(app=None)

Obtain a new (decorated) WSGI app to hook into the origin server.

httpserver_class = 'cherrypy._cpwsgi_server.CPWSGIServer'
sync_apps()

Hook a new WSGI app into the origin server.

using_apache = False
using_wsgi = True
class cherrypy.test.helper.NativeServerSupervisor(**kwargs)

Bases: cherrypy.test.helper.LocalSupervisor

Server supervisor for the builtin HTTP server.

httpserver_class = 'cherrypy._cpnative_server.CPHTTPServer'
using_apache = False
using_wsgi = False
class cherrypy.test.helper.Supervisor(**kwargs)

Bases: object

Base class for modeling and controlling servers during testing.

cherrypy.test.helper.get_cpmodpy_supervisor(**options)
cherrypy.test.helper.get_modfastcgi_supervisor(**options)
cherrypy.test.helper.get_modfcgid_supervisor(**options)
cherrypy.test.helper.get_modpygw_supervisor(**options)
cherrypy.test.helper.get_modwsgi_supervisor(**options)
cherrypy.test.helper.get_tst_config(overconf={})
cherrypy.test.helper.get_wsgi_u_supervisor(**options)
cherrypy.test.helper.log_to_stderr(msg, level)
cherrypy.test.helper.setup_client()

Set up the WebCase classes to match the server’s socket settings.

cherrypy.test.logtest module

logtest, a unittest.TestCase helper for testing log output.

class cherrypy.test.logtest.LogCase

Bases: object

unittest.TestCase mixin for testing log messages.

logfile: a filename for the desired log. Yes, I know modes are evil,
but it makes the test functions so much cleaner to set this once.
lastmarker: the last marker in the log. This can be used to search for
messages since the last marker.
markerPrefix: a string with which to prefix log markers. This should be
unique enough from normal log output to use for marker identification.
assertInLog(line, marker=None)

Fail if the given (partial) line is not in the log.

The log will be searched from the given marker to the next marker. If marker is None, self.lastmarker is used. If the log hasn’t been marked (using self.markLog), the entire log will be searched.

assertLog(sliceargs, lines, marker=None)

Fail if log.readlines()[sliceargs] is not contained in ‘lines’.

The log will be searched from the given marker to the next marker. If marker is None, self.lastmarker is used. If the log hasn’t been marked (using self.markLog), the entire log will be searched.

assertNotInLog(line, marker=None)

Fail if the given (partial) line is in the log.

The log will be searched from the given marker to the next marker. If marker is None, self.lastmarker is used. If the log hasn’t been marked (using self.markLog), the entire log will be searched.

emptyLog()

Overwrite self.logfile with 0 bytes.

exit()
lastmarker = None
logfile = None
markLog(key=None)

Insert a marker line into the log and set self.lastmarker.

markerPrefix = b'test suite marker: '
cherrypy.test.logtest.getchar()

cherrypy.test.modfastcgi module

Wrapper for mod_fastcgi, for use as a CherryPy HTTP server when testing.

To autostart fastcgi, the “apache” executable or script must be on your system path, or you must override the global APACHE_PATH. On some platforms, “apache” may be called “apachectl”, “apache2ctl”, or “httpd”–create a symlink to them if needed.

You’ll also need the WSGIServer from flup.servers. See http://projects.amor.org/misc/wiki/ModPythonGateway

KNOWN BUGS

  1. Apache processes Range headers automatically; CherryPy’s truncated

    output is then truncated again by Apache. See test_core.testRanges. This was worked around in http://www.cherrypy.org/changeset/1319.

  2. Apache does not allow custom HTTP methods like CONNECT as per the spec.

    See test_core.testHTTPMethods.

  3. Max request header and body settings do not work with Apache.

  4. Apache replaces status “reason phrases” automatically. For example,

    CherryPy may set “304 Not modified” but Apache will write out “304 Not Modified” (capital “M”).

  5. Apache does not allow custom error codes as per the spec.

  6. Apache (or perhaps modpython, or modpython_gateway) unquotes %xx in the

    Request-URI too early.

  7. mod_python will not read request bodies which use the “chunked”

    transfer-coding (it passes REQUEST_CHUNKED_ERROR to ap_setup_client_block instead of REQUEST_CHUNKED_DECHUNK, see Apache2’s http_protocol.c and mod_python’s requestobject.c).

  8. Apache will output a “Content-Length: 0” response header even if there’s

    no response entity body. This isn’t really a bug; it just differs from the CherryPy default.

class cherrypy.test.modfastcgi.ModFCGISupervisor(**kwargs)

Bases: cherrypy.test.helper.LocalWSGISupervisor

httpserver_class = 'cherrypy.process.servers.FlupFCGIServer'
start(modulename)
start_apache()
stop()

Gracefully shutdown a server that is serving forever.

sync_apps()
template = '\n# Apache2 server conf file for testing CherryPy with mod_fastcgi.\n# fumanchu: I had to hard-code paths due to crazy Debian layouts :(\nServerRoot /usr/lib/apache2\nUser #1000\nErrorLog %(root)s/mod_fastcgi.error.log\n\nDocumentRoot "%(root)s"\nServerName 127.0.0.1\nListen %(port)s\nLoadModule fastcgi_module modules/mod_fastcgi.so\nLoadModule rewrite_module modules/mod_rewrite.so\n\nOptions +ExecCGI\nSetHandler fastcgi-script\nRewriteEngine On\nRewriteRule ^(.*)$ /fastcgi.pyc [L]\nFastCgiExternalServer "%(server)s" -host 127.0.0.1:4000\n'
using_apache = True
using_wsgi = True
cherrypy.test.modfastcgi.erase_script_name(environ, start_response)
cherrypy.test.modfastcgi.read_process(cmd, args='')

cherrypy.test.modfcgid module

Wrapper for mod_fcgid, for use as a CherryPy HTTP server when testing.

To autostart fcgid, the “apache” executable or script must be on your system path, or you must override the global APACHE_PATH. On some platforms, “apache” may be called “apachectl”, “apache2ctl”, or “httpd”–create a symlink to them if needed.

You’ll also need the WSGIServer from flup.servers. See http://projects.amor.org/misc/wiki/ModPythonGateway

KNOWN BUGS

  1. Apache processes Range headers automatically; CherryPy’s truncated

    output is then truncated again by Apache. See test_core.testRanges. This was worked around in http://www.cherrypy.org/changeset/1319.

  2. Apache does not allow custom HTTP methods like CONNECT as per the spec.

    See test_core.testHTTPMethods.

  3. Max request header and body settings do not work with Apache.

  4. Apache replaces status “reason phrases” automatically. For example,

    CherryPy may set “304 Not modified” but Apache will write out “304 Not Modified” (capital “M”).

  5. Apache does not allow custom error codes as per the spec.

  6. Apache (or perhaps modpython, or modpython_gateway) unquotes %xx in the

    Request-URI too early.

  7. mod_python will not read request bodies which use the “chunked”

    transfer-coding (it passes REQUEST_CHUNKED_ERROR to ap_setup_client_block instead of REQUEST_CHUNKED_DECHUNK, see Apache2’s http_protocol.c and mod_python’s requestobject.c).

  8. Apache will output a “Content-Length: 0” response header even if there’s

    no response entity body. This isn’t really a bug; it just differs from the CherryPy default.

class cherrypy.test.modfcgid.ModFCGISupervisor(**kwargs)

Bases: cherrypy.test.helper.LocalSupervisor

start(modulename)
start_apache()
stop()

Gracefully shutdown a server that is serving forever.

sync_apps()
template = '\n# Apache2 server conf file for testing CherryPy with mod_fcgid.\n\nDocumentRoot "%(root)s"\nServerName 127.0.0.1\nListen %(port)s\nLoadModule fastcgi_module modules/mod_fastcgi.dll\nLoadModule rewrite_module modules/mod_rewrite.so\n\nOptions ExecCGI\nSetHandler fastcgi-script\nRewriteEngine On\nRewriteRule ^(.*)$ /fastcgi.pyc [L]\nFastCgiExternalServer "%(server)s" -host 127.0.0.1:4000\n'
using_apache = True
using_wsgi = True
cherrypy.test.modfcgid.read_process(cmd, args='')

cherrypy.test.modpy module

Wrapper for mod_python, for use as a CherryPy HTTP server when testing.

To autostart modpython, the “apache” executable or script must be on your system path, or you must override the global APACHE_PATH. On some platforms, “apache” may be called “apachectl” or “apache2ctl”– create a symlink to them if needed.

If you wish to test the WSGI interface instead of our _cpmodpy interface, you also need the ‘modpython_gateway’ module at: http://projects.amor.org/misc/wiki/ModPythonGateway

KNOWN BUGS

  1. Apache processes Range headers automatically; CherryPy’s truncated

    output is then truncated again by Apache. See test_core.testRanges. This was worked around in http://www.cherrypy.org/changeset/1319.

  2. Apache does not allow custom HTTP methods like CONNECT as per the spec.

    See test_core.testHTTPMethods.

  3. Max request header and body settings do not work with Apache.

  4. Apache replaces status “reason phrases” automatically. For example,

    CherryPy may set “304 Not modified” but Apache will write out “304 Not Modified” (capital “M”).

  5. Apache does not allow custom error codes as per the spec.

  6. Apache (or perhaps modpython, or modpython_gateway) unquotes %xx in the

    Request-URI too early.

  7. mod_python will not read request bodies which use the “chunked”

    transfer-coding (it passes REQUEST_CHUNKED_ERROR to ap_setup_client_block instead of REQUEST_CHUNKED_DECHUNK, see Apache2’s http_protocol.c and mod_python’s requestobject.c).

  8. Apache will output a “Content-Length: 0” response header even if there’s

    no response entity body. This isn’t really a bug; it just differs from the CherryPy default.

class cherrypy.test.modpy.ModPythonSupervisor(**kwargs)

Bases: cherrypy.test.helper.Supervisor

start(modulename)
stop()

Gracefully shutdown a server that is serving forever.

template = None
using_apache = True
using_wsgi = False
cherrypy.test.modpy.cpmodpysetup(req)
cherrypy.test.modpy.read_process(cmd, args='')
cherrypy.test.modpy.wsgisetup(req)

cherrypy.test.modwsgi module

Wrapper for mod_wsgi, for use as a CherryPy HTTP server.

To autostart modwsgi, the “apache” executable or script must be on your system path, or you must override the global APACHE_PATH. On some platforms, “apache” may be called “apachectl” or “apache2ctl”– create a symlink to them if needed.

KNOWN BUGS

##1. Apache processes Range headers automatically; CherryPy’s truncated ## output is then truncated again by Apache. See test_core.testRanges. ## This was worked around in http://www.cherrypy.org/changeset/1319. 2. Apache does not allow custom HTTP methods like CONNECT as per the spec.

See test_core.testHTTPMethods.

3. Max request header and body settings do not work with Apache. ##4. Apache replaces status “reason phrases” automatically. For example, ## CherryPy may set “304 Not modified” but Apache will write out ## “304 Not Modified” (capital “M”). ##5. Apache does not allow custom error codes as per the spec. ##6. Apache (or perhaps modpython, or modpython_gateway) unquotes %xx in the ## Request-URI too early. 7. mod_wsgi will not read request bodies which use the “chunked”

transfer-coding (it passes REQUEST_CHUNKED_ERROR to ap_setup_client_block instead of REQUEST_CHUNKED_DECHUNK, see Apache2’s http_protocol.c and mod_python’s requestobject.c).
  1. When responding with 204 No Content, mod_wsgi adds a Content-Length

    header for you.

  2. When an error is raised, mod_wsgi has no facility for printing a

    traceback as the response content (it’s sent to the Apache log instead).

  3. Startup and shutdown of Apache when running mod_wsgi seems slow.

class cherrypy.test.modwsgi.ModWSGISupervisor(**kwargs)

Bases: cherrypy.test.helper.Supervisor

Server Controller for ModWSGI and CherryPy.

start(modulename)
stop()

Gracefully shutdown a server that is serving forever.

template = '\n# Apache2 server conf file for testing CherryPy with modpython_gateway.\n\nServerName 127.0.0.1\nDocumentRoot "/"\nListen %(port)s\n\nAllowEncodedSlashes On\nLoadModule rewrite_module modules/mod_rewrite.so\nRewriteEngine on\nRewriteMap escaping int:escape\n\nLoadModule log_config_module modules/mod_log_config.so\nLogFormat "%%h %%l %%u %%t \\"%%r\\" %%>s %%b \\"%%{Referer}i\\" \\"%%{User-agent}i\\"" combined\nCustomLog "%(curdir)s/apache.access.log" combined\nErrorLog "%(curdir)s/apache.error.log"\nLogLevel debug\n\nLoadModule wsgi_module modules/mod_wsgi.so\nLoadModule env_module modules/mod_env.so\n\nWSGIScriptAlias / "%(curdir)s/modwsgi.py"\nSetEnv testmod %(testmod)s\n'
using_apache = True
using_wsgi = True
cherrypy.test.modwsgi.application(environ, start_response)
cherrypy.test.modwsgi.read_process(cmd, args='')

cherrypy.test.sessiondemo module

A session demonstration app.

class cherrypy.test.sessiondemo.Root

Bases: object

expire()
index()
page()
regen()

cherrypy.test.test_auth_basic module

class cherrypy.test.test_auth_basic.BasicAuthTest(methodName='runTest')

Bases: cherrypy.test.helper.CPWebCase

static setup_server()
testBasic()
testBasic2()
testPublic()

cherrypy.test.test_auth_digest module

class cherrypy.test.test_auth_digest.DigestAuthTest(methodName='runTest')

Bases: cherrypy.test.helper.CPWebCase

static setup_server()
testDigest()
testPublic()

cherrypy.test.test_bus module

class cherrypy.test.test_bus.BusMethodTests(methodName='runTest')

Bases: unittest.case.TestCase

assertLog(entries)
get_listener(channel, index)
log(bus)
test_block()
test_exit()
test_graceful()
test_log()
test_start()
test_start_with_callback()
test_stop()
test_wait()
class cherrypy.test.test_bus.PublishSubscribeTests(methodName='runTest')

Bases: unittest.case.TestCase

get_listener(channel, index)
test_builtin_channels()
test_custom_channels()
test_listener_errors()

cherrypy.test.test_caching module

class cherrypy.test.test_caching.CacheTest(methodName='runTest')

Bases: cherrypy.test.helper.CPWebCase

static setup_server()
testCaching()
testExpiresTool()
testLastModified()
testVaryHeader()
test_antistampede()
test_cache_control()

cherrypy.test.test_compat module

class cherrypy.test.test_compat.StringTester(methodName='runTest')

Bases: unittest.case.TestCase

test_ntob_non_native()

ntob should raise an Exception on unicode. (Python 2 only)

See #1132 for discussion.

cherrypy.test.test_config module

Tests for the CherryPy configuration system.

class cherrypy.test.test_config.CallablesInConfigTest(methodName='runTest')

Bases: unittest.case.TestCase

static setup_server()
test_call_with_kwargs()
test_call_with_literal_dict()
class cherrypy.test.test_config.ConfigTests(methodName='runTest')

Bases: cherrypy.test.helper.CPWebCase

static setup_server()
testConfig()
testCustomNamespaces()
testHandlerToolConfigOverride()
testRespNamespaces()
testUnrepr()
test_request_body_namespace()
cherrypy.test.test_config.StringIOFromNative(x)
class cherrypy.test.test_config.VariableSubstitutionTests(methodName='runTest')

Bases: unittest.case.TestCase

static setup_server()
test_config()
cherrypy.test.test_config.setup_server()

cherrypy.test.test_config_server module

Tests for the CherryPy configuration system.

class cherrypy.test.test_config_server.ServerConfigTests(methodName='runTest')

Bases: cherrypy.test.helper.CPWebCase

PORT = 9876
static setup_server()
testAdditionalServers()
testBasicConfig()
testMaxRequestSize()
testMaxRequestSizePerHandler()

cherrypy.test.test_conn module

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

class cherrypy.test.test_conn.BadRequestTests(methodName='runTest')

Bases: cherrypy.test.helper.CPWebCase

static setup_server()
test_No_CRLF()
class cherrypy.test.test_conn.ConnectionCloseTests(methodName='runTest')

Bases: cherrypy.test.helper.CPWebCase

static setup_server()
test_HTTP10_KeepAlive()
test_HTTP11()
test_Streaming_no_len()
test_Streaming_with_len()
class cherrypy.test.test_conn.ConnectionTests(methodName='runTest')

Bases: cherrypy.test.helper.CPWebCase

static setup_server()
test_598()
test_Chunked_Encoding()
test_Content_Length_in()
test_Content_Length_out_postheaders()
test_Content_Length_out_preheaders()
test_No_Message_Body()
test_readall_or_close()
class cherrypy.test.test_conn.LimitedRequestQueueTests(methodName='runTest')

Bases: cherrypy.test.helper.CPWebCase

static setup_server()
test_queue_full()
class cherrypy.test.test_conn.PipelineTests(methodName='runTest')

Bases: cherrypy.test.helper.CPWebCase

static setup_server()
test_100_Continue()
test_HTTP11_Timeout()
test_HTTP11_Timeout_after_request()
test_HTTP11_pipelining()
cherrypy.test.test_conn.setup_server()
cherrypy.test.test_conn.setup_upload_server()
cherrypy.test.test_conn.socket_reset_errors = [104, 'Remote end closed connection without response']

reset error numbers available on this platform

cherrypy.test.test_core module

Basic tests for the CherryPy core: request handling.

class cherrypy.test.test_core.CoreRequestHandlingTest(methodName='runTest')

Bases: cherrypy.test.helper.CPWebCase

static setup_server()
skip_if_bad_cookies()

cookies module fails to reject invalid cookies https://github.com/cherrypy/cherrypy/issues/1405

testCookies()
testDefaultContentType()
testFavicon()
testFlatten()
testRanges()
testRedirect()
testSlashes()
testStatus()
test_InternalRedirect()
test_cherrypy_url()
test_expose_decorator()
test_multiple_headers()
test_on_end_resource_status()
test_redirect_with_unicode()

A redirect to a URL with Unicode should return a Location header containing that Unicode URL.

class cherrypy.test.test_core.ErrorTests(methodName='runTest')

Bases: cherrypy.test.helper.CPWebCase

static setup_server()
test_contextmanager()
test_start_response_error()

cherrypy.test.test_dynamicobjectmapping module

class cherrypy.test.test_dynamicobjectmapping.DynamicObjectMappingTest(methodName='runTest')

Bases: cherrypy.test.helper.CPWebCase

static setup_server()
testMethodDispatch()
testObjectMapping()
testVpathDispatch()
cherrypy.test.test_dynamicobjectmapping.setup_server()

cherrypy.test.test_encoding module

class cherrypy.test.test_encoding.EncodingTests(methodName='runTest')

Bases: cherrypy.test.helper.CPWebCase

static setup_server()
testEncoding()
testGzip()
test_UnicodeHeaders()
test_decode_tool()
test_multipart_decoding()
test_multipart_decoding_bigger_maxrambytes()

Decoding of a multipart entity should also pass when the entity is bigger than maxrambytes. See ticket #1352.

test_multipart_decoding_no_charset()
test_multipart_decoding_no_successful_charset()
test_nontext()
test_query_string_decoding()
test_urlencoded_decoding()

cherrypy.test.test_etags module

class cherrypy.test.test_etags.ETagTest(methodName='runTest')

Bases: cherrypy.test.helper.CPWebCase

static setup_server()
test_errors()
test_etags()
test_unicode_body()

cherrypy.test.test_http module

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

class cherrypy.test.test_http.HTTPTests(methodName='runTest')

Bases: cherrypy.test.helper.CPWebCase

make_connection()
static setup_server()
test_garbage_in()
test_http_over_https()
test_malformed_header()
test_malformed_request_line()
test_no_content_length()
test_post_filename_with_special_characters()

Testing that we can handle filenames with special characters. This was reported as a bug in:

test_post_multipart()
test_request_line_split_issue_1220()
cherrypy.test.test_http.encode_multipart_formdata(files)

Return (content_type, body) ready for httplib.HTTP instance.

files: a sequence of (name, filename, value) tuples for multipart uploads.

cherrypy.test.test_httpauth module

class cherrypy.test.test_httpauth.HTTPAuthTest(methodName='runTest')

Bases: cherrypy.test.helper.CPWebCase

static setup_server()
testBasic()
testBasic2()
testDigest()
testPublic()

cherrypy.test.test_httplib module

Tests for cherrypy/lib/httputil.py.

class cherrypy.test.test_httplib.UtilityTests(methodName='runTest')

Bases: unittest.case.TestCase

test_urljoin()

cherrypy.test.test_json module

class cherrypy.test.test_json.JsonTest(methodName='runTest')

Bases: cherrypy.test.helper.CPWebCase

static setup_server()
test_cached()
test_json_input()
test_json_output()

cherrypy.test.test_logging module

Basic tests for the CherryPy core: request handling.

class cherrypy.test.test_logging.AccessLogTests(methodName='runTest')

Bases: cherrypy.test.helper.CPWebCase, cherrypy.test.logtest.LogCase

logfile = '/home/docs/checkouts/readthedocs.org/user_builds/cherrypy/checkouts/latest/docs/../cherrypy/test/access.log'
static setup_server()
testCustomLogFormat()

Test a customized access_log_format string, which is a feature of _cplogging.LogManager.access()

testEscapedOutput()
testNormalReturn()
testNormalYield()
class cherrypy.test.test_logging.ErrorLogTests(methodName='runTest')

Bases: cherrypy.test.helper.CPWebCase, cherrypy.test.logtest.LogCase

logfile = '/home/docs/checkouts/readthedocs.org/user_builds/cherrypy/checkouts/latest/docs/../cherrypy/test/error.log'
static setup_server()
testTracebacks()
cherrypy.test.test_logging.setup_server()

cherrypy.test.test_mime module

Tests for various MIME issues, including the safe_multipart Tool.

class cherrypy.test.test_mime.MultipartTest(methodName='runTest')

Bases: cherrypy.test.helper.CPWebCase

static setup_server()
test_multipart()
test_multipart_form_data()
class cherrypy.test.test_mime.SafeMultipartHandlingTest(methodName='runTest')

Bases: cherrypy.test.helper.CPWebCase

static setup_server()
test_Flash_Upload()
cherrypy.test.test_mime.setup_server()

cherrypy.test.test_misc_tools module

class cherrypy.test.test_misc_tools.AcceptTest(methodName='runTest')

Bases: cherrypy.test.helper.CPWebCase

static setup_server()
test_Accept_Tool()
test_accept_selection()
class cherrypy.test.test_misc_tools.AutoVaryTest(methodName='runTest')

Bases: cherrypy.test.helper.CPWebCase

static setup_server()
testAutoVary()
class cherrypy.test.test_misc_tools.RefererTest(methodName='runTest')

Bases: cherrypy.test.helper.CPWebCase

static setup_server()
testReferer()
class cherrypy.test.test_misc_tools.ResponseHeadersTest(methodName='runTest')

Bases: cherrypy.test.helper.CPWebCase

static setup_server()
testResponseHeaders()
testResponseHeadersDecorator()
cherrypy.test.test_misc_tools.setup_server()

cherrypy.test.test_objectmapping module

class cherrypy.test.test_objectmapping.ObjectMappingTest(methodName='runTest')

Bases: cherrypy.test.helper.CPWebCase

static setup_server()
testExpose()
testKeywords()
testMethodDispatch()
testObjectMapping()
testPositionalParams()
testTreeMounting()
test_redir_using_url()
test_translate()

cherrypy.test.test_proxy module

class cherrypy.test.test_proxy.ProxyTest(methodName='runTest')

Bases: cherrypy.test.helper.CPWebCase

static setup_server()
testProxy()

cherrypy.test.test_refleaks module

Tests for refleaks.

class cherrypy.test.test_refleaks.ReferenceTests(methodName='runTest')

Bases: cherrypy.test.helper.CPWebCase

static setup_server()
test_threadlocal_garbage()

cherrypy.test.test_request_obj module

Basic tests for the cherrypy.Request object.

class cherrypy.test.test_request_obj.RequestObjectTests(methodName='runTest')

Bases: cherrypy.test.helper.CPWebCase

static setup_server()
testAbsoluteURIPathInfo()
testEmptyThreadlocals()
testErrorHandling()
testExpect()
testHeaderElements()
testParamErrors()
testParams()
testRelativeURIPathInfo()
test_CONNECT_method()
test_basic_HTTPMethods()
test_encoded_headers()
test_header_presence()
test_repeated_headers()
test_scheme()

cherrypy.test.test_routes module

class cherrypy.test.test_routes.RoutesDispatchTest(methodName='runTest')

Bases: cherrypy.test.helper.CPWebCase

static setup_server()
test_Routes_Dispatch()

cherrypy.test.test_session module

class cherrypy.test.test_session.MemcachedSessionTest(methodName='runTest')

Bases: cherrypy.test.helper.CPWebCase

static setup_server()
test()
class cherrypy.test.test_session.SessionTest(methodName='runTest')

Bases: cherrypy.test.helper.CPWebCase

static setup_server()
tearDown()
test_0_Session()
test_1_Ram_Concurrency()
test_2_File_Concurrency()
test_3_Redirect()
test_4_File_deletion()
test_5_Error_paths()
test_6_regenerate()
test_7_session_cookies()
test_8_Ram_Cleanup()
cherrypy.test.test_session.http_methods_allowed(methods=['GET', 'HEAD'])
cherrypy.test.test_session.setup_server()

cherrypy.test.test_sessionauthenticate module

class cherrypy.test.test_sessionauthenticate.SessionAuthenticateTest(methodName='runTest')

Bases: cherrypy.test.helper.CPWebCase

static setup_server()
testSessionAuthenticate()

cherrypy.test.test_states module

class cherrypy.test.test_states.Dependency(bus)

Bases: object

graceful()
start()
startthread(thread_id)
stop()
stopthread(thread_id)
subscribe()
class cherrypy.test.test_states.PluginTests(methodName='runTest')

Bases: cherrypy.test.helper.CPWebCase

test_daemonize()
class cherrypy.test.test_states.ServerStateTests(methodName='runTest')

Bases: cherrypy.test.helper.CPWebCase

setUp()
static setup_server()
test_0_NormalStateFlow()
test_1_Restart()
test_2_KeyboardInterrupt()
test_3_Deadlocks()
test_4_Autoreload()
test_5_Start_Error()
class cherrypy.test.test_states.SignalHandlingTests(methodName='runTest')

Bases: cherrypy.test.helper.CPWebCase

test_SIGHUP_daemonized()
test_SIGHUP_tty()
test_SIGTERM()

SIGTERM should shut down the server whether daemonized or not.

test_signal_handler_unsubscribe()
class cherrypy.test.test_states.WaitTests(methodName='runTest')

Bases: unittest.case.TestCase

find_free_port()

Find a free port by binding to port 0 then unbinding.

test_wait_for_occupied_port_INADDR_ANY()

Wait on INADDR_ANY should not raise IOError

In cases where the loopback interface does not exist, CherryPy cannot effectively determine if a port binding to INADDR_ANY was effected. In this situation, CherryPy should assume that it failed to detect the binding (not that the binding failed) and only warn that it could not verify it.

cherrypy.test.test_states.setup_server()

cherrypy.test.test_static module

class cherrypy.test.test_static.StaticTest(methodName='runTest')

Bases: cherrypy.test.helper.CPWebCase

static setup_server()
static teardown_server()
test_755_vhost()
test_config_errors()
test_error_page_with_serve_file()
test_fallthrough()
test_file_stream()
test_file_stream_deadlock()
test_index()
test_modif()
test_null_bytes()
test_security()
test_serve_bytesio()
test_serve_fileobj()
test_static()
test_unicode()
static unicode_file()
cherrypy.test.test_static.error_page_404(status, message, traceback, version)

cherrypy.test.test_tools module

Test the various means of instantiating and invoking tools.

class cherrypy.test.test_tools.SessionAuthTest(methodName='runTest')

Bases: unittest.case.TestCase

test_login_screen_returns_bytes()

login_screen must return bytes even if unicode parameters are passed. Issue 1132 revealed that login_screen would return unicode if the username and password were unicode.

class cherrypy.test.test_tools.ToolTests(methodName='runTest')

Bases: cherrypy.test.helper.CPWebCase

static setup_server()
testBareHooks()
testCombinedTools()
testDecorator()
testEndRequestOnDrop()
testGuaranteedHooks()
testHandlerWrapperTool()
testHookErrors()
testToolWithConfig()
testWarnToolOn()

cherrypy.test.test_tutorials module

class cherrypy.test.test_tutorials.TutorialTest(methodName='runTest')

Bases: cherrypy.test.helper.CPWebCase

static load_module(name)

Import or reload tutorial module as needed.

classmethod setup_server()

Mount something so the engine starts.

classmethod setup_tutorial(name, root_name, config={})
test01HelloWorld()
test02ExposeMethods()
test03GetAndPost()
test04ComplexSite()
test05DerivedObjects()
test06DefaultMethod()
test07Sessions()
test08GeneratorsAndYield()
test09Files()
test10HTTPErrors()

cherrypy.test.test_virtualhost module

class cherrypy.test.test_virtualhost.VirtualHostTest(methodName='runTest')

Bases: cherrypy.test.helper.CPWebCase

static setup_server()
testVirtualHost()
test_VHost_plus_Static()

cherrypy.test.test_wsgi_ns module

class cherrypy.test.test_wsgi_ns.WSGI_Namespace_Test(methodName='runTest')

Bases: cherrypy.test.helper.CPWebCase

static setup_server()
test_pipeline()

cherrypy.test.test_wsgi_vhost module

class cherrypy.test.test_wsgi_vhost.WSGI_VirtualHost_Test(methodName='runTest')

Bases: cherrypy.test.helper.CPWebCase

static setup_server()
test_welcome()

cherrypy.test.test_wsgiapps module

class cherrypy.test.test_wsgiapps.WSGIGraftTests(methodName='runTest')

Bases: cherrypy.test.helper.CPWebCase

static setup_server()
test_01_standard_app()
test_04_pure_wsgi()
test_05_wrapped_cp_app()
test_06_empty_string_app()
wsgi_output = 'Hello, world!\nThis is a wsgi app running within CherryPy!'

cherrypy.test.test_xmlrpc module

class cherrypy.test.test_xmlrpc.XmlRpcTest(methodName='runTest')

Bases: cherrypy.test.helper.CPWebCase

static setup_server()
testXmlRpc()
cherrypy.test.test_xmlrpc.setup_server()

cherrypy.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 cherrypy.test.webtest.NonDataProperty(fget)

Bases: object

class cherrypy.test.webtest.ReloadingTestLoader

Bases: unittest.loader.TestLoader

loadTestsFromName(name, module=None)

Return a suite of all tests cases given a string specifier.

The name may resolve either to a module, a test case class, a test method within a test case class, or a callable object which returns a TestCase or TestSuite instance.

The method optionally resolves the names relative to a given module.

exception cherrypy.test.webtest.ServerError

Bases: Exception

on = False
class cherrypy.test.webtest.TerseTestResult(stream, descriptions, verbosity)

Bases: unittest.runner.TextTestResult

printErrors()
class cherrypy.test.webtest.TerseTestRunner(stream=None, descriptions=True, verbosity=1, failfast=False, buffer=False, resultclass=None, warnings=None)

Bases: unittest.runner.TextTestRunner

A test runner class that displays results in textual form.

run(test)

Run the given test case or test suite.

class cherrypy.test.webtest.WebCase(methodName='runTest')

Bases: unittest.case.TestCase

HOST = '127.0.0.1'
HTTP_CONN

alias of 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.

assertNotInBody(value, msg=None)

Fail if value in self.body.

assertStatus(status, msg=None)

Fail if self.status != status.

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

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

raise_subcls must be a tuple with the exceptions classes or a single exception class that are not going to be considered a socket.error regardless that they were are subclass of a socket.error and therefore not considered for a connection retry.

get_conn(auto_open=False)

Return a connection to our HTTP server.

headers = None
interactive
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.

persistent
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 HTTPConnection (or HTTPS if self.scheme is “https”). This will then persist across requests.

We only allow for a single open connection, so if you call this and we currently have an open connection, it will be closed.

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

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

cherrypy.test.webtest.getchar()
cherrypy.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.

cherrypy.test.webtest.openURL(url, headers=None, method='GET', body=None, host='127.0.0.1', port=8000, http_conn=<class 'http.client.HTTPConnection'>, protocol='HTTP/1.1', raise_subcls=None)

Open the given HTTP resource and return status, headers, and body.

raise_subcls must be a tuple with the exceptions classes or a single exception class that are not going to be considered a socket.error regardless that they were are subclass of a socket.error and therefore not considered for a connection retry.

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

cherrypy.test.webtest.shb(response)

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

Module contents

Regression test suite for CherryPy.

Run ‘nosetests -s test/’ to exercise all tests.

The ‘-s’ flag instructs nose to output stdout messages, wihch is crucial to the ‘interactive’ mode of webtest.py. If you run these tests without the ‘-s’ flag, don’t be surprised if the test seems to hang: it’s waiting for your interactive input.

cherrypy.test.newexit()
cherrypy.test.setup()
cherrypy.test.teardown()