import io import shutil import time from datetime import date import pytest from fastapi.testclient import TestClient from openpyxl import Workbook, load_workbook from app.collect.gongcan import GongcanMissing from app.evaluate.compute import EvalFailure, equiv_carriers, evaluate_site, norm_freq, windows from app.evaluate.demand import DemandError, DemandRow, SiteGroup, group_rows, parse_demand, template_workbook from app.evaluate.report import Item1, NeighborGroup, write_dixiao, write_pinduan from app.evaluate.compute import month_ready, mr_months from app.evaluate import sources from app.evaluate.sources import LTE_MR, LTE_WEEK, NR_KPI, NR_MR, NR_WEEK, MockGongcan, MockMetrics, Period, PlatformMetrics, PlatformTables, mr_weak TODAY = date(2026, 11, 11) def xlsx_bytes(rows: list[list[object]], sheet: str = "拆站清单", extra_first: bool = False) -> bytes: workbook = Workbook() target = workbook.active if extra_first: target.title = "说明" target.append(["这页不是清单"]) target = workbook.create_sheet(sheet) else: target.title = sheet for row in rows: target.append(row) buffer = io.BytesIO() workbook.save(buffer) return buffer.getvalue() HEADER = ["区县", "小区名", "CGI", "扇区", "物理站名(综资站点)", "发起人", "是否已发邮件安排拆除", "需求日期", "退网工单类型"] def test_parse_demand_reports_bad_rows_with_excel_line_numbers(): content = xlsx_bytes( [ HEADER, ["台山市", "站A F-ZLH-1", "460-00-1001-1", "", "", "张三", "搬迁", "2026-10-15", "频段清退"], ["台山市", "站A F-ZLH-2", "460-00-1001-2", "", "", "张三", "搬迁", 46310, "频段清退"], [None, None, None, None, None, None, None, None, None], ["台山市", "站B E-ZLW-9", "460-00-2002-9", "", "", "李四", "低效", "2026/12/20", "低效拆除"], ["台山市", "坏行", "460-00-1001-1", "", "", "", "", "2026-10-15", "频段清退"], ["台山市", "坏行2", "abc", "", "", "", "", "明天", ""], ], extra_first=True, ) sheet = parse_demand("清单.xlsx", content) assert sheet.sheet == "拆站清单" assert [row.cgi for row in sheet.rows] == ["460-00-1001-1", "460-00-1001-2", "460-00-2002-9"] assert sheet.rows[1].need_date == date(2026, 10, 15) assert sheet.rows[2].need_date == date(2026, 12, 20) assert [error["line"] for error in sheet.errors] == [6, 7] assert [row.line for row in sheet.rows] == [2, 3, 5] assert "重复" in sheet.errors[0]["message"] assert "格式不对" in sheet.errors[1]["message"] and "缺少退网工单类型" in sheet.errors[1]["message"] and "看不懂" in sheet.errors[1]["message"] groups = group_rows(sheet.rows) assert [(group.kind, group.key, len(group.rows)) for group in groups] == [("pinduan", "站A F-ZLH", 2), ("dixiao", "站B E-ZLW", 1)] def test_parse_demand_needs_columns_and_supports_gbk_csv(): with pytest.raises(DemandError, match="CGI"): parse_demand("a.xlsx", xlsx_bytes([["小区名", "需求日期"], ["x", "2026-01-01"]])) with pytest.raises(DemandError, match="退网工单类型"): parse_demand("a.xlsx", xlsx_bytes([["CGI", "需求日期"], ["460-00-1-1", "2026-01-01"]])) with pytest.raises(DemandError, match="xlsx"): parse_demand("a.xls", b"x") csv_text = "CGI,需求日期,退网工单类型,小区名\n460-00-3-1,2026-10-01,频段清退,\n" sheet = parse_demand("a.csv", csv_text.encode("gbk")) assert sheet.rows[0].cgi == "460-00-3-1" and sheet.rows[0].cell_name == "" assert group_rows(sheet.rows)[0].key == "460-00-3" def test_template_workbook_parses_back(): sheet = parse_demand("模板.xlsx", template_workbook()) assert len(sheet.rows) == 1 and not sheet.errors assert sheet.rows[0].order_type == "频段清退" def test_frequency_rules_and_windows(): assert norm_freq("E1") == "E" and norm_freq("A频段") == "A" and norm_freq("FDD1800-1") == "FDD1800" and norm_freq("F2") == "F2" assert equiv_carriers("D1", "", 20) == 1.0 assert equiv_carriers("FDD1800", "", 20) == 1.5 assert equiv_carriers("E1", "3D-MIMO", 20) == 2.5 assert equiv_carriers("", "", 20) is None before, after = windows(date(2026, 10, 15), TODAY) assert before == (date(2026, 10, 5), date(2026, 10, 11)) assert after == (date(2026, 10, 12), date(2026, 10, 18)) assert windows(date(2026, 11, 10), TODAY)[1] is None # 平台数据约三天同步好:11-02 这一周周日是 11-08,到 11-11 才能查。 assert windows(date(2026, 11, 4), TODAY)[1] == (date(2026, 11, 2), date(2026, 11, 8)) assert windows(date(2026, 11, 4), date(2026, 11, 10))[1] is None # 4G 的 MR 只有月数据:停闭前用上一个月,停闭后用当月;月底过后第 3 天才有。 assert mr_months(date(2026, 10, 15)) == (date(2026, 9, 1), date(2026, 10, 1)) assert mr_months(date(2026, 1, 10)) == (date(2025, 12, 1), date(2026, 1, 1)) assert not month_ready(date(2026, 10, 1), date(2026, 11, 2)) and month_ready(date(2026, 10, 1), date(2026, 11, 3)) LTE_ROW = { "starttime": "2026-10-05 00:00:00", "cgi": "460-00-1-1", "cell_name": "礼睦F-ZLH-1", "station_name": "礼睦", "upoctudl_avg": 21.1019, "bh_effectiveconnmax": 25.28571, "bh_connmax": 49.71429, "bh_peak_use_rate": 31.7206, "radio_succ_rate": 99.92656, "radio_drop_rate_cell": 0.02945, "is_highflow": False, "is_highload": "false", "is_highflow_perceive": True, "sectors_name": "礼睦-扇区0", "freq_name": "F1", "freq": "F频段", "bandwidth": 20, "equivalent_20m_carrier": 1.0, } PLATFORM_ROWS = { # 周表里同一小区偶尔有完全相同的两行;别的周的行不该被用上。 LTE_WEEK.name: [LTE_ROW, dict(LTE_ROW), {**LTE_ROW, "starttime": "2026-09-28 00:00:00", "upoctudl_avg": 1.0}], LTE_MR.name: [{ "starttime": "2026-09-01 00:00:00", "cgi": "460-00-1-1", "mro_all_rsrp_count": 9880971, "mro_yd_rsrp_gt_f110": 9605340, "mro_yd_rsrp_rate": 97.21049, "mro_yd_rsrp_rate_untime": 97.41865, "mro_yd_rsrp_rate_tetime": 96.71725, "is_lowrsrp": False, "is_lowrsrp_un": True, "is_lowrsrp_te": False, }], NR_WEEK.name: [{ "starttime": "2026-10-05 00:00:00", "ncgi": "460-00-9-1", "nrcell_name": "礼睦D-ZRH-1", "station_name": "礼睦", "sectors_name": "礼睦-扇区0", "freq": "2.6GHz", "band_width": "100MHZ", "pdcp_upoctudl": 306.66953, "bh_rrc_connmean": 53.49278, "bh_rrc_connmax": 75, "is_highload": True, "bh_cellprbrate": 18.4876, }], NR_KPI.name: [{"starttime": "2026-10-05 00:00:00", "ncgi": "460-00-9-1", "kpi_wirelesssuccconnrate": 99.9765, "kpi_wirelessdroprate_celllevel": 0.00113}], NR_MR.name: [{"starttime": "2026-10-05 00:00:00", "ncgi": "460-00-9-1", "nr_rsrp_count": 2878061, "nr_rsrp_gt_f110": 2871285, "nr_rsrp_rate": 99.76456}], } class FakeTables(PlatformTables): """不连平台,按表名回放即席查询的行,并记下发出的查询。""" def __init__(self): super().__init__("local", "tester", "江门") self.queries = [] def _run(self, queries): self.queries += [(table.title, field, tuple(values), start, end) for table, field, values, start, end in queries] return [[row for row in PLATFORM_ROWS[table.name] if row.get(field) in values] for table, field, values, _start, _end in queries] def test_platform_metrics_read_every_value_from_adhoc_tables(): tables = FakeTables() metrics = PlatformMetrics(tables) cells = [{"cgi": "460-00-1-1", "tech": "4G"}, {"cgi": "460-00-9-1", "tech": "5G"}, {"cgi": "460-00-2-2", "tech": "4G"}] period = Period(date(2026, 10, 5), date(2026, 10, 11), date(2026, 9, 1)) window = metrics.window(cells, period) assert set(window) == {"460-00-1-1", "460-00-9-1"} # 「MR 弱覆盖」原样填平台的「大于等于 -110 占比」,和原模板工具一样。 assert window["460-00-1-1"] == { "traffic_gb": 21.1019, "rrc_max": 25.28571, "high_load": 0, "mr_weak_pct": 97.21049, "access_rate": 99.92656, "drop_rate": 0.02945, "util_peak": 31.7206, } assert window["460-00-9-1"] == { "traffic_gb": 306.66953, "rrc_max": 53.49278, "high_load": 1, "mr_weak_pct": 99.76456, "access_rate": 99.9765, "drop_rate": 0.00113, "util_peak": 18.4876, } assert [(title, field, start, end) for title, field, _values, start, end in tables.queries] == [ ("4G 小区周表", "cgi", date(2026, 10, 5), date(2026, 10, 11)), ("4G MR 月表", "cgi", date(2026, 9, 1), date(2026, 9, 30)), ("5G 容量周表", "ncgi", date(2026, 10, 5), date(2026, 10, 11)), ("5G MRO 表", "ncgi", date(2026, 10, 5), date(2026, 10, 11)), ("5G SA_CU 性能表", "ncgi", date(2026, 10, 5), date(2026, 10, 11)), ] assert (NR_KPI.time_dimension, NR_KPI.geo_dimension, NR_MR.time_dimension, LTE_MR.time_dimension) == ("2", "0", "2", None) profile = metrics.profile(cells, period) assert len(tables.queries) == 5 # 同一批小区、同一段时间不再查 lte, nr = profile["460-00-1-1"], profile["460-00-9-1"] assert (lte["sector_name"], lte["freq"], lte["freq_band"], lte["equiv"], lte["high_perception"]) == ("礼睦-扇区0", "F1", "F频段", 1.0, "是") assert (lte["mr_total"], lte["mr_good_cnt"], lte["mr_cover_pct"], lte["unicom_cov"], lte["telecom_cov"]) == (9880971, 9605340, 97.21049, 97.41865, 96.71725) assert (lte["weak_cell"], lte["worse_unicom"], lte["worse_telecom"]) == ("否", "是", "否") assert (nr["sector_name"], nr["freq"], nr["freq_band"], nr["bandwidth"], nr["equiv"]) == ("礼睦-扇区0", "", "2.6GHz", 100.0, None) assert (nr["traffic_gb"], nr["rrc_max"], nr["rrc_max_abs"], nr["util_peak"], nr["high_load_expand"]) == (306.66953, 53.49278, 75, 18.4876, "是") assert (nr["mr_total"], nr["mr_cover_pct"], nr["unicom_cov"], nr["weak_cell"], nr["high_traffic_warn"]) == (2878061, 99.76456, None, None, None) assert profile["460-00-2-2"]["sector_name"] == "" and profile["460-00-2-2"]["mr_total"] is None and profile["460-00-2-2"]["weak_cell"] is None members = metrics.sector_members({"礼睦-扇区0"}, period, [])["礼睦-扇区0"] assert [(item["tech"], item["cgi"], item["cell_name"], item["site_name"]) for item in members] == [ ("4G", "460-00-1-1", "礼睦F-ZLH-1", "礼睦"), ("5G", "460-00-9-1", "礼睦D-ZRH-1", "礼睦"), ] assert [query[1] for query in tables.queries[5:]] == ["sectors_name", "sectors_name"] # 4G 的 MR 月数据还没出:不查月表,MR 留空,别的照常。 early = PlatformMetrics(FakeTables()) no_month = early.window(cells[:1], Period(date(2026, 10, 5), date(2026, 10, 11))) assert no_month["460-00-1-1"]["mr_weak_pct"] is None and no_month["460-00-1-1"]["traffic_gb"] == 21.1019 assert [query[0] for query in early.tables.queries] == ["4G 小区周表"] def test_mr_weak_column_keeps_platform_ratio_unless_switched(monkeypatch): assert mr_weak(None) is None and mr_weak("83.9838") == 83.9838 # 以后要改成「弱于 -110 的比例」时只改这一个开关。 monkeypatch.setattr(sources, "WEAK_AS_SHARE", True) assert mr_weak(None) is None and mr_weak("83.9838") == pytest.approx(16.0162) assert PlatformMetrics(FakeTables()).window([{"cgi": "460-00-1-1", "tech": "4G"}], Period(date(2026, 10, 5), date(2026, 10, 11), date(2026, 9, 1)))["460-00-1-1"]["mr_weak_pct"] == pytest.approx(2.78951) def demand(cgi: str, name: str, order: str = "频段清退", when: date = date(2026, 10, 15)) -> DemandRow: return DemandRow(line=2, cgi=cgi, order_type=order, need_date=when, cell_name=name, county="台山市", applicant="张三", retire_reason="搬迁") def test_evaluate_site_finds_neighbors_and_sectors_with_mock_sources(): groups = group_rows([demand("460-00-5001-1", "目标F-ZLH-1"), demand("460-00-5001-2", "")]) assert len(groups) == 1 and groups[0].key == "目标F-ZLH" group = groups[0] stages: list[str] = [] payload = evaluate_site(group, "江门", TODAY, MockGongcan(), MockMetrics(), stage=stages.append) # 拆除前工参是拆除日上一周的周一,拆除后工参是拆除日下一周的周一。 assert payload["beforeDay"] == "2026-10-05" and payload["afterDay"] == "2026-10-19" and payload["afterPresent"] is True assert len(payload["neighbors"]) == 3 and payload["locatable"] assert all(item["site"] != "模拟待拆站点" for item in payload["item2"]) assert not {"460-00-5001-1", "460-00-5001-2"} & {item["cgi"] for item in payload["item2"]} assert all(item["before"] and item["after"] for item in payload["item2"]) techs = [item["tech"] for item in payload["item2"] if item["site"] == payload["neighbors"][0]["site"]] assert techs == sorted(techs, key=lambda tech: tech != "4G") assert payload["rows"][1]["cellName"] == "模拟待拆站点-2" assert stages[0] == "确定拆除前工参" and stages[-1] == "完成" def low_site(when: date) -> SiteGroup: return SiteGroup(key="低效站", kind="dixiao", order_type="低效拆除", removal=when, rows=[demand("460-00-6001-1", "低效站E-ZLW-1", "低效拆除", when)]) def test_evaluate_site_waits_for_weeks_the_platform_has_not_synced(): done = evaluate_site(low_site(date(2026, 10, 15)), "江门", TODAY, MockGongcan(), MockMetrics()) assert done["windows"]["after"] == ["2026-10-12", "2026-10-18"] and not any("同步好" in note for note in done["notes"]) assert done["mrMonths"] == {"before": "2026-09", "after": "2026-10"} and not any("月数据" in note for note in done["notes"]) assert len(done["section1"]) == 1 and done["section1"][0]["站点类型"] == "室分" and done["section1"][0]["扇区名称"] assert done["sectors"] and done["sectors"][0]["base"] >= 1 # 拆除日在本周:上一周的数据今天刚同步好,当周的要等到 11-18。 this_week = evaluate_site(low_site(date(2026, 11, 10)), "江门", TODAY, MockGongcan(), MockMetrics()) assert this_week["beforeDay"] == "2026-11-02" and this_week["afterDay"] is None and this_week["windows"]["after"] is None assert any("2026-11-09 至 2026-11-15" in note and "2026-11-18" in note for note in this_week["notes"]) assert this_week["sectors"] and all(item["before"] and item["after"] == {} for item in this_week["item2"]) # 拆除日在上周:前后两周的周数据都有了,但 4G 的 MR 要用 11 月的月数据,12-03 才有。 last_week = evaluate_site(low_site(date(2026, 11, 4)), "江门", TODAY, MockGongcan(), MockMetrics()) assert last_week["windows"]["after"] == ["2026-11-02", "2026-11-08"] and last_week["mrMonths"] == {"before": "2026-10", "after": None} assert any("停闭后的 4G MR 用 2026-11 的月数据" in note and "2026-12-03" in note for note in last_week["notes"]) # 停闭后一周的指标今天(周三)有了,下一周周一 11-09 的工参明天才取。 assert last_week["afterDay"] is None and "拆除后工参用 2026-11-09 的,要到 2026-11-12 才取,周边站先按拆除前工参算" in last_week["notes"] assert not any("拆除后工参用" in note for note in done["notes"] + this_week["notes"]) lte_rows = [item for item in last_week["item2"] if item["tech"] == "4G"] assert all(item["before"]["mr_weak_pct"] is not None and item["after"]["mr_weak_pct"] is None and item["after"]["traffic_gb"] is not None for item in lte_rows) assert all(item["after"]["mr_weak_pct"] is not None for item in last_week["item2"] if item["tech"] == "5G") assert all(sector["cover_b"] is not None and sector["cover_a"] is None for sector in last_week["sectors"]) # 拆除日还远:上一周的数据也没有,不去查,结果里说明哪天之后再评估。 later = evaluate_site(low_site(date(2026, 12, 20)), "江门", TODAY, MockGongcan(), MockMetrics()) assert later["beforeDay"] == "2026-11-02" and later["afterDay"] is None assert any("2026-12-07 至 2026-12-13" in note and "2026-12-16" in note for note in later["notes"]) assert later["sectors"] == [] and later["section1"][0]["扇区名称"] is None assert all(item["before"] == {} and item["after"] == {} for item in later["item2"]) class NoGongcan: def before_day(self, city, target, removal, today): raise GongcanMissing("2026-10-05 及之前 4 周的工参里都没有小区 460-00-1-1") def test_evaluate_site_fails_when_target_missing_from_gongcan(): group = group_rows([demand("460-00-1-1", "x")])[0] with pytest.raises(EvalFailure, match="4 周"): evaluate_site(group, "江门", TODAY, NoGongcan(), MockMetrics()) def neighbor_cells(prefix: str, count: int, with_after: bool = True) -> list[dict]: before = {"traffic_gb": 10.0, "rrc_max": 20, "high_load": 0, "mr_weak_pct": 2.0, "access_rate": 99.5, "drop_rate": 0.1} return [ {"cell": f"{prefix}-{index}", "cgi": f"460-00-9-{index}", "tech": "4G", "site": prefix, "distance": 300.0, "before": before, "after": dict(before, traffic_gb=11.0) if with_after else {}} for index in range(1, count + 1) ] def item(cgi: str, site: str, locatable: bool = True) -> Item1: return Item1(county="台山市", logical_site=site, cell_name=f"{site}-1", cgi=cgi, retire_reason="搬迁", applicant="张三", need_date=date(2026, 10, 15), locatable=locatable) def test_write_pinduan_groups_neighbors_per_site(): content = write_pinduan( [item("460-00-1-1", "站A"), item("460-00-2-1", "站B", locatable=False)], [NeighborGroup("站A", neighbor_cells("周边一", 3)), NeighborGroup("站B", neighbor_cells("周边二", 2, with_after=False))], ) sheet = load_workbook(io.BytesIO(content)).worksheets[0] assert sheet["E3"].value == "460-00-1-1" and sheet["D3"].value == "460-00-1" and sheet["J3"].number_format == "yyyy-mm-dd" assert sheet["A4"].fill.start_color.rgb.endswith("FFC7CE") assert sheet["A5"].value is None assert [str(item.sqref) for item in sheet.conditional_formatting] == ["C3:C4"] leaf = next(row for row in range(1, 40) if sheet.cell(row, 2).value == "日均流量(GB)" and sheet.cell(row, 3).value == "日均有效RRC连接最大数") first = leaf + 1 assert sheet.cell(first, 1).value == "周边一-1" summary_a = first + 3 assert sheet.cell(summary_a, 1).value == "汇总" assert sheet.cell(summary_a, 2).value == f'=IFERROR(AVERAGE(B{first}:B{first + 2}),"")' merges = {str(item) for item in sheet.merged_cells.ranges} assert f"W{first}:W{summary_a}" in merges and f"X{first}:X{summary_a}" in merges assert sheet.cell(first, 24).value == "站A" # 判断列和评估结果是固定值,和原模板工具一样:小区行前三项「/」、后四项「Y」,汇总行全「Y」,评估结果「通过」。 assert [sheet.cell(first, col).value for col in range(16, 23)] == ["/", "/", "/", "Y", "Y", "Y", "Y"] assert [sheet.cell(summary_a, col).value for col in range(16, 23)] == ["Y"] * 7 assert sheet.cell(first, 23).value == "通过" second = summary_a + 1 assert sheet.cell(second, 1).value == "周边二-1" and sheet.cell(second, 9).value is None assert sheet.cell(second, 2).fill.start_color.rgb.endswith("F2F6FC") assert sheet.cell(second + 2, 1).value == "汇总" # 停闭后的数据还没有时也一样写固定值,缺什么只写在结果说明里。 assert [sheet.cell(second, col).value for col in range(16, 23)] == ["/", "/", "/", "Y", "Y", "Y", "Y"] assert [sheet.cell(second + 2, col).value for col in range(16, 23)] == ["Y"] * 7 and sheet.cell(second, 23).value == "通过" assert sheet.cell(second + 3, 1).value.startswith("CGI评估对象") def test_write_dixiao_fills_three_sections(): section1 = [{"逻辑站点名称": "站C", "小区名称": "站C-1", "扇区名称": "扇区甲", "站点类型": "宏站", "日均4G流量(GB)": 3.2, "评估结果": "通过"}] sectors = [{ "sector": "扇区甲", "site": "站C", "total": 3, "base": 2, "equiv": 2.0, "traffic_b": 20.0, "traffic_a": 22.0, "single_b": 10.0, "single_a": 11.0, "util_b": 15.0, "util_a": 18.0, "cover_b": 97.0, "cover_a": 96.5, "cells": [ {"cell": "站C-2", "cgi": "460-00-3-2", "band": "D", "equiv": 1.0, "traffic_b": 10.0, "traffic_a": 11.0, "util_b": 15.0, "util_a": 18.0, "cover_b": 97.0, "cover_a": 96.5}, {"cell": "站C-NR", "cgi": "460-00-30-1", "band": "2.6G", "equiv": None, "traffic_b": 10.0, "traffic_a": 11.0, "util_b": 15.0, "util_a": 18.0, "cover_b": 97.0, "cover_a": 96.5}, ], }] content = write_dixiao([item("460-00-3-1", "站C")], section1, sectors, [NeighborGroup("站C", neighbor_cells("周边三", 2))]) sheet = load_workbook(io.BytesIO(content))["低效评估模板"] assert sheet["E3"].value == "460-00-3-1" and sheet["A4"].value is None leaf1 = next(row for row in range(1, 30) if sheet.cell(row, 1).value == "逻辑站点名称") assert sheet.cell(leaf1 + 1, 3).value == "扇区甲" and sheet.cell(leaf1 + 1, 27).value == "通过" leaf2 = next(row for row in range(1, 40) if sheet.cell(row, 1).value == "扇区名称" and sheet.cell(row, 3).value == "CGI") first = leaf2 + 1 assert sheet.cell(first, 1).value == "扇区甲" and sheet.cell(first + 1, 9).value == "/" summary = first + 2 assert sheet.cell(summary, 2).value == "扇区汇总评估" and sheet.cell(summary, 7).value == 20.0 # 判断列和评估结果是固定值,和原模板工具一样:小区行全「/」,汇总行 N、Y、Y、Y、Y,评估结果「通过」。 assert [sheet.cell(first, col).value for col in range(19, 24)] == ["/"] * 5 assert [sheet.cell(summary, col).value for col in range(19, 24)] == ["N", "Y", "Y", "Y", "Y"] assert sheet.cell(first, 24).value == "通过" merges = {str(item) for item in sheet.merged_cells.ranges} assert {f"A{first}:A{summary}", f"X{first}:X{summary}", f"Y{first}:Y{summary}"} <= merges leaf3 = next(row for row in range(summary, 80) if sheet.cell(row, 2).value == "日均流量(GB)" and sheet.cell(row, 3).value == "日均有效RRC连接最大数") assert sheet.cell(leaf3 + 1, 1).value == "周边三-1" and sheet.cell(leaf3 + 3, 1).value == "汇总" @pytest.fixture() def client(monkeypatch): import os from pathlib import Path from app.db import reset_engine from app.main import create_app monkeypatch.setenv("DECOM_EVAL_SOURCE", "mock") data = Path(os.environ["DECOM_DATA_DIR"]) if data.exists(): shutil.rmtree(data) reset_engine() with TestClient(create_app()) as test_client: assert test_client.post("/api/install", json={"sqlite": True, "adminUsername": "admin", "adminPassword": "admin-pass"}).status_code == 200 yield test_client reset_engine() if data.exists(): shutil.rmtree(data) def test_job_stage_shows_only_for_a_single_site_still_running(): from types import SimpleNamespace from app.api.evaluate import _public_job def job(total: int, status: str) -> SimpleNamespace: return SimpleNamespace( id=1, mode="single", title="站A", city="江门", source_name="", status=status, total=total, finished=0, failed=0, results=[], warnings=[], error="", created_at=None, finished_at=None, ) assert _public_job(job(1, "running"), None, "查询停闭前后指标")["stage"] == "查询停闭前后指标" # 多个站点同时在跑,说不清是哪一步,列表里只看完成数。 assert _public_job(job(3, "running"), None, "查询停闭前后指标")["stage"] == "" assert _public_job(job(1, "done"), None, "完成")["stage"] == "" assert _public_job(job(1, "queued"))["stage"] == "" def wait_job(client: TestClient, headers: dict, job_id: int) -> dict: for _ in range(100): detail = client.get(f"/api/eval/jobs/{job_id}", headers=headers).json() if detail["job"]["status"] in ("done", "partial", "failed"): return detail time.sleep(0.1) raise AssertionError(detail) def test_eval_api_end_to_end(client: TestClient): admin = {"Authorization": f"Bearer {client.post('/api/auth/local', json={'username': 'admin', 'password': 'admin-pass'}).json()['token']}"} assert client.get("/api/eval/jobs", headers=admin).status_code == 403 assert client.post("/api/admin/users", json={"username": "u1", "password": "user-pass", "role": "user"}, headers=admin).status_code == 200 user = {"Authorization": f"Bearer {client.post('/api/auth/local', json={'username': 'u1', 'password': 'user-pass'}).json()['token']}"} options = client.get("/api/eval/options", headers=user).json() assert options["metricsMocked"] is True and options["applicant"] == "u1" and "低效拆除" in options["orderTypes"] template = client.get("/api/eval/template", headers=user) assert template.status_code == 200 and template.content[:2] == b"PK" content = xlsx_bytes([ HEADER, ["台山市", "站A F-ZLH-1", "460-00-1001-1", "", "", "张三", "搬迁", "2026-10-15", "频段清退"], ["台山市", "站A F-ZLH-2", "460-00-1001-2", "", "", "张三", "搬迁", "2026-10-15", "频段清退"], ["台山市", "站B E-ZLW-9", "460-00-2002-9", "", "", "李四", "低效", "2026-12-20", "低效拆除"], ["台山市", "坏行", "bad", "", "", "", "", "2026-10-15", "频段清退"], ]) files = {"file": ("一批.xlsx", content, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")} preview = client.post("/api/eval/preview", files=files, headers=user).json() assert preview["total"] == 3 and preview["errorCount"] == 1 and preview["summary"] == {"sites": 2, "pinduan": 1, "dixiao": 1, "cells": 3} refused = client.post("/api/eval/jobs/list", files=files, data={"city": "江门"}, headers=user) assert refused.status_code == 400 and "1 行" in refused.json()["detail"] created = client.post("/api/eval/jobs/list", files=files, data={"city": "江门市", "skipErrors": "true"}, headers=user).json()["job"] assert created["city"] == "江门" and created["total"] == 2 and created["title"] == "一批" detail = wait_job(client, user, created["id"]) assert detail["job"]["status"] == "done", detail assert [result["kind"] for result in detail["job"]["results"]] == ["pinduan", "dixiao"] assert detail["job"]["warnings"][0].startswith("模拟数据:") assert [task["status"] for task in detail["tasks"]] == ["done", "done"] assert detail["tasks"][0]["beforeDate"] == "2026-10-05" and len(detail["tasks"][0]["neighbors"]) == 3 for result in detail["job"]["results"]: downloaded = client.get(f"/api/eval/jobs/{created['id']}/files/{result['kind']}", headers=user) assert downloaded.status_code == 200 and downloaded.content[:2] == b"PK" assert "filename*=utf-8''" in downloaded.headers["content-disposition"].lower() single = client.post( "/api/eval/jobs/single", json={"orderType": "频段清退", "removalDate": "2026-10-01", "city": "江门", "cells": [{"cgi": "460-00-7001-1", "cellName": ""}]}, headers=user, ).json()["job"] assert single["mode"] == "single" and single["title"] == "460-00-7001" by_site = client.post( "/api/eval/jobs/single", json={"orderType": "低效拆除", "removalDate": "2026-10-01", "city": "江门", "mode": "site", "site": "某站点"}, headers=user, ).json()["job"] site_detail = wait_job(client, user, by_site["id"]) assert site_detail["job"]["status"] == "done" and site_detail["tasks"][0]["cells"] assert client.post("/api/eval/jobs/single", json={"orderType": "频段清退", "removalDate": "2026-10-01", "city": "江门", "cells": [{"cgi": "x"}]}, headers=user).status_code == 400 wait_job(client, user, single["id"]) listing = client.get("/api/eval/jobs", headers=user).json()["jobs"] assert [job["id"] for job in listing][:3] == [by_site["id"], single["id"], created["id"]] assert listing[-1]["kinds"] == {"pinduan": 1, "dixiao": 1} assert all(job["stage"] == "" for job in listing) and site_detail["job"]["stage"] == "" assert client.delete(f"/api/eval/jobs/{created['id']}", headers=user).json() == {"ok": True} assert client.get(f"/api/eval/jobs/{created['id']}", headers=user).status_code == 404