0

Sometimes I use a pytest fixture defined in another module (probably because I want to re-use it in multiple places). As a minimal artificial example, the structure would be something like this:

mwe20.py:

def circle(pi, r):
    return pi*r**2

test_mwe20a.py:

import pytest
@pytest.fixture
def pi():
    return 3

test_mwe20b.py:

from test_mwe20a import pi


def test_circle(pi):
    from mwe20 import circle
    assert circle(pi, 2) == 12

This runs fine: pytest test_mwe20b.py will run one test, which will pass. However flake8 complains. Running flake8 test_mwe20b.py gives:

test_mwe20b.py:1:1: F401 'test_mwe20a.pi' imported but unused
test_mwe20b.py:4:17: F811 redefinition of unused 'pi' from line 1

I can of course add noqa directives to shut up flake8, such that test_mwe20b.py looks like:

from test_mwe20a import pi  # noqa: F401


def test_circle(pi):  # noqa: F811
    from mwe20 import circle
    assert circle(pi, 2) == 12

but I want to make sure there is no other way.

What is the PEP8-conform way to use fixtures defined in another module? Or is my code actually PEP8-conform and is this a limitation of flake8? The only related issue I find is closed and about the line number for the F811 warning, not for the fact that it warns in the first place.

See also: Why I'm getting F811 error in this code? for a poorly phrased and incorrectly answered related question.

gerrit
  • 24,025
  • 17
  • 97
  • 170
  • 2
    You don't need to import the fixtures to use them, `pytest` will resolve them by itself. Since you use the fixture `pi` in several test modules, create a file `conftest.py` in the tests root dir and move the fixture function in there, it will also be resolved automatically. – hoefling Feb 07 '20 at 10:23
  • @hoefling Yep — I found about the `conftest.py` magic after I wrote the question in what I then linked as a duplicate. – gerrit Feb 07 '20 at 11:54

0 Answers0