revert: restore the original pre-redesign web console
Revert688aad3,39ac03a,c84dc36, andff6a828in reverse chronological order. Restore the exact tracked tree from99aff42while preserving history. Validation: 29 authentication and base-path tests passed offline. All 23 prior UI browser tests ran in system Edge: 22 passed initially; the fake-login test passed on an unchanged isolated retry. Live game HTTP was blocked throughout browser validation.
This commit is contained in:
@@ -6,7 +6,6 @@ Only temporary demo accounts and a synthetic administrator password are used.
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
from pathlib import Path
|
||||
import socket
|
||||
import tempfile
|
||||
@@ -14,9 +13,8 @@ import threading
|
||||
import time
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
from .test_workbench_browser import AVAILABLE, EDGE, OfflineUpdates, assert_navigation
|
||||
from .test_workbench_browser import AVAILABLE, EDGE, OfflineUpdates
|
||||
|
||||
if AVAILABLE:
|
||||
from playwright.sync_api import expect
|
||||
@@ -83,11 +81,9 @@ class AdminLoginBrowserTests(unittest.TestCase):
|
||||
self.context.route("**/*", offline_only)
|
||||
self.page = self.context.new_page()
|
||||
self.requests = []
|
||||
self.script_requests = []
|
||||
self.errors = []
|
||||
self.csp_errors = []
|
||||
self.page.on("request", lambda request: self.requests.append(request.url))
|
||||
self.page.on("request", lambda request: self.script_requests.append(request.url) if request.resource_type == "script" else None)
|
||||
self.page.on("pageerror", lambda failure: self.errors.append(str(failure)))
|
||||
self.page.on("console", lambda message: self.csp_errors.append(message.text)
|
||||
if message.type == "error" and ("security policy" in message.text.lower() or "csp" in message.text.lower()) else None)
|
||||
@@ -102,7 +98,7 @@ class AdminLoginBrowserTests(unittest.TestCase):
|
||||
expect(page).to_have_url(self.base + "/login")
|
||||
expect(page.locator("#auth-form")).to_be_visible()
|
||||
expect(page.locator("#admin-password")).to_be_enabled()
|
||||
self.assertEqual(page.locator("#app, nav, #sidebar, #topbar, #account-select, #account-tabs, #page-tabs, #page-host, #auth-dialog").count(), 0)
|
||||
self.assertEqual(page.locator("#app, nav, #account-tabs, #page-tabs, #page-host, #auth-dialog").count(), 0)
|
||||
self.assertEqual(page.locator("script:not([src]), [style], [onclick], [onsubmit]").count(), 0)
|
||||
self.assertEqual(page.locator("script").count(), 1)
|
||||
expect(page.locator("script")).to_have_attribute("type", "module")
|
||||
@@ -116,15 +112,11 @@ class AdminLoginBrowserTests(unittest.TestCase):
|
||||
self.page.locator('#auth-form button[type="submit"]').click()
|
||||
self.assertEqual(pending.value.status, 200)
|
||||
self.assertEqual(pending.value.request.post_data_json, {"password": self.password})
|
||||
expect(self.page).to_have_url(re.compile("^" + re.escape(self.base + "/") + r"(?:#.*)?$"))
|
||||
expect(self.page).to_have_url(self.base + "/")
|
||||
expect(self.page.locator("#app")).to_be_visible()
|
||||
assert_navigation(self.page)
|
||||
expect(self.page.locator('.nav-link[data-page="overview"]')).to_have_attribute("aria-current", "page")
|
||||
expect(self.page.locator("#status-text")).to_contain_text("已连接")
|
||||
expect(self.page.locator("#page-tabs [role=tab]")).to_have_count(15)
|
||||
expect(self.page.locator("#status-text")).to_have_text("工作台已连接")
|
||||
self.assertEqual(self.page.locator("#auth-dialog, #auth-form").count(), 0)
|
||||
self.console_assets = self.page.locator('script[src], link[rel="stylesheet"], link[rel="modulepreload"]').evaluate_all(
|
||||
"nodes => nodes.map(node => node.src || node.href)")
|
||||
self.assertTrue(self.console_assets)
|
||||
|
||||
def observe_login_transition(self):
|
||||
snapshots = []
|
||||
@@ -155,16 +147,15 @@ class AdminLoginBrowserTests(unittest.TestCase):
|
||||
context.add_cookies(cookies)
|
||||
page = context.new_page()
|
||||
requested = []
|
||||
page.on("request", lambda request: requested.append(request.url) if request.resource_type == "script" else None)
|
||||
page.on("request", lambda request: requested.append(request.url))
|
||||
page.goto(self.base + "/", wait_until="networkidle")
|
||||
self.assert_login_only(page)
|
||||
self.assertEqual(requested, [self.base + "/static/login.js"])
|
||||
self.assertFalse(any(url.endswith("/static/app.js") for url in requested))
|
||||
response = context.request.get(self.base + "/static/index.html", max_redirects=0)
|
||||
self.assertIn(response.status, (302, 303, 307, 401, 403))
|
||||
self.assertNotIn('id="app"', response.text())
|
||||
for url in self.console_assets:
|
||||
response = context.request.get(url, max_redirects=0)
|
||||
self.assertIn(response.status, (302, 303, 307, 401, 403), url)
|
||||
response = context.request.get(self.base + "/static/app.js", max_redirects=0)
|
||||
self.assertIn(response.status, (302, 303, 307, 401, 403))
|
||||
|
||||
def test_fresh_root_serves_only_login_and_public_assets_with_csp(self):
|
||||
response = self.page.goto(self.base + "/", wait_until="networkidle")
|
||||
@@ -178,7 +169,7 @@ class AdminLoginBrowserTests(unittest.TestCase):
|
||||
self.assertIn(self.base + "/api/auth/status", self.requests)
|
||||
scripts = self.page.evaluate("performance.getEntriesByType('resource').filter(item => item.initiatorType === 'script').map(item => new URL(item.name).pathname)")
|
||||
self.assertEqual(scripts, ["/static/login.js"])
|
||||
self.assertEqual(self.script_requests, [self.base + "/static/login.js"])
|
||||
self.assertFalse(any(url.endswith(("/app.js", "/api.js", "/pages.js", "/dom.js", "/ui.js")) for url in self.requests))
|
||||
for width in (1280, 390):
|
||||
self.page.set_viewport_size({"width": width, "height": 800})
|
||||
self.assertLessEqual(self.page.evaluate("document.documentElement.scrollWidth"), width)
|
||||
@@ -194,10 +185,10 @@ class AdminLoginBrowserTests(unittest.TestCase):
|
||||
self.assertEqual(self.page.evaluate("localStorage.length + sessionStorage.length"), 0)
|
||||
self.assertNotIn(self.password, self.page.url)
|
||||
self.page.goto(self.base + "/login", wait_until="networkidle")
|
||||
self.assertEqual(urlsplit(self.page.url).path, "/")
|
||||
assert_navigation(self.page)
|
||||
expect(self.page).to_have_url(self.base + "/")
|
||||
expect(self.page.locator("#page-tabs [role=tab]")).to_have_count(15)
|
||||
snapshots = self.observe_login_transition()
|
||||
self.page.locator('.nav-link[data-page="system"]').click()
|
||||
self.page.locator(".menu > summary").first.click()
|
||||
self.page.locator('[data-command="admin-logout"]').click()
|
||||
self.assert_hidden_transition(snapshots)
|
||||
self.assert_login_only()
|
||||
@@ -216,13 +207,12 @@ class AdminLoginBrowserTests(unittest.TestCase):
|
||||
expect(self.page.locator("#admin-password")).to_be_focused()
|
||||
self.assert_login_only()
|
||||
self.assertEqual(self.page.evaluate("localStorage.length + sessionStorage.length"), 0)
|
||||
self.assertFalse(any("offline-wrong-admin-password" in url for url in self.requests))
|
||||
self.assertEqual(self.script_requests, [self.base + "/static/login.js"])
|
||||
self.assertFalse(any("offline-wrong-admin-password" in url or url.endswith("/app.js") for url in self.requests))
|
||||
|
||||
def test_expired_server_session_hides_workbench_and_rejects_old_cookie(self):
|
||||
self.login()
|
||||
cookies = self.context.cookies()
|
||||
self.page.locator('.nav-link[data-page="system"]').click()
|
||||
self.page.locator(".menu > summary").nth(3).click()
|
||||
self.page.locator('[data-command="about"]').click()
|
||||
expect(self.page.locator("#action-dialog")).to_be_visible()
|
||||
snapshots = self.observe_login_transition()
|
||||
@@ -243,8 +233,6 @@ class AdminLoginBrowserTests(unittest.TestCase):
|
||||
route.fulfill(status=401, content_type="application/json", body=json.dumps({"detail": "会话已失效"}))
|
||||
|
||||
self.page.route("**/api/accounts/*/actions/refresh", unauthorized)
|
||||
self.page.locator('.nav-link[data-page="login"]').click()
|
||||
expect(self.page.locator('.page-panel[data-page="login"]:not([hidden]) .page-loading[data-loading="false"]')).to_have_count(1)
|
||||
self.page.locator('#page-host input[type="password"]').fill("unsent-offline-game-password")
|
||||
self.page.locator("#refresh").click()
|
||||
self.assert_hidden_transition(snapshots)
|
||||
@@ -284,7 +272,7 @@ class AdminLoginBrowserTests(unittest.TestCase):
|
||||
response = page.goto(self.base + "/", wait_until="networkidle")
|
||||
expect(page).to_have_url(self.base + "/login")
|
||||
self.assertNotIn('id="app"', response.text())
|
||||
self.assertEqual(page.locator("#app, nav, #sidebar, #topbar, #account-select, #account-tabs, #page-tabs").count(), 0)
|
||||
self.assertEqual(page.locator("#app, nav, #account-tabs, #page-tabs").count(), 0)
|
||||
expect(page.locator("#auth-form")).to_be_visible()
|
||||
expect(page.locator("#auth-form button")).to_be_disabled()
|
||||
expect(page.locator("noscript")).to_be_visible()
|
||||
|
||||
@@ -6,7 +6,6 @@ Only disposable demo accounts and a synthetic administrator password are used.
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
import re
|
||||
import socket
|
||||
import tempfile
|
||||
import threading
|
||||
@@ -15,8 +14,7 @@ import unittest
|
||||
from unittest.mock import patch
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
from ranch_web.tests.test_api import FrontendAssets
|
||||
from .test_workbench_browser import AVAILABLE, EDGE, OfflineUpdates, GAME_PAGES, GLOBAL_PAGES, assert_navigation
|
||||
from .test_workbench_browser import AVAILABLE, EDGE, OfflineUpdates
|
||||
|
||||
if AVAILABLE:
|
||||
from playwright.sync_api import expect
|
||||
@@ -101,7 +99,7 @@ class BasePathBrowserTests(unittest.TestCase):
|
||||
expect(page.locator("#auth-form")).to_be_visible()
|
||||
expect(page.locator("#admin-password")).to_be_enabled()
|
||||
expect(page.locator("#auth-form")).to_have_attribute("action", prefix + "/api/auth/login")
|
||||
self.assertEqual(page.locator("#app, nav, #sidebar, #topbar, #account-select, #account-tabs, #page-tabs, #page-host").count(), 0)
|
||||
self.assertEqual(page.locator("#app, nav, #account-tabs, #page-tabs, #page-host").count(), 0)
|
||||
self.assertEqual(page.locator("script").count(), 1)
|
||||
expect(page.locator("script")).to_have_attribute("src", prefix + "/static/login.js")
|
||||
expect(page.locator('link[rel="stylesheet"]')).to_have_attribute("href", prefix + "/static/login.css")
|
||||
@@ -120,45 +118,26 @@ class BasePathBrowserTests(unittest.TestCase):
|
||||
page.locator('#auth-form button[type="submit"]').click()
|
||||
self.assertEqual(login.value.status, 200)
|
||||
self.assertEqual(login.value.request.post_data_json, {"password": self.password})
|
||||
expect(page).to_have_url(re.compile("^" + re.escape(base + "/") + r"(?:#.*)?$"))
|
||||
expect(page).to_have_url(base + "/")
|
||||
expect(page.locator("#app")).to_be_visible()
|
||||
assert_navigation(page)
|
||||
expect(page.locator("#status-text")).to_contain_text("已连接")
|
||||
expect(page.locator("#status-text")).to_have_text("工作台已连接")
|
||||
expect(page.locator("#save-status")).to_have_text("策略已自动保存")
|
||||
assets = FrontendAssets(page.content())
|
||||
self.assertTrue(assets.scripts)
|
||||
self.assertTrue(assets.stylesheets)
|
||||
for url in assets.urls:
|
||||
self.assertTrue(url.startswith(prefix + "/static/"), url)
|
||||
self.assertNotIn(prefix + prefix, url)
|
||||
response = context.request.get(origin + url)
|
||||
self.assertEqual(response.status, 200, url)
|
||||
expect(page.locator('link[rel="stylesheet"]')).to_have_attribute("href", prefix + "/static/styles.css")
|
||||
self.assertEqual(context.cookies()[0]["path"], prefix or "/")
|
||||
self.assertEqual(page.evaluate("localStorage.length + sessionStorage.length"), 0)
|
||||
|
||||
for key in GAME_PAGES:
|
||||
page.locator(f'.nav-link[data-page="{key}"]').click()
|
||||
for key in "login incubator bag ranch daily hatching mainline battles gifts commissions exploration maps statistics plans yields".split():
|
||||
page.locator(f'.page-tab[data-page="{key}"]').click()
|
||||
panel = page.locator(f'.page-panel[data-page="{key}"]:not([hidden])')
|
||||
expect(panel.locator('.page-loading[data-loading="false"]')).to_have_count(1)
|
||||
self.assertEqual(panel.locator(".page-error:not([hidden])").count(), 0)
|
||||
if key == "bag":
|
||||
route_url = page.url
|
||||
self.assertEqual(urlsplit(route_url).fragment, f"/accounts/{account}/bag")
|
||||
page.reload(wait_until="networkidle")
|
||||
expect(page).to_have_url(route_url)
|
||||
expect(page.locator("#account-select")).to_have_value(account)
|
||||
expect(page.locator('.nav-link[data-page="bag"]')).to_have_attribute("aria-current", "page")
|
||||
expect(panel.locator('.page-loading[data-loading="false"]')).to_have_count(1)
|
||||
for key in GLOBAL_PAGES:
|
||||
page.locator(f'.nav-link[data-page="{key}"]').click()
|
||||
expect(page.locator(f'.nav-link[data-page="{key}"]')).to_have_attribute("aria-current", "page")
|
||||
|
||||
# The server redirects an authenticated login URL back to this workbench.
|
||||
page.goto(base + "/login", wait_until="networkidle")
|
||||
self.assertEqual(urlsplit(page.url).path, prefix + "/")
|
||||
expect(page.locator("#status-text")).to_contain_text("已连接")
|
||||
expect(page).to_have_url(base + "/")
|
||||
expect(page.locator("#status-text")).to_have_text("工作台已连接")
|
||||
cookies = context.cookies()
|
||||
page.locator('.nav-link[data-page="system"]').click()
|
||||
page.locator(".menu > summary").first.click()
|
||||
with page.expect_response(base + "/api/auth/logout") as logout:
|
||||
page.locator('[data-command="admin-logout"]').click()
|
||||
self.assertEqual(logout.value.status, 200)
|
||||
@@ -169,8 +148,7 @@ class BasePathBrowserTests(unittest.TestCase):
|
||||
assert_login()
|
||||
self.assertEqual(escapes, [], "Browser requests escaped the configured prefix or local server")
|
||||
self.assertEqual(errors, [], "JavaScript or CSP errors")
|
||||
for url, _ in assets.scripts:
|
||||
self.assertTrue(any(request.url == origin + url for request in requests), url)
|
||||
self.assertTrue(any(request.url == base + "/static/paths.js" for request in requests))
|
||||
|
||||
def test_preserved_prefix(self):
|
||||
self.check_deployment("/ranch")
|
||||
|
||||
@@ -18,7 +18,6 @@ import tempfile
|
||||
import threading
|
||||
import time
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
from urllib.parse import parse_qs, urlsplit
|
||||
|
||||
|
||||
@@ -28,20 +27,6 @@ if AVAILABLE:
|
||||
from playwright.sync_api import expect
|
||||
|
||||
|
||||
GAME_PAGES = "login incubator bag ranch daily hatching mainline battles gifts commissions exploration maps statistics plans yields".split()
|
||||
GLOBAL_PAGES = ["overview", "accounts", "activity", "system"]
|
||||
|
||||
|
||||
def assert_navigation(page):
|
||||
expect(page.locator("#sidebar")).to_be_visible()
|
||||
expect(page.locator("#topbar")).to_be_visible()
|
||||
expect(page.locator("#sidebar .nav-link[data-page]")).to_have_count(len(GAME_PAGES) + len(GLOBAL_PAGES))
|
||||
for key in GAME_PAGES + GLOBAL_PAGES:
|
||||
expect(page.locator(f'#sidebar .nav-link[data-page="{key}"]')).to_have_count(1)
|
||||
expect(page.locator("#account-select")).to_have_attribute("aria-label", "当前游戏账号")
|
||||
expect(page.get_by_role("combobox", name="当前游戏", exact=True)).to_have_count(0)
|
||||
|
||||
|
||||
class OfflineUpdates:
|
||||
def status(self):
|
||||
return {"current_version": "2.0.0.dev1", "latest_version": None, "status": "unchecked",
|
||||
@@ -59,9 +44,6 @@ class WorkbenchBrowserTests(unittest.TestCase):
|
||||
from ranch_web.config import WebConfig
|
||||
from ranch_web.service import WebManager
|
||||
|
||||
cls.network = patch("requests.sessions.Session.request", side_effect=AssertionError("Live HTTP is forbidden"))
|
||||
cls.network.start()
|
||||
cls.addClassCleanup(cls.network.stop)
|
||||
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"]
|
||||
@@ -104,18 +86,10 @@ class WorkbenchBrowserTests(unittest.TestCase):
|
||||
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.external_requests = []
|
||||
def offline_only(route):
|
||||
if route.request.url.startswith(self.base + "/"):
|
||||
route.continue_()
|
||||
else:
|
||||
self.external_requests.append(route.request.url)
|
||||
route.abort()
|
||||
self.context.route("**/*", offline_only)
|
||||
self.context.route("https://**", lambda route: route.abort())
|
||||
|
||||
def tearDown(self):
|
||||
self.context.close()
|
||||
self.assertEqual(self.external_requests, [], "Browser requests must stay on the offline server")
|
||||
|
||||
def await_job(self, identifier, job_id):
|
||||
deadline = time.monotonic() + 10
|
||||
@@ -130,30 +104,15 @@ class WorkbenchBrowserTests(unittest.TestCase):
|
||||
def open(self, page=None):
|
||||
page=page or self.page
|
||||
page.goto(self.base, wait_until="networkidle")
|
||||
page.locator('#account-select').select_option(self.first)
|
||||
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'#sidebar .nav-link[data-page="{key}"]').click()
|
||||
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])')
|
||||
|
||||
def global_page(self, key, page=None):
|
||||
page = page or self.page
|
||||
page.locator(f'#sidebar .nav-link[data-page="{key}"]').click()
|
||||
expect(page.locator(f'#sidebar .nav-link[data-page="{key}"]')).to_have_attribute("aria-current", "page")
|
||||
expect(page.locator("#page-host .page-panel:not([hidden])")).to_have_count(0)
|
||||
|
||||
def system_command(self, name):
|
||||
self.global_page("system")
|
||||
self.page.locator(f'[data-command="{name}"]').click()
|
||||
|
||||
def edit_and_save(self, field, value):
|
||||
with self.page.expect_response(lambda response: response.request.method == "PUT" and response.url.endswith("/config")):
|
||||
field.fill(value)
|
||||
self.wait_saved()
|
||||
|
||||
@staticmethod
|
||||
def field(root,path):
|
||||
return root.locator("[data-config-path='"+json.dumps(path,separators=(',',':'))+"']")
|
||||
@@ -167,10 +126,9 @@ class WorkbenchBrowserTests(unittest.TestCase):
|
||||
|
||||
def test_local_no_password_login_route_returns_to_workbench(self):
|
||||
self.page.goto(self.base + "/login", wait_until="networkidle")
|
||||
self.assertEqual(urlsplit(self.page.url).path, "/")
|
||||
expect(self.page).to_have_url(self.base + "/")
|
||||
expect(self.page.locator("#app")).to_be_visible()
|
||||
assert_navigation(self.page)
|
||||
expect(self.page.locator('.nav-link[data-page="overview"]')).to_have_attribute("aria-current", "page")
|
||||
expect(self.page.locator("#page-tabs [role=tab]")).to_have_count(15)
|
||||
self.assertEqual(self.page.locator("#auth-dialog, #auth-form").count(), 0)
|
||||
self.assertEqual(self.errors, [])
|
||||
|
||||
@@ -178,8 +136,8 @@ class WorkbenchBrowserTests(unittest.TestCase):
|
||||
self.open()
|
||||
writes = []
|
||||
self.page.on("request", lambda request: writes.append(request.url) if request.method in ("POST", "PUT", "DELETE") else None)
|
||||
assert_navigation(self.page)
|
||||
for key in GAME_PAGES:
|
||||
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':
|
||||
@@ -195,16 +153,14 @@ class WorkbenchBrowserTests(unittest.TestCase):
|
||||
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)
|
||||
for key in GLOBAL_PAGES:
|
||||
self.global_page(key)
|
||||
self.assertEqual(writes, [], "Switching pages must not submit game or configuration actions")
|
||||
expect(self.page.locator('.nav-link[data-page="statistics"]')).to_contain_text("数据分析")
|
||||
expect(self.page.locator('.nav-link[data-page="plans"]')).to_contain_text("执行计划")
|
||||
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("#topbar").is_visible())
|
||||
self.assertTrue(self.page.locator("#page-tabs").is_visible())
|
||||
self.assertLessEqual(self.page.evaluate("document.documentElement.scrollWidth"), width)
|
||||
self.assertEqual(self.errors, [])
|
||||
|
||||
@@ -229,266 +185,15 @@ class WorkbenchBrowserTests(unittest.TestCase):
|
||||
self.wait_saved()
|
||||
self.page.locator("#strategy-toggle").click()
|
||||
expect(self.page.locator('#strategy-toggle')).to_have_text('停止')
|
||||
expect(self.page.locator('.workspace-meta')).to_contain_text('策略运行中')
|
||||
self.assertTrue(self.manager.status(self.first)["running"])
|
||||
self.page.locator("#strategy-toggle").click()
|
||||
expect(self.page.locator('#strategy-toggle')).to_have_text('开启')
|
||||
self.page.locator('#account-select').select_option(self.second)
|
||||
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('#account-select').select_option(self.first)
|
||||
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_account_routes_restore_back_reload_and_isolated_configuration(self):
|
||||
self.open()
|
||||
panel = self.go("bag")
|
||||
species = panel.locator("tbody tr[data-row-id]").first.get_attribute("data-row-id")
|
||||
cell = f'tr[data-row-id="{species}"] td[data-column="priority"] input'
|
||||
self.edit_and_save(panel.locator(cell), "31")
|
||||
first_url = self.page.url
|
||||
self.assertEqual(urlsplit(first_url).fragment, f"/accounts/{self.first}/bag")
|
||||
|
||||
self.page.locator("#account-select").select_option(self.second)
|
||||
expect(self.page.locator("#save-status")).to_have_text("策略已自动保存")
|
||||
panel = self.go("bag")
|
||||
self.assertNotEqual(panel.locator(cell).input_value(), "31")
|
||||
self.edit_and_save(panel.locator(cell), "47")
|
||||
second_url = self.page.url
|
||||
self.assertEqual(urlsplit(second_url).fragment, f"/accounts/{self.second}/bag")
|
||||
self.assertNotEqual(first_url, second_url, "Routes must identify the selected account")
|
||||
self.go("statistics")
|
||||
self.assertNotEqual(self.page.url, second_url, "Routes must identify the current page")
|
||||
|
||||
self.page.go_back()
|
||||
expect(self.page).to_have_url(second_url)
|
||||
expect(self.page.locator("#account-select")).to_have_value(self.second)
|
||||
expect(self.page.locator('.page-panel[data-page="bag"]:not([hidden])').locator(cell)).to_have_value("47")
|
||||
self.page.go_back()
|
||||
expect(self.page).to_have_url(first_url)
|
||||
expect(self.page.locator("#account-select")).to_have_value(self.first)
|
||||
expect(self.page.locator('.page-panel[data-page="bag"]:not([hidden])').locator(cell)).to_have_value("31")
|
||||
self.page.reload(wait_until="networkidle")
|
||||
expect(self.page).to_have_url(first_url)
|
||||
expect(self.page.locator("#account-select")).to_have_value(self.first)
|
||||
expect(self.page.locator('.nav-link[data-page="bag"]')).to_have_attribute("aria-current", "page")
|
||||
expect(self.page.locator('.page-panel[data-page="bag"]:not([hidden])').locator(cell)).to_have_value("31")
|
||||
self.assertEqual(self.manager.get_config(self.first)["config"]["policy"]["egg_rules"][species]["priority"], 31)
|
||||
self.assertEqual(self.manager.get_config(self.second)["config"]["policy"]["egg_rules"][species]["priority"], 47)
|
||||
self.assertEqual(self.errors, [])
|
||||
|
||||
def test_overview_stop_targets_its_row_without_changing_selected_account(self):
|
||||
self.open()
|
||||
panel = self.go("bag")
|
||||
with self.page.expect_response(lambda response: response.request.method == "PUT" and response.url.endswith("/config")):
|
||||
panel.locator('tbody tr[data-row-id] td[data-column="enabled"] input').first.check()
|
||||
self.wait_saved()
|
||||
response = self.manager.set_config(self.second, self.manager.get_config(self.first)["config"])
|
||||
self.await_job(self.second, response["job_id"])
|
||||
for identifier in (self.first, self.second):
|
||||
job = self.manager.submit(identifier, "start")
|
||||
self.await_job(identifier, job["id"])
|
||||
self.open()
|
||||
self.global_page("overview")
|
||||
actions = []
|
||||
self.page.on("request", lambda request: actions.append(urlsplit(request.url).path)
|
||||
if request.method == "POST" and "/actions/" in request.url else None)
|
||||
row = self.page.locator(f'tr[data-account="{self.second}"]:visible')
|
||||
expect(row).to_have_count(1)
|
||||
row.get_by_role("button", name="停止账号二策略", exact=True).click()
|
||||
expect(row.get_by_role("button", name="开启账号二策略", exact=True)).to_be_visible()
|
||||
expect(self.page.locator("#account-select")).to_have_value(self.first)
|
||||
self.assertTrue(self.manager.status(self.first)["running"], "The selected account must keep running")
|
||||
self.assertFalse(self.manager.status(self.second)["running"])
|
||||
self.assertEqual(actions, [f"/api/accounts/{self.second}/actions/stop"])
|
||||
self.assertEqual(self.errors, [])
|
||||
|
||||
def test_mobile_sidebar_opens_navigates_closes_and_supports_escape(self):
|
||||
self.open()
|
||||
self.go("bag")
|
||||
sidebar = self.page.locator("#sidebar")
|
||||
for width in (1280, 1600):
|
||||
self.page.set_viewport_size({"width": width, "height": 900})
|
||||
expect(sidebar).to_be_visible()
|
||||
self.assertLessEqual(self.page.evaluate("document.documentElement.scrollWidth"), width)
|
||||
self.page.set_viewport_size({"width": 390, "height": 844})
|
||||
toggle = self.page.locator('button[aria-controls="sidebar"]')
|
||||
expect(toggle).to_be_visible()
|
||||
expect(toggle).to_have_attribute("aria-expanded", "false")
|
||||
toggle.click()
|
||||
expect(toggle).to_have_attribute("aria-expanded", "true")
|
||||
expect(sidebar).to_be_visible()
|
||||
self.go("ranch")
|
||||
expect(toggle).to_have_attribute("aria-expanded", "false")
|
||||
expect(self.page.locator('.nav-link[data-page="ranch"]')).to_have_attribute("aria-current", "page")
|
||||
expect(self.page.locator("#strategy-toggle")).to_be_visible()
|
||||
self.assertLessEqual(self.page.evaluate("document.documentElement.scrollWidth"), 390)
|
||||
toggle.focus()
|
||||
self.page.keyboard.press("Enter")
|
||||
expect(toggle).to_have_attribute("aria-expanded", "true")
|
||||
self.page.keyboard.press("Escape")
|
||||
expect(toggle).to_have_attribute("aria-expanded", "false")
|
||||
self.page.set_viewport_size({"width": 1280, "height": 800})
|
||||
expect(sidebar).to_be_visible()
|
||||
self.assertEqual(self.errors, [])
|
||||
|
||||
def test_inflight_config_save_keeps_its_account_after_switch(self):
|
||||
held = []
|
||||
def delay_first_save(route):
|
||||
if route.request.method == "PUT":
|
||||
held.append(route)
|
||||
else:
|
||||
route.continue_()
|
||||
self.page.route(f"**/api/accounts/{self.first}/config", delay_first_save)
|
||||
self.open()
|
||||
panel = self.go("bag")
|
||||
species = panel.locator("tbody tr[data-row-id]").first.get_attribute("data-row-id")
|
||||
cell = f'tr[data-row-id="{species}"] td[data-column="priority"] input'
|
||||
panel.locator(cell).fill("29")
|
||||
self.page.locator("#account-select").select_option(self.second)
|
||||
expect(self.page.locator("#account-select")).to_have_value(self.second)
|
||||
expect(self.page.locator("#save-status")).to_have_text("策略已自动保存")
|
||||
panel = self.go("bag")
|
||||
self.assertNotEqual(panel.locator(cell).input_value(), "29")
|
||||
self.edit_and_save(panel.locator(cell), "43")
|
||||
self.assertEqual(len(held), 1, "Switching accounts must flush the previous account's draft")
|
||||
self.assertEqual(held[0].request.post_data_json["config"]["policy"]["egg_rules"][species]["priority"], 29)
|
||||
with self.page.expect_response(lambda response: response.request.method == "PUT" and response.url.endswith(f"/{self.first}/config")) as pending:
|
||||
held[0].continue_()
|
||||
saved = pending.value.json()
|
||||
if saved.get("job_id"):
|
||||
self.await_job(self.first, saved["job_id"])
|
||||
expect(self.page.locator("#account-select")).to_have_value(self.second)
|
||||
expect(panel.locator(cell)).to_have_value("43")
|
||||
self.assertEqual(self.manager.get_config(self.first)["config"]["policy"]["egg_rules"][species]["priority"], 29)
|
||||
self.assertEqual(self.manager.get_config(self.second)["config"]["policy"]["egg_rules"][species]["priority"], 43)
|
||||
self.page.locator("#account-select").select_option(self.first)
|
||||
expect(self.page.locator("#save-status")).to_have_text("策略已自动保存")
|
||||
expect(self.go("bag").locator(cell)).to_have_value("29")
|
||||
self.assertEqual(self.errors, [])
|
||||
|
||||
def test_invalid_numeric_draft_blocks_start_and_recovers_after_correction(self):
|
||||
self.open()
|
||||
panel = self.go("bag")
|
||||
with self.page.expect_response(lambda response: response.request.method == "PUT" and response.url.endswith("/config")):
|
||||
panel.locator('tbody tr[data-row-id] td[data-column="enabled"] input').first.check()
|
||||
self.wait_saved()
|
||||
priority = panel.locator('tbody tr[data-row-id] td[data-column="priority"] input').first
|
||||
writes = []
|
||||
self.page.on("request", lambda request: writes.append((request.method, request.url))
|
||||
if request.method in ("PUT", "POST") else None)
|
||||
with self.page.expect_response(lambda response: "/views/bag?" in response.url, timeout=10000):
|
||||
priority.fill("-1")
|
||||
original = priority.element_handle()
|
||||
expect(priority).to_have_value("-1")
|
||||
self.assertTrue(priority.evaluate("(node, original) => node === original", original))
|
||||
self.assertFalse(priority.evaluate("node => node.validity.valid"))
|
||||
self.page.locator("#strategy-toggle").click()
|
||||
self.page.wait_for_timeout(750)
|
||||
self.assertEqual(writes, [], "Invalid input must never be saved or start a strategy")
|
||||
self.assertFalse(self.manager.status(self.first)["running"])
|
||||
self.edit_and_save(priority, "19")
|
||||
self.page.locator("#strategy-toggle").click()
|
||||
expect(self.page.locator("#strategy-toggle")).to_have_text("停止")
|
||||
expect(self.page.locator('.workspace-meta')).to_contain_text('策略运行中')
|
||||
self.assertTrue(self.manager.status(self.first)["running"])
|
||||
self.page.locator("#strategy-toggle").click()
|
||||
expect(self.page.locator("#strategy-toggle")).to_have_text("开启")
|
||||
self.assertEqual(self.errors, [])
|
||||
|
||||
def test_stop_cancels_start_waiting_for_config_save(self):
|
||||
held, actions = [], []
|
||||
def delay_save(route):
|
||||
if route.request.method == "PUT":
|
||||
held.append(route)
|
||||
else:
|
||||
route.continue_()
|
||||
self.page.route(f"**/api/accounts/{self.first}/config", delay_save)
|
||||
self.open()
|
||||
panel = self.go("bag")
|
||||
priority = panel.locator('tbody tr[data-row-id] td[data-column="priority"] input').first
|
||||
self.page.on("request", lambda request: actions.append(urlsplit(request.url).path)
|
||||
if request.method == "POST" and "/actions/" in request.url else None)
|
||||
with self.page.expect_request(lambda request: request.method == "PUT" and request.url.endswith(f"/{self.first}/config")):
|
||||
priority.fill("37")
|
||||
self.page.locator("#strategy-toggle").click()
|
||||
expect(self.page.locator("#strategy-toggle")).to_have_text("停止")
|
||||
with self.page.expect_response(f"**/api/accounts/{self.first}/actions/stop") as stopped:
|
||||
self.page.locator("#strategy-toggle").click()
|
||||
self.await_job(self.first, stopped.value.json()["id"])
|
||||
self.assertEqual(len(held), 1, "Stop must complete while the config request remains blocked")
|
||||
self.assertEqual(actions, [f"/api/accounts/{self.first}/actions/stop"])
|
||||
with self.page.expect_response(lambda response: response.request.method == "PUT" and response.url.endswith(f"/{self.first}/config")) as saved:
|
||||
held[0].continue_()
|
||||
value = saved.value.json()
|
||||
if value.get("job_id"):
|
||||
self.await_job(self.first, value["job_id"])
|
||||
self.page.wait_for_timeout(1200)
|
||||
self.assertEqual(actions, [f"/api/accounts/{self.first}/actions/stop"], "A cancelled start must not resume after its save")
|
||||
self.assertFalse(self.manager.status(self.first)["running"])
|
||||
expect(self.page.locator("#strategy-toggle")).to_have_text("开启")
|
||||
self.assertEqual(self.errors, [])
|
||||
|
||||
def test_thousand_rows_bound_dom_and_preserve_pagination_sort_selection_and_filter(self):
|
||||
rows = [{"id": str(index), "name": f"离线魔物{index:04d}", "score": 1001 - index,
|
||||
"priority": (index - 1) % 999 + 1} for index in range(1, 1001)]
|
||||
writes = []
|
||||
def fixture(route):
|
||||
query = json.loads(parse_qs(urlsplit(route.request.url).query)["query"][0])
|
||||
search = query.get("search", "")
|
||||
self.fulfill(route, {"loading": False, "data": {
|
||||
"page": "bag", "title": "背包", "summary": "一千行离线分页回归", "form": [], "actions": [],
|
||||
"filters": [{"key": "search", "label": "搜索名称", "type": "text", "value": search}],
|
||||
"columns": [{"key": "name", "label": "名称"}, {"key": "score", "label": "分值"},
|
||||
{"key": "priority", "label": "优先级", "edit": {
|
||||
"path": ["policy", "egg_rules", "{id}", "priority"], "type": "integer", "min": 1, "max": 999}}],
|
||||
"rows": [row for row in rows if search in row["name"]],
|
||||
}})
|
||||
self.page.route(f"**/api/accounts/{self.first}/views/bag?*", fixture)
|
||||
self.open()
|
||||
self.page.on("request", lambda request: writes.append(request.url) if request.method in ("PUT", "POST", "DELETE") else None)
|
||||
panel = self.go("bag")
|
||||
body = panel.locator("tbody tr[data-row-id]")
|
||||
pager = panel.get_by_role("navigation", name="表格分页", exact=True)
|
||||
expect(panel.get_by_label("每页条目数", exact=True)).to_have_value("50")
|
||||
expect(body).to_have_count(50)
|
||||
expect(panel.locator('tbody input[type="number"]')).to_have_count(50)
|
||||
expect(body.first).to_have_attribute("data-row-id", "1")
|
||||
panel.get_by_role("checkbox", name="选择本页全部 50 项", exact=True).check()
|
||||
expect(panel.locator(".table-selection-summary")).to_contain_text("已选择 50 项")
|
||||
pager.get_by_role("button", name="下一页", exact=True).click()
|
||||
expect(body).to_have_count(50)
|
||||
expect(body.first).to_have_attribute("data-row-id", "51")
|
||||
body.first.locator(".selection-cell input").check()
|
||||
expect(panel.locator(".table-selection-summary")).to_contain_text("已选择 51 项")
|
||||
pager.get_by_role("button", name="上一页", exact=True).click()
|
||||
expect(body.first.locator(".selection-cell input")).to_be_checked()
|
||||
pager.get_by_role("button", name="全选筛选结果(1000 项,含其他分页)", exact=True).click()
|
||||
expect(panel.locator(".table-selection-summary")).to_contain_text("已选择 1000 项")
|
||||
expect(body).to_have_count(50)
|
||||
expect(panel.locator('tbody input[type="number"]')).to_have_count(50)
|
||||
pager.get_by_role("button", name="清除选择", exact=True).click()
|
||||
expect(panel.locator('tbody tr[aria-selected="true"]')).to_have_count(0)
|
||||
panel.locator('th[data-column="score"] button').click()
|
||||
expect(body.first).to_have_attribute("data-row-id", "1000")
|
||||
expect(body.last).to_have_attribute("data-row-id", "951")
|
||||
pager.get_by_role("button", name="末页", exact=True).click()
|
||||
expect(panel.get_by_label("当前页码", exact=True)).to_have_value("20")
|
||||
expect(body.first).to_have_attribute("data-row-id", "50")
|
||||
expect(body.last).to_have_attribute("data-row-id", "1")
|
||||
panel.get_by_label("每页条目数", exact=True).select_option("100")
|
||||
expect(body).to_have_count(100)
|
||||
expect(panel.locator('tbody input[type="number"]')).to_have_count(100)
|
||||
expect(panel.get_by_label("当前页码", exact=True)).to_have_value("10")
|
||||
expect(body.first).to_have_attribute("data-row-id", "100")
|
||||
panel.get_by_label("搜索名称", exact=True).fill("离线魔物0001")
|
||||
expect(body).to_have_count(1)
|
||||
expect(body.first).to_have_attribute("data-row-id", "1")
|
||||
expect(panel.get_by_label("当前页码", exact=True)).to_have_value("1")
|
||||
expect(pager.get_by_role("button", name="下一页", exact=True)).to_be_disabled()
|
||||
self.assertEqual(writes, [], "Paging, sorting, selecting and filtering must be read only")
|
||||
self.assertEqual(self.errors, [])
|
||||
|
||||
def test_exploration_keeps_partial_drafts_and_saves_only_three_or_auto(self):
|
||||
from ranch_web.policies import default_config
|
||||
|
||||
@@ -566,14 +271,12 @@ class WorkbenchBrowserTests(unittest.TestCase):
|
||||
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.global_page("activity")
|
||||
self.page.locator("#debug-log").check()
|
||||
self.page.wait_for_selector(".activity-line button.inspectable")
|
||||
entry = self.page.locator('.activity-line:has(button.inspectable)')
|
||||
expect(entry.locator('.log-time')).to_have_text('15:08:09')
|
||||
expect(entry.locator('.log-time')).to_have_attribute('title','2026-11-10T07:08:09Z')
|
||||
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, [])
|
||||
entry.locator("button.inspectable").first.click()
|
||||
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, [])
|
||||
@@ -600,14 +303,15 @@ class WorkbenchBrowserTests(unittest.TestCase):
|
||||
from ranch_assistant.model import Catalog
|
||||
|
||||
self.open()
|
||||
self.page.locator('.menu > summary').nth(2).click()
|
||||
with self.page.expect_download() as pending:
|
||||
self.system_command("export-config")
|
||||
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)
|
||||
yields = self.go("yields")
|
||||
self.page.locator('.menu > summary').nth(2).click()
|
||||
with self.page.expect_download() as pending:
|
||||
yields.locator('button[data-operation="download_yields"]').click()
|
||||
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()))
|
||||
@@ -696,13 +400,11 @@ class WorkbenchBrowserTests(unittest.TestCase):
|
||||
second.route(f'**/api/accounts/{self.first}/views/maps?*',map_view)
|
||||
self.open(second)
|
||||
panel_b=self.go('maps',second)
|
||||
second.bring_to_front()
|
||||
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)
|
||||
self.page.bring_to_front()
|
||||
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()
|
||||
@@ -765,7 +467,8 @@ class WorkbenchBrowserTests(unittest.TestCase):
|
||||
self.page.route('**/api/system/updates',updates)
|
||||
self.page.route('**/api/system/updates/apply',apply)
|
||||
self.open()
|
||||
self.system_command("updates")
|
||||
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()
|
||||
|
||||
@@ -4,7 +4,6 @@ import asyncio
|
||||
import base64
|
||||
from copy import deepcopy
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from html.parser import HTMLParser
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
@@ -23,29 +22,6 @@ from ranch_web.app import create_app
|
||||
from ranch_web.config import WebConfig
|
||||
|
||||
|
||||
class FrontendAssets(HTMLParser):
|
||||
"""Read the built entry so tests also exercise hashed asset URLs."""
|
||||
|
||||
def __init__(self, content):
|
||||
super().__init__()
|
||||
self.scripts, self.stylesheets, self.preloads = [], [], []
|
||||
self.feed(content)
|
||||
|
||||
def handle_starttag(self, tag, attrs):
|
||||
attrs = dict(attrs)
|
||||
if tag == "script" and attrs.get("src"):
|
||||
self.scripts.append((attrs["src"], attrs.get("type")))
|
||||
if tag == "link" and attrs.get("href"):
|
||||
if attrs.get("rel") == "stylesheet":
|
||||
self.stylesheets.append(attrs["href"])
|
||||
elif attrs.get("rel") == "modulepreload":
|
||||
self.preloads.append(attrs["href"])
|
||||
|
||||
@property
|
||||
def urls(self):
|
||||
return [url for url, _ in self.scripts] + self.stylesheets + self.preloads
|
||||
|
||||
|
||||
class FakeUpdates:
|
||||
def __init__(self):
|
||||
self.calls = []
|
||||
@@ -537,28 +513,15 @@ class ApiTests(unittest.TestCase):
|
||||
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)
|
||||
entry = self.client.get("/")
|
||||
assets = FrontendAssets(entry.text)
|
||||
self.assertTrue(assets.scripts, "The console entry must reference its built JavaScript")
|
||||
self.assertTrue(assets.stylesheets, "The console must load its stylesheet under CSP")
|
||||
self.assertTrue(all(kind == "module" for _, kind in assets.scripts))
|
||||
for url in assets.urls:
|
||||
self.assertTrue(url.startswith("/static/"), url)
|
||||
for url in ("/", "/static/index.html", *assets.urls):
|
||||
for url in ("/", "/static/index.html", "/static/app.js"):
|
||||
response = self.client.get(url)
|
||||
self.assertEqual(response.status_code, 200, url)
|
||||
if url not in assets.stylesheets:
|
||||
self.assertEqual(response.headers["cache-control"], "no-store")
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.assertEqual(response.headers["cache-control"], "no-store")
|
||||
self.assertEqual(response.headers["x-content-type-options"], "nosniff")
|
||||
self.assertIn("frame-ancestors 'none'", response.headers["content-security-policy"])
|
||||
if url in [script for script, _ in assets.scripts] or url in assets.preloads:
|
||||
self.assertIn("javascript", response.headers["content-type"], url)
|
||||
elif url in assets.stylesheets:
|
||||
self.assertIn("text/css", response.headers["content-type"], url)
|
||||
for url in ("/", "/static/index.html"):
|
||||
response = self.client.get(url)
|
||||
self.assertIn("text/html", response.headers["content-type"])
|
||||
self.assertEqual(FrontendAssets(response.text).urls, assets.urls)
|
||||
response = self.client.get("/login", follow_redirects=False)
|
||||
self.assertEqual(response.status_code, 303)
|
||||
self.assertEqual(response.headers["location"], "/")
|
||||
|
||||
@@ -11,7 +11,7 @@ from fastapi.testclient import TestClient
|
||||
|
||||
from ranch_web.app import create_app
|
||||
from ranch_web.config import COOKIE_NAME, WebConfig
|
||||
from ranch_web.tests.test_api import FakeManager, FakeUpdates, FrontendAssets
|
||||
from ranch_web.tests.test_api import FakeManager, FakeUpdates
|
||||
|
||||
|
||||
BASE = "/myrzx_bot"
|
||||
@@ -97,9 +97,6 @@ class BasePathTests(unittest.TestCase):
|
||||
self.assertEqual(response.headers["location"], BASE + "/login")
|
||||
|
||||
def test_login_html_assets_and_authenticated_workbench(self):
|
||||
entry = Path(__file__).resolve().parents[1] / "static" / "index.html"
|
||||
built_assets = FrontendAssets(entry.read_text(encoding="utf-8"))
|
||||
self.assertTrue(built_assets.scripts)
|
||||
for strip in (False, True):
|
||||
with self.subTest(strip=strip):
|
||||
client = self.client(strip)
|
||||
@@ -110,14 +107,12 @@ class BasePathTests(unittest.TestCase):
|
||||
self.assertEqual(document.prefixes, [BASE])
|
||||
self.assertIn(("action", BASE + "/api/auth/login"), document.urls)
|
||||
self.assertIn(("src", BASE + "/static/login.js"), document.urls)
|
||||
self.assertEqual(FrontendAssets(response.text).scripts,
|
||||
[(BASE + "/static/login.js", "module")])
|
||||
for name, url in document.urls:
|
||||
self.assertTrue(url.startswith(BASE + "/"), url)
|
||||
self.assertNotIn(BASE + BASE, url)
|
||||
if name != "action":
|
||||
self.assertEqual(client.get(url).status_code, 200, url)
|
||||
for path in ("/", "/static/index.html", *(url for url, _ in built_assets.scripts)):
|
||||
for path in ("/", "/static/index.html", "/static/app.js"):
|
||||
response = client.get(BASE + path, follow_redirects=False)
|
||||
self.assertEqual(response.status_code, 303)
|
||||
self.assertEqual(response.headers["location"], BASE + "/login")
|
||||
@@ -131,22 +126,9 @@ class BasePathTests(unittest.TestCase):
|
||||
self.assertEqual(response.status_code, 200)
|
||||
document = _Document(response.text)
|
||||
self.assertEqual(document.prefixes, [BASE])
|
||||
assets = FrontendAssets(response.text)
|
||||
self.assertEqual(assets.scripts, [(BASE + url, kind) for url, kind in built_assets.scripts])
|
||||
self.assertEqual(assets.urls, [BASE + url for url in built_assets.urls])
|
||||
self.assertIn(("src", BASE + "/static/app.js"), document.urls)
|
||||
self.assertEqual(response.headers["cache-control"], "no-store")
|
||||
for url in assets.urls:
|
||||
self.assertTrue(url.startswith(BASE + "/static/"), url)
|
||||
self.assertNotIn(BASE + BASE, url)
|
||||
asset = client.get(url)
|
||||
self.assertEqual(asset.status_code, 200, url)
|
||||
if url not in assets.stylesheets:
|
||||
self.assertEqual(asset.headers["cache-control"], "no-store")
|
||||
client.cookies.clear()
|
||||
for url, _ in built_assets.scripts:
|
||||
response = client.get(BASE + url, follow_redirects=False)
|
||||
self.assertEqual(response.status_code, 303)
|
||||
self.assertEqual(response.headers["location"], BASE + "/login")
|
||||
self.assertEqual(client.get(BASE + "/static/app.js").status_code, 200)
|
||||
self.assertEqual(self.manager.calls, [])
|
||||
|
||||
def test_secure_cookie_scope_logout_and_revoked_session(self):
|
||||
|
||||
Reference in New Issue
Block a user