test_runtime.py 21.4 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436
# -*- coding: utf-8 -*-
"""取数端常驻运行时:假云端(标准库 HTTP 服务,含 /config 配置下发)+ 模拟 DMS。

    edge\\vendor\\python38\\python.exe -m unittest discover -s edge\\tests -t edge
"""
import http.server
import json
import os
import shutil
import tempfile
import threading
import time
import unittest

from edgeclient.actions import UnknownResult
from edgeclient.connectors.base import LoginRejected
from edgeclient.core import logship
from edgeclient.core.cloud import CloudClient, CloudError
from edgeclient.core.outbox import Outbox
from edgeclient.core.remote import RemoteConfig
from edgeclient.core.service import Heartbeat, Runtime, classify
from edgeclient.core.singleton import AlreadyRunning, InstanceLock
from edgeclient.core.tasks import StepTimeout, TaskContext, TaskError, capabilities
from edgeclient.infra import secret
from edgeclient.infra.config import ConfigError, build
from tests import test_edge


class FakeCloud(object):
    """实现 /api/edge/v1/* 的最小假云端;status 可设成 503(可重试)/ 404(拒绝)模拟故障。"""

    def __init__(self):
        self.tasks, self.results, self.progress, self.logs, self.beats, self.files = [], [], [], [], [], []
        self.status = 200
        self.config = test_edge.make_remote()
        self.config_calls = 0
        st = self

        class H(http.server.BaseHTTPRequestHandler):
            def _send(self, code, obj):
                body = json.dumps(obj).encode()
                self.send_response(code)
                self.send_header("Content-Type", "application/json")
                self.send_header("Content-Length", str(len(body)))
                self.end_headers()
                self.wfile.write(body)

            def _body(self):
                n = int(self.headers.get("Content-Length") or 0)
                return self.rfile.read(n) if n else b""

            def do_GET(self):
                if self.headers.get("X-Edge-Token") != "edg_test":
                    return self._send(401, {"detail": "令牌不对"})
                if st.status != 200:
                    return self._send(st.status, {"detail": "故障"})
                if self.path.startswith("/api/edge/v1/tasks/next"):
                    return self._send(200, {"task": st.tasks.pop(0) if st.tasks else None})
                if self.path == "/api/edge/v1/config":
                    st.config_calls += 1
                    return self._send(200, st.config)
                self._send(404, {})

            def do_POST(self):
                raw = self._body()
                if self.headers.get("X-Edge-Token") != "edg_test":
                    return self._send(401, {"detail": "令牌不对"})
                if st.status != 200:
                    return self._send(st.status, {"detail": "故障"})
                p = self.path
                if p.endswith("/heartbeat"):
                    st.beats.append(json.loads(raw))
                    return self._send(200, {"ok": True, "config_version": st.config["version"]})
                elif p.endswith("/progress"):
                    st.progress.append(json.loads(raw))
                elif p.endswith("/result"):
                    st.results.append(dict(json.loads(raw), task_id=p.split("/")[-2]))
                elif "/file" in p:
                    st.files.append((p, len(raw)))
                    return self._send(200, {"id": len(st.files), "sha256": "x"})
                elif p.endswith("/logs"):
                    st.logs.extend(json.loads(raw)["lines"])
                self._send(200, {"ok": True})

            def log_message(self, *a):
                pass

        self.server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), H)
        self.url = "http://127.0.0.1:%d" % self.server.server_address[1]
        threading.Thread(target=self.server.serve_forever, daemon=True).start()

    def close(self):
        self.server.shutdown()
        self.server.server_close()


class FakeCC(object):
    """记录进度上报的假客户端(不走网络)。"""

    def __init__(self, fail=False):
        self.calls, self.fail = [], fail

    def progress(self, *a):
        if self.fail:
            raise CloudError("down", 0)
        self.calls.append(a)


