Skip to content

Instantly share code, notes, and snippets.

@tentacode
Created February 6, 2015 13:33
Show Gist options
  • Select an option

  • Save tentacode/a8ecced324cd1868a28e to your computer and use it in GitHub Desktop.

Select an option

Save tentacode/a8ecced324cd1868a28e to your computer and use it in GitHub Desktop.

Revisions

  1. tentacode created this gist Feb 6, 2015.
    92 changes: 92 additions & 0 deletions ScreenshotContext.php
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,92 @@
    <?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);
    }
    }