"""Vue 接口测试。不启动真实出图,不打开 Grid 大文件。""" import importlib.util import json from pathlib import Path import tempfile import unittest from unittest.mock import patch from toolbox import tasks from toolbox.tasks import ROOT FASTAPI_READY = importlib.util.find_spec("fastapi") is not None and importlib.util.find_spec("httpx") is not None def _stamp(path): if not path.exists(): return None stat = path.stat() return (stat.st_mtime_ns, stat.st_size) @unittest.skipUnless(FASTAPI_READY, "未安装 FastAPI,跳过 Vue 接口测试") class WebApiTests(unittest.TestCase): def setUp(self): from fastapi.testclient import TestClient from api.app import CONNECTION_FILE, app self.connection_file = CONNECTION_FILE self.real_connection = _stamp(ROOT / "output" / "toolbox" / "nr_connection.json") self.temp = tempfile.TemporaryDirectory(prefix="webapi_") self.root = Path(self.temp.name) self.addCleanup(self.temp.cleanup) self.tasks_patch = patch("toolbox.tasks.TASKS", self.root / "tasks") self.connection_patch = patch("api.app.CONNECTION_FILE", self.root / "nr_connection.json") self.tasks_patch.start() self.connection_patch.start() self.addCleanup(self.tasks_patch.stop) self.addCleanup(self.connection_patch.stop) self.client = TestClient(app) self.addCleanup(self.client.close) def tearDown(self): self.assertEqual(_stamp(ROOT / "output" / "toolbox" / "nr_connection.json"), self.real_connection) def add_task(self, name, files): folder = tasks.TASKS / name results = folder / "results" results.mkdir(parents=True) for filename, payload in files.items(): (results / filename).write_bytes(payload) tasks.write_json(folder / "state.json", { "id": name, "kind": "market", "status": "success", "created": 1700000000, "output": str(results), "directory": str(folder), "params": {"COOKIES": "should-not-appear", "MAX_WORKERS": 4}, "done": 1, "total": 2, "message": "处理完成", }) return results def test_list_tasks(self): marker = b"UNIQUE-BYTES-NOT-IN-TASK-LIST" self.add_task("done-1", {"成果.zip": marker}) with patch.object(Path, "read_bytes", side_effect=AssertionError("不应整文件读入")): response = self.client.get("/api/tasks") self.assertEqual(response.status_code, 200) self.assertNotIn(marker, response.content) self.assertNotIn("should-not-appear", response.text) body = response.json() self.assertEqual(len(body["tasks"]), 1) task = body["tasks"][0] self.assertEqual(task["id"], "done-1") self.assertEqual(task["status_label"], "已完成") self.assertEqual(task["params"], {"MAX_WORKERS": 4}) self.assertNotIn("content", task) cleared = self.client.post("/api/tasks/clear") self.assertEqual(cleared.status_code, 200) self.assertEqual(cleared.json()["deleted"], 1) self.assertFalse((tasks.TASKS / "done-1").exists()) def test_start_validation_failure(self): market = { "kind": "market", "params": { "MARKET_GPKG": str(self.root / "missing.gpkg"), "GRID_5G_GPKG": str(self.root / "missing-grid.gpkg"), "GRID_4G_GPKG": str(self.root / "missing-grid4.gpkg"), "BUILDING_INFO_GPKG": str(self.root / "missing-building.gpkg"), "AOI_CSV": str(self.root / "missing.csv"), "GIS_PROJECT_SOURCE": str(self.root / "missing.qgz"), "NR_BUILDINGS_DATA_CSV": str(self.root / "missing-nr.csv"), "SELECTED_MARKET_IDS": [1], "MAX_WORKERS": 4, "SCALE": 5, "SUMMARY_OUTPUT_ENABLED": True, "MAX_RASTER_PIXELS": 25_000_000, "SUMMARY_MAX_RASTER_PIXELS": 100_000_000, "CLIP_MODE": "intersects", "PROJECT_EXTENT_PADDING_RATIO": 0.05, }, } buildings = { "kind": "buildings", "params": { "INPUT_CSV": str(self.root / "missing.csv"), "INPUT_ENCODING": "gbk", "START_ROW": 0, "LIMIT": 1, "CONCURRENCY": 1, "TIMEOUT": 5, "MAX_RETRIES": 0, "REQUEST_INTERVAL": 0, }, "credentials": { "URL": "http://127.0.0.1/wfs", "COOKIES": "private-cookie-should-not-leak", "REFERER": "", }, } with patch("marketgrid.nrdata.build_gpkg", side_effect=AssertionError("不应整理楼宇")), \ patch("api.app.tasks.start_task", side_effect=AssertionError("不应启动任务")): market_response = self.client.post("/api/tasks", json=market) buildings_response = self.client.post("/api/tasks", json=buildings) self.assertEqual(market_response.status_code, 400) self.assertIn("不存在", market_response.json()["detail"]) self.assertEqual(buildings_response.status_code, 400) self.assertIn("起始行", buildings_response.json()["detail"]) self.assertNotIn("private-cookie-should-not-leak", buildings_response.text) self.assertFalse((self.root / "nr_connection.json").exists()) self.assertFalse(tasks.TASKS.exists() and any(tasks.TASKS.glob("*/state.json"))) def test_building_credentials_stay_out_of_task_response(self): source = self.root / "楼宇轮廓.csv" source.write_text("WKT,building_id\n", encoding="gbk") cookie = "private-cookie-should-not-leak" with patch("api.app.tasks.start_task", return_value="task-1") as start: response = self.client.post("/api/tasks", json={ "kind": "buildings", "params": { "INPUT_CSV": str(source), "INPUT_ENCODING": "gbk", "START_ROW": 1, "LIMIT": 1, "CONCURRENCY": 1, "TIMEOUT": 5, "MAX_RETRIES": 0, "REQUEST_INTERVAL": 0, }, "credentials": {"URL": "http://127.0.0.1/wfs", "COOKIES": cookie, "REFERER": ""}, }) self.assertEqual(response.status_code, 200) self.assertEqual(response.json(), {"id": "task-1"}) self.assertNotIn(cookie, response.text) kind, params, credentials = start.call_args.args self.assertEqual(kind, "buildings") self.assertNotIn("COOKIES", params) self.assertNotIn("URL", params) self.assertEqual(credentials["COOKIES"], cookie) saved = json.loads((self.root / "nr_connection.json").read_text(encoding="utf-8")) self.assertEqual(saved["COOKIES"], cookie) self.assertNotIn(cookie, json.dumps(params, ensure_ascii=False)) def test_result_list_and_download_do_not_inline_file(self): small = "成果内容".encode() large = b"UNIQUE-BYTES-NOT-IN-JSON" self.add_task("pack-1", {"成果.zip": small, "large.bin": large}) with patch("api.app.MAX_INLINE_DOWNLOAD", len(small)), \ patch.object(Path, "read_bytes", side_effect=AssertionError("不应整文件读入")): listed = self.client.get("/api/results/pack-1/files") downloaded = self.client.get("/api/results/pack-1/files/" + "成果.zip") refused = self.client.get("/api/results/pack-1/files/large.bin") self.assertEqual(listed.status_code, 200) self.assertNotIn(large, listed.content) self.assertNotIn(small, listed.content) files = {item["name"]: item for item in listed.json()["files"]} self.assertEqual(set(files), {"成果.zip", "large.bin"}) self.assertFalse(files["成果.zip"]["too_large"]) self.assertTrue(files["large.bin"]["too_large"]) self.assertNotIn("content", files["成果.zip"]) self.assertEqual(downloaded.status_code, 200) self.assertEqual(downloaded.content, small) self.assertIn("filename*=UTF-8''", downloaded.headers["content-disposition"]) self.assertEqual(refused.status_code, 413) self.assertNotIn(large, refused.content) self.assertIn("本地目录", refused.json()["detail"])