# -*- coding: utf-8 -*- """testdata 控制台(本地网页版,2026-10-09)。 双击「启动testdata.bat」自动打开浏览器:http://127.0.0.1:8412 填参数 → 开始生成 → 实时日志;停止 = 软暂停;删除 = 分块删除全部测试数据; 版本对齐 = 测试库换到别的母体后,把测试批次解析器版本对齐到该母体当前版本。 生成写入独立测试库 history-test.db / session-test.db,真实库零污染。 只在本机 127.0.0.1 监听。不改任何软件代码。 """ import json import os import subprocess import sys import threading import webbrowser from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer HERE = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, HERE) import gen_testdata as G # noqa: E402 G._safe_stdio() # GBK 控制台容错(U+200C 等) PORT = 8412 _state = {"proc": None, "mode": None} _lock = threading.Lock() LOG = [] def log(msg): LOG.append("%s %s" % (__import__("time").strftime("%H:%M:%S"), msg)) if len(LOG) > 2000: del LOG[:500] try: print(msg, flush=True) except Exception: pass def _cfg(): """读 config.json(找不到/坏档返回空 dict)。""" try: with open(G.CFG_PATH, encoding="utf-8") as f: return json.load(f) or {} except Exception: return {} def running(): p = _state["proc"] return p is not None and p.poll() is None def _drain(proc): try: for line in iter(proc.stdout.readline, ""): if not line: break log(line.rstrip()) except Exception: pass def start_sub(mode, cfg): with _lock: if running(): return False, "已有任务在跑,请先停止。" args = [sys.executable, "-u", os.path.join(HERE, "gen_testdata.py")] if mode == "run": cfgpath = os.path.join(HERE, "run_cfg.json") with open(cfgpath, "w", encoding="utf-8") as f: json.dump(cfg, f, ensure_ascii=False, indent=2) args += ["--run", cfgpath] elif mode == "delete": args += ["--delete", "--yes"] else: return False, "未知操作" try: if os.path.exists(G.PAUSE_FLAG): os.remove(G.PAUSE_FLAG) except Exception: pass proc = subprocess.Popen(args, cwd=HERE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, encoding="utf-8", errors="replace") _state["proc"] = proc _state["mode"] = mode threading.Thread(target=_drain, args=(proc,), daemon=True).start() return True, "已启动:%s" % mode def stop_sub(): with _lock: if not running(): return "没有在跑的任务。" open(G.PAUSE_FLAG, "w").close() # 软暂停:当前份做完即退出 return "已发软暂停信号:当前这一份做完就安全停(不丢已提交进度)。" class H(BaseHTTPRequestHandler): def _send(self, code, body, ctype="application/json; charset=utf-8"): raw = body if isinstance(body, bytes) else json.dumps( body, ensure_ascii=False).encode("utf-8") self.send_response(code) self.send_header("Content-Type", ctype) self.send_header("Content-Length", str(len(raw))) self.send_header("Cache-Control", "no-store") self.end_headers() self.wfile.write(raw) def log_message(self, *a): pass def do_GET(self): if self.path in ("/", "/index.html"): self._send(200, PAGE.encode("utf-8"), "text/html; charset=utf-8") elif self.path == "/api/stats": dd = G.find_data_dir() try: s = G.stats_of(dd) if dd else {"data_dir": None} except Exception as e: s = {"data_dir": dd, "error": str(e)} rd = _cfg().get("ref_dir", "") G.REF_DIR = rd or None if dd: rh, th, rs, ts = G.db_paths(dd) s["ref_dir"] = os.path.dirname(rh) s["test_dir"] = dd s["ref_names"] = [os.path.basename(rh), os.path.basename(rs)] s["test_names"] = [os.path.basename(th), os.path.basename(ts)] s["ref_ok"] = [os.path.exists(rh), os.path.exists(rs)] s["test_ok"] = [os.path.exists(th), os.path.exists(ts)] s["running"] = running() s["mode"] = _state["mode"] if running() else None self._send(200, s) elif self.path == "/api/log": self._send(200, {"lines": LOG[-400:], "running": running()}) else: self._send(404, {"ok": False, "msg": "not found"}) def do_POST(self): n = int(self.headers.get("Content-Length") or 0) try: body = json.loads(self.rfile.read(n).decode("utf-8")) if n else {} except Exception: body = {} if self.path == "/api/dir": def _normdir(v): p = (v or "").strip() if not p: return "" p = os.path.normpath(p) if os.path.isfile(p): # 粘贴了 .db 文件路径 → 取其目录 p = os.path.dirname(p) return p if os.path.isdir(p) else "" c0 = _cfg() t_raw, r_raw = body.get("test_dir"), body.get("ref_dir") td = _normdir(t_raw) if t_raw is not None else c0.get("data_dir", "") rd = (_normdir(r_raw) if r_raw else "") if r_raw is not None else c0.get("ref_dir", "") if not td: self._send(200, {"ok": False, "msg": "测试库目录无效(目录不存在)"}) elif rd and not (os.path.exists(os.path.join(rd, G.REAL_H)) or os.path.exists(os.path.join(rd, G.TEST_H))): self._send(200, {"ok": False, "msg": "参考目录里没有 history.db"}) else: G.set_data_dir(td, rd or None) self._send(200, {"ok": True, "test_dir": td, "ref_dir": rd}) elif self.path == "/api/run": cfg = {k: G.DEFAULTS.get(k) for k in G.DEFAULTS} cfg.update({k: v for k, v in body.items() if k in G.DEFAULTS}) cfg["data_dir"] = G.find_data_dir() cfg["ref_dir"] = _cfg().get("ref_dir", "") ok, msg = start_sub("run", cfg) self._send(200, {"ok": ok, "msg": msg}) elif self.path == "/api/align": G.REF_DIR = _cfg().get("ref_dir", "") or None dd = G.find_data_dir() if not dd: self._send(200, {"ok": False, "msg": "找不到数据目录"}) else: try: n = G.align_testdata(dd, log=log) self._send(200, {"ok": True, "msg": "已对齐 %d 个批次" % n}) except Exception as e: self._send(200, {"ok": False, "msg": str(e)}) elif self.path == "/api/switch": dd = G.find_data_dir() if not dd: self._send(200, {"ok": False, "msg": "找不到数据目录"}) else: try: G.switch_dbs(dd, log=log) self._send(200, {"ok": True, "msg": "换库完成!现在点「启动造价审核.bat」即可查看测试数据。"}) except Exception as e: self._send(200, {"ok": False, "msg": str(e)}) elif self.path == "/api/delete": ok, msg = start_sub("delete", {}) self._send(200, {"ok": ok, "msg": msg}) elif self.path == "/api/stop": self._send(200, {"ok": True, "msg": stop_sub()}) else: self._send(404, {"ok": False, "msg": "not found"}) PAGE = """ testdata · 测试数据生成器

