平台:Unix / Posix和windows

PyPI包名称:pytest

依赖性:py,colorama模块(Windows),

文档如PDF:下载最新

pytest是一个使构建简单和使测试变得容易的框架。测试具有表达性和可读性——不是固定的代码。在几分钟内开始对应用程序或库进行小型单元测试或复杂的功能测试。

安装pytest

1.运行如下代码安装pytest:pip install -U pytest 

2.检查您安装的版本是否正确:pytest --version

pytest 国内镜像 pytest安装_Python

创建第一个pytest测试程序

下面用四行代码创建一个简单的测试函数

# -*- coding: utf-8 -*-
# @Time    : 2018/7/5 23:57
# @Author  : onesilent
# @File    : FirstTest.py
# @Project : PythonTestDemo
# content of test_sample.py
def func(x):
    return x + 1
def test_answer():
    assert func(3) == 5

 

 

 

 

 

执行结果如下(注释:相当于在命令行窗口在当前包下执行pytest,注意:测试文件和测试函数都是以"test_"开头,test可忽略大小写,即可以写成Test)

pytest 国内镜像 pytest安装_pytest 国内镜像_02

注意:您可以使用assert语句来验证测试期望。pytest的高级断言内省将会智能地报告assert表达式的中间值,这样您就可以避免unittest遗留的许多名称方法。

 

运行多个测试

pytest运行将执行当前目录及其子目录中所有格式为test_*.py或* _test.py在的py的文件,通俗的说,它遵循探索测试规则。

断言某些代码引发的异常

使用raises帮助程序断言某些代码引发的异常:(使用断言捕获程序异常,pytest -q 是静默执行,加入-q打印的信息会少,下图展示静默执行与非静默执行)

# -*- coding: utf-8 -*-
# @Time    : 2018/7/10 23:29
# @Author  : onesilent
# @File    : test_sysexit.py
# @Project : PythonTestDemo

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

pytest 国内镜像 pytest安装_Time_03

 

在一个类中组合多个测试

一旦开发了多个测试,您可能希望将它们分组到一个类中。 使用pytest更容易创建测试类

包含多个测试:

# -*- coding: utf-8 -*-
# @Time    : 2018/7/11 0:00
# @Author  : onesilent
# @File    : test_class.py
# @Project : PythonTestDemo
# content of test_class.py
class TestClass(object):
    def test_one(self):
        x = "this"
        assert 'h' in x
    def test_two(self):
        x = "hello"
        assert hasattr(x, 'check')

 

pytest在其Python测试发现约定之后发现所有测试,因此它发现两个test_前缀功能。 没有必要继承任何东西。 我们可以通过传递文件名来运行模块:

pytest 国内镜像 pytest安装_Time_04

 

第一次测试通过,第二次测试失败。 您可以在断言中轻松查看中间值以帮助您了解失败的原因。

注意:测试结果中“.”代表成功,F代表失败

 

通过请求唯一临时目录完成功能测试

pytest提供了Builtin fixture / function参数来请求任意资源,比如一个唯一的临时目录:

一下函数执行的tmpdir的默认目录:C:\Users\onesilent\AppData\Local\Temp\pytest-of-onesilent\pytest-1\test_needsfiles0

# -*- coding: utf-8 -*-
# @Time    : 2018/7/11 23:57
# @Author  : onesilent
# @File    : test_tmpdir.py
# @Project : PythonTestDemo

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

 

pytest 国内镜像 pytest安装_pytest 国内镜像_05

 

找出pytest fixtures存在哪种内哪些内置命令

 

pytest --fixtures #此命令显示内置命令和custom fixtures 请注意,除非添加-v选项,否则此命令将省略带有前导_的 fixtures。

 

pytest 国内镜像 pytest安装_Time_06