146 lines
7.8 KiB
Python
146 lines
7.8 KiB
Python
"""前端产物托管(React 深链回落)的自检。
|
||
|
||
为什么需要这一组用例:托管路由只在 `SERVE_FRONTEND` 打开时才注册,
|
||
日常自检(含 `tests/` 全部既有用例)跑的是纯 API 模式,这段代码一次都没被执行过。
|
||
而 React Router 用的是 browser history——`/projects/3/storyboard` 刷新一次就打不开的话,
|
||
整站「能进不能刷」,是部署到服务器上才会暴露的事故,所以把判定拆成纯函数后在这里锁死。
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import pytest
|
||
from fastapi import FastAPI, HTTPException
|
||
from fastapi.responses import FileResponse
|
||
from fastapi.testclient import TestClient
|
||
|
||
from app.config import settings
|
||
from app.main import (SPA_ASSET_CACHE, SPA_SHELL_CACHE, spa_assets_app, spa_target)
|
||
|
||
|
||
@pytest.fixture()
|
||
def dist(tmp_path):
|
||
"""一份最小的「构建产物」:index.html + 一个哈希资源 + dist 外的一份敏感文件。"""
|
||
build = tmp_path / "dist"
|
||
(build / "assets").mkdir(parents=True)
|
||
(build / "index.html").write_text("<!doctype html><title>spa</title>", encoding="utf-8")
|
||
(build / "assets" / "index-BRtW2Q.js").write_text("console.log(1)", encoding="utf-8")
|
||
# 交付面用例要一份「真会被压」的文本资源:比 SPA_GZIP_MINIMUM(1024B) 大且高度可压,
|
||
# 模拟 Vite 那个 1 144 kB 的哈希 chunk 的形状。
|
||
(build / "assets" / "vendor-CjO7q3ay.js").write_text("console.log('nex');" * 600, encoding="utf-8")
|
||
# 手册正文搬进 React 后,public/help/ 只剩截图目录:页面本身要回落,图片要直出
|
||
(build / "help").mkdir()
|
||
(build / "help" / "overview.png").write_text("PNG", encoding="utf-8")
|
||
(tmp_path / "secret.txt").write_text("leaked", encoding="utf-8")
|
||
return build
|
||
|
||
|
||
def test_deeplinks_fall_back_to_index(dist, tmp_path):
|
||
"""深链 = 磁盘上没有对应文件 → 必须回 index.html,交给 React Router。"""
|
||
index = dist / "index.html"
|
||
for path in ("", "projects", "projects/3", "projects/3/storyboard", "assets",
|
||
"users", "account", "login", "help"):
|
||
assert spa_target(dist, path) == index, path
|
||
# 目录不是文件:/assets 也只能回落,不能把目录本身当文件发出去
|
||
assert spa_target(dist, "assets") == index
|
||
|
||
|
||
def test_real_build_files_are_served_as_themselves(dist):
|
||
assert spa_target(dist, "assets/index-BRtW2Q.js") == dist / "assets" / "index-BRtW2Q.js"
|
||
assert spa_target(dist, "help/overview.png") == dist / "help" / "overview.png"
|
||
|
||
|
||
def test_missing_asset_falls_back_instead_of_500(dist):
|
||
"""哈希资源在 CDN/旧标签页里对不上时:回壳,别把 FileResponse 的缺文件异常抛给用户。"""
|
||
assert spa_target(dist, "assets/index-STALE00.js") == dist / "index.html"
|
||
|
||
|
||
def test_path_traversal_stays_inside_the_build_dir(dist, tmp_path):
|
||
"""构建目录之外、但磁盘上真实存在的文件,不能被 URL 摸出去。"""
|
||
assert spa_target(dist, "../secret.txt") == dist / "index.html"
|
||
assert spa_target(dist, "assets/../../secret.txt") == dist / "index.html"
|
||
|
||
|
||
def test_unknown_api_path_is_404_not_the_app_shell(dist):
|
||
"""写错的接口路径不能被 history 回落伪装成 200 + HTML。"""
|
||
for path in ("api/nope", "api/library/assets/99999999", "api", "api/"):
|
||
with pytest.raises(HTTPException) as caught:
|
||
spa_target(dist, path)
|
||
assert caught.value.status_code == 404
|
||
assert "接口不存在" in caught.value.detail
|
||
# detail 里只出现一次前缀:/api/nope 不该被写成 /api/api/nope
|
||
with pytest.raises(HTTPException) as caught:
|
||
spa_target(dist, "api/nope")
|
||
assert caught.value.detail == "接口不存在:/api/nope"
|
||
# 只是名字像 api 的页面路由不能被误伤
|
||
assert spa_target(dist, "api-notes") == dist / "index.html"
|
||
|
||
|
||
def test_http_behaviour_matches_the_registered_route(dist):
|
||
"""把同一个判定挂成一个真路由,验 HTTP 层的形状(页面 200 HTML / 接口 404 JSON)。"""
|
||
shell = FastAPI()
|
||
|
||
@shell.get("/{full_path:path}", include_in_schema=False)
|
||
async def spa(full_path: str):
|
||
return FileResponse(spa_target(dist, full_path))
|
||
|
||
client = TestClient(shell)
|
||
page = client.get("/projects/3/timeline")
|
||
assert page.status_code == 200 and "spa" in page.text
|
||
chunk = client.get("/assets/index-BRtW2Q.js")
|
||
assert chunk.status_code == 200 and "javascript" in chunk.headers["content-type"]
|
||
missing = client.get("/api/definitely-not-a-route")
|
||
assert missing.status_code == 404 and "接口不存在" in missing.json()["detail"]
|
||
|
||
|
||
def test_frontend_dist_resolution(monkeypatch, tmp_path, dist):
|
||
"""config 层的三态:关 / 开了但没构建 / 开了且构建过。鉴权中间件问的是同一个问题。"""
|
||
monkeypatch.setattr(settings, "serve_frontend", "off")
|
||
assert settings.frontend_dist() is None
|
||
monkeypatch.setattr(settings, "serve_frontend", "auto")
|
||
monkeypatch.setattr(settings, "frontend_dist_dir", str(tmp_path / "not-built"))
|
||
assert settings.frontend_dist() is None, "没 index.html 的目录不能当 SPA 壳发出去"
|
||
monkeypatch.setattr(settings, "frontend_dist_dir", str(dist))
|
||
assert settings.frontend_dist() == dist
|
||
# 相对路径锚定仓库根,避免「换个目录启动就找不到前端」
|
||
monkeypatch.setattr(settings, "frontend_dist_dir", "frontend/dist")
|
||
resolved = settings.frontend_dist()
|
||
assert resolved is not None and resolved.is_absolute() and resolved.name == "dist"
|
||
|
||
|
||
def test_asset_delivery_cache_and_gzip(dist):
|
||
"""交付面:带哈希的 chunk 长期缓存并 gzip,壳每次回源校验。
|
||
|
||
这条锁的是 Bundle 优化的**另一半**:前面十几轮量的是文件字节(`chunkinfo`),
|
||
但线上真正过网的是这一层的响应头。三条断言各自对应一个会真实发生的事故:
|
||
① 不压 ⇒ 1 144 kB 的 chunk 按 raw 发,量好的 gzip 450 kB 白量;
|
||
② 不给 `index.html` 回源校验 ⇒ 发版后老标签页拿旧壳引已经不存在的哈希文件(白屏);
|
||
③ 反过来给小文件也压 ⇒ 压完加头比原文还大,还多一个 `Vary` 命中率。
|
||
"""
|
||
shell = FastAPI()
|
||
shell.mount("/assets", spa_assets_app(dist))
|
||
|
||
@shell.get("/{full_path:path}", include_in_schema=False)
|
||
async def spa(full_path: str):
|
||
return FileResponse(spa_target(dist, full_path), headers={"Cache-Control": SPA_SHELL_CACHE})
|
||
|
||
client = TestClient(shell)
|
||
big = "/assets/vendor-CjO7q3ay.js"
|
||
gz = client.get(big, headers={"Accept-Encoding": "gzip"})
|
||
assert gz.status_code == 200
|
||
assert gz.headers["cache-control"] == SPA_ASSET_CACHE
|
||
assert gz.headers["content-encoding"] == "gzip"
|
||
assert "accept-encoding" in gz.headers["vary"].lower()
|
||
# httpx 会替我们解回来:解完必须与磁盘上的原文一字不差(压坏了要能在这里抓到)
|
||
assert gz.text == (dist / "assets" / "vendor-CjO7q3ay.js").read_text(encoding="utf-8")
|
||
# 不支持 gzip 的老客户端:原文直出,别留一个骗人的 content-encoding。
|
||
# 必须显式写 identity —— httpx 自己默认就带 `Accept-Encoding: gzip, deflate`,
|
||
# 不写的话这条测的是「中间件压了」而不是「客户端没要」。
|
||
plain = client.get(big, headers={"Accept-Encoding": "identity"})
|
||
assert "content-encoding" not in plain.headers and plain.headers["cache-control"] == SPA_ASSET_CACHE
|
||
assert plain.text == (dist / "assets" / "vendor-CjO7q3ay.js").read_text(encoding="utf-8")
|
||
# 小于阈值的哈希文件不压
|
||
tiny = client.get("/assets/index-BRtW2Q.js", headers={"Accept-Encoding": "gzip"})
|
||
assert "content-encoding" not in tiny.headers
|
||
# 壳与深链:每次回源
|
||
for path in ("/", "/projects/3/storyboard"):
|
||
assert client.get(path).headers["cache-control"] == SPA_SHELL_CACHE
|