|
|
@@ -0,0 +1,293 @@
|
|
|
+package com.etotem.cfc.unit;
|
|
|
+
|
|
|
+import com.etotem.cfc.common.Result;
|
|
|
+import com.etotem.cfc.controller.mind.EmotionRecognitionController;
|
|
|
+import com.etotem.cfc.service.AiGateway;
|
|
|
+import org.junit.jupiter.api.BeforeEach;
|
|
|
+import org.junit.jupiter.api.DisplayName;
|
|
|
+import org.junit.jupiter.api.Test;
|
|
|
+import org.springframework.web.bind.annotation.RequestAttribute;
|
|
|
+import org.springframework.web.multipart.MultipartFile;
|
|
|
+
|
|
|
+import java.lang.reflect.Field;
|
|
|
+import java.lang.reflect.Method;
|
|
|
+import java.util.ArrayList;
|
|
|
+import java.util.Base64;
|
|
|
+import java.util.Collections;
|
|
|
+import java.util.LinkedHashMap;
|
|
|
+import java.util.Map;
|
|
|
+
|
|
|
+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.assertTrue;
|
|
|
+import static org.junit.jupiter.api.Assertions.fail;
|
|
|
+import static org.mockito.ArgumentMatchers.anyString;
|
|
|
+import static org.mockito.Mockito.mock;
|
|
|
+import static org.mockito.Mockito.never;
|
|
|
+import static org.mockito.Mockito.verify;
|
|
|
+import static org.mockito.Mockito.when;
|
|
|
+
|
|
|
+/**
|
|
|
+ * 能力键 {@code tongue.emotion.capture}(S-cfc-289,TDD-RED 阶段)契约级单测。
|
|
|
+ *
|
|
|
+ * <p><b>契约溯源</b></p>
|
|
|
+ * <ul>
|
|
|
+ * <li>需求:{@code tests/user-scenarios/应用场景总览.md} SC-P-70(业务域 I)—
|
|
|
+ * 「拍照/上传 → 识别情绪标签 → 关联测评;非照片/模糊拒绝;隐私标注不外露」;
|
|
|
+ * {@code tests/user-scenarios/02-parent.md} P-70、
|
|
|
+ * {@code tests/test-cases/parent.md} TC-P-70 / TC-P-70-E / TC-P-70-P。</li>
|
|
|
+ * <li>设计:{@code docs/superpowers/api/API_REFERENCE.md} §4.37 / §4.7 —
|
|
|
+ * {@code POST /api/mind/emotion/analyze}(multipart 文件上传,走 LangGraph DeepFace)、
|
|
|
+ * {@code POST /api/mind/emotion/analyze-url};§4.63.9 SC-P-70 载体清单。</li>
|
|
|
+ * <li>AC 条款:TC-P-70-E「非照片/模糊拒绝提示『请上传清晰舌苔照』;低置信度提示
|
|
|
+ * 『识别不清晰,建议重拍』;隐私标注不外露」;TC-P-70-P「非归属数据访问统一 403/401」。</li>
|
|
|
+ * </ul>
|
|
|
+ *
|
|
|
+ * <p><b>实现现状(RED 依据)</b>:当前 {@code EmotionRecognitionController.analyze} 仅校验
|
|
|
+ * 空文件与大小(≤10MB),不校验图片类型/清晰度/置信度,也不剔除调试用原始响应;
|
|
|
+ * {@code EmotionCheckinDTO} / {@code EmotionCheckin} 无测评关联字段。
|
|
|
+ * 因此本测试以「控制器行为 + DTO/实体结构」探测契约缺口:能编译、能运行、断言失败(红)。</p>
|
|
|
+ *
|
|
|
+ * <p><b>GREEN 升级指引</b>:实现者在照片识别链补齐(a)MIME/魔数校验与模糊拒绝、
|
|
|
+ * (b)低置信度重拍提示、(c)测评关联标识透传与持久化、(d)原始响应/隐私标注不回传后,
|
|
|
+ * 本测试自动转绿。纯 Mockito + 反射,无 Spring 上下文 / 无 DB / 无外部服务。</p>
|
|
|
+ */
|
|
|
+class TongueEmotionCaptureContractTest {
|
|
|
+
|
|
|
+ private static final Long USER_ID = 1001L;
|
|
|
+ private static final String MSG_NOT_CLEAR_PHOTO = "请上传清晰舌苔照";
|
|
|
+ private static final String MSG_LOW_CONFIDENCE = "识别不清晰,建议重拍";
|
|
|
+
|
|
|
+ /** 「关联测评」允许的结果键名(SC-P-70 主流程第三段) */
|
|
|
+ private static final String[] ASSESSMENT_LINK_KEYS = {
|
|
|
+ "assessmentId", "assessmentRecordId", "relatedAssessmentId", "assessmentNo", "assessmentRef"
|
|
|
+ };
|
|
|
+
|
|
|
+ private AiGateway aiGateway;
|
|
|
+ private EmotionRecognitionController controller;
|
|
|
+
|
|
|
+ @BeforeEach
|
|
|
+ void setUp() throws Exception {
|
|
|
+ aiGateway = mock(AiGateway.class);
|
|
|
+ controller = new EmotionRecognitionController();
|
|
|
+ Field field = EmotionRecognitionController.class.getDeclaredField("aiGateway");
|
|
|
+ field.setAccessible(true);
|
|
|
+ field.set(controller, aiGateway);
|
|
|
+ }
|
|
|
+
|
|
|
+ // ==================== 正常流:识别情绪标签 + 关联测评 ====================
|
|
|
+
|
|
|
+ @Test
|
|
|
+ @DisplayName("正常流-1:舌苔照识别成功应返回中文情绪标签并携带测评关联标识")
|
|
|
+ void 正常流_识别结果应携带测评关联标识() throws Exception {
|
|
|
+ when(aiGateway.analyzeEmotion(anyString())).thenReturn(highConfidenceResult());
|
|
|
+
|
|
|
+ Result<Map<String, Object>> result = controller.analyze(USER_ID, photo("image/jpeg", "tongue.jpg"));
|
|
|
+
|
|
|
+ assertEquals(200, result.getCode(), "[tongue.emotion.capture] 清晰舌苔照应识别成功(TC-P-70 主流程)。");
|
|
|
+ Map<String, Object> data = result.getData();
|
|
|
+ assertNotNull(data, "[tongue.emotion.capture] 识别成功必须返回结果数据。");
|
|
|
+ assertEquals("开心", data.get("dominant_label_zh"),
|
|
|
+ "[tongue.emotion.capture] 应返回中文情绪标签 dominant_label_zh(§4.37 响应契约)。");
|
|
|
+ assertTrue(hasAnyKey(data, ASSESSMENT_LINK_KEYS),
|
|
|
+ "[tongue.emotion.capture] 识别结果应携带测评关联标识(assessmentId / assessmentRecordId / "
|
|
|
+ + "relatedAssessmentId / assessmentNo / assessmentRef),实现未落地:"
|
|
|
+ + "SC-P-70 主流程为「拍照/上传 → 识别情绪标签 → 关联测评」(TC-P-70)。");
|
|
|
+ }
|
|
|
+
|
|
|
+ @Test
|
|
|
+ @DisplayName("正常流-2:采集载体(DTO/实体)应可承载测评关联标识")
|
|
|
+ void 正常流_采集载体应具备测评关联字段() {
|
|
|
+ String[] carriers = {
|
|
|
+ "com.etotem.cfc.dto.EmotionCheckinDTO",
|
|
|
+ "com.etotem.cfc.dto.TongueEmotionCaptureDTO",
|
|
|
+ "com.etotem.cfc.entity.EmotionCheckin",
|
|
|
+ "com.etotem.cfc.entity.TongueRecord"
|
|
|
+ };
|
|
|
+ boolean carrierFound = false;
|
|
|
+ for (String carrier : carriers) {
|
|
|
+ if (hasAnyField(carrier, ASSESSMENT_LINK_KEYS)) {
|
|
|
+ carrierFound = true;
|
|
|
+ break;
|
|
|
+ }
|
|
|
+ }
|
|
|
+ assertTrue(carrierFound,
|
|
|
+ "[tongue.emotion.capture] 采集载体(EmotionCheckinDTO / EmotionCheckin / TongueRecord)"
|
|
|
+ + "均无测评关联字段(assessmentId 等),无法实现 SC-P-70「关联测评」;实现未落地。");
|
|
|
+ }
|
|
|
+
|
|
|
+ // ==================== 异常/边界流:非照片、模糊、低置信度 ====================
|
|
|
+
|
|
|
+ @Test
|
|
|
+ @DisplayName("异常流-1:非照片文件应拒绝并提示『请上传清晰舌苔照』,且不调用识别服务")
|
|
|
+ void 异常流_非照片应拒绝() throws Exception {
|
|
|
+ MultipartFile textFile = photo("text/plain", "notes.txt");
|
|
|
+
|
|
|
+ Result<Map<String, Object>> result = controller.analyze(USER_ID, textFile);
|
|
|
+
|
|
|
+ assertTrue(result.getMessage() != null && result.getMessage().contains(MSG_NOT_CLEAR_PHOTO),
|
|
|
+ "[tongue.emotion.capture] 非照片(text/plain)应拒绝并提示『" + MSG_NOT_CLEAR_PHOTO
|
|
|
+ + "』,实际 message=" + result.getMessage() + ";实现未落地(TC-P-70-E)。");
|
|
|
+ verify(aiGateway, never()).analyzeEmotion(anyString());
|
|
|
+ }
|
|
|
+
|
|
|
+ @Test
|
|
|
+ @DisplayName("异常流-2:模糊照片应拒绝并提示『请上传清晰舌苔照』")
|
|
|
+ void 异常流_模糊照片应拒绝() throws Exception {
|
|
|
+ Map<String, Object> blurry = highConfidenceResult();
|
|
|
+ blurry.put("is_blur", Boolean.TRUE);
|
|
|
+ blurry.put("sharpness", 8.0);
|
|
|
+ when(aiGateway.analyzeEmotion(anyString())).thenReturn(blurry);
|
|
|
+
|
|
|
+ Result<Map<String, Object>> result = controller.analyze(USER_ID, photo("image/jpeg", "blurry.jpg"));
|
|
|
+
|
|
|
+ assertTrue(result.getMessage() != null && result.getMessage().contains(MSG_NOT_CLEAR_PHOTO),
|
|
|
+ "[tongue.emotion.capture] 模糊照片(is_blur=true / 低锐度)应拒绝并提示『"
|
|
|
+ + MSG_NOT_CLEAR_PHOTO + "』,实际 message=" + result.getMessage()
|
|
|
+ + ";实现未落地(TC-P-70-E)。");
|
|
|
+ }
|
|
|
+
|
|
|
+ @Test
|
|
|
+ @DisplayName("异常流-3:低置信度识别应提示『识别不清晰,建议重拍』")
|
|
|
+ void 异常流_低置信度应提示重拍() throws Exception {
|
|
|
+ Map<String, Object> lowConfidence = highConfidenceResult();
|
|
|
+ Map<String, Object> emotion = new LinkedHashMap<>();
|
|
|
+ emotion.put("emotion", "happy");
|
|
|
+ emotion.put("confidence", 0.12);
|
|
|
+ lowConfidence.put("emotions", Collections.singletonList(emotion));
|
|
|
+ when(aiGateway.analyzeEmotion(anyString())).thenReturn(lowConfidence);
|
|
|
+
|
|
|
+ Result<Map<String, Object>> result = controller.analyze(USER_ID, photo("image/png", "tongue.png"));
|
|
|
+
|
|
|
+ assertTrue(result.getMessage() != null && result.getMessage().contains(MSG_LOW_CONFIDENCE),
|
|
|
+ "[tongue.emotion.capture] 低置信度(0.12)应拒绝并提示『" + MSG_LOW_CONFIDENCE
|
|
|
+ + "』,实际 message=" + result.getMessage() + ";实现未落地(TC-P-70-E)。");
|
|
|
+ }
|
|
|
+
|
|
|
+ // ==================== 隐私流:隐私标注不外露 ====================
|
|
|
+
|
|
|
+ @Test
|
|
|
+ @DisplayName("隐私流-1:识别结果不得回传原始响应/隐私标注")
|
|
|
+ void 隐私流_识别结果不得外露原始响应() throws Exception {
|
|
|
+ Map<String, Object> withPrivacy = highConfidenceResult();
|
|
|
+ withPrivacy.put("rawResponse", "{\"face_annotation\":{\"name\":\"张三\",\"id_card\":\"11010119900101****\"}}");
|
|
|
+ withPrivacy.put("privacy_annotation", "人脸标注-姓名=张三");
|
|
|
+ when(aiGateway.analyzeEmotion(anyString())).thenReturn(withPrivacy);
|
|
|
+
|
|
|
+ Result<Map<String, Object>> result = controller.analyze(USER_ID, photo("image/jpeg", "tongue.jpg"));
|
|
|
+
|
|
|
+ assertEquals(200, result.getCode(), "[tongue.emotion.capture] 正常识别应成功(前置条件)。");
|
|
|
+ Map<String, Object> data = result.getData();
|
|
|
+ assertNotNull(data);
|
|
|
+ String serialized = String.valueOf(data);
|
|
|
+ for (String forbidden : new String[]{"rawResponse", "privacy_annotation", "张三", "id_card"}) {
|
|
|
+ assertFalse(serialized.contains(forbidden),
|
|
|
+ "[tongue.emotion.capture] 隐私标注不外露(TC-P-70-E):响应不应包含 " + forbidden
|
|
|
+ + ",实际响应=" + serialized + ";实现未落地。");
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ @Test
|
|
|
+ @DisplayName("隐私流-2:识别结果 DTO 不应保留调试用原始响应字段")
|
|
|
+ void 隐私流_结果DTO不应保留rawResponse字段() {
|
|
|
+ assertFalse(hasField("com.etotem.cfc.dto.EmotionRecognitionResult",
|
|
|
+ "rawResponse", "raw_response", "rawResponseJson"),
|
|
|
+ "[tongue.emotion.capture] EmotionRecognitionResult.rawResponse(调试用原始响应)"
|
|
|
+ + "属于隐私标注外露风险,应按 SC-P-70「隐私标注不外露」移除;实现未落地。");
|
|
|
+ }
|
|
|
+
|
|
|
+ // ==================== 权限流:身份来源 ====================
|
|
|
+
|
|
|
+ @Test
|
|
|
+ @DisplayName("权限流:两个识别端点均应从 JWT 注入 userId,而非信任请求体传参")
|
|
|
+ void 权限流_识别端点应以JWT身份为准() {
|
|
|
+ for (String methodName : new String[]{"analyze", "analyzeByUrl"}) {
|
|
|
+ Method target = null;
|
|
|
+ for (Method m : EmotionRecognitionController.class.getDeclaredMethods()) {
|
|
|
+ if (m.getName().equals(methodName)) {
|
|
|
+ target = m;
|
|
|
+ break;
|
|
|
+ }
|
|
|
+ }
|
|
|
+ if (target == null) {
|
|
|
+ fail("[tongue.emotion.capture] 识别端点 " + methodName + " 不存在(§4.37)。");
|
|
|
+ }
|
|
|
+ boolean hasJwtUserId = false;
|
|
|
+ for (java.lang.annotation.Annotation[] annotations : target.getParameterAnnotations()) {
|
|
|
+ for (java.lang.annotation.Annotation annotation : annotations) {
|
|
|
+ if (annotation instanceof RequestAttribute
|
|
|
+ && "userId".equals(((RequestAttribute) annotation).value())) {
|
|
|
+ hasJwtUserId = true;
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+ assertTrue(hasJwtUserId,
|
|
|
+ "[tongue.emotion.capture] " + methodName
|
|
|
+ + " 应通过 @RequestAttribute(\"userId\") 取 JWT 身份,避免越权传参(TC-P-70-P)。");
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ // ==================== 辅助 ====================
|
|
|
+
|
|
|
+ private MultipartFile photo(String contentType, String filename) throws Exception {
|
|
|
+ MultipartFile file = mock(MultipartFile.class);
|
|
|
+ when(file.isEmpty()).thenReturn(false);
|
|
|
+ when(file.getSize()).thenReturn(2048L);
|
|
|
+ when(file.getContentType()).thenReturn(contentType);
|
|
|
+ when(file.getOriginalFilename()).thenReturn(filename);
|
|
|
+ when(file.getBytes()).thenReturn(Base64.getDecoder().decode("aGVsbG8tdG9uZ3Vl"));
|
|
|
+ return file;
|
|
|
+ }
|
|
|
+
|
|
|
+ private Map<String, Object> highConfidenceResult() {
|
|
|
+ Map<String, Object> result = new LinkedHashMap<>();
|
|
|
+ result.put("dominant_emotion", "happy");
|
|
|
+ result.put("dominant_label_zh", "开心");
|
|
|
+ Map<String, Object> emotion = new LinkedHashMap<>();
|
|
|
+ emotion.put("emotion", "happy");
|
|
|
+ emotion.put("confidence", 0.85);
|
|
|
+ result.put("emotions", new ArrayList<>(Collections.singletonList(emotion)));
|
|
|
+ result.put("all_emotions", Collections.singletonMap("happy", 0.85));
|
|
|
+ return result;
|
|
|
+ }
|
|
|
+
|
|
|
+ private boolean hasAnyKey(Map<String, Object> map, String... keys) {
|
|
|
+ if (map == null) {
|
|
|
+ return false;
|
|
|
+ }
|
|
|
+ for (String key : keys) {
|
|
|
+ if (map.containsKey(key)) {
|
|
|
+ return true;
|
|
|
+ }
|
|
|
+ }
|
|
|
+ return false;
|
|
|
+ }
|
|
|
+
|
|
|
+ private boolean hasAnyField(String className, String... names) {
|
|
|
+ Class<?> clazz = loadClass(className);
|
|
|
+ if (clazz == null) {
|
|
|
+ return false;
|
|
|
+ }
|
|
|
+ for (String name : names) {
|
|
|
+ for (Field field : clazz.getDeclaredFields()) {
|
|
|
+ if (field.getName().equals(name)) {
|
|
|
+ return true;
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+ return false;
|
|
|
+ }
|
|
|
+
|
|
|
+ private boolean hasField(String className, String... names) {
|
|
|
+ return hasAnyField(className, names);
|
|
|
+ }
|
|
|
+
|
|
|
+ private Class<?> loadClass(String name) {
|
|
|
+ try {
|
|
|
+ return Class.forName(name, false, Thread.currentThread().getContextClassLoader());
|
|
|
+ } catch (ClassNotFoundException e) {
|
|
|
+ return null;
|
|
|
+ }
|
|
|
+ }
|
|
|
+}
|