testdata · 测试数据生成器

数据目录自动跟随母体(release 包改名/挪动均可)。生成写入独立测试库 history-test.db / session-test.db(首次自动从真实库克隆底子),真实库零污染—— 对接软件时把测试库改名换上即可;换到别的母体后点一次「版本对齐」,删除只是兜底手段。

数据库

参考数据库
测试数据库
生成只写测试数据库(history-test.db / session-test.db, 附件也落这个目录,对接软件时整个目录拿走换名即可);参考数据库(history.db / session.db) 只读,仅作克隆底子。两框均可直接粘贴目录或 .db 文件路径(自动取其目录)。

一、后台数据(history-test.db)

入库项目
~
~
~
市场价
~
信息价
~

二、工作台数据(session-test.db)

~

三、时间跨度

操作

日志

就绪。
""" def main(): try: srv = ThreadingHTTPServer(("127.0.0.1", PORT), H) except OSError: # 端口被占(多半已有一个面板在跑)→ 不崩,直接开浏览器指过去 log("端口 %d 已被占用,可能已有面板在跑,直接打开浏览器。" % PORT) webbrowser.open("http://127.0.0.1:%d" % PORT) return log("testdata 控制台:http://127.0.0.1:%d" % PORT) threading.Timer(0.6, lambda: webbrowser.open("http://127.0.0.1:%d" % PORT)).start() try: srv.serve_forever() except KeyboardInterrupt: pass if __name__ == "__main__": main()