python中的單元測試可以使用doctest,unittest完成
1.doctest的使用
(1)寫入程式如下(cubetest.py):
#!/usr/bin/pythondef cube(x):"""cube a number and return the result>>> cube(2)8>>> cube(3)27>>> cube(4)64"""return x**3;if __name__=='__main__':import doctest;doctest.testmod(verbose=True);
測試案例寫在字串””” cube a number… “””中。
調用doctest中的testmod的方法即可測試。
輸出如下:
Trying:
cube(2)
Expecting:
8
ok
Trying:
cube(3)
Expecting:
27
ok
Trying:
cube(4)
Expecting:
64
ok
1 itemshad no tests:
__main__
1 itemspassed all tests:
3 tests in __main__.cube
3 testsin 2 items.
3 passedand 0 failed.
Testpassed.
TestResults(failed=0, attempted=3)
(2)也可以把測試案例寫在記事本檔案中。建立記事本example.txt,寫入以下內容:
>>> from cubetest import cube
>>> cube(1)
1
>>> cube(2)
8
>>> cube(4)
64
然後寫測試代碼 test.py:
import doctestdoctest.testfile("example.txt")
使用python test.py –v 執行測試代碼,可以得到以下結果
Trying:
from cubetest import cube
Expectingnothing
ok
Trying:
cube(1)
Expecting:
1
ok
Trying:
cube(2)
Expecting:
8
ok
Trying:
cube(4)
Expecting:
64
ok
1 items passedall tests:
4 tests in example.txt
4 tests in 1items.
4 passed and 0failed.
Test passed.
2.unittest的使用
(1)寫待測試的程式如下:
def iseven(x):if(x%2==0):return 1;else:return 0;def isodd(x):if(x%2==1):return 1;else:return 0;
測試程式中的類eventest類繼承自TestCase,它包含setUp() ,test_1(),test_2()和tearDown()四個方法。在測試回合前,會自動運行setUp()方法,在測試完成之前,會自動調用tearDown()方法。test_1()和test_2()是自訂的測試方法。寫測試程式如下:
import unittest,evenoddclass eventest(unittest.TestCase):def setUp(self):self.ex1=range(0,2,20);self.ex2=range(1,2,20);def test_1(self):for x in self.ex1:x=evenodd.iseven(x);self.assertEqual(x,1);for x in self.ex2:x=evenodd.iseven(x);self.assertEqual(x,0);def test_2(self):for x in self.ex1:x=evenodd.isodd(x);self.assertEqual(x,0);for x in self.ex2:x=evenodd.isodd(x);self.assertEqual(x,1);def tearDown(self):self.ex1=None;self.ex2=None;if __name__=='__main__':unittest.main();
上面用到了self.AssertEqual(),類似的判斷方法還有:
assertNotEqual(a,b) a!=b
asserTrue(x) bool(x)為真
assertFalse(x) bool(x)為假
assertIs(a,b) a is b
assertIsNot(a,b) a is not b
assertIsNone(x) x is None
assertIsNotNone(x) x is not None
assertIn (a,b) a in b
assertNotIn(a,b) a not in b
assertIsInstance(a,b) isinstance(a,b)
assertNotIsInstance(a,b) not instance(a,b)
(2) 也可以使用TestSuite對測試案例進行封裝,下面的程式定義了類evensuite,它繼承自類TestSuite,方法addTest()用於添加測試方法。
測試程式如下:
import unittest,evenoddclass eventest(unittest.TestCase):def setUp(self):self.ex1=range(0,2,20);self.ex2=range(1,2,20);def test_1(self):for x in self.ex1:x=evenodd.iseven(x);self.assertEqual(x,1);for x in self.ex2:x=evenodd.iseven(x);self.assertEqual(x,0);def test_2(self):for x in self.ex1:x=evenodd.isodd(x);self.assertEqual(x,0);for x in self.ex2:x=evenodd.isodd(x);self.assertEqual(x,1);def tearDown(self):self.ex1=None;self.ex2=None;class evensuite(unittest.TestSuite):def suite(self):suite=unittest.TestSuite();suite.addTest(eventest('test_1'));suite.addTest(eventest('test_2'));return suite;if __name__=='__main__':unittest.main();
運行程式 ,結果輸出:
_ _
ran 2 tests in 0.001s
OK