Add Web 2 workspace and controlled deployment updates

This commit is contained in:
AttilaNet
2026-11-10 16:33:14 +08:00
parent 7fe4c0ffdf
commit dbb31707ea
58 changed files with 11283 additions and 0 deletions
+1
View File
@@ -0,0 +1 @@
"""Offline tests; fixtures must use temporary storage and fake game clients."""
+1
View File
@@ -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()
+560
View File
@@ -0,0 +1,560 @@
"""Exercise HTTP behavior with temporary state and fake, offline collaborators."""
import asyncio
import base64
from copy import deepcopy
from datetime import datetime, timedelta, timezone
import json
import os
from pathlib import Path
import subprocess
import sys
import tempfile
import threading
import time
import unittest
from unittest.mock import patch
import httpx
from fastapi.testclient import TestClient
from ranch_web.app import create_app
from ranch_web.config import WebConfig
class FakeUpdates:
def __init__(self):
self.calls = []
self.closed = False
def status(self):
self.calls.append("status")
return {"current_version": "2.0.0.dev1", "status": "unchecked", "can_apply": False,
"message": "尚未配置部署器", "path": "C:/private/updater-state"}
def check(self):
self.calls.append("check")
return {"status": "no_release", "message": "没有可用的正式版本"}
def request_update(self, version=None):
self.calls.append(("apply", version))
return {"status": "unavailable", "message": "尚未配置部署器", "can_apply": False}
def close(self):
self.closed = True
class FakeManager:
def __init__(self):
self.accounts = {}
self.jobs = {}
self.calls = []
self.closed = False
self.pending_config = False
def list_accounts(self):
self.calls.append("list")
return deepcopy(list(self.accounts.values()))
def create_account(self, label="", demo=True):
identifier = f"account_{len(self.accounts) + 1}"
summary = {"id": identifier, "label": label, "demo": demo, "connected": False,
"running": False, "busy": False, "revision": 0, "error": None,
"player": {"name": "离线演示", "level": 1, "exp": 5, "next_exp": 10,
"money": 100, "ke": 0, "ti": 20, "token": "PLAYER_PRIVATE"},
"password": "SUMMARY_PRIVATE", "raw": {"private": "RAW_PRIVATE"}}
self.accounts[identifier] = summary
self.calls.append(("create", demo))
return deepcopy(summary)
def status(self, account_id):
return deepcopy(self.accounts[account_id])
def remove_account(self, account_id):
del self.accounts[account_id]
def get_config(self, account_id):
self.status(account_id)
return {"config": {"policy": {"fill": False}}, "revision": 3}
def set_config(self, account_id, config, revision=None):
self.status(account_id)
self.calls.append(("config", deepcopy(config), revision))
result = {"config": config, "revision": 4}
if self.pending_config:
result.update(pending=True, job_id="config_job")
return result
def view(self, account_id, page, query=None):
self.status(account_id)
self.calls.append(("view", page, query))
return {"data": {"page": page, "title": "背包", "columns": [{"key": "name", "label": "名称"}],
"filters": [{"key": "category", "label": "分类"}], "rows": [{"id": "100", "name": "测试蛋"}],
"raw": {"password": "VIEW_PRIVATE"}},
"loading": True, "job_id": "view_job", "revision": 3}
def submit(self, account_id, operation, payload=None):
self.status(account_id)
self.calls.append(("submit", operation, deepcopy(payload)))
result = {"id": "job_1", "status": "queued", "operation": operation, "result": None, "error": None}
self.jobs[(account_id, "job_1")] = result
return deepcopy(result)
def job(self, account_id, job_id):
return deepcopy(self.jobs[(account_id, job_id)])
def logs(self, account_id, after=0, debug=False):
self.status(account_id)
self.calls.append(("logs", after, debug))
return {"entries": [{"id": 1, "message": "password=LOG_SECRET token=TOKEN_SECRET reqid=REQ_SECRET C:/private/file.log /data/profiles/a"}], "next": 1}
def log_detail(self, account_id, entry_id):
self.status(account_id)
self.calls.append(("detail", entry_id))
return {"id": entry_id, "request": {"body": {"operation": "refresh", "key": "GAME_KEY"}},
"response": {"body": {"player": {"name": "演示角色"}, "token": "GAME_TOKEN"}},
"headers": {"Authorization": "Bearer PRIVATE_BEARER"}}
def close(self):
self.closed = True
class ApiTests(unittest.TestCase):
def setUp(self):
self.temporary = tempfile.TemporaryDirectory(prefix="ranch-web-api-")
self.addCleanup(self.temporary.cleanup)
self.root = Path(self.temporary.name)
self.manager, self.updates = FakeManager(), FakeUpdates()
self.account_id = self.manager.create_account("离线账号")["id"]
self.settings = WebConfig(data_dir=self.root)
self.app = create_app(manager=self.manager, updates=self.updates, config=self.settings)
self.client = self.enterContext(TestClient(self.app, base_url="http://localhost", client=("127.0.0.1", 50000)))
self.network = self.enterContext(patch("requests.sessions.Session.request", side_effect=AssertionError("禁止真实游戏 API")))
self.url = f"/api/accounts/{self.account_id}"
def test_health_meta_and_updates_have_no_game_side_effects(self):
self.manager.calls.clear()
self.assertEqual(self.client.get("/api/health").json(), {"status": "ok", "version": "2.0.0.dev1"})
meta = self.client.get("/api/meta")
self.assertEqual(meta.status_code, 200)
self.assertEqual(meta.json()["gameVersion"], "1.9.68")
self.assertEqual(meta.json()["access"]["mode"], "local")
self.assertEqual(self.client.get("/api/system/updates").status_code, 200)
self.assertEqual(self.manager.calls, [])
self.assertEqual(self.updates.calls, ["status", "status"])
self.assertNotIn("C:/private", meta.text)
self.network.assert_not_called()
def test_injected_objects_are_not_closed_by_lifespan(self):
app = create_app(manager=self.manager, updates=self.updates, config=self.settings)
with TestClient(app, base_url="http://localhost", client=("127.0.0.1", 50001)) as client:
self.assertEqual(client.get("/api/health").status_code, 200)
self.assertFalse(self.manager.closed)
self.assertFalse(self.updates.closed)
def test_owned_objects_closed_even_when_lifespan_fails(self):
with patch("ranch_web.service.WebManager", return_value=self.manager), patch("ranch_web.updates.UpdateService", side_effect=RuntimeError("injected startup failure")):
app = create_app(config=self.settings)
with self.assertRaises(RuntimeError):
with TestClient(app):
pass
self.assertTrue(self.manager.closed)
def test_only_owned_objects_close(self):
with patch("ranch_web.service.WebManager", return_value=self.manager), patch("ranch_web.updates.UpdateService", return_value=self.updates):
with TestClient(create_app(config=self.settings)):
pass
self.assertTrue(self.manager.closed)
self.assertTrue(self.updates.closed)
def test_shutdown_attempts_all_owned_cleanup_when_one_close_fails(self):
with patch("ranch_web.service.WebManager", return_value=self.manager), patch("ranch_web.updates.UpdateService", return_value=self.updates), patch.object(self.updates, "close", side_effect=OSError("private shutdown detail")):
with self.assertRaisesRegex(RuntimeError, "关闭未完成"):
with TestClient(create_app(config=self.settings)):
pass
self.assertTrue(self.manager.closed)
def test_accounts_are_public_and_creation_does_not_start_strategy(self):
response = self.client.post("/api/accounts", json={"label": "另一个离线账号", "demo": True})
self.assertEqual(response.status_code, 201)
self.assertFalse(response.json()["running"])
self.assertNotIn("PRIVATE", response.text)
accounts = self.client.get("/api/accounts").json()
self.assertEqual(len(accounts), 2)
self.assertEqual(accounts[1]["player"]["money"], 100)
self.assertEqual(self.client.delete(f"/api/accounts/{response.json()['id']}").status_code, 204)
self.assertEqual(self.client.get(f"/api/accounts/{response.json()['id']}/status").status_code, 404)
def test_game_login_is_queued_and_credentials_stay_server_side(self):
response = self.client.post(self.url + "/actions/login", json={"account": "fake-account", "password": "GAME_PASSWORD", "remember": True})
self.assertEqual(response.status_code, 202)
self.assertEqual(response.json()["status"], "queued")
self.assertEqual(self.manager.calls[-1][1], "login")
job_id = response.json()["id"]
self.manager.jobs[(self.account_id, job_id)].update(
status="succeeded", result={"servers": [{"id": 1, "name": "一区", "role_name": "角色"}],
"has_saved_password": True, "key": "GAME_KEY", "token": "GAME_TOKEN",
"message": "GAME_PASSWORD", "raw": {"account": "private"}})
result = self.client.get(self.url + f"/jobs/{job_id}")
self.assertEqual(result.json()["result"]["servers"][0]["name"], "一区")
self.assertTrue(result.json()["result"]["has_saved_password"])
for secret in ("GAME_PASSWORD", "GAME_TOKEN", "GAME_KEY", "private"):
self.assertNotIn(secret, result.text)
def test_views_keep_column_and_filter_keys_and_return_loading(self):
response = self.client.get(self.url + "/views/bag", params={"query": json.dumps({"category": "eggs", "search": "蛋"})})
self.assertEqual(response.status_code, 200)
value = response.json()
self.assertTrue(value["loading"])
self.assertEqual(value["data"]["columns"][0]["key"], "name")
self.assertEqual(value["data"]["filters"][0]["key"], "category")
self.assertEqual(self.manager.calls[-1], ("view", "bag", {"category": "eggs", "search": "蛋"}))
self.assertNotIn("VIEW_PRIVATE", response.text)
def test_schema_page_keys_survive_public_redaction(self):
value = {"pages": [{"key": "login", "title": "登录", "form": []}], "columns": [{"key": "name", "label": "名称"}]}
with patch("ranch_web.views.schema", return_value=value):
response = self.client.get("/api/schema")
self.assertEqual(response.status_code, 200)
self.assertEqual(response.json(), value)
def test_real_demo_pipeline_uses_only_temporary_state_and_offline_core(self):
root = self.root / "real-demo"
with TestClient(create_app(config=WebConfig(data_dir=root)), base_url="http://localhost", client=("127.0.0.1", 50001)) as client:
self.assertEqual(client.get("/api/accounts").json(), [])
created = client.post("/api/accounts", json={"label": "隔离演示", "demo": True})
self.assertEqual(created.status_code, 201)
prefix = "/api/accounts/" + created.json()["id"]
def poll(job_id):
deadline = time.monotonic() + 5
while time.monotonic() < deadline:
response = client.get(prefix + "/jobs/" + job_id)
self.assertEqual(response.status_code, 200)
value = response.json()
if value["status"] in {"succeeded", "failed", "cancelled"}:
self.assertEqual(value["status"], "succeeded", value)
return value
time.sleep(.01)
self.fail("离线任务未在时限内完成")
pages = client.get("/api/schema").json()["pages"]
self.assertEqual(len(pages), 15)
for page in pages:
value = client.get(prefix + "/views/" + page["key"]).json()
if value["loading"] and value.get("job_id"):
poll(value["job_id"])
value = client.get(prefix + "/views/" + page["key"]).json()
self.assertEqual(value["data"]["page"], page["key"])
self.assertTrue(all("key" in column for column in value["data"]["columns"]))
if page["key"] == "mainline":
self.assertEqual(value["data"]["tabs"], [
{"key": "status", "title": "任务状态"},
{"key": "policy", "title": "推进策略"},
])
self.assertTrue(value["data"]["form"])
elif page["key"] == "hatching":
self.assertEqual([tab["key"] for tab in value["data"]["tabs"]], ["孵蛋策略", "牧场策略", "喂养策略"])
config = client.get(prefix + "/config").json()
config["config"]["interval"] = 60
saved = client.put(prefix + "/config", json=config)
self.assertEqual(saved.status_code, 202)
poll(saved.json()["job_id"])
self.assertEqual(client.get(prefix + "/config").json()["config"]["interval"], 60)
exported = client.get(prefix + "/config/export")
document = poll(exported.json()["id"])["result"]
self.assertEqual(document["assistantVersion"], "2.0.0.dev1")
imported = client.post(prefix + "/config/import", json=document)
self.assertEqual(imported.status_code, 202)
poll(imported.json()["id"])
self.assertFalse(client.get(prefix + "/status").json()["running"])
self.network.assert_not_called()
def test_simple_view_query_is_supported_and_mixed_query_rejected(self):
self.assertEqual(self.client.get(self.url + "/views/maps?search=abc").status_code, 200)
self.assertEqual(self.manager.calls[-1], ("view", "maps", {"search": "abc"}))
for params in ({"query": "[1]"}, {"query": "{"}, {"query": "{}", "search": "abc"}):
with self.subTest(params=params):
self.assertEqual(self.client.get(self.url + "/views/maps", params=params).status_code, 400)
def test_configuration_revision_and_deferred_application(self):
self.assertEqual(self.client.get(self.url + "/config").json()["revision"], 3)
response = self.client.put(self.url + "/config", json={"config": {"policy": {"fill": True}}, "revision": 3})
self.assertEqual(response.status_code, 200)
self.assertEqual(self.manager.calls[-1], ("config", {"policy": {"fill": True}}, 3))
self.manager.pending_config = True
response = self.client.put(self.url + "/config", json={"config": {}, "revision": 4})
self.assertEqual(response.status_code, 202)
self.assertTrue(response.json()["pending"])
self.assertEqual(response.json()["job_id"], "config_job")
def test_import_and_export_use_jobs_and_never_accept_server_paths(self):
self.assertEqual(self.client.get(self.url + "/config/export").status_code, 202)
self.assertEqual(self.manager.calls[-1], ("submit", "export_config", {}))
self.assertEqual(self.client.post(self.url + "/config/import", json={"config": {"format": "offline"}}).status_code, 202)
self.assertEqual(self.manager.calls[-1][1], "import_config")
self.assertEqual(self.client.post(self.url + "/config/import", json={"format": "portable", "schema": 2}).status_code, 202)
self.assertEqual(self.manager.calls[-1], ("submit", "import_config", {"config": {"format": "portable", "schema": 2}}))
for payload in ({"path": "C:/private/file.csv"}, {"filename": "../file.csv"}, {"config": {"file_path": "/data/private"}}):
with self.subTest(payload=payload):
self.assertEqual(self.client.post(self.url + "/actions/import_yields", json=payload).status_code, 400)
def test_debug_detail_is_lazy_and_preserves_structured_redacted_body(self):
response = self.client.get(self.url + "/logs?after=7&debug=true")
self.assertEqual(response.status_code, 200)
self.assertEqual(self.manager.calls[-1], ("logs", 7, True))
for secret in ("LOG_SECRET", "TOKEN_SECRET", "REQ_SECRET", "C:/private", "/data/profiles"):
self.assertNotIn(secret, response.text)
self.assertNotIn(("detail", 1), self.manager.calls)
detail = self.client.get(self.url + "/logs/1")
self.assertEqual(detail.status_code, 200)
self.assertEqual(detail.json()["response"]["body"]["player"]["name"], "演示角色")
self.assertEqual(detail.json()["request"]["body"]["operation"], "refresh")
self.assertEqual(self.manager.calls[-1], ("detail", 1))
for secret in ("GAME_KEY", "GAME_TOKEN", "PRIVATE_BEARER"):
self.assertNotIn(secret, detail.text)
alias = self.client.get(self.url + "/debug/1")
self.assertEqual(alias.status_code, 200)
self.assertEqual(alias.json(), detail.json())
def test_updates_check_and_apply_are_explicit_and_invalid_versions_never_dispatched(self):
self.assertEqual(self.client.post("/api/system/updates/check").json()["status"], "no_release")
self.assertEqual(self.updates.calls[-1], "check")
for version in ("main", "v2.0.0.dev1", "2.0.0;whoami", "../v2.0.0", "v2.0.0\n", "v1.2.0", "2.0.1", "v2.01.0"):
with self.subTest(version=version):
response = self.client.post("/api/system/updates/apply", json={"version": version})
self.assertEqual(response.status_code, 400)
self.assertFalse(any(isinstance(call, tuple) for call in self.updates.calls))
response = self.client.post("/api/system/updates/apply", json={"version": "v2.0.1"})
self.assertEqual(response.status_code, 202)
self.assertEqual(response.json()["status"], "unavailable")
self.assertEqual(self.updates.calls[-1], ("apply", "v2.0.1"))
def test_identifiers_allowlists_and_validation_do_not_echo_input(self):
self.manager.calls.clear()
self.assertEqual(self.client.get("/api/accounts/账户/status").status_code, 422)
self.assertEqual(self.client.get(self.url + "/jobs/a.b").status_code, 422)
self.assertEqual(self.client.get(self.url + "/views/unknown").status_code, 404)
self.assertEqual(self.client.post(self.url + "/actions/run_shell", json={}).status_code, 404)
response = self.client.post("/api/accounts", json={"label": {"password": "MUST_NOT_ECHO"}, "demo": "true"})
self.assertEqual(response.status_code, 422)
self.assertNotIn("MUST_NOT_ECHO", response.text)
self.assertEqual(self.manager.calls, [])
def test_body_limit_handles_declared_and_streamed_bodies(self):
app = create_app(manager=self.manager, updates=self.updates, config=WebConfig(data_dir=self.root, max_body_bytes=1024))
with TestClient(app, base_url="http://localhost", client=("127.0.0.1", 50001)) as client:
for body in (b"x" * 1025, iter([b"x" * 800, b"x" * 800])):
self.assertEqual(client.post(self.url + "/actions/refresh", content=body, headers={"Content-Type": "application/json"}).status_code, 413)
self.assertEqual(client.post(self.url + "/actions/refresh", content=b"{}", headers={"Content-Type": "text/plain"}).status_code, 415)
self.assertEqual(client.post(self.url + "/actions/refresh", content=b"{}", headers={"Content-Type": "application/json", "Content-Length": "3"}).status_code, 400)
def test_yield_import_declared_body_limit_is_12mib_for_exact_post_route(self):
limit = 12 * 1024 * 1024
prefix = b'{"filename":"data.csv","content_base64":""}'
body = prefix + b" " * (limit - len(prefix))
response = self.client.post(self.url + "/actions/import_yields", content=body, headers={"Content-Type": "application/json"})
self.assertEqual(response.status_code, 202)
self.assertEqual(self.manager.calls[-1], ("submit", "import_yields", {"filename": "data.csv", "content_base64": ""}))
before = len(self.manager.calls)
response = self.client.post(self.url + "/actions/import_yields", content=b"{}", headers={"Content-Type": "application/json", "Content-Length": str(limit + 1)})
self.assertEqual(response.status_code, 413)
ordinary = prefix + b" " * (1024 * 1024 + 1 - len(prefix))
for method, endpoint in (("POST", self.url + "/actions/refresh"),
("POST", self.url + "/actions/import_config"),
("POST", self.url + "/config/import"),
("POST", self.url + "/actions/import_yields_extra"),
("PUT", self.url + "/actions/import_yields"),
("POST", "/api/accounts/invalid.id/actions/import_yields")):
with self.subTest(method=method, endpoint=endpoint):
response = self.client.request(method, endpoint, content=ordinary, headers={"Content-Type": "application/json"})
self.assertEqual(response.status_code, 413)
self.assertEqual(len(self.manager.calls), before)
def test_yield_import_streamed_body_limit_is_12mib_and_other_routes_keep_1mib(self):
async def stream(size):
prefix = b'{"filename":"data.csv","content_base64":""}'
yield prefix
remaining = size - len(prefix)
chunk = b" " * (256 * 1024)
while remaining:
count = min(remaining, len(chunk))
yield chunk[:count]
remaining -= count
async def scenario():
transport = httpx.ASGITransport(app=self.app, client=("127.0.0.1", 50001))
async with httpx.AsyncClient(transport=transport, base_url="http://localhost") as client:
response = await client.post(self.url + "/actions/import_yields", content=stream(12 * 1024 * 1024), headers={"Content-Type": "application/json"})
self.assertNotIn("content-length", response.request.headers)
self.assertEqual(response.status_code, 202)
before = len(self.manager.calls)
for endpoint, size in ((self.url + "/actions/import_yields", 12 * 1024 * 1024 + 1),
(self.url + "/actions/refresh", 1024 * 1024 + 1)):
response = await client.post(endpoint, content=stream(size), headers={"Content-Type": "application/json"})
self.assertEqual(response.status_code, 413)
self.assertEqual(len(self.manager.calls), before)
asyncio.run(scenario())
def test_real_yield_action_accepts_exact_8mib_and_rejects_one_extra_byte(self):
header = b"typeId,sell_money,note\n"
row = b"1001010,7777," + b"x" * 4096 + b"\n"
count, remainder = divmod(8 * 1024 * 1024 - len(header), len(row))
content = header + row * count + b"\n" * remainder
self.assertEqual(len(content), 8 * 1024 * 1024)
with TestClient(create_app(config=WebConfig(data_dir=self.root / "large-yields")), base_url="http://localhost", client=("127.0.0.1", 50001)) as client:
created = client.post("/api/accounts", json={"demo": True}).json()
prefix = "/api/accounts/" + created["id"]
for suffix, expected_status in ((b"", "succeeded"), (b"\n", "failed")):
with self.subTest(decoded_bytes=len(content) + len(suffix)):
response = client.post(prefix + "/actions/import_yields", json={"filename": "data.csv", "content_base64": base64.b64encode(content + suffix).decode("ascii")})
self.assertEqual(response.status_code, 202, response.text)
job_id = response.json()["id"]
deadline = time.monotonic() + 5
job = None
while time.monotonic() < deadline:
job = client.get(prefix + "/jobs/" + job_id).json()
if job["status"] in {"succeeded", "failed", "cancelled"}:
break
time.sleep(.01)
self.assertEqual(job["status"], expected_status, job)
if expected_status == "succeeded":
self.assertEqual(job["result"]["count"], 1)
self.assertEqual(job["result"]["overrides"]["1001010"]["sell_money"], 7777)
else:
self.assertIn("8MiB", job["error"])
self.assertEqual(client.get(prefix + "/config").json()["config"]["overrides"]["1001010"]["sell_money"], 7777)
self.network.assert_not_called()
def test_real_update_service_request_metadata_survives_only_in_update_dtos(self):
from ranch_web.updates import UpdateService
data = self.root / "updater-data"
control = self.root / "updater-control"
control.mkdir()
now = datetime.now(timezone.utc)
capability = {"protocol": 1, "executor_id": "a" * 32, "enabled": True, "auto_apply": False,
"heartbeat_at": now.isoformat(), "expires_at": (now + timedelta(minutes=15)).isoformat()}
(control / "capability.json").write_text(json.dumps(capability), encoding="utf-8")
service = UpdateService(data, "2.0.0.dev1")
releases = [{"tag_name": "v2.1.0", "draft": False, "prerelease": False}]
with patch.dict(os.environ, {"RANCH_WEB_UPDATER_DIR": str(control)}), patch("ranch_web.updates.github_releases", return_value=releases) as github:
with TestClient(create_app(manager=self.manager, updates=service, config=self.settings), base_url="http://localhost", client=("127.0.0.1", 50001)) as client:
checked = client.post("/api/system/updates/check").json()
self.assertEqual(checked["latest_version"], "v2.1.0")
self.assertTrue(checked["can_apply"])
applied = client.post("/api/system/updates/apply", json={"version": "v2.1.0"})
self.assertEqual(applied.status_code, 202)
pending = applied.json()
self.assertEqual(pending["status"], "pending")
request = pending["request"]
self.assertRegex(request["request_id"], r"^[0-9a-f]{32}$")
self.assertEqual(request["version"], "v2.1.0")
self.assertEqual(request["status"], "pending")
self.assertEqual(client.get("/api/system/updates").json()["request"], request)
self.assertEqual(client.get("/api/meta").json()["updates"]["request"], request)
host = {"protocol": 1, "request_id": request["request_id"], "version": "v2.1.0", "status": "applying",
"updated_at": now.isoformat(), "password": "HOST_PRIVATE", "key": "HOST_KEY", "path": "C:/private/updater"}
(data / "updater-status.json").write_text(json.dumps(host), encoding="utf-8")
for state in (client.get("/api/system/updates").json(), client.get("/api/meta").json()["updates"]):
self.assertEqual(state["status"], "applying")
self.assertEqual(state["request"]["status"], "applying")
self.assertEqual(state["host_status"]["request_id"], request["request_id"])
self.assertEqual(state["host_status"]["version"], "v2.1.0")
for private in ("HOST_PRIVATE", "HOST_KEY", "C:/private", "executor_id"):
self.assertNotIn(private, json.dumps(state))
job = client.post(self.url + "/actions/refresh", json={}).json()
self.manager.jobs[(self.account_id, job["id"])].update(status="succeeded", result={
"request": {"request_id": request["request_id"], "key": "GAME_KEY"},
"request_id": request["request_id"], "reqid": "GAME_REQID", "token": "GAME_TOKEN"})
game = client.get(self.url + "/jobs/" + job["id"]).json()["result"]
self.assertEqual(game, {})
self.assertEqual(github.call_count, 2)
self.network.assert_not_called()
def test_errors_hide_stack_traces_and_local_paths(self):
errors = [ValueError("参数无效 C:/private/key.json password=VALUE_PRIVATE"), RuntimeError("状态不可用 /home/private token=RUNTIME_PRIVATE"), OSError("OSError: C:/private/INTERNAL_PRIVATE")]
for error in errors:
with self.subTest(error=type(error).__name__), patch.object(self.manager, "status", side_effect=error):
response = self.client.get(self.url + "/status")
self.assertIn(response.status_code, (400, 409, 500))
for secret in ("C:/private", "/home/private", "VALUE_PRIVATE", "RUNTIME_PRIVATE", "INTERNAL_PRIVATE", "Traceback", "OSError"):
self.assertNotIn(secret, response.text)
def test_job_errors_are_chinese_and_never_return_tracebacks(self):
job = self.client.post(self.url + "/actions/refresh", json={}).json()
self.manager.jobs[(self.account_id, job["id"])].update(status="failed", error='Traceback (most recent call last):\n File "C:/private/server.py", line 5\nsecret()')
response = self.client.get(self.url + "/jobs/" + job["id"])
self.assertEqual(response.status_code, 200)
self.assertEqual(response.json()["error"], "操作未完成,请查看已脱敏日志后重试")
self.assertNotIn("Traceback", response.text)
def test_cli_demo_uses_explicit_temporary_root_and_no_browser(self):
from ranch_web.__main__ import main
root = self.root / "cli"
def run(application, **kwargs):
self.assertEqual(application.state.config.data_dir, root)
self.assertFalse(kwargs["access_log"])
with TestClient(application, base_url="http://localhost", client=("127.0.0.1", 50001)) as client:
accounts = client.get("/api/accounts").json()
self.assertEqual(len(accounts), 1)
self.assertTrue(accounts[0]["demo"])
self.assertFalse(accounts[0]["running"])
with patch("ranch_web.__main__.uvicorn.run", side_effect=run) as runner, patch("ranch_web.__main__.webbrowser.open") as browser:
result = main(["--host", "127.0.0.1", "--port", "8765", "--data-dir", str(root), "--demo", "--no-browser"])
self.assertEqual(result, 0)
runner.assert_called_once()
browser.assert_not_called()
self.network.assert_not_called()
def test_static_files_are_restricted_to_frontend_assets(self):
for url in ("/static/.env", "/static/config.py", "/static/../app.py", "/static/%2e%2e/requirements.txt"):
with self.subTest(url=url):
self.assertEqual(self.client.get(url).status_code, 404)
response = self.client.get("/")
self.assertIn(response.status_code, (200, 503))
if response.status_code == 200:
self.assertIn("text/html", response.headers["content-type"])
self.assertEqual(response.headers["x-content-type-options"], "nosniff")
self.assertIn("frame-ancestors 'none'", response.headers["content-security-policy"])
def test_cli_help_and_factory_do_not_import_qt_or_open_private_state(self):
project = Path(__file__).resolve().parents[2]
script = "from ranch_web.app import create_app; import sys; assert not any(k.startswith('PySide6') or k.endswith('_gui') for k in sys.modules)"
result = subprocess.run([sys.executable, "-c", script], cwd=project, capture_output=True)
self.assertEqual(result.returncode, 0, result.stderr.decode(errors="replace"))
result = subprocess.run([sys.executable, "-m", "ranch_web", "--help"], cwd=project, capture_output=True)
self.assertEqual(result.returncode, 0)
self.assertIn(b"--no-browser", result.stdout)
self.assertIn(b"--data-dir", result.stdout)
def test_blocking_update_work_does_not_block_event_loop(self):
entered, release = threading.Event(), threading.Event()
def blocking_check():
entered.set()
if not release.wait(5):
raise RuntimeError("offline synchronization timed out")
return {"status": "no_release"}
async def scenario():
transport = httpx.ASGITransport(app=self.app, client=("127.0.0.1", 50001))
async with httpx.AsyncClient(transport=transport, base_url="http://localhost") as client:
task = asyncio.create_task(client.post("/api/system/updates/check"))
try:
self.assertTrue(await asyncio.to_thread(entered.wait, 2))
response = await asyncio.wait_for(client.get("/api/health"), 1)
self.assertEqual(response.status_code, 200)
self.assertFalse(task.done())
finally:
release.set()
self.assertEqual((await task).status_code, 200)
with patch.object(self.updates, "check", side_effect=blocking_check):
asyncio.run(scenario())
if __name__ == "__main__":
unittest.main()
+197
View File
@@ -0,0 +1,197 @@
"""Administrator sessions and browser boundary checks, entirely offline."""
import asyncio
from pathlib import Path
import tempfile
import threading
import unittest
from unittest.mock import patch
import httpx
from fastapi.testclient import TestClient
from ranch_web.app import create_app
from ranch_web.config import COOKIE_NAME, WebConfig, hash_password, verify_password
from ranch_web.tests.test_api import FakeManager, FakeUpdates
class AuthTests(unittest.TestCase):
def setUp(self):
self.temporary = tempfile.TemporaryDirectory(prefix="ranch-web-auth-")
self.addCleanup(self.temporary.cleanup)
self.root = Path(self.temporary.name)
self.manager, self.updates = FakeManager(), FakeUpdates()
def client(self, settings=None, **kwargs):
settings = settings or WebConfig(data_dir=self.root)
app = create_app(manager=self.manager, updates=self.updates, config=settings)
return self.enterContext(TestClient(app, base_url="http://localhost", client=("127.0.0.1", 50000), **kwargs))
def test_loopback_bypass_is_local_and_has_no_password_cookie(self):
client = self.client()
self.assertEqual(client.get("/api/auth/status").json(), {"required": False, "authenticated": True, "access_mode": "local"})
response = client.post("/api/accounts", json={"demo": True}, headers={"Origin": "http://localhost"})
self.assertEqual(response.status_code, 201)
self.assertNotIn("set-cookie", response.headers)
remote = self.enterContext(TestClient(create_app(manager=self.manager, updates=self.updates, config=WebConfig(data_dir=self.root)), base_url="http://localhost", client=("192.0.2.1", 50001)))
self.assertEqual(remote.get("/api/accounts").status_code, 403)
self.assertFalse(remote.get("/api/auth/status").json()["authenticated"])
def test_remote_bind_and_public_proxy_names_require_password(self):
for values in ({"host": "0.0.0.0"}, {"host": "::"}, {"host": "192.0.2.10"}, {"allowed_hosts": ("ranch.example",)}, {"allowed_origins": ("https://ranch.example",)}):
with self.subTest(values=values), self.assertRaises(ValueError):
WebConfig(data_dir=self.root, **values)
def test_plain_password_cookie_login_logout_and_replay(self):
client = self.client(WebConfig(data_dir=self.root, password="离线管理密码"))
self.assertEqual(client.get("/api/accounts").status_code, 401)
self.assertFalse(client.get("/api/auth/status").json()["authenticated"])
self.assertEqual(client.post("/api/auth/login", json={"password": "错误"}).status_code, 401)
response = client.post("/api/auth/login", json={"password": "离线管理密码"})
self.assertEqual(response.status_code, 200)
self.assertNotIn("离线管理密码", response.text)
cookie = response.headers["set-cookie"].lower()
self.assertIn("httponly", cookie)
self.assertIn("samesite=strict", cookie)
self.assertIn("path=/api", cookie)
self.assertEqual(client.get("/api/accounts").status_code, 200)
token = client.cookies.get(COOKIE_NAME)
self.assertEqual(len(token), 43)
self.assertEqual(client.post("/api/auth/logout").status_code, 200)
self.assertEqual(client.get("/api/accounts", headers={"Cookie": f"{COOKIE_NAME}={token}"}).status_code, 401)
def test_hash_password_authentication_and_secure_proxy_cookie(self):
encoded = hash_password("offline-password", iterations=100_000)
settings = WebConfig(data_dir=self.root, host="0.0.0.0", password_hash=encoded, secure_cookie=True,
allowed_hosts=("ranch.example",), allowed_origins=("https://ranch.example",))
app = create_app(manager=self.manager, updates=self.updates, config=settings)
client = self.enterContext(TestClient(app, base_url="https://ranch.example", client=("192.0.2.1", 50000)))
response = client.post("/api/auth/login", json={"password": "offline-password"}, headers={"Origin": "https://ranch.example"})
self.assertEqual(response.status_code, 200)
self.assertIn("Secure", response.headers["set-cookie"])
self.assertEqual(client.get("/api/accounts").status_code, 200)
self.assertNotIn(encoded, repr(settings))
def test_wrong_password_is_rate_limited_without_changing_accounts(self):
client = self.client(WebConfig(data_dir=self.root, password="correct"))
for _ in range(10):
self.assertEqual(client.post("/api/auth/login", json={"password": "wrong"}).status_code, 401)
response = client.post("/api/auth/login", json={"password": "wrong"})
self.assertEqual(response.status_code, 429)
self.assertEqual(self.manager.calls, [])
def test_concurrent_wrong_passwords_reserve_slots_without_serializing_other_peers(self):
client = self.client(WebConfig(data_dir=self.root, password_hash=hash_password("correct", iterations=100_000)))
self.assertEqual(client.post("/api/auth/login", json={"password": "correct"}).status_code, 200)
cookie = client.cookies.get(COOKIE_NAME)
entered, release, counter_lock = threading.Event(), threading.Event(), threading.Lock()
verifying = 0
def blocked_verification(password, configured):
nonlocal verifying
if password == "wrong":
with counter_lock:
verifying += 1
if verifying >= 10:
entered.set()
if not release.wait(5):
raise AssertionError("password verification gate timed out")
return verify_password(password, configured)
async def scenario():
transport = httpx.ASGITransport(app=client.app, client=("127.0.0.1", 50001))
other_transport = httpx.ASGITransport(app=client.app, client=("127.0.0.2", 50002))
async with httpx.AsyncClient(transport=transport, base_url="http://localhost") as http, httpx.AsyncClient(transport=other_transport, base_url="http://localhost") as other:
rejected = 0
rejected_two = asyncio.Event()
async def attempt():
nonlocal rejected
response = await http.post("/api/auth/login", json={"password": "wrong"})
if response.status_code == 429:
rejected += 1
if rejected == 2:
rejected_two.set()
return response.status_code
tasks = [asyncio.create_task(attempt()) for _ in range(12)]
try:
self.assertTrue(await asyncio.to_thread(entered.wait, 2), "ten verifications must run concurrently")
await asyncio.wait_for(rejected_two.wait(), 2)
with counter_lock:
self.assertEqual(verifying, 10)
authenticated = await asyncio.wait_for(http.get("/api/accounts", headers={"Cookie": f"{COOKIE_NAME}={cookie}"}), 2)
self.assertEqual(authenticated.status_code, 200)
unrelated = await asyncio.wait_for(other.post("/api/auth/login", json={"password": "correct"}), 2)
self.assertEqual(unrelated.status_code, 200)
finally:
release.set()
outcomes = await asyncio.gather(*tasks)
self.assertEqual(outcomes.count(401), 10)
self.assertEqual(outcomes.count(429), 2)
self.assertEqual((await http.post("/api/auth/login", json={"password": "wrong"})).status_code, 429)
with counter_lock:
self.assertEqual(verifying, 10)
with patch("ranch_web.app.verify_password", side_effect=blocked_verification):
asyncio.run(scenario())
self.assertEqual(self.manager.calls, ["list"])
def test_admin_password_does_not_corrupt_public_identifiers_or_versions(self):
client = self.client(WebConfig(data_dir=self.root, password="1"))
self.assertEqual(client.post("/api/auth/login", json={"password": "1"}).status_code, 200)
self.assertEqual(client.get("/api/meta").json()["version"], "2.0.0.dev1")
account = client.post("/api/accounts", json={"demo": True}).json()
self.assertEqual(account["id"], "account_1")
self.assertEqual(client.get("/api/accounts/account_1/status").status_code, 200)
def test_dns_rebinding_and_forwarded_host_cannot_bypass_host_allowlist(self):
client = self.client()
for hostname in ("attacker.example", "localhost.attacker.example", "127.0.0.1.attacker.example", "attacker.example:8765", "localhost@attacker.example", "localhost/evil", "localhost:bad"):
with self.subTest(hostname=hostname):
response = client.post("/api/accounts", headers={"Host": hostname, "X-Forwarded-Host": "localhost"}, json={"demo": True})
self.assertEqual(response.status_code, 400)
self.assertEqual(self.manager.calls, [])
def test_cross_site_writes_including_auth_are_blocked_before_dispatch(self):
client = self.client(WebConfig(data_dir=self.root, password="correct"))
for endpoint, payload in (("/api/auth/login", {"password": "correct"}), ("/api/auth/logout", {}), ("/api/accounts", {"demo": True}), ("/api/system/updates/apply", {})):
for origin in ("https://attacker.example", "http://localhost.attacker.example", "null", "file://"):
with self.subTest(endpoint=endpoint, origin=origin):
self.assertEqual(client.post(endpoint, json=payload, headers={"Origin": origin}).status_code, 403)
self.assertEqual(client.post("/api/auth/login", json={"password": "correct"}, headers={"Sec-Fetch-Site": "cross-site"}).status_code, 403)
self.assertEqual(self.manager.calls, [])
def test_origin_includes_port_and_never_uses_forwarded_header(self):
client = self.client()
self.assertEqual(client.post("/api/accounts", json={}, headers={"Origin": "http://localhost:8765"}).status_code, 403)
self.assertEqual(client.post("/api/accounts", json={}, headers={"Origin": "https://localhost", "X-Forwarded-Proto": "https"}).status_code, 403)
self.assertEqual(client.post("/api/accounts", json={}, headers={"Origin": "http://localhost:80"}).status_code, 201)
def test_no_wildcard_cors_and_errors_do_not_echo_password(self):
client = self.client(WebConfig(data_dir=self.root, password="correct"))
response = client.options("/api/accounts", headers={"Origin": "https://attacker.example", "Access-Control-Request-Method": "POST"})
self.assertNotIn("access-control-allow-origin", response.headers)
response = client.post("/api/auth/login", json={"password": "SENSITIVE" * 1000})
self.assertEqual(response.status_code, 422)
self.assertNotIn("SENSITIVE", response.text)
def test_cookie_from_another_application_instance_is_invalid(self):
settings = WebConfig(data_dir=self.root, password="correct")
client = self.client(settings)
client.post("/api/auth/login", json={"password": "correct"})
token = client.cookies.get(COOKIE_NAME)
another = self.client(settings)
self.assertEqual(another.get("/api/accounts", headers={"Cookie": f"{COOKIE_NAME}={token}"}).status_code, 401)
def test_environment_and_cli_overrides_use_same_names(self):
settings = WebConfig.from_env({"RANCH_WEB_HOST": "0.0.0.0", "RANCH_WEB_PORT": "8766", "RANCH_WEB_DATA_DIR": str(self.root / "env"), "RANCH_WEB_PASSWORD": "offline", "RANCH_WEB_SECURE_COOKIE": "1"}, port=8767, data_dir=self.root / "override")
self.assertEqual(settings.host, "0.0.0.0")
self.assertEqual(settings.port, 8767)
self.assertEqual(settings.data_dir, self.root / "override")
self.assertTrue(settings.secure_cookie)
self.assertNotIn("offline", repr(settings))
if __name__ == "__main__":
unittest.main()
+106
View File
@@ -0,0 +1,106 @@
"""Deterministic timing checks: no waits, no game clients and no Qt."""
import math
from types import SimpleNamespace
import unittest
from ranch_assistant.model import Action
from ranch_web.policies import default_config
from ranch_web.scheduler import AccountSchedule
class SchedulerTests(unittest.TestCase):
def setUp(self):
self.now = 1000.0
self.draws = []
def uniform(low, high):
self.draws.append((low, high))
return (low + high) / 2
self.schedule = AccountSchedule(clock=lambda: self.now, uniform=uniform)
self.config = default_config()
self.config["policy"].update(enabled=True, fill=True, gift_enabled=True, breakthrough_targets={"101": 1})
self.config["explore_policy"]["enabled"] = True
self.pending = False
self.snapshot = SimpleNamespace(now=1000, raw={"exploreTeams": []})
self.engine = SimpleNamespace(snapshot=self.snapshot, demo=True, client=None,
heartbeat_enabled=True, last_heartbeat=1000, pending_recovery_due=lambda: False,
master_sync_due=lambda: False, growth_sync_due=lambda: False,
_progression_pending=lambda: self.pending, _breakthrough_pending=None,
explore_planner=SimpleNamespace(pending=lambda snapshot: None, remaining=lambda snapshot, team: 8),
gift_planner=SimpleNamespace(next_ready_at=1003),
pending_hatches=[Action("hatch", "hatch", "offline/hatch", {})])
self.plans = [Action(kind, kind, "offline/" + kind, {}) for kind in ("progression", "explore_start", "breakthrough", "gift")]
self.schedule.monitor()
self.schedule.next_poll = math.inf
def test_hatch_uses_one_to_two_seconds_and_kind_isolation(self):
self.schedule.arm(self.engine, self.config, True, self.plans)
self.assertEqual(self.schedule.next_fast["hatch"], 1001.5)
self.assertIn((1, 2), self.draws)
self.now = 1002
self.assertEqual(self.schedule.due(self.engine, self.config, True), "hatch")
self.assertNotEqual(self.schedule.due(self.engine, self.config, True), "poll")
def test_completing_one_kind_preserves_other_deadlines(self):
self.schedule.arm(self.engine, self.config, True, self.plans)
self.schedule.next_fast["breakthrough"] = 999
self.schedule.next_fast["hatch"] = 999
self.now += 3
self.snapshot.now = self.now
self.schedule.arm(self.engine, self.config, True, self.plans, completed="gift")
self.assertEqual(self.schedule.next_fast["breakthrough"], 999)
self.assertEqual(self.schedule.next_fast["hatch"], 999)
self.assertEqual(self.schedule.next_fast["gift"], 1003)
def test_stop_keeps_monitoring_and_clears_fast_deadlines(self):
self.schedule.arm(self.engine, self.config, True, self.plans)
self.schedule.stop()
self.assertTrue(self.schedule.monitoring)
self.assertTrue(all(math.isinf(value) for value in self.schedule.next_fast.values()))
self.schedule.next_poll = self.now
self.assertEqual(self.schedule.due(self.engine, self.config, False), "poll")
def test_unknown_pending_suppresses_all_fast_retries(self):
self.pending = True
self.schedule.arm(self.engine, self.config, True, self.plans)
self.assertTrue(all(math.isinf(value) for value in self.schedule.next_fast.values()))
def test_priority_heartbeat_reconciliation_master_growth_then_monitor(self):
self.engine.demo, self.engine.client = False, object()
self.engine.last_heartbeat = 0
self.engine.pending_recovery_due = lambda: True
self.engine.master_sync_due = lambda: True
self.engine.growth_sync_due = lambda: True
self.assertEqual(self.schedule.due(self.engine, self.config, False), "heartbeat")
self.engine.last_heartbeat = self.now
self.assertEqual(self.schedule.due(self.engine, self.config, False), "reconcile")
self.engine.pending_recovery_due = lambda: False
self.assertEqual(self.schedule.due(self.engine, self.config, False), "master_sync")
self.engine.master_sync_due = lambda: False
self.assertEqual(self.schedule.due(self.engine, self.config, False), "growth_sync")
def test_random_monitor_interval_is_redrawn_each_time(self):
self.config["interval"] = 120
self.schedule.poll_finished(self.config)
self.now += 1
self.schedule.poll_finished(self.config)
self.assertEqual(self.draws, [(0, 120), (0, 120)])
self.assertEqual(self.schedule.next_poll, 1061)
def test_running_exploration_arms_its_completion_deadline(self):
self.snapshot.raw["exploreTeams"] = [{"id": 1, "status": 1}]
self.schedule.arm(self.engine, self.config, True, [])
self.assertEqual(self.schedule.next_fast["explore"], 1009)
def test_maintenance_errors_back_off_instead_of_busy_looping(self):
self.engine.demo, self.engine.client = False, object()
self.engine.last_heartbeat = 0
self.schedule.maintenance_failed("heartbeat")
self.assertIsNone(self.schedule.due(self.engine, self.config, False))
self.now += 30
self.assertEqual(self.schedule.due(self.engine, self.config, False), "heartbeat")
if __name__ == "__main__":
unittest.main()
+595
View File
@@ -0,0 +1,595 @@
"""Account lifecycle/concurrency with temporary state and offline HTTP fakes."""
from copy import deepcopy
from dataclasses import replace
import json
from pathlib import Path
import subprocess
import sys
import tempfile
import threading
import time
from types import SimpleNamespace
import unittest
from unittest.mock import patch
from requests import Response
from requests.sessions import Session as HttpSession
from ranch_assistant.api import Client, Session, decode, encode
from ranch_assistant.engine import Engine, demo_snapshot
from ranch_assistant.model import Catalog
from ranch_web.service import RevisionConflict, WebManager
from ranch_web.store import session_identity
class FakeClient(Client):
catalog = Catalog()
calls = []
def __init__(self, session, trace=None):
super().__init__(session, trace=trace)
self.raw = deepcopy(demo_snapshot(self.catalog).raw)
role = session.role_id or 100 + (session.server_id or 1)
self.raw["master"].update(id=role, roleName="离线角色 " + str(role), level=1, exp=0, timeTi=int(time.time() * 1000))
for monster in self.raw["monsters"]:
monster.update(process=3, mode=2)
self.http.post = self._post
self.closed = False
def _post(self, url, data, **kwargs):
payload = decode(data, self.session.key)
self.calls.append((self.session.account_id, url, payload))
if url.endswith("masterService/masterQueryDetail"):
role = self.session.role_id or 100 + self.session.server_id
self.raw["master"].update(id=role, roleName="离线角色 " + str(role))
if url.endswith("monsterService/monsterLock"):
for monster in self.raw["monsters"]:
if monster["id"] == payload["monsterId"]:
monster["lock"] = payload["lock"]
return SimpleNamespace(status_code=200, content=encode(self.raw | {"resCode": 0}, self.session.key), headers={})
def close(self):
self.closed = True
super().close()
class FakeLogin:
client_factory = FakeClient
def __init__(self, catalog, device, *, trace=None):
self.catalog, self.device, self.trace = catalog, device, trace
def authenticate(self, account, password):
client = FakeClient(Session(token="synthetic-center-token", account_id=account,
account_name=account), trace=self.trace)
response = {"servers": [{"id": identifier, "serverName": "测试区 " + str(identifier),
"gameServerAddress": "https://offline.invalid/game/", "platform": "ANDROID"} for identifier in (1, 2)],
"masterInfos": [{"serverId": 1, "masterName": "离线角色 101"}],
"playerInfo": {"token": "synthetic-center-token"}}
return client, response, {"uid": account, "center_url": "https://offline.invalid/center/",
"channel": "DYD", "device_id": self.device}
class ServiceTests(unittest.TestCase):
def setUp(self):
self.temp = self.enterContext(tempfile.TemporaryDirectory(prefix="ranch-web-runtime-test-"))
self.root = Path(self.temp) / "web"
# Any unmocked requests call is an immediate test failure, never traffic.
self._http_request = HttpSession.request
self.enterContext(patch("requests.sessions.Session.request", side_effect=AssertionError("Live HTTP is forbidden")))
FakeClient.calls = []
self.manager = WebManager(self.root, start_scheduler=False, login_factory=FakeLogin)
self.addCleanup(self.manager.close)
def account(self, demo=True):
identifier = self.manager.create_account("测试页签", demo)["id"]
self.idle(identifier)
self.assertEqual(self.manager.status(identifier)["error"], "")
return identifier
def idle(self, identifier, timeout=10):
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
if not self.manager.status(identifier)["busy"]:
return
time.sleep(.005)
self.fail("Account did not become idle")
def job(self, identifier, job, *, status="succeeded"):
deadline = time.monotonic() + 10
while time.monotonic() < deadline:
result = self.manager.job(identifier, job["id"])
if result["status"] in {"succeeded", "failed", "cancelled"}:
self.assertEqual(result["status"], status, result)
self.idle(identifier)
return result
time.sleep(.005)
self.fail("Job did not complete")
def login(self, identifier, account="synthetic-owner", server=1):
login = self.job(identifier, self.manager.submit(identifier, "login",
{"account": account, "password": "synthetic-password", "remember": True}))
self.job(identifier, self.manager.submit(identifier, "enter_server", {"server_id": server}))
return login
def enable(self, identifier):
config = self.manager.get_config(identifier)
config["config"]["daily_policy"].update(enabled=True, selected=["gift"])
pending = self.manager.set_config(identifier, config["config"], config["revision"])
self.assertTrue(pending["pending"])
self.job(identifier, pending["job"])
def test_real_engine_demo_config_autosave_and_revision_conflict(self):
identifier = self.account()
self.assertIsInstance(self.manager._worker(identifier).engine, Engine)
self.assertEqual(self.manager.status(identifier)["player"]["name"], demo_snapshot(self.manager.catalog).raw["master"]["roleName"])
config = self.manager.get_config(identifier)
config["config"]["policy"]["keep_money"] = 2345
result = self.manager.set_config(identifier, config["config"], config["revision"])
self.assertEqual(result["revision"], 0)
self.job(identifier, result["job"])
self.assertEqual(self.manager.get_config(identifier)["config"]["policy"]["keep_money"], 2345)
self.assertEqual(self.manager._worker(identifier).engine.policy.keep_money, 2345)
with self.assertRaises(RevisionConflict):
self.manager.set_config(identifier, config["config"], 0)
def test_login_select_server_public_metadata_and_restart_restore(self):
identifier = self.account(False)
result = self.login(identifier)
public = json.dumps(result)
for secret in ("synthetic-password", "synthetic-center-token", "gameServerAddress", "center_url", "reqid"):
self.assertNotIn(secret, public)
self.assertEqual(result["result"]["servers"][0]["role_name"], "离线角色 101")
status = self.manager.status(identifier)
self.assertTrue(status["connected"])
self.assertFalse(status["demo"])
self.assertFalse(status["running"])
worker = self.manager._worker(identifier)
identity = worker.active_identity
before = worker.securestore.load(identity).reqid
self.enable(identifier)
self.job(identifier, self.manager.submit(identifier, "start"))
self.manager.close()
count = len(FakeClient.calls)
self.manager = WebManager(self.root, start_scheduler=False, login_factory=FakeLogin)
self.addCleanup(self.manager.close)
self.idle(identifier)
self.assertEqual(len(FakeClient.calls), count, "Restart issued an unsolicited request")
self.assertFalse(self.manager.status(identifier)["running"])
self.assertFalse(self.manager.status(identifier)["connected"])
self.assertTrue(self.manager.get_config(identifier)["config"]["daily_policy"]["enabled"])
self.job(identifier, self.manager.submit(identifier, "restore_session", {"session_id": identity}))
restored = self.manager._worker(identifier).securestore.load(identity)
self.assertGreater(restored.reqid, before)
self.assertFalse(self.manager.status(identifier)["running"])
def test_role_workspaces_do_not_copy_targets_or_other_profiles_overrides(self):
first, other = self.account(False), self.account()
self.login(first)
worker = self.manager._worker(first)
role_one = worker.state_root
config = self.manager.get_config(first)
config["config"]["policy"]["keep_money"] = 9876
config["config"]["overrides"] = {next(iter(worker.catalog.monsters)): {"sell_money": 123}}
self.job(first, self.manager.set_config(first, config["config"])["job"])
self.assertEqual(self.manager._worker(other).catalog.overrides, {})
self.manager.view(first, "incubator")
self.idle(first)
self.assertIsNotNone(self.manager.view(first, "incubator")["data"])
self.login(first, server=2)
self.assertNotEqual(worker.state_root, role_one)
self.assertIsNone(self.manager.view(first, "incubator")["data"], "Previous role view escaped the cache")
self.idle(first)
self.assertNotEqual(self.manager.get_config(first)["config"]["policy"]["keep_money"], 9876)
self.assertEqual(worker.catalog.overrides, {})
saved = next(row["session_id"] for row in worker.securestore.entries() if row["session_id"] != worker.active_identity)
self.job(first, self.manager.submit(first, "restore_session", {"session_id": saved}))
self.assertEqual(worker.state_root, role_one)
self.assertEqual(self.manager.get_config(first)["config"]["policy"]["keep_money"], 9876)
def test_duplicate_account_server_role_connection_is_refused(self):
first, second = self.account(False), self.account(False)
self.login(first)
self.job(second, self.manager.submit(second, "login", {"account": "synthetic-owner", "password": "synthetic-password"}))
result = self.job(second, self.manager.submit(second, "enter_server", {"server_id": 1}), status="failed")
self.assertIn("另一个", result["error"])
self.assertTrue(self.manager.status(first)["connected"])
self.assertFalse(self.manager.status(second)["connected"])
def test_stop_cancels_queued_start_and_consumer_but_not_read_only_jobs(self):
identifier = self.account()
self.enable(identifier)
entered, release = threading.Event(), threading.Event()
self.addCleanup(release.set)
calls = []
def action(worker, operation, payload):
calls.append(operation)
if payload.get("hold"):
entered.set()
release.wait(5)
return {"message": operation}
with patch("ranch_web.actions.execute_action", side_effect=action):
held = self.manager.submit(identifier, "refresh", {"hold": True})
self.assertTrue(entered.wait(2))
start = self.manager.submit(identifier, "start")
consumer = self.manager.submit(identifier, "consume_probe")
reader = self.manager.submit(identifier, "refresh")
stopped = self.manager.submit(identifier, "stop")
self.assertEqual(stopped["status"], "succeeded")
self.assertFalse(self.manager.status(identifier)["running"])
release.set()
self.job(identifier, held)
self.job(identifier, start, status="cancelled")
self.job(identifier, consumer, status="cancelled")
self.job(identifier, reader)
self.assertEqual(calls, ["refresh", "refresh"])
self.assertFalse(self.manager._worker(identifier).engine.auto)
self.assertTrue(self.manager._worker(identifier).engine._progression_cancel.is_set())
def test_policy_queued_before_stop_saves_without_reactivating(self):
identifier = self.account()
self.enable(identifier)
self.job(identifier, self.manager.submit(identifier, "start"))
entered, release = threading.Event(), threading.Event()
self.addCleanup(release.set)
def hold(worker, operation, payload):
entered.set()
release.wait(5)
return {}
with patch("ranch_web.actions.execute_action", side_effect=hold):
held = self.manager.submit(identifier, "refresh")
self.assertTrue(entered.wait(2))
config = self.manager.get_config(identifier)["config"]
config["policy"]["keep_money"] = 4567
pending = self.manager.set_config(identifier, config)
self.manager.submit(identifier, "stop")
release.set()
self.job(identifier, held)
self.job(identifier, pending["job"])
worker = self.manager._worker(identifier)
self.assertEqual(worker.engine.policy.keep_money, 4567)
self.assertFalse(worker.engine.auto)
self.assertTrue(worker.engine._progression_cancel.is_set())
self.assertFalse(worker.running)
def test_slow_account_does_not_block_other_account_status_or_cached_view(self):
first, second = self.account(), self.account()
self.manager.view(first, "incubator")
self.idle(first)
entered, release = threading.Event(), threading.Event()
self.addCleanup(release.set)
def action(worker, operation, payload):
if worker.id == first:
entered.set()
release.wait(5)
return {"message": "read"}
with patch("ranch_web.actions.execute_action", side_effect=action):
held = self.manager.submit(first, "refresh")
self.assertTrue(entered.wait(2))
started = time.monotonic()
self.assertTrue(self.manager.status(first)["busy"])
view = self.manager.view(first, "incubator")
self.assertIsNotNone(view["data"])
self.manager.logs(first)
self.assertLess(time.monotonic() - started, .2)
self.job(second, self.manager.submit(second, "refresh"))
self.assertTrue(self.manager.status(first)["busy"])
release.set()
self.job(first, held)
def test_worker_owned_manual_stop_preserves_confirmed_request(self):
identifier = self.account(False)
self.login(identifier)
worker = self.manager._worker(identifier)
monster = next(row for row in worker.engine.snapshot.raw["monsters"] if not row.get("lock"))
result = self.job(identifier, self.manager.submit(identifier, "lock", {"monster_ids": [monster["id"]]}))
self.assertTrue(worker.engine.snapshot.monsters[monster["id"]]["lock"])
self.assertIn("message", result["result"])
self.assertFalse(worker.running)
def test_enter_job_is_not_terminal_until_persistence_and_summary_are_published(self):
identifier = self.account(False)
self.job(identifier, self.manager.submit(identifier, "login", {"account": "synthetic-owner", "password": "synthetic-password"}))
worker = self.manager._worker(identifier)
entered, release = threading.Event(), threading.Event()
self.addCleanup(release.set)
original = worker._persist_session
def persist():
if worker.engine.client is not None:
entered.set()
release.wait(5)
return original()
with patch.object(worker, "_persist_session", side_effect=persist):
selected = self.manager.submit(identifier, "enter_server", {"server_id": 1})
self.assertTrue(entered.wait(2))
self.assertEqual(self.manager.job(identifier, selected["id"])["status"], "running")
release.set()
self.job(identifier, selected)
self.assertTrue(self.manager.status(identifier)["connected"])
def test_stop_between_manual_requests_prevents_remaining_dispatches(self):
identifier = self.account(False)
self.login(identifier)
worker = self.manager._worker(identifier)
client = worker.engine.client
ids = [row["id"] for row in worker.engine.snapshot.raw["monsters"] if not row.get("lock")][:2]
self.assertEqual(len(ids), 2)
entered, release = threading.Event(), threading.Event()
self.addCleanup(release.set)
original = client.http.post
def post(url, data, **kwargs):
value = original(url, data, **kwargs)
if url.endswith("monsterService/monsterLock"):
entered.set()
release.wait(5)
return value
with patch.object(client.http, "post", side_effect=post):
job = self.manager.submit(identifier, "lock", {"monster_ids": ids})
self.assertTrue(entered.wait(2))
self.manager.submit(identifier, "stop")
release.set()
self.job(identifier, job, status="cancelled")
locks = [call for call in FakeClient.calls if call[1].endswith("monsterService/monsterLock")]
self.assertEqual(len(locks), 1)
self.assertTrue(any(event["kind"] == "response" and event["operation"] == "monsterService/monsterLock"
for event in worker.trace.events), "Already-sent response evidence was discarded")
def test_stop_during_encoding_prevents_the_encoded_write_reaching_http(self):
identifier = self.account(False)
self.login(identifier)
worker = self.manager._worker(identifier)
monster = next(row for row in worker.engine.snapshot.raw["monsters"] if not row.get("lock"))
entered, release = threading.Event(), threading.Event()
self.addCleanup(release.set)
before = len(FakeClient.calls)
high_water = worker.securestore.load(worker.active_identity).reqid
def paused_encode(value, key):
encoded = encode(value, key)
if "monsterId" in value and "lock" in value:
entered.set()
if not release.wait(5):
raise AssertionError("Encoding gate was not released")
return encoded
with patch("ranch_assistant.api.encode", side_effect=paused_encode):
job = self.manager.submit(identifier, "lock", {"monster_ids": [monster["id"]]})
self.assertTrue(entered.wait(2))
stopped = self.manager.submit(identifier, "stop")
self.assertEqual(stopped["status"], "succeeded")
self.assertFalse(release.is_set())
release.set()
self.job(identifier, job, status="cancelled")
writes = sum(call[1].endswith("monsterService/monsterLock") for call in FakeClient.calls[before:])
self.assertEqual(writes, 0, "An encoded cancelled write reached HTTP")
self.assertGreater(worker.securestore.load(worker.active_identity).reqid, high_water)
def test_stop_during_requests_preparation_prevents_adapter_dispatch(self):
identifier = self.account(False)
self.login(identifier)
worker = self.manager._worker(identifier)
client = worker.engine.client
http = client.http
monster = next(row for row in worker.engine.snapshot.raw["monsters"] if not row.get("lock"))
entered, release = threading.Event(), threading.Event()
self.addCleanup(release.set)
original_prepare = http.prepare_request
before = len(FakeClient.calls)
def paused_prepare(request):
prepared = original_prepare(request)
if request.url.endswith("monsterService/monsterLock"):
entered.set()
if not release.wait(5):
raise AssertionError("Prepared-request gate was not released")
return prepared
def offline_send(request, **kwargs):
value = client._post(request.url, request.body)
response = Response()
response.status_code, response._content, response.headers = value.status_code, value.content, value.headers
response.url, response.request = request.url, request
return response
adapter = http.get_adapter("https://offline.invalid/")
# Exercise requests' real post -> request -> prepare -> send pipeline.
# The adapter stays fake; the class-wide live-HTTP prohibition stays on.
with patch.object(http, "post", HttpSession.post.__get__(http, HttpSession)), \
patch.object(http, "request", self._http_request.__get__(http, HttpSession)), \
patch.object(http, "prepare_request", side_effect=paused_prepare), \
patch.object(adapter, "send", side_effect=offline_send):
job = self.manager.submit(identifier, "lock", {"monster_ids": [monster["id"]]})
self.assertTrue(entered.wait(2))
started = time.monotonic()
self.manager.submit(identifier, "stop")
self.assertLess(time.monotonic() - started, .2)
release.set()
self.job(identifier, job, status="cancelled")
writes = sum(call[1].endswith("monsterService/monsterLock") for call in FakeClient.calls[before:])
self.assertEqual(writes, 0, "A prepared cancelled request reached the adapter")
def test_config_change_during_automatic_poll_keeps_execution_enabled(self):
identifier = self.account(False)
self.login(identifier)
self.enable(identifier)
self.job(identifier, self.manager.submit(identifier, "start"))
worker = self.manager._worker(identifier)
client = worker.engine.client
entered, release = threading.Event(), threading.Event()
self.addCleanup(release.set)
original = client.http.post
def paused_response(url, data, **kwargs):
response = original(url, data, **kwargs)
if url.endswith("masterService/masterQueryDetail"):
entered.set()
if not release.wait(5):
raise AssertionError("Snapshot response gate was not released")
return response
worker.engine.last_heartbeat = time.monotonic()
worker.schedule.next_poll = 0
with patch.object(client.http, "post", side_effect=paused_response):
worker.request_tick()
self.assertTrue(entered.wait(2))
self.assertTrue(worker.running)
config = self.manager.get_config(identifier)["config"]
config["policy"]["keep_money"] += 100
pending = self.manager.set_config(identifier, config)
self.assertTrue(worker.running)
release.set()
self.job(identifier, pending["job"])
self.assertTrue(self.manager.status(identifier)["running"], "Config cancellation disabled the execution switch")
self.assertTrue(worker.engine.auto)
self.assertEqual(worker.engine.policy.keep_money, config["policy"]["keep_money"])
def test_engine_pause_in_current_generation_still_disables_execution(self):
identifier = self.account()
self.enable(identifier)
self.job(identifier, self.manager.submit(identifier, "start"))
worker = self.manager._worker(identifier)
worker.schedule.next_poll = 0
def stopped_poll(**kwargs):
worker.engine.auto = False
return worker.engine.snapshot, [], "Engine paused after validation"
with patch.object(worker.engine, "poll", side_effect=stopped_poll):
worker.request_tick()
self.idle(identifier)
self.assertFalse(self.manager.status(identifier)["running"])
self.assertFalse(worker.engine.auto)
def test_view_task_indices_stay_bounded_after_many_filters_and_failure(self):
identifier = self.account()
worker = self.manager._worker(identifier)
for index in range(120):
view = self.manager.view(identifier, "incubator", {"search": str(index)})
self.job(identifier, {"id": view["job_id"]})
self.assertLessEqual(len(worker._views), 32)
self.assertLessEqual(len(worker._view_jobs), 32, "Completed view task indices grow with every filter")
self.assertFalse(self.manager.view(identifier, "incubator", {"search": "119"})["loading"])
with patch("ranch_web.views.build_view", side_effect=ValueError("synthetic view failure")):
view = self.manager.view(identifier, "incubator", {"search": "failed"})
self.job(identifier, {"id": view["job_id"]}, status="failed")
self.assertNotIn(("incubator", '{"search": "failed"}'), worker._view_jobs)
retry = self.manager.view(identifier, "incubator", {"search": "failed"})
self.job(identifier, {"id": retry["job_id"]})
self.assertFalse(self.manager.view(identifier, "incubator", {"search": "failed"})["loading"])
def test_failed_counter_save_blocks_http_and_a_repaired_store_can_retry(self):
identifier = self.account(False)
self.login(identifier)
worker = self.manager._worker(identifier)
before = len(FakeClient.calls)
with patch.object(worker.securestore, "save", side_effect=OSError("synthetic persistence failure")):
result = self.job(identifier, self.manager.submit(identifier, "refresh"), status="failed")
self.assertTrue(result["error"])
self.assertEqual(len(FakeClient.calls), before)
self.job(identifier, self.manager.submit(identifier, "refresh"))
self.assertGreater(len(FakeClient.calls), before)
def test_account_registry_failure_closes_worker_without_holding_manager_lock(self):
started = time.monotonic()
with patch.object(self.manager.store, "save_accounts", side_effect=OSError("registry unavailable")):
with self.assertRaisesRegex(OSError, "registry unavailable"):
self.manager.create_account()
self.assertLess(time.monotonic() - started, 2)
self.assertEqual(self.manager.list_accounts(), [])
def test_public_structural_keys_survive_but_real_secret_key_is_removed(self):
worker = self.manager._worker(self.account())
value = {name: [{"key": "binding", "label": "选项", "details": {"key": "secret-nested"}}]
for name in ("columns", "filters", "pages", "tabs", "form")}
value.update(key="secret-protocol", token="secret-token", reqid=17, raw={"hidden": True})
result = worker.public_json(value)
for name in ("columns", "filters", "pages", "tabs", "form"):
self.assertEqual(result[name][0]["key"], "binding")
self.assertNotIn("key", result[name][0]["details"])
self.assertNotIn("key", result)
self.assertNotIn("token", result)
self.assertNotIn("reqid", result)
self.assertNotIn("raw", result)
with self.assertRaises(ValueError):
worker.public_json(Session())
def test_debug_summaries_are_small_and_details_keep_redacted_body_headers(self):
identifier = self.account()
worker = self.manager._worker(identifier)
worker.trace.emit("response", "离线请求", headers={"Content-Type": "application/json", "Set-Cookie": "private-cookie"},
body={"monsters": [{"id": index, "name": "测试"} for index in range(80)],
"token": "private-token", "password": "private-password", "key": "private-key", "reqid": 187,
"file_path": str(worker.profile_root / "private.json")})
logs = self.manager.logs(identifier, debug=True)
entry = next(row for row in logs["entries"] if row["details_available"])
self.assertNotIn("body", entry)
self.assertLess(len(json.dumps(entry)), 1000)
details = self.manager.log_detail(identifier, entry["id"])["details"]
self.assertEqual(len(details["body"]["monsters"]), 80)
self.assertEqual(details["headers"]["Content-Type"], "application/json")
for field in ("token", "password", "key", "reqid"):
self.assertEqual(details["body"][field], "<隐藏>")
serialized = json.dumps(details)
for secret in ("private-cookie", "private-token", "private-password", "private-key", str(worker.profile_root)):
self.assertNotIn(secret, serialized)
for index in range(70):
worker.trace.emit("info", "entry", value=index)
with self.assertRaises(KeyError):
self.manager.debug_entry(identifier, entry["id"])
def test_shutdown_cancels_simulation_before_waiting_and_keeps_pending_evidence(self):
first, second = self.account(), self.account()
entered = threading.Event()
worker = self.manager._worker(first)
pending = worker.state_root / "uncertain-evidence.json"
pending.write_text('{"status":"unknown"}', encoding="utf-8")
def simulate(runtime, operation, payload):
entered.set()
runtime.engine._progression_cancel.wait(5)
runtime.check_intent()
return {}
with patch("ranch_web.actions.execute_action", side_effect=simulate):
job = self.manager.submit(first, "simulate_probe")
self.assertTrue(entered.wait(2))
started = time.monotonic()
self.manager.close()
self.assertLess(time.monotonic() - started, 1)
self.assertTrue(pending.exists())
self.assertEqual(self.manager.job(first, job["id"])["status"], "cancelled")
self.assertTrue(self.manager._worker(second)._closed.is_set())
def test_no_pyside_or_gui_import_is_required(self):
code = '''
import importlib.abc, sys, tempfile
class NoGui(importlib.abc.MetaPathFinder):
def find_spec(self, fullname, path=None, target=None):
if fullname.startswith("PySide6") or fullname.endswith("_gui") or fullname == "ranch_assistant.gui":
raise ImportError("GUI forbidden")
sys.meta_path.insert(0, NoGui())
from ranch_web.service import WebManager
with tempfile.TemporaryDirectory() as root:
manager = WebManager(root, start_scheduler=False)
manager.create_account(demo=True)
manager.close()
print("headless-ok")
'''
result = subprocess.run([sys.executable, "-c", code], cwd=Path(__file__).resolve().parents[2],
capture_output=True, text=True, timeout=15)
self.assertEqual(result.returncode, 0, result.stderr)
self.assertIn("headless-ok", result.stdout)
if __name__ == "__main__":
unittest.main()
+120
View File
@@ -0,0 +1,120 @@
"""Web persistence tests use disposable roots and synthetic sessions only."""
from dataclasses import replace
import json
import os
from pathlib import Path
import stat
import tempfile
import unittest
from ranch_assistant.api import Session
from ranch_web.store import WebStore, session_identity
class StoreTests(unittest.TestCase):
def setUp(self):
self.temp = self.enterContext(tempfile.TemporaryDirectory(prefix="ranch-web-store-test-"))
self.root = Path(self.temp) / "web"
self.store = WebStore(self.root)
self.addCleanup(self.store.close)
self.secure = self.store.secure("a" * 32)
def session(self):
return Session("https://offline.invalid/game/", "synthetic-private-token", account_id="fake-owner",
server_id=1, role_id=101, reqid=5, reqsid=9)
def test_fernet_credentials_and_session_survive_restart_without_plaintext(self):
self.secure.save_credentials("synthetic-account", "synthetic-password", True)
session = self.session()
identifier = self.secure.save(session, "测试角色")
self.secure.set_active(identifier)
self.store.close()
reopened = WebStore(self.root)
self.addCleanup(reopened.close)
secure = reopened.secure("a" * 32)
self.assertEqual(secure.load_credentials(), (True, "synthetic-account", "synthetic-password"))
self.assertEqual(secure.load(identifier), session)
self.assertEqual(secure.active(), identifier)
for path in self.root.rglob("*.fernet"):
raw = path.read_text(encoding="utf-8")
for secret in ("synthetic-account", "synthetic-password", session.token, session.key):
self.assertNotIn(secret, raw)
if os.name != "nt":
self.assertEqual(stat.S_IMODE((self.root / "web.key").stat().st_mode), 0o600)
def test_high_water_marks_never_regress(self):
session = self.session()
identifier = self.secure.save(session, "first")
stale = replace(session, reqid=0, reqsid=1)
self.secure.save(stale, "stale")
loaded = self.secure.load(identifier)
self.assertEqual((loaded.reqid, loaded.reqsid), (5, 9))
self.assertEqual((stale.reqid, stale.reqsid), (5, 9))
def test_sessions_are_separated_by_account_region_role_and_profile(self):
first = self.session()
sessions = [first, replace(first, account_id="other"), replace(first, server_id=2), replace(first, role_id=102)]
ids = [self.secure.save(value, "角色") for value in sessions]
self.assertEqual(len(set(ids)), 4)
other = self.store.secure("b" * 32)
self.assertEqual(other.entries(), [])
self.assertEqual(len(self.secure.entries()), 4)
self.assertEqual(set(self.secure.entries()[0]), {"session_id", "label", "saved_at"})
self.assertEqual(session_identity(first), ids[0])
def test_missing_or_different_key_is_reported_without_replacing_ciphertext(self):
self.secure.save(self.session(), "角色")
self.store.close()
original = next(self.secure.folder.glob("*.fernet")).read_bytes()
(self.root / "web.key").unlink()
with self.assertRaisesRegex(ValueError, "密钥"):
WebStore(self.root)
self.assertEqual(next(self.secure.folder.glob("*.fernet")).read_bytes(), original)
def test_tamper_and_path_traversal_are_rejected(self):
identifier = self.secure.save(self.session(), "角色")
path = self.secure.folder / (identifier + ".fernet")
record = json.loads(path.read_text(encoding="utf-8"))
record["protected"] = record["protected"][:-8] + "invalid!"
path.write_text(json.dumps(record), encoding="utf-8")
with self.assertRaisesRegex(ValueError, "加密"):
self.secure.load(identifier)
for bad in ("../other", "A" * 32, "", None):
with self.assertRaises(ValueError):
self.store.remove_profile(bad)
with self.assertRaises(ValueError):
self.secure.load("../credentials")
def test_only_one_instance_owns_the_root(self):
with self.assertRaisesRegex(RuntimeError, "另一个"):
WebStore(self.root)
def test_removal_preserves_siblings_and_shared_files(self):
sibling = self.store.secure("b" * 32)
sibling.save_credentials("b", "password-b")
shared = self.root / "shared-catalog.json"
shared.write_text("shared", encoding="utf-8")
self.secure.save(self.session(), "A")
self.store.remove_profile("a" * 32)
self.assertFalse(self.secure.profile_root.exists())
self.assertEqual(sibling.load_credentials(), (True, "b", "password-b"))
self.assertEqual(shared.read_text(encoding="utf-8"), "shared")
def test_link_inside_profile_blocks_entire_removal(self):
sibling = self.store.secure("b" * 32).profile_root
link = self.secure.profile_root / "sibling-link"
try:
link.symlink_to(sibling, target_is_directory=True)
except (OSError, NotImplementedError):
self.skipTest("Creating symlinks requires Windows privileges")
self.addCleanup(lambda: link.unlink(missing_ok=True))
ordinary = self.secure.profile_root / "keep.txt"
ordinary.write_text("keep", encoding="utf-8")
with self.assertRaisesRegex(ValueError, "链接"):
self.store.remove_profile("a" * 32)
self.assertTrue(ordinary.exists())
self.assertTrue(sibling.exists())
if __name__ == "__main__":
unittest.main()
+216
View File
@@ -0,0 +1,216 @@
"""Offline update protocol checks; no game API, Docker, or live GitHub."""
from datetime import timedelta
import json
import os
from pathlib import Path
import tempfile
import unittest
from unittest.mock import patch
from ranch_web import updates
def release(tag, **extra):
return {"tag_name": tag, "draft": False, "prerelease": False, **extra}
class UpdateTests(unittest.TestCase):
def setUp(self):
self.temporary = tempfile.TemporaryDirectory(prefix="ranch-updates-")
self.addCleanup(self.temporary.cleanup)
self.folder = Path(self.temporary.name)
self.root = self.folder / "data"
self.control = self.folder / "host-control"
self.environment = patch.dict(os.environ, {"RANCH_WEB_UPDATER_DIR": ""})
self.environment.start()
self.addCleanup(self.environment.stop)
self.github = patch.object(updates, "github_releases", return_value=[])
self.releases = self.github.start()
self.addCleanup(self.github.stop)
self.service = updates.UpdateService(self.root, "2.0.0.dev1")
def enable(self, **overrides):
now = updates.utc_now()
value = {"protocol": 1, "executor_id": "a" * 32, "enabled": True, "auto_apply": False,
"heartbeat_at": updates.timestamp(now), "expires_at": updates.timestamp(now + timedelta(minutes=15)),
**overrides}
updates.atomic_json(self.control / "capability.json", value)
os.environ["RANCH_WEB_UPDATER_DIR"] = str(self.control)
def test_status_does_not_create_data_or_use_network(self):
result = self.service.status()
self.assertEqual(result["status"], "unchecked")
self.assertFalse(self.root.exists())
self.releases.assert_not_called()
def test_release_gate_accepts_official_repository_case_and_exact_source_version(self):
for repository in ("AttilaNet/myrzx_bot", "attilanet/myrzx_bot", "ATTILANET/MYRZX_BOT"):
with self.subTest(repository=repository):
self.assertEqual(updates.validate_image_release(repository, "v2.0.0", "2.0.0"), "v2.0.0")
def test_release_gate_rejects_forks_dev_source_and_unstable_tags(self):
variants = [("someone/myrzx_bot", "v2.0.0", "2.0.0"),
("AttilaNet/myrzx_bot", "v2.0.0", "2.0.0.dev1"),
("AttilaNet/myrzx_bot", "v2.0.1", "2.0.0"),
("AttilaNet/myrzx_bot", "v3.0.0", "3.0.0"),
("AttilaNet/myrzx_bot", "v2.0.0-rc1", "2.0.0-rc1")]
for values in variants:
with self.subTest(values=values), self.assertRaises(ValueError):
updates.validate_image_release(*values)
def test_only_desktop_or_no_releases_means_no_web_update(self):
self.releases.return_value = [release("v1.2.0"), release("v3.0.0")]
result = self.service.check()
self.assertEqual(result["status"], "no_release")
self.assertIsNone(result["latest_version"])
self.assertFalse(result["available"])
self.assertIn("桌面", result["message"])
def test_dev_can_upgrade_to_same_number_stable(self):
self.releases.return_value = [release("v2.0.0")]
self.assertTrue(self.service.check()["available"])
def test_same_stable_and_downgrade_are_not_updates(self):
self.releases.return_value = [release("v2.0.0")]
for current in ("2.0.0", "2.1.0", "v2.0.0"):
with self.subTest(current=current):
state = updates.UpdateService(self.root, current).check()
self.assertEqual(state["status"], "up_to_date")
self.assertFalse(state["available"])
def test_numeric_order_and_untrusted_release_url(self):
self.releases.return_value = [release("v2.9.9"), release("v2.10.0", html_url="https://evil.invalid")]
result = self.service.check()
self.assertEqual(result["latest_version"], "v2.10.0")
self.assertEqual(result["release_url"], "https://github.com/attilanet/myrzx_bot/releases/tag/v2.10.0")
def test_draft_prerelease_and_noncanonical_tags_skipped(self):
tags = ["v2.01.0", "v2.1.00", "2.1.0", "v2.1.0-rc1", "v2.1.0+build", "v2.1.0.dev1",
"v2.1.0\n", "v2.1.0;id", "v2.1.0", "v1.99.99", "v3.0.0"]
self.releases.return_value = [release(tag) for tag in tags] + [release("v2.1.0", draft=True),
release("v2.2.0", prerelease=True)]
self.assertEqual(self.service.check()["status"], "no_release")
def test_network_failure_has_no_exception_or_secret_text(self):
self.releases.side_effect = RuntimeError("token=secret C:/private/account")
state = self.service.check()
encoded = json.dumps(state)
self.assertEqual(state["status"], "check_failed")
self.assertFalse(state["available"])
self.assertNotIn("secret", encoded)
self.assertNotIn("private", encoded)
def test_unconfigured_windows_can_only_check(self):
self.releases.return_value = [release("v2.0.0")]
self.service.check()
state = self.service.request_update()
self.assertEqual(state["status"], "unavailable")
self.assertFalse(state["can_apply"])
self.assertFalse((self.root / "update-request.json").exists())
def test_data_cannot_self_enable_host_executor(self):
updates.atomic_json(self.root / "capability.json", {"protocol": 1, "enabled": True})
self.assertFalse(self.service.status()["executor"]["enabled"])
def test_disabled_expired_future_and_malformed_proof_refuse_apply(self):
now = updates.utc_now()
variants = [dict(enabled=False), dict(expires_at=updates.timestamp(now - timedelta(seconds=1))),
dict(heartbeat_at=updates.timestamp(now + timedelta(hours=1))),
dict(expires_at=updates.timestamp(now + timedelta(hours=1))), dict(executor_id="bad"),
dict(protocol=2)]
for variant in variants:
with self.subTest(variant=variant):
self.enable(**variant)
self.assertEqual(self.service.request_update()["status"], "unavailable")
self.assertFalse((self.root / "update-request.json").exists())
def test_apply_creates_only_strict_pending_request(self):
self.enable()
self.releases.return_value = [release("v2.0.0")]
state = self.service.request_update()
self.assertEqual(state["status"], "pending")
self.assertFalse(state["can_apply"])
value = updates.read_json(self.root / "update-request.json")
self.assertEqual(set(value), {"protocol", "request_id", "executor_id", "version", "requested_at"})
self.assertEqual(value["version"], "v2.0.0")
self.assertEqual(value["executor_id"], "a" * 32)
self.assertTrue(updates.valid_id(value["request_id"]))
self.assertIsNone(state["host_status"])
def test_duplicate_request_is_idempotent(self):
self.enable()
self.releases.return_value = [release("v2.0.0")]
first = self.service.request_update()
second = self.service.request_update()
self.assertEqual(first["request"], second["request"])
self.assertEqual(self.releases.call_count, 1)
def test_tampered_cached_release_is_not_enough_for_apply(self):
self.enable()
updates.atomic_json(self.root / "update-check.json", {"status": "available", "latest_version": "v2.9.9"})
with self.assertRaises(ValueError):
self.service.request_update("v2.9.9")
self.assertFalse((self.root / "update-request.json").exists())
def test_apply_rejects_unsafe_tag_before_network(self):
self.enable()
for tag in ("v1.2.0", "v3.0.0", "v2.1.0;rm", "v2.1.0\n", "latest", "v2.1.0-rc1"):
with self.subTest(tag=tag), self.assertRaises(ValueError):
self.service.request_update(tag)
self.releases.assert_not_called()
def test_request_rejects_equal_or_older_official_version(self):
self.enable()
self.releases.return_value = [release("v2.0.0")]
for current in ("2.0.0", "2.1.0"):
with self.subTest(current=current), self.assertRaises(ValueError):
updates.UpdateService(self.root, current).request_update("v2.0.0")
def test_public_host_state_uses_allowlist_and_fixed_error(self):
self.enable()
self.releases.return_value = [release("v2.0.0")]
request = self.service.request_update()["request"]
updates.atomic_json(self.root / "updater-status.json", {
"protocol": 1, "request_id": request["request_id"], "version": "v2.0.0",
"status": "rolled_back", "updated_at": updates.timestamp(),
"error": "private token", "path": "C:/account", "password": "do-not-send",
})
state = self.service.status()
self.assertEqual(state["status"], "rolled_back")
self.assertEqual(state["request"]["status"], "rolled_back")
encoded = json.dumps(state)
for value in ("private token", "C:/account", "do-not-send", "executor_id"):
self.assertNotIn(value, encoded)
def test_corrupt_large_or_wrong_type_control_files_are_ignored(self):
self.root.mkdir()
for content in ("not json", "[]", '"wrong type"', "x" * 65537):
with self.subTest(content=content[:20]):
(self.root / "update-check.json").write_text(content, encoding="utf-8")
(self.root / "update-request.json").write_text(content, encoding="utf-8")
(self.root / "updater-status.json").write_text(content, encoding="utf-8")
self.assertEqual(self.service.status()["status"], "unchecked")
def test_official_fetch_uses_fixed_url_bounded_body_no_redirects(self):
class Reply:
def __enter__(self):
return self
def __exit__(self, *args):
pass
def read(self, size):
self_size.append(size)
return b'[{"tag_name":"v1.2.0","draft":false,"prerelease":false}]'
self_size = []
self.github.stop()
with patch.object(updates, "build_opener") as build:
build.return_value.open.return_value = Reply()
result = updates.github_releases()
self.assertEqual(result[0]["tag_name"], "v1.2.0")
request = build.return_value.open.call_args.args[0]
self.assertEqual(request.full_url, updates.RELEASES_API + "?per_page=100&page=1")
self.assertIsInstance(build.call_args.args[0], updates._NoRedirect)
self.assertEqual(self_size, [2 * 1024 * 1024 + 1])
if __name__ == "__main__":
unittest.main()
+820
View File
@@ -0,0 +1,820 @@
"""Independent HTTP -> WebManager -> existing Engine offline integration checks.
Run: python -m unittest ranch_web.tests.test_web_integration -v
Only the game Client/login boundary and release source are fakes. Each test owns
a new temporary root, disables the scheduler, and blocks external socket I/O.
Fixtures stay in this file to avoid other agents' test/fixture ownership.
"""
from __future__ import annotations
import base64
from contextlib import ExitStack
from copy import deepcopy
import hashlib
import ipaddress
import json
import os
from pathlib import Path
import socket
import subprocess
import sys
import tempfile
import textwrap
import threading
import time
import unittest
from unittest.mock import patch
PAGES = "login incubator bag ranch daily hatching mainline battles gifts commissions exploration maps statistics plans yields".split()
TERMINAL = {"succeeded", "failed", "cancelled"}
TOKEN = "web-integration-synthetic-token-82719"
KEY = "web-integration-synthetic-key-49281"
PASSWORD = "web-integration-synthetic-password-18374"
REQID = 98271948
REQSID = 91283741
ROOT = Path(__file__).resolve().parents[2]
class NoExternalSockets:
"""Allow Windows asyncio's loopback socketpair, reject external addresses."""
def __init__(self):
self.stack = ExitStack()
self.attempts = []
def check(self, address):
host = address[0] if isinstance(address, tuple) else address
if host == "localhost":
return
try:
value = ipaddress.ip_address(host)
if value.is_loopback or (getattr(value, "ipv4_mapped", None) and value.ipv4_mapped.is_loopback):
return
except (ValueError, TypeError):
pass
self.attempts.append(str(host))
raise AssertionError("External socket blocked by Web integration fixture")
def __enter__(self):
for name in ("connect", "connect_ex", "sendto"):
original = getattr(socket.socket, name)
def guarded(sock, *args, _original=original, _name=name, **kwargs):
address = args[-1] if _name == "sendto" else args[0]
self.check(address)
return _original(sock, *args, **kwargs)
self.stack.enter_context(patch.object(socket.socket, name, guarded))
original_dns = socket.getaddrinfo
def dns(host, *args, **kwargs):
self.check(host)
return original_dns(host, *args, **kwargs)
self.stack.enter_context(patch.object(socket, "getaddrinfo", dns))
return self
def __exit__(self, *args):
return self.stack.__exit__(*args)
class SnapshotGate:
def __init__(self):
self.entered = threading.Event()
self.release = threading.Event()
def wait(self):
self.entered.set()
if not self.release.wait(8):
raise AssertionError("Integration snapshot gate was not released")
def seeded_snapshot(catalog, role_id=1):
from ranch_assistant.engine import demo_snapshot
from ranch_assistant.resource_stages import item_requirements, with_resource_data
snapshot = demo_snapshot(catalog)
snapshot.raw["master"]["id"] = role_id
snapshot.raw["master"]["roleName"] = "Integration offline role"
snapshot.raw["teams"][0]["teamName"] = "teamA"
for index, monster in enumerate(snapshot.raw["monsters"][:4]):
monster.update(process=3, mode=2, roomId=1, level=20 - index * 4)
for slot in snapshot.raw["stacks"]:
slot["monsterId"] = 0
snapshot.raw["history"].update(
unlockStage={"0101": [1, 2, 3], "0109": [1, 2, 3]},
passStage={"0101": {"1": True, "2": True, "3": True}, "0109": {"1": True}},
passTask={"1001008": True}, unlockTask={"1001004": True}, openHardMode=True,
)
snapshot.raw["currentTasks"] = [{"id": 711, "typeId": "1001004", "curStep": 1, "stepValue": None}]
snapshot.raw["exploreTeams"] = [{"id": 1, "status": 0, "area": "", "monsters": ""}]
for code in range(1, 6):
item_id = next(key for key in catalog.data["item_info"] if catalog.item_type(key) == code)
snapshot.raw["items"].extend({"id": 11000 + code * 10 + index, "typeId": item_id, "num": count}
for index, count in enumerate((3, 4)))
required_items = {}
for stage in with_resource_data(catalog).data["stage_info"].values():
for item_id, count in item_requirements((stage.get("cost") or {}).get("items") or []).items():
required_items[item_id] = max(required_items.get(item_id, 0), count * 3)
snapshot.raw["items"].extend({"id": 12000 + index, "typeId": item_id, "num": count}
for index, (item_id, count) in enumerate(sorted(required_items.items())))
return snapshot
def real_engine_factory(catalog, client=None, budget_path=None):
from ranch_assistant.engine import Engine
engine = Engine(catalog, client, budget_path)
if client is None:
engine.snapshot = seeded_snapshot(catalog)
role_id = client.session.role_id if client else 1
# Persist through the real SQLite statistics service; no DTOs are injected.
statistics = engine.sweeper.statistics
for source, operation, reward, spent in (
("sweep", "integration-sweep-hit", {"items": [{"typeId": 30005, "num": 2}]}, 10),
("sweep", "integration-sweep-miss", {"items": []}, 10),
("event", "integration-event-hit", {"items": [{"typeId": 30005, "num": 3}]}, 5),
):
statistics.record(role_id, "0101", "3", source, operation, 1, reward, spent=spent)
return engine
class OfflineClient:
def __init__(self, catalog, account="fixture", **kwargs):
from ranch_assistant.api import Session
role_id = 100 + int(hashlib.sha256(account.encode()).hexdigest()[:6], 16)
self.catalog = catalog
self.session = Session(server_url="https://game.invalid/", token=TOKEN, key=KEY,
reqid=REQID, reqsid=REQSID, account_id=account,
server_id=7, role_id=role_id, account_name=account)
self.raw = seeded_snapshot(catalog, role_id).raw
self.trace = kwargs.get("trace")
self.on_session_change = kwargs.get("on_session_change")
self.gate = None
self.fail_snapshot = False
self.reads = 0
self.writes = []
self.closed = False
def enter_server(self, *args, **kwargs):
return {"resCode": 0}
def snapshot(self):
from ranch_assistant.model import Snapshot
self.reads += 1
if self.gate:
self.gate.wait()
if self.fail_snapshot:
raise ValueError("离线读取失败 " + PASSWORD + " token=" + TOKEN + " key=" + KEY)
if self.trace:
self.trace.emit("response", "masterService/masterQueryDetail", http_status=200,
body={"safe_marker": "integration-readable-detail", "token": TOKEN,
"nested": {"password": PASSWORD, "key": KEY, "reqid": REQID}},
message="离线响应 password=" + PASSWORD)
return Snapshot(deepcopy(self.raw))
def call(self, path, payload=None, **kwargs):
self.writes.append((path, deepcopy(payload)))
raise AssertionError("Unexpected game write in integration fixture: " + path)
def close(self):
self.closed = True
class OfflineLoginFactory:
def __init__(self):
self.clients = []
def __call__(self, catalog, device, trace=None):
owner = self
class Flow:
def authenticate(self, account, password):
client = OfflineClient(catalog, account, trace=trace)
owner.clients.append(client)
return client, {"token": TOKEN, "key": KEY,
"servers": [{"id": 7, "serverName": "Offline server", "gameServerAddress": "https://game.invalid/"}],
"masterInfos": [{"serverId": 7, "masterName": "Offline role"}]}, {
"center_url": "https://center.invalid/", "uid": account,
"channel": "DYD", "device_id": "integration-device"}
return Flow()
class WebIntegrationTests(unittest.TestCase):
def setUp(self):
from fastapi.testclient import TestClient
from ranch_web.app import create_app
from ranch_web.config import WebConfig
from ranch_web.service import WebManager
from ranch_web.updates import UpdateService
self.stack = ExitStack()
self.addCleanup(self.stack.close)
self.network = self.stack.enter_context(NoExternalSockets())
self.folder = Path(self.stack.enter_context(tempfile.TemporaryDirectory(prefix="web-integration-")))
self.root = self.folder / "new-web-root"
self.stack.enter_context(patch.dict(os.environ, {"RANCH_WEB_UPDATER_DIR": ""}))
self.source = self.stack.enter_context(patch("ranch_web.updates.github_releases", return_value=[]))
self.login = OfflineLoginFactory()
self.manager = WebManager(self.root, start_scheduler=False,
engine_factory=real_engine_factory, login_factory=self.login)
self.stack.callback(lambda: self.manager.close())
self.updates = UpdateService(self.root, "2.0.0.dev1")
self.app = create_app(manager=self.manager, updates=self.updates,
config=WebConfig(data_dir=self.root))
self.http = self.stack.enter_context(TestClient(self.app, base_url="http://127.0.0.1:8765",
client=("127.0.0.1", 50000)))
self.account = self.create_account()
def tearDown(self):
self.assertEqual(self.network.attempts, [], "An external socket was attempted")
def response(self, response, status=200):
self.assertEqual(response.status_code, status, response.text[:3000])
return response.json()
def create_account(self, demo=True, label="integration"):
value = self.response(self.http.post("/api/accounts", json={"label": label, "demo": demo}), 201)
self.wait_idle(value["id"])
return value["id"]
def path(self, suffix, account=None):
return "/api/accounts/" + (account or self.account) + "/" + suffix
def wait_idle(self, account=None):
deadline = time.monotonic() + 8
while time.monotonic() < deadline:
status = self.manager.status(account or self.account)
if not status["busy"]:
self.assertFalse(status["error"], status)
return status
time.sleep(.005)
self.fail("Account worker did not become idle")
def job(self, value, account=None, expected="succeeded"):
deadline = time.monotonic() + 8
while time.monotonic() < deadline:
current = self.response(self.http.get(self.path("jobs/" + value["id"], account)))
self.assertIn(current["status"], TERMINAL | {"queued", "running"})
if current["status"] in TERMINAL:
self.assertEqual(current["status"], expected, current)
return current
time.sleep(.005)
self.fail("Job did not finish: " + str(value))
def action(self, operation, payload=None, account=None, expected="succeeded"):
value = self.response(self.http.post(self.path("actions/" + operation, account), json=payload or {}), 202)
return self.job(value, account, expected)
def config(self, account=None):
return self.response(self.http.get(self.path("config", account)))
def save(self, value, account=None):
current = self.config(account)
response = self.http.put(self.path("config", account), json={"config": value, "revision": current["revision"]})
self.assertIn(response.status_code, (200, 202), response.text)
pending = response.json()
if pending.get("pending"):
self.job(pending["job"], account)
applied = self.config(account)
self.assertGreater(applied["revision"], current["revision"])
return applied
def view(self, page, query=None, account=None, simple=False):
params = query if simple else {"query": json.dumps(query)} if query is not None else None
value = self.response(self.http.get(self.path("views/" + page, account), params=params))
if value["loading"]:
self.assertIsInstance(value["job_id"], str)
self.job({"id": value["job_id"]}, account)
value = self.response(self.http.get(self.path("views/" + page, account), params=params))
self.assertFalse(value["loading"], value)
self.assertIsInstance(value["revision"], int)
self.assertIsInstance(value["data"], dict)
return value["data"]
def hatch_config(self, account=None, enabled=True, priority=13):
row = self.view("bag", account=account)["rows"][0]
config = deepcopy(self.config(account)["config"])
config["policy"].update(enabled=True, fill=True, buy=False, collect=False, dispatch=False, feed=False,
manual_eggs=True, egg_rules={row["id"]: row["rule_defaults"] | {
"enabled": enabled, "priority": priority, "action": "keep", "keep_count": 2}})
return config, row
def logged_account(self):
account = self.create_account(False, "fake login")
result = self.action("login", {"account": "fixture-account", "password": PASSWORD, "remember": True}, account)
self.assertEqual(result["result"]["servers"][0]["id"], 7)
self.assertTrue(result["result"]["has_saved_password"])
self.action("enter_server", {"server_id": 7}, account)
self.assertTrue(self.manager.status(account)["connected"])
return account, self.login.clients[-1]
def assert_dto(self, page):
from ranch_assistant.engine import Engine
self.assertIs(type(self.manager._worker(self.account).engine), Engine)
dto = self.view(page)
self.assertEqual(dto["page"], page)
self.assertTrue(dto["title"])
for field in ("rows", "columns", "filters", "form"):
self.assertIsInstance(dto[field], list, (page, field))
if page != "login":
self.assertTrue(dto["columns"], page)
for column in dto["columns"]:
self.assertTrue(column["key"], (page, column))
self.assertTrue(column["label"], (page, column))
if "edit" in column:
self.assertIsInstance(column["edit"]["path"], list)
for row in dto["rows"]:
self.assertIn("id", row, (page, row))
for field in dto["form"]:
self.assertTrue({"path", "type", "label", "value"} <= field.keys(), (page, field))
def test_default_queries_schema_and_all_six_bag_categories(self):
schema = self.response(self.http.get("/api/schema"))
self.assertEqual([p["key"] for p in schema["pages"]], PAGES)
self.assertTrue(schema["settings"])
defaults = {"bag": {"category": "eggs"}, "ranch": {"grouped": False},
"mainline": {"category": "mainline", "state": "current"},
"maps": {"category": "all", "only_unlocked": True},
"statistics": {"source": "all", "metric": "rate"}}
for page, filters in defaults.items():
with self.subTest(page=page):
implicit, explicit = self.view(page), self.view(page, filters)
self.assertEqual([r["id"] for r in implicit["rows"]], [r["id"] for r in explicit["rows"]])
values = {f["key"]: f["value"] for f in implicit["filters"]}
for key, value in filters.items():
self.assertEqual(values[key], value)
maps = self.view("maps")
self.assertTrue(maps["groups"])
self.assertTrue(all(group["collapsed"] for group in maps["groups"]))
for category in ("eggs", "usable", "consumables", "materials", "other", "equipment"):
dto = self.view("bag", {"category": category}, simple=True)
self.assertEqual(dto["filters"][0]["value"], category)
self.assertTrue(dto["rows"], category)
if category != "eggs":
self.assertTrue(any(len(row["inventory_ids"]) >= 2 and row["count"] >= 7 for row in dto["rows"]), category)
mixed = self.http.get(self.path("views/bag"), params={"query": "{}", "category": "eggs"})
self.response(mixed, 400)
def test_seeded_maps_tasks_and_exploration_have_business_data(self):
maps = self.view("maps")
stage = next(row for row in maps["rows"] if row["id"] == "0101")
self.assertTrue(stage["unlocked"])
self.assertEqual(len(stage["edits"]["level"]["options"]), 3)
self.assertTrue(stage["costs"])
resource = self.view("maps", {"category": "resource", "only_unlocked": False})
self.assertTrue(resource["rows"])
self.assertTrue(all(row["category"] in ("mine", "ticket") for row in resource["rows"]))
self.assertTrue(any(any(cost["kind"] == "item" for cost in row["costs"]) for row in resource["rows"]))
self.assertTrue(any(any(cost["kind"] == "item" and cost["available"] > 0 for cost in row["costs"]) for row in resource["rows"]))
# Engine deliberately gates full-table task planning until the user
# refreshes tasks or enables that feature. Exercise its real HTTP action.
self.assertEqual(self.manager._worker(self.account).engine.snapshot.raw["currentTasks"][0]["typeId"], "1001004")
self.action("refresh_tasks")
mainline = self.view("mainline")
self.assertTrue(mainline["rows"])
self.assertTrue(any(str(row.get("task_type_id")) == "1001004" for row in mainline["rows"]))
config = self.config()["config"]
config["explore_policy"].update(enabled=True, teams={"1": {"enabled": True, "area": "1", "monsters": [101, 102, 103]}})
self.save(config)
explore = self.view("exploration")
self.assertTrue(explore["rows"])
team = next(row for row in explore["rows"] if str(row["id"]) == "1")
self.assertEqual(team["rule_path"], ["explore_policy", "teams", "1"])
self.assertTrue(team["edits"]["monsters"]["options"])
self.assertEqual(self.manager._worker(self.account).engine.explore_policy.teams["1"].monsters, [101, 102, 103])
self.assertEqual(team["monsters"], [101, 102, 103])
self.assertGreater(team["cost_ti"], 0)
self.assertTrue(any(action.kind == "explore_start" for action in self.manager._worker(self.account).engine.plans()))
self.assertFalse(self.manager.status(self.account)["running"])
def test_job_stays_running_until_persistence_and_status_summary_are_published(self):
account = self.create_account(False, "publication barrier")
self.action("login", {"account": "barrier-account", "password": PASSWORD, "remember": False}, account)
worker = self.manager._worker(account)
gate = SnapshotGate()
self.stack.callback(gate.release.set)
persist = worker._persist_session
def blocked_persist():
if worker.engine.client is not None:
gate.wait()
persist()
with patch.object(worker, "_persist_session", blocked_persist):
value = self.response(self.http.post(self.path("actions/enter_server", account), json={"server_id": 7}), 202)
self.assertTrue(gate.entered.wait(3))
try:
current = self.response(self.http.get(self.path("jobs/" + value["id"], account)))
self.assertEqual(current["status"], "running", "A terminal job must not precede persisted/public status")
finally:
gate.release.set()
self.job(value, account)
self.assertTrue(self.response(self.http.get(self.path("status", account)))["connected"])
def test_seeded_sqlite_statistics_compute_rates_sources_and_stamina(self):
for source, samples, units, rate, efficiency in (("sweep", 2, 2, .5, .1), ("event", 1, 3, 1, .6), ("all", 3, 5, 2/3, .2)):
with self.subTest(source=source):
dto = self.view("statistics", {"stage_id": "0101", "level": "3", "source": source})
row = next(row for row in dto["rows"] if row["id"] == "item:30005")
self.assertEqual((row["samples"], row["units"]), (samples, units))
self.assertAlmostEqual(row["rate"], rate)
self.assertAlmostEqual(row["per_stamina"], efficiency)
self.assertTrue(row["interval"])
point = next(point for point in dto["charts"][0]["series"] if point["id"] == row["id"])
self.assertAlmostEqual(point["value"], rate)
dto = self.view("statistics", {"stage_id": "0101", "level": "3", "metric": "per_stamina"})
point = next(point for point in dto["chart"]["series"] if point["id"] == "item:30005")
self.assertAlmostEqual(point["value"], .2)
def test_dto_egg_edit_autosaves_into_real_engine_plan_and_restart_stays_stopped(self):
config, row = self.hatch_config()
column = next(column for column in self.view("bag")["columns"] if column["key"] == "enabled")
self.assertEqual([row["id"] if part == "{id}" else part for part in column["edit"]["path"]], row["rule_path"] + ["enabled"])
applied = self.save(config)
engine = self.manager._worker(self.account).engine
self.assertEqual(engine.policy.egg_rules[row["id"]]["priority"], 13)
plans = engine.plans()
self.assertTrue(plans)
self.assertTrue(all(plan.kind == "hatch" for plan in plans))
self.assertTrue(all(plan.payload["eggs"][0]["itemId"] in row["inventory_ids"] for plan in plans))
preview = self.view("plans")
self.assertTrue(preview["rows"])
self.assertFalse(engine.auto)
self.action("start")
self.assertTrue(self.manager.status(self.account)["running"])
self.manager.close()
from ranch_web.service import WebManager
self.manager = WebManager(self.root, start_scheduler=False, engine_factory=real_engine_factory, login_factory=self.login)
self.app.state.manager = self.manager
self.wait_idle()
self.assertEqual(self.config(), applied)
self.assertFalse(self.manager.status(self.account)["running"])
self.assertFalse(self.manager._worker(self.account).engine.auto)
def test_same_species_config_and_catalog_overrides_are_independent_between_accounts(self):
other = self.create_account(label="account B")
first, row = self.hatch_config()
second, other_row = self.hatch_config(other, enabled=False, priority=91)
self.assertEqual(row["id"], other_row["id"])
first["overrides"] = {row["id"]: {"sell_money": 123456}}
self.save(first)
self.save(second, other)
engine_a, engine_b = (self.manager._worker(a).engine for a in (self.account, other))
self.assertIsNot(engine_a.catalog, engine_b.catalog)
self.assertEqual(engine_a.catalog.monster(row["id"])["sell_money"], 123456)
self.assertNotEqual(engine_b.catalog.monster(row["id"])["sell_money"], 123456)
self.assertTrue(engine_a.plans())
self.assertEqual(engine_b.plans(), [])
self.assertEqual(next(r for r in self.view("bag", account=other)["rows"] if r["id"] == row["id"])["priority"], 91)
def test_http_reads_with_running_real_engine_do_not_dispatch_game_writes(self):
account, client = self.logged_account()
config, _ = self.hatch_config(account)
self.save(config, account)
self.action("start", account=account)
reads = client.reads
before = deepcopy(client.raw)
for page in PAGES:
self.view(page, account=account)
self.response(self.http.get(self.path("status", account)))
self.assertEqual(client.writes, [])
self.assertEqual(client.reads, reads)
self.assertEqual(client.raw, before)
self.assertTrue(self.manager.status(account)["running"])
def test_blocked_game_job_keeps_http_cached_views_and_other_account_available(self):
account, client = self.logged_account()
cached = self.view("bag", account=account)
gate = client.gate = SnapshotGate()
self.stack.callback(gate.release.set)
refresh = self.response(self.http.post(self.path("actions/refresh", account), json={"page": "incubator"}), 202)
self.assertTrue(gate.entered.wait(3))
for endpoint in ("/api/health", "/api/meta", self.path("status", account), self.path("logs", account), self.path("config", account), self.path("views/bag", account), self.path("views/mainline", account)):
with self.subTest(endpoint=endpoint):
start = time.monotonic()
result = self.response(self.http.get(endpoint))
self.assertLess(time.monotonic() - start, 1.5, endpoint)
self.assertFalse(gate.release.is_set())
if endpoint.endswith("views/bag"):
self.assertEqual(result["data"], cached)
self.assertEqual(self.manager.job(account, refresh["id"])["status"], "running")
self.assertTrue(self.view("bag")["rows"])
old = self.config(account)
config = deepcopy(old["config"])
config["interval"] = 60
pending = self.response(self.http.put(self.path("config", account), json={"config": config, "revision": old["revision"]}), 202)
self.assertTrue(pending["pending"])
self.assertEqual(pending["revision"], old["revision"])
self.assertEqual(self.config(account), old)
gate.release.set()
self.job(refresh, account)
self.job(pending["job"], account)
self.assertEqual(self.config(account)["config"]["interval"], 60)
def test_stop_cancels_queued_start_without_later_resurrection(self):
account, client = self.logged_account()
config, _ = self.hatch_config(account)
self.save(config, account)
gate = client.gate = SnapshotGate()
self.stack.callback(gate.release.set)
refresh = self.response(self.http.post(self.path("actions/refresh", account), json={}), 202)
self.assertTrue(gate.entered.wait(3))
start = self.response(self.http.post(self.path("actions/start", account), json={}), 202)
self.assertEqual(self.manager.job(account, start["id"])["status"], "queued")
begin = time.monotonic()
stop = self.response(self.http.post(self.path("actions/stop", account), json={}), 202)
self.assertLess(time.monotonic() - begin, 1.5)
self.assertEqual(stop["status"], "succeeded")
self.assertFalse(self.manager.status(account)["running"])
self.assertFalse(self.manager._worker(account).engine.auto)
self.job(start, account, "cancelled")
gate.release.set()
self.job(refresh, account)
self.wait_idle(account)
self.assertFalse(self.manager.status(account)["running"])
self.assertFalse(self.manager._worker(account).engine.auto)
self.assertEqual(client.writes, [])
def test_legacy_schema_one_import_is_a_job_and_never_starts_engine(self):
from ranch_assistant.model import Policy
from ranch_assistant.policy_io import portable_policy
config, row = self.hatch_config()
self.save(config)
self.action("start")
engine = self.manager._worker(self.account).engine
bundle = portable_policy(Policy(**config["policy"]), engine.snapshot)
self.assertEqual((bundle["schema"], bundle["assistantVersion"]), (1, "1.2.0"))
bundle["policy"].update(enabled=True, fill=True)
before = deepcopy(engine.snapshot.raw)
value = self.response(self.http.post(self.path("config/import"), json={"config": bundle}), 202)
self.job(value)
self.assertFalse(self.manager.status(self.account)["running"])
self.assertFalse(engine.auto)
self.assertEqual(engine.snapshot.raw, before)
self.assertTrue(self.config()["config"]["policy"]["egg_rules"][row["id"]]["enabled"])
exported = self.job(self.response(self.http.get(self.path("config/export")), 202))["result"]
self.assertEqual(exported["schema"], 2)
self.assertEqual(exported["format"], "ranch-helper-policies")
def test_yield_csv_import_is_saved_and_changes_real_view(self):
row = self.view("bag")["rows"][0]
content = f"typeId,sell_money,sell_exp,time_total\n{row['id']},7777,123,600\n".encode()
result = self.action("import_yields", {"filename": "uploaded.csv", "content_base64": base64.b64encode(content).decode()})["result"]
self.assertEqual(result["count"], 1)
self.assertEqual(self.config()["config"]["overrides"][row["id"]]["sell_money"], 7777)
view = self.view("yields", {"search": row["id"]})
self.assertEqual(next(r for r in view["rows"] if r["id"] == row["id"])["sell_money"], 7777)
def test_http_manual_lock_sell_and_feed_confirmations_reach_real_engine(self):
engine = self.manager._worker(self.account).engine
self.action("lock", {"monster_ids": [101]})
self.assertTrue(engine.snapshot.monsters[101]["lock"])
self.action("unlock", {"monster_ids": [101]})
self.assertFalse(engine.snapshot.monsters[101]["lock"])
before = deepcopy(engine.snapshot.raw)
self.action("sell", {"monster_ids": [101]}, expected="failed")
self.assertEqual(engine.snapshot.raw, before)
self.action("sell", {"monster_ids": [101], "confirm": True})
self.assertNotIn(101, engine.snapshot.monsters)
self.action("feed", {"monster_ids": [102], "target_id": 900}, expected="failed")
self.assertIn(102, engine.snapshot.monsters)
self.action("feed", {"monster_ids": [102], "target_id": 900, "confirm": True})
self.assertNotIn(102, engine.snapshot.monsters)
self.assertIn(900, engine.snapshot.monsters)
self.action("sell", {"monster_ids": [900], "confirm": True}, expected="failed")
self.assertIn(900, engine.snapshot.monsters)
self.assertFalse(self.manager.status(self.account)["running"])
def test_http_expansion_quote_is_confirmed_once_and_bound_to_account(self):
other = self.create_account(label="quote scope")
quote = self.action("quote_expansion", {"kind": "stack", "currency": "money", "position": 6})["result"]
self.assertGreater(quote["cost"], 0)
before = self.manager._worker(self.account).engine.snapshot.raw["master"]["money"]
self.action("expand", {"quote_id": quote["quote_id"], "confirm": True}, other, expected="failed")
self.action("expand", {"quote_id": quote["quote_id"]}, expected="failed")
self.assertEqual(self.manager._worker(self.account).engine.snapshot.raw["master"]["money"], before)
self.action("expand", {"quote_id": quote["quote_id"], "confirm": True})
engine = self.manager._worker(self.account).engine
self.assertEqual(engine.snapshot.raw["master"]["money"], before - quote["cost"])
self.assertTrue(any(row["position"] == 6 for row in engine.snapshot.raw["stacks"]))
self.assertEqual(self.response(self.http.get(self.path("status")))["player"]["money"], before - quote["cost"])
self.action("expand", {"quote_id": quote["quote_id"], "confirm": True}, expected="failed")
self.assertEqual(engine.snapshot.raw["master"]["money"], before - quote["cost"])
def test_local_auth_host_csrf_and_remote_client_boundary(self):
from fastapi.testclient import TestClient
before = self.response(self.http.get("/api/accounts"))
invalid_host = self.response(self.http.post("/api/accounts", json={"demo": True}, headers={"Host": "rebind.invalid"}), 400)
self.assertEqual(invalid_host["error"]["code"], "invalid_host")
for headers in ({"Origin": "https://cross-site.invalid"}, {"Sec-Fetch-Site": "cross-site"}):
self.response(self.http.post("/api/accounts", json={"demo": True}, headers=headers), 403)
self.assertEqual(self.response(self.http.get("/api/accounts")), before)
self.response(self.http.post("/api/accounts", json={"demo": True}, headers={"Origin": "http://127.0.0.1:8765", "Sec-Fetch-Site": "same-origin"}), 201)
with TestClient(self.app, base_url="http://127.0.0.1:8765", client=("203.0.113.2", 51234)) as remote:
self.response(remote.get("/api/accounts", headers={"X-Forwarded-For": "127.0.0.1", "X-Forwarded-Host": "localhost"}), 403)
def test_password_auth_cookie_revocation_and_cross_site_login(self):
from fastapi.testclient import TestClient
from ranch_web.app import create_app
from ranch_web.config import COOKIE_NAME, WebConfig
app = create_app(manager=self.manager, updates=self.updates,
config=WebConfig(data_dir=self.root, password="integration-admin-password"))
with TestClient(app, base_url="http://127.0.0.1:8765", client=("127.0.0.1", 50001)) as http:
self.response(http.get("/api/accounts"), 401)
self.response(http.post("/api/auth/login", json={"password": "wrong"}), 401)
self.response(http.post("/api/auth/login", json={"password": "integration-admin-password"}, headers={"Origin": "https://cross-site.invalid"}), 403)
response = http.post("/api/auth/login", json={"password": "integration-admin-password"})
self.response(response)
self.assertIn("httponly", response.headers["set-cookie"].lower())
self.assertIn("samesite=strict", response.headers["set-cookie"].lower())
token = http.cookies.get(COOKIE_NAME)
self.assertTrue(token)
self.assertNotIn("integration-admin-password", token)
self.response(http.get("/api/accounts"))
self.response(http.post("/api/auth/logout"))
self.response(http.get("/api/accounts", headers={"Cookie": COOKIE_NAME + "=" + token}), 401)
def assert_no_secrets(self, value):
encoded = json.dumps(value, ensure_ascii=False)
for secret in (TOKEN, KEY, PASSWORD, str(REQID), str(REQSID), str(self.root), self.root.as_posix()):
self.assertNotIn(secret, encoded)
self.assertNotIn("Traceback (most recent call last)", encoded)
def test_game_credentials_are_absent_from_http_views_config_jobs_and_logs(self):
account, client = self.logged_account()
for page in PAGES:
self.assert_no_secrets(self.view(page, account=account))
for suffix in ("status", "config", "logs", "logs?debug=true"):
self.assert_no_secrets(self.response(self.http.get(self.path(suffix, account))))
self.assert_no_secrets(self.action("export_config", account=account))
client.fail_snapshot = True
failed = self.action("refresh", account=account, expected="failed")
self.assert_no_secrets(failed)
self.assert_no_secrets(self.response(self.http.get(self.path("logs?debug=true", account))))
self.assert_no_secrets(self.response(self.http.get(self.path("status", account))))
def test_lazy_log_detail_is_available_and_keeps_structure_with_secrets_masked(self):
account, _ = self.logged_account()
logs = self.response(self.http.get(self.path("logs?debug=true", account)))
entries = [entry for entry in logs["entries"] if entry.get("details_available")]
self.assertTrue(entries, logs)
self.assertTrue(all("body" not in entry and "details" not in entry for entry in logs["entries"]))
detail = self.response(self.http.get(self.path("logs/" + str(entries[-1]["id"]), account)))
self.assert_no_secrets(detail)
self.assertIn("integration-readable-detail", json.dumps(detail))
self.assertIn("body", json.dumps(detail))
def test_updates_use_fake_source_and_no_stable_v2_means_no_upgrade(self):
self.response(self.http.get("/api/meta"))
self.response(self.http.get("/api/system/updates"))
self.source.assert_not_called()
for releases in ([], [{"tag_name": "v1.2.0", "draft": False, "prerelease": False}],
[{"tag_name": "v2.0.0.dev1", "draft": False, "prerelease": True},
{"tag_name": "v2.0.0", "draft": True, "prerelease": False},
{"tag_name": "v3.0.0", "draft": False, "prerelease": False}]):
self.source.return_value = releases
result = self.response(self.http.post("/api/system/updates/check"))
self.assertFalse(result["available"])
self.assertIsNone(result["latest_version"])
self.assertEqual(result["status"], "no_release")
self.assertEqual(self.source.call_count, 3)
result = self.response(self.http.post("/api/system/updates/apply", json={}), 202)
self.assertEqual(result["status"], "unavailable")
self.assertFalse((self.root / "update-request.json").exists())
def test_config_revisions_and_invalid_input_are_atomic(self):
old = self.config()
value = deepcopy(old["config"])
value["interval"] = 60
applied = self.save(value)
self.response(self.http.put(self.path("config"), json={"config": old["config"], "revision": old["revision"]}), 409)
bad = deepcopy(value)
bad["policy"]["egg_rules"] = {"1001010": {"enabled": "false"}}
self.response(self.http.put(self.path("config"), json={"config": bad, "revision": applied["revision"]}), 400)
self.assertEqual(self.config(), applied)
self.response(self.http.post(self.path("actions/import_yields"), json={"path": "C:/private/account.csv"}), 400)
def _page_test(page):
def check(self):
self.assert_dto(page)
check.__name__ = "test_page_" + page
return check
for _page in PAGES:
setattr(WebIntegrationTests, "test_page_" + _page, _page_test(_page))
class FreshProcessIntegrationTests(unittest.TestCase):
def child(self, program):
env = {key: value for key, value in os.environ.items() if not key.startswith("RANCH_WEB_")}
env["PYTHONIOENCODING"] = "utf-8"
result = subprocess.run([sys.executable, "-X", "utf8", "-c", textwrap.dedent(program)],
cwd=ROOT, env=env, capture_output=True, text=True, encoding="utf-8", timeout=35,
creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0))
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
return json.loads(result.stdout.strip().splitlines()[-1])
def test_fresh_web_process_blocks_gui_imports_and_serves_demo_strategy(self):
result = self.child('''
import importlib.abc, json, sys, tempfile, time
from pathlib import Path
attempted = []
class BlockGUI(importlib.abc.MetaPathFinder):
def find_spec(self, fullname, path=None, target=None):
if fullname.startswith('PySide6') or fullname.endswith('_gui') or fullname == 'ranch_assistant.gui':
attempted.append(fullname)
raise ImportError('GUI import blocked in fresh Web integration process')
sys.meta_path.insert(0, BlockGUI())
from ranch_web.tests.test_web_integration import NoExternalSockets, real_engine_factory
from ranch_web.app import create_app
from ranch_web.config import WebConfig
from ranch_web.service import WebManager
from fastapi.testclient import TestClient
with NoExternalSockets() as network, tempfile.TemporaryDirectory(prefix='web-fresh-process-') as temporary:
manager = WebManager(Path(temporary) / 'new-root', start_scheduler=False, engine_factory=real_engine_factory)
try:
app = create_app(manager=manager, config=WebConfig(data_dir=Path(temporary) / 'new-root'))
with TestClient(app, base_url='http://127.0.0.1', client=('127.0.0.1', 50000)) as http:
assert http.get('/api/health').json()['status'] == 'ok'
account = http.post('/api/accounts', json={'demo': True}).json()['id']
value = http.get('/api/accounts/' + account + '/config').json()
value['config']['interval'] = 60
saved = http.put('/api/accounts/' + account + '/config', json=value)
assert saved.status_code in (200, 202), saved.text
deadline = time.monotonic() + 8
while manager.status(account)['busy'] and time.monotonic() < deadline:
time.sleep(.005)
assert http.get('/api/accounts/' + account + '/config').json()['config']['interval'] == 60
assert http.get('/api/schema').status_code == 200
view = http.get('/api/accounts/' + account + '/views/bag').json()
if view['loading']:
deadline = time.monotonic() + 8
while manager.job(account, view['job_id'])['status'] not in ('succeeded', 'failed') and time.monotonic() < deadline:
time.sleep(.005)
bag = http.get('/api/accounts/' + account + '/views/bag').json()['data']
assert bag['rows'] and bag['columns'][0]['key']
assert not network.attempts
finally:
manager.close()
assert not attempted, attempted
assert not any(n.startswith('PySide6') for n in sys.modules)
print(json.dumps({'health': 'ok', 'demo_rows': len(bag['rows']), 'interval': 60, 'blocked_import_attempts': attempted}))
''')
self.assertEqual(result["blocked_import_attempts"], [])
self.assertGreater(result["demo_rows"], 0)
def test_real_engine_battle_worker_subprocess_still_runs_after_web_imports(self):
result = self.child('''
import json, tempfile
from pathlib import Path
from unittest.mock import patch
import subprocess
from ranch_web.app import create_app
from ranch_web.service import WebManager
from ranch_web.tests.test_web_integration import NoExternalSockets, real_engine_factory
from ranch_assistant.battle_simulator import combat_tables, simulate
row = combat_tables()['monster_info']['1001010']
mon = {'id': 101, 'typeId': 1001010, 'level': 20, 'mode': 2, 'tpLevel': 0, 'feel': 0, 'upStar': 0, 'pAtk': 0, 'pDef': 0, 'pHp': 0, 'pDex': 0}
for name in ('Atk', 'Def', 'Hp', 'Dex'):
mon['g' + name] = (row[name.lower() + '_grow_min'] + row[name.lower() + '_grow_max']) / 2
enemy = {'type': '1001010', 'team': 2, 'mode': 2, 'level': 1, 'atk': 16, 'def': 20, 'hp': 101, 'dex': 4, 'spd_mov': .92, 'spd_atk': 1595, 'atk_dis': 100, 'skill_1': 0, 'skill_2': 0, 'joinTime': -1, 'wave': 1, 'teamPos': 1, 'ai': 0, 'joinPoint': 'point_team2_fore2', 'controller': []}
request = {'context': 'ordinary_stage', 'seed': 0, 'team': 'teamA',
'battle_position': {'battleType': 'stage', 'stageId': 'fixture', 'stageLevel': '1'},
'roster': {'master': {'level': 43}, 'monsters': [mon], 'teams': [{'teamName': 'teamA', 'monsters': [101]}], 'monsterAttributes': []},
'original_data': {'battle': {'time': 30, 'winType': ['1'], 'loseType': ['1', '2'], 'controller': [], 'triggers': [],
'teams': [{'team': 2, 'numMax': 2, 'ap': 80, 'mons': [enemy]}],
'battleField': {'fieldMode': True, 'fieldName': 'default', 'mapAreas': [], 'mapObjects': []}}}}
with NoExternalSockets() as network, tempfile.TemporaryDirectory(prefix='web-battle-process-') as temporary:
manager = WebManager(Path(temporary) / 'new-root', start_scheduler=False, engine_factory=real_engine_factory)
try:
account = manager.create_account(demo=True)['id']
engine = manager._worker(account).engine
engine._select_battle_runtime('experimental')
with patch('subprocess.Popen', wraps=subprocess.Popen) as launch:
result = engine.battles.runtime.run(request, timeout=15)
assert launch.call_count == 1
assert 'ranch_assistant.battle_simulator' in launch.call_args.args[0]
assert result == simulate(request), result
assert result['outcome'] == 'win', result
assert not network.attempts
print(json.dumps({'outcome': result['outcome'], 'execution_mode': result['execution_mode'], 'real_worker_processes': launch.call_count}))
finally:
manager.close()
''')
self.assertEqual(result["real_worker_processes"], 1)
self.assertEqual(result["outcome"], "win")
if __name__ == "__main__":
unittest.main()
+179
View File
@@ -0,0 +1,179 @@
"""Focused pure-policy tests; no desktop imports or private account files."""
from copy import deepcopy
from pathlib import Path
import tempfile
import unittest
from ranch_assistant.engine import Engine, demo_snapshot
from ranch_assistant.model import Catalog, Policy
from ranch_assistant.policy_io import portable_policy
from ranch_web.policies import apply_config, default_config, export_config, import_config, validate_config
class WebPolicyTests(unittest.TestCase):
def test_defaults_are_independent_and_match_current_desktop(self):
first, second = default_config(), default_config()
first["policy"]["gift_targets"]["900"] = 3
self.assertEqual(second["policy"]["gift_targets"], {})
self.assertTrue(second["policy"]["manual_eggs"])
self.assertEqual(second["progression_policy"]["battle_mode"], "experimental")
def test_validate_original_mode_before_normalizing_for_linux(self):
for source in ("original", "experimental"):
with self.subTest(source=source):
value = validate_config({"progression_policy": {"battle_mode": source}})
self.assertEqual(value["progression_policy"]["battle_mode"], "experimental")
with self.assertRaises(ValueError):
validate_config({"progression_policy": {"battle_mode": "unknown"}})
def test_validate_legacy_egg_mode_before_enforcing_current_desktop(self):
for flag in (False, True):
with self.subTest(flag=flag):
source = {"policy": {"manual_eggs": flag}}
value = validate_config(source)
self.assertTrue(value["policy"]["manual_eggs"])
self.assertIs(source["policy"]["manual_eggs"], flag)
for flag in (0, 1, "false", "true", None, [], {}):
with self.subTest(flag=flag), self.assertRaises(ValueError):
validate_config({"policy": {"manual_eggs": flag}})
def test_apply_legacy_mode_never_plans_unchecked_eggs(self):
with tempfile.TemporaryDirectory() as folder:
engine = Engine(Catalog(), budget_path=Path(folder) / "budget.json")
engine.snapshot = demo_snapshot(engine.catalog)
config = default_config()
config["policy"]["manual_eggs"] = False
applied = apply_config(engine, config)
self.assertTrue(applied["policy"]["manual_eggs"])
self.assertTrue(engine.policy.manual_eggs)
self.assertEqual(engine.planner.available_eggs(engine.snapshot, engine.policy), [])
self.assertEqual(engine.planner.hatch_actions(engine.snapshot, engine.policy), [])
egg = engine.snapshot.eggs(engine.catalog)[0]
config["policy"]["egg_rules"] = {str(egg["typeId"]): {"enabled": True}}
apply_config(engine, config)
eligible = engine.planner.available_eggs(engine.snapshot, engine.policy)
self.assertEqual([str(row["typeId"]) for row, _ in eligible], [str(egg["typeId"])])
actions = engine.planner.hatch_actions(engine.snapshot, engine.policy)
self.assertTrue(actions)
self.assertTrue(all(action.payload["eggs"][0]["itemId"] == egg["id"] for action in actions))
self.assertFalse(engine.auto)
def test_old_portable_both_schemas_enforce_selected_eggs_without_starting(self):
legacy = portable_policy(Policy(manual_eggs=False))
bundle = export_config(default_config())
bundle["policy"]["manual_eggs"] = False
for document in (legacy, bundle):
with self.subTest(schema=document["schema"]):
imported = import_config(document)
self.assertTrue(imported["policy"]["manual_eggs"])
self.assertTrue(export_config(imported)["policy"]["manual_eggs"])
for document in (legacy, bundle):
malformed = deepcopy(document)
malformed["policy"]["manual_eggs"] = "false"
with self.subTest(schema=document["schema"]), self.assertRaises(ValueError):
import_config(malformed)
def test_reject_unknown_secret_and_invalid_dynamic_paths(self):
bad = [
{"password": "synthetic"}, {"policy": {"token": "synthetic"}},
{"policy": {"gift_items": {"30001": {"enabled": True, "password": "synthetic"}}}},
{"policy": {"egg_rules": {"1001010": {"enabled": 1}}}},
{"policy": {"feed_targets": {"900": True}}},
{"policy": {"gift_targets": {"../../settings": 1}}},
{"policy": {"reserved_types": [True]}}, {"policy": {"protect_star": 0}},
{"policy": {"gift_items": {"30001": {"reserve": -1}}}},
{"policy": {"egg_rules": {"1001010": {"keep_count": 1001}}}},
{"policy": {"egg_rules": {"1001010": {"refill_below": 11, "refill_target": 10}}}},
{"sweep_policy": {"rules": {"0101": {"enabled": True, "limit": -1}}}},
{"sweep_policy": {"rules": {"0101": {"level": "4"}}}},
{"explore_policy": {"teams": {"1": {"monsters": [1, 2]}}}},
{"explore_policy": {"teams": {"1": {"monsters": [1, 2, 2]}}}},
{"explore_policy": {"teams": {"1": {"monsters": [True, 2, 3]}}}},
{"daily_policy": {"selected": ["all"]}}, {"interval": True},
{"overrides": {"1001010": {"sell_money": float("nan")}}},
{"overrides": {"1001010": {"time_total": -1}}},
{"overrides": {"1001010": {"path": "private"}}},
{"log_sizes": [0, 0]}, {"yield_stars": [True]},
]
for value in bad:
with self.subTest(value=value), self.assertRaises(ValueError):
validate_config(value)
def test_nested_defaults_and_fractional_thresholds_are_preserved(self):
value = validate_config({"policy": {"min_gold_per_hour": .5, "coins_per_exp": 2.75,
"egg_rules": {"1001010": {"keep_count": 7}}}})
self.assertEqual(value["policy"]["min_gold_per_hour"], .5)
self.assertEqual(value["policy"]["egg_rules"]["1001010"]["keep_count"], 7)
self.assertEqual(value["policy"]["egg_rules"]["1001010"]["action"], "sell")
def test_apply_is_atomic_and_never_starts_automation(self):
with tempfile.TemporaryDirectory() as folder:
engine = Engine(Catalog(), budget_path=Path(folder) / "budget.json")
original = engine.policy
with self.assertRaises(ValueError):
apply_config(engine, {"policy": {"protect_star": 6}, "quest_policy": {"enabled": "yes"}})
self.assertIs(engine.policy, original)
cfg = default_config()
cfg["progression_policy"]["battle_mode"] = "original"
cfg["policy"]["gift_targets"] = {"900": 2}
cfg["overrides"] = {"1001010": {"sell_money": 12.5}}
apply_config(engine, cfg)
self.assertFalse(engine.auto)
self.assertEqual(engine.progression_policy.battle_mode, "experimental")
self.assertEqual(engine.policy.gift_targets, {"900": 2})
self.assertEqual(engine.catalog.monster(1001010)["sell_money"], 12.5)
def test_portable_schema_two_remaps_species_and_normalizes_legacy_mode(self):
snapshot = demo_snapshot(Catalog())
config = default_config()
config["policy"].update(feed_targets={"900": 1}, gift_targets={"900": 2}, breakthrough_targets={"900": 3}, room_id=123456789)
config["sweep_policy"]["rules"] = {"0101": {"enabled": True, "level": "3", "limit": 4}}
exported = export_config(config, snapshot)
self.assertNotIn("feed_targets", exported["policy"])
self.assertNotIn("gift_targets", exported["policy"])
self.assertEqual(exported["policy"]["room_id"], 0)
self.assertNotIn("log_sizes", exported)
exported["progression_policy"]["battle_mode"] = "original"
exported["sweep_policy"]["rules"]["0101"]["level"] = 3
snapshot.monsters[900]["id"] = 999
imported = import_config(exported, snapshot)
for field, priority in (("feed_targets", 1), ("gift_targets", 2), ("breakthrough_targets", 3)):
self.assertEqual(imported["policy"][field], {"999": priority})
self.assertEqual(imported["progression_policy"]["battle_mode"], "experimental")
self.assertEqual(imported["sweep_policy"]["rules"]["0101"]["level"], "3")
self.assertEqual(import_config(exported)["policy"]["feed_targets"], {})
def test_schema_one_and_explore_import_never_copy_instance_ids(self):
snapshot = demo_snapshot(Catalog())
legacy = portable_policy(Policy(feed_targets={"900": 3}, protect_quality=6), snapshot)
snapshot.monsters[900]["id"] = 999
imported = import_config(legacy, snapshot)
self.assertEqual(imported["policy"]["feed_targets"], {"999": 3})
self.assertFalse(imported["policy"]["enabled"])
snapshot = demo_snapshot(Catalog())
for mid in (101, 102):
snapshot.monsters[mid].update(process=3, typeId=snapshot.monsters[900]["typeId"])
snapshot.raw["exploreTeams"] = [{"id": 800, "status": 0}]
config = default_config()
config["explore_policy"] = {"enabled": True, "reserve_ti": 9,
"teams": {"800": {"enabled": True, "area": "1", "monsters": [900, 101, 102]}}}
exported = export_config(config, snapshot)
snapshot.raw["exploreTeams"][0]["id"] = 50
for mon in snapshot.raw["monsters"]:
mon["id"] += 1000
imported = import_config(exported, snapshot)
self.assertNotIn("800", imported["explore_policy"]["teams"])
self.assertEqual(imported["explore_policy"]["teams"]["50"]["monsters"], [1101, 1102, 1900])
self.assertFalse(imported["explore_policy"]["enabled"])
def test_import_rejects_unknown_fields_instead_of_silently_dropping_them(self):
exported = export_config(default_config())
for value in (exported | {"token": "synthetic"},
exported | {"targetSpecies": {"feed": [{"typeId": "1001010", "priority": 2, "password": "synthetic"}]}},
exported | {"policy": exported["policy"] | {"feed_targets": {"900": True}}}):
with self.subTest(value=value), self.assertRaises(ValueError):
import_config(value)
if __name__ == "__main__":
unittest.main()
+349
View File
@@ -0,0 +1,349 @@
"""Temporary filesystem and fake Docker/GitHub transaction tests."""
from contextlib import closing, redirect_stdout
from dataclasses import replace
from datetime import timedelta
import io
import json
import os
from pathlib import Path
import sqlite3
import tempfile
import time
import unittest
from unittest.mock import patch
from deploy.web import updater
from ranch_web import updates
def release(tag):
return {"tag_name": tag, "draft": False, "prerelease": False}
class FakeDocker:
def __init__(self, config):
self.config = config
self.events = []
self.version = "2.0.0.dev1"
self.old_version = self.version
self.image = "sha256:" + "a" * 64
self.old_image = self.image
self.running = True
self.fail_pull = self.fail_start = self.fail_rollback = False
def inspect_service(self, **kwargs):
return {"image": self.image, "version": self.version, "running": self.running, "health": "healthy"}
def validate(self, image):
self.events.append(("validate", image))
def pull(self, image):
self.events.append(("pull", image))
if not self.running:
raise AssertionError("pull must happen while the old app is running")
if self.fail_pull:
raise updater.UpdaterError("fake registry failure")
def stop(self):
self.events.append(("stop", None))
self.running = False
def up(self, image):
self.events.append(("up", image))
self.running = True
if image == self.old_image:
if self.fail_rollback:
raise updater.UpdaterError("fake rollback failure")
self.image = image
self.version = self.old_version
else:
self.image = "sha256:" + "b" * 64
self.version = image.rsplit(":", 1)[1][1:]
(self.config.data_dir / "key.bin").write_bytes(b"changed-key")
with closing(sqlite3.connect(self.config.data_dir / "samples.sqlite3")) as connection, connection:
connection.execute("insert into samples values (2)")
if self.fail_start:
raise updater.UpdaterError("fake health failure")
class HostUpdaterTests(unittest.TestCase):
def setUp(self):
self.temporary = tempfile.TemporaryDirectory(prefix="ranch-host-updater-")
self.addCleanup(self.temporary.cleanup)
self.root = Path(self.temporary.name).resolve()
self.config = updater.Config(
project_dir=self.root, data_dir=self.root / "data", control_dir=self.root / "control",
backup_dir=self.root / "backups", failed_data_dir=self.root / "failed-data",
)
self.config.data_dir.mkdir()
self.config.control_dir.mkdir()
(self.config.data_dir / "key.bin").write_bytes(b"original-encrypted-test-key")
with closing(sqlite3.connect(self.config.data_dir / "samples.sqlite3")) as connection, connection:
connection.execute("create table samples (n integer)")
connection.execute("insert into samples values (1)")
self.docker = FakeDocker(self.config)
self.host = updater.HostUpdater(self.config, self.docker)
self.github = patch.object(updates, "github_releases", return_value=[release("v2.0.0")])
self.releases = self.github.start()
self.addCleanup(self.github.stop)
# Linux CI runs unprivileged; real chown is a host deployment check.
self.chown = patch.object(updater.os, "chown", create=True)
self.chown.start()
self.addCleanup(self.chown.stop)
self.environment = patch.dict(os.environ, {"RANCH_WEB_UPDATER_DIR": str(self.config.control_dir)})
self.environment.start()
self.addCleanup(self.environment.stop)
def samples(self, directory=None):
with closing(sqlite3.connect((directory or self.config.data_dir) / "samples.sqlite3")) as connection:
return connection.execute("select n from samples order by n").fetchall()
def enable(self):
self.config = replace(self.config, accept_web_requests=True)
self.host = updater.HostUpdater(self.config, self.docker)
return self.host.capability()
def request(self, capability, **overrides):
value = {"protocol": 1, "request_id": "c" * 32, "executor_id": capability["executor_id"],
"version": "v2.0.0", "requested_at": updates.timestamp(), **overrides}
updates.atomic_json(self.config.data_dir / "update-request.json", value)
return value
def test_pull_failure_does_not_stop_or_backup(self):
self.docker.fail_pull = True
with self.assertRaises(updater.UpdaterError):
self.host.apply()
self.assertTrue(self.docker.running)
self.assertNotIn("stop", [event[0] for event in self.docker.events])
self.assertFalse(self.config.backup_dir.exists())
self.assertFalse(self.host.journal.exists())
def test_update_stops_before_snapshot_and_persists_image_only_after_health(self):
original_snapshot = updater.snapshot_data
def snapshot(config, identity):
self.assertFalse(self.docker.running)
self.docker.events.append(("snapshot", None))
return original_snapshot(config, identity)
with patch.object(updater, "snapshot_data", side_effect=snapshot):
result = self.host.apply()
self.assertEqual(result["status"], "succeeded")
self.assertEqual([event[0] for event in self.docker.events], ["validate", "pull", "stop", "snapshot", "up"])
self.assertEqual((self.root / ".image.env").read_text(), f"RANCH_WEB_IMAGE={updates.IMAGE}:v2.0.0\n")
self.assertFalse(self.host.journal.exists())
self.assertEqual(len(list(self.config.backup_dir.glob("*.tar.gz"))), 1)
def test_health_failure_restores_sqlite_key_and_keeps_failed_data(self):
self.docker.fail_start = True
result = self.host.apply(request_id="d" * 32)
self.assertEqual(result["status"], "rolled_back")
self.assertTrue(self.docker.running)
self.assertEqual(self.docker.image, self.docker.old_image)
self.assertEqual(self.samples(), [(1,)])
self.assertEqual((self.config.data_dir / "key.bin").read_bytes(), b"original-encrypted-test-key")
failed = self.config.failed_data_dir / ("d" * 32)
self.assertEqual(self.samples(failed), [(1,), (2,)])
self.assertEqual((failed / "key.bin").read_bytes(), b"changed-key")
self.assertIn(self.docker.old_image, (self.root / ".image.env").read_text())
def test_restart_and_snapshot_restore_preserve_preferences_but_never_start_strategies(self):
from ranch_web.service import WebManager
def complete(manager, account_id, job):
until = time.monotonic() + 5
while time.monotonic() < until:
result = manager.job(account_id, job["id"])
if result["status"] in {"succeeded", "failed", "cancelled"}:
self.assertEqual(result["status"], "succeeded", result.get("error"))
return
time.sleep(0.01)
self.fail("offline worker did not finish")
with patch("socket.socket.connect", side_effect=AssertionError("Network forbidden in deployment restart test")):
manager = WebManager(self.config.data_dir, start_scheduler=False)
try:
account_id = manager.create_account(demo=True)["id"]
config = manager.get_config(account_id)["config"]
config["daily_policy"]["enabled"] = True
pending = manager.set_config(account_id, config)
complete(manager, account_id, pending["job"])
complete(manager, account_id, manager.submit(account_id, "start"))
self.assertTrue(manager.status(account_id)["running"])
finally:
manager.close()
key = (self.config.data_dir / "web.key").read_bytes()
identity = "f" * 32
backup = updater.snapshot_data(self.config, identity)
for restore in (False, True):
if restore:
updater.restore_data(self.config, backup, identity)
restarted = WebManager(self.config.data_dir, start_scheduler=False)
try:
self.assertFalse(restarted.status(account_id)["running"])
self.assertTrue(restarted.get_config(account_id)["config"]["daily_policy"]["enabled"])
self.assertEqual((self.config.data_dir / "web.key").read_bytes(), key)
finally:
restarted.close()
def test_backup_failure_resumes_pinned_old_image_without_new_image(self):
with patch.object(updater, "snapshot_data", side_effect=OSError("fake disk full")):
result = self.host.apply()
self.assertEqual(result["status"], "rolled_back")
starts = [image for event, image in self.docker.events if event == "up"]
self.assertEqual(starts, [self.docker.old_image])
self.assertEqual(self.samples(), [(1,)])
def test_failed_rollback_retains_journal_and_backup(self):
self.docker.fail_start = self.docker.fail_rollback = True
with self.assertRaises(updater.UpdaterError):
self.host.apply()
self.assertTrue(self.host.journal.exists())
self.assertEqual(updates.read_json(self.config.data_dir / "updater-status.json")["status"], "failed")
self.assertTrue(list(self.config.backup_dir.glob("*.tar.gz")))
def test_recovery_can_retry_old_start_after_data_was_already_restored(self):
self.docker.fail_start = self.docker.fail_rollback = True
with self.assertRaises(updater.UpdaterError):
self.host.apply()
self.docker.fail_rollback = False
result = self.host.recover()
self.assertEqual(result["status"], "rolled_back")
self.assertEqual(self.samples(), [(1,)])
self.assertFalse(self.host.journal.exists())
def test_interrupted_transaction_recovery_resumes_old_service(self):
identity = "e" * 32
self.docker.stop()
updater.snapshot_data(self.config, identity)
self.docker.up(f"{updates.IMAGE}:v2.0.0")
updates.atomic_json(self.host.journal, {"request_id": identity, "version": "v2.0.0",
"old_image": self.docker.old_image, "backup_ready": True, "new_started": True})
result = self.host.recover()
self.assertEqual(result["status"], "rolled_back")
self.assertEqual(self.samples(), [(1,)])
self.assertFalse(self.host.journal.exists())
def test_only_old_desktop_release_leaves_service_untouched(self):
self.releases.return_value = [release("v1.2.0"), release("v3.0.0")]
result = self.host.apply()
self.assertEqual(result["status"], "no_release")
self.assertEqual(self.docker.events, [])
def test_same_stable_version_or_downgrade_never_pulls(self):
for current in ("2.0.0", "2.1.0"):
with self.subTest(current=current):
self.docker.version = current
with self.assertRaises(updater.UpdaterError):
self.host.apply("v2.0.0")
self.assertEqual(self.docker.events, [])
def test_host_independently_rejects_not_official_request_tag(self):
capability = self.enable()
self.request(capability, version="v2.99.99")
self.releases.return_value = [release("v2.0.0")]
result = self.host.run()
self.assertEqual(result["status"], "failed")
self.assertTrue(self.docker.running)
self.assertEqual(self.docker.events, [])
self.releases.assert_called_once()
def test_web_request_requires_operator_opt_in(self):
capability = self.host.capability()
self.assertFalse(capability["enabled"])
self.request(capability)
self.host.run()
self.assertTrue(self.docker.running)
self.assertEqual(self.docker.events, [])
def test_web_request_success_and_replay_deduplication(self):
capability = self.enable()
request = self.request(capability)
result = self.host.run()
self.assertEqual(result["status"], "succeeded")
self.assertEqual(result["request_id"], request["request_id"])
events = list(self.docker.events)
self.host.run()
self.assertEqual(events, self.docker.events)
def test_stale_other_executor_and_injected_command_are_rejected(self):
capability = self.enable()
variants = [dict(executor_id="a" * 32), dict(command="rm anything"),
dict(requested_at=updates.timestamp(updates.utc_now() - timedelta(days=2))),
dict(requested_at=updates.timestamp(updates.utc_now() + timedelta(hours=1)))]
for index, variant in enumerate(variants):
with self.subTest(variant=variant):
self.request(capability, request_id=f"{index:032x}", **variant)
self.assertEqual(self.host.run()["status"], "failed")
self.assertEqual(self.docker.events, [])
self.releases.assert_not_called()
def test_auto_apply_is_explicit_opt_in(self):
result = self.host.run()
self.assertTrue(result["available"])
self.assertEqual(self.docker.events, [])
config = replace(self.config, auto_apply=True)
result = updater.HostUpdater(config, self.docker).run()
self.assertEqual(result["status"], "succeeded")
def test_malformed_request_fails_without_network_or_docker(self):
self.enable()
updates.atomic_json(self.config.data_dir / "update-request.json", ["invalid"])
self.assertEqual(self.host.run()["status"], "failed")
self.assertEqual(self.docker.events, [])
self.releases.assert_not_called()
def test_dry_run_is_read_only_and_network_free(self):
document = self.root / "updater.toml"
text = "\n".join(f"{key} = {json.dumps(str(getattr(self.config, key)))}" for key in (
"project_dir", "data_dir", "control_dir", "backup_dir", "failed_data_dir"))
document.write_text(text, encoding="utf-8")
before = sorted(str(item.relative_to(self.root)) for item in self.root.rglob("*"))
with patch.object(updater.Docker, "run", side_effect=AssertionError("Docker not allowed")), redirect_stdout(io.StringIO()) as output:
code = updater.main(["--config", str(document), "--apply", "v2.1.0", "--dry-run"])
self.assertEqual(code, 0)
self.assertTrue(json.loads(output.getvalue())["dry_run"])
self.assertEqual(before, sorted(str(item.relative_to(self.root)) for item in self.root.rglob("*")))
self.releases.assert_not_called()
def test_shipped_linux_config_supports_windows_dry_run(self):
source = Path(updater.__file__).with_name("updater.example.toml")
with patch.object(updater.Docker, "run", side_effect=AssertionError("Docker not allowed")), redirect_stdout(io.StringIO()) as output:
code = updater.main(["--config", str(source), "--apply", "v2.0.0", "--dry-run"])
self.assertEqual(code, 0)
self.assertTrue(json.loads(output.getvalue())["dry_run"])
self.releases.assert_not_called()
def test_config_rejects_unknown_fields_and_nested_control_paths(self):
document = self.root / "bad.toml"
for text in ("download_url = 'https://evil.invalid'", f"control_dir = {json.dumps(str(self.config.data_dir / 'control'))}\ndata_dir = {json.dumps(str(self.config.data_dir))}"):
document.write_text(text, encoding="utf-8")
with self.assertRaises(updater.UpdaterError):
updater.Config.load(document)
def test_real_docker_runner_uses_arguments_not_shell_and_never_echoes_output(self):
docker = updater.Docker(self.config)
with patch.object(updater.subprocess, "run") as run:
run.return_value.returncode = 1
run.return_value.stdout = "password=secret"
run.return_value.stderr = "token=secret"
with self.assertRaises(updater.UpdaterError) as error:
docker.pull(f"{updates.IMAGE}:v2.0.0")
args, kwargs = run.call_args
self.assertIsInstance(args[0], list)
self.assertNotIn("shell", kwargs)
self.assertIn("pull", args[0])
self.assertNotIn("secret", str(error.exception))
def test_healthy_container_with_dev_label_is_not_a_completed_stable_update(self):
docker = updater.Docker(self.config)
target = f"{updates.IMAGE}:v2.0.0"
with patch.object(docker, "compose"), patch.object(docker, "inspect_service") as inspect:
inspect.return_value = {"running": True, "health": "healthy", "version": "2.0.0.dev1"}
with self.assertRaises(updater.UpdaterError):
docker.up(target)
inspect.return_value = {"running": True, "health": "unhealthy", "version": "2.0.0"}
with self.assertRaises(updater.UpdaterError):
docker.up(target)
inspect.return_value = {"running": True, "health": "healthy", "version": "2.0.0"}
docker.up(target)
if __name__ == "__main__":
unittest.main()
+398
View File
@@ -0,0 +1,398 @@
"""Parity checks with disposable offline Engines, fake transports and evidence."""
from copy import deepcopy
import base64
import io
import json
from pathlib import Path
import subprocess
import sys
import tempfile
from types import SimpleNamespace
import unittest
from unittest.mock import Mock, patch
from ranch_assistant.engine import Engine, demo_snapshot
from ranch_assistant.exploration import ExplorePlanner
from ranch_assistant.maps import Stage
from ranch_assistant.model import Catalog
from ranch_web.actions import execute_action
from ranch_web.policies import apply_config, default_config, export_config
from ranch_web.views import build_view, PAGES, schema
class OfflineWorker:
def __init__(self, folder):
self.profile_root = Path(folder)
self.engine = Engine(Catalog(), budget_path=self.profile_root / "budget.json")
self.engine.snapshot = demo_snapshot(self.engine.catalog)
self.config = apply_config(self.engine, default_config())
self.running, self.revision = False, 1
self.messages = []
self.trace = SimpleNamespace(path=self.profile_root / "network_debug.jsonl")
def stop(self):
self.running = self.engine.auto = False
def result(self, snapshot, plans, message):
self.engine.snapshot = snapshot
self.messages.append(message)
def save_config(self, config):
self.config = apply_config(self.engine, config)
self.revision += 1
return {"config": deepcopy(self.config), "revision": self.revision}
class WebViewActionTests(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory(prefix="ranch-web-parity-test-")
self.addCleanup(self.temp.cleanup)
self.worker = OfflineWorker(self.temp.name)
self.engine = self.worker.engine
def view(self, page, query=None):
return build_view(self.engine, page, self.worker.config, query)
def action(self, operation, **payload):
return execute_action(self.worker, operation, payload)
def test_all_pages_are_public_json_without_qt_imports_or_network(self):
self.engine.client = SimpleNamespace(call=Mock(side_effect=AssertionError("offline-only")))
self.engine.demo = False
for page, title in PAGES:
with self.subTest(page=page):
dto = self.view(page)
self.assertEqual(dto["title"], title)
json.dumps(dto, ensure_ascii=False, allow_nan=False)
self.assertNotIn('"raw"', json.dumps(dto))
self.engine.client.call.assert_not_called()
script = """import sys, importlib.abc
class BlockGUI(importlib.abc.MetaPathFinder):
def find_spec(self,fullname,path=None,target=None):
if fullname.startswith('PySide6') or fullname.endswith('_gui') or fullname == 'ranch_assistant.gui':
raise AssertionError(fullname)
sys.meta_path.insert(0,BlockGUI())
import ranch_web.policies,ranch_web.views,ranch_web.actions
"""
result = subprocess.run([sys.executable, "-c", script], cwd=Path(__file__).resolve().parents[2], capture_output=True, text=True)
self.assertEqual(result.returncode, 0, result.stderr)
def test_schema_exposes_only_current_gui_fields_and_chinese_labels(self):
value = schema(self.engine.catalog)
fields = [field for page in value["pages"] for field in page["form"]]
self.assertTrue(all(field["label"] and isinstance(field["path"], list) for field in fields))
self.assertNotIn(["policy", "feed_target"], [field["path"] for field in fields])
self.assertNotIn(["progression_policy", "battle_mode"], [field["path"] for field in fields])
self.assertEqual(dict(PAGES)["statistics"], "数据分析")
self.assertEqual(dict(PAGES)["plans"], "执行计划")
self.assertEqual(len(self.view("yields")["rows"]), 749)
self.assertEqual([tab["title"] for tab in self.view("hatching")["tabs"]], ["孵蛋策略", "牧场策略", "喂养策略"])
def test_incubator_includes_closed_slots_and_vip_never_expandable(self):
dto = self.view("incubator")
self.assertEqual(len(dto["rows"]), 11)
self.assertFalse(dto["rows"][3]["can_expand"])
self.assertTrue(dto["rows"][6]["can_expand"])
self.assertEqual(dto["rows"][0]["monster_id"], 101)
def test_bag_uses_real_category_and_groups_inventory_ids(self):
catalog = self.engine.catalog
categories = {"usable": 1, "consumables": 2, "materials": 3, "other": 4, "equipment": 5}
items = []
for category, code in categories.items():
key = next(key for key in catalog.data["item_info"] if catalog.item_type(key) == code)
items += [{"id": len(items) + 10000, "typeId": key, "num": number} for number in (3, 4)]
self.engine.snapshot.raw["items"] += items
for category, code in categories.items():
with self.subTest(category=category):
dto = self.view("bag", {"category": category})
self.assertTrue(dto["rows"])
self.assertTrue(all(catalog.item_type(row["id"]) == code for row in dto["rows"]))
row = next(row for row in dto["rows"] if len(row["inventory_ids"]) == 2)
self.assertEqual(row["count"], 7)
self.assertEqual(row["rule_path"], ["policy", "gift_items", row["id"]])
if code == 5:
self.assertTrue(row["edits"]["enabled"]["disabled"])
def test_egg_keep_count_and_missing_stock_rule_bind_real_config(self):
config = deepcopy(self.worker.config)
config["policy"]["egg_rules"]["1001010"] = {"enabled": True, "keep_count": 5, "priority": 1, "market_id": "sc_city1"}
self.worker.save_config(config)
dto = self.view("bag", {"category": "eggs"})
row = next(row for row in dto["rows"] if row["id"] == "1001010")
column = next(column for column in dto["columns"] if column["key"] == "keep_count")
self.assertEqual(column["label"], "牧场保留")
self.assertEqual(row["keep_count"], 5)
self.assertEqual(column["edit"]["path"], ["policy", "egg_rules", "{id}", "keep_count"])
self.assertTrue(row["edits"]["market_id"]["options"])
def test_add_rule_species_defaults_follow_current_market_and_desktop_fallback(self):
catalog = self.engine.catalog
self.engine.snapshot.raw["items"] = []
config = deepcopy(self.worker.config)
config["policy"]["market_id"] = "sc_city10"
self.worker.save_config(config)
dto = self.view("bag", {"category": "eggs"})
field = next(field for field in dto["form"] if field["type"] == "add_rule")
defaults = field["defaults_by_id"]
self.assertEqual(set(defaults), set(catalog.monsters))
self.assertEqual(dto["rows"], [])
self.assertEqual(defaults["1001010"]["market_id"], "sc_city10")
fallback = next(key for key in catalog.monsters if catalog.markets_for(key) and "sc_city10" not in catalog.markets_for(key))
self.assertEqual(defaults[fallback]["market_id"], catalog.markets_for(fallback)[0])
unavailable = next(key for key in catalog.monsters if not catalog.markets_for(key))
self.assertEqual(defaults[unavailable]["market_id"], "")
config = deepcopy(self.worker.config)
for key in ("1001010", fallback, unavailable):
config["policy"]["egg_rules"][key] = deepcopy(defaults[key])
self.worker.save_config(config)
rows = {row["id"]: row for row in self.view("bag", {"category": "eggs"})["rows"]}
for key in ("1001010", fallback, unavailable):
with self.subTest(species=key):
self.assertEqual(rows[key]["market_id"], defaults[key]["market_id"])
self.assertEqual(rows[key]["rule_defaults"], defaults[key])
self.assertFalse(rows[key]["enabled"])
self.assertEqual(self.engine.policy.egg_rules[key], defaults[key])
self.assertFalse(self.engine.auto)
def test_status_fields_expose_core_feed_draw_and_gift_timing(self):
snapshot, catalog = self.engine.snapshot, self.engine.catalog
config = deepcopy(self.worker.config)
config["policy"]["feed_targets"] = {"900": 1}
self.engine.last_draw = "offline draw: 3 eggs"
self.worker.save_config(config)
details = self.view("hatching")["details"]
self.assertEqual(details["feed_status"], self.engine.planner.feed_status(snapshot, self.engine.policy))
self.assertTrue(details["feed_status"][0])
self.assertIsInstance(details["feed_status"][1], str)
self.assertEqual(details["last_draw"], "offline draw: 3 eggs")
self.assertIsNone(self.view("gifts")["details"]["next_ready_at"])
likes = catalog.monster(snapshot.monsters[900]["typeId"]).get("like") or {}
gift_id = next(str(key) for key, feel in likes.items() if feel > 0 and catalog.item_type(key) not in (5, 6) and catalog.item(key).get("sellable"))
gifted_at = snapshot.now
snapshot.monsters[900]["giftTime"] = gifted_at * 1000
snapshot.raw["items"].append({"id": 8000, "typeId": int(gift_id), "num": 2})
config["policy"].update(gift_enabled=True, gift_targets={"900": 1}, gift_items={gift_id: {"enabled": True, "reserve": 0}})
self.worker.save_config(config)
deadline = self.view("gifts")["details"]["next_ready_at"]
self.assertEqual(deadline, gifted_at + int(catalog.data["game_setting"].get("monGiftTime", 7200)))
def test_ranch_targets_are_real_priorities_and_details_are_whitelisted(self):
config = deepcopy(self.worker.config)
for field, priority in (("feed_targets", 1), ("gift_targets", 2), ("breakthrough_targets", 3)):
config["policy"][field] = {"900": priority}
self.worker.save_config(config)
self.engine.snapshot.monsters[900].update(password="synthetic-secret", raw={"token": "synthetic-secret"})
dto = self.view("ranch", {"grouped": True})
row = next(row for row in dto["rows"] if row["id"] == "900")
self.assertTrue(row["feed_selected"])
self.assertEqual(row["feed_priority"], 1)
self.assertEqual(row["edits"]["feed_selected"]["path"], ["policy", "feed_targets", "900"])
self.assertEqual(row["edits"]["feed_selected"]["type"], "target")
self.assertEqual(self.engine.planner.feeding_target(self.engine.snapshot, self.engine.policy)[0]["id"], 900)
self.assertTrue(dto["groups"])
self.assertTrue(dto["feed_targets"])
self.assertNotIn("synthetic-secret", json.dumps(dto))
def test_mainline_default_current_and_filters_with_chinese_record_messages(self):
self.engine._progression_rows = [
{"task_type_id": "a", "category": "main", "state": "active", "name": "当前主线", "dialogue": "对话", "supported": True},
{"task_type_id": "b", "category": "mainline", "state": "completed", "name": "历史主线"},
{"task_type_id": "c", "category": "sidequest", "state": "received", "name": "支线"}]
self.assertEqual([row["name"] for row in self.view("mainline")["rows"]], ["当前主线"])
dto = self.view("mainline", {"category": "", "state": "", "search": "历史"})
self.assertEqual(dto["rows"][0]["state_label"], "已完成")
self.engine._progression_records = [{"battle_kind": "ordinary_stage", "outcome": "loss", "started_at": 0,
"battle_mode": "experimental", "damage_profile": "client_v4_x10", "message": "Unsupported monster controller: test", "response": {"token": "synthetic-secret"}}]
record = self.view("battles")
self.assertIn("打不过", record["rows"][0]["outcome_label"])
self.assertIn("尚未支持", record["rows"][0]["message"])
self.assertNotIn("synthetic-secret", json.dumps(record))
def test_exploration_three_members_options_and_diagnoses_use_planner(self):
snapshot = self.engine.snapshot
snapshot.raw["history"].update(passTask={"1001008": True}, passStage={"0101": {"1": True}})
snapshot.raw["exploreTeams"] = [{"id": 1, "status": 0}]
for mid, level in ((101, 30), (102, 10), (900, 20)):
snapshot.monsters[mid].update(process=3, level=level, mode=2)
self.engine.explore_planner = ExplorePlanner(self.engine.catalog, areas={"1": {"id": "1", "name": "测试地区", "passStage": "0101", "costTi": 10, "costTime": 3600, "level": [4, 1, 1], "team": "normal"}})
config = deepcopy(self.worker.config)
config["explore_policy"] = {"enabled": True, "reserve_ti": 2, "teams": {"1": {"enabled": True, "area": "1", "monsters": [101, 900, 102]}}}
self.worker.save_config(config)
dto = self.view("exploration")
row = dto["rows"][0]
self.assertEqual(row["monsters"], [101, 900, 102])
self.assertEqual(row["state"], "可出发")
self.assertEqual(row["edits"]["monsters"]["path"], ["explore_policy", "teams", "1", "monsters"])
protected = next(option for option in row["member_options"] if option["value"] == 900)
self.assertFalse(protected["automatic"])
self.assertFalse(protected["disabled"])
def test_maps_resources_show_ticket_cost_and_filter_difficulty_one(self):
snapshot = self.engine.snapshot
snapshot.raw["items"] += [{"id": 7000, "typeId": 20009, "num": 5}, {"id": 7001, "typeId": 20009, "num": 100, "lock": True}]
stages = [Stage("m101", str(level), "测试矿洞", 1, True, False, True, 10, "矿镐×2", city_name="测试地区", category="mine", battle_available=True) for level in (1, 2)]
self.engine.stage_cache.get = Mock(return_value=stages)
self.engine.stage_cache.catalog.data["stage_info"]["m101"] = {"cost": {"items": [{"typeId": 20009, "num": 2}]}}
self.engine.map_stage_reason = Mock(return_value="")
dto = self.view("maps", {"category": "resource"})
self.assertEqual(len(dto["rows"]), 1)
row = dto["rows"][0]
self.assertEqual(row["level"], "1")
self.assertEqual(row["costs"][1]["available"], 5)
self.assertEqual(row["costs"][1]["required"], 2)
self.assertIn("资源关开关", row["status"])
self.assertTrue(dto["groups"][0]["collapsed"])
self.assertEqual([option["value"] for option in row["edits"]["level"]["options"]], ["1"])
def test_statistics_all_event_and_known_stamina_follow_real_store(self):
store = self.engine.sweeper.statistics
owner = self.engine.snapshot.raw["master"]["id"]
for index, kind, amount, spent in ((1, "sweep", 2, 10), (2, "event", 3, 20), (3, "event", 7, None)):
store.record(owner, "0101", "3", kind, f"offline:{index}", index, {"money": 10, "items": [{"typeId": 30005, "num": amount}]}, spent)
dto = self.view("statistics", {"stage_id": "0101", "level": "3", "source": "all"})
row = next(row for row in dto["rows"] if row["typeId"] == "30005")
self.assertEqual(dto["totals"]["n"], 3)
self.assertEqual(dto["totals"]["spent"], 30)
self.assertEqual(row["rate"], 1)
self.assertAlmostEqual(row["per_stamina"], 5 / 30)
self.assertEqual(next(point for point in dto["chart"]["series"] if point["id"] == row["id"])["value"], 1)
self.assertEqual(self.view("statistics", {"stage": "0101", "source": "event"})["totals"]["n"], 2)
self.assertEqual(self.view("statistics", {"stage_id": "0101", "source": "sweep"})["totals"]["n"], 1)
with self.assertRaises(ValueError):
self.view("statistics", {"source": "challenge"})
def test_lock_sell_feed_are_core_operations_and_require_confirmation(self):
self.action("lock", monster_ids=[101])
self.assertTrue(self.engine.snapshot.monsters[101]["lock"])
self.action("unlock", monster_ids=[101])
self.assertFalse(self.engine.snapshot.monsters[101]["lock"])
with self.assertRaises(ValueError):
self.action("sell", monster_ids=[101])
self.action("sell", monster_ids=[101], confirm=True)
self.assertNotIn(101, self.engine.snapshot.monsters)
self.engine.snapshot.monsters[102].update(process=3, roomId=1, mode=2)
self.action("feed", monster_ids=[102], target_id=900, confirm=True)
self.assertNotIn(102, self.engine.snapshot.monsters)
with self.assertRaises(ValueError):
self.action("sell", monster_ids=[900], confirm=True)
def test_daily_refresh_is_preview_and_manual_selected_claims_use_ledger(self):
snapshot = self.engine.snapshot
yesterday = snapshot.now - 86400
snapshot.raw["activityHistory"] = {"dailyGift": {"dailyGiftCheckTime": yesterday * 1000,
"dailyGiftLevel": 1, "dailyGiftCount": 1}, "dailyCheck": {"checkDay": 1, "checkTime": yesterday * 1000}}
snapshot.raw["mails"] = [{"id": 12, "title": "离线测试", "createTime": snapshot.now * 1000,
"isGetReward": 0, "reward": {"money": 10}}]
config = deepcopy(self.worker.config)
config["daily_policy"]["selected"] = ["gift", "mail"]
self.worker.save_config(config)
self.action("refresh", page="daily")
self.assertFalse(self.engine.daily_ledger.state)
result = self.action("claim_daily")
self.assertIn("2 项", result["message"])
self.assertTrue(self.engine.daily_ledger.seen(snapshot, "gift"))
self.assertFalse(self.engine.daily_ledger.seen(snapshot, "check"))
self.assertTrue(self.engine.daily_ledger.seen(snapshot, "mail:12"))
self.assertIn("0 项", self.action("claim_daily")["message"])
def test_commission_rewards_restrictions_and_gift_representatives_are_real(self):
snapshot, catalog = self.engine.snapshot, self.engine.catalog
key = next(key for key, row in catalog.data["task_info"].items() if row.get("type") == 4 and row.get("steps"))
snapshot.raw["currentTasks"] = [{"id": 10000, "typeId": key, "curStep": 999}]
dto = self.view("commissions")
self.assertEqual(dto["rows"][0]["reward_ke"], catalog.data["task_info"][key]["reward"]["ke"])
self.assertEqual(dto["rows"][0]["reason"], "可领取奖励")
config = deepcopy(self.worker.config)
config["policy"].update(gift_enabled=True, gift_auto_representative=True)
self.worker.save_config(config)
dto = self.view("gifts")
self.assertEqual(dto["rows"][0]["monster_id"], 900)
self.assertEqual(dto["rows"][0]["likes"], catalog.likes_text(snapshot.monsters[900]["typeId"]))
def test_engine_failure_does_not_return_success_or_reuse_paid_quote(self):
quote = self.action("quote_expansion", kind="stack", currency="money", position=6)
self.engine.expand = Mock(side_effect=TimeoutError("offline unknown response"))
with self.assertRaises(TimeoutError):
self.action("expand", quote_id=quote["quote_id"], confirm=True)
with self.assertRaisesRegex(ValueError, "报价已失效"):
self.action("expand", quote_id=quote["quote_id"], confirm=True)
self.engine.expand.assert_called_once()
def test_expansion_quote_is_bound_one_use_and_cost_is_rechecked(self):
quote = self.action("quote_expansion", kind="stack", currency="money", position=6)
money = self.engine.snapshot.raw["master"]["money"]
with self.assertRaises(ValueError):
self.action("expand", quote_id=quote["quote_id"])
self.action("expand", quote_id=quote["quote_id"], confirm=True)
self.assertEqual(self.engine.snapshot.raw["master"]["money"], money - quote["cost"])
self.assertTrue(any(row["position"] == 6 for row in self.engine.snapshot.raw["stacks"]))
with self.assertRaises(ValueError):
self.action("expand", quote_id=quote["quote_id"], confirm=True)
quote = self.action("quote_expansion", kind="room", currency="money")
record = self.worker._web_expansion_quotes[quote["quote_id"]][1]
price = self.engine.catalog.data["room_price"][str(record.index)]
price["money"] = int(price["money"]) + 1
with self.assertRaisesRegex(ValueError, "费用或次数已变化"):
self.action("expand", quote_id=quote["quote_id"], confirm=True)
def test_import_csv_xlsx_is_transactional_and_never_accepts_disk_paths(self):
data = "编号,派遣金币,强化经验,孵化秒数\n1001010,999,18,120\n".encode("utf-8-sig")
result = self.action("import_yields", filename="data.csv", content_base64=base64.b64encode(data).decode())
self.assertEqual(result["count"], 1)
self.assertEqual(self.engine.catalog.monster(1001010)["sell_money"], 999)
old = deepcopy(self.worker.config)
data = b"typeId,sell_money\n1001010,nan\n"
with self.assertRaises(ValueError):
self.action("import_yields", filename="data.csv", content_base64=base64.b64encode(data).decode())
self.assertEqual(self.worker.config, old)
with self.assertRaises(ValueError):
self.action("import_yields", path="private-file.csv")
import openpyxl
workbook = openpyxl.Workbook()
workbook.active.append(["typeId", "sell_money"])
workbook.active.append([1001010, 123])
stream = io.BytesIO()
workbook.save(stream)
workbook.close()
result = self.action("import_yields", filename="data.xlsx", content_base64=base64.b64encode(stream.getvalue()).decode())
self.assertEqual(result["overrides"]["1001010"]["sell_money"], 123)
def test_import_only_saves_and_never_executes_a_plan(self):
self.worker.running = self.engine.auto = True
document = export_config(self.worker.config, self.engine.snapshot)
self.engine.poll = Mock(side_effect=AssertionError("import must not run"))
result = self.action("import_config", config=document)
self.assertIn("config", result)
self.assertFalse(self.engine.auto)
self.assertFalse(self.worker.running)
self.engine.poll.assert_not_called()
def test_reset_pending_requires_real_role_matched_evidence_and_keeps_journal(self):
pending = {"stage": "0101", "level": "3", "phase": "遇到事件或响应缺少事件状态,请在游戏内处理"}
self.engine.sweeper.state["pending"] = pending
with self.assertRaises(ValueError):
self.action("reset_map_pending", confirm=True, server_verified=True)
self.assertIs(self.engine.sweeper.state["pending"], pending)
trace = [
{"operation": "读取角色", "kind": "response", "body": {"master": {"id": 2}}},
{"operation": "stageService/stageStart", "kind": "request", "request_id": "offline:1", "body": {"stageTypeId": "0101", "stageLevel": "3"}},
{"operation": "stageService/stageStart", "kind": "response", "request_id": "offline:1", "http_status": 200,
"body": {"resCode": 0, "triggerEvent": True, "stageEvent": {"resCode": 0, "result": {"money": 10}}}},
]
self.worker.trace.path.write_text("\n".join(json.dumps(event) for event in trace), encoding="utf-8")
with self.assertRaises(ValueError):
self.action("reset_map_pending", confirm=True, server_verified=True)
trace[0]["body"]["master"]["id"] = 1
self.worker.trace.path.write_text("\n".join(json.dumps(event) for event in trace), encoding="utf-8")
result = self.action("reset_map_pending", confirm=True)
self.assertTrue(result["cleared"])
self.engine.sweeper.state["pending"] = pending
self.engine.battle_journal.pending = Mock(return_value={"kind": "map_battle", "phase": "unknown"})
with self.assertRaisesRegex(ValueError, "不能手动清除"):
self.action("reset_map_pending", confirm=True, server_verified=True)
self.assertIs(self.engine.sweeper.state["pending"], pending)
if __name__ == "__main__":
unittest.main()