自动截图测试时硒webdriver的Python中失败(Automatic screenshots

2019-06-27 04:22发布

我想自动拍摄截图,如果我的webdriver的试验失败(任何异常或断言错误)。 我使用Python单元测试和硒的webdriver。 没有人有任何解决这个问题?

Answer 1:

做在Firefox中一些webdriver的东西...节省任何异常到一个过时的图像文件截图:

from datetime import datetime
from selenium import webdriver

browser = webdriver.Firefox()

try:
    # do some webdriver stuff here
except Exception as e:
    print e
    now = datetime.now().strftime('%Y-%m-%d_%H-%M-%S')
    browser.get_screenshot_as_file('screenshot-%s.png' % now)


Answer 2:

另一种方法是将以下添加到您的tearDown方法:

if sys.exc_info()[0]:
    test_method_name = self._testMethodName
    self.driver.save_screenshot("Screenshots/%s.png" % test_method_name)

这将是一个测试类是这样的:

class SeleniumTest(unittest2.TestCase):
    ...

    def tearDown(self):
        if sys.exc_info()[0]:
            test_method_name = self._testMethodName
            self.driver.save_screenshot("Screenshots/%s.png" % test_method_name)
        super(SeleniumTest, self).tearDown()

    def test_1(self):
        ...

    def test_2(self):
        ...


Answer 3:

以供将来参考/这里的人是在Python3,既为异常和失败的断言工作有效的解决方案。

(基于https://stackoverflow.com/a/23176373/9427691 )

#!/usr/bin/env python

"""
An Example code to show the set-up with screen-shot on exception.
"""

import unittest
from selenium import webdriver


class TestDemo(unittest.TestCase):
    """An Example test Case, to show off the set-up of a screen-shot on exception."""

    def setUp(self):
        """Set up the Firefox Browser and the Tear Down."""
        self.driver = webdriver.Firefox()
        self.driver.delete_all_cookies()
        # NOTE: In addCleanup, the first in, is executed last.
        self.addCleanup(self.driver.quit)
        self.addCleanup(self.screen_shot)
        self.driver.implicitly_wait(5)

    def screen_shot(self):
        """Take a Screen-shot of the drive homepage, when it Failed."""
        for method, error in self._outcome.errors:
            if error:
                self.driver.get_screenshot_as_file("screenshot" + self.id() + ".png")

    def test_demo(self):
        """A test case that fails because of missing element."""
        self.driver.get("http://www.google.com")
        self.driver.find_element_by_css_selector("div.that-does-not-exist")

    def test_demo2(self):
        """A test case that fails because assert."""
        self.driver.get("https://stackoverflow.com")
        self.assertEqual(True, False)

if __name__ == '__main__':
    unittest.main(verbosity=2)

self._outcome.errors

是Python3而已,所以对于Python2使用

self._outcomeForDoCleanups.errors

代替。

对于那些只想在例外的屏幕截图的人。 你应该看看这个链接: http://blog.likewise.org/2015/01/automatically-capture-browser-screenshots-after-failed-python-ghostdriver-tests/



Answer 4:

下面是使用wrapps每个方法上启动的类的装饰解决方案test_用包装材料,需要一个屏幕截图,如果该方法引发和异常。 该browser_attr用来告诉装饰如何获取网页浏览器(驱动器)。

from functools import partialmethod


def sreenshotOnFail(browser_attr='browser'):
    def decorator(cls):
        def with_screen_shot(self, fn, *args, **kwargs):
            """Take a Screen-shot of the drive page, when a function fails."""
            try:
                return fn(self, *args, **kwargs)
            except Exception:
                # This will only be reached if the test fails
                browser = getattr(self, browser_attr)
                filename = 'screenshot-%s.png' % fn.__name__
                browser.get_screenshot_as_file(filename)
                print('Screenshot saved as %s' % filename)
                raise

        for attr, fn in cls.__dict__.items():
            if attr[:5] == 'test_' and callable(fn):
                setattr(cls, attr, partialmethod(with_screen_shot, fn))

        return cls
    return decorator


@sreenshotOnFail()
class TestDemo(unittest.TestCase):
    def setUp(self):
        """Set up the Firefox Browser and the Tear Down."""
        self.browser = webdriver.Firefox()

    def test_demo2(self):
        """A test case that fails because assert."""
        self.driver.get("https://stackoverflow.com")
        self.assertEqual(True, False)


Answer 5:

你可以开始探索形式self._outcome.errors[1]它在哪里可以找到有关的错误的信息。
即下面的代码将只能用于断言错误

 def tearDown(self):
        if self._outcome.errors[1][1] and hasattr(self._outcome.errors[1][1][1], 'actual'):
            self.driver.save_screenshot(self._testMethodName + '.png')


Answer 6:

对我来说,帮助这个解决方案:

def teardown_method(self, method):
    """Driver elimination"""
    if sys.exc_info():
        allure.attach('screenshot', self.driver.get_screenshot_as_png(), type=AttachmentType.PNG)
    self.driver.quit()
    pass


文章来源: Automatic screenshots when test fail by Selenium Webdriver in Python