import asyncio import csv 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.shared import files as files_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): csv_path = tmp_path / "out.csv" progress = tmp_path / "progress.jsonl" journal = CsvJournal(csv_path, progress, ["栅格", "小区"]) journal.open() assert journal.write_rows("1", [["1", "a"], ["1", "b"]]) == 2 assert journal.write_rows("2", [["2", ""]]) == 1 journal.close() assert all(isinstance(item, int) for item in journal.completed) good_progress = progress.read_bytes() with progress.open("ab") as handle: handle.write(b"{bad\n") with csv_path.open("ab") as handle: handle.write("垃圾,数据\r\n".encode("utf-8")) def fail_read_text(*_args, **_kwargs): raise AssertionError("恢复进度不应整份读入") monkeypatch.setattr(Path, "read_text", fail_read_text) journal.open() monkeypatch.undo() assert progress.read_bytes() == good_progress assert "垃圾" not in csv_path.read_text(encoding="utf-8") assert 1 in journal.completed and "1" in journal.completed assert journal.write_rows("1", [["1", "again"]]) == 0 journal.close() body = list(csv.reader(io.StringIO(csv_path.read_text(encoding="utf-8-sig")))) assert body == [["栅格", "小区"], ["1", "a"], ["1", "b"], ["2", ""]] def test_clean_progress_is_not_rewritten(tmp_path: Path, monkeypatch): csv_path = tmp_path / "out.csv" progress = tmp_path / "progress.jsonl" journal = CsvJournal(csv_path, progress, ["栅格"]) journal.open() journal.write_rows("9", [["9"]]) journal.close() before = progress.read_bytes() calls = _patch_fsync(monkeypatch) journal.open() journal.close() assert progress.read_bytes() == before assert calls == [] def test_commit_many_fsyncs_once_per_batch_and_keeps_progress_open(tmp_path: Path, monkeypatch): journal = CsvJournal(tmp_path / "out.csv", tmp_path / "progress.jsonl", ["栅格"]) journal.open() handle = journal._progress calls = _patch_fsync(monkeypatch) written = journal.commit_many( [ ("1", [["1"], ["1"]]), ("1", [["1"]]), ("2", [["2"]]), ] ) assert written == 3 assert calls == [journal._file.fileno(), handle.fileno()] assert journal._progress is handle assert handle.closed is False calls.clear() assert journal.commit_many([("1", [["1"]])]) == 0 assert calls == [] try: journal.commit_many([("3", [])]) except ValueError as exc: assert "至少要写出一行" in str(exc) else: raise AssertionError("空行应该拒绝") journal.close() rows = list(csv.reader(io.StringIO((tmp_path / "out.csv").read_text(encoding="utf-8-sig")))) assert rows == [["栅格"], ["1"], ["1"], ["2"]] def test_commit_many_is_thread_safe(tmp_path: Path): journal = CsvJournal(tmp_path / "out.csv", tmp_path / "progress.jsonl", ["组", "序号", "内容"]) journal.open() def write_group(name: str) -> None: items = [(f"{name}-{index}", [[name, str(index), "甲" * 20]]) for index in range(20)] journal.commit_many(items) threads = [threading.Thread(target=write_group, args=(name,)) for name in ("甲", "乙")] for thread in threads: thread.start() for thread in threads: thread.join() journal.close() rows = list(csv.reader(io.StringIO((tmp_path / "out.csv").read_text(encoding="utf-8-sig")))) assert len(rows) == 41 assert all(len(row) == 3 for row in rows) assert {row[0] for row in rows[1:]} == {"甲", "乙"} def test_file_errors_use_chinese(tmp_path: Path, monkeypatch): busy = OSError("busy") busy.winerror = 32 locked = OSError("locked") locked.winerror = 33 full = OSError("full") full.winerror = 112 full_errno = OSError("full") full_errno.errno = 28 denied = OSError("denied") denied.winerror = 5 assert explain_os_error(busy) == "文件被占用,请先关闭 Excel 等程序" assert explain_os_error(denied) == "文件被拒绝访问" assert explain_os_error(locked) == "文件被占用,请先关闭 Excel 等程序" assert explain_os_error(full) == "磁盘空间不足" assert explain_os_error(full_errno) == "磁盘空间不足" journal = CsvJournal(tmp_path / "out.csv", tmp_path / "progress.jsonl", ["栅格"]) journal.open() def deny(_fd): error = PermissionError(13, "busy") error.winerror = 32 raise error monkeypatch.setattr("app.features.download.journal.os.fsync", deny) try: journal.write_rows("1", [["1"]]) except NqiError as exc: assert str(exc) == "文件被占用,请先关闭 Excel 等程序" else: raise AssertionError("占用文件时应给出中文") journal.close() 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") manager = JobManager() output = tmp_path / "save" / "栅格.csv" job = manager.create( network="NR", city_code="JM", city_name="江门", month="2026-09", groups=["rsrp"], concurrency=2, grid_ids=["7", "8"], csv_path=output, grid_size="GRID20", whole_city=False, ) stored = json.loads((job.directory / "job.json").read_text(encoding="utf-8")) assert "gridIds" not in stored assert stored["gridCount"] == 2 assert (job.directory / "ids.txt").read_text(encoding="utf-8").splitlines() == ["7", "8"] assert job.csv_path == tmp_path / "save" / job.id / "栅格.csv" job.paused_by = "expired" job.stopping = True job.failed_tiles = [{"west": 1}] job.status = "done" job.save() assert job.grid_ids == [] loaded = JobManager()._load(job.id) assert loaded.paused_by == "expired" assert loaded.stopping is True assert loaded.failed_tiles == [{"west": 1}] assert loaded.snapshot()["pausedBy"] == "expired" assert loaded.snapshot()["stopping"] is True assert loaded.snapshot()["failedTiles"] == [{"west": 1}] assert loaded.snapshot()["total"] == 2 assert loaded.load_ids() == ["7", "8"] other = manager.create( network="LTE", city_code="JM", city_name="江门", month="2026-09", groups=["rsrp"], concurrency=1, grid_ids=["9"], csv_path=output, whole_city=False, ) other.status = "cancelled" other.message = "已停止" other.save() assert other.grid_ids == [] assert manager.get(other.id).grid_ids == ["9"] def test_save_retries_permission_error_and_corrupt_record(tmp_path: Path, monkeypatch): monkeypatch.setattr(job_module, "DATA_DIR", tmp_path / "jobs") monkeypatch.setattr(job_module, "DOWNLOAD_ROOT", tmp_path / "downloads") monkeypatch.setattr(files_module.time, "sleep", lambda _seconds: None) job = JobManager().create( network="NR", city_code="JM", city_name="江门", month="2026-09", groups=["rsrp"], concurrency=1, grid_ids=["1"], csv_path=tmp_path / "a.csv", whole_city=False, ) real = os.replace calls = {"n": 0} def flaky(src, dst): calls["n"] += 1 if calls["n"] < 3: error = PermissionError(13, "busy", str(dst)) error.winerror = 32 raise error return real(src, dst) monkeypatch.setattr(files_module.os, "replace", flaky) job.message = "仍在" job.save() assert calls["n"] == 3 assert json.loads((job.directory / "job.json").read_text(encoding="utf-8"))["message"] == "仍在" assert list(job.directory.glob("*.tmp")) == [] (job.directory / "job.json").write_text("{", encoding="utf-8") try: JobManager()._load(job.id) except NqiError as exc: assert str(exc) == "任务记录损坏" else: raise AssertionError("损坏的任务记录应被拒绝") def test_startup_marks_leftover_jobs_interrupted_and_list_skips_progress(tmp_path: Path, monkeypatch): jobs = tmp_path / "jobs" monkeypatch.setattr(job_module, "DATA_DIR", jobs) monkeypatch.setattr( CsvJournal, "_scan_progress", lambda *_args: (_ for _ in ()).throw(AssertionError("不应读取进度")), ) for index, status in enumerate(("running", "paused", "queued"), start=1): _write_record( jobs / f"2026010101010{index}", status=status, message="下载中", createdAt=f"2026-01-0{index}T00:00:00", completed=index, writtenRows=index * 2, ) (jobs / f"2026010101010{index}" / "progress.jsonl").write_text( '{"id": 1, "offset": 1, "rows": 99}\n' * 20, encoding="utf-8", ) for index in range(60): _write_record( jobs / f"202602{index:08d}", status="done", message="已完成", createdAt=f"2026-02-01T00:00:{index:02d}", completed=1, writtenRows=1, ) reloaded = JobManager()._load("20260101010102") assert reloaded.status == "cancelled" assert reloaded.message == "已中断" items = JobManager().list_jobs() unfinished = [item for item in items if item["status"] != "done"] finished = [item for item in items if item["status"] == "done"] assert len(unfinished) == 3 assert len(finished) == 50 assert {item["message"] for item in unfinished} == {"已中断"} assert {item["status"] for item in unfinished} == {"cancelled"} assert {item["writtenRows"] for item in unfinished} == {2, 4, 6} assert [item["completed"] for item in sorted(unfinished, key=lambda item: item["id"])] == [1, 2, 3] assert finished[0]["createdAt"] >= finished[-1]["createdAt"] stored = json.loads((jobs / "20260101010101" / "job.json").read_text(encoding="utf-8")) assert stored["status"] == "cancelled" assert stored["message"] == "已中断" def test_delete_rejects_active_jobs_and_optional_files(tmp_path: Path, monkeypatch): monkeypatch.setattr(job_module, "DATA_DIR", tmp_path / "jobs") monkeypatch.setattr(job_module, "DOWNLOAD_ROOT", tmp_path / "downloads") manager = JobManager() kept = manager.create( network="NR", city_code="JM", city_name="江门", month="2026-09", groups=["rsrp"], concurrency=1, grid_ids=["1"], csv_path=None, whole_city=True, ) download_dir = kept.csv_path.parent assert download_dir == tmp_path / "downloads" / kept.id asyncio.run(manager.delete(kept.id, files=False)) assert not kept.directory.exists() assert download_dir.exists() removed = manager.create( network="NR", city_code="JM", city_name="江门", month="2026-09", groups=["rsrp"], concurrency=1, grid_ids=["1"], csv_path=None, whole_city=True, ) removed_dir = removed.csv_path.parent asyncio.run(manager.delete(removed.id, files=True)) assert not removed.directory.exists() assert not removed_dir.exists() active = manager.create( network="NR", city_code="JM", city_name="江门", month="2026-09", groups=["rsrp"], concurrency=1, grid_ids=["1"], csv_path=None, whole_city=True, ) class Alive: def done(self): return False active.task = Alive() active.status = "running" try: asyncio.run(manager.delete(active.id, files=True)) except NqiError as exc: assert "不能删除" in str(exc) else: raise AssertionError("进行中的任务不能删除") 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, base_url="http://127.0.0.1") 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 def deny(self, *args, **kwargs): if self.name.startswith(".nqi-write-"): error = PermissionError(13, "busy") error.winerror = 33 raise error return real_open(self, *args, **kwargs) monkeypatch.setattr(Path, "open", deny) try: ensure_output_dir(tmp_path) except NqiError as exc: assert str(exc) == "文件被占用,请先关闭 Excel 等程序" else: raise AssertionError("不可写目录应返回中文") def test_legacy_grid_ids_can_still_be_loaded(tmp_path: Path, monkeypatch): monkeypatch.setattr(job_module, "DATA_DIR", tmp_path / "jobs") directory = tmp_path / "jobs" / "20260101010101" _write_record( directory, status="done", message="已完成", createdAt="2026-01-01T00:00:00", completed=2, writtenRows=2, ) path = directory / "job.json" data = json.loads(path.read_text(encoding="utf-8")) del data["gridCount"] data["gridIds"] = ["3", "4"] path.write_text(json.dumps(data), encoding="utf-8") loaded = JobManager()._load("20260101010101") assert loaded.id_count == 2 assert loaded.load_ids() == ["3", "4"] assert (directory / "ids.txt").read_text(encoding="utf-8").splitlines() == ["3", "4"] 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 = { "id": directory.name, "network": "NR", "cityCode": "JM", "cityName": "江门", "month": "2026-09", "groups": ["rsrp"], "concurrency": 2, "gridCount": 3, "wholeCity": False, "discovered": 0, "listingDone": True, "csvPath": str(directory / "out.csv"), "createdAt": "2026-09-21T12:00:09", "status": "done", "message": "已完成", "completed": 3, "failed": 0, "writtenRows": 4, "duplicateCount": 0, "failures": [], "pausedBy": "", "stopping": False, "failedTiles": [], } payload.update(overrides) (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