561 lines
33 KiB
Python
561 lines
33 KiB
Python
"""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()
|