astrbot_plugin_private_comp.../tests/test_p0_runtime_fixes.py
YokiiroBW 54f892e348 test: assert the provider-not-ready round actually writes nothing
The readiness fix had unit coverage for _chat_provider_ready and the fallback
upgrade helpers, but nothing asserting the thing that actually went wrong in
production: that a not-ready round leaves the day untouched. "It returned
None" and "it wrote a fallback and pinned the whole day" are both plausible
readings of a green pure-function test.

Three cases through _ensure_daily_plan itself: not ready writes no plan and
counts one wait; the round after the configured limit is the first one allowed
to degrade, and it must actually produce a plan; a ready provider generates
immediately and clears the wait counter, so a later genuine outage gets its
full budget.

Companion suite 246 passed, joint E2E 146/146.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-27 05:43:19 +08:00

201 行
9.2 KiB
Python

此文件含有模棱两可的 Unicode 字符

此文件含有可能会与其他字符混淆的 Unicode 字符。 如果您是想特意这样的,可以安全地忽略该警告。 使用 Escape 按钮显示他们。

# -*- coding: utf-8 -*-
"""P0 生产缺陷回归(2026-07-27)。
三件事,共同点是「生产在报错/退化,而验收全绿」:
1. `daily_state.py` 还在调用早已被删掉的 `_ensure_daily_news_reading`,
每轮日程维护写盘后必抛 AttributeError,主动循环把「今日日程」标失败并冷却。
计划本身已经保存,所以故障一直藏在「计划看起来是好的」后面。
2. 归档总闸 `enable_memory_companion_bridge` 不在 `_conf_schema.json` 里,
设置页看不到、改了也不落盘——上次整条归档链路静默停摆三天就是同一处开关问题。
3. 兜底日程带上当天日期后,三处复用分支都会直接把它返回,当天不再生成,
于是一次启动时序抖动把模板兜底固化成正式的一天并归档进长期记忆。
"""
from __future__ import annotations
import asyncio
import importlib
import json
import logging
import pathlib
import sys
import types
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
import _host_stub # noqa: E402
_host_stub.install()
_package_name = "_p0_companion"
_package = types.ModuleType(_package_name)
_package.__path__ = [str(pathlib.Path(__file__).resolve().parents[1])]
sys.modules.setdefault(_package_name, _package)
ROOT = pathlib.Path(__file__).resolve().parents[1]
daily_state = importlib.import_module(f"{_package_name}.daily_state")
helpers = importlib.import_module(f"{_package_name}.helpers")
TODAY = "2026-07-27"
class Host(daily_state.DailyStateMixin):
"""只带本组用例需要的状态,其余走 Mixin 真实实现。"""
def __init__(self, plan=None, retry=None, provider_ready=True):
self.data = {}
if plan is not None:
self.data["daily_plan"] = plan
if retry is not None:
self.data["daily_plan_fallback_retry"] = retry
self._provider_ready = provider_ready
self.saves = 0
def _chat_provider_ready(self) -> bool:
return self._provider_ready
def _save_data_sync(self) -> None:
self.saves += 1
class DeadNewsCallTests(unittest.TestCase):
def test_no_production_code_calls_the_removed_news_reader(self):
offenders = []
for path in ROOT.rglob("*.py"):
parts = set(path.parts)
if parts & {"tests", ".tmp", "__pycache__"}:
continue
for num, line in enumerate(path.read_text(encoding="utf-8", errors="ignore").splitlines(), 1):
if "_ensure_daily_news_reading" in line and not line.strip().startswith("#"):
offenders.append(f"{path.name}:{num}")
self.assertEqual(offenders, [], f"仍在调用已删除的新闻阅读实现: {offenders}")
def test_the_method_really_does_not_exist(self):
"""反面证据:它确实没有实现,所以上面的调用点必然是 AttributeError。"""
self.assertFalse(hasattr(daily_state.DailyStateMixin, "_ensure_daily_news_reading"))
class BridgeSwitchSchemaTests(unittest.TestCase):
def setUp(self):
self.schema = json.loads((ROOT / "_conf_schema.json").read_text(encoding="utf-8"))
def test_bridge_switch_is_visible_in_the_external_memory_group(self):
items = self.schema["external_memory_config"]["items"]
self.assertIn("enable_memory_companion_bridge", items)
entry = items["enable_memory_companion_bridge"]
self.assertEqual(entry["type"], "bool")
self.assertIs(entry["default"], True)
self.assertFalse(entry.get("invisible"), "总闸被标成 invisible 就等于设置页还是看不到")
def test_the_switch_is_read_through_the_same_path_main_uses(self):
"""schema 里挂在分组下,main.py 却按扁平键读——_flat_get 必须能穿过分组。"""
config = {"external_memory_config": {"enable_memory_companion_bridge": False}}
self.assertIs(helpers._flat_get(config, "enable_memory_companion_bridge", True), False)
class FallbackUpgradeTests(unittest.TestCase):
def test_fallback_plan_can_be_upgraded_when_provider_is_back(self):
host = Host(plan={"date": TODAY, "source": "fallback"})
self.assertTrue(host._daily_plan_can_upgrade_from_fallback(host.data["daily_plan"], TODAY))
def test_real_plan_is_never_regenerated(self):
host = Host(plan={"date": TODAY, "source": "llm"})
self.assertFalse(host._daily_plan_can_upgrade_from_fallback(host.data["daily_plan"], TODAY))
def test_provider_still_down_means_no_upgrade_attempt(self):
host = Host(plan={"date": TODAY, "source": "fallback"}, provider_ready=False)
self.assertFalse(host._daily_plan_can_upgrade_from_fallback(host.data["daily_plan"], TODAY))
def test_yesterdays_fallback_is_not_upgraded_today(self):
host = Host(plan={"date": "2026-07-26", "source": "fallback"})
self.assertFalse(host._daily_plan_can_upgrade_from_fallback(host.data["daily_plan"], TODAY))
def test_retry_budget_is_capped(self):
limit = daily_state.DAILY_PLAN_FALLBACK_RETRY_LIMIT
host = Host(plan={"date": TODAY, "source": "fallback"})
for expected in range(1, limit + 1):
self.assertTrue(host._daily_plan_can_upgrade_from_fallback(host.data["daily_plan"], TODAY))
self.assertEqual(host._note_daily_plan_fallback_retry(TODAY), expected)
self.assertFalse(
host._daily_plan_can_upgrade_from_fallback(host.data["daily_plan"], TODAY),
"重试次数用尽后仍在尝试,Provider 就绪但生成始终失败时会每个 tick 重跑模型",
)
def test_retry_counter_is_scoped_to_its_own_day(self):
"""昨天用掉的额度不能占掉今天的。"""
host = Host(plan={"date": TODAY, "source": "fallback"},
retry={"date": "2026-07-26", "count": 99})
self.assertEqual(host._daily_plan_fallback_retries(TODAY), 0)
self.assertTrue(host._daily_plan_can_upgrade_from_fallback(host.data["daily_plan"], TODAY))
def test_broken_retry_state_is_tolerated(self):
host = Host(plan={"date": TODAY, "source": "fallback"}, retry="不是字典")
self.assertEqual(host._daily_plan_fallback_retries(TODAY), 0)
def test_note_retry_persists(self):
host = Host(plan={"date": TODAY, "source": "fallback"})
host._note_daily_plan_fallback_retry(TODAY)
self.assertEqual(host.data["daily_plan_fallback_retry"], {"date": TODAY, "count": 1})
self.assertEqual(host.saves, 1, "重试计数必须落盘,否则重启后额度重置")
class ProviderNotReadySkipsTheRoundTests(unittest.IsolatedAsyncioTestCase):
"""Provider 未就绪时必须跳过本轮,而不是写一份兜底把当天钉死。
这是 2518f7b 的核心分支,此前只有纯函数单测,没有一条断言证明
「这一轮真的什么都没写」——而生产事故恰恰是「写了,而且写死了一整天」。
"""
def build(self, ready: bool):
host = Host()
host.enable_daily_plan = True
host.data["users"] = {"u1": {"umo": "qq:FriendMessage:u1"}}
host._provider_ready = ready
host._data_lock = asyncio.Lock()
host.generated = 0
async def ensure_state(force=False):
return None
async def generate():
host.generated += 1
return {"date": TODAY, "source": "llm", "version": 1,
"items": [{"time": "09:00", "end": "10:00", "activity": "真实计划"}]}
host._ensure_daily_state = ensure_state
host._generate_daily_plan = generate
host._is_daily_plan_due = lambda: True
host._is_plan_date_active = lambda date: False
host._sanitize_daily_plan_inplace = lambda plan: False
host._refresh_daily_state_location_from_plan = lambda **kw: None
host._memory_companion_record_daily_plan = None
return host
async def test_not_ready_writes_nothing_and_counts_a_wait(self):
host = self.build(ready=False)
self.assertIsNone(await host._ensure_daily_plan())
self.assertEqual(host.generated, 0, "Provider 没就绪却仍然调用了模型")
self.assertFalse(host.data.get("daily_plan"), "写了兜底计划,当天就被钉死了")
self.assertEqual(host.data.get("daily_plan_provider_wait_count"), 1)
async def test_it_gives_up_after_the_configured_number_of_rounds(self):
host = self.build(ready=False)
for _ in range(daily_state.DAILY_PLAN_PROVIDER_MAX_WAITS):
self.assertIsNone(await host._ensure_daily_plan())
# 超过上限这一轮才允许退化,且退化必须真的产出计划
plan = await host._ensure_daily_plan()
self.assertIsNotNone(plan)
self.assertEqual(host.generated, 1)
async def test_ready_generates_immediately_and_clears_the_counter(self):
host = self.build(ready=True)
host.data["daily_plan_provider_wait_count"] = 3
plan = await host._ensure_daily_plan()
self.assertEqual(plan["source"], "llm")
self.assertEqual(host.generated, 1)
self.assertNotIn("daily_plan_provider_wait_count", host.data,
"就绪之后等待计数没清,下次真失败时额度会被提前吃掉")
if __name__ == "__main__":
unittest.main()