pytest: conftest.py in root directory should not add root directory to sys.path

I started putting conftest.py in the root directory of my packages, instead of the tests/ directory, because I wanted to modify my doctest namespace.

However, it turns out that putting conftest.py in the root directory causes py.test to use the local rather than the installed version of my package to do the tests, which breaks some of my tests which depend on compiled modules.

Is this the intended behaviour? Some people seem to use this as a feature (e.g. see this stackoverflow answer). However, in my case this was a bug that was relatively difficult to track down.

I fixed this by putting the following lines in the root conftest.py file:

import os.path as op
import sys
sys.path.remove(op.dirname(op.abspath(__file__)))

Anaconda python running on CentOS 6

$ py.test --version
This is pytest version 3.0.6, imported from /opt/conda/lib/python3.5/site-packages/pytest.py
setuptools registered plugins:
  pytest-logging-2015.11.4 at /opt/conda/lib/python3.5/site-packages/pytest_logging/plugin.py
  pytest-cov-2.4.0 at /opt/conda/lib/python3.5/site-packages/pytest_cov/plugin.py
  hypothesis-3.6.1 at /opt/conda/lib/python3.5/site-packages/hypothesis/extra/pytestplugin.py

About this issue

  • Original URL
  • State: closed
  • Created 7 years ago
  • Comments: 17 (16 by maintainers)

Most upvoted comments

Indeed, good catch, thanks!

--import-mode=importlib will prevent pytest from messing with sys.path at all. 👍

(This will be released in 6.0.0, but 6.0.0rc1 can be used to test this already).

@nicoddemus I think --import-mode=importlib fixes this, right?