Files

418 lines
14 KiB
Python

"""并发、重入和文件竞争。每个用例对应一种会让任务出错或漏数据的时序。"""
from __future__ import annotations
import asyncio
import csv
import io
import json
import os
import shutil
import threading
import time
from pathlib import Path
import pytest
from app.features.download import jobs as job_module
from app.features.download.jobs import JobManager, run_download
from app.features.download.journal import CsvJournal
from app.platform.client import NqiError, NqiNetworkError
from app.shared import files as files_module
from app.shared.state import state
@pytest.fixture
def places(tmp_path: Path, monkeypatch) -> Path:
monkeypatch.setattr(job_module, "DATA_DIR", tmp_path / "jobs")
monkeypatch.setattr(job_module, "DOWNLOAD_ROOT", tmp_path / "downloads")
monkeypatch.setattr(job_module, "SETTINGS_PATH", tmp_path / "settings.json")
return tmp_path
@pytest.fixture
def manager(places: Path, monkeypatch) -> JobManager:
current = JobManager()
monkeypatch.setattr(state, "jobs", current)
monkeypatch.setattr(state, "user", {"loginId": "tester"})
monkeypatch.setattr(state, "expired", False)
return current
class FakeClient:
"""按网络返回各自的编号;每个栅格写出一行空数据。"""
def __init__(self, ids: dict[str, list[str]] | None = None, *, delay: float = 0.0) -> None:
self.ids = ids or {}
self.delay = delay
self.fetched: list[str] = []
self.on_fetch = None
async def layer_code(self, *, network, **_kwargs):
return {"serviceCode": network, "originRelatedField": "grid20_id"}
async def iter_grid_ids(
self,
service_code,
_id_field,
cancel_event,
progress,
_skip=None,
run_event=None,
halt_event=None,
*,
seen=None,
**_kwargs,
):
seen = set() if seen is None else seen
ids = self.ids[service_code]
def halted() -> bool:
return cancel_event.is_set() or (halt_event is not None and halt_event.is_set())
for start in range(0, len(ids), 40):
fresh = [item for item in ids[start : start + 40] if int(item) not in seen]
await progress(len(seen) + len(fresh))
for grid_id in fresh:
while run_event is not None and not run_event.is_set():
if halted():
return
await asyncio.sleep(0.005)
if halted():
return
seen.add(int(grid_id))
yield grid_id
await asyncio.sleep(0)
async def grid_feature(self, _service, grid_id, _field):
if self.delay:
await asyncio.sleep(self.delay)
self.fetched.append(grid_id)
if self.on_fetch is not None:
await self.on_fetch(grid_id)
return {"grid20_id": grid_id}
async def cell_rows(self, *_args):
return []
async def aclose(self):
return None
def _create(manager: JobManager, network: str = "NR", *, whole_city: bool = True, grid_ids=None, concurrency: int = 4):
return manager.create(
network=network,
city_code="JM",
city_name="江门",
month="2026-09",
groups=["rsrp"],
concurrency=concurrency,
grid_ids=list(grid_ids or []),
csv_path=None,
grid_size="GRID20",
whole_city=whole_city,
)
def _start(job) -> asyncio.Task:
job.task = asyncio.create_task(run_download(job))
return job.task
def _rows(job) -> list[str]:
"""CSV 里每行的栅格编号。"""
body = list(csv.reader(io.StringIO(job.csv_path.read_text(encoding="utf-8-sig"))))
column = body[0].index("20米栅格ID")
return [row[column] for row in body[1:]]
async def _until(check, seconds: float = 10.0) -> None:
deadline = time.monotonic() + seconds
while not check():
if time.monotonic() > deadline:
raise AssertionError("等待超时")
await asyncio.sleep(0.01)
def _scan(jobs, stop: threading.Event) -> None:
"""模拟杀毒软件和索引:不停打开任务目录里的文件读一下再放手。"""
while not stop.is_set():
for job in jobs:
paths = (
job.directory / "job.json",
job.directory / "ids.spool.meta",
job.directory / "ids.spool",
job.directory / "progress.jsonl",
job.csv_path,
)
for path in paths:
try:
with open(path, "rb") as handle:
handle.read(4096)
time.sleep(0.001)
except OSError:
pass
def test_two_city_jobs_survive_list_polling_and_file_scanners(manager, monkeypatch):
asyncio.run(_two_city_jobs(manager, monkeypatch))
async def _two_city_jobs(manager: JobManager, monkeypatch) -> None:
ids = {
"NR": [str(100000 + number) for number in range(700)],
"LTE": [str(500000 + number) for number in range(700)],
}
monkeypatch.setattr(state, "client", FakeClient(ids, delay=0.001))
first = _create(manager, "NR", concurrency=8)
second = _create(manager, "LTE", concurrency=8)
stop = threading.Event()
scanner = threading.Thread(target=_scan, args=([first, second], stop), daemon=True)
scanner.start()
polls = {"n": 0}
async def poll() -> None:
while not (first.task.done() and second.task.done()):
manager.list_jobs()
polls["n"] += 1
await asyncio.sleep(0.002)
try:
tasks = [_start(first), _start(second)]
await asyncio.wait_for(asyncio.gather(poll(), *tasks), timeout=60)
finally:
stop.set()
scanner.join(timeout=5)
for job, network in ((first, "NR"), (second, "LTE")):
assert job.status == "done", (job.status, job.message)
assert job.completed == 700
assert sorted(_rows(job)) == sorted(ids[network])
assert job.io is None
assert polls["n"] > 10
def test_list_reads_memory_after_first_load(manager, places, monkeypatch):
job = _create(manager, "NR")
job.status = "queued"
job.save()
other = places / "jobs" / "20260101010101"
other.mkdir(parents=True)
record = {
"id": other.name,
"network": "LTE",
"cityCode": "JM",
"cityName": "江门",
"month": "2026-08",
"groups": [],
"concurrency": 2,
"gridCount": 0,
"wholeCity": True,
"csvPath": str(other / "out.csv"),
"createdAt": "2026-01-01T01:01:01",
"status": "done",
"message": "已完成",
}
(other / "job.json").write_text(json.dumps(record, ensure_ascii=False), encoding="utf-8")
assert {item["id"] for item in manager.list_jobs()} == {job.id, other.name}
jobs_root = places / "jobs"
real_read_text = Path.read_text
real_open = Path.open
def guard(path: Path) -> None:
if jobs_root in path.parents:
raise AssertionError(f"不应再读 {path}")
def read_text(self, *args, **kwargs):
guard(self)
return real_read_text(self, *args, **kwargs)
def open_path(self, *args, **kwargs):
guard(self)
return real_open(self, *args, **kwargs)
monkeypatch.setattr(Path, "read_text", read_text)
monkeypatch.setattr(Path, "open", open_path)
assert {item["id"] for item in manager.list_jobs()} == {job.id, other.name}
def test_record_write_failure_never_raises_and_deleted_dirs_stay_deleted(manager, monkeypatch):
job = _create(manager, "NR")
monkeypatch.setattr(files_module.time, "sleep", lambda _seconds: None)
real_replace = files_module.os.replace
def deny(src, dst):
raise PermissionError(13, "Access is denied", str(dst), 5)
monkeypatch.setattr(files_module.os, "replace", deny)
job.message = "写不进去"
job.save()
monkeypatch.setattr(files_module.os, "replace", real_replace)
job.message = "写进去了"
job.save()
stored = json.loads((job.directory / "job.json").read_text(encoding="utf-8"))
assert stored["message"] == "写进去了"
assert list(job.directory.glob("*.tmp")) == []
shutil.rmtree(job.directory)
job.save()
assert not job.directory.exists()
def test_delete_paused_job_stops_its_task_before_removing_files(manager, monkeypatch):
asyncio.run(_delete_paused(manager, monkeypatch))
async def _delete_paused(manager: JobManager, monkeypatch) -> None:
gate = asyncio.Event()
client = FakeClient()
async def hold(_grid_id) -> None:
if len(client.fetched) >= 3:
await gate.wait()
client.on_fetch = hold
monkeypatch.setattr(state, "client", client)
job = _create(manager, "NR", whole_city=False, grid_ids=[str(number) for number in range(1, 30)], concurrency=2)
task = _start(job)
await _until(lambda: len(client.fetched) >= 3)
manager.pause(job)
assert job.is_active()
await manager.delete(job.id, files=True)
assert task.done()
assert job.io is None
assert job.id not in manager.jobs
assert not job.directory.exists()
assert not job.csv_path.parent.exists()
await asyncio.sleep(0.2)
assert not job.directory.exists()
def test_changing_concurrency_mid_city_download_keeps_every_grid(manager, monkeypatch):
asyncio.run(_retune_keeps_every_grid(manager, monkeypatch))
async def _retune_keeps_every_grid(manager: JobManager, monkeypatch) -> None:
ids = {"NR": [str(200000 + number) for number in range(500)]}
client = FakeClient(ids, delay=0.002)
holder: dict = {}
async def pause_once(_grid_id) -> None:
if len(client.fetched) == 60 and "paused" not in holder:
holder["paused"] = True
manager.pause(holder["job"])
client.on_fetch = pause_once
monkeypatch.setattr(state, "client", client)
job = _create(manager, "NR", concurrency=4)
holder["job"] = job
task = _start(job)
await _until(lambda: job.status == "paused")
await asyncio.sleep(0.1)
manager.set_concurrency(job, 7)
assert manager.place(job) == "resume"
await asyncio.wait_for(task, timeout=30)
assert job.status == "done", (job.status, job.message)
assert job.applied_concurrency == 7
assert sorted(_rows(job)) == sorted(ids["NR"])
def test_network_error_retries_the_pass_automatically(manager, monkeypatch):
monkeypatch.setattr(job_module, "PASS_RETRY_WAITS", (0, 0, 0))
asyncio.run(_network_retry(manager, monkeypatch))
async def _network_retry(manager: JobManager, monkeypatch) -> None:
client = FakeClient()
calls = {"n": 0}
real_layer = client.layer_code
async def flaky_layer(**kwargs):
calls["n"] += 1
if calls["n"] <= 2:
raise NqiNetworkError("连接失败,请稍后重试")
return await real_layer(**kwargs)
client.layer_code = flaky_layer
monkeypatch.setattr(state, "client", client)
job = _create(manager, "NR", whole_city=False, grid_ids=["1", "2", "3"])
await asyncio.wait_for(_start(job), timeout=10)
assert job.status == "done", (job.status, job.message)
assert calls["n"] == 3
assert sorted(_rows(job)) == ["1", "2", "3"]
def test_busy_csv_pauses_until_continue(manager, monkeypatch):
asyncio.run(_busy_csv(manager, monkeypatch))
async def _busy_csv(manager: JobManager, monkeypatch) -> None:
real_commit = CsvJournal.commit_many
failures = {"n": 0}
def flaky(self, items):
if failures["n"] == 0:
failures["n"] += 1
raise NqiError("文件被占用,请先关闭 Excel 等程序")
return real_commit(self, items)
monkeypatch.setattr(CsvJournal, "commit_many", flaky)
monkeypatch.setattr(state, "client", FakeClient())
grid_ids = [str(number) for number in range(1, 11)]
job = _create(manager, "NR", whole_city=False, grid_ids=grid_ids)
task = _start(job)
await _until(lambda: job.status == "paused" and job.paused_by == "file")
assert job.message == "文件被占用,请先关闭 Excel 等程序,处理好后点继续"
assert job.is_active()
assert manager.place(job) == "resume"
await asyncio.wait_for(task, timeout=10)
assert job.status == "done", (job.status, job.message)
assert sorted(_rows(job), key=int) == grid_ids
def test_resume_while_previous_run_is_closing_waits_for_it(manager):
job = _create(manager, "NR")
class Alive:
def done(self):
return False
job.task = Alive()
job.closing = True
job.status = "cancelled"
assert manager.place(job) == "wait"
assert job.status == "queued"
assert manager.queued_jobs() == []
job.task = None
assert manager.queued_jobs() == [job]
def test_commit_failure_leaves_no_partial_rows(tmp_path: Path, monkeypatch):
journal = CsvJournal(tmp_path / "out.csv", tmp_path / "progress.jsonl", ["栅格"])
journal.open()
journal.commit_many([("1", [["1"]])])
before_csv = (tmp_path / "out.csv").read_bytes()
before_progress = (tmp_path / "progress.jsonl").read_bytes()
real_fsync = os.fsync
failed = {"n": 0}
def fail_once(fd):
if fd == journal._file.fileno() and failed["n"] == 0:
failed["n"] += 1
error = OSError(33, "locked")
error.winerror = 33
raise error
return real_fsync(fd)
monkeypatch.setattr("app.features.download.journal.os.fsync", fail_once)
with pytest.raises(NqiError):
journal.commit_many([("2", [["2"]]), ("3", [["3"]])])
assert (tmp_path / "out.csv").read_bytes() == before_csv
assert (tmp_path / "progress.jsonl").read_bytes() == before_progress
assert journal.commit_many([("2", [["2"]]), ("3", [["3"]])]) == 2
journal.close()
body = list(csv.reader(io.StringIO((tmp_path / "out.csv").read_text(encoding="utf-8-sig"))))
assert body == [["栅格"], ["1"], ["2"], ["3"]]
reopened = CsvJournal(tmp_path / "out.csv", tmp_path / "progress.jsonl", ["栅格"])
reopened.open()
assert reopened.completed == {1, 2, 3}
reopened.close()