replace implicit code tag with colon .replace("::\n\n.. code-block", ":\n\n.. code-block")

This commit is contained in:
boris 2019-08-06 16:20:06 -07:00
parent 23a0b532db
commit 78de9d4677
23 changed files with 95 additions and 95 deletions

View File

@ -162,7 +162,7 @@ For information about fixtures, see :ref:`fixtures`. To see a complete list of a
no tests ran in 0.12 seconds no tests ran in 0.12 seconds
You can also interactively ask for help, e.g. by typing on the Python interactive prompt something like:: You can also interactively ask for help, e.g. by typing on the Python interactive prompt something like:
.. code-block:: python .. code-block:: python

View File

@ -33,7 +33,7 @@ Other plugins may access the `config.cache`_ object to set/get
Rerunning only failures or failures first Rerunning only failures or failures first
----------------------------------------------- -----------------------------------------------
First, let's create 50 test invocation of which only 2 fail:: First, let's create 50 test invocation of which only 2 fail:
.. code-block:: python .. code-block:: python
@ -186,7 +186,7 @@ The new config.cache object
Plugins or conftest.py support code can get a cached value using the Plugins or conftest.py support code can get a cached value using the
pytest ``config`` object. Here is a basic example plugin which pytest ``config`` object. Here is a basic example plugin which
implements a :ref:`fixture` which re-uses previously created state implements a :ref:`fixture` which re-uses previously created state
across pytest invocations:: across pytest invocations:
.. code-block:: python .. code-block:: python

View File

@ -49,7 +49,7 @@ Using print statements for debugging
--------------------------------------------------- ---------------------------------------------------
One primary benefit of the default capturing of stdout/stderr output One primary benefit of the default capturing of stdout/stderr output
is that you can use print statements for debugging:: is that you can use print statements for debugging:
.. code-block:: python .. code-block:: python

View File

@ -455,7 +455,7 @@ Internal classes accessed through ``Node``
.. versionremoved:: 4.0 .. versionremoved:: 4.0
Access of ``Module``, ``Function``, ``Class``, ``Instance``, ``File`` and ``Item`` through ``Node`` instances now issue Access of ``Module``, ``Function``, ``Class``, ``Instance``, ``File`` and ``Item`` through ``Node`` instances now issue
this warning:: this warning:
.. code-block:: text .. code-block:: text

View File

@ -191,7 +191,7 @@ namespace in which your doctests run. It is intended to be used within
your own fixtures to provide the tests that use them with context. your own fixtures to provide the tests that use them with context.
``doctest_namespace`` is a standard ``dict`` object into which you ``doctest_namespace`` is a standard ``dict`` object into which you
place the objects you want to appear in the doctest namespace:: place the objects you want to appear in the doctest namespace:
.. code-block:: python .. code-block:: python
@ -203,7 +203,7 @@ place the objects you want to appear in the doctest namespace::
def add_np(doctest_namespace): def add_np(doctest_namespace):
doctest_namespace["np"] = numpy doctest_namespace["np"] = numpy
which can then be used in your doctests directly:: which can then be used in your doctests directly:
.. code-block:: python .. code-block:: python
@ -225,7 +225,7 @@ Skipping tests dynamically
.. versionadded:: 4.4 .. versionadded:: 4.4
You can use ``pytest.skip`` to dynamically skip doctests. For example:: You can use ``pytest.skip`` to dynamically skip doctests. For example:
.. code-block:: text .. code-block:: text

View File

