Doctests 是一个很好的建议,但如果你想接近你的示例代码,我建议使用 py.test (pytest.org)。你的例子会写成这样:
def f(x):
return x+2
def test_equal(): # py.test looks for functions that start with test_
assert f(3) == 5
如果我把它放在一个名为 tt.py 的文件中并用 py.test 运行它,它看起来像这样:
w:\tmp>py.test tt.py
============================= test session starts =============================
platform win32 -- Python 2.6.6 -- pytest-2.2.3
collected 1 items
tt.py .
========================== 1 passed in 0.01 seconds ===========================
如果我将断言更改为 f(3) == 6,然后再次运行它,我会得到:
w:\tmp>py.test tt.py
============================= test session starts =============================
platform win32 -- Python 2.6.6 -- pytest-2.2.3
collected 1 items
tt.py F
================================== FAILURES ===================================
_________________________________ test_equal __________________________________
def test_equal(): # py.test looks for functions that start with test_
> assert f(3) == 6
E assert 5 == 6
E + where 5 = f(3)
tt.py:5: AssertionError
========================== 1 failed in 0.01 seconds ===========================
py.test 也可以扩展,你可以让它运行覆盖率,在多个 CPU 上分发测试等。它还可以找到并运行 unittest 测试,还可以运行 doctests。