python---unittest用法

python--unittest用法

下面是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

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以及要測試的函數,再創建一個繼承unittest.TestCase的類,並編寫一系列方法對函數行爲的不同方面進行測試。我們使用了unittest類最有用的功能之一:一個斷言方法。斷言方法用來覈實得到 的結果是否與期望的結果一致下面就是一個小例子!

練習:

11-1 城市和國家:編寫一個函數,它接受兩個形參:一個城市名和一個國家名。這 個函數返回一個格式爲 City, Country 的字符串,如 Santiago, Chile。將這個函數存儲 在一個名爲 city _functions.py的模塊中。 創建一個名爲 test_cities.py的程序,對剛編寫的函數進行測試(別忘了,你需要導 入模塊 unittest 以及要測試的函數)。編寫一個名爲 test_city_country()的方法,覈實使用類似於'santiago'和'chile'這樣的值來調用前述函數時,得到的字符串是正確的。 運行 test_cities.py,確認測試 test_city_country()通過了。 

#city_functions.py
# _*_ coding:utf-8 _*_
def city_functions(City,Country):
	full_city_name = City+" "+Country
	return full_city_name

#test_city_functions.py
import unittest
from city_functions import city_functions

class CityTestCase(unittest.TestCase):
	def test_city_country(self):
		formatted_name = city_functions('santiago','chile')
		self.assertEqual(formatted_name,'santiago chile')
unittest.main()

輸出結果:第1行的句點表明有一個測試通過了。接下來的一行指出Python運行了一個測試,消耗的時 間不到0.001秒。最後的OK表明該測試用例中的所有單元測試都通過了。 

.
----------------------------------------------------------------------
Ran 1 test in 0.000s

OK

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章