单元测试框架 - Py.test 模块


2004 年,Holger Krekel 将他的std包(其名称经常与 Python 附带的标准库的名称混淆)重命名为“py”(只是稍微不那么容易混淆)。尽管该包包含多个子包,但现在几乎完全因其 py.test 框架而闻名。

py.test 框架为 Python 测试建立了新的标准,并且在当今受到许多开发人员的欢迎。它为测试编写引入了优雅且Pythonic的习惯用法,使得以更紧凑的风格编写测试套件成为可能。

py.test 是 Python 标准单元测试模块的无样板替代品。尽管它是一个功能齐全且可扩展的测试工具,但它拥有简单的语法。创建测试套件就像编写具有几个函数的模块一样简单。

py.test 可在所有 POSIX 操作系统和 WINDOWS (XP/7/8) 上运行,Python 版本为 2.6 及更高版本。

安装

使用以下代码加载当前 Python 发行版中的 pytest 模块以及 py.test.exe 实用程序。可以使用两者来运行测试。

pip install pytest

用法

您可以简单地使用断言语句来断言测试期望。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 ======================