pytest icon indicating copy to clipboard operation
pytest copied to clipboard

Provide for an easier way to re-use fixtures or plugins from other conftests

Open astraw38 opened this issue 9 years ago • 3 comments

It'd be very helpful to have one canonical way to re-use fixture code between test modules. Right now, I know of 3 ways to do this, each with their own downsides:

  1. Import the fixture/hook directly -- Results in unused imports, and isn't always clear where the code came from. Easy to break things later when cleaning up unused imports.
  2. Use pytest_plugins = 'path.to.conftest' -- Will result in pytest errors if you run the current module and the module the conftest came from at the same time. Also makes the plugin globally active, which isn't always desired.
  3. Move the code to a common-ancestor -- Can make the fixtures too broadly usable, especially if the test modules aren't relatively close to each other.

astraw38 avatar Nov 14 '16 15:11 astraw38

a few notes

  1. is the wrong way to do it and we plan to warn on it since it creates hard to debug errors
  2. is more elegantly solved by using fixtures modules and refering to them from a conftest as well
  3. is a common but not so nice solution

at the pytest-sprint in june we did conceptualize many aspects of fixture reuse, name-spacing but didn't find time to implement/experiment

we should start to document the finer details and some proposal (that takes a lot of time that many from us don't don't have readily and consistently)

RonnyPfannschmidt avatar Nov 14 '16 16:11 RonnyPfannschmidt

Ah, I remember now why we didn't do the pytest_plugins = ... in the past -- it makes it active globally, rather than at the current conftest level & below. That's a problem for hooks & autouse fixtures. I should add that downside to the original post, since that's a critical difference to importing.

astraw38 avatar Nov 15 '16 16:11 astraw38

Using fixtures from plugins is problematic because, as was already mentioned, once a plugin is loaded, the changes it makes are available globally. This is not explained clearly in the documentation which only warns about the usage of plugins in non-root conftest.py files. And the current versions of pytest explicitly disallow that. But a similar effect can be observed when a plugin is imported in any test module.

It changes the behavior globally. Not only in the module from where it was imported. Not even only in the directory subtree from where it was imported. And that is, in my opinion, very confusing.

Since plugins affect the behavior globally, perhaps they should only be allowed in the top-level conftest.py file.

pbasista avatar Sep 12 '24 09:09 pbasista