我正在用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