Add syntax highlighting to missing snippets in the documentation and other fixes

- Add explicit "code-block" for sessions without syntax highlight
- Moved Metafunc documentation to the class docstring and reused that in the
   docs;
This commit is contained in:
Bruno Oliveira 2015-07-09 21:50:38 -03:00
parent 0624a69964
commit 0ee3ee7333
16 changed files with 100 additions and 64 deletions

View File

@ -787,6 +787,27 @@ class FuncargnamesCompatAttr:
return self.fixturenames return self.fixturenames
class Metafunc(FuncargnamesCompatAttr): class Metafunc(FuncargnamesCompatAttr):
"""
Metafunc objects are passed to the ``pytest_generate_tests`` hook.
They help to inspect a test function and to generate tests according to
test configuration or values specified in the class or module where a
test function is defined.
:ivar fixturenames: set of fixture names required by the test function
:ivar function: underlying python test function
:ivar cls: class object where the test function is defined in or ``None``.
:ivar module: the module object where the test function is defined in.
:ivar config: access to the :class:`_pytest.config.Config` object for the
test session.
:ivar funcargnames:
.. deprecated:: 2.3
Use ``fixturenames`` instead.
"""
def __init__(self, function, fixtureinfo, config, cls=None, module=None): def __init__(self, function, fixtureinfo, config, cls=None, module=None):
self.config = config self.config = config
self.module = module self.module = module

View File

@ -5,6 +5,7 @@ Release announcements
.. toctree:: .. toctree::
:maxdepth: 2 :maxdepth: 2
release-2.7.2
release-2.7.1 release-2.7.1
release-2.7.0 release-2.7.0
release-2.6.3 release-2.6.3

View File

@ -87,7 +87,9 @@ Accessing captured output from a test function
The ``capsys`` and ``capfd`` fixtures allow to access stdout/stderr The ``capsys`` and ``capfd`` fixtures allow to access stdout/stderr
output created during test execution. Here is an example test function output created during test execution. Here is an example test function
that performs some output related checks:: that performs some output related checks:
.. code-block:: python
def test_myoutput(capsys): # or use "capfd" for fd-level def test_myoutput(capsys): # or use "capfd" for fd-level
print ("hello") print ("hello")

View File

