Files
DecomEval/backend/tests/test_evaluate.py
T

336 lines
18 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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.sources import MockGongcan, MockMetrics, PlatformMetrics
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
class _WeekStub:
def __init__(self, row: dict):
self.row = row
def by_cgi(self, cgis, start, end):
return {cgi: self.row for cgi in cgis if cgi == self.row["cgi"]}
def by_sector(self, sectors, start, end):
return {"礼睦-扇区0": [{"cgi": "460-00-1-9", "cell_name": "礼睦-9", "site_name": "礼睦", "tech": "4G"}]}
def test_platform_metrics_keeps_weekly_lte_and_mocks_mr_and_nr():
metrics = PlatformMetrics(
_WeekStub(
{
"cgi": "460-00-1-1",
"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",
}
),
MockMetrics(),
)
cells = [{"cgi": "460-00-1-1", "tech": "4G", "site_name": "礼睦"}, {"cgi": "460-00-9-1", "tech": "5G", "site_name": "礼睦"}]
week = (date(2026, 10, 5), date(2026, 10, 11))
window = metrics.window(cells, *week)
assert window["460-00-1-1"]["traffic_gb"] == pytest.approx(21.1019)
assert window["460-00-1-1"]["high_load"] == 0 and window["460-00-1-1"]["mr_weak_pct"] is not None
assert "460-00-2-2" not in metrics.window([{"cgi": "460-00-2-2", "tech": "4G"}], *week)
assert window["460-00-9-1"]["traffic_gb"] is not None
profile = metrics.profile(cells, *week)
assert profile["460-00-1-1"]["sector_name"] == "礼睦-扇区0"
assert profile["460-00-1-1"]["high_perception"] == "是" and profile["460-00-1-1"]["equiv"] == 1.0
assert profile["460-00-1-1"]["mr_cover_pct"] is not None
assert profile["460-00-9-1"]["freq"] == "N41"
assert metrics.sector_members({"礼睦-扇区0"}, *week, [])["礼睦-扇区0"][0]["cgi"] == "460-00-1-9"
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-09-01" and payload["afterDay"] == "2026-11-10"
assert len(payload["neighbors"]) == 3 and payload["locatable"]
assert all(item["site"] != "模拟待拆站点" 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] == "完成"
low = SiteGroup(key="低效站", kind="dixiao", order_type="低效拆除", removal=date(2026, 12, 20), rows=[demand("460-00-6001-1", "低效站E-ZLW-1", "低效拆除", date(2026, 12, 20))])
result = evaluate_site(low, "江门", TODAY, MockGongcan(), MockMetrics())
assert result["afterDay"] is None and "拆除当周还没结束,没有停闭后的指标" in result["notes"]
assert len(result["section1"]) == 1 and result["section1"][0]["站点类型"] == "室分"
assert result["sectors"] and result["sectors"][0]["base"] >= 1
assert all(item["after"] == {} for item in result["item2"])
class NoGongcan:
def before_day(self, city, target, removal):
raise GongcanMissing("拆除前 3 个月的工参里都没有小区 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="3 个月"):
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"
assert "不通过" in sheet.cell(first, 23).value and "拆除后再评估" in 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 + 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
assert sheet.cell(summary, 19).value == f'=IF(N(E{summary})>=3,"Y","N")'
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 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-09-01" 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 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