feat: add daily commission history for Web 2.0.8
This commit is contained in:
@@ -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="连接已中断")
|
||||
|
||||
Reference in New Issue
Block a user