Selenium2+python自動化60-異常後截圖(screenshot)

來源:互聯網
上載者:User

標籤:出現   case   rom   用例   資料   rac   testcase   tor   分享圖片   

前言

在執行用例過程中由於是無人值守的,用例運行報錯的時候,我們希望能對當前螢幕,留下證據。

在寫用例的時候,最後一步是斷言,可以把的動作放在斷言這裡,那麼如何在宣告失敗後呢?

 

一、方法

1.get_screenshot_as_file(self, filename)

--這個方法是擷取當前window的,出現IOError時候返回False,成功返回True。

filename參數是儲存檔案的路徑。
Usage:
driver.get_screenshot_as_file(‘/Screenshots/foo.png‘)

 

2.get_screenshot_as_base64(self)

--這個方法也是擷取螢幕,儲存的是base64的編碼格式,在HTML介面輸出的時候,會用到。

比如,想把放到html測試報告裡。
Usage:
driver.get_screenshot_as_base64()

 

3.get_screenshot_as_png(self)
--這個是擷取螢幕,儲存的是位元據,很少用到.
Usage:
driver.get_screenshot_as_png()

 

二、異常後

1.為了能拋異常,把定位登入按鈕的id換了個錯的id。

2.給圖片命名時候加個時間戳記,避免同一個檔案名稱被覆蓋掉。

3.檔案路徑,這裡直接寫的檔案名稱,就是跟當前的指令碼同一個路徑。如果圖片輸出到其它檔案路徑,需要些檔案的絕對路徑了。

4.的結果,如果沒截到圖返回False,成功會返回True。

 

三、selenium執行個體

1.在unittest架構裡寫用例的時候,我們希望在宣告失敗的時候,對當前螢幕。

2.如果加try...except捕獲異常後結果,此時所有的測試案例都是通過的了,會影響測試結果。解決辦法其實很簡單,再把異常拋出來就行了。

3.參考代碼:

# coding:utf-8
from selenium import webdriver
import time,unittest
from selenium.webdriver.support import expected_conditions as EC
class Login(unittest.TestCase):
    def setUp(self):
        url_login = "https://passport.cnblogs.com/user/signin"
        self.driver = webdriver.Firefox()
        self.driver.get(url_login)

    def test_01(self):
        ‘‘‘前面輸入帳號密碼,讓正確運行到assert這一步,斷言故意設定為False不成功‘‘‘
        try:
            self.driver.find_element_by_id("input1").send_keys(u"上海-悠悠")
            self.driver.find_element_by_id("input2").send_keys("xxx")
            # 登入id是錯的,定位會拋異常
            self.driver.find_element_by_id("signin").click()
            # 判斷登入成功頁面是否有帳號:"上海-悠悠"
            time.sleep(3)
            locator = ("id", "lnk_current_user")
            result = EC.text_to_be_present_in_element(locator,u"上海-悠悠")(self.driver)
            self.assertFalse(result)
        except Exception as msg:
            print(u"異常原因%s"%msg)
            # 圖片名稱可以加個時間戳記
            nowTime = time.strftime("%Y%m%d.%H.%M.%S")
            self.driver.get_screenshot_as_file(‘%s.jpg‘ % nowTime)
            raise

    def tearDown(self):
        self.driver.quit()

if __name__ == "__main__":
    unittest.main()

4.運行結果:

異常原因True is not false

Failure
Traceback (most recent call last):
  File "D:\test\yoyot\ketang\test01.py", line 22, in test_01
    self.assertFalse(result)
AssertionError: True is not false

Selenium2+python自動化60-異常後(screenshot)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.