32

I'm looking to create a pytest structure where I can separate the fixtures from the tests completely. The reason for this separation is that I want to include the fixtures directory as an external item in subversion and share it between multiple projects.

tree of desired structure

project
|   conftest.py
|
+---fixtures
|       __init__.py
|       conftest.py
|       fixture_cifs.py
|       fixture_ftp.py
|       fixture_service.py
|
\---tests
    |   test_sometest1.py
    |   test_sometest2.py
    |
    \---configurations
            sometest1.conf
            sometest2.conf

I want to implement the functionality for each fixture in a separate file in order to avoid a single huge conftest.py. conftest.py would just include wrappers to return an instance of each fixture annotated with @pytest.fixture. There is no problem using a fixture together with a test when the conftest.py, fixture_*.py and test_*.py files are all in the same directory.

However, when the fixtures are separated in a subdirectory I get an error from pytest fixture 'cifs' not found, available fixtures: .... I haven't found any documentation explaining how to place fixtures outside of test_*.py or the conftest.py adjacent to test_*.py, but nothing to indicate that this shouldn't work either.

How can I place fixtures in their own subdirectory when using pytest?

Jakob Pogulis
  • 1,150
  • 2
  • 9
  • 19

4 Answers4

35

Please add the following in your conftest.py

  import pytest

  pytest_plugins = [
   "fixtures.conftest",
   "fixtures.fixture_cifs",
   "fixtures.fixture_ftp",
   "fixtures.fixture_service"
  ]

This ensures that all fixtures declared under fixtures/ will be found by pytest

As a note that the respective directories referred to in fixtures.conftest" need to have __init__.py files for the plugins to be loaded by pytest

A similar case can be seen here: https://stackoverflow.com/a/54736237/6655459

Brand0R
  • 1,413
  • 11
  • 17
rafalkasa
  • 1,743
  • 20
  • 20
2

read here how structure your test.

Your fixture directory doesn't seem to be part of a package (project does not have __init__.py so cannot be imported as project.fixtures either as fixtures as it is not in the path. You can add required dirs in the path in your tests/conftest.py (sys.path.append(os.path.join(os.path.dirname(__file__), os.pardir, "fixtures")) or sys.path.append(os.path.join(os.path.dirname(__file__), os.pardir) depending how how you want import your modules.

Jonathan
  • 154
  • 2
  • 14
sax
  • 3,708
  • 19
  • 22
1

Try importing your fixtures in project/conftest.py if that is what you mean by "wrappers to return an instance"

Wil Cooley
  • 900
  • 6
  • 18
0

For when I inevitably come back to this question: you can import fixtures in different files (even files which would not typically access the fixture) and the tests will pick it up appropriately!

AetherUnbound
  • 1,714
  • 11
  • 10