此文已由作者吴琪惠授权网易云社区发布。

欢迎访问网易云社区,了解更多网易技术产品运营经验。

纯官网译文而已。。。

pytest是一个成熟的、全功能的python测试工具。

pytest框架编写测试用例时,小的用例会变得更容易编写,但对于复杂的应用或者库应该更谨慎选择。

特征:

1.断言失败之后具备详细的失败信息(不无需记住self.asseer*的名字)

2.自动失败测试模块和方法

3.模块化组件,可用于管理小的或者参数化长时间存活的测试资源

4.可以在box外运行uniitest和nose测试组件

5.支持Python2.6+, Python3.3+, PyPy-2.3, Jython-2.5 (未测试)

6.丰富的插件架构,拥有超过150+个外部插件和人气活动的论坛社区

安装:

支持的python版本:Python 2.6,2.7,3.3,3.4,3.5, Jython, PyPy-2.3

支持的平台:Unix/Posix ,Windows

Pypi连接:pytest

安装命令:

pip install -U pytest

检查安装结果:

$ pytest --version
This is pytest version 3.0.6, imported from $PYTHON_PREFIX/lib/python3.5/site-packages/pytest.py

第一次运行一个简单的例子:

# content of test_sample.pydef inc(x):return x + 1def test_answer():assert inc(3) == 5

运行结果:

$ pytest
======= test session starts ========
platform linux -- Python 3.5.2, pytest-3.0.6, py-1.4.33, pluggy-0.4.0rootdir: $REGENDOC_TMPDIR, inifile:
collected 1 itemstest_sample.py F======= FAILURES ========
_______ test_answer ________    def test_answer():>       assert inc(3) == 5E       assert 4 == 5E        +  where 4 = inc(3)test_sample.py:5: AssertionError
======= 1 failed in 0.12 seconds ========

上面的例子失败是因为func(3)不应该返回5,而是4

提示:你可以简单的使用 assert 语句来进行测试是否异常,pytest内置了详尽的断言,可只能的识别 assert表达式的中间项,你无需记住JUint那么多的传统方法

运行多个测试用例:

pytest会运行当前路径以及其子路径下的所有格式如 test_*.py 或者 *_test.py文件,通常遵循标准试验发现规则。

异常断言:

如果你想要assert一些抛出异常的代码,你可以使用raises,运行脚本,使用“quiet”静默模式(-q):

# content of test_sysexit.pyimport pytestdef f():raise SystemExit(1)def test_mytest():with pytest.raises(SystemExit):f()

运行结果:

$ pytest -q test_sysexit.py
.1 passed in 0.12 seconds

在一个类中分组用例:

实际场景中,会遇到一个类中或者一个模块下有一些逻辑上有关联的用例组,举个例子:

# content of test_class.pyclass TestClass:def test_one(self):x = "this"assert 'h' in xdef test_two(self):x = "hello"assert hasattr(x, 'check')

上面两个用例,没有子类,因此我们可以直接使用文件名来运行:

$ pytest -q test_class.py
.F
======= FAILURES ========
_______ TestClass.test_two ________self = <test_class.TestClass object at 0xdeadbeef>    def test_two(self):x = "hello">       assert hasattr(x, 'check')
E       assert FalseE        +  where False = hasattr('hello', 'check')test_class.py:8: AssertionError1 failed, 1 passed in 0.12 seconds

第一个用例passed,第二个failed,并且我们可以情况的看着断言中的一些中间值,帮助我们理解错误原因。

功能测试用例:生成唯一的临时目录

功能测试经常需要创建一些文件,并将其传递给应用程序对象。pytest提供 Builtin fixtures/function 参数允许请求任意资源,例如唯一的临时目录:

# content of test_tmpdir.pydef test_needsfiles(tmpdir):print (tmpdir)assert 0

在函数中打印了参数 tmpdir,pytest会在执行测试方法之前,查找和调用一个fixture factory来创建资源。运行例子:

$ pytest -q test_tmpdir.py
F
======= FAILURES ========
_______ test_needsfiles ________tmpdir = local('PYTEST_TMPDIR/test_needsfiles0')    def test_needsfiles(tmpdir):print (tmpdir)
>       assert 0E       assert 0test_tmpdir.py:3: AssertionError
--------------------------- Captured stdout call ---------------------------
PYTEST_TMPDIR/test_needsfiles01 failed in 0.12 seconds

