Files
37duAutomation/libs/aitable/_selftest.py
T
puddy 39b768d0b7 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

241 lines
11 KiB
Python

# -*- coding: utf-8 -*-
"""自测:默认全离线(不联网、不读写表格),--online 追加一条在线冒烟。
运行:
.venv\\Scripts\\python.exe libs\\aitable\\_selftest.py
.venv\\Scripts\\python.exe libs\\aitable\\_selftest.py --online
"""
from __future__ import annotations
import os
import sys
from datetime import date, datetime, timedelta, timezone
from pathlib import Path
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from aitable import cli, report # noqa: E402
from aitable.client import (BASE_ALIASES, coerce_for_fields, flatten, # noqa: E402
norm, resolve_base, to_ms)
_passed = 0
TZ_CN = timezone(timedelta(hours=8))
def ok(cond: bool, msg: str) -> None:
global _passed
if not cond:
raise AssertionError(f"[FAIL] {msg}")
_passed += 1
print(f"[PASS] {msg}")
def test_norm() -> None:
ms = int(datetime(2026, 10, 31, tzinfo=TZ_CN).timestamp() * 1000)
ok(norm({"name": "上线", "id": "x"}) == "上线", "单选取 name")
ok(norm([{"name": "EHR"}, {"name": "钉钉"}]) == "EHR、钉钉", "多选顿号连接")
ok(norm(ms) == "2026-10-31", "毫秒时间戳按北京时间转日期")
ok(norm(28) == 28, "小数值不被误判为日期")
ok(norm("") == "", "空值原样返回")
def test_ms() -> None:
ms = to_ms("2026-10-31")
expect = int(datetime(2026, 10, 31, tzinfo=TZ_CN).timestamp() * 1000)
ok(ms == expect, "日期字符串 → 北京时间 00:00 毫秒")
ok(to_ms("2026/10/31") == expect, "斜杠日期兼容")
ok(to_ms(expect) == expect, "已是毫秒则原样返回")
try:
to_ms("10月31日")
ok(False, "非法日期应报错")
except SystemExit:
ok(True, "非法日期报错")
def test_coerce() -> None:
meta = {"value": [
{"name": "状态", "type": "singleSelect",
"property": {"choices": [{"name": "上线"}, {"name": "开发中"}]}},
{"name": "涉及系统", "type": "multipleSelect", "property": {"choices": []}},
{"name": "上线日期", "type": "date", "property": {}},
]}
out = coerce_for_fields(meta, {"状态": "上线", "涉及系统": "EHR,钉钉", "上线日期": "2026-10-31"})
ok(out["状态"] == "上线", "单选写入选项名")
ok(out["涉及系统"] == ["EHR", "钉钉"], "多选字符串拆数组")
ok(isinstance(out["上线日期"], int), "日期转毫秒")
for bad, desc in (({"状态": "不存在的状态"}, "非法单选值"), ({"不存在字段": 1}, "未知字段")):
try:
coerce_for_fields(meta, bad)
ok(False, f"{desc} 应报错")
except SystemExit:
ok(True, f"{desc} 报错")
def test_flatten() -> None:
rec = {"id": "abc", "fields": {"状态": {"name": "上线"}, "需求编号": "XQ0001"}}
row = flatten(rec)
ok(row["_id"] == "abc" and row["状态"] == "上线", "记录拍平 + 归一")
def test_resolve_base() -> None:
ok(resolve_base("workplan")[0] == BASE_ALIASES["workplan"], "别名解析")
link = ("https://alidocs.dingtalk.com/i/nodes/20eMKjyp81RON33AUrE4awEEWxAZB1Gv"
"?iframeQuery=sheetId%3DhERWDMS")
base, _ = resolve_base(link)
ok(base == "20eMKjyp81RON33AUrE4awEEWxAZB1Gv", "文档链接解析 baseId")
try:
resolve_base("unknown")
ok(False, "未知短标识应报错")
except SystemExit:
ok(True, "未知短标识报错")
def test_period() -> None:
m = report.parse_period("2026-10", None)
ok(m["since"] == "2026-10-01" and m["until"] == "2026-10-31", "月份区间")
ok(m["until_excl"] == "2026-11-01" and m["unit"] == "month", "次月首日/单位")
w = report.parse_period("2026-10", "2026-10-31")
ok(w["since"] == "2026-10-26" and w["until"] == "2026-11-01", "周区间(周一~周日,跨月)")
ok(w["unit"] == "week" and "第" in w["label"], "周标签")
last = report.parse_period("2026-10", "last")
ok(last["unit"] == "week", "上周模式")
def test_filters() -> None:
rows = [{"_id": "1", "状态": "上线", "上线日期": "2026-10-28"},
{"_id": "2", "状态": "开发中", "上线日期": ""},
{"_id": "3", "状态": "上线", "上线日期": "2026-09-30"}]
got = cli.apply_filters(rows, ["状态=上线"], ["上线日期=2026-10"])
ok(len(got) == 1 and got[0]["_id"] == "1", "--where + --month 组合过滤")
ok(len(cli.apply_filters(rows, [], ["上线日期=2026-10"])) == 1, "仅月份过滤")
def test_attachment_helpers() -> None:
from aitable.client import (attachment_items, parse_expires, safe_filename,
sniff_kind, unique_path)
val = [{"resourceId": "r1", "filename": "a.jpg", "size": 10, "type": "image",
"url": "https://x.oss-cn/y.jpg?Expires=1794886717&Signature=abc"},
{"resourceId": "r2", "filename": "b.png", "size": 5, "type": "image",
"resourceUrl": "/core/api/resources/img/zz"}]
its = attachment_items(val)
ok(len(its) == 2, "attachment 字段值拆出 2 个附件")
ok(its[0]["url"].startswith("https://") and its[0]["size"] == 10, "直连 url 与声明大小保留")
ok(its[1]["url"] == "", "相对 resourceUrl 不当作可直连地址")
ok(attachment_items(None) == [] and attachment_items({"filename": "c"})[0]["url"] == "",
"空值/单个 dict 兼容")
ok(parse_expires(its[0]["url"]) == 1794886717, "解析预签名 Expires")
ok(parse_expires("https://x/y.jpg") == 0, "无 Expires 返回 0")
ok(safe_filename('a/b:c*?"<>|.jpg') == "a_b_c_.jpg", "非法字符换下划线")
ok(safe_filename("", "") == "file" and safe_filename(" .. ") == "file", "空名兜底")
ok(len(safe_filename("x" * 200)) == 120, "文件名限长 120")
import tempfile
with tempfile.TemporaryDirectory() as d:
png, jpg, txt = (Path(d) / n for n in ("a.png", "b.jpg", "c.txt"))
png.write_bytes(b"\x89PNG\r\n\x1a\n" + b"\0" * 8)
jpg.write_bytes(b"\xff\xd8\xff\xe0" + b"\0" * 8)
txt.write_text("hello", encoding="utf-8")
ok(sniff_kind(png) == "png" and sniff_kind(jpg) == "jpg", "按魔数识别 png/jpg")
ok(sniff_kind(txt) == "unknown", "非图片判为 unknown")
ok(sniff_kind(Path(d) / "nope.png") == "missing", "不存在的文件判为 missing")
ok(unique_path(png) == Path(d) / "a-2.png", "同名文件改名 -2")
(Path(d) / "a-2.png").write_bytes(b"x")
ok(unique_path(png) == Path(d) / "a-3.png", "再同名改名 -3")
def test_attachment_download() -> None:
"""本地 HTTP 服务模拟 OSS:验证下载、魔数/大小校验、同名不覆盖、403/过期判定。"""
import http.server
import socketserver
import tempfile
import threading
from aitable.client import AiTable, ATTACH_MIN_REMAIN # noqa: F401
png = b"\x89PNG\r\n\x1a\n" + b"\0" * 24
class _H(http.server.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, *a):
pass
with socketserver.TCPServer(("127.0.0.1", 0), _H) as srv:
threading.Thread(target=srv.serve_forever, daemon=True).start()
port = srv.server_address[1]
base = f"http://127.0.0.1:{port}"
try:
cli_ = AiTable.__new__(AiTable) # 只测下载,不走鉴权初始化
with tempfile.TemporaryDirectory() as d:
r1 = cli_.download_attachment({"url": f"{base}/ok.png", "size": len(png)},
Path(d) / "x.png")
ok(r1["ok"] and r1["kind"] == "png" and r1["size_match"] is True
and r1["bytes"] == len(png), "下载成功 + 魔数/大小校验通过")
r2 = cli_.download_attachment({"url": f"{base}/ok.png", "size": len(png)},
Path(d) / "x.png")
ok(Path(r2["path"]).name == "x-2.png", "同名附件不覆盖,自动加 -2")
r3 = cli_.download_attachment({"url": f"{base}/deny.png"}, Path(d) / "y.png")
ok(r3["expired"] is True and r3["ok"] is False, "403 判定预签名 url 过期")
r4 = cli_.download_attachment({"url": f"{base}/ok.png?Expires=1000"},
Path(d) / "z.png")
ok(r4["expired"] is True and not (Path(d) / "z.png").exists(),
"Expires 已过期 → 不发请求、直接报过期")
multi = cli_.download_attachments(
[{"url": f"{base}/ok.png", "filename": "卡号面.jpg", "size": len(png)},
{"url": f"{base}/ok.png", "filename": "身份证.png", "size": len(png)}],
Path(d) / "sub", prefix="银行卡-", col="银行卡卡号面照片")
names = sorted(Path(x["path"]).name for x in multi)
ok(len(multi) == 2 and all(x["ok"] for x in multi), "多附件字段批量下载")
ok(names == ["银行卡-卡号面.jpg", "银行卡-身份证.png"], "prefix + 原文件名")
ok(multi[0]["col"] == "银行卡卡号面照片" and multi[1]["index"] == 2,
"结果带字段名与序号")
finally:
srv.shutdown()
def test_online() -> None:
from aitable import AiTable
cli_ = AiTable()
sheets = cli_.sheets(BASE_ALIASES["workplan"])
ok(any(s.get("id") == "hERWDMS" for s in sheets), "在线冒烟:能列出 workplan 的 sheet")
rows = cli_.records(BASE_ALIASES["workplan"], "hERWDMS")
ok(len(rows) > 0, f"在线冒烟:能读取记录({len(rows)} 条)")
print(f"[INFO] 近 6 周趋势(上线):{report.collect_table(report.parse_period('', 'current'), 'workplan', 'hERWDMS', '')['trend']}")
def main() -> int:
try:
sys.stdout.reconfigure(encoding="utf-8")
except Exception:
pass
test_norm()
test_ms()
test_coerce()
test_flatten()
test_resolve_base()
test_period()
test_filters()
test_attachment_helpers()
test_attachment_download()
if "--online" in sys.argv:
test_online()
print(f"\n全部通过:{_passed} 项")
return 0
if __name__ == "__main__":
sys.exit(main())