test_app_api.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581
  1. from __future__ import annotations
  2. from contextlib import nullcontext
  3. from pathlib import Path
  4. from uuid import uuid4
  5. from fastapi.testclient import TestClient
  6. from acquisition.domain import AcquisitionRun, Query, QueryBatch
  7. from app.api import app
  8. from app.dependencies import (
  9. get_acquisition_repository,
  10. get_creation_db_config,
  11. get_decode_repository,
  12. get_pipeline_repository,
  13. )
  14. from app.routes import manual_queries
  15. from decode_content.models import (
  16. DecodeJob,
  17. DecodeResult,
  18. IngestRecord,
  19. KnowledgeParticle,
  20. PayloadDraft,
  21. ScopeResult,
  22. )
  23. from pipeline.models import PipelineRun
  24. class FakeAcquisitionRepo:
  25. def __init__(self):
  26. self.batch_id = uuid4()
  27. self.run_id = uuid4()
  28. self.query_id = uuid4()
  29. self.item_id = uuid4()
  30. self.media_id = uuid4()
  31. self.classification_id = uuid4()
  32. def get_query_batch(self, batch_id):
  33. assert batch_id == self.batch_id
  34. return QueryBatch(
  35. id=batch_id,
  36. name="正式 query 批次",
  37. source_type="manual",
  38. target_platforms=["xiaohongshu", "weixin", "douyin"],
  39. status="ready",
  40. )
  41. def list_queries_for_batch(self, batch_id, *, keep=None):
  42. assert batch_id == self.batch_id
  43. return [
  44. Query(
  45. id=self.query_id,
  46. batch_id=batch_id,
  47. query_text="短视频脚本 开头 怎么写",
  48. keep=True,
  49. status="ready",
  50. )
  51. ]
  52. def get_run_summary(self, run_id):
  53. assert run_id == self.run_id
  54. return {
  55. "id": run_id,
  56. "run_key": "run-1",
  57. "batch_id": self.batch_id,
  58. "status": "running",
  59. "query_count": 1,
  60. "job_count": 3,
  61. "candidate_count": 5,
  62. "creation_hit_count": 2,
  63. "queries": [
  64. {
  65. "query_id": self.query_id,
  66. "query_text": "短视频脚本 开头 怎么写",
  67. "candidate_count": 5,
  68. "creation_hit_count": 2,
  69. "platforms": {"xiaohongshu": {"status": "done"}},
  70. }
  71. ],
  72. }
  73. def get_query_detail(self, *, run_id, query_id):
  74. assert run_id == self.run_id
  75. assert query_id == self.query_id
  76. return {
  77. "query": {
  78. "id": query_id,
  79. "batch_id": self.batch_id,
  80. "query_text": "短视频脚本 开头 怎么写",
  81. "axes": {},
  82. "keep": True,
  83. "filter_reason": None,
  84. "status": "ready",
  85. "sort_order": 0,
  86. },
  87. "jobs": [{"id": uuid4(), "platform": "xiaohongshu", "status": "done"}],
  88. "items": [
  89. {
  90. "id": self.item_id,
  91. "platform": "xiaohongshu",
  92. "platform_item_id": "xhs1",
  93. "unique_key": "xhs:xhs1",
  94. "canonical_url": "https://xhs.test/1",
  95. "content_type": "图文",
  96. "content_mode": "image_post",
  97. "title": "脚本开头",
  98. "author_name": "作者",
  99. "body_text": "先定受众,再写开头钩子",
  100. "raw_summary": "先定受众",
  101. "status": "candidate",
  102. }
  103. ],
  104. "media_assets": [
  105. {
  106. "id": self.media_id,
  107. "item_id": self.item_id,
  108. "media_type": "image",
  109. "source_url": "https://origin.test/1.jpg",
  110. "oss_url": "https://oss.test/1.jpg",
  111. "cdn_url": "https://cdn.test/1.jpg",
  112. "position": 1,
  113. "status": "done",
  114. }
  115. ],
  116. "classifications": [
  117. {
  118. "id": self.classification_id,
  119. "item_id": self.item_id,
  120. "is_creation_knowledge": True,
  121. "label": "creation",
  122. "confidence": 0.98,
  123. "reason": "可复用",
  124. "status": "done",
  125. "error_message": None,
  126. }
  127. ],
  128. }
  129. def get_latest_query_result_list(self, query_id):
  130. assert query_id == self.query_id
  131. return {
  132. "query": {
  133. "id": query_id,
  134. "batch_id": self.batch_id,
  135. "query_text": "短视频脚本 开头 怎么写",
  136. "axes": {},
  137. "keep": True,
  138. "filter_reason": None,
  139. "status": "ready",
  140. "sort_order": 0,
  141. },
  142. "run": {
  143. "id": self.run_id,
  144. "batch_id": self.batch_id,
  145. "run_key": "run-1",
  146. "status": "running",
  147. },
  148. "jobs": [{"id": uuid4(), "platform": "xiaohongshu", "status": "done"}],
  149. "items": [
  150. {
  151. "id": self.item_id,
  152. "platform": "xiaohongshu",
  153. "title": "脚本开头",
  154. "raw_summary": "先定受众",
  155. "status": "candidate",
  156. "content_mode": "image_post",
  157. "metadata": {
  158. "page_index": 1,
  159. "matched_candidate": {"raw": "large"},
  160. "source_payload": {"raw": "large"},
  161. },
  162. }
  163. ],
  164. "media_assets": [
  165. {
  166. "id": self.media_id,
  167. "item_id": self.item_id,
  168. "media_type": "image",
  169. "source_url": "https://origin.test/1.jpg",
  170. "oss_url": "https://oss.test/1.jpg",
  171. "cdn_url": "https://cdn.test/1.jpg",
  172. "position": 1,
  173. "status": "done",
  174. }
  175. ],
  176. "classifications": [
  177. {
  178. "id": self.classification_id,
  179. "item_id": self.item_id,
  180. "is_creation_knowledge": True,
  181. "label": "creation",
  182. "confidence": 0.98,
  183. "status": "done",
  184. "error_message": None,
  185. }
  186. ],
  187. "decode_summaries": [
  188. {
  189. "item_id": self.item_id,
  190. "decode_status": "decoded",
  191. "particle_count": 1,
  192. "payload_count": 1,
  193. }
  194. ],
  195. }
  196. def get_candidate_item(self, item_id):
  197. assert item_id == self.item_id
  198. return self.get_query_detail(run_id=self.run_id, query_id=self.query_id)["items"][0]
  199. def list_media_assets_for_item(self, item_id):
  200. assert item_id == self.item_id
  201. return self.get_query_detail(run_id=self.run_id, query_id=self.query_id)["media_assets"]
  202. class FakeDecodeRepo:
  203. def __init__(self):
  204. self.decode_result_id = uuid4()
  205. self.decode_job_id = uuid4()
  206. self.payload_id = uuid4()
  207. def get_decode_result_for_item(self, item_id):
  208. return DecodeResult(
  209. id=self.decode_result_id,
  210. item_id=item_id,
  211. status="decoded",
  212. read_result={"text": "读懂后的帖子内容"},
  213. gate_result={"passed": True, "reason": "具备可复用创作方法"},
  214. framing_result={"particles": []},
  215. )
  216. def create_decode_job(self, *, item_id, status="pending", metadata=None):
  217. return DecodeJob(
  218. id=self.decode_job_id,
  219. item_id=item_id,
  220. status=status,
  221. metadata=metadata or {},
  222. )
  223. def list_payload_drafts(self, item_id=None):
  224. return [
  225. PayloadDraft(
  226. id=self.payload_id,
  227. item_id=item_id or uuid4(),
  228. payload={"title": "可审核 payload"},
  229. review_status="pending",
  230. ingest_ready=False,
  231. status="draft",
  232. )
  233. ]
  234. def list_knowledge_particles(self, item_id=None):
  235. return [
  236. KnowledgeParticle(
  237. id=uuid4(),
  238. item_id=item_id or uuid4(),
  239. particle_type="what",
  240. title="What I know",
  241. content={"content": "一个可复用知识点"},
  242. status="draft",
  243. )
  244. ]
  245. def list_scope_results(self, item_id=None):
  246. return [
  247. ScopeResult(
  248. id=uuid4(),
  249. item_id=item_id or uuid4(),
  250. scope_type="intent",
  251. scope_value="吸引注意",
  252. status="draft",
  253. )
  254. ]
  255. def list_ingest_records(self, item_id=None):
  256. return [
  257. IngestRecord(
  258. id=uuid4(),
  259. payload_draft_id=self.payload_id,
  260. target_system="dry-run",
  261. status="ingested",
  262. )
  263. ]
  264. class FakePipelineRepo:
  265. def get_pipeline_run(self, run_id):
  266. return PipelineRun(
  267. id=run_id,
  268. run_key="pipeline-run-1",
  269. status="running",
  270. current_stage="decode",
  271. )
  272. class FakeManualRepo:
  273. def __init__(self):
  274. self.batch_id = uuid4()
  275. self.run_id = uuid4()
  276. self.queries = []
  277. self.runs = []
  278. self.updates = []
  279. def create_query_batch(self, **kwargs):
  280. self.batch_kwargs = kwargs
  281. return QueryBatch(id=self.batch_id, **kwargs)
  282. def add_query(self, **kwargs):
  283. query = Query(id=uuid4(), **kwargs)
  284. self.queries.append(query)
  285. return query
  286. def create_acquisition_run(self, **kwargs):
  287. run = AcquisitionRun(id=self.run_id, **kwargs)
  288. self.runs.append(run)
  289. return run
  290. def update_acquisition_run(self, run_id, **kwargs):
  291. assert run_id == self.run_id
  292. self.updates.append(kwargs)
  293. base = self.runs[-1].model_dump()
  294. base.update(kwargs)
  295. return AcquisitionRun(**base)
  296. def _client(repo: FakeAcquisitionRepo):
  297. app.dependency_overrides[get_acquisition_repository] = lambda: repo
  298. return TestClient(app)
  299. def test_manual_query_batch_api_creates_ready_batch_and_starts_pipeline(monkeypatch, tmp_path):
  300. repo = FakeManualRepo()
  301. popen_calls = []
  302. class FakeProcess:
  303. pid = 12345
  304. def fake_popen(cmd, **kwargs):
  305. popen_calls.append((cmd, kwargs))
  306. return FakeProcess()
  307. monkeypatch.setattr(manual_queries, "transaction", lambda _config: nullcontext(object()))
  308. monkeypatch.setattr(manual_queries, "PostgresAcquisitionRepository", lambda _conn: repo)
  309. monkeypatch.setattr(manual_queries, "RUNTIME_MANUAL_DIR", tmp_path)
  310. monkeypatch.setattr(manual_queries.subprocess, "Popen", fake_popen)
  311. app.dependency_overrides[get_creation_db_config] = lambda: object()
  312. client = TestClient(app)
  313. try:
  314. response = client.post(
  315. "/api/query-batches/manual",
  316. json={
  317. "queries": [
  318. "符号 视频 灵感 怎么做",
  319. "符号 视频 灵感 怎么做",
  320. {"query_text": "叙事体裁 视频 灵感 有哪些", "axes": {"实质": "叙事体裁"}},
  321. ]
  322. },
  323. )
  324. assert response.status_code == 200
  325. data = response.json()
  326. assert data["status"] == "queued"
  327. assert data["batch_id"] == str(repo.batch_id)
  328. assert data["run_id"] == str(repo.run_id)
  329. assert data["pid"] == 12345
  330. assert data["query_count"] == 2
  331. assert data["summary_url"] == f"/api/acquisition/runs/{repo.run_id}/summary"
  332. assert repo.batch_kwargs["generation_method"] == "manual_query_api_v1"
  333. assert repo.batch_kwargs["target_platforms"] == ["xiaohongshu", "weixin", "douyin"]
  334. assert [query.query_text for query in repo.queries] == [
  335. "符号 视频 灵感 怎么做",
  336. "叙事体裁 视频 灵感 有哪些",
  337. ]
  338. assert all(query.keep is True and query.status == "ready" for query in repo.queries)
  339. assert all(query.metadata["family_key"] == "manual" for query in repo.queries)
  340. assert repo.runs[0].status == "pending"
  341. assert repo.runs[0].metadata["log_path"].endswith(".log")
  342. assert repo.runs[0].metadata["command"]
  343. assert popen_calls
  344. cmd, kwargs = popen_calls[0]
  345. assert "scripts/run_creation_pipeline.py" in cmd[1]
  346. assert ["--platform", "xiaohongshu"] == cmd[-6:-4]
  347. assert "--no-dry-ingest-record" not in cmd
  348. assert kwargs["cwd"] == str(manual_queries.ROOT)
  349. assert str(manual_queries.ROOT) in kwargs["env"]["PYTHONPATH"]
  350. assert repo.updates == []
  351. finally:
  352. app.dependency_overrides.clear()
  353. def test_manual_query_batch_api_extracts_family_json(monkeypatch, tmp_path):
  354. repo = FakeManualRepo()
  355. monkeypatch.setattr(manual_queries, "transaction", lambda _config: nullcontext(object()))
  356. monkeypatch.setattr(manual_queries, "PostgresAcquisitionRepository", lambda _conn: repo)
  357. monkeypatch.setattr(manual_queries, "RUNTIME_MANUAL_DIR", tmp_path)
  358. monkeypatch.setattr(manual_queries.subprocess, "Popen", lambda *args, **kwargs: type("P", (), {"pid": 1})())
  359. app.dependency_overrides[get_creation_db_config] = lambda: object()
  360. client = TestClient(app)
  361. try:
  362. response = client.post(
  363. "/api/query-batches/manual",
  364. json={
  365. "families": [
  366. {
  367. "key": "f1",
  368. "name": "实质正交",
  369. "items": [{"query": "公共安全 视频 灵感 怎么做"}],
  370. }
  371. ]
  372. },
  373. )
  374. assert response.status_code == 200
  375. assert repo.queries[0].query_text == "公共安全 视频 灵感 怎么做"
  376. assert repo.queries[0].metadata["family_key"] == "manual"
  377. assert repo.queries[0].metadata["source_family_key"] == "f1"
  378. finally:
  379. app.dependency_overrides.clear()
  380. def test_manual_query_batch_api_rejects_empty_and_invalid_platform():
  381. client = TestClient(app)
  382. assert client.post("/api/query-batches/manual", json={"queries": [" "]}).status_code == 422
  383. assert client.post(
  384. "/api/query-batches/manual",
  385. json={"queries": ["符号 视频 灵感 怎么做"], "target_platforms": ["bilibili"]},
  386. ).status_code == 422
  387. def test_app_health_and_formal_acquisition_routes():
  388. repo = FakeAcquisitionRepo()
  389. client = _client(repo)
  390. try:
  391. assert client.get("/health").json()["entrypoint"] == "app.api:app"
  392. batch = client.get(f"/api/query-batches/{repo.batch_id}").json()
  393. assert batch["batch"]["name"] == "正式 query 批次"
  394. assert batch["queries"][0]["id"] == str(repo.query_id)
  395. summary = client.get(f"/api/acquisition/runs/{repo.run_id}/summary").json()
  396. assert summary["creation_hit_count"] == 2
  397. assert summary["queries"][0]["query_id"] == str(repo.query_id)
  398. detail = client.get(f"/api/acquisition/runs/{repo.run_id}/queries/{repo.query_id}").json()
  399. item = detail["platforms"]["xiaohongshu"]["items"][0]
  400. assert item["content_mode"] == "image_post"
  401. assert item["body_text"] == "先定受众,再写开头钩子"
  402. assert item["media_assets"][0]["cdn_url"] == "https://cdn.test/1.jpg"
  403. assert item["classification"]["is_creation_knowledge"] is True
  404. latest = client.get(f"/api/query-generation/latest/queries/{repo.query_id}").json()
  405. lightweight_item = latest["items"][0]
  406. assert "body_text" not in lightweight_item
  407. assert "source_payload" not in lightweight_item
  408. assert "matched_candidate" not in lightweight_item["metadata"]
  409. assert "source_payload" not in lightweight_item["metadata"]
  410. assert lightweight_item["raw_summary"] == "先定受众"
  411. assert len(lightweight_item["media_assets"]) == 1
  412. assert lightweight_item["decode_summary"]["particle_count"] == 1
  413. assert latest["platforms"]["xiaohongshu"]["item_ids"] == [str(repo.item_id)]
  414. assert "items" not in latest["platforms"]["xiaohongshu"]
  415. finally:
  416. app.dependency_overrides.clear()
  417. def test_app_compresses_large_json_responses():
  418. repo = FakeAcquisitionRepo()
  419. client = _client(repo)
  420. try:
  421. response = client.get(
  422. f"/api/query-generation/latest/queries/{repo.query_id}",
  423. headers={"Accept-Encoding": "gzip"},
  424. )
  425. assert response.status_code == 200
  426. assert response.headers.get("content-encoding") == "gzip"
  427. finally:
  428. app.dependency_overrides.clear()
  429. def test_query_generation_preview_defaults_to_first_two_families():
  430. client = TestClient(app)
  431. data = client.get("/api/query-generation/preview?per=2").json()
  432. assert data["summary"]["family_keys"] == ["f1", "f2"]
  433. assert [family["key"] for family in data["families"]] == ["f1", "f2"]
  434. assert data["summary"]["query_count"] == 4
  435. assert data["metadata"]["active_family_keys"] == ["f1", "f2"]
  436. def test_query_generation_preview_can_return_full_cartesian_combinations():
  437. client = TestClient(app)
  438. data = client.get("/api/query-generation/preview?per=0&batch_n=1").json()
  439. assert data["summary"]["family_keys"] == ["f1", "f2"]
  440. assert data["summary"]["query_count"] == 36
  441. assert [len(family["items"]) for family in data["families"]] == [18, 18]
  442. def test_formal_app_does_not_expose_legacy_static_mounts():
  443. paths = {route.path for route in app.routes if hasattr(route, "path")}
  444. assert "/data" not in paths
  445. assert "/frames" not in paths
  446. assert "/api/creation-search/summary" not in paths
  447. assert "/api/creation-search/query" not in paths
  448. def test_pipeline_route_returns_501_instead_of_legacy_data_when_not_wired():
  449. client = TestClient(app)
  450. run_id = uuid4()
  451. assert client.get(f"/api/pipeline/runs/{run_id}").status_code == 501
  452. def test_formal_decode_payload_pipeline_routes_have_override_success_paths():
  453. acquisition_repo = FakeAcquisitionRepo()
  454. decode_repo = FakeDecodeRepo()
  455. pipeline_repo = FakePipelineRepo()
  456. item_id = acquisition_repo.item_id
  457. run_id = uuid4()
  458. app.dependency_overrides[get_acquisition_repository] = lambda: acquisition_repo
  459. app.dependency_overrides[get_decode_repository] = lambda: decode_repo
  460. app.dependency_overrides[get_pipeline_repository] = lambda: pipeline_repo
  461. client = TestClient(app)
  462. try:
  463. result = client.get(f"/api/decode/items/{item_id}/result").json()
  464. assert result["item_id"] == str(item_id)
  465. assert result["read_result"]["text"] == "读懂后的帖子内容"
  466. job = client.post(f"/api/decode/items/{item_id}/jobs").json()["job"]
  467. assert job["item_id"] == str(item_id)
  468. assert job["status"] == "pending"
  469. drafts = client.get(f"/api/payloads/drafts?item_id={item_id}").json()["items"]
  470. assert drafts[0]["item_id"] == str(item_id)
  471. assert drafts[0]["payload"]["title"] == "可审核 payload"
  472. detail = client.get(f"/api/decode/items/{item_id}/detail").json()
  473. assert detail["item"]["id"] == str(item_id)
  474. assert detail["knowledge_particles"][0]["title"] == "What I know"
  475. assert detail["ingest_records"][0]["status"] == "ingested"
  476. run = client.get(f"/api/pipeline/runs/{run_id}").json()["run"]
  477. assert run["id"] == str(run_id)
  478. assert run["current_stage"] == "decode"
  479. finally:
  480. app.dependency_overrides.clear()
  481. def test_no_legacy_api_dependencies_in_formal_app_sources():
  482. roots = [Path("app"), Path("pipeline")]
  483. text = "\n".join(
  484. path.read_text(encoding="utf-8")
  485. for root in roots
  486. for path in root.rglob("*")
  487. if path.is_file() and path.suffix in {".py", ".jsx", ".js"}
  488. )
  489. assert "acquisition.store" not in text
  490. assert "CK_SQLITE_PATH" not in text
  491. assert "/data/queries" not in text
  492. assert "/api/creation-search" not in text
  493. assert "creation_knowledge.api" not in text
  494. def test_legacy_top_level_package_is_archived():
  495. assert not Path("creation_knowledge").exists()
  496. assert Path("archive/2026-06-30-step6/legacy_creation_knowledge/creation_knowledge").exists()
  497. def test_active_sources_do_not_import_legacy_store_or_package():
  498. roots = [Path("app"), Path("pipeline"), Path("acquisition"), Path("decode_content"), Path("scripts")]
  499. text = "\n".join(
  500. path.read_text(encoding="utf-8")
  501. for root in roots
  502. for path in root.rglob("*")
  503. if path.is_file() and path.suffix in {".py", ".jsx", ".js"}
  504. )
  505. assert "from acquisition import store" not in text
  506. assert "import acquisition.store" not in text
  507. assert "from creation_knowledge" not in text
  508. assert "import creation_knowledge" not in text