Merge branch 'MDL-41840-master' of git://github.com/sammarshallou/moodle
[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,
3b7d3fb8
DM
37 WebDriver\Exception\UnknownError as UnknownError,
38 WebDriver\Exception\CurlExec as CurlExec,
870349ee 39 WebDriver\Exception\NoAlertOpenError as NoAlertOpenError;
f5ceb6c2
DM
40
41/**
42 * Hooks to the behat process.
43 *
44 * Behat accepts hooks after and before each
45 * suite, feature, scenario and step.
46 *
47 * They can not call other steps as part of their process
48 * like regular steps definitions does.
49 *
50 * Throws generic Exception because they are captured by Behat.
51 *
52 * @package core
53 * @category test
54 * @copyright 2012 David Monllaó
55 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
56 */
57class behat_hooks extends behat_base {
58
41eb672b
DM
59 /**
60 * @var Last browser session start time.
61 */
62 protected static $lastbrowsersessionstart = 0;
63
95b43d6b
DM
64 /**
65 * @var For actions that should only run once.
66 */
67 protected static $initprocessesfinished = false;
68
f5ceb6c2
DM
69 /**
70 * Gives access to moodle codebase, ensures all is ready and sets up the test lock.
71 *
72 * Includes config.php to use moodle codebase with $CFG->behat_*
73 * instead of $CFG->prefix and $CFG->dataroot, called once per suite.
74 *
75 * @static
76 * @throws Exception
77 * @BeforeSuite
78 */
79 public static function before_suite($event) {
80 global $CFG;
81
cfcbc34a
DM
82 // Defined only when the behat CLI command is running, the moodle init setup process will
83 // read this value and switch to $CFG->behat_dataroot and $CFG->behat_prefix instead of
84 // the normal site.
85 define('BEHAT_TEST', 1);
86
f5ceb6c2
DM
87 define('CLI_SCRIPT', 1);
88
cfcbc34a 89 // With BEHAT_TEST we will be using $CFG->behat_* instead of $CFG->dataroot, $CFG->prefix and $CFG->wwwroot.
f5ceb6c2
DM
90 require_once(__DIR__ . '/../../../config.php');
91
92 // Now that we are MOODLE_INTERNAL.
93 require_once(__DIR__ . '/../../behat/classes/behat_command.php');
17344d4c 94 require_once(__DIR__ . '/../../behat/classes/behat_selectors.php');
f5ceb6c2
DM
95 require_once(__DIR__ . '/../../behat/classes/util.php');
96 require_once(__DIR__ . '/../../testing/classes/test_lock.php');
b08b0a28 97 require_once(__DIR__ . '/../../testing/classes/nasty_strings.php');
f5ceb6c2
DM
98
99 // Avoids vendor/bin/behat to be executed directly without test environment enabled
100 // to prevent undesired db & dataroot modifications, this is also checked
101 // before each scenario (accidental user deletes) in the BeforeScenario hook.
102
103 if (!behat_util::is_test_mode_enabled()) {
104 throw new Exception('Behat only can run if test mode is enabled. More info in ' . behat_command::DOCS_URL . '#Running_tests');
105 }
106
107 if (!behat_util::is_server_running()) {
3b7d3fb8
DM
108 throw new Exception($CFG->behat_wwwroot .
109 ' is not available, ensure you started your PHP built-in server or your web server is correctly started and set up.' .
110 ' More info in ' . behat_command::DOCS_URL . '#Running_tests');
f5ceb6c2
DM
111 }
112
b831d479
DM
113 // Prevents using outdated data, upgrade script would start and tests would fail.
114 if (!behat_util::is_test_data_updated()) {
b32ca4ca 115 $commandpath = 'php admin/tool/behat/cli/init.php';
b831d479
DM
116 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.');
117 }
f5ceb6c2
DM
118 // Avoid parallel tests execution, it continues when the previous lock is released.
119 test_lock::acquire('behat');
41eb672b
DM
120
121 // Store the browser reset time if reset after N seconds is specified in config.php.
122 if (!empty($CFG->behat_restart_browser_after)) {
123 // Store the initial browser session opening.
124 self::$lastbrowsersessionstart = time();
125 }
f5ceb6c2
DM
126 }
127
128 /**
129 * Resets the test environment.
130 *
131 * @throws coding_exception If here we are not using the test database it should be because of a coding error
132 * @BeforeScenario
133 */
134 public function before_scenario($event) {
135 global $DB, $SESSION, $CFG;
136
137 // As many checks as we can.
cfcbc34a
DM
138 if (!defined('BEHAT_TEST') ||
139 !defined('BEHAT_SITE_RUNNING') ||
f5ceb6c2
DM
140 php_sapi_name() != 'cli' ||
141 !behat_util::is_test_mode_enabled() ||
cfcbc34a 142 !behat_util::is_test_site()) {
46ac40cd 143 throw new coding_exception('Behat only can modify the test database and the test dataroot!');
f5ceb6c2
DM
144 }
145
f59f6b6b
DM
146 try {
147 $session = $this->getSession();
148 } catch (CurlExec $e) {
149 // Exception thrown by WebDriver, so only @javascript tests will be caugth; in
150 // behat_util::is_server_running() we already checked that the server is running.
151 $moreinfo = 'More info in ' . behat_command::DOCS_URL . '#Running_tests';
152 $msg = 'Selenium server is not running, you need to start it to run tests that involve Javascript. ' . $moreinfo;
153 throw new Exception($msg);
154 } catch (UnknownError $e) {
155 // Generic 'I have no idea' Selenium error. Custom exception to provide more feedback about possible solutions.
156 $this->throw_unknown_exception($e);
157 }
158
159
17344d4c
DM
160 // We need the Mink session to do it and we do it only before the first scenario.
161 if (self::is_first_scenario()) {
f59f6b6b 162 behat_selectors::register_moodle_selectors($session);
17344d4c
DM
163 }
164
c8619f33
DM
165 // Avoid some notices / warnings.
166 $SESSION = new stdClass();
167
f5ceb6c2
DM
168 behat_util::reset_database();
169 behat_util::reset_dataroot();
170
10dd80c2
DM
171 purge_all_caches();
172 accesslib_clear_all_caches(true);
173
b08b0a28
DM
174 // Reset the nasty strings list used during the last test.
175 nasty_strings::reset_used_strings();
176
f5ceb6c2
DM
177 // Assing valid data to admin user (some generator-related code needs a valid user).
178 $user = $DB->get_record('user', array('username' => 'admin'));
d79d5ac2 179 \core\session\manager::set_user($user);
5f4b4e91 180
41eb672b
DM
181 // Reset the browser if specified in config.php.
182 if (!empty($CFG->behat_restart_browser_after) && $this->running_javascript()) {
183 $now = time();
184 if (self::$lastbrowsersessionstart + $CFG->behat_restart_browser_after < $now) {
f59f6b6b 185 $session->restart();
41eb672b
DM
186 self::$lastbrowsersessionstart = $now;
187 }
188 }
189
5f4b4e91 190 // Start always in the the homepage.
3b7d3fb8 191 try {
f59f6b6b
DM
192 // Let's be conservative as we never know when new upstream issues will affect us.
193 $session->visit($this->locate_path('/'));
3b7d3fb8 194 } catch (UnknownError $e) {
3b7d3fb8
DM
195 $this->throw_unknown_exception($e);
196 }
870349ee 197
f59f6b6b 198
95b43d6b
DM
199 // Checking that the root path is a Moodle test site.
200 if (self::is_first_scenario()) {
201 $notestsiteexception = new Exception('The base URL (' . $CFG->wwwroot . ') is not a behat test site, ' .
3b7d3fb8 202 'ensure you started the built-in web server in the correct directory or your web server is correctly started and set up');
19f6703d 203 $this->find("xpath", "//head/child::title[normalize-space(.)='" . behat_util::BEHATSITENAME . "']", $notestsiteexception);
95b43d6b
DM
204
205 self::$initprocessesfinished = true;
206 }
207
870349ee
DM
208 // Closing JS dialogs if present. Otherwise they would block this scenario execution.
209 if ($this->running_javascript()) {
210 try {
f59f6b6b 211 $session->getDriver()->getWebDriverSession()->accept_alert();
870349ee
DM
212 } catch (NoAlertOpenError $e) {
213 // All ok, there should not be JS dialogs in theory.
214 }
215 }
216
f5ceb6c2
DM
217 }
218
f5ceb6c2
DM
219 /**
220 * Checks that all DOM is ready.
221 *
222 * Executed only when running against a real browser.
223 *
224 * @AfterStep @javascript
225 */
226 public function after_step_javascript($event) {
227
228 // If it doesn't have definition or it fails there is no need to check it.
229 if ($event->getResult() != StepEvent::PASSED ||
230 !$event->hasDefinition()) {
231 return;
232 }
233
28abad1a
DM
234 // Wait until the page is ready.
235 // We are already checking that we use a JS browser, this could
236 // change in case we use another JS driver.
237 try {
238
239 // Safari and Internet Explorer requires time between steps,
240 // otherwise Selenium tries to click in the previous page's DOM.
241 if ($this->getSession()->getDriver()->getBrowserName() == 'safari' ||
242 $this->getSession()->getDriver()->getBrowserName() == 'internet explorer') {
243 $this->getSession()->wait(self::TIMEOUT * 1000, false);
244
245 } else {
246 // With other browsers we just wait for the DOM ready.
247 $this->getSession()->wait(self::TIMEOUT * 1000, '(document.readyState === "complete")');
248 }
249
1303eb29
DM
250 } catch (NoSuchWindow $e) {
251 // If we were interacting with a popup window it will not exists after closing it.
3b7d3fb8
DM
252 } catch (UnknownError $e) {
253 // Custom exception to provide more feedback about possible solutions.
254 $this->throw_unknown_exception($e);
1303eb29 255 }
f5ceb6c2
DM
256 }
257
5f4b4e91
DM
258 /**
259 * Internal step definition to find exceptions, debugging() messages and PHP debug messages.
260 *
261 * Part of behat_hooks class as is part of the testing framework, is auto-executed
262 * after each step so no features will splicitly use it.
263 *
264 * @Given /^I look for exceptions$/
265 * @see Moodle\BehatExtension\Tester\MoodleStepTester
266 */
267 public function i_look_for_exceptions() {
268
217e8e59
DM
269 // Wrap in try in case we were interacting with a closed window.
270 try {
5f4b4e91 271
217e8e59 272 // Exceptions.
3e76c7fa 273 $exceptionsxpath = "//div[@data-rel='fatalerror']";
8aea365f 274 // Debugging messages.
3e76c7fa 275 $debuggingxpath = "//div[@data-rel='debugging']";
8aea365f 276 // PHP debug messages.
3e76c7fa 277 $phperrorxpath = "//div[@data-rel='phpdebugmessage']";
8aea365f 278 // Any other backtrace.
6cd21356 279 $othersxpath = "(//*[contains(., ': call to ')])[1]";
8aea365f
DM
280
281 $xpaths = array($exceptionsxpath, $debuggingxpath, $phperrorxpath, $othersxpath);
282 $joinedxpath = implode(' | ', $xpaths);
283
284 // Joined xpath expression. Most of the time there will be no exceptions, so this pre-check
285 // is faster than to send the 4 xpath queries for each step.
286 if (!$this->getSession()->getDriver()->find($joinedxpath)) {
287 return;
288 }
289
290 // Exceptions.
291 if ($errormsg = $this->getSession()->getPage()->find('xpath', $exceptionsxpath)) {
5f4b4e91 292
217e8e59
DM
293 // Getting the debugging info and the backtrace.
294 $errorinfoboxes = $this->getSession()->getPage()->findAll('css', 'div.notifytiny');
295 $errorinfo = $this->get_debug_text($errorinfoboxes[0]->getHtml()) . "\n" .
296 $this->get_debug_text($errorinfoboxes[1]->getHtml());
5f4b4e91 297
217e8e59
DM
298 $msg = "Moodle exception: " . $errormsg->getText() . "\n" . $errorinfo;
299 throw new \Exception(html_entity_decode($msg));
300 }
301
302 // Debugging messages.
8aea365f 303 if ($debuggingmessages = $this->getSession()->getPage()->findAll('xpath', $debuggingxpath)) {
217e8e59
DM
304 $msgs = array();
305 foreach ($debuggingmessages as $debuggingmessage) {
306 $msgs[] = $this->get_debug_text($debuggingmessage->getHtml());
307 }
308 $msg = "debugging() message/s found:\n" . implode("\n", $msgs);
309 throw new \Exception(html_entity_decode($msg));
5f4b4e91 310 }
90ed22ab 311
217e8e59 312 // PHP debug messages.
8aea365f 313 if ($phpmessages = $this->getSession()->getPage()->findAll('xpath', $phperrorxpath)) {
90ed22ab 314
217e8e59
DM
315 $msgs = array();
316 foreach ($phpmessages as $phpmessage) {
317 $msgs[] = $this->get_debug_text($phpmessage->getHtml());
318 }
319 $msg = "PHP debug message/s found:\n" . implode("\n", $msgs);
320 throw new \Exception(html_entity_decode($msg));
90ed22ab 321 }
bbd802f7 322
217e8e59 323 // Any other backtrace.
9a1f4922
DM
324 // First looking through xpath as it is faster than get and parse the whole page contents,
325 // we get the contents and look for matches once we found something to suspect that there is a backtrace.
8aea365f 326 if ($this->getSession()->getDriver()->find($othersxpath)) {
9a1f4922
DM
327 $backtracespattern = '/(line [0-9]* of [^:]*: call to [\->&;:a-zA-Z_\x7f-\xff][\->&;:a-zA-Z0-9_\x7f-\xff]*)/';
328 if (preg_match_all($backtracespattern, $this->getSession()->getPage()->getContent(), $backtraces)) {
329 $msgs = array();
330 foreach ($backtraces[0] as $backtrace) {
331 $msgs[] = $backtrace . '()';
332 }
333 $msg = "Other backtraces found:\n" . implode("\n", $msgs);
334 throw new \Exception(htmlentities($msg));
217e8e59 335 }
bbd802f7 336 }
217e8e59
DM
337
338 } catch (NoSuchWindow $e) {
339 // If we were interacting with a popup window it will not exists after closing it.
870349ee
DM
340 } catch (UnexpectedAlertOpen $e) {
341 // We fail the scenario if we find an opened JS alert/confirm, in most of the cases it
342 // will be there because we are leaving an edited form without submitting/cancelling
343 // it, but moodle is using JS confirms and we can not just cancel the JS dialog
344 // as in some cases (delete activity with JS enabled for example) the test writer should
345 // use extra steps to deal with moodle's behaviour.
346 throw new Exception('Modal window present. Ensure there are no edited forms pending to submit/cancel.');
bbd802f7 347 }
5f4b4e91
DM
348 }
349
350 /**
351 * Converts HTML tags to line breaks to display the info in CLI
352 *
353 * @param string $html
354 * @return string
355 */
356 protected function get_debug_text($html) {
357
358 // Replacing HTML tags for new lines and keeping only the text.
359 $notags = preg_replace('/<+\s*\/*\s*([A-Z][A-Z0-9]*)\b[^>]*\/*\s*>*/i', "\n", $html);
360 return preg_replace("/(\n)+/s", "\n", $notags);
361 }
362
95b43d6b
DM
363 /**
364 * Returns whether the first scenario of the suite is running
365 *
366 * @return bool
367 */
368 protected static function is_first_scenario() {
369 return !(self::$initprocessesfinished);
370 }
3b7d3fb8
DM
371
372 /**
373 * Throws an exception after appending an extra info text.
374 *
375 * @throws Exception
376 * @param UnknownError $exception
377 * @return void
378 */
379 protected function throw_unknown_exception(UnknownError $exception) {
380 $text = get_string('unknownexceptioninfo', 'tool_behat');
381 throw new Exception($text . PHP_EOL . $exception->getMessage());
382 }
383
f5ceb6c2 384}