Skip to content

Commit e9ea2c6

Browse files
committed
refactor: update test fixtures and remove unused environment variables
1 parent 88a66b1 commit e9ea2c6

File tree

5 files changed

+42
-15
lines changed

5 files changed

+42
-15
lines changed

.env

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@ POSTGRES_PORT=5432
77
POSTGRES_DB=devdb
88
POSTGRES_USER=devdb
99
POSTGRES_TEST_DB=testdb
10-
POSTGRES_TEST_USER=testdb
1110
POSTGRES_PASSWORD=secret
1211

1312
# Redis

app/config.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,6 @@ class Settings(BaseSettings):
3333
POSTGRES_PASSWORD: str
3434
POSTGRES_HOST: str
3535
POSTGRES_DB: str
36-
POSTGRES_TEST_USER: str
3736
POSTGRES_TEST_DB: str
3837

3938
@computed_field

app/database.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@
1818
test_engine = create_async_engine(
1919
global_settings.test_asyncpg_url.unicode_string(),
2020
future=True,
21-
echo=True,
21+
echo=False,
2222
)
2323

2424
# expire_on_commit=False will prevent attributes from being expired

tests/api/test_stuff.py

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,10 @@
44
from httpx import AsyncClient
55
from inline_snapshot import snapshot
66
from polyfactory.factories.pydantic_factory import ModelFactory
7+
from sqlalchemy.ext.asyncio import AsyncSession
78

89
from app.schemas.stuff import StuffSchema
10+
from app.models import Stuff
911

1012
pytestmark = pytest.mark.anyio
1113

@@ -14,7 +16,7 @@ class StuffFactory(ModelFactory[StuffSchema]):
1416
__model__ = StuffSchema
1517

1618

17-
async def test_add_stuff(client: AsyncClient):
19+
async def test_add_stuff(client: AsyncClient, db_session: AsyncSession):
1820
stuff = StuffFactory.build(factory_use_constructors=True).model_dump(mode="json")
1921
response = await client.post("/stuff", json=stuff)
2022
assert response.status_code == status.HTTP_201_CREATED
@@ -32,22 +34,27 @@ async def test_add_stuff(client: AsyncClient):
3234
)
3335

3436

35-
async def test_get_stuff(client: AsyncClient):
37+
async def test_get_stuff(client: AsyncClient, db_session: AsyncSession):
3638
response = await client.get("/stuff/nonexistent")
3739
assert response.status_code == status.HTTP_404_NOT_FOUND
3840
assert response.json() == snapshot(
3941
{"no_response": "The requested resource was not found"}
4042
)
4143
stuff = StuffFactory.build(factory_use_constructors=True).model_dump(mode="json")
42-
await client.post("/stuff", json=stuff)
43-
name = stuff["name"]
44+
# await client.post("/stuff", json=stuff)
45+
# name = stuff["name"]
46+
stuff = Stuff(**stuff)
47+
name = stuff.name
48+
db_session.add(stuff)
49+
await db_session.commit()
50+
4451
response = await client.get(f"/stuff/{name}")
4552
assert response.status_code == status.HTTP_200_OK
4653
assert response.json() == snapshot(
4754
{
4855
"id": IsUUID(4),
49-
"name": stuff["name"],
50-
"description": stuff["description"],
56+
"name": stuff.name,
57+
"description": stuff.description,
5158
}
5259
)
5360

tests/conftest.py

Lines changed: 28 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,12 @@
22
from typing import Any
33

44
import pytest
5+
from fastapi.exceptions import ResponseValidationError
56
from httpx import ASGITransport, AsyncClient
67
from sqlalchemy import text
7-
from sqlalchemy.exc import ProgrammingError
8+
from sqlalchemy.exc import ProgrammingError, SQLAlchemyError
89

9-
from app.database import engine, get_db, get_test_db, test_engine
10+
from app.database import engine, get_db, test_engine, TestAsyncSessionFactory
1011
from app.main import app
1112
from app.models.base import Base
1213
from app.redis import get_redis
@@ -43,7 +44,7 @@ def _create_db_schema(conn) -> None:
4344
pass
4445

4546

46-
@pytest.fixture(scope="session")
47+
@pytest.fixture(scope="session", autouse=True)
4748
async def start_db():
4849
# The `engine` is configured for the default 'postgres' database.
4950
# We connect to it and create the test database.
@@ -63,16 +64,37 @@ async def start_db():
6364
await test_engine.dispose()
6465

6566

66-
@pytest.fixture(scope="session")
67-
async def client(start_db) -> AsyncGenerator[AsyncClient, Any]: # noqa: ARG001
67+
@pytest.fixture()
68+
async def db_session():
69+
connection = await test_engine.connect()
70+
transaction = await connection.begin()
71+
session = TestAsyncSessionFactory(bind=connection)
72+
73+
try:
74+
yield session
75+
finally:
76+
# Rollback the overall transaction, restoring the state before the test ran.
77+
await session.close()
78+
if transaction.is_active:
79+
await transaction.rollback()
80+
await connection.close()
81+
82+
83+
@pytest.fixture(scope="function")
84+
async def client(db_session) -> AsyncGenerator[AsyncClient, Any]: # noqa: ARG001
6885
transport = ASGITransport(
6986
app=app,
7087
)
88+
89+
async def override_get_db():
90+
yield db_session
91+
await db_session.commit()
92+
7193
async with AsyncClient(
7294
base_url="http://testserver/v1",
7395
headers={"Content-Type": "application/json"},
7496
transport=transport,
7597
) as test_client:
76-
app.dependency_overrides[get_db] = get_test_db
98+
app.dependency_overrides[get_db] = override_get_db
7799
app.redis = await get_redis()
78100
yield test_client

0 commit comments

Comments
 (0)