我的建议是使用 Python 为单元测试提供的两个框架之一重构您的代码:unittest(又名 PyUnit)和doctest。
这是使用unittest的示例:
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()
这是使用doctest的示例:
# 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()
使用doctest,我使用 input() 做了另一个示例(我假设您使用的是 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