Peach: Local-first video metadata scraper and media manager.
test(regression): 补充 HTTP 索引器与状态保存回归
FriendlyPasser83c8de8346e1
diff --git a/frontend/e2e/http-configuration.test.ts b/frontend/e2e/http-configuration.test.tsnew file mode 100644index 000000000..c2c952f1c--- /dev/null+++ b/frontend/e2e/http-configuration.test.ts@@ -0,0 +1,75 @@+import assert from 'node:assert/strict';+import { after, before, describe, it } from 'node:test';+import type { Browser } from 'playwright-core';+import { configurationBody, expectBody, launch, layout, requiredEnv, settle, visit, VIEWPORTS } from './harness.ts';++describe('普通 HTTP 的配置与播放', () => {+ let browser: Browser;+ before(async () => { browser = await launch() });+ after(async () => { await browser?.close() });++ for (const viewport of VIEWPORTS) {+ it(`${viewport.name}:非安全来源打开配置、编辑索引器并挂载播放器`, { timeout: 60_000 }, async () => {+ const service = requiredEnv('PEACH_E2E_ORIGIN');+ const origin = 'http://peach-http.test';+ const opened = await visit(browser, '/', viewport, async page => {+ // 只将临时演示服务映射到普通 HTTP 来源;浏览器自行决定 Web Crypto 的可用性。+ await page.route(`${origin}/**`, async route => {+ const request = route.request();+ const url = new URL(request.url());+ const response = await route.fetch({ url: service + url.pathname + url.search, maxRedirects: 0,+ headers: { ...request.headers(), host: new URL(service).host, origin: service } });+ await route.fulfill({ response });+ });+ });+ const { page, problems } = opened;+ try {+ const response = await page.request.get(`${service}/api/configuration`);+ assert.equal(response.status(), 200);+ const configuration = await response.json();+ // 路由拦截只处理重定向的首个请求;别名契约在服务端读取,页面走正式入口。+ const alias = await page.request.get(`${service}/configuration`, { maxRedirects: 0 });+ assert.equal(alias.status(), 307);+ assert.equal(alias.headers().location, '/settings/library');+ await page.route(`${origin}/api/configuration`, route => route.fulfill({ json: { ...configuration, editable: true } }));+ const writes: { indexers: { key: string; name: string; url: string }[] }[] = [];+ await page.route(`${origin}/api/configuration/indexers`, route => {+ if (route.request().method() === 'GET') return route.fulfill({ json: { indexers: [], max_indexers: 4 } });+ const sent = route.request().postDataJSON();+ writes.push(sent);+ return route.fulfill({ json: { ...sent, max_indexers: 4 } });+ });+ page.on('response', response => {+ if (response.url().startsWith(origin) && response.status() >= 400) problems.push(`${response.status()} ${response.url()}`);+ });+ for (const path of ['/settings/library', '/settings/subscriptions']) {+ await page.goto(origin + path, { waitUntil: 'load' });+ assert.deepEqual(await page.evaluate(() => ({+ secure: isSecureContext, uuid: typeof crypto.randomUUID, random: typeof crypto.getRandomValues,+ })), { secure: false, uuid: 'undefined', random: 'function' });+ await expectBody(page, path, configurationBody(page));+ await page.getByRole('tab', { name: '来源与订阅', exact: true }).click();+ const section = page.getByRole('form', { name: '资源搜索', exact: true });+ await section.getByRole('button', { name: '添加索引器', exact: true }).click();+ await section.getByRole('button', { name: '添加索引器', exact: true }).click();+ await section.getByRole('textbox', { name: /名称/ }).nth(1).fill('HTTP 测试');+ await section.getByRole('textbox', { name: /Torznab 地址/ }).nth(1).fill('https://indexer.example/api');+ await section.getByRole('button', { name: '移除索引器 1', exact: true }).click();+ const saved = page.waitForResponse(response => response.url() === `${origin}/api/configuration/indexers`+ && response.request().method() === 'POST');+ await section.getByRole('button', { name: '保存配置', exact: true }).click();+ assert.equal((await saved).status(), 200);+ assert.equal(writes.at(-1)!.indexers.length, 1);+ assert.equal(writes.at(-1)!.indexers[0]!.name, 'HTTP 测试');+ await settle(page, '.ui-configpage');+ const bounds = await layout(page);+ assert.ok(bounds.scrollWidth <= bounds.viewportWidth);+ assert.deepEqual(bounds.offenders, []);+ }+ await page.goto(`${origin}/assets/${requiredEnv('PEACH_E2E_ITEM')}`, { waitUntil: 'load' });+ await page.locator('#stage .video-js video.vjs-tech').waitFor();+ assert.deepEqual(problems, []);+ } finally { await opened.close() }+ });+ }+});diff --git a/frontend/test/player-v10.test.ts b/frontend/test/player-v10.test.tsindex 142eba9b1..2415cd9cc 100644--- a/frontend/test/player-v10.test.ts+++ b/frontend/test/player-v10.test.ts@@ -13,7 +13,7 @@ beforeAll(() => {if (!customElements.get('hlsjs-video')) customElements.define('hlsjs-video', TestMedia);if (!customElements.get('dash-video')) customElements.define('dash-video', class extends TestMedia {});});-afterEach(() => { document.body.replaceChildren(); vi.restoreAllMocks() });+afterEach(() => { document.body.replaceChildren(); vi.restoreAllMocks(); vi.unstubAllGlobals() });function mounted() {const video = document.createElement('video'); document.body.append(video);@@ -23,6 +23,16 @@ function mounted() {}describe('Video.js 10 播放会话', () => {+ it('普通 HTTP 的随机源为无 ID 的视频创建独立播放器', () => {+ vi.stubGlobal('crypto', { getRandomValues: crypto.getRandomValues.bind(crypto) });+ const first = mounted().player;+ const second = mounted().player;+ try {+ expect(first.el().id).toMatch(/^peach-player-/);+ expect(first.el().id).not.toBe(second.el().id);+ } finally { first.dispose(); second.dispose() }+ });+it('片源交给异步 adapter 后立即播放,原生 play 使用已挂载的片源', async () => {const { video, player, media } = mounted();Object.defineProperty(media, 'source', { set: (value: { src: string }) => {diff --git a/frontend/test/react/indexer-settings.test.tsx b/frontend/test/react/indexer-settings.test.tsxindex 277c6975d..8d0a08de0 100644--- a/frontend/test/react/indexer-settings.test.tsx+++ b/frontend/test/react/indexer-settings.test.tsx@@ -2,9 +2,31 @@ import { notifyManager, QueryClientProvider } from '@tanstack/react-query';import { afterEach, expect, it, vi } from 'vitest';import { queryClient } from '../../src/react/query';import { IndexerSettings } from '../../src/react/settings/indexer-settings';-import { mount, pending, settle } from './render';+import { buttonNamed, click, mount, pending, settle, submit, type } from './render';notifyManager.setScheduler(notify => notify());+it('普通 HTTP 的随机源支持添加、编辑、移除和保存索引器', async () => {+ vi.stubGlobal('crypto', { getRandomValues: crypto.getRandomValues.bind(crypto) });+ const fetch = vi.fn(async (_url: string, options?: RequestInit) => ({+ ok: true, status: 200,+ json: async () => options?.body ? JSON.parse(String(options.body)) : { indexers: [], max_indexers: 4 },+ }));+ vi.stubGlobal('fetch', fetch);+ const host = await mount(<QueryClientProvider client={queryClient}><IndexerSettings receipt={vi.fn()} /></QueryClientProvider>);+ await settle();+ await click(buttonNamed('添加索引器', host));+ await click(buttonNamed('添加索引器', host));+ const names = host.querySelectorAll<HTMLInputElement>('input[type="text"]');+ await type(names[0], '第一个');+ await type(names[1], '第二个');+ await type(host.querySelectorAll<HTMLInputElement>('input[type="url"]')[1], 'https://indexer.example/api');+ await click(host.querySelector('button[aria-label="移除索引器 1"]'));+ await submit(host.querySelector('form'));+ const sent = JSON.parse(String(fetch.mock.calls.at(-1)?.[1]?.body));+ expect(sent.indexers).toHaveLength(1);+ expect(sent.indexers[0]).toMatchObject({ name: '第二个', url: 'https://indexer.example/api', enabled: true });+ expect(sent.indexers[0].key).toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/);+});afterEach(() => queryClient.clear());it('进入资源搜索设置时先读取当前值,再创建表单草稿', async () => {const row = { key: 'one', name: '缓存名称', url: 'https://example.com/api', enabled: true, api_key_set: false };diff --git a/tests/test_metadata_library.py b/tests/test_metadata_library.pyindex e170bd3db..c07bda809 100644--- a/tests/test_metadata_library.py+++ b/tests/test_metadata_library.py@@ -7,6 +7,7 @@ import tempfileimport threadingimport timeimport unittest+from concurrent.futures import ThreadPoolExecutorfrom pathlib import Path, PureWindowsPathfrom types import SimpleNamespacefrom unittest.mock import DEFAULT, Mock, patch@@ -2358,6 +2359,68 @@ class LibraryNfoTests(unittest.TestCase):self.assertIn('<LibraryProcessingCard toast={notify} monitor onComplete={refreshReadings} />', page)+class LibraryStatePersistenceTests(unittest.TestCase):+ def setUp(self):+ temporary = tempfile.TemporaryDirectory()+ self.addCleanup(temporary.cleanup)+ self.root = Path(temporary.name).resolve()+ self.path = self.root / 'state/library-processing.json'+ self.path.parent.mkdir()+ self.previous = {'status': 'running', 'job_id': 'one', 'title': '处理进度'}+ self.path.write_text(json.dumps(self.previous, ensure_ascii=False), encoding='utf-8')++ def test_state_save_retries_temporary_replace_denial(self):+ replace = os.replace+ attempts = []+ current = {**self.previous, 'processed': 2}++ def busy_reader(source, destination):+ attempts.append(source)+ if len(attempts) <= 2:+ self.assertEqual(json.loads(self.path.read_text(encoding='utf-8')), self.previous)+ self.assertEqual(json.loads(Path(source).read_text(encoding='utf-8')), current)+ raise PermissionError(13, '目标文件正在读取', str(destination))+ return replace(source, destination)++ with patch('os.replace', side_effect=busy_reader):+ _save(self.path, current)+ self.assertEqual(len(attempts), 3)+ self.assertEqual(json.loads(self.path.read_text(encoding='utf-8')), current)+ self.assertEqual(list(self.path.parent.iterdir()), [self.path])++ def test_state_save_reports_persistent_denial_and_cleans_staging(self):+ denied = PermissionError(13, '目标文件不可替换', str(self.path))+ with patch('os.replace', side_effect=denied), patch('peach.fsutil.READER_WAIT', 0):+ with self.assertRaises(PermissionError) as raised:+ _save(self.path, {**self.previous, 'processed': 2})+ self.assertIs(raised.exception, denied)+ self.assertEqual(json.loads(self.path.read_text(encoding='utf-8')), self.previous)+ self.assertEqual(list(self.path.parent.iterdir()), [self.path])++ def test_concurrent_state_saves_publish_complete_payloads(self):+ replace = os.replace+ ready = threading.Barrier(2)+ writer = threading.local()+ staging = []+ payloads = [{**self.previous, 'processed': index, 'details': '进度' * 1024} for index in (1, 2)]++ def interleaved_replace(source, destination):+ if not getattr(writer, 'ready', False):+ staging.append(Path(source))+ writer.ready = True+ ready.wait(timeout=5)+ return replace(source, destination)++ with patch('os.replace', side_effect=interleaved_replace), ThreadPoolExecutor(max_workers=2) as pool:+ futures = [pool.submit(_save, self.path, payload) for payload in payloads]+ for future in futures:+ future.result(timeout=10)+ self.assertEqual(len(set(staging)), 2)+ self.assertTrue(all(path.parent == self.path.parent for path in staging))+ self.assertIn(json.loads(self.path.read_text(encoding='utf-8')), payloads)+ self.assertEqual(list(self.path.parent.iterdir()), [self.path])++class LibraryWatchdogTests(unittest.TestCase):"""扫描与采集任务的进度心跳、卡住提示、预算与失败项重试。"""diff --git a/tests/test_streaming.py b/tests/test_streaming.pyindex d126bbdc7..e3d293bf7 100644--- a/tests/test_streaming.py+++ b/tests/test_streaming.py@@ -60,8 +60,10 @@ class HlsDisconnectTests(unittest.IsolatedAsyncioTestCase):return registeredself.registry = Registry()+ # 子进程只用标准库;直接运行解释器,退出与管道均属于被登记的同一个进程。+ self.python = sys._base_executableself.service = HlsSegmentService(- Mock(ffmpeg=lambda: SimpleNamespace(path=Path(sys.executable))),+ Mock(ffmpeg=lambda: SimpleNamespace(path=Path(self.python))),self.root / "cache", max_concurrent=1,)executor = ThreadPoolExecutor(max_workers=1)@@ -74,7 +76,7 @@ class HlsDisconnectTests(unittest.IsolatedAsyncioTestCase):def command(target):target.write_bytes(b"segment")- return [sys.executable, "-c", self.child_code]+ return [self.python, "-c", self.child_code]for patcher in (patch("peach.routes_media._hls_plan", return_value=(@@ -134,7 +136,7 @@ class HlsDisconnectTests(unittest.IsolatedAsyncioTestCase):self.service.resolver, self.root / "parallel", max_concurrent=2,)with patch.object(self.service, "_attempts", return_value=[(- "process", lambda target: [sys.executable, "-c", self.child_code],+ "process", lambda target: [self.python, "-c", self.child_code],)]):first, disconnected = self.request(0)first_process = await self.process()