Files
MediaCrawler/tests/test_monitor_digest.py
butubb be917ae6d4
Deploy VitePress site to Pages / build (push) Canceled after 0s
Deploy VitePress site to Pages / Deploy (push) Canceled after 0s
feat(digest): 改成每天 9 点推「昨天」的视频情况
当天还没过完,上午发「今天的」只会是半张表,晚上数据又翻了几倍;改报前一天,
和运营早上看的复盘口径一致。

- default_day() = 昨天,定时 / 手动发送 / 预览三处共用,口径不会再分叉
- 去重标记记的是**被报的那一天**,不是发送时刻 —— 9 点失败、10 点补发成功后
  不会再发一遍
- 推送时间默认 09:00;配置写坏时也按 09:00 兜底,不再是 22:00
2026-10-23 08:35:36 +08:00

203 lines
6.4 KiB
Python

# -*- coding: utf-8 -*-
"""每日「视频情况」图:取数、版式、发送前的大小闸门。"""
from datetime import date, datetime, timedelta
import pytest
import pytest_asyncio
from api.monitor import db as monitor_db
from api.monitor import digest
from api.monitor.models import (
MODE_CREATOR,
MonitorNote,
MonitorNoteMetric,
MonitorTask,
)
def _at(day_offset: int, hour: int = 12) -> int:
"""某天某个整点的毫秒时间戳(``day_offset`` 相对今天,-1 就是昨天)。
不用 ``now - 24h``:凌晨跑测试时它会掉到前天,让本来正确的断言莫名其妙地挂。
"""
day = date.today() + timedelta(days=day_offset)
return int(datetime.combine(day, datetime.min.time()).timestamp() * 1000) + hour * 3_600_000
@pytest_asyncio.fixture
async def db(tmp_path):
monitor_db.set_sqlite_path(tmp_path / "digest.db")
await monitor_db.init_db()
yield monitor_db
await monitor_db.dispose_engine()
async def _task(platform: str = "dy", name: str = "图") -> int:
async with monitor_db.get_session() as session:
task = MonitorTask(
name=name,
platform=platform,
mode=MODE_CREATOR,
enabled=True,
interval_minutes=60,
max_notes_count=20,
enable_comments=False,
max_comments_count=10,
run_timeout_seconds=3600,
created_at=0,
updated_at=0,
)
session.add(task)
await session.flush()
return task.id
async def _note(task_id: int, note_id: str, name: str, published_at: int) -> None:
async with monitor_db.get_session() as session:
session.add(
MonitorNote(
task_id=task_id,
note_id=note_id,
title=f"标题-{note_id}",
hashtags="",
note_url="",
cover="",
creator_hash="hash-a",
creator_name=name,
source_kind="video",
published_at=published_at,
first_seen_at=published_at,
last_seen_at=published_at,
)
)
async def _metric(task_id: int, note_id: str, run_id: int, liked: int | None) -> None:
async with monitor_db.get_session() as session:
session.add(
MonitorNoteMetric(
task_id=task_id,
note_id=note_id,
run_id=run_id,
captured_at=run_id,
liked_count=liked,
comment_count=liked,
collected_count=liked,
share_count=liked,
)
)
def test_the_digest_reports_yesterday():
"""早上九点推的是前一天的账 —— 补发、预览、定时三处都从这里取日子。"""
assert digest.default_day() == date.today() - timedelta(days=1)
@pytest.mark.asyncio
async def test_by_default_only_yesterdays_notes_are_listed(db):
task_id = await _task()
await _note(task_id, "today", "今天", _at(0))
await _note(task_id, "yesterday", "昨天", _at(-1))
async with monitor_db.get_session() as session:
rows = await digest.daily_rows(session, "dy")
assert [row["note_id"] for row in rows] == ["yesterday"]
@pytest.mark.asyncio
async def test_an_explicit_day_wins_over_the_default(db):
task_id = await _task()
await _note(task_id, "today", "今天", _at(0))
await _note(task_id, "yesterday", "昨天", _at(-1))
async with monitor_db.get_session() as session:
rows = await digest.daily_rows(session, "dy", date.today())
assert [row["note_id"] for row in rows] == ["today"]
@pytest.mark.asyncio
async def test_latest_metric_wins_and_rows_sort_by_likes(db):
task_id = await _task()
await _note(task_id, "a", "博主A", _at(-1, 11))
await _note(task_id, "b", "博主B", _at(-1, 10))
await _metric(task_id, "a", run_id=1, liked=5)
await _metric(task_id, "a", run_id=2, liked=99)
await _metric(task_id, "b", run_id=1, liked=500)
async with monitor_db.get_session() as session:
rows = await digest.daily_rows(session, "dy")
assert [row["note_id"] for row in rows] == ["b", "a"] # 点赞降序
assert rows[1]["likes"] == 99 # 取最近一轮,不是先写进去的那轮
@pytest.mark.asyncio
async def test_the_same_note_under_two_tasks_is_listed_once(db):
first = await _task(name="一")
second = await _task(name="二")
await _note(first, "same", "博主A", _at(-1))
await _note(second, "same", "博主A", _at(-1))
async with monitor_db.get_session() as session:
rows = await digest.daily_rows(session, "dy")
assert len(rows) == 1
def _time_reached(send_at: str, now: datetime) -> bool:
from api.monitor.scheduler import _time_reached as reached
return reached(now, send_at)
def test_time_reached_handles_bad_config():
now = datetime(2026, 10, 23, 8, 30)
assert _time_reached("08:00", now) is True
assert _time_reached("09:00", now) is False
assert _time_reached("09:00", datetime(2026, 10, 23, 9, 0)) is True
# 写错就按 09:00 算,而不是永远不发
assert _time_reached("九点半", datetime(2026, 10, 23, 9, 1)) is True
assert _time_reached("", datetime(2026, 10, 23, 8, 59)) is False
@pytest.mark.skipif(digest._font_path() is None, reason="本机没有中文字体")
def test_render_table_returns_a_png():
rows = [
{
"note_id": "1",
"creator": "博主A",
"title": "一条标题",
"hashtags": "",
"likes": 12,
"comments": 3,
"collected": 4,
"shares": 5,
}
]
image = digest.render_table(rows, date.today(), "抖音")
assert image.startswith(b"\x89PNG")
assert len(image) > 1000
@pytest.mark.skipif(digest._font_path() is None, reason="本机没有中文字体")
def test_render_table_handles_an_empty_day():
image = digest.render_table([], date.today(), "抖音")
assert image.startswith(b"\x89PNG")
@pytest.mark.asyncio
async def test_image_sender_guards_missing_webhook_and_oversize():
from api.monitor import notify
ok, detail = await notify.send_wecom_image("", b"x")
assert ok is False and "未配置" in detail
ok, detail = await notify.send_wecom_image(
"http://example.invalid", b"x" * (notify.WECOM_IMAGE_MAX_BYTES + 1)
)
assert ok is False and "太大" in detail