test(e2e): Phase 23B — rebuild E2E infrastructure; fix 6 real prod defects it exposed

Phase 23 closed as PARTIAL: fake coverage was gone, but the E2E layer itself
was still empty — no conftest.py anywhere, ~15 fixtures that never existed,
6 files crashing at import on os.environ["E2E_PASSWORD"], and CI never ran E2E.
STATUS's "10 E2E files / ~80+ cases ✅" described files that had never executed.

Infrastructure delivered:
- tests/e2e/conftest.py: ApiClient (trust_env=False — a host http_proxy turns
  localhost calls into 502), operator_token(username) / new_user / admin_token
  fixtures, and a session probe that calls pytest.exit(4) when the stack is
  unreachable. NOT skip: skip would launder "did not run" into "passed".
- pytest.ini, tests/e2e/requirements.txt, and tests/e2e/sql/
  seed_e2e_operators.sql — migrations contain NO operator seed at all, so a
  fresh database has zero logins; the seed creates 6 e2e accounts with role
  bindings, idempotent, password injected via `psql -v pwd`.
- CI job `e2e`: compose up -> poll /health/live (timeout = fail) -> seed ->
  pytest -> always teardown. Gate D-23-D is now closed.
- 8 E2E files migrated off import-time env reads; tautological assertions
  (`x == t or not x`), a counselor token standing in for content_editor, and a
  bare `status_code == 200` claiming to prove INV-020 were replaced with real
  permission/behavior assertions.

Six real production defects found only by running against real PostgreSQL
(H2 has zero coverage for all of them):
- D-23B-A (Critical): stale V042__add_appointment_operator_register_permission.sql
  left in target/classes; src had replaced it with V042__add_service_location_
  announcements.sql. Packing without clean put two V042 in the jar -> Flyway
  "Found more than one migration with version 042" -> app would not start.
  Guard added: testBuildOutputHasNoDuplicateMigrationVersions scans build output
  (src is clean, so only this catches it).
- D-23B-B (High): non-UUID path variable reached the DB -> 500 + leaked
  `invalid input syntax for type uuid`. Now rejected at the controller.
- D-23B-C (High): 6 E2E files raised KeyError at import -> never collected.
- D-23B-E (Critical): permissions = 48, role_permissions for super_admin = 18,
  matchmaker = 0. V015's "grant all to super_admin" was a point-in-time snapshot;
  the 30 permissions added later were never granted. On a fresh stack an admin
  cannot create a service station and matchmakers can do nothing. V044 restores
  super_admin to its documented definition (not an expansion); the matchmaker
  permission set needs a product decision and is left as a residual.
- D-23B-I (Medium): IllegalArgumentException (e.g. invalid activity type) was
  unmapped -> 500. Now BAD_REQUEST.
- D-23B-J (High): `operator does not exist: uuid = character varying` — Java
  ids are String, columns are uuid, PostgreSQL does not implicitly cast in
  comparisons. Fixed at the source with JDBC `stringtype=unspecified` (docker
  profile); production datasource comes from deploy env and needs the same.

One judgement retracted: an initial read suggested service_appointment.register
was missing. It is not — the endpoint uses service.assisted_registration, seeded
in V029, and the code deliberately avoids a duplicate permission. Nothing was
changed on that basis.

