Take screenshot when step fails.
Works only with Selenium2Driver.

@AfterStep
196932
public function takeScreenshotAfterFailedStep(StepEvent $event) {
		if (4 === $event->getResult()) {
			try{
				$this->takeScreenshot($event);
			}catch(\WebDriver\Exception $e){
				$this->logException($e);
			}
		}
	}
813645
def __capture_screenshot(webdriver, folder_location, file_name):
        ""
        # Check folder location exists.
        if not os.path.exists(folder_location):
            os.makedirs(folder_location)

        file_location = os.path.join(folder_location, file_name)

        if isinstance(webdriver, remote.webdriver.WebDriver):
            # If this is a remote webdriver.  We need to transmit the image data
            # back across system boundries as a base 64 encoded string so it can
            # be decoded back on the local system and written to disk.
            base64_data = webdriver.get_screenshot_as_base64()
            screenshot_data = base64.decodestring(base64_data)
            screenshot_file = open(file_location, "wb")
            screenshot_file.write(screenshot_data)
            screenshot_file.close()
        else:
            webdriver.save_screenshot(file_location)
669177
def clean():
        """"""
        screenshot_dir = settings.SELENIUM_SCREENSHOT_DIR
        if screenshot_dir and os.path.isdir(screenshot_dir):
            rmtree(screenshot_dir, ignore_errors=True)
637154
function( currentStep, nextStep ) {
            if ( lastEntered === currentStep ) {
                lib.util.triggerEvent( currentStep, "impress:stepleave", { next: nextStep } );
                lastEntered = null;
            }
        }
851279
public function readErrorHandlerAfterStep(StepEvent $event) {
		try{
	        $page = $this->getSession()->getPage();
	
	        $jserrors = $page->find('xpath', '//body[@data-jserrors]');
	        if (null !== $jserrors) {
	            $this->takeScreenshot($event);
	            file_put_contents('php://stderr', $jserrors->getAttribute('data-jserrors') . PHP_EOL);
	        }
	
	        $javascript = <<<JS
if ('undefined' !== typeof window.jQuery) {
	window.jQuery(document).ready(function() {
		window.jQuery('body').removeAttr('data-jserrors');
	});
}
JS;

			$this->getSession()->executeScript($javascript);
		}catch(\WebDriver\Exception $e){
			$this->logException($e);
        }
    }
869614
def run
      # We can't just rescue exception because Firefox automatically closes alert when exception raised
      return unless @after_hooks.any? && !@browser.alert.exists?

      each { |after_hook| after_hook.call(@browser) }
    rescue Selenium::WebDriver::Error::NoSuchWindowError => ex
      Watir.logger.info "Could not execute After Hooks because browser window was closed #{ex}"
    end
1267523
def _step_failure(self, exc):
        
        self.log_crit(u"STEP %d (%s) FAILURE" % (self.step_index, self.step_label))
        self.step_index += 1
        self.log_exc(u"Unexpected error while executing task", exc, True, ExecuteTaskExecutionError)
222132
function tryConnect() {
    if (!seleniumIP) {
        process.nextTick(buildDriver);
        return;
    }
    const sock = net.connect({
        host: seleniumIP,
        port: +seleniumPort,
    });
    sock.on("connect", function() {
        sock.end();
        attempts = 0;
        process.nextTick(buildDriver);
    }).on("error", function() {
        if (++attempts > 50) {
            throw new Error("Failed to connect selenium server.");
        }
        setTimeout(tryConnect, 200);
    });
}
151711
def screenshot(self, filename, scale=1.0, quality=100):
        ''''''
        result = self.server.screenshot(filename, scale, quality)
        if result:
            return result

        device_file = self.server.jsonrpc.takeScreenshot("screenshot.png",
                                                         scale, quality)
        if not device_file:
            return None
        p = self.server.adb.cmd("pull", device_file, filename)
        p.wait()
        self.server.adb.cmd("shell", "rm", device_file).wait()
        return filename if p.returncode is 0 else None
255289
@Override
    public void beforeStep(StepExecution stepExecution) {
        super.beforeStep(stepExecution);
        clearErrors();
        try {
            new Retrier().execute(new Retriable() {
                /*
                 * (non-Javadoc)
                 *
                 * @see org.duracloud.common.retry.Retriable#retry()
                 */
                @Override
                public Object retry() throws Exception {
                    RestoreStatus newStatus = RestoreStatus.VERIFYING_TRANSFERRED_CONTENT;
                    restoreManager.transitionRestoreStatus(restoreId, newStatus, "");
                    return null;
                }
            });
        } catch (Exception ex) {
            addError("failed to transition status to "
                     + RestoreStatus.VERIFYING_TRANSFERRED_CONTENT + ": " + ex.getMessage());
            stepExecution.addFailureException(ex);
        }
    }
88361
protected void markStepForFailure() {
        StopLock stopLock = getStopLock(); // Store in local variable to facilitate Ctrl+Shift+G search in Eclipse
        synchronized (stopLock) {
            updateStepBatchStatus(BatchStatus.FAILED);
            if (!issuedFailureMessageToJobLog) {
                stepThreadHelper.logFailedMessage();
                issuedFailureMessageToJobLog = true;
            }
        }
    }
