feat: 工参小区按制式拆成 CellData_4G、CellData_5G;即席查询补上页面必带参数

两张表列名沿用平台工参表,已有快照由迁移 0008 原样搬过去。即席查询的 result 补 tableParams、columnname,计数补 indexcount=0,缺这些服务端会返回 stat 0。
This commit is contained in:
2026-11-11 02:30:21 +08:00
parent dcd0a87cc3
commit 33d132d7b6
8 changed files with 304 additions and 76 deletions
@@ -0,0 +1,83 @@
"""工参小区按制式拆成 CellData_4G、CellData_5G,列名沿用平台工参表,已有快照原样搬过去。"""
from alembic import op
import sqlalchemy as sa
revision = "0008_celldata_split"
down_revision = "0007_gongcan_snapshot"
branch_labels = None
depends_on = None
SHARED = ("network_type", "area", "town", "state", "cover_type", "frequency_band", "vendor", "azimuth")
def _text(name: str) -> sa.Column:
return sa.Column(name, sa.Text(), nullable=False, server_default="")
def _cell_table(name: str, key: str, cell_name: str, node: str, prefix: str) -> None:
op.create_table(
name,
sa.Column("id", sa.BigInteger().with_variant(sa.Integer(), "sqlite"), primary_key=True),
sa.Column("snapshot_id", sa.Integer(), sa.ForeignKey("gongcan_snapshot.id", ondelete="CASCADE"), nullable=False),
sa.Column(key, sa.String(64), nullable=False),
_text(cell_name),
_text("station_name"),
sa.Column("latitude", sa.Float(), nullable=True),
sa.Column("longitude", sa.Float(), nullable=True),
_text(f"{node}_id"),
_text(f"{node}_name"),
*[_text(column) for column in SHARED],
sa.UniqueConstraint("snapshot_id", key, name=f"uq_{prefix}_{key}"),
)
op.create_index(f"ix_{prefix}_station", name, ["snapshot_id", "station_name"])
def upgrade() -> None:
_cell_table("CellData_4G", "cgi", "cell_name", "enodeb", "celldata_4g")
_cell_table("CellData_5G", "ncgi", "nrcell_name", "gnodeb", "celldata_5g")
shared = ", ".join(SHARED)
op.execute(
'insert into "CellData_4G" (snapshot_id, cgi, cell_name, station_name, latitude, longitude, enodeb_id, enodeb_name, '
f"{shared}) select snapshot_id, cgi, cell_name, site_name, latitude, longitude, node_id, node_name, {shared} "
"from gongcan_cell where tech = '4G'"
)
op.execute(
'insert into "CellData_5G" (snapshot_id, ncgi, nrcell_name, station_name, latitude, longitude, gnodeb_id, gnodeb_name, '
f"{shared}) select snapshot_id, cgi, cell_name, site_name, latitude, longitude, node_id, node_name, {shared} "
"from gongcan_cell where tech = '5G'"
)
op.drop_index("ix_gongcan_cell_site", table_name="gongcan_cell")
op.drop_table("gongcan_cell")
def downgrade() -> None:
op.create_table(
"gongcan_cell",
sa.Column("id", sa.BigInteger().with_variant(sa.Integer(), "sqlite"), primary_key=True),
sa.Column("snapshot_id", sa.Integer(), sa.ForeignKey("gongcan_snapshot.id", ondelete="CASCADE"), nullable=False),
sa.Column("tech", sa.String(4), nullable=False),
sa.Column("cgi", sa.String(64), nullable=False),
_text("cell_name"),
_text("site_name"),
sa.Column("latitude", sa.Float(), nullable=True),
sa.Column("longitude", sa.Float(), nullable=True),
_text("node_id"),
_text("node_name"),
*[_text(column) for column in SHARED],
sa.UniqueConstraint("snapshot_id", "cgi", "tech", name="uq_gongcan_cell"),
)
op.create_index("ix_gongcan_cell_site", "gongcan_cell", ["snapshot_id", "site_name"])
shared = ", ".join(SHARED)
op.execute(
f"insert into gongcan_cell (snapshot_id, tech, cgi, cell_name, site_name, latitude, longitude, node_id, node_name, {shared}) "
f'select snapshot_id, \'4G\', cgi, cell_name, station_name, latitude, longitude, enodeb_id, enodeb_name, {shared} from "CellData_4G"'
)
op.execute(
f"insert into gongcan_cell (snapshot_id, tech, cgi, cell_name, site_name, latitude, longitude, node_id, node_name, {shared}) "
f'select snapshot_id, \'5G\', ncgi, nrcell_name, station_name, latitude, longitude, gnodeb_id, gnodeb_name, {shared} from "CellData_5G"'
)
op.drop_index("ix_celldata_5g_station", table_name="CellData_5G")
op.drop_table("CellData_5G")
op.drop_index("ix_celldata_4g_station", table_name="CellData_4G")
op.drop_table("CellData_4G")
+61 -32
View File
@@ -15,11 +15,11 @@ from collections.abc import Awaitable, Callable
from dataclasses import dataclass
from datetime import date, datetime, timedelta, timezone
from sqlalchemy import delete, exists, insert, select, update
from sqlalchemy import delete, exists, insert, or_, select, update
from sqlalchemy.engine import Engine
from sqlalchemy.exc import IntegrityError
from app.models import GongcanCell, GongcanSnapshot, utcnow
from app.models import CellData4G, CellData5G, GongcanSnapshot, utcnow
from app.nqi import adhoc
from app.nqi.client import NqiClient, NqiError
from app.nqi.opencode import EFFECTIVE, ExportFile, OpenCode, snapshot_where, task_session
@@ -30,11 +30,13 @@ TECHS = ("4G", "5G")
ADHOC_TABLES = {"4G": "appdbv3.v_a_common_cfg_lte_cellant_d", "5G": "appdbv3.a_common_cfg_nr_cellant_d"}
PLATFORM_TABLES = {"4G": "appdbv3.a_common_cfg_lte_cellant_d", "5G": "appdbv3.a_common_cfg_nr_cellant_d"}
KEYS = {"4G": ("cgi",), "5G": ("ncgi", "cgi")}
NAMED_FIELDS = {
"4G": {"cell_name": "cell_name", "site_name": "station_name", "node_id": "enodeb_id", "node_name": "enodeb_name"},
"5G": {"cell_name": "nrcell_name", "site_name": "station_name", "node_id": "gnodeb_id", "node_name": "gnodeb_name"},
}
KEY_COLUMN = {"4G": "cgi", "5G": "ncgi"}
SHARED_FIELDS = ("network_type", "area", "town", "state", "cover_type", "frequency_band", "vendor", "azimuth")
ATTRIBUTES = {
"4G": ("cell_name", "station_name", "enodeb_id", "enodeb_name") + SHARED_FIELDS,
"5G": ("nrcell_name", "station_name", "gnodeb_id", "gnodeb_name") + SHARED_FIELDS,
}
CELL_TABLES = {"4G": CellData4G.__table__, "5G": CellData5G.__table__}
COORDS = ("longitude", "latitude")
MATCH_RATIO = 0.98
FAILED_COOLDOWN = timedelta(minutes=10)
@@ -66,7 +68,7 @@ class Target:
def attribute_columns(tech: str) -> tuple[str, ...]:
return tuple(NAMED_FIELDS[tech].values()) + SHARED_FIELDS
return ATTRIBUTES[tech]
def adhoc_fields(tech: str) -> tuple[str, ...]:
@@ -124,21 +126,38 @@ def coordinates(rows: list[dict], tech: str) -> dict[str, tuple[float, float]]:
def build_cells(attr_rows: list[dict], coord_rows: list[dict], tech: str) -> list[dict]:
"""按 CellData_4G / CellData_5G 的列名组成一行一个小区。"""
coords = coordinates(coord_rows, tech)
mapping = {**NAMED_FIELDS[tech], **{name: name for name in SHARED_FIELDS}}
cells: dict[str, dict] = {}
for row in attr_rows:
key = key_of(row, tech)
if not key or key in cells:
continue
lat, lon = coords.get(key, (None, None))
cell = {"tech": tech, "cgi": key, "latitude": lat, "longitude": lon}
for target, source in mapping.items():
cell[target] = str(row.get(source) or "").strip()
cell = {KEY_COLUMN[tech]: key, "latitude": lat, "longitude": lon}
for column in ATTRIBUTES[tech]:
cell[column] = str(row.get(column) or "").strip()
cells[key] = cell
return list(cells.values())
def unified(row, tech: str) -> dict:
"""两张表的行换成同一套字段,邻站等计算不用分制式。"""
name, site, node_id, node_name = ATTRIBUTES[tech][:4]
item = {
"tech": tech,
"cgi": row[KEY_COLUMN[tech]],
"cell_name": row[name],
"site_name": row[site],
"node_id": row[node_id],
"node_name": row[node_name],
"latitude": row["latitude"],
"longitude": row["longitude"],
}
item.update({column: row[column] for column in SHARED_FIELDS})
return item
def key_overlap(attr_rows: list[dict], coord_rows: list[dict], tech: str) -> float:
left = {key_of(row, tech) for row in attr_rows} - {""}
right = {key_of(row, tech) for row in coord_rows} - {""}
@@ -147,8 +166,8 @@ def key_overlap(attr_rows: list[dict], coord_rows: list[dict], tech: str) -> flo
return len(left & right) / len(left | right)
async def fetch_snapshot(nqi: NqiClient, oc: OpenCode, city: str, day: date, *, use_adhoc: bool = True) -> tuple[list[dict], str]:
"""从大数据平台取一份快照,返回小区列表和属性来源(adhoc / opencode)。"""
async def fetch_snapshot(nqi: NqiClient, oc: OpenCode, city: str, day: date, *, use_adhoc: bool = True) -> tuple[dict[str, list[dict]], str]:
"""从大数据平台取一份快照,返回按制式分开的小区行和属性来源(adhoc / opencode)。"""
attrs: dict[str, list[dict]] | None = None
if use_adhoc:
try:
@@ -171,14 +190,13 @@ async def fetch_snapshot(nqi: NqiClient, oc: OpenCode, city: str, day: date, *,
rows = {tech: tables[item.key].rows for tech, item in zip(TECHS, files)}
source = "adhoc" if attrs is not None else "opencode"
attrs = attrs if attrs is not None else rows
cells = [cell for tech in TECHS for cell in build_cells(attrs[tech], rows[tech], tech)]
if not any(cell["tech"] == "4G" for cell in cells) or not any(cell["tech"] == "5G" for cell in cells):
cells = {tech: build_cells(attrs[tech], rows[tech], tech) for tech in TECHS}
if not all(cells.values()):
raise GongcanError(f"{city} {day} 的工参是空的")
return cells, source
_SNAPSHOT = GongcanSnapshot.__table__
_CELL = GongcanCell.__table__
def _aware(value: datetime) -> datetime:
@@ -212,20 +230,22 @@ def claim_snapshot(engine: Engine, city: str, day: date, now: datetime) -> int |
return int(row.id) if taken.rowcount == 1 else None
def save_snapshot(engine: Engine, snapshot_id: int, cells: list[dict], source: str, now: datetime) -> None:
def save_snapshot(engine: Engine, snapshot_id: int, cells: dict[str, list[dict]], source: str, now: datetime) -> None:
with engine.begin() as connection:
connection.execute(delete(_CELL).where(_CELL.c.snapshot_id == snapshot_id))
for start in range(0, len(cells), 2000):
connection.execute(insert(_CELL), [{**cell, "snapshot_id": snapshot_id} for cell in cells[start:start + 2000]])
for tech, table in CELL_TABLES.items():
rows = cells.get(tech) or []
connection.execute(delete(table).where(table.c.snapshot_id == snapshot_id))
for start in range(0, len(rows), 2000):
connection.execute(insert(table), [{**row, "snapshot_id": snapshot_id} for row in rows[start:start + 2000]])
connection.execute(
update(_SNAPSHOT)
.where(_SNAPSHOT.c.id == snapshot_id)
.values(
status="ready",
attr_source=source,
lte_cells=sum(1 for cell in cells if cell["tech"] == "4G"),
nr_cells=sum(1 for cell in cells if cell["tech"] == "5G"),
located_cells=sum(1 for cell in cells if cell["latitude"] is not None),
lte_cells=len(cells.get("4G") or []),
nr_cells=len(cells.get("5G") or []),
located_cells=sum(1 for rows in cells.values() for row in rows if row["latitude"] is not None),
error="",
updated_at=now,
)
@@ -238,8 +258,11 @@ def fail_snapshot(engine: Engine, snapshot_id: int, error: str, now: datetime) -
def _has_target(target: Target):
condition = _CELL.c.site_name == target.site if target.site else _CELL.c.cgi.in_(target.cgis)
return exists(select(_CELL.c.id).where(_CELL.c.snapshot_id == _SNAPSHOT.c.id, condition))
found = []
for tech, table in CELL_TABLES.items():
condition = table.c.station_name == target.site if target.site else table.c[KEY_COLUMN[tech]].in_(target.cgis)
found.append(exists(select(table.c.id).where(table.c.snapshot_id == _SNAPSHOT.c.id, condition)))
return or_(*found)
def _ready(city: str, start: date, end: date):
@@ -252,7 +275,7 @@ class GongcanStore:
def __init__(
self,
engine: Engine,
loader: Callable[[str, date], Awaitable[tuple[list[dict], str]]],
loader: Callable[[str, date], Awaitable[tuple[dict[str, list[dict]], str]]],
*,
poll_seconds: float = 10.0,
wait_timeout: timedelta = timedelta(minutes=45),
@@ -278,10 +301,16 @@ class GongcanStore:
return bool(self.dates_with_target(city, target, day, day + timedelta(days=1)))
def cells(self, city: str, day: date) -> list[dict]:
columns = [column for column in _CELL.c if column.name not in ("id", "snapshot_id")]
"""当天快照里 4G、5G 的全部小区,字段见 unified。"""
with self.engine.connect() as connection:
query = select(*columns).join(_SNAPSHOT, _SNAPSHOT.c.id == _CELL.c.snapshot_id).where(*_ready(city, day, day + timedelta(days=1)))
return [dict(row._mapping) for row in connection.execute(query)]
snapshot_id = connection.execute(select(_SNAPSHOT.c.id).where(*_ready(city, day, day + timedelta(days=1)))).scalar()
if snapshot_id is None:
return []
return [
unified(row, tech)
for tech, table in CELL_TABLES.items()
for row in connection.execute(select(table).where(table.c.snapshot_id == snapshot_id)).mappings()
]
def _state(self, city: str, day: date):
with self.engine.connect() as connection:
@@ -314,13 +343,13 @@ class GongcanStore:
except BaseException as exc:
fail_snapshot(self.engine, snapshot_id, f"{type(exc).__name__}: {exc}", self.clock())
raise
logger.info("工参快照 %s %s 已入库:%s 个小区,属性来自 %s", city, day, len(cells), source)
logger.info("工参快照 %s %s 已入库:4G %s 个、5G %s 个小区,属性来自 %s", city, day, len(cells.get("4G") or []), len(cells.get("5G") or []), source)
def platform_loader(nqi: NqiClient, *, use_adhoc: bool = True) -> Callable[[str, date], Awaitable[tuple[list[dict], str]]]:
def platform_loader(nqi: NqiClient, *, use_adhoc: bool = True) -> Callable[[str, date], Awaitable[tuple[dict[str, list[dict]], str]]]:
oc = OpenCode(nqi)
async def load(city: str, day: date) -> tuple[list[dict], str]:
async def load(city: str, day: date) -> tuple[dict[str, list[dict]], str]:
return await fetch_snapshot(nqi, oc, city, day, use_adhoc=use_adhoc)
return load
+2 -1
View File
@@ -33,7 +33,8 @@ APP_TABLES = {
"collection_source",
"export_task",
"gongcan_snapshot",
"gongcan_cell",
"celldata_4g",
"celldata_5g",
}
_UNSAFE = re.compile(r"[^0-9A-Za-z_]+")
_CHUNK = 300
+37 -8
View File
@@ -101,24 +101,53 @@ class GongcanSnapshot(Base):
updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow)
class GongcanCell(Base):
__tablename__ = "gongcan_cell"
class CellData4G(Base):
"""4G 小区工参快照,列名沿用平台 4G 工参表。"""
__tablename__ = "CellData_4G"
__table_args__ = (
UniqueConstraint("snapshot_id", "cgi", "tech", name="uq_gongcan_cell"),
Index("ix_gongcan_cell_site", "snapshot_id", "site_name"),
UniqueConstraint("snapshot_id", "cgi", name="uq_celldata_4g_cgi"),
Index("ix_celldata_4g_station", "snapshot_id", "station_name"),
)
id: Mapped[int] = mapped_column(BigInteger().with_variant(Integer, "sqlite"), primary_key=True)
snapshot_id: Mapped[int] = mapped_column(ForeignKey("gongcan_snapshot.id", ondelete="CASCADE"))
tech: Mapped[str] = mapped_column(String(4))
cgi: Mapped[str] = mapped_column(String(64))
cell_name: Mapped[str] = mapped_column(Text, default="")
site_name: Mapped[str] = mapped_column(Text, default="")
station_name: Mapped[str] = mapped_column(Text, default="")
latitude: Mapped[float | None] = mapped_column(Float, nullable=True)
longitude: Mapped[float | None] = mapped_column(Float, nullable=True)
enodeb_id: Mapped[str] = mapped_column(Text, default="")
enodeb_name: Mapped[str] = mapped_column(Text, default="")
network_type: Mapped[str] = mapped_column(Text, default="")
area: Mapped[str] = mapped_column(Text, default="")
town: Mapped[str] = mapped_column(Text, default="")
state: Mapped[str] = mapped_column(Text, default="")
cover_type: Mapped[str] = mapped_column(Text, default="")
frequency_band: Mapped[str] = mapped_column(Text, default="")
vendor: Mapped[str] = mapped_column(Text, default="")
azimuth: Mapped[str] = mapped_column(Text, default="")
class CellData5G(Base):
"""5G 小区工参快照,列名沿用平台 5G 工参表。"""
__tablename__ = "CellData_5G"
__table_args__ = (
UniqueConstraint("snapshot_id", "ncgi", name="uq_celldata_5g_ncgi"),
Index("ix_celldata_5g_station", "snapshot_id", "station_name"),
)
id: Mapped[int] = mapped_column(BigInteger().with_variant(Integer, "sqlite"), primary_key=True)
snapshot_id: Mapped[int] = mapped_column(ForeignKey("gongcan_snapshot.id", ondelete="CASCADE"))
ncgi: Mapped[str] = mapped_column(String(64))
nrcell_name: Mapped[str] = mapped_column(Text, default="")
station_name: Mapped[str] = mapped_column(Text, default="")
latitude: Mapped[float | None] = mapped_column(Float, nullable=True)
longitude: Mapped[float | None] = mapped_column(Float, nullable=True)
gnodeb_id: Mapped[str] = mapped_column(Text, default="")
gnodeb_name: Mapped[str] = mapped_column(Text, default="")
network_type: Mapped[str] = mapped_column(Text, default="")
node_id: Mapped[str] = mapped_column(Text, default="")
node_name: Mapped[str] = mapped_column(Text, default="")
area: Mapped[str] = mapped_column(Text, default="")
town: Mapped[str] = mapped_column(Text, default="")
state: Mapped[str] = mapped_column(Text, default="")
+17 -5
View File
@@ -145,7 +145,6 @@ async def export_table(
if not columns:
raise NqiError("这张表没有可导出的字段")
title = str(columns[0].get("tablename_cn") or tablename)
selected = [_field(column) for column in columns]
where = _where(columns[0], start, end, city)
common = {
"geographicdimension": columns[0].get("geographicdimension") or "",
@@ -155,7 +154,7 @@ async def export_table(
"timeField": columns[0].get("time_field") or "starttime",
"cellField": columns[0].get("cell_field") or "",
"cityField": columns[0].get("city_field") or "city",
"result": json.dumps({"result": selected}, ensure_ascii=False),
"result": _result_json(columns[0], columns),
"where": json.dumps(where, ensure_ascii=False),
}
total, index_count = await _count(client, common)
@@ -222,7 +221,7 @@ async def export_day(
"timeField": head.get("time_field") or "starttime",
"cellField": head.get("cell_field") or "",
"cityField": head.get("city_field") or "city",
"result": json.dumps({"result": [_field(column) for column in selected]}, ensure_ascii=False),
"result": _result_json(head, selected),
"where": json.dumps(_where(head, _start(day), _end(day), city), ensure_ascii=False),
}
total, index_count = await _count(client, common)
@@ -266,14 +265,27 @@ def _first_choice(value: object) -> str:
async def _count(client: NqiClient, common: dict) -> tuple[int, str]:
"""平台出错时返回 {"stat":"0"},没有 count。不能当成 0 行。"""
counted = await _post_json(client, f"{PAGE}/getTableCount", common)
"""平台出错时返回 {"stat":"0"},没有 count。不能当成 0 行。页面第一次计数总是带 indexcount=0,缺了会报错。"""
counted = await _post_json(client, f"{PAGE}/getTableCount", {**common, "indexcount": "0"})
if not isinstance(counted, dict) or "count" not in counted:
message = counted.get("message") if isinstance(counted, dict) else ""
raise NqiError(f"即席查询没有返回行数{f':{message}' if message and message != 'null' else ''}")
return int(counted.get("count") or 0), str(counted.get("indexcount") or "0")
def _result_json(head: dict, columns: list[dict]) -> str:
"""页面在字段列表后还带 tableParams 和 columnname,缺了服务端返回 {"stat":"0","message":"null"}。"""
payload = {
"result": [_field(column) for column in columns],
"tableParams": {
"supporteddimension": head.get("supporteddimension"),
"supportedtimedimension": head.get("supportedtimedimension") or "",
},
"columnname": "",
}
return json.dumps(payload, ensure_ascii=False)
def _field(column: dict) -> dict:
return {
"feildtype": column.get("fieldtype") or "",
+43
View File
@@ -0,0 +1,43 @@
import asyncio
import json
import pytest
from app.nqi import adhoc
from app.nqi.client import NqiError
HEAD = {
"tablename": "appdbv3.v_a_common_cfg_lte_cellant_d",
"tablename_cn": "4G小区工参",
"columnname": "cgi",
"columnname_cn": "CGI",
"fieldtype": "基础信息",
"datatype": "character varying",
"columntype": 1,
"supporteddimension": None,
"supportedtimedimension": None,
}
def test_result_json_carries_table_params_like_the_page():
payload = json.loads(adhoc._result_json(HEAD, [HEAD]))
assert list(payload) == ["result", "tableParams", "columnname"]
assert payload["tableParams"] == {"supporteddimension": None, "supportedtimedimension": ""}
assert payload["columnname"] == ""
assert payload["result"][0]["feild"] == "cgi" and payload["result"][0]["table"] == HEAD["tablename"]
def test_count_sends_indexcount_and_rejects_error_payload(monkeypatch):
sent = []
replies = [{"count": 37604, "indexcount": "0"}, {"stat": "0", "message": "null"}, {}]
async def fake_post(client, url, form):
sent.append((url.rsplit("/", 1)[-1], form))
return replies[len(sent) - 1]
monkeypatch.setattr(adhoc, "_post_json", fake_post)
assert asyncio.run(adhoc._count(None, {"where": "[]"})) == (37604, "0")
assert sent[0][0] == "getTableCount" and sent[0][1] == {"where": "[]", "indexcount": "0"}
for _ in range(2):
with pytest.raises(NqiError):
asyncio.run(adhoc._count(None, {"where": "[]"}))
+28 -13
View File
@@ -25,7 +25,7 @@ from app.collect.gongcan import (
snapshot_task_name,
target_center,
)
from app.models import Base, GongcanCell, GongcanSnapshot
from app.models import Base, CellData4G, CellData5G, GongcanSnapshot
from app.nqi.client import NqiError
from app.nqi.opencode import CsvTable, OpenCode
@@ -37,12 +37,20 @@ 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 with_target(*others):
return [cell("t1", "T"), cell("n1", "N", tech="5G")] + [cell(f"x{i}", name) for i, name in enumerate(others)]
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 [cell("n1", "N", tech="5G"), cell("o1", "O")]
return {"4G": [lte("o1", "O")], "5G": [nr("n1", "N")]}
class Clock:
@@ -70,7 +78,7 @@ class Platform:
def make_store(platform, stored=None, clock=None):
db = create_engine("sqlite://")
Base.metadata.create_all(db, tables=[GongcanSnapshot.__table__, GongcanCell.__table__])
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())
@@ -111,13 +119,15 @@ def test_build_cells_merges_coordinates_by_cgi():
{"cgi": "c2", "longitude": "0", "latitude": "0"},
]
cells = build_cells(attrs, coords, "4G")
assert [(item["cgi"], item["cell_name"], item["site_name"], item["latitude"], item["longitude"]) for item in cells] == [
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]["node_id"] == "1" and cells[0]["tech"] == "4G" and cells[1]["network_type"] == ""
nr = build_cells([{"ncgi": "", "cgi": "n1", "nrcell_name": "N", "gnodeb_id": "9"}], [{"ncgi": "n1", "longitude": "113", "latitude": "22"}], "5G")
assert nr == [{**nr[0], "cgi": "n1", "cell_name": "N", "node_id": "9", "latitude": 22.0, "longitude": 113.0}]
assert cells[0]["enodeb_id"] == "1" and cells[1]["network_type"] == ""
assert set(cells[0]) == {"cgi", "latitude", "longitude"} | set(gongcan.ATTRIBUTES["4G"])
rows = build_cells([{"ncgi": "", "cgi": "n1", "nrcell_name": "N", "gnodeb_id": "9"}], [{"ncgi": "n1", "longitude": "113", "latitude": "22"}], "5G")
assert rows == [{**rows[0], "ncgi": "n1", "nrcell_name": "N", "gnodeb_id": "9", "latitude": 22.0, "longitude": 113.0}]
assert "cgi" not in rows[0] and "enodeb_id" not in rows[0]
def test_key_overlap():
@@ -167,19 +177,20 @@ def test_snapshot_takes_attributes_from_adhoc_and_coordinates_from_opencode(monk
oc = SnapshotOpenCode(PLATFORM_ROWS)
cells, source = asyncio.run(fetch_snapshot(None, oc, CITY, date(2026, 11, 1)))
assert source == "adhoc" and oc.phases == ["xy"] and oc.cleaned == [snapshot_task_name(CITY, date(2026, 11, 1))]
assert [(item["tech"], item["site_name"], item["latitude"]) for item in cells] == [("4G", "即席站", 22.0), ("5G", "即席站", 22.0)]
assert [(row["cgi"], row["station_name"], row["latitude"]) for row in cells["4G"]] == [("c1", "即席站", 22.0)]
assert [(row["ncgi"], row["station_name"], row["latitude"]) for row in cells["5G"]] == [("n1", "即席站", 22.0)]
def test_snapshot_falls_back_to_opencode_attributes(monkeypatch):
adhoc_returns(monkeypatch, NqiError("即席查询没有返回行数"))
oc = SnapshotOpenCode(PLATFORM_ROWS)
cells, source = asyncio.run(fetch_snapshot(None, oc, CITY, date(2026, 11, 1)))
assert source == "opencode" and oc.phases == ["attr"] and cells[0]["site_name"] == "OC站"
assert source == "opencode" and oc.phases == ["attr"] and cells["4G"][0]["station_name"] == "OC站"
adhoc_returns(monkeypatch, {"4G": [{"cgi": "other"}], "5G": [{"ncgi": "n1"}]})
mismatch = SnapshotOpenCode(PLATFORM_ROWS)
cells, source = asyncio.run(fetch_snapshot(None, mismatch, CITY, date(2026, 11, 1)))
assert source == "opencode" and mismatch.phases == ["xy", "attr"] and cells[0]["cgi"] == "c1"
assert source == "opencode" and mismatch.phases == ["xy", "attr"] and cells["4G"][0]["cgi"] == "c1"
def test_snapshot_rejects_empty_city(monkeypatch):
@@ -194,10 +205,14 @@ def test_store_answers_presence_queries():
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 {item["cgi"] for item in loaded} == {"t1", "n1"} and loaded[0]["area"] == ""
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():