How to execute code only on test failures with python unittest2?

后端 未结 5 2198
既然无缘
既然无缘 2020-12-06 11:01

I have some class-based unit tests running in python\'s unittest2 framework. We\'re using Selenium WebDriver, which has a convenient save_screenshot() method. I

5条回答
  •  被撕碎了的回忆
    2020-12-06 11:55

    sys.exc_info() should give you exit information on whether a test failed or not. So something like this:

    def tearDown(self):
        if sys.exc_info()[0]:
            path = os.path.join(os.path.dirname(os.path.abspath(__file__)), '../failures', self.driver.browser)
            if not os.path.exists(path):
                try:
                    os.makedirs(path)
                except Exception:
                    # Since this might not be thread safe
                    pass
            filename = '%s.%s.png' % (self.__class__.__name__, self._testMethodName)
            file_path = os.path.join(path, filename)
            self.driver.get_screenshot_as_file(file_path)
    

提交回复
热议问题