1. 程式人生 > >python單元測試框架unittest簡介

python單元測試框架unittest簡介

一:unittest是python自帶的一個單元測試框架,類似於java的junit,基本結構是類似的。基本用法如下:
1.用import unittest匯入unittest模組
2.定義一個繼承自unittest.TestCase的測試用例類,如
class abcd(unittest.TestCase):
3.定義setUp和tearDown,這兩個方法與junit相同,即如果定義了則會在每個測試case執行前先執行setUp方法,執行完畢後執行tearDown方法。
4.定義測試用例,名字以test開頭,unittest會自動將test開頭的方法放入測試用例集中。
5.一個測試用例應該只測試一個方面,測試目的和測試內容應很明確。主要是呼叫assertEqual、assertRaises等斷言方法判斷程式執行結果和預期值是否相符。
6.呼叫unittest.main()啟動測試
7.如果測試未通過,則會顯示e,並給出具體的錯誤(此處為程式問題導致)。如果測試失敗則顯示為f,測試通過為.,如有多個testcase,則結果依次顯示。

一個單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 2015��3��27�� @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
標記測試為一個預期失敗的測試,但不會作為失敗測試統計在結果中;

三:斷言
在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.新增數量較少的測試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匯入。