Files
37duAutomation/libs/dingtalk/dingtalk_sdk/_selftest.py
T
puddy eeeaed1e14 feat(sdk): desktopauto 0.5.3 银行卡/证件 OCR 增强、dingtalk 1.1.0、aitable 0.1.3
- desktopauto:cardocr 引擎/流水线/校验与 ocr 调整,sdk.json/pyproject/版本三处一致
- dingtalk:AI 表格读写与错误封装扩充
- aitable:client/cli/自测与打包配置更新
2026-11-18 18:56:09 +08:00

379 lines
18 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- 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 幂等")
# ==================== AI 表格:附件下载 ====================
def test_aitable_attachment() -> None:
import socketserver
import http.server as httpserver
import tempfile
import threading
value = [{"resourceId": "r1", "filename": "卡号面.jpg", "size": 12, "type": "image",
"url": "https://x.oss-cn/y.jpg?Expires=1794886717&Signature=abc"},
{"resourceId": "r2", "filename": "身份证.png", "size": 8, "type": "image",
"resourceUrl": "/core/api/resources/img/zz"}]
items = aitable.attachment_items(value)
_eq(len(items), 2, "attachment 字段值拆出 2 个附件")
_eq(items[0]["size"], 12, "声明大小保留")
_eq(items[1]["url"], "", "相对 resourceUrl 不当作可直连地址")
_eq(aitable.attachment_items(None), [], "空附件返回空列表")
_eq(aitable.attachment_items({"filename": "x"})[0]["url"], "", "单个 dict 兼容")
_eq(aitable.parse_expires(items[0]["url"]), 1794886717, "解析预签名 Expires")
_eq(aitable.parse_expires("https://x/y.jpg"), 0, "无 Expires 返回 0")
_eq(aitable.safe_filename('a/b:c*?"<>|.jpg'), "a_b_c_.jpg", "非法字符换下划线")
_eq(aitable.safe_filename("", ""), "file", "空名兜底")
_eq(len(aitable.safe_filename("x" * 200)), 120, "文件名限长 120")
# 本地 HTTP 服务模拟 OSS;不联网、不读生产凭证
png = b"\x89PNG\r\n\x1a\n" + b"\0" * 24
class _Handler(httpserver.BaseHTTPRequestHandler):
def do_GET(self):
if self.path.startswith("/ok"):
self.send_response(200)
self.send_header("content-type", "image/png")
self.send_header("content-length", str(len(png)))
self.end_headers()
self.wfile.write(png)
else:
self.send_response(403)
self.end_headers()
def log_message(self, *args):
pass
table = object.__new__(aitable.AiTable) # 只测下载,不初始化鉴权
table._http = http.HttpClient(retries=2, timeout=5, log=lambda m: None)
with socketserver.TCPServer(("127.0.0.1", 0), _Handler) as srv:
threading.Thread(target=srv.serve_forever, daemon=True).start()
base = f"http://127.0.0.1:{srv.server_address[1]}"
try:
with tempfile.TemporaryDirectory() as tmp:
res = table.download_attachment({"url": f"{base}/ok.png", "size": len(png)},
os.path.join(tmp, "a.png"))
_ok(res["ok"] and res["kind"] == "png" and res["size_match"] is True,
"下载成功 + 魔数/声明大小校验")
dup = table.download_attachment({"url": f"{base}/ok.png"},
os.path.join(tmp, "a.png"))
_eq(os.path.basename(dup["path"]), "a-2.png", "同名附件不覆盖")
_raises(aitable.AttachmentExpiredError,
lambda: table.download_attachment({"url": f"{base}/deny.png"},
os.path.join(tmp, "b.png")),
"403 抛 AttachmentExpiredError")
_raises(aitable.AttachmentExpiredError,
lambda: table.download_attachment(
{"url": f"{base}/ok.png?Expires=1000"},
os.path.join(tmp, "c.png")),
"Expires 已过期 → 不发请求直接报过期")
_raises(config.ConfigError,
lambda: table.download_attachment({"resourceUrl": "/x"},
os.path.join(tmp, "d.png")),
"无可直连 url 抛 ConfigError")
# 批量:单文件失败不中断,过期项打 expired,prefix 命名生效
batch = table.download_attachments(
[{"url": f"{base}/ok.png", "filename": "卡号面.jpg", "size": len(png)},
{"url": f"{base}/deny.png", "filename": "身份证.png"}],
os.path.join(tmp, "sub"), prefix="银行卡-", col="银行卡卡号面照片")
_eq(len(batch), 2, "批量下载 2 个附件")
_ok(batch[0]["ok"] and os.path.basename(batch[0]["path"]) == "银行卡-卡号面.jpg",
"批量成功项落盘且带 prefix")
_ok(batch[1]["ok"] is False and batch[1]["expired"] is True
and "403" in batch[1]["error"], "批量失败项标 expired 并带原因")
_eq(batch[1]["col"], "银行卡卡号面照片", "结果带字段名")
_eq(batch[0]["index"], 1, "结果带序号")
finally:
srv.shutdown()
srv.server_close()
# ==================== 媒体 ====================
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),
("aitable_attachment", test_aitable_attachment),
("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())