不再依赖外部报表工具。`/report/matrix` 是后端直接发的一份静态 HTML(不走 Vite
构建,所以不会被 `api/webui` 的产物清理覆盖),数据来自 `/api/monitor/matrix`
(同一套鉴权,靠同源 cookie)。
形状正是用户要的:行=日期(新到旧),列=博主,格子里是当天发出去的标签。
三种格子语义分开:空白=当天没发、无标签=发了没打标签、标签=实际打上的。
**为什么转置放在前端。** MySQL 5.7 没有 PIVOT,而列数随博主变化;写死昵称的
SQL 一改名就废(上一轮的教训)。所以接口只返回长表结构
`{dates, creators, cells}`,前端按 creator_hash 转置 —— 改名、加博主都不用动
任何 SQL。分组/去重放在 `service.daily_tag_matrix` 里做(Python 侧),这样测试
能跑在 SQLite 上,不用 MySQL 的日期函数。
去重特意处理了两件事:
* 同一天同一个号的多条作品合成一格,计数相加、标签取并集并按词表顺序;
* 同一个作品挂在两个任务下(唯一键是 (task_id, note_id))只算一次,否则计数翻倍。
侧边栏加「标签矩阵」入口,新标签页打开(宽表要占满整屏)。
测试:6 条,覆盖分组/排序/窗口/跨任务去重/空结果/接口形状。
209 lines
6.6 KiB
Python
209 lines
6.6 KiB
Python
# -*- 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,
|
||
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)
|
||
)
|
||
|
||
|
||
@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,
|
||
"dates": [],
|
||
"creators": [],
|
||
"cells": {},
|
||
}
|
||
|
||
|
||
@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"
|
||
assert body["cells"][_day(now)]["hash-a"] == {"count": 1, "tags": ["大字报"]}
|