@ -89,7 +89,9 @@ How to change command line options defaults
It can be tedious to type the same series of command line options It can be tedious to type the same series of command line options
every time you use ``pytest``. For example, if you always want to see every time you use ``pytest``. For example, if you always want to see
detailed info on skipped and xfailed tests, as well as have terser "dot" detailed info on skipped and xfailed tests, as well as have terser "dot"
progress output, you can write it into a configuration file:: progress output, you can write it into a configuration file:
.. code-block:: ini
# content of pytest.ini # content of pytest.ini
# (or tox.ini or setup.cfg) # (or tox.ini or setup.cfg)
@ -117,14 +119,16 @@ Builtin configuration file options
.. confval:: addopts .. confval:: addopts
Add the specified ``OPTS`` to the set of command line arguments as if they Add the specified ``OPTS`` to the set of command line arguments as if they
had been specified by the user. Example: if you have this ini file content:: had been specified by the user. Example: if you have this ini file content:
[pytest] .. code-block:: ini
addopts = --maxfail=2 -rf # exit after 2 failures, report fail info
[pytest]
addopts = --maxfail=2 -rf # exit after 2 failures, report fail info
issuing ``py.test test_hello.py`` actually means:: issuing ``py.test test_hello.py`` actually means::
py.test --maxfail=2 -rf test_hello.py py.test --maxfail=2 -rf test_hello.py
Default is to add no options. Default is to add no options.
@ -142,11 +146,13 @@ Builtin configuration file options
Default patterns are ``'.*', 'CVS', '_darcs', '{arch}', '*.egg'``. Default patterns are ``'.*', 'CVS', '_darcs', '{arch}', '*.egg'``.
Setting a ``norecursedirs`` replaces the default. Here is an example of Setting a ``norecursedirs`` replaces the default. Here is an example of
how to avoid certain directories:: how to avoid certain directories:
# content of setup.cfg .. code-block:: ini
[pytest]
norecursedirs = .svn _build tmp* # content of setup.cfg
[pytest]
norecursedirs = .svn _build tmp*
This would tell ``pytest`` to not look into typical subversion or This would tell ``pytest`` to not look into typical subversion or
sphinx-build directories or into any ``tmp`` prefixed directory. sphinx-build directories or into any ``tmp`` prefixed directory.
@ -160,11 +166,13 @@ Builtin configuration file options
One or more name prefixes or glob-style patterns determining which classes One or more name prefixes or glob-style patterns determining which classes
are considered for test collection. Here is an example of how to collect are considered for test collection. Here is an example of how to collect
tests from classes that end in ``Suite``:: tests from classes that end in ``Suite``:
# content of pytest.ini .. code-block:: ini
[pytest]
python_classes = *Suite # content of pytest.ini
[pytest]
python_classes = *Suite
Note that ``unittest.TestCase`` derived classes are always collected Note that ``unittest.TestCase`` derived classes are always collected
regardless of this option, as ``unittest``'s own collection framework is used regardless of this option, as ``unittest``'s own collection framework is used
@ -174,11 +182,13 @@ Builtin configuration file options
One or more name prefixes or glob-patterns determining which test functions One or more name prefixes or glob-patterns determining which test functions
and methods are considered tests. Here is an example of how and methods are considered tests. Here is an example of how
to collect test functions and methods that end in ``_test``:: to collect test functions and methods that end in ``_test``:
# content of pytest.ini .. code-block:: ini
[pytest]
python_functions = *_test # content of pytest.ini
[pytest]
python_functions = *_test
Note that this has no effect on methods that live on a ``unittest Note that this has no effect on methods that live on a ``unittest
.TestCase`` derived class, as ``unittest``'s own collection framework is used .TestCase`` derived class, as ``unittest``'s own collection framework is used

View File

@ -15,7 +15,9 @@ python test modules)::
py.test --doctest-modules py.test --doctest-modules
You can make these changes permanent in your project by You can make these changes permanent in your project by
putting them into a pytest.ini file like this:: putting them into a pytest.ini file like this:
.. code-block:: ini
# content of pytest.ini # content of pytest.ini
[pytest] [pytest]

View File

@ -232,7 +232,9 @@ traceback. As a result, the two test functions using ``smtp`` run as
quick as a single one because they reuse the same instance. quick as a single one because they reuse the same instance.
If you decide that you rather want to have a session-scoped ``smtp`` If you decide that you rather want to have a session-scoped ``smtp``
instance, you can simply declare it:: instance, you can simply declare it:
.. code-block:: python
@pytest.fixture(scope="session") @pytest.fixture(scope="session")
def smtp(...): def smtp(...):
@ -669,20 +671,25 @@ to verify our fixture is activated and the tests pass::
.. ..
2 passed in 0.12 seconds 2 passed in 0.12 seconds
You can specify multiple fixtures like this:: You can specify multiple fixtures like this:
.. code-block:: python
@pytest.mark.usefixtures("cleandir", "anotherfixture") @pytest.mark.usefixtures("cleandir", "anotherfixture")
and you may specify fixture usage at the test module level, using and you may specify fixture usage at the test module level, using
a generic feature of the mark mechanism:: a generic feature of the mark mechanism:
.. code-block:: python
pytestmark = pytest.mark.usefixtures("cleandir") pytestmark = pytest.mark.usefixtures("cleandir")
Lastly you can put fixtures required by all tests in your project Lastly you can put fixtures required by all tests in your project
into an ini-file:: into an ini-file:
.. code-block:: ini
# content of pytest.ini # content of pytest.ini
[pytest] [pytest]
usefixtures = cleandir usefixtures = cleandir

View File

