refactor: 重构项目代码结构与依赖管理

1.  **依赖与导入路径修正
    - 移除所有本地sys.path插入,统一使用绝对包导入
    - 修复logger导入路径,统一从app.utils导入
    - 重构intelligent_retry.py移除冗余导入
    - 统一hrbp各模块的导入路径

2.  **项目配置与构建
    - 新增pyproject.toml配置文件,规范项目元数据与依赖声明
    - 更新requirements.txt新增pyautogui、pywin32、pyperclip依赖

3.  **业务模块重构
    - 重构请假/加班审批模块的导入路径与内部逻辑
    - 重命名审批结果描述(将"不通过"改为"驳回")
    - 统一代码中的箭头符号(将→改为->)
    - 新增请假表单解析模块、钉钉通知模块
    - 重构加班/请假校验模块的报告生成逻辑,统一报告格式与推送流程

4.  **测试与文档
    - 新增端到端测试脚本与统一测试运行器
    - 完善README.md文档,补充项目结构、功能说明与使用方法
    - 新增钉钉消息推送工具文档
    - 新增测试用例与辅助工具

5.  **其他优化
    - 修复common/parser.py中的正则表达式兼容单引号的HTML属性
    - 新增session_manager.py移除冗余导入与路径修正
    - 新增OA审批报告生成逻辑优化,支持分组统计与详细清单输出
