from __future__ import annotations import os import time from pathlib import Path import pytest from fastapi.testclient import TestClient os.environ["DECOM_DATABASE_URL"] = "sqlite+pysqlite:///" + (Path(__file__).resolve().parents[1] / "data" / "test.db").as_posix() os.environ["DECOM_INLINE_WORKER"] = "1" os.environ["DECOM_ADMIN_USERNAME"] = "admin" os.environ["DECOM_ADMIN_PASSWORD"] = "admin-pass" os.environ["DECOM_JWT_SECRET"] = "test-secret" 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_period # noqa: E402 PUBLIC_KEY = ( "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCwjDm1HXDw8QH5ZtGMQIl2h/I8E+" "chOQA8aQ8xCR/+aHnROaN/ZU5Vmd2Zz7g6cAacR9BSm60+iSCYtvEGJKl0WqvbPGJkc8tedjNF1QqgWqkkuE6Udgw2OkEKJCxDg6PrAniR7Cc0io9G8bW4P8JDJjSbbafvMPDDFbVVUWJxxwIDAQAB" ) @pytest.fixture() def client(): database = Path(os.environ["DECOM_DATABASE_URL"].removeprefix("sqlite+pysqlite:///")) if database.exists(): database.unlink() reset_engine() application = create_app() with TestClient(application) as test_client: yield test_client reset_engine() if database.exists(): database.unlink() 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")