first commit

This commit is contained in:
Justin Visser 2026-03-02 20:09:27 +01:00
commit b47f825d54
83 changed files with 10016 additions and 0 deletions

View file

60
backend/tests/conftest.py Normal file
View file

@ -0,0 +1,60 @@
import os
import tempfile
from collections.abc import Generator
from pathlib import Path
import pytest
from fastapi.testclient import TestClient
from app.config import Settings
TEST_ADMIN_TOKEN = "test-secret-token"
@pytest.fixture
def tmp_data_dir() -> Generator[Path, None, None]:
with tempfile.TemporaryDirectory() as tmpdir:
data_dir = Path(tmpdir)
(data_dir / "assets").mkdir()
yield data_dir
@pytest.fixture
def _env_settings(tmp_data_dir: Path) -> Generator[None, None, None]:
original_env = os.environ.copy()
os.environ["HANDIN_ADMIN_TOKEN"] = TEST_ADMIN_TOKEN
os.environ["HANDIN_DATA_DIR"] = str(tmp_data_dir)
from app.config import get_settings
get_settings.cache_clear()
yield
os.environ.clear()
os.environ.update(original_env)
get_settings.cache_clear()
@pytest.fixture
def settings(_env_settings: None) -> Settings:
from app.config import get_settings
s = get_settings()
assert isinstance(s, Settings)
return s
@pytest.fixture
def db(tmp_data_dir: Path) -> Path:
"""Return path to an initialized SQLite database in the temp dir."""
from app.database import init_db
db_path = tmp_data_dir / "handin.db"
init_db(db_path)
return db_path
@pytest.fixture
def client(_env_settings: None) -> TestClient:
from app.main import app
return TestClient(app)

View file

@ -0,0 +1,119 @@
import os
from pathlib import Path
from fastapi.testclient import TestClient
from tests.conftest import TEST_ADMIN_TOKEN
BEARER_HEADERS = {"Authorization": f"Bearer {TEST_ADMIN_TOKEN}"}
def test_upload_asset(client: TestClient) -> None:
resp = client.post(
"/api/assets",
headers=BEARER_HEADERS,
files={"file": ("test.pdf", b"fake pdf content", "application/pdf")},
)
assert resp.status_code == 201
data = resp.json()
assert "filename" in data
assert data["filename"] != "test.pdf"
assert data["filename"].endswith(".pdf")
def test_upload_asset_file_exists_on_disk(client: TestClient) -> None:
resp = client.post(
"/api/assets",
headers=BEARER_HEADERS,
files={"file": ("test.pdf", b"fake pdf content", "application/pdf")},
)
assert resp.status_code == 201
filename = resp.json()["filename"]
from app.config import get_settings
assets_dir = Path(get_settings().data_dir) / "assets"
file_path = assets_dir / filename
assert file_path.exists()
assert file_path.read_bytes() == b"fake pdf content"
def test_upload_asset_disallowed_type(client: TestClient) -> None:
resp = client.post(
"/api/assets",
headers=BEARER_HEADERS,
files={"file": ("malware.exe", b"evil bytes", "application/octet-stream")},
)
assert resp.status_code == 415
def test_upload_asset_too_large(client: TestClient) -> None:
from app.config import get_settings
original = os.environ.get("HANDIN_MAX_UPLOAD_BYTES")
os.environ["HANDIN_MAX_UPLOAD_BYTES"] = "100"
get_settings.cache_clear()
try:
resp = client.post(
"/api/assets",
headers=BEARER_HEADERS,
files={"file": ("big.pdf", b"x" * 200, "application/pdf")},
)
assert resp.status_code == 413
finally:
if original is None:
os.environ.pop("HANDIN_MAX_UPLOAD_BYTES", None)
else:
os.environ["HANDIN_MAX_UPLOAD_BYTES"] = original
get_settings.cache_clear()
def test_upload_asset_unauthorized(client: TestClient) -> None:
resp = client.post(
"/api/assets",
files={"file": ("test.pdf", b"fake pdf content", "application/pdf")},
)
assert resp.status_code == 401
def test_delete_asset(client: TestClient) -> None:
resp = client.post(
"/api/assets",
headers=BEARER_HEADERS,
files={"file": ("test.pdf", b"fake pdf content", "application/pdf")},
)
assert resp.status_code == 201
filename = resp.json()["filename"]
from app.config import get_settings
assets_dir = Path(get_settings().data_dir) / "assets"
del_resp = client.delete(f"/api/assets/{filename}", headers=BEARER_HEADERS)
assert del_resp.status_code == 204
assert not (assets_dir / filename).exists()
def test_delete_asset_not_found(client: TestClient) -> None:
resp = client.delete("/api/assets/nonexistent.pdf", headers=BEARER_HEADERS)
assert resp.status_code == 404
def test_delete_asset_unauthorized(client: TestClient) -> None:
resp = client.delete("/api/assets/somefile.pdf")
assert resp.status_code == 401
def test_serve_asset(client: TestClient) -> None:
content = b"fake pdf content for serving"
resp = client.post(
"/api/assets",
headers=BEARER_HEADERS,
files={"file": ("test.pdf", content, "application/pdf")},
)
assert resp.status_code == 201
filename = resp.json()["filename"]
get_resp = client.get(f"/api/assets/{filename}")
assert get_resp.status_code == 200
assert get_resp.content == content

