單元測試框架(斷言,框架的優化)
阿新 • • 發佈:2021-08-23
一、斷言詳解
(1)assertEqual()是驗證兩個⼈相等,值的是資料型別與內容也是相等的。from selenium import webdriver import unittest class BaiduTest(unittest.TestCase): def setUp(self) -> None: self.driver=webdriver.Chrome() self.driver.maximize_window() self.driver.get('http://www.baidu.com') def tearDown(self) -> None: self.driver.quit()def test_baidu_title(self): # 驗證百度的title是否是“百度一下,你就知道” self.assertEqual(self.driver.title,'百度一下,你就知道') if __name__ == '__main__': unittest.main(verbosity=2)
(2)assertTrue返回的是bool型別,也就是對被測試的物件進⾏驗證,如果返回的是boolean型別並且是true,那麼結果驗證通過,那麼⽅法assertFlase()驗證的是被測試物件返回的內容是false。
from selenium importwebdriver import unittest class BaiduTest(unittest.TestCase): def setUp(self) -> None: self.driver=webdriver.Chrome() self.driver.maximize_window() self.driver.get('http://www.baidu.com') def tearDown(self) -> None: self.driver.quit() def test_baidu_so(self):# 驗證百度搜索框是否可被編輯 so=self.driver.find_element_by_id('kw') # self.assertEqual(so.is_enabled(),True) self.assertTrue(so.is_enabled()) if __name__ == '__main__': unittest.main(verbosity=2)
(3)assertIn()值的是⼀個值是否包含在另外⼀個值⾥⾯,在這⾥特別的強調⼀下,在assertIn()的⽅法⾥⾯,有兩個引數,那麼值的包含其實就是第⼆個實際引數包含第⼀個實際引數。與之相反的⽅法是assergNotIn()
from selenium import webdriver import unittest class BaiduTest(unittest.TestCase): def setUp(self) -> None: self.driver=webdriver.Chrome() self.driver.maximize_window() self.driver.get('http://www.baidu.com') def tearDown(self) -> None: self.driver.quit() def test_baidu_in(self): # assertIn()值的是一個值是否包含在另外一個值裡面 self.assertIn('百度一下', self.driver.title) if __name__ == '__main__': unittest.main(verbosity=2)
(4)斷⾔中的注意事項
在⾃動化測試的應⽤中,測試的結果只有⼀個,那就是通過或者是不通過,不能存在可能通過或者可能不通過,測試結果必須是權威的,確定性的。- 不正確的使⽤if應⽤
from selenium import webdriver import unittest class BaiduTest(unittest.TestCase): def setUp(self) -> None: self.driver=webdriver.Chrome() self.driver.maximize_window() self.driver.get('http://www.baidu.com') def tearDown(self) -> None: self.driver.quit() def test_baidu_if(self): title = self.driver.title if title == '百度一下,你就知道': print('測試通過') else: print('測試不通過') def test_baidu_try(self): # 不正確的斷言,測試報告顯示通過,但測試點實際上沒有通過 title = self.driver.title try: self.assertEqual(title, '百度一,你就知道') except Exception as e: print(e.args[0]) if __name__ == '__main__': unittest.main(verbosity=2)
二、單元測試框架的優化(Json)
例:新浪郵箱的登入
- 先將登入的錯誤資訊和登入成功的驗證資訊分離在data目錄下建立sina.json檔案
- json檔案內容必須使用雙引號
- 獲取當前工程(uiframe)和檔案的路徑
import os def base_dir(): return os.path.dirname(os.path.dirname(__file__)) # """獲取當前工程的路徑""" def filePath(directory='data',fileName=None): # 獲取檔案路徑 return os.path.join(base_dir(),directory,fileName)
- 開啟目錄data下檔名為sina.json檔案
-
出現錯誤:UnicodeDecodeError: 'gbk' codec can't decode byte 0xae in position 92: illegal multibyte sequence
-
獲取不到sina.json檔案內容的解決辦法:1、設定IDE的編碼為UTF-8 2、讀取檔案的時候,設定編碼
import json from utils.pathUtils import base_dir,filePath import os def readJson(): return json.load(open(filePath(directory='data',fileName='sina.json'),encoding='utf-8')) print(readJson())
輸出為字典格式 {'login': {'notEmail': '請輸入郵箱名', 'formatEmail': '您輸入的郵箱名格式不正確', 'errorEmail': '登入名或密碼錯誤', 'username': '[email protected]', 'password': 'admin123', 'shouYe': '郵箱首頁', 'title': '新浪郵箱', 'url': 'https://m0.mail.sina.com.cn/classic/index.php#title=%25E9%2582%25AE%25E7%25AE%25B1%25E9%25A6%2596%25E9%25A1%25B5&action=mailinfo'}}
- 測試模組進行測試 得到的驗證資訊即是sina.json檔案中的資訊
from page.sina import Sina from page.init import InitSina from utils.jsonutils import readJson import unittest class sinaTest(InitSina,Sina): def test_sina_001(self): self.login(username='',password='') self.assertEqual(self.getDivText,readJson()['login']['notEmail']) def test_sina_002(self): self.login(username='5566..oo',password='') self.assertEqual(self.getDivText,readJson()['login']['formatEmail']) def test_sina_003(self): self.login(username='15730996037',password='asd') self.assertEqual(self.getDivText,readJson()['login']['errorEmail']) def test_sina_004(self): self.login(username=readJson()['login']['username'], password=readJson()['login']['password']) self.assertEqual(self.getShouye,readJson()['login']['shouYe']) def test_sina_005(self): self.login(username=readJson()['login']['username'], password=readJson()['login']['password']) self.assertEqual(self.getNick,readJson()['login']['username']) def test_sina_006(self): self.login(username=readJson()['login']['username'], password=readJson()['login']['password']) self.assertEqual(self.getTitle,readJson()['login']['title']) def test_sina_007(self): self.login(username=readJson()['login']['username'], password=readJson()['login']['password']) self.assertEqual(self.getUrl, readJson()['login']['url']) if __name__ == '__main__': unittest.main(verbosity=2)三、單元測試框架的優化(yaml) 安裝yaml pip3 install pyyaml (Python操作Yaml檔案)
例:新浪郵箱的登入
- 先將登入的錯誤資訊和登入成功的驗證資訊分離在data目錄下建立sina.yaml檔案
- 獲取當前工程(uiframe)和檔案的路徑
import os def base_dir(): return os.path.dirname(os.path.dirname(__file__)) # """獲取當前工程的路徑""" def filePath(directory='data',fileName=None): # 獲取檔案路徑 return os.path.join(base_dir(),directory,fileName)
- 開啟目錄data下檔名為sina.yaml檔案
import yaml from utils.pathUtils import filePath import os def readYaml(): return yaml.load(open(filePath(fileName='sina.yaml'),encoding='utf-8')) print(readYaml()) {'login': {'notEmail': '請輸入郵箱名', 'formatEmail': '您輸入的郵箱名格式不正確', 'errorEmail': '登入名或密碼錯誤', 'username': '[email protected]', 'password': 'admin123'}}
- 測試模組進行測試 得到的驗證資訊即是sina.yaml檔案中的資訊
from page.sina import Sina from page.init import InitSina from utils.yamlUtils import readYaml from utils.yamlUtils import getUrl import unittest class sinaTest(InitSina,Sina): def test_sina_001(self): self.login(username='',password='') self.assertEqual(self.getDivText,readYaml()['login']['notEmail']) def test_sina_002(self): self.login(username='5566..oo',password='') self.assertEqual(self.getDivText,readYaml()['login']['formatEmail']) def test_sina_003(self): self.login(username='15730996037',password='asd') self.assertEqual(self.getDivText,readYaml()['login']['errorEmail']) if __name__ == '__main__': unittest.main(verbosity=2)
四、網址的分離 建立config.yaml檔案寫入網址
- 獲取當前工程和檔案的路徑
import os def base_dir(): return os.path.dirname(os.path.dirname(__file__)) # """獲取當前工程的路徑""" def filePath(directory='data',fileName=None): # 獲取檔案路徑(預設引數) return os.path.join(base_dir(),directory,fileName)
- 開啟目錄data下檔名為sina.yaml內容和config.yaml內容
import yaml from utils.pathUtils import filePath import os def readYaml(): return yaml.load(open(filePath(directory='data',fileName='sina.yaml'),encoding='utf-8')) print(readYaml()) def getUrl(): return yaml.load(open(filePath(directory='config',fileName='config.yaml'),encoding='utf-8'))['url']['qa'] print(getUrl()) {'login': {'notEmail': '請輸入郵箱名', 'formatEmail': '您輸入的郵箱名格式不正確', 'errorEmail': '登入名或密碼錯誤', 'username': '[email protected]', 'password': 'admin123'}} https://mail.sina.com.cn/
- init裡面 匯入獲取的網址資訊
import unittest from selenium import webdriver from utils.yamlUtils import getUrl class InitSina(unittest.TestCase): def setUp(self) -> None: self.driver=webdriver.Chrome() self.driver.maximize_window() self.driver.get(getUrl()) self.driver.implicitly_wait(30) def tearDown(self) -> None: self.driver.quit()
- 測試模組進行測試 匯入網址的資訊
五,pytest初步應用
Pytest⽐起unittest來說⽐較⾃由,使⽤unittest⾸先要繼承TestCase的類,但是pytest是不需要的,安裝成功後,直接編寫測試函式或者測試⽅法就可以使⽤了。
安裝的命令為:
Pip3 install pytest 安裝成功後,就可以直接的使⽤。在pytest中,它會⾸先尋找以test開頭或者以test結尾的測試模組,然後執⾏模塊⾥⾯以test開頭或者是以test結尾的測試程式碼,這⾥依據這個要去,編寫測試模組。建立新的工程unit,建立資料夾tests。 建立新的檔案test_add.py 點選底部Terminal 再進入到tests 再輸入python -m pytest -v test_add.py命令即可執行