30

Web ドライバーのテストが失敗した場合 (例外またはアサーション エラー)、スクリーンショットを自動的にキャプチャしたいと考えています。Python unittest と Selenium Webdriver を使用しています。誰にもこの問題の解決策はありますか?

4

8 に答える 8

28

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)
于 2012-08-19T13:12:01.320 に答える
11

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):
        ...
于 2015-12-16T19:42:03.547 に答える
0

私のクラスの Django 2.2.2 (unittest を使用) では、StaticLiveServerTestCase から継承したセレン テスト用に、_feedErrorsToResult メソッドをオーバーライドしました。また、このアプローチは、便利なスクリーンショット調査のために呼び出されたメソッドの名前を知るためのトリッキーな方法を提供します。

@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)
于 2019-10-05T18:19:44.107 に答える
-2

私のためにこの解決策を助けてください:

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
于 2016-04-04T03:10:54.943 に答える