Add Web 2 workspace and controlled deployment updates
This commit is contained in:
@@ -0,0 +1 @@
|
||||
"""Optional system-browser checks; all state is temporary and offline."""
|
||||
@@ -0,0 +1,479 @@
|
||||
"""Run with: python -m unittest ranch_web.tests.browser.test_workbench_browser -v.
|
||||
|
||||
Uses a temporary WebManager with explicit demo accounts and a local ASGI server.
|
||||
Login, populated exploration and measured statistics use browser route fixtures;
|
||||
no test contacts a game server or reads the user's account directories.
|
||||
Set RANCH_WEB_BROWSER to a Chromium executable when Edge is not installed.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import copy
|
||||
import csv
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import socket
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
import unittest
|
||||
from urllib.parse import parse_qs, urlsplit
|
||||
|
||||
|
||||
EDGE = Path(os.environ.get("RANCH_WEB_BROWSER", "C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe"))
|
||||
AVAILABLE = importlib.util.find_spec("playwright") is not None and EDGE.is_file()
|
||||
if AVAILABLE:
|
||||
from playwright.sync_api import expect
|
||||
|
||||
|
||||
class OfflineUpdates:
|
||||
def status(self):
|
||||
return {"current_version": "2.0.0.dev1", "latest_version": None, "status": "unchecked",
|
||||
"message": "尚未检查正式版本", "can_apply": False,
|
||||
"executor": {"enabled": False, "configured": False}}
|
||||
|
||||
|
||||
@unittest.skipUnless(AVAILABLE, "Install Python Playwright and set RANCH_WEB_BROWSER to a system Chromium browser")
|
||||
class WorkbenchBrowserTests(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
import uvicorn
|
||||
from playwright.sync_api import sync_playwright
|
||||
from ranch_web.app import create_app
|
||||
from ranch_web.config import WebConfig
|
||||
from ranch_web.service import WebManager
|
||||
|
||||
cls.temp = tempfile.TemporaryDirectory(prefix="ranch-web-browser-test-")
|
||||
cls.manager = WebManager(cls.temp.name, start_scheduler=False)
|
||||
cls.first = cls.manager.create_account("浏览器离线演示", demo=True)["id"]
|
||||
cls.second = cls.manager.create_account("账号二", demo=True)["id"]
|
||||
with socket.socket() as sock:
|
||||
sock.bind(("127.0.0.1", 0))
|
||||
port = sock.getsockname()[1]
|
||||
cls.base = f"http://127.0.0.1:{port}"
|
||||
settings = WebConfig(port=port, data_dir=Path(cls.temp.name))
|
||||
app = create_app(manager=cls.manager, config=settings, updates=OfflineUpdates())
|
||||
cls.server = uvicorn.Server(uvicorn.Config(app, host="127.0.0.1", port=port, log_level="error"))
|
||||
cls.thread = threading.Thread(target=cls.server.run, daemon=True)
|
||||
cls.thread.start()
|
||||
deadline = time.monotonic() + 15
|
||||
while not cls.server.started and time.monotonic() < deadline:
|
||||
time.sleep(.02)
|
||||
if not cls.server.started:
|
||||
raise RuntimeError("Temporary offline browser server failed to start")
|
||||
cls.playwright = sync_playwright().start()
|
||||
cls.browser = cls.playwright.chromium.launch(executable_path=str(EDGE), headless=True)
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
cls.browser.close()
|
||||
cls.playwright.stop()
|
||||
cls.server.should_exit = True
|
||||
cls.thread.join(timeout=10)
|
||||
cls.manager.close()
|
||||
cls.temp.cleanup()
|
||||
|
||||
def setUp(self):
|
||||
from ranch_web.policies import default_config
|
||||
|
||||
for identifier in (self.first, self.second):
|
||||
self.manager.submit(identifier, "stop")
|
||||
response = self.manager.set_config(identifier, default_config())
|
||||
self.await_job(identifier, response["job_id"])
|
||||
self.context = self.browser.new_context(viewport={"width": 1280, "height": 800}, accept_downloads=True)
|
||||
self.page = self.context.new_page()
|
||||
self.errors = []
|
||||
self.page.on("pageerror", lambda failure: self.errors.append(str(failure)))
|
||||
self.page.on("console", lambda message: self.errors.append(message.text) if message.type == "error" else None)
|
||||
self.context.route("https://**", lambda route: route.abort())
|
||||
|
||||
def tearDown(self):
|
||||
self.context.close()
|
||||
|
||||
def await_job(self, identifier, job_id):
|
||||
deadline = time.monotonic() + 10
|
||||
while time.monotonic() < deadline:
|
||||
job = self.manager.job(identifier, job_id)
|
||||
if job["status"] in ("succeeded", "failed", "cancelled"):
|
||||
self.assertEqual(job["status"], "succeeded", job.get("error"))
|
||||
return job.get("result")
|
||||
time.sleep(.01)
|
||||
self.fail("Offline job did not complete")
|
||||
|
||||
def open(self, page=None):
|
||||
page=page or self.page
|
||||
page.goto(self.base, wait_until="networkidle")
|
||||
page.locator(f'.account-tab[data-account="{self.first}"]').click()
|
||||
expect(page.locator('#save-status')).to_have_text('策略已自动保存')
|
||||
|
||||
def go(self, key, page=None):
|
||||
page=page or self.page
|
||||
page.locator(f'.page-tab[data-page="{key}"]').click()
|
||||
page.wait_for_selector(f'.page-panel[data-page="{key}"]:not([hidden]) .page-loading[data-loading="false"]')
|
||||
return page.locator(f'.page-panel[data-page="{key}"]:not([hidden])')
|
||||
|
||||
@staticmethod
|
||||
def field(root,path):
|
||||
return root.locator("[data-config-path='"+json.dumps(path,separators=(',',':'))+"']")
|
||||
|
||||
def wait_saved(self):
|
||||
expect(self.page.locator('#save-status')).to_have_text('策略已自动保存')
|
||||
|
||||
@staticmethod
|
||||
def fulfill(route, data):
|
||||
route.fulfill(status=200, content_type="application/json", body=json.dumps(data, ensure_ascii=False))
|
||||
|
||||
def test_all_pages_are_read_only_csp_clean_and_responsive(self):
|
||||
self.open()
|
||||
writes = []
|
||||
self.page.on("request", lambda request: writes.append(request.url) if request.method in ("POST", "PUT", "DELETE") else None)
|
||||
keys = ["login", "incubator", "bag", "ranch", "daily", "hatching", "mainline", "battles", "gifts", "commissions", "exploration", "maps", "statistics", "plans", "yields"]
|
||||
for key in keys:
|
||||
panel = self.go(key)
|
||||
self.assertEqual(panel.locator(".page-error:not([hidden])").count(), 0)
|
||||
if key=='hatching':
|
||||
expect(panel.locator('.subtab')).to_have_count(3)
|
||||
expect(panel.locator('.form-section')).to_have_count(1)
|
||||
expect(panel.locator('.form-section legend')).to_have_text('孵蛋策略')
|
||||
panel.locator('.subtab[data-key="喂养策略"]').click()
|
||||
expect(panel.locator('.form-section legend')).to_have_text('喂养策略')
|
||||
expect(panel.locator('[data-view-status="feed_status"]')).to_be_visible()
|
||||
if key=='mainline':
|
||||
expect(panel.locator('.subtab[data-key="policy"]')).to_be_visible()
|
||||
panel.locator('.subtab[data-key="policy"]').click()
|
||||
expect(self.field(panel,['progression_policy','enabled'])).to_be_visible()
|
||||
panel.locator('.subtab[data-key="status"]').click()
|
||||
expect(self.field(panel,['progression_policy','enabled'])).to_have_count(0)
|
||||
self.assertEqual(writes, [], "Switching pages must not submit game or configuration actions")
|
||||
self.assertEqual(self.page.locator('.page-tab[data-page="statistics"]').inner_text(), "数据分析")
|
||||
self.assertEqual(self.page.locator('.page-tab[data-page="plans"]').inner_text(), "执行计划")
|
||||
self.go("bag")
|
||||
for width, height in ((1280, 800), (1600, 900), (390, 844)):
|
||||
self.page.set_viewport_size({"width": width, "height": height})
|
||||
self.assertTrue(self.page.locator("#strategy-toggle").is_visible())
|
||||
self.assertTrue(self.page.locator("#page-tabs").is_visible())
|
||||
self.assertLessEqual(self.page.evaluate("document.documentElement.scrollWidth"), width)
|
||||
self.assertEqual(self.errors, [])
|
||||
|
||||
def test_rule_defaults_autosave_focus_account_isolation_and_start_stop(self):
|
||||
self.open()
|
||||
panel = self.go("bag")
|
||||
row = panel.locator("tbody tr").first
|
||||
species = row.get_attribute("data-row-id")
|
||||
priority = row.locator('td[data-column="priority"] input')
|
||||
priority.fill("17")
|
||||
original = priority.element_handle()
|
||||
self.page.wait_for_timeout(2100)
|
||||
self.wait_saved()
|
||||
self.assertTrue(priority.evaluate("(node, original) => node === original", original))
|
||||
self.assertTrue(priority.evaluate("node => node === document.activeElement"))
|
||||
saved = self.manager.get_config(self.first)["config"]["policy"]["egg_rules"][species]
|
||||
self.assertEqual(saved["priority"], 17)
|
||||
self.assertIn("refill_target", saved)
|
||||
self.assertIn("keep_count", saved)
|
||||
row.locator('td[data-column="enabled"] input').check()
|
||||
self.page.wait_for_timeout(1800)
|
||||
self.wait_saved()
|
||||
self.page.locator("#strategy-toggle").click()
|
||||
expect(self.page.locator('#strategy-toggle')).to_have_text('停止')
|
||||
self.page.locator("#strategy-toggle").click()
|
||||
expect(self.page.locator('#strategy-toggle')).to_have_text('开启')
|
||||
self.page.locator(f'.account-tab[data-account="{self.second}"]').click()
|
||||
expect(self.page.locator('#save-status')).to_have_text('策略已自动保存')
|
||||
self.assertEqual(self.manager.get_config(self.second)["config"]["policy"]["egg_rules"], {})
|
||||
self.page.locator(f'.account-tab[data-account="{self.first}"]').click()
|
||||
self.assertEqual(self.go("bag").locator(f'tr[data-row-id="{species}"] td[data-column="priority"] input').input_value(), "17")
|
||||
self.assertEqual(self.errors, [])
|
||||
|
||||
def test_exploration_keeps_partial_drafts_and_saves_only_three_or_auto(self):
|
||||
from ranch_web.policies import default_config
|
||||
|
||||
fixture_config = default_config()
|
||||
revision = 500
|
||||
writes = []
|
||||
candidates = [{"value": 101, "label": "队长", "level": 30}, {"value": 102, "label": "队员一", "level": 20}, {"value": 103, "label": "队员二", "level": 10}]
|
||||
def route_config(route):
|
||||
nonlocal fixture_config, revision
|
||||
if route.request.method == "PUT":
|
||||
fixture_config = route.request.post_data_json["config"]
|
||||
writes.append(copy.deepcopy(fixture_config))
|
||||
revision += 1
|
||||
self.fulfill(route, {"config": fixture_config, "revision": revision})
|
||||
def route_view(route):
|
||||
row = {"id": "1", "name": '<img src=x onerror="alert(1)">', "enabled": False, "monsters": [], "rule_path": ["explore_policy", "teams", "1"],
|
||||
"rule_defaults": {"enabled": False, "area": "area1", "monsters": []}, "member_options": candidates}
|
||||
self.fulfill(route, {"loading": False, "revision": revision, "data": {"page": "exploration", "title": "自动探险", "summary": "完成后自动领奖", "form": [], "filters": [], "actions": [],
|
||||
"columns": [{"key": "name", "label": "队伍"}, {"key": "monsters", "label": "队员", "edit": {"path": ["explore_policy", "teams", "{id}", "monsters"], "type": "members", "options": candidates}}], "rows": [row]}})
|
||||
self.page.route(f"**/api/accounts/{self.first}/config", route_config)
|
||||
self.page.route(f"**/api/accounts/{self.first}/views/exploration?*", route_view)
|
||||
self.open()
|
||||
panel = self.go("exploration")
|
||||
selects = panel.locator(".member-selects select")
|
||||
selects.nth(0).select_option("101")
|
||||
selects.nth(1).select_option("102")
|
||||
self.page.wait_for_timeout(750)
|
||||
self.assertEqual(writes, [], "An incomplete team must remain a browser draft")
|
||||
self.assertEqual(panel.locator("img").count(), 0, "Game names must be text, never HTML")
|
||||
selects.nth(2).select_option("103")
|
||||
self.page.wait_for_timeout(1400)
|
||||
self.assertEqual(writes[-1]["explore_policy"]["teams"]["1"]["monsters"], [101, 102, 103])
|
||||
panel.get_by_role("button", name="自动选三只", exact=True).click()
|
||||
self.page.wait_for_timeout(1400)
|
||||
self.assertEqual(writes[-1]["explore_policy"]["teams"]["1"]["monsters"], [])
|
||||
self.assertTrue(all(len(config["explore_policy"]["teams"]["1"]["monsters"]) in (0, 3) for config in writes))
|
||||
self.assertEqual(self.errors, [])
|
||||
|
||||
def test_statistics_tree_is_lazy_and_chart_uses_requested_source(self):
|
||||
requests = []
|
||||
def route_view(route):
|
||||
query = json.loads(parse_qs(urlsplit(route.request.url).query)["query"][0])
|
||||
requests.append(query)
|
||||
source = query.get("source", "all")
|
||||
stages = [{"id": f"stage{i}", "label": f"关卡{i}", "city_id": str(i // 30), "city_name": f"地区{i // 30}", "levels": [{"id": str(level), "level": str(level), "sweep": 2, "event": 1} for level in (1, 2, 3)]} for i in range(120)]
|
||||
self.fulfill(route, {"loading": False, "data": {"page": "statistics", "title": "数据分析", "summary": "真实测量 fixture", "stages": stages,
|
||||
"filters": [{"key": "source", "label": "统计范围", "type": "select", "value": source, "options": [{"value": "all", "label": "扫荡+奖励事件"}, {"value": "event", "label": "奖励事件"}]}], "form": [], "actions": [], "columns": [{"key": "name", "label": "掉落物"}], "rows": [],
|
||||
"chart": {"series": [{"label": "测量样本", "value": .25 if source == "event" else .5}]}}})
|
||||
self.page.route(f"**/api/accounts/{self.first}/views/statistics?*", route_view)
|
||||
self.open()
|
||||
panel = self.go("statistics")
|
||||
original_width=float(panel.locator('.chart-bar').get_attribute('width'))
|
||||
self.assertEqual(panel.locator(".statistics-city").count(), 4)
|
||||
self.assertEqual(panel.locator(".statistics-levels button").count(), 0)
|
||||
panel.locator(".statistics-city > summary").first.click()
|
||||
expect(panel.locator('.statistics-stage')).to_have_count(30)
|
||||
self.assertEqual(panel.locator(".statistics-levels button").count(), 0)
|
||||
panel.locator(".statistics-stage > summary").first.click()
|
||||
expect(panel.locator('.statistics-levels button')).to_have_count(3)
|
||||
panel.locator('[data-config-path=\'["source"]\']').select_option("event")
|
||||
expect(panel.locator('.chart-value')).to_have_text('25.00%')
|
||||
self.assertAlmostEqual(float(panel.locator('.chart-bar').get_attribute('width')), original_width / 2)
|
||||
self.assertEqual(requests[-1]["source"], "event")
|
||||
self.assertEqual(self.errors, [])
|
||||
|
||||
def test_network_debug_details_are_loaded_only_when_selected(self):
|
||||
detail_requests = []
|
||||
def route_logs(route):
|
||||
query = parse_qs(urlsplit(route.request.url).query)
|
||||
debug = query.get("debug") == ["true"]
|
||||
self.fulfill(route, {"entries": [{"id": 51, "seq": 51, "time":"2026-11-10T07:08:09Z", "message": "离线请求响应", "details_available": debug}], "next": 51})
|
||||
def route_detail(route):
|
||||
detail_requests.append(route.request.url)
|
||||
self.fulfill(route, {"id": 51, "details": {"operation": "离线测试", "body": {"master": {"name": "演示"}, "token": "<隐藏>"}}})
|
||||
self.page.route(f"**/api/accounts/{self.first}/logs?*", route_logs)
|
||||
self.page.route(f"**/api/accounts/{self.first}/debug/51", route_detail)
|
||||
self.open()
|
||||
self.page.locator("#debug-toggle").click()
|
||||
self.page.wait_for_selector(".log-entry.inspectable")
|
||||
expect(self.page.locator('.log-entry.inspectable .log-time')).to_have_text('15:08:09')
|
||||
expect(self.page.locator('.log-entry.inspectable .log-time')).to_have_attribute('title','2026-11-10T07:08:09Z')
|
||||
self.assertEqual(detail_requests, [])
|
||||
self.page.locator(".log-entry.inspectable").first.click()
|
||||
expect(self.page.locator('.debug-json')).to_contain_text('<隐藏>')
|
||||
self.assertEqual(len(detail_requests), 1)
|
||||
self.assertEqual(self.errors, [])
|
||||
|
||||
def test_fake_login_uses_servers_without_persisting_password(self):
|
||||
payloads = []
|
||||
def route_login(route):
|
||||
payloads.append(route.request.post_data_json)
|
||||
self.fulfill(route, {"id": "fake_login", "status": "succeeded", "operation": "login", "result": {"servers": [{"id": 7, "name": "测试区", "role_name": "测试角色"}], "has_saved_password": True}, "error": None})
|
||||
self.page.route(f"**/api/accounts/{self.first}/actions/login", route_login)
|
||||
self.open()
|
||||
panel = self.go("login")
|
||||
panel.get_by_label("游戏账号", exact=True).fill("offline-test")
|
||||
panel.get_by_label("游戏密码", exact=True).fill("test-password-never-persist")
|
||||
panel.get_by_role("button", name="账号密码登录 / 获取区服", exact=True).click()
|
||||
expect(panel.get_by_label('区服 / 角色',exact=True)).to_contain_text('测试区')
|
||||
self.assertEqual(payloads[0], {"account": "offline-test", "password": "test-password-never-persist", "remember": True})
|
||||
self.assertEqual(panel.get_by_label("游戏密码", exact=True).input_value(), "")
|
||||
self.assertEqual(self.page.evaluate("Object.keys(localStorage).length + Object.keys(sessionStorage).length"), 0)
|
||||
self.assertNotIn("test-password", self.page.url)
|
||||
self.assertEqual(self.errors, [])
|
||||
|
||||
def test_exports_round_trip_and_expansion_requires_confirmation(self):
|
||||
from ranch_assistant.model import Catalog
|
||||
|
||||
self.open()
|
||||
self.page.locator('.menu > summary').nth(2).click()
|
||||
with self.page.expect_download() as pending:
|
||||
self.page.locator('[data-command="export-config"]').click()
|
||||
exported = json.loads(Path(pending.value.path()).read_text(encoding='utf-8'))
|
||||
self.assertIn('policy', exported)
|
||||
self.assertNotIn('password', exported)
|
||||
self.page.locator('.menu > summary').nth(2).click()
|
||||
with self.page.expect_download() as pending:
|
||||
self.page.locator('[data-command="export-yields"]').click()
|
||||
content = Path(pending.value.path()).read_bytes()
|
||||
raw = content.decode('utf-8-sig')
|
||||
rows = list(csv.DictReader(raw.splitlines()))
|
||||
self.assertGreater(len(rows), 100)
|
||||
self.assertIn('孵化秒数', rows[0])
|
||||
path = Path(self.temp.name) / 'round-trip.csv'
|
||||
path.write_bytes(content)
|
||||
catalog = Catalog()
|
||||
self.assertEqual(catalog.import_prices(path), len(rows))
|
||||
|
||||
panel = self.go('incubator')
|
||||
data = self.manager.view(self.first, 'incubator', {})['data']
|
||||
position = next(row['id'] for row in data['rows'] if row['can_expand'])
|
||||
panel.locator(f'tr[data-row-id="{position}"] .selection-cell input').check()
|
||||
writes = []
|
||||
self.page.on('request', lambda request: writes.append(request.url) if request.method == 'POST' and request.url.endswith('/actions/expand') else None)
|
||||
panel.locator('button[data-operation="quote_expansion"]').first.click()
|
||||
expect(self.page.locator('#dialog-title')).to_have_text('确认开启坑位')
|
||||
self.page.locator('#dialog-cancel').click()
|
||||
self.assertEqual(writes, [], 'Reading or cancelling a quote must not expand')
|
||||
panel.locator('button[data-operation="quote_expansion"]').first.click()
|
||||
expect(self.page.locator('#dialog-title')).to_have_text('确认开启坑位')
|
||||
self.page.locator('#dialog-confirm').click()
|
||||
expect(panel.locator(f'tr[data-row-id="{position}"] td[data-column="status"]')).to_have_text('已开启', timeout=10000)
|
||||
self.assertEqual(len(writes), 1)
|
||||
self.assertEqual(self.errors, [])
|
||||
|
||||
def test_target_deletion_never_rechecks_from_stale_view(self):
|
||||
self.open()
|
||||
panel=self.go('ranch')
|
||||
data=self.manager.view(self.first,'ranch',{'grouped':False})['data']
|
||||
identifier=next(row['id'] for row in data['rows'] if row['process']==3)
|
||||
value=self.manager.get_config(self.first)['config']
|
||||
for mapping in ('feed_targets','gift_targets','breakthrough_targets'):
|
||||
value['policy'][mapping]={identifier:100}
|
||||
pending=self.manager.set_config(self.first,value)
|
||||
self.await_job(self.first,pending['job_id'])
|
||||
self.page.reload(wait_until='networkidle')
|
||||
panel=self.go('ranch')
|
||||
for prefix,mapping in [('feed','feed_targets'),('gift','gift_targets'),('breakthrough','breakthrough_targets')]:
|
||||
checkbox=panel.locator(f'tr[data-row-id="{identifier}"] td[data-column="{prefix}_selected"] input')
|
||||
expect(checkbox).to_be_checked()
|
||||
checkbox.uncheck()
|
||||
expect(checkbox).not_to_be_checked()
|
||||
self.page.wait_for_timeout(1200)
|
||||
self.wait_saved()
|
||||
expect(checkbox).not_to_be_checked()
|
||||
self.assertEqual(self.manager.get_config(self.first)['config']['policy'][mapping],{})
|
||||
self.assertEqual(self.errors,[])
|
||||
|
||||
def test_add_rule_uses_species_market_defaults(self):
|
||||
self.open()
|
||||
panel=self.go('bag')
|
||||
data=self.manager.view(self.first,'bag',{'category':'eggs'})['data']
|
||||
field=next(field for field in data['form'] if field['type']=='add_rule')
|
||||
existing={row['id'] for row in data['rows']}
|
||||
identifier,defaults=next((key,value) for key,value in field['defaults_by_id'].items() if key not in existing and value['market_id'])
|
||||
panel.get_by_label('添加魔物蛋规则',exact=True).select_option(identifier)
|
||||
panel.get_by_role('button',name='添加无库存蛋规则',exact=True).click()
|
||||
self.page.wait_for_timeout(1600)
|
||||
self.wait_saved()
|
||||
saved=self.manager.get_config(self.first)['config']['policy']['egg_rules'][identifier]
|
||||
self.assertEqual(saved,defaults)
|
||||
expect(panel.locator(f'tr[data-row-id="{identifier}"] td[data-column="market_id"] select')).to_have_value(defaults['market_id'])
|
||||
self.assertEqual(self.errors,[])
|
||||
|
||||
def test_conflict_between_two_tabs_preserves_new_row_fields(self):
|
||||
# Keep tab A on an earlier revision so it exercises the actual HTTP 409.
|
||||
initial=self.manager.list_accounts()
|
||||
self.page.route('**/api/accounts',lambda route:self.fulfill(route,initial))
|
||||
def map_view(route):
|
||||
config=self.manager.get_config(self.first)
|
||||
defaults={'enabled':False,'level':'1','limit':3}
|
||||
rule=defaults | config['config']['sweep_policy']['rules'].get('stage1',{})
|
||||
data={'page':'maps','title':'自动扫荡','summary':'离线冲突回归','filters':[],'form':[],'actions':[],
|
||||
'groups':[{'id':'1','label':'测试地区','collapsed':False}],
|
||||
'columns':[{'key':'enabled','label':'刷图','edit':{'path':['sweep_policy','rules','{id}','enabled'],'type':'boolean'}},
|
||||
{'key':'level','label':'难度','edit':{'path':['sweep_policy','rules','{id}','level'],'type':'select','options':[{'value':str(i),'label':str(i)} for i in (1,2,3)]}},
|
||||
{'key':'limit','label':'本日上限','edit':{'path':['sweep_policy','rules','{id}','limit'],'type':'integer','min':0,'max':999}}],
|
||||
'rows':[{'id':'stage1','group':'1',**rule,'rule_path':['sweep_policy','rules','stage1'],'rule_defaults':defaults}]}
|
||||
self.fulfill(route,{'data':data,'loading':False,'revision':config['revision']})
|
||||
self.page.route(f'**/api/accounts/{self.first}/views/maps?*',map_view)
|
||||
self.open()
|
||||
panel_a=self.go('maps')
|
||||
second=self.context.new_page()
|
||||
second.route(f'**/api/accounts/{self.first}/views/maps?*',map_view)
|
||||
self.open(second)
|
||||
panel_b=self.go('maps',second)
|
||||
panel_b.locator('td[data-column="level"] select').select_option('2')
|
||||
panel_b.locator('td[data-column="limit"] input').fill('5')
|
||||
second.wait_for_timeout(1400)
|
||||
expect(second.locator('#save-status')).to_have_text('策略已自动保存')
|
||||
self.assertEqual(self.manager.get_config(self.first)['config']['sweep_policy']['rules']['stage1']['limit'],5)
|
||||
panel_a.locator('td[data-column="enabled"] input').check()
|
||||
expect(self.page.locator('#save-status')).to_have_text('保存失败 · 点击重试',timeout=10000)
|
||||
self.page.locator('#save-status').click()
|
||||
expect(self.page.locator('#save-status')).to_have_text('策略已自动保存',timeout=10000)
|
||||
self.assertEqual(self.manager.get_config(self.first)['config']['sweep_policy']['rules']['stage1'],{'enabled':True,'level':'2','limit':5})
|
||||
self.assertFalse([message for message in self.errors if '409' not in message],self.errors)
|
||||
|
||||
def test_small_stamina_efficiency_is_visible_in_chart_and_table(self):
|
||||
# The metric is a GET filter; no configuration changes are submitted.
|
||||
data={'page':'statistics','title':'数据分析','summary':'精度回归','filters':[{'key':'metric','label':'图表指标','type':'select','value':'per_stamina','options':[{'value':'per_stamina','label':'每点体力数量'}]}],
|
||||
'form':[],'actions':[],'columns':[{'key':'name','label':'掉落物'},{'key':'per_stamina','label':'每点体力数量'}],
|
||||
'rows':[{'id':'rare','name':'稀有材料','per_stamina':.001}],'chart':{'max':.002,'series':[{'label':'稀有材料','value':.001}]}}
|
||||
self.page.route(f'**/api/accounts/{self.first}/views/statistics?*',lambda route:self.fulfill(route,{'data':data,'loading':False}))
|
||||
self.open()
|
||||
panel=self.go('statistics')
|
||||
expect(panel.locator('.chart-value')).to_have_text('0.001')
|
||||
expect(panel.locator('.chart-bar title')).to_have_text('稀有材料:0.001')
|
||||
expect(panel.locator('td[data-column="per_stamina"]')).to_have_text('0.001')
|
||||
expect(panel.locator('td[data-column="per_stamina"]')).to_have_attribute('title','0.001')
|
||||
self.assertEqual(self.errors,[])
|
||||
|
||||
def test_runtime_statuses_and_preset_without_confirmation(self):
|
||||
def gifts_view(route):
|
||||
self.fulfill(route,{'data':{'page':'gifts','title':'自动赠礼','summary':'离线状态','form':[],'filters':[],'columns':[],'rows':[],'actions':[],
|
||||
'details':{'next_ready_at':1794294489}},'loading':False})
|
||||
self.page.route(f'**/api/accounts/{self.first}/views/gifts?*',gifts_view)
|
||||
self.open()
|
||||
panel=self.go('hatching')
|
||||
expect(panel.locator('[data-view-status="last_draw"]')).to_contain_text('最近抽蛋:')
|
||||
panel.locator('.subtab[data-key="喂养策略"]').click()
|
||||
data=self.manager.view(self.first,'hatching',{})['data']
|
||||
expect(panel.locator('[data-view-status="feed_status"]')).to_contain_text(data['details']['feed_status'][1])
|
||||
panel.locator('button[data-operation="apply_preset"]').click()
|
||||
expect(self.page.locator('#action-dialog')).not_to_be_visible()
|
||||
self.page.wait_for_timeout(1400)
|
||||
self.wait_saved()
|
||||
self.assertTrue(self.manager.get_config(self.first)['config']['policy']['egg_rules']['1001010']['enabled'])
|
||||
self.assertFalse(self.manager.status(self.first)['running'])
|
||||
panel=self.go('gifts')
|
||||
expect(panel.locator('[data-view-status="next_ready_at"]')).to_contain_text('北京时间')
|
||||
self.assertEqual(self.errors,[])
|
||||
|
||||
def test_update_dialog_polls_host_progress_recovers_and_stops_on_close(self):
|
||||
calls=[]
|
||||
applied=False
|
||||
progress=iter(['applying','disconnected','succeeded'])
|
||||
def status_value(status):
|
||||
return {'current_version':'2.0.0.dev1','latest_version':'v2.0.0','status':status,'message':{'available':'发现正式版本','pending':'等待宿主机','applying':'正在执行更新','succeeded':'宿主机健康检查通过'}[status],
|
||||
'can_apply':status=='available','executor':{'enabled':True},'host_status':{'status':status,'version':'v2.0.0'}}
|
||||
def updates(route):
|
||||
calls.append(route.request.url)
|
||||
stage=next(progress,'succeeded') if applied else 'available'
|
||||
if stage=='disconnected':
|
||||
route.fulfill(status=503,content_type='application/json',body='{"detail":"离线模拟服务重启"}')
|
||||
else:self.fulfill(route,status_value(stage))
|
||||
def apply(route):
|
||||
nonlocal applied
|
||||
applied=True
|
||||
self.fulfill(route,status_value('pending'))
|
||||
self.page.route('**/api/system/updates',updates)
|
||||
self.page.route('**/api/system/updates/apply',apply)
|
||||
self.open()
|
||||
self.page.locator('.menu > summary').nth(3).click()
|
||||
self.page.locator('[data-command="updates"]').click()
|
||||
expect(self.page.get_by_text('发现新版本',exact=True).first).to_be_visible()
|
||||
self.page.once('dialog',lambda prompt:prompt.accept())
|
||||
self.page.get_by_role('button',name='提交更新请求…',exact=True).click()
|
||||
expect(self.page.get_by_text('等待宿主机处理',exact=True).first).to_be_visible()
|
||||
expect(self.page.get_by_text('正在更新并检查健康',exact=True).first).to_be_visible(timeout=7000)
|
||||
expect(self.page.get_by_text('更新完成,健康检查通过',exact=True).first).to_be_visible(timeout=13000)
|
||||
expect(self.page.locator('#dialog-content')).to_contain_text('宿主机健康检查通过')
|
||||
self.page.locator('#dialog-cancel').click()
|
||||
completed=len(calls)
|
||||
self.page.wait_for_timeout(3300)
|
||||
self.assertEqual(len(calls),completed)
|
||||
self.assertFalse([message for message in self.errors if '503' not in message],self.errors)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user