There are similar questions but none of them have a completly sibling test folder with main.py in the src folder and none of them work. Currently I use the following approach
#project/tests/aaa/bbb/test_foo.py
import unittest
import sys
sys.path.append("....")
from src.aaa.bbb import foo as foo
#...
and end up with a
ModuleNotFoundError: No module named 'src'
(I tested profoundly if the amount of points in sys.path.append("....")
is correct)
Maybe I do not understand python but my folder structures (which I would like to keep) goes:
/project
/src
main.py
/aaa
/bbb
foo.py
/tests
/aaa
/bbb
test_foo.py
I execute it in the project folder and for the normal not-test files that works fine.
A former Try was (in test_foo.py):
from ....src.aaa.bbb import foo as foo
This is the approach that works in the normal files but for the test files I got:
ImportError: attempted relative import with no known parent package
``
I tried it with and without the ``` -m``` option.
Also with and without
if __name__ == '__main__':
unittest.main()
3
I suggest you to append to sys.path
the absolute path of the folder project
.
So the test_foo.py
file becomes:
import unittest
import sys
sys.path.append("/absolute/path/to/folder/project")
from src.aaa.bbb import foo as foo
class MyTestCase(unittest.TestCase):
def test_something(self):
self.assertTrue(True)
if __name__ == '__main__':
unittest.main()
To execute the script test_foo.py
use absolute path of the script as in the following command:
> python /absolute/path/to/folder/project/tests/aaa/bbb/test_foo.py
The output is without import error (the import of foo
from src.aaa.bbb
is successfully executed):
----------------------------------------------------------------------
Ran 1 test in 0.000s
OK
PS: I have studied the problem of your instruction sys.path.append("....")
but honestly I don’t have found an exhaustive answer so I think that is better to add the absolute path to sys.path
as I have done in this answer. At this link there is the documentation about absolute and relative imports.