PyTest fails on a directory with multiple test files when modularizing fixtures
You use the fixtures slightly improperly.
Specifically, you declare multiple fixtures of the same name and with the same function-object, but detected at different modules. From the pytest point of view, these should be the separate functions, because pytest does dir(module)
to detect the tests & fixtures in the file. But somehow due to the same function-object, I think, pytest remembers them as the same; so once you get to the second test file, it tries the locally detected fixture name, but finds it already prepared and fails.
The proper use would be to create a pseudo-plugin conftest.py
, and put all the fixtures there. Once declared, these fixtures will be available to all files in that dir and all sub-dirs.
Note: such fixtures must NOT be imported into the test files. The fixtures are NOT the functions. Pytest automatically prepares them and feeds them to the tests.
# tests/conftest.pyimport pytestfrom flask_app import create_app@pytest.fixtures(scope="session")def app(request): app = create_app() with app.app_context(): yield app@pytest.fixture(scope="session"):def client(request, app): client = app.test_client() return client
And the test files (note the absence of the imports!):
# tests/test_1.pydef test_1(client): # test body# tests/test_2.pydef test_2(client): # test body
See more: https://docs.pytest.org/en/latest/writing_plugins.html
If you are using an application instance then this will work for you:
import osimport tempfileimport pytestfrom my_app import app, db@pytest.fixturedef client(): db_fd, app.config["DATABASE"] = tempfile.mkstemp() app.config["TESTING"] = True with app.app_context(): db.init_app(app) yield app os.close(db_fd) os.unlink(app.config["DATABASE"])@pytest.fixturedef client(request): client = app.test_client() return client