chore: reorganize test files into domain-specific subdirectories

This commit is contained in:
2026-06-13 14:32:33 +00:00
parent 8eac4cafba
commit eccec02336
268 changed files with 20634 additions and 9206 deletions
View File
+181
View File
@@ -0,0 +1,181 @@
# retoor <retoor@molodetz.nl>
import time
from datetime import datetime, timezone
import pytest
import requests
from tests.conftest import BASE_URL
from devplacepy.database import get_table, refresh_snapshot, set_setting
from devplacepy.utils import generate_uid, make_combined_slug
JSON_audit_log = {"Accept": "application/json"}
_counter_audit_log = [0]
@pytest.fixture(scope="module", autouse=True)
def _audit_test_settings(app_server):
# On a fresh DB init_db skips seeding the operational/upload settings (its
# `tables` snapshot predates site_settings creation), so those rows are
# absent and the admin settings form would INSERT them as "" - which both
# closes registration and makes consumers that do int("") crash. Seed sane
# values here so the form's empty submissions are skipped (existing key), and
# lift the per-IP rate limit since this file fires many mutating requests.
for key, value in {
"rate_limit_per_minute": "1000000",
"rate_limit_window_seconds": "60",
"registration_open": "1",
"maintenance_mode": "0",
"max_upload_size_mb": "10",
"allowed_file_types": "",
"max_attachments_per_resource": "10",
"session_max_age_days": "7",
"session_remember_days": "30",
"news_service_interval": "3600",
"news_grade_threshold": "7",
}.items():
set_setting(key, value)
yield
def _db_user(name):
# the user is created by the server subprocess; refresh the test-process
# SQLite snapshot before reading it back across the process boundary.
refresh_snapshot()
return get_table("users").find_one(username=name)
def _unique(prefix="au"):
_counter_audit_log[0] += 1
return f"{prefix}{int(time.time() * 1000)}{_counter_audit_log[0]}"
def _member():
name = _unique("aumem")
s = requests.Session()
s.post(
f"{BASE_URL}/auth/signup",
data={
"username": name,
"email": f"{name}@t.dev",
"password": "secret123",
"confirm_password": "secret123",
},
allow_redirects=True,
)
return s, name
def _member_key():
_, name = _member()
return _db_user(name)["api_key"]
def _admin(seeded_db):
# authenticate via the seeded admin's API key (header auth) rather than a
# login POST - GET reads are exempt from the rate limiter, so reusing this
# across the file's many tests never counts against the per-IP write budget.
key = _db_user("alice_test")["api_key"]
s = requests.Session()
s.headers.update({"X-API-KEY": key})
return s
def _audit(admin, **params):
r = admin.get(f"{BASE_URL}/admin/audit-log", headers=JSON_audit_log, params=params)
assert r.status_code == 200, r.text[:300]
return r.json()
def _find(admin, event_key, predicate):
data = _audit(admin, event_key=event_key)
for entry in data["entries"]:
if predicate(entry):
return entry
return None
def _new_post(session, body="audited post body here"):
return session.post(
f"{BASE_URL}/posts/create",
headers=JSON_audit_log,
data={"title": _unique("aup"), "content": body, "topic": "devlog"},
).json()["data"]
def _new_project(session):
return session.post(
f"{BASE_URL}/projects/create",
headers=JSON_audit_log,
data={
"title": _unique("aupr"),
"description": "audited project description text",
"project_type": "software",
"status": "In Development",
"platforms": "",
},
).json()["data"]
def _seed_news_audit_log():
uid = generate_uid()
title = _unique("aunews")
get_table("news").insert(
{
"uid": uid,
"slug": make_combined_slug(title, uid),
"title": title,
"external_id": uid,
"status": "draft",
"featured": 0,
"show_on_landing": 0,
"grade": 5,
"source_name": "AuditTest",
"synced_at": datetime.now(timezone.utc).isoformat(),
"description": "audited news article",
}
)
refresh_snapshot()
return uid
def test_login_failure_is_recorded(seeded_db):
email = f"{_unique('aufail')}@t.dev"
requests.post(
f"{BASE_URL}/auth/login",
data={"email": email, "password": "wrongpassword"},
allow_redirects=False,
)
admin = _admin(seeded_db)
event = _find(
admin,
"auth.login.failure",
lambda e: email in (e.get("summary") or ""),
)
assert event is not None
assert event["result"] == "failure"
assert event["actor_kind"] == "guest"
def test_filter_by_result(seeded_db):
# ensure at least one failure exists
requests.post(
f"{BASE_URL}/auth/login",
data={"email": f"{_unique('aurf')}@t.dev", "password": "nope"},
allow_redirects=False,
)
admin = _admin(seeded_db)
data = _audit(admin, result="failure")
assert data["pagination"]["total"] >= 1
assert all(e["result"] == "failure" for e in data["entries"])
def test_rate_limit_block_recorded(monkeypatch):
# The limiter is disabled suite-wide (conftest sets DEVPLACE_DISABLE_RATE_LIMIT),
# and the shared server runs in its own process, so this runs in-process with the
# limiter re-enabled for itself - the same approach as test_ratelimit.py - and
# asserts the block emits the security.rate_limit.block audit row.
import devplacepy.main as m
from starlette.testclient import TestClient
monkeypatch.setattr(m, "RATE_LIMIT_DISABLED", False)
monkeypatch.setattr(
m,
"get_int_setting",
lambda key, default: {
"rate_limit_per_minute": 1,
"rate_limit_window_seconds": 60,
}.get(key, default),
)
m._rate_limit_store.clear()
ip = "203.0.113.77"
client = TestClient(m.app)
codes = [
client.post(
"/auth/login",
data={"email": "x@y.dev", "password": "nope"},
headers={"X-Real-IP": ip},
).status_code
for _ in range(4)
]
assert 429 in codes, codes
event = get_table("audit_log").find_one(
event_key="security.rate_limit.block", result="denied"
)
assert event is not None
+145
View File
@@ -0,0 +1,145 @@
# retoor <retoor@molodetz.nl>
import time
from datetime import datetime, timezone
import pytest
import requests
from tests.conftest import BASE_URL
from devplacepy.database import get_table, refresh_snapshot, set_setting
from devplacepy.utils import generate_uid, make_combined_slug
JSON_audit_log = {"Accept": "application/json"}
_counter_audit_log = [0]
@pytest.fixture(scope="module", autouse=True)
def _audit_test_settings(app_server):
# On a fresh DB init_db skips seeding the operational/upload settings (its
# `tables` snapshot predates site_settings creation), so those rows are
# absent and the admin settings form would INSERT them as "" - which both
# closes registration and makes consumers that do int("") crash. Seed sane
# values here so the form's empty submissions are skipped (existing key), and
# lift the per-IP rate limit since this file fires many mutating requests.
for key, value in {
"rate_limit_per_minute": "1000000",
"rate_limit_window_seconds": "60",
"registration_open": "1",
"maintenance_mode": "0",
"max_upload_size_mb": "10",
"allowed_file_types": "",
"max_attachments_per_resource": "10",
"session_max_age_days": "7",
"session_remember_days": "30",
"news_service_interval": "3600",
"news_grade_threshold": "7",
}.items():
set_setting(key, value)
yield
def _db_user(name):
# the user is created by the server subprocess; refresh the test-process
# SQLite snapshot before reading it back across the process boundary.
refresh_snapshot()
return get_table("users").find_one(username=name)
def _unique(prefix="au"):
_counter_audit_log[0] += 1
return f"{prefix}{int(time.time() * 1000)}{_counter_audit_log[0]}"
def _member():
name = _unique("aumem")
s = requests.Session()
s.post(
f"{BASE_URL}/auth/signup",
data={
"username": name,
"email": f"{name}@t.dev",
"password": "secret123",
"confirm_password": "secret123",
},
allow_redirects=True,
)
return s, name
def _member_key():
_, name = _member()
return _db_user(name)["api_key"]
def _admin(seeded_db):
# authenticate via the seeded admin's API key (header auth) rather than a
# login POST - GET reads are exempt from the rate limiter, so reusing this
# across the file's many tests never counts against the per-IP write budget.
key = _db_user("alice_test")["api_key"]
s = requests.Session()
s.headers.update({"X-API-KEY": key})
return s
def _audit(admin, **params):
r = admin.get(f"{BASE_URL}/admin/audit-log", headers=JSON_audit_log, params=params)
assert r.status_code == 200, r.text[:300]
return r.json()
def _find(admin, event_key, predicate):
data = _audit(admin, event_key=event_key)
for entry in data["entries"]:
if predicate(entry):
return entry
return None
def _new_post(session, body="audited post body here"):
return session.post(
f"{BASE_URL}/posts/create",
headers=JSON_audit_log,
data={"title": _unique("aup"), "content": body, "topic": "devlog"},
).json()["data"]
def _new_project(session):
return session.post(
f"{BASE_URL}/projects/create",
headers=JSON_audit_log,
data={
"title": _unique("aupr"),
"description": "audited project description text",
"project_type": "software",
"status": "In Development",
"platforms": "",
},
).json()["data"]
def _seed_news_audit_log():
uid = generate_uid()
title = _unique("aunews")
get_table("news").insert(
{
"uid": uid,
"slug": make_combined_slug(title, uid),
"title": title,
"external_id": uid,
"status": "draft",
"featured": 0,
"show_on_landing": 0,
"grade": 5,
"source_name": "AuditTest",
"synced_at": datetime.now(timezone.utc).isoformat(),
"description": "audited news article",
}
)
refresh_snapshot()
return uid
def test_login_logout_recorded(seeded_db):
name = _unique("aulog")
email = f"{name}@t.dev"
s = requests.Session()
s.post(
f"{BASE_URL}/auth/signup",
data={
"username": name,
"email": email,
"password": "secret123",
"confirm_password": "secret123",
},
allow_redirects=True,
)
# explicit login generates auth.login.success (signup alone does not)
s.post(
f"{BASE_URL}/auth/login",
data={"email": email, "password": "secret123"},
allow_redirects=True,
)
s.get(f"{BASE_URL}/auth/logout", allow_redirects=False)
admin = _admin(seeded_db)
success = _find(
admin, "auth.login.success", lambda e: e.get("target_label") == name
)
logout = _find(admin, "auth.logout", lambda e: e.get("target_label") == name)
assert success is not None
assert logout is not None
+153
View File
@@ -0,0 +1,153 @@
# retoor <retoor@molodetz.nl>
import time
import requests
from tests.conftest import BASE_URL
from devplacepy.database import get_table
from devplacepy.docs_api import API_GROUPS, build_services_group
from devplacepy.services.manager import service_manager
JSON_auth_matrix = {"Accept": "application/json"}
_counter_auth_matrix = [0]
LOGIN_REDIRECT = "/auth/login"
FEED_REDIRECT = "/feed"
JSON_BODY_OVERRIDES = {
"push-register": {
"endpoint": "https://example.test/p",
"keys": {"p256dh": "a", "auth": "b"},
},
"gateway-chat": {"model": "x", "messages": [{"role": "user", "content": "hi"}]},
}
def _signup_auth_matrix(role="Member"):
_counter_auth_matrix[0] += 1
name = f"authmx{int(time.time() * 1000)}{_counter_auth_matrix[0]}"
requests.post(
f"{BASE_URL}/auth/signup",
data={
"username": name,
"email": f"{name}@t.dev",
"password": "secret123",
"confirm_password": "secret123",
},
allow_redirects=True,
)
row = get_table("users").find_one(username=name)
get_table("users").update({"uid": row["uid"], "role": role}, ["uid"])
return get_table("users").find_one(username=name)["api_key"]
def _all_endpoints():
endpoints = []
for group in API_GROUPS:
endpoints.extend(group["endpoints"])
endpoints.extend(
build_services_group(service_manager.describe_all(), BASE_URL)["endpoints"]
)
return endpoints
def _build(endpoint):
path = endpoint["path"]
params, data, files = {}, {}, None
for param in endpoint["params"]:
example = param.get("example") or ""
location = param["location"]
if location == "path":
value = str(example)
if "{{" in value or not value:
value = "x"
path = path.replace("{" + param["name"] + "}", value)
elif location == "query":
if example:
params[param["name"]] = example
elif location == "form":
if param["type"] == "file":
files = {"file": ("probe.txt", b"hello", "text/plain")}
else:
data[param["name"]] = param.get("example") or "x"
json_body = None
if endpoint["encoding"] == "json":
json_body = JSON_BODY_OVERRIDES.get(
endpoint["id"],
{
p["name"]: (p.get("example") or "x")
for p in endpoint["params"]
if p["location"] == "json"
},
)
if endpoint["encoding"] == "multipart" and files is None:
files = {"file": ("probe.txt", b"hello", "text/plain")}
return path, params, data, json_body, files
def _call(endpoint, headers):
path, params, data, json_body, files = _build(endpoint)
kwargs = dict(headers=headers, params=params, allow_redirects=False, timeout=15)
if json_body is not None:
kwargs["json"] = json_body
elif files is not None:
kwargs["files"] = files
if data:
kwargs["data"] = data
elif data:
kwargs["data"] = data
return requests.request(endpoint["method"], f"{BASE_URL}{path}", **kwargs)
def _redirects_to(response, target):
return response.status_code in (
302,
303,
307,
308,
) and target in response.headers.get("location", "")
def _is_auth_rejected(response):
return response.status_code == 401 or _redirects_to(response, LOGIN_REDIRECT)
def _is_role_rejected(response):
return response.status_code == 403 or _redirects_to(response, FEED_REDIRECT)
def _is_allowed(response):
return not _is_auth_rejected(response) and response.status_code != 403
def test_documented_minimal_role_matches_enforcement(seeded_db):
# depend on seeded_db so alice_test keeps the is_first -> Admin slot; our signups
# below are never the first user and cannot demote the suite's admin fixture.
member_key = _signup_auth_matrix("Member")
member = {**JSON_auth_matrix, "X-API-KEY": member_key}
endpoints = _all_endpoints()
assert len(endpoints) >= 50
failures = []
for endpoint in endpoints:
auth = endpoint["auth"]
label = (
f"{endpoint['method']} {endpoint['path']} ({endpoint['id']}, doc={auth})"
)
anon = _call(endpoint, JSON_auth_matrix)
if auth == "public":
if not _is_allowed(anon):
failures.append(
f"{label}: public but anonymous was rejected ({anon.status_code})"
)
continue
if not _is_auth_rejected(anon):
failures.append(
f"{label}: requires {auth} but anonymous was NOT rejected ({anon.status_code})"
)
if auth == "user" and endpoint["method"] == "GET":
mem = _call(endpoint, member)
if not _is_allowed(mem):
failures.append(
f"{label}: documented user but a member was rejected ({mem.status_code})"
)
if auth == "admin":
mem = _call(endpoint, member)
if not _is_role_rejected(mem):
failures.append(
f"{label}: documented admin but a non-admin member was NOT rejected ({mem.status_code})"
)
assert not failures, "Auth enforcement does not match documentation:\n" + "\n".join(
failures
)
def test_every_endpoint_documents_minimal_role(seeded_db):
for endpoint in _all_endpoints():
assert endpoint["min_role"] in ("Public", "Member", "Admin"), endpoint["id"]
+34
View File
@@ -0,0 +1,34 @@
# retoor <retoor@molodetz.nl>
import time
import requests
from tests.conftest import BASE_URL
def _session_validation():
s = requests.Session()
name = f"val_{int(time.time() * 1000)}"
s.post(
f"{BASE_URL}/auth/signup",
data={
"username": name,
"email": f"{name}@t.dev",
"password": "secret123",
"confirm_password": "secret123",
},
allow_redirects=True,
)
return s
def test_signup_short_username_rerenders_with_message(app_server):
r = requests.post(
f"{BASE_URL}/auth/signup",
data={
"username": "ab",
"email": "x@y.zz",
"password": "secret123",
"confirm_password": "secret123",
},
allow_redirects=False,
)
assert r.status_code == 400
assert "Username must be between 3 and 32 characters" in r.text