I'm having a circular problem that I'm not able to solve. I started my project as follows:
.
├── conf
│ ├── __init__.py
│ └── server.py
├── __init__.py
├── main.py
├── requirements.txt
└── tests
├── __init__.py
└── v1
├── __init__.py
└── test_item.py
In main.py
I have:
from fastapi import FastAPI
import uvicorn
from conf.server import HOST, PORT
app = FastAPI()
@app.get("/")
async def root():
return {"message": "Hello World"}
if __name__ == '__main__':
uvicorn.run("main:app", host=HOST, port=PORT, reload=True)
In test_main.py
from fastapi.testclient import TestClient
from main import app
client = TestClient(app)
def test_read_main():
response = client.get("/")
assert response.status_code == 200
assert response.json() == {"message": "Hello World"}
The error I get when I run the script from the same level as main.py
with pytest
:
C:\Python39\lib\importlib\__init__.py:127: in import_module
return _bootstrap._gcd_import(name[level:], package, level)
tests\v1\test_item.py:3: in <module>
from main import app
E ModuleNotFoundError: No module named 'main'
If I write the name of the folder before main:
from api.main import app
I get an error with the con/server.py module:
Hint: make sure your test modules/packages have valid Python names.
Traceback:
C:\Python39\lib\importlib\__init__.py:127: in import_module
return _bootstrap._gcd_import(name[level:], package, level)
tests\v1\test_item.py:3: in <module>
from api.main import app
main.py:4: in <module>
from conf.server import HOST, PORT
E ModuleNotFoundError: No module named 'conf'
If I now change in main to include the name of the folder:
from api.conf.server import HOST, PORT
The test finally works, but now If I try to run the server wiht python main.py
it will not work anymore:
from api.conf.server import HOST, PORT
ModuleNotFoundError: No module named 'api'
What I'm doing wrong to get into this loop?