@ -19,7 +19,7 @@ Generating parameters combinations, depending on command line
Let's say we want to execute a test with different computation Let's say we want to execute a test with different computation
parameters and the parameter range shall be determined by a command parameters and the parameter range shall be determined by a command
line argument. Let's first write a simple (do-nothing) computation test:: line argument. Let's first write a simple (do-nothing) computation test:
.. code-block:: python .. code-block:: python
@ -29,7 +29,7 @@ line argument. Let's first write a simple (do-nothing) computation test::
def test_compute(param1): def test_compute(param1):
assert param1 < 4 assert param1 < 4
Now we add a test configuration like this:: Now we add a test configuration like this:
.. code-block:: python .. code-block:: python
@ -89,7 +89,7 @@ Running pytest with ``--collect-only`` will show the generated IDs.
Numbers, strings, booleans and None will have their usual string representation Numbers, strings, booleans and None will have their usual string representation
used in the test ID. For other objects, pytest will make a string based on used in the test ID. For other objects, pytest will make a string based on
the argument name:: the argument name:
.. code-block:: python .. code-block:: python
@ -185,7 +185,7 @@ A quick port of "testscenarios"
Here is a quick port to run tests configured with `test scenarios`_, Here is a quick port to run tests configured with `test scenarios`_,
an add-on from Robert Collins for the standard unittest framework. We an add-on from Robert Collins for the standard unittest framework. We
only have to work a bit to construct the correct arguments for pytest's only have to work a bit to construct the correct arguments for pytest's
:py:func:`Metafunc.parametrize`:: :py:func:`Metafunc.parametrize`:
.. code-block:: python .. code-block:: python
@ -263,7 +263,7 @@ The parametrization of test functions happens at collection
time. It is a good idea to setup expensive resources like DB time. It is a good idea to setup expensive resources like DB
connections or subprocess only when the actual test is run. connections or subprocess only when the actual test is run.
Here is a simple example how you can achieve that, first Here is a simple example how you can achieve that, first
the actual test requiring a ``db`` object:: the actual test requiring a ``db`` object:
.. code-block:: python .. code-block:: python
@ -279,7 +279,7 @@ the actual test requiring a ``db`` object::
We can now add a test configuration that generates two invocations of We can now add a test configuration that generates two invocations of
the ``test_db_initialized`` function and also implements a factory that the ``test_db_initialized`` function and also implements a factory that
creates a database object for the actual test invocations:: creates a database object for the actual test invocations:
.. code-block:: python .. code-block:: python
@ -357,7 +357,7 @@ parameter on particular arguments. It can be done by passing list or tuple of
arguments' names to ``indirect``. In the example below there is a function ``test_indirect`` which uses arguments' names to ``indirect``. In the example below there is a function ``test_indirect`` which uses
two fixtures: ``x`` and ``y``. Here we give to indirect the list, which contains the name of the two fixtures: ``x`` and ``y``. Here we give to indirect the list, which contains the name of the
fixture ``x``. The indirect parameter will be applied to this argument only, and the value ``a`` fixture ``x``. The indirect parameter will be applied to this argument only, and the value ``a``
will be passed to respective fixture function:: will be passed to respective fixture function:
.. code-block:: python .. code-block:: python
@ -406,7 +406,7 @@ Parametrizing test methods through per-class configuration
Here is an example ``pytest_generate_tests`` function implementing a Here is an example ``pytest_generate_tests`` function implementing a
parametrization scheme similar to Michael Foord's `unittest parametrization scheme similar to Michael Foord's `unittest
parametrizer`_ but in a lot less code:: parametrizer`_ but in a lot less code:
.. code-block:: python .. code-block:: python
@ -488,7 +488,7 @@ If you want to compare the outcomes of several implementations of a given
API, you can write test functions that receive the already imported implementations API, you can write test functions that receive the already imported implementations
and get skipped in case the implementation is not importable/available. Let's and get skipped in case the implementation is not importable/available. Let's
say we have a "base" implementation and the other (possibly optimized ones) say we have a "base" implementation and the other (possibly optimized ones)
need to provide similar results:: need to provide similar results:
.. code-block:: python .. code-block:: python
@ -506,7 +506,7 @@ need to provide similar results::
def optmod(request): def optmod(request):
return pytest.importorskip(request.param) return pytest.importorskip(request.param)
And then a base implementation of a simple function:: And then a base implementation of a simple function:
.. code-block:: python .. code-block:: python
@ -514,7 +514,7 @@ And then a base implementation of a simple function::
def func1(): def func1():
return 1 return 1
And an optimized version:: And an optimized version:
.. code-block:: python .. code-block:: python
@ -522,7 +522,7 @@ And an optimized version::
def func1(): def func1():
return 1.0001 return 1.0001
And finally a little test module:: And finally a little test module:
.. code-block:: python .. code-block:: python
@ -631,7 +631,7 @@ Use :func:`pytest.raises` with the
in which some tests raise exceptions and others do not. in which some tests raise exceptions and others do not.
It is helpful to define a no-op context manager ``does_not_raise`` to serve It is helpful to define a no-op context manager ``does_not_raise`` to serve
as a complement to ``raises``. For example:: as a complement to ``raises``. For example:
.. code-block:: python .. code-block:: python
@ -662,19 +662,19 @@ In the example above, the first three test cases should run unexceptionally,
while the fourth should raise ``ZeroDivisionError``. while the fourth should raise ``ZeroDivisionError``.
If you're only supporting Python 3.7+, you can simply use ``nullcontext`` If you're only supporting Python 3.7+, you can simply use ``nullcontext``
to define ``does_not_raise``:: to define ``does_not_raise``:
.. code-block:: python .. code-block:: python
from contextlib import nullcontext as does_not_raise from contextlib import nullcontext as does_not_raise
Or, if you're supporting Python 3.3+ you can use:: Or, if you're supporting Python 3.3+ you can use:
.. code-block:: python .. code-block:: python
from contextlib import ExitStack as does_not_raise from contextlib import ExitStack as does_not_raise
Or, if desired, you can ``pip install contextlib2`` and use:: Or, if desired, you can ``pip install contextlib2`` and use:
.. code-block:: python .. code-block:: python

View File

@ -131,7 +131,7 @@ Here is an example:
This would make ``pytest`` look for tests in files that match the ``check_* This would make ``pytest`` look for tests in files that match the ``check_*
.py`` glob-pattern, ``Check`` prefixes in classes, and functions and methods .py`` glob-pattern, ``Check`` prefixes in classes, and functions and methods
that match ``*_check``. For example, if we have:: that match ``*_check``. For example, if we have:
.. code-block:: python .. code-block:: python
@ -241,7 +241,7 @@ You can easily instruct ``pytest`` to discover tests from every Python file:
However, many projects will have a ``setup.py`` which they don't want to be However, many projects will have a ``setup.py`` which they don't want to be
imported. Moreover, there may files only importable by a specific python imported. Moreover, there may files only importable by a specific python
version. For such cases you can dynamically define files to be ignored by version. For such cases you can dynamically define files to be ignored by
listing them in a ``conftest.py`` file:: listing them in a ``conftest.py`` file:
.. code-block:: python .. code-block:: python
@ -252,7 +252,7 @@ listing them in a ``conftest.py`` file::
if sys.version_info[0] > 2: if sys.version_info[0] > 2:
collect_ignore.append("pkg/module_py2.py") collect_ignore.append("pkg/module_py2.py")
and then if you have a module file like this:: and then if you have a module file like this:
.. code-block:: python .. code-block:: python
@ -263,7 +263,7 @@ and then if you have a module file like this::
except Exception, e: except Exception, e:
pass pass
and a ``setup.py`` dummy file like this:: and a ``setup.py`` dummy file like this:
.. code-block:: python .. code-block:: python
@ -304,7 +304,7 @@ patterns to ``collect_ignore_glob``.
The following example ``conftest.py`` ignores the file ``setup.py`` and in The following example ``conftest.py`` ignores the file ``setup.py`` and in
addition all files that end with ``*_py2.py`` when executed with a Python 3 addition all files that end with ``*_py2.py`` when executed with a Python 3
interpreter:: interpreter:
.. code-block:: python .. code-block:: python

View File

@ -5,7 +5,7 @@ A session-scoped fixture effectively has access to all
collected test items. Here is an example of a fixture collected test items. Here is an example of a fixture
function which walks all collected tests and looks function which walks all collected tests and looks
if their test class defines a ``callme`` method and if their test class defines a ``callme`` method and
calls it:: calls it:
.. code-block:: python .. code-block:: python
@ -27,7 +27,7 @@ calls it::
seen.add(cls) seen.add(cls)
test classes may now define a ``callme`` method which test classes may now define a ``callme`` method which
will be called ahead of running any tests:: will be called ahead of running any tests:
.. code-block:: python .. code-block:: python

View File

@ -15,7 +15,7 @@ Running an existing test suite with pytest
Say you want to contribute to an existing repository somewhere. Say you want to contribute to an existing repository somewhere.
After pulling the code into your development space using some After pulling the code into your development space using some
flavor of version control and (optionally) setting up a virtualenv flavor of version control and (optionally) setting up a virtualenv
you will want to run:: you will want to run:
.. code-block:: bash .. code-block:: bash

View File

@ -49,7 +49,7 @@ argument. For each argument name, a fixture function with that name provides
the fixture object. Fixture functions are registered by marking them with the fixture object. Fixture functions are registered by marking them with
:py:func:`@pytest.fixture <_pytest.python.fixture>`. Let's look at a simple :py:func:`@pytest.fixture <_pytest.python.fixture>`. Let's look at a simple
self-contained test module containing a fixture and a test function self-contained test module containing a fixture and a test function
using it:: using it:
.. code-block:: python .. code-block:: python
@ -185,7 +185,7 @@ Possible values for ``scope`` are: ``function``, ``class``, ``module``, ``packag
The next example puts the fixture function into a separate ``conftest.py`` file The next example puts the fixture function into a separate ``conftest.py`` file
so that tests from multiple test modules in the directory can so that tests from multiple test modules in the directory can
access the fixture function:: access the fixture function:
.. code-block:: python .. code-block:: python
@ -201,7 +201,7 @@ access the fixture function::
The name of the fixture again is ``smtp_connection`` and you can access its The name of the fixture again is ``smtp_connection`` and you can access its
result by listing the name ``smtp_connection`` as an input parameter in any result by listing the name ``smtp_connection`` as an input parameter in any
test or fixture function (in or below the directory where ``conftest.py`` is test or fixture function (in or below the directory where ``conftest.py`` is
located):: located):
.. code-block:: python .. code-block:: python
@ -489,7 +489,7 @@ Fixtures can introspect the requesting test context
Fixture functions can accept the :py:class:`request <FixtureRequest>` object Fixture functions can accept the :py:class:`request <FixtureRequest>` object
to introspect the "requesting" test function, class or module context. to introspect the "requesting" test function, class or module context.
Further extending the previous ``smtp_connection`` fixture example, let's Further extending the previous ``smtp_connection`` fixture example, let's
read an optional server URL from the test module which uses our fixture:: read an optional server URL from the test module which uses our fixture:
.. code-block:: python .. code-block:: python
@ -518,7 +518,7 @@ again, nothing much has changed:
2 failed in 0.12 seconds 2 failed in 0.12 seconds
Let's quickly create another test module that actually sets the Let's quickly create another test module that actually sets the
server URL in its module namespace:: server URL in its module namespace:
.. code-block:: python .. code-block:: python
@ -558,7 +558,7 @@ of a fixture is needed multiple times in a single test. Instead of returning
data directly, the fixture instead returns a function which generates the data. data directly, the fixture instead returns a function which generates the data.
This function can then be called multiple times in the test. This function can then be called multiple times in the test.
Factories can have parameters as needed:: Factories can have parameters as needed:
.. code-block:: python .. code-block:: python
@ -575,7 +575,7 @@ Factories can have parameters as needed::
customer_2 = make_customer_record("Mike") customer_2 = make_customer_record("Mike")
customer_3 = make_customer_record("Meredith") customer_3 = make_customer_record("Meredith")
If the data created by the factory requires managing, the fixture can take care of that:: If the data created by the factory requires managing, the fixture can take care of that:
.. code-block:: python .. code-block:: python
@ -616,7 +616,7 @@ configured in multiple ways.
Extending the previous example, we can flag the fixture to create two Extending the previous example, we can flag the fixture to create two
``smtp_connection`` fixture instances which will cause all tests using the fixture ``smtp_connection`` fixture instances which will cause all tests using the fixture
to run twice. The fixture function gets access to each parameter to run twice. The fixture function gets access to each parameter
through the special :py:class:`request <FixtureRequest>` object:: through the special :py:class:`request <FixtureRequest>` object:
.. code-block:: python .. code-block:: python
@ -710,7 +710,7 @@ Numbers, strings, booleans and None will have their usual string
representation used in the test ID. For other objects, pytest will representation used in the test ID. For other objects, pytest will
make a string based on the argument name. It is possible to customise make a string based on the argument name. It is possible to customise
the string used in a test ID for a certain fixture value by using the the string used in a test ID for a certain fixture value by using the
``ids`` keyword argument:: ``ids`` keyword argument:
.. code-block:: python .. code-block:: python
@ -781,7 +781,7 @@ Using marks with parametrized fixtures
:func:`pytest.param` can be used to apply marks in values sets of parametrized fixtures in the same way :func:`pytest.param` can be used to apply marks in values sets of parametrized fixtures in the same way
that they can be used with :ref:`@pytest.mark.parametrize <@pytest.mark.parametrize>`. that they can be used with :ref:`@pytest.mark.parametrize <@pytest.mark.parametrize>`.
Example:: Example:
.. code-block:: python .. code-block:: python
@ -824,7 +824,7 @@ can use other fixtures themselves. This contributes to a modular design
of your fixtures and allows re-use of framework-specific fixtures across of your fixtures and allows re-use of framework-specific fixtures across
many projects. As a simple example, we can extend the previous example many projects. As a simple example, we can extend the previous example
and instantiate an object ``app`` where we stick the already defined and instantiate an object ``app`` where we stick the already defined
``smtp_connection`` resource into it:: ``smtp_connection`` resource into it:
.. code-block:: python .. code-block:: python
@ -891,7 +891,7 @@ this eases testing of applications which create and use global state.
The following example uses two parametrized fixtures, one of which is The following example uses two parametrized fixtures, one of which is
scoped on a per-module basis, and all the functions perform ``print`` calls scoped on a per-module basis, and all the functions perform ``print`` calls
to show the setup/teardown flow:: to show the setup/teardown flow:
.. code-block:: python .. code-block:: python
@ -999,7 +999,7 @@ current working directory but otherwise do not care for the concrete
directory. Here is how you can use the standard `tempfile directory. Here is how you can use the standard `tempfile
<http://docs.python.org/library/tempfile.html>`_ and pytest fixtures to <http://docs.python.org/library/tempfile.html>`_ and pytest fixtures to
achieve it. We separate the creation of the fixture into a conftest.py achieve it. We separate the creation of the fixture into a conftest.py
file:: file:
.. code-block:: python .. code-block:: python
@ -1015,7 +1015,7 @@ file::
newpath = tempfile.mkdtemp() newpath = tempfile.mkdtemp()
os.chdir(newpath) os.chdir(newpath)
and declare its use in a test module via a ``usefixtures`` marker:: and declare its use in a test module via a ``usefixtures`` marker:
.. code-block:: python .. code-block:: python
@ -1102,7 +1102,7 @@ without declaring a function argument explicitly or a `usefixtures`_ decorator.
As a practical example, suppose we have a database fixture which has a As a practical example, suppose we have a database fixture which has a
begin/rollback/commit architecture and we want to automatically surround begin/rollback/commit architecture and we want to automatically surround
each test method by a transaction and a rollback. Here is a dummy each test method by a transaction and a rollback. Here is a dummy
self-contained implementation of this idea:: self-contained implementation of this idea:
.. code-block:: python .. code-block:: python
@ -1175,7 +1175,7 @@ Here is how autouse fixtures work in other scopes:
Note that the above ``transact`` fixture may very well be a fixture that Note that the above ``transact`` fixture may very well be a fixture that
you want to make available in your project without having it generally you want to make available in your project without having it generally
active. The canonical way to do that is to put the transact definition active. The canonical way to do that is to put the transact definition
into a conftest.py file **without** using ``autouse``:: into a conftest.py file **without** using ``autouse``:
.. code-block:: python .. code-block:: python
@ -1186,7 +1186,7 @@ into a conftest.py file **without** using ``autouse``::
yield yield
db.rollback() db.rollback()
and then e.g. have a TestClass using it by declaring the need:: and then e.g. have a TestClass using it by declaring the need:
.. code-block:: python .. code-block:: python

