MDL-56006 theme: Set Boost as the default theme
[moodle.git] / lib / tests / behat / behat_hooks.php
CommitLineData
f5ceb6c2 1<?php
f5ceb6c2
DM
2// This file is part of Moodle - http://moodle.org/
3//
4// Moodle is free software: you can redistribute it and/or modify
5// it under the terms of the GNU General Public License as published by
6// the Free Software Foundation, either version 3 of the License, or
7// (at your option) any later version.
8//
9// Moodle is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12// GNU General Public License for more details.
13//
14// You should have received a copy of the GNU General Public License
15// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
16
17/**
18 * Behat hooks steps definitions.
19 *
20 * This methods are used by Behat CLI command.
21 *
22 * @package core
23 * @category test
24 * @copyright 2012 David Monllaó
25 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26 */
27
28// NOTE: no MOODLE_INTERNAL test here, this file may be required by behat before including /config.php.
29
30require_once(__DIR__ . '/../../behat/behat_base.php');
31
42ad096f
RT
32use Behat\Testwork\Hook\Scope\BeforeSuiteScope,
33 Behat\Testwork\Hook\Scope\AfterSuiteScope,
34 Behat\Behat\Hook\Scope\BeforeFeatureScope,
35 Behat\Behat\Hook\Scope\AfterFeatureScope,
36 Behat\Behat\Hook\Scope\BeforeScenarioScope,
37 Behat\Behat\Hook\Scope\AfterScenarioScope,
38 Behat\Behat\Hook\Scope\BeforeStepScope,
39 Behat\Behat\Hook\Scope\AfterStepScope,
89cf999a 40 Behat\Mink\Exception\DriverException as DriverException,
870349ee
DM
41 WebDriver\Exception\NoSuchWindow as NoSuchWindow,
42 WebDriver\Exception\UnexpectedAlertOpen as UnexpectedAlertOpen,
3b7d3fb8
DM
43 WebDriver\Exception\UnknownError as UnknownError,
44 WebDriver\Exception\CurlExec as CurlExec,
870349ee 45 WebDriver\Exception\NoAlertOpenError as NoAlertOpenError;
f5ceb6c2
DM
46
47/**
48 * Hooks to the behat process.
49 *
50 * Behat accepts hooks after and before each
51 * suite, feature, scenario and step.
52 *
53 * They can not call other steps as part of their process
54 * like regular steps definitions does.
55 *
56 * Throws generic Exception because they are captured by Behat.
57 *
58 * @package core
59 * @category test
60 * @copyright 2012 David Monllaó
61 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
62 */
63class behat_hooks extends behat_base {
64
41eb672b
DM
65 /**
66 * @var Last browser session start time.
67 */
68 protected static $lastbrowsersessionstart = 0;
69
95b43d6b
DM
70 /**
71 * @var For actions that should only run once.
72 */
73 protected static $initprocessesfinished = false;
74
f49cede7
DM
75 /**
76 * Some exceptions can only be caught in a before or after step hook,
77 * they can not be thrown there as they will provoke a framework level
78 * failure, but we can store them here to fail the step in i_look_for_exceptions()
79 * which result will be parsed by the framework as the last step result.
80 *
81 * @var Null or the exception last step throw in the before or after hook.
82 */
83 protected static $currentstepexception = null;
84
5c0dfe32 85 /**
a964ead0 86 * If we are saving any kind of dump on failure we should use the same parent dir during a run.
5c0dfe32
DM
87 *
88 * @var The parent dir name
89 */
a964ead0 90 protected static $faildumpdirname = false;
5c0dfe32 91
3c71c15c
RT
92 /**
93 * Keeps track of time taken by feature to execute.
94 *
95 * @var array list of feature timings
96 */
97 protected static $timings = array();
98
5aa9b5ce
RT
99 /**
100 * Keeps track of current running suite name.
101 *
102 * @var string current running suite name
103 */
b4bc4286 104 protected static $runningsuite = '';
5aa9b5ce 105
25fbce21
RT
106 /**
107 * Hook to capture BeforeSuite event so as to give access to moodle codebase.
108 * This will try and catch any exception and exists if anything fails.
109 *
110 * @param BeforeSuiteScope $scope scope passed by event fired before suite.
111 * @BeforeSuite
112 */
113 public static function before_suite_hook(BeforeSuiteScope $scope) {
b468dbf5
RT
114 // If behat has been initialised then no need to do this again.
115 if (self::$initprocessesfinished) {
116 return;
117 }
118
25fbce21
RT
119 try {
120 self::before_suite($scope);
121 } catch (behat_stop_exception $e) {
122 echo $e->getMessage() . PHP_EOL;
123 exit(1);
124 }
125 }
126
f5ceb6c2
DM
127 /**
128 * Gives access to moodle codebase, ensures all is ready and sets up the test lock.
129 *
130 * Includes config.php to use moodle codebase with $CFG->behat_*
131 * instead of $CFG->prefix and $CFG->dataroot, called once per suite.
132 *
25fbce21 133 * @param BeforeSuiteScope $scope scope passed by event fired before suite.
f5ceb6c2 134 * @static
25fbce21 135 * @throws behat_stop_exception
f5ceb6c2 136 */
42ad096f 137 public static function before_suite(BeforeSuiteScope $scope) {
f5ceb6c2
DM
138 global $CFG;
139
cfcbc34a
DM
140 // Defined only when the behat CLI command is running, the moodle init setup process will
141 // read this value and switch to $CFG->behat_dataroot and $CFG->behat_prefix instead of
142 // the normal site.
5aa9b5ce
RT
143 if (!defined('BEHAT_TEST')) {
144 define('BEHAT_TEST', 1);
145 }
146
147 if (!defined('CLI_SCRIPT')) {
148 define('CLI_SCRIPT', 1);
149 }
cfcbc34a 150
cfcbc34a 151 // With BEHAT_TEST we will be using $CFG->behat_* instead of $CFG->dataroot, $CFG->prefix and $CFG->wwwroot.
f5ceb6c2
DM
152 require_once(__DIR__ . '/../../../config.php');
153
154 // Now that we are MOODLE_INTERNAL.
155 require_once(__DIR__ . '/../../behat/classes/behat_command.php');
30374580 156 require_once(__DIR__ . '/../../behat/classes/behat_selectors.php');
af4830a2 157 require_once(__DIR__ . '/../../behat/classes/behat_context_helper.php');
f5ceb6c2
DM
158 require_once(__DIR__ . '/../../behat/classes/util.php');
159 require_once(__DIR__ . '/../../testing/classes/test_lock.php');
b08b0a28 160 require_once(__DIR__ . '/../../testing/classes/nasty_strings.php');
f5ceb6c2
DM
161
162 // Avoids vendor/bin/behat to be executed directly without test environment enabled
163 // to prevent undesired db & dataroot modifications, this is also checked
164 // before each scenario (accidental user deletes) in the BeforeScenario hook.
165
166 if (!behat_util::is_test_mode_enabled()) {
25fbce21
RT
167 throw new behat_stop_exception('Behat only can run if test mode is enabled. More info in ' .
168 behat_command::DOCS_URL . '#Running_tests');
f5ceb6c2
DM
169 }
170
d9c55725 171 // Reset all data, before checking for check_server_status.
ab25d8a7 172 // If not done, then it can return apache error, while running tests.
39eb8abe 173 behat_util::clean_tables_updated_by_scenario_list();
ab25d8a7
RT
174 behat_util::reset_all_data();
175
e891c838
RT
176 // Check if server is running and using same version for cli and apache.
177 behat_util::check_server_status();
f5ceb6c2 178
b831d479
DM
179 // Prevents using outdated data, upgrade script would start and tests would fail.
180 if (!behat_util::is_test_data_updated()) {
b32ca4ca 181 $commandpath = 'php admin/tool/behat/cli/init.php';
25fbce21 182 throw new behat_stop_exception("Your behat test site is outdated, please run\n\n " .
d69a6ad9 183 $commandpath . "\n\nfrom your moodle dirroot to drop and install the behat test site again.");
b831d479 184 }
f5ceb6c2
DM
185 // Avoid parallel tests execution, it continues when the previous lock is released.
186 test_lock::acquire('behat');
41eb672b
DM
187
188 // Store the browser reset time if reset after N seconds is specified in config.php.
189 if (!empty($CFG->behat_restart_browser_after)) {
190 // Store the initial browser session opening.
191 self::$lastbrowsersessionstart = time();
192 }
5c0dfe32 193
a964ead0 194 if (!empty($CFG->behat_faildump_path) && !is_writable($CFG->behat_faildump_path)) {
25fbce21 195 throw new behat_stop_exception('You set $CFG->behat_faildump_path to a non-writable directory');
5c0dfe32 196 }
e5f2478b
RT
197
198 // Handle interrupts on PHP7.
199 if (extension_loaded('pcntl')) {
200 $disabled = explode(',', ini_get('disable_functions'));
201 if (!in_array('pcntl_signal', $disabled)) {
202 declare(ticks = 1);
203 }
204 }
f5ceb6c2
DM
205 }
206
3c71c15c
RT
207 /**
208 * Gives access to moodle codebase, to keep track of feature start time.
209 *
25fbce21 210 * @param BeforeFeatureScope $scope scope passed by event fired before feature.
3c71c15c
RT
211 * @BeforeFeature
212 */
25fbce21 213 public static function before_feature(BeforeFeatureScope $scope) {
027212b0 214 if (!defined('BEHAT_FEATURE_TIMING_FILE')) {
3c71c15c
RT
215 return;
216 }
25fbce21 217 $file = $scope->getFeature()->getFile();
08e7f97e
TL
218 self::$timings[$file] = microtime(true);
219 }
220
3c71c15c
RT
221 /**
222 * Gives access to moodle codebase, to keep track of feature end time.
223 *
25fbce21 224 * @param AfterFeatureScope $scope scope passed by event fired after feature.
3c71c15c
RT
225 * @AfterFeature
226 */
25fbce21 227 public static function after_feature(AfterFeatureScope $scope) {
027212b0 228 if (!defined('BEHAT_FEATURE_TIMING_FILE')) {
3c71c15c
RT
229 return;
230 }
25fbce21 231 $file = $scope->getFeature()->getFile();
08e7f97e
TL
232 self::$timings[$file] = microtime(true) - self::$timings[$file];
233 // Probably didn't actually run this, don't output it.
234 if (self::$timings[$file] < 1) {
235 unset(self::$timings[$file]);
236 }
237 }
238
3c71c15c
RT
239 /**
240 * Gives access to moodle codebase, to keep track of suite timings.
241 *
25fbce21 242 * @param AfterSuiteScope $scope scope passed by event fired after suite.
3c71c15c
RT
243 * @AfterSuite
244 */
25fbce21 245 public static function after_suite(AfterSuiteScope $scope) {
027212b0 246 if (!defined('BEHAT_FEATURE_TIMING_FILE')) {
08e7f97e
TL
247 return;
248 }
249 $realroot = realpath(__DIR__.'/../../../').'/';
250 foreach (self::$timings as $k => $v) {
251 $new = str_replace($realroot, '', $k);
252 self::$timings[$new] = round($v, 1);
253 unset(self::$timings[$k]);
254 }
027212b0 255 if ($existing = @json_decode(file_get_contents(BEHAT_FEATURE_TIMING_FILE), true)) {
08e7f97e
TL
256 self::$timings = array_merge($existing, self::$timings);
257 }
258 arsort(self::$timings);
027212b0 259 @file_put_contents(BEHAT_FEATURE_TIMING_FILE, json_encode(self::$timings, JSON_PRETTY_PRINT));
08e7f97e
TL
260 }
261
f5ceb6c2 262 /**
25fbce21 263 * Hook to capture before scenario event to get scope.
f5ceb6c2 264 *
25fbce21 265 * @param BeforeScenarioScope $scope scope passed by event fired before scenario.
f5ceb6c2
DM
266 * @BeforeScenario
267 */
25fbce21
RT
268 public function before_scenario_hook(BeforeScenarioScope $scope) {
269 try {
270 $this->before_scenario($scope);
271 } catch (behat_stop_exception $e) {
272 echo $e->getMessage() . PHP_EOL;
273 exit(1);
274 }
275 }
276
277 /**
278 * Resets the test environment.
279 *
280 * @param BeforeScenarioScope $scope scope passed by event fired before scenario.
281 * @throws behat_stop_exception If here we are not using the test database it should be because of a coding error
282 */
42ad096f 283 public function before_scenario(BeforeScenarioScope $scope) {
5aa9b5ce 284 global $DB, $CFG;
f5ceb6c2
DM
285
286 // As many checks as we can.
cfcbc34a
DM
287 if (!defined('BEHAT_TEST') ||
288 !defined('BEHAT_SITE_RUNNING') ||
f5ceb6c2
DM
289 php_sapi_name() != 'cli' ||
290 !behat_util::is_test_mode_enabled() ||
cfcbc34a 291 !behat_util::is_test_site()) {
25fbce21 292 throw new behat_stop_exception('Behat only can modify the test database and the test dataroot!');
f5ceb6c2
DM
293 }
294
89cf999a
DM
295 $moreinfo = 'More info in ' . behat_command::DOCS_URL . '#Running_tests';
296 $driverexceptionmsg = 'Selenium server is not running, you need to start it to run tests that involve Javascript. ' . $moreinfo;
f59f6b6b
DM
297 try {
298 $session = $this->getSession();
299 } catch (CurlExec $e) {
300 // Exception thrown by WebDriver, so only @javascript tests will be caugth; in
d9c55725 301 // behat_util::check_server_status() we already checked that the server is running.
25fbce21 302 throw new behat_stop_exception($driverexceptionmsg);
89cf999a 303 } catch (DriverException $e) {
25fbce21 304 throw new behat_stop_exception($driverexceptionmsg);
f59f6b6b
DM
305 } catch (UnknownError $e) {
306 // Generic 'I have no idea' Selenium error. Custom exception to provide more feedback about possible solutions.
25fbce21 307 throw new behat_stop_exception($e->getMessage());
f59f6b6b
DM
308 }
309
b4bc4286
RT
310 $suitename = $scope->getSuite()->getName();
311
312 // Register behat selectors for theme, if suite is changed. We do it for every suite change.
313 if ($suitename !== self::$runningsuite) {
314 behat_context_helper::set_environment($scope->getEnvironment());
315
316 // We need the Mink session to do it and we do it only before the first scenario.
520071f0
AN
317 $namedpartialclass = 'behat_partial_named_selector';
318 $namedexactclass = 'behat_exact_named_selector';
319
30374580 320 if ($suitename !== 'default') {
520071f0
AN
321 // If override selector exist, then set it as default behat selectors class.
322 $overrideclass = behat_config_util::get_behat_theme_selector_override_classname($suitename, 'named_partial', true);
323 if (class_exists($overrideclass)) {
324 $namedpartialclass = $overrideclass;
325 }
31c8fd3e 326
520071f0
AN
327 // If override selector exist, then set it as default behat selectors class.
328 $overrideclass = behat_config_util::get_behat_theme_selector_override_classname($suitename, 'named_exact', true);
329 if (class_exists($overrideclass)) {
330 $namedexactclass = $overrideclass;
31c8fd3e 331 }
b4bc4286 332 }
520071f0
AN
333 $this->getSession()->getSelectorsHandler()->registerSelector('named_partial', new $namedpartialclass());
334 $this->getSession()->getSelectorsHandler()->registerSelector('named_exact', new $namedexactclass());
17344d4c
DM
335 }
336
55f47341
RT
337 // Reset mink session between the scenarios.
338 $session->reset();
339
de230fd3 340 // Reset $SESSION.
2e00d01d 341 \core\session\manager::init_empty_session();
c8619f33 342
ef1d45b3 343 behat_util::reset_all_data();
b08b0a28 344
de230fd3 345 // Assign valid data to admin user (some generator-related code needs a valid user).
f5ceb6c2 346 $user = $DB->get_record('user', array('username' => 'admin'));
d79d5ac2 347 \core\session\manager::set_user($user);
5f4b4e91 348
41eb672b
DM
349 // Reset the browser if specified in config.php.
350 if (!empty($CFG->behat_restart_browser_after) && $this->running_javascript()) {
351 $now = time();
352 if (self::$lastbrowsersessionstart + $CFG->behat_restart_browser_after < $now) {
f59f6b6b 353 $session->restart();
41eb672b
DM
354 self::$lastbrowsersessionstart = $now;
355 }
356 }
357
b4bc4286
RT
358 // Set the theme if not default.
359 if ($suitename !== "default") {
360 set_config('theme', $suitename);
361 self::$runningsuite = $suitename;
362 }
363
5f4b4e91 364 // Start always in the the homepage.
3b7d3fb8 365 try {
f59f6b6b
DM
366 // Let's be conservative as we never know when new upstream issues will affect us.
367 $session->visit($this->locate_path('/'));
3b7d3fb8 368 } catch (UnknownError $e) {
25fbce21 369 throw new behat_stop_exception($e->getMessage());
3b7d3fb8 370 }
870349ee 371
95b43d6b
DM
372 // Checking that the root path is a Moodle test site.
373 if (self::is_first_scenario()) {
25fbce21 374 $notestsiteexception = new behat_stop_exception('The base URL (' . $CFG->wwwroot . ') is not a behat test site, ' .
3b7d3fb8 375 'ensure you started the built-in web server in the correct directory or your web server is correctly started and set up');
19f6703d 376 $this->find("xpath", "//head/child::title[normalize-space(.)='" . behat_util::BEHATSITENAME . "']", $notestsiteexception);
95b43d6b
DM
377
378 self::$initprocessesfinished = true;
379 }
5aa9b5ce 380
3b0b5e57
RT
381 // Run all test with medium (1024x768) screen size, to avoid responsive problems.
382 $this->resize_window('medium');
f5ceb6c2
DM
383 }
384
f5ceb6c2 385 /**
d1e55a47 386 * Wait for JS to complete before beginning interacting with the DOM.
f5ceb6c2 387 *
f49cede7
DM
388 * Executed only when running against a real browser. We wrap it
389 * all in a try & catch to forward the exception to i_look_for_exceptions
390 * so the exception will be at scenario level, which causes a failure, by
391 * default would be at framework level, which will stop the execution of
392 * the run.
f5ceb6c2 393 *
25fbce21 394 * @param BeforeStepScope $scope scope passed by event fired before step.
42ad096f 395 * @BeforeStep
f5ceb6c2 396 */
42ad096f
RT
397 public function before_step_javascript(BeforeStepScope $scope) {
398 self::$currentstepexception = null;
f49cede7 399
42ad096f
RT
400 // Only run if JS.
401 if ($this->running_javascript()) {
402 try {
403 $this->wait_for_pending_js();
404 } catch (Exception $e) {
405 self::$currentstepexception = $e;
406 }
f49cede7 407 }
d1e55a47
DM
408 }
409
410 /**
411 * Wait for JS to complete after finishing the step.
412 *
413 * With this we ensure that there are not AJAX calls
414 * still in progress.
415 *
f49cede7
DM
416 * Executed only when running against a real browser. We wrap it
417 * all in a try & catch to forward the exception to i_look_for_exceptions
418 * so the exception will be at scenario level, which causes a failure, by
419 * default would be at framework level, which will stop the execution of
420 * the run.
d1e55a47 421 *
25fbce21 422 * @param AfterStepScope $scope scope passed by event fired after step..
42ad096f 423 * @AfterStep
d1e55a47 424 */
42ad096f
RT
425 public function after_step_javascript(AfterStepScope $scope) {
426 global $CFG, $DB;
427
428 // Save the page content if the step failed.
429 if (!empty($CFG->behat_faildump_path) &&
430 $scope->getTestResult()->getResultCode() === Behat\Testwork\Tester\Result\TestResult::FAILED) {
431 $this->take_contentdump($scope);
432 }
433
434 // Abort any open transactions to prevent subsequent tests hanging.
435 // This does the same as abort_all_db_transactions(), but doesn't call error_log() as we don't
436 // want to see a message in the behat output.
437 if (($scope->getTestResult() instanceof \Behat\Behat\Tester\Result\ExecutedStepResult) &&
438 $scope->getTestResult()->hasException()) {
439 if ($DB && $DB->is_transaction_started()) {
440 $DB->force_transaction_rollback();
441 }
442 }
443
444 // Only run if JS.
445 if (!$this->running_javascript()) {
446 return;
447 }
5c0dfe32
DM
448
449 // Save a screenshot if the step failed.
a964ead0 450 if (!empty($CFG->behat_faildump_path) &&
42ad096f
RT
451 $scope->getTestResult()->getResultCode() === Behat\Testwork\Tester\Result\TestResult::FAILED) {
452 $this->take_screenshot($scope);
5c0dfe32 453 }
f49cede7
DM
454
455 try {
456 $this->wait_for_pending_js();
457 self::$currentstepexception = null;
458 } catch (UnexpectedAlertOpen $e) {
459 self::$currentstepexception = $e;
460
461 // Accepting the alert so the framework can continue properly running
462 // the following scenarios. Some browsers already closes the alert, so
463 // wrapping in a try & catch.
464 try {
465 $this->getSession()->getDriver()->getWebDriverSession()->accept_alert();
466 } catch (Exception $e) {
467 // Catching the generic one as we never know how drivers reacts here.
468 }
469 } catch (Exception $e) {
470 self::$currentstepexception = $e;
471 }
d1e55a47
DM
472 }
473
131d4ac2
T
474 /**
475 * Executed after scenario having switch window to restart session.
476 * This is needed to close all extra browser windows and starting
477 * one browser window.
478 *
25fbce21 479 * @param AfterScenarioScope $scope scope passed by event fired after scenario.
131d4ac2
T
480 * @AfterScenario @_switch_window
481 */
25fbce21 482 public function after_scenario_switchwindow(AfterScenarioScope $scope) {
af7cadbb 483 for ($count = 0; $count < self::EXTENDED_TIMEOUT; $count++) {
5e483833
RT
484 try {
485 $this->getSession()->restart();
486 break;
487 } catch (DriverException $e) {
488 // Wait for timeout and try again.
489 sleep(self::TIMEOUT);
490 }
491 }
492 // If session is not restarted above then it will try to start session before next scenario
493 // and if that fails then exception will be thrown.
131d4ac2
T
494 }
495
a964ead0
AN
496 /**
497 * Getter for self::$faildumpdirname
5c0dfe32
DM
498 *
499 * @return string
500 */
a964ead0
AN
501 protected function get_run_faildump_dir() {
502 return self::$faildumpdirname;
5c0dfe32
DM
503 }
504
505 /**
506 * Take screenshot when a step fails.
3ec07614 507 *
5c0dfe32 508 * @throws Exception
25fbce21 509 * @param AfterStepScope $scope scope passed by event after step.
3ec07614 510 */
42ad096f 511 protected function take_screenshot(AfterStepScope $scope) {
5c0dfe32
DM
512 // Goutte can't save screenshots.
513 if (!$this->running_javascript()) {
514 return false;
3ec07614 515 }
5c0dfe32 516
be8b8950
MJ
517 // Some drivers (e.g. chromedriver) may throw an exception while trying to take a screenshot. If this isn't handled,
518 // the behat run dies. We don't want to lose the information about the failure that triggered the screenshot,
519 // so let's log the exception message to a file (to explain why there's no screenshot) and allow the run to continue,
520 // handling the failure as normal.
521 try {
522 list ($dir, $filename) = $this->get_faildump_filename($scope, 'png');
523 $this->saveScreenshot($filename, $dir);
524 } catch (Exception $e) {
525 // Catching all exceptions as we don't know what the driver might throw.
526 list ($dir, $filename) = $this->get_faildump_filename($scope, 'txt');
527 $message = "Could not save screenshot due to an error\n" . $e->getMessage();
528 file_put_contents($dir . DIRECTORY_SEPARATOR . $filename, $message);
529 }
a964ead0
AN
530 }
531
532 /**
533 * Take a dump of the page content when a step fails.
534 *
535 * @throws Exception
25fbce21 536 * @param AfterStepScope $scope scope passed by event after step.
a964ead0 537 */
42ad096f
RT
538 protected function take_contentdump(AfterStepScope $scope) {
539 list ($dir, $filename) = $this->get_faildump_filename($scope, 'html');
a964ead0 540
be8b8950
MJ
541 try {
542 // Driver may throw an exception during getContent(), so do it first to avoid getting an empty file.
543 $content = $this->getSession()->getPage()->getContent();
544 } catch (Exception $e) {
545 // Catching all exceptions as we don't know what the driver might throw.
546 $content = "Could not save contentdump due to an error\n" . $e->getMessage();
547 }
548 file_put_contents($dir . DIRECTORY_SEPARATOR . $filename, $content);
a964ead0
AN
549 }
550
551 /**
552 * Determine the full pathname to store a failure-related dump.
553 *
554 * This is used for content such as the DOM, and screenshots.
555 *
25fbce21 556 * @param AfterStepScope $scope scope passed by event after step.
167486b3 557 * @param String $filetype The file suffix to use. Limited to 4 chars.
a964ead0 558 */
42ad096f 559 protected function get_faildump_filename(AfterStepScope $scope, $filetype) {
a964ead0
AN
560 global $CFG;
561
562 // All the contentdumps should be in the same parent dir.
563 if (!$faildumpdir = self::get_run_faildump_dir()) {
564 $faildumpdir = self::$faildumpdirname = date('Ymd_His');
5c0dfe32 565
a964ead0 566 $dir = $CFG->behat_faildump_path . DIRECTORY_SEPARATOR . $faildumpdir;
5c0dfe32 567
a964ead0 568 if (!is_dir($dir) && !mkdir($dir, $CFG->directorypermissions, true)) {
5c0dfe32 569 // It shouldn't, we already checked that the directory is writable.
a964ead0 570 throw new Exception('No directories can be created inside $CFG->behat_faildump_path, check the directory permissions.');
5c0dfe32
DM
571 }
572 } else {
573 // We will always need to know the full path.
a964ead0 574 $dir = $CFG->behat_faildump_path . DIRECTORY_SEPARATOR . $faildumpdir;
5c0dfe32
DM
575 }
576
577 // The scenario title + the failed step text.
a964ead0 578 // We want a i-am-the-scenario-title_i-am-the-failed-step.$filetype format.
42ad096f 579 $filename = $scope->getFeature()->getTitle() . '_' . $scope->getStep()->getText();
167486b3
DM
580 $filename = preg_replace('/([^a-zA-Z0-9\_]+)/', '-', $filename);
581
42ad096f 582 // File name limited to 255 characters. Leaving 5 chars for line number and 4 chars for the file.
167486b3 583 // extension as we allow .png for images and .html for DOM contents.
42ad096f 584 $filename = substr($filename, 0, 245) . '_' . $scope->getStep()->getLine() . '.' . $filetype;
5c0dfe32 585
a964ead0 586 return array($dir, $filename);
3ec07614
DW
587 }
588
5f4b4e91
DM
589 /**
590 * Internal step definition to find exceptions, debugging() messages and PHP debug messages.
591 *
592 * Part of behat_hooks class as is part of the testing framework, is auto-executed
593 * after each step so no features will splicitly use it.
594 *
595 * @Given /^I look for exceptions$/
f49cede7 596 * @throw Exception Unknown type, depending on what we caught in the hook or basic \Exception.
1b372a77 597 * @see Moodle\BehatExtension\EventDispatcher\Tester\ChainedStepTester
5f4b4e91
DM
598 */
599 public function i_look_for_exceptions() {
f49cede7
DM
600 // If the step already failed in a hook throw the exception.
601 if (!is_null(self::$currentstepexception)) {
602 throw self::$currentstepexception;
603 }
604
eb9ca848 605 $this->look_for_exceptions();
5f4b4e91
DM
606 }
607
95b43d6b
DM
608 /**
609 * Returns whether the first scenario of the suite is running
610 *
611 * @return bool
612 */
613 protected static function is_first_scenario() {
614 return !(self::$initprocessesfinished);
615 }
f5ceb6c2 616}
a964ead0 617
25fbce21
RT
618/**
619 * Behat stop exception
620 *
621 * This exception is thrown from before suite or scenario if any setup problem found.
622 *
623 * @package core_test
624 * @copyright 2016 Rajesh Taneja <rajesh@moodle.com>
625 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
626 */
e584e6ae 627class behat_stop_exception extends \Exception {
bd1edc83 628}