# -*- 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, MonitorCreatorStat, 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", title: str = "t", ) -> None: async with monitor_db.get_session() as session: session.add( MonitorNote( task_id=task_id, note_id=note_id, title=title, 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) # 日期列是**完整区间**(7 天),不是只有有作品的那天 assert len(data["dates"]) == 7 assert data["dates"][0] == _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_two_notes_with_different_tags_merge_into_one_cell(db): """同一天两条不同标签:合成一格,计数相加,标签取并集。 注意并集**按词表顺序**排,不是按作品先后 —— 否则同样的数据换个遍历顺序就会 看起来不一样。代价是「哪个标签属于哪条视频」这个信息在这一格里没有了。 """ task_id = await _task() now = get_current_timestamp() await _note(task_id, "older", "博主A", now - 2000) await _note(task_id, "newer", "博主A", now - 1000) dazibao = await _tag("大字报", 1) yanghao = await _tag("养号", 2) await _attach("dy", "older", dazibao) await _attach("dy", "newer", yanghao) 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["tags"] == ["大字报", "养号"] # 逐条明细按发布时间正序:先发的在前,各自带自己的标签 assert [item["tags"] for item in cell["details"]] == [["大字报"], ["养号"]] @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 len(data["dates"]) == 7 assert data["dates"][0] == _day(now) assert data["cells"][_day(now)]["hash-a"]["count"] == 1 # 40 天前那天不该出现在 cells 里 assert _day(now - 40 * DAY_MS) not in data["cells"] @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": {}, } async def _stat( task_id: int, creator_hash: str, nickname: str, captured_at: int | None = None, run_id: int = 1, fans: int | None = None, ) -> None: async with monitor_db.get_session() as session: session.add( MonitorCreatorStat( task_id=task_id, run_id=run_id, creator_hash=creator_hash, nickname=nickname, creator_id="", works_count=0, fans=fans, captured_at=captured_at or get_current_timestamp(), ) ) @pytest.mark.asyncio async def test_creators_without_notes_still_get_a_row(db): """只在账号快照里出现的号不能消失。 典型是资料读成纯数字昵称、作品数为 0 的那几个 —— 它们一条作品都没有,如果博主 名单只从作品里取,整行就不见了。日期列也一样:一行数据都没有时,7 个日期还在。 """ task_id = await _task() await _stat(task_id, "hash-num", "26828346705") async with monitor_db.get_session() as session: data = await service.daily_tag_matrix(session, "dy", days=7) assert [c["name"] for c in data["creators"]] == ["26828346705"] assert data["cells"] == {} assert len(data["dates"]) == 7 @pytest.mark.asyncio async def test_the_creator_row_carries_the_latest_fan_count(db): """博主列左边要显示的粉丝数 —— 取最近一次**读到了数字**的快照。 最新一轮如果是 None(没解析出来),不能让几千粉丝变成一个空白 —— 「这一轮没读到」不等于「这个号没有粉丝」。 """ task_id = await _task() now = get_current_timestamp() await _stat(task_id, "hash-a", "博主A", captured_at=now - 120_000, fans=1000, run_id=1) await _stat(task_id, "hash-a", "博主A", captured_at=now - 60_000, fans=1200, run_id=2) await _stat(task_id, "hash-a", "博主A", captured_at=now, fans=None, run_id=3) async with monitor_db.get_session() as session: data = await service.daily_tag_matrix(session, "dy", days=7) assert len(data["creators"]) == 1 assert data["creators"][0]["name"] == "博主A" assert data["creators"][0]["fans"] == 1200 @pytest.mark.asyncio async def test_a_creator_without_a_snapshot_has_no_fan_count(db): """作品模式刚导入、还没跑过一轮:粉丝数留 None,界面不画那个数字(不是 0)。""" task_id = await _task() now = get_current_timestamp() await _note(task_id, "n1", "只有作品", now - 1000) async with monitor_db.get_session() as session: data = await service.daily_tag_matrix(session, "dy", days=7) assert data["creators"][0]["fans"] is None @pytest.mark.asyncio async def test_degraded_stat_snapshot_does_not_hide_the_name(db): """资料接口偶尔回空对象(昵称/粉丝/作品数全空)。 那一轮不能算「最新的名字」—— 否则一个空字符串会把之前的好名字盖掉,界面上 变成「未知(hash)」。线上真有两个号这么丢过名字。 """ task_id = await _task() now = get_current_timestamp() await _stat(task_id, "hash-a", "好名字", captured_at=now - 60_000, run_id=1) await _stat(task_id, "hash-a", "", captured_at=now, run_id=2) # 更新,但是坏的 async with monitor_db.get_session() as session: data = await service.daily_tag_matrix(session, "dy", days=7) assert [c["name"] for c in data["creators"]] == ["好名字"] @pytest.mark.asyncio async def test_empty_stat_falls_back_to_the_note_name(db): task_id = await _task() now = get_current_timestamp() await _note(task_id, "n1", "作品里的名字", now - 1000) await _stat(task_id, "hash-a", "") async with monitor_db.get_session() as session: data = await service.daily_tag_matrix(session, "dy", days=7) assert [c["name"] for c in data["creators"]] == ["作品里的名字"] @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, title="作品一") await _note(task_id, "n2", "博主A", now, title="作品二") # 同一篇有两轮快照,只取 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 # 逐条明细带**各自的**指标,不是格子的合计 —— 悬停时看的就是这个。 by_title = {item["title"]: item for item in cell["details"]} assert by_title["作品一"]["likes"] == 20 # 取最近一轮 assert by_title["作品一"]["comments"] == 2 assert by_title["作品一"]["collected"] == 4 assert by_title["作品一"]["shares"] == 5 assert by_title["作品二"]["likes"] == 5 assert by_title["作品二"]["comments"] is None # 未知不是 0 assert by_title["作品二"]["shares"] == 0 @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_account_pool_status_is_attached_by_nickname(db, monkeypatch): task_id = await _task() now = get_current_timestamp() - 1000 await _note(task_id, "n1", "博主A", now) async def fake_pool(): return [ {"nickname": "博主A", "account_status": "账号异常"}, {"nickname": "别人", "account_status": "账号正常"}, ] monkeypatch.setenv("MC_ACCOUNT_POOL_URL", "http://pool/api") monkeypatch.setattr(service, "_fetch_account_pool", fake_pool) service._reset_account_status_cache() async with monitor_db.get_session() as session: data = await service.daily_tag_matrix(session, "dy", days=7) assert data["creators"][0]["account_status"] == "账号异常" @pytest.mark.asyncio async def test_account_pool_failure_does_not_break_the_report(db, monkeypatch): task_id = await _task() now = get_current_timestamp() - 1000 await _note(task_id, "n1", "博主A", now) async def down(): raise RuntimeError("pool is down") monkeypatch.setenv("MC_ACCOUNT_POOL_URL", "http://pool/api") monkeypatch.setattr(service, "_fetch_account_pool", down) service._reset_account_status_cache() async with monitor_db.get_session() as session: data = await service.daily_tag_matrix(session, "dy", days=7) # 外部服务挂了,报表照出,只是没有状态 assert data["dates"] assert data["creators"][0]["account_status"] == "" @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 _day(now) in body["dates"] assert body["creators"][0]["name"] == "博主A" cell = body["cells"][_day(now)]["hash-a"] assert cell["count"] == 1 assert cell["tags"] == ["大字报"] assert "likes" in cell