test_edge.py 15.4 KB
# -*- coding: utf-8 -*-
"""取数端回归测试:用部署用的 python38 跑,模拟 DMS 由开发环境 Python 拉起。

    edge\\python38\\python.exe -m unittest discover -s edge\\tests -t edge
环境变量 MOCK_PY = 能运行 dev/mock_dms.py 的 Python(需 fastapi uvicorn cryptography),默认 autoRestock 环境。
"""
import glob
import http.server
import json
import os
import shutil
import subprocess
import sys
import tempfile
import threading
import time
import unittest
import urllib.request

HERE = os.path.dirname(os.path.abspath(__file__))
EDGE = os.path.dirname(HERE)
sys.path.insert(0, EDGE)

from edgeclient import actions, cloud, logs                         # noqa: E402
from edgeclient.config import load_config                          # noqa: E402
from edgeclient.dms_api import DmsSession                          # noqa: E402
from edgeclient.dmsfetch.auth import LoginError, LoginRejected     # noqa: E402
from edgeclient.screenshot import ScreenshotError                  # noqa: E402

PORT = 8766
BASE = "http://127.0.0.1:%d" % PORT
MOCK_PY = os.environ.get("MOCK_PY", r"D:\software_install\anaconda_env\envs\autoRestock\python.exe")
CHROME = os.environ.get("CHROME", os.path.join(EDGE, "browser", "chrome-win", "chrome.exe"))   # 打包用的 Chromium 109


class DropProxy(object):
    """模拟 auth-api 的网关:前 drop 个请求读完就断开、不回任何响应(客户端看到 RemoteDisconnected),之后转发给模拟 DMS。"""

    def __init__(self, drop):
        self.drop, self.seen = drop, []
        outer = self

        class H(http.server.BaseHTTPRequestHandler):
            def do_POST(self):
                body = self.rfile.read(int(self.headers.get("Content-Length") or 0))
                outer.seen.append(self.headers.get("Cookie") is not None)
                if len(outer.seen) <= outer.drop:
                    self.close_connection = True
                    return
                req = urllib.request.Request(BASE + self.path, data=body, method="POST",
                                             headers={"Content-Type": self.headers.get("Content-Type")})
                data = urllib.request.urlopen(req, timeout=10).read()
                self.send_response(200)
                self.send_header("Content-Type", "application/json")
                self.send_header("Content-Length", str(len(data)))
                self.end_headers()
                self.wfile.write(data)

            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/auth" % 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()


def mock(**kw):
    req = urllib.request.Request(BASE + "/mock/set", data=json.dumps(kw).encode(), method="POST",
                                 headers={"Content-Type": "application/json"})
    return json.loads(urllib.request.urlopen(req, timeout=5).read())


def mock_state():
    return json.loads(urllib.request.urlopen(BASE + "/mock/state", timeout=5).read())


