feat: 工参每周一一份并提前缓存,登录后自动补缺;评估按周一取工参,指标等平台同步三天后再查
- 工参从 2024-01-01 起每周一一份,排队任务一次补一份,新的周先补;一个地市同时只取一份 - 大数据平台账号登录成功后排补取,排队进程每 10 分钟检查缺的周;排队进程重启时放开没取完的快照 - 拆除前工参用拆除日上一周的周一,拆除后用当周的周一;待拆小区不参与周边站和指标匹配 - 一周的指标等周日过后第 3 天才查,没到时间在结果说明里写明哪天之后有数据 - AI 工作区没就绪时开通接口返回 200,改为等待重试,最多 150 秒 - 排任务加锁,避免多个线程同时排时用到已关闭的连接池 - 运行面板显示各地市工参缓存进度
This commit is contained in:
@@ -91,6 +91,9 @@ def test_frequency_rules_and_windows():
|
||||
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
|
||||
|
||||
|
||||
class _WeekStub:
|
||||
@@ -152,30 +155,50 @@ def test_evaluate_site_finds_neighbors_and_sectors_with_mock_sources():
|
||||
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 payload["beforeDay"] == "2026-10-05" and payload["afterDay"] == "2026-10-12" 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] == "完成"
|
||||
|
||||
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"])
|
||||
|
||||
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 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"])
|
||||
|
||||
# 拆除日还远:上一周的数据也没有,不去查,结果里说明哪天之后再评估。
|
||||
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):
|
||||
raise GongcanMissing("拆除前 3 个月的工参里都没有小区 460-00-1-1")
|
||||
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="3 个月"):
|
||||
with pytest.raises(EvalFailure, match="4 周"):
|
||||
evaluate_site(group, "江门", TODAY, NoGongcan(), MockMetrics())
|
||||
|
||||
|
||||
@@ -306,7 +329,7 @@ def test_eval_api_end_to_end(client: TestClient):
|
||||
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
|
||||
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"
|
||||
|
||||
@@ -7,6 +7,7 @@ from sqlalchemy import create_engine
|
||||
|
||||
from app.collect import gongcan
|
||||
from app.collect.gongcan import (
|
||||
HISTORY_START,
|
||||
AfterPick,
|
||||
GongcanError,
|
||||
GongcanMissing,
|
||||
@@ -14,13 +15,16 @@ from app.collect.gongcan import (
|
||||
Target,
|
||||
build_cells,
|
||||
claim_snapshot,
|
||||
expected_mondays,
|
||||
fetch_snapshot,
|
||||
month_start,
|
||||
latest_monday,
|
||||
nearest_sites,
|
||||
pick_after,
|
||||
pick_before,
|
||||
platform_files,
|
||||
release_loading,
|
||||
save_snapshot,
|
||||
short_city,
|
||||
snapshot_task_name,
|
||||
target_center,
|
||||
)
|
||||
@@ -84,10 +88,16 @@ def make_store(platform, stored=None, clock=None):
|
||||
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_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():
|
||||
@@ -217,67 +227,97 @@ def test_stale_loading_is_taken_over():
|
||||
assert claim_snapshot(store.engine, CITY, date(2026, 11, 1), clock() + timedelta(minutes=41)) is not None
|
||||
|
||||
|
||||
REMOVAL = date(2026, 11, 15)
|
||||
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_before_uses_latest_stored_snapshot_with_target():
|
||||
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-12。
|
||||
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, 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)
|
||||
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_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_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_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_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_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()})
|
||||
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))
|
||||
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)
|
||||
asyncio.run(pick_before(store, CITY, SITE, REMOVAL, TODAY))
|
||||
assert platform.fetched == []
|
||||
|
||||
|
||||
def test_after_uses_yesterday_when_target_is_still_there():
|
||||
def test_before_uses_latest_available_monday_for_a_future_removal():
|
||||
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)
|
||||
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_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_the_monday_of_the_removal_week_and_target_may_still_be_there():
|
||||
platform = Platform({date(2026, 10, 12): with_target()})
|
||||
store = make_store(platform, {date(2026, 10, 19): without_target()})
|
||||
assert asyncio.run(pick_after(store, CITY, SITE, REMOVAL, TODAY)) == AfterPick(date(2026, 10, 12), True)
|
||||
assert asyncio.run(pick_after(store, CITY, SITE, date(2026, 10, 19), TODAY)) == AfterPick(date(2026, 10, 19), False)
|
||||
assert platform.fetched == [date(2026, 10, 12)]
|
||||
|
||||
|
||||
def test_after_is_empty_until_removal_day_has_passed():
|
||||
def test_after_is_empty_until_that_monday_can_be_fetched():
|
||||
store = make_store(Platform({}))
|
||||
assert asyncio.run(pick_after(store, CITY, SITE, date(2026, 11, 10), TODAY)) is None
|
||||
# 11-09 这个周一 11-12 起可取;11-16 的还不行。
|
||||
assert asyncio.run(pick_after(store, CITY, SITE, date(2026, 11, 10), date(2026, 11, 11))) is None
|
||||
assert asyncio.run(pick_after(store, CITY, SITE, date(2026, 11, 17), TODAY)) is None
|
||||
with pytest.raises(GongcanError, match="平台没有这一天"):
|
||||
asyncio.run(pick_after(store, CITY, SITE, date(2026, 11, 10), TODAY))
|
||||
|
||||
|
||||
def test_target_needs_cgis_or_site():
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
from datetime import date, datetime, timedelta, timezone
|
||||
|
||||
from sqlalchemy import create_engine
|
||||
|
||||
from app.collect import gongcan_sync
|
||||
from app.collect.gongcan import GongcanError, GongcanStore, claim_snapshot, save_snapshot
|
||||
from app.models import Base, CellData4G, CellData5G, GongcanSnapshot
|
||||
|
||||
CITY = "江门"
|
||||
TODAY = date(2024, 1, 25) # 可取的周一:01-01、01-08、01-15、01-22
|
||||
CELLS = {
|
||||
"4G": [{"cgi": "c1", "cell_name": "A", "station_name": "S", "latitude": 22.0, "longitude": 113.0}],
|
||||
"5G": [{"ncgi": "n1", "nrcell_name": "N", "station_name": "S", "latitude": 22.0, "longitude": 113.0}],
|
||||
}
|
||||
|
||||
|
||||
class Clock:
|
||||
def __init__(self):
|
||||
self.now = datetime(2024, 1, 25, 2, 0, tzinfo=timezone.utc)
|
||||
|
||||
def __call__(self):
|
||||
return self.now
|
||||
|
||||
|
||||
class Platform:
|
||||
def __init__(self, broken=()):
|
||||
self.broken = set(broken)
|
||||
self.fetched = []
|
||||
|
||||
async def __call__(self, city, day):
|
||||
self.fetched.append(day)
|
||||
if day in self.broken:
|
||||
raise GongcanError("平台出错")
|
||||
return CELLS
|
||||
|
||||
|
||||
def make_store(platform, stored=(), clock=None):
|
||||
db = create_engine("sqlite://")
|
||||
Base.metadata.create_all(db, tables=[GongcanSnapshot.__table__, CellData4G.__table__, CellData5G.__table__])
|
||||
clock = clock or Clock()
|
||||
for day in stored:
|
||||
save_snapshot(db, claim_snapshot(db, CITY, day, clock()), CELLS, clock())
|
||||
return GongcanStore(db, platform, poll_seconds=0.01, clock=clock)
|
||||
|
||||
|
||||
def test_sync_fills_missing_mondays_newest_first_one_per_run():
|
||||
platform = Platform()
|
||||
store = make_store(platform, stored=[date(2024, 1, 15)])
|
||||
runs = [gongcan_sync.sync_once(CITY, today=TODAY, store=store) for _ in range(4)]
|
||||
assert runs == [(date(2024, 1, 22), 2), (date(2024, 1, 8), 1), (date(2024, 1, 1), 0), (None, 0)]
|
||||
assert platform.fetched == [date(2024, 1, 22), date(2024, 1, 8), date(2024, 1, 1)]
|
||||
|
||||
|
||||
def test_sync_stops_while_another_snapshot_is_loading_or_just_failed():
|
||||
clock = Clock()
|
||||
platform = Platform(broken=[date(2024, 1, 22)])
|
||||
store = make_store(platform, clock=clock)
|
||||
# 评估任务正在取 01-08:补取任务不再开第二个。
|
||||
claim_snapshot(store.engine, CITY, date(2024, 1, 8), clock())
|
||||
assert gongcan_sync.sync_once(CITY, today=TODAY, store=store) == (None, 4)
|
||||
save_snapshot(store.engine, 1, CELLS, clock())
|
||||
try:
|
||||
gongcan_sync.sync_once(CITY, today=TODAY, store=store)
|
||||
except GongcanError as exc:
|
||||
assert "平台出错" in str(exc)
|
||||
else:
|
||||
raise AssertionError("失败应当抛出")
|
||||
assert gongcan_sync.sync_once(CITY, today=TODAY, store=store) == (None, 3)
|
||||
clock.now += timedelta(minutes=11)
|
||||
# 冷却后先补别的周,失败过的 01-22 留到最后再试。
|
||||
assert gongcan_sync.sync_once(CITY, today=TODAY, store=store) == (date(2024, 1, 15), 2)
|
||||
assert gongcan_sync.sync_once(CITY, today=TODAY, store=store) == (date(2024, 1, 1), 1)
|
||||
assert platform.fetched == [date(2024, 1, 22), date(2024, 1, 15), date(2024, 1, 1)]
|
||||
|
||||
|
||||
def test_cache_status_counts_mondays_only(monkeypatch):
|
||||
clock = Clock()
|
||||
store = make_store(Platform(broken=[date(2024, 1, 22)]), stored=[date(2024, 1, 8), date(2024, 1, 15), date(2024, 1, 10)], clock=clock)
|
||||
try:
|
||||
gongcan_sync.sync_once(CITY, today=TODAY, store=store)
|
||||
except GongcanError:
|
||||
pass
|
||||
monkeypatch.setattr(gongcan_sync, "engine", lambda: store.engine)
|
||||
assert gongcan_sync.sync_cities() == [CITY]
|
||||
status = gongcan_sync.cache_status(TODAY)
|
||||
assert len(status) == 1
|
||||
item = status[0]
|
||||
assert (item["city"], item["expected"], item["ready"], item["earliest"], item["latest"], item["loading"]) == (CITY, 4, 2, "2024-01-08", "2024-01-15", None)
|
||||
assert item["error"].startswith("2024-01-22 GongcanError: 平台出错") and item["errorAt"]
|
||||
|
||||
|
||||
def test_request_sync_does_nothing_without_a_queue(monkeypatch):
|
||||
monkeypatch.setattr(gongcan_sync, "postgres_conninfo", lambda: None)
|
||||
assert gongcan_sync.request_sync("江门市") is False
|
||||
monkeypatch.setattr(gongcan_sync, "postgres_conninfo", lambda: "postgresql://x")
|
||||
monkeypatch.setenv("DECOM_EVAL_SOURCE", "mock")
|
||||
assert gongcan_sync.request_sync("江门市") is False
|
||||
assert gongcan_sync.request_sync("") is False
|
||||
@@ -180,6 +180,53 @@ def test_export_accepts_empty_result_and_gives_up_after_retries():
|
||||
assert len(never.prompts) == 3
|
||||
|
||||
|
||||
class Reply:
|
||||
def __init__(self, status, location=""):
|
||||
self.status_code = status
|
||||
self.headers = {"location": location} if location else {}
|
||||
|
||||
|
||||
class FakeNqi:
|
||||
"""按顺序回放平台对开通接口和工作区页面的响应。"""
|
||||
|
||||
def __init__(self, replies):
|
||||
self.replies = list(replies)
|
||||
self.urls = []
|
||||
|
||||
def ticket(self):
|
||||
return "ticket"
|
||||
|
||||
async def _request(self, method, url, **kwargs):
|
||||
self.urls.append(url.split("/pro-opencode", 1)[1])
|
||||
return self.replies.pop(0)
|
||||
|
||||
|
||||
def test_provision_waits_until_the_platform_opens_the_workspace():
|
||||
# 工作区没开时开通接口先返回 200 的页面,过一会儿才跳转;跳到别的目录也照样用 /workspace。
|
||||
other_dir = "/pro-opencode/someone/L2hvbWU/session?isApp=1&tickets=x"
|
||||
nqi = FakeNqi([Reply(200), Reply(200), Reply(307, other_dir), Reply(502), Reply(307, f"https://elsewhere.example{other_dir}"), Reply(200)])
|
||||
oc = OpenCode(nqi, poll_seconds=0, provision_wait=5)
|
||||
assert asyncio.run(oc.provision()) == "someone"
|
||||
assert oc.base.endswith("/pro-opencode/someone") and oc.headers["Referer"].endswith("/someone/L3dvcmtzcGFjZQ/session")
|
||||
assert nqi.urls == ["/api/provision", "/api/provision", "/api/provision", "/someone/L2hvbWU/session?isApp=1&tickets=x", "/api/provision", "/someone/L2hvbWU/session?isApp=1&tickets=x"]
|
||||
assert oc.headers["x-opencode-directory"] == "%2Fworkspace"
|
||||
|
||||
|
||||
def test_provision_gives_up_or_reports_expired_login():
|
||||
from app.nqi.client import NqiAuthError
|
||||
|
||||
never = OpenCode(FakeNqi([Reply(200)] * 3), poll_seconds=0, provision_wait=0)
|
||||
with pytest.raises(OpenCodeError, match="开通接口返回 200"):
|
||||
asyncio.run(never.provision())
|
||||
expired = OpenCode(FakeNqi([Reply(302, "https://nqi.gmcc.net:20443/cas/login?service=x")]), poll_seconds=0)
|
||||
with pytest.raises(NqiAuthError):
|
||||
asyncio.run(expired.provision())
|
||||
# 跳转到 /pro-opencode/api/ 下面不是工作区。
|
||||
looping = OpenCode(FakeNqi([Reply(307, "/pro-opencode/api/provision?x=1")]), poll_seconds=0, provision_wait=0)
|
||||
with pytest.raises(OpenCodeError, match="没有跳转到工作区"):
|
||||
asyncio.run(looping.provision())
|
||||
|
||||
|
||||
class FakeSession(OpenCode):
|
||||
def __init__(self, base=""):
|
||||
self.base = base
|
||||
|
||||
Reference in New Issue
Block a user