Is this the correct use of conftest.py?

Yes it is. Fixtures are a potential and common use of conftest.py. The fixtures that you will define will be shared among all tests in your test suite. However, defining fixtures in the root conftest.py might be useless and it would slow down testing if such fixtures are not used by all tests.

Does it have other uses?

Yes it does.

  • Fixtures: Define fixtures for static data used by tests. This data can be accessed by all tests in the suite unless specified otherwise. This could be data as well as helpers of modules which will be passed to all tests.

  • External plugin loading: conftest.py is used to import external plugins or modules. By defining the following global variable, pytest will load the module and make it available for its test. Plugins are generally files defined in your project or other modules which might be needed in your tests. You can also load a set of predefined plugins as explained here.

    pytest_plugins = "someapp.someplugin"

  • Hooks: You can specify hooks such as setup and teardown methods and much more to improve your tests. For a set of available hooks, read Hooks link. Example:

      def pytest_runtest_setup(item):
           """ called before ``pytest_runtest_call(item). """
           #do some stuff`
    
  • Test root path: This is a bit of a hidden feature. By defining conftest.py in your root path, you will have pytest recognizing your application modules without specifying PYTHONPATH. In the background, py.test modifies your sys.path by including all submodules which are found from the root path.

Can I have more than one conftest.py file?

Yes you can and it is strongly recommended if your test structure is somewhat complex. conftest.py files have directory scope. Therefore, creating targeted fixtures and helpers is good practice.

When would I want to do that? Examples will be appreciated.

Several cases could fit:

Creating a set of tools or hooks for a particular group of tests.

root/mod/conftest.py

def pytest_runtest_setup(item):
    print("I am mod")
    #do some stuff


test root/mod2/test.py will NOT produce "I am mod"

Loading a set of fixtures for some tests but not for others.

root/mod/conftest.py

@pytest.fixture()
def fixture():
    return "some stuff"

root/mod2/conftest.py

@pytest.fixture()
def fixture():
    return "some other stuff"

root/mod2/test.py

def test(fixture):
    print(fixture)

Will print "some other stuff".

Overriding hooks inherited from the root conftest.py.

root/mod/conftest.py

def pytest_runtest_setup(item):
    print("I am mod")
    #do some stuff

root/conftest.py

def pytest_runtest_setup(item):
    print("I am root")
    #do some stuff

By running any test inside root/mod, only "I am mod" is printed.

You can read more about conftest.py here.

EDIT:

What if I need plain-old helper functions to be called from a number of tests in different modules - will they be available to me if I put them in a conftest.py? Or should I simply put them in a helpers.py module and import and use it in my test modules?

You can use conftest.py to define your helpers. However, you should follow common practice. Helpers can be used as fixtures at least in pytest. For example in my tests I have a mock redis helper which I inject into my tests this way.

root/helper/redis/redis.py

@pytest.fixture
def mock_redis():
    return MockRedis()

root/tests/stuff/conftest.py

pytest_plugin="helper.redis.redis"

root/tests/stuff/test.py

def test(mock_redis):
    print(mock_redis.get('stuff'))

This will be a test module that you can freely import in your tests. NOTE that you could potentially name redis.py as conftest.py if your module redis contains more tests. However, that practice is discouraged because of ambiguity.

If you want to use conftest.py, you can simply put that helper in your root conftest.py and inject it when needed.

root/tests/conftest.py

@pytest.fixture
def mock_redis():
    return MockRedis()

root/tests/stuff/test.py

def test(mock_redis):
    print(mock_redis.get(stuff))

Another thing you can do is to write an installable plugin. In that case your helper can be written anywhere but it needs to define an entry point to be installed in your and other potential test frameworks. See this.

If you don't want to use fixtures, you could of course define a simple helper and just use the plain old import wherever it is needed.

root/tests/helper/redis.py

class MockRedis():
    # stuff

root/tests/stuff/test.py

from helper.redis import MockRedis

def test():
    print(MockRedis().get(stuff))

However, here you might have problems with the path since the module is not in a child folder of the test. You should be able to overcome this (not tested) by adding an __init__.py to your helper

root/tests/helper/init.py

from .redis import MockRedis

Or simply adding the helper module to your PYTHONPATH.

Answer from birkett on Stack Overflow
🌐
TutorialsPoint
tutorialspoint.com › pytest › pytest_conftest_py.htm
Pytest - Conftest.py
import pytest def test_divisible_by_3(input_value): assert input_value % 3 == 0 def test_divisible_by_6(input_value): assert input_value % 6 == 0 ... Now, we have the files test_div_by_3_6.py and test_div_by_13.py making use of the fixture defined in conftest.py.
Top answer
1 of 6
712