View File

@ -21,7 +21,7 @@ funcarg for a test function is required. If a factory wants to
re-use a resource across different scopes, it often used re-use a resource across different scopes, it often used
the ``request.cached_setup()`` helper to manage caching of the ``request.cached_setup()`` helper to manage caching of
resources. Here is a basic example how we could implement resources. Here is a basic example how we could implement
a per-session Database object:: a per-session Database object:
.. code-block:: python .. code-block:: python
@ -72,7 +72,7 @@ Direct scoping of fixture/funcarg factories
Instead of calling cached_setup() with a cache scope, you can use the Instead of calling cached_setup() with a cache scope, you can use the
:ref:`@pytest.fixture <pytest.fixture>` decorator and directly state :ref:`@pytest.fixture <pytest.fixture>` decorator and directly state
the scope:: the scope:
.. code-block:: python .. code-block:: python
@ -96,7 +96,7 @@ Previously, funcarg factories could not directly cause parametrization.
You needed to specify a ``@parametrize`` decorator on your test function You needed to specify a ``@parametrize`` decorator on your test function
or implement a ``pytest_generate_tests`` hook to perform or implement a ``pytest_generate_tests`` hook to perform
parametrization, i.e. calling a test multiple times with different value parametrization, i.e. calling a test multiple times with different value
sets. pytest-2.3 introduces a decorator for use on the factory itself:: sets. pytest-2.3 introduces a decorator for use on the factory itself:
.. code-block:: python .. code-block:: python
@ -115,7 +115,7 @@ allow to re-use already written factories because effectively
parametrized via parametrized via
:py:func:`~_pytest.python.Metafunc.parametrize(indirect=True)` calls. :py:func:`~_pytest.python.Metafunc.parametrize(indirect=True)` calls.
Of course it's perfectly fine to combine parametrization and scoping:: Of course it's perfectly fine to combine parametrization and scoping:
.. code-block:: python .. code-block:: python
@ -138,7 +138,7 @@ No ``pytest_funcarg__`` prefix when using @fixture decorator
When using the ``@fixture`` decorator the name of the function When using the ``@fixture`` decorator the name of the function
denotes the name under which the resource can be accessed as a function denotes the name under which the resource can be accessed as a function
argument:: argument:
.. code-block:: python .. code-block:: python
@ -149,7 +149,7 @@ argument::
The name under which the funcarg resource can be requested is ``db``. The name under which the funcarg resource can be requested is ``db``.
You can still use the "old" non-decorator way of specifying funcarg factories You can still use the "old" non-decorator way of specifying funcarg factories
aka:: aka:
.. code-block:: python .. code-block:: python