501752
@Override
    public ExitStatus afterStep(final StepExecution stepExecution) {
        if (getErrors().size() == 0) {
            List<String> verifyErrors = verifySpace(verifier);
            for (String error : verifyErrors) {
                addError(error);
            }
        }

        ExitStatus status = stepExecution.getExitStatus();
        List<String> errors = getErrors();
        if (errors.size() > 0) {
            status = status.and(ExitStatus.FAILED);

            for (String error : errors) {
                status = status.addExitDescription(error);
            }

            failExecution();

            log.error("space verification step finished: step_execution_id={} "
                      + "job_execution_id={}  spaceId={} status=\"{}\"",
                      stepExecution.getId(),
                      stepExecution.getJobExecutionId(),
                      spaceId,
                      status);
        } else {

            status = status.and(ExitStatus.COMPLETED);
            log.info("space verification step finished: step_execution_id={} "
                     + "job_execution_id={}  spaceId={} exit_status={} ",
                     stepExecution.getId(),
                     stepExecution.getJobExecutionId(),
                     spaceId,
                     status);
        }

        return status;
    }
197810
@After
    public void afterScenario(Scenario scenario) throws InterruptedException {
        log.debug("Scenarion finished");
        ScenarioGlobals scenarioGlobals = getCucumberManager().getCurrentScenarioGlobals();
    	TestEnvironment testNev = getSeleniumManager().getAssociatedTestEnvironment();
    	if (testNev != null && scenarioGlobals != null) {
    		boolean scenarioUsedSelenium = testNev.isWebDriverAccessedSince(scenarioGlobals.getScenarioStart());
    		if (scenarioUsedSelenium) {
    			if (scenario.isFailed()) {
    				log.debug("Scenarion failed while using selenium, so capture screenshot");
    				TakesScreenshot seleniumDriver = (TakesScreenshot) SenBotContext.getSeleniumDriver();
					byte[] screenshotAs = seleniumDriver.getScreenshotAs(OutputType.BYTES);
					scenario.embed(screenshotAs, "image/png");
    			}
    		}
    	}
        getCucumberManager().stopNewScenario();
    }
87653
@Override
    public void beforeStep(StepExecution stepExecution) {
        super.beforeStep(stepExecution);

        try {
            new Retrier().execute(new Retriable() {
                /*
                 * (non-Javadoc)
                 *
                 * @see org.duracloud.common.retry.Retriable#retry()
                 */
                @Override
                public Object retry() throws Exception {
                    RestoreStatus newStatus = RestoreStatus.VERIFYING_RETRIEVED_CONTENT;
                    restoreManager.transitionRestoreStatus(restorationId, newStatus, "");
                    return null;
                }
            });
        } catch (Exception ex) {
            addError("failed to transition status to "
                     + RestoreStatus.VERIFYING_RETRIEVED_CONTENT + ": " + ex.getMessage());
            stepExecution.addFailureException(ex);
            failExecution();
        }
    }
721391
@Override
    public ExitStatus afterStep(StepExecution stepExecution) {
        // compare counts (which should not include SNAPSHOT_PROPS_FILENAME
        // on the snapshot repo side since it does not get written to the
        // manifest.
        long snapshotItemCount = getItemsRead();
        if (snapshotItemCount == this.manifestSet.size()) {
            log.debug("snapshot repo count matches manifest count: "
                      + "step_execution_id={} job_execution_id={} snapshot_name={}",
                      stepExecution.getId(),
                      stepExecution.getJobExecutionId(),
                      this.snapshotName);
        } else {
            addError("snapshot ("
                     + snapshotName + ") content item count (" + snapshotItemCount
                     + ") does not match manifest count (" + manifestSet.size() + ")");
        }

        ExitStatus status = stepExecution.getExitStatus();

        List<String> errors = getErrors();
        if (errors.size() > 0) {
            status = status.and(ExitStatus.FAILED);

            for (String error : errors) {
                status = status.addExitDescription(error);
            }

            log.error("snapshot repo verification finished: step_execution_id={} "
                      + "job_execution_id={} snapshot_name={} status=\"{}\"",
                      stepExecution.getId(),
                      stepExecution.getJobExecutionId(),
                      snapshotName,
                      status);

            failExecution();

            resetContextState();

        } else {
            status = status.and(ExitStatus.COMPLETED);
        }

        return status;
    }
101509
def error(self, text, screenshot=None):
        
        step = {
            'time': '%.1f' % (time.time()-self.start_time,),
            'action': 'error',
            'description': text,
            'success': False,
        }   
        if screenshot:
            step['screenshot'] = self._take_screenshot(screenshot, name_prefix='error')
        self.steps.append(step)
349039
public function takeScreenshotAfterFailedStep(AfterStepScope $event) {
    if ($event->getTestResult()->isPassed()) {
      // Not a failed step.
      return;
    }
    try {
      $step = $event->getStep();
      if (function_exists('transliteration_clean_filename')) {
        $file_name = transliteration_clean_filename($step->getKeyword() . '_' . $step->getText());
      }
      else {
        $file_name = str_replace(' ', '_', $step->getKeyword() . '_' . $step->getText());
        $file_name = preg_replace('![^0-9A-Za-z_.-]!', '', $file_name);
      }
      $file_name = substr($file_name, 0, 30);
      $file_name = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'behat-failed__' . $file_name;
      $message = "Screenshot for failed step created in @file_name";
      $this->createScreenshot($file_name, $message);
    }
    catch (DriverException $e) {

    }
  }