=============================
z3c.testsetup and testrunners
=============================

Here we discuss complete test setups for the `cave` package contained
in thie `tests` directory. We will run the `zope.testing.testrunner`
and examine their output.

Short setups
------------

Using z3c.testsetup, we can define quite complex testsetups with only
two lines of code::

    >>> import os
    >>> cavepath = os.path.join(os.path.dirname(__file__), 'tests', 'cave')
    >>> setupfile = os.path.join(cavepath, 'samplesetup_short0.py')
    >>> print open(setupfile).read()
    import z3c.testsetup
    test_suite = z3c.testsetup.register_all_tests('z3c.testsetup.tests.cave')

This means, that we want to register all tests (doctests and 'normal'
python tests) from the ``cave`` package, whose name we passed in
dotted name notation as a string. This is enough information for a
testrunner::

    >>> import sys
    >>> defaults = [
    ...     '--path', cavepath,
    ...     '--tests-pattern', '^samplesetup_short0$',
    ...     ]
    >>> sys.argv = 'test '.split()
    >>> from zope.testing import testrunner
    >>> testrunner.run(defaults)
    Running unit tests:
      Ran 2 tests with 0 failures and 0 errors in ... seconds.
    Running z3c.testsetup.functional.doctesting.FunctionalLayer tests:
      Set up z3c.testsetup....doctesting.FunctionalLayer in ... seconds.
      Ran 2 tests with 0 failures and 0 errors in ... seconds.
    Tearing down left over layers:
      Tear down z3c.testsetup....doctesting.FunctionalLayer ... not supported
    Total: 4 tests, 0 failures, 0 errors in ... seconds.
    False

Of the four tests apparently run, there is one 'normal' python test
and three doctests, of which two are functional doctests.

