vomebook commited on
Commit ·
8d52e72
1
Parent(s): 314df05
Track project test suites
Browse files- .gitignore +0 -1
- tests/fixtures/reader/issues/manifest.json +10 -0
- tests/reader_source_contract.js +17 -0
- tests/reader_test_selection.py +119 -0
- tests/real_server.py +89 -0
- tests/test_api_contract.py +110 -0
- tests/test_async_proxy.py +604 -0
- tests/test_benchmark.py +245 -0
- tests/test_browser.py +834 -0
- tests/test_cache_and_malformed.py +135 -0
- tests/test_data_decoding.py +54 -0
- tests/test_fastapi_endpoints.py +425 -0
- tests/test_generated_data_oracle.py +152 -0
- tests/test_live_smoke.py +65 -0
- tests/test_paging_recovery.py +143 -0
- tests/test_reader_accessibility.py +23 -0
- tests/test_reader_architecture.js +173 -0
- tests/test_reader_backend.py +438 -0
- tests/test_reader_chapter_repository.js +64 -0
- tests/test_reader_conversions.py +5 -0
- tests/test_reader_formats.py +5 -0
- tests/test_reader_layout.py +5 -0
- tests/test_reader_lifecycle.py +5 -0
- tests/test_reader_live_formats.py +364 -0
- tests/test_reader_live_smoke.py +31 -0
- tests/test_reader_models.js +9 -0
- tests/test_reader_navigation.py +5 -0
- tests/test_reader_performance.py +0 -0
- tests/test_reader_preload.js +115 -0
- tests/test_reader_refactor.py +470 -0
- tests/test_reader_regression.js +72 -0
- tests/test_reader_request_manager.js +336 -0
- tests/test_reader_runtime.js +65 -0
- tests/test_reader_scroll_anchor.js +70 -0
- tests/test_reader_section_virtualizer.js +36 -0
- tests/test_reader_security.js +189 -0
- tests/test_reader_store_channel.js +7 -0
- tests/test_reader_style.py +281 -0
- tests/test_reader_timeout.py +88 -0
- tests/test_reader_visual.py +37 -0
- tests/test_real_integration.py +196 -0
- tests/test_search.py +127 -0
- tests/test_search_behavior.py +165 -0
- tests/test_security.py +101 -0
.gitignore
CHANGED
|
@@ -3,7 +3,6 @@ __pycache__/
|
|
| 3 |
static/vendor/
|
| 4 |
tests/__pycache__/
|
| 5 |
tests/benchmark-results.json
|
| 6 |
-
/tests/
|
| 7 |
/TESTING.md
|
| 8 |
/requirements-test.txt
|
| 9 |
/docs/READER_GUIDE.md
|
|
|
|
| 3 |
static/vendor/
|
| 4 |
tests/__pycache__/
|
| 5 |
tests/benchmark-results.json
|
|
|
|
| 6 |
/TESTING.md
|
| 7 |
/requirements-test.txt
|
| 8 |
/docs/READER_GUIDE.md
|
tests/fixtures/reader/issues/manifest.json
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"schema": 1,
|
| 3 |
+
"fixtures": [
|
| 4 |
+
{ "id": "pdf-pages-wide-image", "format": "pdf-pages", "source": "production-id:0ii7sf11ig9ls", "expected": "images fit page shells without overlap", "test": "test_converted_pdf_pages_fit_wide_images_without_overlap" },
|
| 5 |
+
{ "id": "epub-nested-resources", "format": "epub", "source": "minimized from nested package resource failures", "expected": "chapter images resolve without escaping the source boundary", "test": "test_foliate_navigation_path_dark_links_and_unique_sections" },
|
| 6 |
+
{ "id": "text-multibyte-boundary", "format": "txt", "source": "minimized from split UTF-8 and legacy encoding failures", "expected": "stream decoding preserves split multibyte characters", "test": "test_txt_displays_before_stream_finishes" }
|
| 7 |
+
,{ "id": "reader-security-boundaries", "format": "html/epub-chapters/epub", "source": "inline deterministic browser routes", "expected": "active resources, oversized chapter resources, and ZIP bomb metadata are rejected while safe text remains", "test": "test_malicious_html_css_and_svg_are_inert_and_keep_safe_text" }
|
| 8 |
+
,{ "id": "reader-navigation-matrix", "format": "html/md/pdf/epub-chapters", "source": "inline deterministic browser routes", "expected": "TOC, outline, first/lazy chapter, and cross-panel store updates navigate through visible Reader UI", "test": "test_epub_chapters_load_first_lazy_next_and_toc_destination" }
|
| 9 |
+
]
|
| 10 |
+
}
|
tests/reader_source_contract.js
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
const assert = require("assert");
|
| 2 |
+
|
| 3 |
+
// Match code tokens across layout changes, preserving quoted values and operators.
|
| 4 |
+
// This is a snippet matcher, not a JavaScript parser or a source minifier.
|
| 5 |
+
function codePattern(snippet) {
|
| 6 |
+
const tokens = snippet.match(/"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|`(?:\\.|[^`\\])*`|[\w$]+|===|!==|=>|\?\.|\?\?|&&|\|\||==|!=|<=|>=|\+\+|--|\S/g) || [];
|
| 7 |
+
return new RegExp(tokens.map((token, index) => {
|
| 8 |
+
const gap = index === 0 ? "" : /[\w$]$/.test(tokens[index - 1]) && /^[\w$]/.test(token) ? "\\s+" : "\\s*";
|
| 9 |
+
return gap + token.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
| 10 |
+
}).join(""));
|
| 11 |
+
}
|
| 12 |
+
|
| 13 |
+
function assertCode(source, snippet) {
|
| 14 |
+
assert.match(source, codePattern(snippet), snippet);
|
| 15 |
+
}
|
| 16 |
+
|
| 17 |
+
module.exports = { codePattern, assertCode };
|
tests/reader_test_selection.py
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import collections
|
| 2 |
+
import unittest
|
| 3 |
+
|
| 4 |
+
from tests.test_reader_performance import ReaderPerformanceTest
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
CATEGORY_METHODS = {
|
| 8 |
+
"layout": (
|
| 9 |
+
"test_pdf_rendering_has_bounded_concurrency_and_canvas_memory",
|
| 10 |
+
"test_pdf_exposes_lazy_accessible_text",
|
| 11 |
+
"test_reader_panel_bookmark_search_and_theme",
|
| 12 |
+
"test_reader_controls_fit_viewport_without_overlap_and_work_on_mobile",
|
| 13 |
+
"test_reader_toolbar_controls_have_accessible_names_and_state",
|
| 14 |
+
"test_mobile_pdf_rendering_uses_one_slot_and_seven_canvases",
|
| 15 |
+
"test_mobile_zoom_enlarges_pdf_page_without_resizing_content_shell",
|
| 16 |
+
),
|
| 17 |
+
"formats": (
|
| 18 |
+
"test_format_modes_expose_matching_controls_and_bookmark_ui",
|
| 19 |
+
"test_video_failure_shows_recoverable_reader_error",
|
| 20 |
+
"test_video_extension_aliases_report_media_errors_consistently",
|
| 21 |
+
"test_unsupported_format_hides_inapplicable_controls",
|
| 22 |
+
"test_truncated_epub_reports_source_damage",
|
| 23 |
+
"test_txt_displays_before_stream_finishes",
|
| 24 |
+
"test_text_reader_uses_scroll_mode_without_pagination_controls",
|
| 25 |
+
"test_reader_tab_is_hidden_for_document_without_toc",
|
| 26 |
+
"test_txt_detects_legacy_encodings_and_multibyte_sample_boundary",
|
| 27 |
+
"test_markdown_extension_aliases_render_content",
|
| 28 |
+
"test_html_aliases_render_safely_with_visible_text",
|
| 29 |
+
"test_malicious_html_css_and_svg_are_inert_and_keep_safe_text",
|
| 30 |
+
"test_image_aliases_decode_real_image_bytes",
|
| 31 |
+
"test_native_media_uses_proxy_controls_and_mobile_layout",
|
| 32 |
+
"test_audio_extension_aliases_use_native_reader_controls",
|
| 33 |
+
"test_cold_cache_first_read_with_real_format_engines",
|
| 34 |
+
),
|
| 35 |
+
"conversions": (
|
| 36 |
+
"test_converted_pdf_pages_reject_invalid_manifest_and_missing_first_page",
|
| 37 |
+
"test_converted_pdf_pages_report_error_when_later_page_is_missing",
|
| 38 |
+
"test_converted_pdf_pages_fit_wide_images_without_overlap",
|
| 39 |
+
"test_compact_pdf_manifest_virtualizes_and_navigates_to_distant_page",
|
| 40 |
+
"test_oversized_chapter_manifest_and_response_use_resource_limit",
|
| 41 |
+
"test_zip_bomb_metadata_is_rejected_before_docx_and_foliate_parsers",
|
| 42 |
+
"test_image_proxy_failure_falls_back_to_direct_source",
|
| 43 |
+
"test_epub_chapters_serve_nested_bundle_with_resources",
|
| 44 |
+
"test_foliate_normalizes_legacy_chm_markup_and_keeps_resources",
|
| 45 |
+
),
|
| 46 |
+
"navigation": (
|
| 47 |
+
"test_reader_controls_honor_boundaries_and_keyboard_activation",
|
| 48 |
+
"test_text_bookmark_uses_progress_excerpt_and_highlights_search",
|
| 49 |
+
"test_full_text_search_lists_highlighted_snippets_and_jumps",
|
| 50 |
+
"test_pdf_allows_two_bookmarks_on_one_page_and_restores_offsets",
|
| 51 |
+
"test_html_bookmark_at_zero_restores_iframe_top",
|
| 52 |
+
"test_foliate_navigation_path_dark_links_and_unique_sections",
|
| 53 |
+
"test_foliate_rapid_toc_navigation_keeps_latest_destination",
|
| 54 |
+
"test_foliate_failed_toc_section_can_retry",
|
| 55 |
+
"test_foliate_duplicate_toc_navigation_shares_section_load",
|
| 56 |
+
"test_foliate_chapter_buttons_use_continuous_reader_navigation",
|
| 57 |
+
"test_foliate_scroll_updates_toc_on_animation_frame",
|
| 58 |
+
"test_foliate_resize_keeps_current_text_anchor",
|
| 59 |
+
"test_foliate_virtualizes_distant_sections_and_reloads_them",
|
| 60 |
+
"test_foliate_full_search_uses_continuous_reader_navigation",
|
| 61 |
+
"test_foliate_bookmark_restores_continuous_section_position",
|
| 62 |
+
"test_foliate_progress_slider_uses_continuous_viewport",
|
| 63 |
+
"test_foliate_history_saves_structured_section_position",
|
| 64 |
+
"test_foliate_history_restores_structured_section_position",
|
| 65 |
+
"test_actual_store_broadcasts_progress_and_bookmark_updates_between_readers",
|
| 66 |
+
"test_html_and_markdown_toc_click_navigation",
|
| 67 |
+
"test_pdf_outline_click_navigates_to_declared_page",
|
| 68 |
+
"test_pdf_outline_marks_current_entry_when_page_changes",
|
| 69 |
+
"test_pdf_stale_navigation_and_search_keep_latest_state",
|
| 70 |
+
"test_epub_chapters_load_first_lazy_next_and_toc_destination",
|
| 71 |
+
),
|
| 72 |
+
"lifecycle": (
|
| 73 |
+
"test_fetch_file_aborts_when_pagehide_disposes_reader",
|
| 74 |
+
"test_concurrent_fetch_file_callers_receive_complete_bodies",
|
| 75 |
+
"test_id_only_resolver_is_lifecycle_managed",
|
| 76 |
+
"test_id_only_resolver_failure_uses_reader_error_ui",
|
| 77 |
+
"test_id_only_reader_source_uses_authoritative_resolve",
|
| 78 |
+
"test_reader_starts_with_session_metadata_before_document_load",
|
| 79 |
+
"test_id_only_reader_falls_back_to_session_source_when_resolve_fails",
|
| 80 |
+
"test_document_preparation_overlaps_delayed_history_restore",
|
| 81 |
+
"test_bfcache_pageshow_waits_for_restoration_gate",
|
| 82 |
+
"test_pagehide_before_restoration_does_not_overwrite_progress",
|
| 83 |
+
"test_pdf_disposal_destroys_loading_task_and_cancels_render_queue",
|
| 84 |
+
"test_blocked_v1_upgrade_does_not_block_document_loading",
|
| 85 |
+
"test_stale_bookmark_query_cannot_overwrite_all_bookmarks",
|
| 86 |
+
"test_reader_store_migrates_history_and_keeps_bookmarks_when_cleared",
|
| 87 |
+
"test_supported_formats_start_loading_while_history_restores",
|
| 88 |
+
),
|
| 89 |
+
}
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def validate_partition():
|
| 93 |
+
source = {
|
| 94 |
+
name for name, value in ReaderPerformanceTest.__dict__.items()
|
| 95 |
+
if name.startswith("test_") and callable(value)
|
| 96 |
+
}
|
| 97 |
+
assigned = [name for methods in CATEGORY_METHODS.values() for name in methods]
|
| 98 |
+
counts = collections.Counter(assigned)
|
| 99 |
+
missing = sorted(source - counts.keys())
|
| 100 |
+
unknown = sorted(counts.keys() - source)
|
| 101 |
+
duplicates = sorted(name for name, count in counts.items() if count > 1)
|
| 102 |
+
if missing or unknown or duplicates:
|
| 103 |
+
raise AssertionError(
|
| 104 |
+
f"invalid Reader test partition: missing={missing}, unknown={unknown}, "
|
| 105 |
+
f"duplicates={duplicates}"
|
| 106 |
+
)
|
| 107 |
+
return {category: len(methods) for category, methods in CATEGORY_METHODS.items()}
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def load_category_tests(loader, category):
|
| 111 |
+
validate_partition()
|
| 112 |
+
return loader.loadTestsFromNames(CATEGORY_METHODS[category], ReaderPerformanceTest)
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
class ReaderPartitionContractTest(unittest.TestCase):
|
| 116 |
+
def test_every_reader_performance_test_is_assigned_once(self):
|
| 117 |
+
self.assertEqual(sum(validate_partition().values()), len(set(
|
| 118 |
+
name for methods in CATEGORY_METHODS.values() for name in methods
|
| 119 |
+
)))
|
tests/real_server.py
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
import signal
|
| 5 |
+
import socket
|
| 6 |
+
import subprocess
|
| 7 |
+
import sys
|
| 8 |
+
import tempfile
|
| 9 |
+
import time
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
from urllib.error import URLError
|
| 12 |
+
from urllib.request import Request, urlopen
|
| 13 |
+
import atexit
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
ROOT = Path(__file__).resolve().parents[1]
|
| 17 |
+
_SHARED_SERVER = None
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class RealUvicornServer:
|
| 21 |
+
def __init__(self):
|
| 22 |
+
with socket.socket() as sock:
|
| 23 |
+
sock.bind(("127.0.0.1", 0))
|
| 24 |
+
self.port = sock.getsockname()[1]
|
| 25 |
+
self.base_url = f"http://127.0.0.1:{self.port}"
|
| 26 |
+
self.stderr_file = tempfile.TemporaryFile(mode="w+t", encoding="utf-8")
|
| 27 |
+
self.process = None
|
| 28 |
+
|
| 29 |
+
def start(self):
|
| 30 |
+
self.process = subprocess.Popen(
|
| 31 |
+
[sys.executable, "-m", "uvicorn", "app:app", "--host", "127.0.0.1", "--port", str(self.port), "--log-level", "warning"],
|
| 32 |
+
cwd=ROOT,
|
| 33 |
+
stdout=subprocess.DEVNULL,
|
| 34 |
+
stderr=self.stderr_file,
|
| 35 |
+
)
|
| 36 |
+
deadline = time.monotonic() + 90
|
| 37 |
+
last_error = None
|
| 38 |
+
while time.monotonic() < deadline:
|
| 39 |
+
if self.process.poll() is not None:
|
| 40 |
+
break
|
| 41 |
+
try:
|
| 42 |
+
repos = self.json("/api/repos", timeout=2)
|
| 43 |
+
if isinstance(repos, list) and repos:
|
| 44 |
+
return self
|
| 45 |
+
except Exception as exc:
|
| 46 |
+
last_error = exc
|
| 47 |
+
time.sleep(0.25)
|
| 48 |
+
stderr = self.stderr()
|
| 49 |
+
self.stop()
|
| 50 |
+
raise RuntimeError(f"real Uvicorn did not become ready: {last_error}\n{stderr}")
|
| 51 |
+
|
| 52 |
+
def request(self, path, payload=None, timeout=30):
|
| 53 |
+
data = json.dumps(payload).encode("utf-8") if payload is not None else None
|
| 54 |
+
headers = {"Content-Type": "application/json"} if data else {}
|
| 55 |
+
return urlopen(Request(self.base_url + path, data=data, headers=headers), timeout=timeout)
|
| 56 |
+
|
| 57 |
+
def json(self, path, payload=None, timeout=30):
|
| 58 |
+
with self.request(path, payload, timeout) as response:
|
| 59 |
+
return json.load(response)
|
| 60 |
+
|
| 61 |
+
def stop(self):
|
| 62 |
+
if self.process is not None and self.process.poll() is None:
|
| 63 |
+
self.process.send_signal(signal.SIGINT)
|
| 64 |
+
try:
|
| 65 |
+
self.process.wait(timeout=20)
|
| 66 |
+
except subprocess.TimeoutExpired:
|
| 67 |
+
self.process.kill()
|
| 68 |
+
self.process.wait(timeout=10)
|
| 69 |
+
return self.process.returncode if self.process is not None else None
|
| 70 |
+
|
| 71 |
+
def stderr(self):
|
| 72 |
+
self.stderr_file.flush()
|
| 73 |
+
self.stderr_file.seek(0)
|
| 74 |
+
return self.stderr_file.read()
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def get_shared_server():
|
| 78 |
+
global _SHARED_SERVER
|
| 79 |
+
if _SHARED_SERVER is None or _SHARED_SERVER.process is None or _SHARED_SERVER.process.poll() is not None:
|
| 80 |
+
_SHARED_SERVER = RealUvicornServer().start()
|
| 81 |
+
return _SHARED_SERVER
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def stop_shared_server():
|
| 85 |
+
if _SHARED_SERVER is not None:
|
| 86 |
+
_SHARED_SERVER.stop()
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
atexit.register(stop_shared_server)
|
tests/test_api_contract.py
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import copy
|
| 4 |
+
import asyncio
|
| 5 |
+
import json
|
| 6 |
+
import unittest
|
| 7 |
+
from unittest import mock
|
| 8 |
+
|
| 9 |
+
IMPORT_ERROR = None
|
| 10 |
+
try:
|
| 11 |
+
import app
|
| 12 |
+
except ModuleNotFoundError as exc: # pragma: no cover
|
| 13 |
+
app = None
|
| 14 |
+
IMPORT_ERROR = exc
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
@unittest.skipIf(app is None, f"app dependencies unavailable: {IMPORT_ERROR}")
|
| 18 |
+
class ApiContractTests(unittest.TestCase):
|
| 19 |
+
def setUp(self):
|
| 20 |
+
self.names = (
|
| 21 |
+
"records", "word_index", "folder_index", "repo_counts", "repo_list",
|
| 22 |
+
"repo_records_map", "sorted_by_name", "sorted_by_size",
|
| 23 |
+
"repo_sorted_by_name", "repo_sorted_by_size", "vocab_by_len",
|
| 24 |
+
"extension_counts", "extension_list", "repo_extension_counts",
|
| 25 |
+
"txt_record_indices", "repo_txt_record_indices", "reader_record_indices", "repo_reader_record_indices", "folder_tree_data",
|
| 26 |
+
"folder_browser_data", "api_response_cache", "initial_payload_global",
|
| 27 |
+
"initial_payload_by_repo",
|
| 28 |
+
)
|
| 29 |
+
self.saved = {name: copy.deepcopy(getattr(app, name)) for name in self.names}
|
| 30 |
+
app.records = [{"Repo": "VoiceOfML/Test", "File": "readme", "Extension": "txt", "Folder": ["docs"], "Size": 10, "HasTxt": True}]
|
| 31 |
+
app.build_indexes()
|
| 32 |
+
app.build_initial_payloads()
|
| 33 |
+
|
| 34 |
+
def tearDown(self):
|
| 35 |
+
for name, value in self.saved.items():
|
| 36 |
+
setattr(app, name, value)
|
| 37 |
+
|
| 38 |
+
def test_search_request_defaults_and_response_shape(self):
|
| 39 |
+
with mock.patch.object(app, "get_reader_assets", mock.AsyncMock(return_value={"v": 1, "f": {}})):
|
| 40 |
+
body = asyncio.run(app.api_search(app.SearchRequest(q="readme", page_size=1)))
|
| 41 |
+
self.assertEqual(body.status_code, 200)
|
| 42 |
+
payload = body.body.decode()
|
| 43 |
+
self.assertIn('"page":1', payload)
|
| 44 |
+
self.assertIn('"page_size":1', payload)
|
| 45 |
+
self.assertIn('"results"', payload)
|
| 46 |
+
|
| 47 |
+
def test_unknown_repo_endpoints_are_404(self):
|
| 48 |
+
self.assertEqual(asyncio.run(app.api_search_repo("Missing", app.SearchRequest())).status_code, 404)
|
| 49 |
+
self.assertEqual(app.api_folders("Missing").status_code, 404)
|
| 50 |
+
self.assertEqual(app.api_folder_contents("Missing").status_code, 404)
|
| 51 |
+
self.assertEqual(app.serve_initial_repo("Missing").status_code, 404)
|
| 52 |
+
|
| 53 |
+
def test_search_response_adds_converted_reader_asset(self):
|
| 54 |
+
key = "VoiceOfML/Test\0docs/readme.txt"
|
| 55 |
+
assets = {"v": 1, "f": {key: {"s": 2, "m": "e", "p": "objects/aa/book.epub"}}}
|
| 56 |
+
with mock.patch.object(app, "get_reader_assets", mock.AsyncMock(return_value=assets)):
|
| 57 |
+
body = asyncio.run(app.api_search(app.SearchRequest(q="readme", page_size=1)))
|
| 58 |
+
payload = body.body.decode()
|
| 59 |
+
self.assertIn('"ReaderExtension":"epub"', payload)
|
| 60 |
+
self.assertIn('"ReaderLink":"https://huggingface.co/datasets/vomebook/Reader-Assets/resolve/main/objects/aa/book.epub"', payload)
|
| 61 |
+
|
| 62 |
+
def test_reader_assets_preserve_native_foliate_extensions(self):
|
| 63 |
+
extensions = ("epub", "mobi", "azw", "azw3", "fb2")
|
| 64 |
+
results = []
|
| 65 |
+
assets = {"v": 1, "f": {}}
|
| 66 |
+
for extension in extensions:
|
| 67 |
+
record = {
|
| 68 |
+
"Repo": "VoiceOfML/Test",
|
| 69 |
+
"File": f"book-{extension}",
|
| 70 |
+
"Extension": extension,
|
| 71 |
+
"Folder": ["docs"],
|
| 72 |
+
"Size": 10,
|
| 73 |
+
"HasTxt": False,
|
| 74 |
+
}
|
| 75 |
+
results.append(record)
|
| 76 |
+
assets["f"][app.build_reader_asset_key(record)] = {
|
| 77 |
+
"s": 2,
|
| 78 |
+
"m": "e",
|
| 79 |
+
"p": f"objects/aa/{'a' * 64}/document.{extension}",
|
| 80 |
+
}
|
| 81 |
+
converted = {
|
| 82 |
+
"Repo": "VoiceOfML/Test",
|
| 83 |
+
"File": "converted",
|
| 84 |
+
"Extension": "txt",
|
| 85 |
+
"Folder": ["docs"],
|
| 86 |
+
"Size": 10,
|
| 87 |
+
"HasTxt": True,
|
| 88 |
+
}
|
| 89 |
+
results.append(converted)
|
| 90 |
+
assets["f"][app.build_reader_asset_key(converted)] = {
|
| 91 |
+
"s": 2,
|
| 92 |
+
"m": "e",
|
| 93 |
+
"p": f"objects/bb/{'b' * 64}/document.epub",
|
| 94 |
+
}
|
| 95 |
+
|
| 96 |
+
enriched = app.add_reader_assets({"results": results}, assets)
|
| 97 |
+
actual = {item["Extension"]: item["ReaderExtension"] for item in enriched["results"]}
|
| 98 |
+
self.assertEqual(
|
| 99 |
+
{extension: extension for extension in extensions} | {"txt": "epub"},
|
| 100 |
+
actual,
|
| 101 |
+
)
|
| 102 |
+
|
| 103 |
+
self.assertEqual(app.serve_initial_manifest().body.decode(), '{"urls":["/data/initial/global.json","/data/initial/repos/Test.json"]}')
|
| 104 |
+
contents = app.api_folder_contents("Test", path="")
|
| 105 |
+
self.assertIn(b'"folders"', contents.body)
|
| 106 |
+
self.assertIn(b'"files"', contents.body)
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
if __name__ == "__main__":
|
| 110 |
+
unittest.main()
|
tests/test_async_proxy.py
ADDED
|
@@ -0,0 +1,604 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import asyncio
|
| 4 |
+
import copy
|
| 5 |
+
import gzip
|
| 6 |
+
import json
|
| 7 |
+
import tempfile
|
| 8 |
+
import threading
|
| 9 |
+
import time
|
| 10 |
+
import unittest
|
| 11 |
+
from collections import OrderedDict
|
| 12 |
+
from pathlib import Path
|
| 13 |
+
from types import SimpleNamespace
|
| 14 |
+
from unittest.mock import AsyncMock, patch
|
| 15 |
+
|
| 16 |
+
IMPORT_ERROR = None
|
| 17 |
+
try:
|
| 18 |
+
import aiohttp
|
| 19 |
+
import app
|
| 20 |
+
except ModuleNotFoundError as exc: # pragma: no cover
|
| 21 |
+
app = None
|
| 22 |
+
IMPORT_ERROR = exc
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
@unittest.skipIf(app is None, f"proxy dependencies unavailable: {IMPORT_ERROR}")
|
| 26 |
+
class FakeResponse:
|
| 27 |
+
def __init__(self, status=200, headers=None, chunks=(b"ok",)):
|
| 28 |
+
self.status = status
|
| 29 |
+
self.headers = headers or {}
|
| 30 |
+
self.content = self
|
| 31 |
+
self.chunks = chunks
|
| 32 |
+
self.released = False
|
| 33 |
+
|
| 34 |
+
def release(self):
|
| 35 |
+
self.released = True
|
| 36 |
+
|
| 37 |
+
async def read(self, amount=-1):
|
| 38 |
+
return b"".join(self.chunks)[:amount if amount >= 0 else None]
|
| 39 |
+
|
| 40 |
+
def iter_chunked(self, size):
|
| 41 |
+
async def generator():
|
| 42 |
+
for chunk in self.chunks:
|
| 43 |
+
yield chunk
|
| 44 |
+
return generator()
|
| 45 |
+
|
| 46 |
+
async def __aenter__(self):
|
| 47 |
+
return self
|
| 48 |
+
|
| 49 |
+
async def __aexit__(self, *args):
|
| 50 |
+
self.release()
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
class FakeSession:
|
| 54 |
+
def __init__(self, responses):
|
| 55 |
+
self.responses = list(responses)
|
| 56 |
+
self.urls = []
|
| 57 |
+
|
| 58 |
+
async def get(self, url, **kwargs):
|
| 59 |
+
self.urls.append((url, kwargs))
|
| 60 |
+
response = self.responses.pop(0)
|
| 61 |
+
if isinstance(response, Exception):
|
| 62 |
+
raise response
|
| 63 |
+
return response
|
| 64 |
+
|
| 65 |
+
async def request(self, method, url, **kwargs):
|
| 66 |
+
kwargs["method"] = method
|
| 67 |
+
return await self.get(url, **kwargs)
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
@unittest.skipIf(app is None, f"proxy dependencies unavailable: {IMPORT_ERROR}")
|
| 71 |
+
class AsyncProxyTests(unittest.IsolatedAsyncioTestCase):
|
| 72 |
+
async def asyncSetUp(self):
|
| 73 |
+
app.initialize_reader_bucket_state(app.app)
|
| 74 |
+
self._redirect_cache = dict(app.upstream_redirect_cache)
|
| 75 |
+
app.upstream_redirect_cache.clear()
|
| 76 |
+
|
| 77 |
+
async def asyncTearDown(self):
|
| 78 |
+
await app.shutdown_reader_bucket_state(app.app)
|
| 79 |
+
app.upstream_redirect_cache.clear()
|
| 80 |
+
app.upstream_redirect_cache.update(self._redirect_cache)
|
| 81 |
+
|
| 82 |
+
def test_reader_assets_decoder_filters_invalid_entries(self):
|
| 83 |
+
valid_path = "objects/aa/" + "b" * 64 + "/document.pdf"
|
| 84 |
+
valid_azw_path = "objects/aa/" + "e" * 64 + "/document.azw"
|
| 85 |
+
page_manifest = "objects/aa/" + "d" * 64 + "/page-manifest.json"
|
| 86 |
+
media_path = "objects/aa/" + "c" * 64 + "/ffmpeg-audio-mp3-v1/audio.mp3"
|
| 87 |
+
raw = gzip.compress(json.dumps({"v": 1, "f": {
|
| 88 |
+
"VoiceOfML/Test\0book.doc": {"s": 2, "m": "p", "p": valid_path},
|
| 89 |
+
"VoiceOfML/Test\0book.azw": {"s": 2, "m": "e", "p": valid_azw_path},
|
| 90 |
+
"VoiceOfML/Test\0sound.wma": {"s": 2, "m": "a", "p": media_path},
|
| 91 |
+
"VoiceOfML/Test\0scan.pdf": {"s": 2, "m": "p", "p": page_manifest},
|
| 92 |
+
"bad-path": {"s": 2, "m": "p", "p": "objects/../../secret.pdf"},
|
| 93 |
+
"failed": {"s": 4},
|
| 94 |
+
}}).encode())
|
| 95 |
+
self.assertEqual(app.decode_reader_assets(raw), {"v": 1, "f": {
|
| 96 |
+
"VoiceOfML/Test\0book.doc": {"s": 2, "m": "p", "p": valid_path},
|
| 97 |
+
"VoiceOfML/Test\0book.azw": {"s": 2, "m": "e", "p": valid_azw_path},
|
| 98 |
+
"VoiceOfML/Test\0sound.wma": {"s": 2, "m": "a", "p": media_path},
|
| 99 |
+
"VoiceOfML/Test\0scan.pdf": {"s": 2, "m": "p", "p": page_manifest},
|
| 100 |
+
"failed": {"s": 4},
|
| 101 |
+
}})
|
| 102 |
+
|
| 103 |
+
async def test_reader_assets_refresh_is_cached_and_releases_response(self):
|
| 104 |
+
payload = gzip.compress(json.dumps({"v": 1, "f": {"failed": {"s": 4}}}).encode())
|
| 105 |
+
response = FakeResponse(200, chunks=(payload,))
|
| 106 |
+
session = FakeSession([response])
|
| 107 |
+
app.app.state.http_session = session
|
| 108 |
+
app.app.state.reader_assets_lock = asyncio.Lock()
|
| 109 |
+
old_cache, old_at = app.reader_assets_cache, app.reader_assets_cache_at
|
| 110 |
+
try:
|
| 111 |
+
app.reader_assets_cache = {"v": 1, "f": {}}
|
| 112 |
+
app.reader_assets_cache_at = 0
|
| 113 |
+
first = await app.get_reader_assets()
|
| 114 |
+
second = await app.get_reader_assets()
|
| 115 |
+
self.assertEqual(first, {"v": 1, "f": {"failed": {"s": 4}}})
|
| 116 |
+
self.assertIs(first, second)
|
| 117 |
+
self.assertEqual(len(session.urls), 1)
|
| 118 |
+
self.assertTrue(response.released)
|
| 119 |
+
finally:
|
| 120 |
+
app.reader_assets_cache, app.reader_assets_cache_at = old_cache, old_at
|
| 121 |
+
|
| 122 |
+
async def test_reader_assets_refresh_failure_backs_off_with_existing_cache(self):
|
| 123 |
+
response = FakeResponse(503)
|
| 124 |
+
session = FakeSession([response])
|
| 125 |
+
app.app.state.http_session = session
|
| 126 |
+
app.app.state.reader_assets_lock = asyncio.Lock()
|
| 127 |
+
old_cache, old_at = app.reader_assets_cache, app.reader_assets_cache_at
|
| 128 |
+
try:
|
| 129 |
+
app.reader_assets_cache = {"v": 1, "f": {"old": {"s": 4}}}
|
| 130 |
+
app.reader_assets_cache_at = time.monotonic() - app.READER_ASSETS_CACHE_TTL_SECONDS - 1
|
| 131 |
+
first = await app.get_reader_assets()
|
| 132 |
+
second = await app.get_reader_assets()
|
| 133 |
+
self.assertIs(first, second)
|
| 134 |
+
self.assertEqual(len(session.urls), 1)
|
| 135 |
+
self.assertTrue(response.released)
|
| 136 |
+
finally:
|
| 137 |
+
app.reader_assets_cache, app.reader_assets_cache_at = old_cache, old_at
|
| 138 |
+
|
| 139 |
+
async def test_reader_bucket_cache_hit_preserves_success_cache_control(self):
|
| 140 |
+
path = f"objects/aa/{'a' * 64}/{'b' * 16}/page-manifest.json"
|
| 141 |
+
with patch.object(app, "read_reader_bucket_resource", return_value=b"manifest") as read:
|
| 142 |
+
first = await app.api_reader_bucket_resource(path)
|
| 143 |
+
second = await app.api_reader_bucket_resource(path)
|
| 144 |
+
self.assertEqual(first.body, b"manifest")
|
| 145 |
+
self.assertEqual(second.body, b"manifest")
|
| 146 |
+
self.assertEqual(read.call_count, 1)
|
| 147 |
+
self.assertEqual(second.headers["cache-control"], "public, max-age=3600")
|
| 148 |
+
|
| 149 |
+
async def test_reader_bucket_single_flight_coalesces_uncached_page(self):
|
| 150 |
+
path = f"objects/aa/{'a' * 64}/{'b' * 16}/pages/page-000002.webp"
|
| 151 |
+
started = threading.Event()
|
| 152 |
+
release = threading.Event()
|
| 153 |
+
|
| 154 |
+
def read(_path):
|
| 155 |
+
started.set()
|
| 156 |
+
release.wait(1)
|
| 157 |
+
return b"page"
|
| 158 |
+
|
| 159 |
+
with patch.object(app, "read_reader_bucket_resource", side_effect=read) as bucket_read:
|
| 160 |
+
first = asyncio.create_task(app.api_reader_bucket_resource(path))
|
| 161 |
+
self.assertTrue(await asyncio.to_thread(started.wait, 1))
|
| 162 |
+
second = asyncio.create_task(app.api_reader_bucket_resource(path))
|
| 163 |
+
await asyncio.sleep(0)
|
| 164 |
+
self.assertEqual(bucket_read.call_count, 1)
|
| 165 |
+
release.set()
|
| 166 |
+
responses = await asyncio.gather(first, second)
|
| 167 |
+
self.assertEqual([response.body for response in responses], [b"page", b"page"])
|
| 168 |
+
self.assertEqual(bucket_read.call_count, 1)
|
| 169 |
+
self.assertNotIn(path, app.app.state.reader_bucket_cache)
|
| 170 |
+
self.assertEqual(app.app.state.reader_bucket_inflight, {})
|
| 171 |
+
|
| 172 |
+
async def test_reader_bucket_semaphore_bounds_distinct_reads(self):
|
| 173 |
+
app.app.state.reader_bucket_semaphore = asyncio.Semaphore(1)
|
| 174 |
+
first_path = f"objects/aa/{'a' * 64}/{'b' * 16}/pages/page-000002.webp"
|
| 175 |
+
second_path = f"objects/aa/{'a' * 64}/{'b' * 16}/pages/page-000003.webp"
|
| 176 |
+
first_started = threading.Event()
|
| 177 |
+
release = threading.Event()
|
| 178 |
+
|
| 179 |
+
def read(path):
|
| 180 |
+
if path == first_path:
|
| 181 |
+
first_started.set()
|
| 182 |
+
release.wait(1)
|
| 183 |
+
return path.encode()
|
| 184 |
+
|
| 185 |
+
with patch.object(app, "read_reader_bucket_resource", side_effect=read) as bucket_read:
|
| 186 |
+
first = asyncio.create_task(app.api_reader_bucket_resource(first_path))
|
| 187 |
+
self.assertTrue(await asyncio.to_thread(first_started.wait, 1))
|
| 188 |
+
second = asyncio.create_task(app.api_reader_bucket_resource(second_path))
|
| 189 |
+
await asyncio.sleep(0.05)
|
| 190 |
+
self.assertEqual(bucket_read.call_count, 1)
|
| 191 |
+
release.set()
|
| 192 |
+
await asyncio.gather(first, second)
|
| 193 |
+
self.assertEqual(bucket_read.call_count, 2)
|
| 194 |
+
|
| 195 |
+
async def test_reader_bucket_failures_are_no_store_and_not_cached(self):
|
| 196 |
+
path = f"objects/aa/{'a' * 64}/{'b' * 16}/page-manifest.json"
|
| 197 |
+
invalid = await app.api_reader_bucket_resource("invalid")
|
| 198 |
+
self.assertEqual(invalid.status_code, 400)
|
| 199 |
+
self.assertEqual(invalid.headers["cache-control"], "no-store")
|
| 200 |
+
|
| 201 |
+
for error, status in ((FileNotFoundError(), 404), (RuntimeError(), 502)):
|
| 202 |
+
with self.subTest(status=status), patch.object(
|
| 203 |
+
app, "read_reader_bucket_resource", side_effect=error
|
| 204 |
+
) as bucket_read:
|
| 205 |
+
first = await app.api_reader_bucket_resource(path)
|
| 206 |
+
second = await app.api_reader_bucket_resource(path)
|
| 207 |
+
self.assertEqual(first.status_code, status)
|
| 208 |
+
self.assertEqual(second.status_code, status)
|
| 209 |
+
self.assertEqual(first.headers["cache-control"], "no-store")
|
| 210 |
+
self.assertEqual(bucket_read.call_count, 2)
|
| 211 |
+
|
| 212 |
+
async def test_reader_bucket_cache_evicts_by_bytes_and_skips_oversize_items(self):
|
| 213 |
+
manifest = f"objects/aa/{'a' * 64}/{'b' * 16}/page-manifest.json"
|
| 214 |
+
first_page = f"objects/aa/{'a' * 64}/{'b' * 16}/pages/page-000001.webp"
|
| 215 |
+
other_manifest = f"objects/bb/{'c' * 64}/{'d' * 16}/page-manifest.json"
|
| 216 |
+
old_total = app.READER_BUCKET_CACHE_MAX_BYTES
|
| 217 |
+
old_item = app.READER_BUCKET_CACHE_MAX_ITEM_BYTES
|
| 218 |
+
app.READER_BUCKET_CACHE_MAX_BYTES = 5
|
| 219 |
+
app.READER_BUCKET_CACHE_MAX_ITEM_BYTES = 4
|
| 220 |
+
payloads = {manifest: b"aaa", first_page: b"bbb", other_manifest: b"12345"}
|
| 221 |
+
try:
|
| 222 |
+
with patch.object(app, "read_reader_bucket_resource", side_effect=payloads.get) as bucket_read:
|
| 223 |
+
await app.api_reader_bucket_resource(manifest)
|
| 224 |
+
await app.api_reader_bucket_resource(first_page)
|
| 225 |
+
self.assertNotIn(manifest, app.app.state.reader_bucket_cache)
|
| 226 |
+
self.assertEqual(app.app.state.reader_bucket_cache_bytes, 3)
|
| 227 |
+
await app.api_reader_bucket_resource(manifest)
|
| 228 |
+
await app.api_reader_bucket_resource(other_manifest)
|
| 229 |
+
await app.api_reader_bucket_resource(other_manifest)
|
| 230 |
+
self.assertEqual(bucket_read.call_count, 5)
|
| 231 |
+
self.assertNotIn(other_manifest, app.app.state.reader_bucket_cache)
|
| 232 |
+
self.assertLessEqual(app.app.state.reader_bucket_cache_bytes, 5)
|
| 233 |
+
finally:
|
| 234 |
+
app.READER_BUCKET_CACHE_MAX_BYTES = old_total
|
| 235 |
+
app.READER_BUCKET_CACHE_MAX_ITEM_BYTES = old_item
|
| 236 |
+
|
| 237 |
+
async def test_reader_bucket_shutdown_cancels_flights_and_clears_cache(self):
|
| 238 |
+
task = asyncio.create_task(asyncio.sleep(10))
|
| 239 |
+
app.app.state.reader_bucket_inflight["path"] = task
|
| 240 |
+
app.app.state.reader_bucket_cache["path"] = (time.monotonic(), b"data")
|
| 241 |
+
app.app.state.reader_bucket_cache_bytes = 4
|
| 242 |
+
await app.shutdown_reader_bucket_state(app.app)
|
| 243 |
+
self.assertTrue(task.cancelled())
|
| 244 |
+
self.assertEqual(app.app.state.reader_bucket_inflight, {})
|
| 245 |
+
self.assertEqual(app.app.state.reader_bucket_cache, {})
|
| 246 |
+
self.assertEqual(app.app.state.reader_bucket_cache_bytes, 0)
|
| 247 |
+
|
| 248 |
+
async def test_relative_redirect_is_resolved_against_current_url(self):
|
| 249 |
+
session = FakeSession([FakeResponse(302, {"Location": "next"}), FakeResponse(200)])
|
| 250 |
+
start = "https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/book.pdf"
|
| 251 |
+
result = await app.open_download_response(
|
| 252 |
+
session, start, aiohttp.ClientTimeout(total=1),
|
| 253 |
+
url_validator=app.validate_voiceofml_source_url,
|
| 254 |
+
)
|
| 255 |
+
self.assertEqual(result.status, 200)
|
| 256 |
+
self.assertEqual([url for url, _ in session.urls], [start, "https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/next"])
|
| 257 |
+
|
| 258 |
+
async def test_redirect_cannot_escape_voiceofml_dataset_scope(self):
|
| 259 |
+
first = FakeResponse(302, {"Location": "https://huggingface.co/datasets/Other/Test/resolve/main/book.pdf"})
|
| 260 |
+
start = "https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/book.pdf"
|
| 261 |
+
with self.assertRaises(ValueError):
|
| 262 |
+
await app.open_download_response(
|
| 263 |
+
FakeSession([first]), start, aiohttp.ClientTimeout(total=1),
|
| 264 |
+
url_validator=app.validate_voiceofml_source_url,
|
| 265 |
+
)
|
| 266 |
+
self.assertTrue(first.released)
|
| 267 |
+
|
| 268 |
+
async def test_redirect_cannot_escape_reader_assets_scope(self):
|
| 269 |
+
digest = "b" * 64
|
| 270 |
+
start = f"https://huggingface.co/datasets/vomebook/Reader-Assets/resolve/main/objects/aa/{digest}/document.pdf"
|
| 271 |
+
first = FakeResponse(302, {"Location": "/datasets/VoiceOfML/Test/resolve/main/book.pdf"})
|
| 272 |
+
with self.assertRaises(ValueError):
|
| 273 |
+
await app.open_download_response(
|
| 274 |
+
FakeSession([first]), start, aiohttp.ClientTimeout(total=1),
|
| 275 |
+
url_validator=app.validate_reader_source_url,
|
| 276 |
+
)
|
| 277 |
+
self.assertTrue(first.released)
|
| 278 |
+
|
| 279 |
+
async def test_multilayer_encoded_reader_assets_redirect_cannot_escape_scope(self):
|
| 280 |
+
digest = "b" * 64
|
| 281 |
+
start = f"https://huggingface.co/datasets/%252576omebook/Reader-Assets/resolve/main/objects/aa/{digest}/document.pdf"
|
| 282 |
+
first = FakeResponse(302, {"Location": "/datasets/VoiceOfML/Test/resolve/main/book.pdf"})
|
| 283 |
+
self.assertEqual(app.validate_reader_source_url(start), start)
|
| 284 |
+
with self.assertRaises(ValueError):
|
| 285 |
+
await app.open_download_response(
|
| 286 |
+
FakeSession([first, FakeResponse(200)]), start, aiohttp.ClientTimeout(total=1),
|
| 287 |
+
url_validator=app.validate_reader_source_url,
|
| 288 |
+
)
|
| 289 |
+
self.assertTrue(first.released)
|
| 290 |
+
|
| 291 |
+
async def test_redirect_to_disallowed_host_is_rejected_and_releases_first(self):
|
| 292 |
+
first = FakeResponse(302, {"Location": "https://evil.test/x"})
|
| 293 |
+
with self.assertRaises(ValueError):
|
| 294 |
+
await app.open_download_response(FakeSession([first]), "https://huggingface.co/x", aiohttp.ClientTimeout(total=1))
|
| 295 |
+
self.assertTrue(first.released)
|
| 296 |
+
|
| 297 |
+
async def test_redirect_without_location_is_rejected_and_released(self):
|
| 298 |
+
response = FakeResponse(302)
|
| 299 |
+
with self.assertRaises(ValueError):
|
| 300 |
+
await app.open_download_response(FakeSession([response]), "https://huggingface.co/x", aiohttp.ClientTimeout(total=1))
|
| 301 |
+
self.assertTrue(response.released)
|
| 302 |
+
|
| 303 |
+
async def test_too_many_redirects_are_rejected(self):
|
| 304 |
+
responses = [FakeResponse(302, {"Location": "/next"}) for _ in range(app.MAX_REDIRECTS + 1)]
|
| 305 |
+
with self.assertRaises(ValueError):
|
| 306 |
+
await app.open_download_response(FakeSession(responses), "https://huggingface.co/x", aiohttp.ClientTimeout(total=1))
|
| 307 |
+
|
| 308 |
+
async def test_resolved_redirect_target_is_reused_and_scoped(self):
|
| 309 |
+
start = "https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/cached.pdf"
|
| 310 |
+
final = "https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/actual.pdf"
|
| 311 |
+
first = FakeSession([FakeResponse(302, {"Location": "actual.pdf"}), FakeResponse(200)])
|
| 312 |
+
result = await app.open_download_response(
|
| 313 |
+
first, start, aiohttp.ClientTimeout(total=1),
|
| 314 |
+
url_validator=app.validate_voiceofml_source_url,
|
| 315 |
+
)
|
| 316 |
+
self.assertEqual(result.status, 200)
|
| 317 |
+
self.assertEqual([url for url, _ in first.urls], [start, final])
|
| 318 |
+
second = FakeSession([FakeResponse(200)])
|
| 319 |
+
result = await app.open_download_response(
|
| 320 |
+
second, start, aiohttp.ClientTimeout(total=1),
|
| 321 |
+
url_validator=app.validate_voiceofml_source_url,
|
| 322 |
+
)
|
| 323 |
+
self.assertEqual(result.status, 200)
|
| 324 |
+
self.assertEqual([url for url, _ in second.urls], [final])
|
| 325 |
+
|
| 326 |
+
async def test_rejected_redirect_target_falls_back_to_fresh_walk(self):
|
| 327 |
+
start = "https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/retry.pdf"
|
| 328 |
+
stale = "https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/stale.pdf"
|
| 329 |
+
fresh = "https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/fresh.pdf"
|
| 330 |
+
app.upstream_redirect_cache[("GET", start)] = (time.monotonic(), stale)
|
| 331 |
+
session = FakeSession([
|
| 332 |
+
FakeResponse(403), FakeResponse(302, {"Location": "fresh.pdf"}), FakeResponse(200),
|
| 333 |
+
])
|
| 334 |
+
result = await app.open_download_response(
|
| 335 |
+
session, start, aiohttp.ClientTimeout(total=1),
|
| 336 |
+
url_validator=app.validate_voiceofml_source_url,
|
| 337 |
+
)
|
| 338 |
+
self.assertEqual(result.status, 200)
|
| 339 |
+
self.assertEqual([url for url, _ in session.urls], [stale, start, fresh])
|
| 340 |
+
self.assertEqual(app.upstream_redirect_cache[("GET", start)][1], fresh)
|
| 341 |
+
|
| 342 |
+
async def test_out_of_scope_cached_target_is_ignored(self):
|
| 343 |
+
start = "https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/scope.pdf"
|
| 344 |
+
escaped = "https://huggingface.co/datasets/vomebook/Reader-Assets/resolve/main/objects/aa/" + "b" * 64 + "/document.pdf"
|
| 345 |
+
app.upstream_redirect_cache[("GET", start)] = (time.monotonic(), escaped)
|
| 346 |
+
session = FakeSession([FakeResponse(200)])
|
| 347 |
+
result = await app.open_download_response(
|
| 348 |
+
session, start, aiohttp.ClientTimeout(total=1),
|
| 349 |
+
)
|
| 350 |
+
self.assertEqual(result.status, 200)
|
| 351 |
+
self.assertEqual([url for url, _ in session.urls], [start])
|
| 352 |
+
|
| 353 |
+
async def test_non_redirect_response_is_returned_without_release(self):
|
| 354 |
+
response = FakeResponse(404)
|
| 355 |
+
result = await app.open_download_response(FakeSession([response]), "https://huggingface.co/x", aiohttp.ClientTimeout(total=1))
|
| 356 |
+
self.assertIs(result, response)
|
| 357 |
+
self.assertFalse(response.released)
|
| 358 |
+
|
| 359 |
+
async def test_download_rejects_external_source_before_session_call(self):
|
| 360 |
+
session = FakeSession([])
|
| 361 |
+
app.app.state.http_session = session
|
| 362 |
+
app.app.state.upstream_semaphore = asyncio.Semaphore(1)
|
| 363 |
+
result = await app.api_download("x.pdf", "https://evil.test/x")
|
| 364 |
+
self.assertEqual(result.status_code, 403)
|
| 365 |
+
self.assertEqual(session.urls, [])
|
| 366 |
+
|
| 367 |
+
async def test_download_upstream_error_releases_semaphore(self):
|
| 368 |
+
session = FakeSession([FakeResponse(502)])
|
| 369 |
+
semaphore = asyncio.Semaphore(1)
|
| 370 |
+
app.app.state.http_session = session
|
| 371 |
+
app.app.state.upstream_semaphore = semaphore
|
| 372 |
+
result = await app.api_download("x.pdf", "https://huggingface.co/datasets/VoiceOfML/A/x")
|
| 373 |
+
self.assertEqual(result.status_code, 502)
|
| 374 |
+
self.assertEqual(semaphore._value, 1)
|
| 375 |
+
|
| 376 |
+
async def test_download_cancellation_releases_semaphore(self):
|
| 377 |
+
semaphore = asyncio.Semaphore(1)
|
| 378 |
+
app.app.state.http_session = FakeSession([])
|
| 379 |
+
app.app.state.upstream_semaphore = semaphore
|
| 380 |
+
with patch.object(app, "open_download_response", AsyncMock(side_effect=asyncio.CancelledError)):
|
| 381 |
+
with self.assertRaises(asyncio.CancelledError):
|
| 382 |
+
await app.api_download("x.pdf", "https://huggingface.co/datasets/VoiceOfML/A/x")
|
| 383 |
+
self.assertEqual(semaphore._value, 1)
|
| 384 |
+
|
| 385 |
+
async def test_download_non_200_releases_upstream_and_semaphore(self):
|
| 386 |
+
upstream = FakeResponse(404)
|
| 387 |
+
app.app.state.http_session = FakeSession([upstream])
|
| 388 |
+
semaphore = asyncio.Semaphore(1)
|
| 389 |
+
app.app.state.upstream_semaphore = semaphore
|
| 390 |
+
result = await app.api_download("x.pdf", "https://huggingface.co/datasets/VoiceOfML/A/x")
|
| 391 |
+
self.assertEqual(result.status_code, 502)
|
| 392 |
+
self.assertTrue(upstream.released)
|
| 393 |
+
self.assertEqual(semaphore._value, 1)
|
| 394 |
+
|
| 395 |
+
async def test_download_response_stream_releases_resources_after_consumption(self):
|
| 396 |
+
upstream = FakeResponse(200, chunks=(b"a", b"b"))
|
| 397 |
+
app.app.state.http_session = FakeSession([upstream])
|
| 398 |
+
semaphore = asyncio.Semaphore(1)
|
| 399 |
+
app.app.state.upstream_semaphore = semaphore
|
| 400 |
+
response = await app.api_download("../book.pdf", "https://huggingface.co/datasets/VoiceOfML/A/x")
|
| 401 |
+
chunks = [chunk async for chunk in response.body_iterator]
|
| 402 |
+
self.assertEqual(chunks, [b"a", b"b"])
|
| 403 |
+
self.assertTrue(upstream.released)
|
| 404 |
+
self.assertEqual(semaphore._value, 1)
|
| 405 |
+
self.assertIn("filename*=UTF-8''book.pdf", response.headers["content-disposition"])
|
| 406 |
+
|
| 407 |
+
async def test_reader_content_forwards_range_and_preserves_partial_headers(self):
|
| 408 |
+
upstream = FakeResponse(206, {
|
| 409 |
+
"Content-Type": "application/pdf",
|
| 410 |
+
"Content-Length": "2",
|
| 411 |
+
"Content-Range": "bytes 0-1/10",
|
| 412 |
+
"Accept-Ranges": "bytes",
|
| 413 |
+
"ETag": '"reader"',
|
| 414 |
+
"Set-Cookie": "secret=1",
|
| 415 |
+
}, chunks=(b"ab",))
|
| 416 |
+
session = FakeSession([upstream])
|
| 417 |
+
semaphore = asyncio.Semaphore(1)
|
| 418 |
+
app.app.state.http_session = session
|
| 419 |
+
app.app.state.upstream_semaphore = semaphore
|
| 420 |
+
request = SimpleNamespace(method="GET", headers={
|
| 421 |
+
"Range": "bytes=0-1", "If-None-Match": '"reader"',
|
| 422 |
+
"If-Modified-Since": "Tue, 25 Aug 2026 00:00:00 GMT", "Cookie": "secret=1",
|
| 423 |
+
})
|
| 424 |
+
url = "https://huggingface.co/datasets/vomebook/Reader-Assets/resolve/main/objects/aa/" + "b" * 64 + "/document.pdf"
|
| 425 |
+
response = await app.api_reader_content(request, url)
|
| 426 |
+
self.assertEqual(response.status_code, 206)
|
| 427 |
+
self.assertEqual([chunk async for chunk in response.body_iterator], [b"ab"])
|
| 428 |
+
self.assertEqual(session.urls[0][1]["headers"], {
|
| 429 |
+
"Accept-Encoding": "identity", "Range": "bytes=0-1",
|
| 430 |
+
"If-None-Match": '"reader"', "If-Modified-Since": "Tue, 25 Aug 2026 00:00:00 GMT",
|
| 431 |
+
})
|
| 432 |
+
self.assertEqual(response.headers["content-range"], "bytes 0-1/10")
|
| 433 |
+
self.assertEqual(response.headers["content-length"], "2")
|
| 434 |
+
self.assertEqual(response.headers["content-encoding"], "identity")
|
| 435 |
+
self.assertIs(session.urls[0][1]["auto_decompress"], False)
|
| 436 |
+
self.assertNotIn("set-cookie", response.headers)
|
| 437 |
+
self.assertTrue(upstream.released)
|
| 438 |
+
self.assertEqual(semaphore._value, 1)
|
| 439 |
+
|
| 440 |
+
async def test_reader_content_reuses_completed_small_range_from_cache(self):
|
| 441 |
+
upstream = FakeResponse(206, {
|
| 442 |
+
"Content-Type": "application/pdf", "Content-Length": "2",
|
| 443 |
+
"Content-Range": "bytes 0-1/10", "Accept-Ranges": "bytes",
|
| 444 |
+
}, chunks=(b"ab",))
|
| 445 |
+
session = FakeSession([upstream])
|
| 446 |
+
app.app.state.http_session = session
|
| 447 |
+
app.app.state.upstream_semaphore = asyncio.Semaphore(1)
|
| 448 |
+
app.app.state.reader_range_cache = OrderedDict()
|
| 449 |
+
app.app.state.reader_range_cache_bytes = 0
|
| 450 |
+
request = SimpleNamespace(method="GET", headers={"Range": "bytes=0-1"})
|
| 451 |
+
url = "https://huggingface.co/datasets/vomebook/Reader-Assets/resolve/main/objects/aa/" + "b" * 64 + "/document.pdf"
|
| 452 |
+
first = await app.api_reader_content(request, url)
|
| 453 |
+
self.assertEqual([chunk async for chunk in first.body_iterator], [b"ab"])
|
| 454 |
+
second = await app.api_reader_content(request, url)
|
| 455 |
+
self.assertEqual(second.body, b"ab")
|
| 456 |
+
self.assertEqual(len(session.urls), 1)
|
| 457 |
+
|
| 458 |
+
async def test_reader_content_rejects_oversized_content_length_before_streaming(self):
|
| 459 |
+
upstream = FakeResponse(200, {"Content-Length": str(app.READER_DOCUMENT_MAX_BYTES + 1)}, chunks=(b"not-read",))
|
| 460 |
+
semaphore = asyncio.Semaphore(1)
|
| 461 |
+
app.app.state.http_session = FakeSession([upstream])
|
| 462 |
+
app.app.state.upstream_semaphore = semaphore
|
| 463 |
+
response = await app.api_reader_content(
|
| 464 |
+
SimpleNamespace(method="GET", headers={}),
|
| 465 |
+
"https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/book.pdf",
|
| 466 |
+
)
|
| 467 |
+
self.assertEqual(response.status_code, 413)
|
| 468 |
+
self.assertTrue(upstream.released)
|
| 469 |
+
self.assertEqual(semaphore._value, 1)
|
| 470 |
+
|
| 471 |
+
async def test_reader_content_rejects_oversized_range_total(self):
|
| 472 |
+
old_limit = app.READER_DOCUMENT_MAX_BYTES
|
| 473 |
+
app.READER_DOCUMENT_MAX_BYTES = 3
|
| 474 |
+
upstream = FakeResponse(206, {
|
| 475 |
+
"Content-Length": "1",
|
| 476 |
+
"Content-Range": "bytes 0-0/4",
|
| 477 |
+
}, chunks=(b"a",))
|
| 478 |
+
semaphore = asyncio.Semaphore(1)
|
| 479 |
+
app.app.state.http_session = FakeSession([upstream])
|
| 480 |
+
app.app.state.upstream_semaphore = semaphore
|
| 481 |
+
try:
|
| 482 |
+
response = await app.api_reader_content(
|
| 483 |
+
SimpleNamespace(method="GET", headers={}),
|
| 484 |
+
"https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/book.pdf",
|
| 485 |
+
)
|
| 486 |
+
finally:
|
| 487 |
+
app.READER_DOCUMENT_MAX_BYTES = old_limit
|
| 488 |
+
self.assertEqual(response.status_code, 413)
|
| 489 |
+
self.assertTrue(upstream.released)
|
| 490 |
+
self.assertEqual(semaphore._value, 1)
|
| 491 |
+
|
| 492 |
+
async def test_reader_content_enforces_actual_stream_limit_and_releases(self):
|
| 493 |
+
old_limit = app.READER_DOCUMENT_MAX_BYTES
|
| 494 |
+
app.READER_DOCUMENT_MAX_BYTES = 3
|
| 495 |
+
upstream = FakeResponse(200, {}, chunks=(b"ab", b"cd"))
|
| 496 |
+
semaphore = asyncio.Semaphore(1)
|
| 497 |
+
app.app.state.http_session = FakeSession([upstream])
|
| 498 |
+
app.app.state.upstream_semaphore = semaphore
|
| 499 |
+
try:
|
| 500 |
+
response = await app.api_reader_content(
|
| 501 |
+
SimpleNamespace(method="GET", headers={}),
|
| 502 |
+
"https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/book.pdf",
|
| 503 |
+
)
|
| 504 |
+
with self.assertRaises(app.ReaderDocumentLimitError):
|
| 505 |
+
[chunk async for chunk in response.body_iterator]
|
| 506 |
+
finally:
|
| 507 |
+
app.READER_DOCUMENT_MAX_BYTES = old_limit
|
| 508 |
+
self.assertTrue(upstream.released)
|
| 509 |
+
self.assertEqual(semaphore._value, 1)
|
| 510 |
+
|
| 511 |
+
async def test_reader_content_cancellation_releases_semaphore(self):
|
| 512 |
+
semaphore = asyncio.Semaphore(1)
|
| 513 |
+
app.app.state.upstream_semaphore = semaphore
|
| 514 |
+
request = SimpleNamespace(method="GET", headers={})
|
| 515 |
+
with patch.object(app, "open_download_response", AsyncMock(side_effect=asyncio.CancelledError)):
|
| 516 |
+
with self.assertRaises(asyncio.CancelledError):
|
| 517 |
+
await app.api_reader_content(
|
| 518 |
+
request, "https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/book.pdf"
|
| 519 |
+
)
|
| 520 |
+
self.assertEqual(semaphore._value, 1)
|
| 521 |
+
|
| 522 |
+
async def test_reader_content_head_releases_resources_without_streaming(self):
|
| 523 |
+
upstream = FakeResponse(200, {"Content-Length": "10", "Accept-Ranges": "bytes"})
|
| 524 |
+
session = FakeSession([upstream])
|
| 525 |
+
semaphore = asyncio.Semaphore(1)
|
| 526 |
+
app.app.state.http_session = session
|
| 527 |
+
app.app.state.upstream_semaphore = semaphore
|
| 528 |
+
request = SimpleNamespace(method="HEAD", headers={})
|
| 529 |
+
response = await app.api_reader_content(request, "https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/book.epub")
|
| 530 |
+
self.assertEqual(response.status_code, 200)
|
| 531 |
+
self.assertEqual(session.urls[0][1]["method"], "HEAD")
|
| 532 |
+
self.assertIs(session.urls[0][1]["auto_decompress"], False)
|
| 533 |
+
self.assertEqual(response.headers["content-length"], "10")
|
| 534 |
+
self.assertTrue(upstream.released)
|
| 535 |
+
self.assertEqual(semaphore._value, 1)
|
| 536 |
+
|
| 537 |
+
async def test_reader_content_rejects_external_source_before_session_call(self):
|
| 538 |
+
session = FakeSession([])
|
| 539 |
+
app.app.state.http_session = session
|
| 540 |
+
app.app.state.upstream_semaphore = asyncio.Semaphore(1)
|
| 541 |
+
result = await app.api_reader_content(SimpleNamespace(method="GET", headers={}), "https://evil.test/book.pdf")
|
| 542 |
+
self.assertEqual(result.status_code, 403)
|
| 543 |
+
self.assertEqual(session.urls, [])
|
| 544 |
+
|
| 545 |
+
async def test_download_check_upstream_error_returns_502_and_releases(self):
|
| 546 |
+
upstream = FakeResponse(503)
|
| 547 |
+
app.app.state.http_session = FakeSession([upstream])
|
| 548 |
+
result = await app.api_download_check("https://huggingface.co/datasets/VoiceOfML/A/x")
|
| 549 |
+
self.assertEqual(result.status_code, 502)
|
| 550 |
+
self.assertTrue(upstream.released)
|
| 551 |
+
|
| 552 |
+
async def test_download_check_uses_head_and_shared_semaphore(self):
|
| 553 |
+
upstream = FakeResponse(200)
|
| 554 |
+
session = FakeSession([upstream])
|
| 555 |
+
semaphore = asyncio.Semaphore(1)
|
| 556 |
+
app.app.state.http_session = session
|
| 557 |
+
app.app.state.upstream_semaphore = semaphore
|
| 558 |
+
result = await app.api_download_check("https://huggingface.co/datasets/VoiceOfML/A/x")
|
| 559 |
+
self.assertEqual(result.status_code, 200)
|
| 560 |
+
self.assertEqual(session.urls[0][1]["method"], "HEAD")
|
| 561 |
+
self.assertTrue(upstream.released)
|
| 562 |
+
self.assertEqual(semaphore._value, 1)
|
| 563 |
+
|
| 564 |
+
async def test_local_txt_file_is_served_without_remote_request(self):
|
| 565 |
+
with tempfile.TemporaryDirectory() as directory:
|
| 566 |
+
old_dir = app.TXT_DIR
|
| 567 |
+
app.TXT_DIR = Path(directory)
|
| 568 |
+
local = Path(directory) / "local.txt"
|
| 569 |
+
local.write_text("local", encoding="utf-8")
|
| 570 |
+
session = FakeSession([])
|
| 571 |
+
app.app.state.http_session = session
|
| 572 |
+
try:
|
| 573 |
+
response = await app.serve_txt_proxy("local.txt")
|
| 574 |
+
self.assertEqual(response.path, local)
|
| 575 |
+
self.assertEqual(session.urls, [])
|
| 576 |
+
finally:
|
| 577 |
+
app.TXT_DIR = old_dir
|
| 578 |
+
|
| 579 |
+
async def test_remote_txt_success_streams_content(self):
|
| 580 |
+
upstream = FakeResponse(200, chunks=(b"remote",))
|
| 581 |
+
app.app.state.http_session = FakeSession([upstream])
|
| 582 |
+
with tempfile.TemporaryDirectory() as directory, patch.object(app, "resolve_safe_txt_path", return_value=Path(directory) / "missing.txt"):
|
| 583 |
+
response = await app.serve_txt_proxy("remote.txt")
|
| 584 |
+
self.assertEqual([chunk async for chunk in response.body_iterator], [b"remote"])
|
| 585 |
+
self.assertTrue(upstream.released)
|
| 586 |
+
|
| 587 |
+
async def test_txt_traversal_is_400_without_remote_request(self):
|
| 588 |
+
session = FakeSession([])
|
| 589 |
+
app.app.state.http_session = session
|
| 590 |
+
response = await app.serve_txt_proxy("../secret.txt")
|
| 591 |
+
self.assertEqual(response.status_code, 400)
|
| 592 |
+
self.assertEqual(session.urls, [])
|
| 593 |
+
|
| 594 |
+
async def test_remote_txt_404_maps_to_404(self):
|
| 595 |
+
upstream = FakeResponse(404)
|
| 596 |
+
app.app.state.http_session = FakeSession([upstream])
|
| 597 |
+
with tempfile.TemporaryDirectory() as directory, patch.object(app, "resolve_safe_txt_path", return_value=Path(directory) / "missing.txt"):
|
| 598 |
+
response = await app.serve_txt_proxy("missing.txt")
|
| 599 |
+
self.assertEqual(response.status_code, 404)
|
| 600 |
+
self.assertTrue(upstream.released)
|
| 601 |
+
|
| 602 |
+
|
| 603 |
+
if __name__ == "__main__":
|
| 604 |
+
unittest.main()
|
tests/test_benchmark.py
ADDED
|
@@ -0,0 +1,245 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
import os
|
| 5 |
+
import socket
|
| 6 |
+
import statistics
|
| 7 |
+
import subprocess
|
| 8 |
+
import sys
|
| 9 |
+
import time
|
| 10 |
+
import unittest
|
| 11 |
+
from datetime import datetime, timezone
|
| 12 |
+
from urllib.request import Request, urlopen
|
| 13 |
+
|
| 14 |
+
IMPORT_ERROR = None
|
| 15 |
+
try:
|
| 16 |
+
import app
|
| 17 |
+
except ModuleNotFoundError as exc:
|
| 18 |
+
app = None
|
| 19 |
+
IMPORT_ERROR = exc
|
| 20 |
+
|
| 21 |
+
RESULTS_PATH = os.path.join(os.path.dirname(__file__), "benchmark-results.json")
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def _git_sha():
|
| 25 |
+
try:
|
| 26 |
+
return subprocess.run(
|
| 27 |
+
["git", "log", "-1", "--format=%H"],
|
| 28 |
+
capture_output=True, text=True, timeout=5,
|
| 29 |
+
).stdout.strip()
|
| 30 |
+
except Exception:
|
| 31 |
+
return ""
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def _save_results(project, queries):
|
| 35 |
+
existing = {"results": []}
|
| 36 |
+
if os.path.isfile(RESULTS_PATH):
|
| 37 |
+
try:
|
| 38 |
+
with open(RESULTS_PATH) as f:
|
| 39 |
+
existing = json.load(f)
|
| 40 |
+
except (json.JSONDecodeError, OSError):
|
| 41 |
+
pass
|
| 42 |
+
existing.setdefault("results", []).append({
|
| 43 |
+
"timestamp": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
|
| 44 |
+
"project": project,
|
| 45 |
+
"git_sha": _git_sha(),
|
| 46 |
+
"queries": queries,
|
| 47 |
+
})
|
| 48 |
+
existing["results"] = existing["results"][-50:]
|
| 49 |
+
with open(RESULTS_PATH, "w") as f:
|
| 50 |
+
json.dump(existing, f, indent=2, ensure_ascii=False)
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def _print_and_collect(results_list, label, iterations, times):
|
| 54 |
+
median = statistics.median(times)
|
| 55 |
+
mn = min(times)
|
| 56 |
+
mx = max(times)
|
| 57 |
+
print(f" {label:<46s} median={median:>8.3f}ms min={mn:>8.3f}ms max={mx:>8.3f}ms (n={iterations})")
|
| 58 |
+
results_list.append({
|
| 59 |
+
"label": label.strip(),
|
| 60 |
+
"iterations": iterations,
|
| 61 |
+
"median_ms": round(median, 3),
|
| 62 |
+
"min_ms": round(mn, 3),
|
| 63 |
+
"max_ms": round(mx, 3),
|
| 64 |
+
})
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def free_port():
|
| 68 |
+
with socket.socket() as sock:
|
| 69 |
+
sock.bind(("127.0.0.1", 0))
|
| 70 |
+
return sock.getsockname()[1]
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
# ---- shared server for API & browser tests ----
|
| 74 |
+
_server_proc = None
|
| 75 |
+
_server_port = None
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def start_server():
|
| 79 |
+
global _server_proc, _server_port
|
| 80 |
+
if _server_proc is not None:
|
| 81 |
+
return
|
| 82 |
+
_server_port = free_port()
|
| 83 |
+
_server_proc = subprocess.Popen(
|
| 84 |
+
[sys.executable, "-m", "uvicorn", "app:app",
|
| 85 |
+
"--host", "127.0.0.1", "--port", str(_server_port),
|
| 86 |
+
"--log-level", "error"],
|
| 87 |
+
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
|
| 88 |
+
)
|
| 89 |
+
for _ in range(120):
|
| 90 |
+
try:
|
| 91 |
+
with urlopen(f"http://127.0.0.1:{_server_port}/api/ping", timeout=2) as r:
|
| 92 |
+
if r.status == 204:
|
| 93 |
+
return
|
| 94 |
+
except Exception:
|
| 95 |
+
time.sleep(0.5)
|
| 96 |
+
stop_server()
|
| 97 |
+
raise RuntimeError("HF search server did not start")
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def stop_server():
|
| 101 |
+
global _server_proc, _server_port
|
| 102 |
+
if _server_proc:
|
| 103 |
+
try:
|
| 104 |
+
_server_proc.terminate()
|
| 105 |
+
_server_proc.wait(timeout=10)
|
| 106 |
+
except Exception:
|
| 107 |
+
_server_proc.kill()
|
| 108 |
+
_server_proc = None
|
| 109 |
+
_server_port = None
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
# ===== local benchmarks (pure function) =====
|
| 113 |
+
|
| 114 |
+
@unittest.skipIf(app is None, f"app dependencies unavailable: {IMPORT_ERROR}")
|
| 115 |
+
class LocalSearchBenchmarkTests(unittest.TestCase):
|
| 116 |
+
_results: list = []
|
| 117 |
+
|
| 118 |
+
@classmethod
|
| 119 |
+
def setUpClass(cls):
|
| 120 |
+
if app and not app.records:
|
| 121 |
+
app.load_data()
|
| 122 |
+
|
| 123 |
+
def _bench(self, label, fn, iterations=10):
|
| 124 |
+
times = []
|
| 125 |
+
for _ in range(iterations):
|
| 126 |
+
start = time.perf_counter()
|
| 127 |
+
fn()
|
| 128 |
+
elapsed = (time.perf_counter() - start) * 1000
|
| 129 |
+
times.append(elapsed)
|
| 130 |
+
_print_and_collect(self._results, label, iterations, times)
|
| 131 |
+
|
| 132 |
+
def test_benchmarks(self):
|
| 133 |
+
self._bench('"手机" normal', lambda: app.search("手机"))
|
| 134 |
+
self._bench('"手机" exact', lambda: app.search("手机", exact=True))
|
| 135 |
+
self._bench('"文化革命" exact', lambda: app.search("文化革命", exact=True))
|
| 136 |
+
self._bench('"文化 革命" normal', lambda: app.search("文化 革命"))
|
| 137 |
+
self._bench('"手。机" exact', lambda: app.search("手。机", exact=True))
|
| 138 |
+
self._bench('"手*机" exact', lambda: app.search("手*机", exact=True))
|
| 139 |
+
self._bench('"手?机" exact', lambda: app.search("手?机", exact=True))
|
| 140 |
+
self._bench('"文" exact', lambda: app.search("文", exact=True))
|
| 141 |
+
self._bench('"ABC" normal', lambda: app.search("ABC"))
|
| 142 |
+
self._bench('"手机" search_folders=False',
|
| 143 |
+
lambda: app.search("手机", search_folders=False))
|
| 144 |
+
self._bench('sort by name', lambda: app.search(page=1, page_size=100, sort="name"))
|
| 145 |
+
self._bench('sort by size', lambda: app.search(page=1, page_size=100, sort="size"))
|
| 146 |
+
|
| 147 |
+
@classmethod
|
| 148 |
+
def tearDownClass(cls):
|
| 149 |
+
if cls._results:
|
| 150 |
+
_save_results("huggingface-Search-local", cls._results)
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
# ===== API benchmarks (HTTP to local server) =====
|
| 154 |
+
|
| 155 |
+
class ApiSearchBenchmarkTests(unittest.TestCase):
|
| 156 |
+
_results: list = []
|
| 157 |
+
|
| 158 |
+
def _bench(self, label, path, payload=None, iterations=5):
|
| 159 |
+
body = json.dumps(payload).encode() if payload else None
|
| 160 |
+
req = Request(f"http://127.0.0.1:{_server_port}{path}", data=body,
|
| 161 |
+
headers={"Content-Type": "application/json"} if body else {})
|
| 162 |
+
times = []
|
| 163 |
+
for i in range(iterations + 1):
|
| 164 |
+
start = time.perf_counter()
|
| 165 |
+
with urlopen(req, timeout=60) as r:
|
| 166 |
+
r.read()
|
| 167 |
+
elapsed = (time.perf_counter() - start) * 1000
|
| 168 |
+
if i > 0:
|
| 169 |
+
times.append(elapsed)
|
| 170 |
+
_print_and_collect(self._results, label, iterations, times)
|
| 171 |
+
|
| 172 |
+
def test_search_api_benchmarks(self):
|
| 173 |
+
self._bench('"手机" normal', "/api/search", {"q": "手机"})
|
| 174 |
+
self._bench('"手机" exact', "/api/search", {"q": "手机", "exact": True})
|
| 175 |
+
self._bench('"文化革命" exact', "/api/search", {"q": "文化革命", "exact": True})
|
| 176 |
+
self._bench('"文化 革命" normal', "/api/search", {"q": "文化 革命"})
|
| 177 |
+
self._bench('"手。机" exact', "/api/search", {"q": "手。机", "exact": True})
|
| 178 |
+
self._bench('"手*机" exact', "/api/search", {"q": "手*机", "exact": True})
|
| 179 |
+
self._bench('"手?机" exact', "/api/search", {"q": "手?机", "exact": True})
|
| 180 |
+
self._bench('"文" exact', "/api/search", {"q": "文", "exact": True})
|
| 181 |
+
self._bench('"ABC" normal', "/api/search", {"q": "ABC"})
|
| 182 |
+
self._bench('repositories', "/api/repos")
|
| 183 |
+
|
| 184 |
+
@classmethod
|
| 185 |
+
def tearDownClass(cls):
|
| 186 |
+
if cls._results:
|
| 187 |
+
_save_results("huggingface-Search-api", cls._results)
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
# ===== browser benchmarks (Playwright) =====
|
| 191 |
+
|
| 192 |
+
try:
|
| 193 |
+
from playwright.sync_api import sync_playwright
|
| 194 |
+
except ImportError:
|
| 195 |
+
sync_playwright = None
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
@unittest.skipUnless(sync_playwright, "install requirements-test.txt, run: playwright install chromium")
|
| 199 |
+
class BrowserSearchBenchmarkTests(unittest.TestCase):
|
| 200 |
+
_results: list = []
|
| 201 |
+
|
| 202 |
+
@classmethod
|
| 203 |
+
def setUpClass(cls):
|
| 204 |
+
cls.playwright = sync_playwright().start()
|
| 205 |
+
cls.browser = cls.playwright.chromium.launch(
|
| 206 |
+
headless=True, args=["--no-sandbox", "--disable-gpu", "--disable-dev-shm-usage"])
|
| 207 |
+
|
| 208 |
+
@classmethod
|
| 209 |
+
def tearDownClass(cls):
|
| 210 |
+
if cls._results:
|
| 211 |
+
_save_results("huggingface-Search-browser", cls._results)
|
| 212 |
+
cls.browser.close()
|
| 213 |
+
cls.playwright.stop()
|
| 214 |
+
|
| 215 |
+
def _bench_search(self, label, query, iterations=3):
|
| 216 |
+
ctx = self.browser.new_context(viewport={"width": 1440, "height": 900})
|
| 217 |
+
page = ctx.new_page()
|
| 218 |
+
times = []
|
| 219 |
+
for i in range(iterations + 1):
|
| 220 |
+
page.goto(f"http://127.0.0.1:{_server_port}/")
|
| 221 |
+
page.wait_for_selector("#results-list .result-item", timeout=30000)
|
| 222 |
+
inp = page.locator("#search-input")
|
| 223 |
+
start = time.perf_counter()
|
| 224 |
+
inp.fill(query)
|
| 225 |
+
page.wait_for_function(f"""
|
| 226 |
+
new URLSearchParams(window.location.search).get('q') === {json.dumps(query)}
|
| 227 |
+
""", timeout=15000)
|
| 228 |
+
elapsed = (time.perf_counter() - start) * 1000
|
| 229 |
+
if i > 0:
|
| 230 |
+
times.append(elapsed)
|
| 231 |
+
ctx.close()
|
| 232 |
+
_print_and_collect(self._results, label, iterations, times)
|
| 233 |
+
|
| 234 |
+
def test_browser_search_benchmarks(self):
|
| 235 |
+
self._bench_search('"手机" normal', "手机")
|
| 236 |
+
self._bench_search('"文化革命" exact', "文化革命")
|
| 237 |
+
self._bench_search('"手*机" exact', "手*机")
|
| 238 |
+
|
| 239 |
+
|
| 240 |
+
def setUpModule():
|
| 241 |
+
start_server()
|
| 242 |
+
|
| 243 |
+
|
| 244 |
+
def tearDownModule():
|
| 245 |
+
stop_server()
|
tests/test_browser.py
ADDED
|
@@ -0,0 +1,834 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
import time
|
| 5 |
+
import unittest
|
| 6 |
+
|
| 7 |
+
try:
|
| 8 |
+
from .real_server import get_shared_server
|
| 9 |
+
except ImportError:
|
| 10 |
+
from real_server import get_shared_server
|
| 11 |
+
|
| 12 |
+
try:
|
| 13 |
+
from playwright.sync_api import Error as PlaywrightError
|
| 14 |
+
from playwright.sync_api import sync_playwright
|
| 15 |
+
except ImportError:
|
| 16 |
+
PlaywrightError = Exception
|
| 17 |
+
sync_playwright = None
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
@unittest.skipUnless(sync_playwright, "install requirements-test.txt and run: playwright install chromium")
|
| 21 |
+
class BrowserInteractionTests(unittest.TestCase):
|
| 22 |
+
@classmethod
|
| 23 |
+
def setUpClass(cls):
|
| 24 |
+
cls.server = get_shared_server()
|
| 25 |
+
cls.base_url = cls.server.base_url
|
| 26 |
+
cls.playwright = sync_playwright().start()
|
| 27 |
+
try:
|
| 28 |
+
cls.browser = cls.playwright.chromium.launch(headless=True, args=["--no-sandbox"])
|
| 29 |
+
except PlaywrightError as error:
|
| 30 |
+
cls.playwright.stop()
|
| 31 |
+
raise unittest.SkipTest(f"Chromium is unavailable: {error}")
|
| 32 |
+
|
| 33 |
+
@classmethod
|
| 34 |
+
def tearDownClass(cls):
|
| 35 |
+
cls.browser.close()
|
| 36 |
+
cls.playwright.stop()
|
| 37 |
+
|
| 38 |
+
def open_page(self, viewport=None, search_handler=None):
|
| 39 |
+
context = self.browser.new_context(viewport=viewport or {"width": 1440, "height": 900})
|
| 40 |
+
page = context.new_page()
|
| 41 |
+
errors = []
|
| 42 |
+
page.on("pageerror", lambda error: errors.append(str(error)))
|
| 43 |
+
result = {
|
| 44 |
+
"Repo": "VoiceOfML/Test", "File": "手机资料", "Extension": "txt",
|
| 45 |
+
"Folder": ["测试目录"], "Size": 1024, "HasTxt": True,
|
| 46 |
+
"Link": "https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/test.txt",
|
| 47 |
+
"Path": "https://huggingface.co/datasets/VoiceOfML/Test/blob/main/test.txt",
|
| 48 |
+
}
|
| 49 |
+
|
| 50 |
+
def route_api(route, request):
|
| 51 |
+
path = request.url.split(self.base_url, 1)[-1]
|
| 52 |
+
if path.startswith("/api/search"):
|
| 53 |
+
body = request.post_data_json or {}
|
| 54 |
+
if search_handler:
|
| 55 |
+
return search_handler(route, request, body, result)
|
| 56 |
+
payload = {"results": [result], "total": 1, "page": body.get("page", 1), "page_size": body.get("page_size", 100)}
|
| 57 |
+
elif path.startswith("/api/repos"):
|
| 58 |
+
payload = [{"name": "VoiceOfML/Test", "count": 1}]
|
| 59 |
+
elif path.startswith("/api/extensions"):
|
| 60 |
+
payload = [{"name": "txt", "count": 1}]
|
| 61 |
+
elif path.startswith("/api/folders/Test/contents"):
|
| 62 |
+
payload = {"folders": [], "files": [], "current_path": ""}
|
| 63 |
+
elif path.startswith("/api/folders/Test"):
|
| 64 |
+
payload = []
|
| 65 |
+
elif path.startswith("/api/random-txt/status"):
|
| 66 |
+
payload = {"available": True, "count": 1}
|
| 67 |
+
elif path.startswith("/api/random"):
|
| 68 |
+
payload = result
|
| 69 |
+
else:
|
| 70 |
+
payload = {}
|
| 71 |
+
route.fulfill(status=200, content_type="application/json", body=json.dumps(payload, ensure_ascii=False))
|
| 72 |
+
|
| 73 |
+
page.route(self.base_url + "/api/**", route_api)
|
| 74 |
+
page.route(
|
| 75 |
+
"https://vomebook-hitokoto.hf.space/**",
|
| 76 |
+
lambda route: route.fulfill(status=200, content_type="application/json", body='{"hitokoto":"test"}'),
|
| 77 |
+
)
|
| 78 |
+
page.goto(self.base_url + "/", wait_until="domcontentloaded")
|
| 79 |
+
page.locator("#search-input").wait_for(state="visible")
|
| 80 |
+
return context, page, errors
|
| 81 |
+
|
| 82 |
+
def test_desktop_search_theme_filters_and_keyboard(self):
|
| 83 |
+
context, page, errors = self.open_page()
|
| 84 |
+
try:
|
| 85 |
+
page.locator("#search-input").fill("手机")
|
| 86 |
+
page.locator("#results-list .result-item").filter(has_text="手机资料").wait_for(timeout=15000)
|
| 87 |
+
self.assertIn("q=", page.url)
|
| 88 |
+
original_class = page.locator("body").get_attribute("class")
|
| 89 |
+
page.locator("#theme-btn").click()
|
| 90 |
+
self.assertNotEqual(original_class, page.locator("body").get_attribute("class"))
|
| 91 |
+
page.locator("#settings-btn").click()
|
| 92 |
+
page.locator("#sort-select").select_option("name")
|
| 93 |
+
page.keyboard.press("Escape")
|
| 94 |
+
page.keyboard.press("/")
|
| 95 |
+
self.assertTrue(page.locator("#search-input").evaluate("node => document.activeElement === node"))
|
| 96 |
+
self.assertEqual(errors, [])
|
| 97 |
+
finally:
|
| 98 |
+
context.close()
|
| 99 |
+
|
| 100 |
+
def test_section_filter_cancel_buttons_follow_selected_state(self):
|
| 101 |
+
context, page, errors = self.open_page()
|
| 102 |
+
try:
|
| 103 |
+
page.locator("#settings-btn").click()
|
| 104 |
+
self.assertTrue(page.locator("#repo-filter-cancel").is_hidden())
|
| 105 |
+
page.locator("#filter-ext-list input").first.check()
|
| 106 |
+
page.locator("#ext-filter-cancel").wait_for(state="visible")
|
| 107 |
+
page.locator("#filter-repo-list input").first.check()
|
| 108 |
+
page.locator("#repo-filter-cancel").wait_for(state="visible")
|
| 109 |
+
page.locator("#repo-filter-cancel").click()
|
| 110 |
+
self.assertEqual(page.evaluate("STATE.filterRepos"), [])
|
| 111 |
+
self.assertNotEqual(page.evaluate("STATE.filterExtensions"), [])
|
| 112 |
+
page.locator("#ext-filter-cancel").click()
|
| 113 |
+
self.assertEqual(page.evaluate("STATE.filterExtensions"), [])
|
| 114 |
+
page.goto(self.base_url + "/MLMRL-Hub", wait_until="domcontentloaded")
|
| 115 |
+
page.locator("#search-input").wait_for(state="visible")
|
| 116 |
+
page.locator("#settings-btn").click()
|
| 117 |
+
page.evaluate("STATE.filterFolderSubtrees = ['archive']; updateFilterCancelButtons()")
|
| 118 |
+
page.locator("#folder-filter-cancel").click()
|
| 119 |
+
self.assertEqual(page.evaluate("[STATE.filterFolderSelfs, STATE.filterFolderSubtrees]"), [[], []])
|
| 120 |
+
self.assertNotIn("folder_subtree=", page.url)
|
| 121 |
+
self.assertEqual(errors, [])
|
| 122 |
+
finally:
|
| 123 |
+
context.close()
|
| 124 |
+
|
| 125 |
+
def test_repository_and_extension_filters_refresh_results(self):
|
| 126 |
+
search_bodies = []
|
| 127 |
+
|
| 128 |
+
def search_handler(route, request, body, result):
|
| 129 |
+
search_bodies.append(body)
|
| 130 |
+
filtered = dict(result)
|
| 131 |
+
if body.get("repos"):
|
| 132 |
+
filtered["File"] = "仓库筛选结果"
|
| 133 |
+
elif body.get("extensions"):
|
| 134 |
+
filtered["File"] = "类型筛选结果"
|
| 135 |
+
route.fulfill(
|
| 136 |
+
status=200,
|
| 137 |
+
content_type="application/json",
|
| 138 |
+
body=json.dumps({
|
| 139 |
+
"results": [filtered],
|
| 140 |
+
"total": 1,
|
| 141 |
+
"page": body.get("page", 1),
|
| 142 |
+
"page_size": body.get("page_size", 100),
|
| 143 |
+
}, ensure_ascii=False),
|
| 144 |
+
)
|
| 145 |
+
|
| 146 |
+
context, page, errors = self.open_page(search_handler=search_handler)
|
| 147 |
+
try:
|
| 148 |
+
page.locator("#settings-btn").click()
|
| 149 |
+
extension = page.locator("#filter-ext-list input").first
|
| 150 |
+
extension.check()
|
| 151 |
+
page.wait_for_function("STATE.results[0] && STATE.results[0].File === '类型筛选结果'", timeout=5000)
|
| 152 |
+
self.assertTrue(extension.is_checked())
|
| 153 |
+
self.assertTrue(any(body.get("extensions") == ["txt"] for body in search_bodies))
|
| 154 |
+
|
| 155 |
+
page.locator("#ext-filter-cancel").click()
|
| 156 |
+
page.wait_for_function("STATE.filterExtensions.length === 0", timeout=5000)
|
| 157 |
+
repository = page.locator("#filter-repo-list input").first
|
| 158 |
+
repository.check()
|
| 159 |
+
page.wait_for_function("STATE.results[0] && STATE.results[0].File === '仓库筛选结果'", timeout=5000)
|
| 160 |
+
self.assertTrue(repository.is_checked())
|
| 161 |
+
self.assertTrue(any(body.get("repos") == ["VoiceOfML/Test"] for body in search_bodies))
|
| 162 |
+
self.assertEqual(errors, [])
|
| 163 |
+
finally:
|
| 164 |
+
context.close()
|
| 165 |
+
|
| 166 |
+
def test_rapid_repository_filter_changes_are_coalesced(self):
|
| 167 |
+
search_bodies = []
|
| 168 |
+
|
| 169 |
+
def search_handler(route, request, body, result):
|
| 170 |
+
search_bodies.append(body)
|
| 171 |
+
filtered = dict(result)
|
| 172 |
+
if body.get("repos"):
|
| 173 |
+
filtered["File"] = "批量仓库筛选结果"
|
| 174 |
+
route.fulfill(
|
| 175 |
+
status=200,
|
| 176 |
+
content_type="application/json",
|
| 177 |
+
body=json.dumps({
|
| 178 |
+
"results": [filtered],
|
| 179 |
+
"total": 1,
|
| 180 |
+
"page": body.get("page", 1),
|
| 181 |
+
"page_size": body.get("page_size", 100),
|
| 182 |
+
}, ensure_ascii=False),
|
| 183 |
+
)
|
| 184 |
+
|
| 185 |
+
context, page, errors = self.open_page(search_handler=search_handler)
|
| 186 |
+
try:
|
| 187 |
+
page.locator("#settings-btn").click()
|
| 188 |
+
page.evaluate("""() => {
|
| 189 |
+
renderCheckboxList(DOM.filterRepoList, [
|
| 190 |
+
{key: 'VoiceOfML/Test', label: 'Test', count: 1},
|
| 191 |
+
{key: 'VoiceOfML/Other', label: 'Other', count: 1},
|
| 192 |
+
], [], vals => {
|
| 193 |
+
STATE.filterRepos = vals;
|
| 194 |
+
STATE.page = 1;
|
| 195 |
+
updateFilterCancelButtons();
|
| 196 |
+
scheduleFilterSearch();
|
| 197 |
+
});
|
| 198 |
+
const inputs = DOM.filterRepoList.querySelectorAll('input');
|
| 199 |
+
for (const input of inputs) {
|
| 200 |
+
input.checked = true;
|
| 201 |
+
input.dispatchEvent(new Event('change', {bubbles: true}));
|
| 202 |
+
}
|
| 203 |
+
}""")
|
| 204 |
+
page.wait_for_function("STATE.results[0] && STATE.results[0].File === '批量仓库筛选结果'", timeout=5000)
|
| 205 |
+
filtered_requests = [body for body in search_bodies if body.get("repos")]
|
| 206 |
+
self.assertEqual(len(filtered_requests), 1)
|
| 207 |
+
self.assertEqual(filtered_requests[0]["repos"], ["VoiceOfML/Test", "VoiceOfML/Other"])
|
| 208 |
+
self.assertEqual(errors, [])
|
| 209 |
+
finally:
|
| 210 |
+
context.close()
|
| 211 |
+
|
| 212 |
+
def test_folder_filter_checkbox_updates_and_searches(self):
|
| 213 |
+
context, page, errors = self.open_page()
|
| 214 |
+
try:
|
| 215 |
+
page.goto(self.base_url + "/MLMRL-Hub", wait_until="domcontentloaded")
|
| 216 |
+
page.locator("#search-input").wait_for(state="visible")
|
| 217 |
+
page.locator("#settings-btn").click()
|
| 218 |
+
page.locator("#filter-folder-section").wait_for(state="visible")
|
| 219 |
+
page.evaluate("""() => {
|
| 220 |
+
STATE.folderTree = [{
|
| 221 |
+
name: "根", path: "", count: 1, isRoot: true,
|
| 222 |
+
hasDirectFiles: false, hasChildren: true,
|
| 223 |
+
children: [{
|
| 224 |
+
name: "一级/二级", path: "一级/二级", count: 1,
|
| 225 |
+
hasDirectFiles: true, hasChildren: false,
|
| 226 |
+
children: []
|
| 227 |
+
}]
|
| 228 |
+
}];
|
| 229 |
+
STATE.folderTreeCollapsed = {};
|
| 230 |
+
initializeFolderTreeCollapsed(STATE.folderTree);
|
| 231 |
+
renderFilterFolderTree();
|
| 232 |
+
}""")
|
| 233 |
+
checkbox = page.locator("#filter-folder-tree .filter-folder-item input").last
|
| 234 |
+
checkbox.click()
|
| 235 |
+
page.wait_for_function("STATE.filterFolderSelfs.includes('一级/二级')", timeout=5000)
|
| 236 |
+
self.assertTrue(checkbox.is_checked(), page.evaluate("""() => ({
|
| 237 |
+
state: [STATE.filterFolderSelfs, STATE.filterFolderSubtrees],
|
| 238 |
+
inputs: [...document.querySelectorAll('#filter-folder-tree input')].map(input => [input.value, input.checked, input.indeterminate])
|
| 239 |
+
})"""))
|
| 240 |
+
self.assertEqual(errors, [])
|
| 241 |
+
finally:
|
| 242 |
+
context.close()
|
| 243 |
+
|
| 244 |
+
def test_desktop_result_order_and_action_heights(self):
|
| 245 |
+
context, page, errors = self.open_page()
|
| 246 |
+
try:
|
| 247 |
+
page.locator("#search-input").fill("手机")
|
| 248 |
+
row = page.locator("#results-list .result-item").filter(has_text="手机资料")
|
| 249 |
+
row.wait_for(timeout=15000)
|
| 250 |
+
layout = row.evaluate("""node => {
|
| 251 |
+
const rect = selector => node.querySelector(selector).getBoundingClientRect();
|
| 252 |
+
const title = rect('.result-title');
|
| 253 |
+
const actions = rect('.result-actions');
|
| 254 |
+
const path = rect('.result-path');
|
| 255 |
+
const meta = rect('.result-meta');
|
| 256 |
+
const buttons = [...node.querySelectorAll('.result-action-btn')].map(item => item.getBoundingClientRect().height);
|
| 257 |
+
return {
|
| 258 |
+
titleTop: title.top,
|
| 259 |
+
actionsTop: actions.top,
|
| 260 |
+
actionsBottom: actions.bottom,
|
| 261 |
+
pathTop: path.top,
|
| 262 |
+
pathBottom: path.bottom,
|
| 263 |
+
pathRight: path.right,
|
| 264 |
+
actionsLeft: actions.left,
|
| 265 |
+
metaTop: meta.top,
|
| 266 |
+
buttons,
|
| 267 |
+
};
|
| 268 |
+
}""")
|
| 269 |
+
self.assertAlmostEqual(layout["titleTop"], layout["actionsTop"], delta=1)
|
| 270 |
+
self.assertGreaterEqual(layout["pathTop"], layout["actionsBottom"] - 1)
|
| 271 |
+
self.assertGreaterEqual(layout["metaTop"], layout["pathBottom"])
|
| 272 |
+
self.assertGreater(layout["pathRight"], layout["actionsLeft"])
|
| 273 |
+
self.assertEqual(len(layout["buttons"]), 4)
|
| 274 |
+
self.assertTrue(all(abs(height - 24) < 0.1 for height in layout["buttons"]))
|
| 275 |
+
self.assertEqual(errors, [])
|
| 276 |
+
finally:
|
| 277 |
+
context.close()
|
| 278 |
+
|
| 279 |
+
def test_mobile_result_actions_use_compact_column(self):
|
| 280 |
+
context, page, errors = self.open_page({"width": 390, "height": 844})
|
| 281 |
+
try:
|
| 282 |
+
page.locator("#search-input").fill("手机")
|
| 283 |
+
row = page.locator("#results-list .result-item").filter(has_text="手机资料")
|
| 284 |
+
row.wait_for(timeout=15000)
|
| 285 |
+
layout = row.evaluate("""node => {
|
| 286 |
+
const actions = node.querySelector('.result-actions').getBoundingClientRect();
|
| 287 |
+
const buttons = [...node.querySelectorAll('.result-action-btn')].map(item => {
|
| 288 |
+
const rect = item.getBoundingClientRect();
|
| 289 |
+
return {height: rect.height, top: rect.top};
|
| 290 |
+
});
|
| 291 |
+
return {height: actions.height, buttons};
|
| 292 |
+
}""")
|
| 293 |
+
self.assertEqual(len(layout["buttons"]), 4)
|
| 294 |
+
self.assertTrue(all(abs(button["height"] - 20) < 0.1 for button in layout["buttons"]))
|
| 295 |
+
self.assertLessEqual(layout["height"], 83)
|
| 296 |
+
self.assertEqual(len({round(button["top"], 1) for button in layout["buttons"]}), 4)
|
| 297 |
+
self.assertEqual(errors, [])
|
| 298 |
+
finally:
|
| 299 |
+
context.close()
|
| 300 |
+
|
| 301 |
+
def test_mobile_long_folder_uses_remaining_path_line(self):
|
| 302 |
+
context, page, errors = self.open_page({"width": 390, "height": 844})
|
| 303 |
+
try:
|
| 304 |
+
layout = page.evaluate("""async () => {
|
| 305 |
+
STATE.results = [{
|
| 306 |
+
Repo: "VoiceOfML/VOMEBOOK",
|
| 307 |
+
File: "路径换行测试",
|
| 308 |
+
Extension: "pdf",
|
| 309 |
+
Folder: [
|
| 310 |
+
"马列之声ebook小组第七批成果集成(2018.8.17)",
|
| 311 |
+
"马列之声ebook小组第七批成果集成(2018.8.17)part 1a",
|
| 312 |
+
"2018.8 part 1",
|
| 313 |
+
],
|
| 314 |
+
Size: 1,
|
| 315 |
+
}];
|
| 316 |
+
STATE.total = 1;
|
| 317 |
+
STATE.hasMore = false;
|
| 318 |
+
resetVirtualScrollState();
|
| 319 |
+
renderResults();
|
| 320 |
+
await new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)));
|
| 321 |
+
const path = document.querySelector('.result-path');
|
| 322 |
+
const folders = [...path.querySelectorAll('.path-folder')];
|
| 323 |
+
const first = document.createRange();
|
| 324 |
+
first.selectNodeContents(folders[1]);
|
| 325 |
+
const repo = folders[0].getBoundingClientRect();
|
| 326 |
+
const firstRect = first.getClientRects()[0];
|
| 327 |
+
return {
|
| 328 |
+
repoTop: repo.top,
|
| 329 |
+
firstTop: firstRect.top,
|
| 330 |
+
firstLeft: firstRect.left,
|
| 331 |
+
separatorsNested: [...path.querySelectorAll('.path-sep')].every(sep => sep.parentElement.classList.contains('path-folder')),
|
| 332 |
+
};
|
| 333 |
+
}""")
|
| 334 |
+
self.assertAlmostEqual(layout["firstTop"], layout["repoTop"], delta=1)
|
| 335 |
+
self.assertGreater(layout["firstLeft"], 0)
|
| 336 |
+
self.assertTrue(layout["separatorsNested"])
|
| 337 |
+
self.assertEqual(errors, [])
|
| 338 |
+
finally:
|
| 339 |
+
context.close()
|
| 340 |
+
|
| 341 |
+
def test_mobile_sidebar_and_view_toggle(self):
|
| 342 |
+
context, page, errors = self.open_page({"width": 390, "height": 844})
|
| 343 |
+
try:
|
| 344 |
+
self.assertTrue(page.locator("body").evaluate("node => node.classList.contains('mobile')"))
|
| 345 |
+
was_open = page.locator("#left-sidebar").evaluate("node => node.classList.contains('open')")
|
| 346 |
+
page.locator("#hamburger-btn").click()
|
| 347 |
+
self.assertNotEqual(was_open, page.locator("#left-sidebar").evaluate("node => node.classList.contains('open')"))
|
| 348 |
+
page.locator("#mobile-toggle-btn").click()
|
| 349 |
+
self.assertFalse(page.locator("body").evaluate("node => node.classList.contains('mobile')"))
|
| 350 |
+
self.assertEqual(errors, [])
|
| 351 |
+
finally:
|
| 352 |
+
context.close()
|
| 353 |
+
|
| 354 |
+
def test_ime_composition_defers_search_until_composition_end(self):
|
| 355 |
+
requests = []
|
| 356 |
+
|
| 357 |
+
def record_search(route, request, body, result):
|
| 358 |
+
requests.append(body.get("q", ""))
|
| 359 |
+
payload = {"results": [result], "total": 1, "page": 1, "page_size": 100}
|
| 360 |
+
route.fulfill(status=200, content_type="application/json", body=json.dumps(payload, ensure_ascii=False))
|
| 361 |
+
|
| 362 |
+
context, page, errors = self.open_page(search_handler=record_search)
|
| 363 |
+
try:
|
| 364 |
+
requests.clear()
|
| 365 |
+
page.locator("#search-input").dispatch_event("compositionstart")
|
| 366 |
+
page.locator("#search-input").fill("手")
|
| 367 |
+
page.wait_for_timeout(300)
|
| 368 |
+
self.assertEqual(requests, [])
|
| 369 |
+
page.locator("#search-input").dispatch_event("compositionend")
|
| 370 |
+
page.wait_for_function("() => new URL(location.href).searchParams.get('q') === '手'")
|
| 371 |
+
self.assertIn("手", requests)
|
| 372 |
+
self.assertEqual(errors, [])
|
| 373 |
+
finally:
|
| 374 |
+
context.close()
|
| 375 |
+
|
| 376 |
+
def test_newer_search_result_wins_when_older_request_is_delayed(self):
|
| 377 |
+
context, page, errors = self.open_page()
|
| 378 |
+
try:
|
| 379 |
+
page.unroute(self.base_url + "/api/**")
|
| 380 |
+
|
| 381 |
+
def ordered(route, request):
|
| 382 |
+
path = request.url.split(self.base_url, 1)[-1]
|
| 383 |
+
if not path.startswith("/api/search"):
|
| 384 |
+
return route.fulfill(status=200, content_type="application/json", body="[]")
|
| 385 |
+
body = request.post_data_json or {}
|
| 386 |
+
query = body.get("q", "")
|
| 387 |
+
if query == "old":
|
| 388 |
+
time.sleep(0.4)
|
| 389 |
+
item = {"Repo": "VoiceOfML/Test", "File": query or "initial", "Extension": "txt", "Folder": [], "Size": 1, "HasTxt": False}
|
| 390 |
+
payload = {"results": [item], "total": 1, "page": 1, "page_size": 100}
|
| 391 |
+
route.fulfill(status=200, content_type="application/json", body=json.dumps(payload))
|
| 392 |
+
|
| 393 |
+
page.route(self.base_url + "/api/**", ordered)
|
| 394 |
+
page.locator("#search-input").fill("old")
|
| 395 |
+
page.wait_for_timeout(130)
|
| 396 |
+
page.locator("#search-input").fill("new")
|
| 397 |
+
page.locator("#results-list .result-item").filter(has_text="new").wait_for(timeout=10000)
|
| 398 |
+
self.assertEqual(page.locator("#results-list .result-title").first.text_content(), "new.txt")
|
| 399 |
+
self.assertEqual(errors, [])
|
| 400 |
+
finally:
|
| 401 |
+
context.close()
|
| 402 |
+
|
| 403 |
+
def test_virtual_scroll_settles_and_thumb_drag_stays_covered(self):
|
| 404 |
+
context, page, errors = self.open_page()
|
| 405 |
+
try:
|
| 406 |
+
result = page.evaluate("""async () => {
|
| 407 |
+
const repeat = (value, count) => Array(count).fill(value).join("");
|
| 408 |
+
STATE.results = Array.from({length: 800}, (_, index) => ({
|
| 409 |
+
Repo: "VoiceOfML/Test",
|
| 410 |
+
File: index % 4 === 1 ? `virtual-${index}-` + repeat("长标题", 45) : `virtual-${index}`,
|
| 411 |
+
Extension: "txt",
|
| 412 |
+
Folder: index % 4 >= 2 ? Array.from({length: 10}, (_, part) => `很长的目录-${index}-${part}`) : [],
|
| 413 |
+
Size: index + 1,
|
| 414 |
+
HasTxt: index % 4 === 3,
|
| 415 |
+
}));
|
| 416 |
+
STATE.total = STATE.results.length;
|
| 417 |
+
STATE.hasMore = false;
|
| 418 |
+
STATE.isLoading = false;
|
| 419 |
+
DOM.resultsContainer.scrollTop = 0;
|
| 420 |
+
resetVirtualScrollState();
|
| 421 |
+
renderResultsSkeleton();
|
| 422 |
+
renderResults();
|
| 423 |
+
await new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)));
|
| 424 |
+
const skeletonCount = DOM.resultsList.querySelectorAll(".result-skeleton-item").length;
|
| 425 |
+
|
| 426 |
+
const samples = [];
|
| 427 |
+
const container = DOM.resultsContainer;
|
| 428 |
+
for (const ratio of [0.82, 0.17, 0.94, 0.33, 0.7, 0.05, 1]) {
|
| 429 |
+
container.scrollTop = ratio * (container.scrollHeight - container.clientHeight);
|
| 430 |
+
container.dispatchEvent(new Event("scroll"));
|
| 431 |
+
await new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)));
|
| 432 |
+
const rect = container.getBoundingClientRect();
|
| 433 |
+
const hit = document.elementFromPoint(rect.left + rect.width / 2, rect.top + rect.height / 2);
|
| 434 |
+
const row = hit && hit.closest(".result-item");
|
| 435 |
+
samples.push(row && row.querySelector(".result-title") ? Number(row.dataset.index) : null);
|
| 436 |
+
}
|
| 437 |
+
|
| 438 |
+
container.scrollTop = 0.4 * (container.scrollHeight - container.clientHeight);
|
| 439 |
+
container.dispatchEvent(new Event("scroll"));
|
| 440 |
+
await new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)));
|
| 441 |
+
const appendRect = container.getBoundingClientRect();
|
| 442 |
+
const preservedRow = document.elementFromPoint(
|
| 443 |
+
appendRect.left + appendRect.width / 2,
|
| 444 |
+
appendRect.top + appendRect.height / 2,
|
| 445 |
+
).closest(".result-item");
|
| 446 |
+
const preservedIndex = preservedRow.dataset.index;
|
| 447 |
+
const heightBeforeAppend = container.scrollHeight;
|
| 448 |
+
const oldLength = STATE.results.length;
|
| 449 |
+
ensureHeightTree();
|
| 450 |
+
const heightTreeBeforeAppend = VSCROLL.heightTree;
|
| 451 |
+
STATE.results = STATE.results.concat(Array.from({length: 100}, (_, index) => ({
|
| 452 |
+
Repo: "VoiceOfML/Test", File: `appended-${index}`, Extension: "txt", Folder: [], Size: oldLength + index,
|
| 453 |
+
})));
|
| 454 |
+
refreshVirtualAfterAppend();
|
| 455 |
+
await new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)));
|
| 456 |
+
let naiveHeight = 0;
|
| 457 |
+
let prefixMatches = true;
|
| 458 |
+
for (let index = 0; index < VSCROLL.heights.length; index++) {
|
| 459 |
+
naiveHeight += VSCROLL.heights[index];
|
| 460 |
+
if (Math.abs(fenwickSum(VSCROLL.heightTree, index + 1) - naiveHeight) > 0.01) prefixMatches = false;
|
| 461 |
+
}
|
| 462 |
+
const measuredRow = DOM.resultsList.querySelector(`.result-item[data-index="${preservedIndex}"]`);
|
| 463 |
+
let repeatedReads = 0;
|
| 464 |
+
const originalRect = measuredRow.getBoundingClientRect.bind(measuredRow);
|
| 465 |
+
measuredRow.getBoundingClientRect = () => { repeatedReads++; return originalRect(); };
|
| 466 |
+
VSCROLL.measuredWindowKey = "";
|
| 467 |
+
measureHeights(VSCROLL.renderStart, VSCROLL.renderEnd);
|
| 468 |
+
const readsAtSameWidth = repeatedReads;
|
| 469 |
+
const originalWidth = DOM.resultsContainer.style.width;
|
| 470 |
+
DOM.resultsContainer.style.width = Math.max(200, container.clientWidth - 1) + "px";
|
| 471 |
+
VSCROLL.measuredWindowKey = "";
|
| 472 |
+
measureHeights(VSCROLL.renderStart, VSCROLL.renderEnd);
|
| 473 |
+
DOM.resultsContainer.style.width = originalWidth;
|
| 474 |
+
const preservedAfterAppend = preservedRow === DOM.resultsList.querySelector(`.result-item[data-index="${preservedIndex}"]`);
|
| 475 |
+
const treeExtendedInPlace = heightTreeBeforeAppend === VSCROLL.heightTree;
|
| 476 |
+
const heightAfterAppend = container.scrollHeight;
|
| 477 |
+
|
| 478 |
+
updateScrollTrack();
|
| 479 |
+
container.scrollTop = 0;
|
| 480 |
+
renderVisible();
|
| 481 |
+
const thumbRect = DOM.scrollThumb.getBoundingClientRect();
|
| 482 |
+
const trackRect = DOM.scrollTrack.getBoundingClientRect();
|
| 483 |
+
DOM.scrollThumb.dispatchEvent(new MouseEvent("mousedown", {
|
| 484 |
+
bubbles: true,
|
| 485 |
+
clientY: thumbRect.top + thumbRect.height / 2,
|
| 486 |
+
}));
|
| 487 |
+
for (let step = 1; step <= 40; step++) {
|
| 488 |
+
document.dispatchEvent(new MouseEvent("mousemove", {
|
| 489 |
+
bubbles: true,
|
| 490 |
+
clientY: thumbRect.top + thumbRect.height / 2 + (trackRect.height - thumbRect.height) * step / 40,
|
| 491 |
+
}));
|
| 492 |
+
}
|
| 493 |
+
const scrollTopBeforeDragFrame = container.scrollTop;
|
| 494 |
+
await new Promise(resolve => requestAnimationFrame(resolve));
|
| 495 |
+
const scrollTopAfterDragFrame = container.scrollTop;
|
| 496 |
+
const dragRect = container.getBoundingClientRect();
|
| 497 |
+
const dragHit = document.elementFromPoint(
|
| 498 |
+
dragRect.left + dragRect.width / 2,
|
| 499 |
+
dragRect.top + dragRect.height / 2,
|
| 500 |
+
);
|
| 501 |
+
const dragHitIndex = dragHit && dragHit.closest(".result-item")
|
| 502 |
+
? Number(dragHit.closest(".result-item").dataset.index)
|
| 503 |
+
: null;
|
| 504 |
+
const dragDomCount = DOM.resultsList.querySelectorAll(".result-item").length;
|
| 505 |
+
document.dispatchEvent(new MouseEvent("mouseup", {bubbles: true}));
|
| 506 |
+
return {
|
| 507 |
+
samples,
|
| 508 |
+
skeletonCount,
|
| 509 |
+
preservedAfterAppend,
|
| 510 |
+
heightBeforeAppend,
|
| 511 |
+
heightAfterAppend,
|
| 512 |
+
treeExtendedInPlace,
|
| 513 |
+
prefixMatches,
|
| 514 |
+
readsAtSameWidth,
|
| 515 |
+
readsAfterWidthChange: repeatedReads,
|
| 516 |
+
scrollTopBeforeDragFrame,
|
| 517 |
+
scrollTopAfterDragFrame,
|
| 518 |
+
dragHitIndex,
|
| 519 |
+
dragDomCount,
|
| 520 |
+
draggingAfterMouseUp: VSCROLL.isDraggingThumb,
|
| 521 |
+
};
|
| 522 |
+
}""")
|
| 523 |
+
self.assertTrue(all(index is not None for index in result["samples"]))
|
| 524 |
+
self.assertEqual(result["skeletonCount"], 0)
|
| 525 |
+
self.assertTrue(result["preservedAfterAppend"])
|
| 526 |
+
self.assertGreater(result["heightAfterAppend"], result["heightBeforeAppend"])
|
| 527 |
+
self.assertTrue(result["treeExtendedInPlace"])
|
| 528 |
+
self.assertTrue(result["prefixMatches"])
|
| 529 |
+
self.assertEqual(result["readsAtSameWidth"], 0)
|
| 530 |
+
self.assertGreater(result["readsAfterWidthChange"], result["readsAtSameWidth"])
|
| 531 |
+
self.assertEqual(result["scrollTopBeforeDragFrame"], 0)
|
| 532 |
+
self.assertGreater(result["scrollTopAfterDragFrame"], result["scrollTopBeforeDragFrame"])
|
| 533 |
+
self.assertIsNotNone(result["dragHitIndex"])
|
| 534 |
+
self.assertLess(result["dragDomCount"], 50)
|
| 535 |
+
self.assertFalse(result["draggingAfterMouseUp"])
|
| 536 |
+
self.assertEqual(errors, [])
|
| 537 |
+
finally:
|
| 538 |
+
context.close()
|
| 539 |
+
|
| 540 |
+
def test_url_filter_roundtrip_restores_query_sort_and_size(self):
|
| 541 |
+
context, page, errors = self.open_page()
|
| 542 |
+
try:
|
| 543 |
+
page.goto(self.base_url + "/?q=phone&sort=name&min_size=1KB&max_size=2MB&search_folders=false&exact=0", wait_until="domcontentloaded")
|
| 544 |
+
page.locator("#search-input").wait_for(state="visible")
|
| 545 |
+
self.assertEqual(page.locator("#search-input").input_value(), "phone")
|
| 546 |
+
self.assertEqual(page.locator("#sort-select").input_value(), "name")
|
| 547 |
+
self.assertEqual(page.locator("#filter-min-size").input_value(), "1")
|
| 548 |
+
self.assertEqual(page.locator("#filter-min-unit").input_value(), "KB")
|
| 549 |
+
self.assertFalse(page.locator("#search-folders-toggle").is_checked())
|
| 550 |
+
self.assertFalse(page.locator("#exact-search-toggle").is_checked())
|
| 551 |
+
self.assertEqual(errors, [])
|
| 552 |
+
finally:
|
| 553 |
+
context.close()
|
| 554 |
+
|
| 555 |
+
def test_repository_folder_filters_remain_in_url_after_reload(self):
|
| 556 |
+
context, page, errors = self.open_page()
|
| 557 |
+
try:
|
| 558 |
+
url = self.base_url + "/MLMRL-Hub?folder_self=docs&folder_subtree=archive%2F2026"
|
| 559 |
+
page.goto(url, wait_until="domcontentloaded")
|
| 560 |
+
page.locator("#search-input").wait_for(state="visible")
|
| 561 |
+
page.wait_for_function("() => STATE.filterFolderSelfs.includes('docs') && STATE.filterFolderSubtrees.includes('archive/2026')")
|
| 562 |
+
self.assertEqual(page.url.count("folder_self=docs"), 1)
|
| 563 |
+
self.assertEqual(page.url.count("folder_subtree=archive%2F2026"), 1)
|
| 564 |
+
page.reload(wait_until="domcontentloaded")
|
| 565 |
+
page.locator("#search-input").wait_for(state="visible")
|
| 566 |
+
page.wait_for_function("() => STATE.filterFolderSelfs.includes('docs') && STATE.filterFolderSubtrees.includes('archive/2026')")
|
| 567 |
+
self.assertIn("folder_self=docs", page.url)
|
| 568 |
+
self.assertIn("folder_subtree=archive%2F2026", page.url)
|
| 569 |
+
self.assertEqual(errors, [])
|
| 570 |
+
finally:
|
| 571 |
+
context.close()
|
| 572 |
+
|
| 573 |
+
def test_random_book_uses_deterministic_api_result(self):
|
| 574 |
+
context, page, errors = self.open_page()
|
| 575 |
+
try:
|
| 576 |
+
page.locator("#random-book-btn").click()
|
| 577 |
+
page.locator("#toast").filter(has_text="开始下载").wait_for(timeout=5000)
|
| 578 |
+
iframe = page.locator('iframe[src^="/api/download?"]')
|
| 579 |
+
iframe.wait_for(state="attached")
|
| 580 |
+
self.assertIn("file=", iframe.get_attribute("src"))
|
| 581 |
+
self.assertEqual(errors, [])
|
| 582 |
+
finally:
|
| 583 |
+
context.close()
|
| 584 |
+
|
| 585 |
+
def test_reader_path_returns_to_matching_folder_filter(self):
|
| 586 |
+
context, page, errors = self.open_page()
|
| 587 |
+
try:
|
| 588 |
+
reader_url = page.evaluate("""() => getReaderLink({
|
| 589 |
+
Repo: "VoiceOfML/Test",
|
| 590 |
+
File: "路径测试",
|
| 591 |
+
Extension: "txt",
|
| 592 |
+
Folder: ["一级目录", "二级目录"],
|
| 593 |
+
HasTxt: true,
|
| 594 |
+
Link: "https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/reader.txt",
|
| 595 |
+
})""")
|
| 596 |
+
page.goto(self.base_url + reader_url, wait_until="domcontentloaded")
|
| 597 |
+
path = page.locator("#reader-path")
|
| 598 |
+
path.wait_for(state="visible", timeout=10000)
|
| 599 |
+
self.assertEqual(path.text_content(), "Test/一级目录/二级目录")
|
| 600 |
+
self.assertTrue(page.locator("#status").is_hidden())
|
| 601 |
+
path.click()
|
| 602 |
+
page.wait_for_url("**/Test?**", timeout=10000)
|
| 603 |
+
target = page.evaluate("() => ({pathname: location.pathname, folders: new URL(location.href).searchParams.getAll('folder_self')})")
|
| 604 |
+
self.assertEqual(target["pathname"], "/Test")
|
| 605 |
+
self.assertEqual(target["folders"], ["一级目录/二级目录"])
|
| 606 |
+
self.assertEqual(errors, [])
|
| 607 |
+
finally:
|
| 608 |
+
context.close()
|
| 609 |
+
|
| 610 |
+
def test_cancelled_extension_filter_is_not_restored_by_stale_reader_link(self):
|
| 611 |
+
context, page, errors = self.open_page()
|
| 612 |
+
try:
|
| 613 |
+
page.evaluate("STATE.filterExtensions = ['pdf']")
|
| 614 |
+
stale_reader_url = page.evaluate("""() => getReaderLink({
|
| 615 |
+
Repo: "VoiceOfML/Test", File: "路径测试", Extension: "txt", Folder: ["docs"], HasTxt: true,
|
| 616 |
+
Link: "https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/path.txt",
|
| 617 |
+
})""")
|
| 618 |
+
page.evaluate("STATE.filterExtensions = []; saveStoredExtensionFilters()")
|
| 619 |
+
folder_url = page.evaluate("url => new URL(syncReaderFolderFilter(url), location.origin).searchParams.get('folder_url') || ''", stale_reader_url)
|
| 620 |
+
self.assertNotIn("ext=", folder_url)
|
| 621 |
+
self.assertEqual(errors, [])
|
| 622 |
+
finally:
|
| 623 |
+
context.close()
|
| 624 |
+
|
| 625 |
+
def test_reader_back_closes_overlay_without_reloading_search(self):
|
| 626 |
+
context, page, errors = self.open_page()
|
| 627 |
+
try:
|
| 628 |
+
page.locator("#search-input").fill("手机")
|
| 629 |
+
page.wait_for_function("() => STATE.query === '手机' && new URL(location.href).searchParams.get('q') === '手机'")
|
| 630 |
+
marker = page.evaluate("() => { window.__readerReturnMarker = Math.random(); return window.__readerReturnMarker; }")
|
| 631 |
+
reader_url = page.evaluate("""() => getReaderLink({
|
| 632 |
+
Repo: "VoiceOfML/Test", File: "返回测试", Extension: "txt", Folder: [], HasTxt: true,
|
| 633 |
+
Link: "https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/return.txt",
|
| 634 |
+
})""")
|
| 635 |
+
search_url = page.url
|
| 636 |
+
page.locator("#search-input").focus()
|
| 637 |
+
page.evaluate("""() => {
|
| 638 |
+
const stale = new URL('/static/reader.html?nav=stale', location.origin).href;
|
| 639 |
+
sessionStorage.setItem('reader-return:stale', location.href);
|
| 640 |
+
sessionStorage.setItem('reader-navigation-current', JSON.stringify({readerUrl: stale, shareUrl: stale}));
|
| 641 |
+
}""")
|
| 642 |
+
page.evaluate("url => navigateToReader(url)", reader_url)
|
| 643 |
+
self.assertEqual(page.evaluate("() => location.pathname"), "/static/reader.html")
|
| 644 |
+
self.assertNotIn("return=", page.url)
|
| 645 |
+
self.assertNotIn("nav=", page.url)
|
| 646 |
+
self.assertIsNone(page.evaluate("() => sessionStorage.getItem('reader-return:stale')"))
|
| 647 |
+
self.assertEqual(page.evaluate("() => Object.keys(sessionStorage).filter(key => key.startsWith('reader-return:')).length"), 1)
|
| 648 |
+
reader = page.frame_locator("iframe.reader-overlay")
|
| 649 |
+
reader.locator("#back").wait_for(state="visible")
|
| 650 |
+
initial_dark = page.evaluate("() => STATE.isDark")
|
| 651 |
+
reader.locator("#history").click()
|
| 652 |
+
reader.locator("#theme-toggle").click()
|
| 653 |
+
page.wait_for_function("initial => STATE.isDark !== initial", arg=initial_dark)
|
| 654 |
+
self.assertEqual(reader.locator("html").get_attribute("data-theme"), "light" if initial_dark else "dark")
|
| 655 |
+
reader.locator("#theme-toggle").click()
|
| 656 |
+
page.wait_for_function("initial => STATE.isDark === initial", arg=initial_dark)
|
| 657 |
+
reader.locator("#history-close").click()
|
| 658 |
+
page.wait_for_function("() => document.activeElement === document.querySelector('iframe.reader-overlay')")
|
| 659 |
+
self.assertGreater(page.locator("body > [inert]").count(), 0)
|
| 660 |
+
reader.locator("#back").click()
|
| 661 |
+
page.locator("iframe.reader-overlay").wait_for(state="detached")
|
| 662 |
+
self.assertEqual(page.url, search_url)
|
| 663 |
+
self.assertEqual(page.evaluate("() => window.__readerReturnMarker"), marker)
|
| 664 |
+
self.assertTrue(page.locator("#search-input").evaluate("el => el === document.activeElement"))
|
| 665 |
+
self.assertEqual(page.locator("body > [inert]").count(), 0)
|
| 666 |
+
self.assertEqual(page.evaluate("() => performance.getEntriesByType('navigation')[0].type"), "navigate")
|
| 667 |
+
page.go_forward(wait_until="commit")
|
| 668 |
+
page.locator("iframe.reader-overlay").wait_for(state="attached")
|
| 669 |
+
self.assertEqual(page.evaluate("() => location.pathname"), "/static/reader.html")
|
| 670 |
+
page.evaluate("() => history.replaceState(null, '', location.href)")
|
| 671 |
+
page.reload(wait_until="domcontentloaded")
|
| 672 |
+
page.locator("#back").click()
|
| 673 |
+
page.locator("#search-input").wait_for(state="visible")
|
| 674 |
+
self.assertEqual(page.url, search_url)
|
| 675 |
+
page.wait_for_function("() => STATE.query === '手机'")
|
| 676 |
+
self.assertEqual(page.evaluate("() => Object.keys(sessionStorage).filter(key => key.startsWith('reader-return:')).length"), 0)
|
| 677 |
+
self.assertIsNone(page.evaluate("() => sessionStorage.getItem('reader-navigation-current')"))
|
| 678 |
+
self.assertEqual(errors, [])
|
| 679 |
+
finally:
|
| 680 |
+
context.close()
|
| 681 |
+
|
| 682 |
+
def test_reader_back_restores_virtual_search_scroll(self):
|
| 683 |
+
context, page, errors = self.open_page()
|
| 684 |
+
try:
|
| 685 |
+
before = page.evaluate("""async () => {
|
| 686 |
+
STATE.results = Array.from({length: 240}, (_, index) => ({
|
| 687 |
+
Repo: "VoiceOfML/Test",
|
| 688 |
+
File: `返回滚动-${index}`,
|
| 689 |
+
Extension: "txt",
|
| 690 |
+
Folder: index % 3 === 0 ? ["目录", `分组-${index}`] : [],
|
| 691 |
+
Size: index + 1,
|
| 692 |
+
HasTxt: true,
|
| 693 |
+
}));
|
| 694 |
+
STATE.total = STATE.results.length;
|
| 695 |
+
STATE.hasMore = false;
|
| 696 |
+
STATE.isLoading = false;
|
| 697 |
+
resetVirtualScrollState();
|
| 698 |
+
renderResults();
|
| 699 |
+
await new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)));
|
| 700 |
+
DOM.resultsContainer.scrollTop = 520;
|
| 701 |
+
DOM.resultsContainer.dispatchEvent(new Event("scroll"));
|
| 702 |
+
await new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)));
|
| 703 |
+
return DOM.resultsContainer.scrollTop;
|
| 704 |
+
}""")
|
| 705 |
+
self.assertGreater(before, 0)
|
| 706 |
+
page.evaluate("url => navigateToReader(url)", "/static/reader.html?title=返回滚动")
|
| 707 |
+
page.locator("iframe.reader-overlay").wait_for(state="attached")
|
| 708 |
+
page.evaluate("history.back()")
|
| 709 |
+
page.locator("iframe.reader-overlay").wait_for(state="detached")
|
| 710 |
+
page.wait_for_function(
|
| 711 |
+
"expected => Math.abs(DOM.resultsContainer.scrollTop - expected) <= 1",
|
| 712 |
+
arg=before,
|
| 713 |
+
timeout=10000,
|
| 714 |
+
)
|
| 715 |
+
self.assertEqual(page.evaluate("DOM.resultsContainer.scrollTop"), before)
|
| 716 |
+
self.assertEqual(errors, [])
|
| 717 |
+
finally:
|
| 718 |
+
context.close()
|
| 719 |
+
|
| 720 |
+
def test_search_snapshot_restores_results_and_page_cache(self):
|
| 721 |
+
context, page, errors = self.open_page()
|
| 722 |
+
try:
|
| 723 |
+
restored = page.evaluate("""async () => {
|
| 724 |
+
const first = [
|
| 725 |
+
{Repo: "VoiceOfML/Test", File: "快照一", Extension: "txt", Folder: ["目录"], Size: 1},
|
| 726 |
+
{Repo: "VoiceOfML/Test", File: "快照二", Extension: "txt", Folder: [], Size: 2},
|
| 727 |
+
];
|
| 728 |
+
STATE.query = "快照查询";
|
| 729 |
+
DOM.searchInput.value = STATE.query;
|
| 730 |
+
STATE.results = first;
|
| 731 |
+
STATE.total = 2;
|
| 732 |
+
STATE.page = 2;
|
| 733 |
+
STATE._loadedPage = 2;
|
| 734 |
+
STATE._pageCache = {1: first.slice(0, 1), 2: first.slice(1)};
|
| 735 |
+
STATE.hasMore = true;
|
| 736 |
+
STATE.isLoading = false;
|
| 737 |
+
resetVirtualScrollState();
|
| 738 |
+
renderResults();
|
| 739 |
+
await new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)));
|
| 740 |
+
const key = getSearchViewKey();
|
| 741 |
+
saveSearchViewSnapshot(key);
|
| 742 |
+
STATE.query = "另一个查询";
|
| 743 |
+
DOM.searchInput.value = STATE.query;
|
| 744 |
+
STATE.results = [];
|
| 745 |
+
STATE.total = 0;
|
| 746 |
+
STATE.page = 1;
|
| 747 |
+
STATE._loadedPage = 0;
|
| 748 |
+
STATE._pageCache = {};
|
| 749 |
+
renderResults();
|
| 750 |
+
STATE.query = "快照查询";
|
| 751 |
+
DOM.searchInput.value = STATE.query;
|
| 752 |
+
const didRestore = restoreSearchViewSnapshot(getSearchViewKey(), false);
|
| 753 |
+
return {
|
| 754 |
+
didRestore,
|
| 755 |
+
files: STATE.results.map(result => result.File),
|
| 756 |
+
total: STATE.total,
|
| 757 |
+
page: STATE.page,
|
| 758 |
+
loadedPage: STATE._loadedPage,
|
| 759 |
+
cachedPages: Object.keys(STATE._pageCache).sort(),
|
| 760 |
+
};
|
| 761 |
+
}""")
|
| 762 |
+
self.assertTrue(restored["didRestore"])
|
| 763 |
+
self.assertEqual(restored["files"], ["快照一", "快照二"])
|
| 764 |
+
self.assertEqual(restored["total"], 2)
|
| 765 |
+
self.assertEqual(restored["page"], 2)
|
| 766 |
+
self.assertEqual(restored["loadedPage"], 2)
|
| 767 |
+
self.assertEqual(restored["cachedPages"], ["1", "2"])
|
| 768 |
+
self.assertEqual(errors, [])
|
| 769 |
+
finally:
|
| 770 |
+
context.close()
|
| 771 |
+
|
| 772 |
+
def test_reader_history_switch_updates_parent_url_and_state(self):
|
| 773 |
+
context, page, errors = self.open_page()
|
| 774 |
+
try:
|
| 775 |
+
page.locator("#search-input").fill("历史切书")
|
| 776 |
+
first_url = page.evaluate("""() => getReaderLink({
|
| 777 |
+
Repo: "VoiceOfML/Test", File: "第一本", Extension: "txt", Folder: [], HasTxt: true,
|
| 778 |
+
Link: "https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/first.txt",
|
| 779 |
+
})""")
|
| 780 |
+
second_url = page.evaluate("""() => new URL(getReaderLink({
|
| 781 |
+
Repo: "VoiceOfML/Test", File: "第二本", Extension: "txt", Folder: [], HasTxt: true,
|
| 782 |
+
Link: "https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/second.txt",
|
| 783 |
+
}), location.origin).href""")
|
| 784 |
+
search_url = page.url
|
| 785 |
+
page.evaluate("url => navigateToReader(url)", first_url)
|
| 786 |
+
page.frame_locator("iframe.reader-overlay").locator("#back").wait_for()
|
| 787 |
+
reader_frame = next(frame for frame in page.frames if frame.parent_frame is not None and "/static/reader.html" in frame.url)
|
| 788 |
+
reader_frame.evaluate("""async (readerUrl) => VoiceOfMLReaderStore.put({
|
| 789 |
+
url: 'https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/second.txt',
|
| 790 |
+
title: '第二本.txt', extension: 'txt', readerUrl, page: 1, pageCount: 0, lastReadAt: Date.now()
|
| 791 |
+
})""", second_url)
|
| 792 |
+
reader_frame.locator("#history").click()
|
| 793 |
+
reader_frame.locator('.reader-panel-tabs button[data-panel="history"]').click()
|
| 794 |
+
reader_frame.locator("#history-list .panel-item-main").filter(has_text="第二本.txt").click()
|
| 795 |
+
page.wait_for_function("() => new URL(location.href).searchParams.get('title') === '第二本.txt'")
|
| 796 |
+
self.assertEqual(page.evaluate("() => new URL(history.state.readerUrl).searchParams.get('title')"), "第二本.txt")
|
| 797 |
+
page.frame_locator("iframe.reader-overlay").locator("#title").filter(has_text="第二本.txt").wait_for()
|
| 798 |
+
page.frame_locator("iframe.reader-overlay").locator("#back").click()
|
| 799 |
+
page.locator("iframe.reader-overlay").wait_for(state="detached")
|
| 800 |
+
self.assertEqual(page.url, search_url)
|
| 801 |
+
self.assertEqual(errors, [])
|
| 802 |
+
finally:
|
| 803 |
+
context.close()
|
| 804 |
+
|
| 805 |
+
def test_indexeddb_restores_last_search_but_explicit_url_wins(self):
|
| 806 |
+
context, page, errors = self.open_page()
|
| 807 |
+
try:
|
| 808 |
+
page.goto(self.base_url + "/?q=持久搜索&ext=pdf&filters=1", wait_until="domcontentloaded")
|
| 809 |
+
page.locator("#search-input").wait_for(state="visible")
|
| 810 |
+
page.wait_for_function("() => STATE.query === '持久搜索' && STATE.filterExtensions.includes('pdf')")
|
| 811 |
+
page.wait_for_function("""async () => {
|
| 812 |
+
const db = await openSearchSessionDB();
|
| 813 |
+
const tx = db.transaction('session', 'readonly');
|
| 814 |
+
const request = tx.objectStore('session').get('last-search');
|
| 815 |
+
const saved = await new Promise((resolve, reject) => { request.onsuccess = () => resolve(request.result); request.onerror = reject; });
|
| 816 |
+
db.close();
|
| 817 |
+
return saved && saved.url.includes(encodeURIComponent('持久搜索'));
|
| 818 |
+
}""")
|
| 819 |
+
page.close()
|
| 820 |
+
page = context.new_page()
|
| 821 |
+
page.on("pageerror", lambda error: errors.append(str(error)))
|
| 822 |
+
page.goto(self.base_url + "/", wait_until="domcontentloaded")
|
| 823 |
+
page.locator("#search-input").wait_for(state="visible")
|
| 824 |
+
page.wait_for_function("() => STATE.query === '持久搜索' && STATE.filterExtensions.includes('pdf') && STATE.rightSidebarOpen")
|
| 825 |
+
page.goto(self.base_url + "/?q=显式搜索&ext=txt", wait_until="domcontentloaded")
|
| 826 |
+
page.locator("#search-input").wait_for(state="visible")
|
| 827 |
+
page.wait_for_function("() => STATE.query === '显式搜索' && STATE.filterExtensions.length === 1 && STATE.filterExtensions[0] === 'txt'")
|
| 828 |
+
self.assertEqual(errors, [])
|
| 829 |
+
finally:
|
| 830 |
+
context.close()
|
| 831 |
+
|
| 832 |
+
|
| 833 |
+
if __name__ == "__main__":
|
| 834 |
+
unittest.main()
|
tests/test_cache_and_malformed.py
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import copy
|
| 4 |
+
import gzip
|
| 5 |
+
import tempfile
|
| 6 |
+
import unittest
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
|
| 9 |
+
IMPORT_ERROR = None
|
| 10 |
+
try:
|
| 11 |
+
import app
|
| 12 |
+
except ModuleNotFoundError as exc: # pragma: no cover
|
| 13 |
+
app = None
|
| 14 |
+
IMPORT_ERROR = exc
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
@unittest.skipIf(app is None, f"app dependencies unavailable: {IMPORT_ERROR}")
|
| 18 |
+
class CacheAndMalformedTests(unittest.TestCase):
|
| 19 |
+
def setUp(self):
|
| 20 |
+
self.cache = copy.deepcopy(app.api_response_cache)
|
| 21 |
+
|
| 22 |
+
def tearDown(self):
|
| 23 |
+
app.api_response_cache = self.cache
|
| 24 |
+
|
| 25 |
+
def test_cache_returns_same_value_before_ttl(self):
|
| 26 |
+
app.api_response_cache.clear()
|
| 27 |
+
self.assertEqual(app.cached_payload("key", lambda: 1), 1)
|
| 28 |
+
self.assertEqual(app.cached_payload("key", lambda: 2), 1)
|
| 29 |
+
|
| 30 |
+
def test_cache_rebuilds_after_ttl(self):
|
| 31 |
+
app.api_response_cache = {"key": (0, "old")}
|
| 32 |
+
original = app.time.monotonic
|
| 33 |
+
app.time.monotonic = lambda: app.API_CACHE_TTL_SECONDS + 1
|
| 34 |
+
try:
|
| 35 |
+
self.assertEqual(app.cached_payload("key", lambda: "new"), "new")
|
| 36 |
+
finally:
|
| 37 |
+
app.time.monotonic = original
|
| 38 |
+
|
| 39 |
+
def test_cache_eviction_removes_oldest_when_over_500(self):
|
| 40 |
+
app.api_response_cache.clear()
|
| 41 |
+
for i in range(500):
|
| 42 |
+
app.api_response_cache[i] = (i, i)
|
| 43 |
+
app.cached_payload(500, lambda: 500)
|
| 44 |
+
self.assertNotIn(0, app.api_response_cache)
|
| 45 |
+
self.assertIn(500, app.api_response_cache)
|
| 46 |
+
|
| 47 |
+
def test_cache_eviction_retains_newer_entries(self):
|
| 48 |
+
app.api_response_cache.clear()
|
| 49 |
+
for i in range(500):
|
| 50 |
+
app.api_response_cache[i] = (i, i)
|
| 51 |
+
app.cached_payload("new", lambda: "value")
|
| 52 |
+
self.assertEqual(app.api_response_cache[499][1], 499)
|
| 53 |
+
|
| 54 |
+
def test_cache_keys_distinguish_equalish_options(self):
|
| 55 |
+
app.api_response_cache.clear()
|
| 56 |
+
app.cached_payload(("search", "x", "name"), lambda: "name")
|
| 57 |
+
app.cached_payload(("search", "x", "size"), lambda: "size")
|
| 58 |
+
self.assertEqual(len(app.api_response_cache), 2)
|
| 59 |
+
|
| 60 |
+
def test_generation_invalidates_folder_and_initial_payload_caches(self):
|
| 61 |
+
old_generation = app._data_generation
|
| 62 |
+
old_tree = app.folder_tree_data
|
| 63 |
+
old_browser = app.folder_browser_data
|
| 64 |
+
old_global = app.initial_payload_global
|
| 65 |
+
old_by_repo = app.initial_payload_by_repo
|
| 66 |
+
try:
|
| 67 |
+
app.api_response_cache.clear()
|
| 68 |
+
app.folder_tree_data = {"VoiceOfML/Test": [{"name": "old"}]}
|
| 69 |
+
app.folder_browser_data = {"VoiceOfML/Test": {"": {"files": [{"name": "old"}], "folders": []}}}
|
| 70 |
+
app.initial_payload_global = {"generation": "old"}
|
| 71 |
+
app.initial_payload_by_repo = {"VoiceOfML/Test": {"generation": "old"}}
|
| 72 |
+
first_tree = app.cached_payload(("folders", "VoiceOfML/Test"), lambda: app.folder_tree_data["VoiceOfML/Test"])
|
| 73 |
+
first_contents = app.cached_payload(("folder_contents", "VoiceOfML/Test", ""), lambda: app.folder_browser_data["VoiceOfML/Test"][""])
|
| 74 |
+
first_global = app.cached_payload(("initial_global",), lambda: app.initial_payload_global)
|
| 75 |
+
first_repo = app.cached_payload(("initial_repo", "VoiceOfML/Test"), lambda: app.initial_payload_by_repo["VoiceOfML/Test"])
|
| 76 |
+
first_manifest = app.cached_payload(("initial_manifest",), lambda: {"generation": "old"})
|
| 77 |
+
app._data_generation += 1
|
| 78 |
+
app.folder_tree_data = {"VoiceOfML/Test": [{"name": "new"}]}
|
| 79 |
+
app.folder_browser_data = {"VoiceOfML/Test": {"": {"files": [{"name": "new"}], "folders": []}}}
|
| 80 |
+
app.initial_payload_global = {"generation": "new"}
|
| 81 |
+
app.initial_payload_by_repo = {"VoiceOfML/Test": {"generation": "new"}}
|
| 82 |
+
second_tree = app.cached_payload(("folders", app._data_generation, "VoiceOfML/Test"), lambda: app.folder_tree_data["VoiceOfML/Test"])
|
| 83 |
+
second_contents = app.cached_payload(("folder_contents", app._data_generation, "VoiceOfML/Test", ""), lambda: app.folder_browser_data["VoiceOfML/Test"][""])
|
| 84 |
+
second_global = app.cached_payload(("initial_global", app._data_generation), lambda: app.initial_payload_global)
|
| 85 |
+
second_repo = app.cached_payload(("initial_repo", app._data_generation, "VoiceOfML/Test"), lambda: app.initial_payload_by_repo["VoiceOfML/Test"])
|
| 86 |
+
second_manifest = app.cached_payload(("initial_manifest", app._data_generation), lambda: {"generation": "new"})
|
| 87 |
+
self.assertEqual(first_tree[0]["name"], "old")
|
| 88 |
+
self.assertEqual(first_contents["files"][0]["name"], "old")
|
| 89 |
+
self.assertEqual(first_global["generation"], "old")
|
| 90 |
+
self.assertEqual(first_repo["generation"], "old")
|
| 91 |
+
self.assertEqual(first_manifest["generation"], "old")
|
| 92 |
+
self.assertEqual(second_tree[0]["name"], "new")
|
| 93 |
+
self.assertEqual(second_contents["files"][0]["name"], "new")
|
| 94 |
+
self.assertEqual(second_global["generation"], "new")
|
| 95 |
+
self.assertEqual(second_repo["generation"], "new")
|
| 96 |
+
self.assertEqual(second_manifest["generation"], "new")
|
| 97 |
+
finally:
|
| 98 |
+
app._data_generation = old_generation
|
| 99 |
+
app.folder_tree_data = old_tree
|
| 100 |
+
app.folder_browser_data = old_browser
|
| 101 |
+
app.initial_payload_global = old_global
|
| 102 |
+
app.initial_payload_by_repo = old_by_repo
|
| 103 |
+
|
| 104 |
+
def test_decode_search_non_mapping_is_empty(self):
|
| 105 |
+
self.assertEqual(app.decode_search_payload(None), [])
|
| 106 |
+
self.assertEqual(app.decode_search_payload("bad"), [])
|
| 107 |
+
self.assertEqual(app.decode_search_payload(3), [])
|
| 108 |
+
|
| 109 |
+
def test_decode_search_empty_and_nested_list_are_empty(self):
|
| 110 |
+
self.assertEqual(app.decode_search_payload([]), [])
|
| 111 |
+
self.assertEqual(app.decode_search_payload([["already", "nested"]]), [])
|
| 112 |
+
|
| 113 |
+
def test_decode_search_missing_compact_sections_is_empty(self):
|
| 114 |
+
self.assertEqual(app.decode_search_payload({"rc": [[0, "x", "txt", 0, 1, 0]]}), [{"Repo": "", "File": "x", "Extension": "txt", "Folder": [], "Size": 1, "HasTxt": False}])
|
| 115 |
+
|
| 116 |
+
def test_decode_tree_none_is_empty_mapping(self):
|
| 117 |
+
self.assertEqual(app.decode_folder_tree_data(None), {})
|
| 118 |
+
|
| 119 |
+
def test_decode_browser_none_is_empty_mapping(self):
|
| 120 |
+
self.assertEqual(app.decode_folder_browser_data(None), {})
|
| 121 |
+
|
| 122 |
+
def test_legacy_full_record_payload_is_rejected(self):
|
| 123 |
+
self.assertEqual(app.decode_search_payload([{"Repo": "A", "File": "x"}]), [])
|
| 124 |
+
|
| 125 |
+
def test_legacy_vng2_index_is_rejected(self):
|
| 126 |
+
digest = b"x" * 32
|
| 127 |
+
payload = b"VNG2" + bytes([2]) + digest + b"\x00\x00"
|
| 128 |
+
with tempfile.TemporaryDirectory() as directory:
|
| 129 |
+
path = Path(directory) / "legacy.bin.gz"
|
| 130 |
+
path.write_bytes(gzip.compress(payload))
|
| 131 |
+
self.assertEqual(app.load_ngram_index(path, 2, 0, digest), ({}, b""))
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
if __name__ == "__main__":
|
| 135 |
+
unittest.main()
|
tests/test_data_decoding.py
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import unittest
|
| 4 |
+
|
| 5 |
+
IMPORT_ERROR = None
|
| 6 |
+
try:
|
| 7 |
+
import app
|
| 8 |
+
except ModuleNotFoundError as exc: # pragma: no cover - environment dependent
|
| 9 |
+
app = None
|
| 10 |
+
IMPORT_ERROR = exc
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
@unittest.skipIf(app is None, f"app dependencies unavailable: {IMPORT_ERROR}")
|
| 14 |
+
class DataDecodingTests(unittest.TestCase):
|
| 15 |
+
def test_compact_records_decode_and_invalid_indexes_are_safe(self):
|
| 16 |
+
data = {"rp": ["Repo/A"], "fd": [["books"]], "rc": [[0, "novel", "pdf", 0, 12, 1], [4, "bad", "txt", 9, 0, 0], [0, "short"]]}
|
| 17 |
+
self.assertEqual(app.decode_search_payload(data), [{
|
| 18 |
+
"Repo": "Repo/A", "File": "novel", "Extension": "pdf",
|
| 19 |
+
"Folder": ["books"], "Size": 12, "HasTxt": True,
|
| 20 |
+
}, {
|
| 21 |
+
"Repo": "", "File": "bad", "Extension": "txt",
|
| 22 |
+
"Folder": [], "Size": 0, "HasTxt": False,
|
| 23 |
+
}])
|
| 24 |
+
|
| 25 |
+
def test_tree_decoding_derives_paths_and_toggle_semantics(self):
|
| 26 |
+
result = app.decode_folder_tree_data({"Repo/A": [{"n": "root", "df": True, "ch": [{"n": "child", "df": True}]}]})["Repo/A"][0]
|
| 27 |
+
self.assertTrue(result["isRoot"])
|
| 28 |
+
self.assertEqual(result["path"], "")
|
| 29 |
+
child = result["children"][0]
|
| 30 |
+
self.assertEqual(child["path"], "child")
|
| 31 |
+
self.assertFalse(child["showSelfToggle"])
|
| 32 |
+
|
| 33 |
+
def test_legacy_long_tree_fields_are_not_decoded(self):
|
| 34 |
+
result = app.decode_folder_tree_data({"Repo/A": [{"name": "legacy", "children": []}]})["Repo/A"][0]
|
| 35 |
+
self.assertEqual(result["name"], "")
|
| 36 |
+
|
| 37 |
+
def test_browser_decoding_preserves_folder_semantics_and_file_size(self):
|
| 38 |
+
result = app.decode_folder_browser_data({"Repo/A": {"books": {"d": [{"n": "part", "c": 2}], "f": [{"n": "book", "e": "pdf", "s": 0}]}}})["Repo/A"]["books"]
|
| 39 |
+
self.assertEqual(result["current_path"], "books")
|
| 40 |
+
self.assertEqual(result["folders"][0]["path"], "books/part")
|
| 41 |
+
self.assertEqual(result["files"][0]["size"], 0)
|
| 42 |
+
|
| 43 |
+
def test_legacy_long_browser_fields_are_not_decoded(self):
|
| 44 |
+
result = app.decode_folder_browser_data({"Repo/A": {"": {"folders": [{"name": "legacy"}], "files": []}}})["Repo/A"][""]
|
| 45 |
+
self.assertEqual(result["folders"], [])
|
| 46 |
+
|
| 47 |
+
def test_record_and_browser_names_do_not_duplicate_extensions(self):
|
| 48 |
+
self.assertEqual(app.build_browser_file_name({"name": "book.PDF", "ext": "pdf"}), "book.PDF")
|
| 49 |
+
self.assertEqual(app.build_browser_file_name({"name": "book", "ext": "pdf"}), "book.pdf")
|
| 50 |
+
self.assertEqual(app.build_txt_relative_path({"File": "book", "Extension": "pdf", "Folder": ["a"]}), "a/book.txt")
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
if __name__ == "__main__":
|
| 54 |
+
unittest.main()
|
tests/test_fastapi_endpoints.py
ADDED
|
@@ -0,0 +1,425 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import copy
|
| 4 |
+
import json
|
| 5 |
+
import tempfile
|
| 6 |
+
import time
|
| 7 |
+
import unittest
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
from unittest import mock
|
| 10 |
+
|
| 11 |
+
IMPORT_ERROR = None
|
| 12 |
+
try:
|
| 13 |
+
import app
|
| 14 |
+
from fastapi.testclient import TestClient
|
| 15 |
+
except ModuleNotFoundError as exc: # pragma: no cover
|
| 16 |
+
app = None
|
| 17 |
+
TestClient = None
|
| 18 |
+
IMPORT_ERROR = exc
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
@unittest.skipIf(app is None or TestClient is None, f"FastAPI dependencies unavailable: {IMPORT_ERROR}")
|
| 22 |
+
class FastApiEndpointTests(unittest.TestCase):
|
| 23 |
+
def setUp(self):
|
| 24 |
+
self.saved = {name: copy.deepcopy(getattr(app, name)) for name in ("records", "repo_counts", "repo_list", "repo_records_map", "extension_counts", "extension_list", "repo_extension_counts", "folder_index", "folder_tree_data", "folder_browser_data", "api_response_cache", "initial_payload_global", "initial_payload_by_repo", "reader_record_indices", "repo_reader_record_indices", "reader_record_key_indices", "reader_assets_cache", "reader_assets_cache_at")}
|
| 25 |
+
self.saved["reader_source_id_indices"] = copy.deepcopy(app.reader_source_id_indices)
|
| 26 |
+
app.records = [{"Repo": "VoiceOfML/Test", "File": "readme", "Extension": "txt", "Folder": ["docs"], "Size": 10, "HasTxt": True}]
|
| 27 |
+
app.reader_assets_cache = {"v": 1, "f": {}}
|
| 28 |
+
app.reader_assets_cache_at = time.monotonic()
|
| 29 |
+
app.build_indexes()
|
| 30 |
+
app.build_initial_payloads()
|
| 31 |
+
self.client = TestClient(app.app)
|
| 32 |
+
|
| 33 |
+
def tearDown(self):
|
| 34 |
+
for name, value in self.saved.items():
|
| 35 |
+
setattr(app, name, value)
|
| 36 |
+
|
| 37 |
+
def test_search_endpoint_accepts_valid_json(self):
|
| 38 |
+
response = self.client.post("/api/search", json={"q": "readme", "page_size": 1})
|
| 39 |
+
self.assertEqual(response.status_code, 200)
|
| 40 |
+
self.assertEqual(response.json()["total"], 1)
|
| 41 |
+
self.assertNotIn("server-timing", response.headers)
|
| 42 |
+
|
| 43 |
+
def test_search_endpoint_rejects_malformed_json(self):
|
| 44 |
+
self.assertEqual(self.client.post("/api/search", content="not-json", headers={"content-type": "application/json"}).status_code, 422)
|
| 45 |
+
|
| 46 |
+
def test_search_endpoint_rejects_wrong_field_type(self):
|
| 47 |
+
self.assertEqual(self.client.post("/api/search", json={"page_size": "many"}).status_code, 422)
|
| 48 |
+
|
| 49 |
+
def test_search_endpoint_rejects_unsupported_enum_values(self):
|
| 50 |
+
sort_response = self.client.post("/api/search", json={"sort": "random"})
|
| 51 |
+
folder_response = self.client.post("/api/search", json={"folder_match_mode": "contains"})
|
| 52 |
+
self.assertEqual(sort_response.status_code, 422)
|
| 53 |
+
self.assertEqual(folder_response.status_code, 422)
|
| 54 |
+
self.assertIn("relevance", sort_response.json()["detail"][0]["msg"])
|
| 55 |
+
self.assertIn("prefix", folder_response.json()["detail"][0]["msg"])
|
| 56 |
+
|
| 57 |
+
def test_search_endpoint_bounds_query_and_list_inputs(self):
|
| 58 |
+
self.assertEqual(self.client.post("/api/search", json={"q": "x" * 257}).status_code, 422)
|
| 59 |
+
self.assertEqual(self.client.post("/api/search", json={"repos": ["Repo"] * 101}).status_code, 422)
|
| 60 |
+
|
| 61 |
+
def test_repo_search_endpoint_returns_repo_results(self):
|
| 62 |
+
response = self.client.post("/api/search/Test", json={"q": "readme"})
|
| 63 |
+
self.assertEqual(response.status_code, 200)
|
| 64 |
+
self.assertEqual(response.json()["results"][0]["Repo"], "VoiceOfML/Test")
|
| 65 |
+
|
| 66 |
+
def test_unknown_repo_search_is_404(self):
|
| 67 |
+
self.assertEqual(self.client.post("/api/search/Missing", json={}).status_code, 404)
|
| 68 |
+
|
| 69 |
+
def test_repos_extensions_and_status_endpoints(self):
|
| 70 |
+
repos = self.client.get("/api/repos")
|
| 71 |
+
self.assertEqual(repos.json()[0]["name"], "VoiceOfML/Test")
|
| 72 |
+
self.assertIn("max-age=300", repos.headers["cache-control"])
|
| 73 |
+
self.assertEqual(self.client.get("/api/extensions").json(), [{"name": "txt", "count": 1}])
|
| 74 |
+
self.assertEqual(self.client.get("/api/random-txt/status").json(), {"available": True, "count": 1})
|
| 75 |
+
self.assertEqual(self.client.get("/api/random-reader/status").json(), {"available": True, "count": 1})
|
| 76 |
+
|
| 77 |
+
def test_bootstrap_combines_global_startup_data(self):
|
| 78 |
+
response = self.client.get("/api/bootstrap")
|
| 79 |
+
self.assertEqual(response.status_code, 200)
|
| 80 |
+
payload = response.json()
|
| 81 |
+
self.assertEqual(payload["generation"], app._data_generation)
|
| 82 |
+
self.assertEqual(payload["repos"][0]["name"], "VoiceOfML/Test")
|
| 83 |
+
self.assertEqual(payload["extensions"], [{"name": "txt", "count": 1}])
|
| 84 |
+
self.assertEqual(payload["random_txt"], {"available": True, "count": 1})
|
| 85 |
+
self.assertIn("sidebar", payload)
|
| 86 |
+
self.assertIn("max-age=300", response.headers["cache-control"])
|
| 87 |
+
|
| 88 |
+
def test_folder_tree_and_contents_endpoints(self):
|
| 89 |
+
self.assertEqual(self.client.get("/api/folders/Test").status_code, 200)
|
| 90 |
+
self.assertEqual(self.client.get("/api/folders/Test/contents", params={"path": "docs"}).json()["files"][0]["name"], "readme")
|
| 91 |
+
|
| 92 |
+
def test_folder_and_initial_caches_include_generation(self):
|
| 93 |
+
app.folder_tree_data = {"VoiceOfML/Test": [{"name": "old"}]}
|
| 94 |
+
app.folder_browser_data = {"VoiceOfML/Test": {"": {"folders": [], "files": [{"name": "old"}]}}}
|
| 95 |
+
app.initial_payload_global = {"generation": "old"}
|
| 96 |
+
app.initial_payload_by_repo = {"VoiceOfML/Test": {"generation": "old"}}
|
| 97 |
+
old_generation = app._data_generation
|
| 98 |
+
try:
|
| 99 |
+
self.assertEqual(self.client.get("/api/folders/Test").json()[0]["name"], "old")
|
| 100 |
+
self.assertEqual(self.client.get("/api/folders/Test/contents").json()["files"][0]["name"], "old")
|
| 101 |
+
self.assertEqual(self.client.get("/data/initial/global.json").json()["generation"], "old")
|
| 102 |
+
self.assertEqual(self.client.get("/data/initial/repos/Test.json").json()["generation"], "old")
|
| 103 |
+
self.assertNotIn("generation", self.client.get("/data/initial/manifest.json").json())
|
| 104 |
+
app._data_generation = old_generation + 1
|
| 105 |
+
app.folder_tree_data = {"VoiceOfML/Test": [{"name": "new"}]}
|
| 106 |
+
app.folder_browser_data = {"VoiceOfML/Test": {"": {"folders": [], "files": [{"name": "new"}]}}}
|
| 107 |
+
app.initial_payload_global = {"generation": "new"}
|
| 108 |
+
app.initial_payload_by_repo = {
|
| 109 |
+
"VoiceOfML/Test": {"generation": "new"},
|
| 110 |
+
"VoiceOfML/New": {"generation": "new"},
|
| 111 |
+
}
|
| 112 |
+
self.assertEqual(self.client.get("/api/folders/Test").json()[0]["name"], "new")
|
| 113 |
+
self.assertEqual(self.client.get("/api/folders/Test/contents").json()["files"][0]["name"], "new")
|
| 114 |
+
self.assertEqual(self.client.get("/data/initial/global.json").json()["generation"], "new")
|
| 115 |
+
self.assertEqual(self.client.get("/data/initial/repos/Test.json").json()["generation"], "new")
|
| 116 |
+
self.assertEqual(
|
| 117 |
+
self.client.get("/data/initial/manifest.json").json()["urls"],
|
| 118 |
+
["/data/initial/global.json", "/data/initial/repos/New.json", "/data/initial/repos/Test.json"],
|
| 119 |
+
)
|
| 120 |
+
finally:
|
| 121 |
+
app._data_generation = old_generation
|
| 122 |
+
|
| 123 |
+
def test_random_endpoint_is_record_shaped_without_private_index_fields(self):
|
| 124 |
+
result = self.client.get("/api/random").json()
|
| 125 |
+
self.assertEqual(result["Repo"], "VoiceOfML/Test")
|
| 126 |
+
self.assertIn("Link", result)
|
| 127 |
+
self.assertIn("Path", result)
|
| 128 |
+
self.assertFalse(any(key.startswith("_") for key in result))
|
| 129 |
+
|
| 130 |
+
def test_random_txt_endpoint_is_record_shaped_without_private_index_fields(self):
|
| 131 |
+
result = self.client.get("/api/random-txt").json()
|
| 132 |
+
self.assertTrue(result["HasTxt"])
|
| 133 |
+
self.assertFalse(any(key.startswith("_") for key in result))
|
| 134 |
+
|
| 135 |
+
def test_random_reader_hides_private_index_fields(self):
|
| 136 |
+
with mock.patch.object(app, "get_reader_assets", mock.AsyncMock(return_value={"v": 1, "f": {}})):
|
| 137 |
+
result = self.client.get("/api/random-reader").json()
|
| 138 |
+
self.assertNotIn("ReaderLink", result)
|
| 139 |
+
self.assertTrue(result["Link"].endswith("/docs/readme.txt"))
|
| 140 |
+
self.assertFalse(any(key.startswith("_") for key in result))
|
| 141 |
+
|
| 142 |
+
def test_reader_source_id_fixed_vector_and_index_rebuild(self):
|
| 143 |
+
app.records = [{"Repo": "VoiceOfML/Test", "File": "book29", "Extension": "txt", "Folder": []}]
|
| 144 |
+
app.build_indexes(build_words=False)
|
| 145 |
+
with mock.patch.object(app, "get_reader_assets", mock.AsyncMock(return_value={"v": 1, "f": {}})), mock.patch.object(app, "reader_short_id", side_effect=AssertionError("request must use index")):
|
| 146 |
+
response = self.client.get("/api/reader-resolve", params={"id": "0ym7e7wbcxau0"})
|
| 147 |
+
self.assertEqual(response.status_code, 200)
|
| 148 |
+
self.assertTrue(response.json()["url"].endswith("/book29.txt"))
|
| 149 |
+
app.records = []
|
| 150 |
+
app.build_indexes(build_words=False)
|
| 151 |
+
response = self.client.get("/api/reader-resolve", params={"id": "0ym7e7wbcxau0"})
|
| 152 |
+
self.assertEqual(response.status_code, 404)
|
| 153 |
+
|
| 154 |
+
def test_reader_source_id_collision_is_not_arbitrarily_resolved(self):
|
| 155 |
+
app.records = [
|
| 156 |
+
{"Repo": "VoiceOfML/Test", "File": name, "Extension": "txt", "Folder": []}
|
| 157 |
+
for name in ("first", "second")
|
| 158 |
+
]
|
| 159 |
+
with mock.patch.object(app, "reader_short_id", return_value="0" * 13):
|
| 160 |
+
app.build_indexes(build_words=False)
|
| 161 |
+
response = self.client.get("/api/reader-resolve", params={"id": "0" * 13})
|
| 162 |
+
self.assertEqual(response.status_code, 409)
|
| 163 |
+
|
| 164 |
+
def test_reader_resolve_uses_native_asset_file_extension(self):
|
| 165 |
+
for extension in ("epub", "mobi", "azw", "azw3", "fb2"):
|
| 166 |
+
with self.subTest(extension=extension):
|
| 167 |
+
app.records = [{"Repo": "VoiceOfML/Test", "File": "book", "Extension": "txt", "Folder": [], "Size": 10, "HasTxt": False}]
|
| 168 |
+
app.build_indexes()
|
| 169 |
+
asset = {"s": 2, "m": "e", "p": f"objects/aa/{'a' * 64}/document.{extension}"}
|
| 170 |
+
sidecar = {"v": 1, "f": {"VoiceOfML/Test\0book.txt": asset}}
|
| 171 |
+
with mock.patch.object(app, "get_reader_assets", mock.AsyncMock(return_value=sidecar)):
|
| 172 |
+
result = self.client.get("/api/reader-resolve", params={"id": app.reader_short_id(app.records[0].get("Link") or app.build_record_link(app.records[0]))})
|
| 173 |
+
self.assertEqual(result.status_code, 200)
|
| 174 |
+
self.assertEqual(result.json()["extension"], extension)
|
| 175 |
+
|
| 176 |
+
app.records = [
|
| 177 |
+
{"Repo": "VoiceOfML/Test", "File": "scan", "Extension": "pdf", "Folder": [], "Size": 10, "HasTxt": False},
|
| 178 |
+
{"Repo": "VoiceOfML/Test", "File": "archive", "Extension": "zip", "Folder": [], "Size": 10, "HasTxt": True},
|
| 179 |
+
]
|
| 180 |
+
app.build_indexes()
|
| 181 |
+
with mock.patch.object(app, "get_reader_assets", mock.AsyncMock(return_value={"v": 1, "f": {}})):
|
| 182 |
+
response = self.client.get("/api/random-reader")
|
| 183 |
+
self.assertEqual(response.status_code, 200)
|
| 184 |
+
self.assertEqual(response.json()["File"], "scan")
|
| 185 |
+
|
| 186 |
+
def test_random_reader_uses_native_media_extensions(self):
|
| 187 |
+
app.records = [
|
| 188 |
+
{"Repo": "VoiceOfML/Test", "File": "speech", "Extension": "mp3", "Folder": [], "Size": 10, "HasTxt": False},
|
| 189 |
+
]
|
| 190 |
+
app.build_indexes()
|
| 191 |
+
with mock.patch.object(app, "get_reader_assets", mock.AsyncMock(return_value={"v": 1, "f": {}})):
|
| 192 |
+
response = self.client.get("/api/random-reader")
|
| 193 |
+
self.assertEqual(response.status_code, 200)
|
| 194 |
+
self.assertEqual(response.json()["Extension"], "mp3")
|
| 195 |
+
|
| 196 |
+
def test_random_reader_uses_original_html(self):
|
| 197 |
+
app.records = [
|
| 198 |
+
{"Repo": "VoiceOfML/Test", "File": "page", "Extension": "html", "Folder": [], "Size": 10, "HasTxt": False},
|
| 199 |
+
]
|
| 200 |
+
app.build_indexes()
|
| 201 |
+
with mock.patch.object(app, "get_reader_assets", mock.AsyncMock(return_value={"v": 1, "f": {}})):
|
| 202 |
+
response = self.client.get("/api/random-reader")
|
| 203 |
+
self.assertEqual(response.status_code, 200)
|
| 204 |
+
self.assertEqual(response.json()["Extension"], "html")
|
| 205 |
+
|
| 206 |
+
def test_random_reader_includes_ready_converted_assets_and_original_download(self):
|
| 207 |
+
app.records = [
|
| 208 |
+
{"Repo": "VoiceOfML/Test", "File": "source", "Extension": "doc", "Folder": ["docs"], "Size": 10, "HasTxt": False},
|
| 209 |
+
]
|
| 210 |
+
app.build_indexes()
|
| 211 |
+
asset = {"s": 2, "m": "p", "p": "objects/aa/" + "a" * 64 + "/document.pdf"}
|
| 212 |
+
sidecar = {"v": 1, "f": {"VoiceOfML/Test\0docs/source.doc": asset}}
|
| 213 |
+
with mock.patch.object(app, "get_reader_assets", mock.AsyncMock(return_value=sidecar)):
|
| 214 |
+
response = self.client.get("/api/random-reader", params={"repo": "Test"})
|
| 215 |
+
status = self.client.get("/api/random-reader/status", params={"repo": "Test"})
|
| 216 |
+
result = response.json()
|
| 217 |
+
self.assertEqual(response.status_code, 200)
|
| 218 |
+
self.assertEqual(result["ReaderExtension"], "pdf")
|
| 219 |
+
self.assertTrue(result["ReaderLink"].endswith(asset["p"]))
|
| 220 |
+
self.assertEqual(result["DownloadLink"], result["Link"])
|
| 221 |
+
self.assertEqual(status.json(), {"available": True, "count": 1})
|
| 222 |
+
|
| 223 |
+
def test_random_reader_preserves_converted_reader_extension_semantics(self):
|
| 224 |
+
cases = [
|
| 225 |
+
("pdf-source", "bin", "p", "pdf"),
|
| 226 |
+
("epub-source", "epub", "e", "epub"),
|
| 227 |
+
("mobi-source", "mobi", "e", "mobi"),
|
| 228 |
+
("azw3-source", "azw3", "e", "azw3"),
|
| 229 |
+
("fb2-source", "fb2", "e", "fb2"),
|
| 230 |
+
("docx-source", "doc", "d", "docx"),
|
| 231 |
+
("html-source", "html", "h", "html"),
|
| 232 |
+
("audio-source", "mp3", "a", "audio"),
|
| 233 |
+
("video-source", "mp4", "v", "video"),
|
| 234 |
+
]
|
| 235 |
+
for name, original_extension, asset_mode, reader_extension in cases:
|
| 236 |
+
with self.subTest(original_extension=original_extension, asset_mode=asset_mode):
|
| 237 |
+
app.records = [
|
| 238 |
+
{"Repo": "VoiceOfML/Test", "File": name, "Extension": original_extension, "Folder": [], "Size": 10, "HasTxt": False},
|
| 239 |
+
]
|
| 240 |
+
app.build_indexes()
|
| 241 |
+
asset_names = {
|
| 242 |
+
"p": "document.pdf",
|
| 243 |
+
"e": "document.epub" if original_extension == "epub" else f"document.{original_extension}",
|
| 244 |
+
"d": "document.docx",
|
| 245 |
+
"h": "document.html",
|
| 246 |
+
"a": "audio.mp3",
|
| 247 |
+
"v": "video.mp4",
|
| 248 |
+
}
|
| 249 |
+
asset_path = "objects/aa/" + "a" * 64 + "/" + asset_names[asset_mode]
|
| 250 |
+
asset = {"s": 2, "m": asset_mode, "p": asset_path}
|
| 251 |
+
sidecar = {"v": 1, "f": {f"VoiceOfML/Test\0{name}.{original_extension}": asset}}
|
| 252 |
+
with mock.patch.object(app, "get_reader_assets", mock.AsyncMock(return_value=sidecar)):
|
| 253 |
+
response = self.client.get("/api/random-reader", params={"repo": "Test"})
|
| 254 |
+
result = response.json()
|
| 255 |
+
self.assertEqual(response.status_code, 200)
|
| 256 |
+
self.assertEqual(result["ReaderExtension"], reader_extension)
|
| 257 |
+
self.assertTrue(result["ReaderLink"].endswith(asset_path))
|
| 258 |
+
self.assertEqual(result["DownloadLink"], result["Link"])
|
| 259 |
+
|
| 260 |
+
def test_reader_resolve_keeps_original_title_and_download_for_converted_asset(self):
|
| 261 |
+
original_link = "https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/books/original.mobi"
|
| 262 |
+
app.records = [
|
| 263 |
+
{"Repo": "VoiceOfML/Test", "File": "原始书名", "Extension": "mobi", "Folder": ["books"], "Size": 10, "HasTxt": False, "Link": original_link},
|
| 264 |
+
]
|
| 265 |
+
app.build_indexes()
|
| 266 |
+
asset_path = "objects/aa/" + "a" * 64 + "/document.epub"
|
| 267 |
+
asset = {"s": 2, "m": "e", "p": asset_path}
|
| 268 |
+
sidecar = {"v": 1, "f": {"VoiceOfML/Test\0books/原始书名.mobi": asset}}
|
| 269 |
+
with mock.patch.object(app, "get_reader_assets", mock.AsyncMock(return_value=sidecar)):
|
| 270 |
+
random_result = self.client.get("/api/random-reader", params={"repo": "Test"}).json()
|
| 271 |
+
reader_url = random_result["ReaderLink"]
|
| 272 |
+
reader_id = "a" * 16
|
| 273 |
+
resolved = self.client.get("/api/reader-resolve", params={"id": reader_id})
|
| 274 |
+
self.assertEqual(resolved.status_code, 200)
|
| 275 |
+
data = resolved.json()
|
| 276 |
+
self.assertEqual(data["title"], "原始书名")
|
| 277 |
+
self.assertEqual(data["original_extension"], "mobi")
|
| 278 |
+
self.assertEqual(data["extension"], "epub")
|
| 279 |
+
self.assertEqual(data["download"], original_link)
|
| 280 |
+
|
| 281 |
+
def test_reader_resolve_upgrades_original_pdf_id_to_page_stream(self):
|
| 282 |
+
original_link = "https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/books/scan.pdf"
|
| 283 |
+
app.records = [
|
| 284 |
+
{"Repo": "VoiceOfML/Test", "File": "scan", "Extension": "pdf", "Folder": ["books"], "Size": 10, "HasTxt": False, "Link": original_link},
|
| 285 |
+
]
|
| 286 |
+
app.build_indexes()
|
| 287 |
+
asset_path = "objects/aa/" + "a" * 64 + "/page-manifest.json"
|
| 288 |
+
sidecar = {"v": 1, "f": {"VoiceOfML/Test\0books/scan.pdf": {"s": 2, "m": "p", "p": asset_path}}}
|
| 289 |
+
with mock.patch.object(app, "get_reader_assets", mock.AsyncMock(return_value=sidecar)):
|
| 290 |
+
response = self.client.get("/api/reader-resolve", params={"id": app.reader_short_id(original_link)})
|
| 291 |
+
self.assertEqual(response.status_code, 200)
|
| 292 |
+
data = response.json()
|
| 293 |
+
self.assertEqual(data["extension"], "pdf-pages")
|
| 294 |
+
self.assertTrue(data["url"].endswith(asset_path))
|
| 295 |
+
self.assertEqual(data["download"], original_link)
|
| 296 |
+
|
| 297 |
+
def test_reader_resolve_deduplicates_metadata_for_the_same_converted_file(self):
|
| 298 |
+
app.records = [
|
| 299 |
+
{"Repo": "VoiceOfML/Test", "File": "second", "Extension": "mobi", "Folder": ["z"], "Size": 10, "HasTxt": False},
|
| 300 |
+
{"Repo": "VoiceOfML/Test", "File": "first", "Extension": "mobi", "Folder": ["a"], "Size": 10, "HasTxt": False},
|
| 301 |
+
]
|
| 302 |
+
app.build_indexes()
|
| 303 |
+
asset_path = "objects/aa/" + "a" * 64 + "/document.mobi"
|
| 304 |
+
asset = {"s": 2, "m": "e", "p": asset_path}
|
| 305 |
+
sidecar = {"v": 1, "f": {
|
| 306 |
+
"VoiceOfML/Test\0z/second.mobi": asset,
|
| 307 |
+
"VoiceOfML/Test\0a/first.mobi": asset,
|
| 308 |
+
}}
|
| 309 |
+
with mock.patch.object(app, "get_reader_assets", mock.AsyncMock(return_value=sidecar)):
|
| 310 |
+
response = self.client.get("/api/reader-resolve", params={"id": "a" * 16})
|
| 311 |
+
self.assertEqual(response.status_code, 200)
|
| 312 |
+
self.assertEqual(response.json()["title"], "first")
|
| 313 |
+
self.assertTrue(response.json()["url"].endswith(asset_path))
|
| 314 |
+
|
| 315 |
+
def test_random_reader_exposes_chapter_manifest_and_fallback_for_converted_book(self):
|
| 316 |
+
original_link = "https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/books/source.epub"
|
| 317 |
+
app.records = [
|
| 318 |
+
{"Repo": "VoiceOfML/Test", "File": "source", "Extension": "epub", "Folder": [], "Size": 10, "HasTxt": False, "Link": original_link},
|
| 319 |
+
]
|
| 320 |
+
app.build_indexes()
|
| 321 |
+
chapter_manifest = "objects/aa/" + "a" * 64 + "/epub-chapters-v1/chapter-manifest.json"
|
| 322 |
+
fallback = "objects/bb/" + "b" * 64 + "/epub-pdf-v1/document.pdf"
|
| 323 |
+
asset = {"s": 2, "m": "e", "p": "objects/aa/" + "a" * 64 + "/book.epub", "c": chapter_manifest, "f": fallback}
|
| 324 |
+
sidecar = {"v": 1, "f": {"VoiceOfML/Test\0source.epub": asset}}
|
| 325 |
+
with mock.patch.object(app, "get_reader_assets", mock.AsyncMock(return_value=sidecar)):
|
| 326 |
+
response = self.client.get("/api/random-reader", params={"repo": "Test"})
|
| 327 |
+
result = response.json()
|
| 328 |
+
self.assertEqual(response.status_code, 200)
|
| 329 |
+
self.assertEqual(result["ReaderExtension"], "epub-chapters")
|
| 330 |
+
self.assertTrue(result["ReaderChapterManifest"].endswith(chapter_manifest))
|
| 331 |
+
self.assertTrue(result["ReaderFallback"].endswith(fallback))
|
| 332 |
+
self.assertEqual(result["DownloadLink"], original_link)
|
| 333 |
+
|
| 334 |
+
def test_reader_resolve_exposes_chapter_metadata_for_id_reader(self):
|
| 335 |
+
original_link = "https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/books/source.epub"
|
| 336 |
+
app.records = [
|
| 337 |
+
{"Repo": "VoiceOfML/Test", "File": "source", "Extension": "epub", "Folder": [], "Size": 10, "HasTxt": False, "Link": original_link},
|
| 338 |
+
]
|
| 339 |
+
app.build_indexes()
|
| 340 |
+
chapter_manifest = "objects/aa/" + "a" * 64 + "/epub-chapters-v1/chapter-manifest.json"
|
| 341 |
+
fallback = "objects/bb/" + "b" * 64 + "/epub-pdf-v1/document.pdf"
|
| 342 |
+
asset = {"s": 2, "m": "e", "p": "objects/aa/" + "a" * 64 + "/book.epub", "c": chapter_manifest, "f": fallback}
|
| 343 |
+
sidecar = {"v": 1, "f": {"VoiceOfML/Test\0source.epub": asset}}
|
| 344 |
+
with mock.patch.object(app, "get_reader_assets", mock.AsyncMock(return_value=sidecar)):
|
| 345 |
+
response = self.client.get("/api/reader-resolve", params={"id": app.reader_short_id(original_link)})
|
| 346 |
+
self.assertEqual(response.status_code, 200)
|
| 347 |
+
result = response.json()
|
| 348 |
+
self.assertEqual(result["extension"], "epub-chapters")
|
| 349 |
+
self.assertTrue(result["chapter_manifest"].endswith(chapter_manifest))
|
| 350 |
+
self.assertTrue(result["fallback"].endswith(fallback))
|
| 351 |
+
|
| 352 |
+
def test_reader_static_assets_are_served(self):
|
| 353 |
+
for path in ("/static/reader.html", "/static/reader.js", "/static/reader.css", "/static/reader-contract.js"):
|
| 354 |
+
self.assertEqual(self.client.get(path).status_code, 200)
|
| 355 |
+
|
| 356 |
+
def test_random_status_empty_repo_is_404(self):
|
| 357 |
+
self.assertEqual(self.client.get("/api/random-txt", params={"repo": "Missing"}).status_code, 404)
|
| 358 |
+
|
| 359 |
+
def test_ping_is_empty_and_not_cached(self):
|
| 360 |
+
response = self.client.get("/api/ping")
|
| 361 |
+
self.assertEqual(response.status_code, 204)
|
| 362 |
+
self.assertEqual(response.headers.get("cache-control"), "no-store")
|
| 363 |
+
|
| 364 |
+
def test_cors_header_is_present(self):
|
| 365 |
+
response = self.client.get("/api/repos", headers={"Origin": "https://example.test"})
|
| 366 |
+
self.assertEqual(response.headers.get("access-control-allow-origin"), "*")
|
| 367 |
+
|
| 368 |
+
def test_gzip_compresses_large_response_when_requested(self):
|
| 369 |
+
response = self.client.get("/static/app.js", headers={"Accept-Encoding": "gzip"})
|
| 370 |
+
self.assertEqual(response.status_code, 200)
|
| 371 |
+
self.assertEqual(response.headers.get("content-encoding"), "gzip")
|
| 372 |
+
|
| 373 |
+
def test_only_content_hashed_static_assets_are_immutable(self):
|
| 374 |
+
from fastapi import FastAPI
|
| 375 |
+
with tempfile.TemporaryDirectory() as directory:
|
| 376 |
+
static_dir = Path(directory)
|
| 377 |
+
(static_dir / "app.js").write_text("plain", encoding="utf-8")
|
| 378 |
+
(static_dir / "app.0123456789ab.js").write_text("hashed", encoding="utf-8")
|
| 379 |
+
static_app = FastAPI()
|
| 380 |
+
static_app.mount("/static", app.HashedStaticFiles(directory=directory), name="static-test")
|
| 381 |
+
with TestClient(static_app) as client:
|
| 382 |
+
plain = client.get("/static/app.js")
|
| 383 |
+
hashed = client.get("/static/app.0123456789ab.js")
|
| 384 |
+
self.assertNotIn("immutable", plain.headers.get("cache-control", ""))
|
| 385 |
+
self.assertEqual(hashed.headers.get("cache-control"), "public, max-age=31536000, immutable")
|
| 386 |
+
|
| 387 |
+
def test_root_serves_html_and_injects_initial_payload(self):
|
| 388 |
+
response = self.client.get("/")
|
| 389 |
+
self.assertEqual(response.status_code, 200)
|
| 390 |
+
self.assertIn("initial-search-data", response.text)
|
| 391 |
+
self.assertIn("/static/app.js", response.text)
|
| 392 |
+
|
| 393 |
+
def test_spa_route_serves_html(self):
|
| 394 |
+
response = self.client.get("/Test/some/client/route")
|
| 395 |
+
self.assertEqual(response.status_code, 200)
|
| 396 |
+
self.assertIn("VoiceOfML Search", response.text)
|
| 397 |
+
|
| 398 |
+
def test_unknown_repository_spa_route_is_404(self):
|
| 399 |
+
response = self.client.get("/Missing/some/client/route")
|
| 400 |
+
self.assertEqual(response.status_code, 404)
|
| 401 |
+
self.assertEqual(response.text, "Repository not found")
|
| 402 |
+
|
| 403 |
+
def test_missing_frontend_shell_is_service_unavailable(self):
|
| 404 |
+
with mock.patch.object(app, "injected_html_cache", {}), mock.patch.object(app, "Path") as path_class:
|
| 405 |
+
path_class.return_value.exists.return_value = False
|
| 406 |
+
root = self.client.get("/")
|
| 407 |
+
spa = self.client.get("/Test/some/client/route")
|
| 408 |
+
self.assertEqual(root.status_code, 503)
|
| 409 |
+
self.assertEqual(spa.status_code, 503)
|
| 410 |
+
self.assertEqual(root.text, "Frontend shell unavailable")
|
| 411 |
+
|
| 412 |
+
def test_static_manifest_and_service_worker_routes(self):
|
| 413 |
+
self.assertEqual(self.client.get("/manifest.json").status_code, 200)
|
| 414 |
+
self.assertEqual(self.client.get("/sw.js").status_code, 200)
|
| 415 |
+
|
| 416 |
+
def test_initial_manifest_contains_global_and_repo_urls(self):
|
| 417 |
+
payload = self.client.get("/data/initial/manifest.json").json()
|
| 418 |
+
self.assertEqual(payload["urls"], ["/data/initial/global.json", "/data/initial/repos/Test.json"])
|
| 419 |
+
|
| 420 |
+
def test_sidebar_missing_repo_is_404(self):
|
| 421 |
+
self.assertEqual(self.client.get("/data/sidebar/repos/Missing.json").status_code, 404)
|
| 422 |
+
|
| 423 |
+
|
| 424 |
+
if __name__ == "__main__":
|
| 425 |
+
unittest.main()
|
tests/test_generated_data_oracle.py
ADDED
|
@@ -0,0 +1,152 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import gzip
|
| 4 |
+
import hashlib
|
| 5 |
+
import json
|
| 6 |
+
import unittest
|
| 7 |
+
from collections import Counter, defaultdict
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
ROOT = Path(__file__).resolve().parents[1]
|
| 12 |
+
DATA = ROOT / "data"
|
| 13 |
+
FIELDS = ("Repo", "File", "Extension", "Folder", "Size", "HasTxt")
|
| 14 |
+
WORD_INDEX_TOKENIZER = "jieba-0.42.1-cjk-char-v1"
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def decode_varint(data, offset):
|
| 18 |
+
value = 0
|
| 19 |
+
shift = 0
|
| 20 |
+
while offset < len(data):
|
| 21 |
+
byte = data[offset]
|
| 22 |
+
offset += 1
|
| 23 |
+
value |= (byte & 0x7F) << shift
|
| 24 |
+
if not byte & 0x80:
|
| 25 |
+
return value, offset
|
| 26 |
+
shift += 7
|
| 27 |
+
raise ValueError("truncated varint")
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def corpus_digest(records):
|
| 31 |
+
digest = hashlib.sha256()
|
| 32 |
+
for record in records:
|
| 33 |
+
values = (
|
| 34 |
+
str(record.get("File") or "").lower(),
|
| 35 |
+
str(record.get("Repo") or "").lower(),
|
| 36 |
+
"/".join(str(item).lower() for item in (record.get("Folder") or [])),
|
| 37 |
+
)
|
| 38 |
+
for value in values:
|
| 39 |
+
digest.update(value.encode("utf-8"))
|
| 40 |
+
digest.update(b"\0")
|
| 41 |
+
return digest.digest()
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def validate_posting_entries(data, offset, expected_count=None):
|
| 45 |
+
count, offset = decode_varint(data, offset)
|
| 46 |
+
if expected_count is not None:
|
| 47 |
+
assert count == expected_count
|
| 48 |
+
for _ in range(count):
|
| 49 |
+
key_length, offset = decode_varint(data, offset)
|
| 50 |
+
data[offset:offset + key_length].decode("utf-8")
|
| 51 |
+
offset += key_length
|
| 52 |
+
_, offset = decode_varint(data, offset)
|
| 53 |
+
posting_length, offset = decode_varint(data, offset)
|
| 54 |
+
offset += posting_length
|
| 55 |
+
if offset > len(data):
|
| 56 |
+
raise ValueError("truncated posting data")
|
| 57 |
+
if offset != len(data):
|
| 58 |
+
raise ValueError("trailing posting data")
|
| 59 |
+
return count
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def decode_corpus_independently():
|
| 63 |
+
with gzip.open(DATA / "search_data.json.gz", "rt", encoding="utf-8") as handle:
|
| 64 |
+
compact = json.load(handle)
|
| 65 |
+
repos = compact.get("rp", [])
|
| 66 |
+
folders = compact.get("fd", [])
|
| 67 |
+
decoded = []
|
| 68 |
+
for row in compact.get("rc", []):
|
| 69 |
+
if not isinstance(row, list) or len(row) < 6:
|
| 70 |
+
continue
|
| 71 |
+
repo = repos[row[0]] if isinstance(row[0], int) and 0 <= row[0] < len(repos) else ""
|
| 72 |
+
folder = folders[row[3]] if isinstance(row[3], int) and 0 <= row[3] < len(folders) else []
|
| 73 |
+
decoded.append({"Repo": repo, "File": row[1], "Extension": row[2], "Folder": folder, "Size": row[4], "HasTxt": bool(row[5])})
|
| 74 |
+
return decoded
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
class GeneratedDataOracleTests(unittest.TestCase):
|
| 78 |
+
@classmethod
|
| 79 |
+
def setUpClass(cls):
|
| 80 |
+
cls.records = decode_corpus_independently()
|
| 81 |
+
cls.by_repo = defaultdict(list)
|
| 82 |
+
for record in cls.records:
|
| 83 |
+
cls.by_repo[record["Repo"]].append(record)
|
| 84 |
+
|
| 85 |
+
def test_compact_corpus_has_expected_record_count(self):
|
| 86 |
+
self.assertEqual(len(self.records), 100203)
|
| 87 |
+
|
| 88 |
+
def test_sidebar_global_counts_equal_independent_corpus_counts(self):
|
| 89 |
+
sidebar = json.loads((DATA / "sidebar/global.json").read_text(encoding="utf-8"))
|
| 90 |
+
expected = Counter(record["Repo"] for record in self.records)
|
| 91 |
+
self.assertEqual({item["name"]: item["count"] for item in sidebar["repos"]}, dict(expected))
|
| 92 |
+
|
| 93 |
+
def test_global_initial_total_and_ordered_first_page_equal_corpus(self):
|
| 94 |
+
payload = json.loads((DATA / "initial/global.json").read_text(encoding="utf-8"))
|
| 95 |
+
self.assertEqual(payload["total"], len(self.records))
|
| 96 |
+
self.assertEqual(payload["results"], self.records[:payload["page_size"]])
|
| 97 |
+
|
| 98 |
+
def test_each_repo_initial_total_and_ordered_page_equal_corpus(self):
|
| 99 |
+
for path in sorted((DATA / "initial/repos").glob("*.json")):
|
| 100 |
+
with self.subTest(repo_file=path.name):
|
| 101 |
+
payload = json.loads(path.read_text(encoding="utf-8"))
|
| 102 |
+
records = self.by_repo[payload["repo"]]
|
| 103 |
+
self.assertEqual(payload["total"], len(records))
|
| 104 |
+
self.assertEqual(payload["results"], records[:payload["page_size"]])
|
| 105 |
+
|
| 106 |
+
def test_initial_manifest_exactly_lists_generated_payload_files(self):
|
| 107 |
+
manifest = json.loads((DATA / "initial/manifest.json").read_text(encoding="utf-8"))
|
| 108 |
+
actual = {"/data/initial/global.json"} | {f"/data/initial/repos/{path.name}" for path in (DATA / "initial/repos").glob("*.json")}
|
| 109 |
+
self.assertEqual(set(manifest["urls"]), actual)
|
| 110 |
+
|
| 111 |
+
def test_sidebar_manifest_exactly_lists_generated_payload_files(self):
|
| 112 |
+
manifest = json.loads((DATA / "sidebar/manifest.json").read_text(encoding="utf-8"))
|
| 113 |
+
actual = {"/data/sidebar/global.json"} | {f"/data/sidebar/repos/{path.name}" for path in (DATA / "sidebar/repos").glob("*.json")}
|
| 114 |
+
self.assertEqual(set(manifest["urls"]), actual)
|
| 115 |
+
|
| 116 |
+
def test_each_repo_sidebar_identity_matches_file_and_corpus_total(self):
|
| 117 |
+
for path in sorted((DATA / "sidebar/repos").glob("*.json")):
|
| 118 |
+
with self.subTest(repo_file=path.name):
|
| 119 |
+
payload = json.loads(path.read_text(encoding="utf-8"))
|
| 120 |
+
expected_repo = f"VoiceOfML/{path.stem}"
|
| 121 |
+
self.assertEqual(payload.get("repo"), expected_repo)
|
| 122 |
+
direct_and_nested = sum(item.get("count", 0) for item in payload.get("folders", payload.get("d", [])))
|
| 123 |
+
files = payload.get("files", payload.get("f", []))
|
| 124 |
+
self.assertLessEqual(len(files), len(self.by_repo[expected_repo]))
|
| 125 |
+
self.assertGreaterEqual(direct_and_nested + len(files), 0)
|
| 126 |
+
|
| 127 |
+
def test_binary_search_indexes_match_corpus_generation(self):
|
| 128 |
+
expected_digest = corpus_digest(self.records)
|
| 129 |
+
words = gzip.decompress((DATA / "search_words.bin.gz").read_bytes())
|
| 130 |
+
self.assertTrue(words.startswith(b"VWI2"))
|
| 131 |
+
offset = 4
|
| 132 |
+
tokenizer_length, offset = decode_varint(words, offset)
|
| 133 |
+
self.assertEqual(words[offset:offset + tokenizer_length].decode("utf-8"), WORD_INDEX_TOKENIZER)
|
| 134 |
+
offset += tokenizer_length
|
| 135 |
+
self.assertEqual(words[offset:offset + 32], expected_digest)
|
| 136 |
+
offset += 32
|
| 137 |
+
record_count, offset = decode_varint(words, offset)
|
| 138 |
+
self.assertEqual(record_count, len(self.records))
|
| 139 |
+
self.assertGreater(validate_posting_entries(words, offset), 0)
|
| 140 |
+
|
| 141 |
+
for width in (2, 3):
|
| 142 |
+
data = gzip.decompress((DATA / f"search_ngrams_{width}.bin.gz").read_bytes())
|
| 143 |
+
self.assertEqual(data[:4], b"VNG3")
|
| 144 |
+
self.assertEqual(data[4], width)
|
| 145 |
+
self.assertEqual(data[5:37], expected_digest)
|
| 146 |
+
record_count, offset = decode_varint(data, 37)
|
| 147 |
+
self.assertEqual(record_count, len(self.records))
|
| 148 |
+
self.assertGreater(validate_posting_entries(data, offset), 0)
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
if __name__ == "__main__":
|
| 152 |
+
unittest.main()
|
tests/test_live_smoke.py
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
import os
|
| 5 |
+
import time
|
| 6 |
+
import unittest
|
| 7 |
+
from http.client import RemoteDisconnected
|
| 8 |
+
from urllib.error import HTTPError, URLError
|
| 9 |
+
from urllib.request import Request, urlopen
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
BASE_URL = os.environ.get("HF_SEARCH_LIVE_BASE_URL", "").rstrip("/")
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
@unittest.skipUnless(BASE_URL, "set HF_SEARCH_LIVE_BASE_URL to run deployment smoke tests")
|
| 16 |
+
class LiveSmokeTests(unittest.TestCase):
|
| 17 |
+
def request_json(self, path, payload=None):
|
| 18 |
+
data = json.dumps(payload).encode() if payload is not None else None
|
| 19 |
+
for attempt in range(3):
|
| 20 |
+
request = Request(BASE_URL + path, data=data, headers={"Content-Type": "application/json"} if data else {})
|
| 21 |
+
try:
|
| 22 |
+
with urlopen(request, timeout=45) as response:
|
| 23 |
+
self.assertEqual(response.status, 200)
|
| 24 |
+
return json.load(response)
|
| 25 |
+
except HTTPError as exc:
|
| 26 |
+
if exc.code < 500 or attempt == 2:
|
| 27 |
+
raise
|
| 28 |
+
except (RemoteDisconnected, TimeoutError, URLError):
|
| 29 |
+
if attempt == 2:
|
| 30 |
+
raise
|
| 31 |
+
time.sleep(attempt + 1)
|
| 32 |
+
self.fail("request retries exhausted")
|
| 33 |
+
|
| 34 |
+
def test_sources_and_search_shape(self):
|
| 35 |
+
repos = self.request_json("/api/repos")
|
| 36 |
+
self.assertIsInstance(repos, list)
|
| 37 |
+
result = self.request_json("/api/search", {"q": "model", "page": 1, "page_size": 5})
|
| 38 |
+
self.assertEqual(result["page"], 1)
|
| 39 |
+
self.assertEqual(result["page_size"], 5)
|
| 40 |
+
self.assertIsInstance(result["total"], int)
|
| 41 |
+
self.assertLessEqual(len(result["results"]), 5)
|
| 42 |
+
|
| 43 |
+
def test_exact_and_filtered_queries_have_stable_results(self):
|
| 44 |
+
exact = self.request_json("/api/search", {"q": "README", "exact": True, "page": 1, "page_size": 5})
|
| 45 |
+
self.assertIsInstance(exact["results"], list)
|
| 46 |
+
if exact["results"]:
|
| 47 |
+
self.assertTrue(all("File" in item and "Repo" in item for item in exact["results"]))
|
| 48 |
+
filtered = self.request_json("/api/search", {"q": "txt", "extensions": ["txt"], "page": 1, "page_size": 5})
|
| 49 |
+
self.assertTrue(all(str(item.get("Extension", "")).lower() == "txt" for item in filtered["results"]))
|
| 50 |
+
|
| 51 |
+
def test_folder_and_sidebar_endpoints_are_available(self):
|
| 52 |
+
self.assertIsInstance(self.request_json("/api/extensions"), list)
|
| 53 |
+
self.assertIsInstance(self.request_json("/api/folders/VOMEBOOK"), list)
|
| 54 |
+
self.assertIsInstance(self.request_json("/data/initial/manifest.json")["urls"], list)
|
| 55 |
+
self.assertIsInstance(self.request_json("/data/sidebar/manifest.json")["urls"], list)
|
| 56 |
+
|
| 57 |
+
def test_static_shell_and_read_only_routes_are_available(self):
|
| 58 |
+
for path in ("/", "/manifest.json", "/sw.js", "/static/style.css", "/static/app.js"):
|
| 59 |
+
request = Request(BASE_URL + path)
|
| 60 |
+
with urlopen(request, timeout=45) as response:
|
| 61 |
+
self.assertEqual(response.status, 200)
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
if __name__ == "__main__":
|
| 65 |
+
unittest.main()
|
tests/test_paging_recovery.py
ADDED
|
@@ -0,0 +1,143 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Focused browser regressions for resumed and stalled result pagination."""
|
| 2 |
+
import unittest
|
| 3 |
+
|
| 4 |
+
from tests.real_server import get_shared_server
|
| 5 |
+
from playwright.sync_api import sync_playwright
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
FETCH_SCRIPT = r"""(() => {
|
| 9 |
+
const nativeFetch = window.fetch.bind(window);
|
| 10 |
+
window.pagingMode = 'stall';
|
| 11 |
+
window.pagingTotal = 301;
|
| 12 |
+
window.pagingRequests = [];
|
| 13 |
+
window.fetch = function(input, options) {
|
| 14 |
+
let body = {};
|
| 15 |
+
try { body = JSON.parse(options && options.body || '{}'); } catch (_) {}
|
| 16 |
+
if (!String(input).includes('/api/search') || !String(body.q || '').startsWith('paging')) return nativeFetch(input, options);
|
| 17 |
+
window.pagingRequests.push(body.page);
|
| 18 |
+
const response = (stale = false) => new Response(JSON.stringify({
|
| 19 |
+
page: body.page, page_size: body.page_size, total: window.pagingTotal,
|
| 20 |
+
results: Array.from({length: Math.min(body.page_size, Math.max(0, window.pagingTotal - (body.page - 1) * body.page_size))}, (_, offset) => {
|
| 21 |
+
const id = (body.page - 1) * body.page_size + offset;
|
| 22 |
+
return {ID: String(id), Repo: 'VoiceOfML/Test', File: (stale ? 'stale-' : 'paging-') + id,
|
| 23 |
+
Extension: 'txt', Folder: [], Size: id + 1, HasTxt: false};
|
| 24 |
+
})
|
| 25 |
+
}), {headers: {'Content-Type': 'application/json'}});
|
| 26 |
+
if (body.page === 2 && window.pagingMode === 'stall') {
|
| 27 |
+
// Deliberately ignore AbortSignal to verify late results cannot win.
|
| 28 |
+
return new Promise(resolve => { window.releaseStalePage = () => resolve(response(true)); });
|
| 29 |
+
}
|
| 30 |
+
if (body.page === 2 && window.pagingMode === 'fail') return Promise.resolve(new Response('{}', {status: 503}));
|
| 31 |
+
return Promise.resolve(response());
|
| 32 |
+
};
|
| 33 |
+
})();"""
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class PagingRecoveryTests(unittest.TestCase):
|
| 37 |
+
@classmethod
|
| 38 |
+
def setUpClass(cls):
|
| 39 |
+
cls.origin = get_shared_server().base_url
|
| 40 |
+
cls.playwright = sync_playwright().start()
|
| 41 |
+
cls.browser = cls.playwright.chromium.launch(headless=True, args=['--no-sandbox'])
|
| 42 |
+
|
| 43 |
+
@classmethod
|
| 44 |
+
def tearDownClass(cls):
|
| 45 |
+
cls.browser.close()
|
| 46 |
+
cls.playwright.stop()
|
| 47 |
+
|
| 48 |
+
def setUp(self):
|
| 49 |
+
self.context = self.browser.new_context(viewport={'width': 1280, 'height': 800})
|
| 50 |
+
self.page = self.context.new_page()
|
| 51 |
+
self.errors = []
|
| 52 |
+
self.page.on('pageerror', lambda error: self.errors.append(str(error)))
|
| 53 |
+
self.page.add_init_script(FETCH_SCRIPT)
|
| 54 |
+
self.page.route('**/api/**', lambda route: route.fulfill(
|
| 55 |
+
content_type='application/json', body='[]' if route.request.url.endswith(('/repos', '/extensions')) else '{}'))
|
| 56 |
+
self.page.route('https://vomebook-hitokoto.hf.space/**', lambda route: route.fulfill(body='{}'))
|
| 57 |
+
self.page.goto(self.origin + '/?q=paging', wait_until='domcontentloaded')
|
| 58 |
+
self.page.wait_for_function('STATE._loadedPage === 1 && !STATE.isLoading && window.pagingRequests.includes(2)')
|
| 59 |
+
|
| 60 |
+
def tearDown(self):
|
| 61 |
+
self.context.close()
|
| 62 |
+
|
| 63 |
+
def reach_bottom(self):
|
| 64 |
+
self.page.evaluate('DOM.resultsContainer.scrollTop = DOM.resultsContainer.scrollHeight')
|
| 65 |
+
self.page.wait_for_function('STATE.isLoading && STATE._pendingPage === 2')
|
| 66 |
+
|
| 67 |
+
def expire_pending(self, mode):
|
| 68 |
+
self.page.evaluate('''mode => {
|
| 69 |
+
window.pagingMode = mode;
|
| 70 |
+
pendingSearchPages.forEach(entry => { entry.deadline = Date.now() - 1; });
|
| 71 |
+
document.dispatchEvent(new Event('visibilitychange'));
|
| 72 |
+
}''', mode)
|
| 73 |
+
|
| 74 |
+
def test_resume_retries_missing_page_and_discards_late_response(self):
|
| 75 |
+
self.reach_bottom()
|
| 76 |
+
self.page.evaluate('for (let i = 0; i < 30; i++) maybeLoadNextPage()')
|
| 77 |
+
self.assertEqual(self.page.evaluate('pagingRequests.filter(page => page === 2).length'), 1)
|
| 78 |
+
self.expire_pending('normal')
|
| 79 |
+
self.page.wait_for_function('STATE._loadedPage === 2 && !STATE.isLoading')
|
| 80 |
+
self.page.evaluate('releaseStalePage()')
|
| 81 |
+
self.page.wait_for_timeout(100)
|
| 82 |
+
self.assertEqual(self.page.evaluate('STATE.results.map(record => record.ID)'), [str(i) for i in range(200)])
|
| 83 |
+
self.assertEqual(self.page.evaluate('STATE.page'), 2)
|
| 84 |
+
self.assertFalse(self.page.evaluate('STATE.results.some(record => record.File.startsWith("stale-"))'))
|
| 85 |
+
self.assertEqual(self.page.evaluate('pagingRequests.filter(page => page === 2).length'), 2)
|
| 86 |
+
self.assertEqual(self.errors, [])
|
| 87 |
+
|
| 88 |
+
def test_failure_retries_once_then_button_recovers_same_page(self):
|
| 89 |
+
self.reach_bottom()
|
| 90 |
+
self.expire_pending('fail')
|
| 91 |
+
self.page.wait_for_function('pagingFailures === 2 && !STATE.isLoading')
|
| 92 |
+
count = self.page.evaluate('pagingRequests.length')
|
| 93 |
+
self.page.wait_for_timeout(1000)
|
| 94 |
+
self.assertEqual(self.page.evaluate('pagingRequests.length'), count)
|
| 95 |
+
self.assertEqual(self.page.evaluate('[STATE.page, STATE._loadedPage, STATE.results.length]'), [1, 1, 100])
|
| 96 |
+
self.page.evaluate("window.pagingMode = 'normal'")
|
| 97 |
+
self.page.locator('#paging-status').click()
|
| 98 |
+
self.page.wait_for_function('STATE._loadedPage === 2 && !STATE.isLoading')
|
| 99 |
+
self.assertEqual(self.page.evaluate('STATE.results.map(record => record.ID)'), [str(i) for i in range(200)])
|
| 100 |
+
self.assertEqual(self.errors, [])
|
| 101 |
+
|
| 102 |
+
def test_touch_at_bottom_retries_without_scroll_position_change(self):
|
| 103 |
+
self.reach_bottom()
|
| 104 |
+
self.expire_pending('fail')
|
| 105 |
+
self.page.wait_for_function('pagingFailures === 2 && !STATE.isLoading')
|
| 106 |
+
self.page.wait_for_timeout(800)
|
| 107 |
+
self.page.evaluate("window.pagingMode = 'normal'; DOM.resultsContainer.dispatchEvent(new Event('touchend'))")
|
| 108 |
+
self.page.wait_for_function('STATE._loadedPage === 2 && !STATE.isLoading')
|
| 109 |
+
self.assertEqual(self.errors, [])
|
| 110 |
+
|
| 111 |
+
def test_short_pages_fill_viewport_and_stop_at_total(self):
|
| 112 |
+
self.page.evaluate('''() => {
|
| 113 |
+
window.pagingMode = 'normal'; window.pagingTotal = 3;
|
| 114 |
+
STATE.query = 'paging-small'; STATE.pageSize = 1; STATE.page = 1;
|
| 115 |
+
doSearch();
|
| 116 |
+
}''')
|
| 117 |
+
self.page.wait_for_function('STATE.results.length === 3 && !STATE.isLoading && !STATE.hasMore')
|
| 118 |
+
self.assertEqual(self.page.evaluate('STATE.results.map(record => record.ID)'), ['0', '1', '2'])
|
| 119 |
+
self.assertEqual(self.page.evaluate('[STATE.page, STATE._loadedPage]'), [3, 3])
|
| 120 |
+
self.assertEqual(self.errors, [])
|
| 121 |
+
|
| 122 |
+
def test_new_query_invalidates_pending_append_and_retry(self):
|
| 123 |
+
self.reach_bottom()
|
| 124 |
+
self.page.evaluate('''() => {
|
| 125 |
+
window.pagingMode = 'normal'; window.pagingTotal = 1;
|
| 126 |
+
STATE.query = 'paging-new'; STATE.page = 1; doSearch();
|
| 127 |
+
}''')
|
| 128 |
+
self.page.wait_for_function('!STATE.isLoading && STATE.results.length === 1')
|
| 129 |
+
self.page.evaluate('releaseStalePage()')
|
| 130 |
+
self.page.wait_for_timeout(850)
|
| 131 |
+
self.assertEqual(self.page.evaluate('[STATE.query, STATE.page, STATE._loadedPage, STATE.results.length]'), ['paging-new', 1, 1, 1])
|
| 132 |
+
self.assertEqual(self.errors, [])
|
| 133 |
+
|
| 134 |
+
def test_page_finishing_during_thumb_drag_is_consumed_once_on_resume(self):
|
| 135 |
+
self.reach_bottom()
|
| 136 |
+
self.page.evaluate("VSCROLL.isDraggingThumb = true; window.pagingMode = 'normal'; releaseStalePage()")
|
| 137 |
+
self.page.wait_for_function('STATE._deferredAppendWhileDragging && !STATE.isLoading')
|
| 138 |
+
self.assertEqual(self.page.evaluate('[STATE.page, STATE._loadedPage]'), [2, 1])
|
| 139 |
+
self.page.evaluate('recoverScrollState()')
|
| 140 |
+
self.page.wait_for_function('STATE._loadedPage === 2')
|
| 141 |
+
self.assertEqual(self.page.evaluate('STATE.results.map(record => record.ID)'), [str(i) for i in range(200)])
|
| 142 |
+
self.assertEqual(self.page.evaluate('STATE.page'), 2)
|
| 143 |
+
self.assertEqual(self.errors, [])
|
tests/test_reader_accessibility.py
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import unittest
|
| 2 |
+
from tests.test_static_contract import assert_source_contains
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
|
| 5 |
+
ROOT = Path(__file__).parents[1]
|
| 6 |
+
|
| 7 |
+
class ReaderAccessibilityTests(unittest.TestCase):
|
| 8 |
+
@classmethod
|
| 9 |
+
def setUpClass(cls):
|
| 10 |
+
cls.reader = (ROOT / "static/reader.js").read_text(encoding="utf-8")
|
| 11 |
+
cls.html = (ROOT / "static/reader.html").read_text(encoding="utf-8")
|
| 12 |
+
cls.css = (ROOT / "static/reader.css").read_text(encoding="utf-8")
|
| 13 |
+
|
| 14 |
+
def test_reader_controls_and_regions_have_accessible_contracts(self):
|
| 15 |
+
for value in ('role="status"', 'id="page-number"', 'id="page-total"'):
|
| 16 |
+
self.assertIn(value, self.html)
|
| 17 |
+
for value in ('["#back", "返回"]', '["#page-number", "页码"]', '["#zoom", "缩放百分比"]'):
|
| 18 |
+
assert_source_contains(self, value, self.reader)
|
| 19 |
+
for value in ('setAttribute("role", "region")', 'setAttribute("aria-label", `第 ${page} 页`)', 'setAttribute("aria-modal", "true")', 'focus({ preventScroll: true })', 'composedPath()'):
|
| 20 |
+
assert_source_contains(self, value, self.reader)
|
| 21 |
+
self.assertRegex(self.css, r'prefers-contrast\s*:\s*more')
|
| 22 |
+
for value in ('aria-label="下载原文件"', 'role="tablist"', 'role="tab"', 'aria-controls="toc-panel"', 'role="tabpanel"'):
|
| 23 |
+
self.assertIn(value, self.html)
|
tests/test_reader_architecture.js
ADDED
|
@@ -0,0 +1,173 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
const fs = require('fs')
|
| 2 |
+
const path = require('path')
|
| 3 |
+
const assert = require('assert')
|
| 4 |
+
const { assertCode, codePattern } = require('./reader_source_contract')
|
| 5 |
+
|
| 6 |
+
const root = path.resolve(__dirname, '..')
|
| 7 |
+
const reader = fs.readFileSync(path.join(root, 'static/reader.js'), 'utf8')
|
| 8 |
+
const css = fs.readFileSync(path.join(root, 'static/reader.css'), 'utf8')
|
| 9 |
+
const view = fs.readFileSync(path.join(root, 'static/foliate-reader/view.js'), 'utf8')
|
| 10 |
+
for (const marker of ["import('./epub.js')", "import('./mobi.js')", "import('./fb2.js')", "import('./pdf.js')", "isFBZ(file)", "isFB2(file)"]) assert.ok(view.includes(marker), marker)
|
| 11 |
+
for (const file of ['epub.js', 'mobi.js', 'fb2.js', 'pdf.js', 'view.js', 'progress.js', 'ui/tree.js']) assert.ok(fs.existsSync(path.join(root, 'static/foliate-reader', file)), file)
|
| 12 |
+
assert.match(fs.readFileSync(path.join(root, 'static/foliate-reader/mobi.js'), 'utf8'), /createDocument/)
|
| 13 |
+
assert.match(fs.readFileSync(path.join(root, 'static/foliate-reader/fb2.js'), 'utf8'), /resolveHref/)
|
| 14 |
+
assert.match(fs.readFileSync(path.join(root, 'static/foliate-reader/epub.js'), 'utf8'), /String\(href \?\? ''\)/)
|
| 15 |
+
const foliateReader = fs.readFileSync(path.join(root, 'static/foliate-reader/reader.js'), 'utf8')
|
| 16 |
+
for (const message of ['voice-foliate-goto-cfi', 'voice-foliate-search', 'voice-foliate-seek', 'voice-foliate-prev', 'voice-foliate-next']) assert.ok(foliateReader.includes(message), message)
|
| 17 |
+
|
| 18 |
+
assert.strictEqual((reader.match(/async function renderFoliate\(/g) || []).length, 1)
|
| 19 |
+
assert.strictEqual(reader.includes('renderFoliateClean'), false)
|
| 20 |
+
assert.strictEqual(reader.includes('renderFoliateLegacy'), false)
|
| 21 |
+
assert.strictEqual(reader.includes('foliate-continuous'), true)
|
| 22 |
+
assert.strictEqual(reader.includes('document.querySelector("#toc-list").addEventListener'), false)
|
| 23 |
+
assert.strictEqual(reader.includes('activateFoliateTocEntryLatest'), false)
|
| 24 |
+
assert.strictEqual(reader.includes('setupFoliateToc'), false)
|
| 25 |
+
assert.strictEqual(reader.includes('foliateVisibleSections'), false)
|
| 26 |
+
assert.strictEqual(reader.includes('foliateVisibleNodes'), false)
|
| 27 |
+
assert.strictEqual(reader.includes('directFoliateMoving'), false)
|
| 28 |
+
assert.strictEqual(reader.includes('directFoliateContainer'), false)
|
| 29 |
+
assert.strictEqual(reader.includes('setInterval(() => { loadNextFoliateSection(); }, 100)'), false)
|
| 30 |
+
assert.strictEqual(reader.includes('setInterval(() => { const tab = document.querySelector("#toc-tab")'), false)
|
| 31 |
+
assert.strictEqual(reader.includes('setInterval('), false)
|
| 32 |
+
assert.match(reader, /function scheduleFoliateScrollSync\(\)/)
|
| 33 |
+
assert.match(reader, /foliateSectionObserver\?\.disconnect\(\)/)
|
| 34 |
+
assert.strictEqual((reader.match(/function disposeReader\(\)/g) || []).length, 1)
|
| 35 |
+
assert.strictEqual((reader.match(/function setReaderPhase\(/g) || []).length, 1)
|
| 36 |
+
assert.strictEqual((reader.match(/function classifyReaderError\(/g) || []).length, 1)
|
| 37 |
+
assert.match(reader, /const readerLifecycle = readerRuntime\.state\.lifecycle/)
|
| 38 |
+
assert.doesNotMatch(reader, /(?:^|\n)\s*let readerStage\b/)
|
| 39 |
+
assert.match(reader, /readerRuntime\.setStage\(stage\)/)
|
| 40 |
+
assert.match(reader, /\$\{readerLifecycle\.stage\}/)
|
| 41 |
+
assertCode(reader, 'function scheduleSave() { if (readerLifecycle.disposed || readerAbortController.signal.aborted) return;')
|
| 42 |
+
assertCode(reader, 'readerLifecycle.disposed || !documentState.restorationReady')
|
| 43 |
+
assert.strictEqual((reader.match(/if \(!setReaderPhase\("ready"\)\) return/g) || []).length, 2)
|
| 44 |
+
assert.match(reader, /addEventListener\("pagehide"/)
|
| 45 |
+
assert.match(reader, /event\.persisted/)
|
| 46 |
+
assert.match(reader, /!event\.persisted/)
|
| 47 |
+
assert.doesNotMatch(reader, /id=["']ocr["']/i)
|
| 48 |
+
assert.match(reader, /validatePdfPageManifest/)
|
| 49 |
+
assert.match(reader, /chapterManifestObserver\?\.disconnect\(\)/)
|
| 50 |
+
assert.match(reader, /content\.dataset\.errorCode = code/)
|
| 51 |
+
assert.match(reader, /reader-request-manager\.js/)
|
| 52 |
+
assert.match(reader, /VoiceOfMLReaderRequests\.createReaderRequestManager\(\)/)
|
| 53 |
+
assert.match(reader, /readerRuntime\.track\(readerRequestManager\)/)
|
| 54 |
+
for (const generation of ['navigation', 'search', 'bookmarks', 'pdf']) assert.match(reader, new RegExp(`nextReaderGeneration\\("${generation}"\\)`))
|
| 55 |
+
for (const timer of ['saveTimer', 'themeAnimationTimer', 'panelAnimationTimer']) assert.match(reader, new RegExp(`clearTimeout\\(${timer}\\)`))
|
| 56 |
+
assertCode(reader, 'for (const frame of [markerFrame, foliateScrollFrame, foliateWindowFrame, epubSeekFrame]) if (frame) cancelAnimationFrame(frame)')
|
| 57 |
+
assert.match(reader, /trackReaderResource\(destroy\)/)
|
| 58 |
+
assert.match(reader, /task\.destroy\(\)/)
|
| 59 |
+
assert.match(reader, /mediaElement\.pause\(\)/)
|
| 60 |
+
assert.match(reader, /mediaElement\.removeAttribute\("src"\)/)
|
| 61 |
+
assert.strictEqual(reader.includes('activeReaderControllers'), false)
|
| 62 |
+
assert.strictEqual(reader.includes('readerRequests'), false)
|
| 63 |
+
assert.match(reader, /function syncTocTab\(\)/)
|
| 64 |
+
assert.match(reader, /function applyReaderMetadata\(data\)/)
|
| 65 |
+
assert.strictEqual((reader.match(/function applyReaderMetadata\(data\)/g) || []).length, 1)
|
| 66 |
+
const viewportDeclaration = codePattern('const viewport = document.querySelector("#viewport")').exec(reader)
|
| 67 |
+
const metadataApplication = codePattern('applyReaderMetadata(resolvedReaderData)').exec(reader)
|
| 68 |
+
assert.ok(viewportDeclaration && metadataApplication && viewportDeclaration.index < metadataApplication.index)
|
| 69 |
+
assertCode(reader, 'formatAdapters.active.open()')
|
| 70 |
+
assertCode(reader, 'await formatAdapters.active.render(prepared)')
|
| 71 |
+
assertCode(reader, 'await formatAdapters.active.restore(documentState.restoredEntry, generation)')
|
| 72 |
+
assert.strictEqual((reader.match(/function loadPdfDocument\(\)/g) || []).length, 1)
|
| 73 |
+
for (const renderer of ['renderImageDocument', 'renderMedia']) assert.strictEqual((reader.match(new RegExp(`function ${renderer}\\s*\\(`,'g')) || []).length, 1)
|
| 74 |
+
for (const renderer of ['renderTextDocument', 'renderMarkdownDocument']) assert.strictEqual((reader.match(new RegExp(`function ${renderer}\\(`,'g')) || []).length, 1)
|
| 75 |
+
for (const loader of ['loadTextDocument', 'loadMarkdownDocument', 'loadHtmlDocument', 'loadDocxDocument']) assert.strictEqual((reader.match(new RegExp(`function ${loader}\\(`,'g')) || []).length, 1)
|
| 76 |
+
for (const loader of ['loadMediaDocument', 'loadImageDocument', 'loadChapterManifestDocument']) assert.strictEqual((reader.match(new RegExp(`function ${loader}\\(`,'g')) || []).length, 1)
|
| 77 |
+
assert.doesNotMatch(reader, /loadFoliateDocument/)
|
| 78 |
+
assert.match(reader, /reader-chapter-repository\.js/)
|
| 79 |
+
assert.match(reader, /reader-scroll-anchor\.js/)
|
| 80 |
+
assert.match(reader, /reader-section-virtualizer\.js/)
|
| 81 |
+
assert.match(reader, /VoiceOfMLReaderChapters\.createChapterRepository\(/)
|
| 82 |
+
assert.match(reader, /VoiceOfMLReaderScroll\.createScrollAnchorManager\(/)
|
| 83 |
+
assert.match(reader, /VoiceOfMLReaderVirtual\.createSectionVirtualizer\(/)
|
| 84 |
+
assert.match(reader, /foliateChapterRepository\?\.dispose\(\)/)
|
| 85 |
+
assertCode(reader, 'readerRuntime.track(VoiceOfMLReaderScroll')
|
| 86 |
+
assert.match(reader, /foliateSectionVirtualizer\?\.dispose\(\)/)
|
| 87 |
+
assert.match(reader, /function foliateSectionRoot\(article\)/)
|
| 88 |
+
assertCode(reader, 'article.attachShadow({ mode: "open" })')
|
| 89 |
+
assert.match(reader, /event\.composedPath\(\)/)
|
| 90 |
+
assert.match(reader, /foliateSectionRoot\(node\)/)
|
| 91 |
+
assert.match(reader, /foliateScrollAnchors\.observe\(article\)/)
|
| 92 |
+
assert.ok((reader.match(/foliateScrollAnchors\.invalidate\(\)/g) || []).length >= 3)
|
| 93 |
+
const renderFoliateSource = reader.match(/async\s+function\s+renderFoliate\s*\([\s\S]*?status\.textContent\s*=\s*"EPUB";/)[0]
|
| 94 |
+
assert.strictEqual(renderFoliateSource.includes('loaded = new Set'), false)
|
| 95 |
+
assert.strictEqual(renderFoliateSource.includes('pending = new Map'), false)
|
| 96 |
+
assert.match(reader, /stream\.insertBefore\(article, next \|\| null\)/)
|
| 97 |
+
assert.match(reader, /foliateSectionLoader = \(index\)/)
|
| 98 |
+
assert.doesNotMatch(reader, /^let navigationGeneration\b/m)
|
| 99 |
+
assert.doesNotMatch(reader, /syncReaderState/)
|
| 100 |
+
assert.doesNotMatch(reader, /^(?:let|var|const)\s+title\b/m)
|
| 101 |
+
for (const mirror of ['zoom', 'currentPage', 'pageCount', 'restoredEntry', 'restorationReady', 'tocEntries', 'currentChapterIndex', 'fullSearchResults', 'fullSearchIndex', 'fullSearchGeneration', 'showingAllBookmarks', 'editingBookmark', 'pdfRenderGeneration']) assert.doesNotMatch(reader, new RegExp(`(?:let|var|const)\\s+${mirror}\\b`), mirror)
|
| 102 |
+
assert.doesNotMatch(reader, /readerRuntime\.updateFormat\(/)
|
| 103 |
+
for (const domain of ['document', 'navigation', 'search', 'panel']) assert.match(reader, new RegExp(`readerRuntime\\.state\\.${domain}`))
|
| 104 |
+
assert.match(reader, /readerRuntime\.currentGeneration\("pdf"\)/)
|
| 105 |
+
assert.match(reader, /const generation = nextReaderGeneration\("search"\)/)
|
| 106 |
+
assert.match(reader, /isReaderGenerationCurrent\("navigation", generation\)/)
|
| 107 |
+
assert.match(reader, /registerReaderFormatAdapters\(\)/)
|
| 108 |
+
assert.match(reader, /function disposeFormatResources\(mode\)/)
|
| 109 |
+
assertCode(reader, 'link.target = "_blank"; link.rel = "noopener noreferrer"')
|
| 110 |
+
assert.doesNotMatch(reader, /function (?:navigateFormat|searchFormat)\(/)
|
| 111 |
+
assert.match(reader, /async function restoreFormat\(mode, entry, generation/)
|
| 112 |
+
assert.match(reader, /formatAdapters\.activate\(capability\.mode\)/)
|
| 113 |
+
assert.match(reader, /readerRuntime\.events\.on\("phase"/)
|
| 114 |
+
assert.strictEqual((reader.match(/function navigateTocEntry\(/g) || []).length, 1)
|
| 115 |
+
assert.match(reader, /await navigateTocEntry\(index\)/)
|
| 116 |
+
assert.strictEqual((reader.match(/function navigateFoliateSearchResult\(/g) || []).length, 1)
|
| 117 |
+
assert.strictEqual((reader.match(/function\s+fullSearchFoliateMatches\s*\(/g) || []).length, 1)
|
| 118 |
+
assertCode(reader, 'publishSearchResults(generation, await fullSearchFoliateMatches(query, generation))')
|
| 119 |
+
assert.match(reader, /function captureFoliateBookmarkPosition\(\)/)
|
| 120 |
+
assert.match(reader, /function restoreFoliateBookmarkPosition\(entry, generation/)
|
| 121 |
+
assert.match(reader, /foliatePosition = captureFoliateBookmarkPosition\(\)/)
|
| 122 |
+
assert.match(reader, /new IntersectionObserver/)
|
| 123 |
+
assert.doesNotMatch(reader, /article\.innerHTML = styles \+/)
|
| 124 |
+
assert.match(reader, /target = await epubRendition\?\.book\?\.resolveHref/)
|
| 125 |
+
assert.match(reader, /applyReaderMetadata\(resolvedReaderData\)/)
|
| 126 |
+
assert.match(css, /\.foliate-continuous\s+a\s*\{\s*color:\s*#8ab4e8\s*!important;\s*\}/)
|
| 127 |
+
assert.match(css, /min-height:\s*0\s*!important;\s*height:\s*auto\s*!important;/)
|
| 128 |
+
assert.strictEqual(view.includes('.find(x => x.index = resolved.index)'), false)
|
| 129 |
+
assert.strictEqual(view.includes('.find(x => x.index === resolved.index)'), true)
|
| 130 |
+
const vm = require('vm')
|
| 131 |
+
function loadExports(file, name) { const sandbox = { self: {} }; sandbox.self = sandbox; vm.runInNewContext(fs.readFileSync(path.join(root, 'static', file), 'utf8'), sandbox); return sandbox[name]; }
|
| 132 |
+
const contractFeatures = loadExports('reader-contract.js', 'VoiceOfMLReader').features
|
| 133 |
+
const runtimeMatrix = loadExports('reader-runtime.js', 'VoiceOfMLReaderRuntime').FEATURE_MATRIX
|
| 134 |
+
for (const mode of Object.keys(contractFeatures)) assert.strictEqual(JSON.stringify(runtimeMatrix[mode]), JSON.stringify(contractFeatures[mode]), mode)
|
| 135 |
+
assert.strictEqual(JSON.stringify(runtimeMatrix.unsupported), JSON.stringify({ toc: false, search: false, zoom: false, bookmarks: false, pagination: false, media: false }))
|
| 136 |
+
// Evaluate the owning registry with identifiable loaders/renderers, so comments or
|
| 137 |
+
// dead dispatch functions cannot satisfy the format wiring contract.
|
| 138 |
+
const registry = reader.match(/function\s+registerReaderFormatAdapters\s*\(\)\s*\{[\s\S]*?\n\}/)
|
| 139 |
+
assert.ok(registry, 'format adapter registry')
|
| 140 |
+
const expected = {
|
| 141 |
+
pdf: ['loadPdfDocument', 'renderPdf'], image: ['loadImageDocument', 'renderImageDocument'],
|
| 142 |
+
text: ['loadTextDocument', 'renderTextDocument'], markdown: ['loadMarkdownDocument', 'renderMarkdownDocument'],
|
| 143 |
+
html: ['loadHtmlDocument', 'renderHtml'], 'epub-chapters': ['loadChapterManifestDocument', 'renderChapterManifest'],
|
| 144 |
+
docx: ['loadDocxDocument', 'renderDocx'], foliate: ['loadMediaDocument', 'renderFoliate'],
|
| 145 |
+
}
|
| 146 |
+
const registered = new Map(), calls = []
|
| 147 |
+
const registryContext = { formatAdapters: { register: (mode, adapter) => registered.set(mode, adapter) } }
|
| 148 |
+
for (const name of [...new Set(Object.values(expected).flat()), 'preloadPdfFirstPage', 'fetchReaderResponse', 'renderPdfPages', 'renderMedia', 'restoreFormat', 'disposeFormatResources']) registryContext[name] = (...args) => calls.push([name, ...args])
|
| 149 |
+
vm.runInNewContext(registry[0] + '; registerReaderFormatAdapters();', registryContext)
|
| 150 |
+
assert.deepStrictEqual([...registered.keys()].sort(), [...Object.keys(expected), 'pdf-pages', 'audio', 'video'].sort())
|
| 151 |
+
for (const [mode, [open, render]] of Object.entries(expected)) {
|
| 152 |
+
assert.strictEqual(registered.get(mode).open, registryContext[open], mode + ' loader')
|
| 153 |
+
assert.strictEqual(registered.get(mode).render, registryContext[render], mode + ' renderer')
|
| 154 |
+
}
|
| 155 |
+
registered.get('pdf-pages').open()
|
| 156 |
+
assert.deepStrictEqual(calls.splice(0), [['preloadPdfFirstPage'], ['fetchReaderResponse']])
|
| 157 |
+
assert.strictEqual(registered.get('pdf-pages').render, registryContext.renderPdfPages)
|
| 158 |
+
for (const mode of ['audio', 'video']) {
|
| 159 |
+
assert.strictEqual(registered.get(mode).open, registryContext.loadMediaDocument)
|
| 160 |
+
registered.get(mode).render()
|
| 161 |
+
assert.deepStrictEqual(calls.splice(0), [['renderMedia', mode]])
|
| 162 |
+
}
|
| 163 |
+
for (const [mode, adapter] of registered) {
|
| 164 |
+
const entry = { page: 2 }
|
| 165 |
+
adapter.restore(entry, 17)
|
| 166 |
+
adapter.dispose()
|
| 167 |
+
assert.deepStrictEqual(calls.splice(0), [['restoreFormat', mode, entry, 17], ['disposeFormatResources', mode]])
|
| 168 |
+
}
|
| 169 |
+
const html = fs.readFileSync(path.join(root, 'static/reader.html'), 'utf8')
|
| 170 |
+
const securityScript = html.indexOf('src="/static/reader-security.js"')
|
| 171 |
+
assert.ok(securityScript >= 0 && securityScript < html.indexOf('src="/static/reader-contract.js"'))
|
| 172 |
+
assert.match(reader, /readerRuntime\.track\(window\.__VOICE_PDF_PRELOAD__\)/)
|
| 173 |
+
console.log('reader architecture contracts passed')
|
tests/test_reader_backend.py
ADDED
|
@@ -0,0 +1,438 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import asyncio
|
| 4 |
+
import contextlib
|
| 5 |
+
import gzip
|
| 6 |
+
import io
|
| 7 |
+
import json
|
| 8 |
+
import struct
|
| 9 |
+
import threading
|
| 10 |
+
import time
|
| 11 |
+
import unittest
|
| 12 |
+
import zipfile
|
| 13 |
+
from types import SimpleNamespace
|
| 14 |
+
from unittest.mock import AsyncMock, patch
|
| 15 |
+
|
| 16 |
+
IMPORT_ERROR = None
|
| 17 |
+
try:
|
| 18 |
+
import app
|
| 19 |
+
import httpx
|
| 20 |
+
except ModuleNotFoundError as exc:
|
| 21 |
+
app = None
|
| 22 |
+
IMPORT_ERROR = exc
|
| 23 |
+
|
| 24 |
+
from tests.test_async_proxy import FakeResponse, FakeSession
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
SOURCE = "https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/book29.txt"
|
| 28 |
+
OBJECT = "objects/aa/" + "a" * 64
|
| 29 |
+
BUCKET_PATH = OBJECT + "/" + "b" * 16 + "/page-manifest.json"
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def make_zip(files=None, comment=b"", zip64=False):
|
| 33 |
+
output = io.BytesIO()
|
| 34 |
+
with zipfile.ZipFile(output, "w", compression=zipfile.ZIP_DEFLATED) as archive:
|
| 35 |
+
for name, content in (files if files is not None else {"image.svg": b"<svg/>"}).items():
|
| 36 |
+
archive.writestr(name, content)
|
| 37 |
+
archive.comment = comment
|
| 38 |
+
raw = output.getvalue()
|
| 39 |
+
if not zip64:
|
| 40 |
+
return raw
|
| 41 |
+
offset = len(raw) - 22 - len(comment)
|
| 42 |
+
end = list(struct.unpack("<4s4H2LH", raw[offset:offset + 22]))
|
| 43 |
+
record64 = struct.pack("<4sQ2H2L4Q", b"PK\x06\x06", 44, 45, 45, 0, 0, end[4], end[4], end[5], end[6])
|
| 44 |
+
locator = struct.pack("<4sLQL", b"PK\x06\x07", 0, offset, 1)
|
| 45 |
+
end[3:7] = [0xffff, 0xffff, 0xffffffff, 0xffffffff]
|
| 46 |
+
return raw[:offset] + record64 + locator + struct.pack("<4s4H2LH", *end) + comment
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
@unittest.skipIf(app is None, f"backend dependencies unavailable: {IMPORT_ERROR}")
|
| 50 |
+
class ReaderArchiveValidationTests(unittest.TestCase):
|
| 51 |
+
def test_base36_independent_fixed_vectors(self):
|
| 52 |
+
for value, expected in ((0, "0"), (35, "z"), (36, "10"), (72, "20"), (1296, "100"), (2**64 - 1, "3w5e11264sgsf")):
|
| 53 |
+
with self.subTest(value=value):
|
| 54 |
+
self.assertEqual(app._base36(value), expected)
|
| 55 |
+
self.assertEqual(app.reader_short_id(SOURCE), "0ym7e7wbcxau0")
|
| 56 |
+
|
| 57 |
+
def test_valid_standard_zip64_comments_and_prepended_data(self):
|
| 58 |
+
for zip64 in (False, True):
|
| 59 |
+
for comment in (b"", b"archive comment"):
|
| 60 |
+
for prefix in (b"", b"self-extracting prefix"):
|
| 61 |
+
with self.subTest(zip64=zip64, comment=comment, prefix=prefix):
|
| 62 |
+
raw = prefix + make_zip(comment=comment, zip64=zip64)
|
| 63 |
+
app.validate_reader_archive(raw)
|
| 64 |
+
self.assertEqual(app.read_reader_archive_member(raw, "image.svg"), b"<svg/>")
|
| 65 |
+
app.validate_reader_archive(make_zip(files={}))
|
| 66 |
+
|
| 67 |
+
def test_gzip_wrapper_has_bounded_expansion(self):
|
| 68 |
+
raw = make_zip()
|
| 69 |
+
self.assertEqual(app.prepare_reader_archive(gzip.compress(raw)), raw)
|
| 70 |
+
with patch.object(app, "READER_RESOURCE_MAX_ARCHIVE_BYTES", len(raw) - 1):
|
| 71 |
+
with self.assertRaises(app.ReaderArchiveLimitError):
|
| 72 |
+
app.prepare_reader_archive(gzip.compress(raw))
|
| 73 |
+
with self.assertRaises(app.ReaderArchiveInvalidError):
|
| 74 |
+
app.prepare_reader_archive(b"\x1f\x8btruncated")
|
| 75 |
+
|
| 76 |
+
def test_directory_limits_checked_before_zipfile_construction(self):
|
| 77 |
+
for zip64 in (False, True):
|
| 78 |
+
raw = make_zip(zip64=zip64)
|
| 79 |
+
for limit in ("READER_ARCHIVE_MAX_CENTRAL_DIRECTORY_BYTES", "READER_ARCHIVE_MAX_ENTRIES"):
|
| 80 |
+
with self.subTest(zip64=zip64, limit=limit), patch.object(app, limit, 0), patch.object(app.zipfile, "ZipFile") as parser:
|
| 81 |
+
with self.assertRaises(app.ReaderArchiveLimitError):
|
| 82 |
+
app.validate_reader_archive(raw)
|
| 83 |
+
parser.assert_not_called()
|
| 84 |
+
|
| 85 |
+
def test_malformed_end_records_and_multidisk_archives(self):
|
| 86 |
+
raw = make_zip()
|
| 87 |
+
variants = [raw[:-1], b"PKnot-a-zip"]
|
| 88 |
+
for offset, fmt, value in ((4, "H", 1), (10, "H", 2), (16, "L", len(raw) + 1), (20, "H", 8)):
|
| 89 |
+
bad = bytearray(raw)
|
| 90 |
+
struct.pack_into("<" + fmt, bad, len(raw) - 22 + offset, value)
|
| 91 |
+
variants.append(bytes(bad))
|
| 92 |
+
raw64 = make_zip(zip64=True)
|
| 93 |
+
bad64 = bytearray(raw64)
|
| 94 |
+
struct.pack_into("<L", bad64, len(raw64) - 22 - 20 + 4, 1)
|
| 95 |
+
variants.extend((bytes(bad64), raw64[:-23] + raw64[-22:]))
|
| 96 |
+
for index, bad in enumerate(variants):
|
| 97 |
+
with self.subTest(index=index), self.assertRaises(app.ReaderArchiveInvalidError):
|
| 98 |
+
app.validate_reader_archive(bad)
|
| 99 |
+
|
| 100 |
+
def test_unsafe_members_and_compression_limits(self):
|
| 101 |
+
for name in ("../escape", "/absolute", "a/../escape", "a//escape", "a\\..\\escape"):
|
| 102 |
+
with self.subTest(name=name), self.assertRaises(app.ReaderArchiveInvalidError):
|
| 103 |
+
app.validate_reader_archive(make_zip({name: b"content"}))
|
| 104 |
+
with self.assertRaises(app.ReaderArchiveLimitError):
|
| 105 |
+
app.validate_reader_archive(make_zip({"bomb": b"x" * 100000}))
|
| 106 |
+
with patch.object(app, "READER_ARCHIVE_MAX_EXPANDED_BYTES", 3), self.assertRaises(app.ReaderArchiveLimitError):
|
| 107 |
+
app.validate_reader_archive(make_zip({"small": b"1234"}))
|
| 108 |
+
with self.assertRaises(app.ReaderArchiveInvalidError):
|
| 109 |
+
app.validate_reader_archive(make_zip().replace(b"image.svg", b"im\x00ge.svg"))
|
| 110 |
+
|
| 111 |
+
def test_accepted_sidecar_paths_match_the_delivery_validator(self):
|
| 112 |
+
files = {}
|
| 113 |
+
for mode, filenames in app.READER_ASSET_FILENAMES.items():
|
| 114 |
+
for filename in filenames:
|
| 115 |
+
for directory in ("", "converter-v1/", "b" * 16 + "/", "b" * 16 + "/converter-v1/"):
|
| 116 |
+
path = OBJECT + "/" + directory + filename
|
| 117 |
+
# Page manifests have only an optional version directory.
|
| 118 |
+
if filename == "page-manifest.json" and "converter" in directory:
|
| 119 |
+
continue
|
| 120 |
+
files[path] = {"s": 2, "m": mode, "p": path}
|
| 121 |
+
files["bucket"] = {"s": 2, "m": "p", "p": BUCKET_PATH, "b": "vomebook/pdf-pages"}
|
| 122 |
+
decoded = app.decode_reader_assets(gzip.compress(json.dumps({"v": 1, "f": files}).encode()))["f"]
|
| 123 |
+
self.assertEqual(set(decoded), set(files))
|
| 124 |
+
for entry in decoded.values():
|
| 125 |
+
if entry.get("b"):
|
| 126 |
+
self.assertIsNotNone(app.READER_BUCKET_PATH_RE.fullmatch(entry["p"]))
|
| 127 |
+
else:
|
| 128 |
+
app.validate_reader_source_url(app.reader_asset_url(entry))
|
| 129 |
+
for bad in (
|
| 130 |
+
{"s": 2, "m": "e", "p": OBJECT + "/document.pdf"},
|
| 131 |
+
{"s": 2, "m": "p", "p": OBJECT + "/document.pdf", "b": "vomebook/pdf-pages"},
|
| 132 |
+
{"s": 2, "m": "p", "p": OBJECT + "/page-manifest.json", "b": "vomebook/pdf-pages"},
|
| 133 |
+
):
|
| 134 |
+
decoded = app.decode_reader_assets(gzip.compress(json.dumps({"v": 1, "f": {"bad": bad}}).encode()))
|
| 135 |
+
self.assertEqual(decoded["f"], {})
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
@unittest.skipIf(app is None, f"backend dependencies unavailable: {IMPORT_ERROR}")
|
| 139 |
+
class ReaderBackendTests(unittest.IsolatedAsyncioTestCase):
|
| 140 |
+
async def asyncSetUp(self):
|
| 141 |
+
self.saved_state = dict(app.app.state._state)
|
| 142 |
+
app.initialize_reader_archive_state(app.app)
|
| 143 |
+
app.initialize_reader_bucket_state(app.app)
|
| 144 |
+
app.app.state.upstream_semaphore = asyncio.Semaphore(1)
|
| 145 |
+
self.stack = contextlib.ExitStack()
|
| 146 |
+
self.record = {"Repo": "VoiceOfML/Test", "File": "book29", "Extension": "txt", "Folder": []}
|
| 147 |
+
self.assets = {"v": 1, "f": {}}
|
| 148 |
+
self.stack.enter_context(patch.object(app, "get_reader_assets", AsyncMock(return_value=self.assets)))
|
| 149 |
+
self.stack.enter_context(patch.object(app, "records", [self.record]))
|
| 150 |
+
self.stack.enter_context(patch.object(app, "reader_record_key_indices", {app.build_reader_asset_key(self.record): 0}))
|
| 151 |
+
self.stack.enter_context(patch.object(app, "reader_source_id_indices", {"0ym7e7wbcxau0": [0]}))
|
| 152 |
+
self.stack.enter_context(patch.object(app, "upstream_redirect_cache", {}))
|
| 153 |
+
|
| 154 |
+
async def asyncTearDown(self):
|
| 155 |
+
await app.shutdown_reader_archive_state(app.app)
|
| 156 |
+
await app.shutdown_reader_bucket_state(app.app)
|
| 157 |
+
self.stack.close()
|
| 158 |
+
app.app.state._state.clear()
|
| 159 |
+
app.app.state._state.update(self.saved_state)
|
| 160 |
+
|
| 161 |
+
def session(self, *responses):
|
| 162 |
+
session = FakeSession(responses)
|
| 163 |
+
app.app.state.http_session = session
|
| 164 |
+
return session
|
| 165 |
+
|
| 166 |
+
async def content(self, upstream, method="GET"):
|
| 167 |
+
self.session(upstream)
|
| 168 |
+
return await app.api_reader_content(SimpleNamespace(method=method, headers={}), SOURCE, None)
|
| 169 |
+
|
| 170 |
+
def assert_isolated(self, response):
|
| 171 |
+
policy = response.headers["content-security-policy"]
|
| 172 |
+
self.assertIn("sandbox;", policy)
|
| 173 |
+
self.assertIn("default-src 'none'", policy)
|
| 174 |
+
self.assertNotIn("allow-scripts", policy)
|
| 175 |
+
self.assertNotIn("allow-same-origin", policy)
|
| 176 |
+
self.assertEqual(response.headers["x-content-type-options"], "nosniff")
|
| 177 |
+
|
| 178 |
+
async def test_valid_resource_roundtrip_and_literal_http_member_names(self):
|
| 179 |
+
files = {"literal%20name.svg": b"percent", "literal name.svg": b"space", "percent%25.svg": b"percent25", "\u4e66.svg": b"unicode"}
|
| 180 |
+
upstream = FakeResponse(chunks=(make_zip(files),))
|
| 181 |
+
session = self.session(upstream)
|
| 182 |
+
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app.app), base_url="http://test") as client:
|
| 183 |
+
for name, body in files.items():
|
| 184 |
+
response = await client.get("/api/reader-resource", params={"book": SOURCE, "path": name})
|
| 185 |
+
self.assertEqual(response.status_code, 200, response.text)
|
| 186 |
+
self.assertEqual(response.content, body)
|
| 187 |
+
self.assert_isolated(response)
|
| 188 |
+
for unsafe in ("../escape", "/absolute", "a//b", "a/../b", "nul\x00"):
|
| 189 |
+
response = await client.get("/api/reader-resource", params={"book": SOURCE, "path": unsafe})
|
| 190 |
+
self.assertEqual(response.status_code, 400)
|
| 191 |
+
self.assertEqual(len(session.urls), 1)
|
| 192 |
+
self.assertTrue(upstream.released)
|
| 193 |
+
|
| 194 |
+
async def test_archive_failures_are_not_cached_and_member_limits_are_reported(self):
|
| 195 |
+
invalid = FakeResponse(chunks=(b"not-a-zip",))
|
| 196 |
+
valid = FakeResponse(chunks=(make_zip(),))
|
| 197 |
+
self.session(invalid, valid)
|
| 198 |
+
self.assertEqual((await app.api_reader_resource(SOURCE, "image.svg")).status_code, 400)
|
| 199 |
+
self.assertEqual(app.app.state.reader_archive_cache, {})
|
| 200 |
+
self.assertEqual((await app.api_reader_resource(SOURCE, "missing.svg")).status_code, 404)
|
| 201 |
+
with patch.object(app, "READER_RESOURCE_MAX_BYTES", 2):
|
| 202 |
+
self.assertEqual((await app.api_reader_resource(SOURCE, "image.svg")).status_code, 413)
|
| 203 |
+
self.assertTrue(invalid.released and valid.released)
|
| 204 |
+
self.assertEqual(app.app.state.upstream_semaphore._value, 1)
|
| 205 |
+
|
| 206 |
+
async def test_archive_cold_requests_share_load_and_cancellation_preserves_waiter(self):
|
| 207 |
+
started, release = asyncio.Event(), asyncio.Event()
|
| 208 |
+
raw = make_zip()
|
| 209 |
+
|
| 210 |
+
class SlowResponse(FakeResponse):
|
| 211 |
+
def iter_chunked(self, _size):
|
| 212 |
+
async def chunks():
|
| 213 |
+
started.set()
|
| 214 |
+
await release.wait()
|
| 215 |
+
yield raw
|
| 216 |
+
return chunks()
|
| 217 |
+
|
| 218 |
+
upstream = SlowResponse()
|
| 219 |
+
session = self.session(upstream)
|
| 220 |
+
first = asyncio.create_task(app.get_reader_archive(SOURCE))
|
| 221 |
+
await asyncio.wait_for(started.wait(), 1)
|
| 222 |
+
second = asyncio.create_task(app.get_reader_archive(SOURCE))
|
| 223 |
+
await asyncio.sleep(0)
|
| 224 |
+
first.cancel()
|
| 225 |
+
with self.assertRaises(asyncio.CancelledError):
|
| 226 |
+
await first
|
| 227 |
+
release.set()
|
| 228 |
+
self.assertEqual(await asyncio.wait_for(second, 2), raw)
|
| 229 |
+
self.assertEqual(len(session.urls), 1)
|
| 230 |
+
self.assertTrue(upstream.released)
|
| 231 |
+
self.assertEqual(app.app.state.reader_archive_inflight, {})
|
| 232 |
+
|
| 233 |
+
async def test_archive_cache_total_bytes_expiry_and_oversize_admission(self):
|
| 234 |
+
raw = make_zip()
|
| 235 |
+
session = self.session(*(FakeResponse(chunks=(raw,)) for _ in range(6)))
|
| 236 |
+
with patch.object(app, "READER_ARCHIVE_CACHE_MAX_BYTES", len(raw) * 2):
|
| 237 |
+
for index in range(3):
|
| 238 |
+
await app.get_reader_archive(SOURCE + str(index))
|
| 239 |
+
cache = app.app.state.reader_archive_cache
|
| 240 |
+
self.assertNotIn(SOURCE + "0", cache)
|
| 241 |
+
self.assertEqual(sum(len(item[1]) for item in cache.values()), len(raw) * 2)
|
| 242 |
+
cache[SOURCE + "2"] = (time.monotonic() - app.READER_ARCHIVE_CACHE_TTL_SECONDS - 1, raw)
|
| 243 |
+
await app.get_reader_archive(SOURCE + "2")
|
| 244 |
+
self.assertEqual(len(session.urls), 4)
|
| 245 |
+
with patch.object(app, "READER_ARCHIVE_CACHE_MAX_BYTES", len(raw) - 1):
|
| 246 |
+
await app.get_reader_archive(SOURCE + "big")
|
| 247 |
+
await app.get_reader_archive(SOURCE + "big")
|
| 248 |
+
self.assertNotIn(SOURCE + "big", cache)
|
| 249 |
+
self.assertEqual(len(session.urls), 6)
|
| 250 |
+
|
| 251 |
+
async def test_archive_shutdown_releases_active_download(self):
|
| 252 |
+
started = asyncio.Event()
|
| 253 |
+
|
| 254 |
+
class BlockedResponse(FakeResponse):
|
| 255 |
+
def iter_chunked(self, _size):
|
| 256 |
+
async def chunks():
|
| 257 |
+
started.set()
|
| 258 |
+
await asyncio.Event().wait()
|
| 259 |
+
yield b""
|
| 260 |
+
return chunks()
|
| 261 |
+
|
| 262 |
+
upstream = BlockedResponse()
|
| 263 |
+
self.session(upstream)
|
| 264 |
+
request = asyncio.create_task(app.get_reader_archive(SOURCE))
|
| 265 |
+
await asyncio.wait_for(started.wait(), 1)
|
| 266 |
+
with patch.object(app, "READER_ARCHIVE_MAX_INFLIGHT", 1):
|
| 267 |
+
rejected = await app.api_reader_resource(SOURCE + "other", "image.svg")
|
| 268 |
+
self.assertEqual(rejected.status_code, 503)
|
| 269 |
+
await app.shutdown_reader_archive_state(app.app)
|
| 270 |
+
with self.assertRaises(asyncio.CancelledError):
|
| 271 |
+
await request
|
| 272 |
+
self.assertTrue(upstream.released)
|
| 273 |
+
self.assertEqual(app.app.state.upstream_semaphore._value, 1)
|
| 274 |
+
self.assertEqual(app.app.state.reader_archive_cache, {})
|
| 275 |
+
|
| 276 |
+
async def test_worker_cancellation_retains_slot_until_thread_finishes(self):
|
| 277 |
+
app.app.state.reader_archive_worker_semaphore = asyncio.Semaphore(1)
|
| 278 |
+
started, release, second_started = threading.Event(), threading.Event(), threading.Event()
|
| 279 |
+
|
| 280 |
+
def blocking():
|
| 281 |
+
started.set()
|
| 282 |
+
release.wait(2)
|
| 283 |
+
|
| 284 |
+
first = asyncio.create_task(app.run_reader_archive_worker(blocking))
|
| 285 |
+
self.assertTrue(await asyncio.to_thread(started.wait, 1))
|
| 286 |
+
first.cancel()
|
| 287 |
+
second = asyncio.create_task(app.run_reader_archive_worker(second_started.set))
|
| 288 |
+
try:
|
| 289 |
+
with self.assertRaises(asyncio.CancelledError):
|
| 290 |
+
await asyncio.wait_for(first, 1)
|
| 291 |
+
await asyncio.sleep(0.02)
|
| 292 |
+
self.assertEqual(len(app.app.state.reader_archive_workers), 1)
|
| 293 |
+
self.assertFalse(second_started.is_set())
|
| 294 |
+
finally:
|
| 295 |
+
release.set()
|
| 296 |
+
results = await asyncio.gather(first, second, return_exceptions=True)
|
| 297 |
+
self.assertIsInstance(results[0], asyncio.CancelledError)
|
| 298 |
+
self.assertTrue(second_started.is_set())
|
| 299 |
+
|
| 300 |
+
async def test_archive_shutdown_waits_for_abandoned_worker(self):
|
| 301 |
+
started, release = threading.Event(), threading.Event()
|
| 302 |
+
|
| 303 |
+
def blocking():
|
| 304 |
+
started.set()
|
| 305 |
+
release.wait(2)
|
| 306 |
+
|
| 307 |
+
caller = asyncio.create_task(app.run_reader_archive_worker(blocking))
|
| 308 |
+
self.assertTrue(await asyncio.to_thread(started.wait, 1))
|
| 309 |
+
caller.cancel()
|
| 310 |
+
with self.assertRaises(asyncio.CancelledError):
|
| 311 |
+
await caller
|
| 312 |
+
shutdown = asyncio.create_task(app.shutdown_reader_archive_state(app.app))
|
| 313 |
+
try:
|
| 314 |
+
await asyncio.sleep(0.02)
|
| 315 |
+
self.assertFalse(shutdown.done())
|
| 316 |
+
finally:
|
| 317 |
+
release.set()
|
| 318 |
+
await asyncio.wait_for(shutdown, 1)
|
| 319 |
+
self.assertEqual(app.app.state.reader_archive_workers, set())
|
| 320 |
+
|
| 321 |
+
async def test_content_isolation_for_active_document_mime_types(self):
|
| 322 |
+
for mime in ("text/html", "application/xhtml+xml", "image/svg+xml"):
|
| 323 |
+
with self.subTest(mime=mime):
|
| 324 |
+
response = await self.content(FakeResponse(headers={"Content-Type": mime}, chunks=(b"active content",)))
|
| 325 |
+
self.assert_isolated(response)
|
| 326 |
+
self.assertEqual(b"".join([part async for part in response.body_iterator]), b"active content")
|
| 327 |
+
|
| 328 |
+
async def test_compressed_upstream_is_rejected_before_body_and_on_head(self):
|
| 329 |
+
for method in ("GET", "HEAD"):
|
| 330 |
+
for status in (200, 206):
|
| 331 |
+
with self.subTest(method=method, status=status):
|
| 332 |
+
upstream = FakeResponse(status, {"Content-Encoding": "gzip", "Content-Length": "35"}, chunks=(gzip.compress(b"reader text\n" * 20),))
|
| 333 |
+
with patch.object(upstream, "iter_chunked", side_effect=AssertionError("encoded body must not be read")):
|
| 334 |
+
response = await self.content(upstream, method)
|
| 335 |
+
self.assertEqual(response.status_code, 502)
|
| 336 |
+
self.assertTrue(upstream.released)
|
| 337 |
+
self.assertEqual(app.app.state.upstream_semaphore._value, 1)
|
| 338 |
+
self.assertIs(app.app.state.http_session.urls[0][1]["auto_decompress"], False)
|
| 339 |
+
|
| 340 |
+
async def test_stream_cleanup_before_start_and_after_first_body(self):
|
| 341 |
+
for fail_at in ("http.response.start", "http.response.body"):
|
| 342 |
+
with self.subTest(fail_at=fail_at):
|
| 343 |
+
upstream = FakeResponse(chunks=(b"one", b"two"))
|
| 344 |
+
with patch.object(upstream, "release", wraps=upstream.release) as released:
|
| 345 |
+
response = await self.content(upstream)
|
| 346 |
+
|
| 347 |
+
async def send(message):
|
| 348 |
+
if message["type"] == fail_at:
|
| 349 |
+
raise OSError("client disconnected")
|
| 350 |
+
|
| 351 |
+
async def receive():
|
| 352 |
+
return {"type": "http.disconnect"}
|
| 353 |
+
|
| 354 |
+
with self.assertRaises(Exception):
|
| 355 |
+
await response({"type": "http", "asgi": {"spec_version": "2.4"}}, receive, send)
|
| 356 |
+
released.assert_called_once()
|
| 357 |
+
self.assertEqual(app.app.state.upstream_semaphore._value, 1)
|
| 358 |
+
|
| 359 |
+
async def test_stream_cleanup_for_legacy_asgi_disconnect_before_iteration(self):
|
| 360 |
+
upstream = FakeResponse()
|
| 361 |
+
response = await self.content(upstream)
|
| 362 |
+
started = asyncio.Event()
|
| 363 |
+
|
| 364 |
+
async def send(message):
|
| 365 |
+
started.set()
|
| 366 |
+
await asyncio.Event().wait()
|
| 367 |
+
|
| 368 |
+
async def receive():
|
| 369 |
+
await started.wait()
|
| 370 |
+
return {"type": "http.disconnect"}
|
| 371 |
+
|
| 372 |
+
await asyncio.wait_for(response({"type": "http", "asgi": {"spec_version": "2.0"}}, receive, send), 1)
|
| 373 |
+
self.assertTrue(upstream.released)
|
| 374 |
+
self.assertEqual(app.app.state.upstream_semaphore._value, 1)
|
| 375 |
+
|
| 376 |
+
async def test_stream_cleanup_after_normal_asgi_completion_is_exactly_once(self):
|
| 377 |
+
upstream = FakeResponse(chunks=(b"one", b"two"))
|
| 378 |
+
messages = []
|
| 379 |
+
with patch.object(upstream, "release", wraps=upstream.release) as released:
|
| 380 |
+
response = await self.content(upstream)
|
| 381 |
+
async def send(message):
|
| 382 |
+
messages.append(message)
|
| 383 |
+
await response({"type": "http", "asgi": {"spec_version": "2.4"}}, AsyncMock(), send)
|
| 384 |
+
released.assert_called_once()
|
| 385 |
+
self.assertEqual(b"".join(message.get("body", b"") for message in messages), b"onetwo")
|
| 386 |
+
self.assertEqual(app.app.state.upstream_semaphore._value, 1)
|
| 387 |
+
|
| 388 |
+
async def test_malformed_headers_and_not_modified_release_upstream(self):
|
| 389 |
+
cases = (
|
| 390 |
+
(200, {"Content-Length": "invalid"}, 502),
|
| 391 |
+
(206, {"Content-Range": "bytes " + "9" * 5000 + "-1/2"}, 502),
|
| 392 |
+
(206, {"Content-Range": "bytes 0-1/2", "Content-Length": "1"}, 502),
|
| 393 |
+
(304, {"ETag": "unchanged"}, 304),
|
| 394 |
+
)
|
| 395 |
+
for status, headers, expected in cases:
|
| 396 |
+
with self.subTest(status=status, expected=expected):
|
| 397 |
+
upstream = FakeResponse(status, headers)
|
| 398 |
+
response = await self.content(upstream)
|
| 399 |
+
self.assertEqual(response.status_code, expected)
|
| 400 |
+
self.assertTrue(upstream.released)
|
| 401 |
+
self.assertEqual(app.app.state.upstream_semaphore._value, 1)
|
| 402 |
+
|
| 403 |
+
async def test_bucket_get_head_direct_and_by_source_or_converted_id(self):
|
| 404 |
+
self.assets["f"][app.build_reader_asset_key(self.record)] = {"s": 2, "m": "p", "p": BUCKET_PATH, "b": "vomebook/pdf-pages"}
|
| 405 |
+
body = b'{"kind":"pdf-pages"}'
|
| 406 |
+
with patch.object(app, "read_reader_bucket_resource", return_value=body) as read:
|
| 407 |
+
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app.app), base_url="http://test") as client:
|
| 408 |
+
cases = (("/api/reader-bucket-resource", {"path": BUCKET_PATH}), ("/api/reader-content", {"id": "0ym7e7wbcxau0"}), ("/api/reader-content", {"id": "a" * 16}))
|
| 409 |
+
for route, params in cases:
|
| 410 |
+
for method in ("GET", "HEAD"):
|
| 411 |
+
with self.subTest(route=route, params=params, method=method):
|
| 412 |
+
response = await client.request(method, route, params=params)
|
| 413 |
+
self.assertEqual(response.status_code, 200, response.text)
|
| 414 |
+
self.assertEqual(response.content, body if method == "GET" else b"")
|
| 415 |
+
self.assertEqual(response.headers["content-length"], str(len(body)))
|
| 416 |
+
self.assertIn("application/json", response.headers["content-type"])
|
| 417 |
+
self.assert_isolated(response)
|
| 418 |
+
self.assertEqual(read.call_count, 1)
|
| 419 |
+
|
| 420 |
+
async def test_bucket_content_rejects_arbitrary_relative_and_ambiguous_paths(self):
|
| 421 |
+
for url in ("https://[broken", "/api/other?path=x", "//evil.test/api/reader-bucket-resource?path=x", "/api/reader-bucket-resource?path=x&path=y", "/api/reader-bucket-resource?path=../escape"):
|
| 422 |
+
response = await app.api_reader_content(SimpleNamespace(method="GET", headers={}), url, None)
|
| 423 |
+
self.assertIn(response.status_code, (400, 403))
|
| 424 |
+
|
| 425 |
+
async def test_converted_id_does_not_hash_originals_and_conversion_precedence_agrees(self):
|
| 426 |
+
asset = {"s": 2, "m": "p", "p": OBJECT + "/page-manifest.json", "c": OBJECT + "/chapters-v1/chapter-manifest.json", "f": OBJECT + "/pdf-v1/document.pdf"}
|
| 427 |
+
self.assets["f"][app.build_reader_asset_key(self.record)] = asset
|
| 428 |
+
with patch.object(app, "reader_short_id", side_effect=AssertionError("unnecessary original scan")):
|
| 429 |
+
resolved = json.loads((await app.api_reader_resolve("a" * 16)).body)
|
| 430 |
+
enriched = app.add_reader_assets({"results": [self.record]}, self.assets)["results"][0]
|
| 431 |
+
self.assertEqual(resolved["extension"], "pdf-pages")
|
| 432 |
+
self.assertEqual(resolved["extension"], enriched["ReaderExtension"])
|
| 433 |
+
self.assertEqual(resolved["chapter_manifest"], enriched["ReaderChapterManifest"])
|
| 434 |
+
self.assertEqual(resolved["fallback"], enriched["ReaderFallback"])
|
| 435 |
+
|
| 436 |
+
|
| 437 |
+
if __name__ == "__main__":
|
| 438 |
+
unittest.main()
|
tests/test_reader_chapter_repository.js
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
const assert = require("assert");
|
| 2 |
+
const fs = require("fs");
|
| 3 |
+
const path = require("path");
|
| 4 |
+
const vm = require("vm");
|
| 5 |
+
|
| 6 |
+
function createRepository(options) {
|
| 7 |
+
const sandbox = { self: {}, DOMException };
|
| 8 |
+
sandbox.self = sandbox;
|
| 9 |
+
vm.runInNewContext(fs.readFileSync(path.join(__dirname, "../static/reader-chapter-repository.js"), "utf8"), sandbox);
|
| 10 |
+
return sandbox.VoiceOfMLReaderChapters.createChapterRepository(options);
|
| 11 |
+
}
|
| 12 |
+
|
| 13 |
+
async function main() {
|
| 14 |
+
const values = new Map();
|
| 15 |
+
let resolveCreate;
|
| 16 |
+
let creates = 0;
|
| 17 |
+
const shared = createRepository({ count: 3, find: (index) => values.get(index), create: (index) => { creates += 1; return new Promise((resolve) => { resolveCreate = () => { const value = { index }; values.set(index, value); resolve(value); }; }); } });
|
| 18 |
+
const first = shared.load(1), second = shared.load(1);
|
| 19 |
+
assert.strictEqual(first, second);
|
| 20 |
+
assert.strictEqual(shared.state(1).status, "loading");
|
| 21 |
+
assert.strictEqual(shared.pending.length, 1);
|
| 22 |
+
await Promise.resolve();
|
| 23 |
+
resolveCreate();
|
| 24 |
+
assert.deepStrictEqual(await first, { index: 1 });
|
| 25 |
+
assert.strictEqual(creates, 1);
|
| 26 |
+
assert.strictEqual(shared.state(1).status, "ready");
|
| 27 |
+
assert.strictEqual(shared.state(1).attempts, 1);
|
| 28 |
+
assert.strictEqual(shared.pending.length, 0);
|
| 29 |
+
values.delete(1);
|
| 30 |
+
assert.strictEqual(shared.release(1), true);
|
| 31 |
+
assert.strictEqual(shared.state(1).status, "idle");
|
| 32 |
+
assert.strictEqual(shared.state(1).value, null);
|
| 33 |
+
|
| 34 |
+
let attempts = 0;
|
| 35 |
+
const retry = createRepository({ count: 1, find: () => null, create: () => ++attempts === 1 ? Promise.reject(new Error("temporary")) : Promise.resolve("ready") });
|
| 36 |
+
await assert.rejects(retry.load(0), /temporary/);
|
| 37 |
+
assert.strictEqual(retry.state(0).status, "error");
|
| 38 |
+
assert.strictEqual(await retry.load(0), "ready");
|
| 39 |
+
assert.strictEqual(retry.state(0).attempts, 2);
|
| 40 |
+
assert.strictEqual(await retry.load(-1), null);
|
| 41 |
+
assert.strictEqual(await retry.load(1), null);
|
| 42 |
+
|
| 43 |
+
let finishLate;
|
| 44 |
+
let commits = 0;
|
| 45 |
+
const disposed = createRepository({ count: 1, find: () => null, create: () => new Promise((resolve) => { finishLate = resolve; }), commit: (_index, value) => { commits += 1; return value; } });
|
| 46 |
+
const late = disposed.load(0);
|
| 47 |
+
await Promise.resolve();
|
| 48 |
+
disposed.dispose();
|
| 49 |
+
finishLate("late");
|
| 50 |
+
assert.strictEqual(await late, null);
|
| 51 |
+
assert.strictEqual(commits, 0);
|
| 52 |
+
assert.strictEqual(disposed.state(0).status, "idle");
|
| 53 |
+
await assert.rejects(disposed.load(0), (error) => error.name === "AbortError");
|
| 54 |
+
let queuedCreates = 0;
|
| 55 |
+
const queued = createRepository({ count: 1, find: () => null, create: () => { queuedCreates += 1; return "unused"; } });
|
| 56 |
+
const queuedLoad = queued.load(0);
|
| 57 |
+
queued.dispose();
|
| 58 |
+
assert.strictEqual(await queuedLoad, null);
|
| 59 |
+
assert.strictEqual(queuedCreates, 0);
|
| 60 |
+
assert.strictEqual(queued.pending.length, 0);
|
| 61 |
+
console.log("reader chapter repository contracts passed");
|
| 62 |
+
}
|
| 63 |
+
|
| 64 |
+
main().catch((error) => { console.error(error); process.exitCode = 1; });
|
tests/test_reader_conversions.py
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from tests.reader_test_selection import load_category_tests
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
def load_tests(loader, _tests, _pattern):
|
| 5 |
+
return load_category_tests(loader, "conversions")
|
tests/test_reader_formats.py
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from tests.reader_test_selection import load_category_tests
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
def load_tests(loader, _tests, _pattern):
|
| 5 |
+
return load_category_tests(loader, "formats")
|
tests/test_reader_layout.py
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from tests.reader_test_selection import load_category_tests
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
def load_tests(loader, _tests, _pattern):
|
| 5 |
+
return load_category_tests(loader, "layout")
|
tests/test_reader_lifecycle.py
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from tests.reader_test_selection import load_category_tests
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
def load_tests(loader, _tests, _pattern):
|
| 5 |
+
return load_category_tests(loader, "lifecycle")
|
tests/test_reader_live_formats.py
ADDED
|
@@ -0,0 +1,364 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import os
|
| 3 |
+
import unittest
|
| 4 |
+
import urllib.parse
|
| 5 |
+
import urllib.request
|
| 6 |
+
from urllib.error import HTTPError, URLError
|
| 7 |
+
|
| 8 |
+
try:
|
| 9 |
+
from playwright.sync_api import sync_playwright
|
| 10 |
+
except ImportError:
|
| 11 |
+
sync_playwright = None
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
BASE = os.environ.get("HF_SEARCH_LIVE_BASE_URL", "").rstrip("/")
|
| 15 |
+
API_BASE = BASE
|
| 16 |
+
READER_PATH = "/static/reader.html"
|
| 17 |
+
MANIFEST_URL = "https://huggingface.co/datasets/vomebook/Reader-Assets/resolve/main/manifest.json"
|
| 18 |
+
REPO_API_URL = "https://huggingface.co/api/datasets/vomebook/Reader-Assets"
|
| 19 |
+
KNOWN_PDF_PAGES_PATH = "objects/40/400fab592d48d49dfbf90c1be75e0fc964557ff044b0df2ebcab35c586ed7f71/4b5e1b60723476d4/page-manifest.json"
|
| 20 |
+
SAMPLES = ()
|
| 21 |
+
"""
|
| 22 |
+
("pdf", f"{ASSET_ROOT}/objects/b4/b449653c13a7442ec1f9c4572c037619646e1b8c57d540a69c5c4a407e0e0a33/qpdf-decrypted-v1/document.pdf", "pdf", "pdf", None),
|
| 23 |
+
("pdf-pages", PDF_PAGES_URL, "pdf-pages", "pdf-pages", False),
|
| 24 |
+
("epub", f"{ASSET_ROOT}/objects/51/5186d06e5ba156db5c82ab011c0f2888553ea7ae6186657fc5f9440d74a09370/foliate-original-v1/document.epub", "epub", "foliate", True),
|
| 25 |
+
("mobi", f"{ASSET_ROOT}/objects/a9/a920bb7db749a5d74bd899a3392fc7c3740f655f3730e3128b23a9fe1eb78563/foliate-original-v1/document.mobi", "mobi", "foliate", None),
|
| 26 |
+
("azw3", f"{ASSET_ROOT}/objects/65/6563fed9b66427417ef9c9c44f9fcc189979cded190a9de7cd445b1cb6c9d14f/foliate-original-v1/document.azw3", "azw3", "foliate", True),
|
| 27 |
+
("audio", f"{ASSET_ROOT}/objects/36/3679a0ead0d3d72bacf71b392dbba708107f767a7bee4382909469d519259120/ffmpeg-audio-mp3-v1/audio.mp3", "mp3", "audio", False),
|
| 28 |
+
("video", f"{ASSET_ROOT}/objects/9b/9bd4e16a28936dbf9f0bf9dbcdb09b0dc9889743c5f314c0720019175181ca91/ffmpeg-video-mp4-h264-aac-v1/video.mp4", "mp4", "video", False),
|
| 29 |
+
("fb2", f"{ASSET_ROOT}/objects/79/794a61d8a31327c495e56313bdf19895b94885e9fcd2e2b8bd5f9fc5057b8608/foliate-original-v1/document.fb2", "fb2", "foliate", True),
|
| 30 |
+
("fb2-cn", f"{ASSET_ROOT}/objects/ab/ab658eeefdcfedf881cc93cff87d10a06d902af497328315460875038c769381/foliate-original-v1/document.fb2", "fb2", "foliate", True),
|
| 31 |
+
("docx", f"{ASSET_ROOT}/objects/37/3795cbd583cbb49d3cef6e4518e7cde21b2de9295f8387327f10e44de3fa8a24/docx-native-v2/document.docx", "docx", "docx", False),
|
| 32 |
+
("html", f"{ASSET_ROOT}/objects/23/23e3eb7e0d93e496ce57e6c0a44d977a42b91991409b516b087e6a79b10bb4a7/sanitized-html-v5-e2f98d3c6dd02d16/document.html", "html", "html", True),
|
| 33 |
+
)
|
| 34 |
+
"""
|
| 35 |
+
SAMPLES = ()
|
| 36 |
+
SAMPLE_BY_NAME = {sample[0]: sample for sample in SAMPLES}
|
| 37 |
+
SAMPLE_FILTER = os.environ.get("READER_LIVE_SAMPLE", "")
|
| 38 |
+
RAW_SAMPLE_NAMES = ("txt", "md")
|
| 39 |
+
RESPONSIVE_THEME_MATRIX = (
|
| 40 |
+
("desktop-light", {"width": 1440, "height": 900}, "light", "no-preference"),
|
| 41 |
+
("tablet-dark", {"width": 820, "height": 1180}, "dark", "no-preference"),
|
| 42 |
+
("mobile-high-contrast", {"width": 390, "height": 844}, "dark", "more"),
|
| 43 |
+
)
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def _normalized_extension(value):
|
| 47 |
+
return str(value or "").lower().lstrip(".")
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def _reader_extension_for_sample(name, item):
|
| 51 |
+
source_extension = _normalized_extension(item.get("source_extension"))
|
| 52 |
+
reader_mode = _normalized_extension(item.get("reader_mode"))
|
| 53 |
+
if name == "pdf" and source_extension == "pdf" and reader_mode == "pdf":
|
| 54 |
+
return "pdf"
|
| 55 |
+
if name in {"epub", "mobi", "azw3", "fb2"} and source_extension == name and reader_mode == "foliate":
|
| 56 |
+
return name
|
| 57 |
+
if name == "docx" and source_extension in {"doc", "docx"} and reader_mode == "docx":
|
| 58 |
+
return "docx"
|
| 59 |
+
if name == "html" and source_extension in {"html", "htm"} and reader_mode == "html":
|
| 60 |
+
return "html"
|
| 61 |
+
if name in {"audio", "video"} and reader_mode == name:
|
| 62 |
+
return name
|
| 63 |
+
raise ValueError(
|
| 64 |
+
f"unsupported Reader sample mapping: name={name!r}, "
|
| 65 |
+
f"source_extension={source_extension!r}, reader_mode={reader_mode!r}"
|
| 66 |
+
)
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
class ReaderSampleMappingTests(unittest.TestCase):
|
| 70 |
+
def test_converted_samples_use_reader_extensions(self):
|
| 71 |
+
cases = (
|
| 72 |
+
("pdf", {"source_extension": "PDF", "reader_mode": "pdf"}, "pdf"),
|
| 73 |
+
("epub", {"source_extension": ".EPUB", "reader_mode": "foliate"}, "epub"),
|
| 74 |
+
("mobi", {"source_extension": "mobi", "reader_mode": "foliate"}, "mobi"),
|
| 75 |
+
("azw3", {"source_extension": "AZW3", "reader_mode": "foliate"}, "azw3"),
|
| 76 |
+
("fb2", {"source_extension": "fb2", "reader_mode": "foliate"}, "fb2"),
|
| 77 |
+
("docx", {"source_extension": "DOC", "reader_mode": "docx"}, "docx"),
|
| 78 |
+
("docx", {"source_extension": "docx", "reader_mode": "docx"}, "docx"),
|
| 79 |
+
("html", {"source_extension": "HTM", "reader_mode": "html"}, "html"),
|
| 80 |
+
("audio", {"source_extension": "amr", "reader_mode": "audio"}, "audio"),
|
| 81 |
+
("video", {"source_extension": "flv", "reader_mode": "video"}, "video"),
|
| 82 |
+
)
|
| 83 |
+
for name, item, expected in cases:
|
| 84 |
+
with self.subTest(name=name, item=item):
|
| 85 |
+
self.assertEqual(_reader_extension_for_sample(name, item), expected)
|
| 86 |
+
|
| 87 |
+
def test_unknown_conversion_is_not_silently_mapped(self):
|
| 88 |
+
with self.assertRaises(ValueError):
|
| 89 |
+
_reader_extension_for_sample("audio", {"source_extension": "amr", "reader_mode": ""})
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def _raw_source_url(record):
|
| 93 |
+
for field in ("ReaderLink", "readerLink", "Link", "link", "source_url", "SourceUrl", "sourceUrl", "DownloadLink", "DownloadURL", "download_link", "download_url"):
|
| 94 |
+
value = record.get(field)
|
| 95 |
+
if not isinstance(value, str) or not value:
|
| 96 |
+
continue
|
| 97 |
+
parsed = urllib.parse.urlsplit(value)
|
| 98 |
+
if parsed.scheme != "https" or parsed.hostname not in {"huggingface.co", "hf-mirror.com"}:
|
| 99 |
+
continue
|
| 100 |
+
parts = [part for part in parsed.path.split("/") if part]
|
| 101 |
+
if len(parts) >= 6 and parts[0] == "datasets" and parts[3] in {"resolve", "raw"} and parts[4] and parts[5:]:
|
| 102 |
+
return value
|
| 103 |
+
return None
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def _select_raw_sample(name, extensions):
|
| 107 |
+
if not API_BASE:
|
| 108 |
+
return None, "HF_SEARCH_LIVE_BASE_URL is not set"
|
| 109 |
+
payload = json.dumps({"q": "", "extensions": list(extensions), "page": 1, "page_size": 5}).encode()
|
| 110 |
+
request = urllib.request.Request(API_BASE + "/api/search", data=payload, headers={"Content-Type": "application/json", "Accept": "application/json"})
|
| 111 |
+
with urllib.request.urlopen(request, timeout=45) as response:
|
| 112 |
+
body = json.load(response)
|
| 113 |
+
records = body.get("results") if isinstance(body, dict) else None
|
| 114 |
+
if not isinstance(records, list):
|
| 115 |
+
raise RuntimeError("API response has no results list")
|
| 116 |
+
for record in records:
|
| 117 |
+
if not isinstance(record, dict):
|
| 118 |
+
continue
|
| 119 |
+
extension = str(record.get("Extension") or record.get("extension") or "").lower().lstrip(".")
|
| 120 |
+
filename = str(record.get("File") or record.get("file") or "")
|
| 121 |
+
suffix = filename.rsplit(".", 1)[-1].lower() if "." in filename else ""
|
| 122 |
+
if extension not in extensions and suffix not in extensions:
|
| 123 |
+
continue
|
| 124 |
+
source = _raw_source_url(record)
|
| 125 |
+
if source:
|
| 126 |
+
return (name, source, name, "text" if name == "txt" else "markdown", None if name == "txt" else True), None
|
| 127 |
+
return None, "API returned no safe direct raw source in the first 5 results"
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
def _select_samples():
|
| 131 |
+
request = urllib.request.Request(MANIFEST_URL, headers={"Accept": "application/json"})
|
| 132 |
+
with urllib.request.urlopen(request, timeout=60) as response:
|
| 133 |
+
manifest = json.load(response)
|
| 134 |
+
revision = os.environ.get("READER_ASSETS_REVISION") or response.headers.get("X-Repo-Commit")
|
| 135 |
+
if not revision:
|
| 136 |
+
try:
|
| 137 |
+
with urllib.request.urlopen(REPO_API_URL, timeout=30) as response:
|
| 138 |
+
revision = json.load(response).get("sha")
|
| 139 |
+
except (HTTPError, URLError, OSError, ValueError):
|
| 140 |
+
revision = None
|
| 141 |
+
if not revision:
|
| 142 |
+
raise RuntimeError("Reader-Assets revision unavailable; set READER_ASSETS_REVISION")
|
| 143 |
+
print("Reader-Assets revision:", revision)
|
| 144 |
+
root = "https://huggingface.co/datasets/vomebook/Reader-Assets/resolve/main"
|
| 145 |
+
ready = [v for v in manifest.get("files", {}).values() if v.get("status") == "ready" and v.get("path") and v.get("sha256")]
|
| 146 |
+
wanted = {"pdf": ("pdf",), "epub": ("epub",), "mobi": ("mobi",), "azw3": ("azw3",), "fb2": ("fb2",), "docx": ("docx", "doc"), "html": ("html", "htm")}
|
| 147 |
+
selected = {}
|
| 148 |
+
for name, extensions in wanted.items():
|
| 149 |
+
candidates = [v for v in ready if v.get("source_extension", "").lower() in extensions]
|
| 150 |
+
if name == "pdf":
|
| 151 |
+
candidates = [v for v in candidates if v.get("reader_mode") == "pdf"] or candidates
|
| 152 |
+
if candidates:
|
| 153 |
+
item = candidates[0]
|
| 154 |
+
selected[name] = (name, f"{root}/{item['path']}", _reader_extension_for_sample(name, item), item.get("reader_mode", name), None)
|
| 155 |
+
for mode in ("audio", "video"):
|
| 156 |
+
candidates = [v for v in ready if v.get("reader_mode") == mode or (mode == "audio" and _normalized_extension(v.get("source_extension")) == "mp3")]
|
| 157 |
+
if candidates:
|
| 158 |
+
item = candidates[0]
|
| 159 |
+
selected[mode] = (mode, f"{root}/{item['path']}", _reader_extension_for_sample(mode, item), mode, False)
|
| 160 |
+
page = manifest.get("pdf_manifest")
|
| 161 |
+
page_path = page.get("path") if isinstance(page, dict) else KNOWN_PDF_PAGES_PATH
|
| 162 |
+
page_url = f"https://voiceofml-search.hf.space/api/reader-bucket-resource?path={urllib.parse.quote(page_path, safe='')}"
|
| 163 |
+
try:
|
| 164 |
+
with urllib.request.urlopen(urllib.request.Request(page_url), timeout=30) as response:
|
| 165 |
+
if 200 <= response.status < 400:
|
| 166 |
+
selected["pdf-pages"] = ("pdf-pages", page_url, "pdf-pages", "pdf-pages", None)
|
| 167 |
+
except (HTTPError, URLError, OSError):
|
| 168 |
+
pass
|
| 169 |
+
raw_skips = {}
|
| 170 |
+
for name, extensions in (("txt", ("txt",)), ("md", ("md", "markdown"))):
|
| 171 |
+
try:
|
| 172 |
+
sample, reason = _select_raw_sample(name, extensions)
|
| 173 |
+
if sample:
|
| 174 |
+
selected[name] = sample
|
| 175 |
+
elif reason:
|
| 176 |
+
raw_skips[name] = reason
|
| 177 |
+
except Exception as error:
|
| 178 |
+
raw_skips[name] = f"raw API selector failed: {error}"
|
| 179 |
+
for name, reason in raw_skips.items():
|
| 180 |
+
print(f"Raw {name} sample skipped: {reason}")
|
| 181 |
+
order = ("pdf", "pdf-pages", "epub", "mobi", "azw3", "audio", "video", "fb2", "docx", "html", "txt", "md")
|
| 182 |
+
return tuple(selected[name] for name in order if name in selected), revision, raw_skips
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
@unittest.skipUnless(BASE and sync_playwright, "set HF_SEARCH_LIVE_BASE_URL and install Playwright")
|
| 186 |
+
class ReaderLiveFormatTests(unittest.TestCase):
|
| 187 |
+
@classmethod
|
| 188 |
+
def setUpClass(cls):
|
| 189 |
+
super().setUpClass()
|
| 190 |
+
global SAMPLES, SAMPLE_BY_NAME
|
| 191 |
+
try:
|
| 192 |
+
SAMPLES, cls.reader_assets_revision, cls.raw_sample_skips = _select_samples()
|
| 193 |
+
except Exception as error:
|
| 194 |
+
raise unittest.SkipTest(f"Reader-Assets/raw sample selection unavailable: {error}")
|
| 195 |
+
SAMPLE_BY_NAME = {sample[0]: sample for sample in SAMPLES}
|
| 196 |
+
|
| 197 |
+
def sample_or_skip(self, name):
|
| 198 |
+
sample = SAMPLE_BY_NAME.get(name)
|
| 199 |
+
if sample is None:
|
| 200 |
+
reason = getattr(self, "raw_sample_skips", {}).get(name)
|
| 201 |
+
source = "raw API" if name in RAW_SAMPLE_NAMES else "Reader-Assets"
|
| 202 |
+
self.skipTest(f"{source} has no readable sample for {name}: {reason or 'no matching sample'}")
|
| 203 |
+
return sample
|
| 204 |
+
|
| 205 |
+
def reader_url(self, source, extension, title):
|
| 206 |
+
query = urllib.parse.urlencode({"url": source, "ext": extension, "title": title})
|
| 207 |
+
return f"{BASE}{READER_PATH}?{query}"
|
| 208 |
+
|
| 209 |
+
def open_reader(self, context, sample):
|
| 210 |
+
name, source, extension, mode, _expected_toc = sample
|
| 211 |
+
page = context.new_page()
|
| 212 |
+
errors = []
|
| 213 |
+
page.on("pageerror", lambda error: errors.append(str(error)))
|
| 214 |
+
page.goto(self.reader_url(source, extension, name), wait_until="domcontentloaded", timeout=120000)
|
| 215 |
+
page.wait_for_function(
|
| 216 |
+
"() => ['ready', 'failed'].includes(document.documentElement.dataset.readerPhase)",
|
| 217 |
+
timeout=120000,
|
| 218 |
+
)
|
| 219 |
+
phase = page.locator("html").get_attribute("data-reader-phase")
|
| 220 |
+
if phase == "failed" and name == "video" and page.locator("#content").get_attribute("data-error-code") == "READER_MEDIA":
|
| 221 |
+
return page, errors
|
| 222 |
+
if phase != "ready":
|
| 223 |
+
self.fail(f"{name}: phase={phase} code={page.locator('#content').get_attribute('data-error-code')} text={page.locator('#content').inner_text()[:300]}")
|
| 224 |
+
self.assertEqual(page.locator("#content").get_attribute("data-mode"), mode, name)
|
| 225 |
+
return page, errors
|
| 226 |
+
|
| 227 |
+
def assert_content_ready(self, page, name, mode):
|
| 228 |
+
if mode == "pdf":
|
| 229 |
+
page.locator(".reader-page[data-page='1'] canvas.ready").wait_for(timeout=120000)
|
| 230 |
+
self.assertGreater(int(page.locator(".reader-page[data-page='1'] canvas").get_attribute("width")), 0, name)
|
| 231 |
+
elif mode == "pdf-pages":
|
| 232 |
+
page.locator(".reader-page[data-page='1'] img.ready").wait_for(timeout=120000)
|
| 233 |
+
self.assertTrue(page.locator(".reader-page[data-page='1'] img").evaluate("image => image.complete && image.naturalWidth > 0"), name)
|
| 234 |
+
elif mode == "foliate":
|
| 235 |
+
article = page.locator(".foliate-continuous article").first
|
| 236 |
+
article.wait_for(state="attached", timeout=120000)
|
| 237 |
+
self.assertGreater(article.evaluate("node => (node.shadowRoot || node).textContent.trim().length"), 0, name)
|
| 238 |
+
elif mode == "html":
|
| 239 |
+
self.assertGreater(len(page.frame_locator(".html-frame").locator("body").inner_text(timeout=120000).strip()), 0, name)
|
| 240 |
+
elif mode == "docx":
|
| 241 |
+
self.assertGreater(len(page.locator("#content").inner_text().strip()), 0, name)
|
| 242 |
+
elif mode in {"text", "markdown"}:
|
| 243 |
+
selector = ".reader-text" if mode == "text" else ".reader-markdown"
|
| 244 |
+
content = page.locator(selector)
|
| 245 |
+
content.wait_for(state="attached", timeout=120000)
|
| 246 |
+
self.assertGreater(len(content.inner_text().strip()), 0, name)
|
| 247 |
+
else:
|
| 248 |
+
media = page.locator(".reader-audio" if mode == "audio" else ".reader-video")
|
| 249 |
+
selector = ".reader-audio" if mode == "audio" else ".reader-video"
|
| 250 |
+
page.wait_for_function("selector => document.querySelector(selector)?.readyState >= 1 || document.documentElement.dataset.readerPhase === 'failed'", arg=selector, timeout=120000)
|
| 251 |
+
if page.locator("html").get_attribute("data-reader-phase") == "failed":
|
| 252 |
+
self.assertEqual(page.locator("#content").get_attribute("data-error-code"), "READER_MEDIA", name)
|
| 253 |
+
return
|
| 254 |
+
metadata = media.evaluate("element => ({controls: element.controls, preload: element.preload, paused: element.paused, autoplay: element.autoplay, duration: element.duration, width: element.videoWidth || 0, height: element.videoHeight || 0})")
|
| 255 |
+
self.assertTrue(metadata["controls"], name)
|
| 256 |
+
self.assertEqual(metadata["preload"], "metadata", name)
|
| 257 |
+
self.assertTrue(metadata["paused"], name)
|
| 258 |
+
self.assertFalse(metadata["autoplay"], name)
|
| 259 |
+
self.assertGreater(metadata["duration"], 0, name)
|
| 260 |
+
if mode == "video":
|
| 261 |
+
self.assertGreater(metadata["width"], 0, name)
|
| 262 |
+
self.assertGreater(metadata["height"], 0, name)
|
| 263 |
+
|
| 264 |
+
def activate_toc_when_available(self, page, expected_toc, name):
|
| 265 |
+
count = page.locator("#toc-list .toc-item").count()
|
| 266 |
+
if expected_toc is True and name != "md":
|
| 267 |
+
self.assertGreater(count, 0, name)
|
| 268 |
+
elif expected_toc is False:
|
| 269 |
+
self.assertEqual(count, 0, name)
|
| 270 |
+
if not count:
|
| 271 |
+
return
|
| 272 |
+
page.locator("#history").click()
|
| 273 |
+
page.locator("#toc-tab").click()
|
| 274 |
+
target = 1 if count > 1 else 0
|
| 275 |
+
page.locator("#toc-list .toc-item .panel-item-main").nth(target).click()
|
| 276 |
+
page.wait_for_timeout(500)
|
| 277 |
+
self.assertEqual(page.locator("html").get_attribute("data-reader-phase"), "ready", name)
|
| 278 |
+
|
| 279 |
+
def test_commit_pinned_format_matrix(self):
|
| 280 |
+
with sync_playwright() as playwright:
|
| 281 |
+
browser = playwright.chromium.launch(headless=True)
|
| 282 |
+
for sample in (item for item in SAMPLES if not SAMPLE_FILTER or item[0] == SAMPLE_FILTER):
|
| 283 |
+
name, _source, _extension, mode, expected_toc = sample
|
| 284 |
+
with self.subTest(sample=name):
|
| 285 |
+
context = browser.new_context(viewport={"width": 1440, "height": 900}, service_workers="block")
|
| 286 |
+
page, errors = self.open_reader(context, sample)
|
| 287 |
+
self.assert_content_ready(page, name, mode)
|
| 288 |
+
self.activate_toc_when_available(page, expected_toc, name)
|
| 289 |
+
self.assertEqual(errors, [], name)
|
| 290 |
+
context.close()
|
| 291 |
+
browser.close()
|
| 292 |
+
|
| 293 |
+
def test_pdf_and_pdf_pages_next_page_navigation(self):
|
| 294 |
+
with sync_playwright() as playwright:
|
| 295 |
+
browser = playwright.chromium.launch(headless=True)
|
| 296 |
+
for name in ("pdf", "pdf-pages"):
|
| 297 |
+
with self.subTest(sample=name):
|
| 298 |
+
sample = self.sample_or_skip(name)
|
| 299 |
+
context = browser.new_context(viewport={"width": 1440, "height": 900}, service_workers="block")
|
| 300 |
+
page, errors = self.open_reader(context, sample)
|
| 301 |
+
self.assertGreaterEqual(int(page.locator("#page-number").get_attribute("max")), 2, name)
|
| 302 |
+
page.locator("#page-next").evaluate("button => button.click()")
|
| 303 |
+
page.wait_for_function("() => document.querySelector('#page-number').value === '2'", timeout=120000)
|
| 304 |
+
ready_selector = ".reader-page[data-page='2'] canvas.ready" if name == "pdf" else ".reader-page[data-page='2'] img.ready"
|
| 305 |
+
page.locator(ready_selector).wait_for(timeout=120000)
|
| 306 |
+
self.assertEqual(errors, [], name)
|
| 307 |
+
context.close()
|
| 308 |
+
browser.close()
|
| 309 |
+
|
| 310 |
+
def test_representative_responsive_theme_matrix(self):
|
| 311 |
+
html_sample = self.sample_or_skip("html")
|
| 312 |
+
with sync_playwright() as playwright:
|
| 313 |
+
browser = playwright.chromium.launch(headless=True)
|
| 314 |
+
for name, viewport, theme, contrast in RESPONSIVE_THEME_MATRIX:
|
| 315 |
+
with self.subTest(matrix=name):
|
| 316 |
+
context = browser.new_context(viewport=viewport, color_scheme=theme, contrast=contrast, service_workers="block")
|
| 317 |
+
context.add_init_script(f"localStorage.setItem('theme', '{theme}')")
|
| 318 |
+
page, errors = self.open_reader(context, html_sample)
|
| 319 |
+
self.assertEqual(page.locator("html").get_attribute("data-theme"), theme, name)
|
| 320 |
+
self.assertEqual(page.evaluate("matchMedia('(prefers-contrast: more)').matches"), contrast == "more", name)
|
| 321 |
+
layout = page.evaluate("""() => {
|
| 322 |
+
const toolbar = document.querySelector('.reader-toolbar').getBoundingClientRect();
|
| 323 |
+
const viewport = document.querySelector('#viewport').getBoundingClientRect();
|
| 324 |
+
const controls = [...document.querySelectorAll('.reader-toolbar button, .reader-toolbar input, .reader-toolbar a')]
|
| 325 |
+
.filter(element => { const rect = element.getBoundingClientRect(); return rect.width > 0 && rect.height > 0; })
|
| 326 |
+
.map(element => { const rect = element.getBoundingClientRect(); return {id: element.id, left: rect.left, right: rect.right, top: rect.top, bottom: rect.bottom}; });
|
| 327 |
+
const overlaps = [];
|
| 328 |
+
controls.forEach((first, index) => controls.slice(index + 1).forEach(second => {
|
| 329 |
+
if (first.left < second.right && second.left < first.right && first.top < second.bottom && second.top < first.bottom) overlaps.push(`${first.id}/${second.id}`);
|
| 330 |
+
}));
|
| 331 |
+
return {toolbar: toolbar.toJSON(), viewport: viewport.toJSON(), controls, overlaps, documentWidth: document.documentElement.scrollWidth, windowWidth: innerWidth};
|
| 332 |
+
}""")
|
| 333 |
+
self.assertEqual(layout["overlaps"], [], name)
|
| 334 |
+
self.assertLessEqual(layout["documentWidth"], layout["windowWidth"] + 1, name)
|
| 335 |
+
self.assertGreaterEqual(layout["viewport"]["top"], layout["toolbar"]["bottom"] - 1, name)
|
| 336 |
+
self.assertGreaterEqual(layout["viewport"]["left"], 0, name)
|
| 337 |
+
self.assertLessEqual(layout["viewport"]["right"], layout["windowWidth"] + 1, name)
|
| 338 |
+
for control in layout["controls"]:
|
| 339 |
+
self.assertGreaterEqual(control["left"], 0, f"{name}: {control['id']}")
|
| 340 |
+
self.assertLessEqual(control["right"], layout["windowWidth"] + 1, f"{name}: {control['id']}")
|
| 341 |
+
self.assertEqual(errors, [], name)
|
| 342 |
+
context.close()
|
| 343 |
+
browser.close()
|
| 344 |
+
|
| 345 |
+
def test_client_local_pdf_pages_progress_restore(self):
|
| 346 |
+
sample = self.sample_or_skip("pdf-pages")
|
| 347 |
+
source = sample[1]
|
| 348 |
+
with sync_playwright() as playwright:
|
| 349 |
+
browser = playwright.chromium.launch(headless=True)
|
| 350 |
+
context = browser.new_context(viewport={"width": 1440, "height": 900}, service_workers="block")
|
| 351 |
+
first, first_errors = self.open_reader(context, sample)
|
| 352 |
+
first.locator("#page-next").evaluate("button => button.click()")
|
| 353 |
+
first.wait_for_function("() => document.querySelector('#page-number').value === '2'", timeout=120000)
|
| 354 |
+
first.wait_for_timeout(1000)
|
| 355 |
+
self.assertEqual(first.locator("#page-number").input_value(), "2")
|
| 356 |
+
first.wait_for_function("url => VoiceOfMLReaderStore.get(url).then(entry => entry?.page === 2)", arg=source, timeout=30000)
|
| 357 |
+
first.close()
|
| 358 |
+
second, second_errors = self.open_reader(context, sample)
|
| 359 |
+
second.wait_for_timeout(1000)
|
| 360 |
+
restored = second.evaluate("url => VoiceOfMLReaderStore.get(url).then(entry => ({entry, page: document.querySelector('#page-number').value}))", source)
|
| 361 |
+
self.assertEqual(restored["page"], "2", restored)
|
| 362 |
+
self.assertEqual(first_errors + second_errors, [])
|
| 363 |
+
context.close()
|
| 364 |
+
browser.close()
|
tests/test_reader_live_smoke.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import time
|
| 3 |
+
import unittest
|
| 4 |
+
import urllib.error
|
| 5 |
+
import urllib.request
|
| 6 |
+
|
| 7 |
+
BASE = os.environ.get("HF_SEARCH_LIVE_BASE_URL", "").rstrip("/")
|
| 8 |
+
|
| 9 |
+
@unittest.skipUnless(BASE, "set HF_SEARCH_LIVE_BASE_URL for production Reader smoke")
|
| 10 |
+
class ReaderLiveSmokeTests(unittest.TestCase):
|
| 11 |
+
def fetch(self, path):
|
| 12 |
+
request = urllib.request.Request(BASE + path, headers={"User-Agent": "reader-live-smoke"})
|
| 13 |
+
for attempt in range(3):
|
| 14 |
+
try:
|
| 15 |
+
with urllib.request.urlopen(request, timeout=30) as response:
|
| 16 |
+
self.assertEqual(response.status, 200, path)
|
| 17 |
+
return response.read().decode("utf-8", "replace")
|
| 18 |
+
except urllib.error.HTTPError as error:
|
| 19 |
+
if error.code < 500 or attempt == 2:
|
| 20 |
+
raise
|
| 21 |
+
except urllib.error.URLError:
|
| 22 |
+
if attempt == 2:
|
| 23 |
+
raise
|
| 24 |
+
time.sleep(2 ** attempt)
|
| 25 |
+
|
| 26 |
+
def test_reader_asset_graph(self):
|
| 27 |
+
files = ["/static/reader.html", "/static/reader.css", "/static/reader.js", "/static/reader-contract.js", "/static/reader-store.js", "/static/reader-request-manager.js", "/static/reader-chapter-repository.js", "/static/reader-scroll-anchor.js", "/static/reader-section-virtualizer.js", "/static/reader-runtime.js", "/static/reader-format-adapters.js", "/static/reader-security.js", "/static/pdf-worker-wrapper.mjs", "/static/foliate-reader/view.js"]
|
| 28 |
+
bodies = {path: self.fetch(path) for path in files}
|
| 29 |
+
self.assertTrue(all(len(body) > 20 for body in bodies.values()))
|
| 30 |
+
self.assertRegex(bodies["/static/reader.js"], r"createReaderRuntime|VoiceOfMLReaderRuntime")
|
| 31 |
+
self.assertRegex(bodies["/static/reader.js"], r"createAdapterRegistry|VoiceOfMLReaderAdapters")
|
tests/test_reader_models.js
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
const assert = require("assert");
|
| 2 |
+
const fs = require("fs");
|
| 3 |
+
const path = require("path");
|
| 4 |
+
const vm = require("vm");
|
| 5 |
+
function random(seed) { let value = seed >>> 0; return () => ((value = Math.imul(value, 1664525) + 1013904223 >>> 0) / 0x100000000); }
|
| 6 |
+
function createRepository(options) { const sandbox = { self: {}, DOMException }; sandbox.self = sandbox; vm.runInNewContext(fs.readFileSync(path.join(__dirname, "../static/reader-chapter-repository.js"), "utf8"), sandbox); return sandbox.VoiceOfMLReaderChapters.createChapterRepository(options); }
|
| 7 |
+
async function runRepositoryModel(seed) { const rand = random(seed), count = 17, present = new Map(), attempts = Array(count).fill(0), repository = createRepository({ count, find: (index) => present.get(index), create: async (index) => { attempts[index]++; if ((index + attempts[index] + seed) % 7 === 0) throw new Error("modeled failure"); return { index, attempt: attempts[index] }; }, commit: (index, value) => (present.set(index, value), value) }); for (let step = 0; step < 300; step++) { const index = Math.floor(rand() * count), operation = Math.floor(rand() * 3); if (operation === 0) { try { await repository.load(index); } catch (_) {} } else if (operation === 1) { present.delete(index); repository.release(index); } else { const first = repository.load(index), second = repository.load(index); if (repository.state(index).status === "loading") assert.strictEqual(first, second); try { await first; } catch (_) {} try { await second; } catch (_) {} } const state = repository.state(index); assert.ok(["idle", "loading", "ready", "error"].includes(state.status)); assert.strictEqual(state.attempts, attempts[index]); if (state.status === "ready") assert.strictEqual(state.value.index, index); } repository.dispose(); await assert.rejects(repository.load(0), (error) => error.name === "AbortError"); }
|
| 8 |
+
function runVirtualizerModel(seed) { const rand = random(seed); for (let round = 0; round < 120; round++) { const count = 10 + Math.floor(rand() * 40), limit = 3 + Math.floor(rand() * 10), center = Math.floor(rand() * count), removed = new Set(), nodes = Array.from({ length: count }, (_, index) => ({ index, height: 100 + index })), sandbox = { self: {} }; sandbox.self = sandbox; vm.runInNewContext(fs.readFileSync(path.join(__dirname, "../static/reader-section-virtualizer.js"), "utf8"), sandbox); const virtualizer = sandbox.VoiceOfMLReaderVirtual.createSectionVirtualizer({ limit, getLoaded: () => nodes.filter((node) => !removed.has(node.index)), getIndex: (node) => node.index, getHeight: (node) => node.height, virtualize: (_node, index) => removed.add(index), release: () => {}, preserve: (change) => change() }), result = virtualizer.trim(center), retained = nodes.filter((node) => !removed.has(node.index)); assert.ok(retained.length <= limit); assert.ok(retained.some((node) => node.index === center)); assert.strictEqual(result.retained, retained.length); } }
|
| 9 |
+
(async () => { for (const seed of [1, 7, 42, 20260903]) { await runRepositoryModel(seed); runVirtualizerModel(seed); } console.log("reader model contracts passed"); })().catch((error) => { console.error(error); process.exitCode = 1; });
|
tests/test_reader_navigation.py
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from tests.reader_test_selection import load_category_tests
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
def load_tests(loader, _tests, _pattern):
|
| 5 |
+
return load_category_tests(loader, "navigation")
|
tests/test_reader_performance.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
tests/test_reader_preload.js
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
const assert = require("assert");
|
| 2 |
+
const fs = require("fs");
|
| 3 |
+
const path = require("path");
|
| 4 |
+
const vm = require("vm");
|
| 5 |
+
|
| 6 |
+
const source = "https://reader.test/api/reader-bucket-resource?path=objects/aa/" + "a".repeat(64) + "/" + "b".repeat(16) + "/page-manifest.json";
|
| 7 |
+
function loadPreload({ chunks = [], header, security = true, blockRead = false, status = 200, saveData = true } = {}) {
|
| 8 |
+
const timers = new Map(), listeners = new Map(), state = { fetches: 0, reads: 0, cancels: 0, imageSrcs: [] };
|
| 9 |
+
class ImageMock { set src(value) { state.imageSrcs.push(value); this.currentSrc = value; } get src() { return this.currentSrc; } }
|
| 10 |
+
let readStarted;
|
| 11 |
+
const reading = new Promise(resolve => { readStarted = resolve; });
|
| 12 |
+
const sandbox = {
|
| 13 |
+
self: {}, URL, URLSearchParams, TextDecoder, Uint8Array, DataView, Response, AbortController,
|
| 14 |
+
location: { origin: "https://reader.test", search: "?url=" + encodeURIComponent(source) },
|
| 15 |
+
navigator: { connection: { saveData } }, Image: ImageMock,
|
| 16 |
+
addEventListener(type, listener) { listeners.set(type, listener); },
|
| 17 |
+
removeEventListener(type, listener) { if (listeners.get(type) === listener) listeners.delete(type); },
|
| 18 |
+
setTimeout(callback) { timers.set(1, callback); return 1; },
|
| 19 |
+
clearTimeout(id) { timers.delete(id); },
|
| 20 |
+
fetch: async (url, options) => {
|
| 21 |
+
state.fetches++;
|
| 22 |
+
state.url = url;
|
| 23 |
+
state.signal = options.signal;
|
| 24 |
+
return {
|
| 25 |
+
status, statusText: status === 200 ? "OK" : "Unavailable",
|
| 26 |
+
headers: new Headers(header ? { "content-length": header } : {}),
|
| 27 |
+
body: {
|
| 28 |
+
cancel: async () => { state.cancels++; },
|
| 29 |
+
getReader: () => ({
|
| 30 |
+
read: async () => {
|
| 31 |
+
readStarted();
|
| 32 |
+
if (blockRead) return new Promise((resolve, reject) => options.signal.addEventListener("abort", () => reject(new DOMException("timeout", "AbortError")), { once: true }));
|
| 33 |
+
const value = chunks[state.reads++];
|
| 34 |
+
return value === undefined ? { done: true } : { done: false, value };
|
| 35 |
+
},
|
| 36 |
+
cancel: async () => { state.cancels++; },
|
| 37 |
+
releaseLock() {},
|
| 38 |
+
}),
|
| 39 |
+
},
|
| 40 |
+
};
|
| 41 |
+
},
|
| 42 |
+
};
|
| 43 |
+
sandbox.self = sandbox;
|
| 44 |
+
if (security) {
|
| 45 |
+
vm.runInNewContext(fs.readFileSync(path.join(__dirname, "../static/reader-security.js"), "utf8"), sandbox);
|
| 46 |
+
sandbox.VoiceOfMLReaderSecurity = {
|
| 47 |
+
...sandbox.VoiceOfMLReaderSecurity,
|
| 48 |
+
LIMITS: { ...sandbox.VoiceOfMLReaderSecurity.LIMITS, manifestBytes: 8 },
|
| 49 |
+
};
|
| 50 |
+
}
|
| 51 |
+
vm.runInNewContext(fs.readFileSync(path.join(__dirname, "../static/reader-contract.js"), "utf8"), sandbox);
|
| 52 |
+
return { preload: sandbox.__VOICE_PDF_PRELOAD__, contract: sandbox.VoiceOfMLReader, timers, listeners, state, reading };
|
| 53 |
+
}
|
| 54 |
+
|
| 55 |
+
async function main() {
|
| 56 |
+
const missing = loadPreload({ security: false });
|
| 57 |
+
assert.strictEqual(missing.state.fetches, 0);
|
| 58 |
+
assert.strictEqual(missing.preload, undefined);
|
| 59 |
+
assert.strictEqual(missing.contract.capability("pdf").mode, "pdf");
|
| 60 |
+
|
| 61 |
+
const valid = loadPreload({ chunks: [Buffer.from("1234"), Buffer.from("5678")], header: "8" });
|
| 62 |
+
assert.strictEqual(await (await valid.preload.manifest).text(), "12345678");
|
| 63 |
+
assert.strictEqual(valid.state.url, source);
|
| 64 |
+
assert.strictEqual(valid.state.cancels, 0);
|
| 65 |
+
assert.strictEqual(valid.timers.size, 0);
|
| 66 |
+
assert.strictEqual(valid.preload.image, null);
|
| 67 |
+
|
| 68 |
+
const image = loadPreload({ chunks: [Buffer.from("ok")], saveData: false });
|
| 69 |
+
assert.strictEqual(image.state.imageSrcs.length, 1);
|
| 70 |
+
const imageRequest = image.preload.manifest;
|
| 71 |
+
image.preload.dispose();
|
| 72 |
+
image.preload.dispose();
|
| 73 |
+
assert.strictEqual(image.state.imageSrcs.at(-1), "");
|
| 74 |
+
assert.strictEqual(image.preload.image, null);
|
| 75 |
+
assert.strictEqual(image.listeners.has("pagehide"), false);
|
| 76 |
+
await imageRequest;
|
| 77 |
+
|
| 78 |
+
const bfcache = loadPreload({ chunks: [Buffer.from("ok")], saveData: false });
|
| 79 |
+
const bfcacheListener = bfcache.listeners.get("pagehide");
|
| 80 |
+
bfcacheListener({ persisted: true });
|
| 81 |
+
assert.strictEqual(bfcache.listeners.has("pagehide"), true);
|
| 82 |
+
assert.notStrictEqual(bfcache.preload.image, null);
|
| 83 |
+
bfcacheListener({ persisted: false });
|
| 84 |
+
assert.strictEqual(bfcache.listeners.has("pagehide"), false);
|
| 85 |
+
assert.strictEqual(bfcache.preload.image, null);
|
| 86 |
+
await bfcache.preload.manifest;
|
| 87 |
+
|
| 88 |
+
const oversized = loadPreload({ header: "9" });
|
| 89 |
+
await assert.rejects(oversized.preload.manifest, /READER_RESOURCE_LIMIT/);
|
| 90 |
+
assert.strictEqual(oversized.state.reads, 0);
|
| 91 |
+
assert.strictEqual(oversized.state.cancels, 1);
|
| 92 |
+
assert.strictEqual(oversized.timers.size, 0);
|
| 93 |
+
|
| 94 |
+
const streaming = loadPreload({ chunks: [new Uint8Array(4), new Uint8Array(5), new Uint8Array(5)] });
|
| 95 |
+
await assert.rejects(streaming.preload.manifest, /READER_RESOURCE_LIMIT/);
|
| 96 |
+
assert.strictEqual(streaming.state.reads, 2);
|
| 97 |
+
assert.strictEqual(streaming.state.cancels, 1);
|
| 98 |
+
assert.strictEqual(streaming.timers.size, 0);
|
| 99 |
+
|
| 100 |
+
const failed = loadPreload({ status: 503, chunks: [Buffer.from("retry")] });
|
| 101 |
+
const response = await failed.preload.manifest;
|
| 102 |
+
assert.strictEqual(response.status, 503);
|
| 103 |
+
assert.strictEqual(await response.text(), "retry");
|
| 104 |
+
|
| 105 |
+
const timeout = loadPreload({ blockRead: true });
|
| 106 |
+
await timeout.reading;
|
| 107 |
+
[...timeout.timers.values()][0]();
|
| 108 |
+
await assert.rejects(timeout.preload.manifest, error => error.name === "AbortError");
|
| 109 |
+
assert.strictEqual(timeout.state.signal.aborted, true);
|
| 110 |
+
assert.strictEqual(timeout.state.cancels, 1);
|
| 111 |
+
assert.strictEqual(timeout.timers.size, 0);
|
| 112 |
+
console.log("reader preload contracts passed");
|
| 113 |
+
}
|
| 114 |
+
|
| 115 |
+
main().catch(error => { console.error(error); process.exitCode = 1; });
|
tests/test_reader_refactor.py
ADDED
|
@@ -0,0 +1,470 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Local Reader behavior regressions; all document/network fixtures stay offline."""
|
| 2 |
+
|
| 3 |
+
import io
|
| 4 |
+
import json
|
| 5 |
+
import unittest
|
| 6 |
+
import urllib.parse
|
| 7 |
+
import zipfile
|
| 8 |
+
|
| 9 |
+
from tests import test_reader_performance as support
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
@unittest.skipIf(support.sync_playwright is None, "Playwright is unavailable")
|
| 13 |
+
class ReaderRefactorTest(unittest.TestCase):
|
| 14 |
+
@classmethod
|
| 15 |
+
def setUpClass(cls):
|
| 16 |
+
cls.server = support.static_server()
|
| 17 |
+
cls.origin = cls.server.__enter__()
|
| 18 |
+
cls.playwright = support.sync_playwright().start()
|
| 19 |
+
try:
|
| 20 |
+
cls.browser = cls.playwright.chromium.launch(headless=True, args=["--no-sandbox"])
|
| 21 |
+
except support.PlaywrightError as error:
|
| 22 |
+
cls.playwright.stop()
|
| 23 |
+
cls.server.__exit__(None, None, None)
|
| 24 |
+
raise unittest.SkipTest(str(error))
|
| 25 |
+
|
| 26 |
+
@classmethod
|
| 27 |
+
def tearDownClass(cls):
|
| 28 |
+
cls.browser.close()
|
| 29 |
+
cls.playwright.stop()
|
| 30 |
+
cls.server.__exit__(None, None, None)
|
| 31 |
+
|
| 32 |
+
def setUp(self):
|
| 33 |
+
self.context = self.browser.new_context(viewport={"width": 1100, "height": 800})
|
| 34 |
+
self.context.route("**/*", lambda route: route.continue_()
|
| 35 |
+
if route.request.url.startswith(self.origin + "/")
|
| 36 |
+
else route.abort())
|
| 37 |
+
self.page = self.context.new_page()
|
| 38 |
+
self.errors = []
|
| 39 |
+
self.page.on("pageerror", lambda error: self.errors.append(str(error)))
|
| 40 |
+
self.page.set_default_timeout(6000)
|
| 41 |
+
|
| 42 |
+
def tearDown(self):
|
| 43 |
+
self.context.close()
|
| 44 |
+
self.assertEqual(self.errors, [])
|
| 45 |
+
|
| 46 |
+
def reader_url(self, extension="txt", name="refactor", **params):
|
| 47 |
+
source = f"https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/{name}.{extension}"
|
| 48 |
+
values = {"url": source, "ext": extension, "title": name, **params}
|
| 49 |
+
return self.origin + "/static/reader.html?" + urllib.parse.urlencode(values)
|
| 50 |
+
|
| 51 |
+
def serve(self, body, mime="text/plain"):
|
| 52 |
+
self.page.route("**/api/reader-content**", lambda route: route.fulfill(
|
| 53 |
+
status=200, content_type=mime, body=body))
|
| 54 |
+
|
| 55 |
+
def open(self, url):
|
| 56 |
+
self.page.goto(url)
|
| 57 |
+
self.page.wait_for_function("() => document.documentElement.dataset.readerPhase === 'ready'")
|
| 58 |
+
|
| 59 |
+
def search(self, query):
|
| 60 |
+
self.page.locator("#history").click()
|
| 61 |
+
self.page.locator("#full-search-toggle").click()
|
| 62 |
+
self.page.locator("#full-search-input").fill(query)
|
| 63 |
+
self.page.wait_for_function("() => /个结果|未找到/.test(document.querySelector('#full-search-status').textContent)")
|
| 64 |
+
|
| 65 |
+
def wait_for_store(self, predicate, arg=None):
|
| 66 |
+
self.page.evaluate("""async arg => {
|
| 67 |
+
const check = """ + predicate + """;
|
| 68 |
+
const deadline = performance.now() + 6000;
|
| 69 |
+
while (performance.now() < deadline) {
|
| 70 |
+
if (await check(arg)) return;
|
| 71 |
+
await new Promise(resolve => setTimeout(resolve, 30));
|
| 72 |
+
}
|
| 73 |
+
throw new Error('Store condition did not become true');
|
| 74 |
+
}""", arg)
|
| 75 |
+
|
| 76 |
+
def test_cross_book_bookmark_restores_selected_position_and_rejects_mismatch(self):
|
| 77 |
+
self.serve("start\n" + "ordinary text\n" * 3000)
|
| 78 |
+
book_b = self.reader_url(name="book-b")
|
| 79 |
+
source_b = urllib.parse.parse_qs(urllib.parse.urlsplit(book_b).query)["url"][0]
|
| 80 |
+
self.open(book_b)
|
| 81 |
+
self.page.evaluate("""async ({url, readerUrl}) => {
|
| 82 |
+
await VoiceOfMLReaderStore.putBookmark({id:'selected-bookmark', url, readerUrl,
|
| 83 |
+
title:'Book B', label:'Selected passage', scrollTop:900, createdAt:1});
|
| 84 |
+
await VoiceOfMLReaderStore.put({url, readerUrl, title:'Book B', scrollTop:2500, lastReadAt:Date.now()});
|
| 85 |
+
}""", {"url": source_b, "readerUrl": book_b})
|
| 86 |
+
self.open(self.reader_url(name="book-a"))
|
| 87 |
+
# Override any pagehide save from the old B page before opening its bookmark.
|
| 88 |
+
self.page.evaluate("""async url => VoiceOfMLReaderStore.put({url, title:'Book B',
|
| 89 |
+
scrollTop:2500, lastReadAt:Date.now()+1})""", source_b)
|
| 90 |
+
self.page.locator("#history").click()
|
| 91 |
+
self.page.locator("#bookmarks-tab").click()
|
| 92 |
+
self.page.locator("#bookmarks-all").click()
|
| 93 |
+
self.page.locator("#bookmarks-list .panel-item-main", has_text="Selected passage").click()
|
| 94 |
+
self.page.wait_for_url(book_b)
|
| 95 |
+
self.page.wait_for_function("() => Math.abs(document.querySelector('#viewport').scrollTop - 900) < 2")
|
| 96 |
+
self.page.wait_for_function("() => document.documentElement.dataset.readerPhase === 'ready'")
|
| 97 |
+
self.page.evaluate("""() => { document.querySelector('#viewport').scrollTop = 2500;
|
| 98 |
+
document.dispatchEvent(new Event('visibilitychange')); }""")
|
| 99 |
+
self.page.wait_for_timeout(650)
|
| 100 |
+
self.page.reload()
|
| 101 |
+
self.page.wait_for_function("() => Math.abs(document.querySelector('#viewport').scrollTop - 2500) < 2")
|
| 102 |
+
self.open(self.reader_url(name="book-a"))
|
| 103 |
+
self.page.locator("#history").click()
|
| 104 |
+
self.page.locator("#bookmarks-tab").click()
|
| 105 |
+
self.page.locator("#bookmarks-all").click()
|
| 106 |
+
self.page.locator("#bookmarks-list .panel-item-main", has_text="Selected passage").click()
|
| 107 |
+
self.page.wait_for_url(book_b)
|
| 108 |
+
self.page.wait_for_function("() => Math.abs(document.querySelector('#viewport').scrollTop - 900) < 2")
|
| 109 |
+
self.page.locator("#viewport").evaluate("node => { node.scrollTop = 2500; node.dispatchEvent(new Event('scroll')); }")
|
| 110 |
+
self.page.wait_for_timeout(650)
|
| 111 |
+
invalid = book_b + "&bookmark=selected-bookmark&bookmark_source=wrong-source"
|
| 112 |
+
self.open(invalid)
|
| 113 |
+
self.page.wait_for_function("() => Math.abs(document.querySelector('#viewport').scrollTop - 2500) < 2")
|
| 114 |
+
saved = self.page.evaluate("url => VoiceOfMLReaderStore.get(url)", source_b)
|
| 115 |
+
self.assertNotIn("bookmark=", saved["readerUrl"])
|
| 116 |
+
|
| 117 |
+
def test_overlay_bookmark_consumes_parent_navigation_records_and_reloads_history(self):
|
| 118 |
+
self.serve("reading\n" * 3000)
|
| 119 |
+
book = self.reader_url(name="overlay-book")
|
| 120 |
+
source = urllib.parse.parse_qs(urllib.parse.urlsplit(book).query)["url"][0]
|
| 121 |
+
self.open(book)
|
| 122 |
+
self.page.evaluate("""async ({source, book}) => {
|
| 123 |
+
await VoiceOfMLReaderStore.putBookmark({id:'overlay-bookmark', url:source,
|
| 124 |
+
readerUrl:book, label:'Overlay', scrollTop:900, createdAt:1});
|
| 125 |
+
}""", {"source": source, "book": book})
|
| 126 |
+
handoff = book + "&" + urllib.parse.urlencode({
|
| 127 |
+
"bookmark": "overlay-bookmark", "bookmark_source": source,
|
| 128 |
+
"return": self.origin + "/Test?q=retained", "nav": "return-token"
|
| 129 |
+
})
|
| 130 |
+
shell = """<!doctype html><body><script>
|
| 131 |
+
window.openReader = readerUrl => {
|
| 132 |
+
const share = new URL(readerUrl); share.searchParams.delete('return'); share.searchParams.delete('nav');
|
| 133 |
+
history.replaceState({voiceReaderOverlay:true, readerUrl, extra:'keep'}, '', share.href);
|
| 134 |
+
sessionStorage.setItem('reader-navigation-current', JSON.stringify({readerUrl, shareUrl:share.href,
|
| 135 |
+
returnScroll:{top:123}, extra:'keep'}));
|
| 136 |
+
document.querySelector('iframe')?.remove();
|
| 137 |
+
const frame = document.createElement('iframe'); frame.className='reader-overlay';
|
| 138 |
+
frame.style='width:100%;height:750px'; frame.src=readerUrl; document.body.append(frame);
|
| 139 |
+
};
|
| 140 |
+
openReader(history.state?.readerUrl || JSON.parse(sessionStorage.getItem('reader-navigation-current') || 'null')?.readerUrl || HANDOFF);
|
| 141 |
+
</script>""".replace("HANDOFF", json.dumps(handoff))
|
| 142 |
+
def overlay(route):
|
| 143 |
+
if route.request.is_navigation_request() and route.request.frame == self.page.main_frame:
|
| 144 |
+
route.fulfill(content_type="text/html", body=shell)
|
| 145 |
+
else:
|
| 146 |
+
route.fallback()
|
| 147 |
+
self.page.route("**/static/reader.html?**", overlay)
|
| 148 |
+
self.page.goto(handoff)
|
| 149 |
+
frame = self.page.frame_locator("iframe.reader-overlay")
|
| 150 |
+
frame.locator("#viewport").evaluate("node => node.scrollTop")
|
| 151 |
+
self.page.wait_for_function("() => !new URL(location.href).searchParams.has('bookmark')")
|
| 152 |
+
state = self.page.evaluate("({state:history.state, saved:JSON.parse(sessionStorage.getItem('reader-navigation-current'))})")
|
| 153 |
+
self.assertNotIn("bookmark=", state["state"]["readerUrl"])
|
| 154 |
+
self.assertNotIn("bookmark=", state["saved"]["readerUrl"])
|
| 155 |
+
self.assertNotIn("bookmark=", state["saved"]["shareUrl"])
|
| 156 |
+
self.assertEqual(state["state"]["extra"], "keep")
|
| 157 |
+
self.assertEqual(state["saved"]["returnScroll"], {"top": 123})
|
| 158 |
+
self.assertIn("nav=return-token", state["state"]["readerUrl"])
|
| 159 |
+
self.assertEqual(frame.locator("#viewport").evaluate("node => node.scrollTop"), 900)
|
| 160 |
+
frame.locator("#viewport").evaluate("node => {node.scrollTop=2500; node.dispatchEvent(new Event('scroll'));}")
|
| 161 |
+
self.wait_for_store("async source => (await document.querySelector('iframe').contentWindow.VoiceOfMLReaderStore.get(source))?.scrollTop === 2500", source)
|
| 162 |
+
for session_only in (False, True):
|
| 163 |
+
if session_only:
|
| 164 |
+
self.page.evaluate("history.replaceState(null, '', location.href)")
|
| 165 |
+
self.page.reload()
|
| 166 |
+
self.page.wait_for_function("() => document.querySelector('iframe')?.contentDocument?.querySelector('#viewport')?.scrollTop === 2500")
|
| 167 |
+
self.page.evaluate("url => openReader(url)", handoff)
|
| 168 |
+
self.page.wait_for_function("() => document.querySelector('iframe')?.contentDocument?.querySelector('#viewport')?.scrollTop === 900 && !new URL(location.href).searchParams.has('bookmark')")
|
| 169 |
+
|
| 170 |
+
def test_remote_history_deletion_blocks_queued_and_future_saves_until_reopen(self):
|
| 171 |
+
self.serve("reading\n" * 3000)
|
| 172 |
+
url = self.reader_url(name="remote-history")
|
| 173 |
+
source = urllib.parse.parse_qs(urllib.parse.urlsplit(url).query)["url"][0]
|
| 174 |
+
peer = self.context.new_page()
|
| 175 |
+
store_path = urllib.parse.urlsplit(url).path.replace("reader.html", "reader-store.js")
|
| 176 |
+
peer.route("**/store-peer", lambda route: route.fulfill(content_type="text/html", body=f'<script src="{store_path}"></script>'))
|
| 177 |
+
peer.goto(self.origin + "/store-peer")
|
| 178 |
+
for event_type in ("history-remove", "history-clear"):
|
| 179 |
+
with self.subTest(event_type=event_type):
|
| 180 |
+
self.open(url)
|
| 181 |
+
self.wait_for_store("async source => !!(await VoiceOfMLReaderStore.get(source))", source)
|
| 182 |
+
self.page.evaluate("""() => {
|
| 183 |
+
const store=VoiceOfMLReaderStore; window.__writes=0; window.__changes=[];
|
| 184 |
+
store.subscribe(change => { if(change.remote) window.__changes.push(change.type); });
|
| 185 |
+
window.VoiceOfMLReaderStore={...store, put:async entry => {
|
| 186 |
+
++window.__writes; await store.put(entry);
|
| 187 |
+
if(window.__writes===1) await new Promise(resolve => window.__releaseWrite=resolve);
|
| 188 |
+
}};
|
| 189 |
+
document.querySelector('#viewport').scrollTop=900;
|
| 190 |
+
}""")
|
| 191 |
+
self.page.wait_for_function("() => !!window.__releaseWrite")
|
| 192 |
+
self.page.locator("#viewport").evaluate("node => {node.scrollTop=1500; node.dispatchEvent(new Event('scroll'));}")
|
| 193 |
+
self.page.wait_for_timeout(650)
|
| 194 |
+
await_event = {"type": event_type, "source": source}
|
| 195 |
+
peer.evaluate("async ({type,source}) => type==='history-clear' ? VoiceOfMLReaderStore.clearHistory() : VoiceOfMLReaderStore.remove(source)", await_event)
|
| 196 |
+
self.page.wait_for_function("type => window.__changes.includes(type)", arg=event_type)
|
| 197 |
+
self.page.evaluate("window.__releaseWrite()")
|
| 198 |
+
self.page.locator("#viewport").evaluate("node => {node.scrollTop=2200; node.dispatchEvent(new Event('scroll'));}")
|
| 199 |
+
self.page.wait_for_timeout(750)
|
| 200 |
+
self.assertEqual(self.page.evaluate("window.__writes"), 1)
|
| 201 |
+
self.assertIsNone(peer.evaluate("source => VoiceOfMLReaderStore.get(source)", source))
|
| 202 |
+
self.page.reload()
|
| 203 |
+
self.wait_for_store("async source => !!(await VoiceOfMLReaderStore.get(source))", source)
|
| 204 |
+
peer.close()
|
| 205 |
+
|
| 206 |
+
def test_bookmark_cleanup_preserves_unrelated_parent_and_session_navigation(self):
|
| 207 |
+
self.serve("reading\n" * 3000)
|
| 208 |
+
book = self.reader_url(name="cleanup-target")
|
| 209 |
+
source = urllib.parse.parse_qs(urllib.parse.urlsplit(book).query)["url"][0]
|
| 210 |
+
self.open(book)
|
| 211 |
+
self.page.evaluate("async ({source,book}) => VoiceOfMLReaderStore.putBookmark({id:'cleanup-mark',url:source,readerUrl:book,label:'Target',scrollTop:900,createdAt:1})", {"source": source, "book": book})
|
| 212 |
+
handoff = book + "&" + urllib.parse.urlencode({"bookmark": "cleanup-mark", "bookmark_source": source})
|
| 213 |
+
unrelated = self.reader_url(name="different", bookmark="other", bookmark_source="other")
|
| 214 |
+
record = {"readerUrl": unrelated, "shareUrl": unrelated, "extra": "preserve"}
|
| 215 |
+
shell = """<!doctype html><body><script>
|
| 216 |
+
history.replaceState({voiceReaderOverlay:true, readerUrl:OTHER}, '', OTHER);
|
| 217 |
+
sessionStorage.setItem('reader-navigation-current', JSON.stringify(RECORD));
|
| 218 |
+
const frame=document.createElement('iframe'); frame.className='reader-overlay';
|
| 219 |
+
frame.style='height:750px;width:100%'; frame.src=HANDOFF; document.body.append(frame);
|
| 220 |
+
</script>""".replace("OTHER", json.dumps(unrelated)).replace("RECORD", json.dumps(record)).replace("HANDOFF", json.dumps(handoff))
|
| 221 |
+
self.page.route("**/unrelated-overlay", lambda route: route.fulfill(content_type="text/html", body=shell))
|
| 222 |
+
self.page.goto(self.origin + "/unrelated-overlay")
|
| 223 |
+
self.page.wait_for_function("() => {const w=document.querySelector('iframe')?.contentWindow; return w?.document.querySelector('#viewport')?.scrollTop===900 && !new URL(w.location.href).searchParams.has('bookmark');}")
|
| 224 |
+
self.assertEqual(self.page.url, unrelated)
|
| 225 |
+
self.assertEqual(self.page.evaluate("history.state.readerUrl"), unrelated)
|
| 226 |
+
self.assertEqual(self.page.evaluate("JSON.parse(sessionStorage.getItem('reader-navigation-current'))"), record)
|
| 227 |
+
|
| 228 |
+
def test_remote_unrelated_history_removal_does_not_suppress_current_media(self):
|
| 229 |
+
self.serve(support.minimal_wav(), "audio/wav")
|
| 230 |
+
self.open(self.reader_url("wav", name="remote-media"))
|
| 231 |
+
self.page.wait_for_function("() => document.querySelector('audio').readyState >= 1")
|
| 232 |
+
self.page.evaluate("""() => {
|
| 233 |
+
window.__changes=[]; VoiceOfMLReaderStore.subscribe(change => {if(change.remote) window.__changes.push(change.type);});
|
| 234 |
+
const media=document.querySelector('audio');
|
| 235 |
+
Object.defineProperty(media,'currentTime',{value:45,writable:true});
|
| 236 |
+
}""")
|
| 237 |
+
peer = self.context.new_page()
|
| 238 |
+
peer.goto(self.origin + "/static/reader.html?ext=unsupported")
|
| 239 |
+
peer.evaluate("() => VoiceOfMLReaderStore.remove('unrelated')")
|
| 240 |
+
self.page.wait_for_function("() => window.__changes.includes('history-remove')")
|
| 241 |
+
self.page.locator("audio").evaluate("media => media.dispatchEvent(new Event('timeupdate'))")
|
| 242 |
+
self.wait_for_store("async () => (await VoiceOfMLReaderStore.get(new URL(location.href).searchParams.get('url')))?.mediaTime===45")
|
| 243 |
+
peer.evaluate("() => VoiceOfMLReaderStore.clearHistory()")
|
| 244 |
+
self.page.wait_for_function("() => window.__changes.includes('history-clear')")
|
| 245 |
+
self.page.locator("audio").evaluate("media => {media.currentTime=60; for(const type of ['timeupdate','pause','seeked']) media.dispatchEvent(new Event(type));}")
|
| 246 |
+
self.page.wait_for_timeout(750)
|
| 247 |
+
self.assertIsNone(self.page.evaluate("() => VoiceOfMLReaderStore.get(new URL(location.href).searchParams.get('url'))"))
|
| 248 |
+
peer.close()
|
| 249 |
+
|
| 250 |
+
def test_search_reopen_rebuilds_live_targets(self):
|
| 251 |
+
self.serve("prefix\n" * 500 + "needle" + "\nending" * 500)
|
| 252 |
+
self.open(self.reader_url())
|
| 253 |
+
self.search("needle")
|
| 254 |
+
self.page.locator("#full-search-toggle").click()
|
| 255 |
+
self.assertEqual(self.page.locator("#content .full-search-highlight").count(), 0)
|
| 256 |
+
self.page.locator("#full-search-toggle").click()
|
| 257 |
+
self.page.locator("#full-search-results .full-search-result").click()
|
| 258 |
+
self.page.wait_for_function("() => document.querySelector('#viewport').scrollTop > 1000")
|
| 259 |
+
self.assertEqual(self.page.locator("#content .full-search-highlight").text_content(), "needle")
|
| 260 |
+
|
| 261 |
+
def test_search_scans_beyond_20000_nodes_and_cancels_old_query(self):
|
| 262 |
+
self.serve("<main>" + "<span>ordinary </span>" * 21000 + "<p>unique-tail</p></main>", "text/html")
|
| 263 |
+
self.open(self.reader_url("html"))
|
| 264 |
+
self.search("unique-tail")
|
| 265 |
+
self.assertEqual(self.page.locator(".full-search-result").count(), 1)
|
| 266 |
+
self.page.locator("#full-search-input").evaluate("""input => {
|
| 267 |
+
input.value='ordinary'; input.dispatchEvent(new Event('input'));
|
| 268 |
+
input.value='unique-tail'; input.dispatchEvent(new Event('input'));
|
| 269 |
+
}""")
|
| 270 |
+
self.page.wait_for_function("() => document.querySelector('#full-search-status').textContent === '1 个结果'")
|
| 271 |
+
self.assertEqual(self.page.frame_locator(".html-frame").locator(".full-search-highlight").all_text_contents(), ["unique-tail"])
|
| 272 |
+
|
| 273 |
+
def test_search_retains_matches_across_character_batches_and_result_cap(self):
|
| 274 |
+
text = "x" * 65533 + "boundary-needle" + " y" * 100
|
| 275 |
+
self.serve(text)
|
| 276 |
+
self.open(self.reader_url())
|
| 277 |
+
self.search("boundary-needle")
|
| 278 |
+
self.assertEqual(self.page.locator(".full-search-result").count(), 1)
|
| 279 |
+
self.page.locator("#full-search-input").fill("x")
|
| 280 |
+
self.page.wait_for_function("() => document.querySelector('#full-search-status').textContent === '100+ 个结果'")
|
| 281 |
+
self.assertEqual(self.page.locator("#content mark").count(), 100)
|
| 282 |
+
|
| 283 |
+
def test_html_preserves_css_prose_and_tracks_progress_and_headings(self):
|
| 284 |
+
html = "<p>Examples: url(icon.png) and @import theme.css;</p>" + "".join(
|
| 285 |
+
f"<h1 id='chapter-{i}'>Chapter {i}</h1><p style='height:1100px'>text</p>" for i in range(4))
|
| 286 |
+
self.serve(html, "text/html")
|
| 287 |
+
self.open(self.reader_url("html"))
|
| 288 |
+
frame = self.page.frame_locator(".html-frame")
|
| 289 |
+
self.assertIn("url(icon.png) and @import theme.css;", frame.locator("body").inner_text())
|
| 290 |
+
self.assertTrue(self.page.locator(".html-frame").get_attribute("title"))
|
| 291 |
+
frame.locator("#chapter-2").evaluate("node => node.scrollIntoView()")
|
| 292 |
+
self.page.locator("#history").click()
|
| 293 |
+
self.page.wait_for_function("() => Number(document.querySelector('.reader-progress-range').value) > 40")
|
| 294 |
+
self.page.wait_for_function("() => document.querySelectorAll('.toc-item')[2].classList.contains('is-current')")
|
| 295 |
+
self.page.locator(".reader-chapter-next").click()
|
| 296 |
+
self.page.wait_for_function("() => document.querySelectorAll('.toc-item')[3].classList.contains('is-current')")
|
| 297 |
+
|
| 298 |
+
def test_html_keyboard_turns_use_iframe_and_reduced_motion(self):
|
| 299 |
+
self.context.clear_permissions()
|
| 300 |
+
self.page.emulate_media(reduced_motion="reduce")
|
| 301 |
+
self.serve("<p style='height:8000px'>Long document</p>", "text/html")
|
| 302 |
+
self.open(self.reader_url("html"))
|
| 303 |
+
self.page.locator(".html-frame").evaluate("""frame => {
|
| 304 |
+
const original = frame.contentWindow.scrollBy.bind(frame.contentWindow);
|
| 305 |
+
frame.contentWindow.scrollBy = options => { window.__turn = options; original(options); };
|
| 306 |
+
}""")
|
| 307 |
+
self.page.evaluate("document.body.dispatchEvent(new KeyboardEvent('keydown', {key:'PageDown', bubbles:true, cancelable:true}))")
|
| 308 |
+
self.assertEqual(self.page.evaluate("window.__turn.behavior"), "instant")
|
| 309 |
+
self.assertGreater(self.page.locator(".html-frame").evaluate("frame => frame.contentWindow.scrollY"), 100)
|
| 310 |
+
self.page.frame_locator(".html-frame").locator("body").evaluate("node => node.dispatchEvent(new KeyboardEvent('keydown', {key:'PageUp', bubbles:true, cancelable:true}))")
|
| 311 |
+
self.assertEqual(self.page.locator(".html-frame").evaluate("frame => frame.contentWindow.scrollY"), 0)
|
| 312 |
+
|
| 313 |
+
def test_bookmark_dialog_focus_inert_and_invoker_restoration(self):
|
| 314 |
+
self.serve("A document\n" * 200)
|
| 315 |
+
self.open(self.reader_url())
|
| 316 |
+
self.page.evaluate("document.querySelector('#download').inert = true")
|
| 317 |
+
self.page.locator("#history").click()
|
| 318 |
+
invoker = self.page.locator(".reader-progress-bookmark")
|
| 319 |
+
invoker.click()
|
| 320 |
+
self.assertEqual(self.page.locator("#bookmark-popover").get_attribute("aria-labelledby"), "bookmark-prompt")
|
| 321 |
+
self.assertTrue(self.page.locator("#history-panel").evaluate("node => node.inert"))
|
| 322 |
+
self.page.keyboard.press("Shift+Tab")
|
| 323 |
+
self.assertEqual(self.page.evaluate("document.activeElement.id"), "bookmark-cancel")
|
| 324 |
+
self.page.keyboard.press("Tab")
|
| 325 |
+
self.assertEqual(self.page.evaluate("document.activeElement.id"), "bookmark-label")
|
| 326 |
+
self.page.keyboard.press("Tab")
|
| 327 |
+
self.assertEqual(self.page.evaluate("document.activeElement.id"), "bookmark-excerpt-input")
|
| 328 |
+
self.page.keyboard.press("Escape")
|
| 329 |
+
self.assertTrue(invoker.evaluate("node => node === document.activeElement"))
|
| 330 |
+
self.assertEqual(invoker.get_attribute("aria-expanded"), "false")
|
| 331 |
+
self.assertFalse(self.page.locator("#history-panel").evaluate("node => node.inert"))
|
| 332 |
+
self.assertTrue(self.page.locator("#download").evaluate("node => node.inert"))
|
| 333 |
+
|
| 334 |
+
def test_media_updates_percentage_and_saves_during_continuous_updates(self):
|
| 335 |
+
self.serve(support.minimal_wav(), "audio/wav")
|
| 336 |
+
self.open(self.reader_url("wav"))
|
| 337 |
+
self.page.wait_for_function("() => document.querySelector('audio').readyState >= 1")
|
| 338 |
+
self.page.evaluate("""() => {
|
| 339 |
+
const media = document.querySelector('audio');
|
| 340 |
+
Object.defineProperty(media, 'duration', {value:100});
|
| 341 |
+
Object.defineProperty(media, 'currentTime', {value:45, writable:true});
|
| 342 |
+
media.dispatchEvent(new Event('timeupdate'));
|
| 343 |
+
window.__tick = setInterval(() => media.dispatchEvent(new Event('timeupdate')), 100);
|
| 344 |
+
}""")
|
| 345 |
+
self.page.locator("#history").click()
|
| 346 |
+
self.page.wait_for_function("() => document.querySelector('.reader-progress-range').value === '45'")
|
| 347 |
+
self.assertEqual(self.page.locator("#media-tab").get_attribute("aria-controls"), "media-panel")
|
| 348 |
+
self.assertEqual(self.page.locator("#media-panel").get_attribute("role"), "tabpanel")
|
| 349 |
+
self.assertTrue(self.page.locator("audio").get_attribute("aria-label"))
|
| 350 |
+
self.wait_for_store("""async () => {
|
| 351 |
+
const url = new URL(location.href).searchParams.get('url');
|
| 352 |
+
return (await VoiceOfMLReaderStore.get(url))?.mediaTime === 45;
|
| 353 |
+
}""")
|
| 354 |
+
self.page.evaluate("clearInterval(window.__tick)")
|
| 355 |
+
|
| 356 |
+
def test_image_disposal_removes_handlers_before_fallback(self):
|
| 357 |
+
self.page.add_init_script("""(() => {
|
| 358 |
+
const NativeImage = window.Image;
|
| 359 |
+
window.Image = function(...args) { const image = new NativeImage(...args); window.__image = image; return image; };
|
| 360 |
+
})()""")
|
| 361 |
+
held = []
|
| 362 |
+
self.page.route("**/api/reader-content**", lambda route: held.append(route))
|
| 363 |
+
self.page.goto(self.reader_url("png"), wait_until="domcontentloaded")
|
| 364 |
+
self.page.wait_for_function("() => window.__image?.getAttribute('src')")
|
| 365 |
+
self.page.evaluate("window.dispatchEvent(new PageTransitionEvent('pagehide', {persisted:false}))")
|
| 366 |
+
self.assertEqual(self.page.evaluate("[window.__image.onload, window.__image.onerror, window.__image.getAttribute('src')]"), [None, None, None])
|
| 367 |
+
for route in held:
|
| 368 |
+
route.abort()
|
| 369 |
+
self.assertEqual(self.page.locator("html").get_attribute("data-reader-phase"), "disposed")
|
| 370 |
+
|
| 371 |
+
def test_folder_navigation_has_one_handler_and_preserves_explicit_target(self):
|
| 372 |
+
source = "https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/folder.txt"
|
| 373 |
+
folder = self.origin + "/Test?folder_self=explicit"
|
| 374 |
+
self.page.add_init_script("sessionStorage.setItem('reader-resolve:folder-id', " + json.dumps(json.dumps({
|
| 375 |
+
"url": source, "extension": "txt", "title": "Folder", "repo": "Test", "folder": ["metadata"]
|
| 376 |
+
})) + ")")
|
| 377 |
+
self.serve("Folder document")
|
| 378 |
+
self.page.goto(self.origin + "/static/reader.html?" + urllib.parse.urlencode({
|
| 379 |
+
"id": "folder-id", "ext": "txt", "path": "Test/explicit", "folder_url": folder
|
| 380 |
+
}))
|
| 381 |
+
self.page.wait_for_function("() => document.documentElement.dataset.readerPhase === 'ready'")
|
| 382 |
+
# With a top-level Reader, the explicit folder URL must win after metadata resolves.
|
| 383 |
+
self.page.route("**/Test?**", lambda route: route.fulfill(content_type="text/html", body="Folder"))
|
| 384 |
+
self.page.locator("#reader-path").click()
|
| 385 |
+
self.page.wait_for_url(folder)
|
| 386 |
+
self.assertEqual(self.page.url, folder)
|
| 387 |
+
|
| 388 |
+
def test_chapter_manifest_restores_structured_history_and_bookmark(self):
|
| 389 |
+
source = "https://huggingface.co/datasets/vomebook/Reader-Assets/resolve/main/objects/aa/" + "a" * 64 + "/chapter-manifest.json"
|
| 390 |
+
manifest = {"version": 1, "kind": "epub-chapters", "chapters": [
|
| 391 |
+
{"index": i, "path": f"chapter-{i}.xhtml", "title": f"Chapter {i}", "bytes": 100} for i in range(1, 5)
|
| 392 |
+
]}
|
| 393 |
+
def serve(route):
|
| 394 |
+
raw = urllib.parse.parse_qs(urllib.parse.urlsplit(route.request.url).query)["url"][0]
|
| 395 |
+
if raw.endswith("chapter-manifest.json"):
|
| 396 |
+
route.fulfill(content_type="application/json", body=json.dumps(manifest))
|
| 397 |
+
else:
|
| 398 |
+
number = raw.rsplit("chapter-", 1)[-1].split(".")[0]
|
| 399 |
+
route.fulfill(content_type="text/html", body=f"<h1>Chapter {number}</h1><p style='height:2000px'>Body</p>")
|
| 400 |
+
self.page.route("**/api/reader-content**", serve)
|
| 401 |
+
url = self.reader_url("epub-chapters", url=source)
|
| 402 |
+
self.open(url)
|
| 403 |
+
self.page.locator("#history").click()
|
| 404 |
+
self.page.locator("#toc-list .panel-item-main").nth(2).click()
|
| 405 |
+
self.page.locator('.reader-epub-chapter[data-chapter="3"]').evaluate("node => { const v=document.querySelector('#viewport'); v.scrollTop += node.getBoundingClientRect().top - v.getBoundingClientRect().top + 250; }")
|
| 406 |
+
self.page.locator("#bookmark-ribbon").click()
|
| 407 |
+
self.page.locator("#bookmark-add").click()
|
| 408 |
+
self.wait_for_store("async source => (await VoiceOfMLReaderStore.listBookmarks(source)).length === 1", source)
|
| 409 |
+
bookmark = self.page.evaluate("async source => (await VoiceOfMLReaderStore.listBookmarks(source))[0]", source)
|
| 410 |
+
self.assertEqual(bookmark["chapterIndex"], 3)
|
| 411 |
+
self.page.wait_for_timeout(700)
|
| 412 |
+
self.open(url)
|
| 413 |
+
self.page.wait_for_function("() => document.querySelector('.reader-epub-chapter[data-chapter=\"3\"]')")
|
| 414 |
+
offset = self.page.locator('.reader-epub-chapter[data-chapter="3"]').evaluate("node => document.querySelector('#viewport').getBoundingClientRect().top + 8 - node.getBoundingClientRect().top")
|
| 415 |
+
self.assertAlmostEqual(offset, bookmark["chapterOffset"], delta=3)
|
| 416 |
+
self.open(url + "&" + urllib.parse.urlencode({"bookmark": bookmark["id"], "bookmark_source": source}))
|
| 417 |
+
self.page.wait_for_function("() => document.querySelector('.reader-epub-chapter[data-chapter=\"3\"]')")
|
| 418 |
+
|
| 419 |
+
def test_foliate_cfi_selects_accented_and_inline_ranges_after_repeated_search(self):
|
| 420 |
+
with zipfile.ZipFile(io.BytesIO(support.epub_with_many_chapters())) as archive:
|
| 421 |
+
files = {name: archive.read(name) for name in archive.namelist()}
|
| 422 |
+
chapter = next(name for name in files if name.endswith("chapter-1.xhtml"))
|
| 423 |
+
files[chapter] = b'''<?xml version="1.0" encoding="UTF-8"?>
|
| 424 |
+
<html xmlns="http://www.w3.org/1999/xhtml"><head><title>Search</title></head><body>
|
| 425 |
+
<h1>Search</h1><p style="height:1300px">Before</p>
|
| 426 |
+
<p id="accent">café</p><p style="height:1300px">Between</p>
|
| 427 |
+
<p id="plain">cafe</p><p id="inline">inter<b>national</b></p><p style="height:1300px">After</p>
|
| 428 |
+
</body></html>'''
|
| 429 |
+
self.serve(support.zip_bytes(files), "application/epub+zip")
|
| 430 |
+
self.open(self.reader_url("epub"))
|
| 431 |
+
self.search("cafe")
|
| 432 |
+
self.assertEqual(self.page.locator(".full-search-result").count(), 2)
|
| 433 |
+
self.page.locator(".full-search-result").first.click()
|
| 434 |
+
self.assertEqual(self.page.locator("#accent .full-search-highlight").text_content(), "caf\u00e9")
|
| 435 |
+
self.page.locator("#history").click()
|
| 436 |
+
self.page.locator("#full-search-toggle").click()
|
| 437 |
+
self.page.locator(".full-search-result").nth(1).click()
|
| 438 |
+
self.assertEqual(self.page.locator("#plain .full-search-highlight").text_content(), "cafe")
|
| 439 |
+
self.page.locator("#history").click()
|
| 440 |
+
self.page.locator("#full-search-toggle").click()
|
| 441 |
+
self.page.locator("#full-search-input").fill("international")
|
| 442 |
+
self.page.locator(".full-search-result").click()
|
| 443 |
+
self.page.locator("#inline .full-search-highlight").first.wait_for()
|
| 444 |
+
self.assertEqual("".join(self.page.locator("#inline .full-search-highlight").all_text_contents()), "international")
|
| 445 |
+
|
| 446 |
+
|
| 447 |
+
def test_chapter_resources_allow_siblings_within_manifest_family_only(self):
|
| 448 |
+
object_root = "https://huggingface.co/datasets/vomebook/Reader-Assets/resolve/main/objects/aa/" + "a" * 64 + "/"
|
| 449 |
+
for variant in ("", "epub-chapters/"):
|
| 450 |
+
with self.subTest(variant=variant):
|
| 451 |
+
base = object_root + variant
|
| 452 |
+
source = base + "chapter-manifest.json"
|
| 453 |
+
manifest = {"version": 1, "kind": "epub-chapters", "chapters": [
|
| 454 |
+
{"index": 1, "path": "chapters/chapter-1.xhtml", "bytes": 100}
|
| 455 |
+
]}
|
| 456 |
+
self.page.route("**/api/reader-content**", lambda route: route.fulfill(
|
| 457 |
+
content_type="application/json" if "chapter-manifest.json" in route.request.url else "text/html",
|
| 458 |
+
body=json.dumps(manifest) if "chapter-manifest.json" in route.request.url else """
|
| 459 |
+
<h1>Chapter</h1><img id='cover' src='../resources/cover.svg'>
|
| 460 |
+
<img id='escape' src='../../resources/outside.svg'>
|
| 461 |
+
<img id='external' src='https://evil.test/cover.svg'>
|
| 462 |
+
"""))
|
| 463 |
+
self.open(self.reader_url("epub-chapters", url=source))
|
| 464 |
+
self.assertEqual(self.page.locator("#cover").get_attribute("src"), base + "resources/cover.svg")
|
| 465 |
+
self.assertIsNone(self.page.locator("#escape").get_attribute("src"))
|
| 466 |
+
self.assertIsNone(self.page.locator("#external").get_attribute("src"))
|
| 467 |
+
|
| 468 |
+
|
| 469 |
+
if __name__ == "__main__":
|
| 470 |
+
unittest.main()
|
tests/test_reader_regression.js
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
const fs = require('fs')
|
| 2 |
+
const path = require('path')
|
| 3 |
+
const assert = require('assert')
|
| 4 |
+
const vm = require('vm')
|
| 5 |
+
const { TextEncoder } = require('util')
|
| 6 |
+
const { assertCode } = require('./reader_source_contract')
|
| 7 |
+
|
| 8 |
+
const root = path.resolve(__dirname, '..')
|
| 9 |
+
const reader = fs.readFileSync(path.join(root, 'static/reader.js'), 'utf8')
|
| 10 |
+
const contract = fs.readFileSync(path.join(root, 'static/reader-contract.js'), 'utf8')
|
| 11 |
+
const sandbox = { self: {}, TextEncoder, URLSearchParams }
|
| 12 |
+
vm.runInNewContext(contract, sandbox)
|
| 13 |
+
|
| 14 |
+
for (const extension of ['pdf', 'pdf-pages', 'txt', 'md', 'markdown', 'html', 'htm', 'docx', 'epub', 'mobi', 'azw3', 'fb2', 'fbz', 'jpg', 'png', 'mp3', 'm4a', 'flac', 'mpga', 'audio', 'mp4', 'mov', 'video']) {
|
| 15 |
+
assert.ok(sandbox.self.VoiceOfMLReader.capability(extension).mode, extension)
|
| 16 |
+
}
|
| 17 |
+
for (const extension of ['epub', 'mobi', 'azw3', 'fb2', 'fbz']) assert.strictEqual(sandbox.self.VoiceOfMLReader.capability(extension).mode, 'foliate')
|
| 18 |
+
for (const extension of sandbox.self.VoiceOfMLReader.articleExtensions) assert.deepStrictEqual(Object.keys(sandbox.self.VoiceOfMLReader.capability(extension).features).sort(), ['bookmarks', 'media', 'pagination', 'search', 'toc', 'zoom'])
|
| 19 |
+
assert.strictEqual(sandbox.self.VoiceOfMLReader.capability('pdf-pages').mode, 'pdf-pages')
|
| 20 |
+
assert.strictEqual(sandbox.self.VoiceOfMLReader.capability('pdf-pages').features.toc, true)
|
| 21 |
+
assert.strictEqual(sandbox.self.VoiceOfMLReader.capability('epub-chapters').features.search, false)
|
| 22 |
+
for (const extension of ['mp3', 'm4a', 'flac', 'mpga', 'audio']) assert.strictEqual(sandbox.self.VoiceOfMLReader.capability(extension).mode, 'audio')
|
| 23 |
+
for (const extension of ['mp4', 'mov', 'video']) assert.strictEqual(sandbox.self.VoiceOfMLReader.capability(extension).mode, 'video')
|
| 24 |
+
assert.strictEqual(sandbox.self.VoiceOfMLReader.capability('zip').mode, null)
|
| 25 |
+
const convertedUrl = sandbox.self.VoiceOfMLReader.readerUrl({
|
| 26 |
+
Link: 'https://download.example.test/books/book.mobi',
|
| 27 |
+
File: '原始书名', Extension: 'mobi', ReaderExtension: 'epub',
|
| 28 |
+
DownloadLink: 'https://download.example.test/books/book.mobi',
|
| 29 |
+
ReaderFallback: 'https://huggingface.co/datasets/vomebook/Reader-Assets/resolve/main/fallback.pdf',
|
| 30 |
+
ReaderChapterManifest: 'https://huggingface.co/datasets/vomebook/Reader-Assets/resolve/main/chapters.json',
|
| 31 |
+
}, '/reader.html')
|
| 32 |
+
const convertedParams = new URL(`https://example.test${convertedUrl}`).searchParams
|
| 33 |
+
assert.strictEqual(convertedParams.get('ext'), 'epub')
|
| 34 |
+
assert.strictEqual(convertedParams.get('title'), '原始书名.mobi')
|
| 35 |
+
assert.strictEqual(convertedParams.get('download'), 'https://download.example.test/books/book.mobi')
|
| 36 |
+
assert.strictEqual(convertedParams.get('fallback'), 'https://huggingface.co/datasets/vomebook/Reader-Assets/resolve/main/fallback.pdf')
|
| 37 |
+
assert.strictEqual(convertedParams.get('chapter_manifest'), 'https://huggingface.co/datasets/vomebook/Reader-Assets/resolve/main/chapters.json')
|
| 38 |
+
const pageAssetUrl = sandbox.self.VoiceOfMLReader.readerUrl({
|
| 39 |
+
ReaderLink: 'https://huggingface.co/datasets/vomebook/Reader-Assets/resolve/main/objects/aa/' + 'a'.repeat(64) + '/1234567890abcdef/page-manifest.json',
|
| 40 |
+
ReaderExtension: 'pdf-pages', Extension: 'mobi', File: '原始书名',
|
| 41 |
+
})
|
| 42 |
+
assert.strictEqual(new URL(`https://example.test${pageAssetUrl}`).searchParams.get('id'), 'aaaaaaaaaaaaaaaa')
|
| 43 |
+
assert.strictEqual(new URL(`https://example.test${pageAssetUrl}`).searchParams.get('ext'), 'pdf-pages')
|
| 44 |
+
const normalizedUrl = sandbox.self.VoiceOfMLReader.readerUrl({ Link: 'https://download.example.test/book.TXT', File: '书名', Extension: 'TXT', ReaderExtension: 'TXT' }, '/reader.html')
|
| 45 |
+
const normalizedParams = new URL(`https://example.test${normalizedUrl}`).searchParams
|
| 46 |
+
assert.strictEqual(normalizedParams.get('ext'), 'TXT')
|
| 47 |
+
assert.strictEqual(normalizedParams.get('title'), '书名.TXT')
|
| 48 |
+
assert.strictEqual(sandbox.self.VoiceOfMLReader.readerUrl(null, '/reader.html'), '')
|
| 49 |
+
assert.strictEqual(sandbox.self.VoiceOfMLReader.readerUrl({ Link: 'https://download.example.test/archive.zip', Extension: 'zip' }, '/reader.html'), '')
|
| 50 |
+
assert.strictEqual(sandbox.self.VoiceOfMLReader.readerUrl({ Link: 'https://download.example.test/book.txt', Extension: '.txt' }, '/reader.html'), '')
|
| 51 |
+
assert.strictEqual(sandbox.self.VoiceOfMLReader.capability('PDF').readerMode, sandbox.self.VoiceOfMLReader.ReaderMode.ORIGINAL)
|
| 52 |
+
assert.strictEqual(sandbox.self.VoiceOfMLReader.capability('PDF').article, true)
|
| 53 |
+
assert.strictEqual(sandbox.self.VoiceOfMLReader.capability('zip').readerMode, sandbox.self.VoiceOfMLReader.ReaderMode.UNSUPPORTED)
|
| 54 |
+
assert.strictEqual(sandbox.self.VoiceOfMLReader.capability('zip').article, false)
|
| 55 |
+
for (const extension of ['pdf', 'pdf-pages', 'epub', 'mobi', 'azw3', 'fb2', 'fbz', 'docx', 'txt', 'md', 'html', 'jpg', 'png', 'webp', 'mp3', 'm4a', 'flac', 'mp4', 'mov']) assert.ok(sandbox.self.VoiceOfMLReader.articleExtensions.includes(extension), extension)
|
| 56 |
+
assert.strictEqual(Object.isFrozen(sandbox.self.VoiceOfMLReader.articleExtensions), true)
|
| 57 |
+
assert.strictEqual(Object.isFrozen(sandbox.self.VoiceOfMLReader.capability('pdf')), true)
|
| 58 |
+
const immutableRecord = { Link: 'https://download.example.test/book.txt', File: 'book', Extension: 'txt' }
|
| 59 |
+
const immutableBefore = JSON.stringify(immutableRecord)
|
| 60 |
+
const defaultReaderUrl = sandbox.self.VoiceOfMLReader.readerUrl(immutableRecord)
|
| 61 |
+
assert.ok(defaultReaderUrl.startsWith('/static/reader.html?'))
|
| 62 |
+
assert.strictEqual(JSON.stringify(immutableRecord), immutableBefore)
|
| 63 |
+
assert.strictEqual((reader.match(/function setToc\(/g) || []).length, 1)
|
| 64 |
+
assertCode(reader, 'const previousList = document.querySelector("#toc-list"), list = previousList.cloneNode(false)')
|
| 65 |
+
assertCode(reader, 'previousList.replaceWith(list)')
|
| 66 |
+
assert.strictEqual((reader.match(/function activateFoliateTocEntry\(/g) || []).length, 1)
|
| 67 |
+
assert.match(reader, /reader-source:/)
|
| 68 |
+
assert.match(reader, /reader-zoom/)
|
| 69 |
+
assert.match(reader, /readerRuntime\.track\(readerRequestManager\)/)
|
| 70 |
+
assert.match(reader, /readerPath[\s\S]*voice-reader-navigate/)
|
| 71 |
+
assert.match(reader, /title: historyTitle|title,\s*extension/)
|
| 72 |
+
console.log('reader regression contracts passed')
|
tests/test_reader_request_manager.js
ADDED
|
@@ -0,0 +1,336 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
const assert = require("assert");
|
| 2 |
+
const fs = require("fs");
|
| 3 |
+
const path = require("path");
|
| 4 |
+
const vm = require("vm");
|
| 5 |
+
|
| 6 |
+
function loadManager(fetchImpl) {
|
| 7 |
+
const timers = new Map();
|
| 8 |
+
let nextTimer = 1;
|
| 9 |
+
const sandbox = {
|
| 10 |
+
self: {},
|
| 11 |
+
DOMException,
|
| 12 |
+
Response,
|
| 13 |
+
ReadableStream,
|
| 14 |
+
AbortController,
|
| 15 |
+
fetch: fetchImpl,
|
| 16 |
+
setTimeout(callback) {
|
| 17 |
+
const id = nextTimer++;
|
| 18 |
+
timers.set(id, callback);
|
| 19 |
+
return id;
|
| 20 |
+
},
|
| 21 |
+
clearTimeout(id) {
|
| 22 |
+
timers.delete(id);
|
| 23 |
+
}
|
| 24 |
+
};
|
| 25 |
+
sandbox.self = sandbox;
|
| 26 |
+
vm.runInNewContext(
|
| 27 |
+
fs.readFileSync(path.join(__dirname, "../static/reader-request-manager.js"), "utf8"),
|
| 28 |
+
sandbox
|
| 29 |
+
);
|
| 30 |
+
return { manager: sandbox.VoiceOfMLReaderRequests.createReaderRequestManager(), timers };
|
| 31 |
+
}
|
| 32 |
+
|
| 33 |
+
async function main() {
|
| 34 |
+
let resolveFetch,
|
| 35 |
+
calls = 0;
|
| 36 |
+
const shared = loadManager(() => {
|
| 37 |
+
calls += 1;
|
| 38 |
+
return new Promise((resolve) => {
|
| 39 |
+
resolveFetch = resolve;
|
| 40 |
+
});
|
| 41 |
+
});
|
| 42 |
+
const first = shared.manager.request("book", 1000),
|
| 43 |
+
second = shared.manager.request("book", 1000);
|
| 44 |
+
await Promise.resolve();
|
| 45 |
+
assert.notStrictEqual(first, second);
|
| 46 |
+
assert.strictEqual(calls, 1);
|
| 47 |
+
assert.strictEqual(shared.timers.size, 1);
|
| 48 |
+
resolveFetch(new Response("shared body", { status: 200 }));
|
| 49 |
+
const [firstResponse, secondResponse] = await Promise.all([first, second]);
|
| 50 |
+
assert.notStrictEqual(firstResponse, secondResponse);
|
| 51 |
+
assert.strictEqual(await firstResponse.text(), "shared body");
|
| 52 |
+
assert.strictEqual(await secondResponse.text(), "shared body");
|
| 53 |
+
assert.strictEqual(shared.manager.pendingCount, 0);
|
| 54 |
+
assert.strictEqual(shared.manager.activeCount, 0);
|
| 55 |
+
assert.strictEqual(shared.timers.size, 0);
|
| 56 |
+
|
| 57 |
+
const timedOut = loadManager(
|
| 58 |
+
(_url, { signal }) =>
|
| 59 |
+
new Promise((_resolve, reject) => {
|
| 60 |
+
signal.onabort = () => reject(new DOMException("timed out", "AbortError"));
|
| 61 |
+
})
|
| 62 |
+
);
|
| 63 |
+
const timedRequest = timedOut.manager.request("timeout", 25);
|
| 64 |
+
await Promise.resolve();
|
| 65 |
+
[...timedOut.timers.values()][0]();
|
| 66 |
+
await assert.rejects(timedRequest, (error) => error.name === "TimeoutError");
|
| 67 |
+
assert.strictEqual(timedOut.manager.pendingCount, 0);
|
| 68 |
+
assert.strictEqual(timedOut.timers.size, 0);
|
| 69 |
+
|
| 70 |
+
let attempts = 0;
|
| 71 |
+
const retry = loadManager(() =>
|
| 72 |
+
++attempts === 1 ? Promise.reject(new Error("temporary")) : Promise.resolve({ ok: true })
|
| 73 |
+
);
|
| 74 |
+
await assert.rejects(retry.manager.request("retry", 1000), /temporary/);
|
| 75 |
+
assert.strictEqual((await retry.manager.request("retry", 1000)).ok, true);
|
| 76 |
+
assert.strictEqual(attempts, 2);
|
| 77 |
+
|
| 78 |
+
const disposed = loadManager(
|
| 79 |
+
(_url, { signal }) =>
|
| 80 |
+
new Promise((_resolve, reject) => {
|
| 81 |
+
signal.onabort = () => reject(new DOMException("aborted", "AbortError"));
|
| 82 |
+
})
|
| 83 |
+
);
|
| 84 |
+
const pending = disposed.manager.request("slow", 1000);
|
| 85 |
+
await Promise.resolve();
|
| 86 |
+
disposed.manager.dispose();
|
| 87 |
+
await assert.rejects(pending, (error) => error.name === "AbortError");
|
| 88 |
+
assert.strictEqual(disposed.manager.pendingCount, 0);
|
| 89 |
+
assert.strictEqual(disposed.timers.size, 0);
|
| 90 |
+
await assert.rejects(
|
| 91 |
+
disposed.manager.request("late", 1000),
|
| 92 |
+
(error) => error.name === "AbortError"
|
| 93 |
+
);
|
| 94 |
+
|
| 95 |
+
let streamController;
|
| 96 |
+
const bodyTimeout = loadManager((_url, { signal }) =>
|
| 97 |
+
Promise.resolve(
|
| 98 |
+
new Response(
|
| 99 |
+
new ReadableStream({
|
| 100 |
+
start(controller) {
|
| 101 |
+
streamController = controller;
|
| 102 |
+
signal.onabort = () => controller.error(new DOMException("timed out", "AbortError"));
|
| 103 |
+
}
|
| 104 |
+
}),
|
| 105 |
+
{ status: 200 }
|
| 106 |
+
)
|
| 107 |
+
)
|
| 108 |
+
);
|
| 109 |
+
const bodyRequest = bodyTimeout.manager.request("body", 25);
|
| 110 |
+
const bodyResponse = await bodyRequest;
|
| 111 |
+
assert.strictEqual(bodyTimeout.timers.size, 1);
|
| 112 |
+
[...bodyTimeout.timers.values()][0]();
|
| 113 |
+
await assert.rejects(bodyResponse.text(), (error) => error.name === "TimeoutError");
|
| 114 |
+
assert.ok(streamController);
|
| 115 |
+
assert.strictEqual(bodyTimeout.timers.size, 0);
|
| 116 |
+
assert.strictEqual(bodyTimeout.manager.activeCount, 0);
|
| 117 |
+
|
| 118 |
+
// Fetch headers have settled, but both independent bodies still need disposal.
|
| 119 |
+
let bodyCancels = 0;
|
| 120 |
+
const signals = [];
|
| 121 |
+
const streaming = loadManager((_url, { signal }) => {
|
| 122 |
+
signals.push(signal);
|
| 123 |
+
return Promise.resolve(
|
| 124 |
+
new Response(
|
| 125 |
+
new ReadableStream({
|
| 126 |
+
cancel(reason) {
|
| 127 |
+
assert.strictEqual(reason.name, "AbortError");
|
| 128 |
+
bodyCancels++;
|
| 129 |
+
}
|
| 130 |
+
})
|
| 131 |
+
)
|
| 132 |
+
);
|
| 133 |
+
});
|
| 134 |
+
const firstBody = await streaming.manager.request("stream", 1000);
|
| 135 |
+
const secondBody = await streaming.manager.request("stream", 1000);
|
| 136 |
+
assert.strictEqual(streaming.manager.pendingCount, 0);
|
| 137 |
+
assert.strictEqual(streaming.manager.activeCount, 2);
|
| 138 |
+
const firstReading = assert.rejects(firstBody.text(), (error) => error.name === "AbortError");
|
| 139 |
+
streaming.manager.dispose();
|
| 140 |
+
await firstReading;
|
| 141 |
+
await assert.rejects(secondBody.text(), (error) => error.name === "AbortError");
|
| 142 |
+
assert.strictEqual(bodyCancels, 2);
|
| 143 |
+
assert.ok(signals.every((signal) => signal.aborted));
|
| 144 |
+
assert.strictEqual(streaming.timers.size, 0);
|
| 145 |
+
assert.strictEqual(streaming.manager.activeCount, 0);
|
| 146 |
+
streaming.manager.dispose();
|
| 147 |
+
assert.strictEqual(bodyCancels, 2);
|
| 148 |
+
|
| 149 |
+
let finishClonedFetch,
|
| 150 |
+
cloneCancels = 0;
|
| 151 |
+
const cloned = loadManager(
|
| 152 |
+
() =>
|
| 153 |
+
new Promise((resolve) => {
|
| 154 |
+
finishClonedFetch = resolve;
|
| 155 |
+
})
|
| 156 |
+
);
|
| 157 |
+
const cloneOne = cloned.manager.request("clones", 1000),
|
| 158 |
+
cloneTwo = cloned.manager.request("clones", 1000);
|
| 159 |
+
await Promise.resolve();
|
| 160 |
+
finishClonedFetch(
|
| 161 |
+
new Response(
|
| 162 |
+
new ReadableStream({
|
| 163 |
+
cancel() {
|
| 164 |
+
cloneCancels++;
|
| 165 |
+
}
|
| 166 |
+
})
|
| 167 |
+
)
|
| 168 |
+
);
|
| 169 |
+
const cloneResponses = await Promise.all([cloneOne, cloneTwo]);
|
| 170 |
+
const cloneReads = cloneResponses.map((response) =>
|
| 171 |
+
assert.rejects(response.text(), (error) => error.name === "AbortError")
|
| 172 |
+
);
|
| 173 |
+
cloned.manager.dispose();
|
| 174 |
+
await Promise.all(cloneReads);
|
| 175 |
+
assert.strictEqual(cloneCancels, 1);
|
| 176 |
+
assert.strictEqual(cloned.manager.activeCount, 0);
|
| 177 |
+
|
| 178 |
+
const cancelled = loadManager(() => Promise.resolve(new Response(new ReadableStream())));
|
| 179 |
+
const cancelResponse = await cancelled.manager.request("cancel", 1000);
|
| 180 |
+
await cancelResponse.body.cancel();
|
| 181 |
+
assert.strictEqual(cancelled.manager.activeCount, 0);
|
| 182 |
+
assert.strictEqual(cancelled.timers.size, 0);
|
| 183 |
+
|
| 184 |
+
let queuedCalls = 0;
|
| 185 |
+
const queued = loadManager(() => {
|
| 186 |
+
queuedCalls++;
|
| 187 |
+
return Promise.resolve(new Response("unused"));
|
| 188 |
+
});
|
| 189 |
+
const queuedRequest = queued.manager.request("queued", 1000);
|
| 190 |
+
queued.manager.dispose();
|
| 191 |
+
await assert.rejects(queuedRequest, (error) => error.name === "AbortError");
|
| 192 |
+
assert.strictEqual(queuedCalls, 0);
|
| 193 |
+
assert.strictEqual(queued.manager.activeCount, 0);
|
| 194 |
+
|
| 195 |
+
let finishLate,
|
| 196 |
+
lateCancels = 0;
|
| 197 |
+
const late = loadManager(
|
| 198 |
+
() =>
|
| 199 |
+
new Promise((resolve) => {
|
| 200 |
+
finishLate = resolve;
|
| 201 |
+
})
|
| 202 |
+
);
|
| 203 |
+
const lateRequest = late.manager.request("late-response", 1000);
|
| 204 |
+
await Promise.resolve();
|
| 205 |
+
late.manager.dispose();
|
| 206 |
+
finishLate(
|
| 207 |
+
new Response(
|
| 208 |
+
new ReadableStream({
|
| 209 |
+
cancel() {
|
| 210 |
+
lateCancels++;
|
| 211 |
+
}
|
| 212 |
+
})
|
| 213 |
+
)
|
| 214 |
+
);
|
| 215 |
+
await assert.rejects(lateRequest, (error) => error.name === "AbortError");
|
| 216 |
+
assert.strictEqual(lateCancels, 1);
|
| 217 |
+
assert.strictEqual(late.manager.activeCount, 0);
|
| 218 |
+
// Exercise the same cancellation boundaries for deadlines and lifecycle disposal.
|
| 219 |
+
for (const timeout of [true, false]) {
|
| 220 |
+
const name = timeout ? "TimeoutError" : "AbortError";
|
| 221 |
+
const stop = (harness) => {
|
| 222 |
+
if (timeout) [...harness.timers.values()][0]();
|
| 223 |
+
else harness.manager.dispose();
|
| 224 |
+
};
|
| 225 |
+
const assertSettled = (harness) => {
|
| 226 |
+
assert.strictEqual(harness.manager.pendingCount, 0);
|
| 227 |
+
assert.strictEqual(harness.manager.activeCount, 0);
|
| 228 |
+
assert.strictEqual(harness.timers.size, 0);
|
| 229 |
+
assert.strictEqual(harness.manager.disposed, !timeout);
|
| 230 |
+
};
|
| 231 |
+
|
| 232 |
+
let starts = 0;
|
| 233 |
+
const beforeFetch = loadManager(() => {
|
| 234 |
+
starts++;
|
| 235 |
+
return Promise.resolve(new Response("unused"));
|
| 236 |
+
});
|
| 237 |
+
const queued = beforeFetch.manager.request("queued", 25);
|
| 238 |
+
stop(beforeFetch);
|
| 239 |
+
await assert.rejects(queued, (error) => error.name === name);
|
| 240 |
+
assert.strictEqual(starts, 0);
|
| 241 |
+
assertSettled(beforeFetch);
|
| 242 |
+
|
| 243 |
+
let headerSignal;
|
| 244 |
+
const headers = loadManager((_url, { signal }) => {
|
| 245 |
+
headerSignal = signal;
|
| 246 |
+
return new Promise((_resolve, reject) => {
|
| 247 |
+
// Some transports reject with AbortError even when given a custom reason.
|
| 248 |
+
signal.addEventListener(
|
| 249 |
+
"abort",
|
| 250 |
+
() => reject(new DOMException("transport aborted", "AbortError")),
|
| 251 |
+
{ once: true }
|
| 252 |
+
);
|
| 253 |
+
});
|
| 254 |
+
});
|
| 255 |
+
const headerRequests = [
|
| 256 |
+
headers.manager.request("headers", 25),
|
| 257 |
+
headers.manager.request("headers", 25)
|
| 258 |
+
];
|
| 259 |
+
await Promise.resolve();
|
| 260 |
+
stop(headers);
|
| 261 |
+
await Promise.all(
|
| 262 |
+
headerRequests.map((request) =>
|
| 263 |
+
assert.rejects(request, (error) => error === headerSignal.reason && error.name === name)
|
| 264 |
+
)
|
| 265 |
+
);
|
| 266 |
+
assertSettled(headers);
|
| 267 |
+
|
| 268 |
+
let finish, lateSignal, cancelledWith;
|
| 269 |
+
const delayedHeaders = loadManager((_url, { signal }) => {
|
| 270 |
+
lateSignal = signal;
|
| 271 |
+
return new Promise((resolve) => {
|
| 272 |
+
finish = resolve;
|
| 273 |
+
});
|
| 274 |
+
});
|
| 275 |
+
const delayedRequest = delayedHeaders.manager.request("late", 25);
|
| 276 |
+
await Promise.resolve();
|
| 277 |
+
stop(delayedHeaders);
|
| 278 |
+
finish(
|
| 279 |
+
new Response(
|
| 280 |
+
new ReadableStream({
|
| 281 |
+
cancel(reason) {
|
| 282 |
+
cancelledWith = reason;
|
| 283 |
+
}
|
| 284 |
+
})
|
| 285 |
+
)
|
| 286 |
+
);
|
| 287 |
+
await assert.rejects(
|
| 288 |
+
delayedRequest,
|
| 289 |
+
(error) => error === lateSignal.reason && error.name === name
|
| 290 |
+
);
|
| 291 |
+
assert.strictEqual(cancelledWith, lateSignal.reason);
|
| 292 |
+
assertSettled(delayedHeaders);
|
| 293 |
+
|
| 294 |
+
let bodySignal,
|
| 295 |
+
cancels = 0;
|
| 296 |
+
const bodies = loadManager((_url, { signal }) => {
|
| 297 |
+
bodySignal = signal;
|
| 298 |
+
return Promise.resolve(
|
| 299 |
+
new Response(
|
| 300 |
+
new ReadableStream({
|
| 301 |
+
cancel(reason) {
|
| 302 |
+
assert.strictEqual(reason, signal.reason);
|
| 303 |
+
assert.strictEqual(reason.name, name);
|
| 304 |
+
cancels++;
|
| 305 |
+
}
|
| 306 |
+
})
|
| 307 |
+
)
|
| 308 |
+
);
|
| 309 |
+
});
|
| 310 |
+
const responses = await Promise.all([
|
| 311 |
+
bodies.manager.request("clones", 25),
|
| 312 |
+
bodies.manager.request("clones", 25)
|
| 313 |
+
]);
|
| 314 |
+
assert.notStrictEqual(responses[0], responses[1]);
|
| 315 |
+
assert.strictEqual(bodies.manager.pendingCount, 0);
|
| 316 |
+
assert.strictEqual(bodies.manager.activeCount, 1);
|
| 317 |
+
const reads = responses.map((response) =>
|
| 318 |
+
assert.rejects(response.text(), (error) => error.name === name)
|
| 319 |
+
);
|
| 320 |
+
stop(bodies);
|
| 321 |
+
const firstReason = bodySignal.reason;
|
| 322 |
+
bodies.manager.dispose();
|
| 323 |
+
await Promise.all(reads);
|
| 324 |
+
assert.strictEqual(bodySignal.reason, firstReason);
|
| 325 |
+
assert.strictEqual(bodySignal.reason.name, name);
|
| 326 |
+
assert.strictEqual(cancels, 1);
|
| 327 |
+
assert.strictEqual(bodies.manager.activeCount, 0);
|
| 328 |
+
assert.strictEqual(bodies.timers.size, 0);
|
| 329 |
+
}
|
| 330 |
+
console.log("reader request manager contracts passed");
|
| 331 |
+
}
|
| 332 |
+
|
| 333 |
+
main().catch((error) => {
|
| 334 |
+
console.error(error);
|
| 335 |
+
process.exitCode = 1;
|
| 336 |
+
});
|
tests/test_reader_runtime.js
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
const assert = require("assert");
|
| 2 |
+
const fs = require("fs");
|
| 3 |
+
const path = require("path");
|
| 4 |
+
const vm = require("vm");
|
| 5 |
+
|
| 6 |
+
const sandbox = { self: {}, setTimeout, clearTimeout, requestAnimationFrame: (callback) => setTimeout(callback, 0), cancelAnimationFrame: clearTimeout };
|
| 7 |
+
sandbox.self = sandbox;
|
| 8 |
+
for (const file of ["reader-runtime.js", "reader-format-adapters.js"]) vm.runInNewContext(fs.readFileSync(path.join(__dirname, "../static", file), "utf8"), sandbox);
|
| 9 |
+
|
| 10 |
+
async function main() {
|
| 11 |
+
const events = [];
|
| 12 |
+
const runtime = sandbox.VoiceOfMLReaderRuntime.createReaderRuntime();
|
| 13 |
+
runtime.events.on("*", (_detail, type) => events.push(type));
|
| 14 |
+
assert.strictEqual(runtime.update("source", { url: "book" }), true);
|
| 15 |
+
assert.strictEqual(runtime.snapshot().source.url, "book");
|
| 16 |
+
let documentEvent;
|
| 17 |
+
runtime.events.on("state:document", (state) => { documentEvent = state; });
|
| 18 |
+
assert.strictEqual(runtime.update("document", { page: 7, restorationReady: true }), true);
|
| 19 |
+
assert.strictEqual(documentEvent.document.page, 7);
|
| 20 |
+
assert.strictEqual(documentEvent.document.restorationReady, true);
|
| 21 |
+
const delayed = runtime.schedule(() => { throw new Error("disposed timer fired"); }, 10000); runtime.cancel(delayed);
|
| 22 |
+
assert.strictEqual(runtime.updateFormat("pdf", { activeRenders: 1 }), true);
|
| 23 |
+
assert.strictEqual(runtime.snapshot().formats.pdf.activeRenders, 1);
|
| 24 |
+
const capability = runtime.negotiate({ mode: "pdf", extension: "pdf" });
|
| 25 |
+
assert.deepStrictEqual(JSON.parse(JSON.stringify(capability.features)), { toc: true, search: true, zoom: true, bookmarks: true, pagination: true, media: false });
|
| 26 |
+
const first = runtime.nextGeneration("navigation");
|
| 27 |
+
assert.strictEqual(runtime.currentGeneration("navigation"), first);
|
| 28 |
+
assert.strictEqual(runtime.isCurrent("navigation", first), true);
|
| 29 |
+
runtime.nextGeneration("navigation");
|
| 30 |
+
assert.strictEqual(runtime.isCurrent("navigation", first), false);
|
| 31 |
+
assert.strictEqual(runtime.currentGeneration("search"), 0);
|
| 32 |
+
const pdfGeneration = runtime.nextGeneration("pdf");
|
| 33 |
+
assert.strictEqual(runtime.currentGeneration("pdf"), pdfGeneration);
|
| 34 |
+
assert.strictEqual(runtime.currentGeneration("navigation"), first + 1);
|
| 35 |
+
assert.strictEqual(runtime.setStage("prepare"), true);
|
| 36 |
+
runtime.fail("READER_PARSE");
|
| 37 |
+
assert.strictEqual(runtime.state.lifecycle.phase, "failed");
|
| 38 |
+
assert.ok(events.includes("state:source") && events.includes("capability") && events.includes("generation") && events.includes("error"));
|
| 39 |
+
const calls = [];
|
| 40 |
+
runtime.track(() => calls.push("first")); runtime.track({ dispose: () => calls.push("second") }); runtime.dispose();
|
| 41 |
+
assert.deepStrictEqual(calls, ["second", "first"]); assert.strictEqual(runtime.state.lifecycle.phase, "disposed");
|
| 42 |
+
assert.strictEqual(runtime.currentGeneration("navigation"), first + 2);
|
| 43 |
+
assert.strictEqual(runtime.currentGeneration("pdf"), pdfGeneration + 1);
|
| 44 |
+
assert.strictEqual(runtime.update("source", { url: "late" }), false); assert.strictEqual(runtime.setPhase("ready"), false);
|
| 45 |
+
const registry = sandbox.VoiceOfMLReaderAdapters.createAdapterRegistry();
|
| 46 |
+
assert.throws(() => registry.register("bad", {}), /READER_ADAPTER_METHOD:bad:open/);
|
| 47 |
+
let finishOpen; const trace = [];
|
| 48 |
+
assert.deepStrictEqual(Array.from(sandbox.VoiceOfMLReaderAdapters.METHODS), ["open", "render", "restore", "dispose"]);
|
| 49 |
+
const adapter = registry.register("pdf", {
|
| 50 |
+
open: () => new Promise((resolve) => { finishOpen = () => { trace.push("open"); resolve("prepared"); }; }),
|
| 51 |
+
render: (value) => trace.push(`render:${value}`),
|
| 52 |
+
restore: (value) => trace.push(`restore:${value}`),
|
| 53 |
+
dispose: () => trace.push("dispose"),
|
| 54 |
+
});
|
| 55 |
+
assert.strictEqual(registry.activate("pdf"), adapter);
|
| 56 |
+
const opening = adapter.open();
|
| 57 |
+
adapter.restore("position");
|
| 58 |
+
finishOpen();
|
| 59 |
+
await adapter.render(await opening);
|
| 60 |
+
registry.dispose();
|
| 61 |
+
assert.deepStrictEqual(trace, ["restore:position", "open", "render:prepared", "dispose"]);
|
| 62 |
+
assert.throws(() => registry.register("pdf", adapter), /READER_ADAPTER_DUPLICATE/);
|
| 63 |
+
console.log("reader runtime contracts passed");
|
| 64 |
+
}
|
| 65 |
+
main().catch((error) => { console.error(error); process.exitCode = 1; });
|
tests/test_reader_scroll_anchor.js
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
const assert = require("assert");
|
| 2 |
+
const fs = require("fs");
|
| 3 |
+
const path = require("path");
|
| 4 |
+
const vm = require("vm");
|
| 5 |
+
|
| 6 |
+
function loadManager(options) {
|
| 7 |
+
const sandbox = { self: {} };
|
| 8 |
+
sandbox.self = sandbox;
|
| 9 |
+
vm.runInNewContext(fs.readFileSync(path.join(__dirname, "../static/reader-scroll-anchor.js"), "utf8"), sandbox);
|
| 10 |
+
return sandbox.VoiceOfMLReaderScroll.createScrollAnchorManager(options);
|
| 11 |
+
}
|
| 12 |
+
|
| 13 |
+
function main() {
|
| 14 |
+
const frames = new Map();
|
| 15 |
+
let nextFrame = 1, resizeCallback;
|
| 16 |
+
class ResizeObserverMock {
|
| 17 |
+
constructor(callback) { resizeCallback = callback; this.observed = new Set(); this.disconnected = false; }
|
| 18 |
+
observe(node) { this.observed.add(node); }
|
| 19 |
+
disconnect() { this.disconnected = true; this.observed.clear(); }
|
| 20 |
+
}
|
| 21 |
+
let idleCallback;
|
| 22 |
+
const listeners = new Map();
|
| 23 |
+
const viewport = { scrollTop: 200, getBoundingClientRect: () => ({ top: 0, bottom: 100 }), addEventListener: (name, callback) => listeners.set(name, callback), removeEventListener: (name) => listeners.delete(name) };
|
| 24 |
+
const article = { isConnected: true, top: 0, height: 400, getBoundingClientRect() { return { top: this.top - viewport.scrollTop, bottom: this.top - viewport.scrollTop + this.height, height: this.height }; } };
|
| 25 |
+
const paragraph = { isConnected: true, top: 210, height: 30, getBoundingClientRect() { return { top: this.top - viewport.scrollTop, bottom: this.top - viewport.scrollTop + this.height, height: this.height }; } };
|
| 26 |
+
const manager = loadManager({ viewport, candidates: () => [article, paragraph], ResizeObserverImpl: ResizeObserverMock, requestFrame: (callback) => { const id = nextFrame++; frames.set(id, callback); return id; }, cancelFrame: (id) => frames.delete(id), setTimer: (callback) => { idleCallback = callback; return 1; }, clearTimer: () => { idleCallback = null; } });
|
| 27 |
+
|
| 28 |
+
const anchor = manager.capture();
|
| 29 |
+
assert.strictEqual(anchor.node, paragraph);
|
| 30 |
+
assert.strictEqual(anchor.offset, 10);
|
| 31 |
+
paragraph.top += 50;
|
| 32 |
+
assert.strictEqual(manager.restore(anchor), true);
|
| 33 |
+
assert.strictEqual(viewport.scrollTop, 250);
|
| 34 |
+
assert.strictEqual(paragraph.getBoundingClientRect().top, 10);
|
| 35 |
+
|
| 36 |
+
manager.observe(article);
|
| 37 |
+
manager.capture();
|
| 38 |
+
paragraph.top += 40;
|
| 39 |
+
resizeCallback();
|
| 40 |
+
assert.strictEqual(frames.size, 0);
|
| 41 |
+
assert.strictEqual(viewport.scrollTop, 290);
|
| 42 |
+
|
| 43 |
+
listeners.get("wheel")();
|
| 44 |
+
listeners.get("scroll")();
|
| 45 |
+
assert.strictEqual(manager.scrolling, true);
|
| 46 |
+
paragraph.top += 60;
|
| 47 |
+
resizeCallback();
|
| 48 |
+
assert.strictEqual(viewport.scrollTop, 290);
|
| 49 |
+
let idleRuns = 0;
|
| 50 |
+
manager.whenIdle(() => { idleRuns += 1; });
|
| 51 |
+
assert.strictEqual(idleRuns, 0);
|
| 52 |
+
idleCallback();
|
| 53 |
+
assert.strictEqual(manager.scrolling, false);
|
| 54 |
+
assert.strictEqual(idleRuns, 1);
|
| 55 |
+
|
| 56 |
+
manager.preserve(() => { paragraph.top += 25; });
|
| 57 |
+
assert.strictEqual(viewport.scrollTop, 315);
|
| 58 |
+
manager.remember();
|
| 59 |
+
assert.strictEqual(frames.size, 1);
|
| 60 |
+
manager.invalidate();
|
| 61 |
+
assert.strictEqual(frames.size, 0);
|
| 62 |
+
assert.strictEqual(manager.restore(anchor), false);
|
| 63 |
+
manager.dispose();
|
| 64 |
+
assert.strictEqual(frames.size, 0);
|
| 65 |
+
paragraph.top += 100;
|
| 66 |
+
assert.strictEqual(manager.restore(anchor), false);
|
| 67 |
+
console.log("reader scroll anchor contracts passed");
|
| 68 |
+
}
|
| 69 |
+
|
| 70 |
+
main();
|
tests/test_reader_section_virtualizer.js
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
const assert = require("assert");
|
| 2 |
+
const fs = require("fs");
|
| 3 |
+
const path = require("path");
|
| 4 |
+
const vm = require("vm");
|
| 5 |
+
|
| 6 |
+
function loadVirtualizer(options) {
|
| 7 |
+
const sandbox = { self: {} };
|
| 8 |
+
sandbox.self = sandbox;
|
| 9 |
+
vm.runInNewContext(fs.readFileSync(path.join(__dirname, "../static/reader-section-virtualizer.js"), "utf8"), sandbox);
|
| 10 |
+
return sandbox.VoiceOfMLReaderVirtual.createSectionVirtualizer(options);
|
| 11 |
+
}
|
| 12 |
+
|
| 13 |
+
function main() {
|
| 14 |
+
const nodes = Array.from({ length: 12 }, (_, index) => ({ index, height: 100 + index }));
|
| 15 |
+
const removed = [];
|
| 16 |
+
let preserveCalls = 0;
|
| 17 |
+
const virtualizer = loadVirtualizer({ limit: 9, getLoaded: () => nodes.filter((node) => !removed.includes(node.index)), getIndex: (node) => node.index, getHeight: (node) => node.height, virtualize: (node, index, height) => removed.push(index) && { node, height }, release: () => {}, preserve: (change) => { preserveCalls += 1; return change(); } });
|
| 18 |
+
const result = virtualizer.trim(6);
|
| 19 |
+
assert.strictEqual(result.removed, 3);
|
| 20 |
+
assert.strictEqual(result.retained, 9);
|
| 21 |
+
assert.strictEqual(removed.includes(6), false);
|
| 22 |
+
assert.strictEqual(preserveCalls, 1);
|
| 23 |
+
assert.strictEqual(virtualizer.trim(6).removed, 0);
|
| 24 |
+
const protectedNodes = Array.from({ length: 12 }, (_, index) => ({ index, height: 100 }));
|
| 25 |
+
const protectedRemoved = [];
|
| 26 |
+
const protectedVirtualizer = loadVirtualizer({ limit: 9, getLoaded: () => protectedNodes.filter((node) => !protectedRemoved.includes(node.index)), getIndex: (node) => node.index, getHeight: (node) => node.height, canVirtualize: (node) => node.index < 2, virtualize: (_node, index) => protectedRemoved.push(index), release: () => {} });
|
| 27 |
+
const protectedResult = protectedVirtualizer.trim(6);
|
| 28 |
+
assert.strictEqual(protectedResult.removed, 2);
|
| 29 |
+
assert.deepStrictEqual(protectedRemoved, [0, 1]);
|
| 30 |
+
assert.strictEqual(protectedResult.retained, 10);
|
| 31 |
+
virtualizer.dispose();
|
| 32 |
+
assert.strictEqual(virtualizer.trim(0).removed, 0);
|
| 33 |
+
console.log("reader section virtualizer contracts passed");
|
| 34 |
+
}
|
| 35 |
+
|
| 36 |
+
main();
|
tests/test_reader_security.js
ADDED
|
@@ -0,0 +1,189 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
const assert = require("assert");
|
| 2 |
+
const fs = require("fs");
|
| 3 |
+
const path = require("path");
|
| 4 |
+
const vm = require("vm");
|
| 5 |
+
const { deflateRawSync } = require("zlib");
|
| 6 |
+
const sandbox = { self: {}, TextDecoder, Uint8Array, DataView };
|
| 7 |
+
sandbox.self = sandbox;
|
| 8 |
+
vm.runInNewContext(fs.readFileSync(path.join(__dirname, "../static/reader-security.js"), "utf8"), sandbox);
|
| 9 |
+
const security = sandbox.VoiceOfMLReaderSecurity;
|
| 10 |
+
|
| 11 |
+
function crc32(bytes) {
|
| 12 |
+
let crc = 0xffffffff;
|
| 13 |
+
for (const byte of bytes) {
|
| 14 |
+
crc ^= byte;
|
| 15 |
+
for (let bit = 0; bit < 8; bit++) crc = (crc >>> 1) ^ ((crc & 1) ? 0xedb88320 : 0);
|
| 16 |
+
}
|
| 17 |
+
return (crc ^ 0xffffffff) >>> 0;
|
| 18 |
+
}
|
| 19 |
+
|
| 20 |
+
function zip(entries, comment = Buffer.alloc(0)) {
|
| 21 |
+
const locals = [], directory = [];
|
| 22 |
+
let position = 0;
|
| 23 |
+
for (const { name, data, deflate = false, descriptor = false, extra = Buffer.alloc(0) } of entries) {
|
| 24 |
+
const filename = Buffer.from(name), packed = deflate ? deflateRawSync(data) : data;
|
| 25 |
+
const crc = crc32(data), method = deflate ? 8 : 0, flags = descriptor ? 8 : 0;
|
| 26 |
+
const local = Buffer.alloc(30);
|
| 27 |
+
local.writeUInt32LE(0x04034b50);
|
| 28 |
+
local.writeUInt16LE(20, 4);
|
| 29 |
+
local.writeUInt16LE(flags, 6);
|
| 30 |
+
local.writeUInt16LE(method, 8);
|
| 31 |
+
if (!descriptor) {
|
| 32 |
+
local.writeUInt32LE(crc, 14);
|
| 33 |
+
local.writeUInt32LE(packed.length, 18);
|
| 34 |
+
local.writeUInt32LE(data.length, 22);
|
| 35 |
+
}
|
| 36 |
+
local.writeUInt16LE(filename.length, 26);
|
| 37 |
+
const central = Buffer.alloc(46);
|
| 38 |
+
central.writeUInt32LE(0x02014b50);
|
| 39 |
+
central.writeUInt16LE(20, 4);
|
| 40 |
+
central.writeUInt16LE(20, 6);
|
| 41 |
+
central.writeUInt16LE(flags, 8);
|
| 42 |
+
central.writeUInt16LE(method, 10);
|
| 43 |
+
central.writeUInt32LE(crc, 16);
|
| 44 |
+
central.writeUInt32LE(packed.length, 20);
|
| 45 |
+
central.writeUInt32LE(data.length, 24);
|
| 46 |
+
central.writeUInt16LE(filename.length, 28);
|
| 47 |
+
central.writeUInt16LE(extra.length, 30);
|
| 48 |
+
central.writeUInt32LE(position, 42);
|
| 49 |
+
const trailer = Buffer.alloc(descriptor ? 16 : 0);
|
| 50 |
+
if (descriptor) {
|
| 51 |
+
trailer.writeUInt32LE(0x08074b50);
|
| 52 |
+
trailer.writeUInt32LE(crc, 4);
|
| 53 |
+
trailer.writeUInt32LE(packed.length, 8);
|
| 54 |
+
trailer.writeUInt32LE(data.length, 12);
|
| 55 |
+
}
|
| 56 |
+
locals.push(local, filename, packed, trailer);
|
| 57 |
+
directory.push(central, filename, extra);
|
| 58 |
+
position += local.length + filename.length + packed.length + trailer.length;
|
| 59 |
+
}
|
| 60 |
+
const central = Buffer.concat(directory), end = Buffer.alloc(22);
|
| 61 |
+
end.writeUInt32LE(0x06054b50);
|
| 62 |
+
end.writeUInt16LE(entries.length, 8);
|
| 63 |
+
end.writeUInt16LE(entries.length, 10);
|
| 64 |
+
end.writeUInt32LE(central.length, 12);
|
| 65 |
+
end.writeUInt32LE(position, 16);
|
| 66 |
+
end.writeUInt16LE(comment.length, 20);
|
| 67 |
+
return { bytes: Buffer.concat([...locals, central, end, comment]), directory: position, end: position + central.length };
|
| 68 |
+
}
|
| 69 |
+
|
| 70 |
+
function streamResponse(chunks, header = null) {
|
| 71 |
+
const state = { reads: 0, cancels: 0, released: false };
|
| 72 |
+
const response = {
|
| 73 |
+
headers: { get: () => header },
|
| 74 |
+
body: {
|
| 75 |
+
cancel: async () => { state.cancels++; },
|
| 76 |
+
getReader: () => ({
|
| 77 |
+
read: async () => {
|
| 78 |
+
const value = chunks[state.reads++];
|
| 79 |
+
return value === undefined ? { done: true } : { value, done: false };
|
| 80 |
+
},
|
| 81 |
+
cancel: async () => { state.cancels++; },
|
| 82 |
+
releaseLock: () => { state.released = true; },
|
| 83 |
+
}),
|
| 84 |
+
},
|
| 85 |
+
};
|
| 86 |
+
return { response, state };
|
| 87 |
+
}
|
| 88 |
+
|
| 89 |
+
async function main() {
|
| 90 |
+
const valid = zip([{ name: "chapter.xhtml", data: Buffer.from("Readable chapter"), deflate: true, descriptor: true }], Buffer.from("ZIP comment PK\x05\x06"));
|
| 91 |
+
assert.strictEqual(security.inspectZip(valid.bytes).entries, 1);
|
| 92 |
+
assert.strictEqual(security.inspectZip(valid.bytes).compressed, deflateRawSync(Buffer.from("Readable chapter")).length);
|
| 93 |
+
assert.strictEqual(security.inspectZip(valid.bytes).expanded, 16);
|
| 94 |
+
assert.strictEqual(security.isZipContainer("mobi", valid.bytes), true);
|
| 95 |
+
assert.strictEqual(security.isZipContainer("FBZ"), true);
|
| 96 |
+
assert.strictEqual(security.isZipContainer("mobi", new Uint8Array(4)), false);
|
| 97 |
+
assert.strictEqual(security.isZipContainer("mobi"), false);
|
| 98 |
+
|
| 99 |
+
// This stored member previously redirected the scanner past the real directory.
|
| 100 |
+
const decoy = Buffer.alloc(46);
|
| 101 |
+
decoy.writeUInt32LE(0x02014b50);
|
| 102 |
+
decoy.writeUInt32LE(100, 20);
|
| 103 |
+
decoy.writeUInt32LE(100, 24);
|
| 104 |
+
decoy.writeUInt16LE(65535, 28);
|
| 105 |
+
const bomb = zip([
|
| 106 |
+
{ name: "decoy.bin", data: decoy },
|
| 107 |
+
{ name: "chapter.xhtml", data: Buffer.alloc(1024 * 1024, 65), deflate: true },
|
| 108 |
+
]);
|
| 109 |
+
assert.throws(() => security.inspectZip(bomb.bytes), /READER_ARCHIVE_LIMIT/);
|
| 110 |
+
decoy.writeUInt32LE(0xffffffff, 24);
|
| 111 |
+
const harmless = zip([{ name: "decoy.bin", data: decoy }]);
|
| 112 |
+
assert.strictEqual(security.inspectZip(harmless.bytes).expanded, decoy.length);
|
| 113 |
+
assert.throws(() => security.inspectZip(decoy), /READER_ARCHIVE_INVALID/);
|
| 114 |
+
assert.throws(() => security.inspectZip(valid.bytes.subarray(0, valid.end + 10)), /READER_ARCHIVE_INVALID/);
|
| 115 |
+
assert.throws(() => security.inspectZip(new Uint8Array(3)), /READER_ARCHIVE_INVALID/);
|
| 116 |
+
assert.throws(() => security.inspectZip(valid.bytes, { ...security.LIMITS, archiveCompressedBytes: 1 }), /READER_ARCHIVE_LIMIT/);
|
| 117 |
+
assert.throws(() => security.inspectZip(valid.bytes, { ...security.LIMITS, archiveExpandedBytes: 1 }), /READER_ARCHIVE_LIMIT/);
|
| 118 |
+
assert.throws(() => security.inspectZip(valid.bytes, { ...security.LIMITS, archiveEntries: 0 }), /READER_ARCHIVE_LIMIT/);
|
| 119 |
+
|
| 120 |
+
for (const [mutate, expected] of [
|
| 121 |
+
[(b) => b.writeUInt32LE(valid.directory + 1, valid.end + 16), /READER_ARCHIVE_INVALID/],
|
| 122 |
+
[(b) => { b.writeUInt16LE(2, valid.end + 8); b.writeUInt16LE(2, valid.end + 10); }, /READER_ARCHIVE_INVALID/],
|
| 123 |
+
[(b) => b.writeUInt16LE(65535, valid.directory + 28), /READER_ARCHIVE_INVALID/],
|
| 124 |
+
[(b) => b.writeUInt32LE(valid.directory, valid.directory + 42), /READER_ARCHIVE_INVALID/],
|
| 125 |
+
[(b) => b.writeUInt32LE(0, 0), /READER_ARCHIVE_INVALID/],
|
| 126 |
+
[(b) => b.writeUInt16LE(1, valid.end + 4), /READER_ARCHIVE_MULTIDISK_UNSUPPORTED/],
|
| 127 |
+
[(b) => b.writeUInt16LE(1, valid.directory + 34), /READER_ARCHIVE_MULTIDISK_UNSUPPORTED/],
|
| 128 |
+
[(b) => b.writeUInt16LE(0xffff, valid.end + 10), /READER_ARCHIVE_ZIP64_UNSUPPORTED/],
|
| 129 |
+
[(b) => b.writeUInt32LE(0xffffffff, valid.directory + 24), /READER_ARCHIVE_ZIP64_UNSUPPORTED/],
|
| 130 |
+
]) {
|
| 131 |
+
const bytes = Buffer.from(valid.bytes);
|
| 132 |
+
mutate(bytes);
|
| 133 |
+
assert.throws(() => security.inspectZip(bytes), expected);
|
| 134 |
+
}
|
| 135 |
+
const zip64Extra = zip([{ name: "a", data: Buffer.from("a"), extra: Buffer.from([1, 0, 0, 0]) }]);
|
| 136 |
+
assert.throws(() => security.inspectZip(zip64Extra.bytes), /READER_ARCHIVE_ZIP64_UNSUPPORTED/);
|
| 137 |
+
|
| 138 |
+
const chapterManifest = { version: 1, kind: "epub-chapters", chapters: [{ index: 1, path: "chapter.xhtml", bytes: 10 }] };
|
| 139 |
+
security.validateChapterManifest(chapterManifest);
|
| 140 |
+
for (const [chapter, expected] of [
|
| 141 |
+
[{ index: 1, path: "chapter.xhtml", bytes: security.LIMITS.chapterBytes + 1 }, /READER_RESOURCE_LIMIT/],
|
| 142 |
+
[{ index: 2, path: "chapter.xhtml" }, /EPUB_INVALID/],
|
| 143 |
+
[{ index: 1, path: "../escape.xhtml" }, /EPUB_INVALID/],
|
| 144 |
+
]) assert.throws(() => security.validateChapterManifest({ ...chapterManifest, chapters: [chapter] }), expected);
|
| 145 |
+
const validTocManifest = { version: 2, kind: "pdf-pages", page_count: 1, toc: [{ title: "Chapter 1", page: 1, depth: 0 }] };
|
| 146 |
+
security.validatePdfPageManifest(validTocManifest);
|
| 147 |
+
security.validatePdfPageManifest({ version: 2, kind: "pdf-pages", page_count: 100, toc: [{ title: "Chapter 1", page: 100, depth: 0 }] });
|
| 148 |
+
assert.throws(() => security.validatePdfPageManifest({ version: 2, kind: "pdf-pages", page_count: 0 }), /PDF_MANIFEST_INVALID/);
|
| 149 |
+
assert.throws(() => security.validatePdfPageManifest({ version: 2, kind: "pdf-pages", page_count: 1, pages: [] }), /PDF_MANIFEST_INVALID/);
|
| 150 |
+
assert.throws(() => security.validatePdfPageManifest({ ...validTocManifest, toc: [{ title: "bad", page: 2, depth: 0 }] }), /PDF_MANIFEST_INVALID/);
|
| 151 |
+
assert.throws(() => security.validatePdfPageManifest({ ...validTocManifest, pages: [] }), /PDF_MANIFEST_INVALID/);
|
| 152 |
+
assert.throws(() => security.validatePdfPageManifest({ version: 1, kind: "pdf-pages", pages: [{ page: 1, path: "pages/page-000001.webp" }] }), /PDF_MANIFEST_INVALID/);
|
| 153 |
+
|
| 154 |
+
const oversized = streamResponse([], "9");
|
| 155 |
+
assert.throws(() => security.assertResponseSize(oversized.response, 8), /READER_RESOURCE_LIMIT/);
|
| 156 |
+
await assert.rejects(security.readBytes(oversized.response, 8), /READER_RESOURCE_LIMIT/);
|
| 157 |
+
assert.strictEqual(oversized.state.reads, 0);
|
| 158 |
+
assert.strictEqual(oversized.state.cancels, 1);
|
| 159 |
+
oversized.response.body.cancel = async () => { throw new Error("cancel failed"); };
|
| 160 |
+
await assert.rejects(security.readBytes(oversized.response, 8), /READER_RESOURCE_LIMIT/);
|
| 161 |
+
const overflow = streamResponse([new Uint8Array(5), new Uint8Array(5), new Uint8Array(5)]);
|
| 162 |
+
await assert.rejects(security.readBytes(overflow.response, 8), /READER_RESOURCE_LIMIT/);
|
| 163 |
+
assert.deepStrictEqual(overflow.state, { reads: 2, cancels: 1, released: true });
|
| 164 |
+
assert.strictEqual(await security.readText(streamResponse([Buffer.from("text")]).response, 4), "text");
|
| 165 |
+
|
| 166 |
+
const budget = security.createByteBudget(8);
|
| 167 |
+
const first = streamResponse([new Uint8Array(3), new Uint8Array(3)]);
|
| 168 |
+
const second = streamResponse([new Uint8Array(3), new Uint8Array(3)]);
|
| 169 |
+
const results = await Promise.allSettled([security.readBytes(first.response, 8, budget), security.readBytes(second.response, 8, budget)]);
|
| 170 |
+
assert.strictEqual(results.filter((result) => result.status === "fulfilled").length, 1);
|
| 171 |
+
assert.strictEqual(results.find((result) => result.status === "rejected").reason.code, "READER_RESOURCE_LIMIT");
|
| 172 |
+
assert.strictEqual(budget.used, 6);
|
| 173 |
+
assert.strictEqual(budget.remaining, 2);
|
| 174 |
+
assert.strictEqual(first.state.cancels + second.state.cancels, 1);
|
| 175 |
+
budget.release(6);
|
| 176 |
+
assert.strictEqual(await security.readText(streamResponse([Buffer.from("retry")]).response, 8, "utf-8", budget), "retry");
|
| 177 |
+
assert.strictEqual(budget.used, 5);
|
| 178 |
+
const failed = streamResponse([new Uint8Array(2), new Uint8Array(9)]);
|
| 179 |
+
await assert.rejects(security.readBytes(failed.response, 8, budget), /READER_RESOURCE_LIMIT/);
|
| 180 |
+
assert.strictEqual(budget.used, 5);
|
| 181 |
+
await assert.rejects(security.readBytes({ headers: { get: () => null }, arrayBuffer: async () => new ArrayBuffer(4) }, 8, budget), /READER_RESOURCE_LIMIT/);
|
| 182 |
+
assert.strictEqual(budget.used, 5);
|
| 183 |
+
assert.throws(() => budget.release(6), /Invalid byte release/);
|
| 184 |
+
assert.throws(() => budget.reserve(-1), /Invalid byte count/);
|
| 185 |
+
assert.throws(() => security.createByteBudget(-1), /Invalid byte budget/);
|
| 186 |
+
console.log("reader security contracts passed");
|
| 187 |
+
}
|
| 188 |
+
|
| 189 |
+
main().catch((error) => { console.error(error); process.exitCode = 1; });
|
tests/test_reader_store_channel.js
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
const assert = require("assert");
|
| 2 |
+
const fs = require("fs");
|
| 3 |
+
const vm = require("vm");
|
| 4 |
+
const source = fs.readFileSync("static/reader-store.js", "utf8"), channels = new Set();
|
| 5 |
+
class BroadcastChannel { constructor(name) { this.name = name; this.closed = false; channels.add(this); } postMessage(data) { for (const channel of channels) if (channel !== this && !channel.closed && channel.name === this.name) channel.onmessage?.({ data }); } close() { this.closed = true; channels.delete(this); } }
|
| 6 |
+
function loadStore() { const sandbox = { self: {}, BroadcastChannel }; sandbox.self = sandbox; vm.runInNewContext(source, sandbox); return sandbox.VoiceOfMLReaderStore; }
|
| 7 |
+
const first = loadStore(), second = loadStore(), received = []; second.subscribe((change) => received.push(change)); const sender = new BroadcastChannel("voiceofml-reader-store-v1"); sender.postMessage({ type: "bookmark", url: "book", id: "one" }); assert.deepStrictEqual(JSON.parse(JSON.stringify(received)), [{ type: "bookmark", url: "book", id: "one", remote: true }]); second.dispose(); sender.postMessage({ type: "history", url: "book" }); assert.strictEqual(received.length, 1); first.dispose(); sender.close(); console.log("reader store channel contracts passed");
|
tests/test_reader_style.py
ADDED
|
@@ -0,0 +1,281 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Focused browser checks for reader CSS, independent of format-engine suites."""
|
| 2 |
+
|
| 3 |
+
import io
|
| 4 |
+
import unittest
|
| 5 |
+
import urllib.parse
|
| 6 |
+
import zipfile
|
| 7 |
+
|
| 8 |
+
from tests.test_reader_performance import (
|
| 9 |
+
STORE_SCRIPT,
|
| 10 |
+
PlaywrightError,
|
| 11 |
+
epub_with_navigation,
|
| 12 |
+
static_server,
|
| 13 |
+
sync_playwright,
|
| 14 |
+
zip_bytes,
|
| 15 |
+
)
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
@unittest.skipIf(sync_playwright is None, "install requirements-test.txt for reader style tests")
|
| 19 |
+
class ReaderStyleTests(unittest.TestCase):
|
| 20 |
+
@classmethod
|
| 21 |
+
def setUpClass(cls):
|
| 22 |
+
cls.server = static_server()
|
| 23 |
+
cls.origin = cls.server.__enter__()
|
| 24 |
+
cls.addClassCleanup(cls.server.__exit__, None, None, None)
|
| 25 |
+
cls.playwright = sync_playwright().start()
|
| 26 |
+
cls.addClassCleanup(cls.playwright.stop)
|
| 27 |
+
try:
|
| 28 |
+
cls.browser = cls.playwright.chromium.launch(headless=True)
|
| 29 |
+
except PlaywrightError as error:
|
| 30 |
+
raise unittest.SkipTest(str(error))
|
| 31 |
+
cls.addClassCleanup(cls.browser.close)
|
| 32 |
+
|
| 33 |
+
def setUp(self):
|
| 34 |
+
context = self.browser.new_context(viewport={"width": 1440, "height": 900})
|
| 35 |
+
self.addCleanup(context.close)
|
| 36 |
+
self.page = context.new_page()
|
| 37 |
+
self.page.add_init_script("localStorage.setItem('theme', 'dark')")
|
| 38 |
+
self.page.route("**/static/reader-store.js", lambda route: route.fulfill(
|
| 39 |
+
content_type="text/javascript", body=STORE_SCRIPT
|
| 40 |
+
))
|
| 41 |
+
self.page.route("**/api/reader-content**", lambda route: route.fulfill(
|
| 42 |
+
content_type="text/plain", body="Reader style fixture\n" * 80
|
| 43 |
+
))
|
| 44 |
+
source = urllib.parse.quote(
|
| 45 |
+
"https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/style.txt", safe=""
|
| 46 |
+
)
|
| 47 |
+
self.page.goto(
|
| 48 |
+
f"{self.origin}/static/reader.html?url={source}&ext=txt&title=Style&path=Test",
|
| 49 |
+
wait_until="domcontentloaded",
|
| 50 |
+
)
|
| 51 |
+
self.page.wait_for_function("() => document.documentElement.dataset.readerPhase === 'ready'")
|
| 52 |
+
|
| 53 |
+
def settle(self):
|
| 54 |
+
self.page.wait_for_function("""() =>
|
| 55 |
+
!document.documentElement.classList.contains('theme-transition') &&
|
| 56 |
+
!document.getAnimations().some(animation => animation.playState === 'running')
|
| 57 |
+
""")
|
| 58 |
+
|
| 59 |
+
def assert_contrast(self, selector):
|
| 60 |
+
result = self.page.locator(selector).first.evaluate("""element => {
|
| 61 |
+
const rgb = value => value.match(/[\\d.]+/g).map(Number);
|
| 62 |
+
const luminance = color => rgb(color).slice(0, 3).reduce((sum, value, index) => {
|
| 63 |
+
const channel = value / 255;
|
| 64 |
+
return sum + [0.2126, 0.7152, 0.0722][index] *
|
| 65 |
+
(channel <= 0.04045 ? channel / 12.92 : ((channel + 0.055) / 1.055) ** 2.4);
|
| 66 |
+
}, 0);
|
| 67 |
+
const foreground = getComputedStyle(element).color;
|
| 68 |
+
let background = getComputedStyle(element).backgroundColor;
|
| 69 |
+
for (let parent = element.parentElement; rgb(background)[3] === 0 && parent;
|
| 70 |
+
parent = parent.parentElement) background = getComputedStyle(parent).backgroundColor;
|
| 71 |
+
const a = luminance(foreground), b = luminance(background);
|
| 72 |
+
return {foreground, background, ratio: (Math.max(a, b) + 0.05) / (Math.min(a, b) + 0.05)};
|
| 73 |
+
}""")
|
| 74 |
+
self.assertGreaterEqual(result["ratio"], 4.5, (selector, result))
|
| 75 |
+
|
| 76 |
+
def test_light_contrast_after_theme_transition(self):
|
| 77 |
+
self.page.locator("#history").click()
|
| 78 |
+
self.page.locator("#theme-toggle").click()
|
| 79 |
+
self.settle()
|
| 80 |
+
self.page.locator("#full-search-toggle").click()
|
| 81 |
+
self.page.locator("#full-search-input").fill("Reader")
|
| 82 |
+
self.page.locator(".full-search-result").first.wait_for()
|
| 83 |
+
for selector in ("#full-search-input", ".full-search-status", ".full-search-location",
|
| 84 |
+
".full-search-snippet", "#full-search-toggle", "#reader-path"):
|
| 85 |
+
self.assert_contrast(selector)
|
| 86 |
+
self.page.locator("#reader-path").hover()
|
| 87 |
+
self.assert_contrast("#reader-path")
|
| 88 |
+
# Exercise document surfaces without loading external conversion engines.
|
| 89 |
+
self.page.locator("#content").evaluate("""content => content.insertAdjacentHTML('beforeend', `
|
| 90 |
+
<div class="reader-error">Failed to load</div>
|
| 91 |
+
<div class="epub-frame"><article class="reader-markdown">Chapter text</article></div>
|
| 92 |
+
<article class="reader-markdown"><a href="#test">Document link</a></article>`)
|
| 93 |
+
""")
|
| 94 |
+
for selector in (".reader-error", ".epub-frame .reader-markdown", ".reader-markdown a"):
|
| 95 |
+
self.assert_contrast(selector)
|
| 96 |
+
|
| 97 |
+
def test_numeric_controls_have_visible_keyboard_focus_in_both_themes(self):
|
| 98 |
+
self.page.locator(".page-controls").evaluate("element => element.hidden = false")
|
| 99 |
+
for theme in ("dark", "light"):
|
| 100 |
+
self.page.locator("html").evaluate("(element, theme) => element.dataset.theme = theme", theme)
|
| 101 |
+
self.page.keyboard.press("Tab")
|
| 102 |
+
for selector in ("#page-number", "#zoom"):
|
| 103 |
+
control = self.page.locator(selector)
|
| 104 |
+
control.focus()
|
| 105 |
+
style = control.evaluate("""element => ({
|
| 106 |
+
visible: element.matches(':focus-visible'),
|
| 107 |
+
width: parseFloat(getComputedStyle(element).outlineWidth),
|
| 108 |
+
style: getComputedStyle(element).outlineStyle
|
| 109 |
+
})""")
|
| 110 |
+
self.assertTrue(style["visible"])
|
| 111 |
+
self.assertGreaterEqual(style["width"], 2)
|
| 112 |
+
self.assertEqual(style["style"], "solid")
|
| 113 |
+
|
| 114 |
+
def test_short_dialog_scrolls_to_actions_and_retains_editor_grid(self):
|
| 115 |
+
self.page.set_viewport_size({"width": 390, "height": 240})
|
| 116 |
+
self.page.locator("#bookmark-ribbon").click()
|
| 117 |
+
dialog = self.page.locator("#bookmark-popover")
|
| 118 |
+
self.page.locator("#bookmark-excerpt-input").evaluate("element => element.style.height = '500px'")
|
| 119 |
+
metrics = dialog.evaluate("""element => ({
|
| 120 |
+
bottom: element.getBoundingClientRect().bottom,
|
| 121 |
+
overflow: getComputedStyle(element).overflowY,
|
| 122 |
+
scrollable: element.scrollHeight > element.clientHeight,
|
| 123 |
+
editor: getComputedStyle(element.querySelector('.bookmark-edit-fields')).display
|
| 124 |
+
})""")
|
| 125 |
+
self.assertLessEqual(metrics["bottom"], 230)
|
| 126 |
+
self.assertEqual(metrics["overflow"], "auto")
|
| 127 |
+
self.assertTrue(metrics["scrollable"])
|
| 128 |
+
self.assertEqual(metrics["editor"], "grid")
|
| 129 |
+
cancel = self.page.locator("#bookmark-cancel")
|
| 130 |
+
cancel.scroll_into_view_if_needed()
|
| 131 |
+
rect = cancel.bounding_box()
|
| 132 |
+
self.assertGreaterEqual(rect["y"], 78)
|
| 133 |
+
self.assertLessEqual(rect["y"] + rect["height"], 230)
|
| 134 |
+
cancel.click()
|
| 135 |
+
self.assertTrue(dialog.is_hidden())
|
| 136 |
+
|
| 137 |
+
def test_foliate_and_video_follow_toolbar_across_breakpoint_and_resize(self):
|
| 138 |
+
for width, height in ((390, 844), (390, 360), (600, 500), (601, 500), (1440, 900)):
|
| 139 |
+
with self.subTest(width=width, height=height):
|
| 140 |
+
self.page.set_viewport_size({"width": width, "height": height})
|
| 141 |
+
for mode in ("foliate", "video"):
|
| 142 |
+
metrics = self.page.locator("#content").evaluate("""(content, mode) => {
|
| 143 |
+
content.dataset.mode = mode;
|
| 144 |
+
content.innerHTML = mode === 'video' ? '<video class="reader-video"></video>' : '';
|
| 145 |
+
const toolbar = document.querySelector('.reader-toolbar').getBoundingClientRect();
|
| 146 |
+
const style = getComputedStyle(content);
|
| 147 |
+
return {toolbar: toolbar.height, height: parseFloat(style.height),
|
| 148 |
+
minHeight: parseFloat(style.minHeight), padding: style.padding,
|
| 149 |
+
video: content.firstChild?.getBoundingClientRect().height};
|
| 150 |
+
}""", mode)
|
| 151 |
+
expected_toolbar = 36 if width <= 600 else 44
|
| 152 |
+
self.assertEqual(metrics["toolbar"], expected_toolbar)
|
| 153 |
+
self.assertAlmostEqual(metrics["height"], height - expected_toolbar, delta=1)
|
| 154 |
+
self.assertEqual(metrics["padding"], "0px")
|
| 155 |
+
if mode == "foliate":
|
| 156 |
+
self.assertAlmostEqual(metrics["minHeight"], height - expected_toolbar, delta=1)
|
| 157 |
+
else:
|
| 158 |
+
self.assertAlmostEqual(metrics["video"], height - expected_toolbar, delta=1)
|
| 159 |
+
|
| 160 |
+
def test_theme_transition_preserves_drawer_and_filter_motion(self):
|
| 161 |
+
self.page.locator("#history").click()
|
| 162 |
+
self.page.locator("#bookmarks-tab").click()
|
| 163 |
+
self.page.locator("#bookmarks-panel .panel-search-toggle").click()
|
| 164 |
+
self.settle()
|
| 165 |
+
transitions = self.page.evaluate("""() => {
|
| 166 |
+
document.documentElement.classList.add('theme-transition');
|
| 167 |
+
document.documentElement.dataset.theme = 'light';
|
| 168 |
+
return ['#history-panel', '#bookmarks-panel .panel-search'].map(selector => {
|
| 169 |
+
const style = getComputedStyle(document.querySelector(selector));
|
| 170 |
+
return style.transitionProperty.split(',').map(value => value.trim());
|
| 171 |
+
});
|
| 172 |
+
}""")
|
| 173 |
+
for properties in transitions:
|
| 174 |
+
self.assertIn("transform", properties)
|
| 175 |
+
self.assertIn("opacity", properties)
|
| 176 |
+
self.assertIn("background-color", properties)
|
| 177 |
+
self.assertIn("visibility", transitions[0])
|
| 178 |
+
self.assertIn("max-height", transitions[1])
|
| 179 |
+
delay = self.page.locator("#history-panel").evaluate("""element => {
|
| 180 |
+
element.classList.remove('is-open');
|
| 181 |
+
const style = getComputedStyle(element);
|
| 182 |
+
return style.transitionDelay.split(',')[style.transitionProperty.split(',')
|
| 183 |
+
.findIndex(value => value.trim() === 'visibility')].trim();
|
| 184 |
+
}""")
|
| 185 |
+
self.assertEqual(delay, "0.24s")
|
| 186 |
+
self.page.emulate_media(reduced_motion="reduce")
|
| 187 |
+
for selector in ("#history-panel", "#bookmarks-panel .panel-search"):
|
| 188 |
+
values = self.page.locator(selector).evaluate("""element => {
|
| 189 |
+
const style = getComputedStyle(element);
|
| 190 |
+
return [style.transitionDuration, style.transitionDelay];
|
| 191 |
+
}""")
|
| 192 |
+
self.assertTrue(all(float(value.strip().removesuffix('s')) == 0
|
| 193 |
+
for group in values for value in group.split(',')), values)
|
| 194 |
+
|
| 195 |
+
def test_high_contrast_overrides_light_borders_and_internal_link_reset(self):
|
| 196 |
+
self.page.emulate_media(contrast="more")
|
| 197 |
+
self.page.locator("#content").evaluate("""content => content.insertAdjacentHTML('beforeend',
|
| 198 |
+
'<div class="foliate-continuous"><a href="#internal">Internal link</a></div>')""")
|
| 199 |
+
for theme in ("dark", "light"):
|
| 200 |
+
self.page.locator("html").evaluate("(element, theme) => element.dataset.theme = theme", theme)
|
| 201 |
+
for selector, border in ((".reader-toolbar", "borderBottomColor"),
|
| 202 |
+
(".reader-panel", "borderLeftColor"),
|
| 203 |
+
(".reader-panel-tabs", "borderBottomColor"),
|
| 204 |
+
(".reader-panel > header", "borderBottomColor"),
|
| 205 |
+
(".reader-progress-tools", "borderTopColor")):
|
| 206 |
+
colors = self.page.locator(selector).evaluate("""(element, border) => {
|
| 207 |
+
const style = getComputedStyle(element);
|
| 208 |
+
return [style[border], style.color];
|
| 209 |
+
}""", border)
|
| 210 |
+
self.assertEqual(colors[0], colors[1], (selector, theme, colors))
|
| 211 |
+
self.assertIn("underline", self.page.locator(".foliate-continuous a").evaluate(
|
| 212 |
+
"element => getComputedStyle(element).textDecorationLine"
|
| 213 |
+
))
|
| 214 |
+
|
| 215 |
+
def test_rendered_foliate_shadow_tracks_contrast_without_layout_changes(self):
|
| 216 |
+
with zipfile.ZipFile(io.BytesIO(epub_with_navigation())) as archive:
|
| 217 |
+
files = {name: archive.read(name) for name in archive.namelist()}
|
| 218 |
+
# A book rule makes normal and high-contrast underlining distinguishable.
|
| 219 |
+
files["OEBPS/nav.xhtml"] = files["OEBPS/nav.xhtml"].decode().replace(
|
| 220 |
+
"a{color:#000}", "a{color:#000;text-decoration:none!important}"
|
| 221 |
+
).replace("</a>", " ContrastTarget</a>", 1)
|
| 222 |
+
book = zip_bytes(files)
|
| 223 |
+
self.page.route("**/api/reader-content**", lambda route: route.fulfill(
|
| 224 |
+
content_type="application/epub+zip", body=book
|
| 225 |
+
))
|
| 226 |
+
source = urllib.parse.quote(
|
| 227 |
+
"https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/contrast.epub", safe=""
|
| 228 |
+
)
|
| 229 |
+
self.page.emulate_media(contrast="no-preference")
|
| 230 |
+
self.page.goto(
|
| 231 |
+
f"{self.origin}/static/reader.html?url={source}&ext=epub&title=Contrast",
|
| 232 |
+
wait_until="domcontentloaded",
|
| 233 |
+
)
|
| 234 |
+
self.page.wait_for_function("() => document.documentElement.dataset.readerPhase === 'ready'")
|
| 235 |
+
self.page.locator("#history").click()
|
| 236 |
+
self.page.locator("#full-search-toggle").click()
|
| 237 |
+
self.page.locator("#full-search-input").fill("ContrastTarget")
|
| 238 |
+
self.page.locator("#full-search-results .full-search-result").first.click()
|
| 239 |
+
highlight = self.page.locator(".foliate-continuous mark.full-search-highlight").first
|
| 240 |
+
highlight.wait_for()
|
| 241 |
+
self.settle()
|
| 242 |
+
measure = """mark => {
|
| 243 |
+
const root = mark.getRootNode(), link = mark.closest('a[href]');
|
| 244 |
+
const style = getComputedStyle(mark);
|
| 245 |
+
const rect = element => {
|
| 246 |
+
const box = element.getBoundingClientRect();
|
| 247 |
+
return [box.x, box.y, box.width, box.height];
|
| 248 |
+
};
|
| 249 |
+
const viewport = document.querySelector('#viewport');
|
| 250 |
+
return {
|
| 251 |
+
shadow: root instanceof ShadowRoot && root.host.matches('article[data-section]'),
|
| 252 |
+
text: mark.textContent,
|
| 253 |
+
decoration: getComputedStyle(link).textDecorationLine,
|
| 254 |
+
outline: style.outlineStyle,
|
| 255 |
+
width: parseFloat(style.outlineWidth),
|
| 256 |
+
outlineColor: style.outlineColor,
|
| 257 |
+
color: style.color,
|
| 258 |
+
layout: [rect(document.querySelector('.reader-toolbar')), rect(viewport),
|
| 259 |
+
rect(root.host), rect(link), rect(mark),
|
| 260 |
+
[viewport.scrollWidth, viewport.scrollHeight, viewport.scrollTop]]
|
| 261 |
+
};
|
| 262 |
+
}"""
|
| 263 |
+
for theme in ("dark", "light"):
|
| 264 |
+
with self.subTest(theme=theme):
|
| 265 |
+
self.page.locator("html").evaluate(
|
| 266 |
+
"(element, theme) => element.dataset.theme = theme", theme
|
| 267 |
+
)
|
| 268 |
+
before = highlight.evaluate(measure)
|
| 269 |
+
self.assertTrue(before["shadow"])
|
| 270 |
+
self.assertEqual(before["text"], "ContrastTarget")
|
| 271 |
+
self.assertEqual(before["decoration"], "none")
|
| 272 |
+
self.assertEqual(before["outline"], "none")
|
| 273 |
+
self.page.emulate_media(contrast="more")
|
| 274 |
+
high = highlight.evaluate(measure)
|
| 275 |
+
self.assertIn("underline", high["decoration"])
|
| 276 |
+
self.assertEqual(high["outline"], "solid")
|
| 277 |
+
self.assertEqual(high["width"], 2)
|
| 278 |
+
self.assertEqual(high["outlineColor"], high["color"])
|
| 279 |
+
self.assertEqual(high["layout"], before["layout"])
|
| 280 |
+
self.page.emulate_media(contrast="no-preference")
|
| 281 |
+
self.assertEqual(highlight.evaluate(measure), before)
|
tests/test_reader_timeout.py
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import contextlib
|
| 2 |
+
import json
|
| 3 |
+
import unittest
|
| 4 |
+
import urllib.parse
|
| 5 |
+
|
| 6 |
+
from tests.test_reader_performance import (
|
| 7 |
+
PlaywrightError,
|
| 8 |
+
static_server,
|
| 9 |
+
sync_playwright,
|
| 10 |
+
)
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
SOURCE = "https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/timeout.txt"
|
| 14 |
+
TIMEOUT_SCRIPT = """
|
| 15 |
+
const nativeTimeout = window.setTimeout.bind(window);
|
| 16 |
+
window.__requestTimeouts = [];
|
| 17 |
+
window.setTimeout = (callback, delay, ...args) =>
|
| 18 |
+
nativeTimeout(callback, delay === 120000 ? 50 : delay, ...args);
|
| 19 |
+
const nativeFetch = window.fetch.bind(window);
|
| 20 |
+
window.fetch = (input, init = {}) => {
|
| 21 |
+
const url = new URL(String(input), location.href);
|
| 22 |
+
if (!url.pathname.startsWith('/api/reader-content') &&
|
| 23 |
+
!url.pathname.startsWith('/api/reader-resolve') &&
|
| 24 |
+
!url.pathname.endsWith('/timeout.txt')) return nativeFetch(input, init);
|
| 25 |
+
const signal = init.signal;
|
| 26 |
+
signal.addEventListener('abort', () => {
|
| 27 |
+
window.__requestTimeouts.push(signal.reason.name);
|
| 28 |
+
}, { once: true });
|
| 29 |
+
if (window.__timeoutScenario === 'body') {
|
| 30 |
+
return Promise.resolve(new Response(new ReadableStream({
|
| 31 |
+
start(controller) {
|
| 32 |
+
signal.addEventListener('abort', () => controller.error(signal.reason),
|
| 33 |
+
{ once: true });
|
| 34 |
+
}
|
| 35 |
+
}), { headers: { 'Content-Type': 'text/plain' } }));
|
| 36 |
+
}
|
| 37 |
+
return new Promise((resolve, reject) => {
|
| 38 |
+
signal.addEventListener('abort', () => reject(signal.reason), { once: true });
|
| 39 |
+
});
|
| 40 |
+
};
|
| 41 |
+
"""
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
@unittest.skipIf(sync_playwright is None, "install requirements-test.txt to run Reader timeout tests")
|
| 45 |
+
class ReaderTimeoutTests(unittest.TestCase):
|
| 46 |
+
@classmethod
|
| 47 |
+
def setUpClass(cls):
|
| 48 |
+
resources = contextlib.ExitStack()
|
| 49 |
+
cls.addClassCleanup(resources.close)
|
| 50 |
+
cls.origin = resources.enter_context(static_server())
|
| 51 |
+
playwright = resources.enter_context(sync_playwright())
|
| 52 |
+
try:
|
| 53 |
+
cls.browser = playwright.chromium.launch(headless=True, args=["--no-sandbox"])
|
| 54 |
+
except PlaywrightError as error:
|
| 55 |
+
raise unittest.SkipTest(f"Chromium is unavailable: {error}")
|
| 56 |
+
cls.addClassCleanup(cls.browser.close)
|
| 57 |
+
|
| 58 |
+
def assert_timeout_ui(self, scenario):
|
| 59 |
+
with self.browser.new_context(service_workers="block") as context:
|
| 60 |
+
page = context.new_page()
|
| 61 |
+
page_errors = []
|
| 62 |
+
page.on("pageerror", lambda error: page_errors.append(str(error)))
|
| 63 |
+
page.add_init_script(
|
| 64 |
+
f"window.__timeoutScenario = {json.dumps(scenario)};\n" + TIMEOUT_SCRIPT
|
| 65 |
+
)
|
| 66 |
+
query = {"ext": "txt", "title": "Timeout"}
|
| 67 |
+
query.update({"id": "timeout-id"} if scenario == "resolve" else {"url": SOURCE})
|
| 68 |
+
page.goto(
|
| 69 |
+
f"{self.origin}/static/reader.html?{urllib.parse.urlencode(query)}",
|
| 70 |
+
wait_until="domcontentloaded",
|
| 71 |
+
)
|
| 72 |
+
page.locator(".reader-error").wait_for(state="visible", timeout=10000)
|
| 73 |
+
self.assertEqual(page.locator("html").get_attribute("data-reader-phase"), "failed")
|
| 74 |
+
self.assertEqual(page.locator("#content").get_attribute("data-error-code"), "READER_NETWORK")
|
| 75 |
+
self.assertEqual(page.locator(".reader-loading-indicator").count(), 0)
|
| 76 |
+
names = page.evaluate("window.__requestTimeouts")
|
| 77 |
+
self.assertTrue(names)
|
| 78 |
+
self.assertEqual(set(names), {"TimeoutError"})
|
| 79 |
+
self.assertEqual(page_errors, [])
|
| 80 |
+
|
| 81 |
+
def test_txt_timeout_before_headers_shows_failure(self):
|
| 82 |
+
self.assert_timeout_ui("headers")
|
| 83 |
+
|
| 84 |
+
def test_txt_timeout_after_headers_shows_failure(self):
|
| 85 |
+
self.assert_timeout_ui("body")
|
| 86 |
+
|
| 87 |
+
def test_id_resolution_timeout_shows_failure(self):
|
| 88 |
+
self.assert_timeout_ui("resolve")
|
tests/test_reader_visual.py
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import pathlib
|
| 3 |
+
import unittest
|
| 4 |
+
import urllib.parse
|
| 5 |
+
|
| 6 |
+
from tests.test_reader_performance import STORE_SCRIPT, static_server, sync_playwright, PlaywrightError
|
| 7 |
+
|
| 8 |
+
ROOT = pathlib.Path(__file__).parents[1]
|
| 9 |
+
SNAPSHOTS = ROOT / "tests/snapshots/reader/chromium-linux"
|
| 10 |
+
MATRIX = (("desktop", 1440, 900), ("tablet", 820, 1180), ("mobile", 390, 844))
|
| 11 |
+
|
| 12 |
+
@unittest.skipIf(sync_playwright is None, "install requirements-test.txt to run Reader visual tests")
|
| 13 |
+
class ReaderVisualTests(unittest.TestCase):
|
| 14 |
+
@classmethod
|
| 15 |
+
def setUpClass(cls):
|
| 16 |
+
cls.server = static_server(); cls.origin = cls.server.__enter__(); cls.playwright = sync_playwright().start()
|
| 17 |
+
try: cls.browser = cls.playwright.chromium.launch(headless=True)
|
| 18 |
+
except PlaywrightError as error: cls.playwright.stop(); cls.server.__exit__(None, None, None); raise unittest.SkipTest(str(error))
|
| 19 |
+
|
| 20 |
+
@classmethod
|
| 21 |
+
def tearDownClass(cls): cls.browser.close(); cls.playwright.stop(); cls.server.__exit__(None, None, None)
|
| 22 |
+
|
| 23 |
+
def test_reader_visual_matrix(self):
|
| 24 |
+
source = urllib.parse.quote("https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/visual.txt", safe="")
|
| 25 |
+
for name, width, height in MATRIX:
|
| 26 |
+
for theme in ("light", "dark"):
|
| 27 |
+
with self.subTest(viewport=name, theme=theme):
|
| 28 |
+
context = self.browser.new_context(viewport={"width": width, "height": height}, color_scheme=theme)
|
| 29 |
+
page = context.new_page(); page.add_init_script(f"localStorage.setItem('theme', '{theme}')")
|
| 30 |
+
page.route("**/static/reader-store.js", lambda route: route.fulfill(status=200, content_type="text/javascript", body=STORE_SCRIPT))
|
| 31 |
+
page.route("**/api/reader-content**", lambda route: route.fulfill(status=200, content_type="text/plain", body=("Reader visual fixture\n" * 80).encode()))
|
| 32 |
+
page.goto(f"{self.origin}/static/reader.html?url={source}&ext=txt&title=Visual", wait_until="domcontentloaded")
|
| 33 |
+
page.locator(".reader-text").wait_for(); page.add_style_tag(content="*,*::before,*::after{animation:none!important;transition:none!important;caret-color:transparent!important}")
|
| 34 |
+
image = page.screenshot(animations="disabled"); baseline = SNAPSHOTS / f"{name}-{theme}.png"
|
| 35 |
+
if os.environ.get("UPDATE_READER_SNAPSHOTS") == "1": baseline.parent.mkdir(parents=True, exist_ok=True); baseline.write_bytes(image)
|
| 36 |
+
self.assertTrue(baseline.exists(), f"missing baseline {baseline}"); self.assertEqual(image, baseline.read_bytes())
|
| 37 |
+
context.close()
|
tests/test_real_integration.py
ADDED
|
@@ -0,0 +1,196 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import gzip
|
| 4 |
+
import json
|
| 5 |
+
import unittest
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
|
| 8 |
+
try:
|
| 9 |
+
from .real_server import ROOT, get_shared_server
|
| 10 |
+
except ImportError: # unittest discovery with tests as the top-level directory
|
| 11 |
+
from real_server import ROOT, get_shared_server
|
| 12 |
+
|
| 13 |
+
try:
|
| 14 |
+
from playwright.sync_api import Error as PlaywrightError
|
| 15 |
+
from playwright.sync_api import sync_playwright
|
| 16 |
+
except ImportError: # pragma: no cover
|
| 17 |
+
PlaywrightError = Exception
|
| 18 |
+
sync_playwright = None
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
COMMON_FIELDS = ("Repo", "File", "Extension", "Folder", "Size", "HasTxt")
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def common(record):
|
| 25 |
+
return {field: record.get(field) for field in COMMON_FIELDS}
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class RealDataIntegrationTests(unittest.TestCase):
|
| 29 |
+
@classmethod
|
| 30 |
+
def setUpClass(cls):
|
| 31 |
+
cls.server = get_shared_server()
|
| 32 |
+
cls.base_url = cls.server.base_url
|
| 33 |
+
cls.data = ROOT / "data"
|
| 34 |
+
with gzip.open(cls.data / "search_data.json.gz", "rt", encoding="utf-8") as handle:
|
| 35 |
+
cls.compact = json.load(handle)
|
| 36 |
+
cls.playwright = None
|
| 37 |
+
cls.browser = None
|
| 38 |
+
if sync_playwright:
|
| 39 |
+
cls.playwright = sync_playwright().start()
|
| 40 |
+
try:
|
| 41 |
+
cls.browser = cls.playwright.chromium.launch(headless=True, args=["--no-sandbox"])
|
| 42 |
+
except PlaywrightError:
|
| 43 |
+
cls.playwright.stop()
|
| 44 |
+
cls.playwright = None
|
| 45 |
+
|
| 46 |
+
@classmethod
|
| 47 |
+
def tearDownClass(cls):
|
| 48 |
+
if cls.browser:
|
| 49 |
+
cls.browser.close()
|
| 50 |
+
if cls.playwright:
|
| 51 |
+
cls.playwright.stop()
|
| 52 |
+
if cls.server.process.poll() is None:
|
| 53 |
+
cls.server.stop()
|
| 54 |
+
|
| 55 |
+
def test_01_readiness_repositories_equal_sidebar_counts(self):
|
| 56 |
+
api = self.server.json("/api/repos")
|
| 57 |
+
sidebar = json.loads((self.data / "sidebar/global.json").read_text(encoding="utf-8"))["repos"]
|
| 58 |
+
self.assertEqual(api, sidebar)
|
| 59 |
+
self.assertEqual(sum(item["count"] for item in api), 100203)
|
| 60 |
+
|
| 61 |
+
def test_02_empty_search_page_one_matches_generated_initial_common_fields(self):
|
| 62 |
+
initial = json.loads((self.data / "initial/global.json").read_text(encoding="utf-8"))
|
| 63 |
+
api = self.server.json("/api/search", {"page": 1, "page_size": 100})
|
| 64 |
+
self.assertEqual((api["total"], api["page"], api["page_size"]), (initial["total"], 1, 100))
|
| 65 |
+
self.assertEqual([common(item) for item in api["results"]], [common(item) for item in initial["results"]])
|
| 66 |
+
|
| 67 |
+
def test_03_page_two_matches_independently_decoded_compact_slice(self):
|
| 68 |
+
repos, folders = self.compact["rp"], self.compact["fd"]
|
| 69 |
+
expected = []
|
| 70 |
+
for row in self.compact["rc"][100:200]:
|
| 71 |
+
expected.append({"Repo": repos[row[0]], "File": row[1], "Extension": row[2], "Folder": folders[row[3]], "Size": row[4], "HasTxt": bool(row[5])})
|
| 72 |
+
api = self.server.json("/api/search", {"page": 2, "page_size": 100})
|
| 73 |
+
self.assertEqual(api["total"], 100203)
|
| 74 |
+
self.assertEqual([common(item) for item in api["results"]], expected)
|
| 75 |
+
|
| 76 |
+
def test_04_every_repo_route_matches_generated_initial_page_and_total(self):
|
| 77 |
+
for path in sorted((self.data / "initial/repos").glob("*.json")):
|
| 78 |
+
with self.subTest(repo=path.stem):
|
| 79 |
+
initial = json.loads(path.read_text(encoding="utf-8"))
|
| 80 |
+
api = self.server.json(f"/api/search/{path.stem}", {"page": 1, "page_size": 100})
|
| 81 |
+
self.assertEqual(api["total"], initial["total"])
|
| 82 |
+
self.assertEqual([common(item) for item in api["results"]], [common(item) for item in initial["results"]])
|
| 83 |
+
|
| 84 |
+
def test_05_folder_api_root_count_matches_generated_tree_and_not_above_repo_total(self):
|
| 85 |
+
repos = self.server.json("/api/repos")
|
| 86 |
+
with gzip.open(self.data / "folder_tree.json.gz", "rt", encoding="utf-8") as handle:
|
| 87 |
+
generated_tree = json.load(handle)
|
| 88 |
+
for repo in repos:
|
| 89 |
+
short = repo["name"].split("/")[-1]
|
| 90 |
+
with self.subTest(repo=short):
|
| 91 |
+
tree = self.server.json(f"/api/folders/{short}")
|
| 92 |
+
self.assertIsInstance(tree, list)
|
| 93 |
+
self.assertTrue(tree)
|
| 94 |
+
self.assertEqual(tree[0]["count"], generated_tree[repo["name"]][0]["c"])
|
| 95 |
+
self.assertLessEqual(tree[0]["count"], repo["count"])
|
| 96 |
+
self.assertEqual(tree[0]["path"], "")
|
| 97 |
+
|
| 98 |
+
def test_06_folder_contents_shape_and_direct_file_counts_are_consistent(self):
|
| 99 |
+
contents = self.server.json("/api/folders/VOMEBOOK/contents?path=")
|
| 100 |
+
self.assertEqual(set(contents), {"folders", "files", "current_path"})
|
| 101 |
+
self.assertEqual(contents["current_path"], "")
|
| 102 |
+
self.assertTrue(all({"name", "path", "count"} <= set(item) for item in contents["folders"]))
|
| 103 |
+
self.assertTrue(all(item["count"] > 0 for item in contents["folders"]))
|
| 104 |
+
|
| 105 |
+
def test_07_real_search_matrix_response_invariants(self):
|
| 106 |
+
matrix = [
|
| 107 |
+
{"q": "手机", "page": 1, "page_size": 7},
|
| 108 |
+
{"q": "文化 革命", "page": 1, "page_size": 7},
|
| 109 |
+
{"q": "README", "exact": True, "page": 1, "page_size": 7},
|
| 110 |
+
{"q": "资料", "extensions": ["pdf"], "sort": "size", "page": 1, "page_size": 7},
|
| 111 |
+
{"q": "不存在的集成测试词", "page": 1, "page_size": 7},
|
| 112 |
+
]
|
| 113 |
+
for body in matrix:
|
| 114 |
+
with self.subTest(body=body):
|
| 115 |
+
result = self.server.json("/api/search", body)
|
| 116 |
+
self.assertEqual(set(result), {"results", "total", "page", "page_size"})
|
| 117 |
+
self.assertEqual((result["page"], result["page_size"]), (1, 7))
|
| 118 |
+
self.assertLessEqual(len(result["results"]), 7)
|
| 119 |
+
self.assertGreaterEqual(result["total"], len(result["results"]))
|
| 120 |
+
self.assertTrue(all(set(COMMON_FIELDS) <= set(item) for item in result["results"]))
|
| 121 |
+
|
| 122 |
+
def test_08_repeated_search_and_page_two_are_stable(self):
|
| 123 |
+
body = {"q": "文化", "sort": "name", "page": 1, "page_size": 11}
|
| 124 |
+
first = self.server.json("/api/search", body)
|
| 125 |
+
repeated = self.server.json("/api/search", body)
|
| 126 |
+
second_page = self.server.json("/api/search", {**body, "page": 2})
|
| 127 |
+
self.assertEqual(first, repeated)
|
| 128 |
+
self.assertEqual(first["total"], second_page["total"])
|
| 129 |
+
self.assertEqual(second_page["page"], 2)
|
| 130 |
+
self.assertEqual(len({(item["Repo"], tuple(item["Folder"]), item["File"], item["Extension"]) for item in first["results"] + second_page["results"]}), len(first["results"] + second_page["results"]))
|
| 131 |
+
|
| 132 |
+
@unittest.skipUnless(sync_playwright, "Playwright is not installed")
|
| 133 |
+
def test_20_browser_initial_injected_payload_is_visible_without_api_mock(self):
|
| 134 |
+
if not self.browser:
|
| 135 |
+
self.skipTest("Chromium is unavailable")
|
| 136 |
+
context = self.browser.new_context(viewport={"width": 1440, "height": 900})
|
| 137 |
+
page = context.new_page()
|
| 138 |
+
try:
|
| 139 |
+
page.route("https://vomebook-hitokoto.hf.space/**", lambda route: route.fulfill(status=200, content_type="application/json", body='{"hitokoto":"integration"}'))
|
| 140 |
+
page.goto(self.base_url + "/", wait_until="domcontentloaded")
|
| 141 |
+
page.locator("#results-list .result-item").first.wait_for(timeout=20000)
|
| 142 |
+
injected = page.locator("#initial-search-data")
|
| 143 |
+
self.assertEqual(injected.count(), 1)
|
| 144 |
+
self.assertIn("目录", page.locator("#results-list").inner_text())
|
| 145 |
+
finally:
|
| 146 |
+
context.close()
|
| 147 |
+
|
| 148 |
+
@unittest.skipUnless(sync_playwright, "Playwright is not installed")
|
| 149 |
+
def test_21_browser_query_posts_to_real_api_and_dom_matches_response(self):
|
| 150 |
+
if not self.browser:
|
| 151 |
+
self.skipTest("Chromium is unavailable")
|
| 152 |
+
expected = self.server.json("/api/search", {"q": "README", "page": 1, "page_size": 100, "sort": "relevance", "exact": True})
|
| 153 |
+
context = self.browser.new_context(viewport={"width": 1440, "height": 900})
|
| 154 |
+
page = context.new_page()
|
| 155 |
+
posts = []
|
| 156 |
+
page.on("request", lambda request: posts.append(request.url) if request.method == "POST" and "/api/search" in request.url else None)
|
| 157 |
+
try:
|
| 158 |
+
page.route("https://vomebook-hitokoto.hf.space/**", lambda route: route.fulfill(status=200, content_type="application/json", body='{"hitokoto":"integration"}'))
|
| 159 |
+
page.goto(self.base_url + "/", wait_until="domcontentloaded")
|
| 160 |
+
page.locator("#search-input").fill("README")
|
| 161 |
+
page.wait_for_function("() => new URL(location.href).searchParams.get('q') === 'README'")
|
| 162 |
+
page.locator("#results-list .result-item").first.wait_for(timeout=30000)
|
| 163 |
+
self.assertTrue(posts)
|
| 164 |
+
self.assertIn(expected["results"][0]["File"], page.locator("#results-list .result-title").first.inner_text())
|
| 165 |
+
self.assertIn(str(expected["total"]), page.locator("#result-count").inner_text().replace(",", ""))
|
| 166 |
+
finally:
|
| 167 |
+
context.close()
|
| 168 |
+
|
| 169 |
+
@unittest.skipUnless(sync_playwright, "Playwright is not installed")
|
| 170 |
+
def test_22_browser_repo_route_and_name_sort_use_real_backend(self):
|
| 171 |
+
if not self.browser:
|
| 172 |
+
self.skipTest("Chromium is unavailable")
|
| 173 |
+
context = self.browser.new_context(viewport={"width": 1440, "height": 900})
|
| 174 |
+
page = context.new_page()
|
| 175 |
+
try:
|
| 176 |
+
page.route("https://vomebook-hitokoto.hf.space/**", lambda route: route.fulfill(status=200, content_type="application/json", body='{"hitokoto":"integration"}'))
|
| 177 |
+
page.goto(self.base_url + "/Omnibus", wait_until="domcontentloaded")
|
| 178 |
+
page.locator("#results-list .result-item").first.wait_for(timeout=20000)
|
| 179 |
+
self.assertEqual(page.locator("#header-title").inner_text(), "Omnibus")
|
| 180 |
+
page.locator("#sort-select").select_option("name")
|
| 181 |
+
expected = self.server.json("/api/search/Omnibus", {"page": 1, "page_size": 100, "sort": "name", "exact": True})
|
| 182 |
+
page.wait_for_function("name => document.querySelector('.result-title')?.textContent.includes(name)", arg=expected["results"][0]["File"])
|
| 183 |
+
self.assertIn(expected["results"][0]["File"], page.locator(".result-title").first.inner_text())
|
| 184 |
+
finally:
|
| 185 |
+
context.close()
|
| 186 |
+
|
| 187 |
+
def test_99_graceful_shutdown_has_no_resource_leak_warnings(self):
|
| 188 |
+
returncode = self.server.stop()
|
| 189 |
+
stderr = self.server.stderr()
|
| 190 |
+
self.assertEqual(returncode, 0, stderr)
|
| 191 |
+
forbidden = ("Unclosed client session", "Unclosed connector", "Task was destroyed but it is pending", "never awaited")
|
| 192 |
+
self.assertFalse(any(message in stderr for message in forbidden), stderr)
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
if __name__ == "__main__":
|
| 196 |
+
unittest.main()
|
tests/test_search.py
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import unittest
|
| 4 |
+
from copy import deepcopy
|
| 5 |
+
from unittest import mock
|
| 6 |
+
|
| 7 |
+
IMPORT_ERROR = None
|
| 8 |
+
try:
|
| 9 |
+
import app
|
| 10 |
+
except ModuleNotFoundError as exc: # pragma: no cover - environment dependent
|
| 11 |
+
app = None
|
| 12 |
+
IMPORT_ERROR = exc
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
@unittest.skipIf(app is None, f"app dependencies unavailable: {IMPORT_ERROR}")
|
| 16 |
+
class SearchContractTests(unittest.TestCase):
|
| 17 |
+
def setUp(self):
|
| 18 |
+
self.original_state = {
|
| 19 |
+
name: deepcopy(getattr(app, name))
|
| 20 |
+
for name in (
|
| 21 |
+
"records", "word_index", "folder_index", "repo_counts", "repo_list",
|
| 22 |
+
"repo_records_map", "sorted_by_name", "sorted_by_size",
|
| 23 |
+
"repo_sorted_by_name", "repo_sorted_by_size", "vocab_by_len",
|
| 24 |
+
"extension_counts", "extension_list", "repo_extension_counts",
|
| 25 |
+
"txt_record_indices", "repo_txt_record_indices", "reader_record_indices", "repo_reader_record_indices", "initial_payload_global",
|
| 26 |
+
"initial_payload_by_repo", "api_response_cache", "ngram_postings",
|
| 27 |
+
)
|
| 28 |
+
}
|
| 29 |
+
app.records = [
|
| 30 |
+
self.record("Repo/A", "文化革命资料", ["历史"], 30),
|
| 31 |
+
self.record("Repo/B", "文化资料", ["革命文献"], 20),
|
| 32 |
+
self.record("Repo/C", "革命资料", ["其他"], 10),
|
| 33 |
+
]
|
| 34 |
+
app.build_indexes()
|
| 35 |
+
app.ngram_postings = {}
|
| 36 |
+
|
| 37 |
+
def tearDown(self):
|
| 38 |
+
for name, value in self.original_state.items():
|
| 39 |
+
setattr(app, name, value)
|
| 40 |
+
|
| 41 |
+
@staticmethod
|
| 42 |
+
def record(repo, file_name, folders, size):
|
| 43 |
+
return {
|
| 44 |
+
"Repo": repo,
|
| 45 |
+
"File": file_name,
|
| 46 |
+
"Extension": "txt",
|
| 47 |
+
"Folder": folders,
|
| 48 |
+
"Size": size,
|
| 49 |
+
"HasTxt": True,
|
| 50 |
+
}
|
| 51 |
+
|
| 52 |
+
def test_multiple_terms_are_intersected(self):
|
| 53 |
+
result = app.search("文化 革命")
|
| 54 |
+
self.assertEqual(result["total"], 2)
|
| 55 |
+
self.assertEqual({item["File"] for item in result["results"]}, {"文化革命资料", "文化资料"})
|
| 56 |
+
|
| 57 |
+
def test_search_folders_false_excludes_folder_only_match(self):
|
| 58 |
+
result = app.search("革命", search_folders=False)
|
| 59 |
+
self.assertEqual({item["File"] for item in result["results"]}, {"文化革命资料", "革命资料"})
|
| 60 |
+
|
| 61 |
+
def test_exact_search_is_contiguous(self):
|
| 62 |
+
self.assertEqual(app.search("文化革命", exact=True)["total"], 1)
|
| 63 |
+
self.assertEqual(app.search("手。机", exact=True)["total"], 0)
|
| 64 |
+
|
| 65 |
+
def test_wildcards_are_supported(self):
|
| 66 |
+
self.assertEqual(app.search("文化*", exact=True)["total"], 2)
|
| 67 |
+
self.assertEqual(app.search("文??革命", exact=True)["total"], 0)
|
| 68 |
+
|
| 69 |
+
def test_filters_sorting_and_pagination(self):
|
| 70 |
+
result = app.search("资料", repos=["Repo/B"], min_size=20, sort="size", page_size=1)
|
| 71 |
+
self.assertEqual(result["total"], 1)
|
| 72 |
+
self.assertEqual(result["results"][0]["File"], "文化资料")
|
| 73 |
+
|
| 74 |
+
def test_empty_search_filters_multiple_repositories(self):
|
| 75 |
+
result = app.search("", repos=["Repo/A", "Repo/C"])
|
| 76 |
+
self.assertEqual(result["total"], 2)
|
| 77 |
+
self.assertEqual({item["Repo"] for item in result["results"]}, {"Repo/A", "Repo/C"})
|
| 78 |
+
|
| 79 |
+
def test_zero_size_keeps_current_filter_bypass_behavior(self):
|
| 80 |
+
app.records.append(self.record("Repo/Z", "unknown-size", [], 0))
|
| 81 |
+
app.build_indexes()
|
| 82 |
+
result = app.search("", min_size=100)
|
| 83 |
+
self.assertIn("unknown-size", {item["File"] for item in result["results"]})
|
| 84 |
+
|
| 85 |
+
def test_cache_key_separates_search_options(self):
|
| 86 |
+
app.api_response_cache.clear()
|
| 87 |
+
first = app.cached_payload(("search", "x", 1), lambda: {"value": 1})
|
| 88 |
+
second = app.cached_payload(("search", "x", 1), lambda: {"value": 2})
|
| 89 |
+
different = app.cached_payload(("search", "x", 2), lambda: {"value": 3})
|
| 90 |
+
self.assertEqual(first, second)
|
| 91 |
+
self.assertEqual(different, {"value": 3})
|
| 92 |
+
|
| 93 |
+
def test_exact_search_uses_ngram_candidates(self):
|
| 94 |
+
app.ngram_postings = {
|
| 95 |
+
2: {},
|
| 96 |
+
3: {
|
| 97 |
+
"文化革": b"\x00",
|
| 98 |
+
"化革命": b"\x00",
|
| 99 |
+
},
|
| 100 |
+
}
|
| 101 |
+
self.assertEqual(app.literal_candidates("文化革命"), {0})
|
| 102 |
+
with mock.patch.object(app, "literal_candidates", wraps=app.literal_candidates) as candidates:
|
| 103 |
+
result = app._search_uncached("文化革命", exact=True)
|
| 104 |
+
candidates.assert_called_once_with("文化革命", None)
|
| 105 |
+
self.assertEqual(result["total"], 1)
|
| 106 |
+
self.assertEqual(result["results"][0]["File"], "文化革命资料")
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
@unittest.skipIf(app is None, f"app dependencies unavailable: {IMPORT_ERROR}")
|
| 110 |
+
class UtilityTests(unittest.TestCase):
|
| 111 |
+
def test_wildcard_matches_newlines_only_in_existing_semantics(self):
|
| 112 |
+
self.assertTrue(app.matches_exact_query("手持电话机", "手*机"))
|
| 113 |
+
self.assertFalse(app.matches_exact_query("手持电话", "手*机"))
|
| 114 |
+
|
| 115 |
+
def test_response_shape_is_stable(self):
|
| 116 |
+
original_records = app.records
|
| 117 |
+
app.records = []
|
| 118 |
+
try:
|
| 119 |
+
result = app.search("")
|
| 120 |
+
self.assertEqual(set(result), {"results", "total", "page", "page_size"})
|
| 121 |
+
self.assertEqual(result["results"], [])
|
| 122 |
+
finally:
|
| 123 |
+
app.records = original_records
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
if __name__ == "__main__":
|
| 127 |
+
unittest.main()
|
tests/test_search_behavior.py
ADDED
|
@@ -0,0 +1,165 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import copy
|
| 4 |
+
import unittest
|
| 5 |
+
|
| 6 |
+
IMPORT_ERROR = None
|
| 7 |
+
try:
|
| 8 |
+
import app
|
| 9 |
+
except ModuleNotFoundError as exc: # pragma: no cover
|
| 10 |
+
app = None
|
| 11 |
+
IMPORT_ERROR = exc
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
@unittest.skipIf(app is None, f"app dependencies unavailable: {IMPORT_ERROR}")
|
| 15 |
+
class SearchBehaviorTests(unittest.TestCase):
|
| 16 |
+
NAMES = (
|
| 17 |
+
"records", "word_index", "folder_index", "repo_counts", "repo_list",
|
| 18 |
+
"repo_records_map", "sorted_by_name", "sorted_by_size", "repo_sorted_by_name",
|
| 19 |
+
"repo_sorted_by_size", "vocab_by_len", "extension_counts", "extension_list",
|
| 20 |
+
"repo_extension_counts", "txt_record_indices", "repo_txt_record_indices", "reader_record_indices", "repo_reader_record_indices",
|
| 21 |
+
)
|
| 22 |
+
|
| 23 |
+
def setUp(self):
|
| 24 |
+
self.saved = {name: copy.deepcopy(getattr(app, name)) for name in self.NAMES}
|
| 25 |
+
app.records = [
|
| 26 |
+
self.rec("VoiceOfML/A", "alpha", ["one", "deep"], "txt", 30),
|
| 27 |
+
self.rec("VoiceOfML/A", "beta", ["one"], "pdf", 20),
|
| 28 |
+
self.rec("VoiceOfML/A", "gamma", ["two"], "txt", 10),
|
| 29 |
+
self.rec("VoiceOfML/B", "alpha", ["one"], "txt", 40),
|
| 30 |
+
self.rec("VoiceOfML/B", "delta", [], "epub", 0),
|
| 31 |
+
]
|
| 32 |
+
app.build_indexes()
|
| 33 |
+
|
| 34 |
+
def tearDown(self):
|
| 35 |
+
for name, value in self.saved.items():
|
| 36 |
+
setattr(app, name, value)
|
| 37 |
+
|
| 38 |
+
@staticmethod
|
| 39 |
+
def rec(repo, name, folders, ext, size):
|
| 40 |
+
return {"Repo": repo, "File": name, "Extension": ext, "Folder": folders, "Size": size, "HasTxt": ext == "txt"}
|
| 41 |
+
|
| 42 |
+
def test_tokenize_lowercases_latin_and_keeps_chinese_token(self):
|
| 43 |
+
tokens = app.tokenize("Alpha 手机")
|
| 44 |
+
self.assertIn("alpha", tokens)
|
| 45 |
+
self.assertIn("手机", tokens)
|
| 46 |
+
|
| 47 |
+
def test_tokenize_does_not_emit_ascii_punctuation(self):
|
| 48 |
+
self.assertNotIn(".", app.tokenize("a.b"))
|
| 49 |
+
self.assertNotIn("-", app.tokenize("a-b"))
|
| 50 |
+
|
| 51 |
+
def test_tokenize_current_jieba_behavior_keeps_compound_token(self):
|
| 52 |
+
self.assertIn("手机", app.tokenize("手机"))
|
| 53 |
+
|
| 54 |
+
def test_edit_distance_exact_zero(self):
|
| 55 |
+
self.assertEqual(app.edit_distance("same", "same"), 0)
|
| 56 |
+
|
| 57 |
+
def test_edit_distance_insert_delete_and_replace(self):
|
| 58 |
+
self.assertEqual(app.edit_distance("cat", "cats"), 1)
|
| 59 |
+
self.assertEqual(app.edit_distance("cat", "cut"), 1)
|
| 60 |
+
self.assertEqual(app.edit_distance("cats", "cat"), 1)
|
| 61 |
+
|
| 62 |
+
def test_edit_distance_returns_sentinel_when_length_exceeds_limit(self):
|
| 63 |
+
self.assertEqual(app.edit_distance("a", "abcdef", max_dist=2), 999)
|
| 64 |
+
|
| 65 |
+
def test_edit_distance_returns_sentinel_when_row_exceeds_limit(self):
|
| 66 |
+
self.assertEqual(app.edit_distance("abcdef", "uvwxyz", max_dist=2), 999)
|
| 67 |
+
|
| 68 |
+
def test_prefix_folder_filter_includes_descendants(self):
|
| 69 |
+
result = app.search("", folders=["one"], folder_match_mode="prefix")
|
| 70 |
+
self.assertEqual({x["File"] for x in result["results"]}, {"alpha", "beta", "alpha"})
|
| 71 |
+
self.assertEqual(result["total"], 3)
|
| 72 |
+
|
| 73 |
+
def test_exact_folder_filter_excludes_descendants(self):
|
| 74 |
+
result = app.search("", repos=["VoiceOfML/A"], folders=["one"], folder_match_mode="exact")
|
| 75 |
+
self.assertEqual({x["File"] for x in result["results"]}, {"beta"})
|
| 76 |
+
|
| 77 |
+
def test_root_prefix_filter_matches_root_files(self):
|
| 78 |
+
result = app.search("", folders=["/"], folder_match_mode="prefix")
|
| 79 |
+
self.assertEqual(result["total"], 5)
|
| 80 |
+
|
| 81 |
+
def test_mixed_folder_self_matches_only_direct_files(self):
|
| 82 |
+
result = app.search("", repos=["VoiceOfML/A"], folder_match_mode="mixed", folder_selfs=["one"], folder_subtrees=[])
|
| 83 |
+
self.assertEqual({x["File"] for x in result["results"]}, {"beta"})
|
| 84 |
+
|
| 85 |
+
def test_mixed_folder_subtree_matches_nested_and_direct_files(self):
|
| 86 |
+
result = app.search("", repos=["VoiceOfML/A"], folder_match_mode="mixed", folder_subtrees=["one"])
|
| 87 |
+
self.assertEqual({x["File"] for x in result["results"]}, {"alpha", "beta"})
|
| 88 |
+
|
| 89 |
+
def test_repository_filter_does_not_leak_records(self):
|
| 90 |
+
result = app.search("alpha", repos=["VoiceOfML/B"])
|
| 91 |
+
self.assertEqual(result["total"], 1)
|
| 92 |
+
self.assertEqual(result["results"][0]["Repo"], "VoiceOfML/B")
|
| 93 |
+
|
| 94 |
+
def test_extension_filter_is_case_insensitive(self):
|
| 95 |
+
result = app.search("", extensions=["PDF"])
|
| 96 |
+
self.assertEqual(result["total"], 1)
|
| 97 |
+
self.assertEqual(result["results"][0]["Extension"], "pdf")
|
| 98 |
+
|
| 99 |
+
def test_name_sort_is_case_insensitive_and_stable(self):
|
| 100 |
+
result = app.search("", sort="name")
|
| 101 |
+
self.assertEqual([x["File"] for x in result["results"]], ["alpha", "alpha", "beta", "delta", "gamma"])
|
| 102 |
+
|
| 103 |
+
def test_size_sort_descends_and_unknown_size_sorts_last(self):
|
| 104 |
+
result = app.search("", sort="size")
|
| 105 |
+
self.assertEqual([x["Size"] for x in result["results"]], [40, 30, 20, 10, 0])
|
| 106 |
+
|
| 107 |
+
def test_page_two_has_correct_total_and_slice(self):
|
| 108 |
+
result = app.search("", page=2, page_size=2)
|
| 109 |
+
self.assertEqual(result["total"], 5)
|
| 110 |
+
self.assertEqual(result["page"], 2)
|
| 111 |
+
self.assertEqual([x["File"] for x in result["results"]], ["gamma", "alpha"])
|
| 112 |
+
|
| 113 |
+
def test_page_beyond_end_is_empty_not_error(self):
|
| 114 |
+
self.assertEqual(app.search("", page=99, page_size=2)["results"], [])
|
| 115 |
+
|
| 116 |
+
def test_fuzzy_query_can_match_typo(self):
|
| 117 |
+
self.assertGreaterEqual(app.search("alpa")["total"], 1)
|
| 118 |
+
|
| 119 |
+
def test_multi_token_fuzzy_query_uses_and_semantics(self):
|
| 120 |
+
result = app.search("alpa deep")
|
| 121 |
+
self.assertEqual(result["total"], 1)
|
| 122 |
+
self.assertEqual(result["results"][0]["File"], "alpha")
|
| 123 |
+
self.assertEqual(result["results"][0]["Folder"], ["one", "deep"])
|
| 124 |
+
|
| 125 |
+
def test_multi_token_fuzzy_query_keeps_match_after_per_token_candidates(self):
|
| 126 |
+
near_matches = [
|
| 127 |
+
"al" + chr(97 + index // 26) + chr(97 + index % 26)
|
| 128 |
+
for index in range(220)
|
| 129 |
+
]
|
| 130 |
+
app.records = [
|
| 131 |
+
self.rec("VoiceOfML/A", name, [], "txt", 1)
|
| 132 |
+
for name in near_matches
|
| 133 |
+
] + [self.rec("VoiceOfML/A", "alpha", ["omega"], "txt", 1)]
|
| 134 |
+
app.build_indexes()
|
| 135 |
+
result = app.search("alpa omaga")
|
| 136 |
+
self.assertEqual(result["total"], 1)
|
| 137 |
+
self.assertEqual(result["results"][0]["File"], "alpha")
|
| 138 |
+
|
| 139 |
+
def test_relevance_ties_keep_corpus_order(self):
|
| 140 |
+
result = app.search("alpha")
|
| 141 |
+
self.assertEqual([item["Repo"] for item in result["results"]], ["VoiceOfML/A", "VoiceOfML/B"])
|
| 142 |
+
|
| 143 |
+
def test_exact_query_does_not_use_fuzzy_matching(self):
|
| 144 |
+
self.assertEqual(app.search("alpa", exact=True)["total"], 0)
|
| 145 |
+
|
| 146 |
+
def test_search_folders_false_excludes_folder_only_query(self):
|
| 147 |
+
self.assertEqual(app.search("deep", search_folders=False)["total"], 0)
|
| 148 |
+
|
| 149 |
+
def test_empty_query_without_filters_preserves_record_order(self):
|
| 150 |
+
self.assertEqual([x["File"] for x in app.search("")["results"]], ["alpha", "beta", "gamma", "alpha", "delta"])
|
| 151 |
+
|
| 152 |
+
def test_single_repository_empty_query_uses_precomputed_order(self):
|
| 153 |
+
original = app.apply_filters
|
| 154 |
+
try:
|
| 155 |
+
app.apply_filters = lambda *args, **kwargs: self.fail("single-repository fast path scanned records")
|
| 156 |
+
relevance = app._search_uncached("", repos=["VoiceOfML/A"], page=2, page_size=1)
|
| 157 |
+
by_name = app._search_uncached("", repos=["VoiceOfML/A"], sort="name")
|
| 158 |
+
finally:
|
| 159 |
+
app.apply_filters = original
|
| 160 |
+
self.assertEqual(relevance["results"][0]["File"], "beta")
|
| 161 |
+
self.assertEqual([item["File"] for item in by_name["results"]], ["alpha", "beta", "gamma"])
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
if __name__ == "__main__":
|
| 165 |
+
unittest.main()
|
tests/test_security.py
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import unittest
|
| 4 |
+
|
| 5 |
+
IMPORT_ERROR = None
|
| 6 |
+
try:
|
| 7 |
+
import app
|
| 8 |
+
except ModuleNotFoundError as exc: # pragma: no cover
|
| 9 |
+
app = None
|
| 10 |
+
IMPORT_ERROR = exc
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
@unittest.skipIf(app is None, f"app dependencies unavailable: {IMPORT_ERROR}")
|
| 14 |
+
class SecurityContractTests(unittest.TestCase):
|
| 15 |
+
def test_download_host_allowlist_rejects_confusable_hosts(self):
|
| 16 |
+
allowed = ["https://huggingface.co/x", "https://datasets.huggingface.co/x", "https://hf-mirror.com/x"]
|
| 17 |
+
rejected = ["http://huggingface.co/x", "https://huggingface.co.evil.test/x", "https://huggingface.co:444/x", "https://user@huggingface.co/x"]
|
| 18 |
+
for url in allowed:
|
| 19 |
+
self.assertEqual(app.validate_download_url(url), url)
|
| 20 |
+
for url in rejected:
|
| 21 |
+
with self.assertRaises(ValueError):
|
| 22 |
+
app.validate_download_url(url)
|
| 23 |
+
|
| 24 |
+
def test_voiceofml_source_scope_and_mirror_normalization(self):
|
| 25 |
+
self.assertEqual(app.validate_voiceofml_source_url("https://hf-mirror.com/datasets/VoiceOfML/A/resolve/main/x"), "https://huggingface.co/datasets/VoiceOfML/A/resolve/main/x")
|
| 26 |
+
rejected = [
|
| 27 |
+
"https://huggingface.co/datasets/Other/A/resolve/main/x",
|
| 28 |
+
"https://huggingface.co/datasets/VoiceOfML/%2e%2e/Other/resolve/main/x",
|
| 29 |
+
"https://huggingface.co/datasets/VoiceOfML/../Other/resolve/main/x",
|
| 30 |
+
"https://huggingface.co/datasets/VoiceOfML/A/resolve/main/x?download=1",
|
| 31 |
+
"https://huggingface.co/datasets/VoiceOfML/A/resolve/main/x#fragment",
|
| 32 |
+
"https://huggingface.co/datasets/VoiceOfML/A/resolve/main/a%5cb",
|
| 33 |
+
"https://huggingface.co/datasets/VoiceOfML/A/resolve/main/%252e%252e/secret",
|
| 34 |
+
"https://huggingface.co/datasets/VoiceOfML/A/resolve/main/%255csecret",
|
| 35 |
+
"https://huggingface.co/datasets/VoiceOfML/A/resolve/main/%2500secret",
|
| 36 |
+
]
|
| 37 |
+
for url in rejected:
|
| 38 |
+
with self.subTest(url=url), self.assertRaises(ValueError):
|
| 39 |
+
app.validate_voiceofml_source_url(url)
|
| 40 |
+
|
| 41 |
+
def test_reader_source_scope_is_limited_to_originals_and_reader_objects(self):
|
| 42 |
+
original = "https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/%E4%B9%A6.txt"
|
| 43 |
+
asset = "https://huggingface.co/datasets/vomebook/Reader-Assets/resolve/main/objects/aa/" + "b" * 64 + "/libreoffice-pdf-v2/document.pdf"
|
| 44 |
+
manifest = "https://huggingface.co/datasets/vomebook/Reader-Assets/resolve/main/objects/aa/" + "b" * 64 + "/page-manifest.json"
|
| 45 |
+
page = "https://huggingface.co/datasets/vomebook/Reader-Assets/resolve/main/objects/aa/" + "b" * 64 + "/pages/page-000001.webp"
|
| 46 |
+
docx_asset = "https://huggingface.co/datasets/vomebook/Reader-Assets/resolve/main/objects/aa/" + "b" * 64 + "/docx-native-v1/document.docx"
|
| 47 |
+
html_asset = "https://huggingface.co/datasets/vomebook/Reader-Assets/resolve/main/objects/aa/" + "b" * 64 + "/sanitized-html-v1/document.html"
|
| 48 |
+
video_asset = "https://huggingface.co/datasets/vomebook/Reader-Assets/resolve/main/objects/aa/" + "b" * 64 + "/ffmpeg-video-mp4-h264-aac-v1/video.mp4"
|
| 49 |
+
self.assertEqual(app.validate_reader_source_url(original), original)
|
| 50 |
+
self.assertEqual(app.validate_reader_source_url(asset), asset)
|
| 51 |
+
self.assertEqual(app.validate_reader_source_url(manifest), manifest)
|
| 52 |
+
self.assertEqual(app.validate_reader_source_url(page), page)
|
| 53 |
+
self.assertEqual(app.validate_reader_source_url(docx_asset), docx_asset)
|
| 54 |
+
self.assertEqual(app.validate_reader_source_url(html_asset), html_asset)
|
| 55 |
+
self.assertEqual(app.validate_reader_source_url(video_asset), video_asset)
|
| 56 |
+
chapter_base = "https://huggingface.co/datasets/vomebook/Reader-Assets/resolve/main/objects/aa/" + "b" * 64 + "/foliate-original-v1/epub-chapters"
|
| 57 |
+
for url in (
|
| 58 |
+
chapter_base + "/chapter-manifest.json",
|
| 59 |
+
chapter_base + "/chapters/chapter-0001.xhtml",
|
| 60 |
+
chapter_base + "/resources/OEBPS/images/x.png",
|
| 61 |
+
chapter_base + "/resources/style.css",
|
| 62 |
+
chapter_base + "/epub-search-index.json.gz",
|
| 63 |
+
):
|
| 64 |
+
self.assertEqual(app.validate_reader_source_url(url), url)
|
| 65 |
+
for url in (
|
| 66 |
+
chapter_base + "/chapters/chapter-1.xhtml",
|
| 67 |
+
chapter_base + "/chapters/chapter-0001.txt",
|
| 68 |
+
chapter_base + "/resources/%2e%2e/secret.png",
|
| 69 |
+
chapter_base + "/other/evil.xhtml",
|
| 70 |
+
chapter_base + "/chapter-manifest.json/extra",
|
| 71 |
+
):
|
| 72 |
+
with self.assertRaises(ValueError):
|
| 73 |
+
app.validate_reader_source_url(url)
|
| 74 |
+
rejected = [
|
| 75 |
+
"https://huggingface.co/datasets/Other/Test/resolve/main/book.pdf",
|
| 76 |
+
"https://huggingface.co/datasets/vomebook/Reader-Assets/resolve/main/reader_assets.json.gz",
|
| 77 |
+
asset + "/extra",
|
| 78 |
+
manifest.replace("page-manifest.json", "pages/page-000001.png"),
|
| 79 |
+
page.replace("page-000001.webp", "page-1.webp"),
|
| 80 |
+
asset + "?download=1",
|
| 81 |
+
asset.replace("/main/", "/dev/"),
|
| 82 |
+
original.replace("%E4%B9%A6.txt", "%2e%2e/secret.txt"),
|
| 83 |
+
]
|
| 84 |
+
for url in rejected:
|
| 85 |
+
with self.assertRaises(ValueError):
|
| 86 |
+
app.validate_reader_source_url(url)
|
| 87 |
+
|
| 88 |
+
def test_archive_name_sanitization_removes_paths_controls_and_limits_length(self):
|
| 89 |
+
self.assertEqual(app.sanitize_archive_name("../../secret\x00\\book.pdf"), "book.pdf")
|
| 90 |
+
self.assertEqual(len(app.sanitize_archive_name("x" * 500)), app.MAX_ARCHIVE_NAME_LENGTH)
|
| 91 |
+
self.assertEqual(app.sanitize_archive_name("../"), "file")
|
| 92 |
+
|
| 93 |
+
def test_txt_path_resolution_stays_inside_txt_directory(self):
|
| 94 |
+
self.assertTrue(str(app.resolve_safe_txt_path("a%2Fb.txt")).endswith("/txt/a/b.txt"))
|
| 95 |
+
for path in ("../secret.txt", "%2e%2e/secret.txt", "..\\secret.txt"):
|
| 96 |
+
with self.assertRaises(ValueError):
|
| 97 |
+
app.resolve_safe_txt_path(path)
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
if __name__ == "__main__":
|
| 101 |
+
unittest.main()
|