Is this the correct use of conftest.py?

Yes it is. Fixtures are a potential and common use of conftest.py. The fixtures that you will define will be shared among all tests in your test suite. However, defining fixtures in the root conftest.py might be useless and it would slow down testing if such fixtures are not used by all tests.

Does it have other uses?

Yes it does.

  • Fixtures: Define fixtures for static data used by tests. This data can be accessed by all tests in the suite unless specified otherwise. This could be data as well as helpers of modules which will be passed to all tests.

  • External plugin loading: conftest.py is used to import external plugins or modules. By defining the following global variable, pytest will load the module and make it available for its test. Plugins are generally files defined in your project or other modules which might be needed in your tests. You can also load a set of predefined plugins as explained here.

    pytest_plugins = "someapp.someplugin"

  • Hooks: You can specify hooks such as setup and teardown methods and much more to improve your tests. For a set of available hooks, read Hooks link. Example:

      def pytest_runtest_setup(item):
           """ called before ``pytest_runtest_call(item). """
           #do some stuff`
    
  • Test root path: This is a bit of a hidden feature. By defining conftest.py in your root path, you will have pytest recognizing your application modules without specifying PYTHONPATH. In the background, py.test modifies your sys.path by including all submodules which are found from the root path.

Can I have more than one conftest.py file?

Yes you can and it is strongly recommended if your test structure is somewhat complex. conftest.py files have directory scope. Therefore, creating targeted fixtures and helpers is good practice.

When would I want to do that? Examples will be appreciated.

Several cases could fit:

Creating a set of tools or hooks for a particular group of tests.

root/mod/conftest.py

def pytest_runtest_setup(item):
    print("I am mod")
    #do some stuff


test root/mod2/test.py will NOT produce "I am mod"

Loading a set of fixtures for some tests but not for others.

root/mod/conftest.py

@pytest.fixture()
def fixture():
    return "some stuff"

root/mod2/conftest.py

@pytest.fixture()
def fixture():
    return "some other stuff"

root/mod2/test.py

def test(fixture):
    print(fixture)

Will print "some other stuff".

Overriding hooks inherited from the root conftest.py.

root/mod/conftest.py

def pytest_runtest_setup(item):
    print("I am mod")
    #do some stuff

root/conftest.py

def pytest_runtest_setup(item):
    print("I am root")
    #do some stuff

By running any test inside root/mod, only "I am mod" is printed.

You can read more about conftest.py here.

EDIT:

What if I need plain-old helper functions to be called from a number of tests in different modules - will they be available to me if I put them in a conftest.py? Or should I simply put them in a helpers.py module and import and use it in my test modules?

You can use conftest.py to define your helpers. However, you should follow common practice. Helpers can be used as fixtures at least in pytest. For example in my tests I have a mock redis helper which I inject into my tests this way.

root/helper/redis/redis.py

@pytest.fixture
def mock_redis():
    return MockRedis()

root/tests/stuff/conftest.py

pytest_plugin="helper.redis.redis"

root/tests/stuff/test.py

def test(mock_redis):
    print(mock_redis.get('stuff'))

This will be a test module that you can freely import in your tests. NOTE that you could potentially name redis.py as conftest.py if your module redis contains more tests. However, that practice is discouraged because of ambiguity.

If you want to use conftest.py, you can simply put that helper in your root conftest.py and inject it when needed.

root/tests/conftest.py

@pytest.fixture
def mock_redis():
    return MockRedis()

root/tests/stuff/test.py

def test(mock_redis):
    print(mock_redis.get(stuff))

Another thing you can do is to write an installable plugin. In that case your helper can be written anywhere but it needs to define an entry point to be installed in your and other potential test frameworks. See this.

If you don't want to use fixtures, you could of course define a simple helper and just use the plain old import wherever it is needed.

root/tests/helper/redis.py

class MockRedis():
    # stuff

root/tests/stuff/test.py

from helper.redis import MockRedis

def test():
    print(MockRedis().get(stuff))

However, here you might have problems with the path since the module is not in a child folder of the test. You should be able to overcome this (not tested) by adding an __init__.py to your helper

root/tests/helper/init.py

from .redis import MockRedis

Or simply adding the helper module to your PYTHONPATH.

2 of 6
25

Update Pytest 7.2 (2023 - March)

Adding this answer because there are some comment regarding missing information in the docs, which I guess was back when this question was first asked, but now is very well explained and documented.

