4

Assuming the following standard project structure

- project
-- src
---- __init__.py
---- script1.py
---- script2.py
---- module
---- __init__.py
------ helper.py
-- test
---- __init__.py
---- test_script1.py
---- test_script2.py
---- module
---- __init__.py
------ test_helper.py

the following imports in script1.py

import script2
from module import helper

and in test_script1.py

from src import script1

Calling the tests from the project directory with

python -m pytest tests

Fails, because when script1.py tries to import e.g. script2, the module will not be found because root is project/test that contains no src, throwing something like

 ModuleNotFoundError: No module named 'script2'

Modifying script1.py the following way

from src import script2
from src.module import helper

would fix the import at test time, but it would break when trying to run script1, whose root folder is src (which doesn't contain itself).

I assume that this is a standard case, but I couldn't find a clean solution (meaning not relying on sys.path.append('src') ).

The solution pointed out in Running unittest with typical test directory structure does not take into account imports within the src folder.

My workaround at the moment is having the test folder inside src

- project
-- src
---- __init__.py
---- script1.py
---- script2.py
---- module
---- __init__.py
------ helper.py
---- test
------- __init__.py
------- test_script1.py
------- test_script2.py
------ module
------ __init__.py
-------- test_helper.py

and having inside of, g.e. test_script1.py the following import

import script1

but I want to keep the folder structure mentioned at the beginning.

I will think of you for any suggestion.

Francesco
  • 393
  • 1
  • 3
  • 8

0 Answers0