博客
关于我
pytest框架快速入门-pytest运行时参数说明,pytest详解,pytest.ini详解
阅读量:803 次
发布时间: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/

    你可能感兴趣的文章
    pytest-xdist:远程多主机 - 分布式运行自动化测试
    查看>>
    Pytest中进行测试环境切换:pytest_addoption!
    查看>>
    pytest利用request fixture实现个性化测试需求详解
    查看>>
    pytest单元测试实战
    查看>>
    pytest单元测试框架
    查看>>
    Pytest参数详解 — 基于命令行模式
    查看>>
    pytorch cv2 plt transforms pause waitforbuttonpress一个完整的图片处理程序
    查看>>
    pytest学习和使用 - Pytest用例执行结果有哪几种状态?
    查看>>
    pytest实战技巧之参数化应用!
    查看>>
    Pytest实践:Python测试技术基础知识!
    查看>>
    Pytest数据驱动怎么玩?实战教程来了!
    查看>>
    Pytest框架 之【用例执行顺序】
    查看>>
    Pytest框架中的测试用例执行方式!
    查看>>
    pytest框架快速入门-pytest运行时参数说明,pytest详解,pytest.ini详解
    查看>>
    Pytest框架环境切换实战教程!赶快收藏
    查看>>
    Pytest测试实战|Conftest.py详解
    查看>>
    Pytest测试框架快速搭建
    查看>>
    pytest测试框架:最强大的自动化测试工具,让测试变得轻松有趣
    查看>>
    pytest简介及jenkins集成
    查看>>
    Pytest自动化框架运行全局配置文件pytest.ini
    查看>>