2

Poetry and pytest are relatively new to me and I am seeking to understand a specific behavior.

I have created a project with poetry, and I have added pytest as a dependy with poetry add --group dev pytest. As a result, here are the relevant line from pyproject.toml:

[tool.poetry.dependencies]
python = "^3.10"

[tool.poetry.group.dev.dependencies]
pytest = "^7.2.0"

Here is the project/modules structure:

.
├── app
│   ├── core
│   │   ├── cli.py
│   │   └── __init__.py
│   ├── __init__.py
│   └── run.py
├── poetry.lock
├── pyproject.toml
├── README.md
└── tests
    └── test_cli.py

In test_cli.py I am importing the cli module with from app.core.cli import *

With this particular setup, running poetry run pytest fails with:

tests/test_cli.py:2: in <module>
    from app.core.cli import *
E   ModuleNotFoundError: No module named 'app'

However, if I invoke a poetry shell and run python3 -m pytest tests/ it works.

It also works if I create an __init__.py in the tests/ directory.

I have seen a similar issue described here but I do not understand how it was resolved. One the suggestions to include include the project root name in the import statement did not help.

I also tried this answer, but it also did not work.

I was under the impression that an __init__.py is not necessary in tests/ and that poetry run pytest should work without it.

sinoroc
  • 18,409
  • 2
  • 39
  • 70
  • could you try adding sys.path.append(os.path.join(os.path.dirname(__file__), "..", "..")) to the test_cli.py file before the import statement. You can find more information about finding he path to parent directory here - [link](https://stackoverflow.com/questions/21005822/what-does-os-path-abspathos-path-joinos-path-dirname-file-os-path-pardir) – Manish Jan 16 '23 at 07:29
  • Your setup looks ok, so maybe there is a problem with the installation of the project in the virtual environment. Open pyproject.toml and under [tool.poetry], check that name = "app". If it's different I think that poetry does not find your package somehow. – edd313 Jan 16 '23 at 16:04
  • @edd313 In pyproject.toml name is not set to "app", it's set to the name of the whole project / the root directory name. In any case, what confuses me most is that invoking an interactive poetry shell then the paths are correctly set, but not with `poetry run`. – Backwater1296 Jan 17 '23 at 09:34

0 Answers0