# -*- 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 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_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() if "--online" in sys.argv: test_online() print(f"\n全部通过:{_passed} 项") return 0 if __name__ == "__main__": sys.exit(main())