From f43b54aaeb533371e53d45683c919db588f21747 Mon Sep 17 00:00:00 2001 From: Bruno Oliveira Date: Mon, 5 Aug 2019 15:05:28 -0300 Subject: [PATCH 01/11] Add CHANGELOG for 4.6.5 (#5696) --- CHANGELOG.rst | 21 +++++++++++++++++++++ doc/en/announce/index.rst | 1 + doc/en/announce/release-4.6.5.rst | 21 +++++++++++++++++++++ 3 files changed, 43 insertions(+) create mode 100644 doc/en/announce/release-4.6.5.rst diff --git a/CHANGELOG.rst b/CHANGELOG.rst index 811f7475d..390fe84ca 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -243,6 +243,27 @@ Improved Documentation - `#5416 `_: Fix PytestUnknownMarkWarning in run/skip example. +pytest 4.6.5 (2019-08-05) +========================= + +Bug Fixes +--------- + +- `#4344 `_: Fix RuntimeError/StopIteration when trying to collect package with "__init__.py" only. + + +- `#5478 `_: Fix encode error when using unicode strings in exceptions with ``pytest.raises``. + + +- `#5524 `_: Fix issue where ``tmp_path`` and ``tmpdir`` would not remove directories containing files marked as read-only, + which could lead to pytest crashing when executed a second time with the ``--basetemp`` option. + + +- `#5547 `_: ``--step-wise`` now handles ``xfail(strict=True)`` markers properly. + + +- `#5650 `_: Improved output when parsing an ini configuration file fails. + pytest 4.6.4 (2019-06-28) ========================= diff --git a/doc/en/announce/index.rst b/doc/en/announce/index.rst index 84cbdd9d3..d372c92fa 100644 --- a/doc/en/announce/index.rst +++ b/doc/en/announce/index.rst @@ -8,6 +8,7 @@ Release announcements release-5.0.1 release-5.0.0 + release-4.6.5 release-4.6.4 release-4.6.3 release-4.6.2 diff --git a/doc/en/announce/release-4.6.5.rst b/doc/en/announce/release-4.6.5.rst new file mode 100644 index 000000000..6998d4e4c --- /dev/null +++ b/doc/en/announce/release-4.6.5.rst @@ -0,0 +1,21 @@ +pytest-4.6.5 +======================================= + +pytest 4.6.5 has just been released to PyPI. + +This is a bug-fix release, being a drop-in replacement. To upgrade:: + + pip install --upgrade pytest + +The full changelog is available at https://docs.pytest.org/en/latest/changelog.html. + +Thanks to all who contributed to this release, among them: + +* Anthony Sottile +* Bruno Oliveira +* Daniel Hahler +* Thomas Grainger + + +Happy testing, +The pytest Development Team From ef0915e1db3561b5cde7a2e6c60ef692bad1a2a1 Mon Sep 17 00:00:00 2001 From: Thomas Grainger Date: Tue, 6 Aug 2019 15:27:36 +0100 Subject: [PATCH 02/11] fix grammar in test_collect_functools_partial docstr --- testing/python/collect.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/testing/python/collect.py b/testing/python/collect.py index c2b09aeb8..61fc58579 100644 --- a/testing/python/collect.py +++ b/testing/python/collect.py @@ -1146,7 +1146,7 @@ def test_unorderable_types(testdir): def test_collect_functools_partial(testdir): """ Test that collection of functools.partial object works, and arguments - to the wrapped functions are dealt correctly (see #811). + to the wrapped functions are dealt with correctly (see #811). """ testdir.makepyfile( """ From cf7761f91f7b194dd89fae13c356d2d4a4d90d0a Mon Sep 17 00:00:00 2001 From: boris Date: Tue, 6 Aug 2019 12:40:27 -0700 Subject: [PATCH 03/11] ran pyupgrade-docs --- doc/en/assert.rst | 4 ++-- doc/en/example/attic.rst | 4 ++-- doc/en/example/markers.rst | 12 ++++++------ doc/en/example/simple.rst | 8 ++++---- doc/en/monkeypatch.rst | 6 +++--- doc/en/skipping.rst | 2 +- doc/en/usage.rst | 2 +- doc/en/writing_plugins.rst | 2 +- 8 files changed, 20 insertions(+), 20 deletions(-) diff --git a/doc/en/assert.rst b/doc/en/assert.rst index 465b8d86c..41afc1abf 100644 --- a/doc/en/assert.rst +++ b/doc/en/assert.rst @@ -238,14 +238,14 @@ file which provides an alternative explanation for ``Foo`` objects: def pytest_assertrepr_compare(op, left, right): if isinstance(left, Foo) and isinstance(right, Foo) and op == "==": - return ["Comparing Foo instances:", " vals: %s != %s" % (left.val, right.val)] + return ["Comparing Foo instances:", " vals: {} != {}".format(left.val, right.val)] now, given this test module: .. code-block:: python # content of test_foocompare.py - class Foo(object): + class Foo: def __init__(self, val): self.val = val diff --git a/doc/en/example/attic.rst b/doc/en/example/attic.rst index 9bf3703ce..2ea870062 100644 --- a/doc/en/example/attic.rst +++ b/doc/en/example/attic.rst @@ -18,7 +18,7 @@ example: specifying and selecting acceptance tests return AcceptFixture(request) - class AcceptFixture(object): + class AcceptFixture: def __init__(self, request): if not request.config.getoption("acceptance"): pytest.skip("specify -A to run acceptance tests") @@ -65,7 +65,7 @@ extend the `accept example`_ by putting this in our test module: return arg - class TestSpecialAcceptance(object): + class TestSpecialAcceptance: def test_sometest(self, accept): assert accept.tmpdir.join("special").check() diff --git a/doc/en/example/markers.rst b/doc/en/example/markers.rst index 218ef2707..a1fe65874 100644 --- a/doc/en/example/markers.rst +++ b/doc/en/example/markers.rst @@ -33,7 +33,7 @@ You can "mark" a test function with custom metadata like this: pass - class TestClass(object): + class TestClass: def test_method(self): pass @@ -278,7 +278,7 @@ its test methods: @pytest.mark.webtest - class TestClass(object): + class TestClass: def test_startup(self): pass @@ -295,7 +295,7 @@ Due to legacy reasons, it is possible to set the ``pytestmark`` attribute on a T import pytest - class TestClass(object): + class TestClass: pytestmark = pytest.mark.webtest or if you need to use multiple markers you can use a list: @@ -305,7 +305,7 @@ or if you need to use multiple markers you can use a list: import pytest - class TestClass(object): + class TestClass: pytestmark = [pytest.mark.webtest, pytest.mark.slowtest] You can also set a module level marker:: @@ -523,7 +523,7 @@ code you can read over all such settings. Example: @pytest.mark.glob("class", x=2) - class TestClass(object): + class TestClass: @pytest.mark.glob("function", x=3) def test_something(self): pass @@ -539,7 +539,7 @@ test function. From a conftest file we can read it like this: def pytest_runtest_setup(item): for mark in item.iter_markers(name="glob"): - print("glob args=%s kwargs=%s" % (mark.args, mark.kwargs)) + print("glob args={} kwargs={}".format(mark.args, mark.kwargs)) sys.stdout.flush() Let's run this without capturing output and see what we get: diff --git a/doc/en/example/simple.rst b/doc/en/example/simple.rst index 87b68245b..dbfba0fa0 100644 --- a/doc/en/example/simple.rst +++ b/doc/en/example/simple.rst @@ -238,7 +238,7 @@ Example: def checkconfig(x): __tracebackhide__ = True if not hasattr(x, "config"): - pytest.fail("not configured: %s" % (x,)) + pytest.fail("not configured: {}".format(x)) def test_something(): @@ -280,7 +280,7 @@ this to make sure unexpected exception types aren't hidden: def checkconfig(x): __tracebackhide__ = operator.methodcaller("errisinstance", ConfigException) if not hasattr(x, "config"): - raise ConfigException("not configured: %s" % (x,)) + raise ConfigException("not configured: {}".format(x)) def test_something(): @@ -491,7 +491,7 @@ tests in a class. Here is a test module example: @pytest.mark.incremental - class TestUserHandling(object): + class TestUserHandling: def test_login(self): pass @@ -556,7 +556,7 @@ Here is an example for making a ``db`` fixture available in a directory: import pytest - class DB(object): + class DB: pass diff --git a/doc/en/monkeypatch.rst b/doc/en/monkeypatch.rst index fd277d234..a38f07e79 100644 --- a/doc/en/monkeypatch.rst +++ b/doc/en/monkeypatch.rst @@ -272,7 +272,7 @@ to do this using the ``setenv`` and ``delenv`` method. Our example code to test: username = os.getenv("USER") if username is None: - raise EnvironmentError("USER environment is not set.") + raise OSError("USER environment is not set.") return username.lower() @@ -296,7 +296,7 @@ both paths can be safely tested without impacting the running environment: """Remove the USER env var and assert EnvironmentError is raised.""" monkeypatch.delenv("USER", raising=False) - with pytest.raises(EnvironmentError): + with pytest.raises(OSError): _ = get_os_user_lower() This behavior can be moved into ``fixture`` structures and shared across tests: @@ -323,7 +323,7 @@ This behavior can be moved into ``fixture`` structures and shared across tests: def test_raise_exception(mock_env_missing): - with pytest.raises(EnvironmentError): + with pytest.raises(OSError): _ = get_os_user_lower() diff --git a/doc/en/skipping.rst b/doc/en/skipping.rst index 0f57284b3..d1b308ac0 100644 --- a/doc/en/skipping.rst +++ b/doc/en/skipping.rst @@ -145,7 +145,7 @@ You can use the ``skipif`` marker (as any other marker) on classes: .. code-block:: python @pytest.mark.skipif(sys.platform == "win32", reason="does not run on windows") - class TestPosixCalls(object): + class TestPosixCalls: def test_function(self): "will not be setup or run under 'win32' platform" diff --git a/doc/en/usage.rst b/doc/en/usage.rst index 84edb5705..75f5aacfd 100644 --- a/doc/en/usage.rst +++ b/doc/en/usage.rst @@ -652,7 +652,7 @@ to all tests. record_testsuite_property("STORAGE_TYPE", "CEPH") - class TestMe(object): + class TestMe: def test_foo(self): assert True diff --git a/doc/en/writing_plugins.rst b/doc/en/writing_plugins.rst index 67a8fcecf..7975f5826 100644 --- a/doc/en/writing_plugins.rst +++ b/doc/en/writing_plugins.rst @@ -693,7 +693,7 @@ declaring the hook functions directly in your plugin module, for example: # contents of myplugin.py - class DeferPlugin(object): + class DeferPlugin: """Simple plugin to defer pytest-xdist hook functions.""" def pytest_testnodedown(self, node, error): From 7f90e74e0268721045413ae6e0944685cbcf59da Mon Sep 17 00:00:00 2001 From: boris Date: Tue, 6 Aug 2019 13:25:54 -0700 Subject: [PATCH 04/11] label code blocks --- doc/en/builtin.rst | 2 ++ doc/en/cache.rst | 4 ++++ doc/en/capture.rst | 2 ++ doc/en/deprecations.rst | 2 ++ doc/en/doctest.rst | 6 +++++ doc/en/example/parametrize.rst | 32 +++++++++++++++++++++++++++ doc/en/example/pythoncollection.rst | 10 +++++++++ doc/en/example/special.rst | 4 ++++ doc/en/existingtestsuite.rst | 2 ++ doc/en/fixture.rst | 34 +++++++++++++++++++++++++++++ doc/en/funcarg_compare.rst | 12 ++++++++++ doc/en/getting-started.rst | 8 +++++++ doc/en/goodpractices.rst | 14 ++++++++++++ doc/en/logging.rst | 14 ++++++++++++ doc/en/plugins.rst | 6 +++++ doc/en/pythonpath.rst | 4 ++++ doc/en/reference.rst | 4 ++++ doc/en/skipping.rst | 6 +++++ doc/en/tmpdir.rst | 2 ++ doc/en/unittest.rst | 8 +++++++ doc/en/usage.rst | 6 +++++ doc/en/warnings.rst | 5 ++++- doc/en/xunit_setup.rst | 8 +++++++ 23 files changed, 194 insertions(+), 1 deletion(-) diff --git a/doc/en/builtin.rst b/doc/en/builtin.rst index a4c20695c..4f93b877e 100644 --- a/doc/en/builtin.rst +++ b/doc/en/builtin.rst @@ -164,5 +164,7 @@ For information about fixtures, see :ref:`fixtures`. To see a complete list of a You can also interactively ask for help, e.g. by typing on the Python interactive prompt something like:: +.. code-block:: python + import pytest help(pytest) diff --git a/doc/en/cache.rst b/doc/en/cache.rst index af1d403b5..1323c8b58 100644 --- a/doc/en/cache.rst +++ b/doc/en/cache.rst @@ -35,6 +35,8 @@ Rerunning only failures or failures first First, let's create 50 test invocation of which only 2 fail:: +.. code-block:: python + # content of test_50.py import pytest @@ -185,6 +187,8 @@ pytest ``config`` object. Here is a basic example plugin which implements a :ref:`fixture` which re-uses previously created state across pytest invocations:: +.. code-block:: python + # content of test_caching.py import pytest import time diff --git a/doc/en/capture.rst b/doc/en/capture.rst index 338996ce8..5e821dfcb 100644 --- a/doc/en/capture.rst +++ b/doc/en/capture.rst @@ -51,6 +51,8 @@ Using print statements for debugging One primary benefit of the default capturing of stdout/stderr output is that you can use print statements for debugging:: +.. code-block:: python + # content of test_module.py def setup_function(function): diff --git a/doc/en/deprecations.rst b/doc/en/deprecations.rst index e2399dd41..d000dd6a1 100644 --- a/doc/en/deprecations.rst +++ b/doc/en/deprecations.rst @@ -457,6 +457,8 @@ Internal classes accessed through ``Node`` Access of ``Module``, ``Function``, ``Class``, ``Instance``, ``File`` and ``Item`` through ``Node`` instances now issue this warning:: +.. code-block:: text + usage of Function.Module is deprecated, please use pytest.Module instead Users should just ``import pytest`` and access those objects using the ``pytest`` module. diff --git a/doc/en/doctest.rst b/doc/en/doctest.rst index 3c40036ef..e6388c66b 100644 --- a/doc/en/doctest.rst +++ b/doc/en/doctest.rst @@ -193,6 +193,8 @@ your own fixtures to provide the tests that use them with context. ``doctest_namespace`` is a standard ``dict`` object into which you place the objects you want to appear in the doctest namespace:: +.. code-block:: python + # content of conftest.py import numpy @pytest.fixture(autouse=True) @@ -201,6 +203,8 @@ place the objects you want to appear in the doctest namespace:: which can then be used in your doctests directly:: +.. code-block:: python + # content of numpy.py def arange(): """ @@ -221,6 +225,8 @@ Skipping tests dynamically You can use ``pytest.skip`` to dynamically skip doctests. For example:: +.. code-block:: text + >>> import sys, pytest >>> if sys.platform.startswith('win'): ... pytest.skip('this doctest does not work on Windows') diff --git a/doc/en/example/parametrize.rst b/doc/en/example/parametrize.rst index 3dff2c559..ac9f81a38 100644 --- a/doc/en/example/parametrize.rst +++ b/doc/en/example/parametrize.rst @@ -21,6 +21,8 @@ Let's say we want to execute a test with different computation parameters and the parameter range shall be determined by a command line argument. Let's first write a simple (do-nothing) computation test:: +.. code-block:: python + # content of test_compute.py def test_compute(param1): @@ -28,6 +30,8 @@ line argument. Let's first write a simple (do-nothing) computation test:: Now we add a test configuration like this:: +.. code-block:: python + # content of conftest.py def pytest_addoption(parser): @@ -85,6 +89,8 @@ 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 the argument name:: +.. code-block:: python + # content of test_time.py import pytest @@ -173,6 +179,8 @@ 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 :py:func:`Metafunc.parametrize`:: +.. code-block:: python + # content of test_scenarios.py def pytest_generate_tests(metafunc): @@ -246,6 +254,8 @@ connections or subprocess only when the actual test is run. Here is a simple example how you can achieve that, first the actual test requiring a ``db`` object:: +.. code-block:: python + # content of test_backends.py import pytest @@ -258,6 +268,8 @@ We can now add a test configuration that generates two invocations of the ``test_db_initialized`` function and also implements a factory that creates a database object for the actual test invocations:: +.. code-block:: python + # content of conftest.py import pytest @@ -329,6 +341,8 @@ two fixtures: ``x`` and ``y``. Here we give to indirect the list, which contains fixture ``x``. The indirect parameter will be applied to this argument only, and the value ``a`` will be passed to respective fixture function:: +.. code-block:: python + # content of test_indirect_list.py import pytest @@ -372,6 +386,8 @@ Here is an example ``pytest_generate_tests`` function implementing a parametrization scheme similar to Michael Foord's `unittest parametrizer`_ but in a lot less code:: +.. code-block:: python + # content of ./test_parametrize.py import pytest @@ -449,6 +465,8 @@ 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) need to provide similar results:: +.. code-block:: python + # content of conftest.py import pytest @@ -463,18 +481,24 @@ need to provide similar results:: And then a base implementation of a simple function:: +.. code-block:: python + # content of base.py def func1(): return 1 And an optimized version:: +.. code-block:: python + # content of opt1.py def func1(): return 1.0001 And finally a little test module:: +.. code-block:: python + # content of test_module.py def test_func1(basemod, optmod): @@ -581,6 +605,8 @@ 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 as a complement to ``raises``. For example:: +.. code-block:: python + from contextlib import contextmanager import pytest @@ -606,12 +632,18 @@ while the fourth should raise ``ZeroDivisionError``. If you're only supporting Python 3.7+, you can simply use ``nullcontext`` to define ``does_not_raise``:: +.. code-block:: python + from contextlib import nullcontext as does_not_raise Or, if you're supporting Python 3.3+ you can use:: +.. code-block:: python + from contextlib import ExitStack as does_not_raise Or, if desired, you can ``pip install contextlib2`` and use:: +.. code-block:: python + from contextlib2 import ExitStack as does_not_raise diff --git a/doc/en/example/pythoncollection.rst b/doc/en/example/pythoncollection.rst index 6ca5a1eeb..86b7fe566 100644 --- a/doc/en/example/pythoncollection.rst +++ b/doc/en/example/pythoncollection.rst @@ -133,6 +133,8 @@ This would make ``pytest`` look for tests in files that match the ``check_* .py`` glob-pattern, ``Check`` prefixes in classes, and functions and methods that match ``*_check``. For example, if we have:: +.. code-block:: python + # content of check_myapp.py class CheckMyApp(object): def simple_check(self): @@ -240,6 +242,8 @@ imported. Moreover, there may files only importable by a specific python version. For such cases you can dynamically define files to be ignored by listing them in a ``conftest.py`` file:: +.. code-block:: python + # content of conftest.py import sys @@ -249,6 +253,8 @@ listing them in a ``conftest.py`` file:: and then if you have a module file like this:: +.. code-block:: python + # content of pkg/module_py2.py def test_only_on_python2(): try: @@ -258,6 +264,8 @@ and then if you have a module file like this:: and a ``setup.py`` dummy file like this:: +.. code-block:: python + # content of setup.py 0/0 # will raise exception if imported @@ -297,6 +305,8 @@ 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 interpreter:: +.. code-block:: python + # content of conftest.py import sys diff --git a/doc/en/example/special.rst b/doc/en/example/special.rst index 800cb8e90..c8fc96786 100644 --- a/doc/en/example/special.rst +++ b/doc/en/example/special.rst @@ -7,6 +7,8 @@ function which walks all collected tests and looks if their test class defines a ``callme`` method and calls it:: +.. code-block:: python + # content of conftest.py import pytest @@ -26,6 +28,8 @@ calls it:: test classes may now define a ``callme`` method which will be called ahead of running any tests:: +.. code-block:: python + # content of test_module.py class TestHello(object): diff --git a/doc/en/existingtestsuite.rst b/doc/en/existingtestsuite.rst index d304b30c9..956c970c2 100644 --- a/doc/en/existingtestsuite.rst +++ b/doc/en/existingtestsuite.rst @@ -17,6 +17,8 @@ After pulling the code into your development space using some flavor of version control and (optionally) setting up a virtualenv you will want to run:: +.. code-block:: bash + cd pip install -e . # Environment dependent alternatives include # 'python setup.py develop' and 'conda develop' diff --git a/doc/en/fixture.rst b/doc/en/fixture.rst index 40493e66f..9ba2552ba 100644 --- a/doc/en/fixture.rst +++ b/doc/en/fixture.rst @@ -51,6 +51,8 @@ the fixture object. Fixture functions are registered by marking them with self-contained test module containing a fixture and a test function using it:: +.. code-block:: python + # content of ./test_smtpsimple.py import pytest @@ -182,6 +184,8 @@ The next example puts the fixture function into a separate ``conftest.py`` file so that tests from multiple test modules in the directory can access the fixture function:: +.. code-block:: python + # content of conftest.py import pytest import smtplib @@ -195,6 +199,8 @@ 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 located):: +.. code-block:: python + # content of test_module.py def test_ehlo(smtp_connection): @@ -479,6 +485,8 @@ to introspect the "requesting" test function, class or module context. Further extending the previous ``smtp_connection`` fixture example, let's read an optional server URL from the test module which uses our fixture:: +.. code-block:: python + # content of conftest.py import pytest import smtplib @@ -505,6 +513,8 @@ again, nothing much has changed: Let's quickly create another test module that actually sets the server URL in its module namespace:: +.. code-block:: python + # content of test_anothersmtp.py smtpserver = "mail.python.org" # will be read by smtp fixture @@ -542,6 +552,8 @@ This function can then be called multiple times in the test. Factories can have parameters as needed:: +.. code-block:: python + @pytest.fixture def make_customer_record(): @@ -561,6 +573,8 @@ Factories can have parameters as needed:: If the data created by the factory requires managing, the fixture can take care of that:: +.. code-block:: python + @pytest.fixture def make_customer_record(): @@ -600,6 +614,8 @@ Extending the previous example, we can flag the fixture to create two to run twice. The fixture function gets access to each parameter through the special :py:class:`request ` object:: +.. code-block:: python + # content of conftest.py import pytest import smtplib @@ -692,6 +708,8 @@ 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 ``ids`` keyword argument:: +.. code-block:: python + # content of test_ids.py import pytest @@ -756,6 +774,8 @@ that they can be used with :ref:`@pytest.mark.parametrize <@pytest.mark.parametr Example:: +.. code-block:: python + # content of test_fixture_marks.py import pytest @pytest.fixture(params=[0, 1, pytest.param(2, marks=pytest.mark.skip)]) @@ -794,6 +814,8 @@ many projects. As a simple example, we can extend the previous example and instantiate an object ``app`` where we stick the already defined ``smtp_connection`` resource into it:: +.. code-block:: python + # content of test_appsetup.py import pytest @@ -856,6 +878,8 @@ The following example uses two parametrized fixtures, one of which is scoped on a per-module basis, and all the functions perform ``print`` calls to show the setup/teardown flow:: +.. code-block:: python + # content of test_module.py import pytest @@ -955,6 +979,8 @@ directory. Here is how you can use the standard `tempfile achieve it. We separate the creation of the fixture into a conftest.py file:: +.. code-block:: python + # content of conftest.py import pytest @@ -968,6 +994,8 @@ file:: and declare its use in a test module via a ``usefixtures`` marker:: +.. code-block:: python + # content of test_setenv.py import os import pytest @@ -1052,6 +1080,8 @@ begin/rollback/commit architecture and we want to automatically surround each test method by a transaction and a rollback. Here is a dummy self-contained implementation of this idea:: +.. code-block:: python + # content of test_db_transact.py import pytest @@ -1118,6 +1148,8 @@ 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 into a conftest.py file **without** using ``autouse``:: +.. code-block:: python + # content of conftest.py @pytest.fixture def transact(request, db): @@ -1127,6 +1159,8 @@ into a conftest.py file **without** using ``autouse``:: and then e.g. have a TestClass using it by declaring the need:: +.. code-block:: python + @pytest.mark.usefixtures("transact") class TestClass(object): def test_method1(self): diff --git a/doc/en/funcarg_compare.rst b/doc/en/funcarg_compare.rst index 4fa9b79ae..c9939d70f 100644 --- a/doc/en/funcarg_compare.rst +++ b/doc/en/funcarg_compare.rst @@ -23,6 +23,8 @@ the ``request.cached_setup()`` helper to manage caching of resources. Here is a basic example how we could implement a per-session Database object:: +.. code-block:: python + # content of conftest.py class Database(object): def __init__(self): @@ -70,6 +72,8 @@ Instead of calling cached_setup() with a cache scope, you can use the :ref:`@pytest.fixture ` decorator and directly state the scope:: +.. code-block:: python + @pytest.fixture(scope="session") def db(request): # factory will only be invoked once per session - @@ -92,6 +96,8 @@ or implement a ``pytest_generate_tests`` hook to perform parametrization, i.e. calling a test multiple times with different value sets. pytest-2.3 introduces a decorator for use on the factory itself:: +.. code-block:: python + @pytest.fixture(params=["mysql", "pg"]) def db(request): ... # use request.param @@ -109,6 +115,8 @@ parametrized via Of course it's perfectly fine to combine parametrization and scoping:: +.. code-block:: python + @pytest.fixture(scope="session", params=["mysql", "pg"]) def db(request): if request.param == "mysql": @@ -130,6 +138,8 @@ When using the ``@fixture`` decorator the name of the function denotes the name under which the resource can be accessed as a function argument:: +.. code-block:: python + @pytest.fixture() def db(request): ... @@ -139,6 +149,8 @@ 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 aka:: +.. code-block:: python + def pytest_funcarg__db(request): ... diff --git a/doc/en/getting-started.rst b/doc/en/getting-started.rst index c313f3849..124c1e686 100644 --- a/doc/en/getting-started.rst +++ b/doc/en/getting-started.rst @@ -37,6 +37,8 @@ Create your first test Create a simple test function with just four lines of code:: +.. code-block:: python + # content of test_sample.py def func(x): return x + 1 @@ -85,6 +87,8 @@ Assert that a certain exception is raised Use the :ref:`raises ` helper to assert that some code raises an exception:: +.. code-block:: python + # content of test_sysexit.py import pytest def f(): @@ -107,6 +111,8 @@ 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:: +.. code-block:: python + # content of test_class.py class TestClass(object): def test_one(self): @@ -144,6 +150,8 @@ Request a unique temporary directory for functional tests ``pytest`` provides `Builtin fixtures/function arguments `_ to request arbitrary resources, like a unique temporary directory:: +.. code-block:: python + # content of test_tmpdir.py def test_needsfiles(tmpdir): print(tmpdir) diff --git a/doc/en/goodpractices.rst b/doc/en/goodpractices.rst index 9622cc766..065308c14 100644 --- a/doc/en/goodpractices.rst +++ b/doc/en/goodpractices.rst @@ -14,12 +14,16 @@ This ensures your code and dependencies are isolated from your system Python ins Next, place a ``setup.py`` file in the root of your package with the following minimum content:: +.. code-block:: python + from setuptools import setup, 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:: +.. code-block:: bash + pip install -e . which lets you change your source code (both tests and application) and rerun tests at will. @@ -62,6 +66,8 @@ 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 to keep tests separate from actual application code (often a good idea):: +.. code-block:: text + setup.py mypkg/ __init__.py @@ -94,6 +100,8 @@ be imported as ``test_app`` and ``test_view`` top-level modules by adding ``test 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:: +.. code-block:: text + setup.py mypkg/ ... @@ -116,6 +124,8 @@ because you want to test the *installed* version of your package, not the local In this situation, it is **strongly** suggested to use a ``src`` layout where application root package resides in a sub-directory of your root:: +.. code-block:: text + setup.py src/ mypkg/ @@ -142,6 +152,8 @@ Inlining test directories into your application package is useful if you have direct relation between tests and application modules and want to distribute them along with your application:: +.. code-block:: text + setup.py mypkg/ __init__.py @@ -155,6 +167,8 @@ want to distribute them along with your application:: In this scheme, it is easy to run your tests using the ``--pyargs`` option:: +.. code-block:: bash + pytest --pyargs mypkg ``pytest`` will discover where ``mypkg`` is installed and collect tests from there. diff --git a/doc/en/logging.rst b/doc/en/logging.rst index a53509184..681a8f6ac 100644 --- a/doc/en/logging.rst +++ b/doc/en/logging.rst @@ -72,6 +72,8 @@ caplog fixture Inside tests it is possible to change the log level for the captured log messages. This is supported by the ``caplog`` fixture:: +.. code-block:: python + def test_foo(caplog): caplog.set_level(logging.INFO) pass @@ -80,6 +82,8 @@ 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 logger:: +.. code-block:: python + def test_foo(caplog): caplog.set_level(logging.CRITICAL, logger='root.baz') pass @@ -89,6 +93,8 @@ 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 level inside a ``with`` block:: +.. code-block:: python + def test_bar(caplog): with caplog.at_level(logging.INFO): pass @@ -96,6 +102,8 @@ level inside a ``with`` block:: Again, by default the level of the root logger is affected but the level of any logger can be changed instead with:: +.. code-block:: python + def test_bar(caplog): with caplog.at_level(logging.CRITICAL, logger='root.baz'): pass @@ -104,6 +112,8 @@ 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. This is useful for when you want to assert on the contents of a message:: +.. code-block:: python + def test_baz(caplog): func_under_test() for record in caplog.records: @@ -117,6 +127,8 @@ 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 severity and message:: +.. code-block:: python + def test_foo(caplog): logging.getLogger().info('boo %s', 'arg') @@ -126,6 +138,8 @@ severity and message:: You can call ``caplog.clear()`` to reset the captured log records in a test:: +.. code-block:: python + def test_something_with_clearing_records(caplog): some_method_that_creates_log_records() caplog.clear() diff --git a/doc/en/plugins.rst b/doc/en/plugins.rst index e80969193..1168d3aad 100644 --- a/doc/en/plugins.rst +++ b/doc/en/plugins.rst @@ -10,6 +10,8 @@ For writing your own plugins, please refer to :ref:`writing-plugins`. Installing a third party plugin can be easily done with ``pip``:: +.. code-block:: bash + pip install pytest-NAME pip uninstall pytest-NAME @@ -97,6 +99,8 @@ Finding out which plugins are active If you want to find out which plugins are active in your environment you can type:: +.. code-block:: bash + pytest --trace-config and will get an extended test header which shows activated plugins @@ -110,6 +114,8 @@ Deactivating / unregistering a plugin by name You can prevent plugins from loading or unregister them:: +.. code-block:: bash + pytest -p no:NAME This means that any subsequent try to activate/load the named diff --git a/doc/en/pythonpath.rst b/doc/en/pythonpath.rst index b64742768..498dd3360 100644 --- a/doc/en/pythonpath.rst +++ b/doc/en/pythonpath.rst @@ -24,6 +24,8 @@ Consider this file and directory layout:: When executing:: +.. code-block:: bash + pytest root/ @@ -56,6 +58,8 @@ Consider this file and directory layout:: When executing:: +.. code-block:: bash + pytest root/ pytest will find ``foo/bar/tests/test_foo.py`` and realize it is NOT part of a package given that diff --git a/doc/en/reference.rst b/doc/en/reference.rst index afbef6b1e..9cbef184d 100644 --- a/doc/en/reference.rst +++ b/doc/en/reference.rst @@ -471,6 +471,8 @@ test plugins. To use it, include in your top-most ``conftest.py`` file:: +.. code-block:: python + pytest_plugins = 'pytester' @@ -1001,6 +1003,8 @@ passed multiple times. The expected format is ``name=value``. For example:: issuing ``pytest test_hello.py`` actually means:: + .. code-block:: bash + pytest --maxfail=2 -rf test_hello.py Default is to add no options. diff --git a/doc/en/skipping.rst b/doc/en/skipping.rst index d1b308ac0..f9b6ed0f6 100644 --- a/doc/en/skipping.rst +++ b/doc/en/skipping.rst @@ -182,12 +182,16 @@ Skipping on a missing import dependency You can use the following helper at module level or within a test or test setup function:: +.. code-block:: python + docutils = pytest.importorskip("docutils") If ``docutils`` cannot be imported here, this will lead to a skip outcome of the test. You can also skip based on the version number of a library:: +.. code-block:: python + docutils = pytest.importorskip("docutils", minversion="0.3") The version will be read from the specified @@ -225,6 +229,8 @@ XFail: mark test functions as expected to fail You can use the ``xfail`` marker to indicate that you expect a test to fail:: +.. code-block:: python + @pytest.mark.xfail def test_function(): ... diff --git a/doc/en/tmpdir.rst b/doc/en/tmpdir.rst index 689622956..0c9f59b96 100644 --- a/doc/en/tmpdir.rst +++ b/doc/en/tmpdir.rst @@ -92,6 +92,8 @@ created in the `base temporary directory`_. ``tmpdir`` is a `py.path.local`_ object which offers ``os.path`` methods and more. Here is an example test usage:: +.. code-block:: python + # content of test_tmpdir.py import os def test_create_file(tmpdir): diff --git a/doc/en/unittest.rst b/doc/en/unittest.rst index a913f72b7..9b3d9bd60 100644 --- a/doc/en/unittest.rst +++ b/doc/en/unittest.rst @@ -12,6 +12,8 @@ the test suite to take full advantage of pytest's features. To run an existing ``unittest``-style test suite using ``pytest``, type:: +.. code-block:: bash + pytest tests @@ -80,6 +82,8 @@ let's jump-start into an example that integrates a pytest ``db_class`` fixture, setting up a class-cached database object, and then reference it from a unittest-style test:: +.. code-block:: python + # content of conftest.py # we define a fixture function below and it will be "used" by @@ -105,6 +109,8 @@ 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 fixture definition:: +.. code-block:: python + # content of test_unittest_db.py import unittest @@ -181,6 +187,8 @@ pre-initialized ``samplefile.ini``. Our ``initdir`` fixture itself uses the pytest builtin :ref:`tmpdir ` fixture to delegate the creation of a per-test temporary directory:: +.. code-block:: python + # content of test_unittest_cleandir.py import pytest import unittest diff --git a/doc/en/usage.rst b/doc/en/usage.rst index 75f5aacfd..f29e018a1 100644 --- a/doc/en/usage.rst +++ b/doc/en/usage.rst @@ -756,16 +756,22 @@ Calling pytest from Python code You can invoke ``pytest`` from Python code directly:: +.. code-block:: python + pytest.main() this acts as if you would call "pytest" from the command line. It will not raise ``SystemExit`` but return the exitcode instead. You can pass in options and arguments:: +.. code-block:: python + pytest.main(['-x', 'mytestdir']) You can specify additional plugins to ``pytest.main``:: +.. code-block:: python + # content of myinvoke.py import pytest class MyPlugin(object): diff --git a/doc/en/warnings.rst b/doc/en/warnings.rst index 382f15928..40d9230b3 100644 --- a/doc/en/warnings.rst +++ b/doc/en/warnings.rst @@ -180,6 +180,7 @@ This will ignore all warnings of type ``DeprecationWarning`` where the start of the regular expression ``".*U.*mode is deprecated"``. .. note:: + If warnings are configured at the interpreter level, using the `PYTHONWARNINGS `_ environment variable or the ``-W`` command-line option, pytest will not configure any filters by default. @@ -279,6 +280,8 @@ argument ``match`` to assert that the exception matches a text or regex:: You can also call ``pytest.warns`` on a function or code string:: +.. code-block:: python + pytest.warns(expected_warning, func, *args, **kwargs) pytest.warns(expected_warning, "func(*args, **kwargs)") @@ -411,7 +414,7 @@ These warnings might be filtered using the same builtin mechanisms used to filte Please read our :ref:`backwards-compatibility` to learn how we proceed about deprecating and eventually removing features. -The following warning types ares used by pytest and are part of the public API: +The following warning types are used by pytest and are part of the public API: .. autoclass:: pytest.PytestWarning diff --git a/doc/en/xunit_setup.rst b/doc/en/xunit_setup.rst index 466873302..e96744cb6 100644 --- a/doc/en/xunit_setup.rst +++ b/doc/en/xunit_setup.rst @@ -29,6 +29,8 @@ If you have multiple test functions and test classes in a single module you can optionally implement the following fixture methods which will usually be called once for all the functions:: +.. code-block:: python + def setup_module(module): """ setup any state specific to the execution of the given module.""" @@ -45,6 +47,8 @@ Class level setup/teardown Similarly, the following methods are called at class level before and after all test methods of the class are called:: +.. code-block:: python + @classmethod def setup_class(cls): """ setup any state specific to the execution of the given class (which @@ -62,6 +66,8 @@ Method and function level setup/teardown Similarly, the following methods are called around each method invocation:: +.. code-block:: python + def setup_method(self, method): """ setup any state tied to the execution of the given method in a class. setup_method is invoked for every test method of a class. @@ -77,6 +83,8 @@ As of pytest-3.0, the ``method`` parameter is optional. If you would rather define test functions directly at module level you can also use the following functions to implement fixtures:: +.. code-block:: python + def setup_function(function): """ setup any state tied to the execution of the given function. Invoked for every test function in the module. From 75d0b899bbb56d6849e9d69d83a9426ed3f43f8b Mon Sep 17 00:00:00 2001 From: boris Date: Tue, 6 Aug 2019 13:33:21 -0700 Subject: [PATCH 05/11] ran pyupgrade-docs again --- doc/en/example/parametrize.rst | 10 +++++----- doc/en/example/pythoncollection.rst | 2 +- doc/en/example/special.rst | 6 +++--- doc/en/fixture.rst | 14 +++++++------- doc/en/funcarg_compare.rst | 2 +- doc/en/getting-started.rst | 2 +- doc/en/unittest.rst | 2 +- doc/en/usage.rst | 2 +- 8 files changed, 20 insertions(+), 20 deletions(-) diff --git a/doc/en/example/parametrize.rst b/doc/en/example/parametrize.rst index ac9f81a38..b707aeac4 100644 --- a/doc/en/example/parametrize.rst +++ b/doc/en/example/parametrize.rst @@ -190,13 +190,13 @@ only have to work a bit to construct the correct arguments for pytest's idlist.append(scenario[0]) items = scenario[1].items() argnames = [x[0] for x in items] - argvalues.append(([x[1] for x in items])) + argvalues.append([x[1] for x in items]) metafunc.parametrize(argnames, argvalues, ids=idlist, scope="class") scenario1 = ('basic', {'attribute': 'value'}) scenario2 = ('advanced', {'attribute': 'value2'}) - class TestSampleWithScenarios(object): + class TestSampleWithScenarios: scenarios = [scenario1, scenario2] def test_demo1(self, attribute): @@ -277,9 +277,9 @@ creates a database object for the actual test invocations:: if 'db' in metafunc.fixturenames: metafunc.parametrize("db", ['d1', 'd2'], indirect=True) - class DB1(object): + class DB1: "one database object" - class DB2(object): + class DB2: "alternative database object" @pytest.fixture @@ -398,7 +398,7 @@ parametrizer`_ but in a lot less code:: metafunc.parametrize(argnames, [[funcargs[name] for name in argnames] for funcargs in funcarglist]) - class TestClass(object): + class TestClass: # a map specifying multiple argument sets for a test method params = { 'test_equals': [dict(a=1, b=2), dict(a=3, b=3), ], diff --git a/doc/en/example/pythoncollection.rst b/doc/en/example/pythoncollection.rst index 86b7fe566..89619bca3 100644 --- a/doc/en/example/pythoncollection.rst +++ b/doc/en/example/pythoncollection.rst @@ -136,7 +136,7 @@ that match ``*_check``. For example, if we have:: .. code-block:: python # content of check_myapp.py - class CheckMyApp(object): + class CheckMyApp: def simple_check(self): pass def complex_check(self): diff --git a/doc/en/example/special.rst b/doc/en/example/special.rst index c8fc96786..bc65f4d48 100644 --- a/doc/en/example/special.rst +++ b/doc/en/example/special.rst @@ -16,7 +16,7 @@ calls it:: @pytest.fixture(scope="session", autouse=True) def callattr_ahead_of_alltests(request): print("callattr_ahead_of_alltests called") - seen = set([None]) + seen = {None} session = request.node for item in session.items: cls = item.getparent(pytest.Class) @@ -32,7 +32,7 @@ will be called ahead of running any tests:: # content of test_module.py - class TestHello(object): + class TestHello: @classmethod def callme(cls): print("callme called!") @@ -43,7 +43,7 @@ will be called ahead of running any tests:: def test_method2(self): print("test_method1 called") - class TestOther(object): + class TestOther: @classmethod def callme(cls): print("callme other called") diff --git a/doc/en/fixture.rst b/doc/en/fixture.rst index 9ba2552ba..8957c48bb 100644 --- a/doc/en/fixture.rst +++ b/doc/en/fixture.rst @@ -496,7 +496,7 @@ read an optional server URL from the test module which uses our fixture:: server = getattr(request.module, "smtpserver", "smtp.gmail.com") smtp_connection = smtplib.SMTP(server, 587, timeout=5) yield smtp_connection - print("finalizing %s (%s)" % (smtp_connection, server)) + print("finalizing {} ({})".format(smtp_connection, server)) smtp_connection.close() We use the ``request.module`` attribute to optionally obtain an @@ -820,7 +820,7 @@ and instantiate an object ``app`` where we stick the already defined import pytest - class App(object): + class App: def __init__(self, smtp_connection): self.smtp_connection = smtp_connection @@ -902,7 +902,7 @@ to show the setup/teardown flow:: def test_1(modarg): print(" RUN test1 with modarg %s" % modarg) def test_2(otherarg, modarg): - print(" RUN test2 with otherarg %s and modarg %s" % (otherarg, modarg)) + print(" RUN test2 with otherarg {} and modarg {}".format(otherarg, modarg)) Let's run the tests in verbose mode and with looking at the print-output: @@ -1001,7 +1001,7 @@ and declare its use in a test module via a ``usefixtures`` marker:: import pytest @pytest.mark.usefixtures("cleandir") - class TestDirectoryInit(object): + class TestDirectoryInit: def test_cwd_starts_empty(self): assert os.listdir(os.getcwd()) == [] with open("myfile", "w") as f: @@ -1086,7 +1086,7 @@ self-contained implementation of this idea:: import pytest - class DB(object): + class DB: def __init__(self): self.intransaction = [] def begin(self, name): @@ -1098,7 +1098,7 @@ self-contained implementation of this idea:: def db(): return DB() - class TestClass(object): + class TestClass: @pytest.fixture(autouse=True) def transact(self, request, db): db.begin(request.function.__name__) @@ -1162,7 +1162,7 @@ and then e.g. have a TestClass using it by declaring the need:: .. code-block:: python @pytest.mark.usefixtures("transact") - class TestClass(object): + class TestClass: def test_method1(self): ... diff --git a/doc/en/funcarg_compare.rst b/doc/en/funcarg_compare.rst index c9939d70f..131ceb1ae 100644 --- a/doc/en/funcarg_compare.rst +++ b/doc/en/funcarg_compare.rst @@ -26,7 +26,7 @@ a per-session Database object:: .. code-block:: python # content of conftest.py - class Database(object): + class Database: def __init__(self): print("database instance created") def destroy(self): diff --git a/doc/en/getting-started.rst b/doc/en/getting-started.rst index 124c1e686..b2d597e1e 100644 --- a/doc/en/getting-started.rst +++ b/doc/en/getting-started.rst @@ -114,7 +114,7 @@ Once you develop multiple tests, you may want to group them into a class. pytest .. code-block:: python # content of test_class.py - class TestClass(object): + class TestClass: def test_one(self): x = "this" assert 'h' in x diff --git a/doc/en/unittest.rst b/doc/en/unittest.rst index 9b3d9bd60..e8063c173 100644 --- a/doc/en/unittest.rst +++ b/doc/en/unittest.rst @@ -93,7 +93,7 @@ it from a unittest-style test:: @pytest.fixture(scope="class") def db_class(request): - class DummyDB(object): + class DummyDB: pass # set a class attribute on the invoking test context request.cls.db = DummyDB() diff --git a/doc/en/usage.rst b/doc/en/usage.rst index f29e018a1..ef6d2712e 100644 --- a/doc/en/usage.rst +++ b/doc/en/usage.rst @@ -774,7 +774,7 @@ You can specify additional plugins to ``pytest.main``:: # content of myinvoke.py import pytest - class MyPlugin(object): + class MyPlugin: def pytest_sessionfinish(self): print("*** test run reporting finishing") From 5f95dce95602921a70bfbc7d8de2f7712c5e4505 Mon Sep 17 00:00:00 2001 From: boris Date: Tue, 6 Aug 2019 13:34:58 -0700 Subject: [PATCH 06/11] ran blacken-docs --- doc/en/assert.rst | 5 +- doc/en/builtin.rst | 1 + doc/en/cache.rst | 6 +- doc/en/capture.rst | 3 + doc/en/doctest.rst | 4 +- doc/en/example/parametrize.rst | 94 +++++++++++++++++++---------- doc/en/example/pythoncollection.rst | 3 +- doc/en/example/special.rst | 8 ++- doc/en/fixture.rst | 47 ++++++++++++--- doc/en/funcarg_compare.rst | 10 +-- doc/en/getting-started.rst | 8 ++- doc/en/logging.rst | 16 +++-- doc/en/reference.rst | 2 +- doc/en/tmpdir.rst | 2 + doc/en/unittest.rst | 11 ++-- doc/en/usage.rst | 5 +- doc/en/xunit_setup.rst | 4 ++ 17 files changed, 163 insertions(+), 66 deletions(-) diff --git a/doc/en/assert.rst b/doc/en/assert.rst index 41afc1abf..bc7e75256 100644 --- a/doc/en/assert.rst +++ b/doc/en/assert.rst @@ -238,7 +238,10 @@ file which provides an alternative explanation for ``Foo`` objects: def pytest_assertrepr_compare(op, left, right): if isinstance(left, Foo) and isinstance(right, Foo) and op == "==": - return ["Comparing Foo instances:", " vals: {} != {}".format(left.val, right.val)] + return [ + "Comparing Foo instances:", + " vals: {} != {}".format(left.val, right.val), + ] now, given this test module: diff --git a/doc/en/builtin.rst b/doc/en/builtin.rst index 4f93b877e..c4a6c0c2a 100644 --- a/doc/en/builtin.rst +++ b/doc/en/builtin.rst @@ -167,4 +167,5 @@ You can also interactively ask for help, e.g. by typing on the Python interactiv .. code-block:: python import pytest + help(pytest) diff --git a/doc/en/cache.rst b/doc/en/cache.rst index 1323c8b58..a4bc3be5c 100644 --- a/doc/en/cache.rst +++ b/doc/en/cache.rst @@ -40,10 +40,11 @@ First, let's create 50 test invocation of which only 2 fail:: # content of test_50.py import pytest + @pytest.mark.parametrize("i", range(50)) def test_num(i): if i in (17, 25): - pytest.fail("bad luck") + pytest.fail("bad luck") If you run this for the first time you will see two failures: @@ -193,9 +194,11 @@ across pytest invocations:: import pytest import time + def expensive_computation(): print("running expensive computation...") + @pytest.fixture def mydata(request): val = request.config.cache.get("example/value", None) @@ -205,6 +208,7 @@ across pytest invocations:: request.config.cache.set("example/value", val) return val + def test_function(mydata): assert mydata == 23 diff --git a/doc/en/capture.rst b/doc/en/capture.rst index 5e821dfcb..48b0226a4 100644 --- a/doc/en/capture.rst +++ b/doc/en/capture.rst @@ -55,12 +55,15 @@ is that you can use print statements for debugging:: # content of test_module.py + def setup_function(function): print("setting up %s" % function) + def test_func1(): assert True + def test_func2(): assert False diff --git a/doc/en/doctest.rst b/doc/en/doctest.rst index e6388c66b..c11aaaaec 100644 --- a/doc/en/doctest.rst +++ b/doc/en/doctest.rst @@ -197,9 +197,11 @@ place the objects you want to appear in the doctest namespace:: # content of conftest.py import numpy + + @pytest.fixture(autouse=True) def add_np(doctest_namespace): - doctest_namespace['np'] = numpy + doctest_namespace["np"] = numpy which can then be used in your doctests directly:: diff --git a/doc/en/example/parametrize.rst b/doc/en/example/parametrize.rst index b707aeac4..86cc2bf64 100644 --- a/doc/en/example/parametrize.rst +++ b/doc/en/example/parametrize.rst @@ -25,6 +25,7 @@ line argument. Let's first write a simple (do-nothing) computation test:: # content of test_compute.py + def test_compute(param1): assert param1 < 4 @@ -34,13 +35,14 @@ Now we add a test configuration like this:: # content of conftest.py + def pytest_addoption(parser): - parser.addoption("--all", action="store_true", - help="run all combinations") + parser.addoption("--all", action="store_true", help="run all combinations") + def pytest_generate_tests(metafunc): - if 'param1' in metafunc.fixturenames: - if metafunc.config.getoption('all'): + if "param1" in metafunc.fixturenames: + if metafunc.config.getoption("all"): end = 5 else: end = 2 @@ -118,7 +120,7 @@ the argument name:: def idfn(val): if isinstance(val, (datetime,)): # note this wouldn't show any hours/minutes/seconds - return val.strftime('%Y%m%d') + return val.strftime("%Y%m%d") @pytest.mark.parametrize("a,b,expected", testdata, ids=idfn) @@ -126,12 +128,18 @@ the argument name:: diff = a - b assert diff == expected - @pytest.mark.parametrize("a,b,expected", [ - pytest.param(datetime(2001, 12, 12), datetime(2001, 12, 11), - timedelta(1), id='forward'), - pytest.param(datetime(2001, 12, 11), datetime(2001, 12, 12), - timedelta(-1), id='backward'), - ]) + + @pytest.mark.parametrize( + "a,b,expected", + [ + pytest.param( + datetime(2001, 12, 12), datetime(2001, 12, 11), timedelta(1), id="forward" + ), + pytest.param( + datetime(2001, 12, 11), datetime(2001, 12, 12), timedelta(-1), id="backward" + ), + ], + ) def test_timedistance_v3(a, b, expected): diff = a - b assert diff == expected @@ -183,6 +191,7 @@ only have to work a bit to construct the correct arguments for pytest's # content of test_scenarios.py + def pytest_generate_tests(metafunc): idlist = [] argvalues = [] @@ -193,8 +202,10 @@ only have to work a bit to construct the correct arguments for pytest's argvalues.append([x[1] for x in items]) metafunc.parametrize(argnames, argvalues, ids=idlist, scope="class") - scenario1 = ('basic', {'attribute': 'value'}) - scenario2 = ('advanced', {'attribute': 'value2'}) + + scenario1 = ("basic", {"attribute": "value"}) + scenario2 = ("advanced", {"attribute": "value2"}) + class TestSampleWithScenarios: scenarios = [scenario1, scenario2] @@ -259,6 +270,8 @@ the actual test requiring a ``db`` object:: # content of test_backends.py import pytest + + def test_db_initialized(db): # a dummy test if db.__class__.__name__ == "DB2": @@ -273,15 +286,20 @@ creates a database object for the actual test invocations:: # content of conftest.py import pytest + def pytest_generate_tests(metafunc): - if 'db' in metafunc.fixturenames: - metafunc.parametrize("db", ['d1', 'd2'], indirect=True) + if "db" in metafunc.fixturenames: + metafunc.parametrize("db", ["d1", "d2"], indirect=True) + class DB1: "one database object" + + class DB2: "alternative database object" + @pytest.fixture def db(request): if request.param == "d1": @@ -346,18 +364,22 @@ will be passed to respective fixture function:: # content of test_indirect_list.py import pytest - @pytest.fixture(scope='function') + + + @pytest.fixture(scope="function") def x(request): return request.param * 3 - @pytest.fixture(scope='function') + + @pytest.fixture(scope="function") def y(request): return request.param * 2 - @pytest.mark.parametrize('x, y', [('a', 'b')], indirect=['x']) - def test_indirect(x,y): - assert x == 'aaa' - assert y == 'b' + + @pytest.mark.parametrize("x, y", [("a", "b")], indirect=["x"]) + def test_indirect(x, y): + assert x == "aaa" + assert y == "b" The result of this test will be successful: @@ -391,18 +413,21 @@ parametrizer`_ but in a lot less code:: # content of ./test_parametrize.py import pytest + def pytest_generate_tests(metafunc): # called once per each test function funcarglist = metafunc.cls.params[metafunc.function.__name__] argnames = sorted(funcarglist[0]) - metafunc.parametrize(argnames, [[funcargs[name] for name in argnames] - for funcargs in funcarglist]) + metafunc.parametrize( + argnames, [[funcargs[name] for name in argnames] for funcargs in funcarglist] + ) + class TestClass: # a map specifying multiple argument sets for a test method params = { - 'test_equals': [dict(a=1, b=2), dict(a=3, b=3), ], - 'test_zerodivision': [dict(a=1, b=0), ], + "test_equals": [dict(a=1, b=2), dict(a=3, b=3)], + "test_zerodivision": [dict(a=1, b=0)], } def test_equals(self, a, b): @@ -471,10 +496,12 @@ need to provide similar results:: import pytest + @pytest.fixture(scope="session") def basemod(request): return pytest.importorskip("base") + @pytest.fixture(scope="session", params=["opt1", "opt2"]) def optmod(request): return pytest.importorskip(request.param) @@ -501,6 +528,7 @@ And finally a little test module:: # content of test_module.py + def test_func1(basemod, optmod): assert round(basemod.func1(), 3) == round(optmod.func1(), 3) @@ -610,17 +638,21 @@ as a complement to ``raises``. For example:: from contextlib import contextmanager import pytest + @contextmanager def does_not_raise(): yield - @pytest.mark.parametrize('example_input,expectation', [ - (3, does_not_raise()), - (2, does_not_raise()), - (1, does_not_raise()), - (0, pytest.raises(ZeroDivisionError)), - ]) + @pytest.mark.parametrize( + "example_input,expectation", + [ + (3, does_not_raise()), + (2, does_not_raise()), + (1, does_not_raise()), + (0, pytest.raises(ZeroDivisionError)), + ], + ) def test_division(example_input, expectation): """Test how much I know division.""" with expectation: diff --git a/doc/en/example/pythoncollection.rst b/doc/en/example/pythoncollection.rst index 89619bca3..729f35e17 100644 --- a/doc/en/example/pythoncollection.rst +++ b/doc/en/example/pythoncollection.rst @@ -139,6 +139,7 @@ that match ``*_check``. For example, if we have:: class CheckMyApp: def simple_check(self): pass + def complex_check(self): pass @@ -267,7 +268,7 @@ and a ``setup.py`` dummy file like this:: .. code-block:: python # content of setup.py - 0/0 # will raise exception if imported + 0 / 0 # will raise exception if imported If you run with a Python 2 interpreter then you will find the one test and will leave out the ``setup.py`` file: diff --git a/doc/en/example/special.rst b/doc/en/example/special.rst index bc65f4d48..d7f6ec2eb 100644 --- a/doc/en/example/special.rst +++ b/doc/en/example/special.rst @@ -13,6 +13,7 @@ calls it:: import pytest + @pytest.fixture(scope="session", autouse=True) def callattr_ahead_of_alltests(request): print("callattr_ahead_of_alltests called") @@ -22,7 +23,7 @@ calls it:: cls = item.getparent(pytest.Class) if cls not in seen: if hasattr(cls.obj, "callme"): - cls.obj.callme() + cls.obj.callme() seen.add(cls) test classes may now define a ``callme`` method which @@ -32,6 +33,7 @@ will be called ahead of running any tests:: # content of test_module.py + class TestHello: @classmethod def callme(cls): @@ -43,16 +45,20 @@ will be called ahead of running any tests:: def test_method2(self): print("test_method1 called") + class TestOther: @classmethod def callme(cls): print("callme other called") + def test_other(self): print("test other") + # works with unittest as well ... import unittest + class SomeTest(unittest.TestCase): @classmethod def callme(self): diff --git a/doc/en/fixture.rst b/doc/en/fixture.rst index 8957c48bb..ddcb09b8c 100644 --- a/doc/en/fixture.rst +++ b/doc/en/fixture.rst @@ -56,15 +56,18 @@ using it:: # content of ./test_smtpsimple.py import pytest + @pytest.fixture def smtp_connection(): import smtplib + return smtplib.SMTP("smtp.gmail.com", 587, timeout=5) + def test_ehlo(smtp_connection): response, msg = smtp_connection.ehlo() assert response == 250 - assert 0 # for demo purposes + assert 0 # for demo purposes Here, the ``test_ehlo`` needs the ``smtp_connection`` fixture value. pytest will discover and call the :py:func:`@pytest.fixture <_pytest.python.fixture>` @@ -190,6 +193,7 @@ access the fixture function:: import pytest import smtplib + @pytest.fixture(scope="module") def smtp_connection(): return smtplib.SMTP("smtp.gmail.com", 587, timeout=5) @@ -203,12 +207,14 @@ located):: # content of test_module.py + def test_ehlo(smtp_connection): response, msg = smtp_connection.ehlo() assert response == 250 assert b"smtp.gmail.com" in msg assert 0 # for demo purposes + def test_noop(smtp_connection): response, msg = smtp_connection.noop() assert response == 250 @@ -491,6 +497,7 @@ read an optional server URL from the test module which uses our fixture:: import pytest import smtplib + @pytest.fixture(scope="module") def smtp_connection(request): server = getattr(request.module, "smtpserver", "smtp.gmail.com") @@ -519,6 +526,7 @@ server URL in its module namespace:: smtpserver = "mail.python.org" # will be read by smtp fixture + def test_showhelo(smtp_connection): assert 0, smtp_connection.helo() @@ -556,12 +564,8 @@ Factories can have parameters as needed:: @pytest.fixture def make_customer_record(): - def _make_customer_record(name): - return { - "name": name, - "orders": [] - } + return {"name": name, "orders": []} return _make_customer_record @@ -620,8 +624,8 @@ through the special :py:class:`request ` object:: import pytest import smtplib - @pytest.fixture(scope="module", - params=["smtp.gmail.com", "mail.python.org"]) + + @pytest.fixture(scope="module", params=["smtp.gmail.com", "mail.python.org"]) def smtp_connection(request): smtp_connection = smtplib.SMTP(request.param, 587, timeout=5) yield smtp_connection @@ -713,23 +717,28 @@ the string used in a test ID for a certain fixture value by using the # content of test_ids.py import pytest + @pytest.fixture(params=[0, 1], ids=["spam", "ham"]) def a(request): return request.param + def test_a(a): pass + def idfn(fixture_value): if fixture_value == 0: return "eggs" else: return None + @pytest.fixture(params=[0, 1], ids=idfn) def b(request): return request.param + def test_b(b): pass @@ -778,10 +787,13 @@ Example:: # content of test_fixture_marks.py import pytest + + @pytest.fixture(params=[0, 1, pytest.param(2, marks=pytest.mark.skip)]) def data_set(request): return request.param + def test_data(data_set): pass @@ -820,14 +832,17 @@ and instantiate an object ``app`` where we stick the already defined import pytest + class App: def __init__(self, smtp_connection): self.smtp_connection = smtp_connection + @pytest.fixture(scope="module") def app(smtp_connection): return App(smtp_connection) + def test_smtp_connection_exists(app): assert app.smtp_connection @@ -883,6 +898,7 @@ to show the setup/teardown flow:: # content of test_module.py import pytest + @pytest.fixture(scope="module", params=["mod1", "mod2"]) def modarg(request): param = request.param @@ -890,17 +906,23 @@ to show the setup/teardown flow:: yield param print(" TEARDOWN modarg %s" % param) - @pytest.fixture(scope="function", params=[1,2]) + + @pytest.fixture(scope="function", params=[1, 2]) def otherarg(request): param = request.param print(" SETUP otherarg %s" % param) yield param print(" TEARDOWN otherarg %s" % param) + def test_0(otherarg): print(" RUN test0 with otherarg %s" % otherarg) + + def test_1(modarg): print(" RUN test1 with modarg %s" % modarg) + + def test_2(otherarg, modarg): print(" RUN test2 with otherarg {} and modarg {}".format(otherarg, modarg)) @@ -987,6 +1009,7 @@ file:: import tempfile import os + @pytest.fixture() def cleandir(): newpath = tempfile.mkdtemp() @@ -1000,6 +1023,7 @@ and declare its use in a test module via a ``usefixtures`` marker:: import os import pytest + @pytest.mark.usefixtures("cleandir") class TestDirectoryInit: def test_cwd_starts_empty(self): @@ -1086,18 +1110,23 @@ self-contained implementation of this idea:: import pytest + class DB: def __init__(self): self.intransaction = [] + def begin(self, name): self.intransaction.append(name) + def rollback(self): self.intransaction.pop() + @pytest.fixture(scope="module") def db(): return DB() + class TestClass: @pytest.fixture(autouse=True) def transact(self, request, db): diff --git a/doc/en/funcarg_compare.rst b/doc/en/funcarg_compare.rst index 131ceb1ae..2f6e7a1ec 100644 --- a/doc/en/funcarg_compare.rst +++ b/doc/en/funcarg_compare.rst @@ -29,13 +29,15 @@ a per-session Database object:: class Database: def __init__(self): print("database instance created") + def destroy(self): print("database instance destroyed") + def pytest_funcarg__db(request): - return request.cached_setup(setup=DataBase, - teardown=lambda db: db.destroy, - scope="session") + return request.cached_setup( + setup=DataBase, teardown=lambda db: db.destroy, scope="session" + ) There are several limitations and difficulties with this approach: @@ -100,7 +102,7 @@ sets. pytest-2.3 introduces a decorator for use on the factory itself:: @pytest.fixture(params=["mysql", "pg"]) def db(request): - ... # use request.param + ... # use request.param Here the factory will be invoked twice (with the respective "mysql" and "pg" values set as ``request.param`` attributes) and all of diff --git a/doc/en/getting-started.rst b/doc/en/getting-started.rst index b2d597e1e..808ffcc64 100644 --- a/doc/en/getting-started.rst +++ b/doc/en/getting-started.rst @@ -43,6 +43,7 @@ Create a simple test function with just four lines of code:: def func(x): return x + 1 + def test_answer(): assert func(3) == 5 @@ -91,9 +92,12 @@ Use the :ref:`raises ` helper to assert that some code raises an e # content of test_sysexit.py import pytest + + def f(): raise SystemExit(1) + def test_mytest(): with pytest.raises(SystemExit): f() @@ -117,11 +121,11 @@ Once you develop multiple tests, you may want to group them into a class. pytest class TestClass: def test_one(self): x = "this" - assert 'h' in x + assert "h" in x def test_two(self): x = "hello" - assert hasattr(x, 'check') + assert hasattr(x, "check") ``pytest`` discovers all tests following its :ref:`Conventions for Python test discovery `, so it finds both ``test_`` prefixed functions. There is no need to subclass anything. We can simply run the module by passing its filename: diff --git a/doc/en/logging.rst b/doc/en/logging.rst index 681a8f6ac..888254a85 100644 --- a/doc/en/logging.rst +++ b/doc/en/logging.rst @@ -85,7 +85,7 @@ logger:: .. code-block:: python def test_foo(caplog): - caplog.set_level(logging.CRITICAL, logger='root.baz') + caplog.set_level(logging.CRITICAL, logger="root.baz") pass The log levels set are restored automatically at the end of the test. @@ -105,7 +105,7 @@ logger can be changed instead with:: .. code-block:: python def test_bar(caplog): - with caplog.at_level(logging.CRITICAL, logger='root.baz'): + with caplog.at_level(logging.CRITICAL, logger="root.baz"): pass Lastly all the logs sent to the logger during the test run are made available on @@ -117,8 +117,8 @@ This is useful for when you want to assert on the contents of a message:: def test_baz(caplog): func_under_test() for record in caplog.records: - assert record.levelname != 'CRITICAL' - assert 'wally' not in caplog.text + assert record.levelname != "CRITICAL" + assert "wally" not in caplog.text For all the available attributes of the log records see the ``logging.LogRecord`` class. @@ -130,11 +130,9 @@ severity and message:: .. code-block:: python def test_foo(caplog): - logging.getLogger().info('boo %s', 'arg') + logging.getLogger().info("boo %s", "arg") - 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:: @@ -144,7 +142,7 @@ You can call ``caplog.clear()`` to reset the captured log records in a test:: some_method_that_creates_log_records() caplog.clear() your_test_method() - assert ['Foo'] == [rec.message for rec in caplog.records] + assert ["Foo"] == [rec.message for rec in caplog.records] The ``caplog.records`` attribute contains records from the current stage only, so diff --git a/doc/en/reference.rst b/doc/en/reference.rst index 9cbef184d..173090cec 100644 --- a/doc/en/reference.rst +++ b/doc/en/reference.rst @@ -473,7 +473,7 @@ To use it, include in your top-most ``conftest.py`` file:: .. code-block:: python - pytest_plugins = 'pytester' + pytest_plugins = "pytester" diff --git a/doc/en/tmpdir.rst b/doc/en/tmpdir.rst index 0c9f59b96..a4747f3a2 100644 --- a/doc/en/tmpdir.rst +++ b/doc/en/tmpdir.rst @@ -96,6 +96,8 @@ and more. Here is an example test usage:: # content of test_tmpdir.py import os + + def test_create_file(tmpdir): p = tmpdir.mkdir("sub").join("hello.txt") p.write("content") diff --git a/doc/en/unittest.rst b/doc/en/unittest.rst index e8063c173..e5253af69 100644 --- a/doc/en/unittest.rst +++ b/doc/en/unittest.rst @@ -91,10 +91,12 @@ it from a unittest-style test:: import pytest + @pytest.fixture(scope="class") def db_class(request): class DummyDB: pass + # set a class attribute on the invoking test context request.cls.db = DummyDB() @@ -116,14 +118,15 @@ fixture definition:: import unittest import pytest + @pytest.mark.usefixtures("db_class") class MyTest(unittest.TestCase): def test_method1(self): assert hasattr(self, "db") - assert 0, self.db # fail for demo purposes + assert 0, self.db # fail for demo purposes def test_method2(self): - assert 0, self.db # fail for demo purposes + assert 0, self.db # fail for demo purposes The ``@pytest.mark.usefixtures("db_class")`` class-decorator makes sure that the pytest fixture function ``db_class`` is called once per class. @@ -193,11 +196,11 @@ creation of a per-test temporary directory:: import pytest import unittest - class MyTest(unittest.TestCase): + class MyTest(unittest.TestCase): @pytest.fixture(autouse=True) def initdir(self, tmpdir): - tmpdir.chdir() # change to pytest-provided temporary directory + tmpdir.chdir() # change to pytest-provided temporary directory tmpdir.join("samplefile.ini").write("# testdata") def test_method(self): diff --git a/doc/en/usage.rst b/doc/en/usage.rst index ef6d2712e..eb04b6220 100644 --- a/doc/en/usage.rst +++ b/doc/en/usage.rst @@ -766,7 +766,7 @@ You can pass in options and arguments:: .. code-block:: python - pytest.main(['-x', 'mytestdir']) + pytest.main(["-x", "mytestdir"]) You can specify additional plugins to ``pytest.main``:: @@ -774,10 +774,13 @@ You can specify additional plugins to ``pytest.main``:: # content of myinvoke.py import pytest + + class MyPlugin: def pytest_sessionfinish(self): print("*** test run reporting finishing") + pytest.main(["-qq"], plugins=[MyPlugin()]) Running it will show that ``MyPlugin`` was added and its diff --git a/doc/en/xunit_setup.rst b/doc/en/xunit_setup.rst index e96744cb6..22a0e51d0 100644 --- a/doc/en/xunit_setup.rst +++ b/doc/en/xunit_setup.rst @@ -34,6 +34,7 @@ which will usually be called once for all the functions:: def setup_module(module): """ setup any state specific to the execution of the given module.""" + def teardown_module(module): """ teardown any state that was previously setup with a setup_module method. @@ -55,6 +56,7 @@ and after all test methods of the class are called:: usually contains tests). """ + @classmethod def teardown_class(cls): """ teardown any state that was previously setup with a call to @@ -73,6 +75,7 @@ Similarly, the following methods are called around each method invocation:: class. setup_method is invoked for every test method of a class. """ + def teardown_method(self, method): """ teardown any state that was previously setup with a setup_method call. @@ -90,6 +93,7 @@ you can also use the following functions to implement fixtures:: Invoked for every test function in the module. """ + def teardown_function(function): """ teardown any state that was previously setup with a setup_function call. From 9fce0bdd88c425aa7b98dc4cc0c2696c19fdbd95 Mon Sep 17 00:00:00 2001 From: boris Date: Tue, 6 Aug 2019 15:46:57 -0700 Subject: [PATCH 07/11] remove implicit code tags .replace("::\n\n.. code-block", "\n\n.. code-block") --- doc/en/builtin.rst | 2 +- doc/en/cache.rst | 4 ++-- doc/en/capture.rst | 2 +- doc/en/deprecations.rst | 2 +- doc/en/doctest.rst | 6 ++--- doc/en/example/parametrize.rst | 32 +++++++++++++-------------- doc/en/example/pythoncollection.rst | 10 ++++----- doc/en/example/special.rst | 4 ++-- doc/en/existingtestsuite.rst | 2 +- doc/en/fixture.rst | 34 ++++++++++++++--------------- doc/en/funcarg_compare.rst | 12 +++++----- doc/en/getting-started.rst | 8 +++---- doc/en/goodpractices.rst | 14 ++++++------ doc/en/logging.rst | 14 ++++++------ doc/en/plugins.rst | 6 ++--- doc/en/pythonpath.rst | 4 ++-- doc/en/reference.rst | 2 +- doc/en/skipping.rst | 6 ++--- doc/en/tmpdir.rst | 2 +- doc/en/unittest.rst | 8 +++---- doc/en/usage.rst | 6 ++--- doc/en/warnings.rst | 2 +- doc/en/xunit_setup.rst | 8 +++---- 23 files changed, 95 insertions(+), 95 deletions(-) diff --git a/doc/en/builtin.rst b/doc/en/builtin.rst index c4a6c0c2a..68c23ebef 100644 --- a/doc/en/builtin.rst +++ b/doc/en/builtin.rst @@ -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 -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 diff --git a/doc/en/cache.rst b/doc/en/cache.rst index a4bc3be5c..501ccd810 100644 --- a/doc/en/cache.rst +++ b/doc/en/cache.rst @@ -33,7 +33,7 @@ Other plugins may access the `config.cache`_ object to set/get 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 @@ -186,7 +186,7 @@ The new config.cache object Plugins or conftest.py support code can get a cached value using the pytest ``config`` object. Here is a basic example plugin which implements a :ref:`fixture` which re-uses previously created state -across pytest invocations:: +across pytest invocations .. code-block:: python diff --git a/doc/en/capture.rst b/doc/en/capture.rst index 48b0226a4..c4b0a8d89 100644 --- a/doc/en/capture.rst +++ b/doc/en/capture.rst @@ -49,7 +49,7 @@ Using print statements for debugging --------------------------------------------------- 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 diff --git a/doc/en/deprecations.rst b/doc/en/deprecations.rst index d000dd6a1..92caee17b 100644 --- a/doc/en/deprecations.rst +++ b/doc/en/deprecations.rst @@ -455,7 +455,7 @@ Internal classes accessed through ``Node`` .. versionremoved:: 4.0 Access of ``Module``, ``Function``, ``Class``, ``Instance``, ``File`` and ``Item`` through ``Node`` instances now issue -this warning:: +this warning .. code-block:: text diff --git a/doc/en/doctest.rst b/doc/en/doctest.rst index c11aaaaec..7b1f20d15 100644 --- a/doc/en/doctest.rst +++ b/doc/en/doctest.rst @@ -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. ``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 @@ -203,7 +203,7 @@ place the objects you want to appear in the doctest namespace:: def add_np(doctest_namespace): 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 @@ -225,7 +225,7 @@ Skipping tests dynamically .. 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 diff --git a/doc/en/example/parametrize.rst b/doc/en/example/parametrize.rst index 86cc2bf64..19a18bf3d 100644 --- a/doc/en/example/parametrize.rst +++ b/doc/en/example/parametrize.rst @@ -19,7 +19,7 @@ Generating parameters combinations, depending on command line Let's say we want to execute a test with different computation 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 @@ -29,7 +29,7 @@ line argument. Let's first write a simple (do-nothing) computation test:: def test_compute(param1): assert param1 < 4 -Now we add a test configuration like this:: +Now we add a test configuration like this .. 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 used in the test ID. For other objects, pytest will make a string based on -the argument name:: +the argument name .. code-block:: python @@ -185,7 +185,7 @@ A quick port of "testscenarios" Here is a quick port to run tests configured with `test scenarios`_, 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 -:py:func:`Metafunc.parametrize`:: +:py:func:`Metafunc.parametrize` .. 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 connections or subprocess only when the actual test is run. 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 @@ -279,7 +279,7 @@ the actual test requiring a ``db`` object:: We can now add a test configuration that generates two invocations of 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 @@ -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 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`` -will be passed to respective fixture function:: +will be passed to respective fixture function .. code-block:: python @@ -406,7 +406,7 @@ Parametrizing test methods through per-class configuration Here is an example ``pytest_generate_tests`` function implementing a 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 @@ -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 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) -need to provide similar results:: +need to provide similar results .. code-block:: python @@ -506,7 +506,7 @@ need to provide similar results:: def optmod(request): 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 @@ -514,7 +514,7 @@ And then a base implementation of a simple function:: def func1(): return 1 -And an optimized version:: +And an optimized version .. code-block:: python @@ -522,7 +522,7 @@ And an optimized version:: def func1(): return 1.0001 -And finally a little test module:: +And finally a little test module .. code-block:: python @@ -631,7 +631,7 @@ Use :func:`pytest.raises` with the 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 -as a complement to ``raises``. For example:: +as a complement to ``raises``. For example .. 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``. 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 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 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 diff --git a/doc/en/example/pythoncollection.rst b/doc/en/example/pythoncollection.rst index 729f35e17..63b5a4b29 100644 --- a/doc/en/example/pythoncollection.rst +++ b/doc/en/example/pythoncollection.rst @@ -131,7 +131,7 @@ Here is an example: This would make ``pytest`` look for tests in files that match the ``check_* .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 @@ -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 imported. Moreover, there may files only importable by a specific python 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 @@ -252,7 +252,7 @@ listing them in a ``conftest.py`` file:: if sys.version_info[0] > 2: 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 @@ -263,7 +263,7 @@ and then if you have a module file like this:: except Exception, e: pass -and a ``setup.py`` dummy file like this:: +and a ``setup.py`` dummy file like this .. code-block:: python @@ -304,7 +304,7 @@ patterns to ``collect_ignore_glob``. 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 -interpreter:: +interpreter .. code-block:: python diff --git a/doc/en/example/special.rst b/doc/en/example/special.rst index d7f6ec2eb..28002fb03 100644 --- a/doc/en/example/special.rst +++ b/doc/en/example/special.rst @@ -5,7 +5,7 @@ A session-scoped fixture effectively has access to all collected test items. Here is an example of a fixture function which walks all collected tests and looks if their test class defines a ``callme`` method and -calls it:: +calls it .. code-block:: python @@ -27,7 +27,7 @@ calls it:: seen.add(cls) 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 diff --git a/doc/en/existingtestsuite.rst b/doc/en/existingtestsuite.rst index 956c970c2..8676baf76 100644 --- a/doc/en/existingtestsuite.rst +++ b/doc/en/existingtestsuite.rst @@ -15,7 +15,7 @@ Running an existing test suite with pytest Say you want to contribute to an existing repository somewhere. After pulling the code into your development space using some flavor of version control and (optionally) setting up a virtualenv -you will want to run:: +you will want to run .. code-block:: bash diff --git a/doc/en/fixture.rst b/doc/en/fixture.rst index ddcb09b8c..2bded9364 100644 --- a/doc/en/fixture.rst +++ b/doc/en/fixture.rst @@ -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 :py:func:`@pytest.fixture <_pytest.python.fixture>`. Let's look at a simple self-contained test module containing a fixture and a test function -using it:: +using it .. 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 so that tests from multiple test modules in the directory can -access the fixture function:: +access the fixture function .. 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 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 -located):: +located) .. code-block:: python @@ -489,7 +489,7 @@ Fixtures can introspect the requesting test context Fixture functions can accept the :py:class:`request ` object to introspect the "requesting" test function, class or module context. 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 @@ -518,7 +518,7 @@ again, nothing much has changed: 2 failed in 0.12 seconds 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 @@ -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. 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 @@ -575,7 +575,7 @@ Factories can have parameters as needed:: customer_2 = make_customer_record("Mike") 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 @@ -616,7 +616,7 @@ configured in multiple ways. Extending the previous example, we can flag the fixture to create two ``smtp_connection`` fixture instances which will cause all tests using the fixture to run twice. The fixture function gets access to each parameter -through the special :py:class:`request ` object:: +through the special :py:class:`request ` object .. 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 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 -``ids`` keyword argument:: +``ids`` keyword argument .. 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 that they can be used with :ref:`@pytest.mark.parametrize <@pytest.mark.parametrize>`. -Example:: +Example .. 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 many projects. As a simple example, we can extend the previous example and instantiate an object ``app`` where we stick the already defined -``smtp_connection`` resource into it:: +``smtp_connection`` resource into it .. 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 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 @@ -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 `_ and pytest fixtures to achieve it. We separate the creation of the fixture into a conftest.py -file:: +file .. code-block:: python @@ -1015,7 +1015,7 @@ file:: newpath = tempfile.mkdtemp() 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 @@ -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 begin/rollback/commit architecture and we want to automatically surround 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 @@ -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 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 -into a conftest.py file **without** using ``autouse``:: +into a conftest.py file **without** using ``autouse`` .. code-block:: python @@ -1186,7 +1186,7 @@ into a conftest.py file **without** using ``autouse``:: yield 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 diff --git a/doc/en/funcarg_compare.rst b/doc/en/funcarg_compare.rst index 2f6e7a1ec..d802dd585 100644 --- a/doc/en/funcarg_compare.rst +++ b/doc/en/funcarg_compare.rst @@ -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 the ``request.cached_setup()`` helper to manage caching of resources. Here is a basic example how we could implement -a per-session Database object:: +a per-session Database object .. 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 :ref:`@pytest.fixture ` decorator and directly state -the scope:: +the scope .. 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 or implement a ``pytest_generate_tests`` hook to perform 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 @@ -115,7 +115,7 @@ allow to re-use already written factories because effectively parametrized via :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 @@ -138,7 +138,7 @@ No ``pytest_funcarg__`` prefix when using @fixture decorator When using the ``@fixture`` decorator the name of the function denotes the name under which the resource can be accessed as a function -argument:: +argument .. code-block:: python @@ -149,7 +149,7 @@ argument:: 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 -aka:: +aka .. code-block:: python diff --git a/doc/en/getting-started.rst b/doc/en/getting-started.rst index 808ffcc64..ca62a9667 100644 --- a/doc/en/getting-started.rst +++ b/doc/en/getting-started.rst @@ -35,7 +35,7 @@ Install ``pytest`` 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 @@ -86,7 +86,7 @@ Run multiple tests Assert that a certain exception is raised -------------------------------------------------------------- -Use the :ref:`raises ` helper to assert that some code raises an exception:: +Use the :ref:`raises ` helper to assert that some code raises an exception .. code-block:: python @@ -113,7 +113,7 @@ Execute the test function with “quiet” reporting mode: 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 @@ -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 -------------------------------------------------------------- -``pytest`` provides `Builtin fixtures/function arguments `_ to request arbitrary resources, like a unique temporary directory:: +``pytest`` provides `Builtin fixtures/function arguments `_ to request arbitrary resources, like a unique temporary directory .. code-block:: python diff --git a/doc/en/goodpractices.rst b/doc/en/goodpractices.rst index 065308c14..61f18b555 100644 --- a/doc/en/goodpractices.rst +++ b/doc/en/goodpractices.rst @@ -12,7 +12,7 @@ pip_ for installing your application and any dependencies, as well as the ``pytest`` package itself. 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 @@ -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()) -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 @@ -64,7 +64,7 @@ Tests outside 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 -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 @@ -98,7 +98,7 @@ be imported as ``test_app`` and ``test_view`` top-level modules by adding ``test ``sys.path``. 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 @@ -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. 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 @@ -150,7 +150,7 @@ Tests as part of application code Inlining test directories into your application package 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 @@ -165,7 +165,7 @@ want to distribute them along with your application:: 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 diff --git a/doc/en/logging.rst b/doc/en/logging.rst index 888254a85..54edee38d 100644 --- a/doc/en/logging.rst +++ b/doc/en/logging.rst @@ -70,7 +70,7 @@ caplog fixture ^^^^^^^^^^^^^^ 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 @@ -80,7 +80,7 @@ messages. This is supported by the ``caplog`` fixture:: 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 -logger:: +logger .. code-block:: python @@ -91,7 +91,7 @@ logger:: 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 -level inside a ``with`` block:: +level inside a ``with`` block .. code-block:: python @@ -100,7 +100,7 @@ level inside a ``with`` block:: pass 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 @@ -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 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 @@ -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, that certain messages have been logged under a given logger name with a given -severity and message:: +severity and message .. code-block:: python @@ -134,7 +134,7 @@ severity and message:: 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 diff --git a/doc/en/plugins.rst b/doc/en/plugins.rst index 1168d3aad..1d5422364 100644 --- a/doc/en/plugins.rst +++ b/doc/en/plugins.rst @@ -8,7 +8,7 @@ Installing and Using plugins This section talks about installing and using third party 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 @@ -97,7 +97,7 @@ Finding out which plugins are active ------------------------------------ If you want to find out which plugins are active in your -environment you can type:: +environment you can type .. code-block:: bash @@ -112,7 +112,7 @@ and their names. It will also print local plugins aka 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 diff --git a/doc/en/pythonpath.rst b/doc/en/pythonpath.rst index 498dd3360..796b12b0b 100644 --- a/doc/en/pythonpath.rst +++ b/doc/en/pythonpath.rst @@ -22,7 +22,7 @@ Consider this file and directory layout:: |- test_foo.py -When executing:: +When executing .. code-block:: bash @@ -56,7 +56,7 @@ Consider this file and directory layout:: |- test_foo.py -When executing:: +When executing .. code-block:: bash diff --git a/doc/en/reference.rst b/doc/en/reference.rst index 173090cec..a39c6d4f6 100644 --- a/doc/en/reference.rst +++ b/doc/en/reference.rst @@ -469,7 +469,7 @@ testdir This fixture provides a :class:`Testdir` instance useful for black-box testing of test files, making it ideal to 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 diff --git a/doc/en/skipping.rst b/doc/en/skipping.rst index f9b6ed0f6..0ded839ae 100644 --- a/doc/en/skipping.rst +++ b/doc/en/skipping.rst @@ -180,7 +180,7 @@ Skipping on a missing import dependency ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 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 @@ -188,7 +188,7 @@ or within a test or test setup function:: If ``docutils`` cannot be imported here, this will lead to a 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 @@ -227,7 +227,7 @@ XFail: mark test functions as expected to fail ---------------------------------------------- You can use the ``xfail`` marker to indicate that you -expect a test to fail:: +expect a test to fail .. code-block:: python diff --git a/doc/en/tmpdir.rst b/doc/en/tmpdir.rst index a4747f3a2..b0ecfaab7 100644 --- a/doc/en/tmpdir.rst +++ b/doc/en/tmpdir.rst @@ -90,7 +90,7 @@ provide a temporary directory unique to the test invocation, created in the `base temporary directory`_. ``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 diff --git a/doc/en/unittest.rst b/doc/en/unittest.rst index e5253af69..af0da0923 100644 --- a/doc/en/unittest.rst +++ b/doc/en/unittest.rst @@ -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 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 @@ -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, let's jump-start into an example that integrates a pytest ``db_class`` 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 @@ -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 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 -fixture definition:: +fixture definition .. 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 pre-initialized ``samplefile.ini``. Our ``initdir`` fixture itself uses the pytest builtin :ref:`tmpdir ` fixture to delegate the -creation of a per-test temporary directory:: +creation of a per-test temporary directory .. code-block:: python diff --git a/doc/en/usage.rst b/doc/en/usage.rst index eb04b6220..d69397f8f 100644 --- a/doc/en/usage.rst +++ b/doc/en/usage.rst @@ -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 @@ -762,13 +762,13 @@ You can invoke ``pytest`` from Python code directly:: this acts as if you would call "pytest" from the command line. 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 pytest.main(["-x", "mytestdir"]) -You can specify additional plugins to ``pytest.main``:: +You can specify additional plugins to ``pytest.main`` .. code-block:: python diff --git a/doc/en/warnings.rst b/doc/en/warnings.rst index 40d9230b3..201e41e03 100644 --- a/doc/en/warnings.rst +++ b/doc/en/warnings.rst @@ -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... -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 diff --git a/doc/en/xunit_setup.rst b/doc/en/xunit_setup.rst index 22a0e51d0..9a0ccf9b4 100644 --- a/doc/en/xunit_setup.rst +++ b/doc/en/xunit_setup.rst @@ -27,7 +27,7 @@ Module level setup/teardown If you have multiple test functions and test classes in a single 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 @@ -46,7 +46,7 @@ Class level setup/teardown ---------------------------------- 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 @@ -66,7 +66,7 @@ and after all test methods of the class are called:: 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 @@ -84,7 +84,7 @@ Similarly, the following methods are called around each method invocation:: As of pytest-3.0, the ``method`` parameter is optional. 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 From 23a0b532dbe72d6cb6ec923d9ce6f0a63a34fc28 Mon Sep 17 00:00:00 2001 From: boris Date: Tue, 6 Aug 2019 16:18:06 -0700 Subject: [PATCH 08/11] Revert "remove implicit code tags .replace("::\n\n.. code-block", "\n\n.. code-block")" This reverts commit 9fce0bdd88c425aa7b98dc4cc0c2696c19fdbd95. --- doc/en/builtin.rst | 2 +- doc/en/cache.rst | 4 ++-- doc/en/capture.rst | 2 +- doc/en/deprecations.rst | 2 +- doc/en/doctest.rst | 6 ++--- doc/en/example/parametrize.rst | 32 +++++++++++++-------------- doc/en/example/pythoncollection.rst | 10 ++++----- doc/en/example/special.rst | 4 ++-- doc/en/existingtestsuite.rst | 2 +- doc/en/fixture.rst | 34 ++++++++++++++--------------- doc/en/funcarg_compare.rst | 12 +++++----- doc/en/getting-started.rst | 8 +++---- doc/en/goodpractices.rst | 14 ++++++------ doc/en/logging.rst | 14 ++++++------ doc/en/plugins.rst | 6 ++--- doc/en/pythonpath.rst | 4 ++-- doc/en/reference.rst | 2 +- doc/en/skipping.rst | 6 ++--- doc/en/tmpdir.rst | 2 +- doc/en/unittest.rst | 8 +++---- doc/en/usage.rst | 6 ++--- doc/en/warnings.rst | 2 +- doc/en/xunit_setup.rst | 8 +++---- 23 files changed, 95 insertions(+), 95 deletions(-) diff --git a/doc/en/builtin.rst b/doc/en/builtin.rst index 68c23ebef..c4a6c0c2a 100644 --- a/doc/en/builtin.rst +++ b/doc/en/builtin.rst @@ -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 -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 diff --git a/doc/en/cache.rst b/doc/en/cache.rst index 501ccd810..a4bc3be5c 100644 --- a/doc/en/cache.rst +++ b/doc/en/cache.rst @@ -33,7 +33,7 @@ Other plugins may access the `config.cache`_ object to set/get 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 @@ -186,7 +186,7 @@ The new config.cache object Plugins or conftest.py support code can get a cached value using the pytest ``config`` object. Here is a basic example plugin which implements a :ref:`fixture` which re-uses previously created state -across pytest invocations +across pytest invocations:: .. code-block:: python diff --git a/doc/en/capture.rst b/doc/en/capture.rst index c4b0a8d89..48b0226a4 100644 --- a/doc/en/capture.rst +++ b/doc/en/capture.rst @@ -49,7 +49,7 @@ Using print statements for debugging --------------------------------------------------- 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 diff --git a/doc/en/deprecations.rst b/doc/en/deprecations.rst index 92caee17b..d000dd6a1 100644 --- a/doc/en/deprecations.rst +++ b/doc/en/deprecations.rst @@ -455,7 +455,7 @@ Internal classes accessed through ``Node`` .. versionremoved:: 4.0 Access of ``Module``, ``Function``, ``Class``, ``Instance``, ``File`` and ``Item`` through ``Node`` instances now issue -this warning +this warning:: .. code-block:: text diff --git a/doc/en/doctest.rst b/doc/en/doctest.rst index 7b1f20d15..c11aaaaec 100644 --- a/doc/en/doctest.rst +++ b/doc/en/doctest.rst @@ -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. ``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 @@ -203,7 +203,7 @@ place the objects you want to appear in the doctest namespace def add_np(doctest_namespace): 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 @@ -225,7 +225,7 @@ Skipping tests dynamically .. 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 diff --git a/doc/en/example/parametrize.rst b/doc/en/example/parametrize.rst index 19a18bf3d..86cc2bf64 100644 --- a/doc/en/example/parametrize.rst +++ b/doc/en/example/parametrize.rst @@ -19,7 +19,7 @@ Generating parameters combinations, depending on command line Let's say we want to execute a test with different computation 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 @@ -29,7 +29,7 @@ line argument. Let's first write a simple (do-nothing) computation test def test_compute(param1): assert param1 < 4 -Now we add a test configuration like this +Now we add a test configuration like this:: .. 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 used in the test ID. For other objects, pytest will make a string based on -the argument name +the argument name:: .. code-block:: python @@ -185,7 +185,7 @@ A quick port of "testscenarios" Here is a quick port to run tests configured with `test scenarios`_, 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 -:py:func:`Metafunc.parametrize` +:py:func:`Metafunc.parametrize`:: .. 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 connections or subprocess only when the actual test is run. 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 @@ -279,7 +279,7 @@ the actual test requiring a ``db`` object We can now add a test configuration that generates two invocations of 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 @@ -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 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`` -will be passed to respective fixture function +will be passed to respective fixture function:: .. code-block:: python @@ -406,7 +406,7 @@ Parametrizing test methods through per-class configuration Here is an example ``pytest_generate_tests`` function implementing a 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 @@ -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 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) -need to provide similar results +need to provide similar results:: .. code-block:: python @@ -506,7 +506,7 @@ need to provide similar results def optmod(request): 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 @@ -514,7 +514,7 @@ And then a base implementation of a simple function def func1(): return 1 -And an optimized version +And an optimized version:: .. code-block:: python @@ -522,7 +522,7 @@ And an optimized version def func1(): return 1.0001 -And finally a little test module +And finally a little test module:: .. code-block:: python @@ -631,7 +631,7 @@ Use :func:`pytest.raises` with the 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 -as a complement to ``raises``. For example +as a complement to ``raises``. For example:: .. 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``. 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 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 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 diff --git a/doc/en/example/pythoncollection.rst b/doc/en/example/pythoncollection.rst index 63b5a4b29..729f35e17 100644 --- a/doc/en/example/pythoncollection.rst +++ b/doc/en/example/pythoncollection.rst @@ -131,7 +131,7 @@ Here is an example: This would make ``pytest`` look for tests in files that match the ``check_* .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 @@ -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 imported. Moreover, there may files only importable by a specific python 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 @@ -252,7 +252,7 @@ listing them in a ``conftest.py`` file if sys.version_info[0] > 2: 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 @@ -263,7 +263,7 @@ and then if you have a module file like this except Exception, e: pass -and a ``setup.py`` dummy file like this +and a ``setup.py`` dummy file like this:: .. code-block:: python @@ -304,7 +304,7 @@ patterns to ``collect_ignore_glob``. 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 -interpreter +interpreter:: .. code-block:: python diff --git a/doc/en/example/special.rst b/doc/en/example/special.rst index 28002fb03..d7f6ec2eb 100644 --- a/doc/en/example/special.rst +++ b/doc/en/example/special.rst @@ -5,7 +5,7 @@ A session-scoped fixture effectively has access to all collected test items. Here is an example of a fixture function which walks all collected tests and looks if their test class defines a ``callme`` method and -calls it +calls it:: .. code-block:: python @@ -27,7 +27,7 @@ calls it seen.add(cls) 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 diff --git a/doc/en/existingtestsuite.rst b/doc/en/existingtestsuite.rst index 8676baf76..956c970c2 100644 --- a/doc/en/existingtestsuite.rst +++ b/doc/en/existingtestsuite.rst @@ -15,7 +15,7 @@ Running an existing test suite with pytest Say you want to contribute to an existing repository somewhere. After pulling the code into your development space using some flavor of version control and (optionally) setting up a virtualenv -you will want to run +you will want to run:: .. code-block:: bash diff --git a/doc/en/fixture.rst b/doc/en/fixture.rst index 2bded9364..ddcb09b8c 100644 --- a/doc/en/fixture.rst +++ b/doc/en/fixture.rst @@ -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 :py:func:`@pytest.fixture <_pytest.python.fixture>`. Let's look at a simple self-contained test module containing a fixture and a test function -using it +using it:: .. 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 so that tests from multiple test modules in the directory can -access the fixture function +access the fixture function:: .. 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 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 -located) +located):: .. code-block:: python @@ -489,7 +489,7 @@ Fixtures can introspect the requesting test context Fixture functions can accept the :py:class:`request ` object to introspect the "requesting" test function, class or module context. 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 @@ -518,7 +518,7 @@ again, nothing much has changed: 2 failed in 0.12 seconds 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 @@ -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. 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 @@ -575,7 +575,7 @@ Factories can have parameters as needed customer_2 = make_customer_record("Mike") 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 @@ -616,7 +616,7 @@ configured in multiple ways. Extending the previous example, we can flag the fixture to create two ``smtp_connection`` fixture instances which will cause all tests using the fixture to run twice. The fixture function gets access to each parameter -through the special :py:class:`request ` object +through the special :py:class:`request ` object:: .. 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 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 -``ids`` keyword argument +``ids`` keyword argument:: .. 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 that they can be used with :ref:`@pytest.mark.parametrize <@pytest.mark.parametrize>`. -Example +Example:: .. 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 many projects. As a simple example, we can extend the previous example and instantiate an object ``app`` where we stick the already defined -``smtp_connection`` resource into it +``smtp_connection`` resource into it:: .. 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 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 @@ -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 `_ and pytest fixtures to achieve it. We separate the creation of the fixture into a conftest.py -file +file:: .. code-block:: python @@ -1015,7 +1015,7 @@ file newpath = tempfile.mkdtemp() 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 @@ -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 begin/rollback/commit architecture and we want to automatically surround 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 @@ -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 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 -into a conftest.py file **without** using ``autouse`` +into a conftest.py file **without** using ``autouse``:: .. code-block:: python @@ -1186,7 +1186,7 @@ into a conftest.py file **without** using ``autouse`` yield 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 diff --git a/doc/en/funcarg_compare.rst b/doc/en/funcarg_compare.rst index d802dd585..2f6e7a1ec 100644 --- a/doc/en/funcarg_compare.rst +++ b/doc/en/funcarg_compare.rst @@ -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 the ``request.cached_setup()`` helper to manage caching of resources. Here is a basic example how we could implement -a per-session Database object +a per-session Database object:: .. 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 :ref:`@pytest.fixture ` decorator and directly state -the scope +the scope:: .. 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 or implement a ``pytest_generate_tests`` hook to perform 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 @@ -115,7 +115,7 @@ allow to re-use already written factories because effectively parametrized via :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 @@ -138,7 +138,7 @@ No ``pytest_funcarg__`` prefix when using @fixture decorator When using the ``@fixture`` decorator the name of the function denotes the name under which the resource can be accessed as a function -argument +argument:: .. code-block:: python @@ -149,7 +149,7 @@ argument 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 -aka +aka:: .. code-block:: python diff --git a/doc/en/getting-started.rst b/doc/en/getting-started.rst index ca62a9667..808ffcc64 100644 --- a/doc/en/getting-started.rst +++ b/doc/en/getting-started.rst @@ -35,7 +35,7 @@ Install ``pytest`` 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 @@ -86,7 +86,7 @@ Run multiple tests Assert that a certain exception is raised -------------------------------------------------------------- -Use the :ref:`raises ` helper to assert that some code raises an exception +Use the :ref:`raises ` helper to assert that some code raises an exception:: .. code-block:: python @@ -113,7 +113,7 @@ Execute the test function with “quiet” reporting mode: 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 @@ -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 -------------------------------------------------------------- -``pytest`` provides `Builtin fixtures/function arguments `_ to request arbitrary resources, like a unique temporary directory +``pytest`` provides `Builtin fixtures/function arguments `_ to request arbitrary resources, like a unique temporary directory:: .. code-block:: python diff --git a/doc/en/goodpractices.rst b/doc/en/goodpractices.rst index 61f18b555..065308c14 100644 --- a/doc/en/goodpractices.rst +++ b/doc/en/goodpractices.rst @@ -12,7 +12,7 @@ pip_ for installing your application and any dependencies, as well as the ``pytest`` package itself. 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 @@ -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()) -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 @@ -64,7 +64,7 @@ Tests outside 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 -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 @@ -98,7 +98,7 @@ be imported as ``test_app`` and ``test_view`` top-level modules by adding ``test ``sys.path``. 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 @@ -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. 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 @@ -150,7 +150,7 @@ Tests as part of application code Inlining test directories into your application package 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 @@ -165,7 +165,7 @@ want to distribute them along with your application 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 diff --git a/doc/en/logging.rst b/doc/en/logging.rst index 54edee38d..888254a85 100644 --- a/doc/en/logging.rst +++ b/doc/en/logging.rst @@ -70,7 +70,7 @@ caplog fixture ^^^^^^^^^^^^^^ 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 @@ -80,7 +80,7 @@ messages. This is supported by the ``caplog`` fixture 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 -logger +logger:: .. code-block:: python @@ -91,7 +91,7 @@ logger 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 -level inside a ``with`` block +level inside a ``with`` block:: .. code-block:: python @@ -100,7 +100,7 @@ level inside a ``with`` block pass 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 @@ -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 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 @@ -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, that certain messages have been logged under a given logger name with a given -severity and message +severity and message:: .. code-block:: python @@ -134,7 +134,7 @@ severity and message 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 diff --git a/doc/en/plugins.rst b/doc/en/plugins.rst index 1d5422364..1168d3aad 100644 --- a/doc/en/plugins.rst +++ b/doc/en/plugins.rst @@ -8,7 +8,7 @@ Installing and Using plugins This section talks about installing and using third party 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 @@ -97,7 +97,7 @@ Finding out which plugins are active ------------------------------------ If you want to find out which plugins are active in your -environment you can type +environment you can type:: .. code-block:: bash @@ -112,7 +112,7 @@ and their names. It will also print local plugins aka 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 diff --git a/doc/en/pythonpath.rst b/doc/en/pythonpath.rst index 796b12b0b..498dd3360 100644 --- a/doc/en/pythonpath.rst +++ b/doc/en/pythonpath.rst @@ -22,7 +22,7 @@ Consider this file and directory layout:: |- test_foo.py -When executing +When executing:: .. code-block:: bash @@ -56,7 +56,7 @@ Consider this file and directory layout:: |- test_foo.py -When executing +When executing:: .. code-block:: bash diff --git a/doc/en/reference.rst b/doc/en/reference.rst index a39c6d4f6..173090cec 100644 --- a/doc/en/reference.rst +++ b/doc/en/reference.rst @@ -469,7 +469,7 @@ testdir This fixture provides a :class:`Testdir` instance useful for black-box testing of test files, making it ideal to 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 diff --git a/doc/en/skipping.rst b/doc/en/skipping.rst index 0ded839ae..f9b6ed0f6 100644 --- a/doc/en/skipping.rst +++ b/doc/en/skipping.rst @@ -180,7 +180,7 @@ Skipping on a missing import dependency ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 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 @@ -188,7 +188,7 @@ or within a test or test setup function If ``docutils`` cannot be imported here, this will lead to a 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 @@ -227,7 +227,7 @@ XFail: mark test functions as expected to fail ---------------------------------------------- You can use the ``xfail`` marker to indicate that you -expect a test to fail +expect a test to fail:: .. code-block:: python diff --git a/doc/en/tmpdir.rst b/doc/en/tmpdir.rst index b0ecfaab7..a4747f3a2 100644 --- a/doc/en/tmpdir.rst +++ b/doc/en/tmpdir.rst @@ -90,7 +90,7 @@ provide a temporary directory unique to the test invocation, created in the `base temporary directory`_. ``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 diff --git a/doc/en/unittest.rst b/doc/en/unittest.rst index af0da0923..e5253af69 100644 --- a/doc/en/unittest.rst +++ b/doc/en/unittest.rst @@ -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 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 @@ -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, let's jump-start into an example that integrates a pytest ``db_class`` 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 @@ -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 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 -fixture definition +fixture definition:: .. 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 pre-initialized ``samplefile.ini``. Our ``initdir`` fixture itself uses the pytest builtin :ref:`tmpdir ` fixture to delegate the -creation of a per-test temporary directory +creation of a per-test temporary directory:: .. code-block:: python diff --git a/doc/en/usage.rst b/doc/en/usage.rst index d69397f8f..eb04b6220 100644 --- a/doc/en/usage.rst +++ b/doc/en/usage.rst @@ -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 @@ -762,13 +762,13 @@ You can invoke ``pytest`` from Python code directly this acts as if you would call "pytest" from the command line. 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 pytest.main(["-x", "mytestdir"]) -You can specify additional plugins to ``pytest.main`` +You can specify additional plugins to ``pytest.main``:: .. code-block:: python diff --git a/doc/en/warnings.rst b/doc/en/warnings.rst index 201e41e03..40d9230b3 100644 --- a/doc/en/warnings.rst +++ b/doc/en/warnings.rst @@ -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... -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 diff --git a/doc/en/xunit_setup.rst b/doc/en/xunit_setup.rst index 9a0ccf9b4..22a0e51d0 100644 --- a/doc/en/xunit_setup.rst +++ b/doc/en/xunit_setup.rst @@ -27,7 +27,7 @@ Module level setup/teardown If you have multiple test functions and test classes in a single 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 @@ -46,7 +46,7 @@ Class level setup/teardown ---------------------------------- 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 @@ -66,7 +66,7 @@ and after all test methods of the class are called 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 @@ -84,7 +84,7 @@ Similarly, the following methods are called around each method invocation As of pytest-3.0, the ``method`` parameter is optional. 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 From 78de9d4677ce99186b685e5c54accf84d19a3028 Mon Sep 17 00:00:00 2001 From: boris Date: Tue, 6 Aug 2019 16:20:06 -0700 Subject: [PATCH 09/11] replace implicit code tag with colon .replace("::\n\n.. code-block", ":\n\n.. code-block") --- doc/en/builtin.rst | 2 +- doc/en/cache.rst | 4 ++-- doc/en/capture.rst | 2 +- doc/en/deprecations.rst | 2 +- doc/en/doctest.rst | 6 ++--- doc/en/example/parametrize.rst | 32 +++++++++++++-------------- doc/en/example/pythoncollection.rst | 10 ++++----- doc/en/example/special.rst | 4 ++-- doc/en/existingtestsuite.rst | 2 +- doc/en/fixture.rst | 34 ++++++++++++++--------------- doc/en/funcarg_compare.rst | 12 +++++----- doc/en/getting-started.rst | 8 +++---- doc/en/goodpractices.rst | 14 ++++++------ doc/en/logging.rst | 14 ++++++------ doc/en/plugins.rst | 6 ++--- doc/en/pythonpath.rst | 4 ++-- doc/en/reference.rst | 2 +- doc/en/skipping.rst | 6 ++--- doc/en/tmpdir.rst | 2 +- doc/en/unittest.rst | 8 +++---- doc/en/usage.rst | 6 ++--- doc/en/warnings.rst | 2 +- doc/en/xunit_setup.rst | 8 +++---- 23 files changed, 95 insertions(+), 95 deletions(-) diff --git a/doc/en/builtin.rst b/doc/en/builtin.rst index c4a6c0c2a..4309a16ea 100644 --- a/doc/en/builtin.rst +++ b/doc/en/builtin.rst @@ -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 -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 diff --git a/doc/en/cache.rst b/doc/en/cache.rst index a4bc3be5c..84b3fa009 100644 --- a/doc/en/cache.rst +++ b/doc/en/cache.rst @@ -33,7 +33,7 @@ Other plugins may access the `config.cache`_ object to set/get 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 @@ -186,7 +186,7 @@ The new config.cache object Plugins or conftest.py support code can get a cached value using the pytest ``config`` object. Here is a basic example plugin which implements a :ref:`fixture` which re-uses previously created state -across pytest invocations:: +across pytest invocations: .. code-block:: python diff --git a/doc/en/capture.rst b/doc/en/capture.rst index 48b0226a4..356da2678 100644 --- a/doc/en/capture.rst +++ b/doc/en/capture.rst @@ -49,7 +49,7 @@ Using print statements for debugging --------------------------------------------------- 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 diff --git a/doc/en/deprecations.rst b/doc/en/deprecations.rst index d000dd6a1..4c7170910 100644 --- a/doc/en/deprecations.rst +++ b/doc/en/deprecations.rst @@ -455,7 +455,7 @@ Internal classes accessed through ``Node`` .. versionremoved:: 4.0 Access of ``Module``, ``Function``, ``Class``, ``Instance``, ``File`` and ``Item`` through ``Node`` instances now issue -this warning:: +this warning: .. code-block:: text diff --git a/doc/en/doctest.rst b/doc/en/doctest.rst index c11aaaaec..ce23563ee 100644 --- a/doc/en/doctest.rst +++ b/doc/en/doctest.rst @@ -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. ``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 @@ -203,7 +203,7 @@ place the objects you want to appear in the doctest namespace:: def add_np(doctest_namespace): 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 @@ -225,7 +225,7 @@ Skipping tests dynamically .. 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 diff --git a/doc/en/example/parametrize.rst b/doc/en/example/parametrize.rst index 86cc2bf64..1e6d53e37 100644 --- a/doc/en/example/parametrize.rst +++ b/doc/en/example/parametrize.rst @@ -19,7 +19,7 @@ Generating parameters combinations, depending on command line Let's say we want to execute a test with different computation 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 @@ -29,7 +29,7 @@ line argument. Let's first write a simple (do-nothing) computation test:: def test_compute(param1): assert param1 < 4 -Now we add a test configuration like this:: +Now we add a test configuration like this: .. 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 used in the test ID. For other objects, pytest will make a string based on -the argument name:: +the argument name: .. code-block:: python @@ -185,7 +185,7 @@ A quick port of "testscenarios" Here is a quick port to run tests configured with `test scenarios`_, 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 -:py:func:`Metafunc.parametrize`:: +:py:func:`Metafunc.parametrize`: .. 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 connections or subprocess only when the actual test is run. 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 @@ -279,7 +279,7 @@ the actual test requiring a ``db`` object:: We can now add a test configuration that generates two invocations of 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 @@ -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 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`` -will be passed to respective fixture function:: +will be passed to respective fixture function: .. code-block:: python @@ -406,7 +406,7 @@ Parametrizing test methods through per-class configuration Here is an example ``pytest_generate_tests`` function implementing a 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 @@ -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 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) -need to provide similar results:: +need to provide similar results: .. code-block:: python @@ -506,7 +506,7 @@ need to provide similar results:: def optmod(request): 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 @@ -514,7 +514,7 @@ And then a base implementation of a simple function:: def func1(): return 1 -And an optimized version:: +And an optimized version: .. code-block:: python @@ -522,7 +522,7 @@ And an optimized version:: def func1(): return 1.0001 -And finally a little test module:: +And finally a little test module: .. code-block:: python @@ -631,7 +631,7 @@ Use :func:`pytest.raises` with the 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 -as a complement to ``raises``. For example:: +as a complement to ``raises``. For example: .. 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``. 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 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 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 diff --git a/doc/en/example/pythoncollection.rst b/doc/en/example/pythoncollection.rst index 729f35e17..4fd0cb645 100644 --- a/doc/en/example/pythoncollection.rst +++ b/doc/en/example/pythoncollection.rst @@ -131,7 +131,7 @@ Here is an example: This would make ``pytest`` look for tests in files that match the ``check_* .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 @@ -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 imported. Moreover, there may files only importable by a specific python 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 @@ -252,7 +252,7 @@ listing them in a ``conftest.py`` file:: if sys.version_info[0] > 2: 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 @@ -263,7 +263,7 @@ and then if you have a module file like this:: except Exception, e: pass -and a ``setup.py`` dummy file like this:: +and a ``setup.py`` dummy file like this: .. code-block:: python @@ -304,7 +304,7 @@ patterns to ``collect_ignore_glob``. 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 -interpreter:: +interpreter: .. code-block:: python diff --git a/doc/en/example/special.rst b/doc/en/example/special.rst index d7f6ec2eb..5161c43ab 100644 --- a/doc/en/example/special.rst +++ b/doc/en/example/special.rst @@ -5,7 +5,7 @@ A session-scoped fixture effectively has access to all collected test items. Here is an example of a fixture function which walks all collected tests and looks if their test class defines a ``callme`` method and -calls it:: +calls it: .. code-block:: python @@ -27,7 +27,7 @@ calls it:: seen.add(cls) 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 diff --git a/doc/en/existingtestsuite.rst b/doc/en/existingtestsuite.rst index 956c970c2..cda38918c 100644 --- a/doc/en/existingtestsuite.rst +++ b/doc/en/existingtestsuite.rst @@ -15,7 +15,7 @@ Running an existing test suite with pytest Say you want to contribute to an existing repository somewhere. After pulling the code into your development space using some flavor of version control and (optionally) setting up a virtualenv -you will want to run:: +you will want to run: .. code-block:: bash diff --git a/doc/en/fixture.rst b/doc/en/fixture.rst index ddcb09b8c..ea5e2dc86 100644 --- a/doc/en/fixture.rst +++ b/doc/en/fixture.rst @@ -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 :py:func:`@pytest.fixture <_pytest.python.fixture>`. Let's look at a simple self-contained test module containing a fixture and a test function -using it:: +using it: .. 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 so that tests from multiple test modules in the directory can -access the fixture function:: +access the fixture function: .. 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 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 -located):: +located): .. code-block:: python @@ -489,7 +489,7 @@ Fixtures can introspect the requesting test context Fixture functions can accept the :py:class:`request ` object to introspect the "requesting" test function, class or module context. 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 @@ -518,7 +518,7 @@ again, nothing much has changed: 2 failed in 0.12 seconds 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 @@ -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. 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 @@ -575,7 +575,7 @@ Factories can have parameters as needed:: customer_2 = make_customer_record("Mike") 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 @@ -616,7 +616,7 @@ configured in multiple ways. Extending the previous example, we can flag the fixture to create two ``smtp_connection`` fixture instances which will cause all tests using the fixture to run twice. The fixture function gets access to each parameter -through the special :py:class:`request ` object:: +through the special :py:class:`request ` object: .. 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 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 -``ids`` keyword argument:: +``ids`` keyword argument: .. 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 that they can be used with :ref:`@pytest.mark.parametrize <@pytest.mark.parametrize>`. -Example:: +Example: .. 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 many projects. As a simple example, we can extend the previous example and instantiate an object ``app`` where we stick the already defined -``smtp_connection`` resource into it:: +``smtp_connection`` resource into it: .. 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 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 @@ -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 `_ and pytest fixtures to achieve it. We separate the creation of the fixture into a conftest.py -file:: +file: .. code-block:: python @@ -1015,7 +1015,7 @@ file:: newpath = tempfile.mkdtemp() 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 @@ -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 begin/rollback/commit architecture and we want to automatically surround 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 @@ -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 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 -into a conftest.py file **without** using ``autouse``:: +into a conftest.py file **without** using ``autouse``: .. code-block:: python @@ -1186,7 +1186,7 @@ into a conftest.py file **without** using ``autouse``:: yield 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 diff --git a/doc/en/funcarg_compare.rst b/doc/en/funcarg_compare.rst index 2f6e7a1ec..af7030165 100644 --- a/doc/en/funcarg_compare.rst +++ b/doc/en/funcarg_compare.rst @@ -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 the ``request.cached_setup()`` helper to manage caching of resources. Here is a basic example how we could implement -a per-session Database object:: +a per-session Database object: .. 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 :ref:`@pytest.fixture ` decorator and directly state -the scope:: +the scope: .. 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 or implement a ``pytest_generate_tests`` hook to perform 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 @@ -115,7 +115,7 @@ allow to re-use already written factories because effectively parametrized via :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 @@ -138,7 +138,7 @@ No ``pytest_funcarg__`` prefix when using @fixture decorator When using the ``@fixture`` decorator the name of the function denotes the name under which the resource can be accessed as a function -argument:: +argument: .. code-block:: python @@ -149,7 +149,7 @@ argument:: 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 -aka:: +aka: .. code-block:: python diff --git a/doc/en/getting-started.rst b/doc/en/getting-started.rst index 808ffcc64..149bd33f1 100644 --- a/doc/en/getting-started.rst +++ b/doc/en/getting-started.rst @@ -35,7 +35,7 @@ Install ``pytest`` 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 @@ -86,7 +86,7 @@ Run multiple tests Assert that a certain exception is raised -------------------------------------------------------------- -Use the :ref:`raises ` helper to assert that some code raises an exception:: +Use the :ref:`raises ` helper to assert that some code raises an exception: .. code-block:: python @@ -113,7 +113,7 @@ Execute the test function with “quiet” reporting mode: 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 @@ -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 -------------------------------------------------------------- -``pytest`` provides `Builtin fixtures/function arguments `_ to request arbitrary resources, like a unique temporary directory:: +``pytest`` provides `Builtin fixtures/function arguments `_ to request arbitrary resources, like a unique temporary directory: .. code-block:: python diff --git a/doc/en/goodpractices.rst b/doc/en/goodpractices.rst index 065308c14..0aa0dc97c 100644 --- a/doc/en/goodpractices.rst +++ b/doc/en/goodpractices.rst @@ -12,7 +12,7 @@ pip_ for installing your application and any dependencies, as well as the ``pytest`` package itself. 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 @@ -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()) -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 @@ -64,7 +64,7 @@ Tests outside 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 -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 @@ -98,7 +98,7 @@ be imported as ``test_app`` and ``test_view`` top-level modules by adding ``test ``sys.path``. 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 @@ -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. 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 @@ -150,7 +150,7 @@ Tests as part of application code Inlining test directories into your application package 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 @@ -165,7 +165,7 @@ want to distribute them along with your application:: 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 diff --git a/doc/en/logging.rst b/doc/en/logging.rst index 888254a85..c32205f13 100644 --- a/doc/en/logging.rst +++ b/doc/en/logging.rst @@ -70,7 +70,7 @@ caplog fixture ^^^^^^^^^^^^^^ 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 @@ -80,7 +80,7 @@ messages. This is supported by the ``caplog`` fixture:: 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 -logger:: +logger: .. code-block:: python @@ -91,7 +91,7 @@ logger:: 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 -level inside a ``with`` block:: +level inside a ``with`` block: .. code-block:: python @@ -100,7 +100,7 @@ level inside a ``with`` block:: pass 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 @@ -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 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 @@ -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, that certain messages have been logged under a given logger name with a given -severity and message:: +severity and message: .. code-block:: python @@ -134,7 +134,7 @@ severity and message:: 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 diff --git a/doc/en/plugins.rst b/doc/en/plugins.rst index 1168d3aad..4443dafd4 100644 --- a/doc/en/plugins.rst +++ b/doc/en/plugins.rst @@ -8,7 +8,7 @@ Installing and Using plugins This section talks about installing and using third party 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 @@ -97,7 +97,7 @@ Finding out which plugins are active ------------------------------------ If you want to find out which plugins are active in your -environment you can type:: +environment you can type: .. code-block:: bash @@ -112,7 +112,7 @@ and their names. It will also print local plugins aka 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 diff --git a/doc/en/pythonpath.rst b/doc/en/pythonpath.rst index 498dd3360..113c95c30 100644 --- a/doc/en/pythonpath.rst +++ b/doc/en/pythonpath.rst @@ -22,7 +22,7 @@ Consider this file and directory layout:: |- test_foo.py -When executing:: +When executing: .. code-block:: bash @@ -56,7 +56,7 @@ Consider this file and directory layout:: |- test_foo.py -When executing:: +When executing: .. code-block:: bash diff --git a/doc/en/reference.rst b/doc/en/reference.rst index 173090cec..7e47ffce0 100644 --- a/doc/en/reference.rst +++ b/doc/en/reference.rst @@ -469,7 +469,7 @@ testdir This fixture provides a :class:`Testdir` instance useful for black-box testing of test files, making it ideal to 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 diff --git a/doc/en/skipping.rst b/doc/en/skipping.rst index f9b6ed0f6..eb00a6dfb 100644 --- a/doc/en/skipping.rst +++ b/doc/en/skipping.rst @@ -180,7 +180,7 @@ Skipping on a missing import dependency ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 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 @@ -188,7 +188,7 @@ or within a test or test setup function:: If ``docutils`` cannot be imported here, this will lead to a 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 @@ -227,7 +227,7 @@ XFail: mark test functions as expected to fail ---------------------------------------------- You can use the ``xfail`` marker to indicate that you -expect a test to fail:: +expect a test to fail: .. code-block:: python diff --git a/doc/en/tmpdir.rst b/doc/en/tmpdir.rst index a4747f3a2..1b565cee8 100644 --- a/doc/en/tmpdir.rst +++ b/doc/en/tmpdir.rst @@ -90,7 +90,7 @@ provide a temporary directory unique to the test invocation, created in the `base temporary directory`_. ``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 diff --git a/doc/en/unittest.rst b/doc/en/unittest.rst index e5253af69..18b6a721b 100644 --- a/doc/en/unittest.rst +++ b/doc/en/unittest.rst @@ -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 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 @@ -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, let's jump-start into an example that integrates a pytest ``db_class`` 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 @@ -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 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 -fixture definition:: +fixture definition: .. 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 pre-initialized ``samplefile.ini``. Our ``initdir`` fixture itself uses the pytest builtin :ref:`tmpdir ` fixture to delegate the -creation of a per-test temporary directory:: +creation of a per-test temporary directory: .. code-block:: python diff --git a/doc/en/usage.rst b/doc/en/usage.rst index eb04b6220..d5ff8a984 100644 --- a/doc/en/usage.rst +++ b/doc/en/usage.rst @@ -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 @@ -762,13 +762,13 @@ You can invoke ``pytest`` from Python code directly:: this acts as if you would call "pytest" from the command line. 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 pytest.main(["-x", "mytestdir"]) -You can specify additional plugins to ``pytest.main``:: +You can specify additional plugins to ``pytest.main``: .. code-block:: python diff --git a/doc/en/warnings.rst b/doc/en/warnings.rst index 40d9230b3..398380ea5 100644 --- a/doc/en/warnings.rst +++ b/doc/en/warnings.rst @@ -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... -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 diff --git a/doc/en/xunit_setup.rst b/doc/en/xunit_setup.rst index 22a0e51d0..83545223a 100644 --- a/doc/en/xunit_setup.rst +++ b/doc/en/xunit_setup.rst @@ -27,7 +27,7 @@ Module level setup/teardown If you have multiple test functions and test classes in a single 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 @@ -46,7 +46,7 @@ Class level setup/teardown ---------------------------------- 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 @@ -66,7 +66,7 @@ and after all test methods of the class are called:: 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 @@ -84,7 +84,7 @@ Similarly, the following methods are called around each method invocation:: As of pytest-3.0, the ``method`` parameter is optional. 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 From 7560a7b8088f598c11f410478e7f5bf88f68fb56 Mon Sep 17 00:00:00 2001 From: boris Date: Wed, 7 Aug 2019 21:49:30 -0600 Subject: [PATCH 10/11] trivial doc change --- doc/en/example/pythoncollection.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc/en/example/pythoncollection.rst b/doc/en/example/pythoncollection.rst index 4fd0cb645..cd4e34352 100644 --- a/doc/en/example/pythoncollection.rst +++ b/doc/en/example/pythoncollection.rst @@ -31,7 +31,7 @@ you will see that ``pytest`` only collects test-modules, which do not match the .. code-block:: pytest =========================== test session starts ============================ - platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y + platform linux -- Python 3.x.y, pytest-5.x.y, py-1.x.y, pluggy-0.x.y rootdir: $REGENDOC_TMPDIR, inifile: collected 5 items From 0a19439677bb5ce509200818de7a7bc34795d0c6 Mon Sep 17 00:00:00 2001 From: Florian Bruhin Date: Thu, 8 Aug 2019 14:01:29 +0200 Subject: [PATCH 11/11] Add a code of conduct See #5709 and the mails linked from there --- CODE_OF_CONDUCT.md | 84 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 84 insertions(+) create mode 100644 CODE_OF_CONDUCT.md diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 000000000..72c7ff8c6 --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,84 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +In the interest of fostering an open and welcoming environment, we as +contributors and maintainers pledge to making participation in our project and +our community a harassment-free experience for everyone, regardless of age, body +size, disability, ethnicity, sex characteristics, gender identity and expression, +level of experience, education, socio-economic status, nationality, personal +appearance, race, religion, or sexual identity and orientation. + +## Our Standards + +Examples of behavior that contributes to creating a positive environment +include: + +* Using welcoming and inclusive language +* Being respectful of differing viewpoints and experiences +* Gracefully accepting constructive criticism +* Focusing on what is best for the community +* Showing empathy towards other community members + +Examples of unacceptable behavior by participants include: + +* The use of sexualized language or imagery and unwelcome sexual attention or + advances +* Trolling, insulting/derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or electronic + address, without explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Our Responsibilities + +Project maintainers are responsible for clarifying the standards of acceptable +behavior and are expected to take appropriate and fair corrective action in +response to any instances of unacceptable behavior. + +Project maintainers have the right and responsibility to remove, edit, or +reject comments, commits, code, wiki edits, issues, and other contributions +that are not aligned to this Code of Conduct, or to ban temporarily or +permanently any contributor for other behaviors that they deem inappropriate, +threatening, offensive, or harmful. + +## Scope + +This Code of Conduct applies both within project spaces and in public spaces +when an individual is representing the project or its community. Examples of +representing a project or community include using an official project e-mail +address, posting via an official social media account, or acting as an appointed +representative at an online or offline event. Representation of a project may be +further defined and clarified by project maintainers. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported by contacting the project team at coc@pytest.org. All +complaints will be reviewed and investigated and will result in a response that +is deemed necessary and appropriate to the circumstances. The project team is +obligated to maintain confidentiality with regard to the reporter of an incident. +Further details of specific enforcement policies may be posted separately. + +Project maintainers who do not follow or enforce the Code of Conduct in good +faith may face temporary or permanent repercussions as determined by other +members of the project's leadership. + +The coc@pytest.org address is routed to the following people who can also be +contacted individually: + +- Brianna Laugher ([@pfctdayelise](https://github.com/pfctdayelise)): brianna@laugher.id.au +- Bruno Oliveira ([@nicoddemus](https://github.com/nicoddemus)): nicoddemus@gmail.com +- Florian Bruhin ([@the-compiler](https://github.com/the-compiler)): pytest@the-compiler.org +- Ronny Pfannschmidt ([@RonnyPfannschmidt](https://github.com/RonnyPfannschmidt)): ich@ronnypfannschmidt.de + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, +available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html + +[homepage]: https://www.contributor-covenant.org + +For answers to common questions about this code of conduct, see +https://www.contributor-covenant.org/faq