詳解python單元測試框架unittest
一:unittest是python自帶的一個單元測試框架,類似于java的junit,基本結(jié)構(gòu)是類似的。
基本用法如下:
1.用import unittest導(dǎo)入unittest模塊
2.定義一個繼承自unittest.TestCase的測試用例類,如
class abcd(unittest.TestCase):
3.定義setUp和tearDown,這兩個方法與junit相同,即如果定義了則會在每個測試case執(zhí)行前先執(zhí)行setUp方法,執(zhí)行完畢后執(zhí)行tearDown方法。
4.定義測試用例,名字以test開頭,unittest會自動將test開頭的方法放入測試用例集中。
5.一個測試用例應(yīng)該只測試一個方面,測試目的和測試內(nèi)容應(yīng)很明確。主要是調(diào)用assertEqual、assertRaises等斷言方法判斷程序執(zhí)行結(jié)果和預(yù)期值是否相符。
6.調(diào)用unittest.main()啟動測試
7.如果測試未通過,則會顯示e,并給出具體的錯誤(此處為程序問題導(dǎo)致)。如果測試失敗則顯示為f,測試通過為.,如有多個testcase,則結(jié)果依次顯示。
一個單testcase的簡單的例子:
# -*- coding:UTF-8 -*- ''' Created on 2015年3月24日 @author: Administrator ''' import unittest from selenium import webdriver import time class TestCase1(unittest.TestCase): def setUp(self): self.driver=webdriver.Firefox() self.base_url="http://www.baidu.com" def tearDown(self): self.driver.quit() def testCase1(self): driver=self.driver driver.get(self.base_url) print "將窗口最大化" driver.maximize_window() time.sleep(10) if __name__ == "__main__": unittest.main()
一個多testcase的例子:
# -*- coding:UTF-8 -*- ''' Created on @author: Administrator ''' from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support.ui import Select from selenium.common.exceptions import NoSuchElementException,\ NoAlertPresentException import HTMLTestRunner #form selenium.common.exceptions import NoAlertPresentException import unittest, time, re class Baidu(unittest.TestCase): def setUp(self): self.driver = webdriver.Firefox() self.driver.implicitly_wait(30) self.base_url = "http://www.baidu.com/?tn=98012088_4_dg&ch=3" self.verificationErrors = [] self.accept_next_alert = True self.driver.get(self.base_url) def test_baidu_search(self): '''百度搜索''' driver = self.driver # driver.get(self.base_url + "/") try: driver.find_element_by_id("kw").send_keys("selenium webdriver") driver.find_element_by_id("su").click() except: driver.get_screenshot_as_file('D:\\workspace\\python_prictise\\src\\error.png') time.sleep(2) driver.close() def test_baidu_set(self): '''百度新聞''' driver = self.driver driver.find_element_by_name("tj_trnews").click() self.assertEqual(driver.title,u'百度新聞搜索——全球最大的中文新聞平臺',"switch to baidu news faile!") # time.sleep(2) def is_element_present(self, how, what): try: self.driver.find_element(by=how, value=what) except NoSuchElementException: return False return True def is_alert_present(self): try: self.driver.switch_to_alert() except NoAlertPresentException: return False return True def close_alert_and_get_its_text(self): try: alert = self.driver.switch_to_alert() alert_text = alert.text if self.accept_next_alert: alert.accept() else: alert.dismiss() return alert_text finally: self.accept_next_alert = True def tearDown(self): self.driver.quit() self.assertEqual([], self.verificationErrors) if __name__ == "__main__": unittest.main()
二:跳過單個testcase和testclass的方法
在unittest中也支持類似junit中的跳過單個測試case或者測試class的方法,如下:
@unittest.skip(reason)
無條件的跳過被修飾的testcase或者testclass,reason描述為何跳過該測試,為一個字符串;
@unittest.skipIf(condition,reason)
如果條件condition為真,則跳過該testcase或者testclass;
@unittest.skipUnless(condition,reason)
除非條件condition為真,否則跳過被修飾的testcase或者testclass;
@unittest.expectedFailure
標(biāo)記測試為一個預(yù)期失敗的測試,但不會作為失敗測試統(tǒng)計在結(jié)果中;
三:斷言
在unittest中用斷言來判斷是pass還是fail,常見的斷言方法如下:
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
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 isinstance(a, b)
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
其他斷言方法請查閱官方文檔
四:組成測試套件
1.添加數(shù)量較少的測試case,可以用如下方法:
suite=unittest.Testsuite()
suite.addTest(testclass(testcase))
這里testclass為測試類的名稱,testcase為該測試類下的測試case的名稱,為字符串。
2.對于有多個測試類的情況,可以用如下方法:
def createsuite(): testunit=unittest.TestSuite() discover=unittest.defaultTestLoader.discover(testdir,pattern='test_*.py', top_level_dir=None) print discover for test_suite in discover: for testsuit in test_suite: testunit.addTest(testsuit) return testunit alltestnames = createsuite()
如此便可以將一個目錄下多個測試文件中的testcase導(dǎo)入。
相關(guān)文章
Python中生成一個指定長度的隨機字符串實現(xiàn)示例
這篇文章主要介紹了Python中生成一個指定長度的隨機字符串,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-11-11Python+Pygame實現(xiàn)懷舊游戲飛機大戰(zhàn)
第一次見到飛機大戰(zhàn)是在小學(xué)五年級下半學(xué)期的時候,這個游戲中可以說包含了幾乎所有我目前可接觸到的pygame知識。本文就來利用Pygame實現(xiàn)飛機大戰(zhàn)游戲,需要的可以參考一下2022-11-11使用python模塊plotdigitizer摳取論文圖片中的數(shù)據(jù)實例詳解
這篇文章主要介紹了使用python模塊plotdigitizer摳取論文圖片中的數(shù)據(jù),本文通過實例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-03-03Python趣味挑戰(zhàn)之教你用pygame畫進(jìn)度條
pygame四種方法教會你畫進(jìn)度條,其實也不難,文中有非常詳細(xì)的代碼示例,對正在學(xué)習(xí)python的小伙伴們很有幫助,需要的朋友可以參考下2021-05-05python函數(shù)聲明和調(diào)用定義及原理詳解
這篇文章主要介紹了python函數(shù)聲明和調(diào)用定義及原理詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2019-12-12