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

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

纯官网译文而已。。。

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 items test_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 x     def 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
cache
    Return 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 the
    name of your plugin or application to avoid clashes with other cache users.     Values can be any object handled by the json stdlib module.
capsys
    Enable capturing of writes to sys.stdout/sys.stderr and make
    captured output available via ``capsys.readouterr()`` method calls
    which return a ``(out, err)`` tuple.
capfd
    Enable capturing of writes to file descriptors 1 and 2 and make
    captured output available via ``capfd.readouterr()`` method calls
    which return a ``(out, err)`` tuple.
doctest_namespace
    Inject names into the doctest namespace.
pytestconfig
    the pytest config object with access to command line opts.
record_xml_property
    Add extra xml properties to the tag for the calling test.
    The fixture is callable with ``(name, value)``, with value being automatical
ly
    xml-encoded.
monkeypatch
    The returned ``monkeypatch`` fixture provides these
    helper 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 requesting
    test function or fixture has finished. The ``raising``
    parameter determines if a KeyError or AttributeError
    will be raised if the set/deletion operation has no target.
recwarn
    Return a WarningsRecorder instance that provides these methods:     * ``pop(category=None)``: return last warning matching the category.
    * ``clear()``: clear list of warnings     See http://docs.python.org/library/warnings.html for information    on warning categories.
tmpdir_factory
    Return a TempdirFactory instance for the test session.
tmpdir
    Return a temporary directory path object
    which is unique to each test function invocation,
    created as a sub directory of the base temporary
    directory.  The returned object is a `py.path.local`_
    path object. ------------------ fixtures defined from pytest_html.plugin -------------------
environment
    Provide environment details for HTML report ======================== no tests ran in 0.21 seconds =========================

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

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

相关文章:
【推荐】 Kubernetes在网易云中的落地优化实践

[翻译]pytest测试框架(一)的更多相关文章

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

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

  2. pytest测试框架 -- 简介

    一.pytest测试框架简介: (1)pytest是python的第三方测试框架,是基于unittest的扩展框架,比unittest更简洁,更高效. (2)pytest框架可以兼容unittest用 ...

  3. Pytest测试框架(一):pytest安装及用例执行

    PyTest是基于Python的开源测试框架,语法简单易用,有大量的插件,功能非常多.自动检测测试用例,支持参数化,跳过特定用例,失败重试等功能. 安装 pip install -U pytest  ...

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

    PyTest支持xUnit style 结构, setup() 和 teardown() 方法用于初始化和清理测试环境,可以保证测试用例的独立性.pytest的setup/teardown方法包括:模 ...

  5. Pytest测试框架(三):pytest fixture 用法

    xUnit style 结构的 fixture用于初始化测试函数, pytest fixture是对传统的 xUnit 架构的setup/teardown功能的改进.pytest fixture为测试 ...

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

    Allure 是一款轻量级.支持多语言的开源自动化测试报告生成框架,由Java语言开发,可以集成到 Jenkins. pytest 测试框架支持Allure 报告生成. pytest也可以生成juni ...

  7. 『德不孤』Pytest框架 — 1、Pytest测试框架介绍

    目录 1.什么是单元测试框架 2.单元测试框架主要做什么 3.单元测试框架和自动化测试框架有什么关系 4.Pytest测试框架说明 5.Pytest框架和Unittest框架区别 (1)Unittes ...

  8. python pytest测试框架介绍二

    在介绍一中简单介绍了pytest的安装和简单使用,接下来我们就要实际了解pytest了 一.pytest的用例发现规则 pytest可以在不同的函数.包中发现用例,发现的规则如下 文件名以test_开 ...

  9. Pytest 测试框架

    一 . Pytest 简介 Pytest是python的一种单元测试框架. 1. pytest 特点 入门简单,文档丰富 支持单元测试,功能测试 支持参数化,重复执行,部分执行,测试跳过 兼容其他测试 ...

随机推荐

  1. views中class定义(类的写法)CBV

    from django.views import View class Home(View): def dispatch(self, request, *args, **kwargs): print( ...

  2. delphi datasnap

    http://blog.csdn.net/shuaihj/article/details/6129121 http://blog.csdn.net/ddqqyy/article/details/617 ...

  3. FullBg-网页图片背景自适应大小

      网页背景自适应大小jQuery插件 fullBG.js http://cbavota.bitbucket.org/fullbg/ HTML <img id="background& ...

  4. jboss & eclipse 集成

    * 前提:       * 安装了 eclipse-jee-3.5.1       * 解压了 jboss5.1       * * "jboss tools" - "J ...

  5. 迷你MVVM框架 avalonjs 学习教程2、模块化、ViewModel、作用域

    一个项目是由许多人分工写的,因此必须要合理地拆散,于是有了模块化.体现在工作上,PM通常它这为某某版块,某某频道,某某页面.某一个模块,必须是包含其固有的数据,样式,HTML与处理逻辑.在jQuery ...

  6. Win7删除远程连接历史记录

    打开注册表,找到 HKEY_CURRENT_USER\Software\Microsoft\Terminal Server Client\Default 删除右侧的 MRUn(n是索引号) 项 即可.

  7. LevelDB 写入与删除记录

    [LevelDB 写入与删除记录] levelDb的记录更新操作,即插入一条KV记录或者删除一条KV记录.levelDb的更新操作速度是非常快的,源于其内部机制决定了这种更新操作的简单性. 图6.1是 ...

  8. node.js中的匿名函数, 回调函数和嵌套函数

    定义一个函数相信大家已经很熟悉了, 在javascript里的函数也是非常重要的, 使用率非常高, 有几种函数不是很好理解 一, 匿名函数 var remove = function(num1) { ...

  9. DropDownList控件的使用方法

    1. 使用代码添加数据 <asp:DropDownList ID="DropDownList1" runat="server"> </asp: ...

  10. PHP ImageMagick

    简介:       ImageMagick是用C语言开发图片处理程序.可以对图片进行改变大小.旋转.锐化.减色或增加特效等操作.对图片的操作,即可以通过命令行进行,也可以用C/C++.Perl.Jav ...