refactor(tests): 归档旧版HRBP测试文件,新增新版测试辅助脚本和雇主险WPS可行性验证
本次提交主要包含以下内容: 1. 归档tests/hrbp目录下的旧版测试文件至tests/_app_蓝图版归档目录 2. 新增tests/_app_蓝图版归档/hrbp目录下的新版测试辅助脚本和测试用例 3. 新增雇主险场景下的WPS COM可行性验证脚本 4. 更新README.md中关于tests目录的说明,明确各子目录用途 5. 更新XQ0035工作流相关文件中的操作人UnionID,更换为人资专用号 6. 修复试用期变更脚本中日期转换的问题,确保AI表格时间戳正确转换为日期格式 7. 归档XQ0035工作流下的旧版测试脚本至测试归档目录
This commit is contained in:
@@ -0,0 +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")
|
||||
@@ -0,0 +1,9 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: tests.hrbp
|
||||
@FileName: __init__.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-06 10:30
|
||||
@Description: HRBP OA 系统接口连通性测试
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
@@ -0,0 +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"))
|
||||
@@ -0,0 +1,49 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: tests.hrbp.test_01_login_session
|
||||
@FileName: test_01_login_session.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-06 10:35
|
||||
@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 get_logged_in_session, logger # noqa: E402
|
||||
|
||||
|
||||
def test_session_reuse():
|
||||
"""测试:复用已保存 cookies 构建会话(无 cookies 时触发登录)"""
|
||||
browser, session = get_logged_in_session(subject="加班")
|
||||
assert session is not None, "会话获取失败"
|
||||
logger.info("[通过] 会话获取成功")
|
||||
return browser, session
|
||||
|
||||
|
||||
def test_todo_list(session, subject: str = "加班"):
|
||||
"""测试:待办列表接口连通性 + 分页解析"""
|
||||
from app.service.hrbp.oa.common.oa_api import get_documents, fetch_todo_page
|
||||
|
||||
# 单页探活
|
||||
page_data = fetch_todo_page(session, subject=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=subject)
|
||||
logger.info("[通过] 待办解析完成,共 %d 条", len(docs))
|
||||
for d in docs[:3]:
|
||||
logger.info(" - %s | %s | %s", d.get("creator"), d.get("time"), d.get("title"))
|
||||
return docs
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
logger.info("========== 测试①:登录 + 会话 + 待办列表 ==========")
|
||||
browser, session = test_session_reuse()
|
||||
test_todo_list(session)
|
||||
logger.info("========== 测试①结束 ==========")
|
||||
@@ -0,0 +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("========== 测试②结束 ==========")
|
||||
@@ -0,0 +1,47 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: tests.hrbp.test_03_attendance
|
||||
@FileName: test_03_attendance.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-06 10:45
|
||||
@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 get_logged_in_session, logger # noqa: E402
|
||||
|
||||
# 测试用员工(黄俊林),可按需改成环境变量或从待办单据动态获取
|
||||
TEST_STAFF_ID = "572e6cce-7a9f-11ec-b449-000c296f9469"
|
||||
TEST_DATE = "2026-08-02"
|
||||
|
||||
|
||||
def test_attendance_daily(session, staff_id: str, start_date: str, end_date: str):
|
||||
"""测试:考勤逐日接口(班次名 + 上下班打卡)"""
|
||||
from app.service.hrbp.oa.common.oa_api import get_attendance_daily
|
||||
|
||||
records = get_attendance_daily(session, staff_id, start_date, end_date)
|
||||
assert isinstance(records, list), "考勤逐日格式异常"
|
||||
logger.info("[通过] 考勤逐日接口正常,返回 %d 天数据", len(records))
|
||||
for r in records[:10]:
|
||||
logger.info(" %s | %s | %s~%s | 上班:%s 下班:%s",
|
||||
r.get("work_day"),
|
||||
r.get("bc_name"),
|
||||
r.get("bc_begin_time") or "-",
|
||||
r.get("bc_end_time") or "-",
|
||||
r.get("sb_dk_time") or r.get("sb_dk_time2") or "无",
|
||||
r.get("xb_dk_time") or r.get("xb_dk_time2") or "无")
|
||||
return records
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
logger.info("========== 测试③:考勤逐日接口 ==========")
|
||||
browser, session = get_logged_in_session(subject="加班")
|
||||
|
||||
test_attendance_daily(session, TEST_STAFF_ID, TEST_DATE, TEST_DATE)
|
||||
|
||||
logger.info("========== 测试③结束 ==========")
|
||||
@@ -0,0 +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("========== 测试④结束 ==========")
|
||||
@@ -0,0 +1,512 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: tests.hrbp.test_05_leave_validator
|
||||
@FileName: test_05_leave_validator.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-06
|
||||
@Description: 连通性测试⑤——请假校验模块(纯逻辑,离线测试,无需登录)
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
import os
|
||||
import sys
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..'))
|
||||
|
||||
from tests.hrbp._helpers import logger # noqa: E402
|
||||
|
||||
|
||||
# ---------- 测试数据 ----------
|
||||
|
||||
# 测试用排班数据(动态列 "YYYY-MM-DD_bc_name" 表示当日班次名,空串/"休息"为休息日,
|
||||
# 数据源 rf_p_kq_count_SelectBanci,一条记录 = 一个员工在查询范围内的全部排班)
|
||||
SAMPLE_SHIFT = [
|
||||
{
|
||||
"2026-08-10_bc_name": "经营正班A",
|
||||
"2026-08-10_bc_time": "09:00 ~ 18:00",
|
||||
"2026-08-10_paiban_type": "-2",
|
||||
"2026-08-11_bc_name": "经营正班A",
|
||||
"2026-08-12_bc_name": "休息",
|
||||
"2026-08-13_bc_name": "经营正班A",
|
||||
"2026-08-14_bc_name": "经营正班A",
|
||||
"2026-08-15_bc_name": "休息",
|
||||
"2026-08-16_bc_name": "休息",
|
||||
"2026-08-17_bc_name": "经营正班A",
|
||||
},
|
||||
]
|
||||
|
||||
# 跨月排班数据(8月底休息 + 9月上班)
|
||||
SAMPLE_SHIFT_CROSS_MONTH = [
|
||||
{
|
||||
"2026-08-30_bc_name": "休息",
|
||||
"2026-08-31_bc_name": "休息",
|
||||
"2026-09-01_bc_name": "经营正班A",
|
||||
"2026-09-02_bc_name": "经营正班A",
|
||||
},
|
||||
]
|
||||
|
||||
|
||||
# ---------- 测试:假期类型编码映射 ----------
|
||||
|
||||
def test_vacation_type_mapping():
|
||||
"""测试:假期类型编码→名称映射"""
|
||||
from app.service.hrbp.oa.leave.parser import _resolve_vacation_type, VACATION_TYPE_MAP
|
||||
|
||||
# 所有编码应能映射到名称
|
||||
for code, name in VACATION_TYPE_MAP.items():
|
||||
result = _resolve_vacation_type({"vacation_type": code})
|
||||
assert result == name, f"编码 {code} 映射失败: 期望 {name}, 实际 {result}"
|
||||
|
||||
# 直接传名称也能识别
|
||||
result = _resolve_vacation_type({"vacation_type": "事假"})
|
||||
assert result == "事假"
|
||||
|
||||
# 通过 leave_type 字段
|
||||
result = _resolve_vacation_type({"leave_type": "04"})
|
||||
assert result == "病假"
|
||||
|
||||
# 通过 sub_type 字段
|
||||
result = _resolve_vacation_type({"sub_type": "05"})
|
||||
assert result == "产假"
|
||||
|
||||
# 空值返回空字符串
|
||||
result = _resolve_vacation_type({})
|
||||
assert result == ""
|
||||
|
||||
logger.info("[通过] 假期类型编码映射: %d 种类型全部正确", len(VACATION_TYPE_MAP))
|
||||
|
||||
|
||||
# ---------- 测试:请假表单解析 ----------
|
||||
|
||||
def test_parse_leave_form():
|
||||
"""测试:请假表单解析"""
|
||||
from app.service.hrbp.oa.leave.parser import _parse_leave_form
|
||||
|
||||
form_data = {
|
||||
"staff_id": "test-001",
|
||||
"staff_name": "张三",
|
||||
"dept_org_name": "技术部",
|
||||
"vacation_type": "09",
|
||||
"start_time": "2026-08-10 09:00",
|
||||
"end_time": "2026-08-12 18:00",
|
||||
"leave_days": 3.0,
|
||||
"leave_hours": 24.0,
|
||||
"file": "attachment-id-123",
|
||||
}
|
||||
info = _parse_leave_form(form_data)
|
||||
assert info["请假人员ID"] == "test-001"
|
||||
assert info["请假人员"] == "张三"
|
||||
assert info["所属部门"] == "技术部"
|
||||
assert info["假期类型"] == "事假"
|
||||
assert info["开始时间"] == "2026-08-10 09:00"
|
||||
assert info["结束时间"] == "2026-08-12 18:00"
|
||||
assert info["请假天数"] == 3.0
|
||||
assert info["请假小时"] == 24.0
|
||||
assert info["附件"] == "attachment-id-123"
|
||||
|
||||
# 无附件场景
|
||||
form_data_no_file = {**form_data, "file": None}
|
||||
info2 = _parse_leave_form(form_data_no_file)
|
||||
assert info2["附件"] is None
|
||||
|
||||
logger.info("[通过] 请假表单解析: 字段提取正确")
|
||||
|
||||
|
||||
def test_parse_leave_form_fallback_fields():
|
||||
"""测试:请假表单解析的降级字段名"""
|
||||
from app.service.hrbp.oa.leave.parser import _parse_leave_form
|
||||
|
||||
# 使用备用字段名(leave_day / ot_day)
|
||||
form_data = {
|
||||
"staff_id": "test-002",
|
||||
"staff_name": "李四",
|
||||
"vacation_type": "04",
|
||||
"start_time": "2026-08-10 09:00",
|
||||
"end_time": "2026-08-10 18:00",
|
||||
"leave_day": 1.0,
|
||||
"leave_hour": 8.0,
|
||||
}
|
||||
info = _parse_leave_form(form_data)
|
||||
assert info["假期类型"] == "病假"
|
||||
assert info["请假天数"] == 1.0
|
||||
assert info["请假小时"] == 8.0
|
||||
|
||||
# 使用 ot_day / ot_hour 字段
|
||||
form_data2 = {
|
||||
"staff_id": "test-003",
|
||||
"staff_name": "王五",
|
||||
"sub_type": "11",
|
||||
"start_time": "2026-08-10 09:00",
|
||||
"end_time": "2026-08-10 12:00",
|
||||
"ot_day": 0.5,
|
||||
"ot_hour": 4.0,
|
||||
}
|
||||
info2 = _parse_leave_form(form_data2)
|
||||
assert info2["假期类型"] == "调休假"
|
||||
assert info2["请假天数"] == 0.5
|
||||
assert info2["请假小时"] == 4.0
|
||||
|
||||
logger.info("[通过] 请假表单降级字段: 备用字段名解析正确")
|
||||
|
||||
|
||||
# ---------- 测试:日期处理 ----------
|
||||
|
||||
def test_get_date_range():
|
||||
"""测试:从起止时间提取日期范围"""
|
||||
from app.service.hrbp.oa.leave.validator import _get_date_range
|
||||
|
||||
start, end = _get_date_range("2026-08-10 09:00", "2026-08-12 18:00")
|
||||
assert start == "2026-08-10"
|
||||
assert end == "2026-08-12"
|
||||
|
||||
# 空值处理
|
||||
start2, end2 = _get_date_range(None, "2026-08-12 18:00")
|
||||
assert start2 is None
|
||||
assert end2 == "2026-08-12"
|
||||
|
||||
logger.info("[通过] 日期范围提取: start=%s, end=%s", start, end)
|
||||
|
||||
|
||||
# ---------- 测试:validate_doc 审批决策逻辑 ----------
|
||||
|
||||
@patch("app.service.hrbp.oa.leave.validator.fetch_all_shift")
|
||||
@patch("app.service.hrbp.oa.leave.validator._get_hr_context")
|
||||
def test_validate_doc_group1_pass(mock_get_hr_context, mock_fetch_all_shift):
|
||||
"""测试:Group 1(事假)天数一致 → 通过"""
|
||||
from app.service.hrbp.oa.leave.validator import validate_doc
|
||||
|
||||
mock_get_hr_context.return_value = (MagicMock(), "user-001")
|
||||
mock_fetch_all_shift.return_value = SAMPLE_SHIFT
|
||||
|
||||
doc = {
|
||||
"title": "张三的请假申请",
|
||||
"creator": "张三",
|
||||
"time": "2026-08-09 10:00",
|
||||
"formData": {
|
||||
"staff_id": "test-001",
|
||||
"staff_code": "A001",
|
||||
"staff_name": "张三",
|
||||
"vacation_type": "09", # 事假
|
||||
"begin_date": "2026-08-10",
|
||||
"end_date": "2026-08-11",
|
||||
"leave_days": 2.0, # 填报2天,排班2天(10、11都是正常)
|
||||
},
|
||||
}
|
||||
session = MagicMock()
|
||||
result = validate_doc(doc, session)
|
||||
|
||||
assert result["decision"] == "通过", f"期望通过,实际: {result['decision']} - {result['note']}"
|
||||
assert result["leave_info"]["实际上班天数"] == 2
|
||||
assert result["leave_info"]["填报天数"] == 2.0
|
||||
logger.info("[通过] Group1(事假)天数一致→通过: %s", result["note"])
|
||||
|
||||
|
||||
@patch("app.service.hrbp.oa.leave.validator.fetch_all_shift")
|
||||
@patch("app.service.hrbp.oa.leave.validator._get_hr_context")
|
||||
def test_validate_doc_group1_reject(mock_get_hr_context, mock_fetch_all_shift):
|
||||
"""测试:Group 1(事假)天数不一致 → 校验不通过未处理"""
|
||||
from app.service.hrbp.oa.leave.validator import validate_doc
|
||||
|
||||
mock_get_hr_context.return_value = (MagicMock(), "user-001")
|
||||
mock_fetch_all_shift.return_value = SAMPLE_SHIFT
|
||||
|
||||
doc = {
|
||||
"title": "张三的请假申请",
|
||||
"creator": "张三",
|
||||
"time": "2026-08-09 10:00",
|
||||
"formData": {
|
||||
"staff_id": "test-001",
|
||||
"staff_code": "A001",
|
||||
"staff_name": "张三",
|
||||
"vacation_type": "09", # 事假
|
||||
"begin_date": "2026-08-10",
|
||||
"end_date": "2026-08-14",
|
||||
"leave_days": 5.0, # 填报5天,但排班中12、15、16休息,实际只有3天上班
|
||||
},
|
||||
}
|
||||
session = MagicMock()
|
||||
result = validate_doc(doc, session)
|
||||
|
||||
assert result["decision"] == "校验不通过未处理", f"期望校验不通过未处理,实际: {result['decision']} - {result['note']}"
|
||||
assert "不一致" in result["note"]
|
||||
assert result["leave_info"]["实际上班天数"] == 4
|
||||
assert result["leave_info"]["填报天数"] == 5.0
|
||||
logger.info("[通过] Group1(事假)天数不一致→校验不通过未处理: %s", result["note"])
|
||||
|
||||
|
||||
@patch("app.service.hrbp.oa.leave.validator.check_leave_attachment")
|
||||
@patch("app.service.hrbp.oa.leave.validator.download_attachment")
|
||||
@patch("app.service.hrbp.oa.leave.validator.fetch_all_shift")
|
||||
@patch("app.service.hrbp.oa.leave.validator._get_hr_context")
|
||||
def test_validate_doc_group2_pass(mock_get_hr_context, mock_fetch_all_shift, mock_download, mock_check):
|
||||
"""测试:Group 2(病假)天数一致 + 有附件 → 通过"""
|
||||
from app.service.hrbp.oa.leave.validator import validate_doc
|
||||
|
||||
mock_get_hr_context.return_value = (MagicMock(), "user-001")
|
||||
mock_fetch_all_shift.return_value = SAMPLE_SHIFT
|
||||
mock_download.return_value = r"D:\tmp\sick.jpg" # 附件下载成功
|
||||
mock_check.return_value = True # OCR 命中病假关键词
|
||||
|
||||
doc = {
|
||||
"title": "李四的病假申请",
|
||||
"creator": "李四",
|
||||
"time": "2026-08-09 10:00",
|
||||
"formData": {
|
||||
"staff_id": "test-002",
|
||||
"staff_code": "A002",
|
||||
"staff_name": "李四",
|
||||
"vacation_type": "04", # 病假
|
||||
"begin_date": "2026-08-10",
|
||||
"end_date": "2026-08-11",
|
||||
"leave_days": 2.0, # 填报2天,排班2天
|
||||
"file": "attachment-id-456",
|
||||
},
|
||||
}
|
||||
session = MagicMock()
|
||||
result = validate_doc(doc, session)
|
||||
|
||||
assert result["decision"] == "通过", f"期望通过,实际: {result['decision']} - {result['note']}"
|
||||
assert "附件" in result["note"]
|
||||
logger.info("[通过] Group2(病假)天数一致+有附件→通过: %s", result["note"])
|
||||
|
||||
|
||||
@patch("app.service.hrbp.oa.leave.validator.fetch_all_shift")
|
||||
@patch("app.service.hrbp.oa.leave.validator._get_hr_context")
|
||||
def test_validate_doc_group2_reject_no_attachment(mock_get_hr_context, mock_fetch_all_shift):
|
||||
"""测试:Group 2(病假)天数一致但无附件 → 校验不通过未处理"""
|
||||
from app.service.hrbp.oa.leave.validator import validate_doc
|
||||
|
||||
mock_get_hr_context.return_value = (MagicMock(), "user-001")
|
||||
mock_fetch_all_shift.return_value = SAMPLE_SHIFT
|
||||
|
||||
doc = {
|
||||
"title": "李四的病假申请",
|
||||
"creator": "李四",
|
||||
"time": "2026-08-09 10:00",
|
||||
"formData": {
|
||||
"staff_id": "test-002",
|
||||
"staff_code": "A002",
|
||||
"staff_name": "李四",
|
||||
"vacation_type": "04", # 病假
|
||||
"begin_date": "2026-08-10",
|
||||
"end_date": "2026-08-11",
|
||||
"leave_days": 2.0, # 天数一致
|
||||
# 无 file 字段
|
||||
},
|
||||
}
|
||||
session = MagicMock()
|
||||
result = validate_doc(doc, session)
|
||||
|
||||
assert result["decision"] == "校验不通过未处理", f"期望校验不通过未处理,实际: {result['decision']} - {result['note']}"
|
||||
assert "附件" in result["note"]
|
||||
logger.info("[通过] Group2(病假)无附件→校验不通过未处理: %s", result["note"])
|
||||
|
||||
|
||||
@patch("app.service.hrbp.oa.leave.validator.fetch_all_shift")
|
||||
@patch("app.service.hrbp.oa.leave.validator._get_hr_context")
|
||||
def test_validate_doc_group2_reject_both(mock_get_hr_context, mock_fetch_all_shift):
|
||||
"""测试:Group 2(病假)天数不一致 + 无附件 → 校验不通过未处理(双原因)"""
|
||||
from app.service.hrbp.oa.leave.validator import validate_doc
|
||||
|
||||
mock_get_hr_context.return_value = (MagicMock(), "user-001")
|
||||
mock_fetch_all_shift.return_value = SAMPLE_SHIFT
|
||||
|
||||
doc = {
|
||||
"title": "李四的病假申请",
|
||||
"creator": "李四",
|
||||
"time": "2026-08-09 10:00",
|
||||
"formData": {
|
||||
"staff_id": "test-002",
|
||||
"staff_code": "A002",
|
||||
"staff_name": "李四",
|
||||
"vacation_type": "04", # 病假
|
||||
"begin_date": "2026-08-10",
|
||||
"end_date": "2026-08-14",
|
||||
"leave_days": 5.0, # 填报5天,排班10/11/13/14上班,实际4天,不一致
|
||||
# 无附件
|
||||
},
|
||||
}
|
||||
session = MagicMock()
|
||||
result = validate_doc(doc, session)
|
||||
|
||||
assert result["decision"] == "校验不通过未处理"
|
||||
assert "不一致" in result["note"]
|
||||
assert "附件" in result["note"]
|
||||
logger.info("[通过] Group2(病假)天数不一致+无附件→校验不通过未处理: %s", result["note"])
|
||||
|
||||
|
||||
@patch("app.service.hrbp.oa.leave.validator.fetch_all_shift")
|
||||
@patch("app.service.hrbp.oa.leave.validator._get_hr_context")
|
||||
def test_validate_doc_unknown_type(mock_get_hr_context, mock_fetch_all_shift):
|
||||
"""测试:未识别的假期类型 → 校验不通过未处理"""
|
||||
from app.service.hrbp.oa.leave.validator import validate_doc
|
||||
|
||||
mock_get_hr_context.return_value = (MagicMock(), "user-001")
|
||||
mock_fetch_all_shift.return_value = SAMPLE_SHIFT
|
||||
|
||||
doc = {
|
||||
"title": "未知假期申请",
|
||||
"creator": "赵六",
|
||||
"time": "2026-08-09 10:00",
|
||||
"formData": {
|
||||
"staff_id": "test-003",
|
||||
"staff_code": "A003",
|
||||
"staff_name": "赵六",
|
||||
"vacation_type": "99", # 不存在的类型
|
||||
"begin_date": "2026-08-10",
|
||||
"end_date": "2026-08-11",
|
||||
"leave_days": 2.0,
|
||||
},
|
||||
}
|
||||
session = MagicMock()
|
||||
result = validate_doc(doc, session)
|
||||
|
||||
assert result["decision"] == "校验不通过未处理"
|
||||
assert "无法识别" in result["note"]
|
||||
logger.info("[通过] 未识别假期类型→校验不通过未处理: %s", result["note"])
|
||||
|
||||
|
||||
@patch("app.service.hrbp.oa.leave.validator.fetch_all_shift")
|
||||
@patch("app.service.hrbp.oa.leave.validator._get_hr_context")
|
||||
def test_validate_doc_missing_fields(mock_get_hr_context, mock_fetch_all_shift):
|
||||
"""测试:缺失必要字段 → 校验不通过未处理"""
|
||||
from app.service.hrbp.oa.leave.validator import validate_doc
|
||||
|
||||
session = MagicMock()
|
||||
|
||||
# 缺失假期类型
|
||||
doc1 = {"title": "test", "creator": "t", "time": "t", "formData": {"staff_id": "001"}}
|
||||
r1 = validate_doc(doc1, session)
|
||||
assert r1["decision"] == "校验不通过未处理"
|
||||
assert "假期类型" in r1["note"]
|
||||
|
||||
# 缺失 staff_id
|
||||
doc2 = {"title": "test", "creator": "t", "time": "t", "formData": {"vacation_type": "09"}}
|
||||
r2 = validate_doc(doc2, session)
|
||||
assert r2["decision"] == "校验不通过未处理"
|
||||
assert "人员ID" in r2["note"]
|
||||
|
||||
# 缺失工号
|
||||
doc3 = {"title": "test", "creator": "t", "time": "t",
|
||||
"formData": {"staff_id": "001", "vacation_type": "09"}}
|
||||
r3 = validate_doc(doc3, session)
|
||||
assert r3["decision"] == "校验不通过未处理"
|
||||
assert "工号" in r3["note"]
|
||||
|
||||
# 缺失起止日期
|
||||
doc4 = {"title": "test", "creator": "t", "time": "t",
|
||||
"formData": {"staff_id": "001", "staff_code": "A001", "vacation_type": "09"}}
|
||||
r4 = validate_doc(doc4, session)
|
||||
assert r4["decision"] == "校验不通过未处理"
|
||||
assert "日期" in r4["note"]
|
||||
|
||||
logger.info("[通过] 缺失必要字段→校验不通过未处理: 4种场景均正确")
|
||||
|
||||
|
||||
@patch("app.service.hrbp.oa.leave.validator.fetch_all_shift")
|
||||
@patch("app.service.hrbp.oa.leave.validator._get_hr_context")
|
||||
def test_validate_doc_cross_month(mock_get_hr_context, mock_fetch_all_shift):
|
||||
"""测试:跨月请假排班获取"""
|
||||
from app.service.hrbp.oa.leave.validator import validate_doc
|
||||
|
||||
mock_get_hr_context.return_value = (MagicMock(), "user-001")
|
||||
mock_fetch_all_shift.return_value = SAMPLE_SHIFT_CROSS_MONTH
|
||||
|
||||
doc = {
|
||||
"title": "跨月请假",
|
||||
"creator": "王五",
|
||||
"time": "2026-08-30 10:00",
|
||||
"formData": {
|
||||
"staff_id": "test-004",
|
||||
"staff_code": "A004",
|
||||
"staff_name": "王五",
|
||||
"vacation_type": "11", # 调休假
|
||||
"begin_date": "2026-08-30",
|
||||
"end_date": "2026-09-02",
|
||||
"leave_days": 2.0, # 8月30/31休息不计数,9月1/2正常 = 2天
|
||||
},
|
||||
}
|
||||
session = MagicMock()
|
||||
result = validate_doc(doc, session)
|
||||
|
||||
assert result["decision"] == "通过", f"期望通过,实际: {result['decision']} - {result['note']}"
|
||||
assert result["leave_info"]["实际上班天数"] == 2
|
||||
logger.info("[通过] 跨月请假排班获取: 实际上班天数=%d, %s",
|
||||
result["leave_info"]["实际上班天数"], result["note"])
|
||||
|
||||
|
||||
# ---------- 测试:reporter 报告生成 ----------
|
||||
|
||||
def test_generate_report():
|
||||
"""测试:报告生成"""
|
||||
from app.service.hrbp.oa.leave.reporter import generate_report
|
||||
|
||||
results = [
|
||||
{
|
||||
"title": "张三的请假",
|
||||
"creator": "张三",
|
||||
"time": "2026-08-09 10:00",
|
||||
"decision": "通过",
|
||||
"note": "审批通过",
|
||||
"leave_info": {
|
||||
"假期类型": "事假",
|
||||
"请假人员": "张三",
|
||||
"所属部门": "技术部",
|
||||
"开始时间": "2026-08-10 09:00",
|
||||
"结束时间": "2026-08-11 18:00",
|
||||
"填报天数": 2.0,
|
||||
"实际上班天数": 2,
|
||||
"请假小时": 16.0,
|
||||
"附件": "file-id",
|
||||
},
|
||||
},
|
||||
{
|
||||
"title": "李四的病假",
|
||||
"creator": "李四",
|
||||
"time": "2026-08-09 11:00",
|
||||
"decision": "不通过",
|
||||
"note": "未上传附件",
|
||||
"leave_info": {
|
||||
"假期类型": "病假",
|
||||
"请假人员": "李四",
|
||||
"所属部门": "人事部",
|
||||
"开始时间": "2026-08-10 09:00",
|
||||
"结束时间": "2026-08-10 18:00",
|
||||
"填报天数": 1.0,
|
||||
"实际上班天数": 1,
|
||||
"请假小时": 8.0,
|
||||
"附件": None,
|
||||
},
|
||||
},
|
||||
]
|
||||
|
||||
report = generate_report(results)
|
||||
assert "请假审批报告" in report
|
||||
assert "张三" in report
|
||||
assert "李四" in report
|
||||
assert "通过" in report
|
||||
assert "不通过" in report
|
||||
assert "共 2 单" in report
|
||||
logger.info("[通过] 报告生成: 包含 %d 条记录", len(results))
|
||||
|
||||
|
||||
# ---------- 主入口 ----------
|
||||
|
||||
if __name__ == "__main__":
|
||||
logger.info("========== 测试⑤:请假校验模块(离线) ==========")
|
||||
|
||||
test_vacation_type_mapping()
|
||||
test_parse_leave_form()
|
||||
test_parse_leave_form_fallback_fields()
|
||||
test_get_date_range()
|
||||
test_validate_doc_group1_pass()
|
||||
test_validate_doc_group1_reject()
|
||||
test_validate_doc_group2_pass()
|
||||
test_validate_doc_group2_reject_no_attachment()
|
||||
test_validate_doc_group2_reject_both()
|
||||
test_validate_doc_unknown_type()
|
||||
test_validate_doc_missing_fields()
|
||||
test_validate_doc_cross_month()
|
||||
test_generate_report()
|
||||
|
||||
logger.info("========== 测试⑤结束 ==========")
|
||||
@@ -0,0 +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)
|
||||
|
||||
logger.info("========== 测试⑥结束 ==========")
|
||||
@@ -0,0 +1,113 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: tests.hrbp.test_07_confirm_abnormal
|
||||
@FileName: test_07_confirm_abnormal.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-24
|
||||
@Description: 周考勤异常「确认异常」功能测试:
|
||||
拉取上周未调整异常 → 展示列表供人工挑选一条 → 确认无误后调用确认接口提交
|
||||
→ 重查验证该条已从「未调整」列表消失。
|
||||
注意:确认异常为真实写操作(type=1 自动确认异常),提交后无法撤销,
|
||||
请务必人工核对所选记录无误后再确认。
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..'))
|
||||
|
||||
from tests.hrbp._helpers import setup_logging, get_logger # noqa: E402
|
||||
|
||||
setup_logging()
|
||||
logger = get_logger("tests.hrbp.test_07_confirm_abnormal")
|
||||
|
||||
|
||||
def fetch_unadjusted():
|
||||
"""构建会话并拉取当月未调整考勤异常,返回 (session, data)。"""
|
||||
from app.service.hrbp.ehr.attendance.attendance_abnormal import (
|
||||
build_hr_session,
|
||||
_validate_session,
|
||||
fetch_all_attendance_abnormal,
|
||||
last_week_range,
|
||||
IS_ADJUSTED,
|
||||
)
|
||||
|
||||
session = build_hr_session()
|
||||
session, user_id, treecode = _validate_session(session)
|
||||
begin, end = last_week_range()
|
||||
logger.info("查询范围:%s ~ %s,状态:未调整(%s)", begin, end, IS_ADJUSTED)
|
||||
data = fetch_all_attendance_abnormal(session, user_id, treecode, begin, end, IS_ADJUSTED)
|
||||
return session, data
|
||||
|
||||
|
||||
def show_list(data):
|
||||
"""按行展示未调整异常,返回序号 → abnormal_id 的映射。"""
|
||||
print("\n===== 上周未调整考勤异常清单 =====")
|
||||
print(f"{'序号':<4}{'abnormal_id':<34}{'工号':<10}{'姓名':<10}{'日期':<12}{'班次':<10}{'异常类型':<14}{'时长'}")
|
||||
for i, it in enumerate(data, 1):
|
||||
print(
|
||||
f"{i:<4}{str(it.get('abnormal_id', '')):<34}"
|
||||
f"{str(it.get('base_code', '')):<10}{str(it.get('STAFF_NAME', '')):<10}"
|
||||
f"{str(it.get('work_day', '')):<12}{str(it.get('bc_name', '')):<10}"
|
||||
f"{str(it.get('abnormal', '')):<14}{str(it.get('abnormal_minute', '') or 0)}"
|
||||
)
|
||||
print(f"共 {len(data)} 条\n")
|
||||
return {i: it.get("abnormal_id") for i, it in enumerate(data, 1)}
|
||||
|
||||
|
||||
def main():
|
||||
session, data = fetch_unadjusted()
|
||||
if not data:
|
||||
logger.warning("上周无未调整考勤异常,无需测试")
|
||||
return
|
||||
|
||||
mapping = show_list(data)
|
||||
|
||||
raw = input("请输入要确认的异常序号(Enter 取消):").strip()
|
||||
if not raw:
|
||||
logger.info("已取消,未提交任何确认")
|
||||
return
|
||||
try:
|
||||
idx = int(raw)
|
||||
except ValueError:
|
||||
logger.error("输入无效:%s", raw)
|
||||
return
|
||||
if idx not in mapping:
|
||||
logger.error("序号 %d 不在清单范围内", idx)
|
||||
return
|
||||
abnormal_id = mapping[idx]
|
||||
|
||||
logger.warning("即将对 abnormal_id=%s 调用确认接口(type=1,真实提交,不可撤销)", abnormal_id)
|
||||
again = input("再次确认无误?输入 y 提交,其他取消:").strip().lower()
|
||||
if again != "y":
|
||||
logger.info("已取消,未提交")
|
||||
return
|
||||
|
||||
from app.service.hrbp.ehr.attendance.attendance_abnormal import confirm_abnormal
|
||||
result = confirm_abnormal(abnormal_id, session=session)
|
||||
logger.info("确认接口返回:%s", result)
|
||||
if result.get("state") != "1":
|
||||
logger.error("确认失败:%s", result.get("meg") or result)
|
||||
return
|
||||
|
||||
# 重查验证:该条应从「未调整」列表消失
|
||||
_, data_after = fetch_unadjusted()
|
||||
remaining = [it for it in data_after if str(it.get("abnormal_id", "")) == str(abnormal_id)]
|
||||
if remaining:
|
||||
logger.error("验证失败:abnormal_id=%s 仍在未调整列表中", abnormal_id)
|
||||
else:
|
||||
logger.info("[通过] abnormal_id=%s 已确认成功,不再出现在未调整列表(剩余 %d 条)",
|
||||
abnormal_id, len(data_after))
|
||||
|
||||
# 影刀单文件版静态就绪校验(不发起真实请求)
|
||||
import importlib
|
||||
workflows = importlib.import_module("workflows.hr.attendance_abnormal")
|
||||
assert callable(workflows.confirm_abnormal), "影刀版缺少 confirm_abnormal"
|
||||
assert callable(workflows.adjust_abnormal), "影刀版缺少 adjust_abnormal"
|
||||
assert workflows.ATTENDANCE_ADJUST_URL.endswith("KqCountAbnormal.mc"), "影刀版确认接口地址异常"
|
||||
logger.info("[通过] 影刀单文件版 confirm_abnormal 已就绪(未发请求)")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +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"))
|
||||
@@ -0,0 +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 "-"
|
||||
print(f"{unit:<12} | {org:<10} | {seq_display:<12} | {rule.days:<4} | {rule.rule_type:<10} | {rule.note}")
|
||||
@@ -0,0 +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__":
|
||||
main()
|
||||
Reference in New Issue
Block a user