在测试执行之前,一个 唯一的-单独的-测试-执行 临时路径被创建。

断言的前面的print内容也会打印出来,测试时可以多加print语句,保证异常时输出一些有用的信息。

以下命令可以看到更多的内置函数:

pytest --fixtures   # shows builtin and custom fixtures
E:\0WORKS\MyPytest>py.test --fixtures
============================= test session starts =============================
platform win32 -- Python 2.7.10, pytest-3.0.4, py-1.4.31, pluggy-0.4.0rootdir: E:\0WORKS\MyPytest, inifile:plugins: html-1.11.0, rerunfailures-2.1.0collected 1 items
cacheReturn a cache object that can persist state between testing sessions.cache.get(key, default)cache.set(key, value)Keys must be a ``/`` separated value, where the first part is usually thename of your plugin or application to avoid clashes with other cache users.Values can be any object handled by the json stdlib module.
capsysEnable capturing of writes to sys.stdout/sys.stderr and makecaptured output available via ``capsys.readouterr()`` method callswhich return a ``(out, err)`` tuple.
capfdEnable capturing of writes to file descriptors 1 and 2 and makecaptured output available via ``capfd.readouterr()`` method callswhich return a ``(out, err)`` tuple.
doctest_namespaceInject names into the doctest namespace.
pytestconfigthe pytest config object with access to command line opts.
record_xml_propertyAdd extra xml properties to the tag for the calling test.The fixture is callable with ``(name, value)``, with value being automatical
lyxml-encoded.
monkeypatchThe returned ``monkeypatch`` fixture provides thesehelper methods to modify objects, dictionaries or os.environ::monkeypatch.setattr(obj, name, value, raising=True)monkeypatch.delattr(obj, name, raising=True)monkeypatch.setitem(mapping, name, value)monkeypatch.delitem(obj, name, raising=True)monkeypatch.setenv(name, value, prepend=False)monkeypatch.delenv(name, value, raising=True)monkeypatch.syspath_prepend(path)monkeypatch.chdir(path)All modifications will be undone after the requestingtest function or fixture has finished. The ``raising``parameter determines if a KeyError or AttributeErrorwill be raised if the set/deletion operation has no target.
recwarnReturn a WarningsRecorder instance that provides these methods:* ``pop(category=None)``: return last warning matching the category.* ``clear()``: clear list of warningsSee http://docs.python.org/library/warnings.html for information    on warning categories.
tmpdir_factoryReturn a TempdirFactory instance for the test session.
tmpdirReturn a temporary directory path objectwhich is unique to each test function invocation,created as a sub directory of the base temporarydirectory.  The returned object is a `py.path.local`_path object.------------------ fixtures defined from pytest_html.plugin -------------------
environmentProvide environment details for HTML report======================== no tests ran in 0.21 seconds =========================

网易云免费体验馆,0成本体验20+款云产品!

更多网易技术、产品、运营经验分享请点击。

相关文章:
【推荐】 iOS 安装包瘦身 (上篇)
【推荐】 爬虫开发python工具包介绍 (2)
【推荐】 使用Phaser开发你的第一个H5游戏(一)

