python with contextmanger理解應用之自動化測試webdriver 抓屏示例

  1. 結合aop設計思想以及pathon函數式編程、decorator能夠理解更清楚
    python

  2. 示例class中with 語句執行過程web

    1. 執行contex manager表達式AssertErrorScreenShot(fn2shot,driver),獲取對應上下文
    2. 執行AssertErrorScreenShot中__init__初始化contex實例,這裏能夠傳入所需的參數
    3. __enter__ 返回實例
    4. 執行with:下面的語句塊self.assertEqual
    5. __exit__ 處理可能的異常及其它自定義內容,相似try語句的finally ,返回false從新拋出該異常,true則忽略該異常繼續
class AssertErrorScreenShot:
    def __init__(self,filename2shot,webdriver):
        self.filename2shot=filename2shot
        self.webdriver=webdriver
    def __enter__(self):
        return self
    def __exit__(self, exception_type, exception_value, exception_traceback):
        if exception_type == AssertionError:
            self.webdriver.get_screenshot_as_file(self.filename2shot)
            print '請查看出差頁面截圖'+self.filename2shot
            print exception_value
            self.webdriver.quit()
            return False
#調用
with AssertErrorScreenShot(fn2shot,driver):
            self.assertEqual(text,prompt_info,'登陸信息驗證不經過,請檢查網絡或登陸信息!')
相關文章
相關標籤/搜索