pytest icon indicating copy to clipboard operation
pytest copied to clipboard

Unable to import from a package in conftest.py.

Open bimargulies opened this issue 7 months ago • 3 comments

Following all the many posts about namespaces, I have the following setup, using pytest 8.3.4 and poetry 0.1.0:

In pyproject.toml:

[tool.pytest.ini_options]
consider_namespace_packages=true
addopts = [
    "--import-mode=importlib",
]

My overall tree is set up as:

<root>
  - pkg1
      - pkg1sub
        - __init__.py
      - test_helpers
        - __init__.py
        - helpers.py
  - tests
    - conftest.py
    - some_test.py
  pyproject.toml

conftest.py imports things from pkg1.test_helpers.

If I run

poetry run python -m mytest

all is well.

If I run

 poetry run pytest

the import statements in conftest.py fail to find packages in the namespace packages (subpackages_without_init_py in the tree above).

bimargulies avatar Apr 16 '25 21:04 bimargulies

This is not something pytest controls really. python -m always auto-adds the current working directory to the import path. And then, you're not testing "as installed" but "as cloned from Git". This may miss packaging problems if your project is a library and not an app.

webknjaz avatar Apr 17 '25 10:04 webknjaz

The intent of this testing, which is unit testing, is to test 'as cloned from git.' However, consider it as a library, consisting of a namespace package. What would be the correct configuration of pytest (or just plain poetry) so that the test 'sees' the package structure as defined? Note that we have other projects that do not use conftest.py in which the tests have no problem importing from the namespace package without switching to python -m.

bimargulies avatar Apr 17 '25 11:04 bimargulies

It's possible that you install those projects. In general, it's either -m or PYTHONPATH. And maybe poetry does something weird for you, I wouldn't know.

webknjaz avatar Apr 17 '25 12:04 webknjaz