View File

@ -35,7 +35,7 @@ Install ``pytest``
Create your first test Create your first test
---------------------------------------------------------- ----------------------------------------------------------
Create a simple test function with just four lines of code:: Create a simple test function with just four lines of code:
.. code-block:: python .. code-block:: python
@ -86,7 +86,7 @@ Run multiple tests
Assert that a certain exception is raised Assert that a certain exception is raised
-------------------------------------------------------------- --------------------------------------------------------------
Use the :ref:`raises <assertraises>` helper to assert that some code raises an exception:: Use the :ref:`raises <assertraises>` helper to assert that some code raises an exception:
.. code-block:: python .. code-block:: python
@ -113,7 +113,7 @@ Execute the test function with “quiet” reporting mode:
Group multiple tests in a class Group multiple tests in a class
-------------------------------------------------------------- --------------------------------------------------------------
Once you develop multiple tests, you may want to group them into a class. pytest makes it easy to create a class containing more than one test:: Once you develop multiple tests, you may want to group them into a class. pytest makes it easy to create a class containing more than one test:
.. code-block:: python .. code-block:: python
@ -152,7 +152,7 @@ The first test passed and the second failed. You can easily see the intermediate
Request a unique temporary directory for functional tests Request a unique temporary directory for functional tests
-------------------------------------------------------------- --------------------------------------------------------------
``pytest`` provides `Builtin fixtures/function arguments <https://docs.pytest.org/en/latest/builtin.html>`_ to request arbitrary resources, like a unique temporary directory:: ``pytest`` provides `Builtin fixtures/function arguments <https://docs.pytest.org/en/latest/builtin.html>`_ to request arbitrary resources, like a unique temporary directory:
.. code-block:: python .. code-block:: python

