I understand that there are many resources available and this question is asked many times. However, I am still wondering why I am getting this error.
I have a project structure like this:
PROJECT-MAIN-DIR
src
__init__.py
driver.py
app
__init__.py
app.py
docs
tests
app
test_app.py
venv
.gitignore
requirements.txt
And here is my code:
# driver.py
class MyDriverClass:
pass
# app.py
from src.driver import MyDriverClass,
class Application(MyDriverClass):
def foo():
print("foo")
if I create a file PROJECT-MAIN-DIR\test_app.py
from src.app.app import Application
def test_app():
my_app = Application()
my_app.foo()
test_app()
It will work
but if I write a test in PROJECT-MAIN-DIR\tests\app\unit\test_app.py
from src.app.app import Application
def test_app():
my_app = Application()
my_app.foo()
assert True
and run pytest \tests\app
Then I have
tests\app\unit\test_app.py:1: in <module>
from src.app.app import Application
E ModuleNotFoundError: No module named 'src'
How to fix it?
Note1: I am not looking for adding src to path using sys.path.append
Note2: It is a simplified version of the code and I cannot move things to root. Also I want to keep everything under src
.
Note3: I do want to keep scripts in my package but I need to at least be able to test my classes with pytest
SOLUTION:
I decided to add this line to tests\app\unit\test_app.py
sys.path.append(os.getcwd())
It worked for me