test_crawler.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. """M2 离线测试:用 5 个真实 capture 验证 parse_detail_response 字段映射。"""
  2. from __future__ import annotations
  3. import json
  4. from pathlib import Path
  5. import pytest
  6. from creation_knowledge.integrations.crawler import (
  7. parse_content_id,
  8. parse_detail_response,
  9. )
  10. FIXTURES = Path(__file__).parent / "fixtures"
  11. # content_id -> (期望作者, 标题里应出现的子串)
  12. EXPECTED = {
  13. "67e4bdf50000000006028a59": ("海狸教自媒体运营", "短视频脚本"),
  14. "698481e1000000000a02a7c1": ("Irvin是个编剧(接稿版)", "叙事结构"),
  15. "67e2e39b0000000003028ff0": ("拾意", "剧本创作"),
  16. "699308fa0000000016009697": ("方圆的增长飞轮", "选题"),
  17. "680659e8000000001a007a11": ("故事设计原理拆解学习"[:2], "故事设计"),
  18. }
  19. def _load(content_id: str) -> dict:
  20. return json.loads((FIXTURES / f"xhs_case_{content_id}.json").read_text("utf-8"))
  21. @pytest.mark.parametrize("content_id", list(EXPECTED))
  22. def test_parse_detail_fields(content_id: str):
  23. # 重抓的 xhs_case_*.json 即原始响应 {code,msg,data},无 response 包裹
  24. response = _load(content_id)
  25. post = parse_detail_response(response, fallback_content_id=content_id)
  26. assert post.id == f"xhs_{content_id}"
  27. assert post.platform == "xiaohongshu"
  28. assert post.content_id == content_id
  29. assert content_id in post.url
  30. assert post.title, "title 不应为空"
  31. _, title_sub = EXPECTED[content_id]
  32. assert title_sub in post.title
  33. assert post.raw.get("code") == 0
  34. def test_authors():
  35. for cid, (author, _) in EXPECTED.items():
  36. post = parse_detail_response(_load(cid), fallback_content_id=cid)
  37. if cid in ("67e4bdf50000000006028a59", "698481e1000000000a02a7c1",
  38. "67e2e39b0000000003028ff0", "699308fa0000000016009697"):
  39. assert post.author_name == author
  40. def test_shiyi_posts_text_sparse():
  41. """拾意两条正文几乎只有话题串——M3 多模态提取存在的理由。"""
  42. for cid in ("67e2e39b0000000003028ff0", "680659e8000000001a007a11"):
  43. post = parse_detail_response(_load(cid), fallback_content_id=cid)
  44. stripped = post.body_text.replace("#", "").replace("话题", "").strip()
  45. assert len(stripped) < 40, f"{cid} body_text 应很稀疏: {post.body_text!r}"
  46. def test_parse_content_id_from_url():
  47. url = ("https://www.xiaohongshu.com/explore/67e4bdf50000000006028a59"
  48. "?xsec_token=ABC=&xsec_source=pc_like")
  49. assert parse_content_id(url) == "67e4bdf50000000006028a59"
  50. assert parse_content_id("67e4bdf50000000006028a59") == "67e4bdf50000000006028a59"