How to evade non-called fixture in Pytest?

Viewed 522

Pytest suite has a brilliant feature of fixtures. To make a reusable fixture, we mark a function with special decorator:

@pytest.fixture
def fix():
    return {...}

It can later be used in our test through an argument name matching the original name of the fixture:

def test_me(fix):
    fix['field'] = 'expected'
    assert(fix['field'] == 'expected')

Although from time to time we might forget to specify the fixture in the arguments, and, since the name of the factory matches the name of the object produced, the test will silently apply changes to the factory object itself:

def test_me():  # notice no arg
    fix['this is'] = 'a hell to debug'

Certainly, the outcome is undesirable. It would be nice, for instance, to be able to add some suffix to factory function, but the pytest.fixture decorator apparently does not have a means to override the name for the fixture. Any other advice would suffice as well.

What is a recommended technique to protect ourselves from this kind of issue?

1 Answers

You can use autouse=True while defining fixture to invoke the fixture every time the scope of fixture starts. This feature was added in pytest 2.0. For example:

import pytest
@pytest.fixture(scope='function',autouse=True)
def fixture_a():
    return 5

def test_a():
    assert fixture_a == 5

As you can see, I did not have to declare fixture as an argument in test_a to access it.

Documentation: https://docs.pytest.org/en/latest/reference.html#pytest-fixture

Code example: https://docs.pytest.org/en/latest/fixture.html#autouse-fixtures-xunit-setup-on-steroids

Related