Merge branch 'MDL-79498-402' of https://github.com/junpataleta/moodle into MOODLE_402...
[moodle.git] / lib / testing / lib.php
blob5622537a9a2eef0e05997c2e663cc2de30af89a9
1 <?php
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.
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/>.
17 /**
18 * Testing general functions
20 * Note: these functions must be self contained and must not rely on any library or include
22 * @package core
23 * @category test
24 * @copyright 2012 Petr Skoda {@link http://skodak.org}
25 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
28 /**
29 * Composer error exit status.
31 * @var int
33 define('TESTING_EXITCODE_COMPOSER', 255);
35 /**
36 * Returns relative path against current working directory,
37 * to be used for shell execution hints.
38 * @param string $moodlepath starting with "/", ex: "/admin/tool/cli/init.php"
39 * @return string path relative to current directory or absolute path
41 function testing_cli_argument_path($moodlepath) {
42 global $CFG;
44 if (isset($CFG->admin) and $CFG->admin !== 'admin') {
45 $moodlepath = preg_replace('|^/admin/|', "/$CFG->admin/", $moodlepath);
48 if (isset($_SERVER['REMOTE_ADDR'])) {
49 // Web access, this should not happen often.
50 $cwd = dirname(dirname(__DIR__));
51 } else {
52 // This is the real CLI script, work with relative paths.
53 $cwd = getcwd();
56 // Remove last directory separator as $path will not contain one.
57 if ((substr($cwd, -1) === '/') || (substr($cwd, -1) === '\\')) {
58 $cwd = substr($cwd, -1);
61 $path = realpath($CFG->dirroot.$moodlepath);
63 // We need standrad directory seperator for path and cwd, so it can be compared.
64 $cwd = testing_cli_fix_directory_separator($cwd);
65 $path = testing_cli_fix_directory_separator($path);
67 if (strpos($path, $cwd) === 0) {
68 // Remove current working directory and directory separator.
69 $path = substr($path, strlen($cwd) + 1);
72 return $path;
75 /**
76 * Try to change permissions to $CFG->dirroot or $CFG->dataroot if possible
77 * @param string $file
78 * @return bool success
80 function testing_fix_file_permissions($file) {
81 global $CFG;
83 $permissions = fileperms($file);
84 if ($permissions & $CFG->filepermissions != $CFG->filepermissions) {
85 $permissions = $permissions | $CFG->filepermissions;
86 return chmod($file, $permissions);
89 return true;
92 /**
93 * Find out if running under Cygwin on Windows.
94 * @return bool
96 function testing_is_cygwin() {
97 if (empty($_SERVER['OS']) or $_SERVER['OS'] !== 'Windows_NT') {
98 return false;
100 } else if (!empty($_SERVER['SHELL']) and $_SERVER['SHELL'] === '/bin/bash') {
101 return true;
103 } else if (!empty($_SERVER['TERM']) and $_SERVER['TERM'] === 'cygwin') {
104 return true;
106 } else {
107 return false;
112 * Returns whether a mingw CLI is running.
114 * MinGW sets $_SERVER['TERM'] to cygwin, but it
115 * can not run .bat files; this function may be useful
116 * when we need to output proposed commands to users
117 * using Windows CLI interfaces.
119 * @link http://sourceforge.net/p/mingw/bugs/1902
120 * @return bool
122 function testing_is_mingw() {
124 if (!testing_is_cygwin()) {
125 return false;
128 if (!empty($_SERVER['MSYSTEM'])) {
129 return true;
132 return false;
136 * Mark empty dataroot to be used for testing.
137 * @param string $dataroot The dataroot directory
138 * @param string $framework The test framework
139 * @return void
141 function testing_initdataroot($dataroot, $framework) {
142 global $CFG;
144 $filename = $dataroot . '/' . $framework . 'testdir.txt';
146 umask(0);
147 if (!file_exists($filename)) {
148 file_put_contents($filename, 'Contents of this directory are used during tests only, do not delete this file!');
150 testing_fix_file_permissions($filename);
152 $varname = $framework . '_dataroot';
153 $datarootdir = $CFG->{$varname} . '/' . $framework;
154 if (!file_exists($datarootdir)) {
155 mkdir($datarootdir, $CFG->directorypermissions);
160 * Prints an error and stops execution
162 * @param integer $errorcode
163 * @param string $text
164 * @return void exits
166 function testing_error($errorcode, $text = '') {
168 // do not write to error stream because we need the error message in PHP exec result from web ui
169 echo($text."\n");
170 if (isset($_SERVER['REMOTE_ADDR'])) {
171 header('HTTP/1.1 500 Internal Server Error');
173 exit($errorcode);
177 * Perform necessary steps to install and/or upgrade composer and its dependencies.
179 * Installation is mandatory, but upgrade is optional.
181 * Note: This function does not return, but will call `exit()` on error.
183 * @param bool $selfupdate Perform a composer self-update to update the composer.phar utility
184 * @param bool $updatedependencies Upgrade dependencies
186 function testing_update_composer_dependencies(bool $selfupdate = true, bool $updatedependencies = true): void {
187 // To restore the value after finishing.
188 $cwd = getcwd();
190 // Set some paths.
191 $dirroot = dirname(dirname(__DIR__));
193 // Switch to Moodle's dirroot for easier path handling.
194 chdir($dirroot);
196 // Download or update composer.phar. Unfortunately we can't use the curl
197 // class in filelib.php as we're running within one of the test platforms.
198 $composerpath = $dirroot . DIRECTORY_SEPARATOR . 'composer.phar';
199 if (!file_exists($composerpath)) {
200 $composerurl = 'https://getcomposer.org/composer.phar';
201 $file = @fopen($composerpath, 'w');
202 if ($file === false) {
203 $errordetails = error_get_last();
204 $error = sprintf("Unable to create composer.phar\nPHP error: %s",
205 $errordetails['message']);
206 testing_error(TESTING_EXITCODE_COMPOSER, $error);
208 $curl = curl_init();
210 curl_setopt($curl, CURLOPT_URL, $composerurl);
211 curl_setopt($curl, CURLOPT_FILE, $file);
212 $result = curl_exec($curl);
214 $curlerrno = curl_errno($curl);
215 $curlerror = curl_error($curl);
216 $curlinfo = curl_getinfo($curl);
218 curl_close($curl);
219 fclose($file);
221 if (!$result) {
222 $error = sprintf("Unable to download composer.phar\ncURL error (%d): %s",
223 $curlerrno, $curlerror);
224 testing_error(TESTING_EXITCODE_COMPOSER, $error);
225 } else if ($curlinfo['http_code'] === 404) {
226 if (file_exists($composerpath)) {
227 // Deleting the resource as it would contain HTML.
228 unlink($composerpath);
230 $error = sprintf("Unable to download composer.phar\n" .
231 "404 http status code fetching $composerurl");
232 testing_error(TESTING_EXITCODE_COMPOSER, $error);
235 // Do not self-update after installation.
236 $selfupdate = false;
239 if ($selfupdate) {
240 passthru("php composer.phar self-update", $code);
241 if ($code != 0) {
242 exit($code);
246 // If the vendor directory does not exist, force the installation of dependencies.
247 $vendorpath = $dirroot . DIRECTORY_SEPARATOR . 'vendor';
248 if (!file_exists($vendorpath)) {
249 $updatedependencies = true;
252 if ($updatedependencies) {
253 // Update composer dependencies.
254 passthru("php composer.phar install", $code);
255 if ($code != 0) {
256 exit($code);
260 // Return to our original location.
261 chdir($cwd);
265 * Fix DIRECTORY_SEPARATOR for windows.
267 * In PHP on Windows, DIRECTORY_SEPARATOR is set to the backslash (\)
268 * character. However, if you're running a Cygwin/Msys/Git shell
269 * exec() calls will return paths using the forward slash (/) character.
271 * NOTE: Because PHP on Windows will accept either forward or backslashes,
272 * paths should be built using ONLY forward slashes, regardless of
273 * OS. MOODLE_DIRECTORY_SEPARATOR should only be used when parsing
274 * paths returned by the shell.
276 * @param string $path
277 * @return string
279 function testing_cli_fix_directory_separator($path) {
280 global $CFG;
282 static $dirseparator = null;
284 if (!$dirseparator) {
285 // Default directory separator.
286 $dirseparator = DIRECTORY_SEPARATOR;
288 // On windows we need to find what directory separator is used.
289 if ($CFG->ostype = 'WINDOWS') {
290 if (!empty($_SERVER['argv'][0])) {
291 if (false === strstr($_SERVER['argv'][0], '\\')) {
292 $dirseparator = '/';
293 } else {
294 $dirseparator = '\\';
296 } else if (testing_is_cygwin()) {
297 $dirseparator = '/';
302 // Normalize \ and / to directory separator.
303 $path = str_replace('\\', $dirseparator, $path);
304 $path = str_replace('/', $dirseparator, $path);
306 return $path;