我的建議是使用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