# -*- coding: utf-8 -*- """离线自测:不联网、不读生产凭证、不调用 dws。 安装时由 ``sdk.json.selftest`` 声明,客户端冒烟会执行 ``main()``; 开发态也可直接跑:``python -m dingtalk_sdk._selftest``。 """ from __future__ import annotations import base64 import hashlib import hmac import os import urllib.parse from datetime import date from . import aitable, config, dws, http, media, report, robot _CHECKS = 0 def _ok(cond, message: str) -> None: global _CHECKS _CHECKS += 1 if not cond: raise AssertionError(message) def _eq(actual, expected, message: str) -> None: _ok(actual == expected, f"{message}:期望 {expected!r},实际 {actual!r}") def _raises(exc_type, fn, message: str) -> None: try: fn() except exc_type: _ok(True, message) return except Exception as other: # noqa: BLE001 raise AssertionError(f"{message}:期望 {exc_type.__name__},实际 {type(other).__name__}") raise AssertionError(f"{message}:未抛出 {exc_type.__name__}") # ==================== 群机器人 ==================== def test_robot() -> None: secret, ts = "SECtest123", 1730000000000 expect = urllib.parse.quote_plus(base64.b64encode( hmac.new(secret.encode(), f"{ts}\n{secret}".encode(), hashlib.sha256).digest())) _eq(robot.build_sign(secret, ts), expect, "加签结果") _eq(robot.build_url("https://oapi.dingtalk.com/robot/send?access_token=x"), "https://oapi.dingtalk.com/robot/send?access_token=x", "无 secret 不加签") signed = robot.build_url("https://oapi.dingtalk.com/robot/send?access_token=x", secret) _ok("timestamp=" in signed and "sign=" in signed, "有 secret 时追加 timestamp/sign") text = robot.render_markdown("标题", "正文", status="error", server_name="署名") _ok("#ff0000" in text and "标题" in text and "正文" in text and "署名" in text, "Markdown 渲染包含状态色/标题/正文/页脚") blocks = [f"block{i}" for i in range(23)] batches = robot.compose_batch_messages(blocks, "【测试】", batch_size=10) _eq(len(batches), 3, "块格式 23 条按 10 分批") _ok("第1/3批" in batches[0] and "本批共10条" in batches[0], "块格式批次头尾") _ok("本批共3条" in batches[2], "最后一批条数正确") _eq(robot.compose_batch_messages([], "x"), [], "空块列表返回空") long_text = "\n".join("行" * 50 for _ in range(10)) parts = robot.split_by_chars(long_text, max_chars=200) _ok(len(parts) > 1, "超长文本被拆成多段") _ok(all(len(p) <= 260 for p in parts), "每段不超过上限附近") _eq(robot.split_by_chars(""), [], "空文本返回空列表") r = robot.Robot(webhook="https://example.invalid/robot/send", server_name="X", retries=1, log=lambda m: None) _eq(r.server_name, "X", "Robot 页脚署名为显式值") _raises(ValueError, lambda: robot.Robot(webhook=" "), "空 webhook 报错") res = robot.push("", log=lambda m: None) _eq(res["success"], False, "空文本 push 失败") res = robot.push("x", env="nope", log=lambda m: None) _eq(res["success"], False, "未知环境 push 失败") _ok("未知环境" in res["message"], "未知环境错误信息可读") # ==================== 配置 ==================== def test_config() -> None: s = config.get_settings(reload=True) _ok({"prod", "dev"} <= set(s.robots), "内置 prod/dev 机器人配置") _ok(s.robots["prod"].webhook.startswith("https://"), "prod webhook 是 URL") _eq(s.robot("unknown").webhook, s.robots["prod"].webhook, "未知环境回退 prod") old = os.environ.get("DINGTALK_ROBOT_PROD_SERVER_NAME") try: os.environ["DINGTALK_ROBOT_PROD_SERVER_NAME"] = "自测署名" _eq(config.get_settings(reload=True).robots["prod"].server_name, "自测署名", "环境变量覆盖页脚署名") finally: if old is None: os.environ.pop("DINGTALK_ROBOT_PROD_SERVER_NAME", None) else: os.environ["DINGTALK_ROBOT_PROD_SERVER_NAME"] = old config.get_settings(reload=True) _ok("workplan" in config.BASE_ALIASES and "hr" in config.BASE_ALIASES, "base 别名内置") _raises(config.ConfigError, lambda: config.Settings().require_app_credentials(), "缺少 app 凭证抛 ConfigError") # ==================== HTTP ==================== def test_http() -> None: masked = http.mask("https://oapi.dingtalk.com/x?access_token=abcdef&a=1") _ok("abcdef" not in masked and "access_token=***" in masked, "URL token 脱敏") masked = http.mask('{"appSecret": "S3cr3t", "x": 1}') _ok("S3cr3t" not in masked, "JSON 密钥脱敏") _ok(http.is_retryable(http.ApiError("x", code="Throttling")), "限流可重试") _ok(not http.is_retryable(http.ApiError("x", code="forbidden.operationIllegal")), "业务错误不重试") _eq(http.join_url("https://a.com/v1.0/", "notable", "/bases/x"), "https://a.com/v1.0/notable/bases/x", "URL 拼接") # ==================== dws ==================== def test_dws() -> None: _eq(dws.normalize_msg_type("文本"), "text", "消息类型 文本") _eq(dws.normalize_msg_type("file"), "file", "消息类型 file") _raises(ValueError, lambda: dws.normalize_msg_type("语音"), "未知消息类型报错") _eq(dws.normalize_chat_type("群聊"), "group", "通道 群聊") _eq(dws.normalize_chat_type("single"), "single", "通道 single") _raises(ValueError, lambda: dws.normalize_chat_type("广播"), "未知通道报错") client = dws.Dws(bin=r"Z:\not-exist\dws.exe", log=lambda m: None) _raises(config.ConfigError, lambda: client.run(["chat", "search"]), "dws 可执行不存在抛 ConfigError") # 限流:窗口内第 3 条必须等待(用小窗口 + 计数验证不丢名额) limiter = dws.Dws(bin=r"Z:\not-exist\dws.exe", rate_limit=2, rate_window=0.3, log=lambda m: None) limiter._rate_wait() limiter._rate_wait() start = __import__("time").time() limiter._rate_wait() _ok(__import__("time").time() - start >= 0.1, "限流窗口满时阻塞等待") # 推送记录落盘 import tempfile with tempfile.TemporaryDirectory() as tmp: path = limiter.record_push("37036361", "张三", "成功", "内容摘要", record_dir=tmp) _ok(path and os.path.isfile(path), "推送记录 CSV 已写入") with open(path, encoding="utf-8-sig") as fp: content = fp.read() _ok("推送时间" in content and "张三" in content, "推送记录包含表头与数据") # 单聊/群聊入参校验(不发网络) res = limiter.send_message("text", "", "", "", record_dir="") _eq(res["success"], False, "空姓名单聊推送失败") res = limiter.send_group_message("", content="x", record_dir="") _eq(res["success"], False, "空群名群聊推送失败") res = limiter.send_group_message("测试群", content="", file_path="", record_dir="") _eq(res["success"], False, "文本与文件都为空时失败") # dws 异步任务返回体(2026-11 实测):outcome=pending + meta.operation 必须算成功, # 否则上层重试会把同一条消息重复发多次。 pending = { "ok": True, "outcome": "pending", "data": {"arguments": [], "errorCode": None, "errorMsg": None, "result": {"friendlyHint": "", "openTaskId": "Dp8G2MgCqJQ=", "retryable": False}, "success": True}, "meta": {"operation": {"id": "Dp8G2MgCqJQ=", "state": "processing", "next_command": "dws chat message query-send-status " "--open-task-id Dp8G2MgCqJQ="}}, } _ok(dws.is_success(pending), "异步受理(pending)判为已受理") _eq(dws.operation_of(pending).get("state"), "processing", "取到 operation.state") _ok(dws.is_success({"success": True}), "同步 success=true 仍判成功") _ok(dws.is_success({"ok": True, "outcome": "success"}), "outcome=success 判成功") _ok(not dws.is_success({"ok": False, "outcome": "failed"}), "outcome=failed 判失败") _ok(not dws.is_success({"error": {"message": "boom"}}), "无 success 字段判失败") _eq(dws.operation_of({"success": True}), {}, "无 meta 时 operation 为空") # ==================== AI 表格 ==================== def test_aitable() -> None: _eq(aitable.ms_to_str(1730000000000), "2024-10-27", "毫秒转北京时间") _eq(aitable.to_ms("2026-11-05"), 1793808000000, "日期转毫秒(北京时间)") _raises(config.ConfigError, lambda: aitable.to_ms("2026/13/40"), "非法日期抛 ConfigError") _eq(aitable.norm({"name": "张三"}), "张三", "单选/成员取 name") _eq(aitable.norm([{"name": "A"}, {"name": "B"}]), "A、B", "多选顿号连接") _eq(aitable.norm(1730000000000), "2024-10-27", "时间戳自动转日期") record = {"id": "r1", "fields": {"状态": "上线", "上线日期": 1730000000000}} _eq(aitable.flatten(record), {"_id": "r1", "状态": "上线", "上线日期": "2024-10-27"}, "记录拍平") meta = {"value": [ {"name": "上线日期", "type": "date"}, {"name": "状态", "type": "singleSelect", "property": {"choices": [{"name": "上线"}, {"name": "开发中"}]}}, {"name": "标签", "type": "multiSelect"}, ]} out = aitable.coerce_for_fields(meta, {"上线日期": "2026-11-05", "状态": "上线", "标签": "A,B"}) _eq(out["上线日期"], 1793808000000, "date 字段转毫秒") _eq(out["标签"], ["A", "B"], "multiSelect 字符串转数组") _raises(config.ConfigError, lambda: aitable.coerce_for_fields(meta, {"状态": "不存在"}), "单选非法选项抛 ConfigError") _raises(config.ConfigError, lambda: aitable.coerce_for_fields(meta, {"不存在字段": 1}), "未知字段抛 ConfigError") _eq(aitable.resolve_base("workplan"), (config.BASE_ALIASES["workplan"], ""), "base 别名") base_id, sheet_id = aitable.resolve_base( "https://alidocs.dingtalk.com/i/nodes/abcDEF123456?sheetId=xyz789") _eq((base_id, sheet_id), ("abcDEF123456", "xyz789"), "链接解析 baseId/sheetId") _raises(config.ConfigError, lambda: aitable.resolve_base("short"), "未知 base 抛 ConfigError") _eq(aitable.to_base_id("workplan"), config.BASE_ALIASES["workplan"], "别名转 baseId") _eq(aitable.to_base_id(config.BASE_ALIASES["workplan"]), config.BASE_ALIASES["workplan"], "baseId 幂等") # ==================== 媒体 ==================== def test_media() -> None: _eq(media.markdown_image("media123", "二维码"), "![二维码](media123)", "Markdown 图片片段") _raises(config.ConfigError, lambda: media.upload_media(r"Z:\not-exist\a.png"), "文件不存在抛 ConfigError") # ==================== 报表 ==================== def test_report() -> None: _eq(report.month_range("2026-10"), ("2026-10-01", "2026-11-01"), "月度区间") _eq(report.month_range("2026-12"), ("2026-12-01", "2027-01-01"), "跨年月度区间") _eq(report.week_range(date(2026, 11, 5)), (date(2026, 11, 2), date(2026, 11, 8)), "自然周区间(周一~周日)") month_period = report.parse_period("2026-10") _eq((month_period["unit"], month_period["since"], month_period["until"]), ("month", "2026-10-01", "2026-10-31"), "月报区间") week_period = report.parse_period("", "2026-11-05") _eq((week_period["unit"], week_period["since"], week_period["until"]), ("week", "2026-11-02", "2026-11-08"), "周报区间") _eq(_count_excluded("desktop/electron-shell/node_modules/a.js"), True, "构建产物被排除") _eq(_count_excluded("libs/dingtalk/dingtalk_sdk/robot.py"), False, "源码不被排除") def _count_excluded(path: str) -> bool: return bool(report._EXCLUDE_RE.search(path)) # ==================== 入口 ==================== def main() -> int: tests = [ ("robot", test_robot), ("config", test_config), ("http", test_http), ("dws", test_dws), ("aitable", test_aitable), ("media", test_media), ("report", test_report), ] failed = 0 for name, fn in tests: try: fn() print(f"[ok] {name}") except AssertionError as exc: failed += 1 print(f"[FAIL] {name}: {exc}") except Exception as exc: # noqa: BLE001 failed += 1 print(f"[ERROR] {name}: {type(exc).__name__}: {exc}") print(f"自测完成:{_CHECKS} 项断言,失败 {failed} 组") return 1 if failed else 0 if __name__ == "__main__": raise SystemExit(main())