test_panel_static.py 2.13 KB
"""后端托管运维面板(/panel)静态资源与 SPA fallback 测试。"""
import pytest
from fastapi.testclient import TestClient

import app.main as main_module


@pytest.fixture
def panel_dist(tmp_path):
    """构造临时 dist 目录并注入 app.main.PANEL_DIST_DIR。"""
    dist = tmp_path / "dist"
    (dist / "assets").mkdir(parents=True)
    (dist / "index.html").write_text("<html><body>panel index</body></html>", encoding="utf-8")
    (dist / "assets" / "app.js").write_text("console.log('app')", encoding="utf-8")

    original = main_module.PANEL_DIST_DIR
    main_module.PANEL_DIST_DIR = dist
    yield dist
    main_module.PANEL_DIST_DIR = original


@pytest.fixture
def client():
    from app.main import app

    return TestClient(app)


def test_panel_root_returns_index(panel_dist, client):
    resp = client.get("/panel")
    assert resp.status_code == 200
    assert "text/html" in resp.headers["content-type"]
    assert "panel index" in resp.text


def test_panel_spa_fallback_returns_index(panel_dist, client):
    resp = client.get("/panel/customer-groups")
    assert resp.status_code == 200
    assert "text/html" in resp.headers["content-type"]
    assert "panel index" in resp.text


def test_panel_deep_route_fallback(panel_dist, client):
    resp = client.get("/panel/customer-groups/123/chat")
    assert resp.status_code == 200
    assert "text/html" in resp.headers["content-type"]
    assert "panel index" in resp.text


def test_panel_assets_returns_file(panel_dist, client):
    resp = client.get("/panel/assets/app.js")
    assert resp.status_code == 200
    assert resp.text == "console.log('app')"
    assert "javascript" in resp.headers["content-type"].lower()


def test_panel_missing_dist_returns_404(client, tmp_path, monkeypatch):
    missing = tmp_path / "no-dist"
    monkeypatch.setattr(main_module, "PANEL_DIST_DIR", missing)
    resp = client.get("/panel")
    assert resp.status_code == 404


def test_panel_path_traversal_not_leak(panel_dist, client):
    resp = client.get("/panel/%2e%2e/app/main.py")
    # 不允许返回越界文件内容(应回退 index.html 或 404)
    assert "Agent Admin" not in resp.text