The OP’s requirement was for setup and teardown each to execute only once, not one time per module. This can be accomplished with a combination of a conftest.py
file, @pytest.fixture(scope="session")
and passing the fixture name to each test function.
These are described in the Pytest fixtures documentation
Here’s an example:
conftest.py
import pytest
@pytest.fixture(scope="session")
def my_setup(request):
print '\nDoing setup'
def fin():
print ("\nDoing teardown")
request.addfinalizer(fin)
test_something.py
def test_dummy(my_setup):
print '\ntest_dummy'
test_something2.py
def test_dummy2(my_setup):
print '\ntest_dummy2'
def test_dummy3(my_setup):
print '\ntest_dummy3'
The output when you run py.test -s:
collected 3 items
test_something.py
Doing setup
test_dummy
.
test_something2.py
test_dummy2
.
test_dummy3
.
Doing teardown
The name conftest.py
matters: you can’t give this file a different name and expect Pytest to find it as a source of fixtures.
Setting scope="session"
is important. Otherwise setup and teardown will be repeated for each test module.
If you’d prefer not to pass the fixture name my_setup as an argument to each test function, you can place test functions inside a class and apply the pytest.mark.usefixtures
decorator to the class.