Skip to content

Commit ab7dd25

Browse files
authored
Merge pull request #233 from grillazz/switch-logger-to-rotoger
refactor: update test fixtures and remove unused environment variables
2 parents af405b6 + 2373ea2 commit ab7dd25

6 files changed

Lines changed: 51 additions & 16 deletions

File tree

.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_auth.py

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -37,17 +37,28 @@ async def test_add_user(client: AsyncClient):
3737

3838
# TODO: parametrize test with diff urls including 404 and 401
3939
async def test_get_token(client: AsyncClient):
40-
payload = {"email": "joe@grillazz.com", "password": "s1lly"}
40+
# Create the user first
41+
user_payload = {
42+
"email": "joe@grillazz.com",
43+
"first_name": "Joe",
44+
"last_name": "Garcia",
45+
"password": "s1lly",
46+
}
47+
create_user_response = await client.post("/user/", json=user_payload)
48+
assert create_user_response.status_code == status.HTTP_201_CREATED
49+
50+
# Now request the token
51+
token_payload = {"email": "joe@grillazz.com", "password": "s1lly"}
4152
response = await client.post(
4253
"/user/token",
43-
data=payload,
54+
data=token_payload,
4455
headers={"Content-Type": "application/x-www-form-urlencoded"},
4556
)
4657
assert response.status_code == status.HTTP_201_CREATED
4758
claimset = jwt.decode(
4859
response.json()["access_token"], options={"verify_signature": False}
4960
)
50-
assert claimset["email"] == payload["email"]
61+
assert claimset["email"] == token_payload["email"]
5162
assert claimset["expiry"] == IsPositiveFloat()
5263
assert claimset["platform"] == "python-httpx/0.28.1"
5364

tests/api/test_stuff.py

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,9 @@
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

9+
from app.models import Stuff
810
from app.schemas.stuff import StuffSchema
911

1012
pytestmark = pytest.mark.anyio
@@ -32,22 +34,26 @@ 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
)
43+
# test if db_session and client share the same in-memory db and rollback works
4144
stuff = StuffFactory.build(factory_use_constructors=True).model_dump(mode="json")
42-
await client.post("/stuff", json=stuff)
43-
name = stuff["name"]
45+
stuff = Stuff(**stuff)
46+
name = stuff.name
47+
db_session.add(stuff)
48+
await db_session.commit()
49+
4450
response = await client.get(f"/stuff/{name}")
4551
assert response.status_code == status.HTTP_200_OK
4652
assert response.json() == snapshot(
4753
{
4854
"id": IsUUID(4),
49-
"name": stuff["name"],
50-
"description": stuff["description"],
55+
"name": stuff.name,
56+
"description": stuff.description,
5157
}
5258
)
5359

tests/conftest.py

Lines changed: 25 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
from sqlalchemy import text
77
from sqlalchemy.exc import ProgrammingError
88

9-
from app.database import engine, get_db, get_test_db, test_engine
9+
from app.database import TestAsyncSessionFactory, engine, get_db, test_engine
1010
from app.main import app
1111
from app.models.base import Base
1212
from app.redis import get_redis
@@ -43,7 +43,7 @@ def _create_db_schema(conn) -> None:
4343
pass
4444

4545

46-
@pytest.fixture(scope="session")
46+
@pytest.fixture(scope="session", autouse=True)
4747
async def start_db():
4848
# The `engine` is configured for the default 'postgres' database.
4949
# We connect to it and create the test database.
@@ -63,16 +63,36 @@ async def start_db():
6363
await test_engine.dispose()
6464

6565

66-
@pytest.fixture(scope="session")
67-
async def client(start_db) -> AsyncGenerator[AsyncClient, Any]: # noqa: ARG001
66+
@pytest.fixture()
67+
async def db_session():
68+
connection = await test_engine.connect()
69+
transaction = await connection.begin()
70+
session = TestAsyncSessionFactory(bind=connection)
71+
72+
try:
73+
yield session
74+
finally:
75+
# Rollback the overall transaction, restoring the state before the test ran.
76+
await session.close()
77+
if transaction.is_active:
78+
await transaction.rollback()
79+
await connection.close()
80+
81+
82+
@pytest.fixture(scope="function")
83+
async def client(db_session) -> AsyncGenerator[AsyncClient, Any]:
6884
transport = ASGITransport(
6985
app=app,
7086
)
87+
88+
async def override_get_db():
89+
yield db_session
90+
7191
async with AsyncClient(
7292
base_url="http://testserver/v1",
7393
headers={"Content-Type": "application/json"},
7494
transport=transport,
7595
) as test_client:
76-
app.dependency_overrides[get_db] = get_test_db
96+
app.dependency_overrides[get_db] = override_get_db
7797
app.redis = await get_redis()
7898
yield test_client

0 commit comments

Comments
 (0)