fix: 下载接口校验保存路径和设置参数,并支持删除任务
This commit is contained in:
+144
-29
@@ -1,15 +1,19 @@
|
||||
import csv
|
||||
import json
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import threading
|
||||
from pathlib import Path
|
||||
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from app.features.download import jobs as job_module
|
||||
from app.features.download.ids import parse_table
|
||||
from app.features.download.jobs import JobManager, ensure_output_dir
|
||||
from app.features.download.journal import CsvJournal, explain_os_error
|
||||
from app.main import app
|
||||
from app.platform.client import NqiError
|
||||
from app.shared.state import state
|
||||
|
||||
|
||||
def test_progress_recovers_by_streaming_and_truncates_only_a_bad_tail(tmp_path: Path, monkeypatch):
|
||||
@@ -140,34 +144,6 @@ def test_file_errors_use_chinese(tmp_path: Path, monkeypatch):
|
||||
journal.close()
|
||||
|
||||
|
||||
def test_area_table_rules():
|
||||
try:
|
||||
parse_table([["序号", "栅格编码"], ["1", "541927061"]])
|
||||
except ValueError as exc:
|
||||
assert str(exc) == "请把编号列的表头写成 20米栅格ID 或 50米栅格ID"
|
||||
else:
|
||||
raise AssertionError("多列且没有编号列时应拒绝")
|
||||
assert parse_table([["541927061"], ["544536471"]]) == (["541927061", "544536471"], 0)
|
||||
try:
|
||||
parse_table([["20米栅格ID"], ["12"]], "GRID50")
|
||||
except ValueError as exc:
|
||||
assert str(exc) == "表头是20米栅格,与所选的50米不一致"
|
||||
else:
|
||||
raise AssertionError("米数不一致时应拒绝")
|
||||
assert parse_table([["栅格ID", "备注"], ["12", "a"]], "GRID50") == (["12"], 0)
|
||||
|
||||
|
||||
def _patch_fsync(monkeypatch):
|
||||
calls = []
|
||||
original = os.fsync
|
||||
|
||||
def spy(fd):
|
||||
calls.append(fd)
|
||||
return original(fd)
|
||||
|
||||
monkeypatch.setattr("app.features.download.journal.os.fsync", spy)
|
||||
return calls
|
||||
|
||||
def test_ids_file_replaces_grid_ids_and_release_reloads(tmp_path: Path, monkeypatch):
|
||||
monkeypatch.setattr(job_module, "DATA_DIR", tmp_path / "jobs")
|
||||
monkeypatch.setattr(job_module, "DOWNLOAD_ROOT", tmp_path / "downloads")
|
||||
@@ -374,6 +350,114 @@ def test_delete_rejects_active_jobs_and_optional_files(tmp_path: Path, monkeypat
|
||||
assert active.directory.exists()
|
||||
|
||||
|
||||
def test_area_table_rules():
|
||||
try:
|
||||
parse_table([["序号", "栅格编码"], ["1", "541927061"]])
|
||||
except ValueError as exc:
|
||||
assert str(exc) == "请把编号列的表头写成 20米栅格ID 或 50米栅格ID"
|
||||
else:
|
||||
raise AssertionError("多列且没有编号列时应拒绝")
|
||||
assert parse_table([["541927061"], ["544536471"]]) == (["541927061", "544536471"], 0)
|
||||
try:
|
||||
parse_table([["20米栅格ID"], ["12"]], "GRID50")
|
||||
except ValueError as exc:
|
||||
assert str(exc) == "表头是20米栅格,与所选的50米不一致"
|
||||
else:
|
||||
raise AssertionError("米数不一致时应拒绝")
|
||||
assert parse_table([["栅格ID", "备注"], ["12", "a"]], "GRID50") == (["12"], 0)
|
||||
|
||||
|
||||
def test_download_api_paths_settings_and_delete(tmp_path: Path, monkeypatch):
|
||||
jobs = tmp_path / "jobs"
|
||||
downloads = tmp_path / "downloads"
|
||||
monkeypatch.setattr(job_module, "DATA_DIR", jobs)
|
||||
monkeypatch.setattr(job_module, "DOWNLOAD_ROOT", downloads)
|
||||
monkeypatch.setattr(job_module, "SETTINGS_PATH", tmp_path / "settings.json")
|
||||
monkeypatch.setattr("app.features.download.router.DOWNLOAD_ROOT", downloads)
|
||||
manager = JobManager()
|
||||
manager.max_concurrent = 0
|
||||
monkeypatch.setattr(state, "jobs", manager)
|
||||
monkeypatch.setattr(state, "client", _SilentClient())
|
||||
monkeypatch.setattr(state, "user", {"loginId": "a"})
|
||||
monkeypatch.setattr(state, "expired", False)
|
||||
with TestClient(app) as client:
|
||||
meta = client.get("/api/download/meta")
|
||||
assert meta.status_code == 200
|
||||
assert meta.json()["defaultOutputDir"] == str(downloads)
|
||||
|
||||
rejected = client.put("/api/download/settings", json=["nope"])
|
||||
assert rejected.status_code == 400
|
||||
empty = client.put(
|
||||
"/api/download/settings",
|
||||
content=b"null",
|
||||
headers={"Content-Type": "application/json"},
|
||||
)
|
||||
assert empty.status_code == 400
|
||||
updated = client.put("/api/download/settings", json={"maxConcurrentJobs": 3})
|
||||
assert updated.status_code == 200
|
||||
assert updated.json()["maxConcurrentJobs"] == 3
|
||||
state.jobs.max_concurrent = 0
|
||||
|
||||
relative = _post_job(client, output_dir="relative\\save")
|
||||
assert relative.status_code == 400
|
||||
assert "绝对路径" in relative.json()["detail"]
|
||||
|
||||
blocked = tmp_path / "not-a-folder"
|
||||
blocked.write_text("x", encoding="utf-8")
|
||||
denied = _post_job(client, output_dir=str(blocked))
|
||||
assert denied.status_code == 400
|
||||
assert denied.json()["detail"]
|
||||
|
||||
created = _post_job(client, output_dir="")
|
||||
assert created.status_code == 200
|
||||
body = created.json()
|
||||
assert body["csvPath"].startswith(str(downloads / body["id"]))
|
||||
assert (downloads / body["id"]).is_dir()
|
||||
|
||||
chosen = tmp_path / "chosen"
|
||||
area = _post_job(
|
||||
client,
|
||||
output_dir=str(chosen),
|
||||
filename="area.csv",
|
||||
content="20米栅格ID\n541927061\n544536471\n541927061\n".encode("utf-8-sig"),
|
||||
)
|
||||
assert area.status_code == 200
|
||||
saved = area.json()
|
||||
assert Path(saved["csvPath"]).parent == chosen / saved["id"]
|
||||
ids = (jobs / saved["id"] / "ids.txt").read_text(encoding="utf-8").splitlines()
|
||||
assert ids == ["541927061", "544536471"]
|
||||
record = json.loads((jobs / saved["id"] / "job.json").read_text(encoding="utf-8"))
|
||||
assert record["gridCount"] == 2
|
||||
assert "gridIds" not in record
|
||||
|
||||
mismatch = _post_job(
|
||||
client,
|
||||
output_dir=str(chosen),
|
||||
grid_size="GRID50",
|
||||
filename="bad.csv",
|
||||
content="20米栅格ID\n12\n".encode("utf-8"),
|
||||
)
|
||||
assert mismatch.status_code == 400
|
||||
assert mismatch.json()["detail"] == "表头是20米栅格,与所选的50米不一致"
|
||||
|
||||
missing = _post_job(
|
||||
client,
|
||||
output_dir=str(chosen),
|
||||
filename="cols.csv",
|
||||
content="序号,栅格编码\n1,12\n".encode("utf-8"),
|
||||
)
|
||||
assert missing.status_code == 400
|
||||
assert missing.json()["detail"] == "请把编号列的表头写成 20米栅格ID 或 50米栅格ID"
|
||||
assert {path.name for path in jobs.iterdir()} == {body["id"], saved["id"]}
|
||||
assert {path.name for path in chosen.iterdir() if path.is_dir()} == {saved["id"]}
|
||||
|
||||
removed = client.delete(f"/api/download/jobs/{saved['id']}?files=true")
|
||||
assert removed.status_code == 200
|
||||
assert removed.json()["ok"] is True
|
||||
assert not (jobs / saved["id"]).exists()
|
||||
assert not (chosen / saved["id"]).exists()
|
||||
assert client.delete(f"/api/download/jobs/{saved['id']}").status_code == 404
|
||||
|
||||
|
||||
def test_output_dir_permission_message(tmp_path: Path, monkeypatch):
|
||||
real_open = Path.open
|
||||
@@ -428,6 +512,22 @@ def test_progress_stats_uses_mtime_cache(tmp_path: Path, monkeypatch):
|
||||
assert job_module._progress_stats(tmp_path) == (2, 3)
|
||||
|
||||
|
||||
def _post_job(client: TestClient, *, output_dir: str, filename: str | None = None, content: bytes | None = None, grid_size: str = "GRID20"):
|
||||
data = {
|
||||
"network": "NR",
|
||||
"city_code": "JM",
|
||||
"month": "2026-09",
|
||||
"groups": "[]",
|
||||
"concurrency": "1",
|
||||
"output_dir": output_dir,
|
||||
"grid_size": grid_size,
|
||||
}
|
||||
files = None
|
||||
if filename is not None:
|
||||
files = {"file": (filename, content or b"", "text/csv")}
|
||||
return client.post("/api/download/jobs", data=data, files=files)
|
||||
|
||||
|
||||
def _write_record(directory: Path, **overrides) -> None:
|
||||
directory.mkdir(parents=True, exist_ok=True)
|
||||
payload = {
|
||||
@@ -459,3 +559,18 @@ def _write_record(directory: Path, **overrides) -> None:
|
||||
(directory / "job.json").write_text(json.dumps(payload, ensure_ascii=False), encoding="utf-8")
|
||||
|
||||
|
||||
class _SilentClient:
|
||||
async def aclose(self):
|
||||
return None
|
||||
|
||||
|
||||
def _patch_fsync(monkeypatch):
|
||||
calls = []
|
||||
original = os.fsync
|
||||
|
||||
def spy(fd):
|
||||
calls.append(fd)
|
||||
return original(fd)
|
||||
|
||||
monkeypatch.setattr("app.features.download.journal.os.fsync", spy)
|
||||
return calls
|
||||
|
||||
Reference in New Issue
Block a user