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\Behat\Event\SuiteEvent
as SuiteEvent
,
33 Behat\Behat\Event\ScenarioEvent
as ScenarioEvent
,
34 Behat\Behat\Event\StepEvent
as StepEvent
,
35 WebDriver\Exception\NoSuchWindow
as NoSuchWindow
;
38 * Hooks to the behat process.
40 * Behat accepts hooks after and before each
41 * suite, feature, scenario and step.
43 * They can not call other steps as part of their process
44 * like regular steps definitions does.
46 * Throws generic Exception because they are captured by Behat.
50 * @copyright 2012 David MonllaĆ³
51 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
53 class behat_hooks
extends behat_base
{
56 * Gives access to moodle codebase, ensures all is ready and sets up the test lock.
58 * Includes config.php to use moodle codebase with $CFG->behat_*
59 * instead of $CFG->prefix and $CFG->dataroot, called once per suite.
65 public static function before_suite($event) {
68 // To work with behat_dataroot and behat_prefix instead of the regular environment.
69 define('BEHAT_RUNNING', 1);
70 define('CLI_SCRIPT', 1);
72 // With BEHAT_RUNNING we will be using $CFG->behat_* instead of $CFG->dataroot, $CFG->prefix and $CFG->wwwroot.
73 require_once(__DIR__
. '/../../../config.php');
75 // Now that we are MOODLE_INTERNAL.
76 require_once(__DIR__
. '/../../behat/classes/behat_command.php');
77 require_once(__DIR__
. '/../../behat/classes/util.php');
78 require_once(__DIR__
. '/../../testing/classes/test_lock.php');
79 require_once(__DIR__
. '/../../testing/classes/nasty_strings.php');
81 // Avoids vendor/bin/behat to be executed directly without test environment enabled
82 // to prevent undesired db & dataroot modifications, this is also checked
83 // before each scenario (accidental user deletes) in the BeforeScenario hook.
85 if (!behat_util
::is_test_mode_enabled()) {
86 throw new Exception('Behat only can run if test mode is enabled. More info in ' . behat_command
::DOCS_URL
. '#Running_tests');
89 if (!behat_util
::is_server_running()) {
90 throw new Exception($CFG->behat_wwwroot
. ' is not available, ensure you started your PHP built-in server. More info in ' . behat_command
::DOCS_URL
. '#Running_tests');
93 // Prevents using outdated data, upgrade script would start and tests would fail.
94 if (!behat_util
::is_test_data_updated()) {
95 $commandpath = 'php admin/tool/behat/cli/util.php';
96 throw new Exception('Your behat test site is outdated, please run ' . $commandpath . ' from your moodle dirroot to drop and install the behat test site again.');
98 // Avoid parallel tests execution, it continues when the previous lock is released.
99 test_lock
::acquire('behat');
103 * Resets the test environment.
105 * @throws coding_exception If here we are not using the test database it should be because of a coding error
108 public function before_scenario($event) {
109 global $DB, $SESSION, $CFG;
111 // As many checks as we can.
112 if (!defined('BEHAT_RUNNING') ||
113 php_sapi_name() != 'cli' ||
114 !behat_util
::is_test_mode_enabled() ||
115 !behat_util
::is_test_site() ||
116 !isset($CFG->originaldataroot
)) {
117 throw new coding_exception('Behat only can modify the test database and the test dataroot!');
120 // Avoid some notices / warnings.
121 $SESSION = new stdClass();
123 behat_util
::reset_database();
124 behat_util
::reset_dataroot();
127 accesslib_clear_all_caches(true);
129 // Reset the nasty strings list used during the last test.
130 nasty_strings
::reset_used_strings();
132 // Assing valid data to admin user (some generator-related code needs a valid user).
133 $user = $DB->get_record('user', array('username' => 'admin'));
134 session_set_user($user);
136 // Start always in the the homepage.
137 $this->getSession()->visit($this->locate_path('/'));
141 * Ensures selenium is running.
143 * Is only executed in scenarios which requires Javascript to run,
144 * it returns a direct error message about what's going on.
147 * @BeforeScenario @javascript
149 public function before_scenario_javascript($event) {
151 // Just trying if server responds.
153 $this->getSession()->executeScript('// empty comment');
154 } catch (Exception
$e) {
155 $moreinfo = 'More info in ' . behat_command
::DOCS_URL
. '#Running_tests';
156 $msg = 'Selenium server is not running, you need to start it to run tests that involves Javascript. ' . $moreinfo;
157 throw new Exception($msg);
162 * Checks that all DOM is ready.
164 * Executed only when running against a real browser.
166 * @AfterStep @javascript
168 public function after_step_javascript($event) {
170 // If it doesn't have definition or it fails there is no need to check it.
171 if ($event->getResult() != StepEvent
::PASSED ||
172 !$event->hasDefinition()) {
176 // Wait until the page is ready.
178 $this->getSession()->wait(self
::TIMEOUT
, '(document.readyState === "complete")');
179 } catch (NoSuchWindow
$e) {
180 // If we were interacting with a popup window it will not exists after closing it.
185 * Internal step definition to find exceptions, debugging() messages and PHP debug messages.
187 * Part of behat_hooks class as is part of the testing framework, is auto-executed
188 * after each step so no features will splicitly use it.
190 * @Given /^I look for exceptions$/
191 * @see Moodle\BehatExtension\Tester\MoodleStepTester
193 public function i_look_for_exceptions() {
196 if ($errormsg = $this->getSession()->getPage()->find('css', '.errorbox p.errormessage')) {
198 // Getting the debugging info and the backtrace.
199 $errorinfoboxes = $this->getSession()->getPage()->findAll('css', 'div.notifytiny');
200 $errorinfo = $this->get_debug_text($errorinfoboxes[0]->getHtml()) . "\n" .
201 $this->get_debug_text($errorinfoboxes[1]->getHtml());
203 $msg = "Moodle exception: " . $errormsg->getText() . "\n" . $errorinfo;
204 throw new \
Exception(html_entity_decode($msg));
207 // Debugging messages.
208 if ($debuggingmessages = $this->getSession()->getPage()->findAll('css', '.debuggingmessage')) {
210 foreach ($debuggingmessages as $debuggingmessage) {
211 $msgs[] = $this->get_debug_text($debuggingmessage->getHtml());
213 $msg = "debugging() message/s found:\n" . implode("\n", $msgs);
214 throw new \
Exception(html_entity_decode($msg));
217 // PHP debug messages.
218 if ($phpmessages = $this->getSession()->getPage()->findAll('css', '.phpdebugmessage')) {
221 foreach ($phpmessages as $phpmessage) {
222 $msgs[] = $this->get_debug_text($phpmessage->getHtml());
224 $msg = "PHP debug message/s found:\n" . implode("\n", $msgs);
225 throw new \
Exception(html_entity_decode($msg));
230 * Converts HTML tags to line breaks to display the info in CLI
232 * @param string $html
235 protected function get_debug_text($html) {
237 // Replacing HTML tags for new lines and keeping only the text.
238 $notags = preg_replace('/<+\s*\/*\s*([A-Z][A-Z0-9]*)\b[^>]*\/*\s*>*/i', "\n", $html);
239 return preg_replace("/(\n)+/s", "\n", $notags);