Files
DecomEval/backend/tests/test_core.py
T

289 lines
12 KiB
Python

from __future__ import annotations
import asyncio
import os
import shutil
import time
from pathlib import Path
import pytest
from fastapi.testclient import TestClient
TEST_DATA = Path(__file__).resolve().parents[1] / "data" / "pytest"
os.environ["DECOM_DATA_DIR"] = str(TEST_DATA)
os.environ["DECOM_ALLOW_SQLITE"] = "1"
from app.collect.io import parse_csv, write_csv # noqa: E402
from app.db import reset_engine # noqa: E402
from app.main import create_app # noqa: E402
from app.nqi.client import needs_captcha, rsa_encrypt # noqa: E402
from app.tasks.runner import check_concurrency, check_period # noqa: E402
PUBLIC_KEY = (
"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCwjDm1HXDw8QH5ZtGMQIl2h/I8E+"
"chOQA8aQ8xCR/+aHnROaN/ZU5Vmd2Zz7g6cAacR9BSm60+iSCYtvEGJKl0WqvbPGJkc8tedjNF1QqgWqkkuE6Udgw2OkEKJCxDg6PrAniR7Cc0io9G8bW4P8JDJjSbbafvMPDDFbVVUWJxxwIDAQAB"
)
@pytest.fixture()
def client():
if TEST_DATA.exists():
shutil.rmtree(TEST_DATA)
reset_engine()
application = create_app()
with TestClient(application) as test_client:
created = test_client.post(
"/api/install",
json={"sqlite": True, "adminUsername": "admin", "adminPassword": "admin-pass"},
)
assert created.status_code == 200
yield test_client
reset_engine()
if TEST_DATA.exists():
shutil.rmtree(TEST_DATA)
def test_install_again_uses_existing_database(client: TestClient):
from app.config import install_file
from app.db import reset_engine
install_file().unlink()
reset_engine()
again = client.post("/api/install", json={"sqlite": True, "adminUsername": "other", "adminPassword": "other-pass"})
assert again.status_code == 200
assert again.json()["already"] is True
logged = client.post("/api/auth/local", json={"username": "admin", "password": "admin-pass"})
assert logged.status_code == 200
rejected = client.post("/api/auth/local", json={"username": "other", "password": "other-pass"})
assert rejected.status_code == 400
def test_period_bounds():
assert check_period(1) == 1
assert check_period(31) == 31
with pytest.raises(ValueError):
check_period(0)
with pytest.raises(ValueError):
check_period(32)
def test_csv_roundtrip_and_gbk():
content = "小区,时间,拆除前\nGZ-1,2026-01-02 03:04:05,-91\n".encode("gbk")
rows = parse_csv(content)
assert rows[0]["cell_key"] == "GZ-1"
assert rows[0]["metrics"]["拆除前"] == "-91"
text = write_csv(rows).decode("utf-8-sig")
assert "GZ-1" in text
def test_needs_captcha_ignores_sms():
assert needs_captcha("图形验证码错误") is True
assert needs_captcha("短信验证码错误") is False
rsa_encrypt(PUBLIC_KEY, "user")
def test_local_login_task_and_admin(client: TestClient):
denied = client.post("/api/auth/local", json={"username": "admin", "password": "wrong"})
assert denied.status_code == 400
logged = client.post("/api/auth/local", json={"username": "admin", "password": "admin-pass"})
assert logged.status_code == 200
token = logged.json()["token"]
headers = {"Authorization": f"Bearer {token}"}
blocked = client.get("/api/tasks", headers=headers)
assert blocked.status_code == 403
created = client.post("/api/admin/users", json={"username": "user", "password": "user-pass", "role": "user"}, headers=headers)
assert created.status_code == 200
user = client.post("/api/auth/local", json={"username": "user", "password": "user-pass"})
user_headers = {"Authorization": f"Bearer {user.json()['token']}"}
task = client.post("/api/tasks", json={"format": "csv", "cellKey": ""}, headers=user_headers)
assert task.status_code == 200
assert task.json()["task"]["status"] == "queued"
task_id = task.json()["task"]["id"]
for _ in range(20):
listing = client.get("/api/tasks", headers=user_headers).json()["tasks"]
if listing[0]["status"] == "done":
break
time.sleep(0.1)
assert listing[0]["status"] == "done"
downloaded = client.get(f"/api/tasks/{task_id}/file", headers=user_headers)
assert downloaded.status_code == 200
assert "小区" in downloaded.content.decode("utf-8-sig")
def test_admin_is_judged_locally_when_users_use_nqi(client: TestClient, monkeypatch):
from app.nqi.client import NqiError
logged = client.post("/api/auth/local", json={"username": "admin", "password": "admin-pass"})
headers = {"Authorization": f"Bearer {logged.json()['token']}"}
client.post("/api/admin/users", json={"username": "user", "password": "user-pass", "role": "user"}, headers=headers)
saved = client.put(
"/api/admin/settings",
json={"loginMode": "nqi", "credentialRefreshSeconds": 300, "workerConcurrency": 4},
headers=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)
wrong = client.post("/api/auth/login", json={"username": "admin", "password": "wrong", "sessionId": "captcha-session", "captcha": "abcd"})
assert wrong.status_code == 400
assert wrong.json()["detail"] == "登录失败"
ok = client.post("/api/auth/login", json={"username": "admin", "password": "admin-pass", "sessionId": "captcha-session", "captcha": "abcd"})
assert ok.status_code == 200
assert ok.json()["user"]["role"] == "admin"
assert calls == []
other = client.post("/api/auth/login", json={"username": "user", "password": "user-pass"})
assert other.status_code == 400
assert other.json()["detail"] == "不应访问平台"
assert calls == ["open"]
def test_platform_login_failure_refreshes_captcha(client: TestClient, monkeypatch):
from app.nqi.client import LoginChallenge, NqiError
logged = client.post("/api/auth/local", json={"username": "admin", "password": "admin-pass"})
headers = {"Authorization": f"Bearer {logged.json()['token']}"}
saved = client.put(
"/api/admin/settings",
json={"loginMode": "nqi", "credentialRefreshSeconds": 300, "workerConcurrency": 4},
headers=headers,
)
assert saved.status_code == 200
async def open_login(self):
return LoginChallenge(execution="exec", public_key=PUBLIC_KEY, captcha_png=b"old", page_url="https://nqi.example/login")
async def prepare_login(self, challenge, username, password, captcha):
raise NqiError("认证失败2!")
async def refresh_captcha(self, challenge):
challenge.captcha_png = b"new"
challenge.captcha_type = "image/png"
return b"new"
monkeypatch.setattr("app.api.http.NqiClient.open_login", open_login)
monkeypatch.setattr("app.api.http.NqiClient.prepare_login", prepare_login)
monkeypatch.setattr("app.api.http.NqiClient.refresh_captcha", refresh_captcha)
started = client.post("/api/auth/nqi/start", json={"purpose": "login"})
assert started.status_code == 200
failed = client.post(
"/api/auth/login",
json={"username": "platform-user", "password": "secret", "captcha": "abcd", "sessionId": started.json()["sessionId"]},
)
assert failed.status_code == 200
body = failed.json()
assert body["status"] == "need_captcha"
assert body["message"] == "认证失败2!"
assert body["captcha"].startswith("data:image/png;base64,")
def test_pool_add_is_allowed_when_login_is_local(client: TestClient, monkeypatch):
from app.nqi.client import NqiError
async def fail_open(self):
raise NqiError("未连接平台")
monkeypatch.setattr("app.api.http.NqiClient.open_login", fail_open)
blocked = client.post("/api/auth/nqi/start", json={"username": "someone"})
assert blocked.status_code == 400
assert blocked.json()["detail"] == "当前使用自有账号登录"
pool = client.post("/api/auth/nqi/start", json={"username": "someone", "purpose": "pool"})
assert pool.status_code == 400
assert pool.json()["detail"] == "未连接平台"
def test_concurrency_bounds():
assert check_concurrency(1) == 1
assert check_concurrency(32) == 32
with pytest.raises(ValueError):
check_concurrency(0)
with pytest.raises(ValueError):
check_concurrency(33)
def test_admin_dashboard_and_user_password(client: TestClient):
from datetime import timedelta
from app.db import session_scope
from app.models import NqiAccount, utcnow
logged = client.post("/api/auth/local", json={"username": "admin", "password": "admin-pass"})
headers = {"Authorization": f"Bearer {logged.json()['token']}"}
admin_id = logged.json()["user"]["id"]
client.post("/api/admin/users", json={"username": "user", "password": "user-pass", "role": "user"}, headers=headers)
client.post("/api/admin/users", json={"username": "boss", "password": "boss-pass", "role": "admin"}, headers=headers)
rows = client.get("/api/admin/users", headers=headers).json()["users"]
user_id = next(row["id"] for row in rows if row["username"] == "user")
other_id = next(row["id"] for row in rows if row["username"] == "boss")
denied = client.put(f"/api/admin/users/{other_id}/password", json={"password": "hacked"}, headers=headers)
assert denied.status_code == 400
changed = client.put(f"/api/admin/users/{user_id}/password", json={"password": "new-user-pass"}, headers=headers)
assert changed.status_code == 200
assert client.post("/api/auth/local", json={"username": "user", "password": "new-user-pass"}).status_code == 200
self_ok = client.put(f"/api/admin/users/{admin_id}/password", json={"password": "admin-pass-2"}, headers=headers)
assert self_ok.status_code == 200
empty = client.get("/api/admin/dashboard", headers=headers)
assert empty.status_code == 200
assert empty.json()["pool"]["total"] == 0
now = utcnow()
with session_scope() as session:
session.add(NqiAccount(login_id="a1", city_name="广州", credential_valid=True, session_open=True, saved_at=now))
session.add(NqiAccount(login_id="a2", city_name="深圳", credential_valid=False, session_open=False, saved_at=now - timedelta(days=2)))
stats = client.get("/api/admin/dashboard", headers=headers).json()["pool"]
assert stats["total"] == 2
assert stats["valid"] == 1
assert stats["invalid"] == 1
assert stats["addedToday"] == 1
assert stats["addedWeek"] == 2
assert stats["sessionOpen"] == 1
def test_admin_can_set_concurrency(client: TestClient):
logged = client.post("/api/auth/local", json={"username": "admin", "password": "admin-pass"})
headers = {"Authorization": f"Bearer {logged.json()['token']}"}
current = client.get("/api/admin/settings", headers=headers)
assert current.json()["workerConcurrency"] == 4
saved = client.put(
"/api/admin/settings",
json={"loginMode": "local", "credentialRefreshSeconds": 300, "workerConcurrency": 8},
headers=headers,
)
assert saved.status_code == 200
assert saved.json()["workerConcurrency"] == 8
rejected = client.put(
"/api/admin/settings",
json={"loginMode": "local", "credentialRefreshSeconds": 300, "workerConcurrency": 0},
headers=headers,
)
assert rejected.status_code == 400
def test_dynamic_gate_shrinks_after_running_tasks_finish():
from app.tasks.queue import DynamicGate
async def scenario() -> None:
gate = DynamicGate(1)
await gate.acquire()
waiting = asyncio.create_task(gate.acquire())
await asyncio.sleep(0.05)
assert not waiting.done()
gate.set_limit(2)
await asyncio.wait_for(waiting, timeout=1)
assert gate.held == 2
gate.set_limit(1)
blocked = asyncio.create_task(gate.acquire())
await asyncio.sleep(0.05)
assert not blocked.done()
gate.release()
await asyncio.sleep(0.05)
assert not blocked.done()
gate.release()
await asyncio.wait_for(blocked, timeout=1)
assert gate.held == 1
asyncio.run(scenario())