From e36d5c05c69c6ba82d4a5517389493a614137939 Mon Sep 17 00:00:00 2001 From: Florian Bruhin Date: Wed, 10 Jun 2020 13:08:27 +0200 Subject: [PATCH] doc: Explain indirect parametrization and markers for fixtures --- changelog/7345.doc.rst | 1 + doc/en/example/parametrize.rst | 24 ++++++++++++++++++++++++ doc/en/fixture.rst | 31 +++++++++++++++++++++++++++++++ 3 files changed, 56 insertions(+) create mode 100644 changelog/7345.doc.rst diff --git a/changelog/7345.doc.rst b/changelog/7345.doc.rst new file mode 100644 index 0000000000..4c7234f414 --- /dev/null +++ b/changelog/7345.doc.rst @@ -0,0 +1 @@ +Explain indirect parametrization and markers for fixtures diff --git a/doc/en/example/parametrize.rst b/doc/en/example/parametrize.rst index 9500af0d34..0b61a19bc9 100644 --- a/doc/en/example/parametrize.rst +++ b/doc/en/example/parametrize.rst @@ -351,6 +351,30 @@ And then when we run the test: The first invocation with ``db == "DB1"`` passed while the second with ``db == "DB2"`` failed. Our ``db`` fixture function has instantiated each of the DB values during the setup phase while the ``pytest_generate_tests`` generated two according calls to the ``test_db_initialized`` during the collection phase. +Indirect parametrization +--------------------------------------------------- + +Using the ``indirect=True`` parameter when parametrizing a test allows to +parametrize a test with a fixture receiving the values before passing them to a +test: + +.. code-block:: python + + import pytest + + + @pytest.fixture + def fixt(request): + return request.param * 3 + + + @pytest.mark.parametrize("fixt", ["a", "b"], indirect=True) + def test_indirect(fixt): + assert len(fixt) == 3 + +This can be used, for example, to do more expensive setup at test run time in +the fixture, rather than having to run those setup steps at collection time. + .. regendoc:wipe Apply indirect on particular arguments diff --git a/doc/en/fixture.rst b/doc/en/fixture.rst index 925a4b5598..b529996ede 100644 --- a/doc/en/fixture.rst +++ b/doc/en/fixture.rst @@ -665,6 +665,37 @@ Running it: voila! The ``smtp_connection`` fixture function picked up our mail server name from the module namespace. +.. _`using-markers`: + +Using markers to pass data to fixtures +------------------------------------------------------------- + +Using the :py:class:`request ` object, a fixture can also access +markers which are applied to a test function. This can be useful to pass data +into a fixture from a test: + +.. code-block:: python + + import pytest + + + @pytest.fixture + def fixt(request): + marker = request.node.get_closest_marker("fixt_data") + if marker is None: + # Handle missing marker in some way... + data = None + else: + data = marker.args[0] + + # Do something with the data + return data + + + @pytest.mark.fixt_data(42) + def test_fixt(fixt): + assert fixt == 42 + .. _`fixture-factory`: Factories as fixtures