How to capture a screenshot if my media doesn’t work?

I am running selenium webdriver tests using nosetests. I want to take a screenshot whenever nosetests fail. How can I do this in the most efficient way using the webdriver, python or nosetests functions?

+5
source share
4 answers

My decision

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()
+8
source

First of all, webdriver has a command:

driver.get_screenshot_as_file(screenshot_file_path)

I am not an expert in the nose (this is actually the first time I have studied it), however I use py.test(which is similar, but superior to noseIMHO).

"plugin" , hook addFailure(test, err), ", ".

addFailure(test, err) Test object .

driver.get_screenshot_as_file(screenshot_file_path).

py.test hook def pytest_runtest_makereport(item, call):. call.excinfo .

+4

Python :

driver.save_screenshot('/file/screenshot.png')
0

, -, , , . , , , , find_element_by_something. , :

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('selector', 'element name')

0

All Articles