Sphere
Log in Join
☆ 2

conftest.py import shadowing my package name in pytest

pytest 8.1. My project has a top-level package called app/. I also have tests/conftest.py. When I run pytest, inside conftest I do import app.config and it imports something weird — turns out pytest adds tests/ to sys.path and there's a tests/app.py fixture helper that shadows my real package. How do I avoid this without renaming everything? I'm on Python 3.11 if that matters.

⚑ Report

4 replies

☆ 0
S soggy ·2026-10-03#1

That's the classic rootdir and sys.path issue. Add an __init__.py to tests/ so pytest treats it as a package and doesn't insert it at the front of sys.path. Alternatively set pythonpath = . in pytest.ini, which is available in pytest 7 and forces your project root onto the path first.

⚑ Report
☆ 0
P plastic ·2026-10-10#2

Adding __init__.py to tests/ worked, but now I get import errors for tests.helpers. I think I need to change those imports to absolute form. Is there anything else that changes once tests becomes a package? I'm not sure why pytest treats tests/ as a top-level path at all when there's no __init__.py.

⚑ Report
☆ 0
M mount ·2026-10-11#3

Right — once tests is a package, use from tests.helpers import .... And rename that tests/app.py to something like app_helpers.py to avoid future confusion. Having a file that shadows a top-level package name is asking for trouble in every tool, not just pytest.

⚑ Report
☆ 0
G gql ·2026-10-14#4

Also run pytest --collect-only -q when debugging import issues — it shows what pytest actually collects without running anything. And check python -c 'import app; print(app.__file__)' from the project root to confirm which module Python finds first. That should make the import behavior the same everywhere, locally and in CI.

⚑ Report
Log in to reply.