ruff icon indicating copy to clipboard operation
ruff copied to clipboard

F811 Redefinition of unused `foo_fixture` and Pytest

Open arrdem opened this issue 1 year ago • 3 comments

  • Ruff version: 0.3.3
  • Rule: redefined-while-unused / F811

Ex. foo_test.py

from .fixtures import foo_fixture

def test_bar_using_foo(foo_fixture):
   with foo_fixture() as foo:
      assert foo.bar() == "baz"

When pytest runs test code it inspects both the namespaces defined by sibling and parent conftest.py files for fixtures, as well as the namespace of the package containing a given test. This makes it possible (although admittedly not great style) for users to explicitly import fixtures they intend to use so as to make them available to pytest in the module.

Doing so produces spurious instances of F811.

While I wouldn't really expect ruff to do a dynamic analysis to see if the imported entity is marked as @pytest.fixture and while this is an idiom I intend to move the codebase away from, it would be nice if we could at a minimum selectively ignore this error generally within the scope of the tests tree without disabling it generally.

arrdem avatar Mar 29 '24 19:03 arrdem

This has come up a few times:

  • https://github.com/astral-sh/ruff/issues/3295
  • https://github.com/astral-sh/ruff/issues/4046

I think the conclusion we came to was that we didn't have a reliable way to detect these without re-implementing a bunch of pytest-specific logic.

charliermarsh avatar Mar 30 '24 00:03 charliermarsh

it would be nice if we could at a minimum selectively ignore this error generally within the scope of the tests tree without disabling it generally.

I'm sorry but I'm unable to follow this. Do you want to ignore F811 in test files? If so, you could use lint.extend-per-file-ignores.

dhruvmanila avatar Apr 01 '24 08:04 dhruvmanila

I think this would do what I want --

[tool.ruff.lint.extend-per-file-ignores]
"src/pytests/**/test_*.py" = ["F811"]
"src/pytests/**/*_test.py" = ["F811"]

arrdem avatar Apr 03 '24 02:04 arrdem