first round of review

This commit is contained in:
counterweight 2025-12-18 22:24:46 +01:00
parent 7ebfb7a2dd
commit da5a0d03eb
Signed by: counterweight
GPG key ID: 883EDBAA726BD96C
14 changed files with 362 additions and 244 deletions

View file

@ -1,4 +1,9 @@
import os
from contextlib import asynccontextmanager
# Set required env vars before importing app
os.environ.setdefault("SECRET_KEY", "test-secret-key-for-testing-only")
import pytest
from httpx import ASGITransport, AsyncClient
from sqlalchemy.ext.asyncio import create_async_engine, async_sessionmaker
@ -12,8 +17,38 @@ TEST_DATABASE_URL = os.getenv(
)
class ClientFactory:
"""Factory for creating httpx clients with optional cookies."""
def __init__(self, transport, base_url):
self._transport = transport
self._base_url = base_url
@asynccontextmanager
async def create(self, cookies: dict | None = None):
"""Create a new client, optionally with cookies set."""
async with AsyncClient(
transport=self._transport,
base_url=self._base_url,
cookies=cookies or {},
) as client:
yield client
async def request(self, method: str, url: str, **kwargs):
"""Make a one-off request without cookies."""
async with self.create() as client:
return await client.request(method, url, **kwargs)
async def get(self, url: str, **kwargs):
return await self.request("GET", url, **kwargs)
async def post(self, url: str, **kwargs):
return await self.request("POST", url, **kwargs)
@pytest.fixture(scope="function")
async def client():
async def client_factory():
"""Fixture that provides a factory for creating clients."""
engine = create_async_engine(TEST_DATABASE_URL)
session_factory = async_sessionmaker(engine, expire_on_commit=False)
@ -28,8 +63,17 @@ async def client():
app.dependency_overrides[get_db] = override_get_db
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as c:
yield c
transport = ASGITransport(app=app)
factory = ClientFactory(transport, "http://test")
yield factory
app.dependency_overrides.clear()
await engine.dispose()
@pytest.fixture(scope="function")
async def client(client_factory):
"""Fixture for a simple client without cookies (backwards compatible)."""
async with client_factory.create() as c:
yield c

View file

