簡體   English   中英

如果我的測試失敗,如何捕獲屏幕截圖?

[英]How do I capture a screenshot if my nosetests fail?

我用nosetests運行selenium webdriver測試。 我想在鼻子測試失敗時捕獲截圖。 如何通過使用webdriver,python或nosetests功能以最有效的方式完成?

我的解決方案

import sys, unittest
from datetime import datetime

class TestCase(unittest.TestCase):

    def setUp(self):
        some_code

    def test_case(self):
        blah-blah-blah

    def tearDown(self):
        if sys.exc_info()[0]:  # Returns the info of exception being handled 
            fail_url = self.driver.current_url
            print fail_url
            now = datetime.now().strftime('%Y-%m-%d_%H-%M-%S-%f')
            self.driver.get_screenshot_as_file('/path/to/file/%s.png' % now) # my tests work in parallel, so I need uniqe file names
            fail_screenshot_url = 'http://debugtool/screenshots/%s.png' % now
            print fail_screenshot_url
        self.driver.quit()

首先,webdriver有以下命令:

driver.get_screenshot_as_file(screenshot_file_path)

我不是鼻子方面的專家(實際上這是我第一次看到它),但是我使用了py.test框架(它類似於nose恕我直言)。

很可能你必須為nose創建“插件” ,你必須實現鈎子addFailure(test, err) ,這是“當測試失敗時調用”。

在這個addFailure(test, err)您可以從Test對象獲取測試名稱並生成文件的路徑。

之后調用driver.get_screenshot_as_file(screenshot_file_path)

py.test我使用def pytest_runtest_makereport(item, call):實現來創建我的插件def pytest_runtest_makereport(item, call): hook。 在內部我分析call.excinfo並在必要時創建屏幕截圖。

在Python中,您可以使用以下代碼:

driver.save_screenshot('/file/screenshot.png')

也許您已經以不同的方式設置了測試,但根據我的經驗,您需要手動構建此類功能並在失敗時重復它。 如果執行Selenium測試,有機會,像我一樣,你用了很多的東西 find_element_by_。 我編寫了以下函數來允許我處理這類事情:

def findelement(self, selector, name, keys='', click=False):

    if keys:
        try:
            self.driver.find_element_by_css_selector(selector).send_keys(keys)
        except NoSuchElementException:
            self.fail("Tried to send %s into element %s but did not find the element." % (keys, name))
    elif click:
        try:
            self.driver.find_element_by_css_selector(selector).click()
        except NoSuchElementException:
            self.fail("Tried to click element %s but did not find it." % name)
    else:
        try:
            self.driver.find_element_by_css_selector(selector)
        except NoSuchElementException:
            self.fail("Expected to find element %s but did not find it." % name)

在您的情況下,屏幕截圖代碼(self.driver.get_screenshot_as_file(screenshot_file_path))將在self.fail之前。

使用此代碼,每次要與元素交互時,都會調用self.findelement('selector','element name')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM