# -*- coding: utf-8 -*- """身份池:分片、解析、健康状态。 这里钉住的是「多个账号怎么分活」和「一个号什么时候该被停用」。真去请求抖音的那层 另有测试(test_douyin_api / test_douyin_fetch),这里全部用假函数。 """ from types import SimpleNamespace import pytest import pytest_asyncio from api.monitor import db as monitor_db from api.monitor import douyin_api, douyin_fetch, identities from api.monitor.models import ( IDENTITY_SOURCE_STORED, IDENTITY_STATUS_COOLDOWN, IDENTITY_STATUS_OK, MODE_CREATOR, MonitorIdentity, ) from tools.time_util import get_current_timestamp @pytest_asyncio.fixture async def db(tmp_path): monitor_db.set_sqlite_path(tmp_path / "identities.db") await monitor_db.init_db() yield monitor_db await monitor_db.dispose_engine() async def _identity( label: str = "主号", cookie: str = "sessionid=abc", user_agent: str = "UA/1.0", ) -> MonitorIdentity: now = get_current_timestamp() async with monitor_db.get_session() as session: row = MonitorIdentity( platform="dy", label=label, source=IDENTITY_SOURCE_STORED, cookie=cookie, user_agent=user_agent, client_hints="{}", created_at=now, updated_at=now, ) session.add(row) await session.flush() return row # --- 分片 ------------------------------------------------------------------- def test_assignment_is_deterministic_and_covers_every_target(): targets = [SimpleNamespace(external_id=f"t{index}") for index in range(30)] first = identities.assign(targets, ["id:1", "id:2"]) second = identities.assign(targets, ["id:1", "id:2"]) assert [t.external_id for t in first["id:1"]] == [t.external_id for t in second["id:1"]] assert sum(len(bucket) for bucket in first.values()) == 30 # 两个身份都应该分到活,否则分片没意义 assert first["id:1"] and first["id:2"] def test_adding_an_identity_moves_only_a_fraction_of_targets(): """Rendezvous Hashing 的意义:加一个身份,只迁移约 1/(n+1) 的目标。""" targets = [SimpleNamespace(external_id=f"t{index}") for index in range(300)] before = { target.external_id: key for key, bucket in identities.assign(targets, ["id:1", "id:2"]).items() for target in bucket } after = { target.external_id: key for key, bucket in identities.assign(targets, ["id:1", "id:2", "id:3"]).items() for target in bucket } moved = sum(1 for external, key in before.items() if after[external] != key) assert 0 < moved < len(targets) * 0.6 # --- 解析 ------------------------------------------------------------------- @pytest.mark.asyncio async def test_resolve_builds_the_identity_from_the_row(db): row = await _identity() identity = await identities.resolve(row) assert identity.cookie == "sessionid=abc" assert identity.user_agent == "UA/1.0" assert identity.identity_key == f"id:{row.id}" @pytest.mark.asyncio async def test_resolve_rejects_a_stored_identity_without_user_agent(db): """没有 UA 就不能用 —— a_bogus 签名要拿它,空 UA 签出来的请求一定被挡。""" row = await _identity(user_agent="") with pytest.raises(ValueError): await identities.resolve(row) @pytest.mark.asyncio async def test_resolve_rejects_a_stored_identity_without_cookie(db): row = await _identity(cookie="") with pytest.raises(ValueError): await identities.resolve(row) # --- 健康状态 --------------------------------------------------------------- @pytest.mark.asyncio async def test_two_failures_trigger_a_cooldown(db): row = await _identity() async with monitor_db.get_session() as session: live = await session.get(MonitorIdentity, row.id) await identities.record_result(session, live, ok=False, error="空 body") # 一次失败可能只是抖动,不停用 assert live.status == IDENTITY_STATUS_OK await identities.record_result(session, live, ok=False, error="空 body") assert live.status == IDENTITY_STATUS_COOLDOWN assert live.cooldown_until > get_current_timestamp() @pytest.mark.asyncio async def test_success_clears_the_cooldown(db): row = await _identity() async with monitor_db.get_session() as session: live = await session.get(MonitorIdentity, row.id) await identities.record_result(session, live, ok=False, error="x") await identities.record_result(session, live, ok=False, error="x") assert live.status == IDENTITY_STATUS_COOLDOWN await identities.record_result(session, live, ok=True) assert live.status == IDENTITY_STATUS_OK assert live.cooldown_until is None assert live.consecutive_failures == 0 assert live.last_ok_at is not None def test_a_cooling_identity_is_not_available(): row = MonitorIdentity( platform="dy", label="x", source=IDENTITY_SOURCE_STORED, cookie="sessionid=a", user_agent="UA", client_hints="{}", status=IDENTITY_STATUS_OK, enabled=True, consecutive_failures=2, cooldown_until=get_current_timestamp() + 60_000, created_at=0, updated_at=0, ) assert identities.is_available(row) is False row.cooldown_until = get_current_timestamp() - 1 assert identities.is_available(row) is True # --- 采集分片 --------------------------------------------------------------- @pytest.mark.asyncio async def test_collect_shards_targets_across_identities(tmp_path, monkeypatch): used = [] async def fake_videos(sec_user_id, count=20, *, cookie="", identity=None): used.append((identity.identity_key, sec_user_id)) return [ { "aweme_id": f"a-{sec_user_id}", "creator_hash": "hash-a", "creator_name": "博主", "title": "", "aweme_url": "", "cover_url": "", "aweme_type": "video", "create_time": 0, } ] async def fake_profile(sec_user_id, *, cookie="", identity=None): return { "creator_hash": "hash-a", "nickname": "博主", "creator_id": sec_user_id, "unique_id": "", "fans": 0, "total_favorited": 0, "works": 0, "following": 0, } monkeypatch.setattr(douyin_api, "author_videos", fake_videos) monkeypatch.setattr(douyin_api, "author_profile", fake_profile) targets = [SimpleNamespace(external_id=f"t{index}") for index in range(20)] pool = [ douyin_api.BrowserIdentity( cookie="sessionid=a", user_agent="UA", client_hints={}, identity_key="id:1" ), douyin_api.BrowserIdentity( cookie="sessionid=b", user_agent="UA", client_hints={}, identity_key="id:2" ), ] result = await douyin_fetch.collect( tmp_path, platform="dy", mode=MODE_CREATOR, limit=20, want_comments=False, comment_limit=0, targets=targets, identities=pool, ) assert len(used) == 20 assert {key for key, _ in used} == {"id:1", "id:2"} assert result["notes"] == 20 assert len(result["shards"]) == 2 assert sum(shard["targets"] for shard in result["shards"]) == 20