首先,先介绍一下pytest
pytest是一个非常成熟的Python框架,主要用于测试,比较简单灵活,非常容易上手,而且文档和相关博客也有很多
学习途径
官方文档和技术博客
首先安装
pip install -U pytest
创建第一个测试实例
# coding=utf-8
def func(x):
return x + 1
def test_answer():
assert func(3) == 5
显而易见,这样的函数调用是错误的
开始测试
# 在命令行中键入pytest,就会得到如下的结果
========================================================== FAILURES ==========================================================
________________________________________________________ test_answer _________________________________________________________
def test_answer():
> assert func(3) == 5
E assert 4 == 5
E + where 4 = func(3)
first_test.py:7: AssertionError
================================================== 1 failed in 0.05 seconds ==================================================
如何运行多个测试
pytest将在当前目录及其子目录中运行test_.py或_test.py形式的所有文件.更一般地,它遵循标准测试发现规则
使用raises帮助程序断言某些代码引发异常
# content of test_sysexit.py
# coding=utf-8
import pytest
def f():
raise SystemExit(1)
def test_mytest():
with pytest.raises(SystemExit):
f()
使用安静报告模式执行测试功能
(venv) ➜ pytest_zzz pytest -q second_test.py
. [100%]
1 passed in 0.01 seconds
在类中组合多个测试
一旦开发了多个测试,我们可能会希望将它们分组到一个类中,实现封装的功能.Pytest可以很容易地创建一个包含多个测试的类
class TestClass:
def test_one(self):
x = "this"
assert "h" in x
def test_two(self):
x = "hello"
assert hasattr(x, "check")
pytest发现遵循其Python测试发现约定的所有测试,因此它找到两个test_前缀函数.没有必要继承任何东西.我们可以通过传递文件名来运行模块:
_____________________________________________________ TestClass.test_two _____________________________________________________
self = <third_test.TestClass instance at 0x10674d758>
def test_two(self):
x = 'hello'
> assert hasattr(x,'check')
E AssertionError: assert False
E + where False = hasattr('hello', 'check')
third_test.py:8: AssertionError
1 failed, 1 passed in 0.20 seconds
在我们封装的类中,第一次测试通过,而第二次的测试失败,我们可以在断言中查看中间值,这可以用来帮助我们了解失败的原因
请求功能测试的唯一临时目录
pytest 提供Builtin fixture/function参数来请求任意资源,比如说一个唯一的临时目录:
def test_needsfiles(tmpdir):
print(tmpdir)
assert 0
列出tmpdir
测试函数签名中的名称,并且在pytest
在执行测试函数调用之前查找并调用fixture工厂以创建资源.在测试运行之前,pytest
创建一个unique-per-test-invocation临时目录:
______________________________________________________ test_needsfiles _______________________________________________________
tmpdir = local('/private/var/folders/63/80c6t46d63z_8p5c78nsq38r0000gn/T/pytest-of-admin/pytest-0/test_needsfiles0')
def test_needsfiles(tmpdir):
print tmpdir
> assert 0
E assert 0
fourth_test.py:3: AssertionError
---------------------------------------------------- Captured stdout call ----------------------------------------------------
/private/var/folders/63/80c6t46d63z_8p5c78nsq38r0000gn/T/pytest-of-admin/pytest-0/test_needsfiles0
1 failed in 0.20 seconds