接口自动化框架篇: 核心执行器封装流程

📝 面试求职: 「面试试题小程序」 ,内容涵盖 测试基础、Linux操作系统、MySQL数据库、Web功能测试、接口测试、APPium移动端测试、Python知识、Selenium自动化测试相关、性能测试、性能测试、计算机网络知识、Jmeter、HR面试,命中率杠杠的。(大家刷起来…)

📝 职场经验干货:

软件测试工程师简历上如何编写个人信息(一周8个面试)

软件测试工程师简历上如何编写专业技能(一周8个面试)

软件测试工程师简历上如何编写项目经验(一周8个面试)

软件测试工程师简历上如何编写个人荣誉(一周8个面试)

软件测试行情分享(这些都不了解就别贸然冲了.)

软件测试面试重点,搞清楚这些轻松拿到年薪30W+

软件测试面试刷题小程序免费使用(永久使用)


在接口自动化测试中,核心执行器是整个测试框架的关键部分,它负责协调测试用例的执行、结果收集和报告生成。封装一个高效、灵活且易于维护的核心执行器可以显著提升测试效率和代码质量。本文将详细介绍如何封装接口自动化框架的核心执行器,包括执行器的设计、实现和使用。

一、核心执行器的设计目标

高效执行:能够快速执行测试用例,支持并行和异步执行。

灵活配置:支持多种配置选项,如测试用例选择、环境配置等。

结果收集:能够收集测试结果,包括成功、失败、跳过等状态。

报告生成:支持生成多种格式的测试报告,如 HTML、XML 等。

日志记录:记录测试过程中的日志信息,便于调试和追踪问题。‍

二、核心执行器的实现

(一)安装依赖库

首先,需要安装 pytest 和 allure-pytest 库,用于测试执行和报告生成。

pip install pytest allure-pytest

(二)封装核心执行器类

创建一个 executor.py 文件,封装核心执行器类。

import pytest

import os

from loguru import logger

class TestExecutor:

    def __init__(self, test_dir, report_dir="reports", log_dir="logs"):

        self.test_dir = test_dir

        self.report_dir = report_dir

        self.log_dir = log_dir

        self.logger = logger

        self.logger.add(f"{log_dir}/{{time}}.log", rotation="1 day", compression="zip")

    def run_tests(self, test_pattern="test_*.py", markers=None, parallel=False):

        """

        运行测试用例。

        :param test_pattern: 测试用例文件匹配模式

        :param markers: 测试用例标记

        :param parallel: 是否并行执行

        """

        pytest_args = [

            self.test_dir,

            f"--alluredir={self.report_dir}",

            f"--log-cli-level=INFO",

            f"--log-file-level=DEBUG",

            f"--log-format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'",

            f"--log-date-format='%Y-%m-%d %H:%M:%S'",

        ]

        if markers:

            pytest_args.append(f"-m {markers}")

        if parallel:

            pytest_args.append("-n auto")  # 使用 pytest-xdist 插件并行执行

        try:

            self.logger.info("开始运行测试用例")

            pytest.main(pytest_args)

            self.logger.info("测试用例运行完成")

        except Exception as e:

            self.logger.error(f"运行测试用例失败:{e}")

            raise

    def generate_report(self):

        """

        生成测试报告。

        """

        try:

            self.logger.info("开始生成测试报告")

            os.system(f"allure generate {self.report_dir} -o {self.report_dir}/html --clean")

            self.logger.info("测试报告生成完成")

        except Exception as e:

            self.logger.error(f"生成测试报告失败:{e}")

            raise

(三)使用核心执行器运行测试

创建一个 run_tests.py 文件,使用封装的核心执行器运行测试。

from executor import TestExecutor

if __name__ == "__main__":

    executor = TestExecutor(test_dir="tests", report_dir="reports", log_dir="logs")

    executor.run_tests(parallel=True)

    executor.generate_report()

(四)示例:运行特定标记的测试用例

假设我们有一些测试用例文件,其中部分用例标记为 smoke。

# tests/test_smoke.py

import pytest

@pytest.mark.smoke

def test_login():

    assertTrue

@pytest.mark.smoke

def test_logout():

    assertTrue

运行特定标记的测试用例:

from executor import TestExecutor

if __name__ == "__main__":

    executor = TestExecutor(test_dir="tests", report_dir="reports", log_dir="logs")

    executor.run_tests(markers="smoke", parallel=True)

    executor.generate_report()

(五)示例:并行运行测试用例

安装 pytest-xdist 插件以支持并行执行。

pip install pytest-xdist

运行测试用例时,设置 parallel=True:

from executor import TestExecutor

if __name__ == "__main__":

    executor = TestExecutor(test_dir="tests", report_dir="reports", log_dir="logs")

    executor.run_tests(parallel=True)

    executor.generate_report()‍

三、日志记录

封装的日志记录器可以记录测试过程中的详细信息,便于调试和追踪问题。

(一)安装 Loguru

pip install loguru

(二)封装日志记录器

在 executor.py 文件中,封装日志记录器。

from loguru import logger

class TestExecutor:

    def __init__(self, test_dir, report_dir="reports", log_dir="logs"):

        self.test_dir = test_dir

        self.report_dir = report_dir

        self.log_dir = log_dir

        self.logger = logger

        self.logger.add(f"{log_dir}/{{time}}.log", rotation="1 day", compression="zip")

    # ... 其他方法 ...

(三)在测试用例中使用日志记录

from loguru import logger

def test_example():

    logger.info("开始测试")

    assert True

    logger.info("测试完成")‍

四、报告生成

封装的核心执行器支持生成多种格式的测试报告,如 HTML、XML 等。

(一)安装 Allure

pip install allure-pytest

(二)生成 HTML 报告

在 executor.py 文件中,封装报告生成方法。

class TestExecutor:

    # ... 其他方法 ...

    def generate_report(self):

        """

        生成测试报告。

        """

        try:

            self.logger.info("开始生成测试报告")

            os.system(f"allure generate {self.report_dir} -o {self.report_dir}/html --clean")

            self.logger.info("测试报告生成完成")

        except Exception as e:

            self.logger.error(f"生成测试报告失败:{e}")

            raise

(三)查看报告

生成报告后,可以通过以下命令查看报告:

allure serve reports/html‍

五、总结

通过封装核心执行器,可以实现高效、灵活且易于维护的接口自动化测试。核心执行器支持多种配置选项,如测试用例选择、环境配置等,同时能够收集测试结果并生成多种格式的报告。希望本文能够对读者在接口自动化框架中实现核心执行器封装提供帮助。

最后: 下方这份完整的软件测试视频教程已经整理上传完成,需要的朋友们可以自行领取【保证100%免费】

​​

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值