我正在考虑使用Python来教授入门编程,我正在寻找一个轻量级的单元测试框架.我已经看到了在单元测试,以及-据我可以告诉-它看起来出奇的非 -lightweight.
例如,这是我想要写的内容:
import unittest
def f(x):
return x+2
checkEqual(f(3),5)
Run Code Online (Sandbox Code Playgroud)
...... 别无其他.为了告诉你我来自哪里,这就是我用Racket开始的学生语言写的:
(define (f x)
(+ x 2))
(check-expect (f 3) 5)
Run Code Online (Sandbox Code Playgroud)
......就是这样.当然有人写了这个工具,我只是没找到它?
(对任何火焰诱饵的出现都要提前道歉.这是一个严肃的问题.)
自编辑:
在任何人指出这一点之前:是的,我可以写def checkEqual(a,b):print(a == b); 我正在寻找更多的东西:它应该能够检查带有容差的数字,它应该支持仅打印失败的测试用例,它应该能够告诉你有多少测试用例失败了.再次,我相信这段代码可以写出来; 我只是想避免重新发明轮子.
我会推荐Doctest.
你的例子看起来像:
def f(x):
"""
>>> f(3)
5
"""
return x + 2
Run Code Online (Sandbox Code Playgroud)
为什么?:
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
Run Code Online (Sandbox Code Playgroud)
如果我将其放入名为 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 ===========================
Run Code Online (Sandbox Code Playgroud)
如果我将断言更改为 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 ===========================
Run Code Online (Sandbox Code Playgroud)
py.test 还可以扩展,您可以让它运行覆盖范围、在多个 CPU 上分发测试等。它还可以查找并运行单元测试测试,还可以运行文档测试。