View file

@ -0,0 +1,81 @@
from concurrent.futures import ThreadPoolExecutor
from fastapi.testclient import TestClient
from tests.conftest import TEST_ADMIN_TOKEN
BEARER_HEADERS = {"Authorization": f"Bearer {TEST_ADMIN_TOKEN}"}
def test_concurrent_creates(client: TestClient) -> None:
def create_segment(i: int) -> dict[str, object]:
resp = client.post(
"/api/segments",
json={"type": "markdown", "title": f"Seg {i}"},
headers=BEARER_HEADERS,
)
assert resp.status_code == 201
data: dict[str, object] = resp.json()
return data
with ThreadPoolExecutor(max_workers=10) as pool:
results = list(pool.map(create_segment, range(10)))
assert len(results) == 10
ids = {r["id"] for r in results}
assert len(ids) == 10
listing = client.get("/api/segments").json()
assert len(listing) == 10
sort_orders = sorted(s["sort_order"] for s in listing)
assert sort_orders == list(range(10))
def test_concurrent_create_and_reorder(client: TestClient) -> None:
segments = []
for i in range(3):
resp = client.post(
"/api/segments",
json={"type": "markdown", "title": f"Init {i}"},
headers=BEARER_HEADERS,
)
assert resp.status_code == 201
segments.append(resp.json())
seg_ids = [s["id"] for s in segments]
def create_extra(i: int) -> dict[str, object]:
resp = client.post(
"/api/segments",
json={"type": "markdown", "title": f"Extra {i}"},
headers=BEARER_HEADERS,
)
assert resp.status_code == 201
data: dict[str, object] = resp.json()
return data
def reorder() -> int:
resp = client.put(
"/api/segments/reorder",
json={"segment_ids": list(reversed(seg_ids))},
headers=BEARER_HEADERS,
)
return resp.status_code
with ThreadPoolExecutor(max_workers=10) as pool:
create_futures = [pool.submit(create_extra, i) for i in range(2)]
reorder_future = pool.submit(reorder)
for f in create_futures:
f.result()
reorder_status = reorder_future.result()
assert 200 <= reorder_status < 300
listing = client.get("/api/segments").json()
assert len(listing) == 5
sort_orders = [s["sort_order"] for s in listing]
assert len(set(sort_orders)) == 5

View file

