fix: 任务编号改存文件,列表按状态返回并在启动时标记已中断
This commit is contained in:
@@ -1,10 +1,13 @@
|
||||
import csv
|
||||
import json
|
||||
import io
|
||||
import os
|
||||
import threading
|
||||
from pathlib import Path
|
||||
|
||||
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.platform.client import NqiError
|
||||
|
||||
@@ -164,3 +167,295 @@ def _patch_fsync(monkeypatch):
|
||||
|
||||
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")
|
||||
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(job_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(job_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(job_module, "_progress_stats", lambda _directory: (_ 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
|
||||
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
|
||||
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:
|
||||
manager.delete(active.id, files=True)
|
||||
except NqiError as exc:
|
||||
assert "不能删除" in str(exc)
|
||||
else:
|
||||
raise AssertionError("进行中的任务不能删除")
|
||||
assert active.directory.exists()
|
||||
|
||||
|
||||
|
||||
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 test_progress_stats_uses_mtime_cache(tmp_path: Path, monkeypatch):
|
||||
progress = tmp_path / "progress.jsonl"
|
||||
progress.write_bytes(b'{"id": 1, "offset": 3, "rows": 2}\n{"id": 2, "offset": 5, "rows": 1}\n')
|
||||
assert job_module._progress_stats(tmp_path) == (2, 3)
|
||||
|
||||
def fail_open(*_args, **_kwargs):
|
||||
raise AssertionError("缓存命中后不应再读进度")
|
||||
|
||||
monkeypatch.setattr(Path, "open", fail_open)
|
||||
assert job_module._progress_stats(tmp_path) == (2, 3)
|
||||
|
||||
|
||||
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")
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user