Commit 624ee95e authored by 王蔡翾's avatar 王蔡翾
Browse files

bug修复

parent 6e1d9234
package com.example.rzgb;
import com.example.rzgb.common.Json;
import com.example.rzgb.opportunity.*;
import com.example.rzgb.profile.CompanyProfile;
import java.time.*;
import java.math.BigDecimal;
import java.util.*;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.*;
/** 明确标为测试的完整与缺失样本;高分只验证标尺,不伪造真实业务评分。 */
class OpportunityAnalysisTests {
final Json json=new Json();
final OpportunityRanking ranking=new OpportunityRanking(json);
final OpportunityAnalysis analysis=new OpportunityAnalysis();
CompanyProfile profile() {
var node=(tools.jackson.databind.node.ObjectNode)json.read(json.write(CompanyProfile.empty()));
node.put("mainBusiness","智慧水务"); node.put("products","水质监测"); node.put("serviceRegions","浙江");
node.put("amountPreference","80-120 万元"); node.put("qualifications","ISO9001"); node.put("trackRecord","供水业绩"); node.put("version",7); node.put("companyName","测试公司"); node.put("completed",true);
return json.convert(node.toString(),CompanyProfile.class);
}
@Test void completeTestFixtureCanReach100AndUsesExactNormalizedWeights() {
var source=json.read("{\"bid_id\":1,\"title\":\"智慧水务水质监测\",\"province\":\"浙江\",\"money\":1000000,\"fulltext\":\"需ISO9001资质和供水业绩。交付工期90天。\"}");
var match=analysis.analyze(ranking.normalize(source,"e1"),source,profile()).match();
assertThat(match.score()).isEqualByComparingTo("100"); assertThat(match.completeness()).isEqualTo(100);
assertThat(match.profileVersion()).isEqualTo(7);
// 地区不匹配时,仅地区维度从100降到0;40/20/20/20权重得到80,而非取四项简单平均。
var other=(tools.jackson.databind.node.ObjectNode)source.deepCopy(); other.put("province","安徽");
assertThat(analysis.analyze(ranking.normalize(other,"e2"),other,profile()).match().score()).isEqualByComparingTo("80");
var weighted=(tools.jackson.databind.node.ObjectNode)json.read(json.write(profile()));
weighted.set("matchWeights",json.read("{\"business\":3,\"region\":1,\"amount\":0,\"track\":0}"));
assertThat(analysis.analyze(ranking.normalize(other,"e2"),other,json.convert(weighted.toString(),CompanyProfile.class)).match().score()).isEqualByComparingTo("75");
}
@Test void missingBodyAndBudgetStayUnknownAndNeverClaimQualificationsPassed() {
var source=json.read("{\"bid_id\":2,\"title\":\"智慧水务\"}");
var result=analysis.analyze(ranking.normalize(source,"e2"),source,profile());
assertThat(result.summary().qualifications()).isEmpty(); assertThat(result.summary().gaps()).anyMatch(s -> s.contains("未取得正文"));
assertThat(result.match().dimensions().get("track").known()).isFalse();
assertThat(result.match().dimensions().get("amount").known()).isFalse();
assertThat(result.match().completeness()).isEqualTo(25);
}
@Test void incompleteCompanyProfileHasNoOverallFitScore() {
var source=json.read("{\"bid_id\":3,\"title\":\"水务\"}");
assertThat(analysis.analyze(ranking.normalize(source,"e3"),source,CompanyProfile.empty()).match().score()).isNull();
}
@Test void summaryPrefersConstructionAndExplicitRegistrationOverOtherDates() {
var source=json.read("""
{"bid_id":4,"title":"某监测项目","province":"浙江","registration_deadline":"2026-11-12 17:00:00",
"fulltext":"欢迎参与本次项目。建设内容:安装水质监测设备并接入平台。投标截止2026-11-16。需电子与智能化资质。须提供同类业绩。"}
""");
var summary=analysis.analyze(ranking.normalize(source,"e4"),source,profile()).summary();
assertThat(summary.construction()).isEqualTo("建设内容:安装水质监测设备并接入平台");
assertThat(summary.region()).isEqualTo("浙江");
assertThat(summary.schedule()).startsWith("报名截止时间:2026-11-12 17:00:00").contains("投标截止2026-11-16");
assertThat(summary.qualifications()).containsExactly("需电子与智能化资质","须提供同类业绩");
}
@Test void andQueryUsesUpstreamGroupsAndCorrectYuanFieldNames() {
LocalDate today=LocalDate.now(ZoneId.of("Asia/Shanghai"));
var q=new OpportunityQuery(List.of("智慧水务","平台"),null,null,null,null,null,null,null,
OpportunityQuery.Mode.SEARCH,OpportunityQuery.KeywordMode.ALL,List.of("浙江"),new BigDecimal("100.25"),new BigDecimal("200"));
q.validate(); assertThat(q.beginDate()).isEqualTo(today.minusDays(89));
var page=q.page(3,50);
assertThat(q.tool()).isEqualTo("query_bids_advanced");
assertThat(page).containsEntry("min_money",new BigDecimal("1002500")).doesNotContainKeys("min_amount","max_amount");
assertThat(page.get("keyword_groups").toString()).contains("平台");
assertThat(page.get("provinces")).isEqualTo(List.of("浙江"));
}
@Test void marketEmptyKeywordsAreExplicitWaterDefaultsAndLeadCannotUseHardFilters() {
var q=new OpportunityQuery(List.of(),null,null,null,null,null,null,null,OpportunityQuery.Mode.MARKET,null,null,null,null);
q.validate(); assertThat(q.keywords()).isEqualTo(OpportunityQuery.WATER_KEYWORDS);
var invalid=new OpportunityQuery(List.of("水务"),null,null,null,null,null,null,null,OpportunityQuery.Mode.LEADS,null,List.of("浙江"),null,null);
assertThatThrownBy(invalid::validate).hasMessageContaining("仅作偏好");
}
}
package com.example.rzgb;
import com.example.rzgb.common.*;
import com.example.rzgb.opportunity.*;
import java.math.BigDecimal;
import java.time.*;
import java.util.*;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.*;
/** 用固定事实验证关键业务边界,避免再次引入“评分不够就删掉”的漏检逻辑。 */
class OpportunityRankingTests {
private final Json json = new Json();
private final OpportunityRanking ranking = new OpportunityRanking(json);
private OpportunityQuery query(OpportunityQuery.Preference preference) {
LocalDate today = LocalDate.now(ZoneId.of("Asia/Shanghai"));
return new OpportunityQuery(List.of("智慧水务"),today.minusDays(89),today,List.of(1,2,4,7,8),preference,
List.of("浙江"),new BigDecimal("80"),new BigDecimal("120"));
}
@Test void preferenceChangesOrderButNeverDeletesCandidatesOrRewritesFacts() {
var unknown = ranking.normalize(json.read("{\"bid_id\":1,\"title\":\"智慧水务建设\",\"province\":\"安徽\",\"pub_time\":\"2026-10-25\"}"),"e1");
var target = ranking.normalize(json.read("{\"bid_id\":2,\"title\":\"智慧水务建设\",\"province\":\"浙江\",\"money\":1000000,\"pub_time\":\"2026-10-20\"}"),"e2");
var source = List.of(unknown,target);
assertThat(ranking.rank(source,query(OpportunityQuery.Preference.COMPREHENSIVE)).getFirst().facts()).isEqualTo(unknown);
for (var preference : OpportunityQuery.Preference.values())
assertThat(ranking.rank(source,query(preference)).stream().map(OpportunityRanking.Ranked::facts))
.containsExactlyInAnyOrder(unknown,target);
assertThat(ranking.rank(source,query(OpportunityQuery.Preference.REGION)).getFirst().facts()).isEqualTo(target);
assertThat(ranking.rank(source,query(OpportunityQuery.Preference.AMOUNT)).getFirst().facts()).isEqualTo(target);
assertThat(unknown.budgetWan()).isNull();
assertThat(unknown.gaps()).anyMatch(text -> text.contains("预算"));
assertThat(source).containsExactly(unknown,target);
}
@Test void retrievalPayloadContainsOnlyHardConditionsAndExplicitPagination() {
var payload = query(OpportunityQuery.Preference.AMOUNT).page(2,50);
assertThat(payload).containsEntry("page",2).containsEntry("page_size",50)
.doesNotContainKeys("provinces","cities","min_amount","max_amount","min_money","max_money","preferredRegions");
assertThat(payload.get("keywords")).isEqualTo(List.of("智慧水务"));
}
@Test void normalizationKeepsZeroSeparateFromMissingAndDoesNotInventUrlsOrStage() {
var zero = ranking.normalize(json.read("{\"bid_id\":1,\"money\":0,\"url\":\"javascript:alert(1)\"}"),"e");
var unknown = ranking.normalize(json.read("{\"bid_id\":2,\"money\":\"公告未披露\",\"pub_time\":\"not-a-date\"}"),"e2");
assertThat(zero.budgetWan()).isEqualByComparingTo(BigDecimal.ZERO);
assertThat(zero.url()).isNull(); assertThat(zero.stage()).isNull();
assertThat(unknown.budgetWan()).isNull(); assertThat(unknown.publishDate()).isEmpty();
assertThat(ranking.normalize(json.read("{\"money_wan\":\"125.25\"}"),"e3").budgetWan()).isEqualByComparingTo("125.25");
}
@Test void sameTitleDifferentNoticeStagesRemainDifferentRecords() {
var invitation = ranking.normalize(json.read("{\"bid_id\":1,\"title\":\"智慧水务\",\"bid_process\":4}"),"e1");
var award = ranking.normalize(json.read("{\"bid_id\":2,\"title\":\"智慧水务\",\"bid_process\":7}"),"e2");
assertThat(ranking.rank(List.of(invitation,award),query(OpportunityQuery.Preference.COMPREHENSIVE))).hasSize(2);
assertThat(invitation.id()).isNotEqualTo(award.id());
}
@Test void invalidStageAndReversedAmountRangeFailBeforeAnyExternalCall() {
var q = query(OpportunityQuery.Preference.AMOUNT);
assertThatThrownBy(() -> new OpportunityQuery(q.keywords(),q.beginDate(),q.endDate(),q.stages(),q.preference(),q.preferredRegions(),
new BigDecimal("200"),new BigDecimal("100")).validate()).isInstanceOf(ApiException.class);
assertThatThrownBy(() -> new OpportunityQuery(q.keywords(),q.beginDate(),q.endDate(),List.of(999),q.preference(),q.preferredRegions(),null,null).validate())
.isInstanceOf(ApiException.class);
}
}
package com.example.rzgb;
import com.example.rzgb.common.*;
import com.example.rzgb.task.*;
import com.example.rzgb.research.*;
import com.example.rzgb.files.*;
import com.sun.net.httpserver.HttpServer;
import java.math.BigDecimal;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.time.LocalDate;
import java.time.YearMonth;
import java.time.ZoneId;
import java.util.*;
import java.util.concurrent.*;
import org.junit.jupiter.api.*;
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.ActiveProfiles;
import org.springframework.test.context.DynamicPropertyRegistry;
import org.springframework.test.context.DynamicPropertySource;
import org.springframework.test.web.servlet.MockMvc;
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.*;
/** D3 本地契约/事务测试:明确使用模拟 HTTP,不作为真实供应商或数据库联调证据。 */
@SpringBootTest
@AutoConfigureMockMvc
@ActiveProfiles("test")
class ResearchWorkflowTests {
@Autowired TaskService tasks; @Autowired JdbcTemplate jdbc; @Autowired Json json;
@Autowired BidFileService files; @Autowired MockMvc mvc;
private static HttpServer upstream;
private static final List<String> 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 body=new String(exchange.getRequestBody().readAllBytes(),StandardCharsets.UTF_8),path=exchange.getRequestURI().getPath();
REQUESTS.add(path+"|"+body+"|"+exchange.getRequestHeaders().getFirst("X-Client"));
if(path.equals("/get_company_profile")&&body.contains("D3延迟")) try {Thread.sleep(250);} catch(InterruptedException e){Thread.currentThread().interrupt();}
Json j=new Json(); var input=j.read(body); Object data; boolean unknown=false;
switch(path) {
case "/search_company" -> {
String name=input.path("company_name").asText();
List<Object> items=name.contains("同名")?List.of(Map.of("id","d3-a","fullname","D3同名总公司","province","浙江"),Map.of("id","d3-b","fullname","D3同名分公司","province","江苏")):
List.of(Map.of("id",name,"fullname",name,"province","浙江"));
if(name.equals("北京排水集团")) items=List.of(Map.of("id","parent","fullname","北京城市排水集团有限责任公司","name","北京排水集团"),
Map.of("id","branch","fullname","北京城市排水集团有限责任公司第一分公司"),Map.of("id","unrelated","fullname","成都乐一下科技有限公司"));
data=Map.of("total",items.size(),"items",items); unknown=name.contains("未知积分");
}
case "/get_company_profile" -> data=Map.of("fullname",input.path("company").asText(),"winner_count",12,"url","https://example.com/company?sk=keep");
case "/get_company_business_keywords" -> data=Map.of("keywords",List.of(Map.of("keyword","水务","count",12,"amount",100000)));
case "/get_company_partners" -> data=Map.of("partners",List.of(Map.of("company_name","D3共同客户","company_id","customer-1","cooperation_count",2)));
case "/aggregate_bids_advanced" -> data=Map.of("buckets",List.of(Map.of("key",input.path("group_by").path(0).asText().equals("month")
? YearMonth.from(LocalDate.parse(input.path("filters").path("end_date").asText())).toString() : "2026","count",12,"sum_amount",100000)));
case "/get_top_purchasers" -> data=Map.of("items",List.of(Map.of("company_name","某市水务集团","purchase_count",8)));
case "/get_top_suppliers" -> data=Map.of("items",List.of(Map.of("company_name","某智慧水务设备有限公司","win_count",6)));
case "/query_bids_advanced","/search_bids" -> {
boolean purchases=input.path("match_modes").path(0).asText().equals("caller") && input.has("end_date");
data=Map.of("total",1,"items",List.of(Map.of("bid_id",3001,"title",purchases?"D3采购记录样本":input.path("keywords").path(0).asText(),
"caller_name","D3采购方","money",100000,"url","https://example.com/notice?sk=keep")));
}
case "/get_bid_detail" -> data=Map.of("bid_id",3001,"title","D3测试项目","caller_name","D3采购方","fulltext","公开项目建设内容,服务合同,资格待核验","url","https://example.com/notice?sk=keep");
case "/find_competitors" -> data=Map.of("competitors",List.of(Map.of("company_name","D3轻查竞对","company_id","d3-light","co_bid_count",2)));
case "/find_potential_bidders" -> data=Map.of("bidders",List.of(Map.of("company_name","D3候选竞争者","caller_history_count",2)));
default -> data=Map.of();
}
Object response;
if(path.equals("/v1/tools/search")) response=Map.of("results",List.of(Map.of("title","D3公开新闻","url","https://example.com/official?sk=keep","snippet","尚未核实风险")));
else if(path.equals("/v1/tools/fetch")) response=Map.of("title","D3公开项目","content","公开来源正文,不能据此声称无风险");
else if(path.equals("/chat/completions")) {
String output=body.contains("image_url")?"图片可见内容:D3扫描页":body.contains("INVALID_MODEL")?"{\"observations\":[{\"text\":\"无来源99999\",\"evidenceIds\":[\"fake\"]}]}":"{\"observations\":[]}";
if(body.contains("qa-regression")) {
var snapshot=j.read(input.path("messages").path(1).path("content").asText()).path("snapshot");
var ref=snapshot.path("items").path(0).path("facts").path("evidenceId").asText();
output=j.write(Map.of("observations",List.of(Map.of("text","可参考本轮已核验的公开资料。","evidenceIds",List.of(ref)))));
}
response=Map.of("model","d3-test-model","choices",List.of(Map.of("message",Map.of("content",output,"reasoning_content","never-store-private"))),"usage",Map.of("prompt_tokens",11,"completion_tokens",7));
}
else response=unknown?Map.of("data",data):Map.of("data",data,"meta",Map.of("cost_units",path.equals("/search_company")?0:0.5));
byte[] bytes=j.write(response).getBytes(StandardCharsets.UTF_8); exchange.getResponseHeaders().set("Content-Type","application/json");
exchange.sendResponseHeaders(200,bytes.length); exchange.getResponseBody().write(bytes); exchange.close();
}); upstream.start();
String url="http://127.0.0.1:"+upstream.getAddress().getPort();
registry.add("spring.datasource.url",()->"jdbc:h2:mem:d3;MODE=MySQL;DATABASE_TO_LOWER=TRUE;DB_CLOSE_DELAY=-1");
registry.add("rz.zlbx-base-url",()->url); registry.add("rz.deepseek-base-url",()->url);
registry.add("rz.max-calls",()->25); registry.add("rz.max-cost-units",()->100);
}
@AfterAll static void stop(){ upstream.stop(0); }
private String owner(){return jdbc.queryForObject("SELECT id FROM app_user WHERE username='admin'",String.class);}
private TaskRequest company(List<String> names,int calls,String focus) {
return new TaskRequest(TaskRequest.Operation.COMPANY_RESEARCH,TaskRequest.Workflow.COMPANY_INTEL,"",false,calls,new BigDecimal("100"),null,new ResearchRequest(names,Map.of(),ResearchRequest.Mode.FULL,null,null,null,focus,0));
}
private String start(TaskRequest request){ return tasks.create(owner(),UUID.randomUUID().toString(),request).get("id").toString(); }
private Map<String,Object> waitFor(String id,String...states) {
await().atMost(Duration.ofSeconds(20)).untilAsserted(()->assertThat(tasks.get(owner(),id).get("status")).isIn((Object[])states)); return tasks.get(owner(),id);
}
private int external(String id){return jdbc.queryForObject("SELECT COUNT(*) FROM tool_call WHERE task_id=? AND provider<>'LOCAL'",Integer.class,id);}
private TaskRequest resumeRequest(TaskRequest original,Map<String,String> selections,int calls,int ack) {
var r=original.research(); return new TaskRequest(original.operation(),original.workflow(),original.input(),true,calls,original.maxCostUnits(),null,new ResearchRequest(r.companies(),selections,r.mode(),r.fileId(),r.parentId(),r.targetProjectId(),r.focus(),ack));
}
private String newConversation() 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 tools.jackson.databind.JsonNode submitTurn(String conversation,String question,String entry,String key) throws Exception {
var body=new LinkedHashMap<String,String>(); body.put("question",question); body.put("entry",entry);
return json.read(mvc.perform(post("/api/conversations/"+conversation+"/research").with(user("admin")).with(csrf())
.header("Idempotency-Key",key).contentType("application/json").content(json.write(body)))
.andExpect(status().isOk()).andReturn().getResponse().getContentAsString());
}
@Test void companyQuestionUsesNamedSubjectAndFollowUpUsesSameConversationEvidence() throws Exception {
String conversation=newConversation(),question="请帮我查一下北京排水集团的历史客户";
var submitted=submitTurn(conversation,question,"customer",UUID.randomUUID().toString());
String id=submitted.path("id").asText(); var pending=waitFor(id,"WAITING_ENTITY");
var request=json.convert(submitted.path("request").toString(),TaskRequest.class);
assertThat(request.research().companies()).containsExactly("北京排水集团");
assertThat(json.write(pending.get("result"))).contains("北京城市排水集团有限责任公司第一分公司").doesNotContain("成都乐一下科技有限公司");
assertThatThrownBy(()->tasks.resume(owner(),id,UUID.randomUUID().toString(),resumeRequest(request,Map.of("entity:0","unrelated"),18,0)))
.isInstanceOf(ApiException.class);
tasks.resume(owner(),id,UUID.randomUUID().toString(),resumeRequest(request,Map.of("entity:0","branch"),18,0));
var completed=waitFor(id,"SUCCEEDED");
assertThat(completed.get("answeredAt")).isNotNull();
assertThat(json.write(completed.get("result"))).contains("company:0:purchases","D3采购记录样本");
var today=LocalDate.now(ZoneId.of("Asia/Shanghai"));
assertThat(REQUESTS).anyMatch(sent->sent.startsWith("/query_bids_advanced|") && sent.contains("\"match_modes\":[\"caller\"]")
&& sent.contains("北京城市排水集团有限责任公司第一分公司") && sent.contains(today.minusYears(1).plusDays(1).toString()));
var follow=submitTurn(conversation,"它有哪些历史客户? qa-regression",null,UUID.randomUUID().toString());
assertThat(follow.path("request").path("qa").path("reportTaskId").asText()).isEqualTo(id);
var answer=waitFor(follow.path("id").asText(),"SUCCEEDED");
assertThat(json.write(answer.get("result"))).contains("已核验的公开资料");
assertThat(answer.get("calls")).asList().hasSize(1);
mvc.perform(get("/api/conversations/"+conversation+"/messages").with(user("admin")))
.andExpect(jsonPath("$[0].content").value(question)).andExpect(jsonPath("$[1].task_id").value(follow.path("id").asText()));
}
@Test void marketEntryAndOpenQuestionReturnActualAggregatesInTheConversation() throws Exception {
String conversation=newConversation(),key=UUID.randomUUID().toString(),question="调研华东地区智慧水务市场";
var first=submitTurn(conversation,question,"market",key);
String id=first.path("id").asText(); var result=waitFor(id,"SUCCEEDED");
var conditions=first.path("request").path("opportunity");
assertThat(conditions.path("keywords").toString()).isEqualTo("[\"智慧水务\"]");
assertThat(conditions.path("hardRegions").toString()).contains("浙江","上海");
var today=LocalDate.now(ZoneId.of("Asia/Shanghai"));
assertThat(conditions.path("beginDate").asText()).isEqualTo(today.withDayOfMonth(1).minusMonths(5).toString());
assertThat(json.write(result.get("result"))).contains("platformAggregations","某智慧水务设备有限公司");
String recent="调研近一个月智慧水务市场的主要中标企业";
var free=submitTurn(newConversation(),recent,null,UUID.randomUUID().toString());
var freeResult=waitFor(free.path("id").asText(),"SUCCEEDED");
assertThat(free.path("operation").asText()).isEqualTo("OPPORTUNITY_SEARCH");
assertThat(free.path("request").path("opportunity").path("beginDate").asText()).isEqualTo(today.minusMonths(1).plusDays(1).toString());
assertThat(json.write(freeResult.get("calls"))).contains("get_top_suppliers").doesNotContain("search_company");
var follow=submitTurn(conversation,"那近一个月呢?",null,UUID.randomUUID().toString());
assertThat(follow.path("request").path("opportunity").path("hardRegions")).isEqualTo(conditions.path("hardRegions"));
waitFor(follow.path("id").asText(),"SUCCEEDED");
assertThat(submitTurn(conversation,question,"market",key).path("id").asText()).isEqualTo(id);
mvc.perform(get("/api/conversations/"+conversation+"/messages").with(user("admin")))
.andExpect(jsonPath("$.length()").value(2)).andExpect(jsonPath("$[0].content").value(question));
}
@Test void ambiguousCompanyWaitsAndDoesNotChargeDeepLookupBeforeConfirmation() {
var request=company(List.of("D3同名"),18,"profile"); String id=start(request); waitFor(id,"WAITING_ENTITY");
assertThat(external(id)).isEqualTo(1);
assertThat(jdbc.queryForList("SELECT tool_name FROM tool_call WHERE task_id=?",String.class,id)).containsExactly("search_company");
var selected=resumeRequest(request,Map.of("entity:0","d3-b"),18,0);
tasks.resume(owner(),id,UUID.randomUUID().toString(),selected); var done=waitFor(id,"SUCCEEDED");
assertThat(json.write(done)).contains("D3同名分公司").doesNotContain("never-store-private");
assertThat(REQUESTS).anyMatch(r->r.startsWith("/get_company_profile|")&&r.contains("d3-b")&&r.endsWith("company-intel/1.0.2"));
}
@Test void budgetResumeIsIdempotentAndNeverReplaysSuccessfulStep() {
var request=company(List.of("D3预算公司"),1,"profile"); String id=start(request); waitFor(id,"WAITING_BUDGET");
var next=resumeRequest(request,Map.of(),18,0); String key=UUID.randomUUID().toString();
tasks.resume(owner(),id,key,next); tasks.resume(owner(),id,key,next); waitFor(id,"SUCCEEDED");
assertThat(jdbc.queryForObject("SELECT COUNT(*) FROM tool_call WHERE task_id=? AND tool_name='search_company'",Integer.class,id)).isEqualTo(1);
assertThat(external(id)).isEqualTo(4);
}
@Test void cancelledPausedTaskDoesNotIssueFurtherRequestsAndKeepsCost() {
String id=start(company(List.of("D3取消公司"),2,"profile")); waitFor(id,"WAITING_BUDGET"); int before=external(id);
tasks.cancel(owner(),id); assertThat(external(id)).isEqualTo(before);
assertThat(jdbc.queryForObject("SELECT SUM(cost_units) FROM tool_call WHERE task_id=?",BigDecimal.class,id)).isEqualByComparingTo("0.5");
assertThatThrownBy(()->tasks.resume(owner(),id,UUID.randomUUID().toString(),company(List.of("D3取消公司"),18,"profile"))).isInstanceOf(ApiException.class);
}
@Test void unknownCostRequiresExplicitAcknowledgementAndStaysUnknown() {
var request=company(List.of("D3未知积分"),18,"profile"); String id=start(request); waitFor(id,"WAITING_BUDGET"); assertThat(external(id)).isEqualTo(1);
tasks.resume(owner(),id,UUID.randomUUID().toString(),resumeRequest(request,Map.of(),18,1)); waitFor(id,"SUCCEEDED");
assertThat(jdbc.queryForObject("SELECT cost_units FROM tool_call WHERE task_id=? AND tool_name='search_company'",BigDecimal.class,id)).isNull();
}
@Test void twoCompanyComparisonWaitsForBothAndUsesCustomerIntersection() {
var request=company(List.of("D3对比公司","D3同名"),25,null); String id=start(request); waitFor(id,"WAITING_ENTITY");
assertThat(external(id)).isEqualTo(2);
tasks.resume(owner(),id,UUID.randomUUID().toString(),resumeRequest(request,Map.of("entity:1","d3-a"),25,0));
var result=waitFor(id,"SUCCEEDED"); assertThat(json.write(result.get("result"))).contains("D3共同客户","commonCustomers","co_bid_count");
assertThat(jdbc.queryForObject("SELECT COUNT(*) FROM tool_call WHERE task_id=? AND tool_name='get_company_profile'",Integer.class,id)).isEqualTo(2);
}
@Test void invalidSelectionAndChangingFrozenEntityAreRejectedBeforeSavingCommand() {
var request=company(List.of("D3同名"),2,"profile"); String id=start(request); waitFor(id,"WAITING_ENTITY");
assertThatThrownBy(()->tasks.resume(owner(),id,UUID.randomUUID().toString(),resumeRequest(request,Map.of("entity:0","forged-id"),18,0))).isInstanceOf(ApiException.class);
tasks.resume(owner(),id,UUID.randomUUID().toString(),resumeRequest(request,Map.of("entity:0","d3-a"),2,0)); waitFor(id,"WAITING_BUDGET");
assertThatThrownBy(()->tasks.resume(owner(),id,UUID.randomUUID().toString(),resumeRequest(request,Map.of("entity:0","d3-b"),18,0))).isInstanceOf(ApiException.class);
}
private TaskRequest bid(String input,ResearchRequest.Mode mode,String file) {
return new TaskRequest(TaskRequest.Operation.BID_RESEARCH,TaskRequest.Workflow.BID_DECISION,input,false,25,new BigDecimal("100"),null,new ResearchRequest(List.of(),Map.of(),mode,file,null,null,null,0));
}
@Test void titleAndZlbxLinkHaveDifferentLookupPathsAndFullModeHasMoreSteps() {
String quick=start(bid("D3测试项目",ResearchRequest.Mode.QUICK,null)); waitFor(quick,"SUCCEEDED");
var tools=jdbc.queryForList("SELECT tool_name FROM tool_call WHERE task_id=?",String.class,quick);
assertThat(tools).contains("search_bids","get_bid_detail","search_company","get_company_profile").doesNotContain("find_potential_bidders","get_price_trends");
String full=start(bid("https://www.zhiliaobiaoxun.com/content/3001/b1?sk=keep",ResearchRequest.Mode.FULL,null)); waitFor(full,"SUCCEEDED");
var fullTools=jdbc.queryForList("SELECT tool_name FROM tool_call WHERE task_id=?",String.class,full);
assertThat(fullTools).contains("get_company_partners","query_bids_advanced","find_potential_bidders","web_search").doesNotContain("get_price_trends");
assertThat(external(full)).isGreaterThan(external(quick));
assertThat(REQUESTS).anyMatch(r->r.startsWith("/get_bid_detail|")&&r.contains("bid_url")&&r.endsWith("bid-decision/1.0.4"));
}
@Test void publicLinkIsFetchedThenCrossCheckedWithoutLeakingPrivateReasoning() {
String id=start(bid("https://example.com/d3-announcement",ResearchRequest.Mode.QUICK,null)); waitFor(id,"SUCCEEDED");
assertThat(jdbc.queryForList("SELECT tool_name FROM tool_call WHERE task_id=?",String.class,id)).contains("web_fetch","search_bids","get_bid_detail");
assertThat(json.write(tasks.get(owner(),id))).doesNotContain("never-store-private");
}
@Test void invalidModelReferencesNeverAppearAsConclusions() {
String id=start(company(List.of("INVALID_MODEL"),18,"profile")); var task=waitFor(id,"PARTIAL");
assertThat(json.write(task.get("result"))).contains("未通过引用").doesNotContain("无来源99999");
assertThat(json.write(task)).doesNotContain("无来源99999");
}
@Test void fileBindingIsExclusiveAndDeleteWipesOriginalAndDerivatives() {
String file=files.upload(owner(),"BID_PROJECT",new MockMultipartFile("file","d3.txt","text/plain","D3项目\n内部资料不发送公开搜索".getBytes(StandardCharsets.UTF_8))).get("id").toString();
assertThatThrownBy(()->files.get(UUID.randomUUID().toString(),file)).isInstanceOf(ApiException.class);
String id=start(bid("D3测试项目",ResearchRequest.Mode.QUICK,file)); waitFor(id,"SUCCEEDED");
assertThat(json.write(tasks.get(owner(),id))).contains("未经站内公告核实","USER_FILE");
String other=start(bid("D3测试项目",ResearchRequest.Mode.QUICK,file)); waitFor(other,"FAILED"); assertThat(external(other)).isZero();
files.delete(owner(),file); var row=jdbc.queryForMap("SELECT status,original_bytes,segments_json FROM temporary_file WHERE id=?",file);
assertThat(row.get("status")).isEqualTo("DELETED"); assertThat(row.get("original_bytes")).isNull(); assertThat(row.get("segments_json")).isNull();
assertThat(jdbc.queryForObject("SELECT COUNT(*) FROM file_deletion_audit WHERE file_id=?",Integer.class,file)).isEqualTo(1);
assertThat(tasks.get(owner(),id).get("evidence")).isNotNull();
}
@Test void filesRequireAuthenticationCsrfAndBidPurpose()throws Exception {
var file=new MockMultipartFile("file","d3.txt","text/plain","D3测试文件".getBytes(StandardCharsets.UTF_8));
mvc.perform(multipart("/api/files").file(file).param("purpose","BID_PROJECT").with(csrf())).andExpect(status().isUnauthorized());
mvc.perform(multipart("/api/files").file(file).param("purpose","BID_PROJECT").with(user("admin"))).andExpect(status().isForbidden());
mvc.perform(multipart("/api/files").file(file).param("purpose","COMPANY_PROFILE").with(user("admin")).with(csrf())).andExpect(status().isBadRequest());
mvc.perform(multipart("/api/files").file(file).param("purpose","BID_PROJECT").with(user("admin")).with(csrf())).andExpect(status().isOk()).andExpect(jsonPath("$.segments[0].locator").exists());
}
@Test void focusedFollowupReusesConfirmedEntityAndDoesNotRerunWholeReport() {
String parent=start(company(List.of("D3局部追问公司"),18,"profile")); waitFor(parent,"SUCCEEDED");
var request=new TaskRequest(TaskRequest.Operation.COMPANY_RESEARCH,TaskRequest.Workflow.COMPANY_INTEL,"",false,18,new BigDecimal("100"),null,
new ResearchRequest(List.of("D3局部追问公司"),Map.of(),ResearchRequest.Mode.FULL,null,parent,null,"partners",0));
String child=start(request); waitFor(child,"SUCCEEDED");
var tools=jdbc.queryForList("SELECT tool_name FROM tool_call WHERE task_id=?",String.class,child);
assertThat(tools).contains("ENTITY_CACHE","get_company_partners","model_json").doesNotContain("search_company","get_company_profile","find_competitors");
assertThat(external(child)).isEqualTo(3);
}
@Test void tamperedResearchEvidenceCannotBePublished() {
String id=start(company(List.of("D3防篡改公司"),18,"profile")); waitFor(id,"SUCCEEDED");
jdbc.update("UPDATE evidence SET excerpt='changed' WHERE task_id=?",id);
assertThatThrownBy(()->tasks.get(owner(),id)).isInstanceOf(ApiException.class).hasMessageContaining("引用已变化");
}
@Test void projectFileVisionIsAnActualModelCallWithNoBase64InReport()throws Exception {
var image=new java.awt.image.BufferedImage(80,40,java.awt.image.BufferedImage.TYPE_INT_RGB); var out=new java.io.ByteArrayOutputStream(); javax.imageio.ImageIO.write(image,"png",out);
String file=files.upload(owner(),"BID_PROJECT",new MockMultipartFile("file","scan.png","image/png",out.toByteArray())).get("id").toString();
String id=start(bid("D3测试项目",ResearchRequest.Mode.QUICK,file)); var result=waitFor(id,"SUCCEEDED");
assertThat(jdbc.queryForObject("SELECT COUNT(*) FROM tool_call WHERE task_id=? AND tool_name='vision' AND provider='DEEPSEEK'",Integer.class,id)).isEqualTo(1);
assertThat(json.write(result)).contains("D3扫描页").doesNotContain("base64","never-store-private");
assertThat(json.read(json.write(result.get("usage"))).path("external_calls").asInt()).isEqualTo(external(id));
}
@Test void parentDeepDiveRequiresOwnedResultAndSerialExecutionWithFiveObjectLimit() {
var query=new com.example.rzgb.opportunity.OpportunityQuery(List.of("D3父子项目"),null,null,null,null,null,null,null);
String parent=start(new TaskRequest(TaskRequest.Operation.OPPORTUNITY_SEARCH,TaskRequest.Workflow.TENDER_SEARCH,"",false,5,new BigDecimal("100"),query));
waitFor(parent,"SUCCEEDED");
assertThat(external(parent)).isEqualTo(1); // 初始报告没有隐式企业或投标决策调用。
var child=new TaskRequest(TaskRequest.Operation.BID_RESEARCH,TaskRequest.Workflow.BID_DECISION,"D3父子项目",false,1,new BigDecimal("100"),null,
new ResearchRequest(List.of(),Map.of(),ResearchRequest.Mode.QUICK,null,parent,"zlbx-3001",null,0));
String first=start(child); waitFor(first,"WAITING_BUDGET");
assertThatThrownBy(()->start(child)).isInstanceOf(ApiException.class).hasMessageContaining("下一个对象"); tasks.cancel(owner(),first);
for(int i=0;i<4;i++){String id=start(child);waitFor(id,"WAITING_BUDGET");tasks.cancel(owner(),id);}
assertThatThrownBy(()->start(child)).isInstanceOf(ApiException.class).hasMessageContaining("最多五个");
assertThat(json.write(tasks.get(owner(),parent).get("children"))).contains(first,"zlbx-3001");
var forged=new TaskRequest(TaskRequest.Operation.BID_RESEARCH,TaskRequest.Workflow.BID_DECISION,"D3父子项目",false,1,new BigDecimal("100"),null,
new ResearchRequest(List.of(),Map.of(),ResearchRequest.Mode.QUICK,null,parent,"zlbx-forged",null,0));
assertThatThrownBy(()->start(forged)).isInstanceOf(ApiException.class).hasMessageContaining("已取得结果");
}
@Test void cancellationDuringHttpCallRecordsItsCostButPreventsNextCall() {
String id=start(company(List.of("D3延迟公司"),18,"profile"));
await().atMost(Duration.ofSeconds(5)).untilAsserted(()->assertThat(jdbc.queryForObject("SELECT COUNT(*) FROM tool_call WHERE task_id=? AND tool_name='get_company_profile' AND status='STARTED'",Integer.class,id)).isEqualTo(1));
tasks.cancel(owner(),id);
await().atMost(Duration.ofSeconds(5)).untilAsserted(()->assertThat(jdbc.queryForObject("SELECT COUNT(*) FROM tool_call WHERE task_id=? AND tool_name='get_company_profile' AND status='SUCCEEDED'",Integer.class,id)).isEqualTo(1));
assertThat(external(id)).isEqualTo(2); assertThat(tasks.get(owner(),id).get("status")).isEqualTo("CANCELLED");
assertThat(jdbc.queryForObject("SELECT SUM(cost_units) FROM tool_call WHERE task_id=?",BigDecimal.class,id)).isEqualByComparingTo("0.5");
}
@Test void expiredFilesAreWipedAndCannotStartAnalysis() {
String file=files.upload(owner(),"BID_PROJECT",new MockMultipartFile("file","expire.md","text/plain","到期测试文件".getBytes(StandardCharsets.UTF_8))).get("id").toString();
jdbc.update("UPDATE temporary_file SET expires_at=? WHERE id=?",java.sql.Timestamp.from(java.time.Instant.now().minusSeconds(1)),file); files.expire();
String task=start(bid("D3测试项目",ResearchRequest.Mode.QUICK,file)); waitFor(task,"FAILED"); assertThat(external(task)).isZero();
assertThat(jdbc.queryForObject("SELECT original_bytes FROM temporary_file WHERE id=?",byte[].class,file)).isNull();
}
}
package com.example.rzgb;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.*;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.DynamicPropertyRegistry;
import org.springframework.test.context.DynamicPropertySource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.web.servlet.*;
import org.springframework.mock.web.MockHttpSession;
import org.springframework.jdbc.core.JdbcTemplate;
import com.example.rzgb.common.Json;
import com.example.rzgb.task.*;
import com.example.rzgb.opportunity.OpportunityQuery;
import com.example.rzgb.evidence.EvidenceService;
import java.math.BigDecimal;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.concurrent.*;
import com.sun.net.httpserver.HttpServer;
import static org.assertj.core.api.Assertions.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.*;
import static org.awaitility.Awaitility.await;
@SpringBootTest
@AutoConfigureMockMvc
@ActiveProfiles("test")
class RzGbApplicationTests {
@Autowired MockMvc mvc;
@Autowired JdbcTemplate jdbc;
@Autowired Json json;
@Autowired TaskService tasks;
@Autowired EvidenceService evidence;
@Autowired com.example.rzgb.config.AppProperties properties;
@Autowired org.springframework.context.ApplicationContext context;
private static HttpServer upstream;
private static final Map<String,String> CLIENTS = new ConcurrentHashMap<>();
/** 固定本地协议样例,只测试适配与安全边界,不冒充真实供应商联调。 */
@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 body = new String(exchange.getRequestBody().readAllBytes(), StandardCharsets.UTF_8);
String path = exchange.getRequestURI().getPath();
CLIENTS.put(body, Objects.toString(exchange.getRequestHeaders().getFirst("X-Client"), ""));
int code = 200;
String response;
if (body.contains("余额不足")) response = "{\"success\":false,\"error\":{\"code\":\"insufficient_balance\"}}";
else if (body.contains("业务失败")) response = "{\"success\":false,\"error\":\"invalid_company\"}";
else if (body.contains("限流")) { code = 429; response = "{}"; }
else if (path.equals("/get_top_purchasers")) response="{\"data\":{\"total\":80,\"items\":[{\"company_name\":\"测试采购方\",\"purchase_count\":12,\"total_amount\":1000000}]},\"meta\":{\"cost_units\":0.5}}";
else if (path.equals("/get_top_suppliers")) response="{\"data\":{\"total\":40,\"items\":[{\"company_name\":\"测试供应商\",\"win_count\":8,\"total_amount_wan\":200}]},\"meta\":{\"cost_units\":0.5}}";
else if (path.equals("/aggregate_bids_advanced")) response="{\"data\":{\"total_count\":800,\"buckets\":[{\"key\":\"2026-10\",\"count\":80,\"sum_amount\":3000000}]},\"meta\":{\"cost_units\":0.5}}";
else if ((path.equals("/search_bids") || path.equals("/query_bids_advanced")) && body.contains("预算交集验收")) {
var j=new Json(); var request=j.read(body); int page=request.path("page").asInt();
List<Map<String,Object>> fixtures=List.of(Map.of("money",2075000),Map.of("money_wan",new BigDecimal("313.198")),
Map.of("money",7275620),Map.of("money_wan",new BigDecimal("307.962")),Map.of("money_wan",500),Map.of("money",20000000));
List<Map<String,Object>> items=new ArrayList<>();
for(int i=(page-1)*2;i<Math.min(page*2,fixtures.size());i++) {
Map<String,Object> item=new LinkedHashMap<>(fixtures.get(i)); item.put("bid_id",99700+i);
item.put("title","预算交集验收项目"+i); item.put("province","江苏"); item.put("pub_time",request.path("end_date").asText());
items.add(item);
}
response=j.write(Map.of("data",Map.of("total",fixtures.size(),"items",items),"meta",Map.of("cost_units",0.5)));
}
else if ((path.equals("/search_bids") || path.equals("/query_bids_advanced")) && (body.contains("集成获客") || body.contains("智慧水务监测"))) {
var request = new Json().read(body);
int page = request.path("page").asInt();
if (body.contains("取消分页")) try { Thread.sleep(250); } catch (InterruptedException e) { Thread.currentThread().interrupt(); }
if (body.contains("后页失败") && page == 2) { code = 502; response = "{}"; }
else {
Object first = Map.of("bid_id",99101,"title","智慧水务集成获客项目","province","浙江","money",1000000,"pub_time","2026-10-20","bid_process",4,"url","https://example.com/notice/99101?sk=public-test-signature");
Object second = Map.of("bid_id",99102,"title","智慧水务集成获客项目","province","安徽","pub_time","2026-10-25","bid_process",4);
Object third = Map.of("bid_id",99103,"title","智慧水务集成获客项目","province","江苏","money_wan",80,"pub_time","2026-10-24","bid_process",7);
if (body.contains("阶段归并")) {
first=Map.of("bid_id",99101,"title","智慧水务意向","caller_name","测试同一采购方","province","浙江","project_code","TEST-CODE-2026","bid_process",1);
third=Map.of("bid_id",99103,"title","智慧水务合同","caller_name","测试同一采购方","province","浙江","project_code","TEST-CODE-2026","bid_process",8);
}
List<Object> items = page == 1 || body.contains("重复页") ? List.of(first,second) : List.of(second,third);
if (body.contains("空结果")) items = List.of();
if (body.contains("分页上限")) items = List.of(
Map.of("bid_id",100000+page*2,"title","智慧水务第 "+page+" 页公告"),
Map.of("bid_id",100001+page*2,"title","智慧水务第 "+page+" 页公告"));
var data = Map.of("total",body.contains("空结果") ? 0 : body.contains("重复页") || body.contains("分页上限") ? 99 : 4,"items",items);
response = new Json().write(body.contains("未知费用") ? Map.of("success",true,"data",data)
: Map.of("success",true,"data",data,"meta",Map.of("cost_units",0.5)));
}
}
else if (path.equals("/search_bids")) response = "{\"success\":true,\"data\":{\"total\":1,\"items\":[{\"bid_id\":8240,\"title\":\"测试水务项目\",\"url\":\"https://example.com/bid/8240\"}]},\"meta\":{\"cost_units\":0.5}}";
else if (path.equals("/search_company")) response = "{\"data\":{\"total\":0,\"items\":[]}}";
else if (path.equals("/get_company_profile")) response = "{\"data\":{\"fullname\":\"已确认测试公司\"}}";
else if (path.equals("/get_bid_detail")) response = "{\"data\":{\"bid_id\":8240,\"title\":\"测试公告详情\"}}";
else if (path.equals("/v1/tools/search")) response = "{\"results\":[{\"title\":\"测试网页\",\"url\":\"https://example.com/source\",\"snippet\":\"公开网页摘要\"}]}";
else if (path.equals("/v1/tools/fetch")) response = "{\"title\":\"测试网页\",\"content\":\"公开网页正文\"}";
else if (path.equals("/account/balance")) response = "{\"success\":true,\"data\":{\"balance\":100}}";
else if (body.contains("\"response_format\"")) response = "{\"model\":\"test-json-model\",\"choices\":[{\"message\":{\"content\":\"{\\\"answer\\\":\\\"JSON测试\\\"}\"}}],\"usage\":{\"prompt_tokens\":8,\"completion_tokens\":5}}";
else if (body.contains("\"stream\":true")) {
response = "data: {\"model\":\"test-actual-model\",\"choices\":[{\"delta\":{\"content\":\"真实片段\",\"reasoning_content\":\"private-test-reasoning\"}}]}\n\n"
+ "data: {\"usage\":{\"prompt_tokens\":9,\"completion_tokens\":4},\"choices\":[]}\n\ndata: [DONE]\n\n";
} else response = "{\"model\":\"test-actual-model\",\"choices\":[{\"message\":{\"content\":\"测试回复\",\"reasoning_content\":\"private-test-reasoning\"}}],\"usage\":{\"prompt_tokens\":7,\"completion_tokens\":3}}";
exchange.getResponseHeaders().set("Content-Type", "application/json");
byte[] bytes = response.getBytes(StandardCharsets.UTF_8);
exchange.sendResponseHeaders(code, bytes.length); exchange.getResponseBody().write(bytes); exchange.close();
});
upstream.start();
String url = "http://127.0.0.1:" + upstream.getAddress().getPort();
registry.add("rz.zlbx-base-url", () -> url);
registry.add("rz.deepseek-base-url", () -> url);
registry.add("rz.request-timeout-seconds", () -> 3);
registry.add("rz.search-page-size", () -> 2);
}
@AfterAll static void stopUpstream() { upstream.stop(0); }
private String owner() { return jdbc.queryForObject("SELECT id FROM app_user WHERE username='admin'", String.class); }
private TaskRequest request(TaskRequest.Operation op, String input, boolean confirmed) {
return new TaskRequest(op, op.name().startsWith("COMPANY_") ? TaskRequest.Workflow.COMPANY_INTEL : TaskRequest.Workflow.TENDER_SEARCH,
input, confirmed, 1, BigDecimal.ONE);
}
private String create(TaskRequest r) { return tasks.create(owner(), UUID.randomUUID().toString(), r).get("id").toString(); }
private Map<String,Object> settled(String id) {
await().atMost(java.time.Duration.ofSeconds(10)).until(() -> {
String state = tasks.get(owner(), id).get("status").toString();
return TaskService.terminal(state) || state.startsWith("WAITING_");
});
return tasks.get(owner(), id);
}
@Test
void contextLoads() {
assertThat(jdbc.queryForObject("SELECT COUNT(*) FROM flyway_schema_history WHERE success=TRUE AND version IS NOT NULL", Integer.class)).isEqualTo(7);
assertThat(jdbc.queryForObject("SELECT password_hash FROM app_user WHERE username='admin'", String.class)).startsWith("$2");
}
@Test void anonymousCannotReadPrivateResources() throws Exception {
for (String path : List.of("/api/company-profile", "/api/agent/tasks", "/api/agent/tasks/missing/events", "/api/files/missing", "/api/watch"))
mvc.perform(get(path)).andExpect(status().isUnauthorized());
}
@Test void loginRequiresCorrectPasswordAndRealCsrfAndLogoutInvalidatesSession() throws Exception {
mvc.perform(post("/api/auth/login").param("username", "admin").param("password", "anything")).andExpect(status().isForbidden());
mvc.perform(post("/api/auth/login").with(csrf()).param("username", "admin").param("password", "incorrect")).andExpect(status().isUnauthorized());
var bootstrap = mvc.perform(get("/api/auth/csrf")).andExpect(status().isOk()).andReturn();
var token = json.read(bootstrap.getResponse().getContentAsString());
var session = (MockHttpSession) bootstrap.getRequest().getSession();
var login = mvc.perform(post("/api/auth/login").session(session).header(token.path("headerName").asText(), token.path("token").asText())
.param("username", "admin").param("password", "test-only-admin-pass-2026")).andExpect(status().isOk()).andReturn();
session = (MockHttpSession) login.getRequest().getSession();
mvc.perform(get("/api/auth/me").session(session)).andExpect(jsonPath("$.username").value("admin"));
var refresh = mvc.perform(get("/api/auth/csrf").session(session)).andReturn();
token = json.read(refresh.getResponse().getContentAsString());
mvc.perform(post("/api/auth/logout").session(session).header(token.path("headerName").asText(), token.path("token").asText())).andExpect(status().isOk());
assertThat(session.isInvalid()).isTrue();
mvc.perform(get("/api/auth/me")).andExpect(status().isUnauthorized());
}
@Test void profileIsSavedWithServerVersionCompletionAndStaleWriteProtection() throws Exception {
var read = mvc.perform(get("/api/company-profile").with(user("admin"))).andReturn();
var doc = (tools.jackson.databind.node.ObjectNode) json.read(read.getResponse().getContentAsString());
doc.put("companyName", "测试水务公司"); doc.put("mainBusiness", "智慧水务"); doc.put("completed", false);
var saved = mvc.perform(put("/api/company-profile").with(user("admin")).with(csrf()).contentType("application/json").content(doc.toString()))
.andExpect(status().isOk()).andExpect(jsonPath("$.completed").value(true)).andReturn();
long version = json.read(saved.getResponse().getContentAsString()).path("version").asLong();
mvc.perform(get("/api/company-profile").with(user("admin"))).andExpect(jsonPath("$.version").value(version)).andExpect(jsonPath("$.companyName").value("测试水务公司"));
mvc.perform(put("/api/company-profile").with(user("admin")).with(csrf()).contentType("application/json").content(doc.toString()))
.andExpect(status().isConflict());
doc.put("version", version); doc.set("matchWeights", json.read("{\"business\":0,\"region\":0,\"amount\":0,\"track\":0}"));
mvc.perform(put("/api/company-profile").with(user("admin")).with(csrf()).contentType("application/json").content(doc.toString()))
.andExpect(status().isBadRequest());
}
@Test void concurrentIdempotencyCreatesExactlyOneActualCall() throws Exception {
String key = UUID.randomUUID().toString();
var r = request(TaskRequest.Operation.BID_SEARCH, "幂等水务", false);
List<Future<Map<String,Object>>> futures = new ArrayList<>();
try (var pool = Executors.newFixedThreadPool(4)) {
for (int i=0;i<4;i++) futures.add(pool.submit(() -> tasks.create(owner(), key, r)));
Set<String> ids = new HashSet<>(); for (var f : futures) ids.add(f.get().get("id").toString());
assertThat(ids).hasSize(1);
var task = settled(ids.iterator().next());
assertThat(task.get("status")).isEqualTo("SUCCEEDED");
assertThat((List<?>) task.get("calls")).hasSize(1);
assertThat(task.toString()).contains("0.5000");
assertThat(CLIENTS.values()).contains("zlbx-bidding/2.3.0");
}
assertThatThrownBy(() -> tasks.create(owner(), key, request(TaskRequest.Operation.BID_SEARCH, "不同条件", false)))
.isInstanceOf(com.example.rzgb.common.ApiException.class).hasMessageContaining("相同幂等键");
}
@Test void entityConfirmationDoesNotCallUntilExplicitResumeAndResumeIsIdempotent() {
String id = create(request(TaskRequest.Operation.COMPANY_PROFILE, "待确认公司", false));
assertThat(settled(id).get("status")).isEqualTo("WAITING_ENTITY");
assertThat((List<?>) tasks.get(owner(), id).get("calls")).isEmpty();
var confirmed = request(TaskRequest.Operation.COMPANY_PROFILE, "已确认公司", true);
String key = UUID.randomUUID().toString();
tasks.resume(owner(), id, key, confirmed); tasks.resume(owner(), id, key, confirmed);
var task = settled(id);
assertThat(task.get("status")).isEqualTo("SUCCEEDED"); assertThat((List<?>) task.get("calls")).hasSize(1);
assertThat(CLIENTS.values()).contains("company-intel/1.0.2");
}
@Test void missingInputWaitsAndCanBeCancelledWithoutAnyCall() {
String id = create(request(TaskRequest.Operation.BID_SEARCH, "", false));
assertThat(settled(id).get("status")).isEqualTo("WAITING_INPUT");
tasks.cancel(owner(), id);
assertThat(tasks.get(owner(), id).get("status")).isEqualTo("CANCELLED");
assertThat((List<?>) tasks.get(owner(), id).get("calls")).isEmpty();
}
@Test void distinguishesBusinessFailureBalanceAndEmptyResult() {
assertThat(settled(create(request(TaskRequest.Operation.COMPANY_SEARCH, "业务失败", false))).get("status")).isEqualTo("FAILED");
assertThat(settled(create(request(TaskRequest.Operation.COMPANY_SEARCH, "余额不足", false))).get("status")).isEqualTo("WAITING_BUDGET");
var empty = settled(create(request(TaskRequest.Operation.COMPANY_SEARCH, "无匹配公司", false)));
assertThat(empty.get("status")).isEqualTo("SUCCEEDED");
assertThat(empty.toString()).contains("cost_units=null");
var limited = settled(create(request(TaskRequest.Operation.MODEL_TEXT, "限流", false)));
assertThat(limited.get("status")).isEqualTo("FAILED"); assertThat(limited.toString()).contains("UPSTREAM_RATE_LIMIT");
}
@Test void realStreamContentAndUsageAreSavedWithoutPrivateReasoning() {
String id = create(request(TaskRequest.Operation.MODEL_STREAM, "测试真实流式", false));
var task = settled(id);
assertThat(task.get("status")).isEqualTo("SUCCEEDED");
assertThat(task.toString()).contains("真实片段", "test-actual-model", "input_tokens=9").doesNotContain("private-test-reasoning");
var events = tasks.events(owner(), id, 0);
assertThat(events.toString()).contains("REPORT_FRAGMENT", "真实片段").doesNotContain("private-test-reasoning");
}
@Test void eventReplayIsOrderedAndSseReconnectDoesNotCreateAnotherCall() throws Exception {
String id = create(request(TaskRequest.Operation.ZLBX_BALANCE, "", false)); settled(id);
var all = tasks.events(owner(), id, 0);
long first = ((Number) all.getFirst().get("id")).longValue();
assertThat(tasks.events(owner(), id, first)).hasSize(all.size()-1);
long previous = 0; for (var event : all) { assertThat(((Number) event.get("id")).longValue()).isGreaterThan(previous); previous = ((Number) event.get("id")).longValue(); }
var result = mvc.perform(get("/api/agent/tasks/"+id+"/events").with(user("admin")).header("Last-Event-ID", first))
.andExpect(org.springframework.test.web.servlet.result.MockMvcResultMatchers.request().asyncStarted()).andReturn();
result.getAsyncResult(5000);
mvc.perform(asyncDispatch(result)).andExpect(status().isOk()).andExpect(content().contentTypeCompatibleWith("text/event-stream"));
assertThat(result.getResponse().getContentAsString()).contains("event:task-event", "event:idle");
assertThat((List<?>) tasks.get(owner(), id).get("calls")).hasSize(1);
}
@Test void taskOwnershipAndWatchCascadeAreEnforced() throws Exception {
String id = create(request(TaskRequest.Operation.BID_SEARCH, "关注水务", false)); settled(id);
String other = UUID.randomUUID().toString();
jdbc.update("INSERT INTO app_user(id,username,password_hash) VALUES(?,?,'test-only')", other, other);
mvc.perform(get("/api/agent/tasks/"+id).with(user(other))).andExpect(status().isNotFound());
mvc.perform(post("/api/agent/tasks/"+id+"/cancel").with(user(other)).with(csrf())).andExpect(status().isNotFound());
for (int i=0;i<2;i++) mvc.perform(post("/api/watch/zlbx-8240").with(user("admin")).with(csrf())).andExpect(status().isOk());
assertThat(jdbc.queryForObject("SELECT COUNT(*) FROM watch_record WHERE user_id=?", Integer.class, owner())).isEqualTo(1);
mvc.perform(get("/api/watch/zlbx-8240/history").with(user(other))).andExpect(status().isNotFound());
mvc.perform(delete("/api/watch/zlbx-8240").with(user("admin")).with(csrf())).andExpect(status().isOk());
assertThat(jdbc.queryForObject("SELECT COUNT(*) FROM watch_history", Integer.class)).isZero();
assertThat(jdbc.queryForObject("SELECT COUNT(*) FROM project WHERE id='zlbx-8240'", Integer.class)).isEqualTo(1);
}
@Test void rejectsInvalidBudgetsAndPrivateFetchUrl() throws Exception {
var r = new TaskRequest(TaskRequest.Operation.MODEL_TEXT, TaskRequest.Workflow.TENDER_SEARCH, "hello", false, properties.maxCalls()+1, BigDecimal.ONE);
mvc.perform(post("/api/agent/tasks").with(user("admin")).with(csrf()).header("Idempotency-Key", UUID.randomUUID())
.contentType("application/json").content(json.write(r))).andExpect(status().isBadRequest());
assertThatThrownBy(() -> com.example.rzgb.provider.ProviderClient.publicUrl("http://127.0.0.1/private"))
.isInstanceOf(com.example.rzgb.common.ApiException.class);
}
@Test void missingCredentialsAreDetectedBeforeAnyHttpRequest() {
var configuration = (tools.jackson.databind.node.ObjectNode) json.read(json.write(properties));
configuration.put("zlbxApiKey", ""); configuration.put("deepseekApiKey", "");
var client = new com.example.rzgb.provider.ProviderClient(json.convert(configuration.toString(), com.example.rzgb.config.AppProperties.class), json);
assertThat(client.question(request(TaskRequest.Operation.ZLBX_BALANCE, "", false))).contains("ZLBX_API_KEY");
assertThat(client.question(request(TaskRequest.Operation.MODEL_TEXT, "hello", false))).contains("DEEPSEEK_API_KEY");
}
@Test void independentModelJsonWebVisionAndBidDetailContractsAreSupported() {
for (var op : List.of(TaskRequest.Operation.MODEL_TEXT, TaskRequest.Operation.MODEL_JSON,
TaskRequest.Operation.WEB_SEARCH, TaskRequest.Operation.WEB_FETCH, TaskRequest.Operation.VISION, TaskRequest.Operation.BID_DETAIL)) {
String input = op == TaskRequest.Operation.WEB_FETCH ? "https://93.184.216.34/public" : op == TaskRequest.Operation.BID_DETAIL ? "8240" : "协议自测";
var task = settled(create(request(op, input, false)));
assertThat(task.get("status")).as(op.name()).isEqualTo("SUCCEEDED");
assertThat((List<?>) task.get("calls")).hasSize(1);
}
assertThat(CLIENTS.keySet().stream().anyMatch(body -> body.contains("data:image/png;base64,"))).isTrue();
}
@Test void restartRecoveryMarksUnknownCallsWithoutDispatchingThemAgain() throws Exception {
String id = create(request(TaskRequest.Operation.BID_SEARCH, "", false)); settled(id);
jdbc.update("UPDATE agent_task SET status='RUNNING' WHERE id=?", id);
jdbc.update("INSERT INTO tool_call(id,task_id,provider,tool_name,client_version,status) VALUES(?,?,'ZLBX','BID_SEARCH','zlbx-bidding/2.3.0','STARTED')", UUID.randomUUID().toString(), id);
context.getBean("recoverInterruptedTasks", org.springframework.boot.ApplicationRunner.class)
.run(new org.springframework.boot.DefaultApplicationArguments());
var recovered = tasks.get(owner(), id);
assertThat(recovered.get("status")).isEqualTo("PARTIAL");
assertThat(recovered.toString()).contains("UNKNOWN", "RESTART_INTERRUPTED");
assertThat((List<?>) recovered.get("calls")).hasSize(1);
}
private TaskRequest opportunity(String marker, int calls) {
var today = java.time.LocalDate.now(java.time.ZoneId.of("Asia/Shanghai"));
var query = new OpportunityQuery(List.of("智慧水务","集成获客"+marker),today.minusDays(89),today,List.of(1,2,4,7,8),
OpportunityQuery.Preference.REGION,List.of("浙江"),new BigDecimal("80"),new BigDecimal("120"));
return new TaskRequest(TaskRequest.Operation.OPPORTUNITY_SEARCH,TaskRequest.Workflow.TENDER_SEARCH,"",false,calls,new BigDecimal("5"),query);
}
@Test void realPaginatedWorkflowRanksAllReadCandidatesAndKeepsUnknownAmounts() {
String id = create(opportunity("完整召回",3));
var task = settled(id);
var report = json.read(json.write(task.get("result")));
assertThat(task.get("status")).isEqualTo("SUCCEEDED");
assertThat((List<?>)task.get("calls")).hasSize(2);
assertThat(report.path("scope").path("platformTotal").asInt()).isEqualTo(4);
assertThat(report.path("scope").path("fetchedCount").asInt()).isEqualTo(4);
assertThat(report.path("scope").path("uniqueCount").asInt()).isEqualTo(3);
assertThat(report.path("scope").path("complete").asBoolean()).isTrue();
assertThat(report.path("items").path(0).path("facts").path("region").asText()).isEqualTo("浙江");
assertThat(report.path("items").toString()).contains("安徽","江苏","预算未披露");
assertThat(task.toString()).contains("记录").doesNotContain("COMPANY_PROFILE","get_company_profile");
for (String body : CLIENTS.keySet().stream().filter(text -> text.contains("完整召回")).toList()) {
var request = json.read(body);
assertThat(request.has("provinces")).isFalse();
assertThat(request.has("min_amount")).isFalse();
assertThat(request.has("max_amount")).isFalse();
}
assertThat(evidence.list(id)).hasSize(3).allSatisfy(item -> assertThat(item.get("verified")).isEqualTo(true));
assertThat(evidence.list(id).toString()).contains("?sk=public-test-signature");
}
@Test void budgetPauseResumesAtNextPageAndNeverChangesFrozenConditions() {
var original = opportunity("预算续页",1);
String id = create(original);
var paused = settled(id);
assertThat(paused.get("status")).isEqualTo("WAITING_BUDGET");
assertThat((List<?>)paused.get("calls")).hasSize(1);
assertThat(json.read(json.write(paused.get("result"))).path("scope").path("complete").asBoolean()).isFalse();
assertThatThrownBy(() -> tasks.resume(owner(),id,UUID.randomUUID().toString(),opportunity("更改条件",3)))
.isInstanceOf(com.example.rzgb.common.ApiException.class).hasMessageContaining("不能改写");
var resumed = new TaskRequest(original.operation(),original.workflow(),"",false,3,new BigDecimal("5"),original.opportunity());
String command = UUID.randomUUID().toString();
tasks.resume(owner(),id,command,resumed); tasks.resume(owner(),id,command,resumed);
assertThat(settled(id).get("status")).isEqualTo("SUCCEEDED");
assertThat((List<?>)tasks.get(owner(),id).get("calls")).hasSize(2);
assertThat(CLIENTS.keySet().stream().filter(body -> body.contains("预算续页")).count()).isEqualTo(2);
}
@Test void unknownCostAndRepeatedPagesStopWithoutPretendingFullCoverage() {
var unknown = settled(create(opportunity("未知费用",3)));
assertThat(unknown.get("status")).isEqualTo("PARTIAL");
assertThat((List<?>)unknown.get("calls")).hasSize(1);
assertThat(unknown.toString()).contains("COST_UNKNOWN");
var repeated = settled(create(opportunity("重复页",3)));
assertThat(repeated.get("status")).isEqualTo("PARTIAL");
assertThat((List<?>)repeated.get("calls")).hasSize(2);
assertThat(repeated.toString()).contains("REPEATED_PAGE");
}
@Test void failedLaterPageKeepsEarlierEvidenceAndRecordsActualFailure() {
var task = settled(create(opportunity("后页失败",3)));
assertThat(task.get("status")).isEqualTo("PARTIAL");
assertThat((List<?>)task.get("calls")).hasSize(2);
assertThat(json.read(json.write(task.get("result"))).path("items").size()).isEqualTo(2);
assertThat(task.toString()).contains("UPSTREAM_HTTP_502","SUCCEEDED","FAILED");
}
@Test void reportRefusesMutatedSnapshotsAndCrossTaskCitations() {
String id = create(opportunity("证据校验",3)); settled(id);
String evidenceId = evidence.list(id).getFirst().get("id").toString();
String other = create(opportunity("另一任务",3)); settled(other);
assertThatThrownBy(() -> evidence.requireVerified(other,List.of(evidenceId)))
.isInstanceOf(com.example.rzgb.common.ApiException.class).hasMessageContaining("引用不存在");
jdbc.update("UPDATE evidence SET excerpt='篡改后的事实' WHERE id=?",evidenceId);
assertThatThrownBy(() -> tasks.get(owner(),id)).isInstanceOf(com.example.rzgb.common.ApiException.class).hasMessageContaining("报告已停止展示");
// 即使引用编号存在,候选快照也必须与证据重新标准化出的事实完全一致。
jdbc.update("UPDATE search_item SET snapshot=REPLACE(snapshot,'智慧水务集成获客项目','没有依据的高收益项目') WHERE batch_id=?",other);
assertThatThrownBy(() -> tasks.get(owner(),other)).isInstanceOf(com.example.rzgb.common.ApiException.class);
}
@Test void filteredTaskHistoryAndEvidenceAreOnlyVisibleToOwner() throws Exception {
String id = create(opportunity("归属范围",3)); settled(id);
mvc.perform(get("/api/agent/tasks").param("operation","OPPORTUNITY_SEARCH").with(user("admin")))
.andExpect(status().isOk()).andExpect(content().string(org.hamcrest.Matchers.containsString(id)));
mvc.perform(get("/api/agent/tasks/"+id+"/report").with(user("admin")))
.andExpect(status().isOk()).andExpect(jsonPath("$.result.referencesVerified").value(true));
String stranger = UUID.randomUUID().toString();
jdbc.update("INSERT INTO app_user(id,username,password_hash) VALUES(?,?,'test-only')",stranger,stranger);
mvc.perform(get("/api/agent/tasks/"+id+"/report").with(user(stranger))).andExpect(status().isNotFound());
}
@Test void pageLimitIsExplicitAndEmptyResultsAreNotServiceFailures() {
var limited = settled(create(opportunity("分页上限",5)));
assertThat(limited.get("status")).isEqualTo("PARTIAL");
assertThat((List<?>)limited.get("calls")).hasSize(5);
var scope = json.read(json.write(limited.get("result"))).path("scope");
assertThat(scope.path("stopReason").asText()).isEqualTo("PAGE_LIMIT");
assertThat(scope.path("uniqueCount").asInt()).isEqualTo(10);
assertThat(scope.path("complete").asBoolean()).isFalse();
var empty = settled(create(opportunity("空结果",3)));
assertThat(empty.get("status")).isEqualTo("SUCCEEDED");
assertThat(json.read(json.write(empty.get("result"))).path("items").isEmpty()).isTrue();
}
@Test void cancellationPreservesInFlightCostAndNeverStartsNextPage() {
String id = create(opportunity("取消分页",3));
await().atMost(java.time.Duration.ofSeconds(5)).until(() -> !((List<?>)tasks.get(owner(),id).get("calls")).isEmpty());
tasks.cancel(owner(),id);
await().atMost(java.time.Duration.ofSeconds(5)).until(() -> {
var calls = (List<?>)tasks.get(owner(),id).get("calls");
return calls.size() == 1 && ((Map<?,?>)calls.getFirst()).get("status").equals("SUCCEEDED");
});
var task = tasks.get(owner(),id);
assertThat(task.get("status")).isEqualTo("CANCELLED");
assertThat((List<?>)task.get("calls")).hasSize(1);
assertThat(task.toString()).contains("0.5000");
}
/** D2 关注事务:备注独立留痕、任意恢复、幂等重放、旧版本拒绝,标签与账号隔离。 */
@Test void watchChangesAreAtomicVersionedIdempotentAndTagsStayPrivate() throws Exception {
String project="watch-test-"+UUID.randomUUID();
jdbc.update("INSERT INTO project(id,source_id,document) VALUES(?,?,?)",project,project,"{\"title\":\"测试关注事务\"}");
mvc.perform(post("/api/watch/"+project).with(user("admin")).with(csrf())).andExpect(status().isOk());
String watch=jdbc.queryForObject("SELECT id FROM watch_record WHERE project_id=? AND user_id=?",String.class,project,owner());
String key=UUID.randomUUID().toString();
String body=json.write(Map.of("status","准备投标","note","开始备标","version",1));
for(int n=0;n<2;n++) mvc.perform(post("/api/watch/"+project+"/changes").with(user("admin")).with(csrf())
.header("Idempotency-Key",key).contentType("application/json").content(body)).andExpect(status().isOk()).andExpect(jsonPath("$.version").value(2));
assertThat(jdbc.queryForObject("SELECT COUNT(*) FROM watch_history WHERE watch_id=?",Integer.class,watch)).isEqualTo(2);
mvc.perform(post("/api/watch/"+project+"/changes").with(user("admin")).with(csrf()).header("Idempotency-Key",key)
.contentType("application/json").content(body.replace("开始备标","不同命令"))).andExpect(status().isConflict());
mvc.perform(post("/api/watch/"+project+"/changes").with(user("admin")).with(csrf()).header("Idempotency-Key",UUID.randomUUID().toString())
.contentType("application/json").content(body)).andExpect(status().isConflict());
long version=2;
for(String state:List.of("已报名","已提交投标文件","已中标","未中标","已流标","暂不考虑","已关注")) {
mvc.perform(post("/api/watch/"+project+"/changes").with(user("admin")).with(csrf()).header("Idempotency-Key",UUID.randomUUID().toString())
.contentType("application/json").content(json.write(Map.of("status",state,"note",state,"version",version))))
.andExpect(status().isOk()).andExpect(jsonPath("$.version").value(++version));
}
mvc.perform(post("/api/watch/"+project+"/changes").with(user("admin")).with(csrf()).header("Idempotency-Key",UUID.randomUUID().toString())
.contentType("application/json").content(json.write(Map.of("note","单独编辑备注","version",version))))
.andExpect(status().isOk()).andExpect(jsonPath("$.status").value("已关注")); version++;
assertThat(jdbc.queryForMap("SELECT status,note,version FROM watch_record WHERE id=?",watch))
.containsEntry("status","已关注").containsEntry("note","单独编辑备注").containsEntry("version",version);
String tagName="重点-"+UUID.randomUUID();
var tagResponse=mvc.perform(post("/api/tags").with(user("admin")).with(csrf()).contentType("application/json")
.content(json.write(Map.of("name",tagName)))).andExpect(status().isOk()).andReturn();
String tag=json.read(tagResponse.getResponse().getContentAsString()).path("id").asText();
mvc.perform(put("/api/watch/"+project+"/tags").with(user("admin")).with(csrf()).header("Idempotency-Key",UUID.randomUUID().toString())
.contentType("application/json").content(json.write(Map.of("tags",List.of(tagName),"version",version))))
.andExpect(status().isOk()).andExpect(jsonPath("$.version").value(version+1));
mvc.perform(get("/api/watch").param("group","跟进中").param("tag",tagName).with(user("admin")))
.andExpect(status().isOk()).andExpect(jsonPath("$[0].projectId").value(project));
String outsider="outsider-"+UUID.randomUUID();
jdbc.update("INSERT INTO app_user(id,username,password_hash) VALUES(?,?,?)",UUID.randomUUID().toString(),outsider,"unused-test-hash");
mvc.perform(get("/api/watch/"+project+"/history").with(user(outsider))).andExpect(status().isNotFound());
mvc.perform(delete("/api/tags/"+tag).with(user(outsider)).with(csrf())).andExpect(status().isOk());
assertThat(jdbc.queryForObject("SELECT COUNT(*) FROM watch_tag WHERE watch_id=?",Integer.class,watch)).isEqualTo(1);
mvc.perform(delete("/api/tags/"+tag).with(user("admin")).with(csrf())).andExpect(status().isOk());
assertThat(jdbc.queryForObject("SELECT COUNT(*) FROM watch_tag WHERE watch_id=?",Integer.class,watch)).isZero();
mvc.perform(delete("/api/watch/"+project).with(user("admin")).with(csrf())).andExpect(status().isOk());
assertThat(jdbc.queryForObject("SELECT COUNT(*) FROM watch_history WHERE watch_id=?",Integer.class,watch)).isZero();
assertThat(jdbc.queryForObject("SELECT COUNT(*) FROM project WHERE id=?",Integer.class,project)).isEqualTo(1);
}
/** 执行与版本绑定;编辑/删除方案、修改档案及临时重排都不能改变旧快照或额外收费。 */
@Test void schemesFreezeRunsAndReadOnlyPreferenceViewKeepsSameCandidates() throws Exception {
var original=opportunity("方案快照",3);
String body=json.write(Map.of("name","D2测试方案","conditions",original.opportunity(),"version",0));
var saved=mvc.perform(post("/api/search-schemes").with(user("admin")).with(csrf()).contentType("application/json").content(body))
.andExpect(status().isOk()).andReturn();
String scheme=json.read(saved.getResponse().getContentAsString()).path("id").asText(),key=UUID.randomUUID().toString();
String run=mvc.perform(post("/api/search-schemes/"+scheme+"/runs").with(user("admin")).with(csrf()).header("Idempotency-Key",key))
.andExpect(status().isOk()).andReturn().getResponse().getContentAsString();
String id=json.read(run).path("id").asText(); var first=settled(id); String frozen=json.write(first.get("result"));
mvc.perform(put("/api/search-schemes/"+scheme).with(user("admin")).with(csrf()).contentType("application/json")
.content(json.write(Map.of("name","改名方案","conditions",opportunity("新方案内容",3).opportunity(),"version",1))))
.andExpect(status().isOk()).andExpect(jsonPath("$.version").value(2));
mvc.perform(post("/api/search-schemes/"+scheme+"/runs").with(user("admin")).with(csrf()).header("Idempotency-Key",key))
.andExpect(status().isOk()).andExpect(jsonPath("$.id").value(id));
assertThat(json.write(tasks.get(owner(),id).get("result"))).isEqualTo(frozen);
var view=mvc.perform(post("/api/searches/"+id+"/view").with(user("admin")).with(csrf()).contentType("application/json")
.content("{\"preference\":\"AMOUNT\",\"regions\":[],\"minWan\":80,\"maxWan\":120}"))
.andExpect(status().isOk()).andReturn();
assertThat(json.read(view.getResponse().getContentAsString()).path("items").size()).isEqualTo(3);
mvc.perform(get("/api/searches/"+id+"/items").param("page","2").param("size","2").with(user("admin")))
.andExpect(status().isOk()).andExpect(jsonPath("$.items.length()").value(1));
mvc.perform(delete("/api/search-schemes/"+scheme).with(user("admin")).with(csrf())).andExpect(status().isOk());
assertThat(json.write(tasks.get(owner(),id).get("result"))).isEqualTo(frozen);
assertThat(jdbc.queryForObject("SELECT COUNT(*) FROM tool_call WHERE task_id=?",Integer.class,id)).isEqualTo(2);
assertThat(jdbc.queryForMap("SELECT scheme_name,scheme_version FROM search_run WHERE task_id=?",id))
.containsEntry("scheme_name","D2测试方案").containsEntry("scheme_version",1L);
jdbc.update("UPDATE search_item SET ranking_snapshot=REPLACE(ranking_snapshot,'标题命中','无依据排序') WHERE batch_id=?",id);
assertThatThrownBy(() -> tasks.get(owner(),id)).hasMessageContaining("排序快照已变化");
}
@Test void ordinarySearchUsesPublishOrderAndFrozenProfileSurvivesLaterEdits() {
var lead=opportunity("普通检索",3); var q=lead.opportunity();
var query=new OpportunityQuery(q.keywords(),q.beginDate(),q.endDate(),q.stages(),q.preference(),q.preferredRegions(),q.budgetMinWan(),q.budgetMaxWan(),
OpportunityQuery.Mode.SEARCH,OpportunityQuery.KeywordMode.ANY,List.of(),null,null);
String id=create(new TaskRequest(lead.operation(),lead.workflow(),"",false,3,new BigDecimal("5"),query));
var result=settled(id); var report=json.read(json.write(result.get("result")));
assertThat(report.path("items").path(0).path("facts").path("sourceId").asText()).isEqualTo("99102");
String before=json.write(result.get("result"));
// 故意修改当前档案版本;旧报告必须仍读取任务创建时的冻结档案。
var old=jdbc.queryForList("SELECT document FROM company_profile WHERE user_id=?",String.class,owner());
if(old.isEmpty()) {
var temporary=com.example.rzgb.profile.CompanyProfile.empty().saved(9999,java.time.Instant.now());
jdbc.update("INSERT INTO company_profile(user_id,document,version,completed,updated_at) VALUES(?,?,9999,FALSE,CURRENT_TIMESTAMP)",owner(),json.write(temporary));
try { assertThat(json.write(tasks.get(owner(),id).get("result"))).isEqualTo(before); }
finally { jdbc.update("DELETE FROM company_profile WHERE user_id=?",owner()); }
} else {
var updated=(tools.jackson.databind.node.ObjectNode)json.read(old.getFirst()); updated.put("version",9999);
jdbc.update("UPDATE company_profile SET document=? WHERE user_id=?",updated.toString(),owner());
try { assertThat(json.write(tasks.get(owner(),id).get("result"))).isEqualTo(before); }
finally { jdbc.update("UPDATE company_profile SET document=? WHERE user_id=?",old.getFirst(),owner()); }
}
jdbc.update("UPDATE search_item SET analysis_snapshot=REPLACE(analysis_snapshot,'规则匹配分','篡改分数') WHERE batch_id=?",id);
assertThatThrownBy(() -> tasks.get(owner(),id)).hasMessageContaining("快照已变化");
}
/** 第一页没有预算命中仍应继续分页;地区与发布时间仍随每页请求发给供应商。 */
@Test void ordinarySearchRetainsDateAndRegionWhileFilteringBudgetAcrossPages() throws Exception {
var today=java.time.LocalDate.now(java.time.ZoneId.of("Asia/Shanghai"));
var query=new OpportunityQuery(List.of("智慧水务监测"),today.minusDays(29),today,List.of(1,2,4,7,8),
OpportunityQuery.Preference.COMPREHENSIVE,List.of(),null,null,OpportunityQuery.Mode.SEARCH,
OpportunityQuery.KeywordMode.ANY,List.of("江苏"),new BigDecimal("75"),new BigDecimal("90"));
String body=json.write(Map.of("conditions",query,"maxCalls",1,"maxCostUnits",5));
var response=mvc.perform(post("/api/searches").with(user("admin")).with(csrf())
.header("Idempotency-Key",UUID.randomUUID().toString()).contentType("application/json").content(body))
.andExpect(status().isOk()).andReturn();
String id=json.read(response.getResponse().getContentAsString()).path("id").asText();
var paused=settled(id);
assertThat(paused.get("status")).isEqualTo("WAITING_BUDGET");
assertThat(json.read(json.write(paused.get("result"))).path("items")).isEmpty();
mvc.perform(post("/api/searches/"+id+"/continue").with(user("admin")).with(csrf())
.header("Idempotency-Key",UUID.randomUUID().toString()).contentType("application/json")
.content(json.write(Map.of("conditions",query,"maxCalls",3,"maxCostUnits",5)))).andExpect(status().isOk());
var result=settled(id);
assertThat(result.get("status")).isEqualTo("SUCCEEDED");
var report=json.read(json.write(result.get("result")));
assertThat(report.path("items")).hasSize(1);
assertThat(report.path("items").path(0).path("facts").path("sourceId").asText()).isEqualTo("99103");
assertThat(report.path("scope").path("fetchedCount").asInt()).isEqualTo(4);
var sent=CLIENTS.keySet().stream().map(json::read)
.filter(data -> data.path("keywords").toString().equals("[\"智慧水务监测\"]")).toList();
assertThat(sent).hasSize(2).allSatisfy(data -> {
assertThat(data.path("provinces").toString()).isEqualTo("[\"江苏\"]");
assertThat(data.has("min_amount") || data.has("max_amount")).isFalse();
assertThat(data.path("begin_date").asText()).isEqualTo(today.minusDays(29).toString());
assertThat(data.path("end_date").asText()).isEqualTo(today.toString());
});
assertThat(sent.stream().map(data -> data.path("page").asInt())).containsExactlyInAnyOrder(1,2);
}
@Test void ordinaryBudgetUsesDisplayedYuanAndWanValuesWithInclusiveBounds() {
var today=java.time.LocalDate.now(java.time.ZoneId.of("Asia/Shanghai"));
for (var range : List.of(List.of("500","2000"),List.of("100","1000"))) {
var query=new OpportunityQuery(List.of("预算交集验收","水务"),today.minusDays(29),today,List.of(4),null,null,null,null,
OpportunityQuery.Mode.SEARCH,OpportunityQuery.KeywordMode.ALL,List.of("江苏"),new BigDecimal(range.getFirst()),new BigDecimal(range.getLast()));
var result=settled(create(new TaskRequest(TaskRequest.Operation.OPPORTUNITY_SEARCH,TaskRequest.Workflow.TENDER_SEARCH,"",false,3,BigDecimal.TEN,query)));
assertThat(result.get("status")).isEqualTo("SUCCEEDED");
var report=json.read(json.write(result.get("result")));
List<String> amounts=new ArrayList<>();
for(var item:report.path("items")) amounts.add(item.path("facts").path("budgetWan").decimalValue().stripTrailingZeros().toPlainString());
if(range.getFirst().equals("500")) assertThat(amounts).containsExactlyInAnyOrder("500","727.562","2000");
else assertThat(amounts).containsExactlyInAnyOrder("207.5","313.198","727.562","307.962","500");
}
assertThat(CLIENTS.keySet().stream().filter(body->body.contains("预算交集验收")).map(json::read).toList()).hasSize(3).allSatisfy(request->{
assertThat(request.path("provinces").toString()).isEqualTo("[\"江苏\"]");
assertThat(request.path("keyword_groups").path(0).path("keywords").toString()).isEqualTo("[\"水务\"]");
assertThat(request.has("min_money") || request.has("max_money")).isFalse();
assertThat(request.path("begin_date").asText()).isEqualTo(today.minusDays(29).toString());
});
}
/** 旧方案只在发现商机明确要求硬筛选时转换,原方案、日期及其他获客调用均保持原语义。 */
@Test void discoveryCanRunLegacySchemeWithStrictFiltersWithoutRewritingSavedConditions() throws Exception {
var base=opportunity("旧方案硬筛选",3).opportunity();
var query=new OpportunityQuery(base.keywords(),base.beginDate(),base.endDate(),base.stages(),
base.preference(),List.of("江苏"),new BigDecimal("50"),new BigDecimal("200"));
var saved=mvc.perform(post("/api/search-schemes").with(user("admin")).with(csrf()).contentType("application/json")
.content(json.write(Map.of("name","旧版地区预算方案","conditions",query,"version",0))))
.andExpect(status().isOk()).andReturn();
String scheme=json.read(saved.getResponse().getContentAsString()).path("id").asText();
String key=UUID.randomUUID().toString();
var response=mvc.perform(post("/api/search-schemes/"+scheme+"/runs").param("strictFilters","true")
.with(user("admin")).with(csrf()).header("Idempotency-Key",key)).andExpect(status().isOk()).andReturn();
String id=json.read(response.getResponse().getContentAsString()).path("id").asText();
var result=settled(id);
assertThat(result.get("status")).isEqualTo("SUCCEEDED");
var conditions=json.read(json.write(result.get("result"))).path("conditions");
assertThat(conditions.path("mode").asText()).isEqualTo("SEARCH");
assertThat(conditions.path("hardRegions").toString()).isEqualTo("[\"江苏\"]");
assertThat(conditions.path("hardMinWan").asInt()).isEqualTo(50);
assertThat(conditions.path("hardMaxWan").asInt()).isEqualTo(200);
assertThat(conditions.path("beginDate").asText()).isEqualTo(query.beginDate().toString());
assertThat(conditions.path("endDate").asText()).isEqualTo(query.endDate().toString());
var sent=CLIENTS.keySet().stream().filter(body -> body.contains("旧方案硬筛选")).map(json::read).toList();
assertThat(sent).hasSize(2).allSatisfy(data -> {
assertThat(data.path("provinces").toString()).isEqualTo("[\"江苏\"]");
assertThat(data.has("min_amount") || data.has("max_amount")).isFalse();
assertThat(data.path("begin_date").asText()).isEqualTo(query.beginDate().toString());
assertThat(data.path("end_date").asText()).isEqualTo(query.endDate().toString());
});
assertThat(jdbc.queryForObject("SELECT conditions FROM search_scheme WHERE id=?",String.class,scheme)).isEqualTo(json.write(query));
mvc.perform(post("/api/search-schemes/"+scheme+"/runs").param("strictFilters","true")
.with(user("admin")).with(csrf()).header("Idempotency-Key",key))
.andExpect(status().isOk()).andExpect(jsonPath("$.id").value(id));
var legacy=mvc.perform(post("/api/search-schemes/"+scheme+"/runs").with(user("admin")).with(csrf())
.header("Idempotency-Key",UUID.randomUUID().toString())).andExpect(status().isOk()).andReturn();
String legacyId=json.read(legacy.getResponse().getContentAsString()).path("id").asText();
assertThat(json.read(json.write(settled(legacyId).get("result"))).path("conditions").path("mode").asText()).isEqualTo("LEADS");
}
@Test void marketAggregationAndSampleHaveSeparateScopesAndResumeSkipsCompletedTools() {
var basic=opportunity("市场聚合",2); var q=basic.opportunity();
var query=new OpportunityQuery(q.keywords(),q.beginDate(),q.endDate(),q.stages(),q.preference(),List.of(),null,null,
OpportunityQuery.Mode.MARKET,OpportunityQuery.KeywordMode.ANY,List.of("浙江"),new BigDecimal("10"),null);
var request=new TaskRequest(basic.operation(),basic.workflow(),"",false,2,new BigDecimal("5"),query);
String id=create(request); var first=settled(id);
assertThat(first.get("status")).isEqualTo("WAITING_BUDGET");
assertThat(jdbc.queryForObject("SELECT COUNT(*) FROM market_snapshot WHERE task_id=?",Integer.class,id)).isEqualTo(2);
var resumed=new TaskRequest(basic.operation(),basic.workflow(),"",false,5,new BigDecimal("5"),query);
tasks.resume(owner(),id,UUID.randomUUID().toString(),resumed); var result=settled(id);
assertThat(result.get("status")).isEqualTo("SUCCEEDED");
assertThat(jdbc.queryForObject("SELECT COUNT(*) FROM tool_call WHERE task_id=?",Integer.class,id)).isEqualTo(5);
assertThat(jdbc.queryForObject("SELECT COUNT(*) FROM tool_call WHERE task_id=? AND tool_name='get_top_purchasers'",Integer.class,id)).isEqualTo(1);
var report=json.read(json.write(result.get("result")));
assertThat(report.path("market").path("platformAggregations").size()).isEqualTo(3);
assertThat(report.path("market").path("basis").asText()).contains("样本");
assertThat(report.path("scope").path("uniqueCount").asInt()).isEqualTo(3);
assertThat(report.path("market").toString()).contains("测试采购方","测试供应商","30");
assertThat(evidence.list(id)).hasSize(6).allSatisfy(item -> assertThat(item.get("verified")).isEqualTo(true));
for(String body:CLIENTS.keySet().stream().filter(value -> value.contains("市场聚合")).toList()) {
var data=json.read(body);
if(data.has("filters")) assertThat(data.path("filters").path("min_money").asInt()).isEqualTo(100000);
else if(data.has("limit")) assertThat(data.path("min_amount").asInt()).isEqualTo(100000);
}
}
@Test void reliableProjectNumberLinksStagesWithoutDroppingNoticeSources() {
String id=create(opportunity("阶段归并",3));
var report=json.read(json.write(settled(id).get("result")));
assertThat(report.path("items").size()).isEqualTo(3);
assertThat(report.path("stageChains").size()).isEqualTo(1);
assertThat(report.path("stageChains").path(0).path("notices").size()).isEqualTo(2);
assertThat(report.path("stageChains").toString()).contains("TEST-CODE-2026","99101","99103");
}
@Test void allKeywordWorkflowUsesAdvancedEndpointAndRecordsActualToolName() {
var basic=opportunity("AND工具契约",3); var q=basic.opportunity();
var query=new OpportunityQuery(q.keywords(),q.beginDate(),q.endDate(),q.stages(),q.preference(),q.preferredRegions(),null,null,
OpportunityQuery.Mode.SEARCH,OpportunityQuery.KeywordMode.ALL,List.of("浙江"),new BigDecimal("10"),null);
String id=create(new TaskRequest(basic.operation(),basic.workflow(),"",false,3,new BigDecimal("5"),query));
assertThat(settled(id).get("status")).isEqualTo("SUCCEEDED");
assertThat(jdbc.queryForList("SELECT DISTINCT tool_name FROM tool_call WHERE task_id=?",String.class,id)).containsExactly("query_bids_advanced");
assertThat(CLIENTS.keySet().stream().filter(body -> body.contains("AND工具契约")).map(json::read))
.allSatisfy(data -> { assertThat(data.has("keyword_groups")).isTrue(); assertThat(data.has("min_money") || data.has("min_amount")).isFalse(); });
}
}
package com.example.rzgb.auth;
import com.example.rzgb.config.AppProperties;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.UUID;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.SingleConnectionDataSource;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import static org.assertj.core.api.Assertions.*;
/** 单独验证管理员初始化,不启动应用或访问真实数据库、外部服务。 */
class AdminInitializationTests {
private SingleConnectionDataSource dataSource;
private JdbcTemplate jdbc;
private final BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
@BeforeEach void createDatabase() {
// 单连接维持本次测试的内存库;测试结束关闭连接即释放,不影响其他集成测试。
dataSource = new SingleConnectionDataSource("jdbc:h2:mem:" + UUID.randomUUID(), "sa", "", true);
jdbc = new JdbcTemplate(dataSource);
jdbc.execute("CREATE TABLE app_user(id VARCHAR(36), username VARCHAR(100), password_hash VARCHAR(255))");
}
@AfterEach void closeDatabase() { dataSource.destroy(); }
@Test void shortPasswordWorksAndRestartDoesNotResetIt() throws Exception {
initialize("123456");
String hash = jdbc.queryForObject("SELECT password_hash FROM app_user WHERE username='admin'", String.class);
assertThat(encoder.matches("123456", hash)).isTrue();
// 已有账号时,即使新环境未提供初始密码,也不能覆盖已保存的密码或再插入账号。
initialize(null);
assertThat(jdbc.queryForObject("SELECT COUNT(*) FROM app_user", Integer.class)).isEqualTo(1);
assertThat(jdbc.queryForObject("SELECT password_hash FROM app_user", String.class)).isEqualTo(hash);
}
@Test void missingPasswordAndBcryptOverflowDoNotCreateAnAccount() {
// 中文按 UTF-8 字节检查,防止字符数未超限但实际超出 BCrypt 输入上限。
for (String password : Arrays.asList(null, "", " ", "a".repeat(73), "密".repeat(25))) {
assertThatThrownBy(() -> initialize(password)).isInstanceOf(IllegalStateException.class);
assertThat(jdbc.queryForObject("SELECT COUNT(*) FROM app_user", Integer.class)).isZero();
}
}
private void initialize(String password) throws Exception {
var properties = new AppProperties(password, "https://example.com", "", "https://example.com", "", "test",
3, 4194304, 25, BigDecimal.valueOf(100), 50, 5, 20971520, 50, 20, 24, 180);
new SecurityConfig().initializeAdmin(jdbc, encoder, properties)
.run(new org.springframework.boot.DefaultApplicationArguments(new String[0]));
}
}
# 只在测试启用 H2,生产依然必须配置真实 MySQL,不提供默认测试账号。
spring:
datasource:
url: jdbc:h2:mem:rzgb;MODE=MySQL;DATABASE_TO_LOWER=TRUE;DB_CLOSE_DELAY=-1
username: sa
password:
flyway:
enabled: true
rz:
admin-password: test-only-admin-pass-2026
zlbx-api-key: test-only-provider-key
deepseek-api-key: test-only-model-key
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
APACHE POI SUBCOMPONENTS:
Apache POI includes subcomponents with separate copyright notices and
license terms. Your use of these subcomponents is subject to the terms
and conditions of the following licenses:
Office Open XML schemas (poi-ooxml-full-*.jar)
The Office Open XML schema definitions used by Apache POI are
a part of the Office Open XML ECMA Specification (ECMA-376, [1]).
As defined in section 9.4 of the ECMA bylaws [2], this specification
is available to all interested parties without restriction:
9.4 All documents when approved shall be made available to
all interested parties without restriction.
Furthermore, both Microsoft and Adobe have granted patent licenses
to this work [3,4,5].
[1] https://www.ecma-international.org/publications/standards/Ecma-376.htm
[2] https://www.ecma-international.org/memento/Ecmabylaws.htm
[3] https://www.microsoft.com/openspecifications/en/us/programs/osp/default.aspx
[4] https://www.ecma-international.org/publications/files/ECMA-ST/Ecma%20PATENT/
Patent%20statements%20ok/ECMA-376%20Edition%202%20Microsoft%20Patent%20Declaration.pdf
[5] https://www.ecma-international.org/publications/files/ECMA-ST/Ecma%20PATENT/
Patent%20statements%20ok/ECMA-376%20Adobe%20Patent%20Declaration.pdf
org.apache.poi.util.ReplacingInputStream is based on code from
inbot-utils (https://github.com/Inbot/inbot-utils)
The MIT License (MIT)
Copyright (c) 2015 Inbot
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
ExceptionUtils is derived from `scala.util.control.NonFatal` in scala-library
which was released under the Apache 2.0 license.
Copyright (c) 2002-2023 EPFL
Copyright (c) 2011-2023 Lightbend, Inc.
The POI Source Release bundles the Gradle Wrapper. (https://docs.gradle.org/current/userguide/gradle_wrapper.html)
This is released under the Apache License, v2.0.
Copyright © 2015-2021 the original authors.
The wrapper.gradle file was developed by the Apache Kafka project and is released under the Apache License, v2.0.
# 无敏感信息格式测试样本
`apache-poi-simple.doc` 来自 Apache POI 官方仓库的开源测试资料:
https://github.com/apache/poi/blob/trunk/test-data/document/simple.doc
遵循 Apache License 2.0:https://www.apache.org/licenses/LICENSE-2.0 。下载日期:2026-10-28。
其他 Office、PDF、文字及图片样本由 BidFileParserTests 当场生成,未使用真实客户材料。
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment