|
|
@@ -0,0 +1,405 @@
|
|
|
+package com.etotem.cfc.unit;
|
|
|
+
|
|
|
+import org.junit.jupiter.api.DisplayName;
|
|
|
+import org.junit.jupiter.api.Test;
|
|
|
+import org.mockito.Mockito;
|
|
|
+import org.mockito.stubbing.Answer;
|
|
|
+import org.springframework.web.bind.annotation.DeleteMapping;
|
|
|
+import org.springframework.web.bind.annotation.GetMapping;
|
|
|
+import org.springframework.web.bind.annotation.PostMapping;
|
|
|
+import org.springframework.web.bind.annotation.PutMapping;
|
|
|
+import org.springframework.web.bind.annotation.RequestBody;
|
|
|
+
|
|
|
+import java.lang.annotation.Annotation;
|
|
|
+import java.lang.reflect.Field;
|
|
|
+import java.lang.reflect.InvocationTargetException;
|
|
|
+import java.lang.reflect.Method;
|
|
|
+import java.lang.reflect.Modifier;
|
|
|
+import java.util.ArrayList;
|
|
|
+import java.util.Collection;
|
|
|
+import java.util.Collections;
|
|
|
+import java.util.HashMap;
|
|
|
+import java.util.List;
|
|
|
+import java.util.Map;
|
|
|
+
|
|
|
+import static org.junit.jupiter.api.Assertions.assertNotNull;
|
|
|
+import static org.junit.jupiter.api.Assertions.assertTrue;
|
|
|
+import static org.junit.jupiter.api.Assertions.fail;
|
|
|
+
|
|
|
+/**
|
|
|
+ * 契约级单测(TDD-RED):能力键 {@code global.search.query} 的
|
|
|
+ * <b>HTTP 方法约束 + 空结果边界</b>(任务号 S-cfc-299,业务域 L)。
|
|
|
+ *
|
|
|
+ * <p><b>契约溯源</b></p>
|
|
|
+ * <ul>
|
|
|
+ * <li>需求:{@code tests/user-scenarios/应用场景总览.md} SC-P-82
|
|
|
+ * 「全局搜索(报告/方案/任务/商品)」——搜 → 结果按类型分流;
|
|
|
+ * 边界:<b>越权结果过滤</b>、<b>空结果不报错</b>;模块:搜索。</li>
|
|
|
+ * <li>设计:{@code docs/superpowers/api/API_REFERENCE.md} §4.59.10 契约缺口——
|
|
|
+ * {@code POST /api/search/global} <b>不存在</b>(无 SearchController),
|
|
|
+ * SC-P-82 全局搜索<b>未实现</b>;现有食材搜索 {@code /api/diet/ingredients/search}
|
|
|
+ * 与文章列表 {@code /api/articles/list} 为分散的参考入口。</li>
|
|
|
+ * </ul>
|
|
|
+ *
|
|
|
+ * <p><b>本类补齐的契约维度</b>(同批已合入的
|
|
|
+ * {@code GlobalSearchQueryContractTest} / {@code GlobalSearchQueryScP82RestContractTest}
|
|
|
+ * 覆盖类/方法/路由存在性与四类桶结构,本类不重复):</p>
|
|
|
+ * <ol>
|
|
|
+ * <li><b>接口规范</b>:{@code /api/search/global} 只能是 {@code @PostMapping},
|
|
|
+ * 禁止 {@code GET/PUT/DELETE}(项目统一 POST 约定);</li>
|
|
|
+ * <li><b>请求体</b>:搜索条件(keyword,可空)经 {@code @RequestBody} 传入,
|
|
|
+ * 不把关键字塞进 URL;</li>
|
|
|
+ * <li><b>空结果不报错</b>(SC-P-82 边界,行为级):关键字为 null / 空串 / 空白 / 无匹配时,
|
|
|
+ * 聚合入口须正常返回且四类桶为空集合,<b>不得抛异常</b>。</li>
|
|
|
+ * </ol>
|
|
|
+ *
|
|
|
+ * <p><b>RED 预期</b>:{@code SearchController} / {@code GlobalSearchService} 当前均未落地
|
|
|
+ * (src/main 全库 0 引用),故三条用例均在探测处失败(红)。实现落地后自动转绿;
|
|
|
+ * 行为级用例以反射实例化服务并注入 Mockito mock 依赖(mock 默认返回空集合),
|
|
|
+ * 不需要 Spring / DB / 外部服务。</p>
|
|
|
+ */
|
|
|
+class GlobalSearchQueryEmptyResultContractTest {
|
|
|
+
|
|
|
+ /** 控制器包位置二选一(项目既有分组写法) */
|
|
|
+ private static final String[] CONTROLLER_CANDIDATES = {
|
|
|
+ "com.etotem.cfc.controller.search.SearchController",
|
|
|
+ "com.etotem.cfc.controller.SearchController"
|
|
|
+ };
|
|
|
+
|
|
|
+ /** 聚合搜索服务候选名(两份同批契约测试的命名) */
|
|
|
+ private static final String[] SERVICE_CANDIDATES = {
|
|
|
+ "com.etotem.cfc.service.GlobalSearchService",
|
|
|
+ "com.etotem.cfc.service.SearchService"
|
|
|
+ };
|
|
|
+
|
|
|
+ /** SC-P-82 类型分流四类桶(单复数均接受,避免实现命名细节影响契约) */
|
|
|
+ private static final String[][] TYPE_BUCKETS = {
|
|
|
+ {"reports", "report"},
|
|
|
+ {"plans", "plan"},
|
|
|
+ {"tasks", "task"},
|
|
|
+ {"products", "product"}
|
|
|
+ };
|
|
|
+
|
|
|
+ // ------------------------------------------------------------------
|
|
|
+ // 契约-1:/api/search/global 仅允许 POST(项目统一 POST 约定)
|
|
|
+ // ------------------------------------------------------------------
|
|
|
+
|
|
|
+ @Test
|
|
|
+ @DisplayName("契约-1:/api/search/global 只能 @PostMapping,禁止 GET/PUT/DELETE")
|
|
|
+ void globalSearchEndpoint_isPostOnly() {
|
|
|
+ Class<?> controller = loadFirst(CONTROLLER_CANDIDATES);
|
|
|
+ assertNotNull(controller,
|
|
|
+ "[global.search.query] SearchController 不存在:契约要求 POST /api/search/global"
|
|
|
+ + "(API §4.59.10 登记未实现端点),当前实现未落地。");
|
|
|
+
|
|
|
+ Method globalHandler = findGlobalHandler(controller);
|
|
|
+ assertNotNull(globalHandler,
|
|
|
+ "[global.search.query] SearchController 未提供 /global 处理器"
|
|
|
+ + "(类级 @RequestMapping(\"/api/search\") + 方法级 @PostMapping(\"/global\"))。");
|
|
|
+
|
|
|
+ assertTrue(globalHandler.isAnnotationPresent(PostMapping.class),
|
|
|
+ "[global.search.query] /api/search/global 必须使用 @PostMapping(项目统一 POST 约定),"
|
|
|
+ + "实际注解:" + annotationNames(globalHandler));
|
|
|
+
|
|
|
+ for (Method m : controller.getDeclaredMethods()) {
|
|
|
+ if (isSameGlobalPath(m) && (m.isAnnotationPresent(GetMapping.class)
|
|
|
+ || m.isAnnotationPresent(PutMapping.class)
|
|
|
+ || m.isAnnotationPresent(DeleteMapping.class))) {
|
|
|
+ fail("[global.search.query] /api/search/global 不得暴露 GET/PUT/DELETE(统一 POST 约定),"
|
|
|
+ + "违规方法:" + m.getName() + " " + annotationNames(m));
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ // ------------------------------------------------------------------
|
|
|
+ // 契约-2:搜索条件经 @RequestBody 传入(keyword 可空)
|
|
|
+ // ------------------------------------------------------------------
|
|
|
+
|
|
|
+ @Test
|
|
|
+ @DisplayName("契约-2:/global 应以 @RequestBody 接收搜索条件(keyword,可空)")
|
|
|
+ void globalSearchHandler_readsCriteriaFromRequestBody() {
|
|
|
+ Class<?> controller = loadFirst(CONTROLLER_CANDIDATES);
|
|
|
+ assertNotNull(controller,
|
|
|
+ "[global.search.query] SearchController 不存在:无法验证搜索条件经请求体传入。");
|
|
|
+
|
|
|
+ Method globalHandler = findGlobalHandler(controller);
|
|
|
+ assertNotNull(globalHandler,
|
|
|
+ "[global.search.query] SearchController 未提供 /global 处理器,无法验证请求体契约。");
|
|
|
+
|
|
|
+ Class<?>[] types = globalHandler.getParameterTypes();
|
|
|
+ Annotation[][] anns = globalHandler.getParameterAnnotations();
|
|
|
+ boolean hasBody = false;
|
|
|
+ for (int i = 0; i < types.length; i++) {
|
|
|
+ for (Annotation a : anns[i]) {
|
|
|
+ if (a instanceof RequestBody) {
|
|
|
+ hasBody = true;
|
|
|
+ break;
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+ assertTrue(hasBody,
|
|
|
+ "[global.search.query] /global 应通过 @RequestBody 接收搜索条件(Map 或请求 DTO 承载 keyword,"
|
|
|
+ + "可空;SC-P-82「搜 → 结果按类型分流」)。实际参数:" + java.util.Arrays.toString(types));
|
|
|
+ }
|
|
|
+
|
|
|
+ // ------------------------------------------------------------------
|
|
|
+ // 契约-3:空结果不报错(SC-P-82 边界,行为级)
|
|
|
+ // ------------------------------------------------------------------
|
|
|
+
|
|
|
+ @Test
|
|
|
+ @DisplayName("契约-3:空白关键字/无匹配 → 返回空四桶,不抛异常(空结果不报错)")
|
|
|
+ void blankKeyword_returnsEmptyBuckets_withoutError() {
|
|
|
+ Class<?> service = loadFirst(SERVICE_CANDIDATES);
|
|
|
+ assertNotNull(service,
|
|
|
+ "[global.search.query] 聚合搜索服务不存在:SC-P-82「空结果不报错」要求聚合入口在"
|
|
|
+ + "关键字为空/无匹配时返回空四桶而非抛异常(API §4.59.10 未实现)。");
|
|
|
+
|
|
|
+ Method entry = findSearchEntry(service);
|
|
|
+ assertNotNull(entry,
|
|
|
+ "[global.search.query] 聚合搜索服务缺少 globalSearch/search(String keyword, ...) 入口:"
|
|
|
+ + "空结果不报错(SC-P-82)无法承载。");
|
|
|
+
|
|
|
+ Object instance;
|
|
|
+ try {
|
|
|
+ instance = service.getDeclaredConstructor().newInstance();
|
|
|
+ } catch (Exception e) {
|
|
|
+ fail("[global.search.query] 聚合搜索服务应可用无参构造 + @Resource 字段注入实例化"
|
|
|
+ + "(项目约定),当前失败:" + e);
|
|
|
+ return;
|
|
|
+ }
|
|
|
+ injectMockDependencies(instance);
|
|
|
+
|
|
|
+ String[] blankKeywords = {null, "", " ", "绝对不存在的关键字_契约测试"};
|
|
|
+ for (String keyword : blankKeywords) {
|
|
|
+ Object result;
|
|
|
+ try {
|
|
|
+ result = entry.invoke(instance, buildArgs(entry, keyword));
|
|
|
+ } catch (InvocationTargetException e) {
|
|
|
+ fail("[global.search.query] 空结果不报错(SC-P-82):keyword=" + show(keyword)
|
|
|
+ + " 时聚合搜索抛出异常 " + e.getCause());
|
|
|
+ return;
|
|
|
+ } catch (Exception e) {
|
|
|
+ fail("[global.search.query] 聚合搜索入口调用失败:" + e);
|
|
|
+ return;
|
|
|
+ }
|
|
|
+
|
|
|
+ assertNotNull(result,
|
|
|
+ "[global.search.query] 空结果不报错(SC-P-82):keyword=" + show(keyword)
|
|
|
+ + " 时应返回空四桶(Result/Map/结果载体),不得返回 null。");
|
|
|
+
|
|
|
+ Map<String, Object> buckets = toBuckets(result);
|
|
|
+ assertNotNull(buckets,
|
|
|
+ "[global.search.query] 空结果不报错(SC-P-82):keyword=" + show(keyword)
|
|
|
+ + " 时应返回 Map 结果或含 reports/plans/tasks/products 的结果载体,"
|
|
|
+ + "实际返回 " + result.getClass().getName() + "。");
|
|
|
+
|
|
|
+ for (String[] aliases : TYPE_BUCKETS) {
|
|
|
+ String hit = null;
|
|
|
+ for (String alias : aliases) {
|
|
|
+ if (buckets.containsKey(alias)) {
|
|
|
+ hit = alias;
|
|
|
+ break;
|
|
|
+ }
|
|
|
+ }
|
|
|
+ assertNotNull(hit,
|
|
|
+ "[global.search.query] 空结果不报错(SC-P-82):结果缺少类型分流桶 "
|
|
|
+ + java.util.Arrays.toString(aliases) + "(结果按类型分流)。");
|
|
|
+ Object bucket = buckets.get(hit);
|
|
|
+ if (bucket == null) {
|
|
|
+ continue;
|
|
|
+ }
|
|
|
+ assertTrue(bucket instanceof Collection,
|
|
|
+ "[global.search.query] 类型分流桶 " + hit + " 应为集合,实际为 "
|
|
|
+ + bucket.getClass().getName() + "。");
|
|
|
+ assertTrue(((Collection<?>) bucket).isEmpty(),
|
|
|
+ "[global.search.query] 空结果不报错(SC-P-82):keyword=" + show(keyword)
|
|
|
+ + " 时桶 " + hit + " 应为空集合,实际有 " + ((Collection<?>) bucket).size() + " 条。");
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ // ------------------------------------------------------------------
|
|
|
+ // 反射辅助
|
|
|
+ // ------------------------------------------------------------------
|
|
|
+
|
|
|
+ private Class<?> loadFirst(String[] candidates) {
|
|
|
+ for (String name : candidates) {
|
|
|
+ try {
|
|
|
+ return Class.forName(name, false, Thread.currentThread().getContextClassLoader());
|
|
|
+ } catch (ClassNotFoundException ignored) {
|
|
|
+ // 继续尝试下一个候选
|
|
|
+ }
|
|
|
+ }
|
|
|
+ return null;
|
|
|
+ }
|
|
|
+
|
|
|
+ /** 定位 /global 处理器:方法级 @PostMapping("/global")(类级前缀由契约测试另行校验) */
|
|
|
+ private Method findGlobalHandler(Class<?> controller) {
|
|
|
+ for (Method m : controller.getDeclaredMethods()) {
|
|
|
+ if (isSameGlobalPath(m)) {
|
|
|
+ return m;
|
|
|
+ }
|
|
|
+ }
|
|
|
+ return null;
|
|
|
+ }
|
|
|
+
|
|
|
+ private boolean isSameGlobalPath(Method m) {
|
|
|
+ for (Annotation a : m.getAnnotations()) {
|
|
|
+ String[] paths = mappingPaths(a);
|
|
|
+ if (paths == null) {
|
|
|
+ continue;
|
|
|
+ }
|
|
|
+ for (String p : paths) {
|
|
|
+ if ("global".equals(p.trim()) || "/global".equals(p.trim())) {
|
|
|
+ return true;
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+ return false;
|
|
|
+ }
|
|
|
+
|
|
|
+ private String[] mappingPaths(Annotation a) {
|
|
|
+ try {
|
|
|
+ Method value = a.annotationType().getMethod("value");
|
|
|
+ Object v = value.invoke(a);
|
|
|
+ if (v instanceof String[] && ((String[]) v).length > 0) {
|
|
|
+ return (String[]) v;
|
|
|
+ }
|
|
|
+ Method path = a.annotationType().getMethod("path");
|
|
|
+ Object p = path.invoke(a);
|
|
|
+ if (p instanceof String[] && ((String[]) p).length > 0) {
|
|
|
+ return (String[]) p;
|
|
|
+ }
|
|
|
+ } catch (Exception ignored) {
|
|
|
+ // 非 Mapping 注解
|
|
|
+ }
|
|
|
+ return null;
|
|
|
+ }
|
|
|
+
|
|
|
+ private String annotationNames(Method m) {
|
|
|
+ List<String> names = new ArrayList<>();
|
|
|
+ for (Annotation a : m.getAnnotations()) {
|
|
|
+ names.add(a.annotationType().getSimpleName());
|
|
|
+ }
|
|
|
+ return names.toString();
|
|
|
+ }
|
|
|
+
|
|
|
+ /** 定位聚合搜索入口:globalSearch/search,首参为 String(keyword) */
|
|
|
+ private Method findSearchEntry(Class<?> service) {
|
|
|
+ for (Method m : service.getDeclaredMethods()) {
|
|
|
+ if (!m.getName().equalsIgnoreCase("globalSearch") && !m.getName().equalsIgnoreCase("search")) {
|
|
|
+ continue;
|
|
|
+ }
|
|
|
+ Class<?>[] pts = m.getParameterTypes();
|
|
|
+ if (pts.length >= 1 && String.class.isAssignableFrom(pts[0])) {
|
|
|
+ return m;
|
|
|
+ }
|
|
|
+ }
|
|
|
+ return null;
|
|
|
+ }
|
|
|
+
|
|
|
+ /** 按参数类型构造调用实参:String=keyword,Long/Integer=调用者上下文占位,Map=空请求体 */
|
|
|
+ private Object[] buildArgs(Method entry, String keyword) {
|
|
|
+ Class<?>[] pts = entry.getParameterTypes();
|
|
|
+ Object[] args = new Object[pts.length];
|
|
|
+ for (int i = 0; i < pts.length; i++) {
|
|
|
+ Class<?> t = pts[i];
|
|
|
+ if (t == String.class) {
|
|
|
+ args[i] = keyword;
|
|
|
+ } else if (t == Long.class || t == Long.TYPE) {
|
|
|
+ args[i] = 1001L;
|
|
|
+ } else if (t == Integer.class || t == Integer.TYPE) {
|
|
|
+ args[i] = 1;
|
|
|
+ } else if (Map.class.isAssignableFrom(t)) {
|
|
|
+ Map<String, Object> body = new HashMap<>();
|
|
|
+ body.put("keyword", keyword);
|
|
|
+ args[i] = body;
|
|
|
+ } else {
|
|
|
+ args[i] = null;
|
|
|
+ }
|
|
|
+ }
|
|
|
+ return args;
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 为服务实例的每个字段注入 Mockito mock。默认答案按返回类型给空集合,
|
|
|
+ * 模拟 MyBatis "无匹配返回空列表" 的真实语义(而非 null),避免把空结果误判为异常。
|
|
|
+ */
|
|
|
+ private void injectMockDependencies(Object instance) {
|
|
|
+ Answer<Object> emptyAnswer = invocation -> {
|
|
|
+ Class<?> rt = invocation.getMethod().getReturnType();
|
|
|
+ if (List.class.isAssignableFrom(rt) || Collection.class.isAssignableFrom(rt)) {
|
|
|
+ return Collections.emptyList();
|
|
|
+ }
|
|
|
+ if (Map.class.isAssignableFrom(rt)) {
|
|
|
+ return Collections.emptyMap();
|
|
|
+ }
|
|
|
+ if (rt == long.class) {
|
|
|
+ return 0L;
|
|
|
+ }
|
|
|
+ if (rt == int.class) {
|
|
|
+ return 0;
|
|
|
+ }
|
|
|
+ if (rt == boolean.class) {
|
|
|
+ return false;
|
|
|
+ }
|
|
|
+ return null;
|
|
|
+ };
|
|
|
+
|
|
|
+ for (Class<?> c = instance.getClass(); c != null && c != Object.class; c = c.getSuperclass()) {
|
|
|
+ for (Field f : c.getDeclaredFields()) {
|
|
|
+ if (Modifier.isStatic(f.getModifiers()) || Modifier.isFinal(f.getModifiers())) {
|
|
|
+ continue;
|
|
|
+ }
|
|
|
+ try {
|
|
|
+ Object mock = Mockito.mock(f.getType(), emptyAnswer);
|
|
|
+ f.setAccessible(true);
|
|
|
+ f.set(instance, mock);
|
|
|
+ } catch (Throwable ignored) {
|
|
|
+ // 无法 mock 的字段保持 null;空关键字路径应短路,不依赖这些字段
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ /** 结果归一化:Result.data → Map,Map 直用,结果载体(VO)按 getter 取桶 */
|
|
|
+ @SuppressWarnings("unchecked")
|
|
|
+ private Map<String, Object> toBuckets(Object result) {
|
|
|
+ if (result == null) {
|
|
|
+ return null;
|
|
|
+ }
|
|
|
+ if (result instanceof Map) {
|
|
|
+ return (Map<String, Object>) result;
|
|
|
+ }
|
|
|
+ for (Class<?> c = result.getClass(); c != null && c != Object.class; c = c.getSuperclass()) {
|
|
|
+ if ("com.etotem.cfc.common.Result".equals(c.getName())) {
|
|
|
+ try {
|
|
|
+ Method getData = c.getMethod("getData");
|
|
|
+ return toBuckets(getData.invoke(result));
|
|
|
+ } catch (Exception e) {
|
|
|
+ return null;
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+ Map<String, Object> byGetter = new HashMap<>();
|
|
|
+ for (String[] aliases : TYPE_BUCKETS) {
|
|
|
+ for (String alias : aliases) {
|
|
|
+ String getter = "get" + Character.toUpperCase(alias.charAt(0)) + alias.substring(1);
|
|
|
+ try {
|
|
|
+ Method m = result.getClass().getMethod(getter);
|
|
|
+ byGetter.put(alias, m.invoke(result));
|
|
|
+ break;
|
|
|
+ } catch (NoSuchMethodException ignored) {
|
|
|
+ // 尝试下一个别名
|
|
|
+ } catch (Exception ignored) {
|
|
|
+ break;
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+ return byGetter.isEmpty() ? null : byGetter;
|
|
|
+ }
|
|
|
+
|
|
|
+ private String show(String keyword) {
|
|
|
+ return keyword == null ? "null" : "\"" + keyword + "\"";
|
|
|
+ }
|
|
|
+}
|