Search code examples
pythonimportmodulepackagepytest

pytest import errors - module not found


I have this directory structure:

app/
    pyproject.toml
    src/
        app/
            __init__.py
            app.py
            functions1.py
            functions2.py
    tests/
        test_functions1.py
        test_functions2.py
 

If I run this on command line from the app directory (app>python path/to/app/src/app/app.py -flags) it works. However, when I run my tests with pytest (app>pytest path/to/app/tests/test_functions1.py), I get the following error (adapted to this dummy example) during collection:

ImportError while importing test module 'path/to/app/tests/test_functions1.py'.
Hint: make sure your test modules/packages have valid Python names.
Traceback:
tests\test_functions1.py:9: in <module>
    from app.functions1 import MyClass
src\app\functions1.py:13: in <module>
    from functions2 import other_function
E   ModuleNotFoundError: No module named 'functions2'

As per the pytest docs, I have the following in my TOML:

[tool.pytest.ini_options]
pythonpath = "src"
addopts = [
    "--import-mode=importlib",
]

Can someone tell me the proper way to import functions in this context?

EDIT: Thanks for the link suggestion. I have made some changes and updated this answer, but I believe my issues may be specific to pytest (the link was a more general discussion).

I believe the issue is that my import namespaces are incorrect when run with pytest, but i'm not sure how to reference them properly without breaking the app outside of testing. If I do:

functions1.py

from app.functions2 import other_function

rather than:

functions1.py

import functions2 import other_function

Then my tests work but app>python path/to/app/src/app/app.py -flags fails with ModuleNotFoundError: No module named 'app'. Please note, other_function is used by functions in functions2.py, but not by the specific function from functions2.py i am testing.


Solution

  • In case anyone else has these issues, the issue was I hadn't installed the package I was working on locally in editable mode (i.e. navigate to package, then do pip install -e .). Once that is done my tests work with imports as app.module in both tests and main .py files. This is mentioned in the docs, so no excuse on my part!

    Cheers, Tim