MDL-39686 behat: Adding into to config-dist.php
[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
1303eb29
DM
32use Behat\Behat\Event\SuiteEvent as SuiteEvent,
33 Behat\Behat\Event\ScenarioEvent as ScenarioEvent,
34 Behat\Behat\Event\StepEvent as StepEvent,
870349ee
DM
35 WebDriver\Exception\NoSuchWindow as NoSuchWindow,
36 WebDriver\Exception\UnexpectedAlertOpen as UnexpectedAlertOpen,
37 WebDriver\Exception\NoAlertOpenError as NoAlertOpenError;
f5ceb6c2
DM
38
39/**
40 * Hooks to the behat process.
41 *
42 * Behat accepts hooks after and before each
43 * suite, feature, scenario and step.
44 *
45 * They can not call other steps as part of their process
46 * like regular steps definitions does.
47 *
48 * Throws generic Exception because they are captured by Behat.
49 *
50 * @package core
51 * @category test
52 * @copyright 2012 David MonllaĆ³
53 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
54 */
55class behat_hooks extends behat_base {
56
f5ceb6c2
DM
57 /**
58 * Gives access to moodle codebase, ensures all is ready and sets up the test lock.
59 *
60 * Includes config.php to use moodle codebase with $CFG->behat_*
61 * instead of $CFG->prefix and $CFG->dataroot, called once per suite.
62 *
63 * @static
64 * @throws Exception
65 * @BeforeSuite
66 */
67 public static function before_suite($event) {
68 global $CFG;
69
cfcbc34a
DM
70 // Defined only when the behat CLI command is running, the moodle init setup process will
71 // read this value and switch to $CFG->behat_dataroot and $CFG->behat_prefix instead of
72 // the normal site.
73 define('BEHAT_TEST', 1);
74
f5ceb6c2
DM
75 define('CLI_SCRIPT', 1);
76
cfcbc34a 77 // With BEHAT_TEST we will be using $CFG->behat_* instead of $CFG->dataroot, $CFG->prefix and $CFG->wwwroot.
f5ceb6c2
DM
78 require_once(__DIR__ . '/../../../config.php');
79
80 // Now that we are MOODLE_INTERNAL.
81 require_once(__DIR__ . '/../../behat/classes/behat_command.php');
82 require_once(__DIR__ . '/../../behat/classes/util.php');
83 require_once(__DIR__ . '/../../testing/classes/test_lock.php');
b08b0a28 84 require_once(__DIR__ . '/../../testing/classes/nasty_strings.php');
f5ceb6c2
DM
85
86 // Avoids vendor/bin/behat to be executed directly without test environment enabled
87 // to prevent undesired db & dataroot modifications, this is also checked
88 // before each scenario (accidental user deletes) in the BeforeScenario hook.
89
90 if (!behat_util::is_test_mode_enabled()) {
91 throw new Exception('Behat only can run if test mode is enabled. More info in ' . behat_command::DOCS_URL . '#Running_tests');
92 }
93
94 if (!behat_util::is_server_running()) {
95 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');
96 }
97
b831d479
DM
98 // Prevents using outdated data, upgrade script would start and tests would fail.
99 if (!behat_util::is_test_data_updated()) {
b32ca4ca 100 $commandpath = 'php admin/tool/behat/cli/init.php';
b831d479
DM
101 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.');
102 }
f5ceb6c2
DM
103 // Avoid parallel tests execution, it continues when the previous lock is released.
104 test_lock::acquire('behat');
105 }
106
107 /**
108 * Resets the test environment.
109 *
110 * @throws coding_exception If here we are not using the test database it should be because of a coding error
111 * @BeforeScenario
112 */
113 public function before_scenario($event) {
114 global $DB, $SESSION, $CFG;
115
116 // As many checks as we can.
cfcbc34a
DM
117 if (!defined('BEHAT_TEST') ||
118 !defined('BEHAT_SITE_RUNNING') ||
f5ceb6c2
DM
119 php_sapi_name() != 'cli' ||
120 !behat_util::is_test_mode_enabled() ||
cfcbc34a 121 !behat_util::is_test_site()) {
46ac40cd 122 throw new coding_exception('Behat only can modify the test database and the test dataroot!');
f5ceb6c2
DM
123 }
124
c8619f33
DM
125 // Avoid some notices / warnings.
126 $SESSION = new stdClass();
127
f5ceb6c2
DM
128 behat_util::reset_database();
129 behat_util::reset_dataroot();
130
10dd80c2
DM
131 purge_all_caches();
132 accesslib_clear_all_caches(true);
133
b08b0a28
DM
134 // Reset the nasty strings list used during the last test.
135 nasty_strings::reset_used_strings();
136
f5ceb6c2
DM
137 // Assing valid data to admin user (some generator-related code needs a valid user).
138 $user = $DB->get_record('user', array('username' => 'admin'));
139 session_set_user($user);
5f4b4e91
DM
140
141 // Start always in the the homepage.
142 $this->getSession()->visit($this->locate_path('/'));
870349ee
DM
143
144 // Closing JS dialogs if present. Otherwise they would block this scenario execution.
145 if ($this->running_javascript()) {
146 try {
147 $this->getSession()->getDriver()->getWebDriverSession()->accept_alert();
148 } catch (NoAlertOpenError $e) {
149 // All ok, there should not be JS dialogs in theory.
150 }
151 }
152
f5ceb6c2
DM
153 }
154
155 /**
156 * Ensures selenium is running.
157 *
158 * Is only executed in scenarios which requires Javascript to run,
159 * it returns a direct error message about what's going on.
160 *
161 * @throws Exception
162 * @BeforeScenario @javascript
163 */
164 public function before_scenario_javascript($event) {
165
166 // Just trying if server responds.
167 try {
c59e52f5 168 $this->getSession()->wait(0, false);
f5ceb6c2
DM
169 } catch (Exception $e) {
170 $moreinfo = 'More info in ' . behat_command::DOCS_URL . '#Running_tests';
171 $msg = 'Selenium server is not running, you need to start it to run tests that involves Javascript. ' . $moreinfo;
172 throw new Exception($msg);
173 }
174 }
175
176 /**
177 * Checks that all DOM is ready.
178 *
179 * Executed only when running against a real browser.
180 *
181 * @AfterStep @javascript
182 */
183 public function after_step_javascript($event) {
184
185 // If it doesn't have definition or it fails there is no need to check it.
186 if ($event->getResult() != StepEvent::PASSED ||
187 !$event->hasDefinition()) {
188 return;
189 }
190
28abad1a
DM
191 // Wait until the page is ready.
192 // We are already checking that we use a JS browser, this could
193 // change in case we use another JS driver.
194 try {
195
196 // Safari and Internet Explorer requires time between steps,
197 // otherwise Selenium tries to click in the previous page's DOM.
198 if ($this->getSession()->getDriver()->getBrowserName() == 'safari' ||
199 $this->getSession()->getDriver()->getBrowserName() == 'internet explorer') {
200 $this->getSession()->wait(self::TIMEOUT * 1000, false);
201
202 } else {
203 // With other browsers we just wait for the DOM ready.
204 $this->getSession()->wait(self::TIMEOUT * 1000, '(document.readyState === "complete")');
205 }
206
1303eb29
DM
207 } catch (NoSuchWindow $e) {
208 // If we were interacting with a popup window it will not exists after closing it.
209 }
f5ceb6c2
DM
210 }
211
5f4b4e91
DM
212 /**
213 * Internal step definition to find exceptions, debugging() messages and PHP debug messages.
214 *
215 * Part of behat_hooks class as is part of the testing framework, is auto-executed
216 * after each step so no features will splicitly use it.
217 *
218 * @Given /^I look for exceptions$/
219 * @see Moodle\BehatExtension\Tester\MoodleStepTester
220 */
221 public function i_look_for_exceptions() {
222
217e8e59
DM
223 // Wrap in try in case we were interacting with a closed window.
224 try {
5f4b4e91 225
217e8e59
DM
226 // Exceptions.
227 if ($errormsg = $this->getSession()->getPage()->find('css', '.errorbox p.errormessage')) {
5f4b4e91 228
217e8e59
DM
229 // Getting the debugging info and the backtrace.
230 $errorinfoboxes = $this->getSession()->getPage()->findAll('css', 'div.notifytiny');
231 $errorinfo = $this->get_debug_text($errorinfoboxes[0]->getHtml()) . "\n" .
232 $this->get_debug_text($errorinfoboxes[1]->getHtml());
5f4b4e91 233
217e8e59
DM
234 $msg = "Moodle exception: " . $errormsg->getText() . "\n" . $errorinfo;
235 throw new \Exception(html_entity_decode($msg));
236 }
237
238 // Debugging messages.
239 if ($debuggingmessages = $this->getSession()->getPage()->findAll('css', '.debuggingmessage')) {
240 $msgs = array();
241 foreach ($debuggingmessages as $debuggingmessage) {
242 $msgs[] = $this->get_debug_text($debuggingmessage->getHtml());
243 }
244 $msg = "debugging() message/s found:\n" . implode("\n", $msgs);
245 throw new \Exception(html_entity_decode($msg));
5f4b4e91 246 }
90ed22ab 247
217e8e59
DM
248 // PHP debug messages.
249 if ($phpmessages = $this->getSession()->getPage()->findAll('css', '.phpdebugmessage')) {
90ed22ab 250
217e8e59
DM
251 $msgs = array();
252 foreach ($phpmessages as $phpmessage) {
253 $msgs[] = $this->get_debug_text($phpmessage->getHtml());
254 }
255 $msg = "PHP debug message/s found:\n" . implode("\n", $msgs);
256 throw new \Exception(html_entity_decode($msg));
90ed22ab 257 }
bbd802f7 258
217e8e59
DM
259 // Any other backtrace.
260 $backtracespattern = '/(line [0-9]* of [^:]*: call to [\->&;:a-zA-Z_\x7f-\xff][\->&;:a-zA-Z0-9_\x7f-\xff]*)/';
261 if (preg_match_all($backtracespattern, $this->getSession()->getPage()->getContent(), $backtraces)) {
262 $msgs = array();
263 foreach ($backtraces[0] as $backtrace) {
264 $msgs[] = $backtrace . '()';
265 }
266 $msg = "Other backtraces found:\n" . implode("\n", $msgs);
267 throw new \Exception(htmlentities($msg));
bbd802f7 268 }
217e8e59
DM
269
270 } catch (NoSuchWindow $e) {
271 // If we were interacting with a popup window it will not exists after closing it.
870349ee
DM
272 } catch (UnexpectedAlertOpen $e) {
273 // We fail the scenario if we find an opened JS alert/confirm, in most of the cases it
274 // will be there because we are leaving an edited form without submitting/cancelling
275 // it, but moodle is using JS confirms and we can not just cancel the JS dialog
276 // as in some cases (delete activity with JS enabled for example) the test writer should
277 // use extra steps to deal with moodle's behaviour.
278 throw new Exception('Modal window present. Ensure there are no edited forms pending to submit/cancel.');
bbd802f7 279 }
5f4b4e91
DM
280 }
281
282 /**
283 * Converts HTML tags to line breaks to display the info in CLI
284 *
285 * @param string $html
286 * @return string
287 */
288 protected function get_debug_text($html) {
289
290 // Replacing HTML tags for new lines and keeping only the text.
291 $notags = preg_replace('/<+\s*\/*\s*([A-Z][A-Z0-9]*)\b[^>]*\/*\s*>*/i', "\n", $html);
292 return preg_replace("/(\n)+/s", "\n", $notags);
293 }
294
f5ceb6c2 295}