View File

@ -12,7 +12,7 @@ pip_ for installing your application and any dependencies,
as well as the ``pytest`` package itself. as well as the ``pytest`` package itself.
This ensures your code and dependencies are isolated from your system Python installation. This ensures your code and dependencies are isolated from your system Python installation.
Next, place a ``setup.py`` file in the root of your package with the following minimum content:: Next, place a ``setup.py`` file in the root of your package with the following minimum content:
.. code-block:: python .. code-block:: python
@ -20,7 +20,7 @@ Next, place a ``setup.py`` file in the root of your package with the following m
setup(name="PACKAGENAME", packages=find_packages()) setup(name="PACKAGENAME", packages=find_packages())
Where ``PACKAGENAME`` is the name of your package. You can then install your package in "editable" mode by running from the same directory:: Where ``PACKAGENAME`` is the name of your package. You can then install your package in "editable" mode by running from the same directory:
.. code-block:: bash .. code-block:: bash
@ -64,7 +64,7 @@ Tests outside application code
Putting tests into an extra directory outside your actual application code Putting tests into an extra directory outside your actual application code
might be useful if you have many functional tests or for other reasons want might be useful if you have many functional tests or for other reasons want
to keep tests separate from actual application code (often a good idea):: to keep tests separate from actual application code (often a good idea):
.. code-block:: text .. code-block:: text
@ -98,7 +98,7 @@ be imported as ``test_app`` and ``test_view`` top-level modules by adding ``test
``sys.path``. ``sys.path``.
If you need to have test modules with the same name, you might add ``__init__.py`` files to your If you need to have test modules with the same name, you might add ``__init__.py`` files to your
``tests`` folder and subfolders, changing them to packages:: ``tests`` folder and subfolders, changing them to packages:
.. code-block:: text .. code-block:: text
@ -122,7 +122,7 @@ This is problematic if you are using a tool like `tox`_ to test your package in
because you want to test the *installed* version of your package, not the local code from the repository. because you want to test the *installed* version of your package, not the local code from the repository.
In this situation, it is **strongly** suggested to use a ``src`` layout where application root package resides in a In this situation, it is **strongly** suggested to use a ``src`` layout where application root package resides in a
sub-directory of your root:: sub-directory of your root:
.. code-block:: text .. code-block:: text
@ -150,7 +150,7 @@ Tests as part of application code
Inlining test directories into your application package Inlining test directories into your application package
is useful if you have direct relation between tests and application modules and is useful if you have direct relation between tests and application modules and
want to distribute them along with your application:: want to distribute them along with your application:
.. code-block:: text .. code-block:: text
@ -165,7 +165,7 @@ want to distribute them along with your application::
test_view.py test_view.py
... ...
In this scheme, it is easy to run your tests using the ``--pyargs`` option:: In this scheme, it is easy to run your tests using the ``--pyargs`` option:
.. code-block:: bash .. code-block:: bash

