我的建议是使用Python提供了单元测试的两个框架的一个重构代码:单元测试(又名PyUnit中)和文档测试。
这是使用一个例子单元测试:
import unittest
def adder(a, b):
"Return the sum of two numbers as int"
return int(a) + int(b)
class TestAdder(unittest.TestCase):
"Testing adder() with two int"
def test_adder_int(self):
self.assertEqual(adder(2,3), 5)
"Testing adder() with two float"
def test_adder_float(self):
self.assertEqual(adder(2.0, 3.0), 5)
"Testing adder() with two str - lucky case"
def test_adder_str_lucky(self):
self.assertEqual(adder('4', '1'), 5)
"Testing adder() with two str"
def test_adder_str(self):
self.assertRaises(ValueError, adder, 'x', 'y')
if __name__ == '__main__':
unittest.main()
而这是使用文档测试一个例子:
# adder.py
def main(a, b):
"""This program calculate the sum of two numbers.
It prints an int (see %d in print())
>>> main(2, 3)
The sum is 5
>>> main(3, 2)
The sum is 5
>>> main(2.0, 3)
The sum is 5
>>> main(2.0, 3.0)
The sum is 5
>>> main('2', '3')
Traceback (most recent call last):
...
TypeError: %d format: a number is required, not str
"""
c = a + b
print("The sum is %d" % c)
def _test():
import doctest, adder
return doctest.testmod(adder)
if __name__ == '__main__':
_test()
随着文档测试我使用输入由另一个例子中()(我假设你正在使用Python 3。X):
# adder_ugly.py
def main():
"""This program calculate the sum of two numbers.
It prints an int (see %d in print())
>>> main()
The sum is 5
"""
a = int(input("Enter an integer: "))
b = int(input("Enter another integer: "))
c = a+b
print("The sum is %d" % c)
def _test():
import doctest, adder_ugly
return doctest.testmod(adder_ugly)
if __name__ == '__main__':
_test()
我会跑各的上述与-v
选项的例子:
python adder_ugly.py -v
供您参考看到:
http://docs.python.org/py3k/library/unittest.html?highlight=unittest#unittest
和
http://docs.python.org/py3k/library/doctest.html#module-doctest
两条输入行缺少右括号。 – Javier 2011-02-28 14:54:55
@Javier:固定。谢谢,有人编辑了我的问题,并添加了`eval(`但没有关闭另一边。 – Jason 2011-03-05 20:12:22