package com.example.rzgb; import com.example.rzgb.common.*; import com.example.rzgb.task.*; import com.example.rzgb.files.BidFileService; import com.example.rzgb.opportunity.OpportunityQuery; import com.sun.net.httpserver.HttpServer; import java.net.*; import java.nio.charset.StandardCharsets; import java.math.BigDecimal; import java.time.*; import java.util.*; import java.util.concurrent.*; import org.junit.jupiter.api.*; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc; import org.springframework.test.context.*; import org.springframework.test.web.servlet.*; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.mock.web.MockMultipartFile; import static org.assertj.core.api.Assertions.*; import static org.awaitility.Awaitility.await; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.*; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; /** D4 可重复验收只使用本机 HTTP 样例,验证业务边界,不代表真实数据、模型或供应商账单验收。 */ @SpringBootTest @AutoConfigureMockMvc @ActiveProfiles("test") class Day4AcceptanceTests { @Autowired MockMvc mvc; @Autowired Json json; @Autowired JdbcTemplate jdbc; @Autowired TaskService tasks; @Autowired BidFileService files; private static HttpServer upstream; private static final List requests=new CopyOnWriteArrayList<>(); @DynamicPropertySource static void providers(DynamicPropertyRegistry registry)throws Exception { upstream=HttpServer.create(new InetSocketAddress("127.0.0.1",0),0); upstream.setExecutor(Executors.newCachedThreadPool()); upstream.createContext("/",exchange->{ String raw=new String(exchange.getRequestBody().readAllBytes(),StandardCharsets.UTF_8),path=exchange.getRequestURI().getPath(); requests.add(path+"|"+raw); var j=new Json(); var body=j.read(raw); Object response; int status=200; if(path.equals("/search_bids")) { List items=new ArrayList<>(); int page=body.path("page").asInt(); for(int i=(page-1)*20;ibase); registry.add("rz.deepseek-base-url",()->base); registry.add("rz.search-page-size",()->20); registry.add("rz.request-timeout-seconds",()->1); registry.add("spring.datasource.url",()->"jdbc:h2:mem:day4;MODE=MySQL;DATABASE_TO_LOWER=TRUE;DB_CLOSE_DELAY=-1"); } @AfterAll static void stop() {upstream.stop(0);} private String owner(){return jdbc.queryForObject("SELECT id FROM app_user WHERE username='admin'",String.class);} private Map settled(String id) { await().atMost(Duration.ofSeconds(10)).until(()->{String s=tasks.get(owner(),id).get("status").toString();return TaskService.terminal(s)||s.startsWith("WAITING_");}); return tasks.get(owner(),id); } private String batch() {return batch("第四天");} private String batch(String keyword) { var today=LocalDate.now(ZoneId.of("Asia/Shanghai")); var q=new OpportunityQuery(List.of(keyword),today.minusDays(89),today,List.of(4),OpportunityQuery.Preference.COMPREHENSIVE,List.of(),null,null,OpportunityQuery.Mode.SEARCH,OpportunityQuery.KeywordMode.ANY,List.of(),null,null); String id=tasks.create(owner(),UUID.randomUUID().toString(),new TaskRequest(TaskRequest.Operation.OPPORTUNITY_SEARCH,TaskRequest.Workflow.TENDER_SEARCH,"",false,3,BigDecimal.TEN,q)).get("id").toString(); assertThat(settled(id).get("status")).isEqualTo("SUCCEEDED"); return id; } private String conversation()throws Exception { return json.read(mvc.perform(post("/api/conversations").with(user("admin")).with(csrf()).contentType("application/json").content("{\"title\":\"\"}")).andExpect(status().isOk()).andReturn().getResponse().getContentAsString()).path("id").asText(); } private String question(String conv,String batch,String project,String question,String key)throws Exception { Map scope=new LinkedHashMap<>();scope.put("batchId",batch);scope.put("projectId",project); return json.read(mvc.perform(post("/api/conversations/"+conv+"/messages").with(user("admin")).with(csrf()).header("Idempotency-Key",key).contentType("application/json").content(json.write(Map.of("question",question,"scope",scope)))).andExpect(status().isOk()).andReturn().getResponse().getContentAsString()).path("id").asText(); } @Test void conversationsPersistAutoTitleRenameSearchAndDeleteWithoutDeletingReports()throws Exception { String conv=conversation(),batch=batch(),key=UUID.randomUUID().toString(); String task=question(conv,batch,null,"预算%_披露情况",key); assertThat(settled(task).get("status")).isEqualTo("SUCCEEDED"); assertThat(question(conv,batch,null,"预算%_披露情况",key)).isEqualTo(task); mvc.perform(get("/api/conversations/"+conv).with(user("admin"))).andExpect(jsonPath("$.title").value("预算%_披露情况")); mvc.perform(get("/api/conversations").param("q","%_").with(user("admin"))).andExpect(jsonPath("$[0].id").value(conv)); mvc.perform(patch("/api/conversations/"+conv).with(user("admin")).with(csrf()).contentType("application/json").content("{\"title\":\"人工标题\",\"version\":2}")).andExpect(status().isOk()); mvc.perform(patch("/api/conversations/"+conv).with(user("admin")).with(csrf()).contentType("application/json").content("{\"title\":\"冲突覆盖\",\"version\":2}")).andExpect(status().isConflict()); question(conv,batch,null,"后续提问",UUID.randomUUID().toString()); mvc.perform(get("/api/conversations/"+conv).with(user("admin"))).andExpect(jsonPath("$.title").value("人工标题")); mvc.perform(delete("/api/conversations/"+conv).with(user("admin")).with(csrf())).andExpect(status().isOk()); mvc.perform(get("/api/conversations/"+conv+"/messages").with(user("admin"))).andExpect(status().isNotFound()); assertThat(tasks.get(owner(),task).get("calls")).asList().hasSize(1); } @Test void wholeBatchCoversLastPageAndFrozenScopeSurvivesLaterChanges()throws Exception { String batch=batch(),conv=conversation(),task=question(conv,batch,null,"比较整批",UUID.randomUUID().toString()); var result=settled(task); assertThat(json.write(result.get("result"))).contains("第四天测试项目24","\"candidateCount\":25"); assertThat(result.get("usage").toString()).contains("external_calls=1","input_tokens=25"); String frozen=jdbc.queryForObject("SELECT qa_snapshot FROM agent_task WHERE id=?",String.class,task); assertThat(json.read(frozen).path("items")).hasSize(25); jdbc.update("UPDATE search_batch SET platform_total=999 WHERE id=?",batch); assertThat(jdbc.queryForObject("SELECT qa_snapshot FROM agent_task WHERE id=?",String.class,task)).isEqualTo(frozen); assertThat(requests.stream().filter(r->r.startsWith("/chat/completions|")&&r.contains("比较整批")).toList()).hasSize(1); assertThat(tasks.get(owner(),task).get("calls").toString()).doesNotContain("COMPANY","BID_RESEARCH"); } @Test void projectQuestionOnlyIncludesChosenSnapshotAndRejectsForeignScope()throws Exception { String batch=batch(),conv=conversation(),task=question(conv,batch,"zlbx-940002","单项目",UUID.randomUUID().toString()); settled(task); var frozen=json.read(jdbc.queryForObject("SELECT qa_snapshot FROM agent_task WHERE id=?",String.class,task)); assertThat(frozen.path("items")).hasSize(1);assertThat(frozen.path("items").path(0).path("facts").path("id").asText()).isEqualTo("zlbx-940002"); mvc.perform(post("/api/conversations/"+conv+"/messages").with(user("admin")).with(csrf()).header("Idempotency-Key",UUID.randomUUID().toString()).contentType("application/json").content("{\"question\":\"越权\",\"scope\":{\"batchId\":\"missing\"}}")).andExpect(status().isNotFound()); } @ParameterizedTest @ValueSource(strings={"坏引用","坏数字"}) void unverifiableAnswersAreHiddenWhileUsageIsKept(String input)throws Exception { String task=question(conversation(),batch(),null,input,UUID.randomUUID().toString());var result=settled(task); assertThat(result.get("status")).isEqualTo("PARTIAL"); assertThat(json.read(json.write(result.get("result"))).path("observations")).isEmpty(); assertThat(result.get("calls").toString()).contains("SUCCEEDED","d4-local-fixture"); } @ParameterizedTest @ValueSource(strings={"认证失败","限流","超时","网页不可达"}) void upstreamFailureNeverRetriesAndShowsActionableReason(String input)throws Exception { String task=question(conversation(),batch(),null,input,UUID.randomUUID().toString());var result=settled(task); assertThat(result.get("status")).isEqualTo("FAILED");assertThat(result.get("calls")).asList().hasSize(1); assertThat(result.get("question").toString()).isNotBlank(); assertThat(result.get("calls").toString()).contains(input.equals("超时")?"UNKNOWN":"FAILED"); } @Test void parallelDuplicateClickCreatesOneMessageAndOneModelCall()throws Exception { String conv=conversation(),batch=batch(),key=UUID.randomUUID().toString(); Set ids=new HashSet<>(); try(var pool=Executors.newFixedThreadPool(3)) { List> futures=new ArrayList<>();for(int i=0;i<3;i++) futures.add(pool.submit(()->question(conv,batch,null,"并发提问",key))); for(var future:futures) ids.add(future.get()); } assertThat(ids).hasSize(1); assertThat(settled(ids.iterator().next()).get("calls")).asList().hasSize(1); assertThat(jdbc.queryForObject("SELECT COUNT(*) FROM conversation_message WHERE conversation_id=?",Integer.class,conv)).isEqualTo(1); String other=conversation(); mvc.perform(post("/api/conversations/"+other+"/messages").with(user("admin")).with(csrf()).header("Idempotency-Key",key).contentType("application/json").content(json.write(Map.of("question","并发提问","scope",Map.of("batchId",batch))))).andExpect(status().isConflict()); } @Test void conversationOwnershipCsrfAndInvalidCursorAreEnforced()throws Exception { String id=conversation(),other=UUID.randomUUID().toString();jdbc.update("INSERT INTO app_user(id,username,password_hash) VALUES(?,'d4-other','test-only')",other); mvc.perform(get("/api/conversations")).andExpect(status().isUnauthorized()); mvc.perform(get("/api/conversations/"+id+"/messages").with(user("d4-other"))).andExpect(status().isNotFound()); mvc.perform(delete("/api/conversations/"+id).with(user("admin"))).andExpect(status().isForbidden()); mvc.perform(get("/api/agent/tasks/"+batch()+"/event-history").param("after","-1").with(user("admin"))).andExpect(status().isBadRequest()); } @Test void readingExpiredFileWipesFulltextBeforeSchedulerAndRepeatedDeleteAuditsOnce() { String id=files.upload(owner(),"BID_PROJECT",new MockMultipartFile("file","中文.md","text/plain","到期敏感全文".getBytes(StandardCharsets.UTF_8))).get("id").toString(); jdbc.update("UPDATE temporary_file SET expires_at=? WHERE id=?",java.sql.Timestamp.from(Instant.now().minusSeconds(1)),id); assertThat(files.get(owner(),id).get("segments")).asList().isEmpty(); files.expire();files.delete(owner(),id);files.delete(owner(),id); assertThat(jdbc.queryForObject("SELECT COUNT(*) FROM file_deletion_audit WHERE file_id=?",Integer.class,id)).isEqualTo(1); assertThat(jdbc.queryForObject("SELECT original_bytes FROM temporary_file WHERE id=?",byte[].class,id)).isNull(); } @Test void deletingOriginalKeepsOnlyBoundedReportExcerptsRatherThanAnotherFulltextCopy() { String text="必要摘录".repeat(1000)+"不应长期留存的末尾全文"; String file=files.upload(owner(),"BID_PROJECT",new MockMultipartFile("file","excerpt.txt","text/plain",text.getBytes(StandardCharsets.UTF_8))).get("id").toString(); String task=batch(); files.record(owner(),file,task); files.delete(owner(),file); var snapshots=jdbc.queryForList("SELECT source_snapshot FROM evidence WHERE task_id=? AND source_type='USER_FILE'",String.class,task); assertThat(snapshots).hasSize(1);assertThat(snapshots.getFirst()).contains("必要摘录","excerptOnly").doesNotContain("不应长期留存的末尾全文"); assertThat(files.get(owner(),file).get("segments")).asList().isEmpty(); } @Test void oversizedWholeBatchIsRejectedWithoutDroppingCandidatesOrCallingModel()throws Exception { String batch=batch("超长上下文"),conv=conversation(); mvc.perform(post("/api/conversations/"+conv+"/messages").with(user("admin")).with(csrf()).header("Idempotency-Key",UUID.randomUUID().toString()).contentType("application/json").content(json.write(Map.of("question","整个超长批次","scope",Map.of("batchId",batch))))).andExpect(status().isPayloadTooLarge()); assertThat(jdbc.queryForObject("SELECT COUNT(*) FROM conversation_message WHERE conversation_id=?",Integer.class,conv)).isZero(); assertThat(jdbc.queryForObject("SELECT COUNT(*) FROM search_item WHERE batch_id=?",Integer.class,batch)).isEqualTo(25); } @Test void changedCandidateCannotBorrowValidSourceToCreateQuestion()throws Exception { String batch=batch(),conv=conversation(); String raw=jdbc.queryForObject("SELECT snapshot FROM search_item WHERE batch_id=? AND position=0",String.class,batch); var candidate=(tools.jackson.databind.node.ObjectNode)json.read(raw);candidate.put("title","被篡改的项目"); jdbc.update("UPDATE search_item SET snapshot=? WHERE batch_id=? AND position=0",candidate.toString(),batch); mvc.perform(post("/api/conversations/"+conv+"/messages").with(user("admin")).with(csrf()).header("Idempotency-Key",UUID.randomUUID().toString()).contentType("application/json").content(json.write(Map.of("question","不能引用篡改事实","scope",Map.of("batchId",batch))))).andExpect(status().isConflict()); assertThat(jdbc.queryForObject("SELECT COUNT(*) FROM conversation_message WHERE conversation_id=?",Integer.class,conv)).isZero(); } @Test void usageIsReadOnlyAndSeparatesLocalCostsFromPlatformBalance()throws Exception { mvc.perform(get("/api/usage").with(user("admin"))).andExpect(status().isOk()).andExpect(jsonPath("$.ledger.unknown_cost_calls").exists()).andExpect(jsonPath("$.platformBalance").isString()); mvc.perform(get("/api/usage")).andExpect(status().isUnauthorized()); } }