Unittest Framework 简明教程

UnitTest Framework - Py.test Module

2004 年,Holger Krekel 将其 std 包重命名为“py”(仅略微没那么容易混淆),因为该名称经常与随 Python 一起提供的标准库混淆。尽管此包包含多个子包,但直到现在,它几乎完全以其 py.test 框架而闻名。

It was in 2004 that Holger Krekel renamed his std package, whose name was often confused with that of the Standard Library that ships with Python, to the (only slightly less confusing) name 'py.' Though the package contains several sub-packages, it is now known almost entirely for its py.test framework.

py.test 框架为 Python 测试制定了新的标准,如今已受到许多开发者的欢迎。它为编写测试而引入的优雅且具有 Pythonic 特性的习语使得测试套件可以使用更为简洁的风格编写。

The py.test framework has set up a new standard for Python testing, and has become very popular with many developers today. The elegant and Pythonic idioms it introduced for test writing have made it possible for test suites to be written in a far more compact style.

py.test 是 Python 标准 unittest 模块的无样板代码替代方案。它作为功能完备且可扩展的测试工具,其语法简洁。创建测试套件就像编写具有几个函数的模块一样简单。

py.test is a no-boilerplate alternative to Python’s standard unittest module. Despite being a fully-featured and extensible test tool, it boasts of a simple syntax. Creating a test suite is as easy as writing a module with a couple of functions.

py.test 可以在所有 POSIX 操作系统和 Windows (XP/7/8) 上运行,并支持 Python 2.6 及以上版本。

py.test runs on all POSIX operating systems and WINDOWS (XP/7/8) with Python versions 2.6 and above.

Installation

使用以下代码即可在当前 Python 分发中加载 pytest 模块以及 py.test.exe 实用程序。可以使用这两种方式运行测试。

Use the following code to load the pytest module in the current Python distribution as well as a py.test.exe utility. Tests can be run using both.

pip install pytest

Usage

你可以使用 assert 语句为测试期望提供断言。pytest 的断言内省将智能地报告 assert 表达式的中间值,从而使你无需学习 JUnit legacy methods 的许多名称。

You can simply use the assert statement for asserting test expectations. pytest’s assert introspection will intelligently report intermediate values of the assert expression freeing you from the need to learn the many names of JUnit legacy methods.

# content of test_sample.py
def func(x):
   return x + 1

def test_answer():
   assert func(3) == 5

使用以下命令行运行上述测试。运行测试后,将在控制台上显示以下结果

Use the following command line to run the above test. Once the test is run, the following result is displayed on console −

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 模块从命令行运行测试。

The test can also be run from the command line by including pytest module using –m switch.

python -m pytest test_sample.py

Grouping Multiple Tests in a Class

一旦开始拥有多个测试,通常可按逻辑将这些测试分组为类和模块。让我们编写一个包含两个测试的类

Once you start to have more than a few tests it often makes sense to group tests logically, in classes and modules. Let’s write a class containing two tests −

class TestClass:
   def test_one(self):
      x = "this"
      assert 'h' in x
   def test_two(self):
      x = "hello"
      assert hasattr(x, 'check')

将显示以下测试结果 −

The following test result will be displayed −

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 ======================