Now, we only want to run the doctests in the ``cave`` package. A
suitable setup is contained in `samplesetup_short1.py`` in the
``cave`` package::

    >>> setupfile = os.path.join(cavepath, 'samplesetup_short1.py')
    >>> print open(setupfile).read()
    import z3c.testsetup
    <BLANKLINE>
    test_suite = z3c.testsetup.register_doctests('z3c.testsetup.tests.cave')

This means, that we want to register all doctests from the ``cave``
package, whose name we passed in dotted name notation as a
string. This is enough information for a testrunner::

    >>> defaults = [
    ...     '--path', cavepath,
    ...     '--tests-pattern', '^samplesetup_short1$',
    ...     ]
    >>> sys.argv = 'test '.split()
    >>> from zope.testing import testrunner
    >>> testrunner.run(defaults)
    Running unit tests:
      Ran 1 tests with 0 failures and 0 errors in ... seconds.
    Running z3c.testsetup....doctesting.FunctionalLayer tests:
      Set up z3c.testsetup....doctesting.FunctionalLayer in ... seconds.
      Ran 2 tests with 0 failures and 0 errors in ... seconds.
    Tearing down left over layers:
      Tear down z3c.testsetup....doctesting.FunctionalLayer ... not supported
    Total: 3 tests, 0 failures, 0 errors in ... seconds.
    False

In the above setup the handled package was given as a string with
dotted name notation. We can instead also pass the package itself, if
it was loaded before. This results in a slight longer example::

    >>> setupfile = os.path.join(cavepath, 'samplesetup_short2.py')
    >>> print open(setupfile).read()
    import z3c.testsetup
    from z3c.testsetup.tests import cave
    <BLANKLINE>
    test_suite = z3c.testsetup.register_doctests(cave)


Here we register all doctests from the ``cave`` module. Let's start a
testrunner with this setup::

    >>> defaults = [
    ...     '--path', cavepath,
    ...     '--tests-pattern', '^samplesetup_short2$',
    ...     ]
    >>> sys.argv = 'test '.split()
    >>> from zope.testing import testrunner
    >>> testrunner.run(defaults)
    Running unit tests:
      Ran 1 tests with 0 failures and 0 errors in ... seconds.
    Running z3c.testsetup....doctesting.FunctionalLayer tests:
      Set up z3c.testsetup....doctesting.FunctionalLayer in ... seconds.
      Ran 2 tests with 0 failures and 0 errors in ... seconds.
    Tearing down left over layers:
      Tear down z3c.testsetup....doctesting.FunctionalLayer ... not supported
    Total: 3 tests, 0 failures, 0 errors in ... seconds.
    False

Now let's run a suite of 'normal' python unit tests, i.e. tests, that
are not doctests. An appropriate setup file might look like this::

    >>> setupfile = os.path.join(cavepath, 'samplesetup_short3.py')
    >>> print open(setupfile).read()
    import z3c.testsetup
    from z3c.testsetup.tests import cave
    <BLANKLINE>
    test_suite = z3c.testsetup.register_pytests(cave)


The only difference to the example before is, that we use
`register_pytests` instead of `register_doctests`. If we run this
setup with the testrunner, one test should be found and executed. This
time we pass the `-vv` option to the testrunner, to get some more
information from the run::

    >>> defaults = [
    ...     '--path', cavepath,
    ...     '--tests-pattern', '^samplesetup_short3$',
    ...     ]
    >>> sys.argv = 'test -vv'.split()
    >>> from zope.testing import testrunner
    >>> testrunner.run(defaults)
    Running tests at level 1
    Running unit tests:
      Running:
     testFoo (z3c.testsetup.tests.cave.file1.TestTest)
      Ran 1 tests with 0 failures and 0 errors in ... seconds.
    False


Modified short setups
---------------------

The default settings of test setups might serve for plain testing
environments. Especially for functional tests, however, one often want
to set some basic values not foreseeable by default. Here some hints,
how default settings can be tweaked.

Setting ZCML config file for functional tests
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Functional tests often require ZCML registration of components to make
sense. For example one wants to register permissions etc. for use with
a testbrowser. In other words: often one wants to register a custom
ZCML layer when running functional doctests. This can be archieved as
follows:

We wrote a (more or less empty) ZCML config file in the ``cave``
package, which we want to be registered with functional doctests. To
do that, we use the now well-known ``register_all_tests`` function,
but give a ZCML file path and a layer name as arguments::

    >>> setupfile = os.path.join(cavepath, 'samplesetup_short4.py')
    >>> print open(setupfile).read()
    import z3c.testsetup
    test_suite = z3c.testsetup.register_all_tests(
        'z3c.testsetup.tests.cave',
        zcml_config='sampleftesting.zcml',
        layer_name = 'SampleLayer')

This will result in::

    >>> defaults = [
    ...     '--path', cavepath,
    ...     '--tests-pattern', '^samplesetup_short4$',
    ...     ]
    >>> sys.argv = 'test '.split()
    >>> from zope.testing import testrunner
    >>> testrunner.run(defaults)
    Running unit tests:
      Ran 2 tests with 0 failures and 0 errors in ... seconds.
    Running z3c.testsetup.tests.cave.SampleLayer tests:
      Set up z3c.testsetup.tests.cave.SampleLayer in ... seconds.
      Ran 2 tests with 0 failures and 0 errors in ... seconds.
    Tearing down left over layers:
      Tear down z3c.testsetup.tests.cave.SampleLayer ... not supported
    Total: 4 tests, 0 failures, 0 errors in ... seconds.
    False

Apparently now the custom ZCML file in the ``cave`` package was used.


Setting output checker for functional tests
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Output checkers modify the way, output of tests is recognized. This is
important for output which can not be foreseen exactly, timestamps for
example, or local file paths. In this case sometimes a regular
expression would match every single expression, but how can I tell the
testrunner, that all timestamps of the form 'N.NNN seconds' are
acceptable? Easy: use a checker::

    >>> setupfile = os.path.join(cavepath, 'samplesetup_short5.py')
    >>> print open(setupfile).read()
    import re
    from zope.testing import renormalizing
    import z3c.testsetup
    mychecker = renormalizing.RENormalizing([
        (re.compile('[0-9]*[.][0-9]* seconds'),
         '<SOME NUMBER OF> seconds'),
        (re.compile('at 0x[0-9a-f]+'), 'at <SOME ADDRESS>'),
        ])
    test_suite = z3c.testsetup.register_all_tests(
        'z3c.testsetup.tests.cave',
        checker = mychecker,
        extensions = ['.chk',],
        fregexp_list = ['.*checker.*',],
        )

This setup will find exactly one testfile, the file
``checkertest.chk`` in the ``cave`` package, that checks for output of
the form 'N.NNN seconds', with an arbitrary number of numbers.

Running the testrunner with this setup will result in::

    >>> defaults = [
    ...     '--path', cavepath,
    ...     '--tests-pattern', '^samplesetup_short5$',
    ...     ]
    >>> sys.argv = 'test -f '.split()
    >>> testrunner.run(defaults)
    Running z3c.testsetup....doctesting.FunctionalLayer tests:
      Set up z3c.testsetup....doctesting.FunctionalLayer in ... seconds.
      Ran 2 tests with 0 failures and 0 errors in ... seconds.
    Tearing down left over layers:
      Tear down z3c.testsetup....doctesting.FunctionalLayer ... not supported
    False

The same setup, but without a modified checker will deliver::

    >>> defaults = [
    ...     '--path', cavepath,
    ...     '--tests-pattern', '^samplesetup_short6$',
    ...     ]
    >>> sys.argv = 'test -f '.split()
    >>> testrunner.run(defaults)
    Running z3c.testsetup....doctesting.FunctionalLayer tests:
      Set up z3c.testsetup....doctesting.FunctionalLayer in ... seconds.
    <BLANKLINE>
    <BLANKLINE>
    Failure in test ...checkertest.chk
    Failed doctest test for checkertest.chk
      File "...checkertest.chk", line 0
    <BLANKLINE>
    ----------------------------------------------------------------------
    File "...checkertest.chk", line 10, in checkertest.chk
    Failed example:
        print "%s seconds" % 0.123
    Differences (ndiff with -expected +actual):
        - <SOME NUMBER OF> seconds
        + 0.123 seconds
    ----------------------------------------------------------------------
    File "...checkertest.chk", line 15, in checkertest.chk
    Failed example:
        print "A memory address at 0x1a0322ff"
    Differences (ndiff with -expected +actual):
        - A memory address at <SOME ADDRESS>
        + A memory address at 0x1a0322ff
    <BLANKLINE>
      Ran 2 tests with 1 failures and 0 errors in ... seconds.
    Tearing down left over layers:
      Tear down z3c.testsetup....doctesting.FunctionalLayer ... not supported
    True

Note that checkers are currently only supported for functional
doctests.


Setting globals for doctests
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

For a testsuite you can define a set of globals, which are applied to
each test before it runs. Normally one uses such globals, to have
certain functions or objects available, which are complex to setup
during tests but useful.

The objects and functions registered this way can then be used by
their names in tests out-of-the-box.

You can pass the globals for a testsetup by passing the ``globs``
keyword parameter or ``fglobs``/``uglobs``, if you only want them to
be applied to either functional or unit doctests. 

If you specify a `globs` parameter and a `fglobs` or `uglobs`
parameter, the latter will shadow the `globs` values. So `globs` will
have no effect, if you specify also both, `fglobs` and `uglobs`.

An example of the ``globs`` usage can be found in
``samplesetup_short7`` of the ``cave`` package::

    >>> setupfile = os.path.join(cavepath, 'samplesetup_short7.py')
    >>> print open(setupfile).read()
    import os
    from zope.testing import renormalizing
    import z3c.testsetup
    test_suite = z3c.testsetup.register_all_tests(
        'z3c.testsetup.tests.cave',
        extensions = ['.chk',],
        fregexp_list = [':Test-Layer:.*globs.*',],
        globs = {
            'basename' : os.path.basename
        }
        )

Here the ``os.path.basename`` function is registered under the name
'basename' and should be usable in the doctest file
``globstest.chk``::

    >>> defaults = [
    ...     '--path', cavepath,
    ...     '--tests-pattern', '^samplesetup_short7$',
    ...     ]
    >>> sys.argv = 'test -f '.split()
    >>> testrunner.run(defaults)
    Running z3c.testsetup....doctesting.FunctionalLayer tests:
      Set up z3c.testsetup....doctesting.FunctionalLayer in ... seconds.
      Ran 1 tests with 0 failures and 0 errors in ... seconds.
    Tearing down left over layers:
      Tear down z3c.testsetup....doctesting.FunctionalLayer ... not supported
    False

The testrunner finished without any error. So the ``basename``
function was indeed known to the doctest and could be used.

The same should happen, if we use the ``fglobs`` argument instead of
``globs``::

    >>> setupfile = os.path.join(cavepath, 'samplesetup_short8.py')
    >>> print open(setupfile).read()
    import os
    ...
    test_suite = z3c.testsetup.register_all_tests(
        'z3c.testsetup.tests.cave',
        extensions = ['.chk',],
        fregexp_list = [':Test-Layer:.*globs.*',],
        fglobs = {
            'basename' : os.path.basename
        }
        )

    >>> defaults = [
    ...     '--path', cavepath,
    ...     '--tests-pattern', '^samplesetup_short8$',
    ...     ]
    >>> sys.argv = 'test -f '.split()
    >>> testrunner.run(defaults)
    Running z3c.testsetup....doctesting.FunctionalLayer tests:
    ...
      Ran 1 tests with 0 failures and 0 errors in ... seconds.
    ...
    False

Finally, we can register the same doctestfile as unit doctest, such
making sure, that also unit doctests globals can be set, using the
``uglobs`` keyword parameter::

    >>> setupfile = os.path.join(cavepath, 'samplesetup_short9.py')
    >>> print open(setupfile).read()
    import os
    ...
    test_suite = z3c.testsetup.register_all_tests(
        'z3c.testsetup.tests.cave',
        extensions = ['.chk',],
        uregexp_list = [':Test-Layer:.*globs.*',],
        uglobs = {
            'basename' : os.path.basename
        }
        )

    >>> defaults = [
    ...     '--path', cavepath,
    ...     '--tests-pattern', '^samplesetup_short9$',
    ...     ]
    >>> sys.argv = 'test -u '.split()
    >>> testrunner.run(defaults)
    Running unit tests:
      Ran 2 tests with 0 failures and 0 errors in ... seconds.
    False







Extended setups
---------------

Let's have a look at the test setup module `samplesetup1` in the
`cave` package::

    >>> setupfile = os.path.join(cavepath, 'samplesetup1.py')
    >>> print open(setupfile).read()
    import unittest
    import z3c.testsetup
    from z3c.testsetup.tests import cave # The package that contains
                                         # the doctest files
    def test_suite():
        suite = unittest.TestSuite()
        suite.addTest( # Add all unittests from `cave`
            z3c.testsetup.UnitDocTestSetup(cave).getTestSuite())
        suite.addTest( # Add all functional tests from `cave`
            z3c.testsetup.FunctionalDocTestSetup(cave).getTestSuite())
        return suite


As we see, there is a unittest setup and a functional test setup
initialized. Both collect one kind of tests and feed their collection
in the same testsuite (where each kind of tests is setup differently,
of course). 

Now let's run a testrunner and see the result. The testrunner will be
configured such, that all files named 'samplesetup1.py' will be asked
to return a testsuite::

    >>> defaults = [
    ...     '--path', cavepath,
    ...     '--tests-pattern', '^samplesetup1$',
    ...     ]
    >>> sys.argv = 'test '.split()
    >>> from zope.testing import testrunner
    >>> testrunner.run(defaults)
    Running unit tests:
      Ran 1 tests with 0 failures and 0 errors in ... seconds.
    Running z3c.testsetup....doctesting.FunctionalLayer tests:
      Set up z3c.testsetup....doctesting.FunctionalLayer in ... seconds.
      Ran 2 tests with 0 failures and 0 errors in ... seconds.
    Tearing down left over layers:
      Tear down z3c.testsetup....doctesting.FunctionalLayer ... not supported
    Total: 3 tests, 0 failures, 0 errors in ... seconds.
    False

We ran one unittest and two functional tests.
