80 lines
2.8 KiB
Python
80 lines
2.8 KiB
Python
import asyncio
|
|
import unittest
|
|
from types import SimpleNamespace
|
|
|
|
from fastapi import HTTPException
|
|
|
|
from core.settings import BASE_DIR, settings
|
|
from main import index, resolve_theme_file, theme_asset
|
|
|
|
|
|
class SettingsOverrideMixin:
|
|
def setUp(self):
|
|
self._original_user_config = dict(settings.user_config)
|
|
|
|
def tearDown(self):
|
|
settings.user_config = self._original_user_config
|
|
|
|
|
|
THEMES_BUILT = all((BASE_DIR / f"themes/{year}/assets").is_dir() for year in (2023, 2024))
|
|
|
|
|
|
class ThemeAssetTests(SettingsOverrideMixin, unittest.TestCase):
|
|
def get_theme_index_asset(self, theme: str) -> str:
|
|
assets = sorted((BASE_DIR / theme / "assets").glob("index-*.js"))
|
|
self.assertTrue(assets, f"{theme} 缺少 index JS 资源")
|
|
return assets[0].name
|
|
|
|
@unittest.skipUnless(THEMES_BUILT, "Requires Docker-built themes; verified again inside image")
|
|
def test_resolves_assets_from_current_theme(self):
|
|
settings.themesSelect = "themes/2023"
|
|
theme_2023_asset = resolve_theme_file(
|
|
"assets", self.get_theme_index_asset("themes/2023")
|
|
)
|
|
|
|
settings.themesSelect = "themes/2024"
|
|
theme_2024_asset = resolve_theme_file(
|
|
"assets", self.get_theme_index_asset("themes/2024")
|
|
)
|
|
|
|
self.assertIn("themes/2023/assets", str(theme_2023_asset))
|
|
self.assertIn("themes/2024/assets", str(theme_2024_asset))
|
|
|
|
def test_rejects_theme_asset_path_traversal(self):
|
|
settings.themesSelect = "themes/2024"
|
|
|
|
with self.assertRaises(HTTPException) as error:
|
|
resolve_theme_file("assets", "..", "..", "core", "settings.py")
|
|
|
|
self.assertEqual(error.exception.status_code, 404)
|
|
|
|
def test_theme_asset_returns_404_for_missing_or_traversal_paths(self):
|
|
settings.themesSelect = "themes/2023"
|
|
|
|
for asset_path in ("missing.js", "../../core/settings.py"):
|
|
with self.subTest(asset_path=asset_path):
|
|
with self.assertRaises(HTTPException) as error:
|
|
asyncio.run(theme_asset(asset_path))
|
|
self.assertEqual(error.exception.status_code, 404)
|
|
|
|
response = asyncio.run(
|
|
index(
|
|
request=SimpleNamespace(
|
|
url=SimpleNamespace(path="/theme-assets/missing.js")
|
|
)
|
|
)
|
|
)
|
|
self.assertEqual(response.status_code, 404)
|
|
|
|
@unittest.skipUnless(THEMES_BUILT, "Requires Docker-built themes; verified again inside image")
|
|
def test_index_rewrites_assets_to_theme_specific_urls(self):
|
|
settings.themesSelect = "themes/2023"
|
|
|
|
response = asyncio.run(index())
|
|
html = response.body.decode("utf-8")
|
|
|
|
self.assertIn('src="/theme-assets/', html)
|
|
self.assertIn('href="/theme-assets/', html)
|
|
self.assertNotIn('src="/assets/', html)
|
|
self.assertNotIn('href="/assets/', html)
|