每个逻辑站点一个排队任务,与采集共用并行数量;工参按拆除前后规则取本系统快照,指标暂用模拟数据;全部站点结束后写频段清退、低效拆除两份结果表。去掉原来的通用导出任务。
365 lines
17 KiB
Python
365 lines
17 KiB
Python
from __future__ import annotations
|
|
|
|
import os
|
|
import shutil
|
|
import time
|
|
from pathlib import Path
|
|
from urllib.parse import quote
|
|
|
|
import pytest
|
|
from fastapi.testclient import TestClient
|
|
|
|
TEST_DATA = Path(os.environ["DECOM_DATA_DIR"])
|
|
|
|
from sqlalchemy import select # noqa: E402
|
|
|
|
from app.auth.platform import base_href, platform_identity # noqa: E402
|
|
from app.db import reset_engine, session_scope # noqa: E402
|
|
from app.main import create_app # noqa: E402
|
|
|
|
TOKEN = "proxy-token-for-tests"
|
|
INDEX = '<!DOCTYPE html>\n<html>\n <head>\n <base href="/" />\n <title>DecomEval</title>\n </head>\n <body><script type="module" src="./assets/app.js"></script></body>\n</html>\n'
|
|
|
|
|
|
def identity(role: str, user_id: str = "u-1", username: str = "zhang", display: str = "张三", token: str = TOKEN) -> dict:
|
|
return {
|
|
"X-Metrix-Proxy-Token": token,
|
|
"X-Forwarded-Prefix": "/apps/decomeval",
|
|
"X-Metrix-User-Id": user_id,
|
|
"X-Metrix-Username": username,
|
|
"X-Metrix-Display-Name": quote(display, encoding="utf-8"),
|
|
"X-Metrix-App-Role": role,
|
|
}
|
|
|
|
|
|
def bearer(token: str, headers: dict | None = None) -> dict:
|
|
return {**(headers or {}), "Authorization": f"Bearer {token}"}
|
|
|
|
|
|
@pytest.fixture()
|
|
def web_dist() -> Path:
|
|
dist = TEST_DATA.parent / "web-dist"
|
|
if dist.exists():
|
|
shutil.rmtree(dist)
|
|
(dist / "assets").mkdir(parents=True)
|
|
(dist / "index.html").write_text(INDEX, encoding="utf-8")
|
|
(dist / "assets" / "app.js").write_text("console.log(1)", encoding="utf-8")
|
|
(dist / "favicon.svg").write_text("<svg/>", encoding="utf-8")
|
|
yield dist
|
|
shutil.rmtree(dist, ignore_errors=True)
|
|
|
|
|
|
@pytest.fixture()
|
|
def hosted(monkeypatch, web_dist: Path):
|
|
if TEST_DATA.exists():
|
|
shutil.rmtree(TEST_DATA)
|
|
monkeypatch.setenv("METRIX_APP_PROXY_TOKEN", TOKEN)
|
|
monkeypatch.setattr("app.install.hosted_database_url", lambda: f"sqlite+pysqlite:///{(TEST_DATA / 'decom.db').as_posix()}")
|
|
reset_engine()
|
|
with TestClient(create_app(web_dist=web_dist)) as test_client:
|
|
yield test_client
|
|
reset_engine()
|
|
if TEST_DATA.exists():
|
|
shutil.rmtree(TEST_DATA)
|
|
|
|
|
|
def admin_token(client: TestClient) -> str:
|
|
response = client.post("/api/auth/platform", headers=identity("admin", user_id="a-1", username="boss", display="管理员甲"))
|
|
assert response.status_code == 200
|
|
return response.json()["token"]
|
|
|
|
|
|
def test_config_falls_back_to_metrix_env(monkeypatch):
|
|
from app.config import data_dir, env_database, env_database_complete, hosted
|
|
|
|
monkeypatch.delenv("DECOM_DATA_DIR")
|
|
monkeypatch.setenv("METRIX_APP_DATA_DIR", "/data")
|
|
assert data_dir() == Path("/data")
|
|
monkeypatch.setenv("DECOM_DATA_DIR", "/var/lib/decom")
|
|
assert data_dir() == Path("/var/lib/decom")
|
|
|
|
assert env_database_complete() is False
|
|
monkeypatch.setenv("METRIX_PG_HOST", "postgres")
|
|
monkeypatch.setenv("METRIX_PG_PORT", "5432")
|
|
monkeypatch.setenv("METRIX_PG_DATABASE", "app_db")
|
|
monkeypatch.setenv("METRIX_PG_USER", "app_user")
|
|
monkeypatch.setenv("METRIX_PG_PASSWORD", "pg-pass")
|
|
assert env_database() == {"host": "postgres", "port": 5432, "database": "app_db", "username": "app_user", "password": "pg-pass"}
|
|
assert env_database_complete() is True
|
|
monkeypatch.setenv("DECOM_DB_HOST", "db.local")
|
|
monkeypatch.setenv("DECOM_DB_NAME", "decom")
|
|
assert env_database()["host"] == "db.local"
|
|
assert env_database()["database"] == "decom"
|
|
assert env_database()["username"] == "app_user"
|
|
|
|
for name in ("DECOM_DB_HOST", "DECOM_DB_NAME", "METRIX_PG_HOST", "METRIX_PG_PORT", "METRIX_PG_DATABASE", "METRIX_PG_USER", "METRIX_PG_PASSWORD"):
|
|
monkeypatch.delenv(name)
|
|
monkeypatch.setenv("METRIX_PG_URL", "postgresql://url_user:url%40pass@pg.example:6543/url_db")
|
|
assert env_database() == {"host": "pg.example", "port": 6543, "database": "url_db", "username": "url_user", "password": "url@pass"}
|
|
|
|
assert hosted() is False
|
|
monkeypatch.setenv("METRIX_APP_PROXY_TOKEN", " ")
|
|
assert hosted() is False
|
|
monkeypatch.setenv("METRIX_APP_PROXY_TOKEN", TOKEN)
|
|
assert hosted() is True
|
|
|
|
|
|
def test_identity_needs_matching_proxy_token(monkeypatch):
|
|
headers = {key.lower(): value for key, value in identity("admin").items()}
|
|
assert platform_identity(headers) is None
|
|
monkeypatch.setenv("METRIX_APP_PROXY_TOKEN", TOKEN)
|
|
found = platform_identity(headers)
|
|
assert found is not None
|
|
assert (found.user_id, found.username, found.display_name, found.role) == ("u-1", "zhang", "张三", "admin")
|
|
assert found.name == "张三"
|
|
assert platform_identity({**headers, "x-metrix-proxy-token": "wrong"}) is None
|
|
assert platform_identity({key: value for key, value in headers.items() if key != "x-metrix-proxy-token"}) is None
|
|
assert platform_identity({**headers, "x-metrix-app-role": "owner"}) is None
|
|
assert platform_identity({**headers, "x-metrix-user-id": ""}) is None
|
|
no_display = platform_identity({**headers, "x-metrix-display-name": ""})
|
|
assert no_display is not None and no_display.name == "zhang"
|
|
chinese_username = platform_identity({**headers, "x-metrix-username": quote("李四", encoding="utf-8"), "x-metrix-display-name": ""})
|
|
assert chinese_username is not None and chinese_username.name == "李四"
|
|
|
|
|
|
def test_base_href_only_accepts_app_prefix():
|
|
assert base_href({"x-forwarded-prefix": "/apps/decomeval"}) == "/apps/decomeval/"
|
|
assert base_href({"x-forwarded-prefix": "/apps/decom-eval-2"}) == "/apps/decom-eval-2/"
|
|
assert base_href({}) == "/"
|
|
for bad in ("/apps/DecomEval", "/apps/decomeval/", "/evil", "//evil.example", "/apps/a\"><script>", "/apps/"):
|
|
assert base_href({"x-forwarded-prefix": bad}) == "/"
|
|
|
|
|
|
def test_auto_install_on_start(hosted: TestClient):
|
|
from app.install import auto_install
|
|
from app.models import AppSetting, User
|
|
|
|
status = hosted.get("/api/install/status").json()
|
|
assert status["installed"] is True
|
|
assert status["hosted"] is True
|
|
assert hosted.get("/api/auth/mode").json() == {"mode": "local", "hosted": True}
|
|
with session_scope() as session:
|
|
setting = session.get(AppSetting, 1)
|
|
secret = setting.jwt_secret
|
|
assert len(secret) == 64
|
|
assert session.query(User).count() == 0
|
|
assert auto_install() is True
|
|
with session_scope() as session:
|
|
assert session.get(AppSetting, 1).jwt_secret == secret
|
|
assert session.query(AppSetting).count() == 1
|
|
|
|
|
|
def test_auto_install_skipped_without_database(monkeypatch):
|
|
from app.install import auto_install
|
|
|
|
monkeypatch.setenv("METRIX_APP_PROXY_TOKEN", TOKEN)
|
|
assert auto_install() is False
|
|
monkeypatch.delenv("METRIX_APP_PROXY_TOKEN")
|
|
monkeypatch.setattr("app.install.hosted_database_url", lambda: "sqlite+pysqlite:///never.db")
|
|
assert auto_install() is False
|
|
|
|
|
|
def test_platform_login_three_cases(hosted: TestClient):
|
|
admin = hosted.post("/api/auth/platform", headers=identity("admin", user_id="a-1", username="boss", display="管理员甲"))
|
|
assert admin.status_code == 200
|
|
assert admin.json()["user"] == {"kind": "platform", "id": "a-1", "role": "admin", "name": "管理员甲"}
|
|
|
|
user = hosted.post("/api/auth/platform", headers=identity("user"))
|
|
assert user.status_code == 403
|
|
assert user.json()["detail"] == "请从应用托管进入管理"
|
|
|
|
saved = hosted.put(
|
|
"/api/admin/settings",
|
|
json={"loginMode": "nqi", "credentialRefreshSeconds": 300, "workerConcurrency": 4},
|
|
headers=bearer(admin.json()["token"], identity("admin", user_id="a-1", username="boss", display="管理员甲")),
|
|
)
|
|
assert saved.status_code == 200
|
|
refused = hosted.post("/api/auth/platform", headers=identity("user"))
|
|
assert refused.status_code == 403
|
|
assert refused.json()["detail"] == "请从应用托管进入管理"
|
|
still_admin = hosted.post("/api/auth/platform", headers=identity("admin", user_id="a-1"))
|
|
assert still_admin.status_code == 200
|
|
|
|
nobody = hosted.post("/api/auth/platform", headers={"X-Metrix-Proxy-Token": TOKEN})
|
|
assert nobody.status_code == 401
|
|
forged = hosted.post("/api/auth/platform", headers=identity("admin", token="forged"))
|
|
assert forged.status_code == 401
|
|
bare = hosted.post("/api/auth/platform")
|
|
assert bare.status_code == 401
|
|
|
|
|
|
def test_platform_login_refused_when_not_hosted(web_dist: Path):
|
|
if TEST_DATA.exists():
|
|
shutil.rmtree(TEST_DATA)
|
|
reset_engine()
|
|
with TestClient(create_app(web_dist=web_dist)) as client:
|
|
assert client.post("/api/install", json={"sqlite": True, "adminUsername": "admin", "adminPassword": "admin-pass"}).status_code == 200
|
|
assert client.get("/api/install/status").json()["hosted"] is False
|
|
refused = client.post("/api/auth/platform", headers=identity("admin"))
|
|
assert refused.status_code == 401
|
|
local = client.post("/api/auth/local", json={"username": "admin", "password": "admin-pass"})
|
|
assert local.status_code == 200
|
|
reset_engine()
|
|
shutil.rmtree(TEST_DATA, ignore_errors=True)
|
|
|
|
|
|
def test_local_password_login_closed_when_hosted(hosted: TestClient):
|
|
from app.models import User
|
|
from app.security import hash_password
|
|
|
|
with session_scope() as session:
|
|
session.add(User(username="admin", password_hash=hash_password("admin-pass"), role="admin"))
|
|
session.add(User(username="worker", password_hash=hash_password("worker-pass"), role="user"))
|
|
for path in ("/api/auth/local", "/api/auth/login"):
|
|
blocked = hosted.post(path, json={"username": "admin", "password": "admin-pass"})
|
|
assert blocked.status_code == 400
|
|
assert blocked.json()["detail"] == "账号或密码不正确"
|
|
allowed = hosted.post("/api/auth/login", json={"username": "worker", "password": "worker-pass"})
|
|
assert allowed.status_code == 200
|
|
assert allowed.json()["user"]["role"] == "user"
|
|
|
|
admin_headers = identity("admin", user_id="a-1", username="boss", display="管理员甲")
|
|
headers = bearer(admin_token(hosted), admin_headers)
|
|
listed = hosted.get("/api/admin/users", headers=headers)
|
|
assert listed.status_code == 200
|
|
created = hosted.post("/api/admin/users", json={"username": "new", "password": "new-pass", "role": "admin"}, headers=headers)
|
|
assert created.status_code == 200
|
|
with session_scope() as session:
|
|
created_user = session.scalar(select(User).where(User.username == "new"))
|
|
assert created_user is not None and created_user.role == "user"
|
|
|
|
|
|
def test_nqi_admin_name_goes_to_platform_when_hosted(hosted: TestClient, monkeypatch):
|
|
from app.models import User
|
|
from app.nqi.client import NqiError
|
|
from app.security import hash_password
|
|
|
|
with session_scope() as session:
|
|
session.add(User(username="admin", password_hash=hash_password("admin-pass"), role="admin"))
|
|
admin_headers = identity("admin", user_id="a-1", username="boss", display="管理员甲")
|
|
saved = hosted.put(
|
|
"/api/admin/settings",
|
|
json={"loginMode": "nqi"},
|
|
headers=bearer(admin_token(hosted), admin_headers),
|
|
)
|
|
assert saved.status_code == 200
|
|
calls: list[str] = []
|
|
|
|
async def fail_open(self):
|
|
calls.append("open")
|
|
raise NqiError("未连接平台")
|
|
|
|
monkeypatch.setattr("app.api.http.NqiClient.open_login", fail_open)
|
|
response = hosted.post("/api/auth/login", json={"username": "admin", "password": "admin-pass"})
|
|
assert response.status_code == 400
|
|
assert response.json()["detail"] == "未连接平台"
|
|
assert calls == ["open"]
|
|
|
|
|
|
def test_platform_token_follows_platform_login(hosted: TestClient):
|
|
admin_headers = identity("admin", user_id="a-1", username="boss", display="管理员甲")
|
|
token = admin_token(hosted)
|
|
me = hosted.get("/api/me", headers=bearer(token, admin_headers))
|
|
assert me.status_code == 200
|
|
assert me.json()["user"]["kind"] == "platform"
|
|
assert hosted.get("/api/me", headers=bearer(token)).status_code == 401
|
|
assert hosted.get("/api/me", headers=bearer(token, identity("admin", user_id="someone-else"))).status_code == 401
|
|
assert hosted.get("/api/me", headers=bearer(token, identity("user", user_id="a-1"))).status_code == 401
|
|
assert hosted.get("/api/me", headers=bearer(token, {**admin_headers, "X-Metrix-Proxy-Token": "forged"})).status_code == 401
|
|
|
|
|
|
def test_switch_to_local_needs_no_local_admin_when_hosted(hosted: TestClient):
|
|
admin_headers = identity("admin", user_id="a-1", username="boss", display="管理员甲")
|
|
headers = bearer(admin_token(hosted), admin_headers)
|
|
assert hosted.put("/api/admin/settings", json={"loginMode": "nqi"}, headers=headers).status_code == 200
|
|
back = hosted.put("/api/admin/settings", json={"loginMode": "local"}, headers=headers)
|
|
assert back.status_code == 200
|
|
assert back.json()["loginMode"] == "local"
|
|
|
|
|
|
def test_local_user_runs_evaluation(hosted: TestClient, monkeypatch):
|
|
from app.models import EvalJob, User
|
|
from app.security import hash_password
|
|
|
|
monkeypatch.setenv("DECOM_EVAL_SOURCE", "mock")
|
|
with session_scope() as session:
|
|
session.add(User(username="worker", password_hash=hash_password("worker-pass"), role="user"))
|
|
session.add(User(username="other", password_hash=hash_password("other-pass"), role="user"))
|
|
login = hosted.post("/api/auth/login", json={"username": "worker", "password": "worker-pass"})
|
|
headers = bearer(login.json()["token"])
|
|
body = {"orderType": "频段清退", "removalDate": "2026-10-01", "city": "江门", "cells": [{"cgi": "460-00-8001-1", "cellName": "某站F-ZLH-1"}]}
|
|
created = hosted.post("/api/eval/jobs/single", json=body, headers=headers)
|
|
assert created.status_code == 200
|
|
job_id = created.json()["job"]["id"]
|
|
detail = {}
|
|
for _ in range(50):
|
|
detail = hosted.get(f"/api/eval/jobs/{job_id}", headers=headers).json()
|
|
if detail["job"]["status"] in ("done", "partial", "failed"):
|
|
break
|
|
time.sleep(0.1)
|
|
assert detail["job"]["status"] == "done"
|
|
with session_scope() as session:
|
|
job = session.get(EvalJob, job_id)
|
|
owner = session.scalar(select(User).where(User.username == "worker"))
|
|
assert (job.owner_kind, job.owner_id) == ("local", str(owner.id))
|
|
downloaded = hosted.get(f"/api/eval/jobs/{job_id}/files/pinduan", headers=headers)
|
|
assert downloaded.status_code == 200
|
|
other_login = hosted.post("/api/auth/login", json={"username": "other", "password": "other-pass"})
|
|
other = bearer(other_login.json()["token"])
|
|
assert hosted.get(f"/api/eval/jobs/{job_id}/files/pinduan", headers=other).status_code == 404
|
|
assert hosted.get(f"/api/eval/jobs/{job_id}", headers=other).status_code == 404
|
|
admin_headers = identity("admin", user_id="a-1")
|
|
assert hosted.get("/api/eval/jobs", headers=bearer(admin_token(hosted), admin_headers)).status_code == 403
|
|
|
|
|
|
def test_index_gets_base_for_prefix(hosted: TestClient):
|
|
proxied = hosted.get("/", headers={"X-Forwarded-Prefix": "/apps/decomeval"})
|
|
assert proxied.status_code == 200
|
|
assert '<base href="/apps/decomeval/" />' in proxied.text
|
|
assert proxied.text.count("<base") == 1
|
|
assert proxied.headers["cache-control"] == "no-store"
|
|
deep = hosted.get("/admin/users", headers={"X-Forwarded-Prefix": "/apps/decomeval"})
|
|
assert '<base href="/apps/decomeval/" />' in deep.text
|
|
direct = hosted.get("/tasks")
|
|
assert '<base href="/" />' in direct.text
|
|
evil = hosted.get("/", headers={"X-Forwarded-Prefix": "//evil.example"})
|
|
assert '<base href="/" />' in evil.text
|
|
named = hosted.get("/index.html", headers={"X-Forwarded-Prefix": "/apps/decomeval"})
|
|
assert '<base href="/apps/decomeval/" />' in named.text
|
|
asset = hosted.get("/assets/app.js")
|
|
assert asset.status_code == 200
|
|
assert asset.text == "console.log(1)"
|
|
assert hosted.get("/favicon.svg").text == "<svg/>"
|
|
assert hosted.get("/api/unknown").status_code == 404
|
|
|
|
|
|
def test_index_without_base_tag_gets_one():
|
|
from app.main import render_index
|
|
|
|
html = render_index("<html><head><title>x</title></head></html>", "/apps/decomeval/")
|
|
assert html.startswith('<html><head>\n <base href="/apps/decomeval/" />')
|
|
|
|
|
|
def test_queue_defer_uses_independent_sync_connection(monkeypatch):
|
|
import contextlib
|
|
from app.tasks import queue as task_queue
|
|
|
|
calls: list[tuple[str, object]] = []
|
|
|
|
class Deferrer:
|
|
def defer(self, **kwargs):
|
|
calls.append(("defer", kwargs))
|
|
|
|
monkeypatch.setattr(task_queue.defer_queue, "open", lambda: contextlib.nullcontext())
|
|
|
|
def configure(name: str, **kwargs):
|
|
calls.append(("configure", (name, kwargs)))
|
|
return Deferrer()
|
|
|
|
monkeypatch.setattr(task_queue.defer_queue, "configure_task", configure)
|
|
task_queue.defer("decom_export", task_id=7)
|
|
assert calls == [
|
|
("configure", ("decom_export", {"queue": "decom"})),
|
|
("defer", {"task_id": 7}),
|
|
]
|