1. 程式人生 > >python單元測試-unittest

python單元測試-unittest

main 工作 應用 rec recent rtg 測試的 開頭 詳細信息

python內部自帶了一個單元測試的模塊,pyUnit也就是我們說的:unittest

1、介紹下unittest的基本使用方法:

1)import unittest

2)定義一個繼承自unittest.TestCase的測試用例類

3)定義setUp和tearDown,在每個測試用例前後做一些輔助工作。

4)定義測試用例,名字以test開頭。

5)一個測試用例應該只測試一個方面,測試目的和測試內容應很明確。主要是調用assertEqual、assertRaises等斷言方法判斷程序執行結果和預期值是否相符。

6)調用unittest.main()啟動測試

7)如果測試未通過,會輸出相應的錯誤提示。如果測試全部通過則不顯示任何東西,這時可以添加-v參數顯示詳細信息。

2、 下面是unittest模塊的常用方法:

assertEqual(a, b) a == b

assertNotEqual(a, b) a != b

assertTrue(x) bool(x) is True

assertFalse(x) bool(x) is False

assertIs(a, b) a is b 2.7

assertIsNot(a, b) a is not b 2.7

assertIsNone(x) x is None 2.7

assertIsNotNone(x) x is not None 2.7

assertIn(a, b) a in b 2.7

assertNotIn(a, b) a not in b 2.7

assertIsInstance(a, b) isinstance(a, b) 2.7

assertNotIsInstance(a, b) not isinstance(a, b) 2.7

下面看具體的代碼應用:

首先寫了一個簡單應用:

import random

import unittest

class TestSequenceFunctions(unittest.TestCase):

def setUp(self):

self.seq = range(10)

def test_shuffle(self):

# make sure the shuffled sequence does not lose any elements

random.shuffle(self.seq)

self.seq.sort()

self.assertEqual(self.seq, range(10))

# should raise an exception for an immutable sequence

self.assertRaises(TypeError, random.shuffle, (1,2,3))

def test_choice(self):
element = random.choice(self.seq)

self.assertTrue(element inself.seq)

def test_error(self):

element = random.choice(self.seq)

self.assertTrue(element not in self.seq)

if __name__ == ‘__main__‘:

unittest.main()

下面是寫了一個簡單的應用,測試下面4個網址返回的狀態碼是否是200。

import unittest
import urllib

class TestUrlHttpcode(unittest.TestCase):
def setUp(self):
urlinfo = [‘http://www.baidu.com‘,‘http://www.163.com‘,‘http://www.sohu.com‘,‘http://www.cnpythoner.com‘]
self.checkurl = urlinfo

def test_ok(self):
for m in self.checkurl:
httpcode = urllib.urlopen(m).getcode()
self.assertEqual(httpcode,200)

if __name__ == ‘__main__‘:
unittest.main()

如果有的網址打不開,返回404的話,測試則會報錯

如果有的網址打不開,返回404的話,測試則會報錯

ERROR: test_ok (__main__.TestUrlHttpcode)
----------------------------------------------------------------------
Traceback (most recent call last):
File "jay.py", line 12, in test_ok
httpcode = urllib.urlopen(m).getcode()
File "/usr/lib/python2.7/urllib.py", line 86, in urlopen
return opener.open(url)
File "/usr/lib/python2.7/urllib.py", line 207, in open
return getattr(self, name)(url)
File "/usr/lib/python2.7/urllib.py", line 462, in open_file
return self.open_local_file(url)
File "/usr/lib/python2.7/urllib.py", line 476, in open_local_file
raise IOError(e.errno, e.strerror, e.filename)
IOError: [Errno 2] No such file or directory: ‘fewfe.com‘

----------------------------------------------------------------------
Ran 1 test in 1.425s

FAILED (errors=1)

3也有其他的unittest方法,用於執行更具體的檢查,如:

Method Checks that New in
assertAlmostEqual(a, b) round(a-b, 7) == 0
assertNotAlmostEqual(a, b) round(a-b, 7) != 0
assertGreater(a, b) a > b 2.7
assertGreaterEqual(a, b) a >= b 2.7
assertLess(a, b) a < b 2.7
assertLessEqual(a, b) a <= b 2.7
assertRegexpMatches(s, re) regex.search(s) 2.7
assertNotRegexpMatches(s, re) not regex.search(s) 2.7
assertItemsEqual(a, b) sorted(a) == sorted(b) and works with unhashable objs 2.7
assertDictContainsSubset(a, b) all the key/value pairs in a exist in b 2.7
assertMultiLineEqual(a, b) strings 2.7
assertSequenceEqual(a, b) sequences 2.7
assertListEqual(a, b) lists 2.7
assertTupleEqual(a, b) tuples 2.7
assertSetEqual(a, b) sets or frozensets 2.7
assertDictEqual(a, b) dicts 2.7
assertMultiLineEqual(a, b) strings 2.7
assertSequenceEqual(a, b) sequences 2.7
assertListEqual(a, b) lists 2.7
assertTupleEqual(a, b) tuples 2.7
assertSetEqual(a, b) sets or frozensets 2.7
assertDictEqual(a, b) dicts 2.7

通過以上介紹的unittest模塊方法,我們可以根據實際情況來設計自己的單元測試。

python單元測試-unittest