pytest --fixtures Python版本: Python 2.七、3.四、3.五、3.六、Jython、PyPy-2.3
平台:Unix / Posix和windows
pytest是一个使构建简单和使测试变得容易的框架。测试具备表达性和可读性——不是固定的代码。在几分钟内开始对应用程序或库进行小型单元测试或复杂的功能测试。
安装pytest
1.运行以下代码安装pytest:pip install -U pytest
2.检查您安装的版本是否正确:pytest --version
建立第一个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运行将执行当前目录及其子目录中全部格式为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更容易建立测试类
包含多个测试:
# -*- 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_前缀功能。 没有必要继承任何东西。 咱们能够经过传递文件名来运行模块:
第一次测试经过,第二次测试失败。 您能够在断言中轻松查看中间值以帮助您了解失败的缘由。
注意:测试结果中“.”表明成功,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 fixtures存在哪一种内哪些内置命令
继续阅读
查看其余pytest资源,以帮助您为本身独特的工做流程自定义测试:
•“经过python -m pytest调用pytest”用于命令行调用示例
•“将pytest与现有测试套件一块儿使用”以处理预先存在的测试
•“使用属性标记测试函数”以获取有关pytest.mark机制的信息
•“pytest fixture:显式,模块化,可扩展”,为您的测试提供功能基准
•“编写插件”,用于管理和编写插件
•virtualenv和测试布局的“良好集成实践”
pytest fixture 是pytest的高级功能,后面继续学习