zope.testing-4.9/ 0000755 0001001 0000024 00000000000 13776002023 013662 5 ustar mac staff 0000000 0000000 zope.testing-4.9/CHANGES.rst 0000644 0001001 0000024 00000034660 13776002022 015474 0 ustar mac staff 0000000 0000000 Changes
=======
4.9 (2021-01-08)
----------------
- Make ``setupstack.txt`` test work again if the current directory is empty.
4.8 (2021-01-04)
----------------
- Add support for Python 3.8 and 3.9.
- Drop support for Python 3.3 and 3.4.
- Extend IGNORE_EXCEPTION_MODULE_IN_PYTHON2 to cover also exceptions without
arguments (thus without a colon on the last line of the traceback output).
4.7 (2018-10-04)
----------------
- Added support for Python 3.7.
4.6.2 (2017-06-12)
------------------
- Remove dependencies on ``zope.interface`` and ``zope.exceptions``;
they're not used here.
- Remove use of 2to3 for outdated versions of PyPy3, letting us build
universal wheels.
4.6.1 (2017-01-04)
------------------
- Add support for Python 3.6.
4.6.0 (2016-10-20)
------------------
- Introduce option flag ``IGNORE_EXCEPTION_MODULE_IN_PYTHON2`` to normalize
exception class names in traceback output. In Python 3 they are displayed as
the full dotted name. In Python 2 they are displayed as "just" the class
name. When running doctests in Python 3, the option flag will not have any
effect, however when running the same test in Python 2, the segments in the
full dotted name leading up to the class name are stripped away from the
"expected" string.
- Drop support for Python 2.6 and 3.2.
- Add support for Python 3.5.
- Cleaned up useless 2to3 conversion.
4.5.0 (2015-09-02)
------------------
- Added meta data for test case methods created with
``zope.testing.doctestcase``.
- Reasonable values for ``__name__``, making sure that ``__name__``
starts with ``test``.
- For ``doctestfile`` methods, provide ``filename`` and ``filepath``
attributes.
The meta data us useful, for example, for selecting tests with the
nose attribute mechanism.
- Added ``doctestcase.doctestfiles``
- Define multiple doctest files at once.
- Automatically assign test class members. So rather than::
class MYTests(unittest.TestCase):
...
test_foo = doctestcase.doctestfile('foo.txt')
You can use::
@doctestcase.doctestfiles('foo.txt', 'bar.txt', ...)
class MYTests(unittest.TestCase):
...
4.4.0 (2015-07-16)
------------------
- Added ``zope.testing.setupstack.mock`` as a convenience function for
setting up mocks in tests. (The Python ``mock`` package must be in
the path for this to work. The excellent ``mock`` package isn't a
dependency of ``zope.testing``.)
- Added the base class ``zope.testing.setupstack.TestCase`` to make it
much easier to use ``zope.testing.setupstack`` in ``unittest`` test
cases.
4.3.0 (2015-07-15)
------------------
- Added support for creating doctests as methods of
``unittest.TestCase`` classes so that they can found automatically
by test runners, like *nose* that ignore test suites.
4.2.0 (2015-06-01)
------------------
- **Actually** remove long-deprecated ``zope.testing.doctest`` (announced as
removed in 4.0.0) and ``zope.testing.doctestunit``.
- Add support for PyPy and PyPy3.
4.1.3 (2014-03-19)
------------------
- Add support for Python 3.4.
- Update ``boostrap.py`` to version 2.2.
4.1.2 (2013-02-19)
------------------
- Adjust Trove classifiers to reflect the currently supported Python
versions. Officially drop Python 2.4 and 2.5. Add Python 3.3.
- LP: #1055720: Fix failing test on Python 3.3 due to changed exception
messaging.
4.1.1 (2012-02-01)
------------------
- Fix: Windows test failure.
4.1.0 (2012-01-29)
------------------
- Add context-manager support to ``zope.testing.setupstack``
- Make ``zope.testing.setupstack`` usable with all tests, not just
doctests and added ``zope.testing.setupstack.globs``, which makes it
easier to write test setup code that workes with doctests and other
kinds of tests.
- Add the ``wait`` module, which makes it easier to deal with
non-deterministic timing issues.
- Rename ``zope.testing.renormalizing.RENormalizing`` to
``zope.testing.renormalizing.OutputChecker``. The old name is an
alias.
- Update tests to run with Python 3.
- Label more clearly which features are supported by Python 3.
- Reorganize documentation.
4.0.0 (2011-11-09)
------------------
- Remove the deprecated ``zope.testing.doctest``.
- Add Python 3 support.
- Fix test which fails if there is a file named `Data.fs` in the current
working directory.
3.10.2 (2010-11-30)
-------------------
- Fix test of broken symlink handling to not break on Windows.
3.10.1 (2010-11-29)
-------------------
- Fix removal of broken symlinks on Unix.
3.10.0 (2010-07-21)
-------------------
- Remove ``zope.testing.testrunner``, which now is moved to zope.testrunner.
- Update fix for LP #221151 to a spelling compatible with Python 2.4.
3.9.5 (2010-05-19)
------------------
- LP #579019: When layers are run in parallel, ensure that each ``tearDown``
is called, including the first layer which is run in the main
thread.
- Deprecate ``zope.testing.testrunner`` and ``zope.testing.exceptions``.
They have been moved to a separate zope.testrunner module, and will be
removed from zope.testing in 4.0.0, together with ``zope.testing.doctest``.
3.9.4 (2010-04-13)
------------------
- LP #560259: Fix subunit output formatter to handle layer setup
errors.
- LP #399394: Add a ``--stop-on-error`` / ``--stop`` / ``-x`` option to
the testrunner.
- LP #498162: Add a ``--pdb`` alias for the existing ``--post-mortem``
/ ``-D`` option to the testrunner.
- LP #547023: Add a ``--version`` option to the testrunner.
- Add tests for LP #144569 and #69988.
https://bugs.launchpad.net/bugs/69988
https://bugs.launchpad.net/zope3/+bug/144569
3.9.3 (2010-03-26)
------------------
- Remove import of ``zope.testing.doctest`` from ``zope.testing.renormalizer``.
- Suppress output to ``sys.stderr`` in ``testrunner-layers-ntd.txt``.
- Suppress ``zope.testing.doctest`` deprecation warning when running
our own test suite.
3.9.2 (2010-03-15)
------------------
- Fix broken ``from zope.testing.doctest import *``
3.9.1 (2010-03-15)
------------------
- No changes; reupload to fix broken 3.9.0 release on PyPI.
3.9.0 (2010-03-12)
------------------
- Modify the testrunner to use the standard Python ``doctest`` module instead
of the deprecated ``zope.testing.doctest``.
- Fix ``testrunner-leaks.txt`` to use the ``run_internal`` helper, so that
``sys.exit`` isn't triggered during the test run.
- Add support for conditionally using a subunit-based output
formatter upon request if subunit and testtools are available. Patch
contributed by Jonathan Lange.
3.8.7 (2010-01-26)
------------------
- Downgrade the ``zope.testing.doctest`` deprecation warning into a
PendingDeprecationWarning.
3.8.6 (2009-12-23)
------------------
- Add ``MANIFEST.in`` and reupload to fix broken 3.8.5 release on PyPI.
3.8.5 (2009-12-23)
------------------
- Add back ``DocFileSuite``, ``DocTestSuite``, ``debug_src`` and ``debug``
BBB imports back into ``zope.testing.doctestunit``; apparently many packages
still import them from there!
- Deprecate ``zope.testing.doctest`` and ``zope.testing.doctestunit``
in favor of the stdlib ``doctest`` module.
3.8.4 (2009-12-18)
------------------
- Fix missing imports and undefined variables reported by pyflakes,
adding tests to exercise the blind spots.
- Cleaned up unused imports reported by pyflakes.
- Add two new options to generate randomly ordered list of tests and to
select a specific order of tests.
- Allow combining RENormalizing checkers via ``+`` now:
``checker1 + checker2`` creates a checker with the transformations of both
checkers.
- Fix tests under Python 2.7.
3.8.3 (2009-09-21)
------------------
- Fix test failures due to using ``split()`` on filenames when running from a
directory with spaces in it.
- Fix testrunner behavior on Windows for ``-j2`` (or greater) combined with
``-v`` (or greater).
3.8.2 (2009-09-15)
------------------
- Remove hotshot profiler when using Python 2.6. That makes zope.testing
compatible with Python 2.6
3.8.1 (2009-08-12)
------------------
- Avoid hardcoding ``sys.argv[0]`` as script;
allow, for instance, Zope 2's `bin/instance test` (LP#407916).
- Produce a clear error message when a subprocess doesn't follow the
``zope.testing.testrunner`` protocol (LP#407916).
- Avoid unnecessarily squelching verbose output in a subprocess when there are
not multiple subprocesses.
- Avoid unnecessarily batching subprocess output, which can stymie automated
and human processes for identifying hung tests.
- Include incremental output when there are multiple subprocesses and a
verbosity of ``-vv`` or greater is requested. This again is not batched,
supporting automated processes and humans looking for hung tests.
3.8.0 (2009-07-24)
------------------
- Allow testrunner to include descendants of ``unittest.TestCase`` in test
modules, which no longer need to provide ``test_suite()``.
3.7.7 (2009-07-15)
------------------
- Clean up support for displaying tracebacks with supplements by turning it
into an always-enabled feature and making the dependency on
``zope.exceptions`` explicit.
- Fix #251759: prevent the testrunner descending into directories that
aren't Python packages.
- Code cleanups.
3.7.6 (2009-07-02)
------------------
- Add zope-testrunner ``console_scripts`` entry point. This exposes a
``zope-testrunner`` script with default installs allowing the testrunner
to be run from the command line.
3.7.5 (2009-06-08)
------------------
- Fix bug when running subprocesses on Windows.
- The option ``REPORT_ONLY_FIRST_FAILURE`` (command line option "-1") is now
respected even when a doctest declares its own ``REPORTING_FLAGS``, such as
``REPORT_NDIFF``.
- Fix bug that broke readline with pdb when using doctest
(see http://bugs.python.org/issue5727).
- Make tests pass on Windows and Linux at the same time.
3.7.4 (2009-05-01)
------------------
- Filenames of doctest examples now contain the line number and not
only the example number. So a stack trace in pdb tells the exact
line number of the current example. This fixes
https://bugs.launchpad.net/bugs/339813
- Colorization of doctest output correctly handles blank lines.
3.7.3 (2009-04-22)
------------------
- Improve handling of rogue threads: always exit with status so even
spinning daemon threads won't block the runner from exiting. This deprecated
the ``--with-exit-status`` option.
3.7.2 (2009-04-13)
------------------
- Fix test failure on Python 2.4 due to slight difference in the way
coverage is reported (__init__ files with only a single comment line are now
not reported)
- Fix bug that caused the test runner to hang when running subprocesses (as a
result Python 2.3 is no longer supported).
- Work around a bug in Python 2.6 (related to
http://bugs.python.org/issue1303673) that causes the profile tests to fail.
- Add explanitory notes to ``buildout.cfg`` about how to run the tests with
multiple versions of Python
3.7.1 (2008-10-17)
------------------
- The ``setupstack`` temporary directory support now properly handles
read-only files by making them writable before removing them.
3.7.0 (2008-09-22)
------------------
- Add alterate setuptools / distutils commands for running all tests
using our testrunner. See 'zope.testing.testrunner.eggsupport:ftest'.
- Add a setuptools-compatible test loader which skips tests with layers:
the testrunner used by ``setup.py test`` doesn't know about them, and those
tests then fail. See ``zope.testing.testrunner.eggsupport:SkipLayers``.
- Add support for Jython, when a garbage collector call is sent.
- Add support to bootstrap on Jython.
- Fix NameError in StartUpFailure.
- Open doctest files in universal mode, so that packages released on Windows
can be tested on Linux, for example.
3.6.0 (2008-07-10)
------------------
- Add ``-j`` option to parallel tests run in subprocesses.
- RENormalizer accepts plain Python callables.
- Add ``--slow-test`` option.
- Add ``--no-progress`` and ``--auto-progress`` options.
- Complete refactoring of the test runner into multiple code files and a more
modular (pipeline-like) architecture.
- Unify unit tests with the layer support by introducing a real unit test
layer.
- Add a doctest for ``zope.testing.module``. There were several bugs
that were fixed:
* ``README.txt`` was a really bad default argument for the module
name, as it is not a proper dotted name. The code would
immediately fail as it would look for the ``txt`` module in the
``README`` package. The default is now ``__main__``.
* The ``tearDown`` function did not clean up the ``__name__`` entry in the
global dictionary.
- Fix a bug that caused a SubprocessError to be generated if a subprocess
sent any output to stderr.
- Fix a bug that caused the unit tests to be skipped if run in a subprocess.
3.5.1 (2007-08-14)
------------------
- Invoke post-mortem debugging for layer-setup failures.
3.5.0 (2007-07-19)
------------------
- Ensure that the test runner works on Python 2.5.
- Add support for ``cProfile``.
- Add output colorizing (``-c`` option).
- Add ``--hide-secondary-failures`` and ``--show-secondary-failures`` options
(https://bugs.launchpad.net/zope3/+bug/115454).
- Fix some problems with Unicode in doctests.
- Fix "Error reading from subprocess" errors on Unix-like systems.
3.4 (2007-03-29)
----------------
- Add ``exit-with-status`` support (supports use with buildbot and
``zc.recipe.testing``)
- Add a small framework for automating set up and tear down of
doctest tests. See ``setupstack.txt``.
- Allow ``testrunner-wo-source.txt`` and ``testrunner-errors.txt`` to run
within a read-only source tree.
3.0 (2006-09-20)
----------------
- Update the doctest copy with text-file encoding support.
- Add logging-level support to the ``loggingsuppport`` module.
- At verbosity-level 1, dots are not output continuously, without any
line breaks.
- Improve output when the inability to tear down a layer causes tests
to be run in a subprocess.
- Make ``zope.exception`` required only if the ``zope_tracebacks`` extra is
requested.
- Fix the test coverage. If a module, for example `interfaces`, was in an
ignored directory/package, then if a module of the same name existed in a
covered directory/package, then it was also ignored there, because the
ignore cache stored the result by module name and not the filename of the
module.
2.0 (2006-01-05)
----------------
- Release a separate project corresponding to the version of ``zope.testing``
shipped as part of the Zope 3.2.0 release.
zope.testing-4.9/COPYRIGHT.txt 0000644 0001001 0000024 00000000040 13776002022 015764 0 ustar mac staff 0000000 0000000 Zope Foundation and Contributors zope.testing-4.9/LICENSE.txt 0000644 0001001 0000024 00000004026 13776002022 015506 0 ustar mac staff 0000000 0000000 Zope Public License (ZPL) Version 2.1
A copyright notice accompanies this license document that identifies the
copyright holders.
This license has been certified as open source. It has also been designated as
GPL compatible by the Free Software Foundation (FSF).
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions in source code must retain the accompanying copyright
notice, this list of conditions, and the following disclaimer.
2. Redistributions in binary form must reproduce the accompanying copyright
notice, this list of conditions, and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Names of the copyright holders must not be used to endorse or promote
products derived from this software without prior written permission from the
copyright holders.
4. The right to distribute this software or to use it for any purpose does not
give you the right to use Servicemarks (sm) or Trademarks (tm) of the
copyright
holders. Use of them is covered by separate agreement with the copyright
holders.
5. If any files are modified, you must cause the modified files to carry
prominent notices stating that you changed the files and the date of any
change.
Disclaimer
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY EXPRESSED
OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
zope.testing-4.9/MANIFEST.in 0000644 0001001 0000024 00000000474 13776002022 015424 0 ustar mac staff 0000000 0000000 # Generated from:
# https://github.com/zopefoundation/meta/tree/master/config/pure-python
include *.rst
include *.txt
include buildout.cfg
include tox.ini
include appveyor.yml
recursive-include src *.pt
recursive-include src *.py
recursive-include src *.rst
recursive-include src *.txt
recursive-include src *.zcml
zope.testing-4.9/PKG-INFO 0000644 0001001 0000024 00000210130 13776002023 014754 0 ustar mac staff 0000000 0000000 Metadata-Version: 2.1
Name: zope.testing
Version: 4.9
Summary: Zope testing helpers
Home-page: https://github.com/zopefoundation/zope.testing
Author: Zope Foundation and Contributors
Author-email: zope-dev@zope.org
License: ZPL 2.1
Description: =================
``zope.testing``
=================
.. image:: https://img.shields.io/pypi/v/zope.testing.svg
:target: https://pypi.python.org/pypi/zope.testing/
:alt: Latest Version
.. image:: https://travis-ci.com/zopefoundation/zope.testing.svg?branch=master
:target: https://travis-ci.com/zopefoundation/zope.testing
.. image:: https://readthedocs.org/projects/zopetesting/badge/?version=latest
:target: http://zopetesting.readthedocs.org/en/latest/
:alt: Documentation Status
This package provides a number of testing frameworks.
cleanup
Provides a mixin class for cleaning up after tests that
make global changes.
formparser
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.
loggingsupport
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.
loghandler
Logging handler for tests that check logging output.
module
Lets a doctest pretend to be a Python module.
See module.txt.
renormalizing
Regular expression pattern normalizing output checker.
Useful for doctests.
server
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**
setupstack
A simple framework for automating doctest set-up and tear-down.
See setupstack.txt.
wait
A small utility for dealing with timing non-determinism
See wait.txt.
doctestcase
Support for defining doctests as methods of ``unittest.TestCase``
classes so that they can be more easily found by test runners, like
nose, that ignore test suites.
.. contents::
Getting started developing zope.testing
=======================================
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.
Parsing HTML Forms
==================
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.
NOTE
formparser doesn't support Python 3.
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 = '''\
...
...
...
... Just for fun, a second form, after specifying a base:
...
...
...
... '''
>>> 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
`` `` 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 ```` element provides some additional attributes:
>>> ta = forms[1]["sometext"]
>>> print ta.rows
5
>>> print ta.cols
None
>>> ta.value
'Some text.'
The ```` 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']
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:
>>> 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
[]
Regular expression pattern normalizing output checker
=====================================================
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 = '''\
...
... completed in 1.234 seconds.
...
...
... completed in 123.234 seconds.
...
...
... completed in .234 seconds.
...
...
... completed in 1.234 seconds.
...
... '''
>>> got = '''\
...
... completed in 1.235 seconds.
...
...
... completed in 123.233 seconds.
...
...
... completed in .231 seconds.
...
...
... 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'), ' seconds'),
... (re.compile('at 0x[0-9a-f]+'), 'at '),
... ])
>>> checker.check_output(want, got, 0)
True
Usual OutputChecker options work as expected:
>>> want_ellided = '''\
...
... completed in 1.234 seconds.
... ...
...
... completed in 1.234 seconds.
...
... '''
>>> 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()
...
... completed in 1.234 seconds.
... ...
...
... completed in 1.234 seconds.
...
... '''
>>> example = doctest.Example(source, want_ellided)
>>> print_(checker.output_difference(example, got, 0))
Expected:
>
completed in seconds.
...
>
completed in seconds.
Got:
>
completed in seconds.
>
completed in seconds.
>
completed in seconds.
>
completed in seconds.
>>> print_(checker.output_difference(example, got,
... doctest.REPORT_NDIFF))
Differences (ndiff with -expected +actual):
- >
- completed in seconds.
- ...
>
completed in seconds.
+ >
+ completed in seconds.
+
+ >
+ completed in seconds.
+
+ >
+ completed in seconds.
+
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:
Got:
completed in 1.235 seconds.
completed in 123.233 seconds.
completed in .231 seconds.
completed in 1.23 seconds.
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('', ''),
... ])
>>> want = '''\
... Usage: thundermonkey [options] [url]
...
... 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 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]
-
+
options:
-h display this help message
It is possible to combine OutputChecker checkers for easy reuse:
>>> address_and_time_checker = OutputChecker([
... (re.compile('[0-9]*[.][0-9]* seconds'), ' seconds'),
... (re.compile('at 0x[0-9a-f]+'), 'at '),
... ])
>>> 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 +: ...
Using the 2to3 exception normalization:
>>> from zope.testing.renormalizing import (
... IGNORE_EXCEPTION_MODULE_IN_PYTHON2)
>>> checker = OutputChecker()
>>> want = """\
... Traceback (most recent call last):
... foo.bar.FooBarError: requires at least one argument."""
>>> got = """\
... Traceback (most recent call last):
... FooBarError: requires at least one argument."""
>>> result = checker.check_output(
... want, got, IGNORE_EXCEPTION_MODULE_IN_PYTHON2)
>>> import sys
>>> if sys.version_info[0] < 3:
... expected = True
... else:
... expected = False
>>> result == expected
True
When reporting a failing test and running in Python 2, the normalizer tries
to be helpful by explaining how to test for exceptions in the traceback output.
>>> want = """\
... Traceback (most recent call last):
... foo.bar.FooBarErrorXX: requires at least one argument.
... """
>>> got = """\
... Traceback (most recent call last):
... FooBarError: requires at least one argument.
... """
>>> checker.check_output(want, got, IGNORE_EXCEPTION_MODULE_IN_PYTHON2)
False
>>> from doctest import Example
>>> example = Example('dummy', want)
>>> result = checker.output_difference(
... example, got, IGNORE_EXCEPTION_MODULE_IN_PYTHON2)
>>> output = """\
... Expected:
... Traceback (most recent call last):
... foo.bar.FooBarErrorXX: requires at least one argument.
... Got:
... Traceback (most recent call last):
... FooBarError: requires at least one argument.
... """
>>> hint = """\
... ===============================================================
... HINT:
... The optionflag IGNORE_EXCEPTION_MODULE_IN_PYTHON2 is set.
... You seem to test traceback output.
... If you are indeed, make sure to use the full dotted name of
... the exception class like Python 3 displays,
... even though you are running the tests in Python 2.
... The exception message needs to be last line (and thus not
... split over multiple lines).
... ==============================================================="""
>>> if sys.version_info[0] < 3:
... expected = output + hint
... else:
... expected = output
>>> result == expected
True
Stack-based test setUp and tearDown
===================================
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
Temporary Test Directory
------------------------
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:
>>> with open('Data.fs', 'w') as f:
... foo = f.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 sys.platform != 'win32':
... 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
Context-manager support
-----------------------
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 __init__(self, *args, **kw):
... if kw:
... args += (kw, )
... self.args = args
... def __enter__(self):
... print_('enter', *self.args)
... return 42
... def __exit__(self, *args):
... print_('exit', args, *self.args)
>>> manager = Manager()
>>> test = Test()
>>> zope.testing.setupstack.context_manager(test, manager)
enter
42
>>> zope.testing.setupstack.tearDown(test)
exit (None, None, None)
.. faux mock
>>> old_mock = sys.modules.get('mock')
>>> class FauxMock:
... @classmethod
... def patch(self, *args, **kw):
... return Manager(*args, **kw)
>>> sys.modules['mock'] = FauxMock
By far the most commonly called context manager is ``mock.patch``, so
there's a convenience function to make that simpler:
>>> zope.testing.setupstack.mock(test, 'time.time', return_value=42)
enter time.time {'return_value': 42}
42
>>> zope.testing.setupstack.tearDown(test)
exit (None, None, None) time.time {'return_value': 42}
globs
-----
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.
TestCase
--------
A TestCase class is provided that:
- Makes it easier to call setupstack apis, and
- provides an inheritable tearDown method.
In addition to a tearDown method, the class provides methods:
``setupDirectory()``
Creates a temporary directory, runs the test, and cleans it up.
``register(func)``
Register a tear-down function.
``context_manager(manager)``
Enters a context manager and exits it on tearDown.
``mock(*args, **kw)``
Enters ``mock.patch`` with the given arguments.
This is syntactic sugur for::
context_manager(mock.patch(*args, **kw))
Here's an example:
>>> class MyTests(zope.testing.setupstack.TestCase):
...
... def setUp(self):
... self.setUpDirectory()
... self.context_manager(manager)
... self.mock("time.time", return_value=42)
...
... @self.register
... def _():
... print('done w test')
...
... def test(self):
... if here == os.getcwd():
... print('Failed to change directory')
.. let's try it
>>> import unittest
>>> loader = unittest.TestLoader()
>>> suite = loader.loadTestsFromTestCase(MyTests)
>>> result = suite.run(unittest.TestResult())
enter
enter time.time {'return_value': 42}
done w test
exit (None, None, None) time.time {'return_value': 42}
exit (None, None, None)
.. cleanup
>>> if old_mock:
... sys.modules['mock'] = old_mock
... else:
... del sys.modules['mock']
Wait until a condition holds (or until a time out)
==================================================
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:
``wait`` has some keyword options:
timeout
How long, in seconds, to wait for the condition to hold
Defaults to 9 seconds.
wait
How long to wait between calls.
Defaults to .01 seconds.
message
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
.. more tests
>>> import time
>>> now = time.time()
>>> @wait(timeout=.01, message='dang')
... def no_way():
... "never true"
Traceback (most recent call last):
...
TimeOutWaitingFor: dang
>>> .01 < (time.time() - now) < .03
True
Customization
-------------
``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:
exception
Timeout exception class
getnow
Function used to get a function for getting the current time.
Default: lambda : time.time
getsleep
Function used to get a sleep function.
Default: lambda : time.sleep
timeout
Default timeout
Default: 9
wait
Default time to wait between attempts
Default: .01
.. more tests
>>> def mysleep(t):
... print_('mysleep', t)
... time.sleep(t)
>>> def mynow():
... print_('mynow')
... return time.time()
>>> wait = zope.testing.wait.Wait(
... getnow=(lambda : mynow), getsleep=(lambda : mysleep),
... exception=ValueError, timeout=.1, wait=.02)
>>> @wait
... def _(state=[]):
... if len(state) > 1:
... return True
... state.append(0)
mynow
mysleep 0.02
mynow
mysleep 0.02
>>> @wait(wait=.002)
... def _(state=[]):
... if len(state) > 1:
... return True
... state.append(0)
mynow
mysleep 0.002
mynow
mysleep 0.002
>>> @wait(timeout=0)
... def _(state=[]):
... if len(state) > 1:
... return True
... state.append(0)
Traceback (most recent call last):
...
ValueError: _
>>> wait = zope.testing.wait.Wait(timeout=0)
>>> @wait(timeout=0)
... def _(state=[]):
... if len(state) > 1:
... return True
... state.append(0)
Traceback (most recent call last):
...
TimeOutWaitingFor: _
Doctests in TestCase classes
============================
The original ``doctest`` unittest integration was based on
``unittest`` test suites, which have fallen out of favor. This module
provides a way to define doctests inside of unittest ``TestCase``
classes. It provides better integration with unittest test fixtures,
because doctests use setup provided by the containing test case
class. It provides access to unittest assertion methods.
You can define doctests in multiple ways:
- references to named files
- strings
- decorated functions with docstrings
- reference to named files decorating test-specific setup functions
- reference to named files decorating a test class
.. some setup
>>> __name__ = 'tests'
Here are some examples::
>>> from zope.testing import doctestcase
>>> import doctest
>>> import unittest
>>> g = 'global'
>>> class MyTest(unittest.TestCase):
...
... def setUp(self):
... self.a = 1
... self.globs = dict(c=9)
...
... test1 = doctestcase.file('test-1.txt', optionflags=doctest.ELLIPSIS)
...
... test2 = doctestcase.docteststring('''
... >>> self.a, g, c
... (1, 'global', 9)
... ''')
...
... @doctestcase.doctestmethod(optionflags=doctest.ELLIPSIS)
... def test3(self):
... '''
... >>> self.a, self.x, g, c
... (1, 3, 'global', 9)
... '''
... self.x = 3
...
... @doctestcase.doctestfile('test4.txt')
... def test4(self):
... self.x = 5
>>> import sys
>>> @doctestcase.doctestfiles('loggingsupport.txt', 'renormalizing.txt')
... class MoreTests(unittest.TestCase):
...
... def setUp(self):
... def print_(*args):
... sys.stdout.write(' '.join(map(str, args))+'\n')
... self.globs = dict(print_=print_)
.. We can run these tests with the ``unittest`` test runner.
>>> loader = unittest.TestLoader()
>>> sys.stdout.writeln = lambda s: sys.stdout.write(s+'\n')
>>> suite = loader.loadTestsFromTestCase(MyTest)
>>> result = suite.run(unittest.TextTestResult(sys.stdout, True, 3))
test1 (tests.MyTest) ... ok
test2 (tests.MyTest) ... ok
test3 (tests.MyTest) ... ok
test4 (tests.MyTest) ... ok
>>> suite = loader.loadTestsFromTestCase(MoreTests)
>>> result = suite.run(unittest.TextTestResult(sys.stdout, True, 3))
test_loggingsupport (tests.MoreTests) ... ok
test_renormalizing (tests.MoreTests) ... ok
>>> for _, e in result.errors:
... print(e); print
Check meta data:
>>> MyTest.test1.__name__
'test_1'
>>> import os, zope.testing
>>> (MyTest.test1.filepath ==
... os.path.join(os.path.dirname(zope.testing.__file__), 'test-1.txt'))
True
>>> MyTest.test1.filename
'test-1.txt'
>>> MyTest.test3.__name__
'test3'
>>> MyTest.test4.__name__
'test4'
>>> (MyTest.test4.filepath ==
... os.path.join(os.path.dirname(zope.testing.__file__), 'test4.txt'))
True
>>> MyTest.test4.filename
'test4.txt'
>>> MoreTests.test_loggingsupport.__name__
'test_loggingsupport'
>>> MoreTests.test_loggingsupport.filename
'loggingsupport.txt'
>>> (MoreTests.test_loggingsupport.filepath ==
... os.path.join(os.path.dirname(zope.testing.__file__),
... 'loggingsupport.txt'))
True
In these examples, 4 constructors were used:
doctestfile (alias: file)
doctestfile makes a file-based test case.
This can be used as a decorator, in which case, the decorated
function is called before the test is run, to provide test-specific
setup.
doctestfiles (alias: files)
doctestfiles makes file-based test cases and assigns them to the
decorated class.
Multiple files can be specified and the resulting doctests are added
as members of the decorated class.
docteststring (alias string)
docteststring constructs a doctest from a string.
doctestmethod (alias method)
doctestmethod constructs a doctest from a method.
The method's docstring provides the test. The method's body provides
optional test-specific setup.
Note that short aliases are provided, which maye be useful in certain
import styles.
Tests have access to the following data:
- Tests created with the ``docteststring`` and ``doctestmethod``
constructors have access to the module globals of the defining
module.
- In tests created with the ``docteststring`` and ``doctestmethod``
constructors, the test case instance is available as the ``self``
variable.
- In tests created with the ``doctestfile`` and ``doctestfiles``
constructor, the test case instance is available as the ``test``
variable.
- If a test case defines a globs attribute, it must be a dictionary
and it's contents are added to the test globals.
The constructors accept standard doctest ``optionflags`` and
``checker`` arguments.
Note that the doctest IGNORE_EXCEPTION_DETAIL option flag is
added to optionflags.
When using ``doctestfile`` and ``doctestfile``, ``filename`` and
``filepath`` attributes are available that contain the test file name
and full path.
``__name__`` attributes of class members
----------------------------------------
Class members have ``__name__`` attributes set as follows:
- When using ``doctestmethod`` or ``doctestfile`` with a setup
function, ``__name__`` attribute is set to the name of the function.
A ``test_`` prefix is added, if the name doesn't start with ``test``.
- When ``doctestfile`` is used without a setup function or when
``doctestfiles`` is used, ``__name__`` is set to the last part of the
file path with the extension removed and non-word characters
converted to underscores. For example, with a test path of
``'/foo/bar/test-it.rst'``, the ``__name__`` attribute is set to
``'test_it'``. A ``test_`` prefix is added, if the name doesn't
start with ``test``.
- when using ``docteststring``, a ``name`` option can be passed in to
set ``__name__``. A ``test_`` prefix is added, if the name doesn't
start with ``test``.
The ``__name__`` attribute is important when using nose, because nose
discovers tests as class members using their ``__name__`` attributes,
whereas the unittest and py.test test runners use class dictionary keys.
.. Let's look at some failure cases:
>>> class MyTest(unittest.TestCase):
...
... test2 = doctestcase.string('''
... >>> 1
... 1
... >>> 1 + 1
... 1
... ''', name='test2')
...
... @doctestcase.method
... def test3(self):
... '''
... >>> self.x
... 3
... >>> 1 + 1
... 1
... '''
... self.x = 3
...
... @doctestcase.file('test4f.txt')
... def test4(self):
... self.x = 5
>>> suite = loader.loadTestsFromTestCase(MyTest)
>>> result = suite.run(unittest.TextTestResult(sys.stdout, True, 1))
FFF
>>> for c, e in result.failures:
... print(e) # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
Traceback (most recent call last):
...
...: Failed doctest test for
File "", line 0, in
----------------------------------------------------------------------
File "", line 4, in
Failed example:
1 + 1
Expected:
1
Got:
2
Traceback (most recent call last):
...
...: Failed doctest test for test3
File "None", line 10, in test3
----------------------------------------------------------------------
Line 4, in test3
Failed example:
1 + 1
Expected:
1
Got:
2
Traceback (most recent call last):
...
...: Failed doctest test for test4f.txt
File "...test4f.txt", line 0, in txt
----------------------------------------------------------------------
File "...test4f.txt", line 3, in test4f.txt
Failed example:
1 + 1
Expected:
1
Got:
2
Check string meta data:
>>> MyTest.test2.__name__
'test2'
.. Verify setting optionflags and checker
>>> class EasyChecker:
... def check_output(self, want, got, optionflags):
... return True
... def output_difference(self, example, got, optionflags):
... return ''
>>> class MyTest(unittest.TestCase):
...
... test2 = doctestcase.string('''
... >>> 1
... 2
... ''', checker=EasyChecker())
...
... @doctestcase.method(optionflags=doctest.ELLIPSIS)
... def test3(self):
... '''
... >>> 'Hello'
... '...'
... '''
...
... @doctestcase.file('test4e.txt', optionflags=doctest.ELLIPSIS)
... def test4(self):
... self.x = 5
>>> suite = loader.loadTestsFromTestCase(MyTest)
>>> result = suite.run(unittest.TextTestResult(sys.stdout, True, 2))
test2 (tests.MyTest) ... ok
test3 (tests.MyTest) ... ok
test4 (tests.MyTest) ... ok
.. test __name__ variations
>>> class MyTest(unittest.TestCase):
...
... foo = doctestcase.string('''>>> 1''', name='foo')
...
... @doctestcase.method
... def bar(self):
... '''
... >>> self.x
... 3
... '''
... @doctestcase.file('test4f.txt')
... def baz(self):
... pass
... wait = doctestcase.file('wait.txt')
>>> MyTest.foo.__name__
'test_foo'
>>> MyTest.bar.__name__
'test_bar'
>>> MyTest.baz.__name__
'test_baz'
>>> MyTest.wait.__name__
'test_wait'
Changes
=======
4.9 (2021-01-08)
----------------
- Make ``setupstack.txt`` test work again if the current directory is empty.
4.8 (2021-01-04)
----------------
- Add support for Python 3.8 and 3.9.
- Drop support for Python 3.3 and 3.4.
- Extend IGNORE_EXCEPTION_MODULE_IN_PYTHON2 to cover also exceptions without
arguments (thus without a colon on the last line of the traceback output).
4.7 (2018-10-04)
----------------
- Added support for Python 3.7.
4.6.2 (2017-06-12)
------------------
- Remove dependencies on ``zope.interface`` and ``zope.exceptions``;
they're not used here.
- Remove use of 2to3 for outdated versions of PyPy3, letting us build
universal wheels.
4.6.1 (2017-01-04)
------------------
- Add support for Python 3.6.
4.6.0 (2016-10-20)
------------------
- Introduce option flag ``IGNORE_EXCEPTION_MODULE_IN_PYTHON2`` to normalize
exception class names in traceback output. In Python 3 they are displayed as
the full dotted name. In Python 2 they are displayed as "just" the class
name. When running doctests in Python 3, the option flag will not have any
effect, however when running the same test in Python 2, the segments in the
full dotted name leading up to the class name are stripped away from the
"expected" string.
- Drop support for Python 2.6 and 3.2.
- Add support for Python 3.5.
- Cleaned up useless 2to3 conversion.
4.5.0 (2015-09-02)
------------------
- Added meta data for test case methods created with
``zope.testing.doctestcase``.
- Reasonable values for ``__name__``, making sure that ``__name__``
starts with ``test``.
- For ``doctestfile`` methods, provide ``filename`` and ``filepath``
attributes.
The meta data us useful, for example, for selecting tests with the
nose attribute mechanism.
- Added ``doctestcase.doctestfiles``
- Define multiple doctest files at once.
- Automatically assign test class members. So rather than::
class MYTests(unittest.TestCase):
...
test_foo = doctestcase.doctestfile('foo.txt')
You can use::
@doctestcase.doctestfiles('foo.txt', 'bar.txt', ...)
class MYTests(unittest.TestCase):
...
4.4.0 (2015-07-16)
------------------
- Added ``zope.testing.setupstack.mock`` as a convenience function for
setting up mocks in tests. (The Python ``mock`` package must be in
the path for this to work. The excellent ``mock`` package isn't a
dependency of ``zope.testing``.)
- Added the base class ``zope.testing.setupstack.TestCase`` to make it
much easier to use ``zope.testing.setupstack`` in ``unittest`` test
cases.
4.3.0 (2015-07-15)
------------------
- Added support for creating doctests as methods of
``unittest.TestCase`` classes so that they can found automatically
by test runners, like *nose* that ignore test suites.
4.2.0 (2015-06-01)
------------------
- **Actually** remove long-deprecated ``zope.testing.doctest`` (announced as
removed in 4.0.0) and ``zope.testing.doctestunit``.
- Add support for PyPy and PyPy3.
4.1.3 (2014-03-19)
------------------
- Add support for Python 3.4.
- Update ``boostrap.py`` to version 2.2.
4.1.2 (2013-02-19)
------------------
- Adjust Trove classifiers to reflect the currently supported Python
versions. Officially drop Python 2.4 and 2.5. Add Python 3.3.
- LP: #1055720: Fix failing test on Python 3.3 due to changed exception
messaging.
4.1.1 (2012-02-01)
------------------
- Fix: Windows test failure.
4.1.0 (2012-01-29)
------------------
- Add context-manager support to ``zope.testing.setupstack``
- Make ``zope.testing.setupstack`` usable with all tests, not just
doctests and added ``zope.testing.setupstack.globs``, which makes it
easier to write test setup code that workes with doctests and other
kinds of tests.
- Add the ``wait`` module, which makes it easier to deal with
non-deterministic timing issues.
- Rename ``zope.testing.renormalizing.RENormalizing`` to
``zope.testing.renormalizing.OutputChecker``. The old name is an
alias.
- Update tests to run with Python 3.
- Label more clearly which features are supported by Python 3.
- Reorganize documentation.
4.0.0 (2011-11-09)
------------------
- Remove the deprecated ``zope.testing.doctest``.
- Add Python 3 support.
- Fix test which fails if there is a file named `Data.fs` in the current
working directory.
3.10.2 (2010-11-30)
-------------------
- Fix test of broken symlink handling to not break on Windows.
3.10.1 (2010-11-29)
-------------------
- Fix removal of broken symlinks on Unix.
3.10.0 (2010-07-21)
-------------------
- Remove ``zope.testing.testrunner``, which now is moved to zope.testrunner.
- Update fix for LP #221151 to a spelling compatible with Python 2.4.
3.9.5 (2010-05-19)
------------------
- LP #579019: When layers are run in parallel, ensure that each ``tearDown``
is called, including the first layer which is run in the main
thread.
- Deprecate ``zope.testing.testrunner`` and ``zope.testing.exceptions``.
They have been moved to a separate zope.testrunner module, and will be
removed from zope.testing in 4.0.0, together with ``zope.testing.doctest``.
3.9.4 (2010-04-13)
------------------
- LP #560259: Fix subunit output formatter to handle layer setup
errors.
- LP #399394: Add a ``--stop-on-error`` / ``--stop`` / ``-x`` option to
the testrunner.
- LP #498162: Add a ``--pdb`` alias for the existing ``--post-mortem``
/ ``-D`` option to the testrunner.
- LP #547023: Add a ``--version`` option to the testrunner.
- Add tests for LP #144569 and #69988.
https://bugs.launchpad.net/bugs/69988
https://bugs.launchpad.net/zope3/+bug/144569
3.9.3 (2010-03-26)
------------------
- Remove import of ``zope.testing.doctest`` from ``zope.testing.renormalizer``.
- Suppress output to ``sys.stderr`` in ``testrunner-layers-ntd.txt``.
- Suppress ``zope.testing.doctest`` deprecation warning when running
our own test suite.
3.9.2 (2010-03-15)
------------------
- Fix broken ``from zope.testing.doctest import *``
3.9.1 (2010-03-15)
------------------
- No changes; reupload to fix broken 3.9.0 release on PyPI.
3.9.0 (2010-03-12)
------------------
- Modify the testrunner to use the standard Python ``doctest`` module instead
of the deprecated ``zope.testing.doctest``.
- Fix ``testrunner-leaks.txt`` to use the ``run_internal`` helper, so that
``sys.exit`` isn't triggered during the test run.
- Add support for conditionally using a subunit-based output
formatter upon request if subunit and testtools are available. Patch
contributed by Jonathan Lange.
3.8.7 (2010-01-26)
------------------
- Downgrade the ``zope.testing.doctest`` deprecation warning into a
PendingDeprecationWarning.
3.8.6 (2009-12-23)
------------------
- Add ``MANIFEST.in`` and reupload to fix broken 3.8.5 release on PyPI.
3.8.5 (2009-12-23)
------------------
- Add back ``DocFileSuite``, ``DocTestSuite``, ``debug_src`` and ``debug``
BBB imports back into ``zope.testing.doctestunit``; apparently many packages
still import them from there!
- Deprecate ``zope.testing.doctest`` and ``zope.testing.doctestunit``
in favor of the stdlib ``doctest`` module.
3.8.4 (2009-12-18)
------------------
- Fix missing imports and undefined variables reported by pyflakes,
adding tests to exercise the blind spots.
- Cleaned up unused imports reported by pyflakes.
- Add two new options to generate randomly ordered list of tests and to
select a specific order of tests.
- Allow combining RENormalizing checkers via ``+`` now:
``checker1 + checker2`` creates a checker with the transformations of both
checkers.
- Fix tests under Python 2.7.
3.8.3 (2009-09-21)
------------------
- Fix test failures due to using ``split()`` on filenames when running from a
directory with spaces in it.
- Fix testrunner behavior on Windows for ``-j2`` (or greater) combined with
``-v`` (or greater).
3.8.2 (2009-09-15)
------------------
- Remove hotshot profiler when using Python 2.6. That makes zope.testing
compatible with Python 2.6
3.8.1 (2009-08-12)
------------------
- Avoid hardcoding ``sys.argv[0]`` as script;
allow, for instance, Zope 2's `bin/instance test` (LP#407916).
- Produce a clear error message when a subprocess doesn't follow the
``zope.testing.testrunner`` protocol (LP#407916).
- Avoid unnecessarily squelching verbose output in a subprocess when there are
not multiple subprocesses.
- Avoid unnecessarily batching subprocess output, which can stymie automated
and human processes for identifying hung tests.
- Include incremental output when there are multiple subprocesses and a
verbosity of ``-vv`` or greater is requested. This again is not batched,
supporting automated processes and humans looking for hung tests.
3.8.0 (2009-07-24)
------------------
- Allow testrunner to include descendants of ``unittest.TestCase`` in test
modules, which no longer need to provide ``test_suite()``.
3.7.7 (2009-07-15)
------------------
- Clean up support for displaying tracebacks with supplements by turning it
into an always-enabled feature and making the dependency on
``zope.exceptions`` explicit.
- Fix #251759: prevent the testrunner descending into directories that
aren't Python packages.
- Code cleanups.
3.7.6 (2009-07-02)
------------------
- Add zope-testrunner ``console_scripts`` entry point. This exposes a
``zope-testrunner`` script with default installs allowing the testrunner
to be run from the command line.
3.7.5 (2009-06-08)
------------------
- Fix bug when running subprocesses on Windows.
- The option ``REPORT_ONLY_FIRST_FAILURE`` (command line option "-1") is now
respected even when a doctest declares its own ``REPORTING_FLAGS``, such as
``REPORT_NDIFF``.
- Fix bug that broke readline with pdb when using doctest
(see http://bugs.python.org/issue5727).
- Make tests pass on Windows and Linux at the same time.
3.7.4 (2009-05-01)
------------------
- Filenames of doctest examples now contain the line number and not
only the example number. So a stack trace in pdb tells the exact
line number of the current example. This fixes
https://bugs.launchpad.net/bugs/339813
- Colorization of doctest output correctly handles blank lines.
3.7.3 (2009-04-22)
------------------
- Improve handling of rogue threads: always exit with status so even
spinning daemon threads won't block the runner from exiting. This deprecated
the ``--with-exit-status`` option.
3.7.2 (2009-04-13)
------------------
- Fix test failure on Python 2.4 due to slight difference in the way
coverage is reported (__init__ files with only a single comment line are now
not reported)
- Fix bug that caused the test runner to hang when running subprocesses (as a
result Python 2.3 is no longer supported).
- Work around a bug in Python 2.6 (related to
http://bugs.python.org/issue1303673) that causes the profile tests to fail.
- Add explanitory notes to ``buildout.cfg`` about how to run the tests with
multiple versions of Python
3.7.1 (2008-10-17)
------------------
- The ``setupstack`` temporary directory support now properly handles
read-only files by making them writable before removing them.
3.7.0 (2008-09-22)
------------------
- Add alterate setuptools / distutils commands for running all tests
using our testrunner. See 'zope.testing.testrunner.eggsupport:ftest'.
- Add a setuptools-compatible test loader which skips tests with layers:
the testrunner used by ``setup.py test`` doesn't know about them, and those
tests then fail. See ``zope.testing.testrunner.eggsupport:SkipLayers``.
- Add support for Jython, when a garbage collector call is sent.
- Add support to bootstrap on Jython.
- Fix NameError in StartUpFailure.
- Open doctest files in universal mode, so that packages released on Windows
can be tested on Linux, for example.
3.6.0 (2008-07-10)
------------------
- Add ``-j`` option to parallel tests run in subprocesses.
- RENormalizer accepts plain Python callables.
- Add ``--slow-test`` option.
- Add ``--no-progress`` and ``--auto-progress`` options.
- Complete refactoring of the test runner into multiple code files and a more
modular (pipeline-like) architecture.
- Unify unit tests with the layer support by introducing a real unit test
layer.
- Add a doctest for ``zope.testing.module``. There were several bugs
that were fixed:
* ``README.txt`` was a really bad default argument for the module
name, as it is not a proper dotted name. The code would
immediately fail as it would look for the ``txt`` module in the
``README`` package. The default is now ``__main__``.
* The ``tearDown`` function did not clean up the ``__name__`` entry in the
global dictionary.
- Fix a bug that caused a SubprocessError to be generated if a subprocess
sent any output to stderr.
- Fix a bug that caused the unit tests to be skipped if run in a subprocess.
3.5.1 (2007-08-14)
------------------
- Invoke post-mortem debugging for layer-setup failures.
3.5.0 (2007-07-19)
------------------
- Ensure that the test runner works on Python 2.5.
- Add support for ``cProfile``.
- Add output colorizing (``-c`` option).
- Add ``--hide-secondary-failures`` and ``--show-secondary-failures`` options
(https://bugs.launchpad.net/zope3/+bug/115454).
- Fix some problems with Unicode in doctests.
- Fix "Error reading from subprocess" errors on Unix-like systems.
3.4 (2007-03-29)
----------------
- Add ``exit-with-status`` support (supports use with buildbot and
``zc.recipe.testing``)
- Add a small framework for automating set up and tear down of
doctest tests. See ``setupstack.txt``.
- Allow ``testrunner-wo-source.txt`` and ``testrunner-errors.txt`` to run
within a read-only source tree.
3.0 (2006-09-20)
----------------
- Update the doctest copy with text-file encoding support.
- Add logging-level support to the ``loggingsuppport`` module.
- At verbosity-level 1, dots are not output continuously, without any
line breaks.
- Improve output when the inability to tear down a layer causes tests
to be run in a subprocess.
- Make ``zope.exception`` required only if the ``zope_tracebacks`` extra is
requested.
- Fix the test coverage. If a module, for example `interfaces`, was in an
ignored directory/package, then if a module of the same name existed in a
covered directory/package, then it was also ignored there, because the
ignore cache stored the result by module name and not the filename of the
module.
2.0 (2006-01-05)
----------------
- Release a separate project corresponding to the version of ``zope.testing``
shipped as part of the Zope 3.2.0 release.
Keywords: zope testing doctest RENormalizing OutputChecker timeout logging
Platform: UNKNOWN
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: Zope Public License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python
Classifier: Programming Language :: Python :: 2
Classifier: Programming Language :: Python :: 2.7
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.5
Classifier: Programming Language :: Python :: 3.6
Classifier: Programming Language :: Python :: 3.7
Classifier: Programming Language :: Python :: 3.8
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: Implementation :: CPython
Classifier: Programming Language :: Python :: Implementation :: PyPy
Classifier: Framework :: Zope :: 3
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Topic :: Software Development :: Testing
Provides-Extra: test
zope.testing-4.9/README.rst 0000644 0001001 0000024 00000004340 13776002022 015351 0 ustar mac staff 0000000 0000000 =================
``zope.testing``
=================
.. image:: https://img.shields.io/pypi/v/zope.testing.svg
:target: https://pypi.python.org/pypi/zope.testing/
:alt: Latest Version
.. image:: https://travis-ci.com/zopefoundation/zope.testing.svg?branch=master
:target: https://travis-ci.com/zopefoundation/zope.testing
.. image:: https://readthedocs.org/projects/zopetesting/badge/?version=latest
:target: http://zopetesting.readthedocs.org/en/latest/
:alt: Documentation Status
This package provides a number of testing frameworks.
cleanup
Provides a mixin class for cleaning up after tests that
make global changes.
formparser
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.
loggingsupport
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.
loghandler
Logging handler for tests that check logging output.
module
Lets a doctest pretend to be a Python module.
See module.txt.
renormalizing
Regular expression pattern normalizing output checker.
Useful for doctests.
server
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**
setupstack
A simple framework for automating doctest set-up and tear-down.
See setupstack.txt.
wait
A small utility for dealing with timing non-determinism
See wait.txt.
doctestcase
Support for defining doctests as methods of ``unittest.TestCase``
classes so that they can be more easily found by test runners, like
nose, that ignore test suites.
.. contents::
Getting started developing zope.testing
=======================================
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.
zope.testing-4.9/appveyor.yml 0000644 0001001 0000024 00000002163 13776002022 016253 0 ustar mac staff 0000000 0000000 # Generated from:
# https://github.com/zopefoundation/meta/tree/master/config/pure-python
environment:
matrix:
- python: 27
- python: 27-x64
- python: 35
- python: 35-x64
- python: 36
- python: 36-x64
- python: 37
- python: 37-x64
- python: 38
- python: 38-x64
- python: 39
- python: 39-x64
install:
- "SET PATH=C:\\Python%PYTHON%;c:\\Python%PYTHON%\\scripts;%PATH%"
- ps: |
$env:PYTHON = "C:\\Python${env:PYTHON}"
if (-not (Test-Path $env:PYTHON)) {
curl -o install_python.ps1 https://raw.githubusercontent.com/matthew-brett/multibuild/11a389d78892cf90addac8f69433d5e22bfa422a/install_python.ps1
.\install_python.ps1
}
- ps: if (-not (Test-Path $env:PYTHON)) { throw "No $env:PYTHON" }
- echo "C:\Program Files\Microsoft SDKs\Windows\v7.1\Bin\SetEnv.cmd" /x64 > "C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\bin\amd64\vcvars64.bat"
- python -m pip install -U pip
- pip install -U setuptools wheel
- pip install -U -e .[test]
build: false
test_script:
- zope-testrunner --test-path=src
on_success:
- echo Build succesful!
zope.testing-4.9/buildout.cfg 0000644 0001001 0000024 00000000273 13776002022 016173 0 ustar mac staff 0000000 0000000 [buildout]
develop = .
parts = py
unzip = true
[test]
recipe = zc.recipe.testrunner
eggs =
zope.testing
[py]
recipe = zc.recipe.egg
eggs = ${test:eggs}
nose
interpreter = py
zope.testing-4.9/rtd.txt 0000644 0001001 0000024 00000000073 13776002022 015213 0 ustar mac staff 0000000 0000000 repoze.sphinx.autointerface
zope.exceptions
zope.interface
zope.testing-4.9/setup.cfg 0000644 0001001 0000024 00000000221 13776002023 015476 0 ustar mac staff 0000000 0000000 [bdist_wheel]
universal = 1
[flake8]
doctests = 1
[check-manifest]
ignore =
.editorconfig
.meta.toml
[egg_info]
tag_build =
tag_date = 0
zope.testing-4.9/setup.py 0000644 0001001 0000024 00000006234 13776002022 015400 0 ustar mac staff 0000000 0000000 ##############################################################################
#
# Copyright (c) 2004 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
# This package is developed by the Zope Toolkit project, documented here:
# http://docs.zope.org/zopetoolkit
# When developing and releasing this package, please follow the documented
# Zope Toolkit policies as described by this documentation.
##############################################################################
"""Setup for zope.testing package
"""
import os
from setuptools import setup
def read(*rnames):
with open(os.path.join(os.path.dirname(__file__), *rnames)) as f:
return f.read()
chapters = [
read((os.path.join('src', 'zope', 'testing', name)))
for name in [
'formparser.txt',
'loggingsupport.txt',
'renormalizing.txt',
'setupstack.txt',
'wait.txt',
'doctestcase.txt',
]
]
long_description = '\n\n'.join(
[read('README.rst')] +
chapters +
[read('CHANGES.rst')]
)
keywords = "zope testing doctest RENormalizing OutputChecker timeout logging"
setup(
name='zope.testing',
version='4.9',
url='https://github.com/zopefoundation/zope.testing',
license='ZPL 2.1',
description='Zope testing helpers',
long_description=long_description,
author='Zope Foundation and Contributors',
author_email='zope-dev@zope.org',
classifiers=[
"Development Status :: 5 - Production/Stable",
"Intended Audience :: Developers",
"License :: OSI Approved :: Zope Public License",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.5",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
"Programming Language :: Python :: Implementation :: CPython",
"Programming Language :: Python :: Implementation :: PyPy",
"Framework :: Zope :: 3",
"Topic :: Software Development :: Libraries :: Python Modules",
"Topic :: Software Development :: Testing",
],
keywords=keywords,
packages=[
"zope",
"zope.testing",
],
package_dir={'': 'src'},
namespace_packages=['zope'],
install_requires=[
'setuptools',
],
extras_require={
'test': [
'zope.testrunner',
],
},
include_package_data=True,
zip_safe=False,
test_suite='zope.testing.tests.test_suite',
)
zope.testing-4.9/src/ 0000755 0001001 0000024 00000000000 13776002023 014451 5 ustar mac staff 0000000 0000000 zope.testing-4.9/src/zope/ 0000755 0001001 0000024 00000000000 13776002023 015426 5 ustar mac staff 0000000 0000000 zope.testing-4.9/src/zope/__init__.py 0000644 0001001 0000024 00000000070 13776002022 017533 0 ustar mac staff 0000000 0000000 __import__('pkg_resources').declare_namespace(__name__)
zope.testing-4.9/src/zope/testing/ 0000755 0001001 0000024 00000000000 13776002023 017103 5 ustar mac staff 0000000 0000000 zope.testing-4.9/src/zope/testing/__init__.py 0000644 0001001 0000024 00000001202 13776002022 021206 0 ustar mac staff 0000000 0000000 ##############################################################################
#
# Copyright (c) 2001, 2002 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
zope.testing-4.9/src/zope/testing/cleanup.py 0000644 0001001 0000024 00000003404 13776002022 021104 0 ustar mac staff 0000000 0000000 ##############################################################################
#
# Copyright (c) 2001, 2002 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""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)
"""
_cleanups = []
def addCleanUp(func, args=(), kw={}):
"""Register a cleanup routines
Pass a function to be called to cleanup global data.
Optional argument tuple and keyword arguments may be passed.
"""
_cleanups.append((func, args, kw))
class CleanUp(object):
"""Mix-in class providing clean-up setUp and tearDown routines."""
def cleanUp(self):
"""Clean up global data."""
cleanUp()
setUp = tearDown = cleanUp
def cleanUp():
"""Clean up global data."""
for func, args, kw in _cleanups:
func(*args, **kw)
setUp = tearDown = cleanUp
zope.testing-4.9/src/zope/testing/doctestcase.py 0000644 0001001 0000024 00000020245 13776002022 021760 0 ustar mac staff 0000000 0000000 r"""Doctests in TestCase classes
The original ``doctest`` unittest integration was based on
``unittest`` test suites, which have fallen out of favor. This module
provides a way to define doctests inside of unittest ``TestCase``
classes. It also provides better integration with unittest test
fixtures, because doctests use setup provided by the containing test
case class. It also provides access to unittest assertion
methods.
You can define doctests in 4 ways:
- references to named files
- strings
- decorated functions with docstrings
- reference to named files decorating test-specific setup functions
.. some setup
>>> __name__ = 'tests'
Here are some examples::
from zope.testing import doctestcase
import doctest
import unittest
g = 'global'
class MyTest(unittest.TestCase):
def setUp(self):
self.a = 1
self.globs = dict(c=9)
test1 = doctestcase.file('test1.txt', optionflags=doctest.ELLIPSIS)
test2 = doctestcase.docteststring('''
>>> self.a, g, c
(1, 'global', 9)
''')
@doctestcase.doctestmethod(optionflags=doctest.ELLIPSIS)
def test3(self):
'''
>>> self.a, self.x, g, c
(1, 3, 'global', 9)
'''
self.x = 3
@doctestcase.doctestfile('test4.txt')
def test4(self):
self.x = 5
In this example, 3 constructors were used:
doctestfile (alias: file)
doctestfile makes a file-based test case.
This can be used as a decorator, in which case, the decorated
function is called before the test is run, to provide test-specific
setup.
docteststring (alias string)
docteststring constructs a doctest from a string.
doctestmethod (alias method)
doctestmethod constructs a doctest from a method.
The method's docstring provides the test. The method's body provides
optional test-specific setup.
Note that short aliases are provided, which may be useful in certain
import styles.
Tests have access to the following data:
- Tests created with the ``docteststring`` and ``doctestmethod``
constructors have access to the module globals of the defining
module.
- In tests created with the ``docteststring`` and ``doctestmethod``
constructors, the test case instance is available as the ``self``
variable.
- In tests created with the ``doctestfile`` constructor, the test case
instance is available as the ``test`` variable.
- If a test case defines a globs attribute, it must be a dictionary
and its contents are added to the test globals.
The constructors accept standard doctest ``optionflags`` and
``checker`` arguments.
Note that the doctest IGNORE_EXCEPTION_DETAIL option flag is
added to optionflags.
"""
import doctest
import inspect
import os
import re
import sys
import types
__all__ = ['doctestmethod', 'docteststring', 'doctestfile']
_parser = doctest.DocTestParser()
def _testify(name):
if not name.startswith('test'):
name = 'test_' + name
return name
def doctestmethod(test=None, optionflags=0, checker=None):
"""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.
"""
if test is None:
return lambda test: _doctestmethod(test, optionflags, checker)
return _doctestmethod(test, optionflags, checker)
method = doctestmethod
def _doctestmethod(test, optionflags, checker):
doc = test.__doc__
if not doc:
raise ValueError(test, "has no docstring")
setup = test
name = test.__name__
path = inspect.getsourcefile(test)
lineno = inspect.getsourcelines(test)[1]
fglobs = sys._getframe(3).f_globals
def test_method(self):
setup(self)
_run_test(self, doc, fglobs.copy(), name, path,
optionflags, checker, lineno=lineno)
test_method.__name__ = _testify(name)
return test_method
def docteststring(test, optionflags=0, checker=None, name=None):
"""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.
"""
fglobs = sys._getframe(2).f_globals
def test_string(self):
_run_test(self, test, fglobs.copy(), '', '',
optionflags, checker)
if name:
test_string.__name__ = _testify(name)
return test_string
string = docteststring
_not_word = re.compile(r'\W')
def doctestfile(path, optionflags=0, checker=None):
"""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.)
"""
base = os.path.dirname(os.path.abspath(
sys._getframe(2).f_globals['__file__']
))
path = os.path.join(base, path)
with open(path) as f:
test = f.read()
name = os.path.basename(path)
def test_file(self):
if isinstance(self, types.FunctionType):
setup = self
def test_file_w_setup(self):
setup(self)
_run_test(self, test, {}, name, path, optionflags, checker,
'test')
test_file_w_setup.__name__ = _testify(setup.__name__)
test_file_w_setup.filepath = path
test_file_w_setup.filename = os.path.basename(path)
return test_file_w_setup
_run_test(self, test, {}, name, path, optionflags, checker, 'test')
test_file.__name__ = name_from_path(path)
test_file.filepath = path
test_file.filename = os.path.basename(path)
return test_file
file = doctestfile
def doctestfiles(*paths, **kw):
"""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.
"""
def doctestfiles_(class_):
for path in paths:
name = name_from_path(path)
test = doctestfile(path, **kw)
test.__name__ = name
setattr(class_, name, test)
return class_
return doctestfiles_
files = doctestfiles
def name_from_path(path):
return _testify(
_not_word.sub('_', os.path.splitext(os.path.basename(path))[0])
)
def _run_test(self, test, globs, name, path,
optionflags, checker, testname='self', lineno=0):
globs.update(getattr(self, 'globs', ()))
globs[testname] = self
optionflags |= doctest.IGNORE_EXCEPTION_DETAIL
doctest.DocTestCase(
_parser.get_doctest(test, globs, name, path, lineno),
optionflags=optionflags,
checker=checker,
).runTest()
zope.testing-4.9/src/zope/testing/doctestcase.txt 0000644 0001001 0000024 00000023305 13776002022 022147 0 ustar mac staff 0000000 0000000 Doctests in TestCase classes
============================
The original ``doctest`` unittest integration was based on
``unittest`` test suites, which have fallen out of favor. This module
provides a way to define doctests inside of unittest ``TestCase``
classes. It provides better integration with unittest test fixtures,
because doctests use setup provided by the containing test case
class. It provides access to unittest assertion methods.
You can define doctests in multiple ways:
- references to named files
- strings
- decorated functions with docstrings
- reference to named files decorating test-specific setup functions
- reference to named files decorating a test class
.. some setup
>>> __name__ = 'tests'
Here are some examples::
>>> from zope.testing import doctestcase
>>> import doctest
>>> import unittest
>>> g = 'global'
>>> class MyTest(unittest.TestCase):
...
... def setUp(self):
... self.a = 1
... self.globs = dict(c=9)
...
... test1 = doctestcase.file('test-1.txt', optionflags=doctest.ELLIPSIS)
...
... test2 = doctestcase.docteststring('''
... >>> self.a, g, c
... (1, 'global', 9)
... ''')
...
... @doctestcase.doctestmethod(optionflags=doctest.ELLIPSIS)
... def test3(self):
... '''
... >>> self.a, self.x, g, c
... (1, 3, 'global', 9)
... '''
... self.x = 3
...
... @doctestcase.doctestfile('test4.txt')
... def test4(self):
... self.x = 5
>>> import sys
>>> @doctestcase.doctestfiles('loggingsupport.txt', 'renormalizing.txt')
... class MoreTests(unittest.TestCase):
...
... def setUp(self):
... def print_(*args):
... sys.stdout.write(' '.join(map(str, args))+'\n')
... self.globs = dict(print_=print_)
.. We can run these tests with the ``unittest`` test runner.
>>> loader = unittest.TestLoader()
>>> sys.stdout.writeln = lambda s: sys.stdout.write(s+'\n')
>>> suite = loader.loadTestsFromTestCase(MyTest)
>>> result = suite.run(unittest.TextTestResult(sys.stdout, True, 3))
test1 (tests.MyTest) ... ok
test2 (tests.MyTest) ... ok
test3 (tests.MyTest) ... ok
test4 (tests.MyTest) ... ok
>>> suite = loader.loadTestsFromTestCase(MoreTests)
>>> result = suite.run(unittest.TextTestResult(sys.stdout, True, 3))
test_loggingsupport (tests.MoreTests) ... ok
test_renormalizing (tests.MoreTests) ... ok
>>> for _, e in result.errors:
... print(e); print
Check meta data:
>>> MyTest.test1.__name__
'test_1'
>>> import os, zope.testing
>>> (MyTest.test1.filepath ==
... os.path.join(os.path.dirname(zope.testing.__file__), 'test-1.txt'))
True
>>> MyTest.test1.filename
'test-1.txt'
>>> MyTest.test3.__name__
'test3'
>>> MyTest.test4.__name__
'test4'
>>> (MyTest.test4.filepath ==
... os.path.join(os.path.dirname(zope.testing.__file__), 'test4.txt'))
True
>>> MyTest.test4.filename
'test4.txt'
>>> MoreTests.test_loggingsupport.__name__
'test_loggingsupport'
>>> MoreTests.test_loggingsupport.filename
'loggingsupport.txt'
>>> (MoreTests.test_loggingsupport.filepath ==
... os.path.join(os.path.dirname(zope.testing.__file__),
... 'loggingsupport.txt'))
True
In these examples, 4 constructors were used:
doctestfile (alias: file)
doctestfile makes a file-based test case.
This can be used as a decorator, in which case, the decorated
function is called before the test is run, to provide test-specific
setup.
doctestfiles (alias: files)
doctestfiles makes file-based test cases and assigns them to the
decorated class.
Multiple files can be specified and the resulting doctests are added
as members of the decorated class.
docteststring (alias string)
docteststring constructs a doctest from a string.
doctestmethod (alias method)
doctestmethod constructs a doctest from a method.
The method's docstring provides the test. The method's body provides
optional test-specific setup.
Note that short aliases are provided, which maye be useful in certain
import styles.
Tests have access to the following data:
- Tests created with the ``docteststring`` and ``doctestmethod``
constructors have access to the module globals of the defining
module.
- In tests created with the ``docteststring`` and ``doctestmethod``
constructors, the test case instance is available as the ``self``
variable.
- In tests created with the ``doctestfile`` and ``doctestfiles``
constructor, the test case instance is available as the ``test``
variable.
- If a test case defines a globs attribute, it must be a dictionary
and it's contents are added to the test globals.
The constructors accept standard doctest ``optionflags`` and
``checker`` arguments.
Note that the doctest IGNORE_EXCEPTION_DETAIL option flag is
added to optionflags.
When using ``doctestfile`` and ``doctestfile``, ``filename`` and
``filepath`` attributes are available that contain the test file name
and full path.
``__name__`` attributes of class members
----------------------------------------
Class members have ``__name__`` attributes set as follows:
- When using ``doctestmethod`` or ``doctestfile`` with a setup
function, ``__name__`` attribute is set to the name of the function.
A ``test_`` prefix is added, if the name doesn't start with ``test``.
- When ``doctestfile`` is used without a setup function or when
``doctestfiles`` is used, ``__name__`` is set to the last part of the
file path with the extension removed and non-word characters
converted to underscores. For example, with a test path of
``'/foo/bar/test-it.rst'``, the ``__name__`` attribute is set to
``'test_it'``. A ``test_`` prefix is added, if the name doesn't
start with ``test``.
- when using ``docteststring``, a ``name`` option can be passed in to
set ``__name__``. A ``test_`` prefix is added, if the name doesn't
start with ``test``.
The ``__name__`` attribute is important when using nose, because nose
discovers tests as class members using their ``__name__`` attributes,
whereas the unittest and py.test test runners use class dictionary keys.
.. Let's look at some failure cases:
>>> class MyTest(unittest.TestCase):
...
... test2 = doctestcase.string('''
... >>> 1
... 1
... >>> 1 + 1
... 1
... ''', name='test2')
...
... @doctestcase.method
... def test3(self):
... '''
... >>> self.x
... 3
... >>> 1 + 1
... 1
... '''
... self.x = 3
...
... @doctestcase.file('test4f.txt')
... def test4(self):
... self.x = 5
>>> suite = loader.loadTestsFromTestCase(MyTest)
>>> result = suite.run(unittest.TextTestResult(sys.stdout, True, 1))
FFF
>>> for c, e in result.failures:
... print(e) # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
Traceback (most recent call last):
...
...: Failed doctest test for
File "", line 0, in
----------------------------------------------------------------------
File "", line 4, in
Failed example:
1 + 1
Expected:
1
Got:
2
Traceback (most recent call last):
...
...: Failed doctest test for test3
File "None", line 10, in test3
----------------------------------------------------------------------
Line 4, in test3
Failed example:
1 + 1
Expected:
1
Got:
2
Traceback (most recent call last):
...
...: Failed doctest test for test4f.txt
File "...test4f.txt", line 0, in txt
----------------------------------------------------------------------
File "...test4f.txt", line 3, in test4f.txt
Failed example:
1 + 1
Expected:
1
Got:
2
Check string meta data:
>>> MyTest.test2.__name__
'test2'
.. Verify setting optionflags and checker
>>> class EasyChecker:
... def check_output(self, want, got, optionflags):
... return True
... def output_difference(self, example, got, optionflags):
... return ''
>>> class MyTest(unittest.TestCase):
...
... test2 = doctestcase.string('''
... >>> 1
... 2
... ''', checker=EasyChecker())
...
... @doctestcase.method(optionflags=doctest.ELLIPSIS)
... def test3(self):
... '''
... >>> 'Hello'
... '...'
... '''
...
... @doctestcase.file('test4e.txt', optionflags=doctest.ELLIPSIS)
... def test4(self):
... self.x = 5
>>> suite = loader.loadTestsFromTestCase(MyTest)
>>> result = suite.run(unittest.TextTestResult(sys.stdout, True, 2))
test2 (tests.MyTest) ... ok
test3 (tests.MyTest) ... ok
test4 (tests.MyTest) ... ok
.. test __name__ variations
>>> class MyTest(unittest.TestCase):
...
... foo = doctestcase.string('''>>> 1''', name='foo')
...
... @doctestcase.method
... def bar(self):
... '''
... >>> self.x
... 3
... '''
... @doctestcase.file('test4f.txt')
... def baz(self):
... pass
... wait = doctestcase.file('wait.txt')
>>> MyTest.foo.__name__
'test_foo'
>>> MyTest.bar.__name__
'test_bar'
>>> MyTest.baz.__name__
'test_baz'
>>> MyTest.wait.__name__
'test_wait'
zope.testing-4.9/src/zope/testing/exceptions.py 0000644 0001001 0000024 00000001741 13776002022 021640 0 ustar mac staff 0000000 0000000 ##############################################################################
#
# Copyright (c) 2004 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""Exceptions for zope.testing
"""
import warnings
# Tell people to use the builtin module instead.
warnings.warn(
'zope.testing.exceptions is deprecated in favour of '
'zope.testrunner.exceptions', DeprecationWarning,
stacklevel=2)
class DocTestFailureException(AssertionError):
"""Use custom exception for doctest unit test failures"""
zope.testing-4.9/src/zope/testing/formparser.py 0000644 0001001 0000024 00000016307 13776002022 021643 0 ustar mac staff 0000000 0000000 """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 *formparser.txt* for documentation.
This isn't intended to simulate a browser session; that's provided by
the `zope.testbrowser` package.
"""
__docformat__ = "reStructuredText"
import HTMLParser
import urlparse
def parse(data, base=None):
"""Return a form collection parsed from `data`.
`base` should be the URL from which `data` was retrieved.
"""
parser = FormParser(data, base)
return parser.parse()
class FormParser(object):
def __init__(self, data, base=None):
self.data = data
self.base = base
self._parser = HTMLParser.HTMLParser()
self._parser.handle_data = self._handle_data
self._parser.handle_endtag = self._handle_endtag
self._parser.handle_starttag = self._handle_starttag
self._parser.handle_startendtag = self._handle_starttag
self._buffer = []
self.current = None # current form
self.forms = FormCollection()
def parse(self):
"""Parse the document, returning the collection of forms."""
self._parser.feed(self.data)
self._parser.close()
return self.forms
# HTMLParser handlers
def _handle_data(self, data):
self._buffer.append(data)
def _handle_endtag(self, tag):
if tag == "textarea":
self.textarea.value = "".join(self._buffer)
self.textarea = None
elif tag == "select":
self.select = None
elif tag == "option":
option = self.select.options[-1]
label = "".join(self._buffer)
if not option.label:
option.label = label
if not option.value:
option.value = label
if option.selected:
if self.select.multiple:
self.select.value.append(option.value)
else:
self.select.value = option.value
def _handle_starttag(self, tag, attrs):
del self._buffer[:]
d = {}
for name, value in attrs:
d[name] = value
name = d.get("name")
id = d.get("id") or d.get("xml:id")
if tag == "form":
method = kwattr(d, "method", "get")
action = d.get("action", "").strip() or None
if self.base and action:
action = urlparse.urljoin(self.base, action)
enctype = kwattr(d, "enctype", "application/x-www-form-urlencoded")
self.current = Form(name, id, method, action, enctype)
self.forms.append(self.current)
elif tag == "input":
type = kwattr(d, "type", "text")
checked = "checked" in d
disabled = "disabled" in d
readonly = "readonly" in d
src = d.get("src", "").strip() or None
if self.base and src:
src = urlparse.urljoin(self.base, src)
value = d.get("value")
size = intattr(d, "size")
maxlength = intattr(d, "maxlength")
self._add_field(
Input(name, id, type, value, checked,
disabled, readonly, src, size, maxlength))
elif tag == "button":
pass
elif tag == "textarea":
disabled = "disabled" in d
readonly = "readonly" in d
self.textarea = Input(name, id, "textarea", None,
None, disabled, readonly,
None, None, None)
self.textarea.rows = intattr(d, "rows")
self.textarea.cols = intattr(d, "cols")
self._add_field(self.textarea)
# The value will be set when the is seen.
elif tag == "base":
href = d.get("href", "").strip()
if href and self.base:
href = urlparse.urljoin(self.base, href)
self.base = href
elif tag == "select":
disabled = "disabled" in d
multiple = "multiple" in d
size = intattr(d, "size")
self.select = Select(name, id, disabled, multiple, size)
self._add_field(self.select)
elif tag == "option":
disabled = "disabled" in d
selected = "selected" in d
value = d.get("value")
label = d.get("label")
option = Option(id, value, selected, label, disabled)
self.select.options.append(option)
# Helpers:
def _add_field(self, field):
if field.name in self.current:
ob = self.current[field.name]
if isinstance(ob, list):
ob.append(field)
else:
self.current[field.name] = [ob, field]
else:
self.current[field.name] = field
def kwattr(d, name, default=None):
"""Return attribute, converted to lowercase."""
v = d.get(name, default)
if v != default and v is not None:
v = v.strip().lower()
v = v or default
return v
def intattr(d, name):
"""Return attribute as an integer, or None."""
if name in d:
v = d[name].strip()
return int(v)
else:
return None
class FormCollection(list):
"""Collection of all forms from a page."""
def __getattr__(self, name):
for form in self:
if form.name == name:
return form
raise AttributeError(name)
class Form(dict):
"""A specific form within a page."""
# This object should provide some method to prepare a dictionary
# that can be passed directly as the value of the `form` argument
# to the `http()` function of the Zope functional test.
#
# This is probably a low priority given the availability of the
# `zope.testbrowser` package.
def __init__(self, name, id, method, action, enctype):
super(Form, self).__init__()
self.name = name
self.id = id
self.method = method
self.action = action
self.enctype = enctype
class Input(object):
"""Input element."""
rows = None
cols = None
def __init__(self, name, id, type, value, checked, disabled, readonly,
src, size, maxlength):
super(Input, self).__init__()
self.name = name
self.id = id
self.type = type
self.value = value
self.checked = checked
self.disabled = disabled
self.readonly = readonly
self.src = src
self.size = size
self.maxlength = maxlength
class Select(Input):
"""Select element."""
def __init__(self, name, id, disabled, multiple, size):
super(Select, self).__init__(name, id, "select", None, None,
disabled, None, None, size, None)
self.options = []
self.multiple = multiple
if multiple:
self.value = []
class Option(object):
"""Individual value representation for a select element."""
def __init__(self, id, value, selected, label, disabled):
super(Option, self).__init__()
self.id = id
self.value = value
self.selected = selected
self.label = label
self.disabled = disabled
zope.testing-4.9/src/zope/testing/formparser.txt 0000644 0001001 0000024 00000007626 13776002022 022036 0 ustar mac staff 0000000 0000000 Parsing HTML Forms
==================
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.
NOTE
formparser doesn't support Python 3.
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 = '''\
...
...
...
...
...
...
... First
... Another
...
... Third
... Fourth
...
...
...
...
... Just for fun, a second form, after specifying a base:
...
...
... Some text.
...
...
...
...
...
... '''
>>> 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
`` `` 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 ```` element provides some additional attributes:
>>> ta = forms[1]["sometext"]
>>> print ta.rows
5
>>> print ta.cols
None
>>> ta.value
'Some text.'
The ```` 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']
zope.testing-4.9/src/zope/testing/loggingsupport.py 0000644 0001001 0000024 00000003667 13776002022 022553 0 ustar mac staff 0000000 0000000 ##############################################################################
#
# Copyright (c) 2004 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
import logging
class Handler(logging.Handler):
def __init__(self, *names, **kw):
logging.Handler.__init__(self)
self.names = names
self.records = []
self.setLoggerLevel(**kw)
def setLoggerLevel(self, level=1):
self.level = level
self.oldlevels = {}
def emit(self, record):
self.records.append(record)
def clear(self):
del self.records[:]
def install(self):
for name in self.names:
logger = logging.getLogger(name)
self.oldlevels[name] = logger.level
logger.setLevel(self.level)
logger.addHandler(self)
def uninstall(self):
for name in self.names:
logger = logging.getLogger(name)
logger.setLevel(self.oldlevels[name])
logger.removeHandler(self)
def __str__(self):
return '\n'.join(
"%s %s\n %s" % (
record.name, record.levelname,
'\n'.join(
line
for line in record.getMessage().split('\n')
if line.strip()
),
)
for record in self.records
)
class InstalledHandler(Handler):
def __init__(self, *names, **kw):
Handler.__init__(self, *names, **kw)
self.install()
zope.testing-4.9/src/zope/testing/loggingsupport.txt 0000644 0001001 0000024 00000003027 13776002022 022730 0 ustar mac staff 0000000 0000000 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:
>>> 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
[]
zope.testing-4.9/src/zope/testing/loghandler.py 0000644 0001001 0000024 00000005113 13776002022 021573 0 ustar mac staff 0000000 0000000 ##############################################################################
#
# Copyright (c) 2003 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""logging handler for tests that check logging output.
"""
import logging
class Handler(logging.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.
"""
def __init__(self, testcase, propagate=False):
logging.Handler.__init__(self)
self.records = []
# loggers stores (logger, propagate) tuples
self.loggers = []
self.closed = False
self.propagate = propagate
self.testcase = testcase
def close(self):
"""Remove handler from any loggers it was added to."""
if self.closed:
return
for logger, propagate in self.loggers:
logger.removeHandler(self)
logger.propagate = propagate
self.closed = True
def add(self, name):
"""Add handler to logger named name."""
logger = logging.getLogger(name)
old_prop = logger.propagate
logger.addHandler(self)
if self.propagate:
logger.propagate = 1
else:
logger.propagate = 0
self.loggers.append((logger, old_prop))
def emit(self, record):
self.records.append(record)
def assertLogsMessage(self, msg, level=None):
for r in self.records:
if r.getMessage() == msg:
if level is not None and r.levelno == level:
return
msg = "No log message contained %r" % msg
if level is not None:
msg += " at level %d" % level
self.testcase.fail(msg)
def failIfLogsMessage(self, msg):
for r in self.records:
if r.getMessage() == msg:
self.testcase.fail("Found log message %r" % msg)
zope.testing-4.9/src/zope/testing/module.py 0000644 0001001 0000024 00000003004 13776002022 020736 0 ustar mac staff 0000000 0000000 ##############################################################################
#
# Copyright (c) 2004 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""Fake module support
"""
import sys
class FakeModule(object):
def __init__(self, dict):
self.__dict = dict
def __getattr__(self, name):
try:
return self.__dict[name]
except KeyError:
raise AttributeError(name)
def __dir__(self):
return self.__dict.keys()
def setUp(test, name='__main__'):
dict = test.globs
dict['__name__'] = name
module = FakeModule(dict)
sys.modules[name] = module
if '.' in name:
name = name.split('.')
parent = sys.modules['.'.join(name[:-1])]
setattr(parent, name[-1], module)
def tearDown(test, name=None):
if name is None:
name = test.globs['__name__']
del test.globs['__name__']
del sys.modules[name]
if '.' in name:
name = name.split('.')
parent = sys.modules['.'.join(name[:-1])]
delattr(parent, name[-1])
zope.testing-4.9/src/zope/testing/module.txt 0000644 0001001 0000024 00000005373 13776002022 021140 0 ustar mac staff 0000000 0000000 Module setup
============
Normally when you create a class in a doctest, it will have the
``__module__`` attribute of ``'__builtin__'``. This is sometimes not
desirable. Let's demonstrate the behavior::
>>> class Foo(object):
... pass
>>> 'builtin' in Foo.__module__
True
By using ``zope.testing.module.setUp`` this can be
controlled. Normally you set up your tests with it, but in this case
we'll just call it manually.
To call this function manually, we need to set up a fake ``test``
object. This because the ``setUp`` function expects a test with at
least the ``globs`` dictionary attribute being present. Let's make
such a fake test object, using the globals of the doctest::
>>> class FakeTest(object):
... def __init__(self):
... self.globs = globals()
>>> test = FakeTest()
We can now call the ``setUp`` function::
>>> from zope.testing.module import setUp
>>> setUp(test)
We will now demonstrate that the ``__module__`` argument is something
else, in this case the default, ``__main__``::
>>> class Foo(object):
... pass
>>> Foo.__module__
'__main__'
Calling ``dir`` on the module will yield the expected attributes,
including the ``FakeTest`` class we added above.
>>> import __main__
>>> attrs = dir(__main__)
>>> "FakeTest" in attrs
True
Let's tear this down again::
>>> from zope.testing.module import tearDown
>>> tearDown(test)
We should now be back to the original situation::
>>> class Foo(object):
... pass
>>> 'builtin' in Foo.__module__
True
Importing
---------
Let's now imagine a more complicated example, were we actually want to
be able to import the fake module as well::
>>> setUp(test, 'fake')
>>> a = 'Hello world'
The import should not fail::
>>> import fake
>>> fake.a
'Hello world'
Let's tear it down again::
>>> tearDown(test)
>>> import fake
Traceback (most recent call last):
...
ImportError: No module named fake
If we enter a dotted name, it will actually try to place the fake
module in that dotted name::
>>> setUp(test, 'zope.testing.unlikelymodulename')
>>> a = 'Bye world'
>>> import zope.testing.unlikelymodulename
>>> zope.testing.unlikelymodulename.a
'Bye world'
>>> from zope.testing import unlikelymodulename
>>> unlikelymodulename.a
'Bye world'
>>> tearDown(test)
>>> import zope.testing.unlikelymodulename
Traceback (most recent call last):
...
ImportError: No module named unlikelymodulename
This only works for packages that already exist::
>>> setUp(test, 'unlikelynamespacename.fake')
Traceback (most recent call last):
...
KeyError: 'unlikelynamespacename'
Even so, we still need to tear down::
>>> tearDown(test)
Traceback (most recent call last):
...
KeyError: 'unlikelynamespacename'
zope.testing-4.9/src/zope/testing/renormalizing.py 0000644 0001001 0000024 00000013001 13776002022 022327 0 ustar mac staff 0000000 0000000 ##############################################################################
#
# Copyright (c) 2004 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
import doctest
import re
import sys
IGNORE_EXCEPTION_MODULE_IN_PYTHON2 = doctest.register_optionflag(
'IGNORE_EXCEPTION_MODULE_IN_PYTHON2')
IGNORE_EXCEPTION_MODULE_IN_PYTHON2_HINT = """\
===============================================================
HINT:
The optionflag IGNORE_EXCEPTION_MODULE_IN_PYTHON2 is set.
You seem to test traceback output.
If you are indeed, make sure to use the full dotted name of
the exception class like Python 3 displays,
even though you are running the tests in Python 2.
The exception message needs to be last line (and thus not
split over multiple lines).
==============================================================="""
class OutputChecker(doctest.OutputChecker):
"""Pattern-normalizing output checker
"""
def __init__(self, patterns=None):
if patterns is None:
patterns = []
self.transformers = list(map(self._cook, patterns))
def __add__(self, other):
if not isinstance(other, RENormalizing):
return NotImplemented
return RENormalizing(self.transformers + other.transformers)
def _cook(self, pattern):
if hasattr(pattern, '__call__'):
return pattern
regexp, replacement = pattern
return lambda text: regexp.sub(replacement, text)
def check_output(self, want, got, optionflags):
if got == want:
return True
for transformer in self.transformers:
want = transformer(want)
got = transformer(got)
if doctest.OutputChecker.check_output(self, want, got, optionflags):
return True
if sys.version_info[0] < 3:
if optionflags & IGNORE_EXCEPTION_MODULE_IN_PYTHON2:
want = strip_dottedname_from_traceback(want)
if doctest.OutputChecker.check_output(
self, want, got, optionflags):
return True
return False
def output_difference(self, example, got, optionflags):
want = example.want
# If want is empty, use original outputter. This is useful
# when setting up tests for the first time. In that case, we
# generally use the differencer to display output, which we evaluate
# by hand.
if not want.strip():
return doctest.OutputChecker.output_difference(
self, example, got, optionflags)
# Dang, this isn't as easy to override as we might wish
original = want
for transformer in self.transformers:
want = transformer(want)
got = transformer(got)
# temporarily hack example with normalized want:
example.want = want
if sys.version_info[0] < 3:
if optionflags & IGNORE_EXCEPTION_MODULE_IN_PYTHON2:
if maybe_a_traceback(got) is not None:
got += IGNORE_EXCEPTION_MODULE_IN_PYTHON2_HINT
result = doctest.OutputChecker.output_difference(
self, example, got, optionflags)
example.want = original
return result
RENormalizing = OutputChecker
def is_dotted_name(name):
if sys.version_info[0] >= 3:
return (
name and
all(element.isidentifier() for element in name.split('.')))
else:
# Python 2 lacked str.isidentifier, but also restricted identifiers
# to ASCII so a regex match is straightforward.
match = re.match(
r'^(?:[A-Za-z_][A-Za-z0-9_]*\.)*[A-Za-z_][A-Za-z0-9_]*$', name)
return match is not None
def maybe_a_traceback(string):
# We wanted to confirm more strictly we're dealing with a traceback here.
# However, doctest will preprocess exception output. It gets rid of the
# the stack trace and the "Traceback (most recent call last)"-part. It
# passes only the exception message to the checker.
if not string:
return None
lines = string.splitlines()
last = lines[-1]
if not last:
return None
words = last.split(' ')
first = words[0]
if len(words) > 1 and not first.endswith(':'):
return None
# If IGNORE_EXCEPTION_MODULE_IN_PYTHON2 was applied to an entire file,
# then this may run on strings that aren't the exception message part of
# a traceback. The doctest interface makes it impossible to detect this
# reasonably, so do our best to restrict this to only lines that start
# with something that looks like a Python dotted name. It's best to
# apply IGNORE_EXCEPTION_MODULE_IN_PYTHON2 only to examples that need
# it.
if not is_dotted_name(first[:-1]):
return None
return lines, last, words, first
def strip_dottedname_from_traceback(string):
maybe = maybe_a_traceback(string)
if maybe is None:
return string
lines, last, words, first = maybe
name = first.split('.')[-1]
words[0] = name
last = ' '.join(words)
lines[-1] = last
return '\n'.join(lines)
zope.testing-4.9/src/zope/testing/renormalizing.txt 0000644 0001001 0000024 00000022555 13776002022 022534 0 ustar mac staff 0000000 0000000 Regular expression pattern normalizing output checker
=====================================================
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 = '''\
...
... completed in 1.234 seconds.
...
...
... completed in 123.234 seconds.
...
...
... completed in .234 seconds.
...
...
... completed in 1.234 seconds.
...
... '''
>>> got = '''\
...
... completed in 1.235 seconds.
...
...
... completed in 123.233 seconds.
...
...
... completed in .231 seconds.
...
...
... 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'), ' seconds'),
... (re.compile('at 0x[0-9a-f]+'), 'at '),
... ])
>>> checker.check_output(want, got, 0)
True
Usual OutputChecker options work as expected:
>>> want_ellided = '''\
...
... completed in 1.234 seconds.
... ...
...
... completed in 1.234 seconds.
...
... '''
>>> 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()
...
... completed in 1.234 seconds.
... ...
...
... completed in 1.234 seconds.
...
... '''
>>> example = doctest.Example(source, want_ellided)
>>> print_(checker.output_difference(example, got, 0))
Expected:
>
completed in seconds.
...
>
completed in seconds.
Got:
>
completed in seconds.
>
completed in seconds.
>
completed in seconds.
>
completed in seconds.
>>> print_(checker.output_difference(example, got,
... doctest.REPORT_NDIFF))
Differences (ndiff with -expected +actual):
- >
- completed in seconds.
- ...
>
completed in seconds.
+ >
+ completed in seconds.
+
+ >
+ completed in seconds.
+
+ >
+ completed in seconds.
+
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:
Got:
completed in 1.235 seconds.
completed in 123.233 seconds.
completed in .231 seconds.
completed in 1.23 seconds.
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('', ''),
... ])
>>> want = '''\
... Usage: thundermonkey [options] [url]
...
... 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 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]
-
+
options:
-h display this help message
It is possible to combine OutputChecker checkers for easy reuse:
>>> address_and_time_checker = OutputChecker([
... (re.compile('[0-9]*[.][0-9]* seconds'), ' seconds'),
... (re.compile('at 0x[0-9a-f]+'), 'at '),
... ])
>>> 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 +: ...
Using the 2to3 exception normalization:
>>> from zope.testing.renormalizing import (
... IGNORE_EXCEPTION_MODULE_IN_PYTHON2)
>>> checker = OutputChecker()
>>> want = """\
... Traceback (most recent call last):
... foo.bar.FooBarError: requires at least one argument."""
>>> got = """\
... Traceback (most recent call last):
... FooBarError: requires at least one argument."""
>>> result = checker.check_output(
... want, got, IGNORE_EXCEPTION_MODULE_IN_PYTHON2)
>>> import sys
>>> if sys.version_info[0] < 3:
... expected = True
... else:
... expected = False
>>> result == expected
True
When reporting a failing test and running in Python 2, the normalizer tries
to be helpful by explaining how to test for exceptions in the traceback output.
>>> want = """\
... Traceback (most recent call last):
... foo.bar.FooBarErrorXX: requires at least one argument.
... """
>>> got = """\
... Traceback (most recent call last):
... FooBarError: requires at least one argument.
... """
>>> checker.check_output(want, got, IGNORE_EXCEPTION_MODULE_IN_PYTHON2)
False
>>> from doctest import Example
>>> example = Example('dummy', want)
>>> result = checker.output_difference(
... example, got, IGNORE_EXCEPTION_MODULE_IN_PYTHON2)
>>> output = """\
... Expected:
... Traceback (most recent call last):
... foo.bar.FooBarErrorXX: requires at least one argument.
... Got:
... Traceback (most recent call last):
... FooBarError: requires at least one argument.
... """
>>> hint = """\
... ===============================================================
... HINT:
... The optionflag IGNORE_EXCEPTION_MODULE_IN_PYTHON2 is set.
... You seem to test traceback output.
... If you are indeed, make sure to use the full dotted name of
... the exception class like Python 3 displays,
... even though you are running the tests in Python 2.
... The exception message needs to be last line (and thus not
... split over multiple lines).
... ==============================================================="""
>>> if sys.version_info[0] < 3:
... expected = output + hint
... else:
... expected = output
>>> result == expected
True
zope.testing-4.9/src/zope/testing/server.py 0000644 0001001 0000024 00000007347 13776002022 020775 0 ustar mac staff 0000000 0000000 ##############################################################################
#
# Copyright (c) 2007 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""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.
"""
from __future__ import print_function
import sys
import webbrowser
import urlparse
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
# XXX: I don't think this module works on Python 3!
def makeRequestHandler(http, user=None, password=None):
class FunctionalTestRequestHandler(BaseHTTPRequestHandler):
def do_GET(self):
request = self.raw_requestline
if user and password:
# Authentication is built in, as there is no fluent
# way of transferring session from functional test to
# the real browser
request += "Authorization: Basic %s:%s\r\n" % (user, password)
# Write headers to the request
for header in self.headers.headers:
request += header
request += '\r\n'
if self.headers.get('Content-Length'):
data = self.rfile.read(int(self.headers.get('Content-Length')))
request += data
else:
# if no content-length was set - read until the last
# char, then finish
self.request.setblocking(0)
while True:
try:
char = self.rfile.read()
except Exception: # XXX: should probably be IOError?
break
request += char
response = http(request)
self.wfile.write(response)
do_POST = do_GET
return FunctionalTestRequestHandler
def addPortToURL(url, port):
"""Add a port number to the url.
>>> 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'
"""
(scheme, netloc, url, query, fragment) = urlparse.urlsplit(url)
netloc = netloc.split(':')[0]
netloc = "%s:%s" % (netloc, port)
url = urlparse.urlunsplit((scheme, netloc, url, query, fragment))
return url
def startServer(http, url, user=None, password=None, port=8000):
try:
server_address = ('', port)
requestHandler = makeRequestHandler(http, user, password)
url = addPortToURL(url, port)
httpd = HTTPServer(server_address, requestHandler)
# XXX we rely on browser being slower than our server
webbrowser.open(url)
print('Starting HTTP server...', file=sys.stderr)
httpd.serve_forever()
except KeyboardInterrupt:
print('Stopped HTTP server.', file=sys.stderr)
zope.testing-4.9/src/zope/testing/setupstack.py 0000644 0001001 0000024 00000004257 13776002022 021652 0 ustar mac staff 0000000 0000000 ##############################################################################
#
# Copyright (c) 2005 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""Stack-based test doctest setUp and tearDown
See setupstack.txt
"""
import os
import stat
import tempfile
import unittest
key = '__' + __name__
def globs(test):
try:
return test.globs
except AttributeError:
return test.__dict__
def register(test, function, *args, **kw):
tglobs = globs(test)
stack = tglobs.get(key)
if stack is None:
stack = tglobs[key] = []
stack.append((function, args, kw))
def tearDown(test):
tglobs = globs(test)
stack = tglobs.get(key)
while stack:
f, p, k = stack.pop()
f(*p, **k)
def setUpDirectory(test):
tmp = tempfile.mkdtemp()
register(test, rmtree, tmp)
here = os.getcwd()
register(test, os.chdir, here)
os.chdir(tmp)
def rmtree(path):
for path, dirs, files in os.walk(path, False):
for fname in files:
fname = os.path.join(path, fname)
if not os.path.islink(fname):
os.chmod(fname, stat.S_IWUSR)
os.remove(fname)
for dname in dirs:
dname = os.path.join(path, dname)
os.rmdir(dname)
os.rmdir(path)
def context_manager(test, manager):
result = manager.__enter__()
register(test, manager.__exit__, None, None, None)
return result
def mock(test, *args, **kw):
import mock as mock_module
return context_manager(test, mock_module.patch(*args, **kw))
class TestCase(unittest.TestCase):
tearDown = tearDown
register = register
setUpDirectory = setUpDirectory
context_manager = context_manager
mock = mock
zope.testing-4.9/src/zope/testing/setupstack.txt 0000644 0001001 0000024 00000016116 13776002022 022036 0 ustar mac staff 0000000 0000000 Stack-based test setUp and tearDown
===================================
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
Temporary Test Directory
------------------------
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:
>>> with open('Data.fs', 'w') as f:
... foo = f.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 sys.platform != 'win32':
... 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
Context-manager support
-----------------------
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 __init__(self, *args, **kw):
... if kw:
... args += (kw, )
... self.args = args
... def __enter__(self):
... print_('enter', *self.args)
... return 42
... def __exit__(self, *args):
... print_('exit', args, *self.args)
>>> manager = Manager()
>>> test = Test()
>>> zope.testing.setupstack.context_manager(test, manager)
enter
42
>>> zope.testing.setupstack.tearDown(test)
exit (None, None, None)
.. faux mock
>>> old_mock = sys.modules.get('mock')
>>> class FauxMock:
... @classmethod
... def patch(self, *args, **kw):
... return Manager(*args, **kw)
>>> sys.modules['mock'] = FauxMock
By far the most commonly called context manager is ``mock.patch``, so
there's a convenience function to make that simpler:
>>> zope.testing.setupstack.mock(test, 'time.time', return_value=42)
enter time.time {'return_value': 42}
42
>>> zope.testing.setupstack.tearDown(test)
exit (None, None, None) time.time {'return_value': 42}
globs
-----
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.
TestCase
--------
A TestCase class is provided that:
- Makes it easier to call setupstack apis, and
- provides an inheritable tearDown method.
In addition to a tearDown method, the class provides methods:
``setupDirectory()``
Creates a temporary directory, runs the test, and cleans it up.
``register(func)``
Register a tear-down function.
``context_manager(manager)``
Enters a context manager and exits it on tearDown.
``mock(*args, **kw)``
Enters ``mock.patch`` with the given arguments.
This is syntactic sugur for::
context_manager(mock.patch(*args, **kw))
Here's an example:
>>> class MyTests(zope.testing.setupstack.TestCase):
...
... def setUp(self):
... self.setUpDirectory()
... self.context_manager(manager)
... self.mock("time.time", return_value=42)
...
... @self.register
... def _():
... print('done w test')
...
... def test(self):
... if here == os.getcwd():
... print('Failed to change directory')
.. let's try it
>>> import unittest
>>> loader = unittest.TestLoader()
>>> suite = loader.loadTestsFromTestCase(MyTests)
>>> result = suite.run(unittest.TestResult())
enter
enter time.time {'return_value': 42}
done w test
exit (None, None, None) time.time {'return_value': 42}
exit (None, None, None)
.. cleanup
>>> if old_mock:
... sys.modules['mock'] = old_mock
... else:
... del sys.modules['mock']
zope.testing-4.9/src/zope/testing/test-1.txt 0000644 0001001 0000024 00000000015 13776002022 020754 0 ustar mac staff 0000000 0000000 >>> test.a
1
zope.testing-4.9/src/zope/testing/test4.txt 0000644 0001001 0000024 00000000050 13776002022 020701 0 ustar mac staff 0000000 0000000 >>> test.a, test.x, c
(1, 5, 9)
zope.testing-4.9/src/zope/testing/test4e.txt 0000644 0001001 0000024 00000000024 13776002022 021047 0 ustar mac staff 0000000 0000000 >>> 'Hello'
'H...o'
zope.testing-4.9/src/zope/testing/test4f.txt 0000644 0001001 0000024 00000000052 13776002022 021051 0 ustar mac staff 0000000 0000000 >>> test.x
5
>>> 1 + 1
1
zope.testing-4.9/src/zope/testing/test_renormalizing.py 0000644 0001001 0000024 00000007117 13776002022 023401 0 ustar mac staff 0000000 0000000 import sys
import textwrap
import unittest
from zope.testing.renormalizing import (
is_dotted_name,
strip_dottedname_from_traceback,
)
class Exception2To3(unittest.TestCase):
def test_is_dotted_name_ascii_no_dots(self):
self.assertTrue(is_dotted_name('FooBarError'))
def test_is_dotted_name_ascii_dots(self):
self.assertTrue(is_dotted_name('foo.bar.FooBarError'))
def test_is_dotted_name_unicode_no_dots(self):
result = is_dotted_name(u'FooB\xe1rError')
if sys.version_info[0] >= 3:
self.assertTrue(result)
else:
self.assertFalse(result)
def test_is_dotted_name_unicode_dots(self):
result = is_dotted_name(u'foo.b\xe1r.FooB\xe1rError')
if sys.version_info[0] >= 3:
self.assertTrue(result)
else:
self.assertFalse(result)
def test_is_dotted_name_ellipsis(self):
self.assertFalse(is_dotted_name('...'))
def test_is_dotted_name_not_identifier(self):
self.assertFalse(is_dotted_name('foo=bar'))
def test_strip_dottedname(self):
string = textwrap.dedent("""\
Traceback (most recent call last):
foo.bar.FooBarError: requires at least one argument.""")
expected = textwrap.dedent("""\
Traceback (most recent call last):
FooBarError: requires at least one argument.""")
self.assertEqual(expected, strip_dottedname_from_traceback(string))
def test_strip_dottedname_without_exception_arguments(self):
string = textwrap.dedent("""\
Traceback (most recent call last):
foo.bar.FooBarError""")
expected = textwrap.dedent("""\
Traceback (most recent call last):
FooBarError""")
self.assertEqual(expected, strip_dottedname_from_traceback(string))
def test_no_dots_in_name(self):
string = textwrap.dedent("""\
Traceback (most recent call last):
FooBarError: requires at least one argument.""")
expected = textwrap.dedent("""\
Traceback (most recent call last):
FooBarError: requires at least one argument.""")
self.assertEqual(expected, strip_dottedname_from_traceback(string))
def test_no_colon_in_first_word(self):
string = textwrap.dedent("""\
Traceback (most recent call last):
foo.bar.FooBarError requires at least one argument.""")
expected = textwrap.dedent("""\
Traceback (most recent call last):
foo.bar.FooBarError requires at least one argument.""")
self.assertEqual(expected, strip_dottedname_from_traceback(string))
def test_input_empty(self):
string = ''
expected = ''
self.assertEqual(expected, strip_dottedname_from_traceback(string))
def test_input_spaces(self):
string = ' '
expected = ' '
self.assertEqual(expected, strip_dottedname_from_traceback(string))
def test_input_ellipsis(self):
string = '...'
expected = '...'
self.assertEqual(expected, strip_dottedname_from_traceback(string))
def test_input_last_line_not_dotted_name(self):
string = 'foo=bar'
expected = 'foo=bar'
self.assertEqual(expected, strip_dottedname_from_traceback(string))
def test_last_line_empty(self):
string = textwrap.dedent("""\
Traceback (most recent call last):
""")
expected = textwrap.dedent("""\
Traceback (most recent call last):
""")
self.assertEqual(expected, strip_dottedname_from_traceback(string))
zope.testing-4.9/src/zope/testing/testrunner.py 0000644 0001001 0000024 00000000515 13776002022 021666 0 ustar mac staff 0000000 0000000 import warnings
warnings.warn('zope.testing.testrunner is deprecated in favour of '
'zope.testrunner', DeprecationWarning, stacklevel=2)
try:
from zope import testrunner
import zope.testing
# Now replace this module with the right one:
zope.testing.testrunner = testrunner
except ImportError:
pass
zope.testing-4.9/src/zope/testing/tests.py 0000644 0001001 0000024 00000005011 13776002022 020613 0 ustar mac staff 0000000 0000000 ##############################################################################
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""Tests for the testing framework.
"""
import doctest
import sys
import re
import unittest
from zope.testing import renormalizing
from zope.testing.test_renormalizing import Exception2To3
def print_(*args):
sys.stdout.write(' '.join(map(str, args))+'\n')
def setUp(test):
test.globs['print_'] = print_
def test_suite():
suite = unittest.TestSuite((
doctest.DocFileSuite(
'module.txt',
# Python 3.3 changed exception messaging:
# https://bugs.launchpad.net/zope.testing/+bug/1055720
# and then Python 3.6 introduced ImportError subclasses
checker=renormalizing.RENormalizing([
(re.compile('ModuleNotFoundError:'), 'ImportError:'),
(re.compile(
"No module named '?zope.testing.unlikelymodulename'?"),
'No module named unlikelymodulename'),
(re.compile("No module named '?fake'?"),
'No module named fake')])),
doctest.DocFileSuite('loggingsupport.txt', setUp=setUp),
doctest.DocFileSuite('renormalizing.txt', setUp=setUp),
doctest.DocFileSuite('setupstack.txt', setUp=setUp),
doctest.DocFileSuite(
'wait.txt', setUp=setUp,
checker=renormalizing.RENormalizing([
# For Python 3.4.
(re.compile('zope.testing.wait.TimeOutWaitingFor: '),
'TimeOutWaitingFor: '),
# For Python 3.5
(re.compile('zope.testing.wait.Wait.TimeOutWaitingFor: '),
'TimeOutWaitingFor: '),
])
),
))
if sys.version_info[:2] >= (2, 7):
suite.addTests(doctest.DocFileSuite('doctestcase.txt'))
if sys.version_info[0] < 3:
suite.addTests(doctest.DocTestSuite('zope.testing.server'))
suite.addTests(doctest.DocFileSuite('formparser.txt'))
suite.addTest(
unittest.makeSuite(Exception2To3))
return suite
zope.testing-4.9/src/zope/testing/wait.py 0000644 0001001 0000024 00000003653 13776002022 020427 0 ustar mac staff 0000000 0000000 ##############################################################################
#
# Copyright Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
import time
class Wait:
class TimeOutWaitingFor(Exception):
"A test condition timed out"
timeout = 9
wait = .01
def __init__(self,
timeout=None, wait=None, exception=None,
getnow=lambda: time.time, getsleep=lambda: time.sleep):
if timeout is not None:
self.timeout = timeout
if wait is not None:
self.wait = wait
if exception is not None:
self.TimeOutWaitingFor = exception
self.getnow = getnow
self.getsleep = getsleep
def __call__(self, func=None, timeout=None, wait=None, message=None):
if func is None:
return lambda func: self(func, timeout, wait, message)
if func():
return
now = self.getnow()
sleep = self.getsleep()
if timeout is None:
timeout = self.timeout
if wait is None:
wait = self.wait
wait = float(wait)
deadline = now() + timeout
while 1:
sleep(wait)
if func():
return
if now() > deadline:
raise self.TimeOutWaitingFor(
message or
getattr(func, '__doc__') or
getattr(func, '__name__')
)
wait = Wait()
zope.testing-4.9/src/zope/testing/wait.txt 0000644 0001001 0000024 00000007472 13776002022 020621 0 ustar mac staff 0000000 0000000 Wait until a condition holds (or until a time out)
==================================================
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:
``wait`` has some keyword options:
timeout
How long, in seconds, to wait for the condition to hold
Defaults to 9 seconds.
wait
How long to wait between calls.
Defaults to .01 seconds.
message
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
.. more tests
>>> import time
>>> now = time.time()
>>> @wait(timeout=.01, message='dang')
... def no_way():
... "never true"
Traceback (most recent call last):
...
TimeOutWaitingFor: dang
>>> .01 < (time.time() - now) < .03
True
Customization
-------------
``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:
exception
Timeout exception class
getnow
Function used to get a function for getting the current time.
Default: lambda : time.time
getsleep
Function used to get a sleep function.
Default: lambda : time.sleep
timeout
Default timeout
Default: 9
wait
Default time to wait between attempts
Default: .01
.. more tests
>>> def mysleep(t):
... print_('mysleep', t)
... time.sleep(t)
>>> def mynow():
... print_('mynow')
... return time.time()
>>> wait = zope.testing.wait.Wait(
... getnow=(lambda : mynow), getsleep=(lambda : mysleep),
... exception=ValueError, timeout=.1, wait=.02)
>>> @wait
... def _(state=[]):
... if len(state) > 1:
... return True
... state.append(0)
mynow
mysleep 0.02
mynow
mysleep 0.02
>>> @wait(wait=.002)
... def _(state=[]):
... if len(state) > 1:
... return True
... state.append(0)
mynow
mysleep 0.002
mynow
mysleep 0.002
>>> @wait(timeout=0)
... def _(state=[]):
... if len(state) > 1:
... return True
... state.append(0)
Traceback (most recent call last):
...
ValueError: _
>>> wait = zope.testing.wait.Wait(timeout=0)
>>> @wait(timeout=0)
... def _(state=[]):
... if len(state) > 1:
... return True
... state.append(0)
Traceback (most recent call last):
...
TimeOutWaitingFor: _
zope.testing-4.9/src/zope.testing.egg-info/ 0000755 0001001 0000024 00000000000 13776002023 020574 5 ustar mac staff 0000000 0000000 zope.testing-4.9/src/zope.testing.egg-info/PKG-INFO 0000644 0001001 0000024 00000210130 13776002022 021665 0 ustar mac staff 0000000 0000000 Metadata-Version: 2.1
Name: zope.testing
Version: 4.9
Summary: Zope testing helpers
Home-page: https://github.com/zopefoundation/zope.testing
Author: Zope Foundation and Contributors
Author-email: zope-dev@zope.org
License: ZPL 2.1
Description: =================
``zope.testing``
=================
.. image:: https://img.shields.io/pypi/v/zope.testing.svg
:target: https://pypi.python.org/pypi/zope.testing/
:alt: Latest Version
.. image:: https://travis-ci.com/zopefoundation/zope.testing.svg?branch=master
:target: https://travis-ci.com/zopefoundation/zope.testing
.. image:: https://readthedocs.org/projects/zopetesting/badge/?version=latest
:target: http://zopetesting.readthedocs.org/en/latest/
:alt: Documentation Status
This package provides a number of testing frameworks.
cleanup
Provides a mixin class for cleaning up after tests that
make global changes.
formparser
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.
loggingsupport
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.
loghandler
Logging handler for tests that check logging output.
module
Lets a doctest pretend to be a Python module.
See module.txt.
renormalizing
Regular expression pattern normalizing output checker.
Useful for doctests.
server
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**
setupstack
A simple framework for automating doctest set-up and tear-down.
See setupstack.txt.
wait
A small utility for dealing with timing non-determinism
See wait.txt.
doctestcase
Support for defining doctests as methods of ``unittest.TestCase``
classes so that they can be more easily found by test runners, like
nose, that ignore test suites.
.. contents::
Getting started developing zope.testing
=======================================
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.
Parsing HTML Forms
==================
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.
NOTE
formparser doesn't support Python 3.
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 = '''\
...
...
...
...
...
...
... First
... Another
...
... Third
... Fourth
...
...
...
...
... Just for fun, a second form, after specifying a base:
...
...
... Some text.
...
...
...
...
...
... '''
>>> 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
`` `` 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 ```` element provides some additional attributes:
>>> ta = forms[1]["sometext"]
>>> print ta.rows
5
>>> print ta.cols
None
>>> ta.value
'Some text.'
The ```` 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']
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:
>>> 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
[]
Regular expression pattern normalizing output checker
=====================================================
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 = '''\
...
... completed in 1.234 seconds.
...
...
... completed in 123.234 seconds.
...
...
... completed in .234 seconds.
...
...
... completed in 1.234 seconds.
...
... '''
>>> got = '''\
...
... completed in 1.235 seconds.
...
...
... completed in 123.233 seconds.
...
...
... completed in .231 seconds.
...
...
... 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'), ' seconds'),
... (re.compile('at 0x[0-9a-f]+'), 'at '),
... ])
>>> checker.check_output(want, got, 0)
True
Usual OutputChecker options work as expected:
>>> want_ellided = '''\
...
... completed in 1.234 seconds.
... ...
...
... completed in 1.234 seconds.
...
... '''
>>> 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()
...
... completed in 1.234 seconds.
... ...
...
... completed in 1.234 seconds.
...
... '''
>>> example = doctest.Example(source, want_ellided)
>>> print_(checker.output_difference(example, got, 0))
Expected:
>
completed in seconds.
...
>
completed in seconds.
Got:
>
completed in seconds.
>
completed in seconds.
>
completed in seconds.
>
completed in seconds.
>>> print_(checker.output_difference(example, got,
... doctest.REPORT_NDIFF))
Differences (ndiff with -expected +actual):
- >
- completed in seconds.
- ...
>
completed in seconds.
+ >
+ completed in seconds.
+
+ >
+ completed in seconds.
+
+ >
+ completed in seconds.
+
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:
Got:
completed in 1.235 seconds.
completed in 123.233 seconds.
completed in .231 seconds.
completed in 1.23 seconds.
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('', ''),
... ])
>>> want = '''\
... Usage: thundermonkey [options] [url]
...
... 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 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]
-
+
options:
-h display this help message
It is possible to combine OutputChecker checkers for easy reuse:
>>> address_and_time_checker = OutputChecker([
... (re.compile('[0-9]*[.][0-9]* seconds'), ' seconds'),
... (re.compile('at 0x[0-9a-f]+'), 'at '),
... ])
>>> 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 +: ...
Using the 2to3 exception normalization:
>>> from zope.testing.renormalizing import (
... IGNORE_EXCEPTION_MODULE_IN_PYTHON2)
>>> checker = OutputChecker()
>>> want = """\
... Traceback (most recent call last):
... foo.bar.FooBarError: requires at least one argument."""
>>> got = """\
... Traceback (most recent call last):
... FooBarError: requires at least one argument."""
>>> result = checker.check_output(
... want, got, IGNORE_EXCEPTION_MODULE_IN_PYTHON2)
>>> import sys
>>> if sys.version_info[0] < 3:
... expected = True
... else:
... expected = False
>>> result == expected
True
When reporting a failing test and running in Python 2, the normalizer tries
to be helpful by explaining how to test for exceptions in the traceback output.
>>> want = """\
... Traceback (most recent call last):
... foo.bar.FooBarErrorXX: requires at least one argument.
... """
>>> got = """\
... Traceback (most recent call last):
... FooBarError: requires at least one argument.
... """
>>> checker.check_output(want, got, IGNORE_EXCEPTION_MODULE_IN_PYTHON2)
False
>>> from doctest import Example
>>> example = Example('dummy', want)
>>> result = checker.output_difference(
... example, got, IGNORE_EXCEPTION_MODULE_IN_PYTHON2)
>>> output = """\
... Expected:
... Traceback (most recent call last):
... foo.bar.FooBarErrorXX: requires at least one argument.
... Got:
... Traceback (most recent call last):
... FooBarError: requires at least one argument.
... """
>>> hint = """\
... ===============================================================
... HINT:
... The optionflag IGNORE_EXCEPTION_MODULE_IN_PYTHON2 is set.
... You seem to test traceback output.
... If you are indeed, make sure to use the full dotted name of
... the exception class like Python 3 displays,
... even though you are running the tests in Python 2.
... The exception message needs to be last line (and thus not
... split over multiple lines).
... ==============================================================="""
>>> if sys.version_info[0] < 3:
... expected = output + hint
... else:
... expected = output
>>> result == expected
True
Stack-based test setUp and tearDown
===================================
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
Temporary Test Directory
------------------------
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:
>>> with open('Data.fs', 'w') as f:
... foo = f.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 sys.platform != 'win32':
... 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
Context-manager support
-----------------------
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 __init__(self, *args, **kw):
... if kw:
... args += (kw, )
... self.args = args
... def __enter__(self):
... print_('enter', *self.args)
... return 42
... def __exit__(self, *args):
... print_('exit', args, *self.args)
>>> manager = Manager()
>>> test = Test()
>>> zope.testing.setupstack.context_manager(test, manager)
enter
42
>>> zope.testing.setupstack.tearDown(test)
exit (None, None, None)
.. faux mock
>>> old_mock = sys.modules.get('mock')
>>> class FauxMock:
... @classmethod
... def patch(self, *args, **kw):
... return Manager(*args, **kw)
>>> sys.modules['mock'] = FauxMock
By far the most commonly called context manager is ``mock.patch``, so
there's a convenience function to make that simpler:
>>> zope.testing.setupstack.mock(test, 'time.time', return_value=42)
enter time.time {'return_value': 42}
42
>>> zope.testing.setupstack.tearDown(test)
exit (None, None, None) time.time {'return_value': 42}
globs
-----
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.
TestCase
--------
A TestCase class is provided that:
- Makes it easier to call setupstack apis, and
- provides an inheritable tearDown method.
In addition to a tearDown method, the class provides methods:
``setupDirectory()``
Creates a temporary directory, runs the test, and cleans it up.
``register(func)``
Register a tear-down function.
``context_manager(manager)``
Enters a context manager and exits it on tearDown.
``mock(*args, **kw)``
Enters ``mock.patch`` with the given arguments.
This is syntactic sugur for::
context_manager(mock.patch(*args, **kw))
Here's an example:
>>> class MyTests(zope.testing.setupstack.TestCase):
...
... def setUp(self):
... self.setUpDirectory()
... self.context_manager(manager)
... self.mock("time.time", return_value=42)
...
... @self.register
... def _():
... print('done w test')
...
... def test(self):
... if here == os.getcwd():
... print('Failed to change directory')
.. let's try it
>>> import unittest
>>> loader = unittest.TestLoader()
>>> suite = loader.loadTestsFromTestCase(MyTests)
>>> result = suite.run(unittest.TestResult())
enter
enter time.time {'return_value': 42}
done w test
exit (None, None, None) time.time {'return_value': 42}
exit (None, None, None)
.. cleanup
>>> if old_mock:
... sys.modules['mock'] = old_mock
... else:
... del sys.modules['mock']
Wait until a condition holds (or until a time out)
==================================================
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:
``wait`` has some keyword options:
timeout
How long, in seconds, to wait for the condition to hold
Defaults to 9 seconds.
wait
How long to wait between calls.
Defaults to .01 seconds.
message
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
.. more tests
>>> import time
>>> now = time.time()
>>> @wait(timeout=.01, message='dang')
... def no_way():
... "never true"
Traceback (most recent call last):
...
TimeOutWaitingFor: dang
>>> .01 < (time.time() - now) < .03
True
Customization
-------------
``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:
exception
Timeout exception class
getnow
Function used to get a function for getting the current time.
Default: lambda : time.time
getsleep
Function used to get a sleep function.
Default: lambda : time.sleep
timeout
Default timeout
Default: 9
wait
Default time to wait between attempts
Default: .01
.. more tests
>>> def mysleep(t):
... print_('mysleep', t)
... time.sleep(t)
>>> def mynow():
... print_('mynow')
... return time.time()
>>> wait = zope.testing.wait.Wait(
... getnow=(lambda : mynow), getsleep=(lambda : mysleep),
... exception=ValueError, timeout=.1, wait=.02)
>>> @wait
... def _(state=[]):
... if len(state) > 1:
... return True
... state.append(0)
mynow
mysleep 0.02
mynow
mysleep 0.02
>>> @wait(wait=.002)
... def _(state=[]):
... if len(state) > 1:
... return True
... state.append(0)
mynow
mysleep 0.002
mynow
mysleep 0.002
>>> @wait(timeout=0)
... def _(state=[]):
... if len(state) > 1:
... return True
... state.append(0)
Traceback (most recent call last):
...
ValueError: _
>>> wait = zope.testing.wait.Wait(timeout=0)
>>> @wait(timeout=0)
... def _(state=[]):
... if len(state) > 1:
... return True
... state.append(0)
Traceback (most recent call last):
...
TimeOutWaitingFor: _
Doctests in TestCase classes
============================
The original ``doctest`` unittest integration was based on
``unittest`` test suites, which have fallen out of favor. This module
provides a way to define doctests inside of unittest ``TestCase``
classes. It provides better integration with unittest test fixtures,
because doctests use setup provided by the containing test case
class. It provides access to unittest assertion methods.
You can define doctests in multiple ways:
- references to named files
- strings
- decorated functions with docstrings
- reference to named files decorating test-specific setup functions
- reference to named files decorating a test class
.. some setup
>>> __name__ = 'tests'
Here are some examples::
>>> from zope.testing import doctestcase
>>> import doctest
>>> import unittest
>>> g = 'global'
>>> class MyTest(unittest.TestCase):
...
... def setUp(self):
... self.a = 1
... self.globs = dict(c=9)
...
... test1 = doctestcase.file('test-1.txt', optionflags=doctest.ELLIPSIS)
...
... test2 = doctestcase.docteststring('''
... >>> self.a, g, c
... (1, 'global', 9)
... ''')
...
... @doctestcase.doctestmethod(optionflags=doctest.ELLIPSIS)
... def test3(self):
... '''
... >>> self.a, self.x, g, c
... (1, 3, 'global', 9)
... '''
... self.x = 3
...
... @doctestcase.doctestfile('test4.txt')
... def test4(self):
... self.x = 5
>>> import sys
>>> @doctestcase.doctestfiles('loggingsupport.txt', 'renormalizing.txt')
... class MoreTests(unittest.TestCase):
...
... def setUp(self):
... def print_(*args):
... sys.stdout.write(' '.join(map(str, args))+'\n')
... self.globs = dict(print_=print_)
.. We can run these tests with the ``unittest`` test runner.
>>> loader = unittest.TestLoader()
>>> sys.stdout.writeln = lambda s: sys.stdout.write(s+'\n')
>>> suite = loader.loadTestsFromTestCase(MyTest)
>>> result = suite.run(unittest.TextTestResult(sys.stdout, True, 3))
test1 (tests.MyTest) ... ok
test2 (tests.MyTest) ... ok
test3 (tests.MyTest) ... ok
test4 (tests.MyTest) ... ok
>>> suite = loader.loadTestsFromTestCase(MoreTests)
>>> result = suite.run(unittest.TextTestResult(sys.stdout, True, 3))
test_loggingsupport (tests.MoreTests) ... ok
test_renormalizing (tests.MoreTests) ... ok
>>> for _, e in result.errors:
... print(e); print
Check meta data:
>>> MyTest.test1.__name__
'test_1'
>>> import os, zope.testing
>>> (MyTest.test1.filepath ==
... os.path.join(os.path.dirname(zope.testing.__file__), 'test-1.txt'))
True
>>> MyTest.test1.filename
'test-1.txt'
>>> MyTest.test3.__name__
'test3'
>>> MyTest.test4.__name__
'test4'
>>> (MyTest.test4.filepath ==
... os.path.join(os.path.dirname(zope.testing.__file__), 'test4.txt'))
True
>>> MyTest.test4.filename
'test4.txt'
>>> MoreTests.test_loggingsupport.__name__
'test_loggingsupport'
>>> MoreTests.test_loggingsupport.filename
'loggingsupport.txt'
>>> (MoreTests.test_loggingsupport.filepath ==
... os.path.join(os.path.dirname(zope.testing.__file__),
... 'loggingsupport.txt'))
True
In these examples, 4 constructors were used:
doctestfile (alias: file)
doctestfile makes a file-based test case.
This can be used as a decorator, in which case, the decorated
function is called before the test is run, to provide test-specific
setup.
doctestfiles (alias: files)
doctestfiles makes file-based test cases and assigns them to the
decorated class.
Multiple files can be specified and the resulting doctests are added
as members of the decorated class.
docteststring (alias string)
docteststring constructs a doctest from a string.
doctestmethod (alias method)
doctestmethod constructs a doctest from a method.
The method's docstring provides the test. The method's body provides
optional test-specific setup.
Note that short aliases are provided, which maye be useful in certain
import styles.
Tests have access to the following data:
- Tests created with the ``docteststring`` and ``doctestmethod``
constructors have access to the module globals of the defining
module.
- In tests created with the ``docteststring`` and ``doctestmethod``
constructors, the test case instance is available as the ``self``
variable.
- In tests created with the ``doctestfile`` and ``doctestfiles``
constructor, the test case instance is available as the ``test``
variable.
- If a test case defines a globs attribute, it must be a dictionary
and it's contents are added to the test globals.
The constructors accept standard doctest ``optionflags`` and
``checker`` arguments.
Note that the doctest IGNORE_EXCEPTION_DETAIL option flag is
added to optionflags.
When using ``doctestfile`` and ``doctestfile``, ``filename`` and
``filepath`` attributes are available that contain the test file name
and full path.
``__name__`` attributes of class members
----------------------------------------
Class members have ``__name__`` attributes set as follows:
- When using ``doctestmethod`` or ``doctestfile`` with a setup
function, ``__name__`` attribute is set to the name of the function.
A ``test_`` prefix is added, if the name doesn't start with ``test``.
- When ``doctestfile`` is used without a setup function or when
``doctestfiles`` is used, ``__name__`` is set to the last part of the
file path with the extension removed and non-word characters
converted to underscores. For example, with a test path of
``'/foo/bar/test-it.rst'``, the ``__name__`` attribute is set to
``'test_it'``. A ``test_`` prefix is added, if the name doesn't
start with ``test``.
- when using ``docteststring``, a ``name`` option can be passed in to
set ``__name__``. A ``test_`` prefix is added, if the name doesn't
start with ``test``.
The ``__name__`` attribute is important when using nose, because nose
discovers tests as class members using their ``__name__`` attributes,
whereas the unittest and py.test test runners use class dictionary keys.
.. Let's look at some failure cases:
>>> class MyTest(unittest.TestCase):
...
... test2 = doctestcase.string('''
... >>> 1
... 1
... >>> 1 + 1
... 1
... ''', name='test2')
...
... @doctestcase.method
... def test3(self):
... '''
... >>> self.x
... 3
... >>> 1 + 1
... 1
... '''
... self.x = 3
...
... @doctestcase.file('test4f.txt')
... def test4(self):
... self.x = 5
>>> suite = loader.loadTestsFromTestCase(MyTest)
>>> result = suite.run(unittest.TextTestResult(sys.stdout, True, 1))
FFF
>>> for c, e in result.failures:
... print(e) # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
Traceback (most recent call last):
...
...: Failed doctest test for
File "", line 0, in
----------------------------------------------------------------------
File "", line 4, in
Failed example:
1 + 1
Expected:
1
Got:
2
Traceback (most recent call last):
...
...: Failed doctest test for test3
File "None", line 10, in test3
----------------------------------------------------------------------
Line 4, in test3
Failed example:
1 + 1
Expected:
1
Got:
2
Traceback (most recent call last):
...
...: Failed doctest test for test4f.txt
File "...test4f.txt", line 0, in txt
----------------------------------------------------------------------
File "...test4f.txt", line 3, in test4f.txt
Failed example:
1 + 1
Expected:
1
Got:
2
Check string meta data:
>>> MyTest.test2.__name__
'test2'
.. Verify setting optionflags and checker
>>> class EasyChecker:
... def check_output(self, want, got, optionflags):
... return True
... def output_difference(self, example, got, optionflags):
... return ''
>>> class MyTest(unittest.TestCase):
...
... test2 = doctestcase.string('''
... >>> 1
... 2
... ''', checker=EasyChecker())
...
... @doctestcase.method(optionflags=doctest.ELLIPSIS)
... def test3(self):
... '''
... >>> 'Hello'
... '...'
... '''
...
... @doctestcase.file('test4e.txt', optionflags=doctest.ELLIPSIS)
... def test4(self):
... self.x = 5
>>> suite = loader.loadTestsFromTestCase(MyTest)
>>> result = suite.run(unittest.TextTestResult(sys.stdout, True, 2))
test2 (tests.MyTest) ... ok
test3 (tests.MyTest) ... ok
test4 (tests.MyTest) ... ok
.. test __name__ variations
>>> class MyTest(unittest.TestCase):
...
... foo = doctestcase.string('''>>> 1''', name='foo')
...
... @doctestcase.method
... def bar(self):
... '''
... >>> self.x
... 3
... '''
... @doctestcase.file('test4f.txt')
... def baz(self):
... pass
... wait = doctestcase.file('wait.txt')
>>> MyTest.foo.__name__
'test_foo'
>>> MyTest.bar.__name__
'test_bar'
>>> MyTest.baz.__name__
'test_baz'
>>> MyTest.wait.__name__
'test_wait'
Changes
=======
4.9 (2021-01-08)
----------------
- Make ``setupstack.txt`` test work again if the current directory is empty.
4.8 (2021-01-04)
----------------
- Add support for Python 3.8 and 3.9.
- Drop support for Python 3.3 and 3.4.
- Extend IGNORE_EXCEPTION_MODULE_IN_PYTHON2 to cover also exceptions without
arguments (thus without a colon on the last line of the traceback output).
4.7 (2018-10-04)
----------------
- Added support for Python 3.7.
4.6.2 (2017-06-12)
------------------
- Remove dependencies on ``zope.interface`` and ``zope.exceptions``;
they're not used here.
- Remove use of 2to3 for outdated versions of PyPy3, letting us build
universal wheels.
4.6.1 (2017-01-04)
------------------
- Add support for Python 3.6.
4.6.0 (2016-10-20)
------------------
- Introduce option flag ``IGNORE_EXCEPTION_MODULE_IN_PYTHON2`` to normalize
exception class names in traceback output. In Python 3 they are displayed as
the full dotted name. In Python 2 they are displayed as "just" the class
name. When running doctests in Python 3, the option flag will not have any
effect, however when running the same test in Python 2, the segments in the
full dotted name leading up to the class name are stripped away from the
"expected" string.
- Drop support for Python 2.6 and 3.2.
- Add support for Python 3.5.
- Cleaned up useless 2to3 conversion.
4.5.0 (2015-09-02)
------------------
- Added meta data for test case methods created with
``zope.testing.doctestcase``.
- Reasonable values for ``__name__``, making sure that ``__name__``
starts with ``test``.
- For ``doctestfile`` methods, provide ``filename`` and ``filepath``
attributes.
The meta data us useful, for example, for selecting tests with the
nose attribute mechanism.
- Added ``doctestcase.doctestfiles``
- Define multiple doctest files at once.
- Automatically assign test class members. So rather than::
class MYTests(unittest.TestCase):
...
test_foo = doctestcase.doctestfile('foo.txt')
You can use::
@doctestcase.doctestfiles('foo.txt', 'bar.txt', ...)
class MYTests(unittest.TestCase):
...
4.4.0 (2015-07-16)
------------------
- Added ``zope.testing.setupstack.mock`` as a convenience function for
setting up mocks in tests. (The Python ``mock`` package must be in
the path for this to work. The excellent ``mock`` package isn't a
dependency of ``zope.testing``.)
- Added the base class ``zope.testing.setupstack.TestCase`` to make it
much easier to use ``zope.testing.setupstack`` in ``unittest`` test
cases.
4.3.0 (2015-07-15)
------------------
- Added support for creating doctests as methods of
``unittest.TestCase`` classes so that they can found automatically
by test runners, like *nose* that ignore test suites.
4.2.0 (2015-06-01)
------------------
- **Actually** remove long-deprecated ``zope.testing.doctest`` (announced as
removed in 4.0.0) and ``zope.testing.doctestunit``.
- Add support for PyPy and PyPy3.
4.1.3 (2014-03-19)
------------------
- Add support for Python 3.4.
- Update ``boostrap.py`` to version 2.2.
4.1.2 (2013-02-19)
------------------
- Adjust Trove classifiers to reflect the currently supported Python
versions. Officially drop Python 2.4 and 2.5. Add Python 3.3.
- LP: #1055720: Fix failing test on Python 3.3 due to changed exception
messaging.
4.1.1 (2012-02-01)
------------------
- Fix: Windows test failure.
4.1.0 (2012-01-29)
------------------
- Add context-manager support to ``zope.testing.setupstack``
- Make ``zope.testing.setupstack`` usable with all tests, not just
doctests and added ``zope.testing.setupstack.globs``, which makes it
easier to write test setup code that workes with doctests and other
kinds of tests.
- Add the ``wait`` module, which makes it easier to deal with
non-deterministic timing issues.
- Rename ``zope.testing.renormalizing.RENormalizing`` to
``zope.testing.renormalizing.OutputChecker``. The old name is an
alias.
- Update tests to run with Python 3.
- Label more clearly which features are supported by Python 3.
- Reorganize documentation.
4.0.0 (2011-11-09)
------------------
- Remove the deprecated ``zope.testing.doctest``.
- Add Python 3 support.
- Fix test which fails if there is a file named `Data.fs` in the current
working directory.
3.10.2 (2010-11-30)
-------------------
- Fix test of broken symlink handling to not break on Windows.
3.10.1 (2010-11-29)
-------------------
- Fix removal of broken symlinks on Unix.
3.10.0 (2010-07-21)
-------------------
- Remove ``zope.testing.testrunner``, which now is moved to zope.testrunner.
- Update fix for LP #221151 to a spelling compatible with Python 2.4.
3.9.5 (2010-05-19)
------------------
- LP #579019: When layers are run in parallel, ensure that each ``tearDown``
is called, including the first layer which is run in the main
thread.
- Deprecate ``zope.testing.testrunner`` and ``zope.testing.exceptions``.
They have been moved to a separate zope.testrunner module, and will be
removed from zope.testing in 4.0.0, together with ``zope.testing.doctest``.
3.9.4 (2010-04-13)
------------------
- LP #560259: Fix subunit output formatter to handle layer setup
errors.
- LP #399394: Add a ``--stop-on-error`` / ``--stop`` / ``-x`` option to
the testrunner.
- LP #498162: Add a ``--pdb`` alias for the existing ``--post-mortem``
/ ``-D`` option to the testrunner.
- LP #547023: Add a ``--version`` option to the testrunner.
- Add tests for LP #144569 and #69988.
https://bugs.launchpad.net/bugs/69988
https://bugs.launchpad.net/zope3/+bug/144569
3.9.3 (2010-03-26)
------------------
- Remove import of ``zope.testing.doctest`` from ``zope.testing.renormalizer``.
- Suppress output to ``sys.stderr`` in ``testrunner-layers-ntd.txt``.
- Suppress ``zope.testing.doctest`` deprecation warning when running
our own test suite.
3.9.2 (2010-03-15)
------------------
- Fix broken ``from zope.testing.doctest import *``
3.9.1 (2010-03-15)
------------------
- No changes; reupload to fix broken 3.9.0 release on PyPI.
3.9.0 (2010-03-12)
------------------
- Modify the testrunner to use the standard Python ``doctest`` module instead
of the deprecated ``zope.testing.doctest``.
- Fix ``testrunner-leaks.txt`` to use the ``run_internal`` helper, so that
``sys.exit`` isn't triggered during the test run.
- Add support for conditionally using a subunit-based output
formatter upon request if subunit and testtools are available. Patch
contributed by Jonathan Lange.
3.8.7 (2010-01-26)
------------------
- Downgrade the ``zope.testing.doctest`` deprecation warning into a
PendingDeprecationWarning.
3.8.6 (2009-12-23)
------------------
- Add ``MANIFEST.in`` and reupload to fix broken 3.8.5 release on PyPI.
3.8.5 (2009-12-23)
------------------
- Add back ``DocFileSuite``, ``DocTestSuite``, ``debug_src`` and ``debug``
BBB imports back into ``zope.testing.doctestunit``; apparently many packages
still import them from there!
- Deprecate ``zope.testing.doctest`` and ``zope.testing.doctestunit``
in favor of the stdlib ``doctest`` module.
3.8.4 (2009-12-18)
------------------
- Fix missing imports and undefined variables reported by pyflakes,
adding tests to exercise the blind spots.
- Cleaned up unused imports reported by pyflakes.
- Add two new options to generate randomly ordered list of tests and to
select a specific order of tests.
- Allow combining RENormalizing checkers via ``+`` now:
``checker1 + checker2`` creates a checker with the transformations of both
checkers.
- Fix tests under Python 2.7.
3.8.3 (2009-09-21)
------------------
- Fix test failures due to using ``split()`` on filenames when running from a
directory with spaces in it.
- Fix testrunner behavior on Windows for ``-j2`` (or greater) combined with
``-v`` (or greater).
3.8.2 (2009-09-15)
------------------
- Remove hotshot profiler when using Python 2.6. That makes zope.testing
compatible with Python 2.6
3.8.1 (2009-08-12)
------------------
- Avoid hardcoding ``sys.argv[0]`` as script;
allow, for instance, Zope 2's `bin/instance test` (LP#407916).
- Produce a clear error message when a subprocess doesn't follow the
``zope.testing.testrunner`` protocol (LP#407916).
- Avoid unnecessarily squelching verbose output in a subprocess when there are
not multiple subprocesses.
- Avoid unnecessarily batching subprocess output, which can stymie automated
and human processes for identifying hung tests.
- Include incremental output when there are multiple subprocesses and a
verbosity of ``-vv`` or greater is requested. This again is not batched,
supporting automated processes and humans looking for hung tests.
3.8.0 (2009-07-24)
------------------
- Allow testrunner to include descendants of ``unittest.TestCase`` in test
modules, which no longer need to provide ``test_suite()``.
3.7.7 (2009-07-15)
------------------
- Clean up support for displaying tracebacks with supplements by turning it
into an always-enabled feature and making the dependency on
``zope.exceptions`` explicit.
- Fix #251759: prevent the testrunner descending into directories that
aren't Python packages.
- Code cleanups.
3.7.6 (2009-07-02)
------------------
- Add zope-testrunner ``console_scripts`` entry point. This exposes a
``zope-testrunner`` script with default installs allowing the testrunner
to be run from the command line.
3.7.5 (2009-06-08)
------------------
- Fix bug when running subprocesses on Windows.
- The option ``REPORT_ONLY_FIRST_FAILURE`` (command line option "-1") is now
respected even when a doctest declares its own ``REPORTING_FLAGS``, such as
``REPORT_NDIFF``.
- Fix bug that broke readline with pdb when using doctest
(see http://bugs.python.org/issue5727).
- Make tests pass on Windows and Linux at the same time.
3.7.4 (2009-05-01)
------------------
- Filenames of doctest examples now contain the line number and not
only the example number. So a stack trace in pdb tells the exact
line number of the current example. This fixes
https://bugs.launchpad.net/bugs/339813
- Colorization of doctest output correctly handles blank lines.
3.7.3 (2009-04-22)
------------------
- Improve handling of rogue threads: always exit with status so even
spinning daemon threads won't block the runner from exiting. This deprecated
the ``--with-exit-status`` option.
3.7.2 (2009-04-13)
------------------
- Fix test failure on Python 2.4 due to slight difference in the way
coverage is reported (__init__ files with only a single comment line are now
not reported)
- Fix bug that caused the test runner to hang when running subprocesses (as a
result Python 2.3 is no longer supported).
- Work around a bug in Python 2.6 (related to
http://bugs.python.org/issue1303673) that causes the profile tests to fail.
- Add explanitory notes to ``buildout.cfg`` about how to run the tests with
multiple versions of Python
3.7.1 (2008-10-17)
------------------
- The ``setupstack`` temporary directory support now properly handles
read-only files by making them writable before removing them.
3.7.0 (2008-09-22)
------------------
- Add alterate setuptools / distutils commands for running all tests
using our testrunner. See 'zope.testing.testrunner.eggsupport:ftest'.
- Add a setuptools-compatible test loader which skips tests with layers:
the testrunner used by ``setup.py test`` doesn't know about them, and those
tests then fail. See ``zope.testing.testrunner.eggsupport:SkipLayers``.
- Add support for Jython, when a garbage collector call is sent.
- Add support to bootstrap on Jython.
- Fix NameError in StartUpFailure.
- Open doctest files in universal mode, so that packages released on Windows
can be tested on Linux, for example.
3.6.0 (2008-07-10)
------------------
- Add ``-j`` option to parallel tests run in subprocesses.
- RENormalizer accepts plain Python callables.
- Add ``--slow-test`` option.
- Add ``--no-progress`` and ``--auto-progress`` options.
- Complete refactoring of the test runner into multiple code files and a more
modular (pipeline-like) architecture.
- Unify unit tests with the layer support by introducing a real unit test
layer.
- Add a doctest for ``zope.testing.module``. There were several bugs
that were fixed:
* ``README.txt`` was a really bad default argument for the module
name, as it is not a proper dotted name. The code would
immediately fail as it would look for the ``txt`` module in the
``README`` package. The default is now ``__main__``.
* The ``tearDown`` function did not clean up the ``__name__`` entry in the
global dictionary.
- Fix a bug that caused a SubprocessError to be generated if a subprocess
sent any output to stderr.
- Fix a bug that caused the unit tests to be skipped if run in a subprocess.
3.5.1 (2007-08-14)
------------------
- Invoke post-mortem debugging for layer-setup failures.
3.5.0 (2007-07-19)
------------------
- Ensure that the test runner works on Python 2.5.
- Add support for ``cProfile``.
- Add output colorizing (``-c`` option).
- Add ``--hide-secondary-failures`` and ``--show-secondary-failures`` options
(https://bugs.launchpad.net/zope3/+bug/115454).
- Fix some problems with Unicode in doctests.
- Fix "Error reading from subprocess" errors on Unix-like systems.
3.4 (2007-03-29)
----------------
- Add ``exit-with-status`` support (supports use with buildbot and
``zc.recipe.testing``)
- Add a small framework for automating set up and tear down of
doctest tests. See ``setupstack.txt``.
- Allow ``testrunner-wo-source.txt`` and ``testrunner-errors.txt`` to run
within a read-only source tree.
3.0 (2006-09-20)
----------------
- Update the doctest copy with text-file encoding support.
- Add logging-level support to the ``loggingsuppport`` module.
- At verbosity-level 1, dots are not output continuously, without any
line breaks.
- Improve output when the inability to tear down a layer causes tests
to be run in a subprocess.
- Make ``zope.exception`` required only if the ``zope_tracebacks`` extra is
requested.
- Fix the test coverage. If a module, for example `interfaces`, was in an
ignored directory/package, then if a module of the same name existed in a
covered directory/package, then it was also ignored there, because the
ignore cache stored the result by module name and not the filename of the
module.
2.0 (2006-01-05)
----------------
- Release a separate project corresponding to the version of ``zope.testing``
shipped as part of the Zope 3.2.0 release.
Keywords: zope testing doctest RENormalizing OutputChecker timeout logging
Platform: UNKNOWN
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: Zope Public License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python
Classifier: Programming Language :: Python :: 2
Classifier: Programming Language :: Python :: 2.7
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.5
Classifier: Programming Language :: Python :: 3.6
Classifier: Programming Language :: Python :: 3.7
Classifier: Programming Language :: Python :: 3.8
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: Implementation :: CPython
Classifier: Programming Language :: Python :: Implementation :: PyPy
Classifier: Framework :: Zope :: 3
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Topic :: Software Development :: Testing
Provides-Extra: test
zope.testing-4.9/src/zope.testing.egg-info/SOURCES.txt 0000644 0001001 0000024 00000002303 13776002023 022456 0 ustar mac staff 0000000 0000000 CHANGES.rst
COPYRIGHT.txt
LICENSE.txt
MANIFEST.in
README.rst
appveyor.yml
buildout.cfg
rtd.txt
setup.cfg
setup.py
tox.ini
src/zope/__init__.py
src/zope.testing.egg-info/PKG-INFO
src/zope.testing.egg-info/SOURCES.txt
src/zope.testing.egg-info/dependency_links.txt
src/zope.testing.egg-info/namespace_packages.txt
src/zope.testing.egg-info/not-zip-safe
src/zope.testing.egg-info/requires.txt
src/zope.testing.egg-info/top_level.txt
src/zope/testing/__init__.py
src/zope/testing/cleanup.py
src/zope/testing/doctestcase.py
src/zope/testing/doctestcase.txt
src/zope/testing/exceptions.py
src/zope/testing/formparser.py
src/zope/testing/formparser.txt
src/zope/testing/loggingsupport.py
src/zope/testing/loggingsupport.txt
src/zope/testing/loghandler.py
src/zope/testing/module.py
src/zope/testing/module.txt
src/zope/testing/renormalizing.py
src/zope/testing/renormalizing.txt
src/zope/testing/server.py
src/zope/testing/setupstack.py
src/zope/testing/setupstack.txt
src/zope/testing/test-1.txt
src/zope/testing/test4.txt
src/zope/testing/test4e.txt
src/zope/testing/test4f.txt
src/zope/testing/test_renormalizing.py
src/zope/testing/testrunner.py
src/zope/testing/tests.py
src/zope/testing/wait.py
src/zope/testing/wait.txt zope.testing-4.9/src/zope.testing.egg-info/dependency_links.txt 0000644 0001001 0000024 00000000001 13776002022 024641 0 ustar mac staff 0000000 0000000
zope.testing-4.9/src/zope.testing.egg-info/namespace_packages.txt 0000644 0001001 0000024 00000000005 13776002022 025121 0 ustar mac staff 0000000 0000000 zope
zope.testing-4.9/src/zope.testing.egg-info/not-zip-safe 0000644 0001001 0000024 00000000001 13776002022 023021 0 ustar mac staff 0000000 0000000
zope.testing-4.9/src/zope.testing.egg-info/requires.txt 0000644 0001001 0000024 00000000043 13776002022 023170 0 ustar mac staff 0000000 0000000 setuptools
[test]
zope.testrunner
zope.testing-4.9/src/zope.testing.egg-info/top_level.txt 0000644 0001001 0000024 00000000005 13776002022 023320 0 ustar mac staff 0000000 0000000 zope
zope.testing-4.9/tox.ini 0000644 0001001 0000024 00000002075 13776002022 015200 0 ustar mac staff 0000000 0000000 # Generated from:
# https://github.com/zopefoundation/meta/tree/master/config/pure-python
[tox]
envlist =
lint
py27
py35
py36
py37
py38
py39
pypy
pypy3
coverage
[testenv]
usedevelop = true
deps =
zope.testrunner
commands =
zope-testrunner --test-path=src []
extras =
test
[testenv:lint]
basepython = python3
skip_install = true
deps =
flake8
check-manifest
check-python-versions
commands =
flake8 src setup.py
check-manifest
check-python-versions
[testenv:coverage]
basepython = python3
deps =
coverage
coverage-python-version
zope.testrunner
commands =
coverage run -m zope.testrunner --test-path=src []
coverage html
coverage report -m --fail-under=55
[coverage:run]
branch = True
plugins = coverage_python_version
source = src
[coverage:report]
precision = 2
exclude_lines =
pragma: no cover
pragma: nocover
except ImportError:
raise NotImplementedError
if __name__ == '__main__':
self.fail
raise AssertionError
[coverage:html]
directory = htmlcov