API Reference

zope.testing.cleanup

Provide a standard cleanup registry

Unit tests that change global data should include the CleanUp base class, which provides simpler setUp and tearDown methods that call global-data cleanup routines:

class Test(CleanUp, unittest.TestCase):

    ....

If custom setUp or tearDown are needed, then the base routines should be called, as in:

def tearDown(self):
    super(Test, self).tearDown()
    ....

Cleanup routines for global data should be registered by passing them to addCleanup:

addCleanUp(pigRegistry._clear)
zope.testing.cleanup.addCleanUp(func, args=(), kw={})[source]

Register a cleanup routines

Pass a function to be called to cleanup global data. Optional argument tuple and keyword arguments may be passed.

class zope.testing.cleanup.CleanUp[source]

Bases: object

Mix-in class providing clean-up setUp and tearDown routines.

cleanUp()[source]

Clean up global data.

setUp()

Clean up global data.

tearDown()

Clean up global data.

zope.testing.cleanup.cleanUp()[source]

Clean up global data.

zope.testing.cleanup.setUp()

Clean up global data.

zope.testing.cleanup.tearDown()

Clean up global data.

zope.testing.doctestcase

Doctests in TestCase classes

zope.testing.doctestcase.doctestmethod(test=None, optionflags=0, checker=None)[source]

Define a doctest from a method within a unittest.TestCase.

The method’s doc string provides the test source. Its body is called before the test and may perform test-specific setup.

You can pass doctest option flags and a custon checker.

Variables defined in the enclosing module are available in the test.

If a test case defines a globs attribute, it must be a dictionary and its contents are added to the test globals.

The test object is available as the variable self in the test.

zope.testing.doctestcase.method(test=None, optionflags=0, checker=None)

Alias of doctestmethod

zope.testing.doctestcase.docteststring(test, optionflags=0, checker=None, name=None)[source]

Define a doctest from a string within a unittest.TestCase.

You can pass doctest option flags and a custon checker.

Variables defined in the enclosing module are available in the test.

If a test case defines a globs attribute, it must be a dictionary and its contents are added to the test globals.

The test object is available as the variable self in the test.

zope.testing.doctestcase.string(test, optionflags=0, checker=None, name=None)

Alias of docteststring

zope.testing.doctestcase.doctestfile(path, optionflags=0, checker=None)[source]

Define a doctest from a test file within a unittest.TestCase.

The file path may be relative or absolute. If its relative (the common case), it will be interpreted relative to the directory containing the referencing module.

You can pass doctest option flags and a custon checker.

If a test case defines a globs attribute, it must be a dictionary and its contents are added to the test globals.

The test object is available as the variable test in the test.

The resulting object can be used as a function decorator. The decorated method is called before the test and may perform test-specific setup. (The decorated method’s doc string is ignored.)

zope.testing.doctestcase.file(path, optionflags=0, checker=None)

Alias of doctestfile

zope.testing.doctestcase.doctestfiles(*paths, **kw)[source]

Define doctests from test files in a decorated class.

Multiple files can be specified. A member is added to the decorated class for each file.

The file paths may be relative or absolute. If relative (the common case), they will be interpreted relative to the directory containing the referencing module.

You can pass doctest option flags and a custon checker.

If a test case defines a globs attribute, it must be a dictionary and its contents are added to the test globals.

The test object is available as the variable test in the test.

The resulting object must be used as a class decorator.

zope.testing.doctestcase.files(*paths, **kw)

Alias of doctestfiles

zope.testing.exceptions

Exceptions for zope.testing

exception zope.testing.exceptions.DocTestFailureException[source]

Bases: AssertionError

Use custom exception for doctest unit test failures

zope.testing.formparser

HTML parser that extracts form information.

This is intended to support functional tests that need to extract information from HTML forms returned by the publisher.

See Parsing HTML Forms for documentation.

This isn’t intended to simulate a browser session; that’s provided by the zope.testbrowser package.

