Skip to content

Instantly share code, notes, and snippets.

@tentacode
Created February 6, 2015 13:33
Show Gist options
  • Save tentacode/a8ecced324cd1868a28e to your computer and use it in GitHub Desktop.
Save tentacode/a8ecced324cd1868a28e to your computer and use it in GitHub Desktop.
After a Behat javascript scenario fails, taking a screenshot then sending it to wsend as an anonymous user. (could be improved, juste a POC really)
<?php
namespace Context;
use Behat\MinkExtension\Context\RawMinkContext;
use Behat\Testwork\Tester\Result\TestResult;
use Behat\Mink\Driver\Selenium2Driver;
class ScreenshotContext extends RawMinkContext
{
protected $scenarioTitle = null;
protected static $wsendUser = null;
/**
* @BeforeScenario
*/
public function keepScenarioTitle($event)
{
$this->scenarioTitle = $event->getScenario()->getTitle();
}
/**
* @AfterStep
*/
public function takeScreenshotAfterFailedStep($event)
{
if ($event->getTestResult()->getResultCode() !== TestResult::FAILED) {
return;
}
$this->takeAScreenshot();
}
/**
* @Then take a screenshot
*/
public function takeAScreenshot()
{
if (!$this->getSession()->getDriver() instanceof Selenium2Driver) {
print "Screenshot cannot be taken from non javascript scenario.";
return;
}
$screenshot = $this->getSession()->getDriver()->getScreenshot();
$filename = $this->getScreenshotFilename();
file_put_contents($filename, $screenshot);
$url = $this->sendScreenshot($filename);
print sprintf("Screenshot is available :\n%s", $url);
}
protected function sendScreenshot($filename)
{
if (!self::$wsendUser) {
self::$wsendUser = $this->getWsendUser();
}
exec(sprintf(
'curl -F "uid=%s" -F "filehandle=@%s" https://wsend.net/upload_cli 2>/dev/null',
self::$wsendUser,
$filename
), $output, $return);
if ($return !== 0) {
throw new \RuntimeException('Sending screenshot failed : '.implode("\n", $output));
}
return $output[0];
}
protected function getWsendUser()
{
exec('curl -F "start=1" https://wsend.net/createunreg 2>/dev/null', $output, $return);
if ($return !== 0) {
throw new \RuntimeException('Sending screenshot failed : '.implode("\n", $output));
}
return $output[0];
}
protected function getScreenshotFilename()
{
$filename = $this->scenarioTitle;
$filename = preg_replace("#[^a-zA-Z0-9\._-]#", '_', $filename);
return sprintf('%s/%s.png', sys_get_temp_dir(), $filename);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment