|
| 1 | +"""Unit tests for static asset cache-busting. |
| 2 | +
|
| 3 | +Two mechanisms work together: |
| 4 | +- a content-hash version token (``asset_v``, sha256 of every file under |
| 5 | + ``src/web/static`` truncated to 8 hex chars) injected into the Jinja |
| 6 | + template globals, so rendered pages reference ``/static/...?v=<token>`` |
| 7 | + and any static file change busts intermediary/browser caches; |
| 8 | +- ``Cache-Control: no-cache`` on every ``/static/`` response, so caches |
| 9 | + always revalidate (ETag still yields 304 and saves bandwidth -- this is |
| 10 | + revalidation, not no-store). |
| 11 | +
|
| 12 | +All console output must be pure English (no emoji, no Chinese), per |
| 13 | +project testing conventions. |
| 14 | +""" |
| 15 | + |
| 16 | +from pathlib import Path |
| 17 | + |
| 18 | +import pytest |
| 19 | +from fastapi.testclient import TestClient |
| 20 | + |
| 21 | +from video_transcript_api.api.context import ( |
| 22 | + compute_asset_version, |
| 23 | + get_static_dir, |
| 24 | + get_templates, |
| 25 | +) |
| 26 | + |
| 27 | + |
| 28 | +def _write(path: Path, content: str) -> None: |
| 29 | + path.parent.mkdir(parents=True, exist_ok=True) |
| 30 | + path.write_text(content, encoding="utf-8") |
| 31 | + |
| 32 | + |
| 33 | +def _minimal_llm_config() -> dict: |
| 34 | + """Smallest llm section satisfying LLMConfig.from_dict's hard keys; |
| 35 | + base_url points at a closed local port so nothing reaches the network.""" |
| 36 | + return { |
| 37 | + "api_key": "test-llm-key", |
| 38 | + "base_url": "http://127.0.0.1:1/v1", |
| 39 | + "calibrate_model": "test-calibrate-model", |
| 40 | + "summary_model": "test-summary-model", |
| 41 | + } |
| 42 | + |
| 43 | + |
| 44 | +def _minimal_config(tmp_path: Path) -> dict: |
| 45 | + return { |
| 46 | + "api": {"host": "127.0.0.1", "port": 8000, "auth_token": "test-token"}, |
| 47 | + "concurrent": {"max_workers": 1, "queue_size": 2, "llm_max_workers": 1}, |
| 48 | + "storage": { |
| 49 | + "cache_dir": str(tmp_path / "cache"), |
| 50 | + "workspace_dir": str(tmp_path / "workspace"), |
| 51 | + "temp_dir": str(tmp_path / "temp"), |
| 52 | + "audit_db": str(tmp_path / "audit.db"), |
| 53 | + }, |
| 54 | + "web": {"base_url": "http://localhost:8000"}, |
| 55 | + "llm": _minimal_llm_config(), |
| 56 | + "log": {"file": str(tmp_path / "app.log")}, |
| 57 | + } |
| 58 | + |
| 59 | + |
| 60 | +def _render_transcript(**overrides) -> str: |
| 61 | + """Render transcript.html through the app's own Jinja2Templates so the |
| 62 | + asset_v global injected by get_templates() is in scope.""" |
| 63 | + ctx = { |
| 64 | + "title": "Sample Video Title", |
| 65 | + "author": "Sample Author", |
| 66 | + "url": "https://example.com/video/123", |
| 67 | + "created_at_display": "2026-07-11 10:00", |
| 68 | + "platform": "youtube", |
| 69 | + "summary_html": "<p>Summary body.</p>", |
| 70 | + "calibrated_html": "<p>Calibrated body.</p>", |
| 71 | + "use_speaker_recognition": False, |
| 72 | + "view_token": "test-view-token-123", |
| 73 | + "stats": { |
| 74 | + "original_length": 100, |
| 75 | + "calibrated_length": 90, |
| 76 | + "summary_length": 50, |
| 77 | + }, |
| 78 | + "llm_config": None, |
| 79 | + } |
| 80 | + ctx.update(overrides) |
| 81 | + return get_templates().env.get_template("transcript.html").render(**ctx) |
| 82 | + |
| 83 | + |
| 84 | +class TestComputeAssetVersion: |
| 85 | + def test_token_is_short_lowercase_hex(self, tmp_path): |
| 86 | + _write(tmp_path / "js" / "app.js", "console.log(1)") |
| 87 | + token = compute_asset_version(tmp_path) |
| 88 | + assert len(token) == 8 |
| 89 | + assert all(c in "0123456789abcdef" for c in token) |
| 90 | + |
| 91 | + def test_token_stable_when_content_unchanged(self, tmp_path): |
| 92 | + """Same files -> same token, so unchanged assets keep their cache.""" |
| 93 | + _write(tmp_path / "js" / "app.js", "alpha") |
| 94 | + _write(tmp_path / "css" / "site.css", "body {}") |
| 95 | + assert compute_asset_version(tmp_path) == compute_asset_version(tmp_path) |
| 96 | + |
| 97 | + def test_token_changes_when_file_content_changes(self, tmp_path): |
| 98 | + _write(tmp_path / "js" / "app.js", "alpha") |
| 99 | + before = compute_asset_version(tmp_path) |
| 100 | + _write(tmp_path / "js" / "app.js", "alpha-modified") |
| 101 | + assert compute_asset_version(tmp_path) != before |
| 102 | + |
| 103 | + def test_token_changes_when_file_added(self, tmp_path): |
| 104 | + _write(tmp_path / "js" / "app.js", "alpha") |
| 105 | + before = compute_asset_version(tmp_path) |
| 106 | + _write(tmp_path / "js" / "extra.js", "beta") |
| 107 | + assert compute_asset_version(tmp_path) != before |
| 108 | + |
| 109 | + def test_missing_directory_yields_stable_hex_token(self, tmp_path): |
| 110 | + token = compute_asset_version(tmp_path / "does-not-exist") |
| 111 | + assert len(token) == 8 |
| 112 | + assert token == compute_asset_version(tmp_path / "does-not-exist") |
| 113 | + |
| 114 | + |
| 115 | +class TestTemplateAssetVersioning: |
| 116 | + def test_templates_env_exposes_asset_v_global(self): |
| 117 | + token = get_templates().env.globals.get("asset_v") |
| 118 | + assert isinstance(token, str) |
| 119 | + assert token == compute_asset_version(get_static_dir()) |
| 120 | + |
| 121 | + def test_transcript_page_versions_floating_toc_assets(self): |
| 122 | + html = _render_transcript() |
| 123 | + token = compute_asset_version(get_static_dir()) |
| 124 | + assert f'href="/static/css/floating-toc.css?v={token}"' in html |
| 125 | + assert f'src="/static/js/floating-toc.js?v={token}"' in html |
| 126 | + |
| 127 | + def test_transcript_page_has_no_unversioned_static_asset_refs(self): |
| 128 | + """Every /static/ css/js reference in the rendered page must carry |
| 129 | + the version query parameter.""" |
| 130 | + html = _render_transcript() |
| 131 | + assert 'href="/static/css/floating-toc.css"' not in html |
| 132 | + assert 'src="/static/js/floating-toc.js"' not in html |
| 133 | + |
| 134 | + def test_base_template_versions_history_page_link(self): |
| 135 | + """history.html suffers the same intermediary-cache disease; its |
| 136 | + link is versioned with the same token.""" |
| 137 | + html = _render_transcript() |
| 138 | + assert '/static/history.html?v=' in html |
| 139 | + |
| 140 | + |
| 141 | +class TestStaticNoCacheHeader: |
| 142 | + @pytest.fixture |
| 143 | + def client(self, tmp_path): |
| 144 | + from video_transcript_api.api.app import create_app |
| 145 | + |
| 146 | + config = _minimal_config(tmp_path) |
| 147 | + app = create_app(config_loader=lambda: config, start_background=False) |
| 148 | + with TestClient(app) as test_client: |
| 149 | + yield test_client |
| 150 | + |
| 151 | + def test_static_js_response_has_no_cache_header(self, client): |
| 152 | + resp = client.get("/static/js/floating-toc.js") |
| 153 | + assert resp.status_code == 200 |
| 154 | + assert resp.headers["Cache-Control"] == "no-cache" |
| 155 | + |
| 156 | + def test_static_css_response_has_no_cache_header(self, client): |
| 157 | + resp = client.get("/static/css/floating-toc.css") |
| 158 | + assert resp.status_code == 200 |
| 159 | + assert resp.headers["Cache-Control"] == "no-cache" |
| 160 | + |
| 161 | + def test_static_304_response_keeps_no_cache_header(self, client): |
| 162 | + """ETag revalidation must still save bandwidth (304) and the 304 |
| 163 | + response itself must carry no-cache so caches keep revalidating.""" |
| 164 | + first = client.get("/static/js/floating-toc.js") |
| 165 | + etag = first.headers.get("ETag") |
| 166 | + assert etag |
| 167 | + second = client.get( |
| 168 | + "/static/js/floating-toc.js", headers={"If-None-Match": etag} |
| 169 | + ) |
| 170 | + assert second.status_code == 304 |
| 171 | + assert second.headers["Cache-Control"] == "no-cache" |
0 commit comments