0

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?

Vitalii Mytenko
  • 544
  • 5
  • 20
  • 1
    You need to create a fixture named `get_db`, otherwise your program will never be able to find such fixture – lsabi Dec 26 '22 at 14:34
  • @VitaliiMytenko check out https://stackoverflow.com/a/61045326/2518962 for a potential solution. Essentially, you can structure your fixture hierarchy to generate the test client dynamically within a fixture which itself depends on another database session fixture. – Kieran Aug 11 '23 at 07:55

2 Answers2

2

you must set a fixture with get_db name:


@pytest.fixture(name="get_db")
def get_test_db():
    return override_get_db()

I suggest you have a conftest.py and put this config into it.

  • AttributeError: 'generator' object has no attribute 'add' – Vitalii Mytenko Dec 26 '22 at 14:50
  • `@pytest.fixture(scope="function")` delete this above your test function. fixture doesn't use above function tests. What Are Pytest Fixtures? Pytest fixtures are functions that can be used to manage our apps states and dependencies. Most importantly, they can provide data for testing and a wide range of value types when explicitly called by our testing software. You can use the mock data that fixtures create across multiple tests. – Ali Mahdavi Dec 26 '22 at 16:21
0

I've handled it in this way in conftest.py:

@pytest.fixture(scope="module")
def db_session():
    """Fixture to connect with DB."""
    connection = engine.connect()
    session = TestingSessionLocal(bind=connection)

    yield session

    session.close()

@pytest.fixture(scope="function")
def test_db_data(db_session):
    waiter = Waiter(
        username="User name",
        password="$12$BQhTQ6/OLAmkG/LU6G2J2.ngFk6EI9hBjFNjeTnpj2eVfQ3DCAtT.",
    )
    db_session.add(waiter)
    db_session.commit()
    yield db_session
Vitalii Mytenko
  • 544
  • 5
  • 20