安装及入门
Python支持版本: Python 2.6,2.7,3.3,3.4,3.5,Jython,PyPy-2.3
支持的平台: Unix/Posix and Windows
PyPI包名: pytest
依赖项: py,colorama (Windows)
创建你的第一个测试用例
只需要4行代码即可创建一个简单的测试用例:
# test_sample.py文件内容
def func(x):
return x + 1
def test_answer():
assert func(3) == 5
现在你可以执行一下这个测试用例:
$ pytest
=========================== test session starts ============================
platform linux -- Python 3.x.y,pytest-3.x.y,py-1.x.y,pluggy-0.x.y
rootdir: $REGENDOC_TMPDIR,inifile:
collected 1 item
test_sample.py F [100%]
================================= FAILURES =================================
_______________________________ test_answer ________________________________
def test_answer():
> assert func(3) == 5
E assert 4 == 5
E + where 4 = func(3)
test_sample.py:5: AssertionError
========================= 1 failed in 0.12 seconds =========================
执行多条测试用例
pytest
命令会执行当前目录及子目录下所有test_*.py
及*_test.py
格式的文件。一般来说,用例需要遵循标准的测试发现规则。
断言抛出了指定异常
使用raise
可以在相应代码的抛出的指定异常:
# test_sysexit.py文件内容
import pytest
def f():
raise SystemExit(1)
def test_mytest():
with pytest.raises(SystemExit):
f()
使用类组织多条测试用例
# 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 -q test_class.py 运行该命令