test_xiaohongshu_paging_logic.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. import asyncio
  2. import sys
  3. from pathlib import Path
  4. CURRENT_DIR = Path(__file__).parent.resolve()
  5. if str(CURRENT_DIR) not in sys.path:
  6. sys.path.insert(0, str(CURRENT_DIR))
  7. from platforms.xiaohongshu import XiaohongshuPublisher
  8. async def main():
  9. publisher = XiaohongshuPublisher(headless=True)
  10. async def fake_fetch_notes_page(p: int):
  11. if str(p) == "0":
  12. return {
  13. "success": True,
  14. "data": {
  15. "notes": [{"id": "1"}, {"id": "2"}],
  16. "tags": [{"id": "special.note_time_desc", "notes_count": 3}],
  17. "page": 1,
  18. },
  19. }
  20. if str(p) == "1":
  21. return {
  22. "success": True,
  23. "data": {
  24. "notes": [{"id": "3"}],
  25. "tags": [{"id": "special.note_time_desc", "notes_count": 3}],
  26. "page": -1,
  27. },
  28. }
  29. return {"success": True, "data": {"notes": []}}
  30. class DummyPage:
  31. url = "https://creator.xiaohongshu.com/new/note-manager"
  32. async def goto(self, *_args, **_kwargs):
  33. return None
  34. async def evaluate(self, _script, p):
  35. return await fake_fetch_notes_page(p)
  36. publisher.page = DummyPage()
  37. publisher.context = object()
  38. publisher.browser = object()
  39. async def dummy_init_browser():
  40. return None
  41. async def dummy_set_cookies(_cookies):
  42. return None
  43. publisher.init_browser = dummy_init_browser # type: ignore
  44. publisher.set_cookies = dummy_set_cookies # type: ignore
  45. publisher.parse_cookies = lambda _c: [] # type: ignore
  46. publisher.close_browser = lambda: asyncio.sleep(0) # type: ignore
  47. r0 = await publisher.get_works("[]", page=0, page_size=20)
  48. assert r0.success
  49. assert r0.total == 3
  50. assert r0.has_more is True
  51. assert r0.next_page == 1
  52. r1 = await publisher.get_works("[]", page=1, page_size=20)
  53. assert r1.success
  54. assert r1.total == 3
  55. assert r1.has_more is False
  56. assert r1.next_page == -1
  57. print("test_xiaohongshu_paging_logic passed")
  58. r_all = await publisher.get_all_works("[]")
  59. assert r_all.success
  60. assert r_all.total == 3
  61. assert len(r_all.works) == 3
  62. assert r_all.has_more is False
  63. print("test_xiaohongshu_auto_paging passed")
  64. if __name__ == "__main__":
  65. asyncio.run(main())