簡介
在 app 自動化測試中,彈窗異常處理是指處理應用程序中可能出現的各種彈窗、對話框或提示框等用戶界面元素的情況。這些彈窗可能包括警告、確認、輸入框等,它們可能是應用程序的正常行爲,也可能是錯誤或異常的指示。有效的彈窗異常處理是自動化測試穩定性和可靠性的關鍵組成部分。
使用場景
- 運行過程中不定時彈框(廣告彈窗,升級提示框,新消息提示框等等)
- 彈框不是 BUG(UI 界面提示,警告的作用)
操作步驟
黑名單處理
def find(self, by, locator):
try:
return self.driver.find_element(by, locator)
except Exception as e:
for black in black_list:
eles = self.driver.find_elements(*black)
if len(eles) > 0:
eles[0].click()
return find(by, locator)
raise e
異常處理 - 裝飾器
裝飾器優勢
- 對原有函數的功能增強
- 不改變原有函數的邏輯
- 使代碼更簡潔、易維護
代碼實現
# 聲明一個黑名單
def black_wrapper(fun):
def run(*args, **kwargs):
self = args[0]
try:
return func(*args, **kwargs)
except Exception as e:
# 這裏添加所有的異常情況處理
# 日誌
logger.warning("執行過程中發生異常")
# 截圖
timestamp = int(time.time())
image_path = f"./images/image_{timestamp}.PNG"
page_source_path = \
f"./page_source/{timestamp}_page_source.html"
# page_source
with open(f"./page_source/{timestamp}_page_source.html",\
"w", encoding="u8") as f:
f.write(self.driver.page_source)
self.driver.save_screenshot(image_path)
allure.attach.file(image_path, name="image",\
attachment_type=allure.attachment_type.PNG)
allure.attach.file(page_source_path, \
name="page_source", \
attachment_type=allure.attachment_type.TEXT)
raise e
return run
裝飾元素查找方法
@black_wrapper
def find(self, by, locator)
return self.driver.find_element(by, locator)
總結
- 黑名單處理
- 異常處理裝飾器