@ -0,0 +1,78 @@
import sqlite3
from pathlib import Path
from app.database import get_connection, init_db
def test_init_db_creates_tables(tmp_data_dir: Path) -> None:
db_path = tmp_data_dir / "handin.db"
init_db(db_path)
conn = sqlite3.connect(db_path)
cursor = conn.execute(
"SELECT name FROM sqlite_master WHERE type='table' ORDER BY name"
)
tables = {row[0] for row in cursor.fetchall()}
conn.close()
assert "site" in tables
assert "segments" in tables
def test_init_db_idempotent(tmp_data_dir: Path) -> None:
db_path = tmp_data_dir / "handin.db"
init_db(db_path)
init_db(db_path)
conn = sqlite3.connect(db_path)
cursor = conn.execute(
"SELECT name FROM sqlite_master WHERE type='table' ORDER BY name"
)
tables = {row[0] for row in cursor.fetchall()}
conn.close()
assert "site" in tables
assert "segments" in tables
def test_wal_mode_enabled(tmp_data_dir: Path) -> None:
db_path = tmp_data_dir / "handin.db"
init_db(db_path)
conn = sqlite3.connect(db_path)
cursor = conn.execute("PRAGMA journal_mode")
mode = cursor.fetchone()[0]
conn.close()
assert mode == "wal"
def test_get_connection_busy_timeout(db: Path) -> None:
conn = get_connection(db)
cursor = conn.execute("PRAGMA busy_timeout")
timeout = cursor.fetchone()[0]
conn.close()
assert timeout == 5000
def test_segments_table_schema(db: Path) -> None:
conn = sqlite3.connect(db)
cursor = conn.execute("PRAGMA table_info(segments)")
columns = {row[1] for row in cursor.fetchall()}
conn.close()
expected = {
"id", "type", "sort_order", "title",
"content", "metadata", "created_at", "updated_at",
}
assert columns == expected
def test_site_table_schema(db: Path) -> None:
conn = sqlite3.connect(db)
cursor = conn.execute("PRAGMA table_info(site)")
columns = {row[1] for row in cursor.fetchall()}
conn.close()
assert columns == {"key", "value"}

View file

