博客
关于我
pytest框架快速入门-pytest运行时参数说明,pytest详解,pytest.ini详解
阅读量:799 次
发布时间:2023-03-05

本文共 1339 字,大约阅读时间需要 4 分钟。

Pytest简介与应用指南

Pytest 是一个成熟的全功能 Python 测试框架,广泛应用于单元测试、功能测试以及自动化测试等领域。以下将从安装、基础使用、运行参数以及配置等方面详细介绍 Pytest 的使用方法。

Pytest 安装

安装 Pytest 及其常用插件,可以通过以下步骤完成:

  • 安装依赖

    将以下内容写入 require-install.txt 文件:

    pytestpytest-htmlpytest-xdistpytest-rerunfailures

    在命令提示符下运行:

    pip install -r require-install.txt

    验证安装结果:

    pytest --version

    如果出现版本冲突,可以降低 Python 或 Pytest 版本。

  • 示例环境配置

    作者推荐的环境为:

    • 操作系统:Windows 7
    • Python 版本:3.7.3
    • Pytest 版本:5.4.1
  • Pytest 基础应用

    测试用例编写

  • 函数测试

    定义测试函数,命名为 test_ 开头:

    import pytestdef test_01():    print('测试用例一')
  • 类测试

    测试类需以 Test 开头,且不包含 __init__ 方法:

    class TestCase:    def test_03(self):        print('测试用例三')    def defg(self):        print('测试用例四')
  • 运行方式

    • 主函数方式
      if __name__ == '__main__':    pytest.main(['-s', 'pytest-demo.py'])
    • 命令行方式
      在 Pycharm 中打开终端,运行:
      pytest pytest-demo.py
  • 运行时参数说明

    • -s:启用打印输出。
    • :::指定测试用例。
    • --html=./report.html:生成 HTML 测试报告(需安装 pytest-html)。
    • --maxfail=1:允许 1 个失败后停止测试。
    • -n=2:使用多线程运行测试(需安装 pytest-xdist)。
    • --reruns=2:重试失败的测试用例(需安装 pytest-rerunfailures)。

    测试配置文件

    Pytest 的 pytest.ini 文件位于项目根目录下,配置方式如下:

    [pytest]addopts = -s --html=./report.htmltestpaths = ../pytestprojectpython_files = test*.pypython_classes = Test*python_functions = test*

    示例配置:

    [pytest]addopts = -s --html=./report.htmltestpaths = ..python_files = test_*.pypython_classes = Test*

    总结

    Pytest 是一个强大的测试框架,支持灵活的配置和丰富的插件扩展。通过合理的测试用例编写和配置文件设置,可以实现高效的测试自动化。希望本文能为您的测试工作提供帮助,祝您测试顺利!

    转载地址:http://ynafk.baihongyu.com/

    你可能感兴趣的文章
    Pyinstaller:‘;Fiona‘;没有属性‘;_loading‘;(很可能是由于循环导入)
    查看>>
    pyinstaller:更改应用程序图标
    查看>>
    Pylint“未解决的导入“;Visual Studio 代码中的错误
    查看>>
    pyLoad远程代码执行漏洞复现(CVE-2023-0297)
    查看>>
    pymongo update_one(),upsert=True,不使用$运算符
    查看>>
    pymongo 中的快速或批量更新
    查看>>
    pymongo删除操作
    查看>>
    PyMongo按多个关键点分组
    查看>>
    Pympress:强大的双屏PDF阅读器
    查看>>
    pymysql.err.InternalError: (1054, "Unknown column '27D24A3B' in 'where clause'")之错误解决
    查看>>
    pymysql.err.OperationalError: (1364, “Field ‘id‘ doesn‘t have a default value“)
    查看>>
    Pytorch Tensor 维度操作的形象理解 Tensor.unsqueeze() Tensor.squeeze()
    查看>>
    PyMySQL库对Mysql数据库进行增删改查与工具类封装
    查看>>
    pynput的基本介绍和使用
    查看>>
    pyodbc 通过 IIS7 连接到 MSSQL 2005 服务器
    查看>>
    PyPI 存储库中的 JarkaStealer:深入解析与防范措施
    查看>>
    Pyplot tutorial,Pyplot官方教程自翻译
    查看>>
    PyQ5学习笔记——使用内部槽函数关闭窗口
    查看>>
    PyQ5学习笔记——使用自定义槽函数关闭窗口
    查看>>
    PyQt MimeData 文件名
    查看>>