@ -1,28 +1,14 @@
import pytest
import uuid
from auth import COOKIE_NAME
def unique_email(prefix: str = "test") -> str:
"""Generate a unique email for tests sharing the same database."""
return f"{prefix}-{uuid.uuid4().hex[:8]}@example.com"
async def create_user_and_get_token(client, email: str = None, password: str = "testpass123") -> str:
"""Helper to create a user and return their auth token."""
if email is None:
email = unique_email()
response = await client.post(
"/api/auth/register",
json={"email": email, "password": password},
)
return response.json()["access_token"]
def auth_header(token: str) -> dict:
"""Helper to create auth headers from token."""
return {"Authorization": f"Bearer {token}"}
# Registration tests
@pytest.mark.asyncio
async def test_register_success(client):
@ -33,10 +19,10 @@ async def test_register_success(client):
)
assert response.status_code == 200
data = response.json()
assert "access_token" in data
assert data["token_type"] == "bearer"
assert data["user"]["email"] == email
assert "id" in data["user"]
assert data["email"] == email
assert "id" in data
# Cookie should be set
assert COOKIE_NAME in response.cookies
@pytest.mark.asyncio
@ -101,9 +87,8 @@ async def test_login_success(client):
)
assert response.status_code == 200
data = response.json()
assert "access_token" in data
assert data["token_type"] == "bearer"
assert data["user"]["email"] == email
assert data["email"] == email
assert COOKIE_NAME in response.cookies
@pytest.mark.asyncio
@ -148,10 +133,20 @@ async def test_login_missing_fields(client):
# Get current user tests
@pytest.mark.asyncio
async def test_get_me_success(client):
async def test_get_me_success(client_factory):
email = unique_email("me")
token = await create_user_and_get_token(client, email)
response = await client.get("/api/auth/me", headers=auth_header(token))
# Register and get cookies
reg_response = await client_factory.post(
"/api/auth/register",
json={"email": email, "password": "password123"},
)
cookies = dict(reg_response.cookies)
# Use authenticated client
async with client_factory.create(cookies=cookies) as authed:
response = await authed.get("/api/auth/me")
assert response.status_code == 200
data = response.json()
assert data["email"] == email
@ -159,94 +154,89 @@ async def test_get_me_success(client):
@pytest.mark.asyncio
async def test_get_me_no_token(client):
async def test_get_me_no_cookie(client):
response = await client.get("/api/auth/me")
# HTTPBearer returns 401/403 when credentials are missing
assert response.status_code in [401, 403]
assert response.status_code == 401
@pytest.mark.asyncio
async def test_get_me_invalid_token(client):
response = await client.get(
"/api/auth/me",
headers={"Authorization": "Bearer invalidtoken123"},
)
async def test_get_me_invalid_cookie(client_factory):
async with client_factory.create(cookies={COOKIE_NAME: "invalidtoken123"}) as authed:
response = await authed.get("/api/auth/me")
assert response.status_code == 401
assert response.json()["detail"] == "Invalid authentication credentials"
@pytest.mark.asyncio
async def test_get_me_malformed_auth_header(client):
response = await client.get(
"/api/auth/me",
headers={"Authorization": "NotBearer token123"},
)
# Invalid scheme returns 401/403
assert response.status_code in [401, 403]
@pytest.mark.asyncio
async def test_get_me_expired_token(client):
response = await client.get(
"/api/auth/me",
headers={"Authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOjEsImV4cCI6MH0.invalid"},
)
async def test_get_me_expired_token(client_factory):
bad_token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOjEsImV4cCI6MH0.invalid"
async with client_factory.create(cookies={COOKIE_NAME: bad_token}) as authed:
response = await authed.get("/api/auth/me")
assert response.status_code == 401
# Token validation tests
# Cookie validation tests
@pytest.mark.asyncio
async def test_token_from_register_works_for_me(client):
async def test_cookie_from_register_works_for_me(client_factory):
email = unique_email("tokentest")
register_response = await client.post(
reg_response = await client_factory.post(
"/api/auth/register",
json={"email": email, "password": "password123"},
)
token = register_response.json()["access_token"]
cookies = dict(reg_response.cookies)
async with client_factory.create(cookies=cookies) as authed:
me_response = await authed.get("/api/auth/me")
me_response = await client.get("/api/auth/me", headers=auth_header(token))
assert me_response.status_code == 200
assert me_response.json()["email"] == email
@pytest.mark.asyncio
async def test_token_from_login_works_for_me(client):
async def test_cookie_from_login_works_for_me(client_factory):
email = unique_email("logintoken")
await client.post(
await client_factory.post(
"/api/auth/register",
json={"email": email, "password": "password123"},
)
login_response = await client.post(
login_response = await client_factory.post(
"/api/auth/login",
json={"email": email, "password": "password123"},
)
token = login_response.json()["access_token"]
cookies = dict(login_response.cookies)
async with client_factory.create(cookies=cookies) as authed:
me_response = await authed.get("/api/auth/me")
me_response = await client.get("/api/auth/me", headers=auth_header(token))
assert me_response.status_code == 200
assert me_response.json()["email"] == email
# Multiple users tests
@pytest.mark.asyncio
async def test_multiple_users_isolated(client):
async def test_multiple_users_isolated(client_factory):
email1 = unique_email("user1")
email2 = unique_email("user2")
resp1 = await client.post(
resp1 = await client_factory.post(
"/api/auth/register",
json={"email": email1, "password": "password1"},
)
resp2 = await client.post(
resp2 = await client_factory.post(
"/api/auth/register",
json={"email": email2, "password": "password2"},
)
token1 = resp1.json()["access_token"]
token2 = resp2.json()["access_token"]
cookies1 = dict(resp1.cookies)
cookies2 = dict(resp2.cookies)
me1 = await client.get("/api/auth/me", headers=auth_header(token1))
me2 = await client.get("/api/auth/me", headers=auth_header(token2))
async with client_factory.create(cookies=cookies1) as user1:
me1 = await user1.get("/api/auth/me")
async with client_factory.create(cookies=cookies2) as user2:
me2 = await user2.get("/api/auth/me")
assert me1.json()["email"] == email1
assert me2.json()["email"] == email2
@ -280,3 +270,21 @@ async def test_case_sensitive_password(client):
json={"email": email, "password": "password123"},
)
assert response.status_code == 401
# Logout tests
@pytest.mark.asyncio
async def test_logout_success(client_factory):
email = unique_email("logout")
reg_response = await client_factory.post(
"/api/auth/register",
json={"email": email, "password": "password123"},
)
cookies = dict(reg_response.cookies)
async with client_factory.create(cookies=cookies) as authed:
logout_response = await authed.post("/api/auth/logout")
assert logout_response.status_code == 200
assert logout_response.json() == {"ok": True}

View file

@ -1,128 +1,149 @@
import pytest
import uuid
from auth import COOKIE_NAME
def unique_email(prefix: str = "counter") -> str:
"""Generate a unique email for tests sharing the same database."""
return f"{prefix}-{uuid.uuid4().hex[:8]}@example.com"
async def create_user_and_get_headers(client, email: str = None) -> dict:
"""Create a user and return auth headers for authenticated requests."""
if email is None:
email = unique_email()
response = await client.post(
"/api/auth/register",
json={"email": email, "password": "testpass123"},
)
token = response.json()["access_token"]
return {"Authorization": f"Bearer {token}"}
# Protected endpoint tests - without auth
@pytest.mark.asyncio
async def test_get_counter_requires_auth(client):
response = await client.get("/api/counter")
assert response.status_code in [401, 403]
assert response.status_code == 401
@pytest.mark.asyncio
async def test_increment_counter_requires_auth(client):
response = await client.post("/api/counter/increment")
assert response.status_code in [401, 403]
@pytest.mark.asyncio
async def test_get_counter_invalid_token(client):
response = await client.get(
"/api/counter",
headers={"Authorization": "Bearer invalidtoken"},
)
assert response.status_code == 401
@pytest.mark.asyncio
async def test_increment_counter_invalid_token(client):
response = await client.post(
"/api/counter/increment",
headers={"Authorization": "Bearer invalidtoken"},
)
async def test_get_counter_invalid_cookie(client_factory):
async with client_factory.create(cookies={COOKIE_NAME: "invalidtoken"}) as authed:
response = await authed.get("/api/counter")
assert response.status_code == 401
@pytest.mark.asyncio
async def test_increment_counter_invalid_cookie(client_factory):
async with client_factory.create(cookies={COOKIE_NAME: "invalidtoken"}) as authed:
response = await authed.post("/api/counter/increment")
assert response.status_code == 401
# Authenticated counter tests
@pytest.mark.asyncio
async def test_get_counter_authenticated(client):
auth_headers = await create_user_and_get_headers(client)
response = await client.get("/api/counter", headers=auth_headers)
async def test_get_counter_authenticated(client_factory):
reg = await client_factory.post(
"/api/auth/register",
json={"email": unique_email(), "password": "testpass123"},
)
cookies = dict(reg.cookies)
async with client_factory.create(cookies=cookies) as authed:
response = await authed.get("/api/counter")
assert response.status_code == 200
assert "value" in response.json()
@pytest.mark.asyncio
async def test_increment_counter(client):
auth_headers = await create_user_and_get_headers(client)
async def test_increment_counter(client_factory):
reg = await client_factory.post(
"/api/auth/register",
json={"email": unique_email(), "password": "testpass123"},
)
cookies = dict(reg.cookies)
# Get current value
before = await client.get("/api/counter", headers=auth_headers)
before_value = before.json()["value"]
# Increment
response = await client.post("/api/counter/increment", headers=auth_headers)
assert response.status_code == 200
assert response.json()["value"] == before_value + 1
async with client_factory.create(cookies=cookies) as authed:
# Get current value
before = await authed.get("/api/counter")
before_value = before.json()["value"]
# Increment
response = await authed.post("/api/counter/increment")
assert response.status_code == 200
assert response.json()["value"] == before_value + 1
@pytest.mark.asyncio
async def test_increment_counter_multiple(client):
auth_headers = await create_user_and_get_headers(client)
async def test_increment_counter_multiple(client_factory):
reg = await client_factory.post(
"/api/auth/register",
json={"email": unique_email(), "password": "testpass123"},
)
cookies = dict(reg.cookies)
# Get starting value
before = await client.get("/api/counter", headers=auth_headers)
start = before.json()["value"]
# Increment 3 times
await client.post("/api/counter/increment", headers=auth_headers)
await client.post("/api/counter/increment", headers=auth_headers)
response = await client.post("/api/counter/increment", headers=auth_headers)
assert response.json()["value"] == start + 3
async with client_factory.create(cookies=cookies) as authed:
# Get starting value
before = await authed.get("/api/counter")
start = before.json()["value"]
# Increment 3 times
await authed.post("/api/counter/increment")
await authed.post("/api/counter/increment")
response = await authed.post("/api/counter/increment")
assert response.json()["value"] == start + 3
@pytest.mark.asyncio
async def test_get_counter_after_increment(client):
auth_headers = await create_user_and_get_headers(client)
async def test_get_counter_after_increment(client_factory):
reg = await client_factory.post(
"/api/auth/register",
json={"email": unique_email(), "password": "testpass123"},
)
cookies = dict(reg.cookies)
before = await client.get("/api/counter", headers=auth_headers)
start = before.json()["value"]
await client.post("/api/counter/increment", headers=auth_headers)
await client.post("/api/counter/increment", headers=auth_headers)
response = await client.get("/api/counter", headers=auth_headers)
assert response.json()["value"] == start + 2
async with client_factory.create(cookies=cookies) as authed:
before = await authed.get("/api/counter")
start = before.json()["value"]
await authed.post("/api/counter/increment")
await authed.post("/api/counter/increment")
response = await authed.get("/api/counter")
assert response.json()["value"] == start + 2
# Counter is shared between users
@pytest.mark.asyncio
async def test_counter_shared_between_users(client):
headers1 = await create_user_and_get_headers(client, unique_email("share1"))
async def test_counter_shared_between_users(client_factory):
# Create first user
reg1 = await client_factory.post(
"/api/auth/register",
json={"email": unique_email("share1"), "password": "testpass123"},
)
cookies1 = dict(reg1.cookies)
# Get starting value
before = await client.get("/api/counter", headers=headers1)
start = before.json()["value"]
async with client_factory.create(cookies=cookies1) as user1:
# Get starting value
before = await user1.get("/api/counter")
start = before.json()["value"]
await user1.post("/api/counter/increment")
await user1.post("/api/counter/increment")
await client.post("/api/counter/increment", headers=headers1)
await client.post("/api/counter/increment", headers=headers1)
# Create second user - should see the increments
reg2 = await client_factory.post(
"/api/auth/register",
json={"email": unique_email("share2"), "password": "testpass123"},
)
cookies2 = dict(reg2.cookies)
# Second user sees the increments
headers2 = await create_user_and_get_headers(client, unique_email("share2"))
response = await client.get("/api/counter", headers=headers2)
assert response.json()["value"] == start + 2
# Second user increments
await client.post("/api/counter/increment", headers=headers2)
async with client_factory.create(cookies=cookies2) as user2:
response = await user2.get("/api/counter")
assert response.json()["value"] == start + 2
# Second user increments
await user2.post("/api/counter/increment")
# First user sees the increment
response = await client.get("/api/counter", headers=headers1)
assert response.json()["value"] == start + 3
async with client_factory.create(cookies=cookies1) as user1:
response = await user1.get("/api/counter")
assert response.json()["value"] == start + 3