Skip to content

Instantly share code, notes, and snippets.

@peterhurford
Created July 28, 2016 15:48
Show Gist options
  • Save peterhurford/09f7dcda0ab04b95c026c60fa49c2a68 to your computer and use it in GitHub Desktop.
Save peterhurford/09f7dcda0ab04b95c026c60fa49c2a68 to your computer and use it in GitHub Desktop.
How to modularize your py.test fixtures

Using py.test is great and the support for test fixtures is pretty awesome. However, in order to share your fixtures across your entire module, py.test suggests you define all your fixtures within one single conftest.py file. This is impractical if you have a large quantity of fixtures -- for better organization and readibility, you would much rather define your fixtures across multiple, well-named files. But how do you do that? ...No one on the internet seemed to know.

Turns out, however, you can define fixtures in individual files like this:

tests/fixtures/add.py

import pytest

@pytest.fixture
def add(x, y):
    x + y

Then you can import these fixtures in your conftest.py:

tests/conftest.py

import pytest
from fixtures.add import add

...and then you're good to test!

tests/adding_test.py

import pytest

@pytest.mark.usefixtures("add")
def test_adding(add):
    assert add(2, 3) == 5

Because of the modularity, tests will have to be run with python -m py.test instead of py.test directly.

@umbertogriffo
Copy link

Another option would be to have multiple nested directories/packages containing your tests, and each directory can have its own conftest.py with its own fixtures, adding on to the ones provided by the conftest.py files in parent directories as written in the official doc here

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment