Files
MediaCrawler/tests/test_monitor_superdir.py
T
butubb d30ccb196a
Deploy VitePress site to Pages / build (push) Canceled after 0s
Deploy VitePress site to Pages / Deploy (push) Canceled after 0s
feat(monitor): 超级编导账号密码 + token 失效自动续期
设置里新增「超级编导账号」「超级编导密码」(密码是 secret,不回显)。查询/
自动追加撞上 4017/5006 等登录失效错误时,用它们调密码登录接口换新 token,
写回设置,再把整段操作重试一次。

- 续期加锁:超级编导是单登录态,新登录会顶掉旧 token;并发续期只会互相作废。
- 重试放在整段而不是单个请求:一次预览并发十几个请求,请求层重试会变成
  十几个并发登录。
- 没有 token 但配了账号密码时也直接登录,不必先粘一次 token。
- 登录失败(1002 密码错误 / 10006 未设密码)原样报出来,不吞成「token 失效」。
2026-10-25 11:08:23 +08:00

718 lines
26 KiB
Python

# -*- coding: utf-8 -*-
"""超级编导导入:区间筛选、去重、建任务时的作品 id,以及那些「看起来像没数据」的坑。"""
from datetime import date, datetime, timezone
import pytest
import pytest_asyncio
from sqlalchemy import select
from api.monitor import db as monitor_db
from api.monitor import superdir
from api.monitor.models import MODE_NOTE, MonitorTarget
from tools.time_util import get_current_timestamp
AWEME_A = "7699073324462902970"
AWEME_B = "7580311223398286720"
AWEME_C = "7638788935163048838"
def _video(aweme_id: str, **overrides):
record = {
"share_url": f"https://www.douyin.com/video//{aweme_id}",
"nickname": "帆",
"title": "美女请多营业",
"published_at": 1792748542,
"play_count": 243,
"digg_count": 9,
"comment_count": 0,
"share_count": 0,
"video_status": 5,
}
record.update(overrides)
return record
def _activity(activity_id: int, day: date, title: str = "活动"):
return {
"id": activity_id,
"title": title,
"created_at": superdir._day_start(day) + 3600,
}
class TestDayBounds:
def test_days_are_east_eight_not_the_containers_timezone(self):
"""created_at 是「本地时区」的 Unix 秒,而容器通常跑在 UTC。
按容器 localtime 算边界,整段查询会错开 8 小时:早上的「今天」会算进昨晚的活动。
"""
assert superdir._day_start(date(2026, 10, 21)) == int(
datetime(2026, 10, 20, 16, 0, 0, tzinfo=timezone.utc).timestamp()
)
def test_the_whole_day_is_included(self):
start = superdir._day_start(date(2026, 10, 21))
end = superdir._day_end(date(2026, 10, 21))
assert end - start == 86399
class TestPreview:
@pytest.mark.asyncio
async def test_only_activities_created_in_the_range_are_fetched(self, monkeypatch):
fetched: list = []
async def fake_activities(token, client):
return [
_activity(1, date(2026, 10, 19), "区间外"),
_activity(2, date(2026, 10, 21), "目标活动"),
]
async def fake_videos(token, activity_id, client):
fetched.append(activity_id)
return [_video(AWEME_A)]
async def fake_token(session, platform=superdir.adapters.PLATFORM_DY):
return "token"
monkeypatch.setattr(superdir, "_fetch_activities", fake_activities)
monkeypatch.setattr(superdir, "_fetch_videos", fake_videos)
monkeypatch.setattr(superdir, "get_token", fake_token)
result = await superdir.preview(None, "2026-10-21", "2026-10-21")
assert fetched == [2]
assert result["activities"] == 1
assert result["videos"] == 1
assert result["rows"][0]["aweme_id"] == AWEME_A
@pytest.mark.asyncio
async def test_matched_activities_explain_a_zero_video_result(self, monkeypatch):
"""活动建了但还没人发布 —— 0 条作品是真的,界面上得说得出是哪几个活动。
实测踩到过:运营按「10-22 ~ 10-24」查,返回 4 个活动、0 条作品,以为链接没取到。
那 4 个活动全是排期在未来的(10.26/10.27/10.28/10.29),当然还没有作品。
"""
async def fake_activities(token, client):
return [
{
"id": 9,
"title": "10.26 漫展",
"created_at": superdir._day_start(date(2026, 10, 22)) + 3600,
"total_count": 0,
"published_count": 0,
}
]
async def fake_videos(token, activity_id, client):
return []
async def fake_token(session, platform=superdir.adapters.PLATFORM_DY):
return "token"
monkeypatch.setattr(superdir, "_fetch_activities", fake_activities)
monkeypatch.setattr(superdir, "_fetch_videos", fake_videos)
monkeypatch.setattr(superdir, "get_token", fake_token)
result = await superdir.preview(None, "2026-10-22", "2026-10-24")
assert result["videos"] == 0
assert result["rows"] == []
assert result["matched_activities"] == [
{
"id": 9,
"title": "10.26 漫展",
"created_at": superdir._day_start(date(2026, 10, 22)) + 3600,
"total_count": 0,
"published_count": 0,
}
]
@pytest.mark.asyncio
async def test_unpublished_and_private_videos_are_skipped(self, monkeypatch):
async def fake_activities(token, client):
return [_activity(2, date(2026, 10, 21))]
async def fake_videos(token, activity_id, client):
return [
_video(AWEME_A),
# 还没发布:没有 share_url
_video(AWEME_B, share_url=""),
# 私密:链接点不开,拉进监控每轮都会失败一次
_video(AWEME_C, video_status=2),
]
async def fake_token(session, platform=superdir.adapters.PLATFORM_DY):
return "token"
monkeypatch.setattr(superdir, "_fetch_activities", fake_activities)
monkeypatch.setattr(superdir, "_fetch_videos", fake_videos)
monkeypatch.setattr(superdir, "get_token", fake_token)
result = await superdir.preview(None, "2026-10-21", "2026-10-21")
assert [row["aweme_id"] for row in result["rows"]] == [AWEME_A]
assert result["skipped"] == 2
@pytest.mark.asyncio
async def test_the_same_video_under_two_activities_is_one_row(self, monkeypatch):
"""分发活动被复制过,同一件作品会挂在两个活动下面 —— 建任务时不能重复。"""
async def fake_activities(token, client):
return [
_activity(2, date(2026, 10, 21)),
_activity(3, date(2026, 10, 21)),
]
async def fake_videos(token, activity_id, client):
return [_video(AWEME_A)]
async def fake_token(session, platform=superdir.adapters.PLATFORM_DY):
return "token"
monkeypatch.setattr(superdir, "_fetch_activities", fake_activities)
monkeypatch.setattr(superdir, "_fetch_videos", fake_videos)
monkeypatch.setattr(superdir, "get_token", fake_token)
result = await superdir.preview(None, "2026-10-21", "2026-10-21")
assert len(result["rows"]) == 1
@pytest.mark.asyncio
async def test_one_broken_activity_does_not_sink_the_preview(self, monkeypatch):
async def fake_activities(token, client):
return [
_activity(2, date(2026, 10, 21), "坏的"),
_activity(3, date(2026, 10, 21), "好的"),
]
async def fake_videos(token, activity_id, client):
if activity_id == 2:
raise superdir.SuperDirError(500, "取作品失败")
return [_video(AWEME_A)]
async def fake_token(session, platform=superdir.adapters.PLATFORM_DY):
return "token"
monkeypatch.setattr(superdir, "_fetch_activities", fake_activities)
monkeypatch.setattr(superdir, "_fetch_videos", fake_videos)
monkeypatch.setattr(superdir, "get_token", fake_token)
result = await superdir.preview(None, "2026-10-21", "2026-10-21")
assert len(result["rows"]) == 1
assert [item["activity_id"] for item in result["failed_activities"]] == [2]
@pytest.mark.asyncio
async def test_more_than_the_limit_is_truncated_not_silently_dropped(self, monkeypatch):
async def fake_activities(token, client):
return [_activity(2, date(2026, 10, 21))]
async def fake_videos(token, activity_id, client):
return [_video(str(7000000000000000000 + i)) for i in range(3)]
async def fake_token(session, platform=superdir.adapters.PLATFORM_DY):
return "token"
monkeypatch.setattr(superdir, "_fetch_activities", fake_activities)
monkeypatch.setattr(superdir, "_fetch_videos", fake_videos)
monkeypatch.setattr(superdir, "get_token", fake_token)
monkeypatch.setattr(superdir, "MAX_TARGETS", 2)
result = await superdir.preview(None, "2026-10-21", "2026-10-21")
assert result["truncated"] is True
assert result["videos"] == 3
assert len(result["rows"]) == 2
@pytest.mark.asyncio
async def test_without_a_token_the_message_says_where_to_put_it(
self, session, monkeypatch
):
async def fake_token(session, platform=superdir.adapters.PLATFORM_DY):
return ""
monkeypatch.setattr(superdir, "get_token", fake_token)
with pytest.raises(superdir.SuperDirError) as excinfo:
await superdir.preview(session, "2026-10-21", "2026-10-21")
assert "设置" in str(excinfo.value)
@pytest.mark.asyncio
async def test_a_backwards_range_is_rejected(self):
with pytest.raises(ValueError):
await superdir.preview(None, "2026-10-21", "2026-10-20")
@pytest.mark.asyncio
async def test_a_too_wide_range_is_rejected(self):
with pytest.raises(ValueError):
await superdir.preview(None, "2026-01-01", "2026-03-01")
class TestPagination:
@pytest.mark.asyncio
async def test_pages_stop_at_total(self, monkeypatch):
calls: list = []
async def fake_request(path, params, token, client):
calls.append(params["page"])
if params["page"] == 1:
return {"items": [{"id": 1}, {"id": 2}], "total": 3}
return {"items": [{"id": 3}], "total": 3}
monkeypatch.setattr(superdir, "_request", fake_request)
items = await superdir._paginate(
"/x", {}, "token", None, page_size=2, max_pages=10
)
assert [item["id"] for item in items] == [1, 2, 3]
assert calls == [1, 2]
class TestActivityPaging:
@pytest.mark.asyncio
async def test_every_activity_page_is_fetched(self, monkeypatch):
"""活动列表没有日期过滤,每次查询都要把整个历史翻完 —— 一页都不能少。"""
calls: list = []
async def fake_request(path, params, token, client):
calls.append(params["page"])
pages = {
1: [{"id": 1}, {"id": 2}],
2: [{"id": 3}, {"id": 4}],
3: [{"id": 5}],
}
return {"items": pages[params["page"]], "total": 5}
monkeypatch.setattr(superdir, "_request", fake_request)
monkeypatch.setattr(superdir, "ACTIVITY_PAGE_SIZE", 2)
items = await superdir._fetch_activities("token", None)
assert sorted(calls) == [1, 2, 3]
assert [item["id"] for item in items] == [1, 2, 3, 4, 5]
@pytest.mark.asyncio
async def test_a_failed_page_fails_the_whole_list_not_a_partial_one(self, monkeypatch):
"""少一页 = 少一批活动,看上去却像「这段时间就这些」—— 必须报错。"""
async def fake_request(path, params, token, client):
if params["page"] == 2:
raise superdir.SuperDirError(500, "这一页没取到")
return {"items": [{"id": 1}, {"id": 2}], "total": 5}
monkeypatch.setattr(superdir, "_request", fake_request)
monkeypatch.setattr(superdir, "ACTIVITY_PAGE_SIZE", 2)
with pytest.raises(superdir.SuperDirError):
await superdir._fetch_activities("token", None)
class TestErrorHints:
def test_a_relogin_error_explains_itself(self):
error = superdir._error({"code": 4017, "message": "账号已在别处登录"})
assert "4017" in str(error)
assert "自动用账号密码续期" in str(error)
@pytest_asyncio.fixture
async def session(tmp_path):
monitor_db.set_sqlite_path(tmp_path / "monitor.db")
await monitor_db.init_db()
async with monitor_db.get_session() as db_session:
yield db_session
await monitor_db.dispose_engine()
class TestCreateTask:
@pytest.mark.asyncio
async def test_targets_are_bare_aweme_ids_not_share_urls(self, session):
"""``share_url`` 是双斜杠形态,``prepare_target`` 认不出来。
原样存进去的话,采集时会把一整条链接当作品 id 去请求,每轮都抓不到东西 ——
而且不会报错,只会安静地什么也没有。
"""
task, count = await superdir.create_task(
session,
[
f"https://www.douyin.com/video//{AWEME_A}",
f"https://www.douyin.com/video//{AWEME_A}",
f"https://www.douyin.com/video/{AWEME_B}",
],
"测试导入",
)
targets = list(
await session.scalars(
select(MonitorTarget).where(MonitorTarget.task_id == task.id)
)
)
assert count == 2
assert task.mode == MODE_NOTE
assert sorted(target.external_id for target in targets) == sorted(
[AWEME_A, AWEME_B]
)
@pytest.mark.asyncio
async def test_comments_are_off_by_default(self, session):
"""批量导入动辄上百条,评论默认抓的话请求量直接翻倍。"""
task, _ = await superdir.create_task(session, [AWEME_A], "")
assert task.enable_comments is False
@pytest.mark.asyncio
async def test_a_name_is_generated_when_blank(self, session):
task, _ = await superdir.create_task(session, [AWEME_A], " ")
assert task.name.startswith("超级编导导入")
@pytest.mark.asyncio
async def test_links_without_an_aweme_id_are_rejected(self, session):
with pytest.raises(ValueError):
await superdir.create_task(session, ["https://example.com/nothing"], "")
@pytest.mark.asyncio
async def test_append_adds_only_the_new_links(self, session):
"""「一个任务一直更新」:每天补一批,已有的不重复、也不丢掉。"""
task, _ = await superdir.create_task(session, [AWEME_A], "同一批")
task, added, total = await superdir.append_task(
session, task.id, [AWEME_A, AWEME_B, f"https://www.douyin.com/video//{AWEME_B}"]
)
assert (added, total) == (1, 2)
targets = list(
await session.scalars(
select(MonitorTarget).where(MonitorTarget.task_id == task.id)
)
)
assert sorted(target.external_id for target in targets) == sorted(
[AWEME_A, AWEME_B]
)
@pytest.mark.asyncio
async def test_appending_nothing_new_is_a_noop(self, session):
task, _ = await superdir.create_task(session, [AWEME_A], "")
_task, added, total = await superdir.append_task(session, task.id, [AWEME_A])
assert (added, total) == (0, 1)
@pytest.mark.asyncio
async def test_append_refuses_a_creator_task(self, session):
"""博主模式的目标是主页,往里面塞作品 id 只会让那个目标永远抓不到东西。"""
task = await superdir.service.create_task(
session,
{
"name": "博主任务",
"platform": "dy",
"mode": "creator",
"targets": ["MS4wLjABAAAAsomebody"],
},
)
with pytest.raises(ValueError):
await superdir.append_task(session, task.id, [AWEME_A])
@pytest.mark.asyncio
async def test_append_to_a_missing_task_is_rejected(self, session):
with pytest.raises(ValueError):
await superdir.append_task(session, 99999, [AWEME_A])
class TestTokenRenewal:
"""Token 过期(4017/5006)时用设置里的账号密码自动续期,并重试整段。"""
async def _set_token(
self,
session,
value: str = "old-token",
username: str = "15655035256",
password: str = "pw",
):
await superdir.app_settings.update(
session,
{
"platform.dy.superdir_token": value,
"platform.dy.superdir_username": username,
"platform.dy.superdir_password": password,
},
"dy",
)
@pytest.mark.asyncio
async def test_an_expired_token_is_renewed_and_the_operation_retried(
self, session, monkeypatch
):
await self._set_token(session)
seen = []
async def fake_login(username, password):
seen.append((username, password))
return {"token": "new-token"}
monkeypatch.setattr(superdir, "_login", fake_login)
calls = []
async def operation(token):
calls.append(token)
if token == "old-token":
raise superdir.SuperDirError(4017, "登录已过期")
return "ok"
result = await superdir._run_with_token(session, "dy", operation)
assert result == "ok"
assert calls == ["old-token", "new-token"]
assert seen == [("15655035256", "pw")]
# 新 token 写回设置,后面的查询就不会再撞一次墙。
assert await superdir.get_token(session) == "new-token"
@pytest.mark.asyncio
async def test_a_non_auth_error_is_not_retried(self, session, monkeypatch):
await self._set_token(session)
async def must_not_login(*args, **kwargs):
raise AssertionError("非登录类错误不该去登录")
monkeypatch.setattr(superdir, "_login", must_not_login)
calls = []
async def operation(token):
calls.append(token)
raise superdir.SuperDirError(500, "服务端错误")
with pytest.raises(superdir.SuperDirError):
await superdir._run_with_token(session, "dy", operation)
assert calls == ["old-token"]
@pytest.mark.asyncio
async def test_without_credentials_the_message_says_where_to_configure(
self, session
):
await self._set_token(session, username="", password="")
async def operation(token):
raise superdir.SuperDirError(4017, "登录已过期")
with pytest.raises(superdir.SuperDirError) as excinfo:
await superdir._run_with_token(session, "dy", operation)
assert "设置" in str(excinfo.value)
@pytest.mark.asyncio
async def test_a_wrong_password_surfaces_1002(self, session, monkeypatch):
"""登录失败不能吞成「token 失效」,要把平台的原话(含剩余次数)报出来。"""
await self._set_token(session)
async def fake_login(*args, **kwargs):
raise superdir._error(
{"code": 1002, "message": "登录密码错误,今日剩余尝试次数 4 次"}
)
monkeypatch.setattr(superdir, "_login", fake_login)
async def operation(token):
raise superdir.SuperDirError(4017, "登录已过期")
with pytest.raises(superdir.SuperDirError) as excinfo:
await superdir._run_with_token(session, "dy", operation)
assert "1002" in str(excinfo.value)
assert "密码" in str(excinfo.value)
class TestAutoAppend:
"""每隔 N 分钟自动把新发布的作品补进同一个任务。"""
async def _task(self, session):
task, _ = await superdir.create_task(session, [AWEME_A], "自动追加")
return task
@pytest.fixture(autouse=True)
def _token(self, monkeypatch):
async def fake_token(session, platform=superdir.adapters.PLATFORM_DY):
return "token"
monkeypatch.setattr(superdir, "get_token", fake_token)
@pytest.mark.asyncio
async def test_sync_appends_only_new_public_videos(self, session, monkeypatch):
task = await self._task(session)
task.superdir_auto_interval_minutes = 120
async def fake_fetch(token, client, start_ts, end_ts):
return [
_video(AWEME_A), # 已经在任务里
_video(AWEME_B), # 新的
_video(AWEME_C, video_status=2), # 私密,不收
]
monkeypatch.setattr(superdir, "_fetch_published", fake_fetch)
result = await superdir.sync_task(session, task)
assert result == {"fetched": 2, "added": 1, "total": 2}
assert task.superdir_auto_last_added == 1
assert task.superdir_auto_last_error == ""
assert task.superdir_auto_last_at is not None
assert task.superdir_auto_next_at is not None
targets = list(
await session.scalars(
select(MonitorTarget).where(MonitorTarget.task_id == task.id)
)
)
assert sorted(t.external_id for t in targets) == sorted([AWEME_A, AWEME_B])
@pytest.mark.asyncio
async def test_the_same_window_twice_adds_nothing_the_second_time(
self, session, monkeypatch
):
task = await self._task(session)
async def fake_fetch(token, client, start_ts, end_ts):
return [_video(AWEME_A), _video(AWEME_B)]
monkeypatch.setattr(superdir, "_fetch_published", fake_fetch)
await superdir.sync_task(session, task)
# 窗口重叠一小时是故意的(接口有索引延迟),重复的靠去重消化。
result = await superdir.sync_task(session, task)
assert result["added"] == 0
assert result["total"] == 2
assert task.superdir_auto_last_added == 0
assert task.superdir_auto_last_error == ""
@pytest.mark.asyncio
async def test_nothing_new_still_advances_the_clock(self, session, monkeypatch):
task = await self._task(session)
async def fake_fetch(token, client, start_ts, end_ts):
return []
monkeypatch.setattr(superdir, "_fetch_published", fake_fetch)
result = await superdir.sync_task(session, task)
assert result["added"] == 0
assert result["total"] == 1
assert task.superdir_auto_last_error == ""
assert task.superdir_auto_last_at is not None
# 下一次在「这次成功」之后一个间隔,而不是更早。
assert (
task.superdir_auto_next_at
== task.superdir_auto_last_at + 120 * 60_000
)
@pytest.mark.asyncio
async def test_the_first_check_covers_all_of_today(self, session, monkeypatch):
"""窗口起点是**今天 00:00**,不是「任务创建时刻」也不是「一个间隔之前」。
活动可以提前几天建好(今天把后面几天的活动都建了),视频却是之后才发 ——
按任务/活动创建时间筛,这些晚发的作品整批都看不到。
"""
task = await self._task(session)
captured = {}
async def fake_fetch(token, client, start_ts, end_ts):
captured["start"] = start_ts
captured["end"] = end_ts
return []
monkeypatch.setattr(superdir, "_fetch_published", fake_fetch)
today = superdir._day_start(datetime.now(superdir.CN_TZ).date())
await superdir.sync_task(session, task)
tomorrow = superdir._day_start(datetime.now(superdir.CN_TZ).date())
# 允许恰好跨过午夜:两次取日期之间可能已经换天了。
assert captured["start"] in (today, tomorrow)
assert captured["end"] >= captured["start"]
@pytest.mark.asyncio
async def test_a_downtime_gap_is_still_covered(self, session, monkeypatch):
"""进程停过几天时不能只看今天 —— 那几天的新作品会永远漏掉。"""
task = await self._task(session)
last = get_current_timestamp() - 3 * 86400 * 1000
task.superdir_auto_last_at = last
captured = {}
async def fake_fetch(token, client, start_ts, end_ts):
captured["start"] = start_ts
return []
monkeypatch.setattr(superdir, "_fetch_published", fake_fetch)
await superdir.sync_task(session, task)
assert captured["start"] <= last // 1000 - superdir.SYNC_OVERLAP_SECONDS
@pytest.mark.asyncio
async def test_a_failure_does_not_advance_the_watermark(self, session, monkeypatch):
"""接口挂了的时候 last_at 必须停住,否则恢复后那段时间的作品就漏了。"""
task = await self._task(session)
async def boom(token, client, start_ts, end_ts):
raise superdir.SuperDirError(500, "接口挂了")
monkeypatch.setattr(superdir, "_fetch_published", boom)
with pytest.raises(superdir.SuperDirError):
await superdir.sync_task(session, task)
assert task.superdir_auto_last_at is None
assert task.superdir_auto_last_added is None
class TestAutoAppendScheduling:
@pytest.mark.asyncio
async def test_enabling_schedules_the_first_check_immediately(self, session):
task, _ = await superdir.create_task(session, [AWEME_A], "自动")
await superdir.service.update_task(
session, task.id, {"superdir_auto_enabled": True}
)
assert task.superdir_auto_enabled is True
assert task.superdir_auto_next_at is not None
@pytest.mark.asyncio
async def test_disabling_clears_the_clock(self, session):
task, _ = await superdir.create_task(session, [AWEME_A], "自动")
await superdir.service.update_task(
session, task.id, {"superdir_auto_enabled": True}
)
await superdir.service.update_task(
session, task.id, {"superdir_auto_enabled": False}
)
assert task.superdir_auto_enabled is False
assert task.superdir_auto_next_at is None
@pytest.mark.asyncio
async def test_a_creator_task_cannot_enable_it(self, session):
task = await superdir.service.create_task(
session,
{
"name": "博主任务",
"platform": "dy",
"mode": "creator",
"targets": ["MS4wLjABAAAAsomebody"],
},
)
with pytest.raises(ValueError):
await superdir.service.update_task(
session, task.id, {"superdir_auto_enabled": True}
)