View File

@ -70,7 +70,7 @@ caplog fixture
^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^
Inside tests it is possible to change the log level for the captured log Inside tests it is possible to change the log level for the captured log
messages. This is supported by the ``caplog`` fixture:: messages. This is supported by the ``caplog`` fixture:
.. code-block:: python .. code-block:: python
@ -80,7 +80,7 @@ messages. This is supported by the ``caplog`` fixture::
By default the level is set on the root logger, By default the level is set on the root logger,
however as a convenience it is also possible to set the log level of any however as a convenience it is also possible to set the log level of any
logger:: logger:
.. code-block:: python .. code-block:: python
@ -91,7 +91,7 @@ logger::
The log levels set are restored automatically at the end of the test. The log levels set are restored automatically at the end of the test.
It is also possible to use a context manager to temporarily change the log It is also possible to use a context manager to temporarily change the log
level inside a ``with`` block:: level inside a ``with`` block:
.. code-block:: python .. code-block:: python
@ -100,7 +100,7 @@ level inside a ``with`` block::
pass pass
Again, by default the level of the root logger is affected but the level of any Again, by default the level of the root logger is affected but the level of any
logger can be changed instead with:: logger can be changed instead with:
.. code-block:: python .. code-block:: python
@ -110,7 +110,7 @@ logger can be changed instead with::
Lastly all the logs sent to the logger during the test run are made available on Lastly all the logs sent to the logger during the test run are made available on
the fixture in the form of both the ``logging.LogRecord`` instances and the final log text. the fixture in the form of both the ``logging.LogRecord`` instances and the final log text.
This is useful for when you want to assert on the contents of a message:: This is useful for when you want to assert on the contents of a message:
.. code-block:: python .. code-block:: python
@ -125,7 +125,7 @@ For all the available attributes of the log records see the
You can also resort to ``record_tuples`` if all you want to do is to ensure, You can also resort to ``record_tuples`` if all you want to do is to ensure,
that certain messages have been logged under a given logger name with a given that certain messages have been logged under a given logger name with a given
severity and message:: severity and message:
.. code-block:: python .. code-block:: python
@ -134,7 +134,7 @@ severity and message::
assert caplog.record_tuples == [("root", logging.INFO, "boo arg")] assert caplog.record_tuples == [("root", logging.INFO, "boo arg")]
You can call ``caplog.clear()`` to reset the captured log records in a test:: You can call ``caplog.clear()`` to reset the captured log records in a test:
.. code-block:: python .. code-block:: python

