Search code examples
pythonpytestflake8

How can i resolve flake8 "unused import" error for pytest fixture imported from another module


I wrote pytest fixture in fixtures.py file and using it in my main_test.py . But I am getting this error in flake8: F401 'utils_test.backup_path' imported but unused for this code:

@pytest.fixture
def backup_path():
    ...
from fixtures import backup_path


def test_filename(backup_path):
    ...

How can I resolve this?


Solution

  • generally you should not do this

    making fixtures available via import side-effects is an unintentional implementation detail of how fixtures work and may break in the future of pytest

    if you want to continue doing so, you can use # noqa: F403 on the import, telling flake8 to ignore the unused imports (though the linter is telling you the right thing here!)

    the supported way to make reusable fixtures is to place them in a conftest.py which is in a directory above all the tests that need it. tests will have these fixtures "in scope" automatically

    if that file is getting too large, you can write your fixtures in a plugin module and add that plugin module via pytest_plugins = ['module.name'] in your conftest.py


    disclaimer: I'm the current flake8 maintainer, I'm also a pytest core dev