認識unittest
單元測驗框架提供功能如下:
- 提供用例組織和執行
- 提供豐富的斷言方法
- 提供豐富的日志
重要概念:
- Test Case
是最小的測驗單元,用于檢查特定輸入集合的特定回傳值, - Test Suite
測驗套件是測驗用例、測驗套件或兩者的集合,用于組裝一組要運行的測驗, - Test Runner
用于協調測驗的執行并向用戶提供結果 - Test Fixture
代表執行一個或多個測驗所需的環境準備,以及關聯的清理動作
unittest框架流程:
1.寫好TestCase(測驗用例)
2.由TestLoder加載TestCase到TestSuite(測驗用例集)
3.然后TextTestRunner來運行TestSuite,然后把結果保存在報告中,
斷言方法
在執行測驗用例的程序中,最終測驗用例執行成功與否,是通過測驗得到的實際結果與預期結果進行比較得到的,
| 方法 | 檢查 | 方法 | 檢查 |
|---|---|---|---|
| assertEqual(a,b) | a==b | assertIsNone(x) | x is None |
| assertNotEqual(a,b) | a!=b | assertIsNotNone(x) | x is not None |
| assertTrue(x) | bool(x) is True | assertIn(a,b) | a in b |
| assertFalse(x) | bool(x) is False | assertNotIn(a,b) | a not in b |
| assertIs(a,b) | a is b | assertIsInstance(a,b) | isinstance(a,b) |
| assertIsNot(a,b) | a is not b | assertNotIsInstance(a,b) | not isinstance(a,b) |
測驗模型
線性測驗
- 概念
通過錄制或撰寫對應應用程式的操作步驟產生的線性腳本, - 優點
每個腳本相對于獨立,且不產生其他依賴和呼叫,任何一個測驗用例腳本拿出來都可以單獨執行, - 缺點
開發成本高,用例之間存在重復的操作
模塊化驅動測驗
- 概念
將重復的操作獨立成共享模塊(函式、類),當用例執行程序中需要用到這一模塊操作的時候被呼叫, - 優點
由于最大限度消除了重復,從而提高了開發效率和提高測驗用例的可維護性 - 缺點
雖然模塊化的步驟相同,但是測驗資料不同
資料驅動測驗
- 概念
它將測驗中的測驗資料和操作分離,資料存放在另外一個檔案中單獨維護,通過資料的改變從而驅動自動化測驗的執行,最終引起測驗結果的改變, - 優點
通過這種方式,將資料和重復操作分開,可以快速增加相似測驗,完成不同資料情況下的測驗, - 缺點
資料的準備作業
實戰
├── test_case 用例檔案夾
│ └── test_baidu.py 測驗用例
├── test_report 測驗報告檔案夾
├── util 工具類
│ └── HTMLTestRunnerCN.py 漢化報告
└── Run_test.py 啟動
test_baidu.py 測驗用例
from selenium import webdriver
import unittest
import time
class TestBaidu(unittest.TestCase):
def setUp(self):
self.driver=webdriver.Chrome()
self.driver.implicitly_wait(10)
self.driver.get('https://www.baidu.com')
time.sleep(3)
#定義測驗用例,名字以test開頭,unittest會自動將test開頭的方法放入測驗用例集中,
def test_baidu(self):
self.driver.find_element_by_id('kw').send_keys('greensunit')
self.driver.find_element_by_id('su').click()
time.sleep(2)
title=self.driver.title
self.assertEqual(title,'greensunit_百度搜索')
def tearDown(self):
self.driver.quit()
Run_test.py 啟動
import unittest,time
from util.HTMLTestRunnerCN import HTMLTestRunner
test_dir='./test_case'
discover=unittest.defaultTestLoader.discover(test_dir,pattern='test*.py')
if __name__ == '__main__':
report_dir='./test_report'
now=time.strftime('%Y-%m-%d %H-%M-%S')
report_name=report_dir+'/'+now+'_result.html'
with open(report_name,'wb') as f:
runner=HTMLTestRunner(stream=f,title='百度搜索報告',description='百度搜索自動化測驗報告總結')
runner.run(discover)

轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/277982.html
標籤:其他
上一篇:介面測驗
下一篇:冒煙測驗知多少
