diff --git a/backend/tests/test_engine.py b/backend/tests/test_engine.py new file mode 100644 index 0000000..5e8f737 --- /dev/null +++ b/backend/tests/test_engine.py @@ -0,0 +1,773 @@ +"""调度、分块重试和全市编号暂存。""" + +from __future__ import annotations + +import asyncio +import logging +from pathlib import Path + +import httpx +import pytest + +from app.features.download.fields import columns_for +from app.features.download.jobs import DownloadJob, JobManager, _pump, run_download +from app.features.download.journal import CsvJournal +from app.features.download.router import active_downloads, router +from app.features.download.rows import build_rows +from app.features.download.spool import IdSpool +from app.features.download import spool as spool_module +from app.platform.client import ( + MIN_TILE_WIDTH, + NqiAuthError, + NqiClient, + TileReadError, +) +from app.platform import client as client_module +from app.shared.state import state + + +class _Alive: + def done(self): + return False + + +def _job( + tmp_path: Path, + *, + whole_city: bool = False, + grid_ids: list[str] | None = None, + job_id: str = "20260921120009", +) -> DownloadJob: + return DownloadJob( + id=job_id, + directory=tmp_path, + network="NR", + city_code="JM", + city_name="江门", + month="2026-09", + groups=["rsrp"], + concurrency=1, + grid_ids=list(grid_ids or []), + csv_path=tmp_path / "out.csv", + created_at="2026-09-21T12:00:09", + grid_size="GRID20", + whole_city=whole_city, + ) + + +def _use(client) -> tuple: + saved = (state.client, state.user, state.expired, state.jobs) + state.client = client + state.user = {"loginId": "tester"} + state.expired = False + state.jobs = JobManager() + return saved + + +def _restore(saved) -> None: + state.client, state.user, state.expired, state.jobs = saved + + +def _bind(client, name: str, method) -> None: + setattr(client, name, method.__get__(client, NqiClient)) + + +async def _fast_sleep(seconds, _cancel, _run): + return True + + +def test_tile_step_follows_grid_size(): + asyncio.run(_tile_step_follows_grid_size()) + + +async def _tile_step_follows_grid_size(): + client = NqiClient() + widths: dict[str, set[float]] = {"GRID20": set(), "GRID50": set()} + + async def bounds(_self, _service_code): + return (0.0, 0.0, 0.1, 0.05) + + async def tile(_self, _service_code, _id_field, area): + return [{"properties": {"grid20_id": "1"}}], 1 + + _bind(client, "_layer_bounds", bounds) + _bind(client, "_tile_features", tile) + try: + for size in ("GRID20", "GRID50"): + async def record(_self, _service_code, _id_field, area, size=size): + widths[size].add(round(area[2] - area[0], 5)) + return [{"properties": {"grid20_id": "1"}}], 1 + + _bind(client, "_tile_features", record) + async for _grid_id in client.iter_grid_ids("svc", "grid20_id", asyncio.Event(), _noop, grid_size=size): + break + finally: + await client.aclose() + assert widths["GRID20"] == {0.02} + assert widths["GRID50"] == {0.05} + + +def test_tile_retries_then_records_failure(monkeypatch): + asyncio.run(_tile_retries_then_records_failure(monkeypatch)) + + +async def _tile_retries_then_records_failure(monkeypatch): + waits: list[float] = [] + + async def remember(seconds, cancel, run): + waits.append(seconds) + return await _fast_sleep(seconds, cancel, run) + + monkeypatch.setattr(client_module, "_interruptible_sleep", remember) + client = NqiClient() + + async def bounds(_self, _service_code): + return (0.0, 0.0, 0.04, 0.02) + + async def tile(_self, _service_code, _id_field, area): + if area[0] < 0.01: + raise TileReadError("连接失败,请稍后重试", "connect") + return [{"properties": {"grid20_id": "8"}}], 1 + + _bind(client, "_layer_bounds", bounds) + _bind(client, "_tile_features", tile) + failed: list = [] + found: list[str] = [] + try: + async for grid_id in client.iter_grid_ids( + "svc", "grid20_id", asyncio.Event(), _noop, failed_tiles=failed + ): + found.append(grid_id) + finally: + await client.aclose() + assert found == ["8"] + assert len(failed) == 1 + assert waits == [1, 3, 9] + + +def test_timeout_splits_until_min_width(monkeypatch): + asyncio.run(_timeout_splits_until_min_width(monkeypatch)) + + +async def _timeout_splits_until_min_width(monkeypatch): + monkeypatch.setattr(client_module, "_interruptible_sleep", _fast_sleep) + client = NqiClient() + widths: list[float] = [] + + async def bounds(_self, _service_code): + return (0.0, 0.0, 0.02, 0.02) + + async def tile(_self, _service_code, _id_field, area): + width = area[2] - area[0] + widths.append(width) + if width > MIN_TILE_WIDTH + 1e-6: + raise TileReadError("平台响应超时,请稍后重试", "timeout") + return [{"properties": {"grid20_id": "3"}}], 1 + + _bind(client, "_layer_bounds", bounds) + _bind(client, "_tile_features", tile) + found: list[str] = [] + failed: list = [] + try: + async for grid_id in client.iter_grid_ids( + "svc", "grid20_id", asyncio.Event(), _noop, failed_tiles=failed + ): + found.append(grid_id) + finally: + await client.aclose() + assert found == ["3"] + assert failed == [] + assert min(widths) <= MIN_TILE_WIDTH + 1e-6 + assert max(widths) > MIN_TILE_WIDTH + + +def test_missing_number_matched_splits_large_tile(monkeypatch): + asyncio.run(_missing_number_matched_splits_large_tile(monkeypatch)) + + +async def _missing_number_matched_splits_large_tile(monkeypatch): + monkeypatch.setattr(client_module, "TILE_SPLIT_AT", 3) + client = NqiClient() + seen: list[float] = [] + + async def bounds(_self, _service_code): + return (0.0, 0.0, 0.02, 0.02) + + async def tile(_self, _service_code, _id_field, area): + width = area[2] - area[0] + seen.append(width) + if width > 0.01: + return [{"properties": {"grid20_id": "1"}}] * 3, None + return [{"properties": {"grid20_id": "4"}}], 1 + + _bind(client, "_layer_bounds", bounds) + _bind(client, "_tile_features", tile) + found: list[str] = [] + try: + async for grid_id in client.iter_grid_ids("svc", "grid20_id", asyncio.Event(), _noop): + found.append(grid_id) + finally: + await client.aclose() + assert found == ["4"] + assert any(width > 0.01 for width in seen) + assert any(width <= 0.01 for width in seen) + + +def test_wfs_requests_send_version_and_chinese_timeout(): + asyncio.run(_wfs_requests_send_version_and_chinese_timeout()) + + +async def _wfs_requests_send_version_and_chinese_timeout(): + client = NqiClient() + params_seen: list[dict] = [] + + class Response: + def __init__(self, status_code: int, text: str): + self.status_code = status_code + self.text = text + self.headers = {"content-type": "application/json"} + + def json(self): + return {"features": [{"properties": {"grid20_id": "9"}}], "numberMatched": 1} + + async def get(_url, params=None, **_kwargs): + params_seen.append(dict(params or {})) + if len(params_seen) == 1: + raise httpx.TimeoutException("timed out") + return Response(200, "{}") + + client.client.get = get + try: + with pytest.raises(TileReadError) as raised: + await client._tile_features("svc", "grid20_id", (0.0, 0.0, 0.01, 0.01)) + assert raised.value.kind == "timeout" + assert "超时" in str(raised.value) + await client.grid_feature("svc", "9", "grid20_id") + finally: + await client.aclose() + assert params_seen[0]["VERSION"] == "2.0.0" + assert params_seen[1]["VERSION"] == "2.0.0" + + +def test_auth_error_while_listing_is_not_a_failed_tile(): + asyncio.run(_auth_error_while_listing_is_not_a_failed_tile()) + + +async def _auth_error_while_listing_is_not_a_failed_tile(): + client = NqiClient() + + async def bounds(_self, _service_code): + return (0.0, 0.0, 0.02, 0.02) + + async def tile(_self, _service_code, _id_field, _area): + raise NqiAuthError("登录已失效,请重新登录") + + _bind(client, "_layer_bounds", bounds) + _bind(client, "_tile_features", tile) + failed: list = [] + try: + with pytest.raises(NqiAuthError): + async for _grid_id in client.iter_grid_ids( + "svc", "grid20_id", asyncio.Event(), _noop, failed_tiles=failed + ): + pass + finally: + await client.aclose() + assert failed == [] + + +def test_server_error_is_retried(monkeypatch): + asyncio.run(_server_error_is_retried(monkeypatch)) + + +async def _server_error_is_retried(monkeypatch): + waits: list[float] = [] + + async def remember(seconds, _cancel, _run): + waits.append(seconds) + return True + + monkeypatch.setattr(client_module, "_interruptible_sleep", remember) + client = NqiClient() + calls = {"n": 0} + + class Response: + def __init__(self, status_code: int, text: str): + self.status_code = status_code + self.text = text + + def json(self): + if not self.text.lstrip().startswith("{"): + raise ValueError("bad") + return {"features": [{"properties": {"grid20_id": "9"}}], "numberMatched": 1} + + async def get(_url, params=None, **_kwargs): + calls["n"] += 1 + if calls["n"] < 4: + return Response(503, "") + return Response(200, '{"features":[{"properties":{"grid20_id":"9"}}],"numberMatched":1}') + + async def bounds(_self, _service_code): + return (0.0, 0.0, 0.01, 0.01) + + client.client.get = get + _bind(client, "_layer_bounds", bounds) + found: list[str] = [] + try: + async for grid_id in client.iter_grid_ids("svc", "grid20_id", asyncio.Event(), _noop): + found.append(grid_id) + finally: + await client.aclose() + assert found == ["9"] + assert calls["n"] == 4 + assert waits == [1, 3, 9] + + +def test_spool_dedups_ints_and_drops_uncommitted_tail(monkeypatch, tmp_path: Path): + clock = {"now": 10.0} + monkeypatch.setattr(spool_module.time, "monotonic", lambda: clock["now"]) + synced = {"n": 0} + real_fsync = spool_module.os.fsync + + def spy(fd): + synced["n"] += 1 + return real_fsync(fd) + + monkeypatch.setattr(spool_module.os, "fsync", spy) + spool = IdSpool(tmp_path) + spool.open() + assert spool.add("10") is True + assert spool.add("010") is False + assert spool.add("11") is True + assert spool.due() is False + clock["now"] = 10.6 + assert spool.due() is True + spool.flush() + assert spool.committed == 2 + assert synced["n"] >= 1 + spool.mark_complete() + assert spool.pull() == ["10", "11"] + assert spool.caught_up() is True + spool.close() + with open(tmp_path / "ids.spool", "ab") as handle: + handle.write(b"12\n") + again = IdSpool(tmp_path) + again.open() + try: + assert again.committed == 2 + assert 12 not in again.seen + assert again.complete is True + assert again.pull() == ["10", "11"] + finally: + again.close() + + +def test_running_count_ignores_paused_and_dead_tasks(tmp_path: Path): + manager = JobManager() + job = _job(tmp_path) + manager.jobs[job.id] = job + job.status = "running" + job.task = None + assert manager.running_count() == 0 + job.task = _Alive() + assert manager.running_count() == 1 + manager.pause(job) + assert job.status == "paused" + assert manager.running_count() == 0 + + +def test_request_stop_sets_stopping_and_requeue_clears_listing(tmp_path: Path): + manager = JobManager() + manager.max_concurrent = 1 + city = _job(tmp_path, whole_city=True) + city.listing_done = True + city.status = "paused" + city.paused_by = "expired" + city.task = _Alive() + manager.jobs[city.id] = city + manager.resume_marked("expired") + assert city.status == "queued" + assert city.listing_done is False + holder_dir = tmp_path / "other" + holder_dir.mkdir() + holder = _job(holder_dir, job_id="20260921120010") + holder.status = "running" + holder.task = _Alive() + manager.jobs[holder.id] = holder + assert manager.place(city) == "wait" + assert city.listing_done is False + manager.request_stop(holder) + assert holder.stopping is True + assert holder.message == "正在停止" + + +def test_active_count_and_sse_removed(tmp_path: Path): + saved = _use(NqiClient()) + try: + manager = state.jobs + job = _job(tmp_path) + job.status = "running" + job.task = _Alive() + paused = _job(tmp_path / "paused", job_id="20260921120010") + paused.status = "paused" + paused.task = _Alive() + manager.jobs[job.id] = job + manager.jobs[paused.id] = paused + assert asyncio.run(active_downloads()) == {"count": 1} + paths = [getattr(route, "path", "") for route in router.routes] + assert "/api/download/active" in paths + assert not any(str(path).endswith("/events") for path in paths) + finally: + client = state.client + _restore(saved) + asyncio.run(client.aclose()) + + +def test_duplicate_write_does_not_increase_completed(tmp_path: Path): + asyncio.run(_duplicate_write_does_not_increase_completed(tmp_path)) + + +async def _duplicate_write_does_not_increase_completed(tmp_path: Path): + job = _job(tmp_path, grid_ids=["1"]) + columns = columns_for("NR", ["rsrp"]) + journal = CsvJournal(job.csv_path, tmp_path / "progress.jsonl", [column.label for column in columns]) + journal.open() + journal.write_rows("1", build_rows("1", {"grid20_id": "1"}, [], columns)) + job.completed = 4 + + async def source(): + yield "1" + + class Fake: + async def grid_feature(self, _service, grid_id, _field): + return {"grid20_id": grid_id} + + async def cell_rows(self, _service, _grid_id, _network): + return [] + + try: + await _pump(job, Fake(), journal, columns, "svc", source()) + finally: + journal.close() + assert job.completed == 4 + assert job.status == "done" + + +def test_writer_flushes_a_batch_of_200(tmp_path: Path): + asyncio.run(_writer_flushes_a_batch_of_200(tmp_path)) + + +async def _writer_flushes_a_batch_of_200(tmp_path: Path): + job = _job(tmp_path) + job.concurrency = 4 + columns = columns_for("NR", ["rsrp"]) + + class Journal: + def __init__(self): + self.completed: set[str] = set() + self.written_rows = 0 + self.batches: list[list] = [] + + def commit_many(self, items): + self.batches.append(list(items)) + for grid_id, rows in items: + self.completed.add(grid_id) + self.written_rows += len(rows) + return self.written_rows + + journal = Journal() + + async def source(): + for number in range(200): + yield str(number) + + class Fake: + async def grid_feature(self, _service, grid_id, _field): + return {"grid20_id": grid_id} + + async def cell_rows(self, _service, _grid_id, _network): + return [] + + await _pump(job, Fake(), journal, columns, "svc", source()) + assert job.completed == 200 + assert journal.batches + assert len(journal.batches[0]) == 200 + + +def test_writer_flushes_after_half_second(tmp_path: Path): + asyncio.run(_writer_flushes_after_half_second(tmp_path)) + + +async def _writer_flushes_after_half_second(tmp_path: Path): + job = _job(tmp_path) + columns = columns_for("NR", ["rsrp"]) + + class Journal: + def __init__(self): + self.completed: set[str] = set() + self.written_rows = 0 + self.batches: list[int] = [] + + def commit_many(self, items): + self.batches.append(len(list(items))) + for grid_id, rows in items: + self.completed.add(grid_id) + self.written_rows += len(rows) + return self.written_rows + + journal = Journal() + release = asyncio.Event() + + async def source(): + yield "1" + await release.wait() + yield "2" + + class Fake: + async def grid_feature(self, _service, grid_id, _field): + return {"grid20_id": grid_id} + + async def cell_rows(self, _service, _grid_id, _network): + return [] + + async def watch(): + for _ in range(40): + if journal.batches == [1]: + break + await asyncio.sleep(0.05) + else: + raise AssertionError(journal.batches) + release.set() + + await asyncio.gather(_pump(job, Fake(), journal, columns, "svc", source()), watch()) + assert journal.batches == [1, 1] + assert job.completed == 2 + + +def test_writer_error_cancels_the_group(tmp_path: Path): + asyncio.run(_writer_error_cancels_the_group(tmp_path)) + + +async def _writer_error_cancels_the_group(tmp_path: Path): + job = _job(tmp_path, grid_ids=["1", "2"]) + columns = columns_for("NR", ["rsrp"]) + started: list[str] = [] + + class Journal: + completed: set[str] = set() + written_rows = 0 + + def commit_many(self, _items): + raise RuntimeError("disk") + + class Fake: + async def grid_feature(self, _service, grid_id, _field): + started.append(grid_id) + if grid_id == "2": + await asyncio.Event().wait() + return {"grid20_id": grid_id} + + async def cell_rows(self, _service, _grid_id, _network): + return [] + + async def source(): + yield "1" + yield "2" + + with pytest.raises(RuntimeError, match="disk"): + await asyncio.wait_for(_pump(job, Fake(), Journal(), columns, "svc", source()), timeout=2) + assert started == ["1"] or started == ["1", "2"] + assert job.status != "done" + + +def test_auth_failure_pauses_without_counting(tmp_path: Path): + asyncio.run(_auth_failure_pauses_without_counting(tmp_path)) + + +async def _auth_failure_pauses_without_counting(tmp_path: Path): + job = _job(tmp_path, grid_ids=["5"]) + used: list[str] = [] + + class Bad: + async def layer_code(self, **_kwargs): + used.append("bad-layer") + return {"serviceCode": "svc", "originRelatedField": "grid20_id"} + + async def grid_feature(self, _service, _grid_id, _field): + used.append("bad-grid") + raise NqiAuthError("登录已失效,请重新登录") + + async def cell_rows(self, _service, _grid_id, _network): + return [] + + async def aclose(self): + return None + + class Good(Bad): + async def layer_code(self, **_kwargs): + used.append("good-layer") + return {"serviceCode": "svc", "originRelatedField": "grid20_id"} + + async def grid_feature(self, _service, grid_id, _field): + used.append("good-grid") + return {"grid20_id": grid_id} + + saved = _use(Bad()) + state.jobs.jobs[job.id] = job + + async def watch(): + for _ in range(200): + if job.status == "paused" and state.expired: + break + await asyncio.sleep(0.01) + else: + raise AssertionError((job.status, job.message, job.failed)) + assert job.failed == 0 + assert job.paused_by == "expired" + state.expired = False + state.client = Good() + state.user = {"loginId": "tester"} + job.run_event.set() + + try: + await asyncio.wait_for(asyncio.gather(run_download(job), watch()), timeout=3) + finally: + _restore(saved) + assert job.failed == 0 + assert job.completed == 1 + assert job.status == "done" + assert used[:2] == ["bad-layer", "bad-grid"] + assert "good-layer" in used and "good-grid" in used + + +def test_unknown_download_error_is_generic(tmp_path: Path, caplog): + asyncio.run(_unknown_download_error_is_generic(tmp_path, caplog)) + + +async def _unknown_download_error_is_generic(tmp_path: Path, caplog): + job = _job(tmp_path, grid_ids=["5"]) + + class Boom: + async def layer_code(self, **_kwargs): + raise RuntimeError("socket exploded") + + async def aclose(self): + return None + + saved = _use(Boom()) + state.jobs.jobs[job.id] = job + try: + with caplog.at_level(logging.ERROR, logger="nqi.download"): + await run_download(job) + finally: + _restore(saved) + assert job.status == "error" + assert job.message == "下载失败,详情见日志" + assert "socket exploded" in caplog.text + assert "socket exploded" not in job.message + + +def test_complete_spool_skips_listing_and_failed_tiles_retry(tmp_path: Path, monkeypatch): + asyncio.run(_complete_spool_skips_listing_and_failed_tiles_retry(tmp_path, monkeypatch)) + + +async def _complete_spool_skips_listing_and_failed_tiles_retry(tmp_path: Path, monkeypatch): + monkeypatch.setattr(client_module, "_interruptible_sleep", _fast_sleep) + prepared = IdSpool(tmp_path) + prepared.open() + assert prepared.add("5") + prepared.mark_complete() + prepared.close() + job = _job(tmp_path, whole_city=True) + calls = {"bounds": 0, "tiles": 0, "iter": 0} + + class Client: + async def layer_code(self, **_kwargs): + return {"serviceCode": "svc", "originRelatedField": "grid20_id"} + + async def grid_feature(self, _service, grid_id, _field): + return {"grid20_id": grid_id} + + async def cell_rows(self, *_args): + return [] + + async def iter_grid_ids(self, *_args, **_kwargs): + calls["iter"] += 1 + raise AssertionError("编号已经读完,不应重读") + yield "5" + + async def aclose(self): + return None + + saved = _use(Client()) + state.jobs.jobs[job.id] = job + try: + await run_download(job) + assert calls["iter"] == 0 + assert job.completed == 1 + assert job.listing_done is True + assert job.status == "done" + + retry_dir = tmp_path / "retry" + retry_dir.mkdir() + retry_job = _job(retry_dir, whole_city=True) + client = NqiClient() + + async def bounds(_self, _service_code): + calls["bounds"] += 1 + return (0.0, 0.0, 0.02, 0.02) + + async def tile(_self, _service_code, _id_field, _area): + calls["tiles"] += 1 + if calls["tiles"] <= 4: + raise TileReadError("连接失败,请稍后重试", "connect") + return [{"properties": {"grid20_id": "6"}}], 1 + + async def layer_code(_self, **_kwargs): + return {"serviceCode": "svc", "originRelatedField": "grid20_id"} + + async def grid_feature(_self, _service, grid_id, _field): + return {"grid20_id": grid_id} + + async def cell_rows(_self, *_args): + return [] + + _bind(client, "_layer_bounds", bounds) + _bind(client, "_tile_features", tile) + _bind(client, "layer_code", layer_code) + _bind(client, "grid_feature", grid_feature) + _bind(client, "cell_rows", cell_rows) + state.client = client + state.jobs.jobs[retry_job.id] = retry_job + await run_download(retry_job) + assert retry_job.message == "有 1 块区域没读到,点继续重试" + assert retry_job.status == "done_with_errors" + first_bounds = calls["bounds"] + await run_download(retry_job) + assert calls["bounds"] == first_bounds + assert calls["tiles"] > 4 + assert retry_job.completed == 1 + assert retry_job.failed_tiles == [] + assert retry_job.status == "done" + finally: + client = state.client + _restore(saved) + close = getattr(client, "aclose", None) + if close is not None: + await close() + + +def test_emit_does_not_publish_to_subscribers(tmp_path: Path): + asyncio.run(_emit_does_not_publish_to_subscribers(tmp_path)) + + +async def _emit_does_not_publish_to_subscribers(tmp_path: Path): + job = _job(tmp_path) + queue: asyncio.Queue = asyncio.Queue() + job.subscribers.append(queue) + await job.emit("progress") + assert queue.empty() + + +async def _noop(_count: int) -> None: + return None