@ -0,0 +1,224 @@
from uuid import uuid4
from fastapi.testclient import TestClient
from tests.conftest import TEST_ADMIN_TOKEN
BEARER_HEADERS = {"Authorization": f"Bearer {TEST_ADMIN_TOKEN}"}
def _create_segment(
client: TestClient,
title: str = "Test",
seg_type: str = "markdown",
) -> dict[str, object]:
resp = client.post(
"/api/segments",
json={"type": seg_type, "title": title},
headers=BEARER_HEADERS,
)
assert resp.status_code == 201
data: dict[str, object] = resp.json()
return data
# --- Segment route tests ---
def test_list_segments_empty(client: TestClient) -> None:
resp = client.get("/api/segments")
assert resp.status_code == 200
assert resp.json() == []
def test_create_segment(client: TestClient) -> None:
data = _create_segment(client, title="Intro")
assert "id" in data
assert data["title"] == "Intro"
assert data["type"] == "markdown"
assert data["sort_order"] == 0
def test_create_segment_unauthorized(client: TestClient) -> None:
resp = client.post("/api/segments", json={"type": "markdown", "title": "X"})
assert resp.status_code == 401
def test_create_segment_wrong_token(client: TestClient) -> None:
resp = client.post(
"/api/segments",
json={"type": "markdown", "title": "X"},
headers={"Authorization": "Bearer wrong-token"},
)
assert resp.status_code == 401
def test_create_segment_via_query_param(client: TestClient) -> None:
resp = client.post(
f"/api/segments?token={TEST_ADMIN_TOKEN}",
json={"type": "markdown", "title": "Query Auth"},
)
assert resp.status_code == 201
def test_get_segment(client: TestClient) -> None:
created = _create_segment(client, title="Fetch Me")
seg_id = created["id"]
resp = client.get(f"/api/segments/{seg_id}")
assert resp.status_code == 200
assert resp.json()["title"] == "Fetch Me"
def test_get_segment_not_found(client: TestClient) -> None:
resp = client.get(f"/api/segments/{uuid4()}")
assert resp.status_code == 404
def test_update_segment(client: TestClient) -> None:
created = _create_segment(client, title="Original")
seg_id = created["id"]
resp = client.patch(
f"/api/segments/{seg_id}",
json={"title": "Updated"},
headers=BEARER_HEADERS,
)
assert resp.status_code == 200
assert resp.json()["title"] == "Updated"
def test_update_segment_not_found(client: TestClient) -> None:
resp = client.patch(
f"/api/segments/{uuid4()}",
json={"title": "Nope"},
headers=BEARER_HEADERS,
)
assert resp.status_code == 404
def test_update_segment_unauthorized(client: TestClient) -> None:
created = _create_segment(client, title="NoAuth")
seg_id = created["id"]
resp = client.patch(
f"/api/segments/{seg_id}",
json={"title": "Hacked"},
)
assert resp.status_code == 401
def test_delete_segment(client: TestClient) -> None:
created = _create_segment(client, title="Delete Me")
seg_id = created["id"]
resp = client.delete(f"/api/segments/{seg_id}", headers=BEARER_HEADERS)
assert resp.status_code == 204
resp2 = client.get(f"/api/segments/{seg_id}")
assert resp2.status_code == 404
def test_delete_segment_not_found(client: TestClient) -> None:
resp = client.delete(f"/api/segments/{uuid4()}", headers=BEARER_HEADERS)
assert resp.status_code == 404
def test_delete_segment_unauthorized(client: TestClient) -> None:
created = _create_segment(client, title="NoAuthDel")
seg_id = created["id"]
resp = client.delete(f"/api/segments/{seg_id}")
assert resp.status_code == 401
def test_reorder_segments(client: TestClient) -> None:
a = _create_segment(client, title="A")
b = _create_segment(client, title="B")
c = _create_segment(client, title="C")
resp = client.put(
"/api/segments/reorder",
json={"segment_ids": [c["id"], a["id"], b["id"]]},
headers=BEARER_HEADERS,
)
assert resp.status_code == 200
listing = client.get("/api/segments").json()
titles = [s["title"] for s in listing]
assert titles == ["C", "A", "B"]
def test_reorder_segments_invalid_ids(client: TestClient) -> None:
resp = client.put(
"/api/segments/reorder",
json={"segment_ids": [str(uuid4())]},
headers=BEARER_HEADERS,
)
assert resp.status_code == 400
def test_reorder_segments_unauthorized(client: TestClient) -> None:
resp = client.put(
"/api/segments/reorder",
json={"segment_ids": []},
)
assert resp.status_code == 401
# --- Site route tests ---
def test_get_site_title_default(client: TestClient) -> None:
resp = client.get("/api/site")
assert resp.status_code == 200
assert resp.json()["title"] == "Untitled Site"
def test_update_site_title(client: TestClient) -> None:
resp = client.put(
"/api/site",
json={"title": "My Course"},
headers=BEARER_HEADERS,
)
assert resp.status_code == 200
assert resp.json()["title"] == "My Course"
resp2 = client.get("/api/site")
assert resp2.json()["title"] == "My Course"
def test_update_site_title_unauthorized(client: TestClient) -> None:
resp = client.put("/api/site", json={"title": "Hacked"})
assert resp.status_code == 401
# --- Auth route tests ---
def test_auth_verify_valid_bearer(client: TestClient) -> None:
resp = client.get("/api/auth/verify", headers=BEARER_HEADERS)
assert resp.status_code == 200
assert resp.json() == {"valid": True}
def test_auth_verify_valid_query_param(client: TestClient) -> None:
resp = client.get(f"/api/auth/verify?token={TEST_ADMIN_TOKEN}")
assert resp.status_code == 200
assert resp.json() == {"valid": True}
def test_auth_verify_invalid(client: TestClient) -> None:
resp = client.get(
"/api/auth/verify",
headers={"Authorization": "Bearer wrong-token"},
)
assert resp.status_code == 401
def test_auth_verify_no_token(client: TestClient) -> None:
resp = client.get("/api/auth/verify")
assert resp.status_code == 401
# --- Health test ---
def test_health(client: TestClient) -> None:
resp = client.get("/api/health")
assert resp.status_code == 200
assert resp.json()["status"] == "ok"

View file

