2004年,Holger Krekel将他的 std 软件包重命名为其名称经常与Python附带的标准库的名称混淆,而名称为'py'(仅略微混乱). "虽然软件包包含几个子软件包,但现在几乎完全知道它的py.test框架.
py.test框架为Python测试建立了一个新标准,并且今天已经成为很多开发人员的热门话题.它为测试编写引入的优雅和Pythonic成语使测试套件能够以更紧凑的方式编写.
py.test是Python标准的无需替代品的替代品unittest模块.尽管它是一个功能齐全且可扩展的测试工具,但它拥有简单的语法.创建测试套件就像编写具有几个函数的模块一样简单.
py.test在所有POSIX操作系统上运行,而WINDOWS(XP/7/8)在Python版本2.6上运行
使用以下代码在当前Python发行版中加载pytest模块以及py.test.exe实用程序.可以使用两者进行测试.
pip install pytest
您可以简单地使用assert语句来断言测试期望. pytest的断言内省将智能地报告断言表达式的中间值,使您无需学习 JUnit遗留方法的许多名称.
# content of test_sample.py def func(x): return x + 1 def test_answer(): assert func(3) == 5
使用以下命令行运行上述测试.运行测试后,控制台上显示以下结果 :
C:\Python27>scripts\py.test -v test_sample.py ============================= test session starts ===================== platform win32 -- Python 2.7.9, pytest-2.9.1, py-1.4.31, pluggy-0.3.1 -- C:\Pyth on27\python.exe cachedir: .cache rootdir: C:\Python27, inifile: collected 1 items test_sample.py::test_answer FAILED ================================== FAILURES ===================== _________________________________ test_answer _________________________________ def test_answer(): > assert func(3) == 5 E assert 4 == 5 E + where 4 = func(3) test_sample.py:7: AssertionError ========================== 1 failed in 0.05 seconds ====================
也可以通过使用-m开关包含pytest模块从命令行运行测试.
python -m pytest test_sample.py
一旦开始要进行多次测试,在类和模块中逻辑分组测试通常是有意义的.让我们写一个包含两个测试的类 :
class TestClass: def test_one(self): x = "this" assert 'h' in x def test_two(self): x = "hello" assert hasattr(x, 'check')
以下测试结果将显示:
C:\Python27>scripts\py.test -v test_class.py ============================= test session starts ===================== platform win32 -- Python 2.7.9, pytest-2.9.1, py-1.4.31, pluggy-0.3.1 -- C:\Pyt on27\python.exe cachedir: .cache rootdir: C:\Python27, inifile: collected 2 items test_class.py::TestClass::test_one PASSED test_class.py::TestClass::test_two FAILED ================================== FAILURES ===================== _____________________________ TestClass.test_two ______________________________ self = <test_class.TestClass instance at 0x01309DA0> def test_two(self): x = "hello" > assert hasattr(x, 'check') E assert hasattr('hello', 'check') test_class.py:7: AssertionError ===================== 1 failed, 1 passed in 0.06 seconds ======================