ci: add test pipeline and API contract guard

- ci.yml: ruff + pytest on push/PR, installing from the hashed lockfile
  with --require-hashes, plus a lockfile-vs-requirements consistency
  check (dependabot cannot regenerate the lockfile; drift was silent).
- test_api_contract.py: deep-scans public config, dashboard, admin file
  list and share metadata responses for camelCase keys - the regression
  net for the D7 public-config leak found during review.
This commit is contained in:
Marrrrrrrrry committed 2026-09-11 04:24:47 +08:00
1 parent 13f572a86a
commit 775f3fc4ce
2 files changed
+140

No files matched your search

+63
View File
@@ -0,0 +1,63 @@
name: CI
on:
push:
branches:
- master
- dev
pull_request:
concurrency:
group: ci-${{ github.ref }}
cancel-in-progress: true
permissions:
contents: read
jobs:
test:
name: Lint and test
runs-on: ubuntu-latest
timeout-minutes: 15
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Setup Python
uses: actions/setup-python@v5
with:
python-version: '3.12'
- name: Install dependencies
run: |
python -m pip install --upgrade pip
# The hashed lockfile is the deploy artifact; install from it with
# --require-hashes so CI fails on lockfile drift, exactly like the
# Docker build does.
pip install --require-hashes -r requirements.lock.txt
pip install pytest pytest-asyncio httpx
- name: Ruff
run: pipx run ruff==0.16.6 check .
- name: Verify lockfile matches requirements.txt
# Dependabot bumps requirements.txt but cannot regenerate the hashed
# lockfile; without this check a stale lockfile would silently keep
# the Docker build on old versions.
run: |
python - <<'PY'
import re, sys
pins = dict(re.findall(r'^([\w-]+)==([\w.]+)$', open('requirements.txt').read(), re.M))
lock = open('requirements.lock.txt').read()
stale = []
for name, ver in pins.items():
m = re.search(rf'(?mi)^{re.escape(name)}==([\w.]+)\b', lock)
if m is None or m.group(1) != ver:
stale.append((name, ver, m.group(1) if m else 'ABSENT'))
for name, req_ver, lock_ver in stale:
print(f'STALE LOCKFILE: {name} requirements.txt={req_ver} lock={lock_ver}')
sys.exit(1 if stale else 0)
PY
- name: Run tests
run: pytest -q
+77
View File
@@ -0,0 +1,77 @@
"""API contract guard: responses must carry snake_case keys only.
Regression net for the D7 lesson: a camel+snake dual-field contract crept
back through build_public_config/build_public_meta (file-based scoping hid
that they serve a live endpoint). Any key matching [a-z]+[A-Z] camel shape
anywhere in these documented response payloads now fails the suite.
"""
import re
import httpx
import pytest
CAMEL_KEY = re.compile(r"^[a-z0-9]+(?:[A-Z][a-zA-Z0-9]*)+$")
def _assert_no_camel_keys(node, path, violations):
if isinstance(node, dict):
for key, value in node.items():
key_path = f"{path}.{key}"
if isinstance(key, str) and CAMEL_KEY.match(key):
violations.append(key_path)
_assert_no_camel_keys(value, key_path, violations)
elif isinstance(node, list):
for index, item in enumerate(node):
_assert_no_camel_keys(item, f"{path}[{index}]", violations)
async def _login(client: httpx.AsyncClient) -> str:
from tests.conftest import TEST_ADMIN_PASSWORD
response = await client.post(
"/admin/login", json={"password": TEST_ADMIN_PASSWORD}
)
assert response.status_code == 200, response.text
return response.json()["detail"]["token"]
def _check_contract(payload: dict, url: str) -> None:
violations = []
_assert_no_camel_keys(payload, url, violations)
assert not violations, f"camelCase keys leaked into {url}: {violations}"
@pytest.mark.asyncio
class TestApiContractSnakeCase:
async def test_public_config(self, initialized_client):
response = await initialized_client.get("/api/v1/config")
assert response.status_code == 200
_check_contract(response.json(), "/api/v1/config")
async def test_dashboard(self, initialized_client):
token = await _login(initialized_client)
response = await initialized_client.get(
"/admin/dashboard", headers={"Authorization": f"Bearer {token}"}
)
assert response.status_code == 200
_check_contract(response.json(), "/admin/dashboard")
async def test_admin_file_list(self, initialized_client):
token = await _login(initialized_client)
response = await initialized_client.get(
"/admin/file/list", headers={"Authorization": f"Bearer {token}"}
)
assert response.status_code == 200
_check_contract(response.json(), "/admin/file/list")
async def test_share_metadata(self, initialized_client):
share = await initialized_client.post(
"/share/text/", data={"text": "contract guard", "expire_value": 1, "expire_style": "day"}
)
assert share.status_code == 200, share.text
code = share.json()["detail"]["code"]
response = await initialized_client.get(
"/share/metadata/", params={"code": code}
)
assert response.status_code == 200
_check_contract(response.json(), "/share/metadata/")