I'm struggling to get imports to work for my python project. I've created a test project to illustrate my issue. This is with Python 3.
My directory structure is as follows:
project/
test.sh
packageA/
__init__.py
moduleA.py
test/
__init__.py
test_moduleA.py
The contents of test.sh is python3 packageA/test/test_moduleA.py
Both __init__py
are empty.
This is moduleA.py
:
class A:
def doSomething(self):
print("Did something")
This is 'test_moduleA.py`:
import unittest
from packageA.moduleA import A
class TestModuleA(unittest.TestCase):
def testSomething(self):
a = A()
self.assertTrue(a.doSomething() == "Did Something")
if __name__ == '__main__':
unittest.main()
When I run test.sh
this is the error I get:
[project] $ ./test.sh
Traceback (most recent call last):
File "packageA/test/test_moduleA.py", line 2, in <module>
from packageA.moduleA import A
ModuleNotFoundError: No module named 'packageA'
[project] $
I have tried using the relative import in `test_moduleA.py' as follows:
from ..moduleA import A
In this case there error I get is shown below:
[project] $ ./test.sh
Traceback (most recent call last):
File "packageA/test/test_moduleA.py", line 2, in <module>
from ..moduleA import A
ValueError: attempted relative import beyond top-level package
[project] $
How do I get this to work properly? What is the Pythonic way to do it?