2 // This file is part of Moodle - http://moodle.org/
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.
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.
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/>.
18 * Behat hooks steps definitions.
20 * This methods are used by Behat CLI command.
24 * @copyright 2012 David Monllaó
25 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
28 // NOTE: no MOODLE_INTERNAL test here, this file may be required by behat before including /config.php.
30 require_once(__DIR__ . '/../../behat/behat_base.php');
32 use 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,
40 Behat\Mink\Exception\ExpectationException,
41 Behat\Mink\Exception\DriverException as DriverException,
42 WebDriver\Exception\NoSuchWindow as NoSuchWindow,
43 WebDriver\Exception\UnexpectedAlertOpen as UnexpectedAlertOpen,
44 WebDriver\Exception\UnknownError as UnknownError,
45 WebDriver\Exception\CurlExec as CurlExec,
46 WebDriver\Exception\NoAlertOpenError as NoAlertOpenError;
49 * Hooks to the behat process.
51 * Behat accepts hooks after and before each
52 * suite, feature, scenario and step.
54 * They can not call other steps as part of their process
55 * like regular steps definitions does.
57 * Throws generic Exception because they are captured by Behat.
61 * @copyright 2012 David Monllaó
62 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
64 class behat_hooks extends behat_base {
67 * @var For actions that should only run once.
69 protected static $initprocessesfinished = false;
71 /** @var bool Whether the first javascript scenario has been seen yet */
72 protected static $firstjavascriptscenarioseen = false;
75 * @var bool Scenario running
77 protected $scenariorunning = false;
80 * Some exceptions can only be caught in a before or after step hook,
81 * they can not be thrown there as they will provoke a framework level
82 * failure, but we can store them here to fail the step in i_look_for_exceptions()
83 * which result will be parsed by the framework as the last step result.
85 * @var Null or the exception last step throw in the before or after hook.
87 protected static $currentstepexception = null;
90 * If an Exception is thrown in the BeforeScenario hook it will cause the Scenario to be skipped, and the exit code
91 * to be non-zero triggering a potential rerun.
93 * To combat this the exception is stored and re-thrown when looking for exceptions.
94 * This allows the test to instead be failed and re-run correctly.
98 protected static $currentscenarioexception = null;
101 * If we are saving any kind of dump on failure we should use the same parent dir during a run.
103 * @var The parent dir name
105 protected static $faildumpdirname = false;
108 * Keeps track of time taken by feature to execute.
110 * @var array list of feature timings
112 protected static $timings = array();
115 * Keeps track of current running suite name.
117 * @var string current running suite name
119 protected static $runningsuite = '';
122 * @var array Array (with tag names in keys) of all tags in current scenario.
124 protected static $scenariotags;
127 * Gives access to moodle codebase, ensures all is ready and sets up the test lock.
129 * Includes config.php to use moodle codebase with $CFG->behat_* instead of $CFG->prefix and $CFG->dataroot, called
133 * @param BeforeSuiteScope $scope scope passed by event fired before suite.
135 public static function before_suite_hook(BeforeSuiteScope $scope) {
138 // If behat has been initialised then no need to do this again.
139 if (!self::is_first_scenario()) {
143 // Defined only when the behat CLI command is running, the moodle init setup process will
144 // read this value and switch to $CFG->behat_dataroot and $CFG->behat_prefix instead of
146 if (!defined('BEHAT_TEST')) {
147 define('BEHAT_TEST', 1);
150 if (!defined('CLI_SCRIPT')) {
151 define('CLI_SCRIPT', 1);
154 // With BEHAT_TEST we will be using $CFG->behat_* instead of $CFG->dataroot, $CFG->prefix and $CFG->wwwroot.
155 require_once(__DIR__ . '/../../../config.php');
157 // Now that we are MOODLE_INTERNAL.
158 require_once(__DIR__ . '/../../behat/classes/behat_command.php');
159 require_once(__DIR__ . '/../../behat/classes/behat_selectors.php');
160 require_once(__DIR__ . '/../../behat/classes/behat_context_helper.php');
161 require_once(__DIR__ . '/../../behat/classes/util.php');
162 require_once(__DIR__ . '/../../testing/classes/test_lock.php');
163 require_once(__DIR__ . '/../../testing/classes/nasty_strings.php');
165 // Avoids vendor/bin/behat to be executed directly without test environment enabled
166 // to prevent undesired db & dataroot modifications, this is also checked
167 // before each scenario (accidental user deletes) in the BeforeScenario hook.
169 if (!behat_util::is_test_mode_enabled()) {
170 self::log_and_stop('Behat only can run if test mode is enabled. More info in ' . behat_command::DOCS_URL);
173 // Reset all data, before checking for check_server_status.
174 // If not done, then it can return apache error, while running tests.
175 behat_util::clean_tables_updated_by_scenario_list();
176 behat_util::reset_all_data();
178 // Check if the web server is running and using same version for cli and apache.
179 behat_util::check_server_status();
181 // Prevents using outdated data, upgrade script would start and tests would fail.
182 if (!behat_util::is_test_data_updated()) {
183 $commandpath = 'php admin/tool/behat/cli/init.php';
185 Your behat test site is outdated, please run the following command from your Moodle dirroot to drop, and reinstall the Behat test site.
190 self::log_and_stop($message);
193 // Avoid parallel tests execution, it continues when the previous lock is released.
194 test_lock::acquire('behat');
196 if (!empty($CFG->behat_faildump_path) && !is_writable($CFG->behat_faildump_path)) {
198 "The \$CFG->behat_faildump_path value is set to a non-writable directory ({$CFG->behat_faildump_path})."
202 // Handle interrupts on PHP7.
203 if (extension_loaded('pcntl')) {
204 $disabled = explode(',', ini_get('disable_functions'));
205 if (!in_array('pcntl_signal', $disabled)) {
212 * Run final tests before running the suite.
215 * @param BeforeSuiteScope $scope scope passed by event fired before suite.
217 public static function before_suite_final_checks(BeforeSuiteScope $scope) {
218 $happy = defined('BEHAT_TEST');
219 $happy = $happy && defined('BEHAT_SITE_RUNNING');
220 $happy = $happy && php_sapi_name() == 'cli';
221 $happy = $happy && behat_util::is_test_mode_enabled();
222 $happy = $happy && behat_util::is_test_site();
225 error_log('Behat only can modify the test database and the test dataroot!');
231 * Gives access to moodle codebase, to keep track of feature start time.
233 * @param BeforeFeatureScope $scope scope passed by event fired before feature.
236 public static function before_feature(BeforeFeatureScope $scope) {
237 if (!defined('BEHAT_FEATURE_TIMING_FILE')) {
240 $file = $scope->getFeature()->getFile();
241 self::$timings[$file] = microtime(true);
245 * Gives access to moodle codebase, to keep track of feature end time.
247 * @param AfterFeatureScope $scope scope passed by event fired after feature.
250 public static function after_feature(AfterFeatureScope $scope) {
251 if (!defined('BEHAT_FEATURE_TIMING_FILE')) {
254 $file = $scope->getFeature()->getFile();
255 self::$timings[$file] = microtime(true) - self::$timings[$file];
256 // Probably didn't actually run this, don't output it.
257 if (self::$timings[$file] < 1) {
258 unset(self::$timings[$file]);
263 * Gives access to moodle codebase, to keep track of suite timings.
265 * @param AfterSuiteScope $scope scope passed by event fired after suite.
268 public static function after_suite(AfterSuiteScope $scope) {
269 if (!defined('BEHAT_FEATURE_TIMING_FILE')) {
272 $realroot = realpath(__DIR__.'/../../../').'/';
273 foreach (self::$timings as $k => $v) {
274 $new = str_replace($realroot, '', $k);
275 self::$timings[$new] = round($v, 1);
276 unset(self::$timings[$k]);
278 if ($existing = @json_decode(file_get_contents(BEHAT_FEATURE_TIMING_FILE), true)) {
279 self::$timings = array_merge($existing, self::$timings);
281 arsort(self::$timings);
282 @file_put_contents(BEHAT_FEATURE_TIMING_FILE, json_encode(self::$timings, JSON_PRETTY_PRINT));
286 * Helper function to restart the Mink session.
288 protected function restart_session(): void {
289 $session = $this->getSession();
290 if ($session->isStarted()) {
295 if ($this->running_javascript() && $this->getSession()->getDriver()->getWebDriverSessionId() === 'session') {
296 throw new DriverException('Unable to create a valid session');
301 * Restart the session before each non-javascript scenario.
303 * @BeforeScenario @~javascript
304 * @param BeforeScenarioScope $scope scope passed by event fired before scenario.
306 public function before_goutte_scenarios(BeforeScenarioScope $scope) {
307 if ($this->running_javascript()) {
308 // A bug in the BeforeScenario filtering prevents the @~javascript filter on this hook from working
310 // See https://github.com/Behat/Behat/issues/1235 for further information.
314 $this->restart_session();
318 * Start the session before the first javascript scenario.
320 * This is treated slightly differently to try to capture when Selenium is not running at all.
322 * @BeforeScenario @javascript
323 * @param BeforeScenarioScope $scope scope passed by event fired before scenario.
325 public function before_first_scenario_start_session(BeforeScenarioScope $scope) {
326 if (!self::is_first_javascript_scenario()) {
327 // The first Scenario has started.
328 // The `before_subsequent_scenario_start_session` function will restart the session instead.
331 self::$firstjavascriptscenarioseen = true;
333 $docsurl = behat_command::DOCS_URL;
334 $driverexceptionmsg = <<<EOF
336 The Selenium or WebDriver server is not running. You must start it to run tests that involve Javascript.
337 See {$docsurl} for more information.
339 The following debugging information is available:
345 $this->restart_session();
346 } catch (CurlExec | DriverException $e) {
347 // The CurlExec Exception is thrown by WebDriver.
349 $driverexceptionmsg . '. ' .
350 $e->getMessage() . "\n\n" .
351 format_backtrace($e->getTrace(), true)
353 } catch (UnknownError $e) {
354 // Generic 'I have no idea' Selenium error. Custom exception to provide more feedback about possible solutions.
356 $e->getMessage() . "\n\n" .
357 format_backtrace($e->getTrace(), true)
363 * Start the session before each javascript scenario.
365 * Note: Before the first scenario the @see before_first_scenario_start_session() function is used instead.
367 * @BeforeScenario @javascript
368 * @param BeforeScenarioScope $scope scope passed by event fired before scenario.
370 public function before_subsequent_scenario_start_session(BeforeScenarioScope $scope) {
371 if (self::is_first_javascript_scenario()) {
372 // The initial init has not yet finished.
373 // The `before_first_scenario_start_session` function will have started the session instead.
376 self::$currentscenarioexception = null;
379 $this->restart_session();
380 } catch (Exception $e) {
381 self::$currentscenarioexception = $e;
386 * Resets the test environment.
389 * @param BeforeScenarioScope $scope scope passed by event fired before scenario.
391 public function before_scenario_hook(BeforeScenarioScope $scope) {
393 if (self::$currentscenarioexception) {
394 // A BeforeScenario hook triggered an exception and marked this test as failed.
395 // Skip this hook as it will likely fail.
399 $suitename = $scope->getSuite()->getName();
401 // Register behat selectors for theme, if suite is changed. We do it for every suite change.
402 if ($suitename !== self::$runningsuite) {
403 self::$runningsuite = $suitename;
404 behat_context_helper::set_environment($scope->getEnvironment());
406 // We need the Mink session to do it and we do it only before the first scenario.
407 $namedpartialclass = 'behat_partial_named_selector';
408 $namedexactclass = 'behat_exact_named_selector';
410 // If override selector exist, then set it as default behat selectors class.
411 $overrideclass = behat_config_util::get_behat_theme_selector_override_classname($suitename, 'named_partial', true);
412 if (class_exists($overrideclass)) {
413 $namedpartialclass = $overrideclass;
416 // If override selector exist, then set it as default behat selectors class.
417 $overrideclass = behat_config_util::get_behat_theme_selector_override_classname($suitename, 'named_exact', true);
418 if (class_exists($overrideclass)) {
419 $namedexactclass = $overrideclass;
422 $this->getSession()->getSelectorsHandler()->registerSelector('named_partial', new $namedpartialclass());
423 $this->getSession()->getSelectorsHandler()->registerSelector('named_exact', new $namedexactclass());
425 // Register component named selectors.
426 foreach (\core_component::get_component_names() as $component) {
427 $this->register_component_selectors_for_component($component);
433 \core\session\manager::init_empty_session();
435 // Ignore E_NOTICE and E_WARNING during reset, as this might be caused because of some existing process
436 // running ajax. This will be investigated in another issue.
437 $errorlevel = error_reporting();
438 error_reporting($errorlevel & ~E_NOTICE & ~E_WARNING);
439 behat_util::reset_all_data();
440 error_reporting($errorlevel);
442 if ($this->running_javascript()) {
443 // Fetch the user agent.
444 // This isused to choose between the SVG/Non-SVG versions of themes.
445 $useragent = $this->getSession()->evaluateScript('return navigator.userAgent;');
446 \core_useragent::instance(true, $useragent);
448 // Restore the saved themes.
449 behat_util::restore_saved_themes();
452 // Assign valid data to admin user (some generator-related code needs a valid user).
453 $user = $DB->get_record('user', array('username' => 'admin'));
454 \core\session\manager::set_user($user);
456 // Set the theme if not default.
457 if ($suitename !== "default") {
458 set_config('theme', $suitename);
461 // Reset the scenariorunning variable to ensure that Step 0 occurs.
462 $this->scenariorunning = false;
464 // Set up the tags for current scenario.
465 self::fetch_tags_for_scenario($scope);
467 // If scenario requires the Moodle app to be running, set this up.
468 if ($this->has_tag('app')) {
469 $this->execute('behat_app::start_scenario');
474 // Run all test with medium (1024x768) screen size, to avoid responsive problems.
475 $this->resize_window('medium');
479 * Hook to open the site root before the first step in the suite.
480 * Yes, this is in a strange location and should be in the BeforeScenario hook, but failures in the test setUp lead
481 * to the test being incorrectly marked as skipped with no way to force the test to be failed.
483 * @param BeforeStepScope $scope
486 public function before_step(BeforeStepScope $scope) {
489 if (!$this->scenariorunning) {
490 // We need to visit / before the first step in any Scenario.
491 // This is our Step 0.
492 // Ideally this would be in the BeforeScenario hook, but any exception in there will lead to the test being
493 // skipped rather than it being failed.
495 // We also need to check that the site returned is a Behat site.
496 // Again, this would be better in the BeforeSuite hook, but that does not have access to the selectors in
497 // order to perform the necessary searches.
498 $session = $this->getSession();
499 $session->visit($this->locate_path('/'));
501 // Checking that the root path is a Moodle test site.
502 if (self::is_first_scenario()) {
503 $message = "The base URL ({$CFG->wwwroot}) is not a behat test site. " .
504 'Ensure that you started the built-in web server in the correct directory, ' .
505 'or that your web server is correctly set up and started.';
508 "xpath", "//head/child::title[normalize-space(.)='" . behat_util::BEHATSITENAME . "']",
509 new ExpectationException($message, $session)
513 $this->scenariorunning = true;
518 * Sets up the tags for the current scenario.
520 * @param \Behat\Behat\Hook\Scope\BeforeScenarioScope $scope Scope
522 protected static function fetch_tags_for_scenario(\Behat\Behat\Hook\Scope\BeforeScenarioScope $scope) {
523 self::$scenariotags = array_flip(array_merge(
524 $scope->getScenario()->getTags(),
525 $scope->getFeature()->getTags()
530 * Gets the tags for the current scenario
532 * @return array Array where key is tag name and value is an integer
534 public static function get_tags_for_scenario() : array {
535 return self::$scenariotags;
539 * Wait for JS to complete before beginning interacting with the DOM.
541 * Executed only when running against a real browser. We wrap it
542 * all in a try & catch to forward the exception to i_look_for_exceptions
543 * so the exception will be at scenario level, which causes a failure, by
544 * default would be at framework level, which will stop the execution of
547 * @param BeforeStepScope $scope scope passed by event fired before step.
550 public function before_step_javascript(BeforeStepScope $scope) {
551 if (self::$currentscenarioexception) {
552 // A BeforeScenario hook triggered an exception and marked this test as failed.
553 // Skip this hook as it will likely fail.
557 self::$currentstepexception = null;
560 if ($this->running_javascript()) {
562 $this->wait_for_pending_js();
563 } catch (Exception $e) {
564 self::$currentstepexception = $e;
570 * Wait for JS to complete after finishing the step.
572 * With this we ensure that there are not AJAX calls
575 * Executed only when running against a real browser. We wrap it
576 * all in a try & catch to forward the exception to i_look_for_exceptions
577 * so the exception will be at scenario level, which causes a failure, by
578 * default would be at framework level, which will stop the execution of
581 * @param AfterStepScope $scope scope passed by event fired after step..
584 public function after_step_javascript(AfterStepScope $scope) {
587 // If step is undefined then throw exception, to get failed exit code.
588 if ($scope->getTestResult()->getResultCode() === Behat\Behat\Tester\Result\StepResult::UNDEFINED) {
589 throw new coding_exception("Step '" . $scope->getStep()->getText() . "'' is undefined.");
592 $isfailed = $scope->getTestResult()->getResultCode() === Behat\Testwork\Tester\Result\TestResult::FAILED;
594 // Abort any open transactions to prevent subsequent tests hanging.
595 // This does the same as abort_all_db_transactions(), but doesn't call error_log() as we don't
596 // want to see a message in the behat output.
597 if (($scope->getTestResult() instanceof \Behat\Behat\Tester\Result\ExecutedStepResult) &&
598 $scope->getTestResult()->hasException()) {
599 if ($DB && $DB->is_transaction_started()) {
600 $DB->force_transaction_rollback();
604 if ($isfailed && !empty($CFG->behat_faildump_path)) {
605 // Save the page content (html).
606 $this->take_contentdump($scope);
608 if ($this->running_javascript()) {
609 // Save a screenshot.
610 $this->take_screenshot($scope);
614 if ($isfailed && !empty($CFG->behat_pause_on_fail)) {
615 $exception = $scope->getTestResult()->getException();
616 $message = "<colour:lightRed>Scenario failed. ";
617 $message .= "<colour:lightYellow>Paused for inspection. Press <colour:lightRed>Enter/Return<colour:lightYellow> to continue.<newline>";
618 $message .= "<colour:lightRed>Exception follows:<newline>";
619 $message .= trim($exception->getMessage());
620 behat_util::pause($this->getSession(), $message);
624 if (!$this->running_javascript()) {
629 $this->wait_for_pending_js();
630 self::$currentstepexception = null;
631 } catch (UnexpectedAlertOpen $e) {
632 self::$currentstepexception = $e;
634 // Accepting the alert so the framework can continue properly running
635 // the following scenarios. Some browsers already closes the alert, so
636 // wrapping in a try & catch.
638 $this->getSession()->getDriver()->getWebDriverSession()->accept_alert();
639 } catch (Exception $e) {
640 // Catching the generic one as we never know how drivers reacts here.
642 } catch (Exception $e) {
643 self::$currentstepexception = $e;
648 * Reset the session between each scenario.
650 * @param AfterScenarioScope $scope scope passed by event fired after scenario.
653 public function reset_webdriver_between_scenarios(AfterScenarioScope $scope) {
654 $this->getSession()->stop();
658 * Getter for self::$faildumpdirname
662 protected function get_run_faildump_dir() {
663 return self::$faildumpdirname;
667 * Take screenshot when a step fails.
670 * @param AfterStepScope $scope scope passed by event after step.
672 protected function take_screenshot(AfterStepScope $scope) {
673 // Goutte can't save screenshots.
674 if (!$this->running_javascript()) {
678 // Some drivers (e.g. chromedriver) may throw an exception while trying to take a screenshot. If this isn't handled,
679 // the behat run dies. We don't want to lose the information about the failure that triggered the screenshot,
680 // so let's log the exception message to a file (to explain why there's no screenshot) and allow the run to continue,
681 // handling the failure as normal.
683 list ($dir, $filename) = $this->get_faildump_filename($scope, 'png');
684 $this->saveScreenshot($filename, $dir);
685 } catch (Exception $e) {
686 // Catching all exceptions as we don't know what the driver might throw.
687 list ($dir, $filename) = $this->get_faildump_filename($scope, 'txt');
688 $message = "Could not save screenshot due to an error\n" . $e->getMessage();
689 file_put_contents($dir . DIRECTORY_SEPARATOR . $filename, $message);
694 * Take a dump of the page content when a step fails.
697 * @param AfterStepScope $scope scope passed by event after step.
699 protected function take_contentdump(AfterStepScope $scope) {
700 list ($dir, $filename) = $this->get_faildump_filename($scope, 'html');
703 // Driver may throw an exception during getContent(), so do it first to avoid getting an empty file.
704 $content = $this->getSession()->getPage()->getContent();
705 } catch (Exception $e) {
706 // Catching all exceptions as we don't know what the driver might throw.
707 $content = "Could not save contentdump due to an error\n" . $e->getMessage();
709 file_put_contents($dir . DIRECTORY_SEPARATOR . $filename, $content);
713 * Determine the full pathname to store a failure-related dump.
715 * This is used for content such as the DOM, and screenshots.
717 * @param AfterStepScope $scope scope passed by event after step.
718 * @param String $filetype The file suffix to use. Limited to 4 chars.
720 protected function get_faildump_filename(AfterStepScope $scope, $filetype) {
723 // All the contentdumps should be in the same parent dir.
724 if (!$faildumpdir = self::get_run_faildump_dir()) {
725 $faildumpdir = self::$faildumpdirname = date('Ymd_His');
727 $dir = $CFG->behat_faildump_path . DIRECTORY_SEPARATOR . $faildumpdir;
729 if (!is_dir($dir) && !mkdir($dir, $CFG->directorypermissions, true)) {
730 // It shouldn't, we already checked that the directory is writable.
731 throw new Exception('No directories can be created inside $CFG->behat_faildump_path, check the directory permissions.');
734 // We will always need to know the full path.
735 $dir = $CFG->behat_faildump_path . DIRECTORY_SEPARATOR . $faildumpdir;
738 // The scenario title + the failed step text.
739 // We want a i-am-the-scenario-title_i-am-the-failed-step.$filetype format.
740 $filename = $scope->getFeature()->getTitle() . '_' . $scope->getStep()->getText();
742 // As file name is limited to 255 characters. Leaving 5 chars for line number and 4 chars for the file.
743 // extension as we allow .png for images and .html for DOM contents.
746 // Suffix suite name to faildump file, if it's not default suite.
747 $suitename = $scope->getSuite()->getName();
748 if ($suitename != 'default') {
749 $suitename = '_' . $suitename;
750 $filenamelen = $filenamelen - strlen($suitename);
752 // No need to append suite name for default.
756 $filename = preg_replace('/([^a-zA-Z0-9\_]+)/', '-', $filename);
757 $filename = substr($filename, 0, $filenamelen) . $suitename . '_' . $scope->getStep()->getLine() . '.' . $filetype;
759 return array($dir, $filename);
763 * Internal step definition to find exceptions, debugging() messages and PHP debug messages.
765 * Part of behat_hooks class as is part of the testing framework, is auto-executed
766 * after each step so no features will splicitly use it.
768 * @Given /^I look for exceptions$/
769 * @throw Exception Unknown type, depending on what we caught in the hook or basic \Exception.
770 * @see Moodle\BehatExtension\EventDispatcher\Tester\ChainedStepTester
772 public function i_look_for_exceptions() {
773 // If the scenario already failed in a hook throw the exception.
774 if (!is_null(self::$currentscenarioexception)) {
775 throw self::$currentscenarioexception;
778 // If the step already failed in a hook throw the exception.
779 if (!is_null(self::$currentstepexception)) {
780 throw self::$currentstepexception;
783 $this->look_for_exceptions();
787 * Returns whether the first scenario of the suite is running
791 protected static function is_first_scenario() {
792 return !(self::$initprocessesfinished);
796 * Returns whether the first scenario of the suite is running
800 protected static function is_first_javascript_scenario(): bool {
801 return !self::$firstjavascriptscenarioseen;
805 * Register a set of component selectors.
807 * @param string $component
809 public function register_component_selectors_for_component(string $component): void {
810 $context = behat_context_helper::get_component_context($component);
812 if ($context === null) {
816 $namedpartial = $this->getSession()->getSelectorsHandler()->getSelector('named_partial');
817 $namedexact = $this->getSession()->getSelectorsHandler()->getSelector('named_exact');
819 // Replacements must come before selectors as they are used in the selectors.
820 foreach ($context->get_named_replacements() as $replacement) {
821 $namedpartial->register_replacement($component, $replacement);
822 $namedexact->register_replacement($component, $replacement);
825 foreach ($context->get_partial_named_selectors() as $selector) {
826 $namedpartial->register_component_selector($component, $selector);
829 foreach ($context->get_exact_named_selectors() as $selector) {
830 $namedexact->register_component_selector($component, $selector);
836 * Mark the first step as having been completed.
838 * This must be the last BeforeStep hook in the setup.
840 * @param BeforeStepScope $scope
843 public function first_step_setup_complete(BeforeStepScope $scope): void {
844 self::$initprocessesfinished = true;
848 * Log a notification, and then exit.
850 * @param string $message The content to dispaly
852 protected static function log_and_stop(string $message): void {