在瞭解了ui自動化的方法後,實際應用時需要按照測試用例的形式來書寫,否則執行起來太過冗餘,這裏引入一個測試框架:unittest,使用這個框架中編寫用例,會更方便管理和運行。
一、unitest基礎寫法格式
1.1引用導入
import unittest
並且需要新建一個類,繼承unittest
class Demo(unittest.TestCase):
1.2格式代碼示例
備註:
1.用例的方法名中,要以test開頭才能被讀取出來
2.用例的讀取順序按照方法名的ASCII碼順序運行,順序:0-9,A-Z,a-z
# -*- coding:utf-8 -*-
import unittest
class Demo(unittest.TestCase):
def setUp(self):
print("測試開始")
def test_01(self):
print("第一條用例")
def tearDown(self):
print("測試結束")
if __name__ == '__main__':
unittest.main()
二、常用方法、裝飾器詳解
2.1 unittest中常用方法、裝飾器
運行該模塊中的測試用例方法
unittest.main()
裝飾器:跳過該方法
@unittest.skip
裝飾器: 滿足條件時,跳過該方法
@skipIf(condition, reason)
- condition:判斷條件
- reason:原因描述
裝飾器:不滿足條件時,跳過該方法
@skipUnless(condition, reason)
- condition:判斷條件
- reason:原因描述
2.2 TestCase中常用方法
每條用例方法執行前,運行此方法
setUp()
每條用例方法執行後,運行此方法
tearDown()
三、實例展示:使用unittest運行UI測試用例
這裏我們把15、16節中的元素等待、使用js語句這兩個例子,作爲兩個測試用例,另外兩個用例,一個使用裝飾器跳過、另一個使用不規範的方法命名,期望結果TestCase會加載三個用例,只運行其中兩個。
# -*- coding:utf-8 -*-
from selenium import webdriver
import unittest
class PcLogin(unittest.TestCase):
def setUp(self):
print("測試開始")
self.driver = webdriver.Chrome()
self.driver.implicitly_wait(10)
self.driver.set_page_load_timeout(15)
@unittest.skip
def test_02(self):
"""使用裝飾器跳過此方法"""
print("第二條用例")
def demo_04(self):
"""方法命名不規範,不會運行此方法"""
print("demo")
def test_03_js(self):
"""使用js高亮顯示元素"""
print("第三條用例")
self.driver.get("http://www.runoob.com/js/js-tutorial.html")
# 高亮顯示所定位的元素
light_element = self.driver.find_element_by_id("s")
js_sentence_light = "arguments[0].setAttribute('style', arguments[1]);"
js_sentence_args = "color: yellow; border: 5px solid yellow;"
self.driver.execute_script(js_sentence_light, light_element, js_sentence_args)
def test_01_register(self):
"""百度註冊頁面"""
print("第一條用例")
self.driver.get("https://passport.baidu.com/v2/?login")
# 點擊註冊
self.driver.find_element("xpath", "//a[text()='立即註冊']").click()
# 切換頁籤
all_handle = self.driver.window_handles
self.driver.switch_to.window(all_handle[1])
# 定位標籤
self.driver.find_element("xpath", "//label[text()='用戶名']/following-sibling::input[last()]").send_keys("用戶西城")
self.driver.find_element("xpath", "//label[text()='手機號']/following-sibling::input[last()]").send_keys("18888888888")
self.driver.find_element("xpath", "//label[text()='密碼']/following-sibling::input[last()]").send_keys("U1sd23456")
def tearDown(self):
print("測試完成")
self.driver.quit()
if __name__ == '__main__':
unittest.main()
運行結果:
測試開始
第一條用例
測試完成
測試開始
.測試完成
測試開始
.第三條用例
測試完成
.
----------------------------------------------------------------------
Ran 3 tests in 31.747s
OK