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
+46 -41
View File
@@ -1,44 +1,49 @@
"""
V1.1 首页 E2E —— 空壳已移除(Phase 23 KEEP-VERIFY,2026-09-18)
首页 E2E(INV-017 八入口固定 / INV-016 Banner 禁外链 / 首页结构固定)。
历史问题
--------
原文件 9 个测试函数中 **7 个是 `pass` 空壳**,其余 5 个虽含断言,
但全部依赖 `api_client` / `authenticated_user` / `banner_factory` /
`user_factory` / `verified_user` / `searching_user` / `paused_user` /
`successful_user` / `admin_client` 等**在本仓库中根本不存在**的 pytest fixture
(全局无 `conftest.py`)→ 整个文件**一次都没执行过**,
却在 `docs/STATUS.md` 中被计为 P23-T01~T04「首页 E2E ✅」。
计划 Phase 23 Gate:「**不允许 skip/pass 空壳**」。
当前状态
--------
本文件现**不含任何测试函数**,pytest 收集 0 个用例。
仍待真实实现的场景(需求不因移除空壳而丢失)
------------------------------------------
1. `GET /api/v1/home` 返回 userState
2. Banner 按时间过滤(未开始 / 已过期不显示)
3. Banner 按 audience_scope 过滤
4. 首页 8 核心入口顺序固定(INV-017)
5. 未审核用户不返回真实推荐
6. Paused 用户不返回新推荐
7. Successful 用户不返回找对象推荐
8. 服务站可展示
9. Banner 不能创建外部 URL 跳转(INV-016)
10. `counselingEnabled` flag 控制 `canApplyCounseling`
11. Capability:`canReceiveRecommendations` 随账号状态变化
现状补充(Phase 23 实测)
------------------------
- 首页聚合与 8 入口已有真实 HTTP 覆盖:
`tests/e2e/run_v11_tests.py::test_02_home` 与 `::test_03_home_8_entries`;
- **INV-017 已由 Phase 23 新增的后端真实行为用例覆盖**
(`V11InvariantsTest#inv017QuickEntriesFixedOrder`,走真实
`HomeApplicationService.getHome(userId)`,断言 8 个编码与顺序完全固定);
- INV-016 已有 `BannerOperatorPhase19IntegrationTest` 真实覆盖。
即:E2E 层待补,但不变量本身已有真实覆盖。
真实可执行的 V1.1 E2E 见:`tests/e2e/run_v11_tests.py`
这些断言打的是**真实活栈**:`GET /api/v1/home` 的真实响应,不是常量、不是自造字面量。
"""
import pytest
pytestmark = pytest.mark.e2e
# AGENTS.md 硬规则 #14/#15:首页 8 核心入口固定,顺序不可更改、运营不可重排。
EXPECTED_QUICK_ENTRIES = [
"find_object", # 第一排
"matchmaker",
"activities",
"counseling",
"classroom", # 第二排
"premarital",
"anti_fraud",
"service_station",
]
# INV-016:Banner 仅内部跳转,target_type 白名单(与生产 HomeBannerOperatorController 一致)。
ALLOWED_BANNER_TARGETS = {
"activity", "matchmaker", "counseling", "premarital",
"service_location", "article", "internal_page", "none",
}
def test_home_returns_fixed_sections(api, user_token):
"""规则 #14:首页区块齐备(缺一个即结构被改)。"""
data = api.ok("GET", "/home", token=user_token)
for key in ("quickEntries", "banners", "userState", "capabilities", "safetyNotice"):
assert key in data, f"首页缺少区块 {key},实际 keys={sorted(data.keys())}"
def test_quick_entries_fixed_order(api, user_token):
"""INV-017:8 个核心入口固定且顺序不可更改。"""
data = api.ok("GET", "/home", token=user_token)
codes = [e.get("code") for e in data["quickEntries"]]
assert codes == EXPECTED_QUICK_ENTRIES, f"首页入口顺序被改动:{codes}"
def test_banner_target_types_are_internal_only(api, user_token):
"""INV-016:Banner 不允许外链(target_type 必须落在白名单内)。"""
data = api.ok("GET", "/home", token=user_token)
banners = data.get("banners") or []
for b in banners:
target = b.get("targetType")
assert target in ALLOWED_BANNER_TARGETS, f"Banner 出现非白名单 target_type={target!r}"