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
@@ -16,6 +16,7 @@ import org.springframework.web.bind.annotation.*;
import java.time.Instant;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
/**
* 婚恋咨询 / 婚前辅导 端点(Phase 13A)
@@ -49,6 +50,10 @@ import java.util.Map;
@RequiredArgsConstructor
public class CounselingController {
/** 主键为 uuid 列,非法字符串必须先挡在 Controller 层,避免打到数据库变成 500。 */
private static final Pattern UUID_PATTERN = Pattern.compile(
"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$");
private final CounselingService counselingService;
// ==================== 用户端 ====================
@@ -91,6 +96,12 @@ public class CounselingController {
public ApiResponse<CounselingServiceRecord> detail(@PathVariable String id,
@AuthenticationPrincipal UserPrincipal principal) {
if (principal == null) return ApiResponse.unauthorized();
// 非法 UUID 直接 400。否则参数会打到数据库,PostgreSQL 抛
// `invalid input syntax for type uuid` → 500 且泄漏数据库异常。
if (!UUID_PATTERN.matcher(id).matches()) {
throw new com.danyang.match.platform.shared.exception.GlobalExceptionHandler.BusinessException(
com.danyang.match.platform.shared.enums.ApiResponseCode.BAD_REQUEST, "非法的 ID 格式");
}
CounselingServiceRecord svc = counselingService.getDetail(principal.id(), principal.role(), id);
if (svc == null) return ApiResponse.forbidden();
return ApiResponse.ok(svc);
@@ -111,6 +111,18 @@ public class GlobalExceptionHandler {
return ApiResponse.error(e.getCode(), e.getMessage());
}
/**
* 参数非法(例:活动类型不在 {@code chk_activity_type} 白名单内)必须回 400。
*
* <p>此前未映射 {@link IllegalArgumentException},这类"客户端传错值"的问题
* 会被兜底成 500:调用方无法区分是自己的参数错还是服务端故障,
* 真实 PostgreSQL 上还会伴随数据库异常语义外泄(H2 测试库则不报错 → 零覆盖)。
*/
@ExceptionHandler(IllegalArgumentException.class)
public ApiResponse<Void> handleIllegalArgument(IllegalArgumentException e) {
return ApiResponse.error(ApiResponseCode.BAD_REQUEST, e.getMessage());
}
@ExceptionHandler(AccessDeniedException.class)
@ResponseStatus(HttpStatus.FORBIDDEN)
public ApiResponse<Void> handleAccessDenied(AccessDeniedException e) {
@@ -1,6 +1,9 @@
spring:
datasource:
url: jdbc:postgresql://${DB_HOST:localhost}:${DB_PORT:5432}/${DB_NAME:danyang_match}
# stringtype=unspecified:Java 侧实体主键/外键统一用 String,而 PostgreSQL 列是 uuid。
# 不加该参数时 pgjdbc 以 varchar 发送,PostgreSQL 在比较操作上不做隐式转换,
# 会抛 `operator does not exist: uuid = character varying`(H2 测试库不报错 → 零覆盖)。
url: jdbc:postgresql://${DB_HOST:localhost}:${DB_PORT:5432}/${DB_NAME:danyang_match}?stringtype=unspecified
username: ${DB_USER:postgres}
password: ${DB_PASSWORD}
@@ -0,0 +1,20 @@
-- ============================================================
-- V044: 补齐 super_admin 权限(实现与定义对齐,非扩权)
--
-- 发现方式:Phase 24 搭建 E2E 基建、用真实 PostgreSQL 活栈执行时发现
-- - permissions 共 48 条,role_permissions 里 super_admin 只有 18 条
-- - matchmaker 角色为 0 条(见报告 D-24-E 遗留项)
--
-- 根因:V015 的「为 super_admin 分配全部权限」是**执行时点快照**,
-- V016 之后新增的 30 条权限从未回补给 super_admin。
-- 后果:全新环境起栈后,超级管理员创建服务站、查看咨询等操作全部 403。
--
-- super_admin 在 V015 中的定义即「系统超级管理员,拥有全部权限」,
-- 本迁移只是让实现回到定义;不新增权限、不授予其它角色。
-- 幂等:ON CONFLICT DO NOTHING。
-- ============================================================
INSERT INTO role_permissions (role_id, permission_id)
SELECT '00000000-0000-0000-0000-000000000001', id
FROM permissions
ON CONFLICT (role_id, permission_id) DO NOTHING;
@@ -18,7 +18,8 @@ class MigrationValidationTest {
// 基线守卫:新增 Flyway 迁移时必须同步递增此值
// Phase 19:V042 善缘服务站「临时公告」表(service_location_announcements)
// Phase 20:V043 打通 analytics.view 授权(data_viewer 专设却零权限 + platform_admin 被老权限段漏掉)
private static final int LATEST_MIGRATION = 43;
// Phase 24:V044 补齐 super_admin 权限(V015 之后新增的 30 条权限从未回补给 super_admin)
private static final int LATEST_MIGRATION = 44;
private static final String MIGRATION_DIR =
"backend/src/main/resources/db/migration/";
@@ -151,6 +152,37 @@ class MigrationValidationTest {
assertTrue(v014.contains("user_privacy_settings"), "V014 应创建 privacy settings 表");
}
/**
* 源码目录版本号唯一 ≠ 打包出来的 jar 版本号唯一。
*
* <p>未 clean 时 {@code target/classes} 会残留历史文件(例如被改名/删除的旧
* {@code V042__*.sql}),打包进 jar 后 Flyway 直接抛
* {@code Found more than one migration with version 042} —— **应用起不来**。
* 该问题在源码层扫不出来(src 是干净的),只有扫构建产物才能发现。
*/
@Test
void testBuildOutputHasNoDuplicateMigrationVersions() throws IOException {
Path dir = Paths.get("backend/target/classes/db/migration");
assertTrue(Files.exists(dir), "构建产物目录不存在,无法校验:" + dir.toAbsolutePath());
Map<Integer, List<String>> byVersion = new HashMap<>();
Pattern versionPattern = Pattern.compile("^V(\\d+)__");
try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir, "V*.sql")) {
for (Path p : stream) {
Matcher m = versionPattern.matcher(p.getFileName().toString());
if (m.find()) {
byVersion.computeIfAbsent(Integer.valueOf(m.group(1)), k -> new ArrayList<>())
.add(p.getFileName().toString());
}
}
}
assertFalse(byVersion.isEmpty(), "构建产物中没有任何迁移文件,校验无意义");
byVersion.forEach((version, names) -> assertEquals(1, names.size(),
"构建产物中版本号 " + version + " 重复 " + names
+ " —— 多为未 clean 的陈旧文件残留,会导致 Flyway 启动失败;请执行 mvn clean"));
}
@Test
void testNoBackwardIncompatibleChanges() throws IOException {
// 验证没有破坏性变更(如 DROP COLUMN)