Browse Source

test(web): S-junit-2 TDD-RED web.adminPanel.runE2E 契约级单测(13 用例:12 绿 + B1 红)

- 新增 cfc-backend/src/test/java/com/etotem/cfc/e2e/WebAdminpanelRune2eContractTest.java
  (扁平类,无 @Nested——surefire -Dtest 单类匹配可全量运行)
- A 组(4 绿):tests/e2e-live/admin-live.spec.js 5 用例在册、live config admin-desktop
  project + R416 双副本守卫、test:e2e:live:admin 规范跑法脚本三要素
- B1(RED):P-474-1 双副本 @playwright/test 声明契约——根 1.63.0 + tests ^1.61.1
  违反单副本契约,GREEN 阶段两侧至多一方声明即转绿
- C 组(8 绿):管理端主链路 API 契约——/api/admin/users(admin 200 分页信封 /
  teacher·parent 越权 403 不触达 DB)、/api/admin/energy-rule(list 原地填充 Page +
  dimensions + 不存在 toggle 业务拒绝 C404 语义)、/api/admin/config/list、/api/system/health
- 不适用边界(replay=true 幂等重放 / 同键异载荷 C4092 / 乐观锁 C422):只读 E2E 能力键 +
  C-code 体系未落地,Javadoc + NOT_APPLICABLE_BOUNDARIES 常量登记
- 隔离 m2 构建:前置校验 SRC=2269/CLS=2487(109.6%) 通过;surefire Tests run: 13,
  Failures: 1(B1 预期红),失败断言:AssertionFailedError P-474-1 双副本
  @playwright/test 声明(根 [1.63.0] vs tests [^1.61.1])==> expected: <true> but was: <false>
- 未改 src/main 一行;未改 tests/test-cases 与 API_REFERENCE.md
Administrator 1 hour ago
parent
commit
f3f3e90f24

+ 403 - 0
cfc-backend/src/test/java/com/etotem/cfc/e2e/WebAdminpanelRune2eContractTest.java

