Pytest: deprecate calling fixtures as functions

Created on 5 Jul 2018  路  4Comments  路  Source: pytest-dev/pytest

We often declare fixtures in the same module that uses them. I've seen people new to the codebase, especially ones who haven't been heavy pytest users before, often use the fixtures interchangeably as functions, i.e.

@pytest.fixture
def model():
   ...

def test_foo(model):
   my_model = model

def test_bar():
   my_model = model()

The fixtures are intentionally made callable, but I'd argue that in many codebases, the the dual use of a fixture in this way breeds confusion and can mislead a novice programmer. For example, if the fixture requires other fixtures, i.e.

@pytest.fixture(params=[1, 2])
def parent_model(request):
   ...

@pytest.fixture
def model(parent_model):
   ...

a novice programmer might conclude that _they_ need to provide the parent_model parameter to model(), not knowing that they're supposed to leave it up to the fixture resolution (which could e.g. result in a parameterized fixture).

I'd like to propose introducing a flag such as strict_fixtures to make fixtures fail fast (with a clear explanation) if they're called as functions.

deprecation feature-branch

Most helpful comment

Thanks @nicoddemus !

All 4 comments

its actually a good point, we should deprecate calling fixtures as functions alltogether, just as we deprecated registring them twice

we should introduce a DeprecationWarning with the next feature release and eventually turn it into a error

GitMate.io thinks possibly related issues are https://github.com/pytest-dev/pytest/issues/498 (Function scope fixture with failing finalizer called only once), https://github.com/pytest-dev/pytest/issues/1805 (Fixture that calls getattr() on request.function throws an AttributeError: 'function' object has no attribute), https://github.com/pytest-dev/pytest/issues/1875 (Cannot create two fixtures based on the same function), https://github.com/pytest-dev/pytest/issues/2001 (Using fixture decorator as a function), and https://github.com/pytest-dev/pytest/issues/2334 (Defining differently-scoped fixtures with single function messes up fixture scope).

(hmm really bad that GitMate removes labels explicitly added by maintainers)

Thanks @nicoddemus !

Was this page helpful?
0 / 5 - 0 ratings