Changed in version 4.10.0: Add support for Python 3.

zope.testing.formparser.parse(data, base=None)[source]

Return a form collection parsed from data.

base should be the URL from which data was retrieved.

class zope.testing.formparser.FormParser(data, base=None)[source]

Bases: object

The parser.

parse()[source]

Parse the document, returning the collection of forms.

zope.testing.formparser.kwattr(d, name, default=None)[source]

Return attribute, converted to lowercase.

zope.testing.formparser.intattr(d, name)[source]

Return attribute as an integer, or None.

class zope.testing.formparser.FormCollection(iterable=(), /)[source]

Bases: list

Collection of all forms from a page.

class zope.testing.formparser.Form(name, id, method, action, enctype)[source]

Bases: dict

A specific form within a page.

class zope.testing.formparser.Input(name, id, type, value, checked, disabled, readonly, src, size, maxlength)[source]

Bases: object

Input element.

class zope.testing.formparser.Select(name, id, disabled, multiple, size)[source]

Bases: Input

Select element.

class zope.testing.formparser.Option(id, value, selected, label, disabled)[source]

Bases: object

Individual value representation for a select element.

zope.testing.loggingsupport

class zope.testing.loggingsupport.Handler(*names, **kw)[source]

Bases: Handler

A logging.Handler that collects logging records that are emitted by the loggers named in names.

You must call install to begin collecting records, and before destroying this object you must call uninstall.

Initializes the instance - basically setting the formatter to None and the filter list to empty.

emit(record)[source]

Save the given record in self.records.

clear()[source]

Delete all records collecting by this object.

install()[source]

Begin collecting logging records for all the logger names given to the constructor.

uninstall()[source]

Stop collecting logging records.

class zope.testing.loggingsupport.InstalledHandler(*names, **kw)[source]

Bases: Handler

A Handler that automatically calls install when constructed.

You must still manually call uninstall.

Initializes the instance - basically setting the formatter to None and the filter list to empty.

zope.testing.loghandler

logging handler for tests that check logging output.

Caution

This is deprecated and may not work on Python 3.

class zope.testing.loghandler.Handler(testcase, propagate=False)[source]

Bases: Handler

Handler for use with unittest.TestCase objects.

The handler takes a TestCase instance as a constructor argument. It can be registered with one or more loggers and collects log records they generate.

The assertLogsMessage and failIfLogsMessage methods can be used to check the logger output and causes the test to fail as appropriate.

Initializes the instance - basically setting the formatter to None and the filter list to empty.

close()[source]

Remove handler from any loggers it was added to.

add(name)[source]

Add handler to logger named name.

emit(record)[source]

Do whatever it takes to actually log the specified logging record.

This version is intended to be implemented by subclasses and so raises a NotImplementedError.

assertLogsMessage(msg, level=None)[source]

Check that a record whose message equals msg (and optionally at level) has been emitted, failing if not.

failIfLogsMessage(msg)[source]

Check that a record whose message equals msg has not been emitted, failing if it has.

zope.testing.module

Fake module support.

See Module setup for documentation.

zope.testing.module.setUp(test, name='__main__')[source]

Replace the module named name with a fake version.

zope.testing.module.tearDown(test, name=None)[source]

Remove the (fake) module named name.

zope.testing.renormalizing

Support for advanced normalization of output in doctests.

See Regular expression pattern normalizing output checker for documentation.

class zope.testing.renormalizing.OutputChecker(patterns=None)[source]

Bases: OutputChecker

Pattern-normalizing output checker

check_output(want, got, optionflags)[source]

Return True iff the actual output from an example (got) matches the expected output (want). These strings are always considered to match if they are identical; but depending on what option flags the test runner is using, several non-exact match types are also possible. See the documentation for TestRunner for more information about option flags.

output_difference(example, got, optionflags)[source]

Return a string describing the differences between the expected output for a given example (example) and the actual output (got). optionflags is the set of option flags used to compare want and got.

