Pytest import problems when tests import from adjacent directory

Viewed 28
/root
|- __init__.py
|
|- /src 
|  |
|  |- __init__.py
|  |- /x
|     |
|     |- __init__.py
|     |- xy.py
|
|- /tests
|  |- __init__.py
|  |- /test_x
|     |
|     |- __init__.py
|     |- test_xy.py
# tests/test_x/test_xy.py 

from src.x.xy import XY

Class TestXY:

    # etc 

When I’m in root I try to run pytest tests/*/* and I get an error that due to from src.x.xy import XY because src can’t be found. If I change the import to from …src.x.xy import XY I get “cannot import” because it’s from a directory one level above.

I also tried running Python -m pytest tests/*/* but I get an error about conftest not being found in __pycache__ which I don’t understand. (ERROR: not found: /root/tests/__pycache__/conftest.cpython-310-pytest-7.1.2.pyc (no name '/root/tests/__pycache__/conftest.cpython-310-pytest-7.1.2.pyc' in any of []))

What am I missing? Why is it so hard to run tests this way? I can run them individually in pycharm by clicking the little green arrows in the test script no problem.

1 Answers

In that architecture of project you should use config file. Config file should have path to src.

pyproject.toml example:

[tool.pytest.ini_options]
pythonpath = [
  "src"
]

pytest.ini example:

[pytest]
pythonpath = src

If you will have multiple src directories you also can add it to config

For example pyproject.toml:

[tool.pytest.ini_options]
pythonpath = [
  "src", "src2",
]
Related