@ -205,7 +205,7 @@ fixtures:
``request.cached_setup()`` calls and allowed using other funcargs via ``request.cached_setup()`` calls and allowed using other funcargs via
``request.getfuncargvalue()`` calls. These intricate APIs made it hard ``request.getfuncargvalue()`` calls. These intricate APIs made it hard
to do proper parametrization and implement resource caching. The to do proper parametrization and implement resource caching. The
new :py:func:`pytest.fixture`` decorator allows to declare the scope new :py:func:`pytest.fixture` decorator allows to declare the scope
and let pytest figure things out for you. and let pytest figure things out for you.
* if you used parametrization and funcarg factories which made use of * if you used parametrization and funcarg factories which made use of

View File

@ -44,7 +44,6 @@ If you want to prevent the "requests" library from performing http
requests in all your tests, you can do:: requests in all your tests, you can do::
# content of conftest.py # content of conftest.py
import pytest import pytest
@pytest.fixture(autouse=True) @pytest.fixture(autouse=True)
def no_requests(monkeypatch): def no_requests(monkeypatch):

View File

@ -30,7 +30,9 @@ pytest supports test parametrization in several well-integrated ways:
.. regendoc: wipe .. regendoc: wipe
.. versionadded:: 2.2, improved in 2.4 .. versionadded:: 2.2
.. versionchanged:: 2.4
Several improvements.
The builtin ``pytest.mark.parametrize`` decorator enables The builtin ``pytest.mark.parametrize`` decorator enables
parametrization of arguments for a test function. Here is a typical example parametrization of arguments for a test function. Here is a typical example
@ -199,25 +201,7 @@ The **metafunc** object
------------------------------------------- -------------------------------------------
.. currentmodule:: _pytest.python .. currentmodule:: _pytest.python
.. autoclass:: Metafunc
metafunc objects are passed to the ``pytest_generate_tests`` hook. .. automethod:: Metafunc.parametrize
They help to inspect a testfunction and to generate tests .. automethod:: Metafunc.addcall(funcargs=None,id=_notexists,param=_notexists)
according to test configuration or values specified
in the class or module where a test function is defined:
``metafunc.fixturenames``: set of required function arguments for given function
``metafunc.function``: underlying python test function
``metafunc.cls``: class object where the test function is defined in or None.
``metafunc.module``: the module object where the test function is defined in.
``metafunc.config``: access to command line opts and general config
``metafunc.funcargnames``: alias for ``fixturenames``, for pre-2.3 compatibility
.. automethod:: Metafunc.parametrize
.. automethod:: Metafunc.addcall(funcargs=None,id=_notexists,param=_notexists)

View File

@ -81,4 +81,5 @@ Some organisations using pytest
* `Open End, Gothenborg <http://www.openend.se>`_ * `Open End, Gothenborg <http://www.openend.se>`_
* `Laboratory of Bioinformatics, Warsaw <http://genesilico.pl/>`_ * `Laboratory of Bioinformatics, Warsaw <http://genesilico.pl/>`_
* `merlinux, Germany <http://merlinux.eu>`_ * `merlinux, Germany <http://merlinux.eu>`_
* `ESSS, Brazil <http://www.esss.com.br>`_
* many more ... (please be so kind to send a note via :ref:`contact`) * many more ... (please be so kind to send a note via :ref:`contact`)

View File

@ -23,8 +23,13 @@ self-contained test::
The ``recwarn`` function argument provides these methods: The ``recwarn`` function argument provides these methods:
* ``pop(category=None)``: return last warning matching the category. .. method:: pop(category=None)
* ``clear()``: clear list of warnings
Return last warning matching the category.
.. method:: clear()
Clear list of warnings
.. _ensuring_function_triggers: .. _ensuring_function_triggers:
@ -33,8 +38,7 @@ Ensuring a function triggers a deprecation warning
------------------------------------------------------- -------------------------------------------------------
You can also call a global helper for checking You can also call a global helper for checking
that a certain function call triggers a Deprecation that a certain function call triggers a ``DeprecationWarning``::
warning::
import pytest import pytest

View File

