亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

詳解python單元測試框架unittest

 更新時(shí)間:2018年07月02日 08:51:48   作者:df0128  
本篇文章給大家詳解了python單元測試框架unittest的相關(guān)知識點(diǎn),有興趣的朋友參考學(xué)習(xí)下。

一:unittest是python自帶的一個(gè)單元測試框架,類似于java的junit,基本結(jié)構(gòu)是類似的。

基本用法如下:

1.用import unittest導(dǎo)入unittest模塊

2.定義一個(gè)繼承自unittest.TestCase的測試用例類,如

class abcd(unittest.TestCase):

3.定義setUp和tearDown,這兩個(gè)方法與junit相同,即如果定義了則會在每個(gè)測試case執(zhí)行前先執(zhí)行setUp方法,執(zhí)行完畢后執(zhí)行tearDown方法。

4.定義測試用例,名字以test開頭,unittest會自動將test開頭的方法放入測試用例集中。

5.一個(gè)測試用例應(yīng)該只測試一個(gè)方面,測試目的和測試內(nèi)容應(yīng)很明確。主要是調(diào)用assertEqual、assertRaises等斷言方法判斷程序執(zhí)行結(jié)果和預(yù)期值是否相符。

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

7.如果測試未通過,則會顯示e,并給出具體的錯誤(此處為程序問題導(dǎo)致)。如果測試失敗則顯示為f,測試通過為.,如有多個(gè)testcase,則結(jié)果依次顯示。

一個(gè)單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()

一個(gè)多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()

二:跳過單個(gè)testcase和testclass的方法

在unittest中也支持類似junit中的跳過單個(gè)測試case或者測試class的方法,如下:

@unittest.skip(reason)

無條件的跳過被修飾的testcase或者testclass,reason描述為何跳過該測試,為一個(gè)字符串;

@unittest.skipIf(condition,reason)

如果條件condition為真,則跳過該testcase或者testclass;

@unittest.skipUnless(condition,reason)

除非條件condition為真,否則跳過被修飾的testcase或者testclass;

@unittest.expectedFailure

標(biāo)記測試為一個(gè)預(yù)期失敗的測試,但不會作為失敗測試統(tǒng)計(jì)在結(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.對于有多個(gè)測試類的情況,可以用如下方法:

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()

如此便可以將一個(gè)目錄下多個(gè)測試文件中的testcase導(dǎo)入。

相關(guān)文章

最新評論