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/lte_nbr_x1.csv" assert "--save-dir" not in item.command() and '--filename "lte_nbr_x1.csv"' in item.command() 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 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()) page = Reply(200) page.text = "

正在准备 工作区

x TGT-999999-zzzzzz" assert never._page_hint(page) == "正在准备 工作区 x <票据>" assert never._page_hint(Reply(200)) == "" 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"]