From be8b89500c47a6155239977da71fa56c3d6ec17b Mon Sep 17 00:00:00 2001 From: Mark Johnson Date: Thu, 12 May 2016 09:49:24 +0100 Subject: [PATCH] MDL-54180 Behat: Handle exceptions from driver when saving screenshot --- lib/tests/behat/behat_hooks.php | 26 +++++++++++++++++++++----- 1 file changed, 21 insertions(+), 5 deletions(-) diff --git a/lib/tests/behat/behat_hooks.php b/lib/tests/behat/behat_hooks.php index c2a9862d141..0b954133e11 100644 --- a/lib/tests/behat/behat_hooks.php +++ b/lib/tests/behat/behat_hooks.php @@ -429,8 +429,19 @@ class behat_hooks extends behat_base { return false; } - list ($dir, $filename) = $this->get_faildump_filename($scope, 'png'); - $this->saveScreenshot($filename, $dir); + // Some drivers (e.g. chromedriver) may throw an exception while trying to take a screenshot. If this isn't handled, + // the behat run dies. We don't want to lose the information about the failure that triggered the screenshot, + // so let's log the exception message to a file (to explain why there's no screenshot) and allow the run to continue, + // handling the failure as normal. + try { + list ($dir, $filename) = $this->get_faildump_filename($scope, 'png'); + $this->saveScreenshot($filename, $dir); + } catch (Exception $e) { + // Catching all exceptions as we don't know what the driver might throw. + list ($dir, $filename) = $this->get_faildump_filename($scope, 'txt'); + $message = "Could not save screenshot due to an error\n" . $e->getMessage(); + file_put_contents($dir . DIRECTORY_SEPARATOR . $filename, $message); + } } /** @@ -442,9 +453,14 @@ class behat_hooks extends behat_base { protected function take_contentdump(AfterStepScope $scope) { list ($dir, $filename) = $this->get_faildump_filename($scope, 'html'); - $fh = fopen($dir . DIRECTORY_SEPARATOR . $filename, 'w'); - fwrite($fh, $this->getSession()->getPage()->getContent()); - fclose($fh); + try { + // Driver may throw an exception during getContent(), so do it first to avoid getting an empty file. + $content = $this->getSession()->getPage()->getContent(); + } catch (Exception $e) { + // Catching all exceptions as we don't know what the driver might throw. + $content = "Could not save contentdump due to an error\n" . $e->getMessage(); + } + file_put_contents($dir . DIRECTORY_SEPARATOR . $filename, $content); } /**