342 lines
14 KiB
Python
342 lines
14 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(os.environ["DECOM_DATA_DIR"])
|
|
|
|
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_collection_borrows_the_less_used_account(client: TestClient):
|
|
from app.collect.accounts import borrow_account, release_account
|
|
from app.db import session_scope
|
|
from app.models import NqiAccount, utcnow
|
|
|
|
now = utcnow()
|
|
with session_scope() as session:
|
|
session.add(NqiAccount(login_id="busy", credential_valid=True, cookies=[{"name": "a"}], active_tasks=1, task_runs=4, last_task_at=now))
|
|
session.add(NqiAccount(login_id="idle", credential_valid=True, cookies=[{"name": "b"}]))
|
|
session.add(NqiAccount(login_id="dead", credential_valid=False, cookies=[{"name": "c"}]))
|
|
account_id, cookies = borrow_account()
|
|
assert cookies == [{"name": "b"}]
|
|
with session_scope() as session:
|
|
account = session.get(NqiAccount, account_id)
|
|
assert account.login_id == "idle"
|
|
assert account.active_tasks == 1
|
|
assert account.task_runs == 1
|
|
release_account(account_id)
|
|
with session_scope() as session:
|
|
assert session.get(NqiAccount, account_id).active_tasks == 0
|
|
|
|
|
|
def test_borrow_skips_an_account_that_just_failed(client: TestClient):
|
|
from app.collect.accounts import borrow_account, release_account
|
|
from app.db import session_scope
|
|
from app.models import NqiAccount
|
|
|
|
with session_scope() as session:
|
|
session.add(NqiAccount(login_id="first", credential_valid=True, cookies=[{"name": "a"}]))
|
|
session.add(NqiAccount(login_id="second", credential_valid=True, cookies=[{"name": "b"}]))
|
|
first_id, _cookies = borrow_account()
|
|
release_account(first_id, invalid=True)
|
|
second_id, cookies = borrow_account({first_id})
|
|
assert cookies == [{"name": "b"}]
|
|
with session_scope() as session:
|
|
assert session.get(NqiAccount, first_id).credential_valid is False
|
|
assert session.get(NqiAccount, second_id).login_id == "second"
|
|
release_account(second_id)
|
|
|
|
|
|
def test_auth_failure_switches_account():
|
|
from app.collect.accounts import AccountUnavailable
|
|
from app.nqi.client import NqiAuthError
|
|
from app.tasks.runner import _use_account
|
|
|
|
def fail():
|
|
raise NqiAuthError("登录已失效")
|
|
|
|
with pytest.raises(AccountUnavailable) as caught:
|
|
_use_account(fail)
|
|
assert caught.value.invalid is True
|
|
|
|
|
|
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, created_at=now, saved_at=now))
|
|
session.add(NqiAccount(login_id="a2", city_name="深圳", credential_valid=False, session_open=False, created_at=now - timedelta(days=2), 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
|
|
denied_role = client.put("/api/admin/pool/1/role", json={"role": "admin"}, headers=headers)
|
|
assert denied_role.status_code == 405
|
|
|
|
|
|
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())
|