How can I enable `pytest_plugins = ('pytester',)` for specific test modules without affecting others?

I’m using a custom pytest plugin that integrates with doctests (scipy_doctest). Some of my test modules need the pytester plugin, but others don’t. When I enable it globally like this:

pytest_plugins = ("pytester",)

It works for the modules that depend on it, but causes import errors in others, especially when both types of modules import the same implementation file used for doctests.

Running the tests individually passes, but running them together fails due to these import errors.

So I’d like to understand:

  • Why does using pytester in one module cause issues in others?
  • How can I safely enable pytester only for specific modules that require it?
  • Is there a way to isolate or unload the plugin between tests?
  • Or should I test my doctest plugin differently without relying on pytester globally?

I ran into the same issue when testing a plugin that needed pytester. The root cause is that pytest plugins are loaded globally, not per-module.

So, when you declare pytest_plugins = ("pytester",) inside one test module, pytest still tries to register it for the entire session, leading to conflicts with doctest imports or shared fixtures.

To fix it, I stopped using pytest_plugins directly and instead imported it locally only when needed:

import pytest

pytest_plugins = []
if "pytester" not in pytest.plugins:
    pytest.importorskip("pytester")

Alternatively, you can move your pytester-dependent tests into a separate folder and run them via:

pytest tests/test_pytester/

This way, it never clashes with doctest-based modules.

I had this problem too when mixing plugin tests with regular tests. The cleanest solution I found was to split test discovery.

Keep the pytester-enabled tests in their own directory and add a local conftest.py with:

pytest_plugins = ("pytester",)

That way, pytest loads the plugin only for that subtree and not for everything else.

So your structure might look like:


tests/
  conftest.py
  test_general/
  test_pytester/  # only this folder has pytest_plugins = ('pytester',)

This isolates your plugin tests perfectly and avoids import errors in doctest modules.

What’s happening here is just pytest being “too global” with plugins.

The pytester plugin patches parts of pytest internals, and when you use doctests, it sometimes interferes with how collect.py imports shared test utilities.

In my case, I solved it by using pytest.register_assert_rewrite() only in the doctest modules and manually calling pytester when I actually needed it:

def test_my_plugin(pytester):
    pytester.makepyfile("def test_example(): pass")

No need for pytest_plugins at the top , pytest auto-loads it when you use the fixture.

That kept the rest of the modules clean and prevented the import errors.