Files
MediaCrawler/tests/test_monitor_matrix.py
T
butubb ffafd90073
Deploy VitePress site to Pages / build (push) Canceled after 0s
Deploy VitePress site to Pages / Deploy (push) Canceled after 0s
feat(report): 格子悬停显示当天点赞/评论/收藏/分享;报表可按任务过滤
两件事:

1. **格子悬停提示**(matrix.html)
   每个有数据的格子挂一个自定义浮层,显示「日期 · 博主 / 条数 / 点赞 / 评论 /
   收藏 / 分享 / 标签」。浮层 `pointer-events: none`,否则它会盖住格子触发
   mouseleave,自己闪个不停;表格滚动时主动收起。内容用 DOM 拼而不是
   innerHTML —— 昵称来自平台,不能当 HTML 解释。

2. **任务过滤**(/api/monitor/matrix 增加 task_id)
   平台下拉旁边加「任务」下拉,数据来自现有的 /api/monitor/tasks。
   `task_id` 会先校验平台归属,传错平台宁可返回空,也不给出别的平台的数。
   选择会写进地址栏,可以直接收藏某一组条件。

指标口径:每篇作品取**最近一轮**快照(run_id 最大)再按格子求和。未知是 None
不是 0 —— 提示里显示成「—」,避免把「没读到」说成「没有互动」。

测试:10 条(新增指标求和取最新一轮、未知为 None、任务过滤、跨平台任务被拒)。
2026-10-22 14:11:38 +08:00

