实测踩到:按 10-22~10-24 查返回「活动 4 个、作品 0 条」,看着像链接没取到。 那 4 个活动全是排期在未来的(10.26/10.27/10.28/10.29),还没人发布。活动名 里的日期只是名字,不是创建时间 —— 这句也写进空态里。
375 lines
14 KiB
Python
375 lines
14 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
|
|
|
|
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, 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(None, "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"], "")
|