有没有办法在网站自动化期间自动为故障截图?

时间:2019-03-28 19:21:43

标签: php behat gitlab-ci-runner gherkin mink

我所有的自动化脚本都必须在午夜运行,第二天早上我在报告中看到失败,并且无法重现,我向开发人员提出的问题被拒绝了,因为它是不可生产的。我想建立一个环境,该环境将能够在失败的步骤之后获取网页的屏幕截图。 *代码是用小黄瓜语言编写的 *我们使用默认的Mink函数和一些自定义PHP函数 *我们使用Gitlab和Gitlab运行程序进行执行

我是Behat和PHP的新手。所以,我还没有尝试过任何东西。

  • 理想情况下,我希望看到带有屏幕名称,特定行或某种唯一标识符的屏幕截图。
  • 可以将图像保存到存储库[Cloud / gitlab / Local system]

3 个答案:

答案 0 :(得分:0)

添加可以处理此问题的after step hook

然后在钩子上拍摄屏幕截图。

找到了一段可以帮助您的代码here

    /**
     * @AfterStep
     */
    public function takeScreenshotAfterFailedStep(AfterStepScope $scope)
    {
        if (TestResult::FAILED === $scope->getTestResult()->getResultCode()) {
            $driver = $this->minkContext->getSession()->getDriver();

            if (!$driver instanceof Behat\Mink\Driver\Selenium2Driver) {
                return;
            }

            $page               = $this->minkContext->getSession()->getPage()->getContent();
            $screenshot         = $driver->getScreenshot();
            $screenshotFileName = date('d-m-y').'-'.uniqid().'.png';
            $pageFileName       = date('d-m-y').'-'.uniqid().'.html';
            // NOTE: hardcoded path:
            $filePath           = "/var/www/symfony.dev/";

            file_put_contents($filePath.$screenshotFileName, $screenshot);
            file_put_contents($filePath.$pageFileName, $page);
            print 'Screenshot at: '.$filePath.$screenshotFileName."\n";
            print 'HTML dump at: '.$filePath.$pageFileName."\n";
        }
    }

答案 1 :(得分:0)

Behat提供了许多现成的扩展,就像您使用Mink库来模仿用户与浏览器的交互一样。同样,也有可用的截图扩展,可以捕获失败步骤的截图。您可以在此处找到详细信息-https://packagist.org/packages/bex/behat-screenshot

答案 2 :(得分:0)

这为我完成了工作:

public function takeScreenshotAfterFailedStep(AfterStepScope $scope) {

    try {    

       $session =  $this->getSession();

       if (99 === $scope->getTestResult()->getResultCode()) {
          $stepName = $scope->getStep()->getText();   
          $this->takeScreenshot($stepName);
          echo "\n\nYour test may have failed - ";
          echo "\nCurrent Page URL: ". $session->getCurrentUrl();
       }
    } catch(Exception $e) {

        $e_msg = "Something went wrong when taking screenshots";
        throw new Exception($e_msg, $e->getCode(), $e);
    }

} 

public function takeScreenshot($stepName=null) {

    echo "The current working directory:  " . getcwd() . "\n";

    $filePath = getcwd();      // default path

    date_default_timezone_set('America/New_York');    
    $fileName =   'screenshot-' . uniqid() . '_' . date('Y-m-d-H-i-s') .'.png';

    # if directory path is specified in Behat yml, use it.
    if (isset($this->parameters['screen_shot_path'])) {
       $filePath = $this->parameters['screen_shot_path'];
    }

    $this->saveScreenshot($fileName, $filePath);
    echo "\nScreenshot taken -> " . $fileName . "\n";
}