跳至内容
Api 自动化测试框架

Api 自动化测试框架

经过前文内容,现在项目结构如下:

      • _init_.py
        • _init_.py
      • _init_.py
      • test_casename.py
        • _init_.py
        • database_connection_pool_strategy.py
        • mysql_connection_pool.py
        • redis_connection_pool.py
      • _init_.py
      • database_connection_pool.py
      • file_data_reader.py
      • parametrize.py
      • timeout.py
      • database.toml
      • api_docs.md
      • project_design.md
      • usage_guide.md
      • _init_.py
      • all.log
      • error.log
    • main.py
    • pytest.toml
    • README.md
    • requirements.txt

延续前文内容,离一个好用的 Api 自动化测试框架已经不远了。

请求库

推荐使用 requests 库,具体用法请查看 Requests:面向人类的 HTTP™

启动脚本

还编辑启动脚本,做一些初始化操作及后续操作。

main.py
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import argparse
import sys

import pytest

from common.log_config import setup_logger

logger = setup_logger()


# 构建参数解析器,传递 pytest 参数,后续根据需求创建自定义参数
def parse_arguments() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(
        description="pytest 启动脚本(支持自定义参数 + pytest 参数)",
        add_help=False,  # 隐藏默认帮助信息,避免与 pytest 的 -h 冲突
    )

    parser.add_argument(
        "-h",
        "--help",
        action="store_true",
        help="显示帮助信息(包含自定义参数和pytest原生参数)",
    )

    return parser


# 运行测试
def run_tests(parser: argparse.ArgumentParser) -> int:
    """运行测试"""
    # 解析自定义参数和 pytest 参数
    customize_args, pytest_args = parser.parse_known_args()

    # 如果用户请求帮助,则打印帮助信息并退出
    if customize_args.help:
        parser.print_help()
        print("\n=== pytest 原生参数 help 信息 ===")
        pytest.main(["-h"])
        return 0

    # 开始运行测试
    try:
        logger.info(f"开始运行测试,,pytest参数: {pytest_args}")
        exit_code = pytest.main(pytest_args)

        exit_code_value = (
            exit_code.value if isinstance(exit_code, pytest.ExitCode) else exit_code
        )
        exit_messages = {
            0: "✅ 全部测试用例通过",
            1: "⚠️ 部分测试用例未通过",
            2: "❌ 测试过程中有中断或其他非正常终止",
            3: "❌ 内部错误",
            4: "❌ 命令行参数错误",
            5: "❌ 没有收集到任何测试用例",
        }

        logger.info(
            exit_messages.get(exit_code_value, f"❓ 未知的退出码: {exit_code_value}")
        )
        return exit_code_value

    except Exception:
        logger.exception("运行测试时发生致命错误:")
        return 1


def main():
    parser = parse_arguments()
    exit_code = run_tests(parser)
    sys.exit(exit_code)
    
if __name__ == "__main__":
    main()

执行 python main.py 即可运行测试项目,同时支持 pytest 框架的各种参数。

最后更新于