7

Suppose I have packageA which provides a class usefulClass, pytest fixtures in a test_stuff.py module, and test configurations in a conftest.py module.

Moreover, suppose that I have packageBand packageC both of which import packageA, installed via pip, and that they use usefulClass in the same way. Because they use usefulClass in the same way, packageB and packageC will require many identical pytest fixtures and configurations. In fact, their tests will primarily differ only in the sets of inputs over which they iterate.

Because the fixtures and configurations are identical and arise from the use of usefulClass, is it possible to define those fixtures and configurations in packageA, and then import them into the testing environments of packageB and packageC?

In particular, I would like to reuse the definition of pytest_generate_tests that appears in packageA's conftest.py module across dozens, if not hundreds of other packages. This way, I only need maintain one confest.py module, rather than hundreds.

Mackie Messer
  • 1,126
  • 2
  • 8
  • 22

1 Answers1

8

The conftest.py file is not part of the module and cannot be imported from other modules.

However you could create a module packageA.testutils, which you then can import in all conftest.py files, including packageA's:

from packageA.testutils import *

Maybe it even warrants creating an individual package that all your other packages depend on.

Nils Werner
  • 34,832
  • 7
  • 76
  • 98
  • I was thinking something like this might be the only option. So if I import the specially named configuration functions, such as `pytest_generate_tests`, from `packageA.testutils` into `packageB`'s `conftest.py`, pytest will correctly discover and apply them? – Mackie Messer Mar 13 '17 at 14:33
  • Yes, it should. – Nils Werner Mar 13 '17 at 14:35
  • 1
    Yes, I just tried it in one of my packages. `pytest_generate_tests` imported into a dependent package's `conftest.py` does get correctly discovered and executed; so, I will assume the same is true of any other specially named functions. Vielen Dank ~MM – Mackie Messer Mar 13 '17 at 15:34
  • 2
    You could use: `pytest_plugins = [ "packageA.testutils"]` in the `conftest.py` at the root of your project. Check [pytest plugins documentation](https://docs.pytest.org/en/latest/plugins.html). – smichaud Jul 17 '20 at 17:49