This commit is contained in:
2026-08-07 00:18:49 +08:00
parent 249088614d
commit 724a4f7b77
31 changed files with 4742 additions and 288 deletions
+4 -8
View File
@@ -11,17 +11,14 @@
import os
import sys
# ---------- 统一 sys.path:项目根 + app/ ----------
# ---------- 统一 sys.path:项目根 ----------
# 项目根加进来后可用 from app.service.hrbp... 形式 import
# app/ 加进来兼容业务模块内部的 from utils.xxx / from hrbp.oa... 写法
_PROJECT_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..'))
_APP_DIR = os.path.join(_PROJECT_ROOT, 'app')
for _p in (_PROJECT_ROOT, _APP_DIR):
if _p not in sys.path:
sys.path.insert(0, _p)
if _PROJECT_ROOT not in sys.path:
sys.path.insert(0, _PROJECT_ROOT)
# 初始化日志(测试脚本共用)
from utils.logger import setup_logging, get_logger # noqa: E402
from app.utils.logger import setup_logging, get_logger # noqa: E402
setup_logging()
logger = get_logger("tests.hrbp")
@@ -43,7 +40,6 @@ def get_logged_in_session(subject: str = "加班"):
from app.service.hrbp.oa.common.session_manager import (
load_saved_session,
is_session_valid,
oa_login, # noqa: F401 (保留便于调试时直接登录)
init_session_from_page,
save_browser_cookies,
create_browser_with_saved_cookies,
+502
View File
@@ -0,0 +1,502 @@
# -*- 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
# ---------- 测试数据 ----------
SAMPLE_ATTENDANCE_HTML = """
<a class='cale_a' data-temp="2026-08-10">正常</a>
<a class='cale_a' data-temp="2026-08-11">正常</a>
<a class='cale_a' data-temp="2026-08-12">休息</a>
<a class='cale_a' data-temp="2026-08-13">正常</a>
<a class='cale_a' data-temp="2026-08-14">正常</a>
<a class='cale_a' data-temp="2026-08-15">休息</a>
<a class='cale_a' data-temp="2026-08-16">休息</a>
<a class='cale_a' data-temp="2026-08-17">正常</a>
"""
# 跨月排班 HTML(9月)
SAMPLE_ATTENDANCE_HTML_SEP = """
<a class='cale_a' data-temp="2026-09-01">正常</a>
<a class='cale_a' data-temp="2026-09-02">正常</a>
<a class='cale_a' data-temp="2026-09-03">休息</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)
def test_get_months_in_range():
"""测试:获取日期范围内所有月份(跨月场景)"""
from app.service.hrbp.oa.leave.validator import _get_months_in_range
# 单月
months = _get_months_in_range("2026-08-10", "2026-08-20")
assert months == [(2026, 8)], f"单月范围错误: {months}"
# 跨月
months = _get_months_in_range("2026-08-10", "2026-10-05")
assert months == [(2026, 8), (2026, 9), (2026, 10)], f"跨月范围错误: {months}"
# 跨年
months = _get_months_in_range("2026-12-25", "2027-01-05")
assert months == [(2026, 12), (2027, 1)], f"跨年范围错误: {months}"
# 同一天
months = _get_months_in_range("2026-08-10", "2026-08-10")
assert months == [(2026, 8)], f"同天范围错误: {months}"
logger.info("[通过] 月份范围计算: 单月/跨月/跨年均正确")
# ---------- 测试:validate_doc 审批决策逻辑 ----------
@patch("app.service.hrbp.oa.leave.validator.get_attendance_html")
def test_validate_doc_group1_pass(mock_get_attendance_html):
"""测试:Group 1(事假)天数一致 → 通过"""
from app.service.hrbp.oa.leave.validator import validate_doc
mock_get_attendance_html.return_value = SAMPLE_ATTENDANCE_HTML
doc = {
"title": "张三的请假申请",
"creator": "张三",
"time": "2026-08-09 10:00",
"formData": {
"staff_id": "test-001",
"staff_name": "张三",
"vacation_type": "09", # 事假
"start_time": "2026-08-10 09:00",
"end_time": "2026-08-11 18:00",
"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.get_attendance_html")
def test_validate_doc_group1_reject(mock_get_attendance_html):
"""测试:Group 1(事假)天数不一致 → 驳回"""
from app.service.hrbp.oa.leave.validator import validate_doc
mock_get_attendance_html.return_value = SAMPLE_ATTENDANCE_HTML
doc = {
"title": "张三的请假申请",
"creator": "张三",
"time": "2026-08-09 10:00",
"formData": {
"staff_id": "test-001",
"staff_name": "张三",
"vacation_type": "09", # 事假
"start_time": "2026-08-10 09:00",
"end_time": "2026-08-14 18:00",
"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.get_attendance_html")
def test_validate_doc_group2_pass(mock_get_attendance_html):
"""测试:Group 2(病假)天数一致 + 有附件 → 通过"""
from app.service.hrbp.oa.leave.validator import validate_doc
mock_get_attendance_html.return_value = SAMPLE_ATTENDANCE_HTML
doc = {
"title": "李四的病假申请",
"creator": "李四",
"time": "2026-08-09 10:00",
"formData": {
"staff_id": "test-002",
"staff_name": "李四",
"vacation_type": "04", # 病假
"start_time": "2026-08-10 09:00",
"end_time": "2026-08-11 18:00",
"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.get_attendance_html")
def test_validate_doc_group2_reject_no_attachment(mock_get_attendance_html):
"""测试:Group 2(病假)天数一致但无附件 → 驳回"""
from app.service.hrbp.oa.leave.validator import validate_doc
mock_get_attendance_html.return_value = SAMPLE_ATTENDANCE_HTML
doc = {
"title": "李四的病假申请",
"creator": "李四",
"time": "2026-08-09 10:00",
"formData": {
"staff_id": "test-002",
"staff_name": "李四",
"vacation_type": "04", # 病假
"start_time": "2026-08-10 09:00",
"end_time": "2026-08-11 18:00",
"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.get_attendance_html")
def test_validate_doc_group2_reject_both(mock_get_attendance_html):
"""测试:Group 2(病假)天数不一致 + 无附件 → 驳回(双原因)"""
from app.service.hrbp.oa.leave.validator import validate_doc
mock_get_attendance_html.return_value = SAMPLE_ATTENDANCE_HTML
doc = {
"title": "李四的病假申请",
"creator": "李四",
"time": "2026-08-09 10:00",
"formData": {
"staff_id": "test-002",
"staff_name": "李四",
"vacation_type": "04", # 病假
"start_time": "2026-08-10 09:00",
"end_time": "2026-08-14 18:00",
"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.get_attendance_html")
def test_validate_doc_unknown_type(mock_get_attendance_html):
"""测试:未识别的假期类型 → 驳回"""
from app.service.hrbp.oa.leave.validator import validate_doc
mock_get_attendance_html.return_value = SAMPLE_ATTENDANCE_HTML
doc = {
"title": "未知假期申请",
"creator": "赵六",
"time": "2026-08-09 10:00",
"formData": {
"staff_id": "test-003",
"staff_name": "赵六",
"vacation_type": "99", # 不存在的类型
"start_time": "2026-08-10 09:00",
"end_time": "2026-08-11 18:00",
"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.get_attendance_html")
def test_validate_doc_missing_fields(mock_get_attendance_html):
"""测试:缺失必要字段 → 驳回"""
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"]
logger.info("[通过] 缺失必要字段→驳回: 3种场景均正确")
@patch("app.service.hrbp.oa.leave.validator.get_attendance_html")
def test_validate_doc_cross_month(mock_get_attendance_html):
"""测试:跨月请假排班获取"""
from app.service.hrbp.oa.leave.validator import validate_doc
# 模拟跨月请求:8月返回部分数据,9月返回部分数据
def side_effect(session, staff_id, year, month):
if month == 8:
return SAMPLE_ATTENDANCE_HTML
elif month == 9:
return SAMPLE_ATTENDANCE_HTML_SEP
return ""
mock_get_attendance_html.side_effect = side_effect
doc = {
"title": "跨月请假",
"creator": "王五",
"time": "2026-08-30 10:00",
"formData": {
"staff_id": "test-004",
"staff_name": "王五",
"vacation_type": "11", # 调休假
"start_time": "2026-08-30 09:00",
"end_time": "2026-09-02 18:00",
"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_get_months_in_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("========== 测试⑤结束 ==========")
+158
View File
@@ -0,0 +1,158 @@
# -*- 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_html(session, staff_id: str):
"""测试:排班 HTML 接口 + 解析(请假场景)"""
from app.service.hrbp.oa.common.oa_api import get_attendance_html
from app.service.hrbp.oa.common.parser import parse_attendance_html, get_work_days_in_range
year = int(TEST_DATE[:4])
month = int(TEST_DATE[5:7])
html = get_attendance_html(session, staff_id, year, month)
assert html, "排班 HTML 为空"
attendance = parse_attendance_html(html)
assert isinstance(attendance, dict), "排班解析结果非字典"
logger.info("[通过] 请假排班接口正常,当月解析到 %d 天班次", len(attendance))
# 验证 get_work_days_in_range 可用
work_days = get_work_days_in_range(attendance, TEST_DATE, TEST_DATE)
logger.info(" %s 排班: %s", TEST_DATE, attendance.get(TEST_DATE, "无排班"))
return attendance
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_html(session, TEST_STAFF_ID)
# 4. 请假全流程(如有待办)
test_leave_full_flow(session, browser)
logger.info("========== 测试⑥结束 ==========")
+132
View File
@@ -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()
+38
View File
@@ -0,0 +1,38 @@
# -*- coding: utf-8 -*-
"""端到端测试:向夏一平(个人)和群聊小布丁分别发送测试文本 + 文件。"""
import os
import sys
import time
# tests/ 在项目根下一级,需往上一级到项目根才能 import app
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from app.utils.dingtalk_sender import send_to_person, send_to_group
TEST_TEXT = "【自动化测试】这是一条测试消息,请忽略"
TEST_FILE = r"C:\Users\11156\Desktop\测试.txt"
def main():
print("=" * 50)
print("即将发送,运行期间请勿移动鼠标/键盘")
print("=" * 50)
time.sleep(3) # 留 3 秒切换到钉钉、把手离开鼠标
# 1. 个人:夏一平 —— 先文本后文件
print("\n[1/2] 发送给个人「夏一平」: 文本 + 文件")
send_to_person("夏一平", text=TEST_TEXT, file_path=TEST_FILE)
time.sleep(2)
# 2. 群聊:小布丁 —— 先文本后文件
print("\n[2/2] 发送给群聊「小布丁」: 文本 + 文件")
send_to_group("小布丁", text=TEST_TEXT, file_path=TEST_FILE)
print("\n" + "=" * 50)
print("全部发送完成,请到钉钉核对")
print("=" * 50)
if __name__ == "__main__":
main()