|
1 | 1 | # -*- coding: utf-8 -*- |
2 | 2 |
|
| 3 | +import asyncio |
| 4 | + |
3 | 5 | import pytest |
4 | 6 |
|
5 | 7 | from media_platform.tieba.client import BaiduTieBaClient |
@@ -108,3 +110,56 @@ async def fake_sleep(_): |
108 | 110 |
|
109 | 111 | assert pages == [1, 2] |
110 | 112 | assert [note.note_id for note in notes] == ["1001", "1002"] |
| 113 | + |
| 114 | + |
| 115 | +@pytest.mark.asyncio |
| 116 | +async def test_creator_feed_skips_failed_thread_and_limits_concurrency(monkeypatch): |
| 117 | + client = BaiduTieBaClient(playwright_page=DummyPage()) |
| 118 | + in_flight = 0 |
| 119 | + peak_in_flight = 0 |
| 120 | + stored = [] |
| 121 | + |
| 122 | + async def fake_get_notes_by_creator_portrait(portrait, page_number, page_size=20): |
| 123 | + return { |
| 124 | + "error_code": 0, |
| 125 | + "data": { |
| 126 | + "has_more": 0, |
| 127 | + "list": [ |
| 128 | + {"thread_info": {"id": tid, "tid": tid}} |
| 129 | + for tid in ("2001", "2002", "2003") |
| 130 | + ], |
| 131 | + }, |
| 132 | + } |
| 133 | + |
| 134 | + async def fake_get_note_by_id(note_id): |
| 135 | + nonlocal in_flight, peak_in_flight |
| 136 | + in_flight += 1 |
| 137 | + peak_in_flight = max(peak_in_flight, in_flight) |
| 138 | + try: |
| 139 | + await asyncio.sleep(0) |
| 140 | + if note_id == "2002": |
| 141 | + raise Exception("Tieba PC API error, url=/c/f/pb/page_pc, response={'error_code': 4}") |
| 142 | + return TiebaNote( |
| 143 | + note_id=note_id, |
| 144 | + title="title", |
| 145 | + note_url=f"https://tieba.baidu.com/p/{note_id}", |
| 146 | + tieba_name="加工中心吧", |
| 147 | + tieba_link="https://tieba.baidu.com/f?kw=%E5%8A%A0%E5%B7%A5%E4%B8%AD%E5%BF%83", |
| 148 | + ) |
| 149 | + finally: |
| 150 | + in_flight -= 1 |
| 151 | + |
| 152 | + async def store_notes(notes): |
| 153 | + stored.extend(note.note_id for note in notes) |
| 154 | + |
| 155 | + client.get_notes_by_creator_portrait = fake_get_notes_by_creator_portrait |
| 156 | + client.get_note_by_id = fake_get_note_by_id |
| 157 | + monkeypatch.setattr("media_platform.tieba.client.config.MAX_CONCURRENCY_NUM", 1) |
| 158 | + |
| 159 | + notes = await client.get_all_notes_by_creator_url( |
| 160 | + "tb.1.creator", crawl_interval=0, callback=store_notes |
| 161 | + ) |
| 162 | + |
| 163 | + assert [note.note_id for note in notes] == ["2001", "2003"] |
| 164 | + assert stored == ["2001", "2003"] |
| 165 | + assert peak_in_flight == 1 |
0 commit comments