zope.testing.renormalizing.RENormalizing

alias of OutputChecker

zope.testing.server

Functional test server to interactively inspect the state of the system.

You can run it in a functional test by adding a line like this:

startServer(http, url, “username”, “password”)

http is an instance of HTTPCaller, url is the url that will be opened in the browser, the username and password are optional. When you’re done with inspecting the application press Ctrl+C to continue with the functional test.

zope.testing.server.addPortToURL(url, port)[source]

Add a port number to the url.

>>> from zope.testing.server import addPortToURL
>>> addPortToURL('http://localhost/foo/bar/baz.html', 3000)
'http://localhost:3000/foo/bar/baz.html'
>>> addPortToURL('http://foo.bar.com/index.html?param=some-value', 555)
'http://foo.bar.com:555/index.html?param=some-value'
>>> addPortToURL('http://localhost:666/index.html', 555)
'http://localhost:555/index.html'

zope.testing.setupstack

Stack-based test doctest setUp and tearDown

See Stack-based test setUp and tearDown

zope.testing.setupstack.globs(test)[source]

Return the globals for test, which can be a doctest or a regular unittest.TestCase.

zope.testing.setupstack.register(test, function, *args, **kw)[source]

Add a clean up function to be called with args and kw when test is torn down.

Clean up functions are called in the reverse order of registration.

zope.testing.setupstack.tearDown(test)[source]

Call all the clean up functions registered for test, in the reverse of their registration order.

zope.testing.setupstack.setUpDirectory(test)[source]

Create and change to a temporary directory, and register rmtree to clean it up. Returns to the starting directory when finished.

zope.testing.setupstack.rmtree(path)[source]

Remove all the files and directories found in path.

Intended to be used as a clean up function with register.

zope.testing.setupstack.context_manager(test, manager)[source]

A stack-based version of the with statement.

The context manager manager is entered when this method is called, and it is exited when the test is torn down.

zope.testing.setupstack.mock(test, *args, **kw)[source]

Patch an object by calling unittest.mock.patch with the args and kw given, and returns the result.

This will be torn down when the test is torn down.

Note

On Python 2, you must manually install the mock package.

class zope.testing.setupstack.TestCase(methodName='runTest')[source]

Bases: TestCase

A TestCase base class that overrides tearDown to use the function from this module.

In addition, it provides other methods using the functions in this module:

Create an instance of the class that will use the named test method when executed. Raises a ValueError if the instance does not have a method with the specified name.

tearDown()

Call all the clean up functions registered for test, in the reverse of their registration order.

register(function, *args, **kw)

Add a clean up function to be called with args and kw when test is torn down.

Clean up functions are called in the reverse order of registration.

setUpDirectory()

Create and change to a temporary directory, and register rmtree to clean it up. Returns to the starting directory when finished.

context_manager(manager)

A stack-based version of the with statement.

The context manager manager is entered when this method is called, and it is exited when the test is torn down.

mock(*args, **kw)

Patch an object by calling unittest.mock.patch with the args and kw given, and returns the result.

This will be torn down when the test is torn down.

Note

On Python 2, you must manually install the mock package.

zope.testing.wait

Provides a class, Wait, and an instance, wait, that can be used for polling for a condition to become true, or raise an exception after a timeout.

class zope.testing.wait.Wait(timeout=None, wait=None, exception=None, getnow=<function Wait.<lambda>>, getsleep=<function Wait.<lambda>>)[source]

Bases: object

A callable object that polls until func returns a true value, sleeping wait seconds between polling attempts.

If timeout seconds elapse, exception will be raised.

timeout = 9

The default timeout value.

wait = 0.01

The default amount of time to sleep between polls.

exception TimeOutWaitingFor[source]

Bases: Exception

The default exception raised when a test condition timed out.

zope.testing.wait.wait = <zope.testing.wait.Wait object>

The default instance of Wait.