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