class EdgeTests(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        env = dict(os.environ, PYTHONNOUSERSITE="1")
        cls.proc = subprocess.Popen([MOCK_PY, os.path.join(EDGE, "dev", "mock_dms.py"), str(PORT)], env=env,
                                    stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
        for _ in range(60):
            try:
                mock_state()
                break
            except Exception:
                time.sleep(0.5)
        cls.tmp = tempfile.mkdtemp(prefix="edge_test_")

    @classmethod
    def tearDownClass(cls):
        cls.proc.kill()
        shutil.rmtree(cls.tmp, ignore_errors=True)

    def cfg(self, **over):
        opts = {"password": "mock_pass_123", "allow": "true", "chrome": CHROME, "strategies": "token,sso",
                "auth_api": BASE + "/auth", "extra": "", "shot_extra": ""}
        opts.update(over)
        ini = os.path.join(self.tmp, "config_%d.ini" % int(time.time() * 1000))
        with open(ini, "w", encoding="utf-8") as f:
            f.write("""[account]
username = mock_user
password = {password}
[urls]
dms_url = {b}/dms/
iam_base = {b}/iam
auth_api = {auth_api}
parts_api = {b}/parts
[auth]
token_exchange_delay = 0
[network]
request_interval = 0
diag_rounds = 2
retry_backoff = 0.1
max_retries = 1
[business]
allow_create_po = {allow}
[screenshot]
chrome_path = {chrome}
chrome_profile = profile
page_timeout = 15
settle_seconds = 0.5
strategies = {strategies}
{shot_extra}
[storage]
data_dir = data
[logging]
log_dir = logs
[cloud]
env = mock
{extra}
""".format(b=BASE, **opts))
        c = load_config(ini)
        logs.setup(c.log_dir, "INFO")
        return c

    def setUp(self):
        mock(reset=True)

    def test_exact_part_match(self):
        c = self.cfg()
        r = actions.scan(c, DmsSession(c), [{"part_no": "019990A115", "name": "", "expected": 2}])
        it = r["items"][0]
        self.assertTrue(r["ok"])
        self.assertEqual(it["stock"], 0)            # 模拟接口模糊匹配会带出 019990A115-B(库存 5),必须排除
        self.assertEqual(it["shortage"], 2)
        self.assertEqual(it["warehouses"], {"GTMC广州": 720, "华南GTMC": 2})
        self.assertEqual(it["daily_surplus"], 4)

    def test_missing_warehouse_is_error(self):
        mock(hide_warehouse=True)
        c = self.cfg()
        r = actions.scan(c, DmsSession(c), [{"part_no": "019990A115", "name": "", "expected": 2}])
        self.assertFalse(r["ok"])
        self.assertIn("找不到仓库 华南GTMC", r["items"][0]["error"])

    def test_wrong_password_single_attempt(self):
        c = self.cfg(password="wrong-pass")
        with self.assertRaises(LoginRejected):
            DmsSession(c).login()
        self.assertEqual(mock_state()["count"]["login_posts"], 1)

    def test_token_expired_relogin(self):
        c = self.cfg()
        s = DmsSession(c)
        s.stock_page(1, 5)
        mock(expire_tokens=True)
        total, rows = s.stock_page(1, 5)
        self.assertGreater(total, 0)
        self.assertEqual(s.relogins, 1)

    def test_create_po_and_verify(self):
        c = self.cfg()
        r = actions.create_po(c, DmsSession(c), [{"part_no": "019990A115", "qty": 2}, {"part_no": "0400007516", "qty": 2}])
        self.assertTrue(r["order_no"].startswith("S"))
        self.assertEqual(r["mismatch"], [])
        st = mock_state()
        self.assertEqual(st["count"]["create"], 1)
        req = json.load(open(os.path.join(r["dir"], "po_request.json"), encoding="utf-8"))
        self.assertEqual(req["orderStatus"], "1")          # 待提交
        self.assertEqual(req["supplierCode"], "APC40")
        self.assertEqual([d["purchaseQty"] for d in req["detailList"]], [2, 2])

    def test_create_rejected_by_dms_sent_once(self):
        mock(fail_create=True)
        c = self.cfg()
        with self.assertRaises(Exception):
            actions.create_po(c, DmsSession(c), [{"part_no": "019990A115", "qty": 2}])
        self.assertEqual(mock_state()["count"]["create"], 1)

    def test_cap_exceeded_blocks_before_create(self):
        c = self.cfg()
        with self.assertRaises(actions.ActionError) as cm:
            actions.create_po(c, DmsSession(c), [{"part_no": "019990A115", "qty": 9}])
        self.assertIn("超过当日剩余可订", str(cm.exception))
        self.assertEqual(mock_state()["count"]["create"], 0)

    def test_allow_create_false(self):
        c = self.cfg(allow="false")
        with self.assertRaises(actions.ActionError):
            actions.create_po(c, DmsSession(c), [{"part_no": "019990A115", "qty": 1}])
        self.assertEqual(mock_state()["count"]["create"], 0)

    def test_screenshot_sso_only(self):
        c = self.cfg(strategies="sso")
        s = DmsSession(c)
        r = actions.create_po(c, s, [{"part_no": "0400007516", "qty": 1}])
        sh = actions.screenshot_po(c, s, row=r["row"], part_nos=["0400007516"])
        self.assertEqual(len(sh["files"]), 2)
        self.assertTrue(all(os.path.getsize(f) > 5000 for f in sh["files"]))

    def test_full_page_screenshot_no_scrollbars(self):
        import struct
        c = self.cfg()
        s = DmsSession(c)
        r = actions.create_po(c, s, [{"part_no": "0400007516", "qty": 1}])
        sh = actions.screenshot_po(c, s, row=r["row"], part_nos=["0400007516"])
        with open(sh["files"][0], "rb") as f:
            w, h = struct.unpack(">II", f.read(24)[16:24])
        # 模拟列表页:表格最小宽 2100(视口 1600 放不下)、内部滚动框只有 260 高 → 整页截图必须加宽、加高
        self.assertGreater(w, 1600 * c.device_scale)
        self.assertGreater(h, 1000 * c.device_scale)

    def test_in_transit_field(self):
        self.assertEqual(actions.pick_in_transit(3, 5, "trans_shipped"), 3)
        self.assertEqual(actions.pick_in_transit(3, 5, "unreceived"), 5)
        self.assertEqual(actions.pick_in_transit(3, 5, "max"), 5)

    def test_parse_custom_lines(self):
        import main
        self.assertEqual(main._parse_lines("019990A115:2,0400007516:3"),
                         [{"part_no": "019990A115", "qty": 2}, {"part_no": "0400007516", "qty": 3}])
        for bad in ("019990A115", "019990A115:0", "x:abc", ""):
            with self.assertRaises(ValueError):
                main._parse_lines(bad)

    def test_screenshot_no_chrome_reports_error(self):
        c = self.cfg(chrome=os.path.join(self.tmp, "no_chrome.exe"))
        with self.assertRaises(ScreenshotError) as cm:
            actions.screenshot_po(c, DmsSession(c))
        self.assertIn("找不到 Chrome", str(cm.exception))

    def test_executed_guard(self):
        ex = cloud._Executed(os.path.join(self.tmp, "guard"))
        self.assertFalse(ex.seen("t1"))
        ex.add("t1")
        self.assertTrue(ex.seen("t1"))

    def test_token_exchange_retry_after_disconnect(self):
        """真机现象:IAM 校验通过后,auth-api 换 token 时对端不回应就断开。重试应能换到 token,且不重复提交密码。"""
        px = DropProxy(drop=2)
        try:
            c = self.cfg(auth_api=px.url)
            s = DmsSession(c)
            s.login()
            self.assertTrue(s.token.value)
            self.assertEqual(px.seen, [True, True, True])          # 与浏览器一致,每次都带 Cookie
            self.assertEqual(mock_state()["count"]["login_posts"], 1)
            self.assertEqual([t["status"] for t in s.client.trace if "iam-oauth" in t["url"]], [0, 0, 200])
            self.assertIn("RemoteDisconnected", s.client.trace[-2]["error"])
        finally:
            px.close()

    def test_login_failure_writes_trace_and_netdiag(self):
        px = DropProxy(drop=99)
        try:
            c = self.cfg(auth_api=px.url)
            r = actions.check(c, DmsSession(c), [])
            self.assertFalse(r["ok"])
            self.assertIn("换 token 请求网络失败", r["steps"][0]["detail"])
            self.assertEqual(len(px.seen), 5)                        # 1 次 + token_exchange_retries=4
            self.assertEqual(mock_state()["count"]["login_posts"], 1)  # 密码只提交一次
            trace = json.load(open(os.path.join(r["dir"], "login_trace.json"), encoding="utf-8"))
            self.assertTrue(any("iam-oauth" in t["url"] and t["status"] == 0 for t in trace))
            diag = json.load(open(os.path.join(r["dir"], "netdiag.json"), encoding="utf-8"))
            self.assertEqual(len(diag), 4)
            self.assertTrue(all(d["success"] == "2/2" for d in diag))
            page = open(os.path.join(r["dir"], "index.html"), encoding="utf-8").read()
            self.assertIn("登录请求轨迹", page)
            self.assertNotIn("mock_pass_123", page)
        finally:
            px.close()

    def test_screenshot_token_via_cookie(self):
        """真实 DMS 前端从 Cookie「Authorization」读 token:token 策略要能直接截到图,不走 sso。"""
        c = self.cfg(strategies="token")
        r = actions.check(c, DmsSession(c), [])
        self.assertTrue(r["ok"], r["steps"])
        self.assertTrue(os.path.exists(os.path.join(r["dir"], "check_po_list.png")))
        self.assertFalse(glob.glob(os.path.join(r["dir"], "debug_*")))

    def test_screenshot_failure_saves_debug(self):
        """token 只写 localStorage(真实前端不认)→ 失败,并留下浏览器画面和诊断信息。"""
        mock(sso_off=True)          # 否则浏览器会借 IAM SSO Cookie 自己登录成功
        c = self.cfg(strategies="token", shot_extra="token_storage = localstorage\ntoken_storage_format = auto")
        s = DmsSession(c)
        r = actions.check(c, s, [])
        self.assertFalse(r["ok"])
        self.assertIn("被跳转到 IAM 登录页", r["steps"][-1]["detail"])
        self.assertIn("token(raw)", r["steps"][-1]["detail"])
        self.assertIn("token(bearer)", r["steps"][-1]["detail"])       # auto:两种格式都试过
        self.assertTrue(os.path.getsize(os.path.join(r["dir"], "debug_token.png")) > 1000)
        info = json.load(open(os.path.join(r["dir"], "debug_token.json"), encoding="utf-8"))
        self.assertIn("Authorization", info["local_storage_keys"])
        page = open(os.path.join(r["dir"], "index.html"), encoding="utf-8").read()
        self.assertIn("debug_token.png", page)
        self.assertNotIn(s.token.value, open(os.path.join(r["dir"], "debug_token.json"), encoding="utf-8").read())

    def test_cloud_env_profiles(self):
        c = self.cfg(extra="")
        self.assertEqual(c.cloud_url, "")                            # env=mock 且没写 url
        ini = os.path.join(EDGE, "config.example.ini")
        text = open(ini, encoding="utf-8").read().replace("(在这里填写 DMS 账号)", "u").replace("(在这里填写 DMS 密码)", "p")
        path = os.path.join(self.tmp, "env_example.ini")
        open(path, "w", encoding="utf-8").write(text)
        c = load_config(path)
        self.assertEqual((c.cloud_env, c.cloud_url, c.cloud_verify_ssl), ("dev", "https://huangng.dev.glsx.com.cn", True))
        self.assertEqual(c.token_storage_format, "bearer")
        open(path, "w", encoding="utf-8").write(text.replace("env = dev", "env = test"))
        self.assertEqual(load_config(path).cloud_url, "https://autorestock.test.glsx.com.cn")
        open(path, "w", encoding="utf-8").write(text.replace("env = dev", "env = prod").replace(
            "[cloud.prod]\n", "[cloud.prod]\nedge_token = prod-token\n"))
        c = load_config(path)
        self.assertEqual((c.cloud_env, c.cloud_url, c.edge_token), ("prod", "", "prod-token"))
        # 旧版 config.ini(没有 env 段,只有 [cloud] url)照样能用
        open(path, "w", encoding="utf-8").write("[account]\nusername=u\npassword=p\n[cloud]\nurl = http://1.2.3.4:53003/\n")
        self.assertEqual(load_config(path).cloud_url, "http://1.2.3.4:53003")
        open(path, "w", encoding="utf-8").write("[account]\nusername=u\npassword=p\n")
        self.assertEqual(load_config(path).cloud_url, "https://huangng.dev.glsx.com.cn")   # 没写 env 默认开发环境

    def test_logs_scrubbed(self):
        c = self.cfg()
        s = DmsSession(c)
        s.login()
        actions.check(c, s, [])
        text = ""
        for f in glob.glob(os.path.join(c.log_dir, "*.log")) + glob.glob(os.path.join(c.data_dir, "**", "*.json"), recursive=True):
            text += open(f, encoding="utf-8").read()
        self.assertNotIn("mock_pass_123", text)
        self.assertNotIn(s.token.value, text)


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