[TIP] get fixtures for each parameter or global variables?

holger krekel holger at merlinux.eu
Sat Oct 22 11:45:20 PDT 2016


On Sat, Oct 22, 2016 at 14:15 -0400, James wrote:
> On 2016-10-22 01:40 PM, holger krekel wrote:
> >
> >Here is how i would write the equivalent without any concept of global state:
> >
> >     # conftest.py
> >     def pytest_addoption(parser):
> >         parser.addoption("--A", action="store", default=None, help="a option")
> >         parser.addoption("--B", action="store", default=None, help="b option")
> >
> >     @pytest.fixture(scope="module")
> >     def a(pytestconfig):
> >         return pytestconfig.getoption("A", skip=True)
> >
> >     @pytest.fixture(scope="module")
> >     def b(pytestconfig):
> >         return pytestconfig.getoption("B", skip=True)
> >
> >     # testscript.py
> >     class TestAClass:
> >         def test_1(self, a, b, request):
> >             print 'inside {0}-{1} step'.format(
> >               self.__class__.__name__, request.function.__name__)
> >
> >             print 'a={0}, b={1}'.format(a, b)
> >
> >The test_1 function can simply use the "a" and "b" argument names in order to use the fixtures defined in the conftest.py file.  pytest was specifically designed to avoid global state. In fact, pytest keeps no global state whatsoever internally.
> >
> >holger
> If I have test_2, test_3, etc. that all take parameters a, b, is
> pytestconfig.getoption being called many times?

No, as long as test_2 and test_3 are residing in the same module.
a" and "b" fixtures have a caching scope of "module".  You can also use the scope "session" then test functions in different modules will all use the same "a" and "b" values, the respective fixture functions will only be called once per session.

holger



More information about the testing-in-python mailing list