feat: 工参按地市和日期入库,先查库再从大数据平台取
即席查询取工参属性,OpenCode 导出当天全市 CGI 和经纬度,按 CGI 合并后存成快照;即席查询失败或 CGI 对不上时改由 OpenCode 一并导出属性。拆除前后的工参日期按库优先、逐月回溯的规则选取,多个任务取同一天时只取一次。即席查询 getTableCount 出错不再被当成 0 行。
This commit is contained in:
@@ -0,0 +1,329 @@
|
||||
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 (
|
||||
AfterPick,
|
||||
GongcanError,
|
||||
GongcanMissing,
|
||||
GongcanStore,
|
||||
Target,
|
||||
build_cells,
|
||||
claim_snapshot,
|
||||
fetch_snapshot,
|
||||
key_overlap,
|
||||
month_start,
|
||||
nearest_sites,
|
||||
pick_after,
|
||||
pick_before,
|
||||
platform_files,
|
||||
save_snapshot,
|
||||
snapshot_task_name,
|
||||
target_center,
|
||||
)
|
||||
from app.models import Base, GongcanCell, GongcanSnapshot
|
||||
from app.nqi.client import NqiError
|
||||
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 with_target(*others):
|
||||
return [cell("t1", "T"), cell("n1", "N", tech="5G")] + [cell(f"x{i}", name) for i, name in enumerate(others)]
|
||||
|
||||
|
||||
def without_target():
|
||||
return [cell("n1", "N", tech="5G"), cell("o1", "O")]
|
||||
|
||||
|
||||
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], "opencode"
|
||||
|
||||
|
||||
def make_store(platform, stored=None, clock=None):
|
||||
db = create_engine("sqlite://")
|
||||
Base.metadata.create_all(db, tables=[GongcanSnapshot.__table__, GongcanCell.__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, "adhoc", clock())
|
||||
return GongcanStore(db, platform, poll_seconds=0.01, clock=clock)
|
||||
|
||||
|
||||
def test_month_start_crosses_year():
|
||||
assert month_start(date(2026, 1, 10), -1) == date(2025, 12, 1)
|
||||
assert month_start(date(2026, 1, 10), -3) == date(2025, 10, 1)
|
||||
assert month_start(date(2026, 11, 30)) == date(2026, 11, 1)
|
||||
|
||||
|
||||
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), attributes=False)
|
||||
assert lte.sql.startswith("select cgi, longitude, latitude, eff_from_date, eff_to_date from appdbv3.a_common_cfg_lte_cellant_d where city = '江门'")
|
||||
assert nr.sql.startswith("select ncgi, cgi, longitude, latitude,")
|
||||
assert "make_date(2026, 11, 1)" in lte.sql and not re.search(r"\d{4}-\d{2}-\d{2}", lte.sql + nr.sql)
|
||||
assert (lte.phase, lte.key, nr.key) == ("xy", "xy/lte", "xy/nr")
|
||||
lte_attr, nr_attr = platform_files(task, CITY, date(2026, 11, 1), attributes=True)
|
||||
assert "replace(station_name::text, ',', ',') as station_name" in lte_attr.sql
|
||||
assert "replace(gnodeb_name::text, ',', ',') as gnodeb_name" in nr_attr.sql
|
||||
assert {"station_name", "enodeb_id", "azimuth"} <= set(lte_attr.required) and lte_attr.phase == "attr"
|
||||
|
||||
|
||||
def test_build_cells_merges_coordinates_by_cgi():
|
||||
attrs = [
|
||||
{"cgi": "c1", "cell_name": "A", "station_name": "S1", "enodeb_id": "1", "network_type": "LTE"},
|
||||
{"cgi": "c1", "cell_name": "A-dup", "station_name": "S1"},
|
||||
{"cgi": "c2", "cell_name": "B", "station_name": "S2"},
|
||||
{"cgi": "", "cell_name": "no key"},
|
||||
]
|
||||
coords = [
|
||||
{"cgi": "c1", "longitude": "", "latitude": ""},
|
||||
{"cgi": "c1", "longitude": "113.1", "latitude": "22.5"},
|
||||
{"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] == [
|
||||
("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}]
|
||||
|
||||
|
||||
def test_key_overlap():
|
||||
assert key_overlap([{"cgi": "a"}, {"cgi": "b"}, {"cgi": "c"}], [{"cgi": "a"}, {"cgi": "b"}, {"cgi": "d"}], "4G") == 0.5
|
||||
assert key_overlap([], [{"cgi": "a"}], "4G") == 0.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 adhoc_returns(monkeypatch, result):
|
||||
async def export_day(client, tablename, day, city, fields, **kwargs):
|
||||
if isinstance(result, Exception):
|
||||
raise result
|
||||
return result["4G" if "lte" in tablename else "5G"]
|
||||
|
||||
monkeypatch.setattr(gongcan.adhoc, "export_day", export_day)
|
||||
|
||||
|
||||
def test_snapshot_takes_attributes_from_adhoc_and_coordinates_from_opencode(monkeypatch):
|
||||
adhoc_returns(monkeypatch, {"4G": [{"cgi": "c1", "station_name": "即席站"}], "5G": [{"ncgi": "n1", "station_name": "即席站"}]})
|
||||
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)]
|
||||
|
||||
|
||||
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站"
|
||||
|
||||
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"
|
||||
|
||||
|
||||
def test_snapshot_rejects_empty_city(monkeypatch):
|
||||
adhoc_returns(monkeypatch, NqiError("x"))
|
||||
with pytest.raises(GongcanError):
|
||||
asyncio.run(fetch_snapshot(None, SnapshotOpenCode({"4G": [], "5G": []}), 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 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"] == ""
|
||||
|
||||
|
||||
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
|
||||
|
||||
|
||||
REMOVAL = date(2026, 11, 15)
|
||||
|
||||
|
||||
def test_before_uses_latest_stored_snapshot_with_target():
|
||||
platform = Platform({})
|
||||
store = make_store(platform, {date(2026, 9, 1): with_target(), date(2026, 10, 20): with_target(), date(2026, 11, 14): without_target()})
|
||||
assert asyncio.run(pick_before(store, CITY, SITE, REMOVAL)) == date(2026, 10, 20)
|
||||
assert platform.fetched == []
|
||||
|
||||
|
||||
def test_before_fetches_previous_month_when_stored_data_is_too_old():
|
||||
platform = Platform({date(2026, 10, 1): with_target()})
|
||||
store = make_store(platform, {date(2026, 7, 1): with_target()})
|
||||
assert asyncio.run(pick_before(store, CITY, SITE, REMOVAL)) == date(2026, 10, 1)
|
||||
assert platform.fetched == [date(2026, 10, 1)]
|
||||
|
||||
|
||||
def test_before_walks_back_month_by_month():
|
||||
platform = Platform({date(2026, 10, 1): without_target(), date(2026, 9, 1): with_target()})
|
||||
store = make_store(platform)
|
||||
assert asyncio.run(pick_before(store, CITY, SITE, REMOVAL)) == date(2026, 9, 1)
|
||||
assert platform.fetched == [date(2026, 10, 1), date(2026, 9, 1)]
|
||||
|
||||
|
||||
def test_before_fails_after_three_months_and_skips_stored_months():
|
||||
platform = Platform({date(2026, 9, 1): without_target(), date(2026, 8, 1): without_target()})
|
||||
store = make_store(platform, {date(2026, 10, 1): without_target()})
|
||||
with pytest.raises(GongcanMissing, match="站点 T"):
|
||||
asyncio.run(pick_before(store, CITY, SITE, REMOVAL))
|
||||
assert platform.fetched == [date(2026, 9, 1), date(2026, 8, 1)]
|
||||
|
||||
|
||||
AFTER_REMOVAL = date(2026, 11, 1)
|
||||
TODAY = date(2026, 11, 11)
|
||||
|
||||
|
||||
def test_after_prefers_latest_snapshot_without_target():
|
||||
platform = Platform({})
|
||||
stored = {date(2026, 11, 3): without_target(), date(2026, 11, 5): with_target(), date(2026, 11, 8): without_target(), date(2026, 10, 30): without_target()}
|
||||
store = make_store(platform, stored)
|
||||
assert asyncio.run(pick_after(store, CITY, SITE, AFTER_REMOVAL, TODAY)) == AfterPick(date(2026, 11, 8), False)
|
||||
assert platform.fetched == []
|
||||
|
||||
|
||||
def test_after_uses_yesterday_when_target_is_still_there():
|
||||
platform = Platform({})
|
||||
store = make_store(platform, {date(2026, 11, 5): with_target(), date(2026, 11, 10): with_target()})
|
||||
assert asyncio.run(pick_after(store, CITY, SITE, AFTER_REMOVAL, TODAY)) == AfterPick(date(2026, 11, 10), True)
|
||||
assert platform.fetched == []
|
||||
|
||||
|
||||
def test_after_fetches_yesterday_when_stored_data_still_has_target():
|
||||
platform = Platform({date(2026, 11, 10): without_target()})
|
||||
store = make_store(platform, {date(2026, 11, 5): with_target(), date(2026, 10, 1): without_target()})
|
||||
assert asyncio.run(pick_after(store, CITY, SITE, AFTER_REMOVAL, TODAY)) == AfterPick(date(2026, 11, 10), False)
|
||||
assert platform.fetched == [date(2026, 11, 10)]
|
||||
|
||||
|
||||
def test_after_is_empty_until_removal_day_has_passed():
|
||||
store = make_store(Platform({}))
|
||||
assert asyncio.run(pick_after(store, CITY, SITE, date(2026, 11, 10), TODAY)) is None
|
||||
|
||||
|
||||
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
|
||||
@@ -0,0 +1,224 @@
|
||||
import asyncio
|
||||
import re
|
||||
from datetime import date
|
||||
|
||||
import pytest
|
||||
|
||||
from app.nqi.opencode import (
|
||||
ExportFile,
|
||||
OpenCode,
|
||||
OpenCodeError,
|
||||
ascending_id,
|
||||
cleanup_prompt,
|
||||
export_prompt,
|
||||
judge_export,
|
||||
parse_export_csv,
|
||||
redo_prompt,
|
||||
snapshot_where,
|
||||
sql_text,
|
||||
task_dir_name,
|
||||
task_session,
|
||||
)
|
||||
|
||||
BEFORE = date(2026, 11, 9)
|
||||
REQUIRED = ("cgi", "longitude", "latitude", "eff_from_date", "eff_to_date")
|
||||
|
||||
|
||||
def lte_file(name="lte_target.csv", phase="before"):
|
||||
sql = f"select {', '.join(REQUIRED)} from appdbv3.a_common_cfg_lte_cellant_d where {snapshot_where('江门', BEFORE)}"
|
||||
return ExportFile("t1", phase, name, sql, BEFORE, REQUIRED)
|
||||
|
||||
|
||||
def bash(message_id, command, output):
|
||||
part = {"type": "tool", "tool": "bash", "state": {"status": "completed", "input": {"command": command}, "output": output}}
|
||||
return {"info": {"role": "assistant", "parentID": message_id}, "parts": [part]}
|
||||
|
||||
|
||||
def ran(item, sql=None):
|
||||
command = item.command() if sql is None else item.command().replace(item.sql, sql)
|
||||
return "cd /home/opencode/.config/opencode/skills/adhoc_query && " + command
|
||||
|
||||
|
||||
def test_task_dir_name_keeps_only_ascii_word_characters():
|
||||
assert task_dir_name("460-00-374730-86") == "460_00_374730_86"
|
||||
site = task_dir_name("江门台山市现代技术学校")
|
||||
assert re.fullmatch(r"[0-9a-f]{10}", site)
|
||||
assert site != task_dir_name("江门台山市东门商业街")
|
||||
assert re.fullmatch(r"job7_[0-9a-f]{10}", task_dir_name("job7 江门某站"))
|
||||
with pytest.raises(ValueError):
|
||||
task_dir_name(" ")
|
||||
|
||||
|
||||
def test_sql_text_quotes_and_rejects_shell_characters():
|
||||
assert sql_text("O'Neil") == "'O''Neil'"
|
||||
for value in ('a"b', "a$b", "a`b", "a\\b"):
|
||||
with pytest.raises(ValueError):
|
||||
sql_text(value)
|
||||
|
||||
|
||||
def test_sql_and_prompt_never_carry_iso_dates():
|
||||
item = lte_file()
|
||||
assert "city = '江门' and eff_from_date <= make_date(2026, 11, 9) and eff_to_date > make_date(2026, 11, 9)" in item.sql
|
||||
for text in (export_prompt([item]), redo_prompt([item]), cleanup_prompt("t1")):
|
||||
assert not re.search(r"\d{4}-\d{2}-\d{2}", text)
|
||||
assert item.command() in export_prompt([item])
|
||||
|
||||
|
||||
def test_export_file_paths_and_retry_names():
|
||||
item = lte_file("lte_nbr_x1.csv", phase="after")
|
||||
assert item.path == "/workspace/tasks/t1/after/lte_nbr_x1.csv"
|
||||
first = item.retry(1)
|
||||
second = first.retry(2)
|
||||
assert (first.filename, second.filename) == ("lte_nbr_x1_r1.csv", "lte_nbr_x1_r2.csv")
|
||||
assert item.key == first.key == second.key == "after/lte_nbr_x1"
|
||||
assert second.required == REQUIRED
|
||||
with pytest.raises(ValueError):
|
||||
ExportFile("../x", "before", "a.csv", "select 1", BEFORE, REQUIRED)
|
||||
with pytest.raises(ValueError):
|
||||
ExportFile("t1", "before", "a.csv", 'select "x"', BEFORE, REQUIRED)
|
||||
with pytest.raises(ValueError):
|
||||
ExportFile("t1", "before", "a.csv", "select 1", BEFORE, ())
|
||||
|
||||
|
||||
def test_judge_accepts_only_script_evidence():
|
||||
item = lte_file()
|
||||
saved = f"文件已保存至:{item.path}"
|
||||
messages = [
|
||||
bash("m1", ran(item), saved),
|
||||
{"info": {"role": "assistant", "parentID": "m1"}, "parts": [{"type": "text", "text": "DONE 1 /workspace/x.csv"}]},
|
||||
]
|
||||
found = judge_export(messages, "m1", [item])[item.key]
|
||||
assert found.saved and found.sql_same and not found.empty
|
||||
assert not judge_export(messages, "other", [item])[item.key].saved
|
||||
|
||||
|
||||
def test_judge_flags_changed_sql_and_empty_result():
|
||||
item = lte_file()
|
||||
changed = judge_export([bash("m1", ran(item, item.sql.replace("make_date(2026, 11, 9)", "'2025-11-11'")), f"文件已保存至:{item.path}")], "m1", [item])
|
||||
assert changed[item.key].saved and changed[item.key].sql_same is False
|
||||
empty = judge_export([bash("m1", ran(item), "文件写入失败:服务端响应体为空,未写入任何数据")], "m1", [item])
|
||||
assert empty[item.key].empty and empty[item.key].sql_same and not empty[item.key].saved
|
||||
|
||||
|
||||
def test_judge_splits_chained_commands():
|
||||
first, second = lte_file("lte_a.csv"), lte_file("lte_b.csv")
|
||||
output = f"文件写入失败:服务端响应体为空\n文件已保存至:{second.path}"
|
||||
found = judge_export([bash("m1", f"{first.command()} && {second.command()}", output)], "m1", [first, second])
|
||||
assert found[first.key].sql_same and not found[first.key].saved and not found[first.key].empty
|
||||
assert found[second.key].saved and found[second.key].sql_same
|
||||
|
||||
|
||||
def test_parse_csv_maps_by_header_and_checks_snapshot_day():
|
||||
content = (
|
||||
"\ufefflatitude,cgi,eff_to_date,cell_name,station_name,longitude,eff_from_date\n"
|
||||
"22.5,460-00-1-1,2026-11-10 00:00:00,A,S,113.1,2026-11-01 00:00:00\n"
|
||||
"22.5,460-00-1-2,broken\n"
|
||||
"22.5,460-00-1-3,2026-11-09 00:00:00,B,S,113.1,2026-11-01 00:00:00\n"
|
||||
)
|
||||
table = parse_export_csv(content, REQUIRED, BEFORE)
|
||||
assert table.header[0] == "latitude"
|
||||
assert [row["cgi"] for row in table.rows] == ["460-00-1-1", "460-00-1-3"]
|
||||
assert (table.bad_rows, table.outside_day, table.missing) == (1, 1, [])
|
||||
assert not table.ok
|
||||
missing = parse_export_csv("cgi,cell_name\n1,A\n", REQUIRED, BEFORE)
|
||||
assert "latitude" in missing.missing and not missing.ok
|
||||
|
||||
|
||||
def test_ascending_id_format_and_order():
|
||||
ids = [ascending_id("msg") for _ in range(50)]
|
||||
assert all(re.fullmatch(r"msg_[0-9a-f]{12}[0-9A-Za-z]{14}", value) for value in ids)
|
||||
stamps = [value[4:16] for value in ids]
|
||||
assert stamps == sorted(stamps) and len(set(stamps)) == len(stamps)
|
||||
|
||||
|
||||
class FakeOpenCode(OpenCode):
|
||||
def __init__(self, replies, files):
|
||||
self.replies = replies
|
||||
self.files = files
|
||||
self.prompts = []
|
||||
|
||||
async def prompt(self, session_id, text):
|
||||
self.prompts.append(text)
|
||||
return f"m{len(self.prompts)}"
|
||||
|
||||
async def wait_reply(self, session_id, message_id, timeout=1200):
|
||||
return self.replies[len(self.prompts) - 1](message_id)
|
||||
|
||||
async def read_text(self, path):
|
||||
return self.files["/workspace/" + path]
|
||||
|
||||
|
||||
GOOD_CSV = (
|
||||
"cgi,cell_name,station_name,longitude,latitude,eff_from_date,eff_to_date\n"
|
||||
"460-00-1-1,A,S,113.1,22.5,2026-11-01 00:00:00,2026-11-10 00:00:00\n"
|
||||
)
|
||||
|
||||
|
||||
def test_export_retries_changed_sql_with_new_filename():
|
||||
good, wrong = lte_file("lte_a.csv"), lte_file("lte_b.csv")
|
||||
retried = wrong.retry(1)
|
||||
replies = [
|
||||
lambda mid: [
|
||||
bash(mid, ran(good), f"文件已保存至:{good.path}"),
|
||||
bash(mid, ran(wrong, wrong.sql + " limit 10"), f"文件已保存至:{wrong.path}"),
|
||||
],
|
||||
lambda mid: [bash(mid, ran(retried), f"文件已保存至:{retried.path}")],
|
||||
]
|
||||
oc = FakeOpenCode(replies, {good.path: GOOD_CSV, retried.path: GOOD_CSV})
|
||||
tables = asyncio.run(oc.export("s1", [good, wrong]))
|
||||
assert set(tables) == {good.key, wrong.key}
|
||||
assert "SQL 被改动" in oc.prompts[1] and "lte_b_r1.csv" in oc.prompts[1] and "lte_a.csv" not in oc.prompts[1]
|
||||
|
||||
|
||||
def test_export_accepts_empty_result_and_gives_up_after_retries():
|
||||
item = lte_file()
|
||||
empty = FakeOpenCode([lambda mid: [bash(mid, ran(item), "服务端响应体为空")]], {})
|
||||
assert asyncio.run(empty.export("s1", [item]))[item.key].empty
|
||||
never = FakeOpenCode([lambda mid: []] * 3, {})
|
||||
with pytest.raises(OpenCodeError):
|
||||
asyncio.run(never.export("s1", [item], retries=2))
|
||||
assert len(never.prompts) == 3
|
||||
|
||||
|
||||
class FakeSession(OpenCode):
|
||||
def __init__(self, base=""):
|
||||
self.base = base
|
||||
self.calls = []
|
||||
|
||||
async def provision(self):
|
||||
self.calls.append("provision")
|
||||
self.base = "provisioned"
|
||||
|
||||
async def create_session(self):
|
||||
self.calls.append("create")
|
||||
return "s1"
|
||||
|
||||
async def cleanup(self, session_id, task):
|
||||
self.calls.append(f"cleanup {task}")
|
||||
raise OpenCodeError("平台没回")
|
||||
|
||||
async def delete_session(self, session_id):
|
||||
self.calls.append(f"delete {session_id}")
|
||||
return True
|
||||
|
||||
|
||||
def test_task_session_always_cleans_up_without_hiding_the_error():
|
||||
oc = FakeSession()
|
||||
|
||||
async def run():
|
||||
async with task_session(oc, "gc_x") as session_id:
|
||||
assert session_id == "s1"
|
||||
raise RuntimeError("导出出错")
|
||||
|
||||
with pytest.raises(RuntimeError, match="导出出错"):
|
||||
asyncio.run(run())
|
||||
assert oc.calls == ["provision", "create", "cleanup gc_x", "delete s1"]
|
||||
|
||||
ready = FakeSession(base="provisioned")
|
||||
|
||||
async def quiet():
|
||||
async with task_session(ready, "gc_y"):
|
||||
pass
|
||||
|
||||
asyncio.run(quiet())
|
||||
assert ready.calls == ["create", "cleanup gc_y", "delete s1"]
|
||||
Reference in New Issue
Block a user