Search code examples
pythonimportmodulepytestimporterror

Pytest "No module named..." issue


So I'm running into issues when I run pytest versus when I invoke the tested module directly. Pytest actually runs fine but I run into issues trying to directly invoke the python file that I'm testing. Here is the basic folder layout:

generate
├── generate
│   ├── __init__.py
│   ├── write_sql.py
│   └── utils.py
└── tests
    └── test_write_sql.py

Within both test_write_sql.py and write_sql.py I'm importing things using the generate module like so:

from generate import utils

Running pytest from the root generate folder works fine. But when I try to invoke write_sql.py directly from the root generate folder I run into the following error:

root@637572f508b9:~/generate# python3 generate/write_sql.py 
Traceback (most recent call last):
  File "/root/generate/generate/write_sql.py", line 5, in <module>
    from generate import utils
ModuleNotFoundError: No module named 'generate'

My impression was that running Python from the generate root folder should add the generate subfolder as a module to the system path (due to the included __init__.py file). I know if I change the import to import utils inside write_sql.py then the direct call to write_sql.py works but then pytest runs into import errors.

Any ideas as to what import scheme I should use to get both pytest and the direct invocation working?


Solution

  • I was having the same issues with imports, the way i fixed it was setting all the imports so that the code runs. In order to run the tests instead of just calling pytest (this runs all tests from the folder where they are located, therefore there will be import error) it should be called from the root directory like this:

    python3 -m pytest

    or

    python -m pytest

    this way it runs all tests from the root directory, and it should not give import errors