我的所有自动化脚本必须在午夜运行,并且我在第二天早上看到报告中的失败并且无法重现,并且我向开发人员提出的问题因不可生产而被拒绝。我想建立一个能够在失败的步骤后截取网页截图的环境。 *代码用Gherkin语言编写*我们使用默认的Mink函数和一些自定义PHP函数*我们使用Gitlab和Gitlab运行器来执行
我是Behat和PHP的新手。所以,我还没有尝试过任何东西。
添加一个可以处理它的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";
}
}
Behat中提供了许多可以使用的扩展,就像您使用Mink库来模仿用户与浏览器的交互一样。同样,还有一个屏幕截图扩展,它可以捕获失败步骤的屏幕截图。你可以在这里找到详细信息 - https://packagist.org/packages/bex/behat-screenshot
这对我有用:
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";
}