← full-stack-fastapi-template  /  backend/tests/conftest.py

1
from collections.abc import Generator
2
3
import pytest
4
from fastapi.testclient import TestClient
5
from sqlmodel import Session, delete
6
7
from app.core.config import settings
8
from app.core.db import engine, init_db
9
from app.main import app
10
from app.models import Item, User
11
from tests.utils.user import authentication_token_from_email
12
from tests.utils.utils import get_superuser_token_headers
13
14
15
@pytest.fixture(scope="session", autouse=True)
16
def db() -> Generator[Session, None, None]:
17
    with Session(engine) as session:
18
        init_db(session)
19
        yield session
20
        statement = delete(Item)
21
        session.execute(statement)
22
        statement = delete(User)
23
        session.execute(statement)
24
        session.commit()
25
26
27
@pytest.fixture(scope="module")
28
def client() -> Generator[TestClient, None, None]:
29
    with TestClient(app) as c:
30
        yield c
31
32
33
@pytest.fixture(scope="module")
34
def superuser_token_headers(client: TestClient) -> dict[str, str]:
35
    return get_superuser_token_headers(client)
36
37
38
@pytest.fixture(scope="module")
39
def normal_user_token_headers(client: TestClient, db: Session) -> dict[str, str]:
40
    return authentication_token_from_email(
41
        client=client, email=settings.EMAIL_TEST_USER, db=db
42
    )
43