Automatic screenshots when test fail by Selenium Webdriver in Python

前端 未结 7 1210
小蘑菇
小蘑菇 2020-12-13 04:42

I want to automatic capturing screenshots if my webdriver tests failed (any exception or assertion error). I am using Python unittest and Selenium Webdriver. Does anyone hav

7条回答
  •  轮回少年
    2020-12-13 04:54

    For Django 2.2.2 (which uses unittest) in my class for selenium tests, which inherited from StaticLiveServerTestCase I've overrided _feedErrorsToResult method. Also this approach provides tricky way to know name of called method for convinient screenshot investigation.

    @classmethod
    def _feedErrorsToResult(cls, result, errors):
        """
        Overriding private method at %library root%/Lib/unittest/case.py
        so you can take screenshot with any failed test and find name of the method
        """
        if SELENIUM_TAKE_SCREENSHOTS:
            for test, exc_info in errors:
                if exc_info is not None:
                    now = datetime.now().strftime('%y-%m-%d_%H-%M-%S')
                    test_name = exc_info[2].tb_frame.f_locals["test_case"]._testMethodName
                    # noinspection PyUnresolvedReferences
                    cls.selenium.get_screenshot_as_file('%s/%s-%s-%s.png' % (SELENIUM_SCREENSHOTS_PATH, cls.__name__, test_name, now))
        # noinspection PyUnresolvedReferences
        super()._feedErrorsToResult(cls, result, errors)
    

提交回复
热议问题