Contents
This package provides a number of testing frameworks.
An HTML parser that extracts form information.
Python 2 only
This is intended to support functional tests that need to extract information from HTML forms returned by the publisher.
See formparser.txt.
Support for testing logging code
If you want to test that your code generates proper log output, you can create and install a handler that collects output.
Lets a doctest pretend to be a Python module.
See module.txt.
Provides a simple HTTP server compatible with the zope.app.testing functional testing API. Lets you interactively play with the system under test. Helpful in debugging functional doctest failures.
Python 2 only
zope.testing uses buildout. To start, run python bootstrap.py. It will create a number of directories and the bin/buildout script. Next, run bin/buildout. It will create a test script for you. Now, run bin/test to run the zope.testing test suite.
Sometimes in functional tests, information from a generated form must be extracted in order to re-submit it as part of a subsequent request. The zope.testing.formparser module can be used for this purpose.
The scanner is implemented using the FormParser class. The constructor arguments are the page data containing the form and (optionally) the URL from which the page was retrieved:
>>> import zope.testing.formparser>>> page_text = '''\ ... <html><body> ... <form name="form1" action="/cgi-bin/foobar.py" method="POST"> ... <input type="hidden" name="f1" value="today" /> ... <input type="submit" name="do-it-now" value="Go for it!" /> ... <input type="IMAGE" name="not-really" value="Don't." ... src="dont.png" /> ... <select name="pick-two" size="3" multiple> ... <option value="one" selected>First</option> ... <option value="two" label="Second">Another</option> ... <optgroup> ... <option value="three">Third</option> ... <option selected="selected">Fourth</option> ... </optgroup> ... </select> ... </form> ... ... Just for fun, a second form, after specifying a base: ... <base href="http://www.example.com/base/" /> ... <form action = 'sproing/sprung.html' enctype="multipart/form"> ... <textarea name="sometext" rows="5">Some text.</textarea> ... <input type="Image" name="action" value="Do something." ... src="else.png" /> ... <input type="text" value="" name="multi" size="2" /> ... <input type="text" value="" name="multi" size="3" /> ... </form> ... </body></html> ... '''>>> parser = zope.testing.formparser.FormParser(page_text) >>> forms = parser.parse()>>> len(forms) 2 >>> forms.form1 is forms[0] True >>> forms.form1 is forms[1] False
More often, the parse() convenience function is all that's needed:
>>> forms = zope.testing.formparser.parse( ... page_text, "http://cgi.example.com/somewhere/form.html")>>> len(forms) 2 >>> forms.form1 is forms[0] True >>> forms.form1 is forms[1] False
Once we have the form we're interested in, we can check form attributes and individual field values:
>>> form = forms.form1 >>> form.enctype 'application/x-www-form-urlencoded' >>> form.method 'post'>>> keys = form.keys() >>> keys.sort() >>> keys ['do-it-now', 'f1', 'not-really', 'pick-two']>>> not_really = form["not-really"] >>> not_really.type 'image' >>> not_really.value "Don't." >>> not_really.readonly False >>> not_really.disabled False
Note that relative URLs are converted to absolute URLs based on the <base> element (if present) or using the base passed in to the constructor.
>>> form.action 'http://cgi.example.com/cgi-bin/foobar.py' >>> not_really.src 'http://cgi.example.com/somewhere/dont.png'>>> forms[1].action 'http://www.example.com/base/sproing/sprung.html' >>> forms[1]["action"].src 'http://www.example.com/base/else.png'
Fields which are repeated are reported as lists of objects that represent each instance of the field:
>>> field = forms[1]["multi"] >>> isinstance(field, list) True >>> [o.value for o in field] ['', ''] >>> [o.size for o in field] [2, 3]
The <textarea> element provides some additional attributes:
>>> ta = forms[1]["sometext"] >>> print ta.rows 5 >>> print ta.cols None >>> ta.value 'Some text.'
The <select> element provides access to the options as well:
>>> select = form["pick-two"] >>> select.multiple True >>> select.size 3 >>> select.type 'select' >>> select.value ['one', 'Fourth']>>> options = select.options >>> len(options) 4 >>> [opt.label for opt in options] ['First', 'Second', 'Third', 'Fourth'] >>> [opt.value for opt in options] ['one', 'two', 'three', 'Fourth']
If you want to test that your code generates proper log output, you can create and install a handler that collects output:
>>> from zope.testing.loggingsupport import InstalledHandler
>>> handler = InstalledHandler('foo.bar')
The handler is installed into loggers for all of the names passed. In addition, the logger level is set to 1, which means, log everything. If you want to log less than everything, you can provide a level keyword argument. The level setting effects only the named loggers.
>>> import logging
>>> handler_with_levels = InstalledHandler('baz', level=logging.WARNING)
Then, any log output is collected in the handler:
>>> logging.getLogger('foo.bar').exception('eek') >>> logging.getLogger('foo.bar').info('blah blah')>>> for record in handler.records: ... print_(record.name, record.levelname) ... print_(' ', record.getMessage()) foo.bar ERROR eek foo.bar INFO blah blah
A similar effect can be gotten by just printing the handler:
>>> print_(handler) foo.bar ERROR eek foo.bar INFO blah blah
After checking the log output, you need to uninstall the handler:
>>> handler.uninstall() >>> handler_with_levels.uninstall()
At which point, the handler won't get any more log output. Let's clear the handler:
>>> handler.clear() >>> handler.records []
And then log something:
>>> logging.getLogger('foo.bar').info('blah')
and, sure enough, we still have no output:
>>> handler.records []
The pattern-normalizing output checker extends the default output checker with an option to normalize expected and actual output.
You specify a sequence of patterns and replacements. The replacements are applied to the expected and actual outputs before calling the default outputs checker. Let's look at an example. In this example, we have some times and addresses:
>>> want = '''\ ... <object object at 0xb7f14438> ... completed in 1.234 seconds. ... <BLANKLINE> ... <object object at 0xb7f14440> ... completed in 123.234 seconds. ... <BLANKLINE> ... <object object at 0xb7f14448> ... completed in .234 seconds. ... <BLANKLINE> ... <object object at 0xb7f14450> ... completed in 1.234 seconds. ... <BLANKLINE> ... '''>>> got = '''\ ... <object object at 0xb7f14458> ... completed in 1.235 seconds. ... ... <object object at 0xb7f14460> ... completed in 123.233 seconds. ... ... <object object at 0xb7f14468> ... completed in .231 seconds. ... ... <object object at 0xb7f14470> ... completed in 1.23 seconds. ... ... '''
We may wish to consider these two strings to match, even though they differ in actual addresses and times. The default output checker will consider them different:
>>> import doctest >>> doctest.OutputChecker().check_output(want, got, 0) False
We'll use the zope.testing.renormalizing.OutputChecker to normalize both the wanted and gotten strings to ignore differences in times and addresses:
>>> import re >>> from zope.testing.renormalizing import OutputChecker >>> checker = OutputChecker([ ... (re.compile('[0-9]*[.][0-9]* seconds'), '<SOME NUMBER OF> seconds'), ... (re.compile('at 0x[0-9a-f]+'), 'at <SOME ADDRESS>'), ... ])>>> checker.check_output(want, got, 0) True
Usual OutputChecker options work as expected:
>>> want_ellided = '''\ ... <object object at 0xb7f14438> ... completed in 1.234 seconds. ... ... ... <object object at 0xb7f14450> ... completed in 1.234 seconds. ... <BLANKLINE> ... '''>>> checker.check_output(want_ellided, got, 0) False>>> checker.check_output(want_ellided, got, doctest.ELLIPSIS) True
When we get differencs, we output them with normalized text:
>>> source = '''\ ... >>> do_something() ... <object object at 0xb7f14438> ... completed in 1.234 seconds. ... ... ... <object object at 0xb7f14450> ... completed in 1.234 seconds. ... <BLANKLINE> ... '''>>> example = doctest.Example(source, want_ellided)>>> print_(checker.output_difference(example, got, 0)) Expected: <object object at <SOME ADDRESS>> completed in <SOME NUMBER OF> seconds. ... <object object at <SOME ADDRESS>> completed in <SOME NUMBER OF> seconds. <BLANKLINE> Got: <object object at <SOME ADDRESS>> completed in <SOME NUMBER OF> seconds. <BLANKLINE> <object object at <SOME ADDRESS>> completed in <SOME NUMBER OF> seconds. <BLANKLINE> <object object at <SOME ADDRESS>> completed in <SOME NUMBER OF> seconds. <BLANKLINE> <object object at <SOME ADDRESS>> completed in <SOME NUMBER OF> seconds. <BLANKLINE> <BLANKLINE>>>> print_(checker.output_difference(example, got, ... doctest.REPORT_NDIFF)) Differences (ndiff with -expected +actual): - <object object at <SOME ADDRESS>> - completed in <SOME NUMBER OF> seconds. - ... <object object at <SOME ADDRESS>> completed in <SOME NUMBER OF> seconds. <BLANKLINE> + <object object at <SOME ADDRESS>> + completed in <SOME NUMBER OF> seconds. + <BLANKLINE> + <object object at <SOME ADDRESS>> + completed in <SOME NUMBER OF> seconds. + <BLANKLINE> + <object object at <SOME ADDRESS>> + completed in <SOME NUMBER OF> seconds. + <BLANKLINE> <BLANKLINE>If the wanted text is empty, however, we don't transform the actual output. This is usful when writing tests. We leave the expected output empty, run the test, and use the actual output as expected, after reviewing it.
>>> source = '''\ ... >>> do_something() ... '''>>> example = doctest.Example(source, '\n') >>> print_(checker.output_difference(example, got, 0)) Expected: <BLANKLINE> Got: <object object at 0xb7f14458> completed in 1.235 seconds. <BLANKLINE> <object object at 0xb7f14460> completed in 123.233 seconds. <BLANKLINE> <object object at 0xb7f14468> completed in .231 seconds. <BLANKLINE> <object object at 0xb7f14470> completed in 1.23 seconds. <BLANKLINE> <BLANKLINE>
If regular expressions aren't expressive enough, you can use arbitrary Python callables to transform the text. For example, suppose you want to ignore case during comparison:
>>> checker = OutputChecker([ ... lambda s: s.lower(), ... lambda s: s.replace('<blankline>', '<BLANKLINE>'), ... ])>>> want = '''\ ... Usage: thundermonkey [options] [url] ... <BLANKLINE> ... Options: ... -h display this help message ... '''>>> got = '''\ ... usage: thundermonkey [options] [URL] ... ... options: ... -h Display this help message ... '''>>> checker.check_output(want, got, 0) True
Suppose we forgot that <BLANKLINE> must be in upper case:
>>> checker = OutputChecker([ ... lambda s: s.lower(), ... ])>>> checker.check_output(want, got, 0) False
The difference would show us that:
>>> source = '''\
... >>> print_help_message()
... ''' + want
>>> example = doctest.Example(source, want)
>>> print_(checker.output_difference(example, got,
... doctest.REPORT_NDIFF))
Differences (ndiff with -expected +actual):
usage: thundermonkey [options] [url]
- <blankline>
+ <BLANKLINE>
options:
-h display this help message
<BLANKLINE>
It is possible to combine OutputChecker checkers for easy reuse:
>>> address_and_time_checker = OutputChecker([
... (re.compile('[0-9]*[.][0-9]* seconds'), '<SOME NUMBER OF> seconds'),
... (re.compile('at 0x[0-9a-f]+'), 'at <SOME ADDRESS>'),
... ])
>>> lowercase_checker = OutputChecker([
... lambda s: s.lower(),
... ])
>>> combined_checker = address_and_time_checker + lowercase_checker
>>> len(combined_checker.transformers)
3
Combining a checker with something else does not work:
>>> lowercase_checker + 5 #doctest: +ELLIPSIS
Traceback (most recent call last):
...
TypeError: unsupported operand type(s) for +: ...
Writing doctest setUp and tearDown functions can be a bit tedious, especially when setUp/tearDown functions are combined.
the zope.testing.setupstack module provides a small framework for automating test tear down. It provides a generic setUp function that sets up a stack. Normal test setUp functions call this function to set up the stack and then use the register function to register tear-down functions.
To see how this works we'll create a faux test:
>>> class Test:
... def __init__(self):
... self.globs = {}
>>> test = Test()
We'll register some tearDown functions that just print something:
>>> import sys
>>> import zope.testing.setupstack
>>> zope.testing.setupstack.register(
... test, lambda : sys.stdout.write('td 1\n'))
>>> zope.testing.setupstack.register(
... test, lambda : sys.stdout.write('td 2\n'))
Now, when we call the tearDown function:
>>> zope.testing.setupstack.tearDown(test) td 2 td 1
The registered tearDown functions are run. Note that they are run in the reverse order that they were registered.
Extra positional arguments can be passed to register:
>>> zope.testing.setupstack.register(
... test, lambda x, y, z: sys.stdout.write('%s %s %s\n' % (x, y, z)),
... 1, 2, z=9)
>>> zope.testing.setupstack.tearDown(test)
1 2 9
Often, tests create files as they demonstrate functionality. They need to arrange for the removeal of these files when the test is cleaned up.
The setUpDirectory function automates this. We'll get the current directory first:
>>> import os >>> here = os.getcwd()
We'll also create a new test:
>>> test = Test()
Now we'll call the setUpDirectory function:
>>> zope.testing.setupstack.setUpDirectory(test)
We don't have to call zope.testing.setupstack.setUp, because setUpDirectory calls it for us.
Now the current working directory has changed:
>>> here == os.getcwd() False >>> setupstack_cwd = os.getcwd()
We can create files to out heart's content:
>>> foo = open('Data.fs', 'w').write('xxx')
>>> os.path.exists(os.path.join(setupstack_cwd, 'Data.fs'))
True
We'll make the file read-only. This can cause problems on Windows, but setupstack takes care of that by making files writable before trying to remove them.
>>> import stat
>>> os.chmod('Data.fs', stat.S_IREAD)
On Unix systems, broken symlinks can cause problems because the chmod attempt by the teardown hook will fail; let's set up a broken symlink as well, and verify the teardown doesn't break because of that:
>>> if hasattr(os, 'symlink'):
... os.symlink('NotThere', 'BrokenLink')
When tearDown is called:
>>> zope.testing.setupstack.tearDown(test)
We'll be back where we started:
>>> here == os.getcwd() True
and the files we created will be gone (along with the temporary directory that was created:
>>> os.path.exists(os.path.join(setupstack_cwd, 'Data.fs')) False
You can leverage context managers using the contextmanager method. The result of calling the content manager's __enter__ method will be returned. The context-manager's __exit__ method will be called as part of test tear down:
>>> class Manager(object): ... def __enter__(self): ... print_('enter') ... return 42 ... def __exit__(self, *args): ... print_('exit', args)>>> manager = Manager() >>> test = Test()>>> zope.testing.setupstack.context_manager(test, manager) enter 42>>> zope.testing.setupstack.tearDown(test) exit (None, None, None)
Doctests have globs attributes used to hold test globals. setupstack was originally designed to work with doctests, but can now work with either doctests, or other test objects, as long as the test objects have either a globs attribute or a __dict__ attribute. The zope.testing.setupstack.globs function is used to get the globals for a test object:
>>> zope.testing.setupstack.globs(test) is test.globs True
Here, because the test object had a globs attribute, it was returned. Because we used the test object above, it has a setupstack:
>>> '__zope.testing.setupstack' in test.globs True
If we remove the globs attribute, the object's instance dictionary will be used:
>>> del test.globs >>> zope.testing.setupstack.globs(test) is test.__dict__ True >>> zope.testing.setupstack.context_manager(test, manager) enter 42>>> '__zope.testing.setupstack' in test.__dict__ True
The globs function is used internally, but can also be used by setup code to support either doctests or other test objects.
Often, in tests, you need to wait until some condition holds. This may be because you're testing interaction with an external system or testing threaded (threads, processes, greenlet's, etc.) interactions.
You can add sleeps to your tests, but it's often hard to know how long to sleep.
zope.testing.wait provides a convenient way to wait until some condition holds. It will test a condition and, when true, return. It will sleep a short time between tests.
Here's a silly example, that illustrates it's use:
>>> from zope.testing.wait import wait >>> wait(lambda : True)
Since the condition we passed is always True, it returned immediately. If the condition doesn't hold, then we'll get a timeout:
>>> wait((lambda : False), timeout=.01) Traceback (most recent call last): ... TimeOutWaitingFor: <lambda>
wait has some keyword options:
How long, in seconds, to wait for the condition to hold
Defaults to 9 seconds.
How long to wait between calls.
Defaults to .01 seconds.
A message (or other data) to pass to the timeout exception.
This defaults to None. If this is false, then the callable's doc string or __name__ is used.
wait can be used as a decorator:
>>> @wait ... def ok(): ... return True>>> @wait(timeout=.01) ... def no_way(): ... pass Traceback (most recent call last): ... TimeOutWaitingFor: no_way>>> @wait(timeout=.01) ... def no_way(): ... "never true" Traceback (most recent call last): ... TimeOutWaitingFor: never true
wait is an instance of Wait. With Wait, you can create you're own custom wait utilities. For example, if you're testing something that uses getevent, you'd want to use gevent's sleep function:
>>> import zope.testing.wait >>> wait = zope.testing.wait.Wait(getsleep=lambda : gevent.sleep)
Wait takes a number of customization parameters:
Function used to get a function for getting the current time.
Default: lambda : time.time
Function used to get a sleep function.
Default: lambda : time.sleep
Default timeout
Default: 9
Default time to wait between attempts
Default: .01
LP #560259: Fix subunit output formatter to handle layer setup errors.
LP #399394: Added a --stop-on-error / --stop / -x option to the testrunner.
LP #498162: Added a --pdb alias for the existing --post-mortem / -D option to the testrunner.
LP #547023: Added a --version option to the testrunner.
Added tests for LP #144569 and #69988.