|
|
@@ -0,0 +1,327 @@
|
|
|
+package com.etotem.cfc.unit;
|
|
|
+
|
|
|
+import com.etotem.cfc.config.GlobalExceptionHandler;
|
|
|
+import com.etotem.cfc.config.JwtInterceptor;
|
|
|
+import com.etotem.cfc.controller.family.FamilyUserController;
|
|
|
+import com.etotem.cfc.entity.Family;
|
|
|
+import com.etotem.cfc.entity.FamilyMember;
|
|
|
+import com.etotem.cfc.entity.User;
|
|
|
+import com.etotem.cfc.mapper.FamilyMapper;
|
|
|
+import com.etotem.cfc.mapper.FamilyMemberMapper;
|
|
|
+import com.etotem.cfc.mapper.UserMapper;
|
|
|
+import com.etotem.cfc.service.UserService;
|
|
|
+import com.jayway.jsonpath.JsonPath;
|
|
|
+import org.junit.jupiter.api.BeforeEach;
|
|
|
+import org.junit.jupiter.api.DisplayName;
|
|
|
+import org.junit.jupiter.api.Test;
|
|
|
+import org.mockito.ArgumentCaptor;
|
|
|
+import org.mockito.Mock;
|
|
|
+import org.mockito.MockitoAnnotations;
|
|
|
+import org.springframework.http.MediaType;
|
|
|
+import org.springframework.mock.web.MockHttpServletRequest;
|
|
|
+import org.springframework.mock.web.MockHttpServletResponse;
|
|
|
+import org.springframework.test.util.ReflectionTestUtils;
|
|
|
+import org.springframework.test.web.servlet.MockMvc;
|
|
|
+import org.springframework.test.web.servlet.MvcResult;
|
|
|
+import org.springframework.test.web.servlet.setup.MockMvcBuilders;
|
|
|
+
|
|
|
+import javax.servlet.http.HttpServletResponse;
|
|
|
+
|
|
|
+import static org.hamcrest.Matchers.containsString;
|
|
|
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
|
|
+import static org.junit.jupiter.api.Assertions.assertEquals;
|
|
|
+import static org.junit.jupiter.api.Assertions.assertFalse;
|
|
|
+import static org.junit.jupiter.api.Assertions.assertNotNull;
|
|
|
+import static org.junit.jupiter.api.Assertions.assertThrows;
|
|
|
+import static org.junit.jupiter.api.Assertions.assertTrue;
|
|
|
+import static org.mockito.ArgumentMatchers.any;
|
|
|
+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;
|
|
|
+
|
|
|
+/**
|
|
|
+ * 契约测试:能力键 {@code family.family.createWithInvite}(S-cfc-256,SC-P-01)。
|
|
|
+ *
|
|
|
+ * <p><b>需求溯源(tests/user-scenarios/应用场景总览.md SC-P-01 · tests/test-cases/parent.md TC-P-01/TC-P-01-E/TC-P-01-P)</b></p>
|
|
|
+ * <ul>
|
|
|
+ * <li>TC-P-01 正常流:创建家庭(名称「测试家庭1」) → 家庭创建成功;生成唯一邀请码+二维码(令牌+落地页);角色变家庭管理员。</li>
|
|
|
+ * <li>TC-P-01-E 异常流:家庭名称传空 / 超长(>30 字符) / 含 {@code <script>} 注入 → 名称空或超长返回 400 且 message 含
|
|
|
+ * 『家庭名称』校验项;HTML/SQL 注入被转义,库内不落恶意串;不抛 500、不泄露堆栈。</li>
|
|
|
+ * <li>TC-P-01-P 权限流:非归属数据访问统一 403/401——本类落地为「建家庭为写操作,无 token 匿名一律 401」。</li>
|
|
|
+ * </ul>
|
|
|
+ *
|
|
|
+ * <p><b>设计锚点(docs/superpowers/api/API_REFERENCE.md §4.2 家庭与成员 /
|
|
|
+ * cfc-backend controller/family/FamilyInviteController(创建/邀请码/二维码落地页)+ FamilyController)</b></p>
|
|
|
+ * <ul>
|
|
|
+ * <li>当前「建家庭」入口为 {@code POST /api/family/user/create-family}
|
|
|
+ * ({@link FamilyUserController#createFamily} → {@link UserService#createFamilyForUser}),
|
|
|
+ * 契约要求该链路同步完成:创建家庭(唯一邀请码)→ 创建者成为家庭管理员 → 名称校验(空/超长/注入)→
|
|
|
+ * 邀请材料(令牌+二维码落地页,复用 {@code FamilyInvitationService.generateInvitation} + 小程序码语义)产出。</li>
|
|
|
+ * <li>管理员语义先例:{@code UserService.createUserAndFamily}(L1534)/ {@code ensureUserHasFamily}(L1569)均已
|
|
|
+ * {@code user.setIsFamilyAdmin(true)};{@code createFamilyForUser} 路径缺失该回写 → RED。</li>
|
|
|
+ * <li>400 语义:{@link GlobalExceptionHandler} 将 {@link IllegalArgumentException} 映射为
|
|
|
+ * {@code Result.error(400, message)};控制层也可直接返回 {@code Result.badRequest(...)}。</li>
|
|
|
+ * <li>同类 RED 先例:family.family.autoCreateForPurchase(S-cfc-188)、family.invite.joinValidationGate/Rules(S-cfc-58/59)。</li>
|
|
|
+ * </ul>
|
|
|
+ *
|
|
|
+ * <p><b>RED 预期</b>(当前实现均未落地 → 断言红):</p>
|
|
|
+ * <ol>
|
|
|
+ * <li>创建者未回写 {@code isFamilyAdmin=true}(SC-P-01「成为管理员」缺失);</li>
|
|
|
+ * <li>空名/超长名无校验、HTML 注入原样落库(TC-P-01-E 校验/转义缺失);</li>
|
|
|
+ * <li>控制层无空名/超长名 400 守卫(TC-P-01-E「返回 400 且 message 含『家庭名称』」缺失);</li>
|
|
|
+ * <li>{@code /api/family/user/create-family} 未入 {@code JwtInterceptor.LOGIN_REQUIRED_PATHS},匿名(userId=-1)被放行
|
|
|
+ * (写操作必须登录,TC-P-01-P 缺失)。</li>
|
|
|
+ * </ol>
|
|
|
+ *
|
|
|
+ * <p><b>测试范围</b>:纯 Mockito + Spring Test(MockMvc standalone + ReflectionTestUtils),
|
|
|
+ * 无 Spring 容器 / 无 DB / 无真实微信;风格与同批 CONTRACT 测试(FamilyAutoCreateForPurchaseContractTest /
|
|
|
+ * FamilyJoinValidationRulesContractTest / TeamInvitationCreateContractTest)一致。</p>
|
|
|
+ */
|
|
|
+public class FamilyCreateWithInviteContractTest {
|
|
|
+
|
|
|
+ private static final String KEY = "[family.family.createWithInvite]";
|
|
|
+ private static final Long CREATOR_USER_ID = 1L;
|
|
|
+ private static final String CREATE_FAMILY_URL = "/api/family/user/create-family";
|
|
|
+ private static final String INJECTION_NAME = "<script>alert('xss')</script>";
|
|
|
+
|
|
|
+ @Mock
|
|
|
+ private UserMapper userMapper;
|
|
|
+
|
|
|
+ @Mock
|
|
|
+ private FamilyMapper familyMapper;
|
|
|
+
|
|
|
+ @Mock
|
|
|
+ private FamilyMemberMapper familyMemberMapper;
|
|
|
+
|
|
|
+ /** 服务段:真实 UserService + 注入 mock mappers —— 验证 service 层契约 */
|
|
|
+ private UserService realService;
|
|
|
+
|
|
|
+ /** 控制段:真实 FamilyUserController + 注入 realService —— 验证 API 层契约 */
|
|
|
+ private FamilyUserController controller;
|
|
|
+
|
|
|
+ private MockMvc mockMvc;
|
|
|
+
|
|
|
+ @BeforeEach
|
|
|
+ void setUp() {
|
|
|
+ MockitoAnnotations.openMocks(this);
|
|
|
+
|
|
|
+ realService = new UserService();
|
|
|
+ ReflectionTestUtils.setField(realService, "userMapper", userMapper);
|
|
|
+ ReflectionTestUtils.setField(realService, "familyMapper", familyMapper);
|
|
|
+ ReflectionTestUtils.setField(realService, "familyMemberMapper", familyMemberMapper);
|
|
|
+
|
|
|
+ controller = new FamilyUserController();
|
|
|
+ ReflectionTestUtils.setField(controller, "userService", realService);
|
|
|
+
|
|
|
+ mockMvc = MockMvcBuilders.standaloneSetup(controller)
|
|
|
+ .setControllerAdvice(new GlobalExceptionHandler())
|
|
|
+ .build();
|
|
|
+
|
|
|
+ // 公共桩:当前用户存在;创建者在目标家庭尚无成员记录(addCreatorAsMember 幂等查不命中)
|
|
|
+ User current = new User();
|
|
|
+ current.setId(CREATOR_USER_ID);
|
|
|
+ when(userMapper.selectById(CREATOR_USER_ID)).thenReturn(current);
|
|
|
+ when(familyMemberMapper.selectCount(any())).thenReturn(0L);
|
|
|
+ }
|
|
|
+
|
|
|
+ // ====================================================================
|
|
|
+ // 服务层契约(UserService.createFamilyForUser)
|
|
|
+ // ====================================================================
|
|
|
+
|
|
|
+ @Test
|
|
|
+ @DisplayName("【服务-正常锚点】合法名称创建成功:唯一邀请码 + creatorId + 创建人入成员表(GREEN 锚点)")
|
|
|
+ void service_createFamily_success_anchor_唯一邀请码与创建者关系() {
|
|
|
+ realService.createFamilyForUser(CREATOR_USER_ID, "测试家庭1");
|
|
|
+
|
|
|
+ ArgumentCaptor<Family> famCap = ArgumentCaptor.forClass(Family.class);
|
|
|
+ verify(familyMapper).insert(famCap.capture());
|
|
|
+ Family family = famCap.getValue();
|
|
|
+ assertNotNull(family.getInviteCode(), KEY + " 创建家庭必须生成唯一邀请码");
|
|
|
+ assertEquals(CREATOR_USER_ID, family.getCreatorId(), KEY + " creatorId 须等于当前用户 ID");
|
|
|
+ assertEquals("测试家庭1", family.getName(), KEY + " 家庭名称应原样入库");
|
|
|
+
|
|
|
+ ArgumentCaptor<User> userCap = ArgumentCaptor.forClass(User.class);
|
|
|
+ verify(userMapper).updateById(userCap.capture());
|
|
|
+ assertEquals(CREATOR_USER_ID, userCap.getValue().getId(), KEY + " 回写用户应为创建者本人");
|
|
|
+
|
|
|
+ verify(familyMemberMapper).insert(any(FamilyMember.class));
|
|
|
+ }
|
|
|
+
|
|
|
+ @Test
|
|
|
+ @DisplayName("【服务-正常流·管理员】createFamilyForUser 创建后必须回写 isFamilyAdmin=true → RED(当前缺失)")
|
|
|
+ void service_createFamily_mustSetCreatorAdminFlag() {
|
|
|
+ realService.createFamilyForUser(CREATOR_USER_ID, "测试家庭1");
|
|
|
+
|
|
|
+ ArgumentCaptor<User> cap = ArgumentCaptor.forClass(User.class);
|
|
|
+ verify(userMapper).updateById(cap.capture());
|
|
|
+ assertEquals(Boolean.TRUE, cap.getValue().getIsFamilyAdmin(),
|
|
|
+ KEY + " 创建者应成为家庭管理员;当前 createFamilyForUser 未回写 isFamilyAdmin=true"
|
|
|
+ + "(对照 createUserAndFamily / ensureUserHasFamily 均已实现该语义)");
|
|
|
+ }
|
|
|
+
|
|
|
+ @Test
|
|
|
+ @DisplayName("【服务-异常流·空名】空字符串应被拒绝且 message 含『家庭名称』,不落库 → RED(当前直接建家庭成功)")
|
|
|
+ void service_emptyName_mustBeRejected_notPersisted() {
|
|
|
+ RuntimeException ex = assertThrows(RuntimeException.class,
|
|
|
+ () -> realService.createFamilyForUser(CREATOR_USER_ID, ""),
|
|
|
+ KEY + " 契约要求空名拒绝,当前直接建家庭成功");
|
|
|
+ assertTrue(ex.getMessage() != null && ex.getMessage().contains("家庭名称"),
|
|
|
+ KEY + " message 应含『家庭名称』校验项;实际: " + ex.getMessage());
|
|
|
+ verify(familyMapper, never()).insert(any(Family.class));
|
|
|
+ verify(userMapper, never()).updateById(any(User.class));
|
|
|
+ verify(familyMemberMapper, never()).insert(any(FamilyMember.class));
|
|
|
+ }
|
|
|
+
|
|
|
+ @Test
|
|
|
+ @DisplayName("【服务-异常流·超长名】超过 30 字符应被拒绝且 message 含『家庭名称』,不落库 → RED(当前不校验)")
|
|
|
+ void service_nameOverMaxLength_mustBeRejected_notPersisted() {
|
|
|
+ String longName = repeat("测", 31); // 契约上限 30 字符
|
|
|
+
|
|
|
+ RuntimeException ex = assertThrows(RuntimeException.class,
|
|
|
+ () -> realService.createFamilyForUser(CREATOR_USER_ID, longName),
|
|
|
+ KEY + " 契约要求 >30 字符拒绝,当前直接建家庭成功");
|
|
|
+ assertTrue(ex.getMessage() != null && ex.getMessage().contains("家庭名称"),
|
|
|
+ KEY + " message 应含『家庭名称』校验项;实际: " + ex.getMessage());
|
|
|
+ verify(familyMapper, never()).insert(any(Family.class));
|
|
|
+ verify(userMapper, never()).updateById(any(User.class));
|
|
|
+ verify(familyMemberMapper, never()).insert(any(FamilyMember.class));
|
|
|
+ }
|
|
|
+
|
|
|
+ @Test
|
|
|
+ @DisplayName("【服务-异常流·注入】含 HTML 注入串的名称必须被拒绝或转义,库内不落恶意串 → RED(当前原样落库)")
|
|
|
+ void service_injectionName_mustNotBeStoredRaw() {
|
|
|
+ try {
|
|
|
+ realService.createFamilyForUser(CREATOR_USER_ID, INJECTION_NAME);
|
|
|
+ } catch (RuntimeException rejected) {
|
|
|
+ // 契约允许「拒绝注入串」:此时不得落库
|
|
|
+ verify(familyMapper, never()).insert(any(Family.class));
|
|
|
+ return;
|
|
|
+ }
|
|
|
+
|
|
|
+ ArgumentCaptor<Family> famCap = ArgumentCaptor.forClass(Family.class);
|
|
|
+ verify(familyMapper).insert(famCap.capture());
|
|
|
+ String stored = famCap.getValue().getName();
|
|
|
+ assertFalse(stored.contains("<script>") && stored.contains("</script>"),
|
|
|
+ KEY + " 库内不应原样存储 HTML 注入串(应转义/净化);当前原样落库");
|
|
|
+ }
|
|
|
+
|
|
|
+ @Test
|
|
|
+ @DisplayName("【服务-边界锚点】恰好 30 字符不触发拒绝,名称原样入库(GREEN 锚点)")
|
|
|
+ void service_nameAtMaxLengthBoundary_passes() {
|
|
|
+ String boundaryName = repeat("测", 30);
|
|
|
+
|
|
|
+ assertDoesNotThrow(() -> realService.createFamilyForUser(CREATOR_USER_ID, boundaryName),
|
|
|
+ KEY + " 恰好 30 字符应为合法边界");
|
|
|
+
|
|
|
+ ArgumentCaptor<Family> famCap = ArgumentCaptor.forClass(Family.class);
|
|
|
+ verify(familyMapper).insert(famCap.capture());
|
|
|
+ assertEquals(boundaryName, famCap.getValue().getName(), KEY + " 边界名应原样入库");
|
|
|
+ }
|
|
|
+
|
|
|
+ // ====================================================================
|
|
|
+ // 控制器层契约(POST /api/family/user/create-family)
|
|
|
+ // ====================================================================
|
|
|
+
|
|
|
+ @Test
|
|
|
+ @DisplayName("【控制-异常流·空名】name=\"\" 应返回 code=400 且 message 含『家庭名称』 → RED(当前透传建家庭 200)")
|
|
|
+ void ctrl_emptyName_returns400_withFamilyNameMessage() throws Exception {
|
|
|
+ mockMvc.perform(post(CREATE_FAMILY_URL)
|
|
|
+ .contentType(MediaType.APPLICATION_JSON)
|
|
|
+ .content("{\"name\":\"\"}")
|
|
|
+ .requestAttr("userId", CREATOR_USER_ID))
|
|
|
+ .andExpect(status().isOk())
|
|
|
+ .andExpect(jsonPath("$.code").value(400))
|
|
|
+ .andExpect(jsonPath("$.message").value(containsString("家庭名称")));
|
|
|
+ }
|
|
|
+
|
|
|
+ @Test
|
|
|
+ @DisplayName("【控制-异常流·超长名】name 超过 30 字符应返回 code=400 且 message 含『家庭名称』 → RED(当前透传建家庭 200)")
|
|
|
+ void ctrl_nameOverMaxLength_returns400_withFamilyNameMessage() throws Exception {
|
|
|
+ String longName = repeat("测", 31);
|
|
|
+ mockMvc.perform(post(CREATE_FAMILY_URL)
|
|
|
+ .contentType(MediaType.APPLICATION_JSON)
|
|
|
+ .content("{\"name\":\"" + longName + "\"}")
|
|
|
+ .requestAttr("userId", CREATOR_USER_ID))
|
|
|
+ .andExpect(status().isOk())
|
|
|
+ .andExpect(jsonPath("$.code").value(400))
|
|
|
+ .andExpect(jsonPath("$.message").value(containsString("家庭名称")));
|
|
|
+ }
|
|
|
+
|
|
|
+ @Test
|
|
|
+ @DisplayName("【控制-异常流·注入】含 HTML 注入串的名称不得原样落库(拒绝 400 或转义后入库)→ RED(当前 200 原样落库)")
|
|
|
+ void ctrl_injectionName_notStoredRaw() throws Exception {
|
|
|
+ MvcResult result = mockMvc.perform(post(CREATE_FAMILY_URL)
|
|
|
+ .contentType(MediaType.APPLICATION_JSON)
|
|
|
+ .content("{\"name\":\"" + INJECTION_NAME + "\"}")
|
|
|
+ .requestAttr("userId", CREATOR_USER_ID))
|
|
|
+ .andExpect(status().isOk())
|
|
|
+ .andReturn();
|
|
|
+
|
|
|
+ Integer code = JsonPath.read(result.getResponse().getContentAsString(), "$.code");
|
|
|
+ if (Integer.valueOf(200).equals(code)) {
|
|
|
+ // 未拒绝 → 必须已转义,库内不落恶意串
|
|
|
+ ArgumentCaptor<Family> famCap = ArgumentCaptor.forClass(Family.class);
|
|
|
+ verify(familyMapper).insert(famCap.capture());
|
|
|
+ String stored = famCap.getValue().getName();
|
|
|
+ assertFalse(stored.contains("<script>") && stored.contains("</script>"),
|
|
|
+ KEY + " 库内不应原样存储 HTML 注入串(应转义/净化);当前原样落库");
|
|
|
+ } else {
|
|
|
+ assertEquals(Integer.valueOf(400), code,
|
|
|
+ KEY + " 若拒绝注入名称,应返回 code=400(实际 " + code + ")");
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ @Test
|
|
|
+ @DisplayName("【控制-正常锚点】合法 name → code=200,家庭落库且名称正确(GREEN 锚点)")
|
|
|
+ void ctrl_validName_createsFamily_andStoresName() throws Exception {
|
|
|
+ mockMvc.perform(post(CREATE_FAMILY_URL)
|
|
|
+ .contentType(MediaType.APPLICATION_JSON)
|
|
|
+ .content("{\"name\":\"测试家庭1\"}")
|
|
|
+ .requestAttr("userId", CREATOR_USER_ID))
|
|
|
+ .andExpect(status().isOk())
|
|
|
+ .andExpect(jsonPath("$.code").value(200));
|
|
|
+
|
|
|
+ ArgumentCaptor<Family> famCap = ArgumentCaptor.forClass(Family.class);
|
|
|
+ verify(familyMapper).insert(famCap.capture());
|
|
|
+ assertEquals("测试家庭1", famCap.getValue().getName(),
|
|
|
+ KEY + " 家庭名称须按提交值入库");
|
|
|
+ }
|
|
|
+
|
|
|
+ // ====================================================================
|
|
|
+ // 权限流契约(TC-P-01-P:写操作必须登录)
|
|
|
+ // ====================================================================
|
|
|
+
|
|
|
+ @Test
|
|
|
+ @DisplayName("【权限流·建家庭】无 token 匿名访问 create-family 必须 401(写操作不得匿名放行)→ RED(当前未入 LOGIN_REQUIRED_PATHS,匿名 userId=-1 放行)")
|
|
|
+ void permission_createFamily_anonymousMustBe401() throws Exception {
|
|
|
+ JwtInterceptor interceptor = new JwtInterceptor();
|
|
|
+ MockHttpServletRequest request = new MockHttpServletRequest();
|
|
|
+ request.setMethod("POST");
|
|
|
+ request.setRequestURI(CREATE_FAMILY_URL);
|
|
|
+ MockHttpServletResponse response = new MockHttpServletResponse();
|
|
|
+
|
|
|
+ boolean allowed = interceptor.preHandle(request, response, null);
|
|
|
+
|
|
|
+ assertFalse(allowed,
|
|
|
+ KEY + " 建家庭/生成邀请为写操作,无 token 不得匿名放行;当前 create-family 未在 LOGIN_REQUIRED_PATHS"
|
|
|
+ + "(对照 /api/family/member/ 等私写端点)→ 匿名 userId=-1 直达 controller");
|
|
|
+ assertEquals(HttpServletResponse.SC_UNAUTHORIZED, response.getStatus(),
|
|
|
+ KEY + " 未登录访问建家庭应返回 HTTP 401");
|
|
|
+ }
|
|
|
+
|
|
|
+ // ====================================================================
|
|
|
+ // 辅助
|
|
|
+ // ====================================================================
|
|
|
+
|
|
|
+ /** Java 8 兼容拼接(避免依赖 String.repeat,Java 11+ API) */
|
|
|
+ private String repeat(String s, int n) {
|
|
|
+ StringBuilder sb = new StringBuilder(s.length() * n);
|
|
|
+ for (int i = 0; i < n; i++) {
|
|
|
+ sb.append(s);
|
|
|
+ }
|
|
|
+ return sb.toString();
|
|
|
+ }
|
|
|
+}
|