View File

@ -8,7 +8,7 @@ Installing and Using plugins
This section talks about installing and using third party plugins. This section talks about installing and using third party plugins.
For writing your own plugins, please refer to :ref:`writing-plugins`. For writing your own plugins, please refer to :ref:`writing-plugins`.
Installing a third party plugin can be easily done with ``pip``:: Installing a third party plugin can be easily done with ``pip``:
.. code-block:: bash .. code-block:: bash
@ -97,7 +97,7 @@ Finding out which plugins are active
------------------------------------ ------------------------------------
If you want to find out which plugins are active in your If you want to find out which plugins are active in your
environment you can type:: environment you can type:
.. code-block:: bash .. code-block:: bash
@ -112,7 +112,7 @@ and their names. It will also print local plugins aka
Deactivating / unregistering a plugin by name Deactivating / unregistering a plugin by name
--------------------------------------------- ---------------------------------------------
You can prevent plugins from loading or unregister them:: You can prevent plugins from loading or unregister them:
.. code-block:: bash .. code-block:: bash

View File

@ -22,7 +22,7 @@ Consider this file and directory layout::
|- test_foo.py |- test_foo.py
When executing:: When executing:
.. code-block:: bash .. code-block:: bash
@ -56,7 +56,7 @@ Consider this file and directory layout::
|- test_foo.py |- test_foo.py
When executing:: When executing:
.. code-block:: bash .. code-block:: bash

View File

@ -469,7 +469,7 @@ testdir
This fixture provides a :class:`Testdir` instance useful for black-box testing of test files, making it ideal to This fixture provides a :class:`Testdir` instance useful for black-box testing of test files, making it ideal to
test plugins. test plugins.
To use it, include in your top-most ``conftest.py`` file:: To use it, include in your top-most ``conftest.py`` file:
.. code-block:: python .. code-block:: python

View File

@ -180,7 +180,7 @@ Skipping on a missing import dependency
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
You can use the following helper at module level You can use the following helper at module level
or within a test or test setup function:: or within a test or test setup function:
.. code-block:: python .. code-block:: python
@ -188,7 +188,7 @@ or within a test or test setup function::
If ``docutils`` cannot be imported here, this will lead to a If ``docutils`` cannot be imported here, this will lead to a
skip outcome of the test. You can also skip based on the skip outcome of the test. You can also skip based on the
version number of a library:: version number of a library:
.. code-block:: python .. code-block:: python
@ -227,7 +227,7 @@ XFail: mark test functions as expected to fail
---------------------------------------------- ----------------------------------------------
You can use the ``xfail`` marker to indicate that you You can use the ``xfail`` marker to indicate that you
expect a test to fail:: expect a test to fail:
.. code-block:: python .. code-block:: python

View File

@ -90,7 +90,7 @@ provide a temporary directory unique to the test invocation,
created in the `base temporary directory`_. created in the `base temporary directory`_.
``tmpdir`` is a `py.path.local`_ object which offers ``os.path`` methods ``tmpdir`` is a `py.path.local`_ object which offers ``os.path`` methods
and more. Here is an example test usage:: and more. Here is an example test usage:
.. code-block:: python .. code-block:: python

View File