From conftest.py: sharing fixtures across multiple files till the bottom of the page (and actually anything related to fixture or setting up pytest can be applied to the conftest.py) is related to conftest.py

Therefore, by quickly scanning the docs these are the main functionality (but not inclusive) :

  • Serve fixtures to tests (no matter the fixture scope)
  • Modularize the available fixture for each conftest.py in a Tree like hierarchy
  • Scope: sharing fixtures across classes, modules, packages or session
  • Child conftest.py can override parent conftest.py (but not the opposite) See this
  • Serve fixtures from a third-party plugins
  • Loading and Sharing test data across multiple tests
  • Using fixtures from other projects
  • Serve and share Hooks

Now on the accepted answer, it says Test root path: : This is a bit of a hidden feature. By defining ... but as for now, the best way to do this is instead add pythonpath to a pytest.ini on the root of your project (the actual project root, not project/tests ) see: pythonpath and does all for you and is more powerfull

Which looks like

[pytest]
pythonpath = src1 src2

Lastly, here I drop one of the many graphs that are in the pytest docs about The boundaries of the scopes can be visualized like this:

Discussions

How pytest fixtures screwed me over
I'll file this post in the "I hope I am never in the situation this will be useful to me, but I'll still save it because you never know" More on reddit.com
🌐 r/Python
63
168
September 26, 2025
Specify conftest / setup file in the ini file
Can't specify a conftest depending on the testing style (we use unit + integration for example) pytest -s -c=./config/python/pytest_unit.ini path/to/tests/file_test.py More on github.com
🌐 github.com
24
September 6, 2019
🌐
pytest
docs.pytest.org › en › stable › reference › fixtures.html
Fixtures reference - pytest documentation
So when they run, outer will have ... will be instantiated in: the order is mandated by the logic described here. The conftest.py file serves as a means of providing fixtures for an entire directory....
🌐
pytest
pytest.org › en › 7.1.x › search.html
Search — pytest documentation
Please activate JavaScript to enable the search functionality · Searching for multiple words only shows matches that contain all words
🌐
pytest
docs.pytest.org › en › stable › contents.html
Full pytest documentation - pytest documentation
Requiring/Loading plugins in a test module or conftest file · Accessing another plugin by name · Registering custom markers · Testing plugins · Writing hook functions · hook function validation and execution · firstresult: stop at first non-None result · hook wrappers: executing around other hooks · Hook function ordering / call example · Declaring new hooks · Using hooks in pytest_addoption ·
🌐
GitHub
gist.github.com › hectorcanto › a57d5ff2c0a043a3626afae245793461
[Conftest example with fixtures] A Pytest conftest example with a function scoped fixture, with autouse. The code will be executed after every function, since it only has logic after the yield. #python #pytest · GitHub
[Conftest example with fixtures] A Pytest conftest example with a function scoped fixture, with autouse. The code will be executed after every function, since it only has logic after the yield. #python #pytest - conftest.py
Find elsewhere
🌐
GeeksforGeeks
geeksforgeeks.org › python › conftest-in-pytest
Conftest in pytest - GeeksforGeeks
July 23, 2025 - The conftest.py is the Python file in which various functions are declared which can be accessed across various test files.
🌐
pytest
docs.pytest.org › en › 7.1.x › reference › fixtures.html
Fixtures reference — pytest documentation
So when they run, outer will have ... will be instantiated in: the order is mandated by the logic described here. The conftest.py file serves as a means of providing fixtures for an entire directory....
🌐
JetBrains
intellij-support.jetbrains.com › hc › en-us › community › posts › 12897247432338-PyCharm-unable-to-find-fixtures-in-conftest-py
PyCharm unable to find fixtures in conftest.py – IDEs Support (IntelliJ Platform) | JetBrains
Hey, I can confirm the bug and it is so annoying. Running all the tests (right click on the tests folder and “Run pytest in tests…” works perfectly. But running a test from a subfile directly doesn't load the conftest anymore.
🌐
Reddit
reddit.com › r/python › how pytest fixtures screwed me over
r/Python on Reddit: How pytest fixtures screwed me over
September 26, 2025 -

I need to write this of my chest, so to however wants to read this, here is my "fuck my life" moment as a python programmer for this week:

I am happily refactoring a bunch of pytest-testcases for a work project. With this, my team decided to switch to explicitly import fixtures into each test-file instead of relying on them "magically" existing everywhere. Sounds like a good plan, makes things more explicit and easier to understand for newcomers. Initial testing looks good, everything works.

I commit, the full testsuit runs over night. Next day I come back to most of the tests erroring out. Each one with a connection error. "But that's impossible?" We use a scope of session for your connection, there's only one connection for the whole testsuite run. There can be a couple of test running fine and than a bunch who get a connection error. How is the fixture re-connecting? I involve my team, nobody knows what the hecks going on here. So I start digging into it, pytests docs usually suggest to import once in the contest.py but there is nothing suggesting other imports should't work.

Than I get my Heureka: unter some obscure stack overflow post is a comment: pytest resolves fixtures by their full import path, not just the symbol used in the file. What?

But that's actually why non of the session-fixtures worked as expected. Each import statement creates a new fixture, each with a different import-path, even if they all look the same when used inside tests. Each one gets initialised seperatly and as they are scoped to the session, only destroyed at the end of the testsuite. Great... So back to global imports we went.

I hope this helps some other tormented should and shortens the search for why pytest fixtures sometimes don't work as expected. Keep Coding!

🌐
Pytest with Eric
pytest-with-eric.com › pytest-best-practices › pytest-conftest
Pytest Conftest With Best Practices And Real Examples | Pytest with Eric
October 25, 2022 - While there’s a lot of documentation on how to use conftest , the best practices using real repeatable examples are often lacking. ... What are Pytest Fixturesand how to use them to improve Unit Testing.
🌐
GitHub
github.com › pytest-dev › pytest › issues › 5822
Specify conftest / setup file in the ini file · Issue #5822 · pytest-dev/pytest
September 6, 2019 - Can't specify a conftest depending on the testing style (we use unit + integration for example) pytest -s -c=./config/python/pytest_unit.ini path/to/tests/file_test.py
Author   ayroblu
🌐
Infinum
infinum.com › handbook › qa › automation › python › pytest-tips-and-tricks
Quality Assurance Handbook | Automation / Python / Pytest tips & tricks
January 18, 2024 - Pytest is a testing framework for Python. For more info, check the documentation. conftest.py is a file in which you can set up your test configuration.
🌐
Medium
medium.com › @pauloarthurvm › setting-up-a-pytest-testing-framework-04-fixtures-and-conftest-py-structures-1faebff595c7
Setting Up a Pytest Testing Framework 04 — Fixtures and conftest.py structures | by Paulo Varassin | Medium
November 25, 2025 - This way, the database package should be able to use its conftest.py imports, and above conftest’s, for example the one in tests/. But it will not be able to access fixtures imported by conftest.py in tests/api/. ... Now you can run the tests and see each fixture being correctly being activate in the setup and in the teardown. Pay attention to the order they are called in the setup and teardown by the logs ... (.venv) > pytest =============================================================== test session starts ================================================================ platform win32 --
🌐
pytest
docs.pytest.org › en › 6.2.x › explanation › fixtures.html
pytest fixtures: explicit, modular, scalable — pytest documentation
So when they run, outer will have ... will be instantiated in: the order is mandated by the logic described here. The conftest.py file serves as a means of providing fixtures for an entire directory....
🌐
Medium
medium.com › @BuzonXXXX › pytest-conftest-py-44903c4c5046
Pytest: conftest.py
October 31, 2023 - In summary, conftest.py in pytest is a versatile tool for efficiently managing fixtures, configurations, and hooks across your test suite. It fosters code reuse, simplifies test setup and teardown, and fine-tunes pytest to meet your project's ...
🌐
Readthedocs
exhale.readthedocs.io › en › latest › testing › conftest.html
Testing Conftest Module — Exhale: Automatic C++ Library API Generation
Testing Conftest Module · Edit on GitHub · Global pytest configurations that are used / executed for every test. See pytest documentation on Package/Directory-level fixtures (setups). testing.conftest.pytest_plugins = ['sphinx.testing.fixtures', 'testing.fixtures'] ·
🌐
TutorialsPoint
tutorialspoint.com › pytest › pytest_fixtures.htm
Pytest - Fixtures
However, the approach comes with its own limitation. A fixture function defined inside a test file has a scope within the test file only. We cannot use that fixture in another test file. To make a fixture available to multiple test files, we have to define the fixture function in a file called conftest.py.
🌐
LobeHub
lobehub.com › home › skills › python-bootstrap
python-bootstrap | Skills Marketplace · LobeHub
March 3, 2026 - Bootstrap Python 3.13 projects ... prek, pytest. ... python ~/.claude/skills/python-bootstrap/scripts/bootstrap_project.py \ --project-name <name> --type <type> --output-dir <path> ... <project-name>/ ├── src/<package_name>/ │ ├── __init__.py │ └── (type-specific files) ├── tests/ │ ├── conftest.py │ └── ...