I have a FastAPI app and I need to populate a testing DB with some data needed for testing using pyTest.
This is my code for testing DB in conftest.py:
SQLALCHEMY_DATABASE_URL = "sqlite:///./test.db"
engine = create_engine(
SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False}
)
TestingSessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base.metadata.drop_all(bind=engine)
Base.metadata.create_all(bind=engine)
def override_get_db():
"""Redirect request to use testing DB."""
try:
db = TestingSessionLocal()
yield db
finally:
db.close()
app.dependency_overrides[get_db] = override_get_db
@pytest.fixture(scope="module")
def test_client():
"""Test client initiation for all tests."""
client = TestClient(app)
yield client
I need to implement something like this:
@pytest.fixture(scope="function")
def test_data(get_db):
waiter = Waiter(
id=1,
username="User name",
password="$12$BQhTQ6/OLAmkG/LU6G2J2.ngFk6EI9hBjFNjeTnpj2eVfQ3DCAtT.",
)
dish = Dish(
id=1,
name="Some dish",
description="Some description",
image_url="https://some.io/fhjhd.jpg",
cost=1.55,
)
get_db.add(waiter)
get_db.add(dish)
get_db.commit()
And here is a test:
def test_get_waiter(test_client, waiter_data):
"""Test Get a waiter by id."""
response = test_client.get("/waiters/1")
assert response.status_code == 200
But in this case I get fixture 'get_db' not found
. How do I?