rescue: 断电事故后工作区全量备份
This commit is contained in:
+24
-24
@@ -1,24 +1,24 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
钉钉自动化(纯 OCR + 键盘)演示入口
|
||||
视觉方案实现已迁移至 app/utils/dingtalk_sender.py,本文件仅作为手动测试入口。
|
||||
功能:
|
||||
- 发送文本到联系人或群组
|
||||
- 发送文件到联系人或群组
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
|
||||
# 以脚本方式直接运行时,将项目根目录加入 sys.path 以导入 app 包
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
|
||||
from app.utils.dingtalk_sender import send_file_to, send_text_to # noqa: E402
|
||||
|
||||
if __name__ == "__main__":
|
||||
# 示例:向联系人发送消息
|
||||
send_text_to("联系人", "夏一平", "测试消息")
|
||||
# 示例:向群组发送消息
|
||||
# send_text_to("群组", "小布丁", "测试消息")
|
||||
# 示例:发送文件
|
||||
# send_file_to("联系人", "夏一平", r"D:\path\to\file.txt")
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
钉钉自动化(纯 OCR + 键盘)演示入口
|
||||
视觉方案实现已迁移至 app/utils/dingtalk_sender.py,本文件仅作为手动测试入口。
|
||||
功能:
|
||||
- 发送文本到联系人或群组
|
||||
- 发送文件到联系人或群组
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
|
||||
# 以脚本方式直接运行时,将项目根目录加入 sys.path 以导入 app 包
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
|
||||
from app.utils.dingtalk_sender import send_file_to, send_text_to # noqa: E402
|
||||
|
||||
if __name__ == "__main__":
|
||||
# 示例:向联系人发送消息
|
||||
send_text_to("联系人", "夏一平", "测试消息")
|
||||
# 示例:向群组发送消息
|
||||
# send_text_to("群组", "小布丁", "测试消息")
|
||||
# 示例:发送文件
|
||||
# send_file_to("联系人", "夏一平", r"D:\path\to\file.txt")
|
||||
|
||||
+845
-845
File diff suppressed because it is too large
Load Diff
+180
-180
@@ -1,181 +1,181 @@
|
||||
import json
|
||||
import urllib.parse
|
||||
|
||||
# ---------- 常量 ----------
|
||||
# 自定义 Base64 字符表(索引0~64,64为填充字符)
|
||||
CUSTOM_CHARS = "y!89(*z02BCcdD_bEeGHIJKLmnNOPQopRMSTqrUklVstWXYZafgh3ij1uvwx456A7"
|
||||
PAD_CHAR = '7' # 填充字符(索引64)
|
||||
SALT = "yyryrtweasdasd" # 固定盐值
|
||||
|
||||
# 反向映射表(解码用)
|
||||
CUSTOM_REV = {ch: idx for idx, ch in enumerate(CUSTOM_CHARS)}
|
||||
|
||||
# ---------- 自定义 Base64 编码 ----------
|
||||
def custom_base64_encode(data: bytes) -> str:
|
||||
"""
|
||||
使用自定义字符表进行 Base64 编码。
|
||||
data: 已 UTF-8 编码的字节序列
|
||||
返回: 编码后的字符串(填充使用 '7')
|
||||
"""
|
||||
result = []
|
||||
for i in range(0, len(data), 3):
|
||||
chunk = data[i:i+3]
|
||||
b1 = chunk[0] if len(chunk) > 0 else 0
|
||||
b2 = chunk[1] if len(chunk) > 1 else 0
|
||||
b3 = chunk[2] if len(chunk) > 2 else 0
|
||||
|
||||
enc1 = (b1 >> 2) & 0x3F
|
||||
enc2 = ((b1 << 4) | (b2 >> 4)) & 0x3F
|
||||
enc3 = ((b2 << 2) | (b3 >> 6)) & 0x3F
|
||||
enc4 = b3 & 0x3F
|
||||
|
||||
if len(chunk) == 1:
|
||||
enc3 = 64
|
||||
enc4 = 64
|
||||
elif len(chunk) == 2:
|
||||
enc4 = 64
|
||||
|
||||
result.append(CUSTOM_CHARS[enc1])
|
||||
result.append(CUSTOM_CHARS[enc2])
|
||||
result.append(CUSTOM_CHARS[enc3])
|
||||
result.append(CUSTOM_CHARS[enc4])
|
||||
|
||||
return ''.join(result)
|
||||
|
||||
# ---------- 自定义 Base64 解码 ----------
|
||||
def custom_base64_decode(s: str) -> bytes:
|
||||
"""
|
||||
使用自定义字符表解码 Base64 字符串。
|
||||
返回原始 UTF-8 字节序列。
|
||||
"""
|
||||
# 过滤掉不属于字符表的字符(与前端一致)
|
||||
filtered = ''.join(ch for ch in s if ch in CUSTOM_REV)
|
||||
result = []
|
||||
for i in range(0, len(filtered), 4):
|
||||
chunk = filtered[i:i+4]
|
||||
# 补足4个字符(使用填充字符'7')
|
||||
while len(chunk) < 4:
|
||||
chunk += PAD_CHAR
|
||||
enc1 = CUSTOM_REV[chunk[0]]
|
||||
enc2 = CUSTOM_REV[chunk[1]]
|
||||
enc3 = CUSTOM_REV[chunk[2]]
|
||||
enc4 = CUSTOM_REV[chunk[3]]
|
||||
|
||||
b1 = ((enc1 << 2) | (enc2 >> 4)) & 0xFF
|
||||
b2 = ((enc2 << 4) | (enc3 >> 2)) & 0xFF
|
||||
b3 = ((enc3 << 6) | enc4) & 0xFF
|
||||
|
||||
result.append(b1)
|
||||
if enc3 != 64:
|
||||
result.append(b2)
|
||||
if enc4 != 64:
|
||||
result.append(b3)
|
||||
return bytes(result)
|
||||
|
||||
# ---------- 加密(编码)----------
|
||||
def encode_common_query(query_list: list) -> str:
|
||||
"""
|
||||
将查询条件列表(Python 对象)加密为 commonQuery 字符串。
|
||||
参数 query_list: 与前端格式一致的列表,例如:
|
||||
[
|
||||
{"queryField": "`hr_staff_move_info.MOVE_DATE`", ...},
|
||||
...
|
||||
]
|
||||
返回: 加密后的字符串(可直接用于表单提交)
|
||||
"""
|
||||
# 1. 转为 JSON 字符串(无空格,与前端 JSON.stringify 一致)
|
||||
json_str = json.dumps(query_list, ensure_ascii=False, separators=(',', ':'))
|
||||
# 2. URI 编码(模拟 encodeURIComponent:不编码 ! ' ( ) * - . _ ~)
|
||||
uri_encoded = urllib.parse.quote(json_str, safe="-_.~!*'()")
|
||||
# 3. 转为 UTF-8 字节
|
||||
utf8_bytes = uri_encoded.encode('utf-8')
|
||||
# 4. 自定义 Base64 编码
|
||||
base64_str = custom_base64_encode(utf8_bytes)
|
||||
# 5. 追加盐值
|
||||
en_str = base64_str + SALT
|
||||
# 6. 重排:前2位 + 后3位 + 中间部分
|
||||
first = en_str[:2]
|
||||
second = en_str[2:-3]
|
||||
third = en_str[-3:]
|
||||
return first + third + second
|
||||
|
||||
# ---------- 解密(解码)----------
|
||||
def decode_common_query(encrypted: str) -> list:
|
||||
"""
|
||||
将加密的 commonQuery 字符串还原为原始查询条件列表。
|
||||
参数 encrypted: 加密后的字符串
|
||||
返回: 原始的查询条件列表(Python 对象)
|
||||
"""
|
||||
# 1. 逆向重排:前2位 + 中间部分 + 后3位
|
||||
first = encrypted[:2]
|
||||
third = encrypted[2:5]
|
||||
second = encrypted[5:]
|
||||
orgin = first + second + third
|
||||
# 2. 去除盐值
|
||||
if orgin.endswith(SALT):
|
||||
orgin = orgin[:-len(SALT)]
|
||||
else:
|
||||
# 容错:如果盐值不完整,尝试匹配前缀(有时末尾会缺失几个字符)
|
||||
if orgin.endswith(SALT[:-3]):
|
||||
orgin = orgin[:-(len(SALT)-3)]
|
||||
# 3. 自定义 Base64 解码
|
||||
utf8_bytes = custom_base64_decode(orgin)
|
||||
uri_encoded = utf8_bytes.decode('utf-8')
|
||||
# 4. URI 解码
|
||||
json_str = urllib.parse.unquote(uri_encoded)
|
||||
# 5. 解析 JSON
|
||||
return json.loads(json_str)
|
||||
|
||||
# ---------- 辅助函数(可选)----------
|
||||
def build_date_range_query(field: str, start_date: str, end_date: str) -> list:
|
||||
"""
|
||||
构造一个标准的日期范围查询列表。
|
||||
参数:
|
||||
field: 字段名(含反引号),如 "`hr_staff_move_info.MOVE_DATE`"
|
||||
start_date: 开始日期,如 "2026-08-01"
|
||||
end_date: 结束日期,如 "2026-08-30"
|
||||
返回: 符合前端格式的查询条件列表。
|
||||
"""
|
||||
return [
|
||||
{
|
||||
"queryField": field,
|
||||
"leftBracket": "(",
|
||||
"queryType": ">=",
|
||||
"queryValue": start_date,
|
||||
"queryText": "",
|
||||
"rightBracket": "",
|
||||
"logic": "AND",
|
||||
"inputType": "date"
|
||||
},
|
||||
{
|
||||
"queryField": field,
|
||||
"leftBracket": "",
|
||||
"queryType": "<=",
|
||||
"queryValue": end_date,
|
||||
"queryText": "",
|
||||
"rightBracket": ")",
|
||||
"logic": "AND",
|
||||
"inputType": "date"
|
||||
}
|
||||
]
|
||||
|
||||
# ---------- 示例 ----------
|
||||
if __name__ == "__main__":
|
||||
# 示例:查询 2026-08-01 至 2026-08-30 的调动记录
|
||||
field = "`hr_staff_move_info.MOVE_DATE`"
|
||||
query = build_date_range_query(field, "2026-08-01", "2026-08-30")
|
||||
|
||||
# 加密
|
||||
encrypted = encode_common_query(query)
|
||||
print("加密后的 commonQuery:")
|
||||
print(encrypted)
|
||||
print()
|
||||
|
||||
# 解密验证
|
||||
decoded = decode_common_query(encrypted)
|
||||
print("解密后的查询条件:")
|
||||
print(json.dumps(decoded, ensure_ascii=False, indent=2))
|
||||
print()
|
||||
|
||||
# 验证是否与原始一致
|
||||
import json
|
||||
import urllib.parse
|
||||
|
||||
# ---------- 常量 ----------
|
||||
# 自定义 Base64 字符表(索引0~64,64为填充字符)
|
||||
CUSTOM_CHARS = "y!89(*z02BCcdD_bEeGHIJKLmnNOPQopRMSTqrUklVstWXYZafgh3ij1uvwx456A7"
|
||||
PAD_CHAR = '7' # 填充字符(索引64)
|
||||
SALT = "yyryrtweasdasd" # 固定盐值
|
||||
|
||||
# 反向映射表(解码用)
|
||||
CUSTOM_REV = {ch: idx for idx, ch in enumerate(CUSTOM_CHARS)}
|
||||
|
||||
# ---------- 自定义 Base64 编码 ----------
|
||||
def custom_base64_encode(data: bytes) -> str:
|
||||
"""
|
||||
使用自定义字符表进行 Base64 编码。
|
||||
data: 已 UTF-8 编码的字节序列
|
||||
返回: 编码后的字符串(填充使用 '7')
|
||||
"""
|
||||
result = []
|
||||
for i in range(0, len(data), 3):
|
||||
chunk = data[i:i+3]
|
||||
b1 = chunk[0] if len(chunk) > 0 else 0
|
||||
b2 = chunk[1] if len(chunk) > 1 else 0
|
||||
b3 = chunk[2] if len(chunk) > 2 else 0
|
||||
|
||||
enc1 = (b1 >> 2) & 0x3F
|
||||
enc2 = ((b1 << 4) | (b2 >> 4)) & 0x3F
|
||||
enc3 = ((b2 << 2) | (b3 >> 6)) & 0x3F
|
||||
enc4 = b3 & 0x3F
|
||||
|
||||
if len(chunk) == 1:
|
||||
enc3 = 64
|
||||
enc4 = 64
|
||||
elif len(chunk) == 2:
|
||||
enc4 = 64
|
||||
|
||||
result.append(CUSTOM_CHARS[enc1])
|
||||
result.append(CUSTOM_CHARS[enc2])
|
||||
result.append(CUSTOM_CHARS[enc3])
|
||||
result.append(CUSTOM_CHARS[enc4])
|
||||
|
||||
return ''.join(result)
|
||||
|
||||
# ---------- 自定义 Base64 解码 ----------
|
||||
def custom_base64_decode(s: str) -> bytes:
|
||||
"""
|
||||
使用自定义字符表解码 Base64 字符串。
|
||||
返回原始 UTF-8 字节序列。
|
||||
"""
|
||||
# 过滤掉不属于字符表的字符(与前端一致)
|
||||
filtered = ''.join(ch for ch in s if ch in CUSTOM_REV)
|
||||
result = []
|
||||
for i in range(0, len(filtered), 4):
|
||||
chunk = filtered[i:i+4]
|
||||
# 补足4个字符(使用填充字符'7')
|
||||
while len(chunk) < 4:
|
||||
chunk += PAD_CHAR
|
||||
enc1 = CUSTOM_REV[chunk[0]]
|
||||
enc2 = CUSTOM_REV[chunk[1]]
|
||||
enc3 = CUSTOM_REV[chunk[2]]
|
||||
enc4 = CUSTOM_REV[chunk[3]]
|
||||
|
||||
b1 = ((enc1 << 2) | (enc2 >> 4)) & 0xFF
|
||||
b2 = ((enc2 << 4) | (enc3 >> 2)) & 0xFF
|
||||
b3 = ((enc3 << 6) | enc4) & 0xFF
|
||||
|
||||
result.append(b1)
|
||||
if enc3 != 64:
|
||||
result.append(b2)
|
||||
if enc4 != 64:
|
||||
result.append(b3)
|
||||
return bytes(result)
|
||||
|
||||
# ---------- 加密(编码)----------
|
||||
def encode_common_query(query_list: list) -> str:
|
||||
"""
|
||||
将查询条件列表(Python 对象)加密为 commonQuery 字符串。
|
||||
参数 query_list: 与前端格式一致的列表,例如:
|
||||
[
|
||||
{"queryField": "`hr_staff_move_info.MOVE_DATE`", ...},
|
||||
...
|
||||
]
|
||||
返回: 加密后的字符串(可直接用于表单提交)
|
||||
"""
|
||||
# 1. 转为 JSON 字符串(无空格,与前端 JSON.stringify 一致)
|
||||
json_str = json.dumps(query_list, ensure_ascii=False, separators=(',', ':'))
|
||||
# 2. URI 编码(模拟 encodeURIComponent:不编码 ! ' ( ) * - . _ ~)
|
||||
uri_encoded = urllib.parse.quote(json_str, safe="-_.~!*'()")
|
||||
# 3. 转为 UTF-8 字节
|
||||
utf8_bytes = uri_encoded.encode('utf-8')
|
||||
# 4. 自定义 Base64 编码
|
||||
base64_str = custom_base64_encode(utf8_bytes)
|
||||
# 5. 追加盐值
|
||||
en_str = base64_str + SALT
|
||||
# 6. 重排:前2位 + 后3位 + 中间部分
|
||||
first = en_str[:2]
|
||||
second = en_str[2:-3]
|
||||
third = en_str[-3:]
|
||||
return first + third + second
|
||||
|
||||
# ---------- 解密(解码)----------
|
||||
def decode_common_query(encrypted: str) -> list:
|
||||
"""
|
||||
将加密的 commonQuery 字符串还原为原始查询条件列表。
|
||||
参数 encrypted: 加密后的字符串
|
||||
返回: 原始的查询条件列表(Python 对象)
|
||||
"""
|
||||
# 1. 逆向重排:前2位 + 中间部分 + 后3位
|
||||
first = encrypted[:2]
|
||||
third = encrypted[2:5]
|
||||
second = encrypted[5:]
|
||||
orgin = first + second + third
|
||||
# 2. 去除盐值
|
||||
if orgin.endswith(SALT):
|
||||
orgin = orgin[:-len(SALT)]
|
||||
else:
|
||||
# 容错:如果盐值不完整,尝试匹配前缀(有时末尾会缺失几个字符)
|
||||
if orgin.endswith(SALT[:-3]):
|
||||
orgin = orgin[:-(len(SALT)-3)]
|
||||
# 3. 自定义 Base64 解码
|
||||
utf8_bytes = custom_base64_decode(orgin)
|
||||
uri_encoded = utf8_bytes.decode('utf-8')
|
||||
# 4. URI 解码
|
||||
json_str = urllib.parse.unquote(uri_encoded)
|
||||
# 5. 解析 JSON
|
||||
return json.loads(json_str)
|
||||
|
||||
# ---------- 辅助函数(可选)----------
|
||||
def build_date_range_query(field: str, start_date: str, end_date: str) -> list:
|
||||
"""
|
||||
构造一个标准的日期范围查询列表。
|
||||
参数:
|
||||
field: 字段名(含反引号),如 "`hr_staff_move_info.MOVE_DATE`"
|
||||
start_date: 开始日期,如 "2026-08-01"
|
||||
end_date: 结束日期,如 "2026-08-30"
|
||||
返回: 符合前端格式的查询条件列表。
|
||||
"""
|
||||
return [
|
||||
{
|
||||
"queryField": field,
|
||||
"leftBracket": "(",
|
||||
"queryType": ">=",
|
||||
"queryValue": start_date,
|
||||
"queryText": "",
|
||||
"rightBracket": "",
|
||||
"logic": "AND",
|
||||
"inputType": "date"
|
||||
},
|
||||
{
|
||||
"queryField": field,
|
||||
"leftBracket": "",
|
||||
"queryType": "<=",
|
||||
"queryValue": end_date,
|
||||
"queryText": "",
|
||||
"rightBracket": ")",
|
||||
"logic": "AND",
|
||||
"inputType": "date"
|
||||
}
|
||||
]
|
||||
|
||||
# ---------- 示例 ----------
|
||||
if __name__ == "__main__":
|
||||
# 示例:查询 2026-08-01 至 2026-08-30 的调动记录
|
||||
field = "`hr_staff_move_info.MOVE_DATE`"
|
||||
query = build_date_range_query(field, "2026-08-01", "2026-08-30")
|
||||
|
||||
# 加密
|
||||
encrypted = encode_common_query(query)
|
||||
print("加密后的 commonQuery:")
|
||||
print(encrypted)
|
||||
print()
|
||||
|
||||
# 解密验证
|
||||
decoded = decode_common_query(encrypted)
|
||||
print("解密后的查询条件:")
|
||||
print(json.dumps(decoded, ensure_ascii=False, indent=2))
|
||||
print()
|
||||
|
||||
# 验证是否与原始一致
|
||||
print("解密后与原始一致:", decoded == query)
|
||||
+86
-86
@@ -1,86 +1,86 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: tests.hrbp._helpers
|
||||
@FileName: _helpers.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-06 10:30
|
||||
@Description: 测试共享辅助:统一 sys.path 设置、登录态获取(优先复用已保存 cookies)
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
|
||||
# ---------- 统一 sys.path:项目根 ----------
|
||||
# 项目根加进来后可用 from app.service.hrbp... 形式 import
|
||||
_PROJECT_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..'))
|
||||
if _PROJECT_ROOT not in sys.path:
|
||||
sys.path.insert(0, _PROJECT_ROOT)
|
||||
|
||||
# 初始化日志(测试脚本共用)
|
||||
from app.utils.logger import setup_logging, get_logger # noqa: E402
|
||||
|
||||
setup_logging()
|
||||
logger = get_logger("tests.hrbp")
|
||||
|
||||
|
||||
def get_logged_in_session(subject: str = "加班"):
|
||||
"""
|
||||
获取已登录的 (browser, session),优先复用本地保存的 cookies,
|
||||
失效或不存在时触发完整登录并保存。
|
||||
|
||||
所有需要登录态的接口测试都应通过此函数获取会话,避免重复登录。
|
||||
|
||||
Args:
|
||||
subject: 待办主题关键字,用于校验会话有效性(默认 "加班")
|
||||
|
||||
Returns:
|
||||
(browser, session):browser 为 ChromiumPage,session 为 SessionPage
|
||||
"""
|
||||
from app.service.hrbp.oa.common.session_manager import (
|
||||
load_saved_session,
|
||||
is_session_valid,
|
||||
init_session_from_page,
|
||||
save_browser_cookies,
|
||||
create_browser_with_saved_cookies,
|
||||
)
|
||||
from app.service.hrbp.oa.common.login import oa_login as _oa_login
|
||||
|
||||
# 1. 尝试复用已保存的 cookies
|
||||
saved_session = load_saved_session()
|
||||
if saved_session is not None and is_session_valid(saved_session, subject):
|
||||
logger.info("复用已保存的登录会话")
|
||||
browser = create_browser_with_saved_cookies()
|
||||
return browser, saved_session
|
||||
|
||||
# 2. 复用失败则完整登录
|
||||
logger.info("无可用会话,执行完整登录")
|
||||
browser = _oa_login()
|
||||
session = init_session_from_page(browser)
|
||||
save_browser_cookies(browser)
|
||||
return browser, session
|
||||
|
||||
|
||||
def pick_first_todo(session, subject: str = "加班"):
|
||||
"""
|
||||
从待办列表取第一条单据,供后续 SSO / 表单详情测试使用。
|
||||
|
||||
Returns:
|
||||
单据字典(含 detail_url 等),无待办时返回 None
|
||||
"""
|
||||
from app.service.hrbp.oa.common.oa_api import get_documents
|
||||
|
||||
docs = get_documents(session, subject=subject)
|
||||
if not docs:
|
||||
logger.warning("无[%s]待办,无法继续后续测试", subject)
|
||||
return None
|
||||
logger.info("取到 %d 条待办,用第一条做后续测试: %s", len(docs), docs[0].get("title"))
|
||||
return docs[0]
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
# 自检:登录并拉取一条待办
|
||||
browser, session = get_logged_in_session()
|
||||
doc = pick_first_todo(session)
|
||||
if doc:
|
||||
logger.info("自检通过,待办示例: %s", doc.get("title"))
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: tests.hrbp._helpers
|
||||
@FileName: _helpers.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-06 10:30
|
||||
@Description: 测试共享辅助:统一 sys.path 设置、登录态获取(优先复用已保存 cookies)
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
|
||||
# ---------- 统一 sys.path:项目根 ----------
|
||||
# 项目根加进来后可用 from app.service.hrbp... 形式 import
|
||||
_PROJECT_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..'))
|
||||
if _PROJECT_ROOT not in sys.path:
|
||||
sys.path.insert(0, _PROJECT_ROOT)
|
||||
|
||||
# 初始化日志(测试脚本共用)
|
||||
from app.utils.logger import setup_logging, get_logger # noqa: E402
|
||||
|
||||
setup_logging()
|
||||
logger = get_logger("tests.hrbp")
|
||||
|
||||
|
||||
def get_logged_in_session(subject: str = "加班"):
|
||||
"""
|
||||
获取已登录的 (browser, session),优先复用本地保存的 cookies,
|
||||
失效或不存在时触发完整登录并保存。
|
||||
|
||||
所有需要登录态的接口测试都应通过此函数获取会话,避免重复登录。
|
||||
|
||||
Args:
|
||||
subject: 待办主题关键字,用于校验会话有效性(默认 "加班")
|
||||
|
||||
Returns:
|
||||
(browser, session):browser 为 ChromiumPage,session 为 SessionPage
|
||||
"""
|
||||
from app.service.hrbp.oa.common.session_manager import (
|
||||
load_saved_session,
|
||||
is_session_valid,
|
||||
init_session_from_page,
|
||||
save_browser_cookies,
|
||||
create_browser_with_saved_cookies,
|
||||
)
|
||||
from app.service.hrbp.oa.common.login import oa_login as _oa_login
|
||||
|
||||
# 1. 尝试复用已保存的 cookies
|
||||
saved_session = load_saved_session()
|
||||
if saved_session is not None and is_session_valid(saved_session, subject):
|
||||
logger.info("复用已保存的登录会话")
|
||||
browser = create_browser_with_saved_cookies()
|
||||
return browser, saved_session
|
||||
|
||||
# 2. 复用失败则完整登录
|
||||
logger.info("无可用会话,执行完整登录")
|
||||
browser = _oa_login()
|
||||
session = init_session_from_page(browser)
|
||||
save_browser_cookies(browser)
|
||||
return browser, session
|
||||
|
||||
|
||||
def pick_first_todo(session, subject: str = "加班"):
|
||||
"""
|
||||
从待办列表取第一条单据,供后续 SSO / 表单详情测试使用。
|
||||
|
||||
Returns:
|
||||
单据字典(含 detail_url 等),无待办时返回 None
|
||||
"""
|
||||
from app.service.hrbp.oa.common.oa_api import get_documents
|
||||
|
||||
docs = get_documents(session, subject=subject)
|
||||
if not docs:
|
||||
logger.warning("无[%s]待办,无法继续后续测试", subject)
|
||||
return None
|
||||
logger.info("取到 %d 条待办,用第一条做后续测试: %s", len(docs), docs[0].get("title"))
|
||||
return docs[0]
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
# 自检:登录并拉取一条待办
|
||||
browser, session = get_logged_in_session()
|
||||
doc = pick_first_todo(session)
|
||||
if doc:
|
||||
logger.info("自检通过,待办示例: %s", doc.get("title"))
|
||||
|
||||
@@ -1,69 +1,69 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: tests.hrbp.test_02_form_detail
|
||||
@FileName: test_02_form_detail.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-06 10:40
|
||||
@Description: 连通性测试②——SSO 解析 + WfActivity + WorkformEngine(表单详情链路)
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..'))
|
||||
|
||||
from tests.hrbp._helpers import get_logged_in_session, pick_first_todo, logger # noqa: E402
|
||||
|
||||
|
||||
def test_sso(browser, detail_url: str):
|
||||
"""测试:SSO 链接解析,提取 taskId + businessKey"""
|
||||
from app.service.hrbp.oa.common.sso import resolve_sso_params
|
||||
|
||||
sso_params = resolve_sso_params(browser, detail_url)
|
||||
assert sso_params.get("taskId"), "taskId 提取失败"
|
||||
assert sso_params.get("businessKey"), "businessKey 提取失败"
|
||||
logger.info("[通过] SSO 解析: taskId=%s, businessKey=%s",
|
||||
sso_params["taskId"], sso_params["businessKey"])
|
||||
return sso_params
|
||||
|
||||
|
||||
def test_wf_activity(session, task_id: str):
|
||||
"""测试:WfActivity 接口 → 提取 formId"""
|
||||
from app.service.hrbp.oa.common.oa_api import get_wf_activity_by_task_id, extract_form_id
|
||||
|
||||
data = get_wf_activity_by_task_id(session, task_id)
|
||||
form_id = extract_form_id(data)
|
||||
assert form_id, "formId 提取失败"
|
||||
logger.info("[通过] WfActivity 接口正常,formId=%s", form_id)
|
||||
return form_id
|
||||
|
||||
|
||||
def test_workform_engine(session, business_key: str, form_id: str):
|
||||
"""测试:WorkformEngine 接口 → 表单数据"""
|
||||
from app.service.hrbp.oa.common.oa_api import get_business_data
|
||||
|
||||
form_data = get_business_data(session, business_key, form_id)
|
||||
assert isinstance(form_data, dict), "表单数据格式异常"
|
||||
# 加班表单应含关键字段
|
||||
assert form_data.get("staff_name"), "表单缺 staff_name"
|
||||
logger.info("[通过] WorkformEngine 接口正常,员工=%s, 加班日期=%s",
|
||||
form_data.get("staff_name"), form_data.get("ot_date"))
|
||||
return form_data
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
logger.info("========== 测试②:SSO + WfActivity + WorkformEngine ==========")
|
||||
browser, session = get_logged_in_session(subject="加班")
|
||||
doc = pick_first_todo(session, subject="加班")
|
||||
if not doc:
|
||||
logger.error("无待办单据,测试中止")
|
||||
else:
|
||||
from app.service.hrbp.oa.common.session_manager import refresh_session_cookies
|
||||
|
||||
sso_params = test_sso(browser, doc["detail_url"])
|
||||
# SSO 后同步 hr 域 cookie 到 session
|
||||
refresh_session_cookies(session, browser)
|
||||
form_id = test_wf_activity(session, sso_params["taskId"])
|
||||
test_workform_engine(session, sso_params["businessKey"], form_id)
|
||||
logger.info("========== 测试②结束 ==========")
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: tests.hrbp.test_02_form_detail
|
||||
@FileName: test_02_form_detail.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-06 10:40
|
||||
@Description: 连通性测试②——SSO 解析 + WfActivity + WorkformEngine(表单详情链路)
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..'))
|
||||
|
||||
from tests.hrbp._helpers import get_logged_in_session, pick_first_todo, logger # noqa: E402
|
||||
|
||||
|
||||
def test_sso(browser, detail_url: str):
|
||||
"""测试:SSO 链接解析,提取 taskId + businessKey"""
|
||||
from app.service.hrbp.oa.common.sso import resolve_sso_params
|
||||
|
||||
sso_params = resolve_sso_params(browser, detail_url)
|
||||
assert sso_params.get("taskId"), "taskId 提取失败"
|
||||
assert sso_params.get("businessKey"), "businessKey 提取失败"
|
||||
logger.info("[通过] SSO 解析: taskId=%s, businessKey=%s",
|
||||
sso_params["taskId"], sso_params["businessKey"])
|
||||
return sso_params
|
||||
|
||||
|
||||
def test_wf_activity(session, task_id: str):
|
||||
"""测试:WfActivity 接口 → 提取 formId"""
|
||||
from app.service.hrbp.oa.common.oa_api import get_wf_activity_by_task_id, extract_form_id
|
||||
|
||||
data = get_wf_activity_by_task_id(session, task_id)
|
||||
form_id = extract_form_id(data)
|
||||
assert form_id, "formId 提取失败"
|
||||
logger.info("[通过] WfActivity 接口正常,formId=%s", form_id)
|
||||
return form_id
|
||||
|
||||
|
||||
def test_workform_engine(session, business_key: str, form_id: str):
|
||||
"""测试:WorkformEngine 接口 → 表单数据"""
|
||||
from app.service.hrbp.oa.common.oa_api import get_business_data
|
||||
|
||||
form_data = get_business_data(session, business_key, form_id)
|
||||
assert isinstance(form_data, dict), "表单数据格式异常"
|
||||
# 加班表单应含关键字段
|
||||
assert form_data.get("staff_name"), "表单缺 staff_name"
|
||||
logger.info("[通过] WorkformEngine 接口正常,员工=%s, 加班日期=%s",
|
||||
form_data.get("staff_name"), form_data.get("ot_date"))
|
||||
return form_data
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
logger.info("========== 测试②:SSO + WfActivity + WorkformEngine ==========")
|
||||
browser, session = get_logged_in_session(subject="加班")
|
||||
doc = pick_first_todo(session, subject="加班")
|
||||
if not doc:
|
||||
logger.error("无待办单据,测试中止")
|
||||
else:
|
||||
from app.service.hrbp.oa.common.session_manager import refresh_session_cookies
|
||||
|
||||
sso_params = test_sso(browser, doc["detail_url"])
|
||||
# SSO 后同步 hr 域 cookie 到 session
|
||||
refresh_session_cookies(session, browser)
|
||||
form_id = test_wf_activity(session, sso_params["taskId"])
|
||||
test_workform_engine(session, sso_params["businessKey"], form_id)
|
||||
logger.info("========== 测试②结束 ==========")
|
||||
|
||||
+119
-119
@@ -1,119 +1,119 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: tests.hrbp.test_04_parsers
|
||||
@FileName: test_04_parsers.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-06 10:50
|
||||
@Description: 连通性测试④——纯解析函数(无需登录,离线测试)
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
import os
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..'))
|
||||
|
||||
from tests.hrbp._helpers import logger # noqa: E402
|
||||
|
||||
|
||||
def test_attendance_daily_work_days():
|
||||
"""测试:排班数据 → 实际上班天数统计(休息日/无记录不计)"""
|
||||
from unittest.mock import MagicMock, patch
|
||||
from app.service.hrbp.oa.leave.validator import _get_work_days_count
|
||||
|
||||
shift = [
|
||||
{
|
||||
"2026-08-10_bc_name": "经营正班A",
|
||||
"2026-08-11_bc_name": "经营正班A",
|
||||
"2026-08-12_bc_name": "休息",
|
||||
"2026-08-13_bc_name": "经营正班A",
|
||||
},
|
||||
]
|
||||
hr_ctx = (MagicMock(), "user-001")
|
||||
|
||||
with patch("app.service.hrbp.oa.leave.validator._get_hr_context",
|
||||
return_value=hr_ctx), \
|
||||
patch("app.service.hrbp.oa.leave.validator.fetch_all_shift",
|
||||
return_value=shift):
|
||||
count = _get_work_days_count("S001", "2026-08-10", "2026-08-13")
|
||||
assert count == 3, f"实际上班天数错误: {count}"
|
||||
|
||||
# 区间内无排班的日期(休息日)也视为休息
|
||||
with patch("app.service.hrbp.oa.leave.validator._get_hr_context",
|
||||
return_value=hr_ctx), \
|
||||
patch("app.service.hrbp.oa.leave.validator.fetch_all_shift",
|
||||
return_value=shift):
|
||||
count2 = _get_work_days_count("S001", "2026-08-10", "2026-08-16")
|
||||
assert count2 == 3, f"含无记录日期的实际上班天数错误: {count2}"
|
||||
|
||||
logger.info("[通过] 排班上班天数统计: 休息日/无记录均不计入")
|
||||
|
||||
|
||||
def test_attendance_daily_merge():
|
||||
"""测试:考勤逐日四种状态(休息/正常/未打卡/异常)各查一次后合并去重"""
|
||||
from unittest.mock import MagicMock, patch
|
||||
from app.service.hrbp.oa.common.oa_api.attendance import get_attendance_daily
|
||||
|
||||
session = MagicMock()
|
||||
normal = [{"work_day": "2026-08-14", "bc_name": "经营正班A", "xb_dk_time": "18:05:58"}]
|
||||
abnormal = [{"work_day": "2026-08-15", "bc_name": "维护早班", "bc_begin_time": "08:00",
|
||||
"bc_end_time": "17:00", "xb_dk_time2": "19:49:49"}]
|
||||
|
||||
def fake_request(session, method, url, params, desc):
|
||||
# 按 kq_status_total 参数返回对应状态的数据
|
||||
status = params.get("kq_status_total")
|
||||
if status == "1":
|
||||
return {"data": normal}
|
||||
if status == "11":
|
||||
return {"data": abnormal}
|
||||
return {"data": []}
|
||||
|
||||
with patch("app.service.hrbp.oa.common.oa_api.attendance.oa_request_json",
|
||||
side_effect=fake_request) as m:
|
||||
records = get_attendance_daily(session, "S001", "2026-08-14", "2026-08-15")
|
||||
|
||||
# 四种状态各请求一次
|
||||
assert m.call_count == 4, f"应请求4次,实际{m.call_count}"
|
||||
# 合并去重后按日期升序
|
||||
assert [r["work_day"] for r in records] == ["2026-08-14", "2026-08-15"], \
|
||||
f"合并顺序错误: {records}"
|
||||
# 异常班记录保留班次与打卡
|
||||
ab_rec = records[1]
|
||||
assert ab_rec["bc_name"] == "维护早班"
|
||||
assert ab_rec["bc_end_time"] == "17:00"
|
||||
assert ab_rec["xb_dk_time2"] == "19:49:49"
|
||||
logger.info("[通过] 考勤逐日状态合并: 休息/正常/未打卡/异常各查一次,合并去重保留班次与打卡")
|
||||
|
||||
|
||||
def test_overtime_form_parse():
|
||||
"""测试:加班表单解析 + 类型映射"""
|
||||
from app.service.hrbp.oa.work_overtime.parser import parse_overtime_form
|
||||
|
||||
form_data = {
|
||||
"staff_id": "572e6cce-7a9f-11ec-b449-000c296f9469",
|
||||
"staff_name": "黄俊林",
|
||||
"dept_org_name": "网络项目小组",
|
||||
"ot_type": "1", # → 延时加班
|
||||
"subsidy_type": "2", # → 转补贴
|
||||
"ot_date": "2026-08-02",
|
||||
"start_time": "2026-08-02 18:00",
|
||||
"end_time": "2026-08-03 00:00",
|
||||
"ot_hour": 6.0,
|
||||
"judge_ot_hour": 6.0,
|
||||
"judge_start_time": "2026-08-02 18:00:00",
|
||||
"judge_end_time": "2026-08-03 00:00:00",
|
||||
"file": "ccc1d3ef-175a-4105-a8a8-0e63ed88d7bd",
|
||||
}
|
||||
info = parse_overtime_form(form_data)
|
||||
assert info["加班人员ID"] == "572e6cce-7a9f-11ec-b449-000c296f9469"
|
||||
assert info["加班类型"] == "延时加班", f"类型映射错误: {info['加班类型']}"
|
||||
assert info["补贴类型"] == "转补贴"
|
||||
assert info["系统判定加班时间"] == "2026-08-02 18:00:00 至 2026-08-03 00:00:00"
|
||||
logger.info("[通过] 加班表单解析 + 类型映射: %s", info["加班类型"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
logger.info("========== 测试④:纯解析函数(离线) ==========")
|
||||
test_attendance_daily_work_days()
|
||||
test_attendance_daily_merge()
|
||||
test_overtime_form_parse()
|
||||
logger.info("========== 测试④结束 ==========")
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: tests.hrbp.test_04_parsers
|
||||
@FileName: test_04_parsers.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-06 10:50
|
||||
@Description: 连通性测试④——纯解析函数(无需登录,离线测试)
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
import os
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..'))
|
||||
|
||||
from tests.hrbp._helpers import logger # noqa: E402
|
||||
|
||||
|
||||
def test_attendance_daily_work_days():
|
||||
"""测试:排班数据 → 实际上班天数统计(休息日/无记录不计)"""
|
||||
from unittest.mock import MagicMock, patch
|
||||
from app.service.hrbp.oa.leave.validator import _get_work_days_count
|
||||
|
||||
shift = [
|
||||
{
|
||||
"2026-08-10_bc_name": "经营正班A",
|
||||
"2026-08-11_bc_name": "经营正班A",
|
||||
"2026-08-12_bc_name": "休息",
|
||||
"2026-08-13_bc_name": "经营正班A",
|
||||
},
|
||||
]
|
||||
hr_ctx = (MagicMock(), "user-001")
|
||||
|
||||
with patch("app.service.hrbp.oa.leave.validator._get_hr_context",
|
||||
return_value=hr_ctx), \
|
||||
patch("app.service.hrbp.oa.leave.validator.fetch_all_shift",
|
||||
return_value=shift):
|
||||
count = _get_work_days_count("S001", "2026-08-10", "2026-08-13")
|
||||
assert count == 3, f"实际上班天数错误: {count}"
|
||||
|
||||
# 区间内无排班的日期(休息日)也视为休息
|
||||
with patch("app.service.hrbp.oa.leave.validator._get_hr_context",
|
||||
return_value=hr_ctx), \
|
||||
patch("app.service.hrbp.oa.leave.validator.fetch_all_shift",
|
||||
return_value=shift):
|
||||
count2 = _get_work_days_count("S001", "2026-08-10", "2026-08-16")
|
||||
assert count2 == 3, f"含无记录日期的实际上班天数错误: {count2}"
|
||||
|
||||
logger.info("[通过] 排班上班天数统计: 休息日/无记录均不计入")
|
||||
|
||||
|
||||
def test_attendance_daily_merge():
|
||||
"""测试:考勤逐日四种状态(休息/正常/未打卡/异常)各查一次后合并去重"""
|
||||
from unittest.mock import MagicMock, patch
|
||||
from app.service.hrbp.oa.common.oa_api.attendance import get_attendance_daily
|
||||
|
||||
session = MagicMock()
|
||||
normal = [{"work_day": "2026-08-14", "bc_name": "经营正班A", "xb_dk_time": "18:05:58"}]
|
||||
abnormal = [{"work_day": "2026-08-15", "bc_name": "维护早班", "bc_begin_time": "08:00",
|
||||
"bc_end_time": "17:00", "xb_dk_time2": "19:49:49"}]
|
||||
|
||||
def fake_request(session, method, url, params, desc):
|
||||
# 按 kq_status_total 参数返回对应状态的数据
|
||||
status = params.get("kq_status_total")
|
||||
if status == "1":
|
||||
return {"data": normal}
|
||||
if status == "11":
|
||||
return {"data": abnormal}
|
||||
return {"data": []}
|
||||
|
||||
with patch("app.service.hrbp.oa.common.oa_api.attendance.oa_request_json",
|
||||
side_effect=fake_request) as m:
|
||||
records = get_attendance_daily(session, "S001", "2026-08-14", "2026-08-15")
|
||||
|
||||
# 四种状态各请求一次
|
||||
assert m.call_count == 4, f"应请求4次,实际{m.call_count}"
|
||||
# 合并去重后按日期升序
|
||||
assert [r["work_day"] for r in records] == ["2026-08-14", "2026-08-15"], \
|
||||
f"合并顺序错误: {records}"
|
||||
# 异常班记录保留班次与打卡
|
||||
ab_rec = records[1]
|
||||
assert ab_rec["bc_name"] == "维护早班"
|
||||
assert ab_rec["bc_end_time"] == "17:00"
|
||||
assert ab_rec["xb_dk_time2"] == "19:49:49"
|
||||
logger.info("[通过] 考勤逐日状态合并: 休息/正常/未打卡/异常各查一次,合并去重保留班次与打卡")
|
||||
|
||||
|
||||
def test_overtime_form_parse():
|
||||
"""测试:加班表单解析 + 类型映射"""
|
||||
from app.service.hrbp.oa.work_overtime.parser import parse_overtime_form
|
||||
|
||||
form_data = {
|
||||
"staff_id": "572e6cce-7a9f-11ec-b449-000c296f9469",
|
||||
"staff_name": "黄俊林",
|
||||
"dept_org_name": "网络项目小组",
|
||||
"ot_type": "1", # → 延时加班
|
||||
"subsidy_type": "2", # → 转补贴
|
||||
"ot_date": "2026-08-02",
|
||||
"start_time": "2026-08-02 18:00",
|
||||
"end_time": "2026-08-03 00:00",
|
||||
"ot_hour": 6.0,
|
||||
"judge_ot_hour": 6.0,
|
||||
"judge_start_time": "2026-08-02 18:00:00",
|
||||
"judge_end_time": "2026-08-03 00:00:00",
|
||||
"file": "ccc1d3ef-175a-4105-a8a8-0e63ed88d7bd",
|
||||
}
|
||||
info = parse_overtime_form(form_data)
|
||||
assert info["加班人员ID"] == "572e6cce-7a9f-11ec-b449-000c296f9469"
|
||||
assert info["加班类型"] == "延时加班", f"类型映射错误: {info['加班类型']}"
|
||||
assert info["补贴类型"] == "转补贴"
|
||||
assert info["系统判定加班时间"] == "2026-08-02 18:00:00 至 2026-08-03 00:00:00"
|
||||
logger.info("[通过] 加班表单解析 + 类型映射: %s", info["加班类型"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
logger.info("========== 测试④:纯解析函数(离线) ==========")
|
||||
test_attendance_daily_work_days()
|
||||
test_attendance_daily_merge()
|
||||
test_overtime_form_parse()
|
||||
logger.info("========== 测试④结束 ==========")
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
+152
-152
@@ -1,153 +1,153 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: tests.hrbp.test_06_leave_online
|
||||
@FileName: test_06_leave_online.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-06
|
||||
@Description: 连通性测试⑥——请假流程在线测试(需登录)
|
||||
测试项:
|
||||
1. 请假记录接口(get_leave_records)
|
||||
2. 待办列表接口 - 请假主题
|
||||
3. 请假全流程(SSO → 表单 → 校验 → 报告)
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..'))
|
||||
|
||||
from tests.hrbp._helpers import get_logged_in_session, pick_first_todo, logger # noqa: E402
|
||||
|
||||
# 测试用员工(黄俊林),与 test_03 共用
|
||||
TEST_STAFF_ID = "572e6cce-7a9f-11ec-b449-000c296f9469"
|
||||
TEST_DATE = "2026-08-02"
|
||||
|
||||
|
||||
def test_leave_records_api(session, staff_id: str):
|
||||
"""测试:请假记录接口连通性 + 自动分页"""
|
||||
from app.service.hrbp.oa.common.oa_api import get_leave_records
|
||||
|
||||
records = get_leave_records(session, staff_id, "2026-01-01", "2026-12-31", page_size=10)
|
||||
assert isinstance(records, list), "请假记录格式异常"
|
||||
logger.info("[通过] 请假记录接口正常,共 %d 条记录", len(records))
|
||||
|
||||
if records:
|
||||
r = records[0]
|
||||
logger.info(" 示例: %s | %s | %s天 | %s~%s",
|
||||
r.get("vacation_type_name") or r.get("sub_type"),
|
||||
r.get("leave_businessKey"),
|
||||
r.get("leave_days"),
|
||||
r.get("start_time"),
|
||||
r.get("end_time"))
|
||||
return records
|
||||
|
||||
|
||||
def test_leave_todo_list(session):
|
||||
"""测试:待办列表接口 - 请假主题过滤"""
|
||||
from app.service.hrbp.oa.common.oa_api import get_documents, fetch_todo_page
|
||||
|
||||
# 单页探活
|
||||
page_data = fetch_todo_page(session, subject="请假", page_no=1, page_size=1)
|
||||
total = int(page_data.get("page", {}).get("totalSize", 0))
|
||||
assert total >= 0, "请假待办总数字段异常"
|
||||
logger.info("[通过] 请假待办接口连通,总数=%d", total)
|
||||
|
||||
# 完整拉取
|
||||
docs = get_documents(session, subject="请假")
|
||||
logger.info("[通过] 请假待办解析完成,共 %d 条", len(docs))
|
||||
for d in docs[:3]:
|
||||
logger.info(" - %s | %s", d.get("creator"), d.get("title"))
|
||||
return docs
|
||||
|
||||
|
||||
def test_leave_attendance_daily(session, staff_id: str):
|
||||
"""测试:考勤逐日接口(请假场景,班次名 + 休息日识别)"""
|
||||
from app.service.hrbp.oa.common.oa_api import get_attendance_daily
|
||||
|
||||
start_date = TEST_DATE
|
||||
end_date = TEST_DATE
|
||||
records = get_attendance_daily(session, staff_id, start_date, end_date)
|
||||
assert isinstance(records, list), "考勤逐日格式异常"
|
||||
logger.info("[通过] 请假考勤逐日接口正常,返回 %d 天数据", len(records))
|
||||
for r in records[:5]:
|
||||
logger.info(" %s | %s", r.get("work_day"), r.get("bc_name"))
|
||||
return records
|
||||
|
||||
|
||||
def test_leave_full_flow(session, browser):
|
||||
"""
|
||||
测试:请假全流程(如有待办)
|
||||
取第一条请假待办 → SSO 解析 → WfActivity → WorkformEngine → 校验 → 报告
|
||||
"""
|
||||
from app.service.hrbp.oa.common.sso import resolve_sso_params
|
||||
from app.service.hrbp.oa.common.session_manager import refresh_session_cookies
|
||||
from app.service.hrbp.oa.common.oa_api import (
|
||||
get_wf_activity_by_task_id,
|
||||
extract_form_id,
|
||||
get_business_data,
|
||||
)
|
||||
from app.service.hrbp.oa.leave.validator import validate_doc
|
||||
from app.service.hrbp.oa.leave.reporter import generate_report
|
||||
|
||||
doc = pick_first_todo(session, subject="请假")
|
||||
if not doc:
|
||||
logger.warning("无请假待办,跳过全流程测试")
|
||||
return None
|
||||
|
||||
logger.info("待办: %s | %s", doc.get("creator"), doc.get("title"))
|
||||
|
||||
# 1. SSO 解析
|
||||
sso_params = resolve_sso_params(browser, doc["detail_url"])
|
||||
assert sso_params.get("taskId"), "taskId 提取失败"
|
||||
assert sso_params.get("businessKey"), "businessKey 提取失败"
|
||||
logger.info(" [SSO] taskId=%s, businessKey=%s", sso_params["taskId"], sso_params["businessKey"])
|
||||
|
||||
# 2. 同步 cookie → WfActivity
|
||||
refresh_session_cookies(session, browser)
|
||||
wf_data = get_wf_activity_by_task_id(session, sso_params["taskId"])
|
||||
form_id = extract_form_id(wf_data)
|
||||
assert form_id, "formId 提取失败"
|
||||
logger.info(" [WfActivity] formId=%s", form_id)
|
||||
|
||||
# 3. WorkformEngine → 表单数据
|
||||
form_data = get_business_data(session, sso_params["businessKey"], form_id)
|
||||
assert isinstance(form_data, dict), "表单数据格式异常"
|
||||
logger.info(" [WorkformEngine] 员工=%s, 表单字段=%s",
|
||||
form_data.get("staff_name"), list(form_data.keys()))
|
||||
|
||||
# 4. 校验
|
||||
doc_detail = {**doc, "formData": form_data}
|
||||
result = validate_doc(doc_detail, session)
|
||||
logger.info(" [校验] decision=%s, note=%s", result["decision"], result["note"])
|
||||
|
||||
# 5. 报告(单条)
|
||||
report = generate_report([result])
|
||||
assert "请假审批报告" in report
|
||||
logger.info(" [报告] 生成成功")
|
||||
|
||||
# 输出表单关键字段供后续适配参考
|
||||
logger.info(" [表单字段快照]")
|
||||
for k, v in form_data.items():
|
||||
logger.info(" %s: %s", k, v)
|
||||
|
||||
return result
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
logger.info("========== 测试⑥:请假流程在线测试 ==========")
|
||||
browser, session = get_logged_in_session(subject="请假")
|
||||
|
||||
# 1. 请假记录接口
|
||||
test_leave_records_api(session, TEST_STAFF_ID)
|
||||
|
||||
# 2. 请假待办列表
|
||||
docs = test_leave_todo_list(session)
|
||||
|
||||
# 3. 请假考勤逐日接口
|
||||
test_leave_attendance_daily(session, TEST_STAFF_ID)
|
||||
|
||||
# 4. 请假全流程(如有待办)
|
||||
test_leave_full_flow(session, browser)
|
||||
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: tests.hrbp.test_06_leave_online
|
||||
@FileName: test_06_leave_online.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-06
|
||||
@Description: 连通性测试⑥——请假流程在线测试(需登录)
|
||||
测试项:
|
||||
1. 请假记录接口(get_leave_records)
|
||||
2. 待办列表接口 - 请假主题
|
||||
3. 请假全流程(SSO → 表单 → 校验 → 报告)
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..'))
|
||||
|
||||
from tests.hrbp._helpers import get_logged_in_session, pick_first_todo, logger # noqa: E402
|
||||
|
||||
# 测试用员工(黄俊林),与 test_03 共用
|
||||
TEST_STAFF_ID = "572e6cce-7a9f-11ec-b449-000c296f9469"
|
||||
TEST_DATE = "2026-08-02"
|
||||
|
||||
|
||||
def test_leave_records_api(session, staff_id: str):
|
||||
"""测试:请假记录接口连通性 + 自动分页"""
|
||||
from app.service.hrbp.oa.common.oa_api import get_leave_records
|
||||
|
||||
records = get_leave_records(session, staff_id, "2026-01-01", "2026-12-31", page_size=10)
|
||||
assert isinstance(records, list), "请假记录格式异常"
|
||||
logger.info("[通过] 请假记录接口正常,共 %d 条记录", len(records))
|
||||
|
||||
if records:
|
||||
r = records[0]
|
||||
logger.info(" 示例: %s | %s | %s天 | %s~%s",
|
||||
r.get("vacation_type_name") or r.get("sub_type"),
|
||||
r.get("leave_businessKey"),
|
||||
r.get("leave_days"),
|
||||
r.get("start_time"),
|
||||
r.get("end_time"))
|
||||
return records
|
||||
|
||||
|
||||
def test_leave_todo_list(session):
|
||||
"""测试:待办列表接口 - 请假主题过滤"""
|
||||
from app.service.hrbp.oa.common.oa_api import get_documents, fetch_todo_page
|
||||
|
||||
# 单页探活
|
||||
page_data = fetch_todo_page(session, subject="请假", page_no=1, page_size=1)
|
||||
total = int(page_data.get("page", {}).get("totalSize", 0))
|
||||
assert total >= 0, "请假待办总数字段异常"
|
||||
logger.info("[通过] 请假待办接口连通,总数=%d", total)
|
||||
|
||||
# 完整拉取
|
||||
docs = get_documents(session, subject="请假")
|
||||
logger.info("[通过] 请假待办解析完成,共 %d 条", len(docs))
|
||||
for d in docs[:3]:
|
||||
logger.info(" - %s | %s", d.get("creator"), d.get("title"))
|
||||
return docs
|
||||
|
||||
|
||||
def test_leave_attendance_daily(session, staff_id: str):
|
||||
"""测试:考勤逐日接口(请假场景,班次名 + 休息日识别)"""
|
||||
from app.service.hrbp.oa.common.oa_api import get_attendance_daily
|
||||
|
||||
start_date = TEST_DATE
|
||||
end_date = TEST_DATE
|
||||
records = get_attendance_daily(session, staff_id, start_date, end_date)
|
||||
assert isinstance(records, list), "考勤逐日格式异常"
|
||||
logger.info("[通过] 请假考勤逐日接口正常,返回 %d 天数据", len(records))
|
||||
for r in records[:5]:
|
||||
logger.info(" %s | %s", r.get("work_day"), r.get("bc_name"))
|
||||
return records
|
||||
|
||||
|
||||
def test_leave_full_flow(session, browser):
|
||||
"""
|
||||
测试:请假全流程(如有待办)
|
||||
取第一条请假待办 → SSO 解析 → WfActivity → WorkformEngine → 校验 → 报告
|
||||
"""
|
||||
from app.service.hrbp.oa.common.sso import resolve_sso_params
|
||||
from app.service.hrbp.oa.common.session_manager import refresh_session_cookies
|
||||
from app.service.hrbp.oa.common.oa_api import (
|
||||
get_wf_activity_by_task_id,
|
||||
extract_form_id,
|
||||
get_business_data,
|
||||
)
|
||||
from app.service.hrbp.oa.leave.validator import validate_doc
|
||||
from app.service.hrbp.oa.leave.reporter import generate_report
|
||||
|
||||
doc = pick_first_todo(session, subject="请假")
|
||||
if not doc:
|
||||
logger.warning("无请假待办,跳过全流程测试")
|
||||
return None
|
||||
|
||||
logger.info("待办: %s | %s", doc.get("creator"), doc.get("title"))
|
||||
|
||||
# 1. SSO 解析
|
||||
sso_params = resolve_sso_params(browser, doc["detail_url"])
|
||||
assert sso_params.get("taskId"), "taskId 提取失败"
|
||||
assert sso_params.get("businessKey"), "businessKey 提取失败"
|
||||
logger.info(" [SSO] taskId=%s, businessKey=%s", sso_params["taskId"], sso_params["businessKey"])
|
||||
|
||||
# 2. 同步 cookie → WfActivity
|
||||
refresh_session_cookies(session, browser)
|
||||
wf_data = get_wf_activity_by_task_id(session, sso_params["taskId"])
|
||||
form_id = extract_form_id(wf_data)
|
||||
assert form_id, "formId 提取失败"
|
||||
logger.info(" [WfActivity] formId=%s", form_id)
|
||||
|
||||
# 3. WorkformEngine → 表单数据
|
||||
form_data = get_business_data(session, sso_params["businessKey"], form_id)
|
||||
assert isinstance(form_data, dict), "表单数据格式异常"
|
||||
logger.info(" [WorkformEngine] 员工=%s, 表单字段=%s",
|
||||
form_data.get("staff_name"), list(form_data.keys()))
|
||||
|
||||
# 4. 校验
|
||||
doc_detail = {**doc, "formData": form_data}
|
||||
result = validate_doc(doc_detail, session)
|
||||
logger.info(" [校验] decision=%s, note=%s", result["decision"], result["note"])
|
||||
|
||||
# 5. 报告(单条)
|
||||
report = generate_report([result])
|
||||
assert "请假审批报告" in report
|
||||
logger.info(" [报告] 生成成功")
|
||||
|
||||
# 输出表单关键字段供后续适配参考
|
||||
logger.info(" [表单字段快照]")
|
||||
for k, v in form_data.items():
|
||||
logger.info(" %s: %s", k, v)
|
||||
|
||||
return result
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
logger.info("========== 测试⑥:请假流程在线测试 ==========")
|
||||
browser, session = get_logged_in_session(subject="请假")
|
||||
|
||||
# 1. 请假记录接口
|
||||
test_leave_records_api(session, TEST_STAFF_ID)
|
||||
|
||||
# 2. 请假待办列表
|
||||
docs = test_leave_todo_list(session)
|
||||
|
||||
# 3. 请假考勤逐日接口
|
||||
test_leave_attendance_daily(session, TEST_STAFF_ID)
|
||||
|
||||
# 4. 请假全流程(如有待办)
|
||||
test_leave_full_flow(session, browser)
|
||||
|
||||
logger.info("========== 测试⑥结束 ==========")
|
||||
+42
-42
@@ -1,42 +1,42 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
OCR 附件检测测试入口。
|
||||
通用图像识别见 app/utils/ocr.py,请假附件业务检测见
|
||||
app/service/hrbp/oa/leave/attachment_check.py,本文件仅做导入与自测。
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
|
||||
# 项目根目录 = tests 的上级目录,保证可导入 app 包
|
||||
_PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
if _PROJECT_ROOT not in sys.path:
|
||||
sys.path.insert(0, _PROJECT_ROOT)
|
||||
|
||||
from app.service.hrbp.oa.leave.attachment_check import (
|
||||
check_leave_attachment,
|
||||
marriage_within_one_year,
|
||||
extract_dates,
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
# 替换为你的附件路径,修改 leave_type 即可测试不同假期
|
||||
test_path = r"D:\downloads\ocr_test_01.png"
|
||||
|
||||
print("病假检测(开启调试)")
|
||||
result = check_leave_attachment(test_path, leave_type="sick", debug=True)
|
||||
print(f"病假检测结果:{result}\n")
|
||||
|
||||
# 测试婚假检测 + 登记日期 1 年内
|
||||
# result = check_leave_attachment("结婚证图片路径", leave_type="marriage", debug=True)
|
||||
# print(f"婚假检测结果:{result}")
|
||||
# ok, reg_date = marriage_within_one_year("结婚证图片路径", debug=True)
|
||||
# print(f"登记日期:{reg_date},1年内:{ok}")
|
||||
|
||||
# 测试产检假检测
|
||||
# result = check_leave_attachment("产检单图片路径", leave_type="maternity", debug=True)
|
||||
# print(f"产检假检测结果:{result}")
|
||||
|
||||
# 日期提取单测
|
||||
print("日期提取测试:", extract_dates("2025年5月20日登记,出生1998年3月2日,2025-05-20"))
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
OCR 附件检测测试入口。
|
||||
通用图像识别见 app/utils/ocr.py,请假附件业务检测见
|
||||
app/service/hrbp/oa/leave/attachment_check.py,本文件仅做导入与自测。
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
|
||||
# 项目根目录 = tests 的上级目录,保证可导入 app 包
|
||||
_PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
if _PROJECT_ROOT not in sys.path:
|
||||
sys.path.insert(0, _PROJECT_ROOT)
|
||||
|
||||
from app.service.hrbp.oa.leave.attachment_check import (
|
||||
check_leave_attachment,
|
||||
marriage_within_one_year,
|
||||
extract_dates,
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
# 替换为你的附件路径,修改 leave_type 即可测试不同假期
|
||||
test_path = r"D:\downloads\ocr_test_01.png"
|
||||
|
||||
print("病假检测(开启调试)")
|
||||
result = check_leave_attachment(test_path, leave_type="sick", debug=True)
|
||||
print(f"病假检测结果:{result}\n")
|
||||
|
||||
# 测试婚假检测 + 登记日期 1 年内
|
||||
# result = check_leave_attachment("结婚证图片路径", leave_type="marriage", debug=True)
|
||||
# print(f"婚假检测结果:{result}")
|
||||
# ok, reg_date = marriage_within_one_year("结婚证图片路径", debug=True)
|
||||
# print(f"登记日期:{reg_date},1年内:{ok}")
|
||||
|
||||
# 测试产检假检测
|
||||
# result = check_leave_attachment("产检单图片路径", leave_type="maternity", debug=True)
|
||||
# print(f"产检假检测结果:{result}")
|
||||
|
||||
# 日期提取单测
|
||||
print("日期提取测试:", extract_dates("2025年5月20日登记,出生1998年3月2日,2025-05-20"))
|
||||
|
||||
+125
-125
@@ -1,126 +1,126 @@
|
||||
from dataclasses import dataclass
|
||||
from typing import Optional
|
||||
|
||||
|
||||
@dataclass
|
||||
class LeaveRule:
|
||||
"""正休规则返回对象"""
|
||||
days: int # 默认正休天数
|
||||
rule_type: str # 规则类型:大小休 / 固休 / 天数限额排休
|
||||
max_days: Optional[int] = None # 限额排休时的上限天数
|
||||
note: str = "" # 备注说明
|
||||
|
||||
|
||||
class LeavePolicyEngine:
|
||||
"""
|
||||
正休规则查询引擎
|
||||
用法:直接调用 .query(所属单位, 组织类型, 职位序列) 即可获得天数
|
||||
"""
|
||||
|
||||
def __init__(self):
|
||||
# ========== 可配置参数(方便后期调整) ==========
|
||||
self.DAYS_SIZE_REST = 6 # 大小休默认天数
|
||||
self.DAYS_FIXED_REST = 5 # 固休天数
|
||||
self.DAYS_QUOTA_LIMIT = 8 # 限额排休上限
|
||||
|
||||
# ========== 规则判定用单位列表(方便后期增删) ==========
|
||||
# 集团总部职能部门(大小休)
|
||||
self.GROUP_HEADQUARTER_UNITS = [
|
||||
"财务管理部",
|
||||
"集团管理中心",
|
||||
"集团营建中心",
|
||||
]
|
||||
|
||||
def query(self, unit: str, org: str, sequence: str = "") -> LeaveRule:
|
||||
"""
|
||||
查询正休天数
|
||||
|
||||
:param unit: 所属单位,如 "财务管理部"、"金色印象事业部"、"金色湖畔事业部"
|
||||
:param org: 组织类型,如 "财务管理部"、"大区"、"会馆"
|
||||
:param sequence: 职位序列,如 "门店技师序列"、"经营系管理序列"(可选)
|
||||
:return: LeaveRule 对象
|
||||
"""
|
||||
# ---------- 优先级1:技师序列(跨事业部通用) ----------
|
||||
if "技师" in sequence:
|
||||
return LeaveRule(
|
||||
days=self.DAYS_QUOTA_LIMIT,
|
||||
rule_type="天数限额排休",
|
||||
max_days=self.DAYS_QUOTA_LIMIT,
|
||||
note=f"排班上限{self.DAYS_QUOTA_LIMIT}天"
|
||||
)
|
||||
|
||||
# ---------- 优先级2:金色湖畔事业部(全员固休,除技师外) ----------
|
||||
if unit == "金色湖畔事业部":
|
||||
return LeaveRule(
|
||||
days=self.DAYS_FIXED_REST,
|
||||
rule_type="固休",
|
||||
note="固定单休"
|
||||
)
|
||||
|
||||
# ---------- 优先级3:集团总部职能部门 ----------
|
||||
if unit in self.GROUP_HEADQUARTER_UNITS:
|
||||
return LeaveRule(
|
||||
days=self.DAYS_SIZE_REST,
|
||||
rule_type="大小休",
|
||||
note=f"大小休,默认{self.DAYS_SIZE_REST}天"
|
||||
)
|
||||
|
||||
# ---------- 优先级4:金色印象事业部 ----------
|
||||
if unit == "金色印象事业部":
|
||||
# 组织类型包含"事业部" → 大小休;其他(大区、经营中心、片区、会馆等)→ 固休
|
||||
if "事业部" in org:
|
||||
return LeaveRule(
|
||||
days=self.DAYS_SIZE_REST,
|
||||
rule_type="大小休",
|
||||
note=f"大小休,默认{self.DAYS_SIZE_REST}天"
|
||||
)
|
||||
else:
|
||||
# 大区、经营中心、片区、会馆(经营/服务序列)
|
||||
return LeaveRule(
|
||||
days=self.DAYS_FIXED_REST,
|
||||
rule_type="固休",
|
||||
note="固定单休"
|
||||
)
|
||||
|
||||
# ---------- 兜底:未匹配到规则 ----------
|
||||
return LeaveRule(
|
||||
days=0,
|
||||
rule_type="未知",
|
||||
note="未匹配到对应规则,请检查入参是否正确"
|
||||
)
|
||||
|
||||
|
||||
# ======================== 使用示例 & 测试 ========================
|
||||
if __name__ == "__main__":
|
||||
engine = LeavePolicyEngine()
|
||||
|
||||
# 构造测试数据(覆盖所有场景)
|
||||
test_cases = [
|
||||
# (所属单位, 组织类型, 职位序列)
|
||||
("财务管理部", "", ""),
|
||||
("集团管理中心", "", ""),
|
||||
("集团营建中心", "", ""),
|
||||
("金色印象事业部", "事业部", ""),
|
||||
("金色印象事业部", "事业部职能部门", ""),
|
||||
("金色印象事业部", "大区", ""),
|
||||
("金色印象事业部", "经营中心", ""),
|
||||
("金色印象事业部", "片区", ""),
|
||||
("金色印象事业部", "会馆", "经营系管理序列"),
|
||||
("金色印象事业部", "会馆", "门店服务序列"),
|
||||
("金色印象事业部", "会馆", "门店技师序列"),
|
||||
("金色湖畔事业部", "事业部", ""),
|
||||
("金色湖畔事业部", "大区", ""),
|
||||
("金色湖畔事业部", "会馆", "经营系管理序列"),
|
||||
("金色湖畔事业部", "会馆", "门店技师序列"),
|
||||
# 异常测试
|
||||
("未知单位", "未知组织", ""),
|
||||
]
|
||||
|
||||
print("=" * 60)
|
||||
print(f"{'所属单位':<12} | {'组织':<10} | {'序列':<12} | {'天数':<4} | {'规则':<10} | 备注")
|
||||
print("=" * 60)
|
||||
|
||||
for unit, org, seq in test_cases:
|
||||
rule = engine.query(unit, org, seq)
|
||||
seq_display = seq if seq else "-"
|
||||
from dataclasses import dataclass
|
||||
from typing import Optional
|
||||
|
||||
|
||||
@dataclass
|
||||
class LeaveRule:
|
||||
"""正休规则返回对象"""
|
||||
days: int # 默认正休天数
|
||||
rule_type: str # 规则类型:大小休 / 固休 / 天数限额排休
|
||||
max_days: Optional[int] = None # 限额排休时的上限天数
|
||||
note: str = "" # 备注说明
|
||||
|
||||
|
||||
class LeavePolicyEngine:
|
||||
"""
|
||||
正休规则查询引擎
|
||||
用法:直接调用 .query(所属单位, 组织类型, 职位序列) 即可获得天数
|
||||
"""
|
||||
|
||||
def __init__(self):
|
||||
# ========== 可配置参数(方便后期调整) ==========
|
||||
self.DAYS_SIZE_REST = 6 # 大小休默认天数
|
||||
self.DAYS_FIXED_REST = 5 # 固休天数
|
||||
self.DAYS_QUOTA_LIMIT = 8 # 限额排休上限
|
||||
|
||||
# ========== 规则判定用单位列表(方便后期增删) ==========
|
||||
# 集团总部职能部门(大小休)
|
||||
self.GROUP_HEADQUARTER_UNITS = [
|
||||
"财务管理部",
|
||||
"集团管理中心",
|
||||
"集团营建中心",
|
||||
]
|
||||
|
||||
def query(self, unit: str, org: str, sequence: str = "") -> LeaveRule:
|
||||
"""
|
||||
查询正休天数
|
||||
|
||||
:param unit: 所属单位,如 "财务管理部"、"金色印象事业部"、"金色湖畔事业部"
|
||||
:param org: 组织类型,如 "财务管理部"、"大区"、"会馆"
|
||||
:param sequence: 职位序列,如 "门店技师序列"、"经营系管理序列"(可选)
|
||||
:return: LeaveRule 对象
|
||||
"""
|
||||
# ---------- 优先级1:技师序列(跨事业部通用) ----------
|
||||
if "技师" in sequence:
|
||||
return LeaveRule(
|
||||
days=self.DAYS_QUOTA_LIMIT,
|
||||
rule_type="天数限额排休",
|
||||
max_days=self.DAYS_QUOTA_LIMIT,
|
||||
note=f"排班上限{self.DAYS_QUOTA_LIMIT}天"
|
||||
)
|
||||
|
||||
# ---------- 优先级2:金色湖畔事业部(全员固休,除技师外) ----------
|
||||
if unit == "金色湖畔事业部":
|
||||
return LeaveRule(
|
||||
days=self.DAYS_FIXED_REST,
|
||||
rule_type="固休",
|
||||
note="固定单休"
|
||||
)
|
||||
|
||||
# ---------- 优先级3:集团总部职能部门 ----------
|
||||
if unit in self.GROUP_HEADQUARTER_UNITS:
|
||||
return LeaveRule(
|
||||
days=self.DAYS_SIZE_REST,
|
||||
rule_type="大小休",
|
||||
note=f"大小休,默认{self.DAYS_SIZE_REST}天"
|
||||
)
|
||||
|
||||
# ---------- 优先级4:金色印象事业部 ----------
|
||||
if unit == "金色印象事业部":
|
||||
# 组织类型包含"事业部" → 大小休;其他(大区、经营中心、片区、会馆等)→ 固休
|
||||
if "事业部" in org:
|
||||
return LeaveRule(
|
||||
days=self.DAYS_SIZE_REST,
|
||||
rule_type="大小休",
|
||||
note=f"大小休,默认{self.DAYS_SIZE_REST}天"
|
||||
)
|
||||
else:
|
||||
# 大区、经营中心、片区、会馆(经营/服务序列)
|
||||
return LeaveRule(
|
||||
days=self.DAYS_FIXED_REST,
|
||||
rule_type="固休",
|
||||
note="固定单休"
|
||||
)
|
||||
|
||||
# ---------- 兜底:未匹配到规则 ----------
|
||||
return LeaveRule(
|
||||
days=0,
|
||||
rule_type="未知",
|
||||
note="未匹配到对应规则,请检查入参是否正确"
|
||||
)
|
||||
|
||||
|
||||
# ======================== 使用示例 & 测试 ========================
|
||||
if __name__ == "__main__":
|
||||
engine = LeavePolicyEngine()
|
||||
|
||||
# 构造测试数据(覆盖所有场景)
|
||||
test_cases = [
|
||||
# (所属单位, 组织类型, 职位序列)
|
||||
("财务管理部", "", ""),
|
||||
("集团管理中心", "", ""),
|
||||
("集团营建中心", "", ""),
|
||||
("金色印象事业部", "事业部", ""),
|
||||
("金色印象事业部", "事业部职能部门", ""),
|
||||
("金色印象事业部", "大区", ""),
|
||||
("金色印象事业部", "经营中心", ""),
|
||||
("金色印象事业部", "片区", ""),
|
||||
("金色印象事业部", "会馆", "经营系管理序列"),
|
||||
("金色印象事业部", "会馆", "门店服务序列"),
|
||||
("金色印象事业部", "会馆", "门店技师序列"),
|
||||
("金色湖畔事业部", "事业部", ""),
|
||||
("金色湖畔事业部", "大区", ""),
|
||||
("金色湖畔事业部", "会馆", "经营系管理序列"),
|
||||
("金色湖畔事业部", "会馆", "门店技师序列"),
|
||||
# 异常测试
|
||||
("未知单位", "未知组织", ""),
|
||||
]
|
||||
|
||||
print("=" * 60)
|
||||
print(f"{'所属单位':<12} | {'组织':<10} | {'序列':<12} | {'天数':<4} | {'规则':<10} | 备注")
|
||||
print("=" * 60)
|
||||
|
||||
for unit, org, seq in test_cases:
|
||||
rule = engine.query(unit, org, seq)
|
||||
seq_display = seq if seq else "-"
|
||||
print(f"{unit:<12} | {org:<10} | {seq_display:<12} | {rule.days:<4} | {rule.rule_type:<10} | {rule.note}")
|
||||
+131
-131
@@ -1,132 +1,132 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: tests.run_all_tests
|
||||
@FileName: run_all_tests.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-06
|
||||
@Description: 统一测试运行器
|
||||
用法:
|
||||
python tests/run_all_tests.py # 仅运行离线测试
|
||||
python tests/run_all_tests.py --online # 运行全部测试(含在线)
|
||||
python tests/run_all_tests.py --list # 列出所有测试
|
||||
python tests/run_all_tests.py test_05 # 运行指定测试
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
# 测试文件列表(按依赖顺序排列)
|
||||
ALL_TESTS = [
|
||||
# 离线测试(无需登录,可独立运行)
|
||||
("test_04_parsers", "离线", "解析函数(排班/打卡/加班表单)"),
|
||||
("test_05_leave_validator", "离线", "请假校验模块"),
|
||||
|
||||
# 在线测试(需登录态,有依赖顺序)
|
||||
("test_01_login_session", "在线", "登录 + 会话 + 待办列表"),
|
||||
("test_02_form_detail", "在线", "SSO + WfActivity + WorkformEngine"),
|
||||
("test_03_attendance", "在线", "排班 + 打卡明细接口"),
|
||||
("test_06_leave_online", "在线", "请假记录 + 全流程"),
|
||||
]
|
||||
|
||||
# 在线测试需要在离线测试之后运行
|
||||
ONLINE_TESTS = [t for t in ALL_TESTS if t[1] == "在线"]
|
||||
OFFLINE_TESTS = [t for t in ALL_TESTS if t[1] == "离线"]
|
||||
|
||||
|
||||
def print_header(text: str):
|
||||
"""打印分隔标题"""
|
||||
width = 60
|
||||
print(f"\n{'=' * width}")
|
||||
print(f" {text}")
|
||||
print(f"{'=' * width}")
|
||||
|
||||
|
||||
def run_test(test_name: str) -> bool:
|
||||
"""运行单个测试文件,返回是否成功"""
|
||||
test_file = os.path.join(os.path.dirname(__file__), "hrbp", f"{test_name}.py")
|
||||
if not os.path.exists(test_file):
|
||||
print(f" [错误] 测试文件不存在: {test_file}")
|
||||
return False
|
||||
|
||||
print(f"\n ▶ 运行: {test_name}")
|
||||
result = subprocess.run(
|
||||
[sys.executable, test_file],
|
||||
capture_output=False,
|
||||
cwd=os.path.join(os.path.dirname(__file__), ".."),
|
||||
)
|
||||
return result.returncode == 0
|
||||
|
||||
|
||||
def list_tests():
|
||||
"""列出所有测试"""
|
||||
print_header("可用测试列表")
|
||||
for name, kind, desc in ALL_TESTS:
|
||||
print(f" [{kind}] {name:30s} {desc}")
|
||||
print(f"\n 离线测试: {len(OFFLINE_TESTS)} 个")
|
||||
print(f" 在线测试: {len(ONLINE_TESTS)} 个")
|
||||
print(f" 共计: {len(ALL_TESTS)} 个")
|
||||
|
||||
|
||||
def run_selected(name: str) -> bool:
|
||||
"""运行指定测试(支持模糊匹配)"""
|
||||
matched = [t for t in ALL_TESTS if name in t[0]]
|
||||
if not matched:
|
||||
print(f"未找到匹配 '{name}' 的测试")
|
||||
return False
|
||||
|
||||
success = True
|
||||
for test_name, kind, desc in matched:
|
||||
print_header(f"运行: {test_name} ({kind} - {desc})")
|
||||
if not run_test(test_name):
|
||||
success = False
|
||||
return success
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description="Process-Automation 统一测试运行器")
|
||||
parser.add_argument("--online", action="store_true", help="同时运行在线测试(需登录态)")
|
||||
parser.add_argument("--list", action="store_true", help="列出所有测试")
|
||||
parser.add_argument("test", nargs="?", help="运行指定测试(支持模糊匹配)")
|
||||
args = parser.parse_args()
|
||||
|
||||
if args.list:
|
||||
list_tests()
|
||||
return
|
||||
|
||||
if args.test:
|
||||
run_selected(args.test)
|
||||
return
|
||||
|
||||
# 默认:运行所有离线测试
|
||||
all_pass = True
|
||||
print_header("Process-Automation 测试套件")
|
||||
print(f" 离线测试: {len(OFFLINE_TESTS)} 个")
|
||||
if args.online:
|
||||
print(f" 在线测试: {len(ONLINE_TESTS)} 个")
|
||||
print()
|
||||
|
||||
for test_name, kind, desc in OFFLINE_TESTS:
|
||||
print(f"\n [{kind}] {desc}")
|
||||
if not run_test(test_name):
|
||||
all_pass = False
|
||||
|
||||
if args.online:
|
||||
print(f"\n{'─' * 60}")
|
||||
print(" 开始在线测试...")
|
||||
for test_name, kind, desc in ONLINE_TESTS:
|
||||
print(f"\n [{kind}] {desc}")
|
||||
if not run_test(test_name):
|
||||
all_pass = False
|
||||
|
||||
print_header("测试结果汇总")
|
||||
if all_pass:
|
||||
print(" ✅ 全部通过")
|
||||
else:
|
||||
print(" ❌ 存在失败项")
|
||||
print(f"{'=' * 60}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: tests.run_all_tests
|
||||
@FileName: run_all_tests.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-06
|
||||
@Description: 统一测试运行器
|
||||
用法:
|
||||
python tests/run_all_tests.py # 仅运行离线测试
|
||||
python tests/run_all_tests.py --online # 运行全部测试(含在线)
|
||||
python tests/run_all_tests.py --list # 列出所有测试
|
||||
python tests/run_all_tests.py test_05 # 运行指定测试
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
# 测试文件列表(按依赖顺序排列)
|
||||
ALL_TESTS = [
|
||||
# 离线测试(无需登录,可独立运行)
|
||||
("test_04_parsers", "离线", "解析函数(排班/打卡/加班表单)"),
|
||||
("test_05_leave_validator", "离线", "请假校验模块"),
|
||||
|
||||
# 在线测试(需登录态,有依赖顺序)
|
||||
("test_01_login_session", "在线", "登录 + 会话 + 待办列表"),
|
||||
("test_02_form_detail", "在线", "SSO + WfActivity + WorkformEngine"),
|
||||
("test_03_attendance", "在线", "排班 + 打卡明细接口"),
|
||||
("test_06_leave_online", "在线", "请假记录 + 全流程"),
|
||||
]
|
||||
|
||||
# 在线测试需要在离线测试之后运行
|
||||
ONLINE_TESTS = [t for t in ALL_TESTS if t[1] == "在线"]
|
||||
OFFLINE_TESTS = [t for t in ALL_TESTS if t[1] == "离线"]
|
||||
|
||||
|
||||
def print_header(text: str):
|
||||
"""打印分隔标题"""
|
||||
width = 60
|
||||
print(f"\n{'=' * width}")
|
||||
print(f" {text}")
|
||||
print(f"{'=' * width}")
|
||||
|
||||
|
||||
def run_test(test_name: str) -> bool:
|
||||
"""运行单个测试文件,返回是否成功"""
|
||||
test_file = os.path.join(os.path.dirname(__file__), "hrbp", f"{test_name}.py")
|
||||
if not os.path.exists(test_file):
|
||||
print(f" [错误] 测试文件不存在: {test_file}")
|
||||
return False
|
||||
|
||||
print(f"\n ▶ 运行: {test_name}")
|
||||
result = subprocess.run(
|
||||
[sys.executable, test_file],
|
||||
capture_output=False,
|
||||
cwd=os.path.join(os.path.dirname(__file__), ".."),
|
||||
)
|
||||
return result.returncode == 0
|
||||
|
||||
|
||||
def list_tests():
|
||||
"""列出所有测试"""
|
||||
print_header("可用测试列表")
|
||||
for name, kind, desc in ALL_TESTS:
|
||||
print(f" [{kind}] {name:30s} {desc}")
|
||||
print(f"\n 离线测试: {len(OFFLINE_TESTS)} 个")
|
||||
print(f" 在线测试: {len(ONLINE_TESTS)} 个")
|
||||
print(f" 共计: {len(ALL_TESTS)} 个")
|
||||
|
||||
|
||||
def run_selected(name: str) -> bool:
|
||||
"""运行指定测试(支持模糊匹配)"""
|
||||
matched = [t for t in ALL_TESTS if name in t[0]]
|
||||
if not matched:
|
||||
print(f"未找到匹配 '{name}' 的测试")
|
||||
return False
|
||||
|
||||
success = True
|
||||
for test_name, kind, desc in matched:
|
||||
print_header(f"运行: {test_name} ({kind} - {desc})")
|
||||
if not run_test(test_name):
|
||||
success = False
|
||||
return success
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description="Process-Automation 统一测试运行器")
|
||||
parser.add_argument("--online", action="store_true", help="同时运行在线测试(需登录态)")
|
||||
parser.add_argument("--list", action="store_true", help="列出所有测试")
|
||||
parser.add_argument("test", nargs="?", help="运行指定测试(支持模糊匹配)")
|
||||
args = parser.parse_args()
|
||||
|
||||
if args.list:
|
||||
list_tests()
|
||||
return
|
||||
|
||||
if args.test:
|
||||
run_selected(args.test)
|
||||
return
|
||||
|
||||
# 默认:运行所有离线测试
|
||||
all_pass = True
|
||||
print_header("Process-Automation 测试套件")
|
||||
print(f" 离线测试: {len(OFFLINE_TESTS)} 个")
|
||||
if args.online:
|
||||
print(f" 在线测试: {len(ONLINE_TESTS)} 个")
|
||||
print()
|
||||
|
||||
for test_name, kind, desc in OFFLINE_TESTS:
|
||||
print(f"\n [{kind}] {desc}")
|
||||
if not run_test(test_name):
|
||||
all_pass = False
|
||||
|
||||
if args.online:
|
||||
print(f"\n{'─' * 60}")
|
||||
print(" 开始在线测试...")
|
||||
for test_name, kind, desc in ONLINE_TESTS:
|
||||
print(f"\n [{kind}] {desc}")
|
||||
if not run_test(test_name):
|
||||
all_pass = False
|
||||
|
||||
print_header("测试结果汇总")
|
||||
if all_pass:
|
||||
print(" ✅ 全部通过")
|
||||
else:
|
||||
print(" ❌ 存在失败项")
|
||||
print(f"{'=' * 60}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
+83
-83
File diff suppressed because one or more lines are too long
+56
-56
@@ -1,57 +1,57 @@
|
||||
import win32com.client
|
||||
from openpyxl import load_workbook
|
||||
import os
|
||||
|
||||
|
||||
def recalc_excel_by_wps_com(file_path: str):
|
||||
"""
|
||||
使用WPS COM重算表格,保存计算缓存到文件
|
||||
仅支持 WPS专业版 / MS‑Excel
|
||||
"""
|
||||
abs_path = os.path.abspath(file_path)
|
||||
app = None
|
||||
try:
|
||||
# 尝试WPS表格 COM
|
||||
app = win32com.client.gencache.EnsureDispatch("Ket.Application")
|
||||
app.Visible = False # 后台不显示窗口
|
||||
app.DisplayAlerts = False # 关闭弹窗警告
|
||||
|
||||
# UpdateLinks=2 更新外部链接;你是本文件公式也带上无妨
|
||||
wb = app.Workbooks.Open(abs_path, UpdateLinks=2)
|
||||
|
||||
# 强制完整重算全部公式
|
||||
wb.Application.CalculateFullRebuild()
|
||||
|
||||
# 关键:保存,把计算结果缓存写入xlsx磁盘
|
||||
wb.Save()
|
||||
wb.Close()
|
||||
|
||||
except Exception as e:
|
||||
print(f"COM执行异常: {e}")
|
||||
raise
|
||||
finally:
|
||||
if app is not None:
|
||||
app.Quit()
|
||||
del app
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
file = r"C:\Users\admin\Desktop\test.xlsx"
|
||||
|
||||
# ==========1. openpyxl写入测试数据(模拟粘贴数值到目标表)==========
|
||||
wb = load_workbook(file)
|
||||
ws = wb.active
|
||||
ws["A2"] = 10
|
||||
ws["B2"] = 20
|
||||
# C2单元格预先在文件内写好公式 =A2+B2
|
||||
wb.save(file)
|
||||
wb.close()
|
||||
|
||||
# ==========2.调用WPS COM后台重算并保存缓存==========
|
||||
recalc_excel_by_wps_com(file)
|
||||
|
||||
# ==========3. openpyxl读取计算后的值==========
|
||||
wb_final = load_workbook(file, data_only=True)
|
||||
val = wb_final.active["C2"].value
|
||||
print(f"C2计算结果 = {val}")
|
||||
import win32com.client
|
||||
from openpyxl import load_workbook
|
||||
import os
|
||||
|
||||
|
||||
def recalc_excel_by_wps_com(file_path: str):
|
||||
"""
|
||||
使用WPS COM重算表格,保存计算缓存到文件
|
||||
仅支持 WPS专业版 / MS‑Excel
|
||||
"""
|
||||
abs_path = os.path.abspath(file_path)
|
||||
app = None
|
||||
try:
|
||||
# 尝试WPS表格 COM
|
||||
app = win32com.client.gencache.EnsureDispatch("Ket.Application")
|
||||
app.Visible = False # 后台不显示窗口
|
||||
app.DisplayAlerts = False # 关闭弹窗警告
|
||||
|
||||
# UpdateLinks=2 更新外部链接;你是本文件公式也带上无妨
|
||||
wb = app.Workbooks.Open(abs_path, UpdateLinks=2)
|
||||
|
||||
# 强制完整重算全部公式
|
||||
wb.Application.CalculateFullRebuild()
|
||||
|
||||
# 关键:保存,把计算结果缓存写入xlsx磁盘
|
||||
wb.Save()
|
||||
wb.Close()
|
||||
|
||||
except Exception as e:
|
||||
print(f"COM执行异常: {e}")
|
||||
raise
|
||||
finally:
|
||||
if app is not None:
|
||||
app.Quit()
|
||||
del app
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
file = r"C:\Users\admin\Desktop\test.xlsx"
|
||||
|
||||
# ==========1. openpyxl写入测试数据(模拟粘贴数值到目标表)==========
|
||||
wb = load_workbook(file)
|
||||
ws = wb.active
|
||||
ws["A2"] = 10
|
||||
ws["B2"] = 20
|
||||
# C2单元格预先在文件内写好公式 =A2+B2
|
||||
wb.save(file)
|
||||
wb.close()
|
||||
|
||||
# ==========2.调用WPS COM后台重算并保存缓存==========
|
||||
recalc_excel_by_wps_com(file)
|
||||
|
||||
# ==========3. openpyxl读取计算后的值==========
|
||||
wb_final = load_workbook(file, data_only=True)
|
||||
val = wb_final.active["C2"].value
|
||||
print(f"C2计算结果 = {val}")
|
||||
wb_final.close()
|
||||
+100
-100
@@ -1,100 +1,100 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Description: WPS COM 可行性验证(雇主险场景)——
|
||||
模拟「openpyxl 写入业务数据 → 目标表公式列缓存丢失 → WPS COM 打开重算保存 → openpyxl 读回公式结果」。
|
||||
验证 WPS 个人版 Ket.Application 是否满足 XQ0002 插件版「自动化替代人工 Ctrl+S 刷新公式」的需求。
|
||||
不触碰真实业务文件,全部在 %TEMP%\\wps_com_feasibility\\ 下完成。
|
||||
@Run: d:\\work\\code\\37duAutomation\\.venv\\Scripts\\python.exe tests\\wps_com_feasibility.py
|
||||
"""
|
||||
import os
|
||||
import sys
|
||||
import shutil
|
||||
import tempfile
|
||||
import traceback
|
||||
from datetime import datetime
|
||||
|
||||
import openpyxl
|
||||
from openpyxl import load_workbook
|
||||
import win32com.client
|
||||
import pythoncom
|
||||
|
||||
WORK_DIR = os.path.join(tempfile.gettempdir(), "wps_com_feasibility")
|
||||
TEST_FILE = os.path.join(WORK_DIR, "雇主险验证-重算公式.xlsx")
|
||||
|
||||
|
||||
def step1_write_data_via_openpyxl():
|
||||
"""openpyxl 模拟雇主险写入:业务值 + 目标表已有公式列(openpyxl 不计算,缓存留空)"""
|
||||
wb = openpyxl.Workbook()
|
||||
ws = wb.active
|
||||
ws.title = "花名册导出-雇主险使用基础信息"
|
||||
# 业务数据(模拟 B~O 列一部分)
|
||||
ws["B4"] = "三十七度"
|
||||
ws["O5"] = "5101**********1234"
|
||||
ws["P5"] = "一类"
|
||||
ws["Q5"] = "人保-20万"
|
||||
ws["W5"] = "增加投保"
|
||||
# 模拟目标表里的公式列:V5 = 证件号长度(真实业务里是公式),openpyxl 只写公式不计算
|
||||
ws["V5"] = '=IF(LEN(O5)>0,"有证","无证")'
|
||||
# 模拟跨 sheet 公式(变更清单场景)
|
||||
ws2 = wb.create_sheet("37度-雇员变更清单-9.22")
|
||||
ws2["B3"] = 100
|
||||
ws2["C3"] = 200
|
||||
ws2["D3"] = "=B3+C3" # 公式列,openpyxl 写后缓存为空
|
||||
ws2["E3"] = '=IF(D3>0,"OK","-")'
|
||||
wb.save(TEST_FILE)
|
||||
wb.close()
|
||||
print(f"[1] openpyxl 写入完成: {TEST_FILE}")
|
||||
|
||||
# 证明:data_only 读公式列缓存为空(这就是业务里"必须人工 Ctrl+S"的原因)
|
||||
wb_r = load_workbook(TEST_FILE, data_only=True)
|
||||
v1 = wb_r["花名册导出-雇主险使用基础信息"]["V5"].value
|
||||
v2 = wb_r["37度-雇员变更清单-9.22"]["D3"].value
|
||||
v3 = wb_r["37度-雇员变更清单-9.22"]["E3"].value
|
||||
wb_r.close()
|
||||
print(f" 写后缓存值(应为 None): V5={v1!r} D3={v2!r} E3={v3!r}")
|
||||
assert v1 is None and v2 is None and v3 is None, "openpyxl 写后公式缓存应全空"
|
||||
|
||||
|
||||
def step2_recalc_via_wps_com():
|
||||
"""WPS COM 打开 → 全量重算 → 保存(替代人工 Ctrl+S)"""
|
||||
pythoncom.CoInitialize()
|
||||
app = None
|
||||
try:
|
||||
app = win32com.client.gencache.EnsureDispatch("Ket.Application")
|
||||
app.Visible = False
|
||||
app.DisplayAlerts = False
|
||||
wb = app.Workbooks.Open(os.path.abspath(TEST_FILE), UpdateLinks=2)
|
||||
wb.Application.CalculateFullRebuild()
|
||||
wb.Save()
|
||||
wb.Close()
|
||||
print("[2] WPS COM 重算并保存成功")
|
||||
finally:
|
||||
if app is not None:
|
||||
app.Quit()
|
||||
pythoncom.CoUninitialize()
|
||||
|
||||
|
||||
def step3_read_back():
|
||||
"""openpyxl data_only 读回公式结果,验证缓存已落盘"""
|
||||
wb = load_workbook(TEST_FILE, data_only=True)
|
||||
v1 = wb["花名册导出-雇主险使用基础信息"]["V5"].value
|
||||
v2 = wb["37度-雇员变更清单-9.22"]["D3"].value
|
||||
v3 = wb["37度-雇员变更清单-9.22"]["E3"].value
|
||||
wb.close()
|
||||
print(f"[3] 重算后缓存值: V5={v1!r} D3={v2!r} E3={v3!r}")
|
||||
assert v1 == "有证" and v2 == 300 and v3 == "OK", f"公式结果不符: {v1=} {v2=} {v3=}"
|
||||
print(" ✅ 全部公式结果已计算并缓存落盘,openpyxl 可直接读取")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
shutil.rmtree(WORK_DIR, ignore_errors=True)
|
||||
os.makedirs(WORK_DIR, exist_ok=True)
|
||||
step1_write_data_via_openpyxl()
|
||||
step2_recalc_via_wps_com()
|
||||
step3_read_back()
|
||||
print("\n结论:WPS 个人版 Ket.Application COM 可行 —— 可替代雇主险人工刷新公式(Ctrl+S)环节")
|
||||
except Exception:
|
||||
print("\n结论:验证失败,详情如下")
|
||||
traceback.print_exc()
|
||||
sys.exit(1)
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Description: WPS COM 可行性验证(雇主险场景)——
|
||||
模拟「openpyxl 写入业务数据 → 目标表公式列缓存丢失 → WPS COM 打开重算保存 → openpyxl 读回公式结果」。
|
||||
验证 WPS 个人版 Ket.Application 是否满足 XQ0002 插件版「自动化替代人工 Ctrl+S 刷新公式」的需求。
|
||||
不触碰真实业务文件,全部在 %TEMP%\\wps_com_feasibility\\ 下完成。
|
||||
@Run: d:\\work\\code\\37duAutomation\\.venv\\Scripts\\python.exe tests\\wps_com_feasibility.py
|
||||
"""
|
||||
import os
|
||||
import sys
|
||||
import shutil
|
||||
import tempfile
|
||||
import traceback
|
||||
from datetime import datetime
|
||||
|
||||
import openpyxl
|
||||
from openpyxl import load_workbook
|
||||
import win32com.client
|
||||
import pythoncom
|
||||
|
||||
WORK_DIR = os.path.join(tempfile.gettempdir(), "wps_com_feasibility")
|
||||
TEST_FILE = os.path.join(WORK_DIR, "雇主险验证-重算公式.xlsx")
|
||||
|
||||
|
||||
def step1_write_data_via_openpyxl():
|
||||
"""openpyxl 模拟雇主险写入:业务值 + 目标表已有公式列(openpyxl 不计算,缓存留空)"""
|
||||
wb = openpyxl.Workbook()
|
||||
ws = wb.active
|
||||
ws.title = "花名册导出-雇主险使用基础信息"
|
||||
# 业务数据(模拟 B~O 列一部分)
|
||||
ws["B4"] = "三十七度"
|
||||
ws["O5"] = "5101**********1234"
|
||||
ws["P5"] = "一类"
|
||||
ws["Q5"] = "人保-20万"
|
||||
ws["W5"] = "增加投保"
|
||||
# 模拟目标表里的公式列:V5 = 证件号长度(真实业务里是公式),openpyxl 只写公式不计算
|
||||
ws["V5"] = '=IF(LEN(O5)>0,"有证","无证")'
|
||||
# 模拟跨 sheet 公式(变更清单场景)
|
||||
ws2 = wb.create_sheet("37度-雇员变更清单-9.22")
|
||||
ws2["B3"] = 100
|
||||
ws2["C3"] = 200
|
||||
ws2["D3"] = "=B3+C3" # 公式列,openpyxl 写后缓存为空
|
||||
ws2["E3"] = '=IF(D3>0,"OK","-")'
|
||||
wb.save(TEST_FILE)
|
||||
wb.close()
|
||||
print(f"[1] openpyxl 写入完成: {TEST_FILE}")
|
||||
|
||||
# 证明:data_only 读公式列缓存为空(这就是业务里"必须人工 Ctrl+S"的原因)
|
||||
wb_r = load_workbook(TEST_FILE, data_only=True)
|
||||
v1 = wb_r["花名册导出-雇主险使用基础信息"]["V5"].value
|
||||
v2 = wb_r["37度-雇员变更清单-9.22"]["D3"].value
|
||||
v3 = wb_r["37度-雇员变更清单-9.22"]["E3"].value
|
||||
wb_r.close()
|
||||
print(f" 写后缓存值(应为 None): V5={v1!r} D3={v2!r} E3={v3!r}")
|
||||
assert v1 is None and v2 is None and v3 is None, "openpyxl 写后公式缓存应全空"
|
||||
|
||||
|
||||
def step2_recalc_via_wps_com():
|
||||
"""WPS COM 打开 → 全量重算 → 保存(替代人工 Ctrl+S)"""
|
||||
pythoncom.CoInitialize()
|
||||
app = None
|
||||
try:
|
||||
app = win32com.client.gencache.EnsureDispatch("Ket.Application")
|
||||
app.Visible = False
|
||||
app.DisplayAlerts = False
|
||||
wb = app.Workbooks.Open(os.path.abspath(TEST_FILE), UpdateLinks=2)
|
||||
wb.Application.CalculateFullRebuild()
|
||||
wb.Save()
|
||||
wb.Close()
|
||||
print("[2] WPS COM 重算并保存成功")
|
||||
finally:
|
||||
if app is not None:
|
||||
app.Quit()
|
||||
pythoncom.CoUninitialize()
|
||||
|
||||
|
||||
def step3_read_back():
|
||||
"""openpyxl data_only 读回公式结果,验证缓存已落盘"""
|
||||
wb = load_workbook(TEST_FILE, data_only=True)
|
||||
v1 = wb["花名册导出-雇主险使用基础信息"]["V5"].value
|
||||
v2 = wb["37度-雇员变更清单-9.22"]["D3"].value
|
||||
v3 = wb["37度-雇员变更清单-9.22"]["E3"].value
|
||||
wb.close()
|
||||
print(f"[3] 重算后缓存值: V5={v1!r} D3={v2!r} E3={v3!r}")
|
||||
assert v1 == "有证" and v2 == 300 and v3 == "OK", f"公式结果不符: {v1=} {v2=} {v3=}"
|
||||
print(" ✅ 全部公式结果已计算并缓存落盘,openpyxl 可直接读取")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
shutil.rmtree(WORK_DIR, ignore_errors=True)
|
||||
os.makedirs(WORK_DIR, exist_ok=True)
|
||||
step1_write_data_via_openpyxl()
|
||||
step2_recalc_via_wps_com()
|
||||
step3_read_back()
|
||||
print("\n结论:WPS 个人版 Ket.Application COM 可行 —— 可替代雇主险人工刷新公式(Ctrl+S)环节")
|
||||
except Exception:
|
||||
print("\n结论:验证失败,详情如下")
|
||||
traceback.print_exc()
|
||||
sys.exit(1)
|
||||
|
||||
+341
-341
@@ -1,341 +1,341 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0002 雇主险插件 全链路冒烟自测(本机 .venv 执行)。
|
||||
|
||||
覆盖链路:花名册筛选复制 → WPS/Excel COM 后台重算(可选)→ 三阶段名额调度
|
||||
(更新在参名单 / 精细更新变更清单 / 备份新在参名单)→ 增/减员导入文件 → 变更清单独立工作簿。
|
||||
|
||||
测试数据(临时目录):
|
||||
- 员工花名册.xlsx:表头行 B 列=「所属单位」,B~O 14 列;8 名员工,含各类被过滤样本
|
||||
(金色湖畔事业部 / 虚拟大区 / 姓名含测试 / 未来入职 / 方案处理=/)。
|
||||
- 三十七度-雇主险变更记录-测试.xlsx:SHEET_BIZ 表头第4行(P/Q/V/W 为公式列)、
|
||||
SHEET_IN_PARAM 表头第6行(数据第17行起)、历史变更清单模板 sheet。
|
||||
- 商业保险增/减员导入模板.xlsx(第1~3行固定,第4行起填数据)。
|
||||
|
||||
预期(业务场景):
|
||||
- 花名册过滤后 4 人(张三/李四/王五/赵六),赵六方案处理=/ 在调度阶段被过滤。
|
||||
- 在参名单:王五(20万,要替换→80万) 迁出;钱十离职减少名额被李四(20万)复用;
|
||||
张三(50万) 全新新增;王五(80万) 全新新增;陈十一(50万) 保留。
|
||||
- 变更清单 4 条:删除钱十 / 增加张三(带四级部门) / 增加李四 / 修改王五。
|
||||
- 减员导入 2 条(钱十、王五);增员导入 3 条(张三/李四/王五)。
|
||||
|
||||
用法(仓库根目录执行):
|
||||
.venv\\Scripts\\python.exe tests\\xq0002_plugin_smoke.py
|
||||
"""
|
||||
import importlib
|
||||
import os
|
||||
import shutil
|
||||
import sys
|
||||
from datetime import date
|
||||
|
||||
REPO_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
sys.path.insert(0, os.path.join(REPO_ROOT, "desktop")) # webhost 底座
|
||||
sys.path.insert(0, os.path.join(REPO_ROOT, "plugins", "XQ0001-0100")) # 插件包
|
||||
|
||||
# 通过 importlib 导入包名含空格/中文的插件模块
|
||||
cfg = importlib.import_module("XQ0002 雇主险增减操作.config")
|
||||
roster_filter = importlib.import_module("XQ0002 雇主险增减操作.logic.roster_filter")
|
||||
schedule_mod = importlib.import_module("XQ0002 雇主险增减操作.logic.schedule")
|
||||
wps_recalc = importlib.import_module("XQ0002 雇主险增减操作.logic.wps_recalc")
|
||||
report_output = importlib.import_module("XQ0002 雇主险增减操作.report.output")
|
||||
|
||||
import pandas as pd
|
||||
from openpyxl import Workbook, load_workbook
|
||||
|
||||
# ==================== 测试目录与结果收集 ====================
|
||||
WORK_DIR = os.path.join(REPO_ROOT, "tests", "_xq0002_smoke_data")
|
||||
if os.path.isdir(WORK_DIR):
|
||||
shutil.rmtree(WORK_DIR)
|
||||
CATEGORY_DIR = os.path.join(WORK_DIR, "三十七度")
|
||||
os.makedirs(CATEGORY_DIR, exist_ok=True)
|
||||
|
||||
RESULTS = [] # (名称, 通过?, 说明)
|
||||
|
||||
|
||||
def check(name, ok, detail=""):
|
||||
RESULTS.append((name, bool(ok), detail))
|
||||
print(f"[{'PASS' if ok else 'FAIL'}] {name}" + (f" -> {detail}" if detail and not ok else ""))
|
||||
|
||||
|
||||
def _sheet(wb, title):
|
||||
if title in wb.sheetnames:
|
||||
return wb[title]
|
||||
return wb.create_sheet(title)
|
||||
|
||||
|
||||
# ==================== 1. 构建测试数据 ====================
|
||||
def build_source(path):
|
||||
"""员工花名册:表头行 B 列=「所属单位」,B~O 14 列。"""
|
||||
wb = Workbook()
|
||||
ws = wb.active
|
||||
ws.title = "花名册"
|
||||
headers = ["类型", "所属单位", "一级部门", "二级部门", "三级部门", "工号", "年龄", "性别",
|
||||
"岗位", "职位序列", "参保类型", "上下班交通方式", "入职时间", "姓名", "证件号"]
|
||||
for i, h in enumerate(headers, start=1):
|
||||
ws.cell(row=1, column=i, value=h)
|
||||
rows = [
|
||||
# 所属单位 一级部门 工号 年龄 性别 岗位 职位序列 参保 交通 入职日期 姓名 证件号
|
||||
["三十七度", "三十七度大区", "10001", 30, "男", "厨师", "厨师长", "全职", "班车", date(2020, 1, 1), "张三", "110101199001010001"],
|
||||
["三十七度", "三十七度大区", "10002", 29, "女", "服务员", "服务员", "全职", "班车", date(2021, 1, 1), "李四", "110101199002010002"],
|
||||
["三十七度", "三十七度大区", "10003", 35, "男", "领班", "领班", "全职", "班车", date(2019, 6, 1), "王五", "110101198906010003"],
|
||||
["三十七度", "三十七度大区", "10004", 28, "男", "传菜", "传菜员", "全职", "班车", date(2022, 1, 1), "赵六", "110101199301010004"],
|
||||
["金色湖畔事业部", "金色湖畔大区", "10005", 26, "女", "前台", "前台", "全职", "班车", date(2020, 5, 1), "孙七", "110101199405010005"],
|
||||
["三十七度", "三十七度大区", "10006", 24, "女", "实习", "实习生", "兼职", "班车", date(2020, 1, 1), "测试员", "110101199601010006"],
|
||||
["三十七度", "虚拟大区", "10007", 27, "男", "杂工", "杂工", "全职", "班车", date(2020, 1, 1), "周八", "110101199701010007"],
|
||||
["三十七度", "三十七度大区", "10008", 25, "男", "帮厨", "帮厨", "全职", "班车", date(2099, 1, 1), "吴九", "110101199801010008"],
|
||||
]
|
||||
for r, row in enumerate(rows, start=2):
|
||||
ws.cell(row=r, column=2, value=row[0]) # B 所属单位
|
||||
ws.cell(row=r, column=3, value=row[1]) # C 一级部门
|
||||
ws.cell(row=r, column=6, value=row[2]) # F 工号
|
||||
ws.cell(row=r, column=7, value=row[3]) # G 年龄
|
||||
ws.cell(row=r, column=8, value=row[4]) # H 性别
|
||||
ws.cell(row=r, column=9, value=row[5]) # I 岗位
|
||||
ws.cell(row=r, column=10, value=row[6]) # J 职位序列
|
||||
ws.cell(row=r, column=11, value=row[7]) # K 参保类型
|
||||
ws.cell(row=r, column=12, value=row[8]) # L 上下班交通方式
|
||||
ws.cell(row=r, column=13, value=row[9]) # M 入职时间
|
||||
ws.cell(row=r, column=14, value=row[10]) # N 姓名
|
||||
ws.cell(row=r, column=15, value=row[11]) # O 证件号
|
||||
wb.save(path)
|
||||
|
||||
|
||||
def build_target(path):
|
||||
"""类别目标表:SHEET_BIZ(表头第4行) + SHEET_IN_PARAM(表头第6行,数据第17行起) + 历史变更清单模板。"""
|
||||
wb = Workbook()
|
||||
|
||||
# ---- SHEET_BIZ:表头第4行 ----
|
||||
ws = _sheet(wb, cfg.SHEET_BIZ)
|
||||
biz_headers = ["序号", "所属单位", "一级部门", "二级部门", "三级部门", "工号", "年龄", "性别",
|
||||
"岗位", "职位序列", "参保类型", "上下班交通方式", "入职时间", "姓名", "证件号",
|
||||
"工种类别", "投保方案", "方案组别编号", "是否有工伤保险", "工作单位",
|
||||
"新增费用会馆", "四级部门", "方案处理"]
|
||||
for i, h in enumerate(biz_headers, start=1):
|
||||
ws.cell(row=4, column=i, value=h)
|
||||
# 模拟真实模板:P/Q/W/V 为公式/待填列(数据行5~8 与花名册筛选结果对应)
|
||||
# 公式列需经 WPS/Excel 重算才有缓存值;重算不可用时测试兜底直接填值
|
||||
# 赵六 为「方案处理=/」的占位员工(调度阶段被过滤,不参与参保)
|
||||
formulas = {
|
||||
5: ("=\"一类\"", "=\"人保-50万\"", "=\"增加投保\"", "三十七度-后厨"),
|
||||
6: ("=\"二类\"", "=\"人保-20万\"", "=\"增加投保\"", "三十七度-前厅"),
|
||||
7: ("=\"三类\"", "=\"人保-80万\"", "=\"要替换\"", "三十七度-后勤"),
|
||||
8: ("=\"一类\"", "=\"人保-20万\"", "=\"/\"", None),
|
||||
}
|
||||
for r, (p, q, w, v) in formulas.items():
|
||||
ws.cell(row=r, column=16, value=p) # P 工种类别
|
||||
ws.cell(row=r, column=17, value=q) # Q 投保方案
|
||||
ws.cell(row=r, column=23, value=w) # W 方案处理
|
||||
ws.cell(row=r, column=22, value=v) # V 四级部门
|
||||
|
||||
# ---- SHEET_IN_PARAM:表头第6行,数据第17行起 ----
|
||||
ws2 = _sheet(wb, cfg.SHEET_IN_PARAM)
|
||||
in_headers = ["序号", "工号", "年龄", "性别", "岗位", "职位序列", "参保类型", "上下班交通方式",
|
||||
"入职时间", "姓名", "证件号", "工种类别", "投保方案", "投保日期",
|
||||
"方案组别编号", "每人责任限额", "是否有工伤保险", "方案处理"]
|
||||
for i, h in enumerate(in_headers, start=1):
|
||||
ws2.cell(row=6, column=i, value=h)
|
||||
# 王五(要替换: 20万→80万) / 钱十(离职减少: 20万) / 陈十一(无需: 50万)
|
||||
in_rows = {
|
||||
17: (1, "10003", "王五", "110101198906010003", "三类", "人保-20万", date(2020, 1, 1), "档次替换"),
|
||||
18: (2, "10009", "钱十", "110101199009010009", "一类", "人保-20万", date(2021, 1, 1), "离职减少"),
|
||||
19: (3, "10010", "陈十一", "110101199110100010", "一类", "人保-50万", date(2020, 6, 1), "无需"),
|
||||
}
|
||||
for r, (seq, code, name, emp_id, cat, scheme, join_date, handle) in in_rows.items():
|
||||
ws2.cell(row=r, column=1, value=seq) # A 序号
|
||||
ws2.cell(row=r, column=2, value=code) # B 工号
|
||||
ws2.cell(row=r, column=10, value=name) # J 姓名
|
||||
ws2.cell(row=r, column=11, value=emp_id) # K 证件号
|
||||
ws2.cell(row=r, column=12, value=cat) # L 工种类别
|
||||
ws2.cell(row=r, column=13, value=scheme) # M 投保方案
|
||||
ws2.cell(row=r, column=14, value=join_date) # N 投保日期
|
||||
ws2.cell(row=r, column=18, value=handle) # R 方案处理
|
||||
|
||||
# ---- 历史变更清单模板 sheet(供复制)----
|
||||
ws3 = _sheet(wb, "37度-雇员变更清单9.1")
|
||||
chg_headers = ["序号", "批改标志*", "姓名", "证件类型", "证件号", "年龄", "员工职业类别",
|
||||
"每人责任限额", "方案组别编号", "是否有工伤保险", "工作单位", "", "备注",
|
||||
"批改日期", "新增费用会馆\n(自留后续划成本用)", "姓名", "证件号", "工种类别", "投保方案"]
|
||||
for i, h in enumerate(chg_headers, start=1):
|
||||
ws3.cell(row=1, column=i, value=h)
|
||||
ws3.cell(row=2, column=1, value="公式")
|
||||
ws3.cell(row=2, column=15, value="公式")
|
||||
|
||||
wb.save(path)
|
||||
|
||||
|
||||
def build_templates(base_dir):
|
||||
"""增/减员导入模板:第1~3行固定,第4行起填数据。"""
|
||||
for name in (cfg.ADD_IMPORT_TEMPLATE, cfg.SUB_IMPORT_TEMPLATE):
|
||||
wb = Workbook()
|
||||
ws = wb.active
|
||||
ws.title = "导入模板"
|
||||
ws.cell(row=1, column=1, value=f"{name} 标题")
|
||||
ws.cell(row=2, column=1, value="序号")
|
||||
ws.cell(row=2, column=2, value="工号/证件号")
|
||||
ws.cell(row=2, column=3, value="姓名")
|
||||
ws.cell(row=3, column=1, value="示例说明行(保留)")
|
||||
wb.save(os.path.join(base_dir, name))
|
||||
|
||||
|
||||
# ==================== 2. 冒烟流程 ====================
|
||||
def main():
|
||||
today = date.today()
|
||||
cfg.set_base_dir(WORK_DIR)
|
||||
cfg.set_ref_date(today.strftime("%Y-%m-%d"))
|
||||
category = cfg.get_category("三十七度")
|
||||
|
||||
source_path = cfg.employee_file()
|
||||
target_path = os.path.join(CATEGORY_DIR, "三十七度-雇主险变更记录-测试.xlsx")
|
||||
|
||||
print("== 构建测试数据 ==")
|
||||
build_source(source_path)
|
||||
build_target(target_path)
|
||||
build_templates(WORK_DIR)
|
||||
|
||||
# ---------- 2.1 WPS/Excel COM 重算能力探测 ----------
|
||||
print("\n== Part A:WPS/Excel COM 公式重算 ==")
|
||||
probe = os.path.join(WORK_DIR, "recalc_probe.xlsx")
|
||||
pb = Workbook()
|
||||
pws = pb.active
|
||||
pws["A1"] = 2
|
||||
pws["B1"] = 3
|
||||
pws["C1"] = "=A1+B1"
|
||||
pb.save(probe)
|
||||
|
||||
com_ok = False
|
||||
try:
|
||||
wps_recalc.recalc_target(probe)
|
||||
cached = load_workbook(probe, data_only=True)["Sheet"]["C1"].value
|
||||
com_ok = (cached == 5)
|
||||
check("PartA 公式重算(Ket/Excel COM)", com_ok,
|
||||
f"期望 C1=5,实际 {cached!r}")
|
||||
except Exception as e:
|
||||
check("PartA 公式重算(Ket/Excel COM)", False, str(e))
|
||||
|
||||
# ---------- 2.2 筛选复制 ----------
|
||||
print("\n== 步骤1:花名册筛选复制 ==")
|
||||
n_copied = roster_filter.filter_and_copy_roster(category, employee_path=source_path,
|
||||
target_file=target_path)
|
||||
check("筛选复制行数=4(张三/李四/王五/赵六)", n_copied == 4, f"实际 {n_copied} 行")
|
||||
# F 列工号强制文本
|
||||
wb0 = load_workbook(target_path)
|
||||
f_val = wb0[cfg.SHEET_BIZ].cell(row=5, column=6).value
|
||||
check("F列工号文本格式", isinstance(f_val, str) and f_val == "10001", repr(f_val))
|
||||
# O 列证件号强制文本(18位身份证号防浮点截断)
|
||||
o_val = wb0[cfg.SHEET_BIZ].cell(row=5, column=15).value
|
||||
check("O列证件号文本格式", isinstance(o_val, str) and o_val == "110101199001010001", repr(o_val))
|
||||
|
||||
# ---------- 2.3 公式重算(可用则走真实链路,否则兜底填值) ----------
|
||||
print("\n== 步骤2:公式重算 ==")
|
||||
if com_ok:
|
||||
try:
|
||||
wps_recalc.recalc_target(target_path)
|
||||
check("目标表公式重算", True)
|
||||
except Exception as e:
|
||||
com_ok = False
|
||||
check("目标表公式重算", False, str(e))
|
||||
if not com_ok:
|
||||
# 兜底:把 P/Q/W 直接填为值(模拟已重算的公式缓存),保证调度链路可继续
|
||||
wb1 = load_workbook(target_path)
|
||||
ws1 = wb1[cfg.SHEET_BIZ]
|
||||
for r, (p, q, w, v) in {
|
||||
5: ("一类", "人保-50万", "增加投保", "三十七度-后厨"),
|
||||
6: ("二类", "人保-20万", "增加投保", "三十七度-前厅"),
|
||||
7: ("三类", "人保-80万", "要替换", "三十七度-后勤"),
|
||||
8: ("一类", "人保-20万", "/", None),
|
||||
}.items():
|
||||
ws1.cell(row=r, column=16, value=p)
|
||||
ws1.cell(row=r, column=17, value=q)
|
||||
ws1.cell(row=r, column=23, value=w)
|
||||
ws1.cell(row=r, column=22, value=v)
|
||||
wb1.save(target_path)
|
||||
print("(提示:本机 COM 重算不可用,已兜底直接填公式列值)")
|
||||
|
||||
# ---------- 2.4 三阶段名额调度 ----------
|
||||
print("\n== 步骤3:三阶段名额调度 ==")
|
||||
final_records = schedule_mod.schedule_category(category,
|
||||
enable_validation=True,
|
||||
gen_import_files=True)
|
||||
check("调度生成参保记录=3", len(final_records) == 3, f"实际 {len(final_records)}")
|
||||
|
||||
# ---------- 2.5 断言在参名单更新 ----------
|
||||
wb2 = load_workbook(target_path)
|
||||
ws_in = wb2[cfg.SHEET_IN_PARAM]
|
||||
expect_in = {
|
||||
17: ("10001", "110101199001010001", "人保-50万"), # 张三 全新新增
|
||||
18: ("10002", "110101199002010002", "人保-20万"), # 李四 复用钱十名额
|
||||
19: ("10010", "110101199110100010", "人保-50万"), # 陈十一 保留
|
||||
20: ("10003", "110101198906010003", "人保-80万"), # 王五 追加新行
|
||||
}
|
||||
for row_idx, (code, emp_id, scheme) in expect_in.items():
|
||||
c_b = ws_in.cell(row=row_idx, column=2).value
|
||||
c_k = ws_in.cell(row=row_idx, column=11).value
|
||||
c_m = ws_in.cell(row=row_idx, column=13).value
|
||||
check(f"在参名单第{row_idx}行: {code}/{emp_id}/{scheme}",
|
||||
str(c_b) == code and str(c_k) == emp_id and c_m == scheme,
|
||||
f"实际 B={c_b!r} K={c_k!r} M={c_m!r}")
|
||||
|
||||
# ---------- 2.6 断言变更清单 ----------
|
||||
chg_name = cfg.category_change_sheet_name(category)
|
||||
ws_chg = wb2[chg_name]
|
||||
expect_chg = {
|
||||
3: ("删除", "钱十", "110101199009010009", "人保-20万"),
|
||||
4: ("增加", "张三", "110101199001010001", "人保-50万"),
|
||||
5: ("增加", "李四", "110101199002010002", "人保-20万"),
|
||||
6: ("修改", "王五", "110101198906010003", "人保-80万"),
|
||||
}
|
||||
for row_idx, (op, name, emp_id, scheme) in expect_chg.items():
|
||||
got = (ws_chg.cell(row=row_idx, column=2).value,
|
||||
ws_chg.cell(row=row_idx, column=16).value,
|
||||
ws_chg.cell(row=row_idx, column=17).value,
|
||||
ws_chg.cell(row=row_idx, column=19).value)
|
||||
check(f"变更清单第{row_idx}行: {op} {name}",
|
||||
got == (op, name, emp_id, scheme), f"实际 {got}")
|
||||
check("变更清单 张三 带四级部门", ws_chg.cell(row=4, column=15).value == "三十七度-后厨",
|
||||
repr(ws_chg.cell(row=4, column=15).value))
|
||||
check("变更清单 王五 备注替换说明",
|
||||
ws_chg.cell(row=6, column=13).value == "由人保-20万替换为人保-80万",
|
||||
repr(ws_chg.cell(row=6, column=13).value))
|
||||
|
||||
# ---------- 2.7 断言备份 ----------
|
||||
backup = cfg.category_output_backup(category)
|
||||
check("备份新在参名单存在", os.path.isfile(backup))
|
||||
if os.path.isfile(backup):
|
||||
df_backup = pd.read_excel(backup)
|
||||
check("备份含 3 条参保记录", len(df_backup) == 3, f"实际 {len(df_backup)}")
|
||||
|
||||
# ---------- 2.8 断言增/减员导入 ----------
|
||||
add_file = cfg.category_import_add_file(category)
|
||||
sub_file = cfg.category_import_sub_file(category)
|
||||
df_add = pd.read_excel(add_file, header=2)
|
||||
df_sub = pd.read_excel(sub_file, header=2)
|
||||
check("增员导入=3 条", len(df_add) == 3, f"实际 {len(df_add)}")
|
||||
check("减员导入=2 条", len(df_sub) == 2, f"实际 {len(df_sub)}")
|
||||
add_codes = [str(v) for v in df_add.iloc[:, 1].tolist()]
|
||||
sub_codes = [str(v) for v in df_sub.iloc[:, 1].tolist()]
|
||||
check("增员含 张三/李四/王五", sorted(add_codes) == ["10001", "10002", "10003"], repr(add_codes))
|
||||
check("减员含 钱十/王五", sorted(sub_codes) == ["10003", "10009"], repr(sub_codes))
|
||||
|
||||
# ---------- 2.9 断言变更清单独立工作簿 ----------
|
||||
ok_wb = report_output.export_change_sheet_workbook(category)
|
||||
wb_out = cfg.category_change_sheet_workbook(category)
|
||||
check("导出变更清单独立工作簿", ok_wb and os.path.isfile(wb_out))
|
||||
if os.path.isfile(wb_out):
|
||||
wb3 = load_workbook(wb_out, data_only=True)
|
||||
ws3 = wb3[chg_name]
|
||||
check("独立工作簿 保留 4 条变更", ws3.cell(row=3, column=2).value == "删除"
|
||||
and ws3.cell(row=6, column=2).value == "修改",
|
||||
f"第3行={ws3.cell(row=3, column=2).value!r} 第6行={ws3.cell(row=6, column=2).value!r}")
|
||||
|
||||
# ---------- 汇总 ----------
|
||||
print("\n" + "=" * 60)
|
||||
failed = [r for r in RESULTS if not r[1]]
|
||||
print(f"共 {len(RESULTS)} 项检查,通过 {len(RESULTS) - len(failed)} 项,失败 {len(failed)} 项")
|
||||
for name, ok, detail in RESULTS:
|
||||
if not ok:
|
||||
print(f" FAIL {name}: {detail}")
|
||||
print(f"测试数据目录(可人工核查):{WORK_DIR}")
|
||||
sys.exit(1 if failed else 0)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0002 雇主险插件 全链路冒烟自测(本机 .venv 执行)。
|
||||
|
||||
覆盖链路:花名册筛选复制 → WPS/Excel COM 后台重算(可选)→ 三阶段名额调度
|
||||
(更新在参名单 / 精细更新变更清单 / 备份新在参名单)→ 增/减员导入文件 → 变更清单独立工作簿。
|
||||
|
||||
测试数据(临时目录):
|
||||
- 员工花名册.xlsx:表头行 B 列=「所属单位」,B~O 14 列;8 名员工,含各类被过滤样本
|
||||
(金色湖畔事业部 / 虚拟大区 / 姓名含测试 / 未来入职 / 方案处理=/)。
|
||||
- 三十七度-雇主险变更记录-测试.xlsx:SHEET_BIZ 表头第4行(P/Q/V/W 为公式列)、
|
||||
SHEET_IN_PARAM 表头第6行(数据第17行起)、历史变更清单模板 sheet。
|
||||
- 商业保险增/减员导入模板.xlsx(第1~3行固定,第4行起填数据)。
|
||||
|
||||
预期(业务场景):
|
||||
- 花名册过滤后 4 人(张三/李四/王五/赵六),赵六方案处理=/ 在调度阶段被过滤。
|
||||
- 在参名单:王五(20万,要替换→80万) 迁出;钱十离职减少名额被李四(20万)复用;
|
||||
张三(50万) 全新新增;王五(80万) 全新新增;陈十一(50万) 保留。
|
||||
- 变更清单 4 条:删除钱十 / 增加张三(带四级部门) / 增加李四 / 修改王五。
|
||||
- 减员导入 2 条(钱十、王五);增员导入 3 条(张三/李四/王五)。
|
||||
|
||||
用法(仓库根目录执行):
|
||||
.venv\\Scripts\\python.exe tests\\xq0002_plugin_smoke.py
|
||||
"""
|
||||
import importlib
|
||||
import os
|
||||
import shutil
|
||||
import sys
|
||||
from datetime import date
|
||||
|
||||
REPO_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
sys.path.insert(0, os.path.join(REPO_ROOT, "desktop")) # webhost 底座
|
||||
sys.path.insert(0, os.path.join(REPO_ROOT, "plugins", "XQ0001-0100")) # 插件包
|
||||
|
||||
# 通过 importlib 导入包名含空格/中文的插件模块
|
||||
cfg = importlib.import_module("XQ0002 雇主险增减操作.config")
|
||||
roster_filter = importlib.import_module("XQ0002 雇主险增减操作.logic.roster_filter")
|
||||
schedule_mod = importlib.import_module("XQ0002 雇主险增减操作.logic.schedule")
|
||||
wps_recalc = importlib.import_module("XQ0002 雇主险增减操作.logic.wps_recalc")
|
||||
report_output = importlib.import_module("XQ0002 雇主险增减操作.report.output")
|
||||
|
||||
import pandas as pd
|
||||
from openpyxl import Workbook, load_workbook
|
||||
|
||||
# ==================== 测试目录与结果收集 ====================
|
||||
WORK_DIR = os.path.join(REPO_ROOT, "tests", "_xq0002_smoke_data")
|
||||
if os.path.isdir(WORK_DIR):
|
||||
shutil.rmtree(WORK_DIR)
|
||||
CATEGORY_DIR = os.path.join(WORK_DIR, "三十七度")
|
||||
os.makedirs(CATEGORY_DIR, exist_ok=True)
|
||||
|
||||
RESULTS = [] # (名称, 通过?, 说明)
|
||||
|
||||
|
||||
def check(name, ok, detail=""):
|
||||
RESULTS.append((name, bool(ok), detail))
|
||||
print(f"[{'PASS' if ok else 'FAIL'}] {name}" + (f" -> {detail}" if detail and not ok else ""))
|
||||
|
||||
|
||||
def _sheet(wb, title):
|
||||
if title in wb.sheetnames:
|
||||
return wb[title]
|
||||
return wb.create_sheet(title)
|
||||
|
||||
|
||||
# ==================== 1. 构建测试数据 ====================
|
||||
def build_source(path):
|
||||
"""员工花名册:表头行 B 列=「所属单位」,B~O 14 列。"""
|
||||
wb = Workbook()
|
||||
ws = wb.active
|
||||
ws.title = "花名册"
|
||||
headers = ["类型", "所属单位", "一级部门", "二级部门", "三级部门", "工号", "年龄", "性别",
|
||||
"岗位", "职位序列", "参保类型", "上下班交通方式", "入职时间", "姓名", "证件号"]
|
||||
for i, h in enumerate(headers, start=1):
|
||||
ws.cell(row=1, column=i, value=h)
|
||||
rows = [
|
||||
# 所属单位 一级部门 工号 年龄 性别 岗位 职位序列 参保 交通 入职日期 姓名 证件号
|
||||
["三十七度", "三十七度大区", "10001", 30, "男", "厨师", "厨师长", "全职", "班车", date(2020, 1, 1), "张三", "110101199001010001"],
|
||||
["三十七度", "三十七度大区", "10002", 29, "女", "服务员", "服务员", "全职", "班车", date(2021, 1, 1), "李四", "110101199002010002"],
|
||||
["三十七度", "三十七度大区", "10003", 35, "男", "领班", "领班", "全职", "班车", date(2019, 6, 1), "王五", "110101198906010003"],
|
||||
["三十七度", "三十七度大区", "10004", 28, "男", "传菜", "传菜员", "全职", "班车", date(2022, 1, 1), "赵六", "110101199301010004"],
|
||||
["金色湖畔事业部", "金色湖畔大区", "10005", 26, "女", "前台", "前台", "全职", "班车", date(2020, 5, 1), "孙七", "110101199405010005"],
|
||||
["三十七度", "三十七度大区", "10006", 24, "女", "实习", "实习生", "兼职", "班车", date(2020, 1, 1), "测试员", "110101199601010006"],
|
||||
["三十七度", "虚拟大区", "10007", 27, "男", "杂工", "杂工", "全职", "班车", date(2020, 1, 1), "周八", "110101199701010007"],
|
||||
["三十七度", "三十七度大区", "10008", 25, "男", "帮厨", "帮厨", "全职", "班车", date(2099, 1, 1), "吴九", "110101199801010008"],
|
||||
]
|
||||
for r, row in enumerate(rows, start=2):
|
||||
ws.cell(row=r, column=2, value=row[0]) # B 所属单位
|
||||
ws.cell(row=r, column=3, value=row[1]) # C 一级部门
|
||||
ws.cell(row=r, column=6, value=row[2]) # F 工号
|
||||
ws.cell(row=r, column=7, value=row[3]) # G 年龄
|
||||
ws.cell(row=r, column=8, value=row[4]) # H 性别
|
||||
ws.cell(row=r, column=9, value=row[5]) # I 岗位
|
||||
ws.cell(row=r, column=10, value=row[6]) # J 职位序列
|
||||
ws.cell(row=r, column=11, value=row[7]) # K 参保类型
|
||||
ws.cell(row=r, column=12, value=row[8]) # L 上下班交通方式
|
||||
ws.cell(row=r, column=13, value=row[9]) # M 入职时间
|
||||
ws.cell(row=r, column=14, value=row[10]) # N 姓名
|
||||
ws.cell(row=r, column=15, value=row[11]) # O 证件号
|
||||
wb.save(path)
|
||||
|
||||
|
||||
def build_target(path):
|
||||
"""类别目标表:SHEET_BIZ(表头第4行) + SHEET_IN_PARAM(表头第6行,数据第17行起) + 历史变更清单模板。"""
|
||||
wb = Workbook()
|
||||
|
||||
# ---- SHEET_BIZ:表头第4行 ----
|
||||
ws = _sheet(wb, cfg.SHEET_BIZ)
|
||||
biz_headers = ["序号", "所属单位", "一级部门", "二级部门", "三级部门", "工号", "年龄", "性别",
|
||||
"岗位", "职位序列", "参保类型", "上下班交通方式", "入职时间", "姓名", "证件号",
|
||||
"工种类别", "投保方案", "方案组别编号", "是否有工伤保险", "工作单位",
|
||||
"新增费用会馆", "四级部门", "方案处理"]
|
||||
for i, h in enumerate(biz_headers, start=1):
|
||||
ws.cell(row=4, column=i, value=h)
|
||||
# 模拟真实模板:P/Q/W/V 为公式/待填列(数据行5~8 与花名册筛选结果对应)
|
||||
# 公式列需经 WPS/Excel 重算才有缓存值;重算不可用时测试兜底直接填值
|
||||
# 赵六 为「方案处理=/」的占位员工(调度阶段被过滤,不参与参保)
|
||||
formulas = {
|
||||
5: ("=\"一类\"", "=\"人保-50万\"", "=\"增加投保\"", "三十七度-后厨"),
|
||||
6: ("=\"二类\"", "=\"人保-20万\"", "=\"增加投保\"", "三十七度-前厅"),
|
||||
7: ("=\"三类\"", "=\"人保-80万\"", "=\"要替换\"", "三十七度-后勤"),
|
||||
8: ("=\"一类\"", "=\"人保-20万\"", "=\"/\"", None),
|
||||
}
|
||||
for r, (p, q, w, v) in formulas.items():
|
||||
ws.cell(row=r, column=16, value=p) # P 工种类别
|
||||
ws.cell(row=r, column=17, value=q) # Q 投保方案
|
||||
ws.cell(row=r, column=23, value=w) # W 方案处理
|
||||
ws.cell(row=r, column=22, value=v) # V 四级部门
|
||||
|
||||
# ---- SHEET_IN_PARAM:表头第6行,数据第17行起 ----
|
||||
ws2 = _sheet(wb, cfg.SHEET_IN_PARAM)
|
||||
in_headers = ["序号", "工号", "年龄", "性别", "岗位", "职位序列", "参保类型", "上下班交通方式",
|
||||
"入职时间", "姓名", "证件号", "工种类别", "投保方案", "投保日期",
|
||||
"方案组别编号", "每人责任限额", "是否有工伤保险", "方案处理"]
|
||||
for i, h in enumerate(in_headers, start=1):
|
||||
ws2.cell(row=6, column=i, value=h)
|
||||
# 王五(要替换: 20万→80万) / 钱十(离职减少: 20万) / 陈十一(无需: 50万)
|
||||
in_rows = {
|
||||
17: (1, "10003", "王五", "110101198906010003", "三类", "人保-20万", date(2020, 1, 1), "档次替换"),
|
||||
18: (2, "10009", "钱十", "110101199009010009", "一类", "人保-20万", date(2021, 1, 1), "离职减少"),
|
||||
19: (3, "10010", "陈十一", "110101199110100010", "一类", "人保-50万", date(2020, 6, 1), "无需"),
|
||||
}
|
||||
for r, (seq, code, name, emp_id, cat, scheme, join_date, handle) in in_rows.items():
|
||||
ws2.cell(row=r, column=1, value=seq) # A 序号
|
||||
ws2.cell(row=r, column=2, value=code) # B 工号
|
||||
ws2.cell(row=r, column=10, value=name) # J 姓名
|
||||
ws2.cell(row=r, column=11, value=emp_id) # K 证件号
|
||||
ws2.cell(row=r, column=12, value=cat) # L 工种类别
|
||||
ws2.cell(row=r, column=13, value=scheme) # M 投保方案
|
||||
ws2.cell(row=r, column=14, value=join_date) # N 投保日期
|
||||
ws2.cell(row=r, column=18, value=handle) # R 方案处理
|
||||
|
||||
# ---- 历史变更清单模板 sheet(供复制)----
|
||||
ws3 = _sheet(wb, "37度-雇员变更清单9.1")
|
||||
chg_headers = ["序号", "批改标志*", "姓名", "证件类型", "证件号", "年龄", "员工职业类别",
|
||||
"每人责任限额", "方案组别编号", "是否有工伤保险", "工作单位", "", "备注",
|
||||
"批改日期", "新增费用会馆\n(自留后续划成本用)", "姓名", "证件号", "工种类别", "投保方案"]
|
||||
for i, h in enumerate(chg_headers, start=1):
|
||||
ws3.cell(row=1, column=i, value=h)
|
||||
ws3.cell(row=2, column=1, value="公式")
|
||||
ws3.cell(row=2, column=15, value="公式")
|
||||
|
||||
wb.save(path)
|
||||
|
||||
|
||||
def build_templates(base_dir):
|
||||
"""增/减员导入模板:第1~3行固定,第4行起填数据。"""
|
||||
for name in (cfg.ADD_IMPORT_TEMPLATE, cfg.SUB_IMPORT_TEMPLATE):
|
||||
wb = Workbook()
|
||||
ws = wb.active
|
||||
ws.title = "导入模板"
|
||||
ws.cell(row=1, column=1, value=f"{name} 标题")
|
||||
ws.cell(row=2, column=1, value="序号")
|
||||
ws.cell(row=2, column=2, value="工号/证件号")
|
||||
ws.cell(row=2, column=3, value="姓名")
|
||||
ws.cell(row=3, column=1, value="示例说明行(保留)")
|
||||
wb.save(os.path.join(base_dir, name))
|
||||
|
||||
|
||||
# ==================== 2. 冒烟流程 ====================
|
||||
def main():
|
||||
today = date.today()
|
||||
cfg.set_base_dir(WORK_DIR)
|
||||
cfg.set_ref_date(today.strftime("%Y-%m-%d"))
|
||||
category = cfg.get_category("三十七度")
|
||||
|
||||
source_path = cfg.employee_file()
|
||||
target_path = os.path.join(CATEGORY_DIR, "三十七度-雇主险变更记录-测试.xlsx")
|
||||
|
||||
print("== 构建测试数据 ==")
|
||||
build_source(source_path)
|
||||
build_target(target_path)
|
||||
build_templates(WORK_DIR)
|
||||
|
||||
# ---------- 2.1 WPS/Excel COM 重算能力探测 ----------
|
||||
print("\n== Part A:WPS/Excel COM 公式重算 ==")
|
||||
probe = os.path.join(WORK_DIR, "recalc_probe.xlsx")
|
||||
pb = Workbook()
|
||||
pws = pb.active
|
||||
pws["A1"] = 2
|
||||
pws["B1"] = 3
|
||||
pws["C1"] = "=A1+B1"
|
||||
pb.save(probe)
|
||||
|
||||
com_ok = False
|
||||
try:
|
||||
wps_recalc.recalc_target(probe)
|
||||
cached = load_workbook(probe, data_only=True)["Sheet"]["C1"].value
|
||||
com_ok = (cached == 5)
|
||||
check("PartA 公式重算(Ket/Excel COM)", com_ok,
|
||||
f"期望 C1=5,实际 {cached!r}")
|
||||
except Exception as e:
|
||||
check("PartA 公式重算(Ket/Excel COM)", False, str(e))
|
||||
|
||||
# ---------- 2.2 筛选复制 ----------
|
||||
print("\n== 步骤1:花名册筛选复制 ==")
|
||||
n_copied = roster_filter.filter_and_copy_roster(category, employee_path=source_path,
|
||||
target_file=target_path)
|
||||
check("筛选复制行数=4(张三/李四/王五/赵六)", n_copied == 4, f"实际 {n_copied} 行")
|
||||
# F 列工号强制文本
|
||||
wb0 = load_workbook(target_path)
|
||||
f_val = wb0[cfg.SHEET_BIZ].cell(row=5, column=6).value
|
||||
check("F列工号文本格式", isinstance(f_val, str) and f_val == "10001", repr(f_val))
|
||||
# O 列证件号强制文本(18位身份证号防浮点截断)
|
||||
o_val = wb0[cfg.SHEET_BIZ].cell(row=5, column=15).value
|
||||
check("O列证件号文本格式", isinstance(o_val, str) and o_val == "110101199001010001", repr(o_val))
|
||||
|
||||
# ---------- 2.3 公式重算(可用则走真实链路,否则兜底填值) ----------
|
||||
print("\n== 步骤2:公式重算 ==")
|
||||
if com_ok:
|
||||
try:
|
||||
wps_recalc.recalc_target(target_path)
|
||||
check("目标表公式重算", True)
|
||||
except Exception as e:
|
||||
com_ok = False
|
||||
check("目标表公式重算", False, str(e))
|
||||
if not com_ok:
|
||||
# 兜底:把 P/Q/W 直接填为值(模拟已重算的公式缓存),保证调度链路可继续
|
||||
wb1 = load_workbook(target_path)
|
||||
ws1 = wb1[cfg.SHEET_BIZ]
|
||||
for r, (p, q, w, v) in {
|
||||
5: ("一类", "人保-50万", "增加投保", "三十七度-后厨"),
|
||||
6: ("二类", "人保-20万", "增加投保", "三十七度-前厅"),
|
||||
7: ("三类", "人保-80万", "要替换", "三十七度-后勤"),
|
||||
8: ("一类", "人保-20万", "/", None),
|
||||
}.items():
|
||||
ws1.cell(row=r, column=16, value=p)
|
||||
ws1.cell(row=r, column=17, value=q)
|
||||
ws1.cell(row=r, column=23, value=w)
|
||||
ws1.cell(row=r, column=22, value=v)
|
||||
wb1.save(target_path)
|
||||
print("(提示:本机 COM 重算不可用,已兜底直接填公式列值)")
|
||||
|
||||
# ---------- 2.4 三阶段名额调度 ----------
|
||||
print("\n== 步骤3:三阶段名额调度 ==")
|
||||
final_records = schedule_mod.schedule_category(category,
|
||||
enable_validation=True,
|
||||
gen_import_files=True)
|
||||
check("调度生成参保记录=3", len(final_records) == 3, f"实际 {len(final_records)}")
|
||||
|
||||
# ---------- 2.5 断言在参名单更新 ----------
|
||||
wb2 = load_workbook(target_path)
|
||||
ws_in = wb2[cfg.SHEET_IN_PARAM]
|
||||
expect_in = {
|
||||
17: ("10001", "110101199001010001", "人保-50万"), # 张三 全新新增
|
||||
18: ("10002", "110101199002010002", "人保-20万"), # 李四 复用钱十名额
|
||||
19: ("10010", "110101199110100010", "人保-50万"), # 陈十一 保留
|
||||
20: ("10003", "110101198906010003", "人保-80万"), # 王五 追加新行
|
||||
}
|
||||
for row_idx, (code, emp_id, scheme) in expect_in.items():
|
||||
c_b = ws_in.cell(row=row_idx, column=2).value
|
||||
c_k = ws_in.cell(row=row_idx, column=11).value
|
||||
c_m = ws_in.cell(row=row_idx, column=13).value
|
||||
check(f"在参名单第{row_idx}行: {code}/{emp_id}/{scheme}",
|
||||
str(c_b) == code and str(c_k) == emp_id and c_m == scheme,
|
||||
f"实际 B={c_b!r} K={c_k!r} M={c_m!r}")
|
||||
|
||||
# ---------- 2.6 断言变更清单 ----------
|
||||
chg_name = cfg.category_change_sheet_name(category)
|
||||
ws_chg = wb2[chg_name]
|
||||
expect_chg = {
|
||||
3: ("删除", "钱十", "110101199009010009", "人保-20万"),
|
||||
4: ("增加", "张三", "110101199001010001", "人保-50万"),
|
||||
5: ("增加", "李四", "110101199002010002", "人保-20万"),
|
||||
6: ("修改", "王五", "110101198906010003", "人保-80万"),
|
||||
}
|
||||
for row_idx, (op, name, emp_id, scheme) in expect_chg.items():
|
||||
got = (ws_chg.cell(row=row_idx, column=2).value,
|
||||
ws_chg.cell(row=row_idx, column=16).value,
|
||||
ws_chg.cell(row=row_idx, column=17).value,
|
||||
ws_chg.cell(row=row_idx, column=19).value)
|
||||
check(f"变更清单第{row_idx}行: {op} {name}",
|
||||
got == (op, name, emp_id, scheme), f"实际 {got}")
|
||||
check("变更清单 张三 带四级部门", ws_chg.cell(row=4, column=15).value == "三十七度-后厨",
|
||||
repr(ws_chg.cell(row=4, column=15).value))
|
||||
check("变更清单 王五 备注替换说明",
|
||||
ws_chg.cell(row=6, column=13).value == "由人保-20万替换为人保-80万",
|
||||
repr(ws_chg.cell(row=6, column=13).value))
|
||||
|
||||
# ---------- 2.7 断言备份 ----------
|
||||
backup = cfg.category_output_backup(category)
|
||||
check("备份新在参名单存在", os.path.isfile(backup))
|
||||
if os.path.isfile(backup):
|
||||
df_backup = pd.read_excel(backup)
|
||||
check("备份含 3 条参保记录", len(df_backup) == 3, f"实际 {len(df_backup)}")
|
||||
|
||||
# ---------- 2.8 断言增/减员导入 ----------
|
||||
add_file = cfg.category_import_add_file(category)
|
||||
sub_file = cfg.category_import_sub_file(category)
|
||||
df_add = pd.read_excel(add_file, header=2)
|
||||
df_sub = pd.read_excel(sub_file, header=2)
|
||||
check("增员导入=3 条", len(df_add) == 3, f"实际 {len(df_add)}")
|
||||
check("减员导入=2 条", len(df_sub) == 2, f"实际 {len(df_sub)}")
|
||||
add_codes = [str(v) for v in df_add.iloc[:, 1].tolist()]
|
||||
sub_codes = [str(v) for v in df_sub.iloc[:, 1].tolist()]
|
||||
check("增员含 张三/李四/王五", sorted(add_codes) == ["10001", "10002", "10003"], repr(add_codes))
|
||||
check("减员含 钱十/王五", sorted(sub_codes) == ["10003", "10009"], repr(sub_codes))
|
||||
|
||||
# ---------- 2.9 断言变更清单独立工作簿 ----------
|
||||
ok_wb = report_output.export_change_sheet_workbook(category)
|
||||
wb_out = cfg.category_change_sheet_workbook(category)
|
||||
check("导出变更清单独立工作簿", ok_wb and os.path.isfile(wb_out))
|
||||
if os.path.isfile(wb_out):
|
||||
wb3 = load_workbook(wb_out, data_only=True)
|
||||
ws3 = wb3[chg_name]
|
||||
check("独立工作簿 保留 4 条变更", ws3.cell(row=3, column=2).value == "删除"
|
||||
and ws3.cell(row=6, column=2).value == "修改",
|
||||
f"第3行={ws3.cell(row=3, column=2).value!r} 第6行={ws3.cell(row=6, column=2).value!r}")
|
||||
|
||||
# ---------- 汇总 ----------
|
||||
print("\n" + "=" * 60)
|
||||
failed = [r for r in RESULTS if not r[1]]
|
||||
print(f"共 {len(RESULTS)} 项检查,通过 {len(RESULTS) - len(failed)} 项,失败 {len(failed)} 项")
|
||||
for name, ok, detail in RESULTS:
|
||||
if not ok:
|
||||
print(f" FAIL {name}: {detail}")
|
||||
print(f"测试数据目录(可人工核查):{WORK_DIR}")
|
||||
sys.exit(1 if failed else 0)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
||||
Reference in New Issue
Block a user