import asyncio import re from datetime import date, datetime, timedelta, timezone import pytest from sqlalchemy import create_engine from app.collect import gongcan from app.collect.gongcan import ( HISTORY_START, AfterPick, GongcanError, GongcanMissing, GongcanStore, Target, build_cells, claim_snapshot, expected_mondays, fetch_snapshot, latest_monday, nearest_sites, pick_after, pick_before, platform_files, release_loading, save_snapshot, short_city, snapshot_task_name, target_center, ) from app.models import Base, CellData4G, CellData5G, GongcanSnapshot from app.nqi.opencode import CsvTable, OpenCode CITY = "江门" SITE = Target(site="T") def cell(cgi, site, tech="4G", lat=22.0, lon=113.0, name="A", network_type="LTE"): return {"tech": tech, "cgi": cgi, "cell_name": name, "site_name": site, "latitude": lat, "longitude": lon, "network_type": network_type} def lte(cgi, site, lat=22.0): return {"cgi": cgi, "cell_name": f"{site}-A", "station_name": site, "latitude": lat, "longitude": 113.0, "network_type": "LTE"} def nr(ncgi, site, lat=22.0): return {"ncgi": ncgi, "nrcell_name": f"{site}-N", "station_name": site, "latitude": lat, "longitude": 113.0, "network_type": "NR"} def with_target(): return {"4G": [lte("t1", "T")], "5G": [nr("n1", "N")]} def without_target(): return {"4G": [lte("o1", "O")], "5G": [nr("n1", "N")]} class Clock: def __init__(self): self.now = datetime(2026, 11, 11, 2, 0, tzinfo=timezone.utc) def __call__(self): return self.now class Platform: def __init__(self, days, delay=0.0): self.days = days self.delay = delay self.fetched = [] async def __call__(self, city, day): self.fetched.append(day) if self.delay: await asyncio.sleep(self.delay) if day not in self.days: raise GongcanError("平台没有这一天") return self.days[day] def make_store(platform, stored=None, clock=None): db = create_engine("sqlite://") Base.metadata.create_all(db, tables=[GongcanSnapshot.__table__, CellData4G.__table__, CellData5G.__table__]) clock = clock or Clock() for day, cells in (stored or {}).items(): snapshot_id = claim_snapshot(db, CITY, day, clock()) save_snapshot(db, snapshot_id, cells, clock()) return GongcanStore(db, platform, poll_seconds=0.01, clock=clock) def test_snapshots_are_mondays_and_wait_three_days_for_the_platform(): # 2026-11-09 是周一,它的工参要到周四 11-12 才取。 assert latest_monday(date(2026, 11, 11)) == date(2026, 11, 2) assert latest_monday(date(2026, 11, 12)) == date(2026, 11, 9) assert latest_monday(date(2026, 11, 18)) == date(2026, 11, 9) days = expected_mondays(date(2026, 11, 12)) assert days[0] == HISTORY_START == date(2024, 1, 1) and days[-1] == date(2026, 11, 9) and len(days) == 150 assert all(day.weekday() == 0 for day in days) assert expected_mondays(date(2024, 1, 3)) == [] assert short_city("江门市") == "江门" and short_city("江门分公司") == "江门" and short_city(" 江门 ") == "江门" and short_city("市") == "市" def test_platform_files_use_make_date_and_keep_commas_out_of_text_columns(): task = snapshot_task_name(CITY, date(2026, 11, 1)) assert re.fullmatch(r"gc_[0-9a-f]{12}", task) and task != snapshot_task_name(CITY, date(2026, 10, 1)) lte, nr = platform_files(task, CITY, date(2026, 11, 1)) assert lte.sql.startswith("select cgi, longitude, latitude, eff_from_date, eff_to_date, replace(cell_name::text, ',', ',') as cell_name") assert lte.sql.endswith("from appdbv3.a_common_cfg_lte_cellant_d where city = '江门' and eff_from_date <= make_date(2026, 11, 1) and eff_to_date > make_date(2026, 11, 1)") assert nr.sql.startswith("select ncgi, cgi, longitude, latitude,") assert "replace(gnodeb_name::text, ',', ',') as gnodeb_name" in nr.sql assert not re.search(r"\d{4}-\d{2}-\d{2}", lte.sql + nr.sql) assert (lte.phase, lte.key, nr.key) == ("gc", "gc/lte", "gc/nr") assert {"cgi", "latitude", "station_name", "enodeb_id", "azimuth"} <= set(lte.required) assert {"ncgi", "nrcell_name", "gnodeb_id"} <= set(nr.required) def test_build_cells_merges_antenna_rows_by_cgi(): rows = [ {"cgi": "c1", "cell_name": "A", "station_name": "S1", "enodeb_id": "1", "network_type": "LTE", "longitude": "", "latitude": ""}, {"cgi": "c1", "cell_name": "A-dup", "station_name": "S1", "longitude": "113.1", "latitude": "22.5"}, {"cgi": "c2", "cell_name": "B", "station_name": "S2", "longitude": "0", "latitude": "0"}, {"cgi": "", "cell_name": "no key"}, ] cells = build_cells(rows, "4G") assert [(item["cgi"], item["cell_name"], item["station_name"], item["latitude"], item["longitude"]) for item in cells] == [ ("c1", "A", "S1", 22.5, 113.1), ("c2", "B", "S2", None, None), ] assert cells[0]["enodeb_id"] == "1" and cells[1]["network_type"] == "" assert set(cells[0]) == {"cgi", "latitude", "longitude"} | set(gongcan.ATTRIBUTES["4G"]) nr_rows = build_cells([{"ncgi": "", "cgi": "n1", "nrcell_name": "N", "gnodeb_id": "9", "longitude": "113", "latitude": "22"}], "5G") assert nr_rows == [{**nr_rows[0], "ncgi": "n1", "nrcell_name": "N", "gnodeb_id": "9", "latitude": 22.0, "longitude": 113.0}] assert "cgi" not in nr_rows[0] and "enodeb_id" not in nr_rows[0] class SnapshotOpenCode(OpenCode): def __init__(self, rows): self.base = "provisioned" self.rows = rows self.phases = [] self.cleaned = [] async def create_session(self): return "s1" async def export(self, session_id, files, retries=2): self.phases.append(files[0].phase) return {item.key: CsvTable(header=list(item.required), rows=self.rows["4G" if item.filename.startswith("lte") else "5G"]) for item in files} async def cleanup(self, session_id, task): self.cleaned.append(task) return True async def delete_session(self, session_id): return True PLATFORM_ROWS = { "4G": [{"cgi": "c1", "station_name": "OC站", "longitude": "113", "latitude": "22"}], "5G": [{"ncgi": "n1", "cgi": "n1", "station_name": "OC站", "longitude": "113", "latitude": "22"}], } def test_snapshot_comes_from_one_opencode_export(): oc = SnapshotOpenCode(PLATFORM_ROWS) cells = asyncio.run(fetch_snapshot(oc, CITY, date(2026, 11, 1))) assert oc.phases == ["gc"] and oc.cleaned == [snapshot_task_name(CITY, date(2026, 11, 1))] assert [(row["cgi"], row["station_name"], row["latitude"]) for row in cells["4G"]] == [("c1", "OC站", 22.0)] assert [(row["ncgi"], row["station_name"], row["latitude"]) for row in cells["5G"]] == [("n1", "OC站", 22.0)] def test_snapshot_rejects_empty_city(): oc = SnapshotOpenCode({"4G": [], "5G": PLATFORM_ROWS["5G"]}) with pytest.raises(GongcanError): asyncio.run(fetch_snapshot(oc, CITY, date(2026, 11, 1))) assert oc.cleaned == [snapshot_task_name(CITY, date(2026, 11, 1))] def test_store_answers_presence_queries(): store = make_store(Platform({}), {date(2026, 10, 1): with_target(), date(2026, 11, 1): without_target()}) assert store.ready_dates(CITY, date(2026, 10, 1), date(2026, 11, 2)) == [date(2026, 10, 1), date(2026, 11, 1)] assert store.ready_dates(CITY, date(2026, 10, 1), date(2026, 11, 1)) == [date(2026, 10, 1)] assert store.dates_with_target(CITY, SITE, date(2026, 1, 1), date(2027, 1, 1)) == [date(2026, 10, 1)] assert store.has_target(CITY, date(2026, 10, 1), Target(cgis=("zz", "t1"))) assert store.has_target(CITY, date(2026, 11, 1), Target(cgis=("n1",))) assert store.has_target(CITY, date(2026, 11, 1), Target(site="N")) assert not store.has_target(CITY, date(2026, 11, 1), Target(cgis=("t1",))) assert not store.has_target("广州", date(2026, 10, 1), SITE) loaded = store.cells(CITY, date(2026, 10, 1)) assert sorted((item["tech"], item["cgi"], item["cell_name"], item["site_name"]) for item in loaded) == [("4G", "t1", "T-A", "T"), ("5G", "n1", "N-N", "N")] assert loaded[0]["area"] == "" and loaded[0]["node_id"] == "" assert store.cells(CITY, date(2026, 9, 1)) == [] def test_ensure_loads_once_even_when_tasks_race(): platform = Platform({date(2026, 11, 1): with_target()}, delay=0.05) store = make_store(platform) async def race(): await asyncio.gather(store.ensure(CITY, date(2026, 11, 1)), store.ensure(CITY, date(2026, 11, 1))) asyncio.run(race()) asyncio.run(store.ensure(CITY, date(2026, 11, 1))) assert platform.fetched == [date(2026, 11, 1)] def test_failed_snapshot_cools_down_then_retries(): clock = Clock() platform = Platform({}) store = make_store(platform, clock=clock) with pytest.raises(GongcanError, match="平台没有这一天"): asyncio.run(store.ensure(CITY, date(2026, 11, 1))) with pytest.raises(GongcanError, match="刚取失败"): asyncio.run(store.ensure(CITY, date(2026, 11, 1))) assert platform.fetched == [date(2026, 11, 1)] clock.now += timedelta(minutes=11) platform.days[date(2026, 11, 1)] = with_target() asyncio.run(store.ensure(CITY, date(2026, 11, 1))) assert platform.fetched == [date(2026, 11, 1)] * 2 and store.has_target(CITY, date(2026, 11, 1), SITE) def test_stale_loading_is_taken_over(): clock = Clock() store = make_store(Platform({}), clock=clock) assert claim_snapshot(store.engine, CITY, date(2026, 11, 1), clock()) is not None assert claim_snapshot(store.engine, CITY, date(2026, 11, 1), clock() + timedelta(minutes=5)) is None assert claim_snapshot(store.engine, CITY, date(2026, 11, 1), clock() + timedelta(minutes=41)) is not None def test_release_loading_frees_snapshots_left_by_a_dead_worker(): clock = Clock() store = make_store(Platform({date(2026, 11, 2): with_target()}), {date(2026, 10, 26): with_target()}, clock=clock) assert claim_snapshot(store.engine, CITY, date(2026, 11, 2), clock()) is not None assert store.next_to_fill(CITY, [date(2026, 11, 2)]) is None assert release_loading(store.engine) == 1 assert store.next_to_fill(CITY, [date(2026, 11, 2)]) == date(2026, 11, 2) assert store.ready_dates(CITY, date(2026, 10, 1), date(2026, 12, 1)) == [date(2026, 10, 26)] def test_next_to_fill_takes_one_at_a_time_and_backs_off_after_a_failure(): clock = Clock() newest_first = [date(2026, 11, 2), date(2026, 10, 26), date(2026, 10, 19)] platform = Platform({date(2026, 10, 26): with_target(), date(2026, 10, 19): with_target()}) store = make_store(platform, {date(2026, 10, 19): with_target()}, clock=clock) assert store.missing_dates(CITY, newest_first) == [date(2026, 11, 2), date(2026, 10, 26)] assert store.missing_dates(CITY, []) == [] assert store.next_to_fill(CITY, newest_first) == date(2026, 11, 2) with pytest.raises(GongcanError): asyncio.run(store.fill(CITY, date(2026, 11, 2))) # 刚失败:冷却期内整个地市都不再取。 assert store.next_to_fill(CITY, newest_first) is None clock.now += timedelta(minutes=11) # 冷却过后先补没失败过的,失败过的排到最后。 assert store.next_to_fill(CITY, newest_first) == date(2026, 10, 26) assert asyncio.run(store.fill(CITY, date(2026, 10, 26))) is True assert store.next_to_fill(CITY, newest_first) == date(2026, 11, 2) assert asyncio.run(store.fill(CITY, date(2026, 10, 26))) is False assert store.next_to_fill(CITY, [date(2026, 10, 26), date(2026, 10, 19)]) is None assert platform.fetched == [date(2026, 11, 2), date(2026, 10, 26)] # 拆除日 2026-10-15 是周四:上一周的周一是 10-05,下一周的周一是 10-19。 REMOVAL = date(2026, 10, 15) TODAY = date(2026, 11, 12) def test_before_is_the_monday_of_the_week_before_removal(): platform = Platform({}) store = make_store(platform, {date(2026, 9, 28): with_target(), date(2026, 10, 5): with_target(), date(2026, 10, 12): with_target()}) assert asyncio.run(pick_before(store, CITY, SITE, REMOVAL, TODAY)) == date(2026, 10, 5) assert platform.fetched == [] def test_before_fetches_the_monday_when_it_is_not_cached(): platform = Platform({date(2026, 10, 5): with_target()}) store = make_store(platform, {date(2026, 9, 28): with_target()}) assert asyncio.run(pick_before(store, CITY, SITE, REMOVAL, TODAY)) == date(2026, 10, 5) assert platform.fetched == [date(2026, 10, 5)] def test_before_walks_back_week_by_week_when_target_is_missing(): platform = Platform({date(2026, 9, 28): without_target(), date(2026, 9, 21): with_target()}) store = make_store(platform, {date(2026, 10, 5): without_target()}) assert asyncio.run(pick_before(store, CITY, SITE, REMOVAL, TODAY)) == date(2026, 9, 21) assert platform.fetched == [date(2026, 9, 28), date(2026, 9, 21)] def test_before_fails_after_four_more_weeks(): mondays = [date(2026, 10, 5), date(2026, 9, 28), date(2026, 9, 21), date(2026, 9, 14), date(2026, 9, 7)] platform = Platform({}) store = make_store(platform, {day: without_target() for day in mondays} | {date(2026, 8, 31): with_target()}) with pytest.raises(GongcanMissing, match="站点 T"): asyncio.run(pick_before(store, CITY, SITE, REMOVAL, TODAY)) assert platform.fetched == [] def test_before_uses_latest_available_monday_for_a_future_removal(): platform = Platform({}) store = make_store(platform, {date(2026, 11, 9): with_target()}) assert asyncio.run(pick_before(store, CITY, SITE, date(2026, 12, 20), TODAY)) == date(2026, 11, 9) with pytest.raises(GongcanMissing, match="太早"): asyncio.run(pick_before(store, CITY, SITE, date(2024, 1, 5), TODAY)) assert platform.fetched == [] def test_after_is_the_monday_after_the_removal_week_and_target_may_still_be_there(): platform = Platform({date(2026, 10, 19): with_target()}) store = make_store(platform, {date(2026, 10, 12): with_target(), date(2026, 10, 26): without_target()}) assert asyncio.run(pick_after(store, CITY, SITE, REMOVAL, TODAY)) == AfterPick(date(2026, 10, 19), True) # 拆除日正好是周一,也用下一周的周一。 assert asyncio.run(pick_after(store, CITY, SITE, date(2026, 10, 19), TODAY)) == AfterPick(date(2026, 10, 26), False) assert platform.fetched == [date(2026, 10, 19)] def test_after_is_empty_until_that_monday_can_be_fetched(): store = make_store(Platform({})) # 拆除日 11-03 的下一周周一是 11-09,11-12 起可取;拆除日 11-10 的是 11-16,还不行。 assert asyncio.run(pick_after(store, CITY, SITE, date(2026, 11, 3), date(2026, 11, 11))) is None assert asyncio.run(pick_after(store, CITY, SITE, date(2026, 11, 10), TODAY)) is None with pytest.raises(GongcanError, match="平台没有这一天"): asyncio.run(pick_after(store, CITY, SITE, date(2026, 11, 3), TODAY)) def test_target_needs_cgis_or_site(): with pytest.raises(ValueError): Target() with pytest.raises(ValueError): Target(cgis=("a",), site="b") def test_nearest_sites_uses_template_rules(): pool = [ cell("t", "target"), cell("a", "near", lat=22.001), cell("b", "near", lat=22.003), cell("c", "indoor", lat=22.0005, name="W-室分"), cell("d", "iot", lat=22.0005, network_type="NB-IoT"), cell("e", "small", lat=22.0005, name="微小站"), cell("f", "same_spot"), cell("g", "nr", lat=22.004, tech="5G", network_type="NR"), cell("h", "unknown", lat=None, lon=None), cell("i", "far", lat=22.2), ] found = nearest_sites(pool, 22.0, 113.0, exclude={"target"}, k=3) assert [site for site, _ in found] == ["near", "nr", "far"] assert 210 < found[0][1] < 235 def test_target_center_falls_back_to_indoor_cells(): assert target_center([cell("a", "T", lat=22.0), cell("b", "T", lat=22.002), cell("c", "T", lat=23.0, name="W-x")]) == pytest.approx((22.001, 113.0)) assert target_center([cell("c", "T", lat=23.0, name="W-x")]) == (23.0, 113.0) assert target_center([cell("c", "T", lat=None, lon=None)]) is None