@ -0,0 +1,172 @@
import time
from pathlib import Path
from uuid import uuid4
import pytest
from app.models import SegmentCreateRequest, SegmentType, SegmentUpdateRequest
from app.services.segment_service import (
create_segment,
delete_segment,
get_segment,
list_segments,
reorder_segments,
update_segment,
)
from app.services.site_service import get_site_title, update_site_title
# --- Segment Service Tests ---
def test_create_segment(db: Path) -> None:
request = SegmentCreateRequest(
type=SegmentType.MARKDOWN,
title="Intro",
content="Hello world",
)
segment = create_segment(db, request)
assert segment.id is not None
assert segment.sort_order == 0
assert segment.title == "Intro"
assert segment.type == SegmentType.MARKDOWN
assert segment.content == "Hello world"
assert segment.created_at == segment.updated_at
def test_create_segment_auto_increments_sort_order(db: Path) -> None:
for i in range(3):
request = SegmentCreateRequest(
type=SegmentType.MARKDOWN,
title=f"Segment {i}",
)
segment = create_segment(db, request)
assert segment.sort_order == i
def test_list_segments_empty(db: Path) -> None:
segments = list_segments(db)
assert segments == []
def test_list_segments_ordered(db: Path) -> None:
titles = ["First", "Second", "Third"]
for title in titles:
create_segment(
db,
SegmentCreateRequest(type=SegmentType.MARKDOWN, title=title),
)
segments = list_segments(db)
assert [s.title for s in segments] == titles
assert [s.sort_order for s in segments] == [0, 1, 2]
def test_get_segment_found(db: Path) -> None:
created = create_segment(
db,
SegmentCreateRequest(type=SegmentType.PDF, title="Slides"),
)
fetched = get_segment(db, created.id)
assert fetched is not None
assert fetched.id == created.id
assert fetched.title == "Slides"
assert fetched.type == SegmentType.PDF
def test_get_segment_not_found(db: Path) -> None:
result = get_segment(db, uuid4())
assert result is None
def test_update_segment_title(db: Path) -> None:
created = create_segment(
db,
SegmentCreateRequest(
type=SegmentType.MARKDOWN,
title="Old Title",
content="Keep me",
),
)
time.sleep(0.01)
updated = update_segment(
db,
created.id,
SegmentUpdateRequest(title="New Title"),
)
assert updated is not None
assert updated.title == "New Title"
assert updated.content == "Keep me"
assert updated.updated_at > updated.created_at
def test_update_segment_not_found(db: Path) -> None:
result = update_segment(
db,
uuid4(),
SegmentUpdateRequest(title="Nope"),
)
assert result is None
def test_delete_segment(db: Path) -> None:
created = create_segment(
db,
SegmentCreateRequest(type=SegmentType.MARKDOWN, title="Bye"),
)
assert delete_segment(db, created.id) is True
assert get_segment(db, created.id) is None
def test_delete_segment_not_found(db: Path) -> None:
assert delete_segment(db, uuid4()) is False
def test_reorder_segments(db: Path) -> None:
a = create_segment(
db,
SegmentCreateRequest(type=SegmentType.MARKDOWN, title="A"),
)
b = create_segment(
db,
SegmentCreateRequest(type=SegmentType.MARKDOWN, title="B"),
)
c = create_segment(
db,
SegmentCreateRequest(type=SegmentType.MARKDOWN, title="C"),
)
reorder_segments(db, [c.id, a.id, b.id])
segments = list_segments(db)
assert [s.title for s in segments] == ["C", "A", "B"]
assert [s.sort_order for s in segments] == [0, 1, 2]
def test_reorder_segments_invalid_ids(db: Path) -> None:
create_segment(
db,
SegmentCreateRequest(type=SegmentType.MARKDOWN, title="Only"),
)
with pytest.raises(ValueError):
reorder_segments(db, [uuid4()])
# --- Site Service Tests ---
def test_get_site_title_default(db: Path) -> None:
assert get_site_title(db) == "Untitled Site"
def test_update_and_get_site_title(db: Path) -> None:
update_site_title(db, "My Course")
assert get_site_title(db) == "My Course"
def test_update_site_title_overwrites(db: Path) -> None:
update_site_title(db, "First")
update_site_title(db, "Second")
assert get_site_title(db) == "Second"