@ -11,7 +11,7 @@ For doing a release of pytest (status April 2015) this rough checklist is used:
3. write ``doc/en/announce/release-VERSION.txt`` 3. write ``doc/en/announce/release-VERSION.txt``
(usually copying from an earlier release version). (usually copying from an earlier release version).
4. regenerate doc examples with ``tox -e regen`` and check with ``hg diff`` 4. regenerate doc examples with ``tox -e regen`` and check with ``git diff``
if the differences show regressions. It's a bit of a manual process because if the differences show regressions. It's a bit of a manual process because
there a large part of the diff is about pytest headers or differences in there a large part of the diff is about pytest headers or differences in
speed ("tests took X.Y seconds"). (XXX automate doc/example diffing to ignore speed ("tests took X.Y seconds"). (XXX automate doc/example diffing to ignore
@ -40,9 +40,9 @@ For doing a release of pytest (status April 2015) this rough checklist is used:
# browse to pytest.org to see # browse to pytest.org to see
devpi push pytest-VERSION pypi:NAME devpi push pytest-VERSION pypi:NAME
hg ci -m "... finalized pytest-VERSION" git commit -a -m "... finalized pytest-VERSION"
hg tag VERSION git tag VERSION
hg push git push
9. send out release announcement to pytest-dev@python.org, 9. send out release announcement to pytest-dev@python.org,
testing-in-python@lists.idyll.org and python-announce-list@python.org . testing-in-python@lists.idyll.org and python-announce-list@python.org .

View File

@ -107,10 +107,11 @@ As with the class-decorator, the ``pytestmark`` special name tells
``pytest`` to apply it to each test function in the class. ``pytest`` to apply it to each test function in the class.
If you want to skip all test functions of a module, you must use If you want to skip all test functions of a module, you must use
the ``pytestmark`` name on the global level:: the ``pytestmark`` name on the global level:
.. code-block:: python
# test_module.py # test_module.py
pytestmark = pytest.mark.skipif(...) pytestmark = pytest.mark.skipif(...)
If multiple "skipif" decorators are applied to a test function, it If multiple "skipif" decorators are applied to a test function, it

View File

@ -1,5 +1,5 @@
pytest development status pytest development status
================================ ================================
https://drone.io/bitbucket.org/pytest-dev/pytest https://travis-ci.org/pytest-dev/pytest

View File

@ -93,10 +93,10 @@ interactive use, this allows one to drop into postmortem debugging with
any debug tool. One can also manually access the exception information, any debug tool. One can also manually access the exception information,
for example:: for example::
>> import sys >>> import sys
>> sys.last_traceback.tb_lineno >>> sys.last_traceback.tb_lineno
42 42
>> sys.last_value >>> sys.last_value
AssertionError('assert result == "ok"',) AssertionError('assert result == "ok"',)
Setting a breakpoint / aka ``set_trace()`` Setting a breakpoint / aka ``set_trace()``

View File

@ -239,7 +239,9 @@ When we implement a ``pytest_collection_modifyitems`` function in our plugin
pytest will during registration verify that you use argument pytest will during registration verify that you use argument
names which match the specification and bail out if not. names which match the specification and bail out if not.
Let's look at a possible implementation:: Let's look at a possible implementation:
.. code-block:: python
def pytest_collection_modifyitems(config, items): def pytest_collection_modifyitems(config, items):
# called after collectin is completed # called after collectin is completed
@ -315,7 +317,9 @@ For any given hook specification there may be more than one
implementation and we thus generally view ``hook`` execution as a implementation and we thus generally view ``hook`` execution as a
``1:N`` function call where ``N`` is the number of registered functions. ``1:N`` function call where ``N`` is the number of registered functions.
There are ways to influence if a hook implementation comes before or There are ways to influence if a hook implementation comes before or
after others, i.e. the position in the ``N``-sized list of functions:: after others, i.e. the position in the ``N``-sized list of functions:
.. code-block:: python
# Plugin 1 # Plugin 1
@pytest.hookimpl_spec(tryfirst=True) @pytest.hookimpl_spec(tryfirst=True)