@@ -0,0 +1,403 @@
+package com.etotem.cfc.e2e;
+
+import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
+import com.etotem.cfc.common.AdminRoles;
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.controller.admin.AdminController;
+import com.etotem.cfc.controller.admin.AdminEnergyRuleController;
+import com.etotem.cfc.controller.admin.AdminSystemController;
+import com.etotem.cfc.controller.config.SysConfigController;
+import com.etotem.cfc.dto.SysConfigDTO;
+import com.etotem.cfc.entity.EnergyDimension;
+import com.etotem.cfc.entity.EnergyRule;
+import com.etotem.cfc.entity.SysConfig;
+import com.etotem.cfc.entity.User;
+import com.etotem.cfc.mapper.EnergyDimensionMapper;
+import com.etotem.cfc.mapper.EnergyRuleMapper;
+import com.etotem.cfc.mapper.UserMapper;
+import com.etotem.cfc.service.SysConfigService;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+import org.springframework.http.MediaType;
+import org.springframework.test.util.ReflectionTestUtils;
+import org.springframework.test.web.servlet.MockMvc;
+import org.springframework.test.web.servlet.setup.MockMvcBuilders;
+
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
+
+/**
+ * S-junit-2 / web.adminPanel.runE2E 契约级单测(TDD-RED 阶段:先写会失败的契约测试)。
+ *
+ * <p>能力键 {@code web.adminPanel.runE2E}(单元 web)=「Web 管理端主链路 E2E 可运行」:
+ * 已部署站点(cfc.iwintrue.com)管理后台 5 条只读用例(TC-A-U01~U05)在
+ * 189:4090 节点 5/5 全绿(R407 专题E 实测),但该能力键<b>未契约化</b>
+ * (API_REFERENCE.md 5.5 槽位 ⏳ 待落地):E2E 主链路缺少机器可验证的契约测试,
+ * 且其工具链根因 P-474-1({@code @playwright/test} 双物理副本 → 假红 "No tests found")
+ * 无任何测试守卫,历轮只能靠人工读 R416 守卫报错才定位。
+ *
+ * <p>本类钉住三段契约(测试工作目录为 {@code cfc-backend},仓库根按 user.dir 上溯定位):
+ * <ul>
+ *   <li><b>A 组 · 套件可用契约</b>:{@code tests/e2e-live/admin-live.spec.js}(5 用例)在册、
+ *       {@code tests/playwright.config.live.js} 的 admin-desktop project 与 R416 双副本守卫在位、
+ *       {@code tests/package.json} 的 {@code test:e2e:live:admin} 规范跑法脚本完整;</li>
+ *   <li><b>B 组 · 工具链单副本契约</b>:仓库根与 {@code tests/} 两侧 package.json
+ *       至多一方声明 {@code @playwright/test}(P-474-1:根 1.63.0 + tests ^1.61.1 双副本
+ *       → CLI 与 spec 各拿一份,{@code test.describe()} 无法注册,runner 假红 "No tests found")。
+ *       <b>B1 当前必失败(RED)</b>;</li>
+ *   <li><b>C 组 · 管理端主链路 API 契约</b>:E2E 4 场景页面(用户列表 / 数据看板 / 能量规则 / 系统配置)
+ *       所依赖的后端端点——{@code POST /api/admin/users}、{@code /api/admin/energy-rule/*}、
+ *       {@code /api/admin/config/list}、{@code /api/system/health}——的 {@code Result} 信封与角色门禁。</li>
+ * </ul>
+ *
+ * <p>边界适用性说明(任务派发边界清单逐项落位):
+ * <ul>
+ *   <li>幂等重放 replay=true / 同键异载荷 C4092 / 乐观锁冲突 C422:<b>不适用</b>——
+ *       该能力键是只读 E2E 套件(唯一例外是登录建立会话,无写操作),
+ *       且 C-code 统一错误码体系未在本仓落地(全仓无 C4092/C422 常量);</li>
+ *   <li>越权 C403:适用 → 以业务码 403 语义覆盖(teacher/parent 访问平台端点
+ *       {@code /api/admin/users} → {@code Result.error(403, "无权限访问该接口")});</li>
+ *   <li>不存在 C404:适用 → 以业务错误语义覆盖({@code /api/admin/energy-rule/toggle}
+ *       不存在 id → "规则不存在")。</li>
+ * </ul>
+ *
+ * <p>测试隔离:MockMvc standalone + 全 mock Mapper/Service,无 Spring 上下文 / 无 DB / 无外部服务。
+ * 类为<b>扁平结构(无 @Nested)</b>,保证 surefire {@code -Dtest=*WebAdminpanelRune2e*}
+ * 单类匹配即可运行全部用例。
+ *
+ * <p>GREEN 阶段最小改动:消除双副本(两侧 package.json 至多一方声明 {@code @playwright/test},
+ * 推荐移除根 devDependency、tests/ 留单副本)——不改 src/main 一行。
+ */
+class WebAdminpanelRune2eContractTest {
+
+    // ================================================================
+    // 仓库根定位(测试 CWD = cfc-backend 模块目录;IDE 下可能 = 仓库根)
+    // ================================================================
+
+    /** 定位仓库根:含 {@code tests/e2e-live/} 目录且根有 package.json 的目录。 */
+    private static Path repoRoot() {
+        String userDir = System.getProperty("user.dir", ".");
+        for (String candidate : new String[]{"..", ".", "./"}) {
+            Path root = Paths.get(userDir, candidate).toAbsolutePath().normalize();
+            if (Files.isDirectory(root.resolve("tests").resolve("e2e-live"))
+                    && Files.isRegularFile(root.resolve("package.json"))) {
+                return root;
+            }
+        }
+        throw new IllegalStateException("无法定位仓库根(user.dir=" + userDir + "),请检查测试运行目录");
+    }
+
+    private static String readRepoFile(String relativePath) throws Exception {
+        return new String(Files.readAllBytes(repoRoot().resolve(relativePath)), StandardCharsets.UTF_8);
+    }
+
+    /** 收集 package.json 中指定 section 的 @playwright/test 版本声明(B 组契约用)。 */
+    private static Set<String> playwrightDecls(JsonNode pkg, String... sections) {
+        Set<String> decls = new HashSet<>();
+        for (String section : sections) {
+            JsonNode node = pkg.path(section).path("@playwright/test");
+            if (!node.isMissingNode() && !node.isNull()) {
+                decls.add(node.asText());
+            }
+        }
+        return decls;
+    }
+
+    // ================================================================
+    // C 组 MockMvc 装配(A/B 组不依赖)
+    // ================================================================
+
+    private MockMvc adminApi;
+    private MockMvc energyRuleApi;
+    private MockMvc sysConfigApi;
+    private MockMvc systemApi;
+    private UserMapper userMapper;
+    private EnergyRuleMapper energyRuleMapper;
+    private EnergyDimensionMapper energyDimensionMapper;
+    private SysConfigService sysConfigService;
+
+    @BeforeEach
+    void setUp() {
+        AdminController adminController = new AdminController();
+        userMapper = mock(UserMapper.class);
+        ReflectionTestUtils.setField(adminController, "userMapper", userMapper);
+        adminApi = MockMvcBuilders.standaloneSetup(adminController).build();
+
+        AdminEnergyRuleController energyRuleController = new AdminEnergyRuleController();
+        energyRuleMapper = mock(EnergyRuleMapper.class);
+        energyDimensionMapper = mock(EnergyDimensionMapper.class);
+        ReflectionTestUtils.setField(energyRuleController, "energyRuleMapper", energyRuleMapper);
+        ReflectionTestUtils.setField(energyRuleController, "energyDimensionMapper", energyDimensionMapper);
+        energyRuleApi = MockMvcBuilders.standaloneSetup(energyRuleController).build();
+
+        SysConfigController sysConfigController = new SysConfigController();
+        sysConfigService = mock(SysConfigService.class);
+        ReflectionTestUtils.setField(sysConfigController, "sysConfigService", sysConfigService);
+        sysConfigApi = MockMvcBuilders.standaloneSetup(sysConfigController).build();
+
+        systemApi = MockMvcBuilders.standaloneSetup(new AdminSystemController()).build();
+    }
+
+    // ================================================================
+    // A 组:E2E 套件可用契约(tests/ 树文件断言)
+    // ================================================================
+
+    @Test
+    @DisplayName("A1 admin E2E spec 在册:admin-live.spec.js 注册 test.describe + 5 用例(TC-A-U01~U05)")
+    void adminLiveSpec_五个用例在册() throws Exception {
+        String spec = readRepoFile("tests/e2e-live/admin-live.spec.js");
+        assertTrue(spec.contains("test.describe("),
+                "tests/e2e-live/admin-live.spec.js 缺少 test.describe() 注册——套件无法被 runner 收集(P-474-1 假红的直接信号之一)");
+        for (int i = 1; i <= 5; i++) {
+            String tc = "TC-A-U0" + i;
+            assertTrue(spec.contains(tc), "admin-live.spec.js 缺少用例 " + tc + "(189:4090 基线为 admin 5/5,缺任一即主链路断链)");
+        }
+    }
+
+    @Test
+    @DisplayName("A2 live config 声明 admin-desktop project 并锁定 admin-live.spec.js")
+    void liveConfig_adminDesktopProject在册() throws Exception {
+        String config = readRepoFile("tests/playwright.config.live.js");
+        assertTrue(config.contains("admin-desktop"),
+                "playwright.config.live.js 缺少 admin-desktop project——test:e2e:live:admin 无 project 可跑");
+        assertTrue(config.matches("(?s).*name: 'admin-desktop'.*?testMatch.*?admin-live.*"),
+                "admin-desktop project 未通过 testMatch 锁定 admin-live.spec.js");
+    }
+
+    @Test
+    @DisplayName("A3 live config 携带 R416 双副本工具链守卫(加载时 fail-fast)")
+    void liveConfig_R416工具链守卫在册() throws Exception {
+        String config = readRepoFile("tests/playwright.config.live.js");
+        assertTrue(config.contains("assertSinglePlaywrightCopy"),
+                "playwright.config.live.js 缺少 R416 assertSinglePlaywrightCopy 守卫——双副本时不再 fail-fast,退回加密报错");
+        assertTrue(config.contains("双物理副本"),
+                "R416 守卫的报错文案(双物理副本提示)缺失——误报 'No tests found' 时无自助指引");
+    }
+
+    @Test
+    @DisplayName("A4 tests/package.json 规范跑法脚本 test:e2e:live:admin 完整(spec + 配置 + project 三要素)")
+    void npmScript_testE2eLiveAdmin_规范跑法完整() throws Exception {
+        JsonNode pkg = new ObjectMapper().readTree(
+                repoRoot().resolve("tests").resolve("package.json").toFile());
+        String script = pkg.path("scripts").path("test:e2e:live:admin").asText("");
+        assertFalse(script.isEmpty(),
+                "tests/package.json 缺少 scripts['test:e2e:live:admin']——规范跑法入口缺失");
+        assertTrue(script.contains("e2e-live/admin-live.spec.js"), "脚本未指向 admin-live.spec.js");
+        assertTrue(script.contains("playwright.config.live.js"), "脚本未指定 live 配置(-c)");
+        assertTrue(script.contains("--project=admin-desktop"), "脚本未指定 admin-desktop project");
+    }
+
+    // ================================================================
+    // B 组:工具链单副本契约(P-474-1 · 当前必失败 = RED)
+    // ================================================================
+
+    @Test
+    @DisplayName("B1 仓库根与 tests/ 不得并存两份 @playwright/test 声明(单物理副本契约)")
+    void playwrightTest_双副本声明_违反单副本契约() throws Exception {
+        JsonNode rootPkg = new ObjectMapper()
+                .readTree(repoRoot().resolve("package.json").toFile());
+        JsonNode testsPkg = new ObjectMapper()
+                .readTree(repoRoot().resolve("tests").resolve("package.json").toFile());
+
+        Set<String> rootDecls = playwrightDecls(rootPkg, "devDependencies", "dependencies");
+        Set<String> testsDecls = playwrightDecls(testsPkg, "devDependencies", "dependencies");
+        int declaredSides = (rootDecls.isEmpty() ? 0 : 1) + (testsDecls.isEmpty() ? 0 : 1);
+
+        assertTrue(declaredSides <= 1,
+                "P-474-1 双副本 @playwright/test 声明:根 package.json 声明 " + rootDecls
+                        + ",tests/package.json 声明 " + testsDecls
+                        + " → 两份 node_modules 物理副本各持模块状态,CLI 与 spec 各拿一份,"
+                        + "test.describe() 无法注册,runner 假红 'No tests found'"
+                        + "(tests/playwright.config.live.js 的 R416 守卫仅在运行时 fail-fast,缺陷仍在仓库里)。"
+                        + "修复:根 package.json 移除 @playwright/test devDependency(tests/ 留单副本),"
+                        + "或 tests/package.json 移除声明改走根副本——两侧至多一方声明。");
+    }
+
+    // ================================================================
+    // C 组:管理端主链路 API 契约(E2E 4 场景页面所依赖的后端端点)
+    // ================================================================
+
+    @Test
+    @DisplayName("C1 /api/admin/users:admin 角色 → 200 + Result 信封 + Page 分页字段(E2E 场景1 用户列表)")
+    void users_admin角色_分页信封() throws Exception {
+        User u = new User();
+        u.setId(1L);
+        u.setRole("parent");
+        u.setNickname("家长甲");
+        Page<User> page = new Page<>(1, 10);
+        page.setRecords(Arrays.asList(u));
+        page.setTotal(1L);
+        doReturn(page).when(userMapper).selectPage(any(), any());
+
+        adminApi.perform(post("/api/admin/users")
+                        .requestAttr("role", "admin")
+                        .requestAttr("roles", Arrays.asList("admin"))
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .content("{}"))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(200))
+                .andExpect(jsonPath("$.data.current").value(1))
+                .andExpect(jsonPath("$.data.size").value(10))
+                .andExpect(jsonPath("$.data.total").value(1))
+                .andExpect(jsonPath("$.data.records[0].id").value(1))
+                .andExpect(jsonPath("$.data.records[0].nickname").value("家长甲"));
+    }
+
+    @Test
+    @DisplayName("C2·越权(C403) /api/admin/users:teacher(入驻角色、非平台角色)→ 业务码 403 且不触达 DB")
+    void users_teacher角色_越权拒绝() throws Exception {
+        adminApi.perform(post("/api/admin/users")
+                        .requestAttr("role", "teacher")
+                        .requestAttr("roles", Arrays.asList("teacher"))
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .content("{}"))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(403))
+                .andExpect(jsonPath("$.message").value("无权限访问该接口"));
+
+        verify(userMapper, never()).selectPage(any(), any());
+    }
+
+    @Test
+    @DisplayName("C3·越权(C403) /api/admin/users:parent(C端角色)→ 业务码 403")
+    void users_parent角色_越权拒绝() throws Exception {
+        adminApi.perform(post("/api/admin/users")
+                        .requestAttr("role", "parent")
+                        .requestAttr("roles", Arrays.asList("parent"))
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .content("{}"))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(403))
+                .andExpect(jsonPath("$.message").value("无权限访问该接口"));
+
+        verify(userMapper, never()).selectPage(any(), any());
+    }
+
+    @Test
+    @DisplayName("C4 /api/admin/energy-rule:list 返回 Page 信封、dimensions 返回列表(E2E 场景3 能量规则管理)")
+    void energyRule_list与dimensions_信封() throws Exception {
+        EnergyRule rule = new EnergyRule();
+        rule.setId(7L);
+        rule.setRuleName("打卡+10");
+        rule.setEventType("checkin");
+        // 控制器原地语义:selectPage(p, null) 的返回值被丢弃,MyBatis-Plus 分页插件
+        // 原地填充传入的 IPage —— 打桩必须同样原地填充 controller 传入的 Page
+        doAnswer(inv -> {
+            com.baomidou.mybatisplus.core.metadata.IPage<EnergyRule> p = inv.getArgument(0);
+            p.setRecords(Arrays.asList(rule));
+            p.setTotal(1L);
+            return p;
+        }).when(energyRuleMapper).selectPage(any(), any());
+
+        EnergyDimension dim = new EnergyDimension();
+        dim.setId(1L);
+        dim.setCode("body");
+        dim.setName("身");
+        when(energyDimensionMapper.selectList(any())).thenReturn(Arrays.asList(dim));
+
+        energyRuleApi.perform(post("/api/admin/energy-rule/list")
+                                .contentType(MediaType.APPLICATION_JSON)
+                                .content("{\"page\":1,\"size\":10}"))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(200))
+                .andExpect(jsonPath("$.data.records[0].ruleName").value("打卡+10"))
+                .andExpect(jsonPath("$.data.total").value(1));
+
+        energyRuleApi.perform(post("/api/admin/energy-rule/dimensions")
+                                .contentType(MediaType.APPLICATION_JSON)
+                                .content("{}"))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(200))
+                .andExpect(jsonPath("$.data[0].code").value("body"));
+    }
+
+    @Test
+    @DisplayName("C5·不存在(C404) /api/admin/energy-rule/toggle:规则不存在 → 业务拒绝(不产生空指针)")
+    void energyRule_toggle不存在_业务拒绝() throws Exception {
+        when(energyRuleMapper.selectById(eq(99L))).thenReturn(null);
+
+        energyRuleApi.perform(post("/api/admin/energy-rule/toggle")
+                                .contentType(MediaType.APPLICATION_JSON)
+                                .content("{\"id\":99}"))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(500))
+                .andExpect(jsonPath("$.message").value("规则不存在"));
+    }
+
+    @Test
+    @DisplayName("C6 /api/admin/config/list:返回 SysConfigDTO 列表(E2E 场景4 系统配置页数据源)")
+    void sysConfig_list_dto字段() throws Exception {
+        SysConfig entity = new SysConfig();
+        entity.setConfigKey("wechat.appid");
+        entity.setConfigValue("wx0000000000");
+        SysConfigDTO dto = SysConfigDTO.from(entity);
+        when(sysConfigService.listAll()).thenReturn(Result.success(Arrays.asList(dto)));
+
+        sysConfigApi.perform(post("/api/admin/config/list")
+                            .contentType(MediaType.APPLICATION_JSON)
+                            .content("{}"))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(200))
+                .andExpect(jsonPath("$.data[0].configKey").value("wechat.appid"))
+                .andExpect(jsonPath("$.data[0].configValue").value("wx0000000000"));
+    }
+
+    @Test
+    @DisplayName("C7 /api/system/health:返回 JVM 运行快照(uptime/memUsagePercent/javaVersion/osName)")
+    void systemHealth_jvm快照字段() throws Exception {
+        systemApi.perform(post("/api/system/health")
+                            .contentType(MediaType.APPLICATION_JSON)
+                            .content("{}"))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(200))
+                .andExpect(jsonPath("$.data.uptime").exists())
+                .andExpect(jsonPath("$.data.memUsagePercent").exists())
+                .andExpect(jsonPath("$.data.javaVersion").exists())
+                .andExpect(jsonPath("$.data.osName").exists());
+    }
+
+    // ================================================================
+    // 边界前提自检
+    // ================================================================
+
+    /**
+     * C4xxx 错误码体系(同键异载荷 C4092 / 乐观锁冲突 C422 / 幂等重放 replay=true)
+     * 在本仓未落地(全仓无 C-code 常量)且本能力键为只读 E2E 套件,不适用;
+     * 此常量为 GREEN 阶段契约化 API_REFERENCE.md §5.5 时预留的边界锚点。
+     */
+    static final List<String> NOT_APPLICABLE_BOUNDARIES =
+            Arrays.asList("replay=true 幂等重放", "同键异载荷 C4092", "乐观锁冲突 C422");
+
+    @Test
+    @DisplayName("C8·平台角色口径自检:admin/operator/finance 可过门禁,teacher/parent 不可(契约前提)")
+    void 平台角色口径_与AdminRoles一致() {
+        assertTrue(AdminRoles.hasAnyPlatformRole(Arrays.asList("admin")), "admin 必须是平台角色");
+        assertTrue(AdminRoles.hasAnyPlatformRole(Arrays.asList("operator", "finance")));
+        assertFalse(AdminRoles.hasAnyPlatformRole(Arrays.asList("teacher")), "teacher(入驻角色)不得越权平台端点");
+        assertFalse(AdminRoles.hasAnyPlatformRole(Arrays.asList("parent")), "parent(C端角色)不得越权平台端点");
+        assertFalse(NOT_APPLICABLE_BOUNDARIES.isEmpty(), "不适用边界清单须随类留存,供 GREEN 阶段 §5.5 契约化引用");
+    }
+}