@ -10,7 +10,7 @@ It's meant for leveraging existing ``unittest``-based test suites
to use pytest as a test runner and also allow to incrementally adapt to use pytest as a test runner and also allow to incrementally adapt
the test suite to take full advantage of pytest's features. the test suite to take full advantage of pytest's features.
To run an existing ``unittest``-style test suite using ``pytest``, type:: To run an existing ``unittest``-style test suite using ``pytest``, type:
.. code-block:: bash .. code-block:: bash
@ -80,7 +80,7 @@ Running your unittest with ``pytest`` allows you to use its
tests. Assuming you have at least skimmed the pytest fixture features, tests. Assuming you have at least skimmed the pytest fixture features,
let's jump-start into an example that integrates a pytest ``db_class`` let's jump-start into an example that integrates a pytest ``db_class``
fixture, setting up a class-cached database object, and then reference fixture, setting up a class-cached database object, and then reference
it from a unittest-style test:: it from a unittest-style test:
.. code-block:: python .. code-block:: python
@ -109,7 +109,7 @@ as the ``cls`` attribute, denoting the class from which the fixture
is used. This architecture de-couples fixture writing from actual test is used. This architecture de-couples fixture writing from actual test
code and allows re-use of the fixture by a minimal reference, the fixture code and allows re-use of the fixture by a minimal reference, the fixture
name. So let's write an actual ``unittest.TestCase`` class using our name. So let's write an actual ``unittest.TestCase`` class using our
fixture definition:: fixture definition:
.. code-block:: python .. code-block:: python
@ -188,7 +188,7 @@ Let's look at an ``initdir`` fixture which makes all test methods of a
``TestCase`` class execute in a temporary directory with a ``TestCase`` class execute in a temporary directory with a
pre-initialized ``samplefile.ini``. Our ``initdir`` fixture itself uses pre-initialized ``samplefile.ini``. Our ``initdir`` fixture itself uses
the pytest builtin :ref:`tmpdir <tmpdir>` fixture to delegate the the pytest builtin :ref:`tmpdir <tmpdir>` fixture to delegate the
creation of a per-test temporary directory:: creation of a per-test temporary directory:
.. code-block:: python .. code-block:: python

View File

@ -754,7 +754,7 @@ Calling pytest from Python code
You can invoke ``pytest`` from Python code directly:: You can invoke ``pytest`` from Python code directly:
.. code-block:: python .. code-block:: python
@ -762,13 +762,13 @@ You can invoke ``pytest`` from Python code directly::
this acts as if you would call "pytest" from the command line. this acts as if you would call "pytest" from the command line.
It will not raise ``SystemExit`` but return the exitcode instead. It will not raise ``SystemExit`` but return the exitcode instead.
You can pass in options and arguments:: You can pass in options and arguments:
.. code-block:: python .. code-block:: python
pytest.main(["-x", "mytestdir"]) pytest.main(["-x", "mytestdir"])
You can specify additional plugins to ``pytest.main``:: You can specify additional plugins to ``pytest.main``:
.. code-block:: python .. code-block:: python

View File

@ -278,7 +278,7 @@ argument ``match`` to assert that the exception matches a text or regex::
... ...
Failed: DID NOT WARN. No warnings of type ...UserWarning... was emitted... Failed: DID NOT WARN. No warnings of type ...UserWarning... was emitted...
You can also call ``pytest.warns`` on a function or code string:: You can also call ``pytest.warns`` on a function or code string:
.. code-block:: python .. code-block:: python

View File

@ -27,7 +27,7 @@ Module level setup/teardown
If you have multiple test functions and test classes in a single If you have multiple test functions and test classes in a single
module you can optionally implement the following fixture methods module you can optionally implement the following fixture methods
which will usually be called once for all the functions:: which will usually be called once for all the functions:
.. code-block:: python .. code-block:: python
@ -46,7 +46,7 @@ Class level setup/teardown
---------------------------------- ----------------------------------
Similarly, the following methods are called at class level before Similarly, the following methods are called at class level before
and after all test methods of the class are called:: and after all test methods of the class are called:
.. code-block:: python .. code-block:: python
@ -66,7 +66,7 @@ and after all test methods of the class are called::
Method and function level setup/teardown Method and function level setup/teardown
----------------------------------------------- -----------------------------------------------
Similarly, the following methods are called around each method invocation:: Similarly, the following methods are called around each method invocation:
.. code-block:: python .. code-block:: python
@ -84,7 +84,7 @@ Similarly, the following methods are called around each method invocation::
As of pytest-3.0, the ``method`` parameter is optional. As of pytest-3.0, the ``method`` parameter is optional.
If you would rather define test functions directly at module level If you would rather define test functions directly at module level
you can also use the following functions to implement fixtures:: you can also use the following functions to implement fixtures:
.. code-block:: python .. code-block:: python