feat(monitor): 抖音接入博主监控
上游爬虫本身不缺抖音能力(三模式、四项指标、二级评论都与小红书对等、指标还是同名同列),
缺的全在监控层的适配。这次把「平台之间不一样」的管子集中到一个新模块,再把散落的
xhs 硬编码接上去。
* 新增 api/monitor/adapters.py:产物目录名、jsonl 字段别名、目标链接形态与正则、
通知链接模板。不放进 platforms.py 是因为那个模块被 describe_all() 整个序列化进
/api/config/platforms 交给前端,塞进正则和目录名会让爬虫内部细节漏进 API 载荷。
代价是两个注册表可能漂移,用一条测试钉住「声明接通就必须有适配器」。
* 两个必须知道的坑,都在这版里处理掉了:
1) 抖音的平台 id 是 dy,而 store 把产物写在 douyin/ 下(store/douyin/_store_impl.py:47)。
不改就是 ingest 一个文件都读不到 —— 不报错,只是 0 条,然后被冒充成「疑似登录失效」。
2) 抖音的作品没有 note_id(叫 aweme_id)、评论也用 aweme_id 指作品。ingest 第一步是
`if not note_id: continue`,不映射就逐条全丢。
另外抖音顶层评论的 parent_comment_id 是字符串 "0",归一成空串,免得前端多出悬空的父节点。
* 顺带把「东西抓到了、只是没落在期望目录里」单独识别出来。这类故障的现象和登录失效
一模一样,按登录失效报会把人指去查完全错误的方向。
* 修两个既有 bug(今天只有小红书所以无害,加抖音就踩响):
- service.py update_task 换目标时漏传 task.platform,回落到默认小红书
- scheduler.py 取 cookie 没传 platform,抖音任务会读着小红书那份 cookie 不动
* 行为变更(已与用户确认):cookie 闸门改成「没 cookie 且没开 CDP」才跳过。
CDP 模式下登录态来自被接管的浏览器,粘不粘 cookie 由不得它决定;不放行的话,
选了「接管已有 Chrome」却没粘 cookie 的用户会看到任务永远不触发,而且不报错。
副作用是开启了 CDP 的小红书任务也不再被该闸门拦住 —— 语义上是对的。
* 目标输入框的示例链接与措辞改由能力矩阵提供(notes_label 抖音说「作品」、小红书说
「笔记」;「建议只填纯 ID」是小红书专属劝告,抖音链接不带令牌,不再显示)。
测试 +22 条(858 通过),其中最关键的是「抖音作品/评论不被静默丢弃」与「产物目录名
不等于平台 id」两条 —— 都是把最难查的失败模式钉死在回归网里。
注意:抖音这条路的**端到端尚未验证**,需要一份可用的抖音登录态(CDP 那台 Chrome 里
登录,或导出一份 cookie)。单测覆盖的是解析与入库,真实抓取还没跑过。
This commit is contained in:
@@ -26,6 +26,37 @@ async def test_cmd_arg_crawler_max_notes_count():
|
||||
config.CRAWLER_MAX_NOTES_COUNT = orig_notes
|
||||
config.CRAWLER_MAX_COMMENTS_COUNT_SINGLENOTES = orig_comments
|
||||
|
||||
def test_douyin_monitor_command_uses_the_right_flags():
|
||||
"""抖音监控任务拼出来的命令行。
|
||||
|
||||
与 runner 走的是同一条 _build_command 路径,所以这一条能守住「监控任务的参数
|
||||
没拼错」—— 尤其是平台值必须是 dy(而不是 douyin),否则上游根本认不出平台。
|
||||
"""
|
||||
cm = CrawlerManager()
|
||||
req = CrawlerStartRequest(
|
||||
platform=PlatformEnum.DOUYIN,
|
||||
login_type=LoginTypeEnum.COOKIE,
|
||||
crawler_type=CrawlerTypeEnum.CREATOR,
|
||||
creator_ids="https://www.douyin.com/user/MS4wLjABAAAATJPY7LAlaa5X",
|
||||
save_data_path="./data/monitor_runs/1/2",
|
||||
enable_cdp_mode=True,
|
||||
inject_all_cookies=True,
|
||||
save_login_state=True,
|
||||
max_notes_count=20,
|
||||
max_comments_count=50,
|
||||
)
|
||||
cmd = cm._build_command(req)
|
||||
|
||||
idx = cmd.index("--platform")
|
||||
assert cmd[idx + 1] == "dy"
|
||||
idx = cmd.index("--type")
|
||||
assert cmd[idx + 1] == "creator"
|
||||
idx = cmd.index("--creator_id")
|
||||
assert cmd[idx + 1] == "https://www.douyin.com/user/MS4wLjABAAAATJPY7LAlaa5X"
|
||||
idx = cmd.index("--enable_cdp_mode")
|
||||
assert cmd[idx + 1] == "true"
|
||||
|
||||
|
||||
def test_crawler_manager_build_command():
|
||||
cm = CrawlerManager()
|
||||
|
||||
|
||||
@@ -78,6 +78,117 @@ class TestParseTargetInput:
|
||||
with pytest.raises(TargetParseError):
|
||||
parse_target_input("not a url at all !!", "creator")
|
||||
|
||||
# --- 抖音 -------------------------------------------------------------
|
||||
# 链接形态由平台决定,所以每一个都要显式带上 "dy"。
|
||||
|
||||
def test_douyin_creator_url(self):
|
||||
parsed = parse_target_input(
|
||||
"https://www.douyin.com/user/MS4wLjABAAAATJPY7LAlaa5X-c8uNdWkvz0jUGgpw4eeXIwu_8BhvqE"
|
||||
"?from_tab_name=main",
|
||||
"creator",
|
||||
"dy",
|
||||
)
|
||||
assert (
|
||||
parsed["external_id"]
|
||||
== "MS4wLjABAAAATJPY7LAlaa5X-c8uNdWkvz0jUGgpw4eeXIwu_8BhvqE"
|
||||
)
|
||||
|
||||
def test_douyin_video_url(self):
|
||||
parsed = parse_target_input(
|
||||
"https://www.douyin.com/video/7525082444551310602", "note", "dy"
|
||||
)
|
||||
assert parsed["external_id"] == "7525082444551310602"
|
||||
|
||||
def test_douyin_modal_id_url(self):
|
||||
"""在别人主页或搜索结果里点开视频,拿到的就是带 modal_id 的链接。"""
|
||||
parsed = parse_target_input(
|
||||
"https://www.douyin.com/root/search/python?aid=b733a3b0&modal_id=7471165520058862848",
|
||||
"note",
|
||||
"dy",
|
||||
)
|
||||
assert parsed["external_id"] == "7471165520058862848"
|
||||
|
||||
def test_douyin_bare_sec_uid_is_accepted(self):
|
||||
sec_uid = "MS4wLjABAAAATJPY7LAlaa5X-c8uNdWkvz0jUGgpw4eeXIwu_8BhvqE"
|
||||
|
||||
parsed = parse_target_input(sec_uid, "creator", "dy")
|
||||
|
||||
assert parsed["external_id"] == sec_uid
|
||||
|
||||
def test_douyin_bare_sec_uid_beyond_the_xhs_length_cap(self):
|
||||
"""裸 id 的长度上限必须按平台分开。
|
||||
|
||||
小红书那条规则封顶 64 字符,而 sec_user_id 长过 64 是常态(实测样本 55,
|
||||
但字段本身是变长的)。共用一条规则的话,长一点的 sec_uid 会被直接拒掉 ——
|
||||
对用户来说就是「粘贴了一个完全正确的链接却报无法识别」。
|
||||
"""
|
||||
sec_uid = "MS4wLjABAAAA" + "aB3dEf6hIj9lMn2pQr5tUv8xYz1" * 3
|
||||
assert len(sec_uid) > 64
|
||||
|
||||
parsed = parse_target_input(sec_uid, "creator", "dy")
|
||||
assert parsed["external_id"] == sec_uid
|
||||
|
||||
# 同一条 id 拿小红书规则来解析会被拒 —— 这正是两条规则必须分开的原因。
|
||||
with pytest.raises(TargetParseError):
|
||||
parse_target_input(sec_uid, "creator", "xhs")
|
||||
|
||||
def test_douyin_bare_video_id(self):
|
||||
parsed = parse_target_input("7525082444551310602", "note", "dy")
|
||||
assert parsed["external_id"] == "7525082444551310602"
|
||||
# 抖音不需要 xsec_token —— 和小红书不同,裸链接就能用。
|
||||
assert parsed["xsec_token"] == ""
|
||||
|
||||
def test_douyin_short_link_is_rejected_with_a_reason(self):
|
||||
"""短链要联网跳一次才知道指向谁。明确拒绝好过存一个永远抓不到东西的目标。"""
|
||||
with pytest.raises(TargetParseError) as excinfo:
|
||||
parse_target_input("https://v.douyin.com/drIPtQ_WPWY/", "note", "dy")
|
||||
assert "短链" in str(excinfo.value)
|
||||
|
||||
def test_a_douyin_link_is_not_parsed_with_xhs_rules(self):
|
||||
with pytest.raises(TargetParseError):
|
||||
parse_target_input(
|
||||
"https://www.douyin.com/video/7525082444551310602", "note", "xhs"
|
||||
)
|
||||
|
||||
def test_an_xhs_link_is_not_parsed_for_douyin(self):
|
||||
with pytest.raises(TargetParseError):
|
||||
parse_target_input(NOTE_URL, "note", "dy")
|
||||
|
||||
def test_a_platform_without_an_adapter_is_rejected(self):
|
||||
with pytest.raises(TargetParseError):
|
||||
parse_target_input("whatever", "creator", "bili")
|
||||
|
||||
|
||||
class TestTargetReplacement:
|
||||
@pytest.mark.asyncio
|
||||
async def test_replacing_targets_uses_the_tasks_own_platform(self, client):
|
||||
"""改目标必须按任务**自己**的平台解析。
|
||||
|
||||
``update_task`` 原先漏传了 platform,解析回落到默认的小红书。只有小红书时
|
||||
行为恰好正确,接上抖音就会拿小红书的正则去解析抖音链接 —— 建任务时对、
|
||||
改任务时错,是最难注意到的那种不一致。
|
||||
"""
|
||||
sec_uid = "MS4wLjABAAAATJPY7LAlaa5X-c8uNdWkvz0jUGgpw4eeXIwu_8BhvqE"
|
||||
created = await client.post(
|
||||
"/api/monitor/tasks",
|
||||
json={"name": "抖音", "mode": "creator", "platform": "dy", "targets": [sec_uid]},
|
||||
)
|
||||
assert created.status_code == 201
|
||||
task_id = created.json()["id"]
|
||||
|
||||
updated = await client.patch(
|
||||
f"/api/monitor/tasks/{task_id}",
|
||||
json={"targets": [f"https://www.douyin.com/user/{sec_uid}"]},
|
||||
)
|
||||
assert updated.status_code == 200
|
||||
|
||||
tasks = (
|
||||
await client.get("/api/monitor/tasks", params={"platform": "dy"})
|
||||
).json()["tasks"]
|
||||
target = tasks[0]["targets"][0]
|
||||
assert target["external_id"] == sec_uid
|
||||
assert target["raw_value"].startswith("https://www.douyin.com/user/")
|
||||
|
||||
|
||||
class TestTaskCrud:
|
||||
@pytest.mark.asyncio
|
||||
|
||||
@@ -35,6 +35,7 @@ from sqlalchemy.pool import StaticPool
|
||||
|
||||
from tools.time_util import get_current_timestamp
|
||||
|
||||
from api.monitor import adapters
|
||||
from api.monitor.ingest import describe_exit_code, ingest_run, parse_count
|
||||
from api.monitor.models import (
|
||||
EVENT_AUTH_FAILURE,
|
||||
@@ -46,6 +47,7 @@ from api.monitor.models import (
|
||||
EVENT_RUN_FAILED,
|
||||
MODE_CREATOR,
|
||||
MonitorBase,
|
||||
MonitorComment,
|
||||
MonitorEvent,
|
||||
MonitorNote,
|
||||
MonitorNoteMetric,
|
||||
@@ -118,9 +120,14 @@ def _write_run_dir(
|
||||
root: Path,
|
||||
notes: List[Dict[str, Any]],
|
||||
comments: Optional[List[Dict[str, Any]]] = None,
|
||||
subdir: str = "xhs",
|
||||
) -> Path:
|
||||
"""Write a run's jsonl output in the crawler's own layout."""
|
||||
jsonl_dir = root / "xhs" / "jsonl"
|
||||
"""Write a run's jsonl output in the crawler's own layout.
|
||||
|
||||
``subdir`` 是**爬虫**落盘的目录名,不是监控层的平台 id —— 抖音那边这两者不同
|
||||
(平台 id 是 ``dy``、目录是 ``douyin``),所以必须能分开指定,否则测不出那个差异。
|
||||
"""
|
||||
jsonl_dir = root / subdir / "jsonl"
|
||||
jsonl_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
contents = jsonl_dir / "creator_contents_2026-01-01.jsonl"
|
||||
@@ -170,6 +177,50 @@ def _comment(comment_id: str, note_id: str, create_time: int, **extra) -> Dict[s
|
||||
return record
|
||||
|
||||
|
||||
def _dy_note(aweme_id: str, liked: Any = "10", **extra) -> Dict[str, Any]:
|
||||
"""抖音作品记录 —— 键名照抄 store/douyin/__init__.py 的落盘字段。
|
||||
|
||||
重点在于**没有** ``note_id``:抖音叫 ``aweme_id``。这一条差异没映射好,就是
|
||||
每条记录都被 ingest 悄悄 continue 掉、一条不剩。
|
||||
"""
|
||||
record = {
|
||||
"aweme_id": aweme_id,
|
||||
"aweme_type": "0",
|
||||
"title": f"title-{aweme_id}",
|
||||
"desc": f"title-{aweme_id}",
|
||||
"create_time": 1700000000000,
|
||||
"creator_hash": "hash",
|
||||
"nickname": "u***r",
|
||||
"liked_count": liked,
|
||||
"collected_count": "1",
|
||||
"comment_count": "1",
|
||||
"share_count": "1",
|
||||
"aweme_url": f"https://www.douyin.com/video/{aweme_id}",
|
||||
"cover_url": "https://img/cover.jpg",
|
||||
}
|
||||
record.update(extra)
|
||||
return record
|
||||
|
||||
|
||||
def _dy_comment(
|
||||
comment_id: str, aweme_id: str, create_time: int, **extra
|
||||
) -> Dict[str, Any]:
|
||||
record = {
|
||||
"comment_id": comment_id,
|
||||
"create_time": create_time,
|
||||
"aweme_id": aweme_id,
|
||||
"content": f"content-{comment_id}",
|
||||
"creator_hash": "hash",
|
||||
"nickname": "u***r",
|
||||
"sub_comment_count": "0",
|
||||
"like_count": "0",
|
||||
# 抖音顶层评论的父 id 是字符串 "0",不是空串。
|
||||
"parent_comment_id": "0",
|
||||
}
|
||||
record.update(extra)
|
||||
return record
|
||||
|
||||
|
||||
async def _events(db: AsyncSession, event_type: Optional[str] = None) -> List[MonitorEvent]:
|
||||
stmt = select(MonitorEvent)
|
||||
if event_type:
|
||||
@@ -525,3 +576,125 @@ class TestIdempotency:
|
||||
assert result.new_notes == 0
|
||||
assert result.new_comments == 0
|
||||
assert len(list((await db.scalars(select(MonitorNote))).all())) == notes_after_first
|
||||
|
||||
|
||||
class TestDouyinIngest:
|
||||
"""抖音的产物形状与小红书不同 —— 这里钉住「不会被静默丢掉」。
|
||||
|
||||
这一组存在的理由,是这个改动最危险的失败模式:字段名或目录名没对上时,ingest
|
||||
不报错,只是**一条都不入库**,然后被当成「疑似登录失效」报出去。
|
||||
"""
|
||||
|
||||
async def _ingest(
|
||||
self,
|
||||
db,
|
||||
tmp_path,
|
||||
notes,
|
||||
comments=None,
|
||||
platform="dy",
|
||||
subdir="douyin",
|
||||
):
|
||||
task = await _make_task(db, platform=platform)
|
||||
run = await _make_run(db, task, started_at=1)
|
||||
_write_run_dir(tmp_path, notes, comments, subdir=subdir)
|
||||
result = await ingest_run(db, run, task, tmp_path)
|
||||
return task, run, result
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_notes_are_ingested_under_their_douyin_field_names(self, db, tmp_path):
|
||||
aweme_id = "7525082444551310602"
|
||||
_task, _run, result = await self._ingest(db, tmp_path, [_dy_note(aweme_id)])
|
||||
|
||||
note = await db.scalar(select(MonitorNote))
|
||||
assert note is not None, "抖音作品被静默丢弃了 —— 多半是 aweme_id 没映射到 note_id"
|
||||
assert note.note_id == aweme_id
|
||||
assert note.note_url == f"https://www.douyin.com/video/{aweme_id}"
|
||||
assert note.cover == "https://img/cover.jpg"
|
||||
assert note.source_kind == "0"
|
||||
assert note.published_at == 1700000000000
|
||||
assert result.notes_fetched == 1
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_the_artifact_directory_is_not_the_platform_id(self, db, tmp_path):
|
||||
"""目录名与平台 id 不一致,是这套适配里最反直觉的一条。
|
||||
|
||||
抖音的平台 id 是 ``dy``,而爬虫把产物写在 ``douyin/`` 下。把它钉在这里,
|
||||
是为了让「顺手改成一致」这件事会在测试里红掉,而不是让 ingest 悄悄读 0 条。
|
||||
"""
|
||||
assert adapters.artifact_dir("dy") == "douyin"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_writing_into_the_platform_id_directory_reads_nothing(self, db, tmp_path):
|
||||
"""反面:产物落在 ``dy/`` 下时一条都读不到 —— 这正是映射要解决的问题。"""
|
||||
_task, _run, result = await self._ingest(db, tmp_path, [_dy_note("1")], subdir="dy")
|
||||
|
||||
assert result.notes_fetched == 0
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_misplaced_output_is_blamed_on_the_directory_not_the_login(
|
||||
self, db, tmp_path
|
||||
):
|
||||
"""产物其实抓到了,只是目录名不对 —— 不该报成「疑似登录失效」。
|
||||
|
||||
这是最难查的一类故障:登录是好的、数据也抓到了,但报出来的现象和登录失效
|
||||
一模一样,会把人指去查完全错误的方向。
|
||||
"""
|
||||
_task, run, _result = await self._ingest(
|
||||
db, tmp_path, [_dy_note("1")], subdir="dy"
|
||||
)
|
||||
|
||||
assert any("目录" in event.title for event in await _events(db, EVENT_NO_DATA))
|
||||
assert await _events(db, EVENT_AUTH_FAILURE) == []
|
||||
assert run.error_message and "dy" in run.error_message
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_comments_are_linked_through_aweme_id(self, db, tmp_path):
|
||||
aweme_id = "7525082444551310602"
|
||||
_task, _run, result = await self._ingest(
|
||||
db,
|
||||
tmp_path,
|
||||
[_dy_note(aweme_id)],
|
||||
comments=[_dy_comment("c1", aweme_id, 500)],
|
||||
)
|
||||
|
||||
comment = await db.scalar(select(MonitorComment))
|
||||
assert comment is not None, "抖音评论被静默丢弃了 —— 多半是 aweme_id 没映射"
|
||||
assert comment.note_id == aweme_id
|
||||
assert result.comments_fetched == 1
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_a_top_level_parent_of_zero_becomes_empty(self, db, tmp_path):
|
||||
"""抖音顶层评论的父 id 是 "0";原样存进去,前端会多出一堆悬空的父节点。"""
|
||||
aweme_id = "7525082444551310602"
|
||||
await self._ingest(
|
||||
db,
|
||||
tmp_path,
|
||||
[_dy_note(aweme_id)],
|
||||
comments=[
|
||||
_dy_comment("c1", aweme_id, 500),
|
||||
_dy_comment("c2", aweme_id, 600, parent_comment_id="c1"),
|
||||
],
|
||||
)
|
||||
|
||||
by_id = {c.comment_id: c for c in (await db.scalars(select(MonitorComment))).all()}
|
||||
assert by_id["c1"].parent_comment_id == ""
|
||||
assert by_id["c2"].parent_comment_id == "c1"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_the_four_metrics_need_no_mapping(self, db, tmp_path):
|
||||
"""四个指标键两边同名 —— 抖音作品照样进 monitor_note_metric,差分照常。"""
|
||||
aweme_id = "7525082444551310602"
|
||||
task = await _make_task(db, platform="dy")
|
||||
|
||||
_write_run_dir(tmp_path, [_dy_note(aweme_id, liked="100")], subdir="douyin")
|
||||
run1 = await _make_run(db, task, started_at=1)
|
||||
await ingest_run(db, run1, task, tmp_path)
|
||||
|
||||
metric = await db.scalar(select(MonitorNoteMetric))
|
||||
assert metric is not None and metric.liked_count == 100
|
||||
|
||||
_write_run_dir(tmp_path, [_dy_note(aweme_id, liked="150")], subdir="douyin")
|
||||
run2 = await _make_run(db, task, started_at=2)
|
||||
await ingest_run(db, run2, task, tmp_path)
|
||||
|
||||
assert len(await _events(db, EVENT_METRIC_DELTA)) == 1
|
||||
|
||||
@@ -118,6 +118,22 @@ class TestBuildRunMessage:
|
||||
assert "标题A" in message
|
||||
assert "https://www.xiaohongshu.com/explore/abc123" in message
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_douyin_notes_link_to_douyin(self, db):
|
||||
"""链接形状按平台走 —— 群里点进去该是能看的作品,不是 404。"""
|
||||
task, run = await _seed(db)
|
||||
task.platform = "dy"
|
||||
_add_event(
|
||||
db, task, run, EVENT_NEW_NOTE, "新作品:标题A",
|
||||
payload={"note_id": "7525082444551310602", "title": "标题A"},
|
||||
)
|
||||
await db.flush()
|
||||
|
||||
message = await notify.build_run_message(db, task, run)
|
||||
|
||||
assert "https://www.douyin.com/video/7525082444551310602" in message
|
||||
assert "xiaohongshu.com" not in message
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_long_note_lists_are_truncated(self, db):
|
||||
"""A first run can find dozens; a wall of text is worse than a count."""
|
||||
|
||||
@@ -34,7 +34,7 @@ from api.monitor.models import (
|
||||
RUN_SUCCESS,
|
||||
)
|
||||
from api.monitor.scheduler import MonitorScheduler
|
||||
from api.monitor.settings import set_cookie
|
||||
from api.monitor.settings import set_cookie, set_setting
|
||||
from tools.time_util import get_current_timestamp
|
||||
|
||||
MS_PER_MINUTE = 60_000
|
||||
@@ -72,12 +72,14 @@ async def executed(monkeypatch):
|
||||
return calls
|
||||
|
||||
|
||||
async def _make_task(next_run_at, enabled: bool = True, interval: int = 60) -> int:
|
||||
async def _make_task(
|
||||
next_run_at, enabled: bool = True, interval: int = 60, platform: str = "xhs"
|
||||
) -> int:
|
||||
async with monitor_db.get_session() as session:
|
||||
now = get_current_timestamp()
|
||||
task = MonitorTask(
|
||||
name="t",
|
||||
platform="xhs",
|
||||
platform=platform,
|
||||
mode=MODE_CREATOR,
|
||||
enabled=enabled,
|
||||
interval_minutes=interval,
|
||||
@@ -145,6 +147,44 @@ class TestFiring:
|
||||
|
||||
assert executed == []
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_the_cookie_gate_reads_the_tasks_own_platform(
|
||||
self, monkeypatch, db, executed
|
||||
):
|
||||
"""cookie 闸门要按任务自己的平台取。
|
||||
|
||||
以前这里是 ``get_cookie(session)``(默认小红书)—— 只有小红书时看不出问题,
|
||||
接上抖音后,抖音任务会因为读的是小红书那份 cookie 而永远不被触发,且不报错。
|
||||
"""
|
||||
monkeypatch.setattr(scheduler_module, "crawler_manager", FakeCrawlerManager(busy=False))
|
||||
async with monitor_db.get_session() as session:
|
||||
await set_cookie(session, "sessionid=dy-secret", "dy")
|
||||
|
||||
task_id = await _make_task(get_current_timestamp() - MS_PER_MINUTE, platform="dy")
|
||||
|
||||
await MonitorScheduler().tick()
|
||||
|
||||
assert executed == [(task_id, "scheduled")]
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_cdp_mode_frees_a_task_from_the_cookie_gate(
|
||||
self, monkeypatch, db, executed
|
||||
):
|
||||
"""开着 CDP 时不该再要求先粘 cookie。
|
||||
|
||||
CDP 模式下登录态来自被接管的那台浏览器,粘不粘 cookie 都由不得它 —— 不放行的话,
|
||||
选了「接管已有 Chrome」却没粘 cookie 的用户会发现任务永远不跑,而且什么错都不报。
|
||||
"""
|
||||
monkeypatch.setattr(scheduler_module, "crawler_manager", FakeCrawlerManager(busy=False))
|
||||
async with monitor_db.get_session() as session:
|
||||
await set_setting(session, "system.cdp_enabled", "true")
|
||||
|
||||
task_id = await _make_task(get_current_timestamp() - MS_PER_MINUTE, platform="dy")
|
||||
|
||||
await MonitorScheduler().tick()
|
||||
|
||||
assert executed == [(task_id, "scheduled")]
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_long_outage_coalesces_into_one_run(self, monkeypatch, db, executed):
|
||||
"""A missed schedule fires once, not once per missed interval."""
|
||||
|
||||
+32
-7
@@ -24,6 +24,7 @@ import pytest_asyncio
|
||||
from sqlalchemy import text
|
||||
|
||||
from api.main import app
|
||||
from api.monitor import adapters
|
||||
from api.monitor import db as monitor_db
|
||||
from api.monitor import platforms
|
||||
from api.monitor.models import MonitorTask
|
||||
@@ -54,7 +55,28 @@ class TestCapabilityMatrix:
|
||||
# what stops the UI offering a platform that can never produce data.
|
||||
assert all("monitor_wired" in p for p in body["platforms"])
|
||||
assert by_value["xhs"]["monitor_wired"] is True
|
||||
assert by_value["dy"]["monitor_wired"] is False
|
||||
assert by_value["dy"]["monitor_wired"] is True
|
||||
|
||||
def test_every_wired_platform_has_an_adapter(self):
|
||||
"""能力矩阵说「接通了」,就必须真的有一套适配管子。
|
||||
|
||||
两个注册表(platforms.PLATFORM_CAPABILITIES 与 adapters.ADAPTERS)分开是有意的
|
||||
—— 前者是给前端看的能力描述,后者是爬虫的管道细节。代价是它们可能漂移,
|
||||
所以在这里钉一条:凡声明接通的,必须能找到适配器。
|
||||
"""
|
||||
for platform in platforms.all_platforms():
|
||||
if platforms.is_monitor_wired(platform):
|
||||
assert adapters.has_adapter(platform), f"{platform} 声明接通但没有适配器"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_target_hints_are_exposed_for_wired_platforms(self, client):
|
||||
"""前端的目标输入框拿它做 placeholder —— 让用户看到本平台该粘什么样的链接。"""
|
||||
body = (await client.get("/api/config/platforms")).json()
|
||||
by_value = {p["value"]: p for p in body["platforms"]}
|
||||
|
||||
assert "douyin.com/user/" in by_value["dy"]["target_hints"]["creator"]
|
||||
assert "douyin.com/video/" in by_value["dy"]["target_hints"]["note"]
|
||||
assert "xiaohongshu.com" in by_value["xhs"]["target_hints"]["creator"]
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_metrics_are_per_platform_and_labelled(self, client):
|
||||
@@ -80,14 +102,17 @@ class TestCapabilityMatrix:
|
||||
class TestTaskCreationGuard:
|
||||
@pytest.mark.asyncio
|
||||
async def test_unwired_platform_is_rejected_with_an_explanation(self, client):
|
||||
"""Accepting it would create a task that silently never produces data."""
|
||||
"""Accepting it would create a task that silently never produces data.
|
||||
|
||||
用 B站 而不是抖音:抖音现在接通了,不再是「已知但未接通」的例子。
|
||||
"""
|
||||
response = await client.post(
|
||||
"/api/monitor/tasks",
|
||||
json={"name": "抖音任务", "mode": "creator", "platform": "dy", "targets": ["x"]},
|
||||
json={"name": "B站任务", "mode": "creator", "platform": "bili", "targets": ["x"]},
|
||||
)
|
||||
assert response.status_code == 400
|
||||
detail = response.json()["detail"]
|
||||
assert "抖音" in detail
|
||||
assert "B站" in detail
|
||||
assert "尚未接通" in detail
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -102,7 +127,7 @@ class TestTaskCreationGuard:
|
||||
async def test_no_task_row_is_created_when_rejected(self, client):
|
||||
await client.post(
|
||||
"/api/monitor/tasks",
|
||||
json={"name": "抖音任务", "mode": "creator", "platform": "dy", "targets": ["x"]},
|
||||
json={"name": "B站任务", "mode": "creator", "platform": "bili", "targets": ["x"]},
|
||||
)
|
||||
assert (await client.get("/api/monitor/tasks")).json()["tasks"] == []
|
||||
|
||||
@@ -126,8 +151,8 @@ class TestTaskCreationGuard:
|
||||
|
||||
class TestPlatformScoping:
|
||||
async def _seed_two_platforms(self, client):
|
||||
"""One real XHS task plus a Douyin task inserted directly, since the API
|
||||
refuses to create the latter."""
|
||||
"""One XHS task created through the API, plus a Douyin task inserted
|
||||
directly so its fields can be pinned exactly."""
|
||||
await client.post(
|
||||
"/api/monitor/tasks",
|
||||
json={"name": "小红书任务", "mode": "creator", "targets": [XHS_TARGET]},
|
||||
|
||||
Reference in New Issue
Block a user