[翻译]pytest测试框架(一)相关推荐

  1. [翻译]pytest测试框架(二):使用

    此文已由作者吴琪惠授权网易云社区发布. 欢迎访问网易云社区,了解更多网易技术产品运营经验. 调用pytest 调用命令: python -m pytest [...] 上面的命令相当于在命令行直接调用 ...

  2. Pytest测试框架(二):pytest 的setup/teardown方法

    系列文章目录 Pytest测试框架(一):pytest安装及用例执行 Pytest测试框架(二):pytest 的setup/teardown方法 Pytest测试框架(三):pytest fixtu ...

  3. Python编程必不可少的pytest测试框架

    进行编程测试重要的是为了更高效的完成功能的实现. pytest是基于unittest实现的第三方测试框架,比 unittest 更加的简洁.高效,并且可以完美兼容 unittest 的测试代码,无需对 ...

  4. Pytest 测试框架——数据驱动

    引言 前面已经和大家介绍过 Unittest 测试框架的数据驱动框架 DDT,以及其实现原理.今天和大家分享的是 Pytest 测试框架的数据驱动,Pytest 测试框架的数据驱动是由 pytest ...

  5. Pytest测试框架(五):pytest + allure生成测试报告

    系列文章目录 Pytest测试框架(一):pytest安装及用例执行 Pytest测试框架(二):pytest 的setup/teardown方法 Pytest测试框架(三):pytest fixtu ...

  6. 5 分钟快速上手 pytest 测试框架

    本文将会把关于 Pytest 的内容分上下两篇,上篇主要涉及关于 pytest 概念以及功能组件知识的介绍,下篇主要以一个 Web 项目来将 Pytest 运用实践中. 为什么要做单元测试 相信很多 ...

  7. pytest测试框架_聊聊 Python 的单元测试框架(三):最火的 pytest

    本文首发于 HelloGitHub 公众号,并发表于 Prodesire 博客. 一.介绍 本篇文章是<聊聊 Python 的单元测试框架>的第三篇,前两篇分别介绍了标准库 unittes ...

  8. pytest测试框架4-插件与hook函数

    一.简介 pytest的自带功能很强大,通过添加插件可以扩展功能,pytest的代码结构适合定制和扩展插件, 可以借助hook函数来实现. 把fixture函数或者hook函数添加到conftest文 ...

  9. Pytest测试框架的基本使用和allure测试报告

    一.测试用例的识别与运行 目录识别 通过pytest.ini配置文件配置 如果未指定任何参数,则收集从testpaths(如已配置)或当前目录开始.另外,命令行参数可以在目录.文件名或节点ID的任何组 ...

最新文章

  1. FreeMarker基本语法详解及模板文件的组成(二)
  2. mysql5.7 rmp_linux MySQL5.7 rpm安装(转)
  3. python是软件吗-python运行环境是什么
  4. 获取NT的admin权限的方法
  5. 1356. 回文质数【难度: 中 / 数学】
  6. 初中计算机学情分析,初中信息技术教学计划
  7. leetcode 633. 平方数之和(双指针)
  8. python字符串随机排序_python 随机数使用方法,推导以及字符串,双色球小程序实例...
  9. 关于ASPNET_Membership用户被锁的解决
  10. vba自动生成html,动态生成嵌入在VBA电子邮件生成中的HTML表
  11. 微正指纹识别算法MZFinger5.0
  12. gif透明背景动画_软件|电脑GIF录制软件,强烈推荐!
  13. Java下载服务器文件
  14. 在校招中,应届生们如何写出简洁的 Android 开发简历,减少被刷的机率
  15. Python进行各项统计检验
  16. 下载新浪android SDK
  17. 天蝎项目整机柜服务器技术规格,天蝎项目整机柜服务器技术规范v1.01天蝎项目整机柜服务器技术规范v1.01.pdf...
  18. 微服务网关搭建(podman+kong+konga)
  19. 网络图像的文本识别(阿里天池竞赛)
  20. 笔记:中国大学MOOC课程《程序设计入门——C语言》编程练习

热门文章

  1. Python中面向对象的讲解(1)
  2. 用HTML制作一个漂亮的成绩表,JS-结合html综合练习js的对象——班级成绩表制作...
  3. php 上万关键字匹配,JavaScript 上万关键字瞬间匹配实现代码
  4. java log4j 多个文件_为什么log4j会记录到两个单独的文件? [重复]
  5. java 三角依次递增在递减_java中用for循环怎样打印三角行啊,主要是不理解什么情况外层循环递增什么时候递减,如等腰三角形...
  6. springboot获取原生js请求_七节课带你学会SpringBoot,第三课
  7. python重复import_Python module重复载入的问题
  8. 基于局部均方差相关信息的图像去噪及其在实时磨皮美容算法中的应用
  9. 【AI学院】新手如何学CV?老司机带学有三书籍《深度学习之图像识别》,赠书8本...
  10. 【GAN优化】从动力学视角看GAN是一种什么感觉?