app.dependency_overrides[get_db] = override_get_db is not working
See original GitHub issueThe problem
Hi, I have followed the tutorials on the fastapi website where I have found everything easy and clear. However, there is one thing I cannot make work and it looks like a lot of people are having this issue. Still, I have tried all the solutions there are on the internet and could not make it work.
I’m trying to run pytest in my fastapi app but even if I follow the tutorial line by line it doesn’t work. The fake database gets created but still, the real one is being used by the tests (which is a huge problem).
The point is if I set a breakpoint inside of the function override_get_db, it never gets there, it is being totally ignored, the rest of the lines are reached by the debugger, so I guess this is the problem. Can anyone who has had the same issue and solved it help, please?
This is my code:
import json
from fastapi.testclient import TestClient
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from starlette import status
from database import get_db, Base
from main import app
TEST_DATABASE_URL = "sqlite:///./test.db"
test_engine = create_engine(
TEST_DATABASE_URL, connect_args={"check_same_thread": False}
)
TestingSessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=test_engine)
Base.metadata.create_all(bind=test_engine)
def override_get_db():
try:
db = TestingSessionLocal()
yield db
finally:
db.close()
app.dependency_overrides[get_db] = override_get_db
client = TestClient(app)
def test_get_course():
response = client.post(
app.url_path_for('create_course'),
json={"name": "q1", "level": "q1", "description": "desc", "background_color": "bg"},
)
response_data = json.loads(response.content)
response = client.get(app.url_path_for('get_course', **{"course_id": 1}))
response_data = json.loads(response.content)
assert response.status_code == status.HTTP_200_OK
print(response_data)
#assert response.json() == {'FastApi': 'UOE PRO'}
I’m using Python 3.8.3 and these are the versions I have installed in my virtual environment:
fastapi==0.65.1
SQLAlchemy==1.4.15
psycopg2-binary==2.8.6
uvicorn==0.13.4
pydantic==1.8.2
starlette==0.14.2
passlib==1.7.4
bcrypt==3.2.0
python-jose==3.2.0
pytest==6.2.4
requests==2.25.1
Thank you so much!
Issue Analytics
- State:
- Created 2 years ago
- Reactions:2
- Comments:7
Top GitHub Comments
I found a workaroud like three months ago, but I’ll take into account how to comment an issue in the future. Thanks.
@oligond Thank you for the above, this all makes sense and I’ve gotten it to work. Thanks again!