class RuntimeTests(unittest.TestCase):
    """复用 test_edge 的模拟 DMS 和配置生成(不继承,避免把那边的用例再跑一遍)。"""

    @classmethod
    def setUpClass(cls):
        test_edge.EdgeTests.setUpClass.__func__(cls)
        cls.cloud = FakeCloud()

    @classmethod
    def tearDownClass(cls):
        cls.cloud.close()
        test_edge.EdgeTests.tearDownClass.__func__(cls)

    def cfg(self, **over):
        return test_edge.EdgeTests.cfg(self, **over)

    def setUp(self):
        test_edge.mock(reset=True)
        test_edge.LIMITER.reset()
        c = self.cloud
        c.status = 200
        c.config = test_edge.make_remote()
        for x in (c.tasks, c.results, c.progress, c.logs, c.beats, c.files):
            del x[:]

    def local(self, run_dir=None):
        return test_edge.make_local(self.tmp, self.cloud.url, "edg_test", run_dir=run_dir)

    # ---------------- 云端配置下发 ----------------
    def test_config_pulled_cached_and_refreshed(self):
        local = self.local()
        rt = Runtime(local)
        rt.prepare()
        self.assertEqual((rt.remote.version, rt.remote.source), (1, "cloud"))
        cfg, sess = rt.sessions.get()
        self.assertEqual(cfg.username, "mock_user")
        # 缓存加密,且云端连不上时能用缓存启动
        raw = open(os.path.join(local.run_dir, "cloud_config.dat"), encoding="utf-8").read()
        if secret.available():
            self.assertNotIn("mock_pass_123", raw)
        self.cloud.status = 503
        r2 = RemoteConfig(local, CloudClient(local))
        self.assertEqual((r2.ensure()["version"], r2.source), (1, "cache"))
        self.cloud.status = 200
        # 后台改账号 → 心跳返回新版本 → 重新拉取 → 新会话(不用去门店电脑上改)
        self.cloud.config = test_edge.make_remote(username="mock_user", password="mock_pass_123", version=2,
                                                  runtime={"page_timeout": 33})
        Heartbeat(rt).beat()
        self.assertEqual(rt.remote.version, 2)
        cfg2, sess2 = rt.sessions.get()
        self.assertEqual(cfg2.page_timeout, 33.0)
        self.assertIs(sess2, sess)                         # 账号没变:同一会话,只换运行参数
        self.cloud.config = test_edge.make_remote(password="changed", version=3)
        Heartbeat(rt).beat()
        self.assertIsNot(rt.sessions.get()[1], sess)       # 密码变了:新会话
        self.assertEqual(self.cloud.beats[-1]["config_version"], 3)     # 拉到新配置后立即再报一次心跳

    def test_no_cache_no_cloud_is_config_error(self):
        local = test_edge.make_local(self.tmp, "http://127.0.0.1:1", "edg_test")
        with self.assertRaises(ConfigError):
            RemoteConfig(local, CloudClient(local)).ensure()

    # ---------------- outbox ----------------
    def test_result_goes_to_outbox_and_is_flushed(self):
        rt = Runtime(self.local())
        self.cloud.status = 503
        rt.post_result("t1", True, {"a": 1}, "", "")
        self.assertEqual(rt.outbox.count(), 1)
        self.cloud.status = 200
        self.assertEqual(rt.outbox.flush(rt.cc), 1)
        self.assertEqual(rt.outbox.count(), 0)
        self.assertEqual(self.cloud.results[-1]["task_id"], "t1")

    def test_rejected_result_is_not_retried(self):
        local = self.local()
        rt = Runtime(local)
        self.cloud.status = 404
        rt.post_result("gone", True, {}, "", "")
        self.assertEqual(rt.outbox.count(), 0)          # 4xx:云端明确拒绝,不进 outbox
        ob = Outbox(local.run_dir)
        ob.put("result", "gone", {"task_id": "gone", "ok": True})
        self.assertEqual(ob.flush(rt.cc), 1)            # 补发时被拒绝 → 丢弃,不会卡住队列
        self.assertEqual(ob.count(), 0)
        self.assertFalse(CloudError("x", 404).retryable)
        self.assertTrue(CloudError("x", 0).retryable and CloudError("x", 503).retryable)

    # ---------------- 日志上云 ----------------
    def test_log_seq_monotonic_and_shipper_spills_to_outbox(self):
        seqs = [logship.next_seq() for _ in range(2000)]
        self.assertEqual(seqs, sorted(seqs))
        self.assertEqual(len(set(seqs)), len(seqs))
        rt = Runtime(self.local())
        logship.drain(100000)
        import logging
        logging.getLogger("edge").handlers.append(logship.ShipHandler())
        logging.getLogger("edge").warning("上传测试一行,密码 mock_pass_123")
        sh = logship.Shipper(rt.cc, rt.outbox)
        self.cloud.status = 503
        sh.ship_once()
        self.assertEqual(rt.outbox.count(), 1)
        self.cloud.status = 200
        rt.outbox.flush(rt.cc)
        self.assertTrue(any("上传测试一行" in l["msg"] for l in self.cloud.logs))

    # ---------------- 步骤超时 ----------------
    def test_step_timeout_reports_and_aborts(self):
        cc = FakeCC()
        ctx = TaskContext(self.cfg(), None, cc, Outbox(tempfile.mkdtemp(dir=self.tmp)),
                          {"id": "t9", "type": "x", "params": {"_steps": {"login": 0.3}}})
        killed = []
        with self.assertRaises(StepTimeout):
            with ctx.step("login", on_timeout=lambda: killed.append(1)):
                time.sleep(0.8)
                raise IOError("连接被强制关闭")
        self.assertEqual(killed, [1])
        self.assertEqual([x[2] for x in cc.calls], ["start", "timeout"])
        # 已结构化的错误(建单结果未知)超时后仍保持原样,不会被改成普通超时
        with self.assertRaises(UnknownResult):
            with ctx.step("login"):
                time.sleep(0.5)
                raise UnknownResult("网络中断,结果未知")
        # 超时后才完成:如实上报成功
        with ctx.step("login"):
            time.sleep(0.5)
        self.assertEqual(cc.calls[-1][2], "ok")
        self.assertIn("超时后完成", cc.calls[-1][3])

    def test_progress_goes_to_outbox_when_cloud_down(self):
        ob = Outbox(tempfile.mkdtemp(dir=self.tmp))
        ctx = TaskContext(self.cfg(), None, FakeCC(fail=True), ob, {"id": "t8", "type": "x", "params": {}})
        with ctx.step("query_part", "P1", timeout=10):
            pass
        self.assertEqual(ob.count(), 2)

    def test_classify(self):
        self.assertEqual(classify(LoginRejected("密码错"))[0], "login_rejected")
        self.assertEqual(classify(UnknownResult("x"))[0], "unknown_result")
        self.assertEqual(classify(TaskError("x", "dms_error"))[0], "dms_error")
        self.assertEqual(classify(ConfigError("x"))[0], "config_missing")
        self.assertEqual(classify(ValueError("x"))[0], "internal")

    # ---------------- 单实例 ----------------
    def test_single_instance_lock(self):
        path = os.path.join(tempfile.mkdtemp(dir=self.tmp), "edge.lock")
        a = InstanceLock(path).acquire()
        with self.assertRaises(AlreadyRunning):
            InstanceLock(path).acquire()
        a.release()
        InstanceLock(path).acquire().release()

    # ---------------- 端到端:领任务 → 执行插件 → 回传 ----------------
    def test_runtime_runs_tasks_and_reports_login_state(self):
        local = self.local()
        rt = Runtime(local)
        self.cloud.tasks.append({"id": "ping1", "type": "sys.ping", "params": {}})
        self.cloud.tasks.append({"id": "scan1", "type": "restock.quote", "params": {
            "dms": "gtmc", "store": {"code": "STORE-T", "name": "测试门店"},
            "parts": [{"part_no": "019990A115", "name": "用户手册", "national": True}],
            "warehouses": ["GTMC广州", "华南GTMC"], "_steps": {"login": 60, "query_part": 30}}})
        self.cloud.tasks.append({"id": "chk1", "type": "sys.check", "params": {"screenshot": False}})
        self.cloud.tasks.append({"id": "bad1", "type": "nope.unknown", "params": {}})
        rt.serve(stop_after=4)
        res = {r["task_id"]: r for r in self.cloud.results}
        self.assertTrue(res["ping1"]["ok"])
        self.assertTrue(res["scan1"]["ok"], res["scan1"])
        self.assertEqual(res["scan1"]["result"]["items"][0]["part_no"], "019990A115")
        calls = res["scan1"]["result"]["api_calls"]                 # 每次 DMS 接口调用的流水摘要随结果回传
        self.assertEqual([c["endpoint"] for c in calls], ["queryByPage", "info-parts-master-dlr",
                                                           "page-national-inventory"])
        self.assertTrue(all(c["ok"] and c["code"] == "10000000" and c["trace_id"] for c in calls))
        self.assertIn("api_trace_evidence", res["scan1"]["result"])
        self.assertIn("dms_rate", res["scan1"]["result"])
        self.assertTrue(res["chk1"]["ok"], res["chk1"])
        self.assertEqual((res["bad1"]["ok"], res["bad1"]["error_code"]), (False, "unsupported"))
        self.assertEqual(test_edge.logins(), 1)          # 扫描登录一次,紧接着的自检复用
        steps = [(p["step"], p["status"]) for p in self.cloud.progress]
        self.assertIn(("login", "start"), steps)
        self.assertIn(("query_part", "ok"), steps)
        st = rt.status()
        self.assertIn("restock.export_history", st["capabilities"])
        self.assertEqual(st["dms_login"]["gtmc"]["state"], "ok")
        self.assertEqual(st["dms_login"]["gtmc"]["today_logins"], 1)
        # 服务重启:登录态从文件恢复,不重新登录
        rt2 = Runtime(local)
        self.cloud.tasks.append({"id": "chk2", "type": "sys.check", "params": {"screenshot": False}})
        rt2.serve(stop_after=1)
        self.assertTrue(self.cloud.results[-1]["ok"])
        self.assertEqual(test_edge.logins(), 1)
        Heartbeat(rt2).beat()
        self.assertEqual(self.cloud.beats[-1]["state"], "idle")
        with open(os.path.join(local.run_dir, "status.json"), encoding="utf-8") as f:
            self.assertTrue(json.load(f)["cloud_ok"])

    def test_wrong_password_reported_as_rejected(self):
        self.cloud.config = test_edge.make_remote(password="wrong")
        rt = Runtime(self.local())
        self.cloud.tasks.append({"id": "s1", "type": "restock.quote", "params": {"parts": [{"part_no": "A"}]}})
        self.cloud.tasks.append({"id": "s2", "type": "restock.quote", "params": {"parts": [{"part_no": "A"}]}})
        rt.serve(stop_after=2)
        self.assertEqual([r["error_code"] for r in self.cloud.results], ["login_rejected", "login_rejected"])
        self.assertEqual(test_edge.logins(), 1)          # 第二个任务不再提交密码
        self.assertEqual(rt.status()["dms_login"]["gtmc"]["state"], "rejected")

    def test_create_po_uploads_snapshots(self):
        local = self.local()
        rt = Runtime(local)
        self.cloud.tasks.append({"id": "po1", "type": "restock.create_po", "params": {
            "lines": [{"part_no": "019990A115", "qty": 2}], "supplier_code": "APC40", "order_type": "S"}})
        rt.serve(stop_after=1)
        r = self.cloud.results[-1]
        self.assertTrue(r["ok"], r)
        self.assertEqual(len(r["result"]["evidence"]), 2)                 # 建单请求 + 响应快照
        kinds = [k for k in ("request", "response", "api_trace") for p, _ in self.cloud.files if "kind=%s" % k in p]
        self.assertEqual(sorted(kinds), ["api_trace", "request", "response"])    # 建单快照 + DMS 接口流水
        # 同一个建单任务再来一次:取数端拒绝重复建单,并回「结果未知」(上次可能已建成,云端要先核实,不能当成没建成)
        self.cloud.tasks.append({"id": "po1", "type": "restock.create_po", "params": {"lines": [{"part_no": "x", "qty": 1}]}})
        Runtime(local).serve(stop_after=1)
        self.assertEqual(self.cloud.results[-1]["error_code"], "unknown_result")
        self.assertTrue(self.cloud.results[-1]["result"].get("duplicate"))
        # 提交:核对 / 检查 / 提交 / 回查的快照都上传;同一个提交任务再来一次拒绝
        po = r["result"]
        sub = {"id": "sb1", "type": "restock.submit_po", "params": {
            "kind": "single", "order_id": po["order_id"], "order_no": po["order_no"],
            "expect": {"lines": [{"part_no": "019990A115", "qty": 2}], "supplier_code": "APC40"}}}
        self.cloud.tasks.append(sub)
        Runtime(local).serve(stop_after=1)
        r2 = self.cloud.results[-1]
        self.assertTrue(r2["ok"], r2)
        self.assertEqual(r2["result"]["status"], "已提交")
        kinds = {k for k in ("submit_verify", "submit_check", "submit_response", "submit_info")
                 for p, _ in self.cloud.files if "kind=%s" % k in p}
        self.assertEqual(kinds, {"submit_verify", "submit_check", "submit_response", "submit_info"})
        self.cloud.tasks.append(dict(sub))
        Runtime(local).serve(stop_after=1)
        self.assertEqual(self.cloud.results[-1]["error_code"], "duplicate")

    def test_export_task_uploads_csv(self):
        rt = Runtime(self.local())
        self.cloud.tasks.append({"id": "ex1", "type": "restock.export_history",
                                 "params": {"kind": "stock", "_steps": {"login": 60, "export": 600}}})
        rt.serve(stop_after=1)
        r = self.cloud.results[-1]
        self.assertTrue(r["ok"], r)
        self.assertEqual(len(r["result"]["evidence"]), 1)
        self.assertTrue(r["result"]["summary"]["rows"] > 0)
        self.assertTrue(any("kind=export" in p and "stock_full.csv" in p for p, _ in self.cloud.files))

    def test_capabilities_cover_server_features(self):
        caps = capabilities()
        for t in ("sys.check", "sys.ping", "sys.upload_logs", "restock.outbound", "restock.quote", "restock.so_sync",
                  "restock.create_po",
                  "restock.screenshot_po", "restock.export_history"):
            self.assertIn(t, caps)

    # ---------------- 本机配置 ----------------
    @unittest.skipUnless(secret.available(), "只有 Windows 有 DPAPI")
    def test_dpapi_roundtrip(self):
        enc = secret.protect("mock_pass_123")
        self.assertTrue(enc.startswith("dpapi:") and "mock_pass_123" not in enc)
        self.assertEqual(secret.unprotect(enc), "mock_pass_123")

    def test_set_ini_value_keeps_comments(self):
        from edgeclient.app.setup import read_ini_value, set_ini_value
        p = os.path.join(tempfile.mkdtemp(dir=self.tmp), "c.ini")
        with open(p, "w", encoding="utf-8") as f:
            f.write("# 头注释\n[cloud]\n# 云端地址\nurl =\n")
        set_ini_value(p, "cloud", "url", "https://a.b")
        set_ini_value(p, "cloud", "edge_token", "edg_x")
        set_ini_value(p, "local", "log_level", "DEBUG")
        text = open(p, encoding="utf-8").read()
        self.assertIn("# 云端地址", text)
        self.assertEqual(read_ini_value(p, "cloud", "url"), "https://a.b")
        self.assertEqual(read_ini_value(p, "cloud", "edge_token"), "edg_x")
        self.assertEqual(read_ini_value(p, "local", "log_level"), "DEBUG")
        shutil.rmtree(os.path.dirname(p), ignore_errors=True)

    def test_cloud_env_sections(self):
        from edgeclient.infra.config import ConfigError, load_local
        d = tempfile.mkdtemp(dir=self.tmp)
        p = os.path.join(d, "c.ini")

        def write(text):
            with open(p, "w", encoding="utf-8") as f:
                f.write(text)

        body = ("[cloud]\nenv = %s\nurl = https://old\nedge_token = edg_old\n"
                "[cloud.dev]\nurl = https://dev.x\nedge_token = edg_dev\n"
                "[cloud.test]\nurl = https://test.x/\nedge_token =\n[cloud.prd]\nurl =\nedge_token =\n")
        write(body % "dev")
        c = load_local(p)
        self.assertEqual((c.cloud_env, c.cloud_url, c.edge_token), ("dev", "https://dev.x", "edg_dev"))
        write(body % "test")                    # 环境段令牌没填:回退到 [cloud] 的老令牌,地址用环境段的
        c = load_local(p)
        self.assertEqual((c.cloud_url, c.edge_token), ("https://test.x", "edg_old"))
        write(body % "prod")                    # prod 是 prd 的别名
        self.assertEqual(load_local(p).cloud_env, "prd")
        write(body % "staging")
        with self.assertRaises(ConfigError):
            load_local(p)
        write("[cloud]\nurl = https://only\nedge_token = edg_o\n")     # 老格式:没有 env 段
        c = load_local(p)
        self.assertEqual((c.cloud_env, c.cloud_url, c.edge_token), ("", "https://only", "edg_o"))
        shutil.rmtree(d, ignore_errors=True)


if __name__ == "__main__":
    unittest.main()


class ClockSyncTest(unittest.TestCase):
    def tearDown(self):
        from edgeclient.infra import apitrace
        apitrace.CLOCK.update(offset=0.0, synced=False)

    def test_heartbeat_sync_clock_shifts_api_trace(self):
        from edgeclient.infra import apitrace
        now = time.time()
        srv = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(now - 4))       # 本机比云端快 4 秒
        Heartbeat.sync_clock(srv, now - 0.1, now + 0.1)
        self.assertTrue(apitrace.CLOCK["synced"])
        self.assertAlmostEqual(apitrace.CLOCK["offset"], -4, delta=1.5)
        Heartbeat.sync_clock(srv, now - 10, now)                                  # 往返太慢不可信:不更新
        self.assertAlmostEqual(apitrace.CLOCK["offset"], -4, delta=1.5)
        tr = apitrace.ApiTrace()
        tr.start("t1")
        tr.add("queryByPage", "POST", "http://x/q", {}, 200, 0.1, ok=True)
        ts = time.mktime(time.strptime(tr.stop()[0]["ts"], "%Y-%m-%d %H:%M:%S"))
        self.assertAlmostEqual(ts, time.time() - 4, delta=2.5)