我正在用nosetests運行硒webdriver測試。我想在鼻子測試失敗時捕捉屏幕截圖。我怎樣才能以最有效的方式做到這一點,無論是通過使用webdriver,python或nosetests功能?如果我的鼻子測試失敗,我如何捕獲屏幕截圖?
回答
在Python中你可以使用下面的代碼:
driver.save_screenshot('/file/screenshot.png')
首先,webdriver的有命令:
driver.get_screenshot_as_file(screenshot_file_path)
我不是鼻子的專家(其實這是第一次我研究過它),但我使用py.test
框架(這是相似的,但優於nose
恕我直言)。
很可能你必須爲鼻子創建"plugin",你必須實現鉤子addFailure(test, err)
這是「當測試失敗時調用」。
在此addFailure(test, err)
中,您可以從Test object獲取測試名稱並生成該文件的路徑。
之後致電driver.get_screenshot_as_file(screenshot_file_path)
。
在py.test
我創建我的插件與執行def pytest_runtest_makereport(item, call):
掛鉤。我在裏面分析call.excinfo
並根據需要創建屏幕截圖。
我試過這個,但我無法在addFailure()中得到TestCase的實例。你可以分享這是如何可能的(只知道測試名稱,它只能指向適當的類,而不是實例) – vvondra 2014-02-05 21:46:32
我的解決方案
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()
問題是關於'nose'框架,而不是默認'unittest'。 – 2013-02-27 20:15:29
「通過使用webdriver,python或nosetests功能」 – 2013-02-27 20:53:26
我不認爲「python」意味着「使用另一個框架(如unittest)」,但我可能是錯的。 – 2013-02-27 20:58:23
也許你不同的設置你的測試,但在我的經驗,你需要手動建立這種類型的功能,並在故障點重複。如果你正在進行硒測試,那麼很可能就像我一樣,你正在使用很多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(「選擇」,「元素名稱」)
類似,但對於單元測試:如何只上執行代碼使用python unittest2測試失敗?](http://stackoverflow.com/q/12290336/55075)在SO – kenorb 2015-05-16 20:46:41