pytest框架 核心知识的系统复习

1. pytest 介绍

  • 是什么:Python 最流行的单元测试框架之一,支持复杂的功能测试和插件扩展。

  • 优点

    • 语法简洁(用 assert 替代 self.assertEqual)。

    • 自动发现测试用例。

    • 丰富的插件生态(如失败重试、并发执行、报告生成)。

    • 兼容unittest框架,比自带unittest框架更加简洁高效,在unittest框架迁移到pytest框架时不需要重写代码。

  • 适用场景:单元测试、接口测试、UI 自动化测试。


2. pytest 环境搭建

安装 pytest

bash

复制

bash 复制代码
pip install pytest

查看pytest是否安装成功

bash 复制代码
pip show pytest

常用扩展插件

bash

复制

bash 复制代码
pip install pytest-html         # HTML 报告
pip install pytest-xdist        # 并发执行
pip install pytest-rerunfailures # 失败重试
pip install allure-pytest       # Allure 报告集成

3. pytest 用例规则

  • 文件命名 :以 test_ 开头或结尾(如 test_login.pylogin_test.py)。

  • 函数/类命名

    • 测试函数:以 test_ 开头(如 test_login_success)。

    • 测试类:以 Test 开头(如 TestLogin),且类中不能有 __init__ 方法。

  • 断言 :直接使用 assert(如 assert response.status_code == 200)。

  • setup和teardown:模块级,类级,方法级,函数级

setup_module和teardown_module,在整个测试用例文件中所有方法运行前后,仅运行1次

setup_class和teardown_class,在一个Class中所有用例前后运行1次

setup_method和teardown_method,在Class下的每个方法前后运行

setup_function和teardown_function,在非Class下的每个方法前后运行


4. pytest 用例编写

示例

python

复制

python 复制代码
# 测试函数
def test_add():
    assert 1 + 1 == 2

# 测试类
class TestMath:
    def test_multiply(self):
        assert 2 * 3 == 6

5. pytest 用例执行顺序

  • 默认顺序:按文件名和测试函数/方法的 ASCII 码顺序执行。

  • 自定义顺序

    • 使用 pytest-ordering 插件:

      python

      复制

      python 复制代码
      @pytest.mark.run(order=1)
      def test_login():
          pass

6. pytest 用例重跑

  • 使用插件pytest-rerunfailures

  • 命令行参数

    bash

    复制

    bash 复制代码
    pytest --reruns 3 --reruns-delay 2  # 失败后重试3次,间隔2秒

7. pytest 用例并发

  • 使用插件pytest-xdist

  • 命令行参数

    bash

    复制

    bash 复制代码
    pytest -n 4  # 启动4个进程并发执行

8. pytest 用例跳过

  • 无条件跳过

    python

    复制

    python 复制代码
    @pytest.mark.skip(reason="功能未实现")
    def test_unimplemented():
        pass
  • 条件跳过

    python

    复制

    python 复制代码
    @pytest.mark.skipif(sys.platform == "win32", reason="Windows 不支持")
    def test_linux_only():
        pass

9. pytest 用例条件判断

  • 结合 pytest.mark.skipif 或自定义条件逻辑:

    python

    复制

    python 复制代码
    def test_feature():
        if not has_feature():
            pytest.skip("环境不支持此功能")
        # 正常测试逻辑

10. pytest 数据初始化与清除

fixture(scope='function', params=None, autouse=False, ids=None, name=None)

  • pytest提供的fixture实现unittest中setup和teardown功能,可以在每次case执行前初始化数据,不同点是,fixture可以只在执行特定case之前运行,使用更灵活
  • autouse参数:默认False须手动调用,只有True时才自动执行
  • scope参数: 有四个级别参数

"function": 在conftest作用域下,每一个test开头的测试方法运行前都会执行一次

"class": 在conftest作用域下,每一个Test开头的测试类运行前都会执行一次

"module": 在conftest作用域下,每一个test开头的测试模块运行前都会执行一次

"session": 在conftest作用域下,这个包运行前只会执行一次

fixture的使用方法:

  • 使用函数名直接调用,但没有返回值

@pytest.mark.usefixtures('function_name')

  • 需要使用到fixture返回值:

直接在对应的接口函数里,加入一个形参,参数名就是fixture函数名


11. pytest 用例定制化执行

添加mark标签,可筛选出对应业务模块的部分接口:

  • 对于Pytest,每一个模块,类,方法和用例前都加上mark,那样在pytest运行的时候就可以只运行带有该mark标签的模块,类或用例:
  • 在配置文件pytest.ini里注册标签:
  • 在类名/方法名前打标签:
bash 复制代码
@pytest.mark.标签名
  • 在类中/方法中打标签:
bash 复制代码
pytestmark = pytest.mark.标签名

执行时可根据标签名来执行想要的用例,例如,运行所有标记为login的测试:

bash 复制代码
pytest -m login

其他运行参数:

  • '-m','user_add',
  • '-m','user_add or user_list',
  • '-m','not user_add',
  • '-m', 'not (user_add or user_list)'
  • '-k',匹配用例文件名,非接口名称,可全部匹配,可模糊匹配
  • '-v',节点 --多层化
  • '-s' 详细输出打印 '-q' 简化打印

12. pytest 参数化

  • 核心装饰器@pytest.mark.parametrize

  • 示例

    python

    复制

    python 复制代码
    @pytest.mark.parametrize("a, b, expected", [
        (1, 2, 3),
        (0, 0, 0),
        (-1, 1, 0),
    ])
    def test_add(a, b, expected):
        assert a + b == expected

13. pytest 插件介绍

  • 常用插件

    • pytest-html:生成 HTML 测试报告。

    • pytest-cov:生成代码覆盖率报告。

    • pytest-mock:集成 Mock 功能。

    • pytest-django:Django 项目测试支持。


14. pytest 插件执行

安装与使用

bash

复制

bash 复制代码
# 安装插件
pip install pytest-html

# 执行并生成 HTML 报告
pytest --html=report.html

15. pytest 集成 Allure

步骤

  1. 安装 Allure 命令行工具(需 Java 环境):
  • 下载allure.zip

  • 解压allure.zip到一个文件目录中

    把解压路径添加到环境变量Path中

    pip isntall pytest-allure

    验证安装完成

方法一

执行pytest单元测试,生成Allure报告需要的数据存在的目录

pytest -sq --alluredir = ../report/tmp

执行命令生成测试报告

allure generate ../report/tmp -o ../report/report --clean

方法二

  1. 生成 Allure 结果数据:

    bash

    复制

    bash 复制代码
    pytest --alluredir=./allure-results
  2. 生成可视化报告:

    bash

    复制

    bash 复制代码
    allure serve ./allure-results  # 本地查看
    allure generate ./allure-results -o ./report --clean  # 生成静态报告

16. pytest 生成测试报告

多种报告形式

  • Python主流自动化测试报告插件:HTMLTestRunner,BeautifulReport,Allure
  • Allure是一款轻量级开源自动化测试报告生成框架,支持绝大部分测试框架,包括TestNG,Junit,pytest,unittest等
  • pytest框架结合Allure可生成格式统一,美观的测试报告
  1. 简单文本报告

    bash

    复制

    复制代码
    pytest -v  # 输出详细结果
  2. HTML 报告

    bash

    复制

    复制代码
    pytest --html=report.html
  3. Allure 报告(需集成):

    bash

    复制

    复制代码
    pytest --alluredir=./results && allure serve ./results

总结

  • 核心优势:简洁语法 + 插件生态 + 高度可定制化。

  • 最佳实践

    • 使用参数化减少重复代码。

    • 结合 CI/CD(如 Jenkins、GitHub Actions)自动化测试。

    • 通过 Allure 或 HTML 报告直观分析结果。

相关推荐
FINE!(正在努力!)2 天前
PyTest框架学习
学习·pytest
程序员杰哥2 天前
接口自动化测试之pytest 运行方式及前置后置封装
自动化测试·软件测试·python·测试工具·职场和发展·测试用例·pytest
测试老哥3 天前
Pytest+Selenium UI自动化测试实战实例
自动化测试·软件测试·python·selenium·测试工具·ui·pytest
水银嘻嘻3 天前
07 APP 自动化- appium+pytest+allure框架封装
python·appium·自动化·pytest
天才测试猿3 天前
接口自动化测试之pytest接口关联框架封装
自动化测试·软件测试·python·测试工具·职场和发展·测试用例·pytest
not coder4 天前
Pytest Fixture 详解
数据库·pytest
not coder5 天前
pytest 常见问题解答 (FAQ)
开发语言·python·pytest
程序员的世界你不懂5 天前
(1)pytest简介和环境准备
pytest
not coder5 天前
Pytest Fixture 是什么?
数据库·oracle·pytest
Tester_孙大壮5 天前
pytest中的元类思想与实战应用
pytest