Search code examples
pythonpython-3.ximportpytestfile-structure

How can I get my Python script to work correctly with both normal execution and pytest?


I'm stuck on import issues while using pytest. My file structure looks like:

src/
| __init__.py
| main.py
| util.py
tests/
| __init__.py
| test_main.py
tox.ini

If I want to run main.py with something from util.py normally, I would use the import line:

from util import UTIL_VALUE

If I try to test main.py with pytest, though, I get the error:

ModuleNotFound: No module named 'util'


I am able to get my pytest working by using this alternate import line in main.py:

from src.util import UTIL_VALUE

This makes my pytest run fine, but now when I try to run main.py normally, I get:

ModuleNotFound: No module named 'src.util'


I just want to be able to run the file and while also having it importable with my pytest, what can I do?


Solution

  • I found that removing the __init__.py's and adding an empty conftest.py in the src/ folder allowed me to keep the original from util import UTIL_VALUE. My working file structure ended up being

    src/
    | conftest.py
    | main.py
    | util.py
    tests/
    | test_main.py
    tox.ini