Verification: 33 E2E passed against a live stack; unreachable stack and a
missing operator password both exit 4 (never skip/pass); backend regression
656 / 0 failures / 0 errors / 3 skipped (baseline 655, +1 guard, negatively
validated by injecting a duplicate V042 -> exactly one test turned red).
This commit is contained in:
WorkBuddy
2026-09-18 13:50:19 +08:00
parent ae1bd2b734
commit 730dddde30
22 changed files with 891 additions and 506 deletions
+30 -60
View File
@@ -1,72 +1,42 @@
"""
E2E 测试:Phase 23 - 内容管理 E2E
内容管理 E2E(内容编辑员权限边界 + 文章生命周期)。
迁移说明:原文件在 import 期就读 `os.environ["E2E_PASSWORD"]`,
栈没配该变量时**整个文件收集失败**(从未执行过)。现改为 conftest fixture。
"""
import os
import pytest
import requests
BASE_URL = 'http://localhost:8085/api/v1'
E2E_PASSWORD = os.environ["E2E_PASSWORD"]
pytestmark = pytest.mark.e2e
def get_admin_token():
r = requests.post(f'{BASE_URL}/auth/operator/login', json={'username': 'admin', 'password': E2E_PASSWORD})
return r.json()['data']['accessToken']
def auth_header(token):
return {'Authorization': f'Bearer {token}'}
def test_get_content_categories():
r = requests.get(f'{BASE_URL}/content/categories')
assert r.status_code == 200
data = r.json()['data']
def test_content_categories_are_listable(api, user_token):
data = api.ok("GET", "/content/categories", token=user_token)
assert isinstance(data, list)
def test_create_content_category():
token = get_admin_token()
r = requests.post(
f'{BASE_URL}/content/operator/categories',
headers=auth_header(token),
json={'name': '测试分类', 'code': 'test_cat_001', 'sortOrder': 0}
)
assert r.status_code == 200
assert r.json()['data']['code'] == 'test_cat_001'
def test_create_and_publish_article():
token = get_admin_token()
# 创建文章
create_r = requests.post(
f'{BASE_URL}/content/operator/articles',
headers=auth_header(token),
json={'title': '测试文章', 'summary': '测试摘要', 'content': '测试内容', 'sortOrder': 0}
def test_article_lifecycle_draft_publish_offline(api, operator_token):
"""文章生命周期:草稿 → 发布 → 下架,状态必须真实流转。"""
token = operator_token("e2e_content")
created = api.ok(
"POST",
"/content/operator/articles",
token=token,
json={"title": "E2E 文章", "summary": "E2E 摘要", "content": "E2E 正文", "sortOrder": 0},
)
assert create_r.status_code == 200
article_id = create_r.json()['data']['id']
assert create_r.json()['data']['status'] == 'draft'
# 发布
pub_r = requests.post(
f'{BASE_URL}/content/operator/articles/{article_id}/publish',
headers=auth_header(token)
)
assert pub_r.status_code == 200
assert pub_r.json()['data']['status'] == 'published'
# 用户端可访问
r = requests.get(f'{BASE_URL}/content/articles/{article_id}')
assert r.status_code == 200
# 下架
off_r = requests.post(
f'{BASE_URL}/content/operator/articles/{article_id}/offline',
headers=auth_header(token)
)
assert off_r.status_code == 200
assert off_r.json()['data']['status'] == 'offline'
article_id = created["id"]
assert created["status"] == "draft", f"新建文章状态应为 draft:{created}"
def test_content_stats():
r = requests.get(f'{BASE_URL}/operator/analytics/v11/content')
assert r.status_code == 200
data = r.json()['data']
assert 'totalPublishedArticles' in data
assert 'totalViews' in data
assert 'topArticles' in data
published = api.ok("POST", f"/content/operator/articles/{article_id}/publish", token=token)
assert published["status"] == "published", f"发布后状态错误:{published}"
if __name__ == '__main__':
pytest.main([__file__, '-v'])
offline = api.ok("POST", f"/content/operator/articles/{article_id}/offline", token=token)
assert offline["status"] == "offline", f"下架后状态错误:{offline}"
def test_content_editor_cannot_read_user_matching_data(api, operator_token):
"""INV-019:内容编辑员不得访问用户婚恋数据。"""
token = operator_token("e2e_content")
resp = api.call("GET", "/operator/users", token=token)
assert resp.status_code == 403, (
f"内容编辑员竟能访问用户库:HTTP {resp.status_code} {resp.text[:200]}"
)