|
|
@@ -0,0 +1,316 @@
|
|
|
+package com.etotem.cfc.unit;
|
|
|
+
|
|
|
+import com.etotem.cfc.mapper.DietRecommendationMapper;
|
|
|
+import com.etotem.cfc.mapper.FamilyMemberMapper;
|
|
|
+import com.etotem.cfc.mapper.MealConfigMapper;
|
|
|
+import com.etotem.cfc.service.AiGateway;
|
|
|
+import com.etotem.cfc.service.BeijingNutritionService;
|
|
|
+import com.etotem.cfc.service.DietRecommendationService;
|
|
|
+import com.etotem.cfc.service.PiisService;
|
|
|
+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.mockito.InjectMocks;
|
|
|
+import org.mockito.Mock;
|
|
|
+import org.mockito.MockitoAnnotations;
|
|
|
+import org.springframework.http.HttpEntity;
|
|
|
+import org.springframework.http.ResponseEntity;
|
|
|
+import org.springframework.web.client.RestTemplate;
|
|
|
+
|
|
|
+import java.io.InputStream;
|
|
|
+import java.lang.reflect.Field;
|
|
|
+import java.nio.charset.StandardCharsets;
|
|
|
+import java.util.HashMap;
|
|
|
+import java.util.Map;
|
|
|
+import java.util.Scanner;
|
|
|
+
|
|
|
+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.any;
|
|
|
+import static org.mockito.ArgumentMatchers.anyString;
|
|
|
+import static org.mockito.ArgumentMatchers.eq;
|
|
|
+import static org.mockito.Mockito.when;
|
|
|
+
|
|
|
+/**
|
|
|
+ * 契约级单测:食谱生成集成(能力键 {@code diet.menu.pairingConstraint},对应 CR-07)。
|
|
|
+ *
|
|
|
+ * <p>契约来源:{@code docs/需求分析/2026-11-22-食材推荐加权规则引擎需求变更.md} §4.7 CR-07
|
|
|
+ * + 第六节能力键拆分(第 7 键)。设计要点:</p>
|
|
|
+ * <ol>
|
|
|
+ * <li><b>配伍避让硬闸门</b>:{@code DietRecommendationService.normalizeMenu()} 增加检查——若菜单同时含
|
|
|
+ * A+B 且 {@code relation_type ∈ {xiangke, antagonism}} 且 {@code intensity ≥ 3} → 用 C 替换 B
|
|
|
+ * (同品类替代),替换失败则提示「已避让忌配伍组合」。</li>
|
|
|
+ * <li><b>加工建议</b>:{@code dish.type} 推断加工方式 → 查 {@code food_processing_effect} → 在返回体加
|
|
|
+ * {@code processingWarning}(如「油炸降低维生素 C 50%,建议改蒸煮」)。</li>
|
|
|
+ * <li><b>营养目标组合优化</b>:按家庭营养目标对菜品做组合优化,11-10 菜数硬保证(D(N)+1 汤)不破坏。</li>
|
|
|
+ * <li><b>AI prompt 注入</b>:{@code constraints_text} 追加「忌配伍:菠菜豆腐、柿子螃蟹等;
|
|
|
+ * 加工偏好:蒸煮优先」,Java 硬保证兜底。</li>
|
|
|
+ * </ol>
|
|
|
+ *
|
|
|
+ * <p><b>实现现状</b>:本分支 src/main 无 {@code food_pairing_matrix} / {@code food_processing_effect} 表,
|
|
|
+ * {@code normalizeMenu} 无配伍避让、返回体无 {@code processingWarning},{@code AiGateway.generateMenu}
|
|
|
+ * 请求体无 {@code constraints_text}。故本测试为 TDD-RED:能编译、能运行、断言失败(红)。</p>
|
|
|
+ *
|
|
|
+ * <p><b>GREEN 升级指引</b>:实现者补齐上述四项后,本测试自动转绿。全程仅用 Mockito / 反射 /
|
|
|
+ * classpath 资源读取,无 Spring 上下文、无 DB、无真实外部服务。</p>
|
|
|
+ */
|
|
|
+class DietMenuPairingConstraintContractTest {
|
|
|
+
|
|
|
+ private static final Long FAMILY_ID = 100L;
|
|
|
+
|
|
|
+ @Mock
|
|
|
+ private DietRecommendationMapper dietRecommendationMapper;
|
|
|
+ @Mock
|
|
|
+ private BeijingNutritionService beijingNutritionService;
|
|
|
+ @Mock
|
|
|
+ private AiGateway aiGateway;
|
|
|
+ @Mock
|
|
|
+ private MealConfigMapper mealConfigMapper;
|
|
|
+ @Mock
|
|
|
+ private FamilyMemberMapper familyMemberMapper;
|
|
|
+
|
|
|
+ @InjectMocks
|
|
|
+ private DietRecommendationService service;
|
|
|
+
|
|
|
+ @BeforeEach
|
|
|
+ void setUp() {
|
|
|
+ MockitoAnnotations.openMocks(this);
|
|
|
+ }
|
|
|
+
|
|
|
+ // ==================== CR-07-1:配伍避让硬闸门 ====================
|
|
|
+
|
|
|
+ @Test
|
|
|
+ @DisplayName("CR-07-1:菜单含忌配伍组合(菠菜+豆腐, antagonism/intensity>=3)应硬避让")
|
|
|
+ void 忌配伍组合应被替换或提示已避让() {
|
|
|
+ // 午餐同时出现菠菜与豆腐(草酸×钙拮抗,语料见 §4.3 / §4.7)
|
|
|
+ String lunch = "{\"name\":\"菠菜炒蛋\",\"type\":\"dish\",\"cooking_method\":\"stir_fried\","
|
|
|
+ + "\"nutrition\":{\"calories\":120},\"ingredients\":[{\"name\":\"菠菜\",\"grams\":120}]},"
|
|
|
+ + "{\"name\":\"麻婆豆腐\",\"type\":\"dish\",\"cooking_method\":\"stir_fried\","
|
|
|
+ + "\"nutrition\":{\"calories\":180},\"ingredients\":[{\"name\":\"豆腐\",\"grams\":150}]},"
|
|
|
+ + "{\"name\":\"紫菜汤\",\"type\":\"soup\",\"cooking_method\":\"boiled\","
|
|
|
+ + "\"nutrition\":{\"calories\":30},\"ingredients\":[]}";
|
|
|
+ String dinner = "{\"name\":\"清蒸鲈鱼\",\"type\":\"dish\",\"cooking_method\":\"steamed\","
|
|
|
+ + "\"nutrition\":{\"calories\":200},\"ingredients\":[{\"name\":\"鲈鱼\",\"grams\":150}]},"
|
|
|
+ + "{\"name\":\"蒜蓉西兰花\",\"type\":\"dish\",\"cooking_method\":\"steamed\","
|
|
|
+ + "\"nutrition\":{\"calories\":80},\"ingredients\":[{\"name\":\"西兰花\",\"grams\":150}]},"
|
|
|
+ + "{\"name\":\"冬瓜汤\",\"type\":\"soup\",\"cooking_method\":\"boiled\","
|
|
|
+ + "\"nutrition\":{\"calories\":20},\"ingredients\":[]}";
|
|
|
+ stubMenu(menuJson(lunch, dinner));
|
|
|
+
|
|
|
+ Map<String, Object> result = service.generateRecommendation(FAMILY_ID, request(null));
|
|
|
+
|
|
|
+ String menuText = String.valueOf(result.get("menu"));
|
|
|
+ String message = String.valueOf(result.get("message"));
|
|
|
+ boolean comboRemoved = !menuText.contains("菠菜") || !menuText.contains("豆腐");
|
|
|
+ boolean fallbackWarned = message.contains("已避让忌配伍组合");
|
|
|
+ assertTrue(comboRemoved || fallbackWarned,
|
|
|
+ "[diet.menu.pairingConstraint] 配伍避让硬闸门未实现:菜单仍同时含菠菜+豆腐且无"
|
|
|
+ + "「已避让忌配伍组合」提示。契约要求 relation_type∈{xiangke,antagonism} 且"
|
|
|
+ + " intensity≥3 时用同品类 C 替换 B,替换失败给出避让提示(§4.7-1)。");
|
|
|
+ }
|
|
|
+
|
|
|
+ // ==================== CR-07-2:加工方式建议 ====================
|
|
|
+
|
|
|
+ @Test
|
|
|
+ @DisplayName("CR-07-2:油炸菜品应在返回体带 processingWarning")
|
|
|
+ void 油炸菜品应返回加工建议() {
|
|
|
+ String lunch = "{\"name\":\"炸鸡块\",\"type\":\"dish\",\"cooking_method\":\"deep_fried\","
|
|
|
+ + "\"nutrition\":{\"calories\":420,\"vitamin_c\":0},"
|
|
|
+ + "\"ingredients\":[{\"name\":\"鸡胸肉\",\"grams\":150}]},"
|
|
|
+ + "{\"name\":\"凉拌黄瓜\",\"type\":\"dish\",\"cooking_method\":\"raw\","
|
|
|
+ + "\"nutrition\":{\"calories\":40},\"ingredients\":[{\"name\":\"黄瓜\",\"grams\":100}]},"
|
|
|
+ + "{\"name\":\"海带汤\",\"type\":\"soup\",\"cooking_method\":\"boiled\","
|
|
|
+ + "\"nutrition\":{\"calories\":20},\"ingredients\":[]}";
|
|
|
+ String dinner = "{\"name\":\"清蒸南瓜\",\"type\":\"dish\",\"cooking_method\":\"steamed\","
|
|
|
+ + "\"nutrition\":{\"calories\":90},\"ingredients\":[{\"name\":\"南瓜\",\"grams\":150}]},"
|
|
|
+ + "{\"name\":\"白灼虾\",\"type\":\"dish\",\"cooking_method\":\"boiled\","
|
|
|
+ + "\"nutrition\":{\"calories\":120},\"ingredients\":[{\"name\":\"虾\",\"grams\":120}]},"
|
|
|
+ + "{\"name\":\"萝卜汤\",\"type\":\"soup\",\"cooking_method\":\"boiled\","
|
|
|
+ + "\"nutrition\":{\"calories\":25},\"ingredients\":[]}";
|
|
|
+ stubMenu(menuJson(lunch, dinner));
|
|
|
+
|
|
|
+ Map<String, Object> result = service.generateRecommendation(FAMILY_ID, request(null));
|
|
|
+
|
|
|
+ Object warning = result.get("processingWarning");
|
|
|
+ assertNotNull(warning,
|
|
|
+ "[diet.menu.pairingConstraint] 返回体缺少 processingWarning:契约要求由 dish 的加工方式"
|
|
|
+ + "(此处 deep_fried)查 food_processing_effect 并在返回体给出加工建议"
|
|
|
+ + "(如「油炸降低维生素 C 50%,建议改蒸煮」,§4.7-2)。");
|
|
|
+ assertFalse(String.valueOf(warning).trim().isEmpty(),
|
|
|
+ "[diet.menu.pairingConstraint] processingWarning 不应为空字符串(§4.7-2)。");
|
|
|
+ }
|
|
|
+
|
|
|
+ // ==================== CR-07-3:营养目标组合优化(菜数硬保证不破坏) ====================
|
|
|
+
|
|
|
+ @Test
|
|
|
+ @DisplayName("CR-07-3:携带营养目标时组合优化不得破坏 11-10 菜数硬保证")
|
|
|
+ void 营养目标组合优化不得破坏菜数硬保证() {
|
|
|
+ String dish = "{\"name\":\"高热量菜\",\"type\":\"dish\",\"cooking_method\":\"deep_fried\","
|
|
|
+ + "\"nutrition\":{\"calories\":900},\"ingredients\":[]}";
|
|
|
+ String soup = "{\"name\":\"汤\",\"type\":\"soup\",\"cooking_method\":\"boiled\","
|
|
|
+ + "\"nutrition\":{\"calories\":50},\"ingredients\":[]}";
|
|
|
+ stubMenu(menuJson(dish, soup, dish, soup));
|
|
|
+
|
|
|
+ Map<String, Object> goals = new HashMap<>();
|
|
|
+ goals.put("calories", 800);
|
|
|
+ goals.put("protein", 40);
|
|
|
+ goals.put("carbs", 60);
|
|
|
+ goals.put("fat", 20);
|
|
|
+ Map<String, Object> result = service.generateRecommendation(FAMILY_ID, request(goals));
|
|
|
+
|
|
|
+ // 组合优化应按家庭营养目标收敛热量,且 11-10 的 D(N)+1 汤硬保证必须保持(N=1 → 4 菜 + 1 汤)
|
|
|
+ assertEquals(4, result.get("dishCount"),
|
|
|
+ "[diet.menu.pairingConstraint] 菜数硬保证被组合优化破坏:N=1 应为 4 道菜(§4.7-3 / 11-10 基线)。");
|
|
|
+ int calories = readCalories(result.get("nutritionSummary"));
|
|
|
+ assertTrue(calories <= 800,
|
|
|
+ "[diet.menu.pairingConstraint] 未实现按家庭营养目标的组合优化:菜单热量 " + calories
|
|
|
+ + " kcal 超过目标 800 kcal,契约要求组合优化收敛到目标内且菜数不破坏(§4.7-3)。");
|
|
|
+ }
|
|
|
+
|
|
|
+ // ==================== CR-07-4:AI prompt 约束注入 ====================
|
|
|
+
|
|
|
+ @Test
|
|
|
+ @DisplayName("CR-07-4:generateMenu 请求体应注入 constraints_text(忌配伍 + 加工偏好)")
|
|
|
+ void 菜单生成请求应注入配伍与加工约束() throws Exception {
|
|
|
+ AiGateway gateway = new AiGateway();
|
|
|
+ setField(gateway, "enabled", true);
|
|
|
+ setField(gateway, "baseUrl", "http://test-ai");
|
|
|
+ setField(gateway, "resetTimeoutMs", 30000);
|
|
|
+ setField(gateway, "failureThreshold", 3);
|
|
|
+
|
|
|
+ PiisService piisService = org.mockito.Mockito.mock(PiisService.class);
|
|
|
+ when(piisService.sanitizeText(anyString())).thenAnswer(inv -> (String) inv.getArguments()[0]);
|
|
|
+ setField(gateway, "piisService", piisService);
|
|
|
+
|
|
|
+ final String[] bodyHolder = new String[1];
|
|
|
+ RestTemplate restTemplate = org.mockito.Mockito.mock(RestTemplate.class);
|
|
|
+ when(restTemplate.postForEntity(anyString(), any(HttpEntity.class), eq(String.class)))
|
|
|
+ .thenAnswer(inv -> {
|
|
|
+ HttpEntity<?> entity = (HttpEntity<?>) inv.getArguments()[1];
|
|
|
+ Object body = entity == null ? null : entity.getBody();
|
|
|
+ bodyHolder[0] = body == null ? "" : body.toString();
|
|
|
+ return ResponseEntity.ok("{\"menu_json\":\"{}\"}");
|
|
|
+ });
|
|
|
+ setField(gateway, "restTemplate", restTemplate);
|
|
|
+
|
|
|
+ gateway.generateMenu("[]", "[]", "2026-11-23", 4);
|
|
|
+
|
|
|
+ String body = bodyHolder[0];
|
|
|
+ assertNotNull(body,
|
|
|
+ "[diet.menu.pairingConstraint] AiGateway.generateMenu 未发出请求,无法验证约束注入(§4.7-4)。");
|
|
|
+ assertTrue(body.contains("constraints_text"),
|
|
|
+ "[diet.menu.pairingConstraint] 请求体缺少 constraints_text:契约要求把忌配伍/加工偏好"
|
|
|
+ + "注入 LangGraph prompt(§4.7-4)。实际请求体=" + body);
|
|
|
+ assertTrue(body.contains("忌配伍"),
|
|
|
+ "[diet.menu.pairingConstraint] constraints_text 应含「忌配伍」(如菠菜豆腐、柿子螃蟹,§4.7-4)。实际=" + body);
|
|
|
+ assertTrue(body.contains("蒸煮"),
|
|
|
+ "[diet.menu.pairingConstraint] constraints_text 应含加工偏好「蒸煮优先」(§4.7-4)。实际=" + body);
|
|
|
+ }
|
|
|
+
|
|
|
+ // ==================== 前置数据源:配伍矩阵 / 加工效应表应落地 ====================
|
|
|
+
|
|
|
+ @Test
|
|
|
+ @DisplayName("前置数据源:schema.sql 应含 food_pairing_matrix 与 food_processing_effect")
|
|
|
+ void 配伍与加工数据表应落地Schema() {
|
|
|
+ String schema = readSchemaSql();
|
|
|
+ assertTrue(schema.contains("food_pairing_matrix"),
|
|
|
+ "[diet.menu.pairingConstraint] schema.sql 缺少 food_pairing_matrix:硬闸门依赖配伍矩阵"
|
|
|
+ + "(relation_type/intensity,§4.3/§4.7-1)。");
|
|
|
+ assertTrue(schema.contains("food_processing_effect"),
|
|
|
+ "[diet.menu.pairingConstraint] schema.sql 缺少 food_processing_effect:加工建议依赖该表"
|
|
|
+ + "(§4.4/§4.7-2)。");
|
|
|
+ }
|
|
|
+
|
|
|
+ // ==================== 权限流(不适用):后端内部集成,无用户权限维度 ====================
|
|
|
+
|
|
|
+ @Test
|
|
|
+ @DisplayName("权限流:本能力为食谱生成内部集成,无独立用户权限维度")
|
|
|
+ void permissionFlow_notApplicable() {
|
|
|
+ assertTrue(true, "权限流不适用:diet.menu.pairingConstraint 为食谱生成内部集成链路,无独立权限校验维度。");
|
|
|
+ }
|
|
|
+
|
|
|
+ // ------------------------------------------------------------------ 辅助
|
|
|
+
|
|
|
+ private void stubMenu(String menuJson) {
|
|
|
+ when(aiGateway.generateMenu(anyString(), anyString(), anyString(), any())).thenReturn(menuJson);
|
|
|
+ }
|
|
|
+
|
|
|
+ private Map<String, Object> request(Map<String, Object> nutritionGoals) {
|
|
|
+ Map<String, Object> request = new HashMap<>();
|
|
|
+ request.put("date", "2026-11-23");
|
|
|
+ request.put("meal_type", "all");
|
|
|
+ request.put("selected_foods", "[\"菠菜\",\"豆腐\"]");
|
|
|
+ if (nutritionGoals != null) {
|
|
|
+ request.put("nutrition_goals", nutritionGoals);
|
|
|
+ }
|
|
|
+ return request;
|
|
|
+ }
|
|
|
+
|
|
|
+ private static String menuJson(String lunchDishes, String dinnerDishes) {
|
|
|
+ return menuJson(lunchDishes, dinnerDishes, null, null);
|
|
|
+ }
|
|
|
+
|
|
|
+ private static String menuJson(String dish1, String dish2, String dish3, String dish4) {
|
|
|
+ String lunch = dish3 == null ? dish1 + "," + dish2 : dish1 + "," + dish2;
|
|
|
+ String dinner = dish4 == null ? dish1 + "," + dish2 : dish3 + "," + dish4;
|
|
|
+ return "{\"meals\":["
|
|
|
+ + "{\"type\":\"lunch\",\"name\":\"午餐\",\"dishes\":[" + lunch + "]},"
|
|
|
+ + "{\"type\":\"dinner\",\"name\":\"晚餐\",\"dishes\":[" + dinner + "]}"
|
|
|
+ + "]}";
|
|
|
+ }
|
|
|
+
|
|
|
+ /** nutritionSummary 在返回体中是 JSON 字符串(落库形态),兼容 Map 形态以便后续实现直接放对象。 */
|
|
|
+ private static int readCalories(Object summary) {
|
|
|
+ try {
|
|
|
+ if (summary instanceof Map) {
|
|
|
+ Object v = ((Map<?, ?>) summary).get("calories");
|
|
|
+ return v instanceof Number ? ((Number) v).intValue() : 0;
|
|
|
+ }
|
|
|
+ JsonNode node = new ObjectMapper().readTree(String.valueOf(summary));
|
|
|
+ return node.path("calories").asInt();
|
|
|
+ } catch (Exception e) {
|
|
|
+ return 0;
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ private static void setField(Object target, String name, Object value) throws Exception {
|
|
|
+ Field field = findField(target.getClass(), name);
|
|
|
+ if (field == null) {
|
|
|
+ fail("[diet.menu.pairingConstraint] 反射失败:字段 " + name + " 不存在于 "
|
|
|
+ + target.getClass().getName());
|
|
|
+ }
|
|
|
+ field.setAccessible(true);
|
|
|
+ field.set(target, value);
|
|
|
+ }
|
|
|
+
|
|
|
+ private static Field findField(Class<?> clazz, String name) {
|
|
|
+ Class<?> c = clazz;
|
|
|
+ while (c != null) {
|
|
|
+ try {
|
|
|
+ return c.getDeclaredField(name);
|
|
|
+ } catch (NoSuchFieldException e) {
|
|
|
+ c = c.getSuperclass();
|
|
|
+ }
|
|
|
+ }
|
|
|
+ return null;
|
|
|
+ }
|
|
|
+
|
|
|
+ private String readSchemaSql() {
|
|
|
+ try (InputStream is = getClass().getClassLoader().getResourceAsStream("schema.sql")) {
|
|
|
+ if (is == null) {
|
|
|
+ return "";
|
|
|
+ }
|
|
|
+ try (Scanner scanner = new Scanner(is, StandardCharsets.UTF_8.name())) {
|
|
|
+ scanner.useDelimiter("\\A");
|
|
|
+ return scanner.hasNext() ? scanner.next() : "";
|
|
|
+ }
|
|
|
+ } catch (Exception e) {
|
|
|
+ return "";
|
|
|
+ }
|
|
|
+ }
|
|
|
+}
|