import asyncio import csv import hashlib import io import threading from datetime import datetime from pathlib import Path from app.features.download.fields import columns_for from app.features.download.ids import parse_table, parse_upload from app.features.download import jobs as job_module from app.features.download.jobs import DownloadJob, JobManager, _pump from app.features.download.journal import CsvJournal from app.platform.constants import APP_SECRET from app.features.download.rows import build_rows from app.platform.sign import build_sign, wfs_sig from app.platform.client import NqiClient, NqiError, login_page_url, month_end, rsa_encrypt, sms_notice from app.platform import sessions from app.platform.keepalive import refresh_saved_session from app.shared.state import state PUBLIC_KEY = ( "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCwjDm1HXDw8QH5ZtGMQIl2h/I8E+" "chOQA8aQ8xCR/+aHnROaN/ZU5Vmd2Zz7g6cAacR9BSm60+iSCYtvEGJKl0WqvbPGJkc8tedjNF1QqgWqkkuE6Udgw2OkEKJCxDg6PrAniR7Cc0io9G8bW4P8JDJjSbbafvMPDDFbVVUWJxxwIDAQAB" ) def test_wfs_signature_matches_capture(): assert wfs_sig("HRwhGIb3") == "b1c5be69ecdd1247d669ddaff4224050" assert wfs_sig("HRxs2eTA") == "ee021c49a89f7560c54a36835ec23d3a" def test_request_sign_is_sorted_md5(): signed = build_sign({"cityCode": "JM", "dataType": "GRID"}, timestamp="1", nonce="abc") raw = "cityCodeJMdataTypeGRIDnonceStrabctimestamp1version1.0.0" expected = hashlib.md5((raw + APP_SECRET).encode()).hexdigest().upper() assert signed["sign"] == expected assert signed["appKey"] def test_month_end(): assert month_end("2026-09") == "20260930" assert month_end("2026-02") == "20260228" def test_login_page_keeps_service_query(): assert login_page_url("https://nqi.gmcc.net:20443/cas/login") == ( "https://nqi.gmcc.net:20443/cas/login?service=https%3A%2F%2Fnqi.gmcc.net%3A20443%2Fpro-portal%2F" ) kept = "https://nqi.gmcc.net:20443/cas/login?service=https%3A%2F%2Fnqi.gmcc.net%3A20443%2Fpro-portal%2F" assert login_page_url(kept) == kept def test_saved_login_replaces_same_account(tmp_path: Path, monkeypatch): monkeypatch.setattr(sessions, "STORE", tmp_path / "sessions.json") user = {"loginId": "a", "userName": "甲", "cityName": "江门", "orgName": ""} sessions.remember(user, [{"name": "TGC", "value": "old", "domain": "", "path": "/"}]) sessions.remember( {"loginId": "b", "userName": "乙", "cityName": "广州", "orgName": ""}, [{"name": "TGC", "value": "b", "domain": "", "path": "/"}], ) sessions.remember(user, [{"name": "TGC", "value": "new", "domain": "", "path": "/"}]) stored = sessions._read() assert [item["loginId"] for item in stored] == ["a", "b"] assert stored[0]["cookies"][0]["value"] == "new" sessions.forget("b") assert [item["loginId"] for item in sessions._read()] == ["a"] def test_sms_notice_reads_accepted_message(): payload = {"msg": "success", "data": '{"Content":"短信发送已受理。","Code":"0000"}', "success": True} assert sms_notice(payload) == "短信发送已受理。" def test_rsa_block_size(): encrypted = rsa_encrypt(PUBLIC_KEY, "demo") assert len(encrypted) == 172 def test_grid_rows_repeat_metrics_per_cell(): columns = columns_for("NR", None) rows = build_rows( "541927061", {"grid20_id": "541927061", "city_name": "江门", "ssb_rsrp_yd": -83.38, "mro_total_yd": 3080}, [ {"cgi": "126160-1", "mro_total": 2067, "ssb_rsrp": -80.37, "rsrp_lt_neg105": 7}, {"cgi": "126160-2", "mro_total": 886, "ssb_rsrp": -91.11, "rsrp_lt_neg105": 13}, ], columns, ) labels = [column.label for column in columns] assert len(rows) == 2 assert rows[0][labels.index("20米栅格ID")] == "541927061" assert rows[1][labels.index("20米栅格ID")] == "541927061" assert rows[0][labels.index("小区ID")] == "126160-1" assert rows[1][labels.index("小区ID")] == "126160-2" assert rows[0][labels.index("中国移动SSB-RSRP(dBm)")] == "-83.38" assert "中国移动SSB-RSRP(dBm)" in labels assert "RSRP(dBm)" in labels def test_missing_cells_keep_one_blank_row(): columns = columns_for("LTE", ["samples"]) rows = build_rows("10001", {"city_name": "江门", "mro_total_yd": 3}, [], columns) labels = [column.label for column in columns] assert len(rows) == 1 assert rows[0][labels.index("20米栅格ID")] == "10001" assert rows[0][labels.index("小区ID")] == "" assert rows[0][labels.index("中国移动MR总数")] == "3" assert "中国移动RSRP(dBm)" not in labels def test_missing_grid_still_writes_requested_id(): columns = columns_for("NR", []) rows = build_rows("42", None, None, columns) labels = [column.label for column in columns] assert len(rows) == 1 assert rows[0][labels.index("20米栅格ID")] == "42" assert rows[0][labels.index("小区ID")] == "" def test_fifty_meter_column_name(): labels = [column.label for column in columns_for("NR", ["rsrp"], "GRID50")] assert "50米栅格ID" in labels assert "20米栅格ID" not in labels rows, duplicates = parse_table( [["20米栅格ID", "备注"], ["541927061", "a"], ["541927061", "b"], [" 12 ", "c"], ["12", "d"], ["", ""]] ) assert rows == ["541927061", "12"] assert duplicates == 2 def test_parse_csv_upload(tmp_path: Path): path = tmp_path / "ids.csv" path.write_bytes("20米栅格ID\n541927061\n544536471\n541927061\n".encode("utf-8-sig")) assert parse_upload(path) == (["541927061", "544536471"], 1) other = tmp_path / "ids.txt" other.write_text("541927061\n", encoding="utf-8") try: parse_upload(other) except ValueError as exc: assert "CSV" in str(exc) else: raise AssertionError("txt 不应被接受") def test_journal_discards_uncommitted_tail(tmp_path: Path): 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 journal.close() with csv_path.open("ab") as handle: handle.write("垃圾,数据\r\n".encode("utf-8")) journal.open() assert "1" in journal.completed assert "垃圾" not in csv_path.read_text(encoding="utf-8") assert journal.write_rows("1", [["1", "again"]]) == 0 assert journal.write_rows("2", [["2", ""]]) == 1 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_journal_writes_do_not_interleave(tmp_path: Path): csv_path = tmp_path / "out.csv" journal = CsvJournal(csv_path, tmp_path / "progress.jsonl", ["组", "序号", "内容"]) journal.open() def write_group(name: str) -> None: for index in range(20): journal.write_rows(f"{name}-{index}", [[name, str(index), "甲" * 30]]) 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(csv_path.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_grid_ids_yield_before_the_scan_finishes(): asyncio.run(_grid_ids_yield_before_the_scan_finishes()) async def _grid_ids_yield_before_the_scan_finishes(): client = NqiClient() release = asyncio.Event() seen_tiles: list[float] = [] async def bounds(_self, _service_code): return (0.0, 0.0, 0.1, 0.05) async def tile(_self, _service_code, _id_field, area): seen_tiles.append(area[0]) if area[0] >= 0.01: await release.wait() grid_id = "1" if area[0] < 0.01 else "2" return [{"properties": {"grid20_id": grid_id}}], 1 client._layer_bounds = bounds.__get__(client, NqiClient) client._tile_features = tile.__get__(client, NqiClient) async def progress(_count: int) -> None: return None agen = client.iter_grid_ids("svc", "grid20_id", asyncio.Event(), progress) try: first = await agen.__anext__() assert first == "1" assert not release.is_set() release.set() second = await agen.__anext__() assert second == "2" finally: await agen.aclose() await client.aclose() def test_grid_ids_skip_edges_already_seen(): asyncio.run(_grid_ids_skip_edges_already_seen()) async def _grid_ids_skip_edges_already_seen(): client = NqiClient() async def bounds(_self, _service_code): return (0.0, 0.0, 0.1, 0.05) async def tile(_self, _service_code, _id_field, area): grid_id = "7" if area[0] < 0.01 else "8" return [{"properties": {"grid20_id": grid_id}}, {"properties": {"grid20_id": "7"}}], 2 client._layer_bounds = bounds.__get__(client, NqiClient) client._tile_features = tile.__get__(client, NqiClient) found: list[str] = [] async for grid_id in client.iter_grid_ids("svc", "grid20_id", asyncio.Event(), _noop, {"7"}): found.append(grid_id) await client.aclose() assert found == ["8"] async def _noop(_count: int) -> None: return None def test_download_starts_before_remaining_ids_arrive(tmp_path: Path): asyncio.run(_download_starts_before_remaining_ids_arrive(tmp_path)) async def _download_starts_before_remaining_ids_arrive(tmp_path: Path): started = asyncio.Event() order: list[str] = [] class Fake: async def grid_feature(self, _service_code, grid_id, _id_field): order.append(grid_id) if grid_id == "1": started.set() return {"grid20_id": grid_id} async def cell_rows(self, _service_code, _grid_id, _network): return [] async def source(): yield "1" await started.wait() order.append("rest") yield "2" job = DownloadJob( id="a" * 32, directory=tmp_path, network="NR", city_code="JM", city_name="江门", month="2026-09", groups=["rsrp"], concurrency=2, grid_ids=["1", "2"], csv_path=tmp_path / "out.csv", created_at="", ) columns = columns_for("NR", ["rsrp"]) journal = CsvJournal(job.csv_path, tmp_path / "progress.jsonl", [column.label for column in columns]) journal.open() await _pump(job, Fake(), journal, columns, "svc", source()) journal.close() assert order.index("1") < order.index("rest") assert job.completed == 2 assert job.status == "done" def test_touch_session_visits_portal_and_layer(): asyncio.run(_touch_session_visits_portal_and_layer()) async def _touch_session_visits_portal_and_layer(): client = NqiClient() calls: list[tuple[str, str]] = [] class Response: def __init__(self, payload: dict, status_code: int = 200): self.status_code = status_code self._payload = payload self.headers = {"content-type": "application/json"} def json(self): return self._payload async def get(url, headers=None, params=None, **_kwargs): calls.append(("GET", str(url))) if "roleCityMapping" in str(url): return Response({"code": 0, "data": []}) if "getOnLineCount" in str(url): return Response({"count": 1}) return Response({"loginId": "a", "userName": "甲", "cityName": "江门", "orgName": "江门", "roleId": "r1"}) async def post(url, json=None, headers=None, **_kwargs): calls.append(("POST", str(url))) return Response({}) client.client.get = get client.client.post = post try: user = await client.touch_session() finally: await client.aclose() assert user["loginId"] == "a" assert user["userName"] == "甲" joined = " ".join(url for _method, url in calls) assert "getCasUser" in joined assert "checkUserPasswordUpdated" in joined assert "getOnLineCount" in joined assert "roleCityMapping/cities" in joined def test_touch_session_rejects_expired_login(): try: asyncio.run(_touch_session_rejects_expired_login()) except NqiError as exc: assert "失效" in str(exc) else: raise AssertionError("失效登录应被拒绝") async def _touch_session_rejects_expired_login(): client = NqiClient() class Response: status_code = 200 headers = {"content-type": "application/json"} def json(self): return {"loginId": "a", "userName": "甲"} class Denied: status_code = 401 headers = {"content-type": "application/json"} def json(self): return {} async def get(url, headers=None, params=None, **_kwargs): return Response() async def post(url, json=None, headers=None, **_kwargs): return Denied() client.client.get = get client.client.post = post try: await client.touch_session() finally: await client.aclose() def test_refresh_saved_session_rewrites_cookie(tmp_path: Path, monkeypatch): monkeypatch.setattr(sessions, "STORE", tmp_path / "sessions.json") class Fake: async def touch_session(self): return {"loginId": "a", "userName": "甲", "cityName": "江门", "orgName": ""} def export_cookies(self): return [{"name": "TGC", "value": "kept", "domain": "", "path": "/"}] state.client = Fake() state.user = {"loginId": "a", "userName": "旧", "cityName": "", "orgName": ""} try: asyncio.run(refresh_saved_session()) assert state.user["userName"] == "甲" stored = sessions._read() finally: state.client = None state.user = None assert stored[0]["cookies"][0]["value"] == "kept" def test_task_folder_uses_second_timestamp(tmp_path: Path, monkeypatch): monkeypatch.setattr(job_module, "DATA_DIR", tmp_path / "jobs") class Clock: @staticmethod def now(): return datetime(2026, 9, 21, 12, 0, 9) monkeypatch.setattr(job_module, "datetime", Clock) manager = JobManager() output = tmp_path / "save" / "栅格.csv" first = _make_job(manager, output) assert first.id == "20260921120009" assert first.directory == tmp_path / "jobs" / "20260921120009" assert first.csv_path == tmp_path / "save" / "20260921120009" / "栅格.csv" second = _make_job(manager, output) assert second.id == "20260921120009_2" assert second.directory != first.directory def test_only_the_task_limit_runs(tmp_path: Path, monkeypatch): monkeypatch.setattr(job_module, "DATA_DIR", tmp_path / "jobs") manager = JobManager() manager.max_concurrent = 1 first = _make_job(manager, None) second = _make_job(manager, None) assert manager.place(first) == "run" assert manager.place(second) == "wait" assert second.status == "queued" assert second.message == "等待中" manager.request_stop(second) assert second.status == "cancelled" assert second.message == "已取消" class Alive: def done(self): return False first.task = Alive() manager.pause(first) assert first.status == "paused" assert manager.running_count() == 0 third = _make_job(manager, None) assert manager.place(third) == "run" assert manager.place(first) == "wait" manager.jobs.clear() manager.hydrate() assert first.id in manager.jobs assert manager.jobs[first.id].status == "queued" assert third.id not in manager.jobs def test_reader_stays_idle_while_paused(): asyncio.run(_reader_stays_idle_while_paused()) async def _reader_stays_idle_while_paused(): client = NqiClient() run = asyncio.Event() reached = asyncio.Event() started: list[float] = [] async def bounds(_self, _service_code): reached.set() return (0.0, 0.0, 0.05, 0.05) async def tile(_self, _service_code, _id_field, area): started.append(area[0]) return [{"properties": {"grid20_id": "5"}}], 1 client._layer_bounds = bounds.__get__(client, NqiClient) client._tile_features = tile.__get__(client, NqiClient) agen = client.iter_grid_ids("svc", "grid20_id", asyncio.Event(), _noop, None, run) nxt = asyncio.create_task(agen.__anext__()) try: await asyncio.wait_for(reached.wait(), 1) await asyncio.sleep(0.05) assert started == [] assert not nxt.done() run.set() assert await nxt == "5" assert started finally: run.set() nxt.cancel() await agen.aclose() await client.aclose() def test_pause_holds_the_next_grid(tmp_path: Path): asyncio.run(_pause_holds_the_next_grid(tmp_path)) async def _pause_holds_the_next_grid(tmp_path: Path): seen: list[str] = [] job = DownloadJob( id="20260921120009", directory=tmp_path, network="NR", city_code="JM", city_name="江门", month="2026-09", groups=["rsrp"], concurrency=1, grid_ids=["1", "2"], csv_path=tmp_path / "out.csv", created_at="", ) class Fake: async def grid_feature(self, _service_code, grid_id, _id_field): seen.append(grid_id) if grid_id == "1": job.run_event.clear() job.status = "paused" return {"grid20_id": grid_id} async def cell_rows(self, _service_code, _grid_id, _network): return [] async def source(): yield "1" yield "2" async def watch(): try: for _ in range(50): if seen == ["1"]: break await asyncio.sleep(0.01) else: raise AssertionError("下载没有在第一格停下") await asyncio.sleep(0.15) assert seen == ["1"] finally: job.run_event.set() columns = columns_for("NR", ["rsrp"]) journal = CsvJournal(job.csv_path, tmp_path / "progress.jsonl", [column.label for column in columns]) journal.open() await asyncio.gather(_pump(job, Fake(), journal, columns, "svc", source()), watch()) journal.close() assert seen == ["1", "2"] assert job.status == "done" def _make_job(manager: JobManager, output: Path | None) -> DownloadJob: return manager.create( network="NR", city_code="JM", city_name="江门", month="2026-09", groups=["rsrp"], concurrency=4, grid_ids=["1"], csv_path=output, grid_size="GRID20", whole_city=output is None, )