feat: add daily commission history for Web 2.0.8

This commit is contained in:
AttilaNet
2026-11-13 09:59:43 +08:00
parent ad25d5b403
commit 296653d8d3
25 changed files with 2179 additions and 96 deletions
@@ -0,0 +1,218 @@
"""Commission subtabs, local reads and the original log region over loopback only."""
from datetime import datetime, timedelta, timezone
import json
from pathlib import Path
import time
import unittest
from unittest.mock import Mock, patch
from urllib.parse import parse_qs, urlsplit
from ranch_assistant.engine import Engine, demo_snapshot
from ranch_assistant.model import Catalog
from ranch_web.tests.test_commission_history import history_fixture
from ranch_web.views import build_view
from . import test_workbench_browser as fixtures
if fixtures.AVAILABLE:
from playwright.sync_api import expect
@unittest.skipUnless(fixtures.AVAILABLE, "Python Playwright and a system Chromium browser are required")
class CommissionHistoryBrowserTests(unittest.TestCase):
setUpClass = classmethod(fixtures.WorkbenchBrowserTests.setUpClass.__func__)
tearDownClass = classmethod(fixtures.WorkbenchBrowserTests.tearDownClass.__func__)
await_job = fixtures.WorkbenchBrowserTests.await_job
open = fixtures.WorkbenchBrowserTests.open
go = fixtures.WorkbenchBrowserTests.go
fulfill = staticmethod(fixtures.WorkbenchBrowserTests.fulfill)
def setUp(self):
self.enterContext(patch("requests.sessions.Session.request", side_effect=AssertionError("Live HTTP forbidden")))
fixtures.WorkbenchBrowserTests.setUp(self)
self.context.set_default_timeout(6000)
self.today = datetime.now(timezone(timedelta(hours=8))).date()
self.external, self.writes, self.reads, self.pending = [], [], [], []
self.hold = self.fail_reads = False
self.engines = {}
for identifier, label in ((self.first, "账号一"), (self.second, "账号二")):
engine = Engine(Catalog(), budget_path=Path(self.temp.name) / identifier / "fixture-budget.json")
engine.snapshot = demo_snapshot(engine.catalog)
engine.catalog.data["task_info"] = {"test20": {"name": label + "高额候选", "reward": {"money": 123, "ke": 20}},
"test15": {"name": label + "回退候选", "reward": {"money": 456, "ke": 15}}}
engine.tasks.rows = Mock(return_value=[("test20", label + "高额候选", "城市 4 可接", "", {"city": 4}),
("test15", label + "回退候选", "城市 1 可接", "", {"city": 1})])
engine.tasks.current = Mock(return_value=[])
engine.commission_offer_diagnostics = Mock(return_value=[])
engine.progression_rows = Mock(return_value=[{"category": "commission", "task_type_id": "test20", "block_reason": "城市尚未解锁"},
{"category": "commission", "task_type_id": "test15", "selection_reason": "20氪金候选未解锁,回退15氪金"}])
engine.commission_history = lambda day=None, label=label: self.history(day, label)
engine.client = Mock()
self.engines[identifier] = engine
def local_only(route):
if route.request.url.startswith(self.base + "/"):
route.continue_()
else:
self.external.append(route.request.url)
route.abort()
self.context.route("**/*", local_only)
self.page.on("request", lambda request: self.writes.append(request) if request.method in ("POST", "PUT", "PATCH", "DELETE") else None)
def view(route):
parsed = urlsplit(route.request.url)
identifier = parsed.path.split("/")[-3]
params = parse_qs(parsed.query)
query = json.loads(params["query"][0]) if "query" in params else {key: value[0] for key, value in params.items()}
self.reads.append((identifier, query))
dto = build_view(self.engines[identifier], "commissions", self.manager.get_config(identifier)["config"], query)
if self.hold:
self.pending.append((route, dto))
elif self.fail_reads:
route.fulfill(status=503, content_type="application/json", body='{"detail":"本地记录读取失败"}')
else:
self.fulfill(route, {"loading": False, "data": dto})
self.page.route("**/api/accounts/*/views/commissions?*", view)
def history(self, day, label):
fixture = history_fixture(day)
fixture["rows"][0]["name"] = label + day + "提交魔物与道具"
return fixture
def tearDown(self):
try:
self.assertEqual(self.external, [])
self.assertEqual(self.errors, [])
for engine in self.engines.values():
engine.client.call.assert_not_called()
finally:
self.context.unroute_all(behavior="ignoreErrors")
self.context.close()
def records(self):
panel = self.go("commissions")
panel.get_by_role("tab", name="每日记录", exact=True).click()
expect(panel.locator('input[type="date"]')).to_have_value(self.today.isoformat())
expect(panel.locator("tbody tr")).to_have_count(2)
expect(panel).to_have_attribute("aria-busy", "false")
return panel
def test_history_refresh_is_get_only_and_original_single_log_stays_collapsed(self):
self.open()
expect(self.page.locator("#page-tabs [role=tab]")).to_have_count(15)
panel = self.records()
expect(panel.get_by_role("tab", name="每日记录")).to_have_attribute("aria-selected", "true")
expect(panel.locator(".policy-form")).to_be_hidden()
expect(panel.locator(".page-surface > p.page-summary")).to_contain_text("已记录接取 2 · 已记录完成 1")
expect(panel.locator(".page-surface > p.page-summary")).to_contain_text("当日领奖确认氪金 15 · 当日接取标注氪金 35")
expect(panel.locator('td[data-column="confirmed_ke"]')).to_have_text(["15", "未确认"])
expect(self.page.locator("#log-panel")).to_have_count(1)
expect(self.page.locator("#log-panel")).to_be_hidden()
before = len(self.writes)
with self.page.expect_request(lambda request: "/views/commissions?" in request.url) as seen:
panel.get_by_role("button", name="刷新记录", exact=True).click()
self.assertEqual(seen.value.method, "GET")
expect(panel).to_have_attribute("aria-busy", "false")
self.assertEqual(len(self.writes), before)
expect(self.page.locator("#log-panel")).to_be_hidden()
self.assertEqual(self.page.locator('[role="log"]').count(), 1)
panel.locator("tbody tr").first.click(button="right")
with self.page.expect_request(lambda request: "/views/commissions?" in request.url) as seen:
self.page.get_by_role("menuitem", name="刷新本页", exact=True).click()
self.assertEqual(seen.value.method, "GET")
expect(panel).to_have_attribute("aria-busy", "false")
self.assertEqual(len(self.writes), before)
artifact = Path(__file__).resolve().parents[3] / "test-artifacts" / "commission-history"
artifact.mkdir(parents=True, exist_ok=True)
self.page.screenshot(path=str(artifact / "desktop-daily-records.png"))
panel.locator("tbody tr").first.dblclick()
detail = self.page.get_by_role("dialog")
expect(detail).to_contain_text("委托详情")
for value in ("铁矿石 ×2", "1级史莱姆 ×1", "城镇守卫", "战斗胜利", "回退15氪金"):
expect(detail).to_contain_text(value)
expect(self.page.locator("#log-panel")).to_be_hidden()
def test_current_policy_autosave_and_original_log_filters_commissions_in_both_subtabs(self):
worker = self.manager._worker(self.first)
worker.log("接取委托:仅委托可见(预计20氪金);已确认", category="commissions")
worker.log("其他分类不可见", category="login")
self.open()
panel = self.go("commissions")
with self.page.expect_request(lambda request: request.method == "PUT" and "/config" in request.url):
panel.get_by_role("checkbox", name="允许提交道具(遵守保留数量)", exact=True).check()
expect(self.page.locator("#save-status")).to_have_text("策略已自动保存")
self.assertTrue(self.manager.get_config(self.first)["config"]["quest_policy"]["allow_items"])
expect(self.page.locator("#log-panel")).to_be_hidden()
self.page.locator("#log-toggle").click()
expect(self.page.locator("#log-heading")).to_have_text("自动委托日志")
expect(self.page.locator("#log-lines")).to_contain_text("仅委托可见")
expect(self.page.locator("#log-lines")).not_to_contain_text("其他分类不可见")
panel.get_by_role("tab", name="每日记录").click()
expect(panel.get_by_label("记录日期(北京时间)")).to_be_visible()
expect(self.page.locator("#log-panel")).to_be_visible()
expect(self.page.locator("#log-panel")).to_have_count(1)
expect(self.page.locator("#log-heading")).to_have_text("自动委托日志")
expect(self.page.locator("#log-lines")).not_to_contain_text("其他分类不可见")
def test_date_account_isolation_and_keyboard_subtabs(self):
self.open()
panel = self.records()
yesterday = (self.today - timedelta(days=1)).isoformat()
panel.get_by_label("记录日期(北京时间)").fill(yesterday)
expect(panel.locator("tbody tr").first).to_contain_text("账号一" + yesterday)
self.page.locator(f'.account-tab[data-account="{self.second}"]').click()
panel = self.records()
expect(panel.get_by_label("记录日期(北京时间)")).to_have_value(self.today.isoformat())
expect(panel.locator("tbody tr").first).to_contain_text("账号二" + self.today.isoformat())
self.page.locator(f'.account-tab[data-account="{self.first}"]').click()
panel = self.page.locator('.page-panel[data-page="commissions"]:not([hidden])')
expect(panel.get_by_label("记录日期(北京时间)")).to_have_value(yesterday)
expect(panel.locator("tbody tr").first).to_contain_text("账号一" + yesterday)
current = panel.get_by_role("tab", name="每日记录")
current.focus()
current.press("Home")
expect(panel.get_by_role("tab", name="当前委托")).to_have_attribute("aria-selected", "true")
expect(panel.locator('th[data-column="reward_ke"]')).to_have_text("标注氪金")
expect(panel.locator("tbody tr").first).to_contain_text("城市尚未解锁")
expect(panel.locator('td[data-column="status"]')).to_have_text(["暂不接取", "候选 / 条件待核对"])
expect(self.page.locator("#log-panel")).to_be_hidden()
def test_loading_error_and_mobile_history_keep_original_layout(self):
self.open()
panel = self.records()
self.hold = True
panel.get_by_label("记录日期(北京时间)").fill((self.today - timedelta(days=2)).isoformat())
expect(panel).to_have_attribute("aria-busy", "true")
expect(panel.locator(".page-loading")).to_be_visible()
expect(self.page.locator("#log-panel")).to_be_hidden()
deadline = time.monotonic() + 5
while not self.pending and time.monotonic() < deadline:
self.page.wait_for_timeout(30)
self.assertTrue(self.pending)
self.hold = False
route, dto = self.pending.pop(0)
self.fulfill(route, {"loading": False, "data": dto})
expect(panel).to_have_attribute("aria-busy", "false")
expect(panel.locator(".page-loading")).to_be_hidden()
self.fail_reads = True
panel.get_by_role("button", name="刷新记录").click()
expect(panel.locator(".page-error")).to_be_visible()
expect(panel).to_have_attribute("aria-busy", "false")
expect(self.page.locator("#log-panel")).to_be_hidden()
self.fail_reads = False
self.errors[:] = [error for error in self.errors if "503 (Service Unavailable)" not in error]
panel.get_by_role("button", name="重新读取").click()
expect(panel.locator(".page-error")).to_be_hidden()
self.page.set_viewport_size({"width": 390, "height": 844})
expect(panel.get_by_label("记录日期(北京时间)")).to_be_visible()
self.assertLessEqual(self.page.evaluate("document.documentElement.scrollWidth"), 391)
artifact = Path(__file__).resolve().parents[3] / "test-artifacts" / "commission-history"
artifact.mkdir(parents=True, exist_ok=True)
self.page.screenshot(path=str(artifact / "mobile-daily-records.png"))
if __name__ == "__main__":
unittest.main()
@@ -51,8 +51,22 @@ class PageLoadingBrowserTests(unittest.TestCase):
"details": {"help": "STATIC_HELP_SENTINEL", "note": "STATIC_NOTE_SENTINEL",
"notes": ["金币不足,等待补货"]}}}
self.hold, self.fail = False, False
self.hold_after_real_retry_click = False
self.page.add_init_script("""(() => {
window.__loadingRetryClicked = false;
document.addEventListener('click', event => {
if (event.target instanceof Element && event.target.closest('.page-panel[data-page="bag"] .page-error button')) {
window.__loadingRetryClicked = true;
}
}, true);
})();""")
def view(route):
if self.hold_after_real_retry_click:
if not self.page.evaluate("window.__loadingRetryClicked"):
route.fulfill(status=503, content_type="application/json", body='{"detail":"读取失败"}')
return
self.hold_after_real_retry_click = False
if self.hold:
self.pending.append(route)
elif self.fail:
@@ -156,8 +170,16 @@ class PageLoadingBrowserTests(unittest.TestCase):
expect(panel.locator(".page-error")).to_be_visible()
expect(panel).to_have_attribute("aria-busy", "false")
expect(panel.locator(".page-loading")).to_be_hidden()
# Passive polling must keep returning the error until the native click.
# Holding a passive request here would hide the button before it can click.
self.hold_after_real_retry_click = True
self.hold, self.fail = True, False
with self.page.expect_response(lambda response: "/views/bag?" in response.url and response.status == 503):
pass # Exercise a real passive refresh during this transition.
expect(panel.locator(".page-error")).to_be_visible()
self.assertEqual(self.pending, [], "Passive errors must not park a request before the retry click")
panel.get_by_role("button", name="重新读取").click()
self.assertTrue(self.page.evaluate("window.__loadingRetryClicked"))
route = self.wait_request()
self.assert_centered(panel)
self.summary.update(connection_state="offline", connected=False, connection_message="连接已中断")
+196
View File
@@ -0,0 +1,196 @@
"""Commission DTO regressions with temporary engines and synthetic local history."""
from datetime import datetime, timezone
import json
from pathlib import Path
import tempfile
import unittest
from unittest.mock import Mock, patch
from ranch_assistant.engine import Engine, demo_snapshot
from ranch_assistant.model import Catalog
from ranch_web.policies import default_config
from ranch_web.views import build_view
def history_fixture(day):
return {"date": day, "dates": [day], "summary": {
"accepted_count": 2, "completed_count": 1, "expected_ke": 35, "confirmed_ke": 15, "pending_count": 1, "unknown_reward_count": 0},
"rows": [{"id": "local-15", "task_id": 71, "task_type_id": "test15", "name": "提交魔物与道具",
"status": "completed", "accepted_at": day + "T01:02:03+00:00", "completed_at": day + "T02:03:04+00:00",
"expected_ke": 15, "confirmed_ke": 15, "selection_reason": "20氪金候选城市尚未解锁,回退15氪金",
"last_action": "服务器已确认领取15氪金", "events": [
{"time": day + "T01:02:03+00:00", "kind": "accept", "status": "confirmed", "description": "接取委托,预计15氪金"},
{"time": day + "T01:03:03+00:00", "kind": "handin_items", "status": "confirmed", "description": "已提交铁矿石 ×2"},
{"time": day + "T01:04:03+00:00", "kind": "handin_monsters", "status": "confirmed", "description": "已提交1级史莱姆 ×1"},
{"time": day + "T01:05:03+00:00", "kind": "dialogue", "status": "confirmed", "description": "已与城镇守卫对话"},
{"time": day + "T01:06:03+00:00", "kind": "battle", "status": "confirmed", "description": "委托战斗胜利,推进第4步"},
{"time": day + "T02:03:04+00:00", "kind": "claim", "status": "confirmed", "description": "服务器奖励回包确认氪金15"}]},
{"id": "local-20", "task_id": 72, "task_type_id": "test20", "name": "奖励待核对的委托",
"status": "unknown", "accepted_at": day + "T03:02:03+08:00", "completed_at": None,
"expected_ke": 20, "confirmed_ke": None, "last_action": "领奖请求超时,等待核对",
"events": [{"time": day + "T03:03:04+08:00", "kind": "claim", "status": "unknown", "description": "领奖回包未知"}]}]}
class CommissionHistoryViewTests(unittest.TestCase):
def setUp(self):
root = self.enterContext(tempfile.TemporaryDirectory(prefix="commission-web-history-"))
self.engine = Engine(Catalog(), budget_path=Path(root) / "budget.json")
self.engine.snapshot = demo_snapshot(self.engine.catalog)
self.engine.demo = False
self.engine.client = Mock()
self.engine.client.call.side_effect = AssertionError("Game calls forbidden in history views")
self.config = default_config()
self.history = history_fixture("2026-11-12")
self.engine.commission_history = Mock(return_value=self.history)
self.engine.commission_offer_diagnostics = Mock(return_value=[])
def view(self, **query):
return build_view(self.engine, "commissions", self.config, {"tab": "history", **query})
def test_history_reads_only_local_helper_and_separates_confirmed_rewards(self):
self.engine.tasks.rows = Mock(side_effect=AssertionError("Current tasks are not history"))
self.engine.progression_rows = Mock(side_effect=AssertionError("Do not plan game actions in history"))
self.engine.commission_offer_diagnostics.side_effect = AssertionError("History must not inspect current offers")
self.engine.plans = Mock(side_effect=AssertionError("Do not plan in history"))
dto = self.view(date="2026-11-12")
self.engine.commission_history.assert_called_once_with(day="2026-11-12")
self.engine.client.call.assert_not_called()
self.assertEqual([tab["title"] for tab in dto["tabs"]], ["当前委托", "每日记录"])
self.assertEqual(dto["form"], [])
self.assertEqual(dto["actions"], [{"operation": "reload_view", "label": "刷新记录"}])
self.assertIn("已记录接取 2", dto["summary"])
self.assertIn("已记录完成 1", dto["summary"])
self.assertIn("仅有本地已保存记录", dto["summary"])
self.assertIn("当日领奖确认氪金 15", dto["summary"])
self.assertIn("当日接取标注氪金 35", dto["summary"])
self.assertIn("操作待核对 1", dto["summary"])
self.assertIn("领奖金额未记录 0", dto["summary"])
self.assertEqual(dto["rows"][1]["confirmed_ke"], "未确认")
self.assertEqual(dto["rows"][1]["status_label"], "结果待核对")
self.assertEqual(dto["rows"][0]["accepted_at"], "2026-11-12 09:02:03")
self.assertEqual(dto["rows"][1]["completed_at"], "—")
json.dumps(dto, ensure_ascii=False, allow_nan=False)
def test_details_show_actual_handins_dialogue_battle_and_claim_evidence(self):
dto = self.view(date="2026-11-12")
detail = dto["details"]["local-15"]
for text in ("铁矿石 ×2", "1级史莱姆 ×1", "城镇守卫", "战斗胜利", "氪金15"):
self.assertIn(text, detail["行动记录"])
self.assertIn("回退15氪金", detail["选择 / 回退原因"])
self.assertIn("结果待核对", dto["details"]["local-20"]["行动记录"])
self.assertNotIn("已确认", dto["details"]["local-20"]["行动记录"])
def test_search_can_find_action_details_without_changing_daily_totals(self):
dto = self.view(date="2026-11-12", search="铁矿石")
self.assertEqual([row["id"] for row in dto["rows"]], ["local-15"])
self.assertIn("已记录接取 2", dto["summary"])
self.assertEqual(set(dto["details"]), {"local-15"})
def test_empty_history_does_not_invent_old_acceptance_from_current_tasks(self):
self.engine.snapshot.raw["currentTasks"] = [{"id": 3, "typeId": "test20", "curStep": 1}]
self.engine.commission_history.return_value = {"date": "2026-11-11", "summary": {}, "rows": []}
dto = self.view(date="2026-11-11")
self.assertEqual(dto["rows"], [])
self.assertIn("已记录接取 0", dto["summary"])
self.assertIn("历史接取与奖励未追溯", dto["summary"])
def test_history_available_without_snapshot(self):
self.engine.snapshot = None
dto = self.view(date="2026-11-12")
self.assertEqual(len(dto["rows"]), 2)
self.engine.client.call.assert_not_called()
current = build_view(self.engine, "commissions", self.config)
self.assertIn("请先登录", current["summary"])
self.assertEqual(len(current["tabs"]), 2)
def test_default_date_is_beijing_today_at_utc_day_boundary(self):
class FixedDatetime(datetime):
@classmethod
def now(cls, tz=None):
return cls(2026, 11, 12, 17, tzinfo=timezone.utc).astimezone(tz)
with patch("ranch_web.views.datetime", FixedDatetime):
dto = self.view()
self.engine.commission_history.assert_called_once_with(day="2026-11-13")
self.assertEqual(dto["filters"][0]["value"], "2026-11-13")
self.assertEqual(dto["filters"][0]["type"], "date")
def test_invalid_date_never_calls_history_helper(self):
for day in ("2026-11-31", "2026-1-1", "../2026-11-12", ["2026-11-12"]):
with self.subTest(day=day), self.assertRaisesRegex(ValueError, "记录日期"):
self.view(date=day)
self.engine.commission_history.assert_not_called()
def test_raw_history_fields_never_reach_public_view(self):
row = self.history["rows"][0]
row["raw_response"] = {"token": "private-response"}
row["events"][0].update(raw={"password": "private-event"}, payload={"removeIds": [1234567]})
wire = json.dumps(self.view(date="2026-11-12"), ensure_ascii=False)
for value in ("private-response", "private-event", "1234567", "raw_response", "removeIds"):
self.assertNotIn(value, wire)
def test_current_offer_presence_never_implies_receivable(self):
self.engine.catalog.data["task_info"] = {
"test20": {"name": "高额候选", "reward": {"money": 123, "ke": 20}},
"test15": {"name": "回退候选", "reward": {"money": 456, "ke": 15}}}
self.engine.tasks.rows = Mock(return_value=[
("test20", "高额候选", "城市 4 可接", "提交物品", {"city": 4}),
("test15", "回退候选", "城市 1 可接", "提交金币", {"city": 1})])
self.engine.tasks.current = Mock(return_value=[])
self.engine.progression_rows = Mock(return_value=[
{"category": "commission", "task_type_id": "test20", "block_reason": "城市尚未解锁"},
{"category": "commission", "task_type_id": "test15", "selection_reason": "20氪金候选未解锁,回退15氪金"}])
dto = build_view(self.engine, "commissions", self.config)
high, fallback = dto["rows"]
self.assertEqual(high["reward_ke"], 20)
self.assertEqual(high["reward_money"], 123)
self.assertEqual(high["status"], "暂不接取")
self.assertEqual(high["reason"], "城市尚未解锁")
self.assertNotIn("可接", fallback["status"])
self.assertIn("回退15氪金", fallback["selection_reason"])
self.assertIn("20 → 15 → 10", dto["details"][fallback["id"]]["接取优先级"])
def test_authoritative_offer_diagnostics_match_city_and_explain_fallback(self):
self.engine.catalog.data["task_info"] = {
"test20": {"name": "高额候选", "reward": {"money": 123, "ke": 20}},
"test15": {"name": "回退候选", "reward": {"money": 456, "ke": 15}}}
self.engine.tasks.rows = Mock(return_value=[
("test20", "高额候选", "城市 4 可接", "", {"city": 4}),
("test15", "回退候选", "城市 1 可接", "", {"city": 1}),
("test15", "回退候选", "城市 9 可接", "", {"city": 9})])
self.engine.tasks.current = Mock(return_value=[])
self.engine.progression_rows = Mock(return_value=[
{"category": "commission", "task_type_id": "test15", "block_reason": "错误城市的阻塞原因"}])
self.engine.commission_offer_diagnostics.return_value = [
{"task_type_id": "test20", "name": "高额候选", "city": 4, "expected_ke": 20, "eligible": False, "reason": "城市尚未解锁"},
{"task_type_id": "test15", "name": "回退候选", "city": 1, "expected_ke": 15, "eligible": True, "reason": "可接取"},
{"task_type_id": "test15", "name": "回退候选", "city": 9, "expected_ke": 15, "eligible": False, "reason": "提交魔物受保留保护"}]
dto = build_view(self.engine, "commissions", self.config)
self.assertEqual([row["status"] for row in dto["rows"]], ["暂不接取", "可接取", "暂不接取"])
self.assertIn("选择 15 氪金", dto["rows"][1]["selection_reason"])
self.assertIn("城市尚未解锁", dto["rows"][1]["selection_reason"])
self.assertNotIn("错误城市", dto["rows"][1]["reason"])
self.assertEqual(dto["rows"][2]["reason"], "提交魔物受保留保护")
self.engine.client.call.assert_not_called()
def test_pending_zero_reward_and_cross_day_totals_remain_distinct(self):
self.history["rows"][0].update(expected_ke=20, confirmed_ke=0, accepted_at="2026-11-11T01:02:03+08:00")
self.history["rows"][1]["status"] = "pending"
self.history["summary"].update(accepted_count=0, expected_ke=0, confirmed_ke=0)
dto = self.view(date="2026-11-12")
self.assertEqual(dto["rows"][0]["confirmed_ke"], 0)
self.assertEqual(dto["rows"][0]["expected_ke"], 20)
self.assertEqual(dto["rows"][1]["confirmed_ke"], "未确认")
self.assertEqual(dto["rows"][1]["status_label"], "等待核对")
self.assertIn("当日接取标注氪金 0", dto["summary"])
self.assertNotIn("损失", dto["summary"])
def test_backend_read_error_visible_without_exposing_private_fields(self):
self.history.update(error="委托历史无法读取,原文件已保留", notice="仅展示本地已保存记录")
dto = self.view(date="2026-11-12")
self.assertIn("委托历史无法读取,原文件已保留", dto["summary"])
self.assertIn("仅有本地已保存记录", dto["summary"])
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,113 @@
"""Real worker/local ledger integration; game transports are always offline fakes."""
from copy import deepcopy
from datetime import datetime, timedelta, timezone
from types import SimpleNamespace
import unittest
from unittest.mock import Mock, patch
from ranch_assistant.engine import Engine
from ranch_web.tests import test_service as fixtures
class CommissionHistoryServiceTests(unittest.TestCase):
setUp = fixtures.ServiceTests.setUp
account = fixtures.ServiceTests.account
idle = fixtures.ServiceTests.idle
job = fixtures.ServiceTests.job
def view(self, identifier, day):
response = self.manager.view(identifier, "commissions", {"tab": "history", "date": day})
if response["loading"]:
self.job(identifier, {"id": response["job_id"]})
response = self.manager.view(identifier, "commissions", {"tab": "history", "date": day})
self.assertFalse(response["loading"])
return response["data"]
def tick(self, identifier, *, failed=False):
worker = self.manager._worker(identifier)
with patch.object(worker.schedule, "due", return_value="poll"):
self.job(identifier, worker.enqueue("__tick"), status="failed" if failed else "succeeded")
def test_real_local_ledger_history_is_account_role_day_isolated_without_game_calls(self):
first, second = self.account(), self.account()
worker = self.manager._worker(first)
engine = worker.engine
role = str(engine.snapshot.raw["master"]["id"])
today = datetime.now(timezone(timedelta(hours=8))).date()
stamp = datetime.combine(today, datetime.min.time(), timezone(timedelta(hours=8))).timestamp() + 3600
info = {"type": 4, "name": "已保存的20氪金委托", "reward": {"ke": 20}}
record = {"attempt_id": "synthetic-accept", "role_id": role, "task_type_id": "test20", "task_id": 71,
"kind": "quest_accept", "path": "taskService/taskLoopReceive", "timestamp": stamp,
"finished_at": stamp, "phase": "done", "outcome": "task", "response_confirmed": True,
"response": {"resCode": 0, "task": {"id": 71, "typeId": "test20", "curStep": 1}},
"commission": {"name": info["name"], "expected_ke": 20}}
engine._commission_history.ingest(role, [record], lambda _: info, engine.snapshot)
after = self.manager.logs(first)["next"]
with patch.object(engine, "read_snapshot", side_effect=AssertionError("history must stay local")), \
patch.object(engine, "poll", side_effect=AssertionError("history must not poll")):
dto = self.view(first, today.isoformat())
self.assertIn("已记录接取 1", dto["summary"])
self.assertEqual(dto["rows"][0]["confirmed_ke"], "未确认")
self.assertEqual(self.view(second, today.isoformat())["rows"], [])
self.assertEqual(self.view(first, (today - timedelta(days=1)).isoformat())["rows"], [])
original = engine.snapshot
engine.snapshot = deepcopy(original)
engine.snapshot.raw["master"]["id"] = "other-local-role"
worker._invalidate_views()
self.assertEqual(self.view(first, today.isoformat())["rows"], [])
engine.snapshot = original
worker._invalidate_views()
self.assertEqual(len(self.view(first, today.isoformat())["rows"]), 1)
self.assertEqual(fixtures.FakeClient.calls, [])
self.assertEqual(self.manager.logs(first, after=after)["entries"], [], "Reading history must not create activity logs")
def test_accept_step_claim_and_unknown_messages_are_chinese_categorized_and_redacted(self):
def action(engine, intent):
return engine.snapshot, [], intent["message"]
with patch.object(Engine, "_run_progression_intent", action):
identifier = self.account()
worker = self.manager._worker(identifier)
worker.engine.game_data = SimpleNamespace(task=lambda _: {"type": 4})
messages = [
("接取委托:本地测试(预计20氪金);已确认", "info"),
("提交委托步骤:本地测试(预计20氪金);已提交铁矿石 ×2", "info"),
("领取委托奖励:本地测试(预计20氪金);已确认,实际获得20氪金", "info"),
("领取委托奖励:本地测试(预计20氪金);结果未知,等待核对,禁止重发", "warning"),
("委托战斗:本地测试(预计20氪金);战斗失败,未推进委托", "error")]
for message, level in messages:
with self.subTest(message=message):
before = self.manager.logs(identifier)["next"]
intent = {"kind": "progression_complete", "task_type_id": "test20", "message": message + ";password=synthetic-password"}
with patch.object(worker.engine, "poll", side_effect=lambda **_: worker.engine._run_progression_intent(intent)):
self.tick(identifier)
entries = self.manager.logs(identifier, after=before)["entries"]
self.assertEqual(len(entries), 1)
self.assertEqual((entries[0]["category"], entries[0]["level"]), ("commissions", level))
self.assertIn("本地测试", entries[0]["message"])
self.assertIn("20氪金", entries[0]["message"])
self.assertNotIn("synthetic-password", entries[0]["message"])
def test_failed_commission_keeps_one_error_with_name_reward_and_no_success(self):
def action(engine, intent):
raise TimeoutError("token=synthetic-token 请求超时")
with patch.object(Engine, "_run_progression_intent", action):
identifier = self.account()
worker = self.manager._worker(identifier)
worker.engine.game_data = SimpleNamespace(task=lambda _: {"type": 4, "name": "受保护的提交委托", "reward": {"ke": 20}})
before = self.manager.logs(identifier)["next"]
intent = {"kind": "progression_loop_accept", "task_type_id": "test20"}
with patch.object(worker.engine, "poll", side_effect=lambda **_: worker.engine._run_progression_intent(intent)):
self.tick(identifier, failed=True)
entries = self.manager.logs(identifier, after=before)["entries"]
self.assertEqual(len(entries), 1)
self.assertEqual((entries[0]["category"], entries[0]["level"]), ("commissions", "error"))
for value in ("受保护的提交委托", "标注20氪金", "接取异常", "结果待核对"):
self.assertIn(value, entries[0]["message"])
self.assertNotIn("synthetic-token", entries[0]["message"])
self.assertNotIn("已确认", entries[0]["message"])
if __name__ == "__main__":
unittest.main()