301 lines
9.6 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- coding: utf-8 -*-
"""标签矩阵:日期 × 博主 → 当天发出去的标签。
这个接口的形状(长表 + 前端转置)是被 MySQL 5.7 逼出来的 —— 没有 PIVOT,列数又随
博主变化。所以这里重点测**分组与去重**,那才是容易出错的地方:
* 同一天同一个号的几条作品要合成一格,计数相加、标签取并集且保序;
* 同一个作品挂在两个任务下(``monitor_note`` 的唯一键是 ``(task_id, note_id)``)
只能算一次,否则计数翻倍;
* 窗口外的老作品不出现。
"""
from datetime import datetime, timedelta
import httpx
import pytest
import pytest_asyncio
from api.main import app
from api.monitor import db as monitor_db
from api.monitor import service
from api.monitor.models import (
MODE_CREATOR,
MonitorNote,
MonitorNoteMetric,
MonitorNoteTag,
MonitorTag,
MonitorTask,
)
from tools.time_util import get_current_timestamp
DAY_MS = 86_400_000
def _day(ms: int) -> str:
return datetime.fromtimestamp(ms / 1000).strftime("%Y-%m-%d")
@pytest_asyncio.fixture
async def db(tmp_path):
monitor_db.set_sqlite_path(tmp_path / "matrix.db")
await monitor_db.init_db()
yield monitor_db
await monitor_db.dispose_engine()
@pytest_asyncio.fixture
async def client(tmp_path):
monitor_db.set_sqlite_path(tmp_path / "matrix_api.db")
await monitor_db.init_db()
transport = httpx.ASGITransport(app=app)
async with httpx.AsyncClient(transport=transport, base_url="http://test") as http:
yield http
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, creator_hash: str = "hash-a"
) -> None:
async with monitor_db.get_session() as session:
session.add(
MonitorNote(
task_id=task_id,
note_id=note_id,
title="t",
note_url="",
cover="",
creator_hash=creator_hash,
creator_name=name,
source_kind="video",
published_at=published_at,
first_seen_at=published_at,
last_seen_at=published_at,
)
)
async def _tag(name: str, sort_order: int) -> int:
async with monitor_db.get_session() as session:
tag = MonitorTag(name=name, color="cyan", keywords="", sort_order=sort_order, created_at=0)
session.add(tag)
await session.flush()
return tag.id
async def _attach(platform: str, note_id: str, tag_id: int) -> None:
async with monitor_db.get_session() as session:
session.add(
MonitorNoteTag(platform=platform, note_id=note_id, tag_id=tag_id, created_at=0)
)
async def _metric(
task_id: int,
note_id: str,
run_id: int,
liked: int | None = None,
comment: int | None = None,
collected: int | None = None,
share: int | None = 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=comment,
collected_count=collected,
share_count=share,
)
)
@pytest.mark.asyncio
async def test_same_day_notes_collapse_with_tags_union(db):
task_id = await _task()
today = get_current_timestamp() - 1000
await _note(task_id, "n1", "博主A", today)
await _note(task_id, "n2", "博主A", today)
dazibao = await _tag("大字报", 1)
yanghao = await _tag("养号", 2)
await _attach("dy", "n1", dazibao)
await _attach("dy", "n2", yanghao)
await _attach("dy", "n2", dazibao)
async with monitor_db.get_session() as session:
data = await service.daily_tag_matrix(session, "dy", days=7)
assert data["dates"] == [_day(today)]
assert [c["name"] for c in data["creators"]] == ["博主A"]
cell = data["cells"][_day(today)]["hash-a"]
assert cell["count"] == 2
# 按词表 order 排序,不是按出现顺序
assert cell["tags"] == ["大字报", "养号"]
@pytest.mark.asyncio
async def test_dates_newest_first_and_creators_sorted(db):
task_id = await _task()
now = get_current_timestamp()
await _note(task_id, "n1", "B博主", now - 2 * DAY_MS, creator_hash="hash-b")
await _note(task_id, "n2", "A博主", now - 1000, creator_hash="hash-a")
async with monitor_db.get_session() as session:
data = await service.daily_tag_matrix(session, "dy", days=7)
assert data["dates"] == sorted(data["dates"], reverse=True)
assert [c["name"] for c in data["creators"]] == ["A博主", "B博主"]
@pytest.mark.asyncio
async def test_notes_outside_the_window_are_excluded(db):
task_id = await _task()
now = get_current_timestamp()
await _note(task_id, "fresh", "博主A", now - 1000)
await _note(task_id, "old", "博主A", now - 40 * DAY_MS)
async with monitor_db.get_session() as session:
data = await service.daily_tag_matrix(session, "dy", days=7)
assert data["dates"] == [_day(now - 1000)]
assert data["cells"][_day(now - 1000)]["hash-a"]["count"] == 1
@pytest.mark.asyncio
async def test_the_same_note_under_two_tasks_counts_once(db):
first = await _task(name="任务一")
second = await _task(name="任务二")
now = get_current_timestamp() - 1000
# 同一个作品被两个任务各记了一行
await _note(first, "same", "博主A", now)
await _note(second, "same", "博主A", now)
async with monitor_db.get_session() as session:
data = await service.daily_tag_matrix(session, "dy", days=7)
assert data["cells"][_day(now)]["hash-a"]["count"] == 1
@pytest.mark.asyncio
async def test_no_tasks_returns_an_empty_shape(db):
async with monitor_db.get_session() as session:
data = await service.daily_tag_matrix(session, "dy", days=7)
assert data == {
"platform": "dy",
"days": 7,
"task_id": None,
"dates": [],
"creators": [],
"cells": {},
}
@pytest.mark.asyncio
async def test_cell_sums_the_latest_metric_of_each_note(db):
task_id = await _task()
now = get_current_timestamp() - 1000
await _note(task_id, "n1", "博主A", now)
await _note(task_id, "n2", "博主A", now)
# 同一篇有两轮快照,只取 run_id 最大的那一轮
await _metric(task_id, "n1", run_id=1, liked=10, comment=1, collected=2, share=3)
await _metric(task_id, "n1", run_id=2, liked=20, comment=2, collected=4, share=5)
await _metric(task_id, "n2", run_id=1, liked=5, comment=None, collected=1, share=0)
async with monitor_db.get_session() as session:
data = await service.daily_tag_matrix(session, "dy", days=7)
cell = data["cells"][_day(now)]["hash-a"]
assert cell["count"] == 2
assert cell["likes"] == 25
assert cell["comments"] == 2 # None 不参与求和
assert cell["collected"] == 5
assert cell["shares"] == 5
@pytest.mark.asyncio
async def test_missing_metrics_are_none_not_zero(db):
task_id = await _task()
now = get_current_timestamp() - 1000
await _note(task_id, "n1", "博主A", now)
async with monitor_db.get_session() as session:
data = await service.daily_tag_matrix(session, "dy", days=7)
cell = data["cells"][_day(now)]["hash-a"]
# 「不知道」和「是 0」要分开 —— 前者在提示里显示成「—」
assert cell["likes"] is None
assert cell["comments"] is None
@pytest.mark.asyncio
async def test_task_filter_scopes_the_matrix(db):
first = await _task(name="任务一")
second = await _task(name="任务二")
now = get_current_timestamp() - 1000
await _note(first, "a", "博主A", now, creator_hash="hash-a")
await _note(second, "b", "博主B", now, creator_hash="hash-b")
async with monitor_db.get_session() as session:
data = await service.daily_tag_matrix(session, "dy", days=7, task_id=second)
assert data["task_id"] == second
assert [c["name"] for c in data["creators"]] == ["博主B"]
@pytest.mark.asyncio
async def test_task_from_another_platform_is_rejected(db):
xhs_task = await _task(platform="xhs")
async with monitor_db.get_session() as session:
data = await service.daily_tag_matrix(session, "dy", days=7, task_id=xhs_task)
assert data["dates"] == []
@pytest.mark.asyncio
async def test_endpoint_returns_the_long_shape(client):
task_id = await _task()
now = get_current_timestamp() - 1000
await _note(task_id, "n1", "博主A", now)
tag_id = await _tag("大字报", 1)
await _attach("dy", "n1", tag_id)
response = await client.get("/api/monitor/matrix", params={"platform": "dy", "days": 7})
assert response.status_code == 200
body = response.json()
assert body["dates"] == [_day(now)]
assert body["creators"][0]["name"] == "博主A"
cell = body["cells"][_day(now)]["hash-a"]
assert cell["count"] == 1
assert cell["tags"] == ["大字报"]
assert "likes" in cell