run.php 18.1 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

/**
 * Wrapper to run previously set-up behat tests in parallel.
 *
 * @package    tool_behat
 * @copyright  2014 NetSpot Pty Ltd
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */

if (isset($_SERVER['REMOTE_ADDR'])) {
    die(); // No access from web!
}

define('CLI_SCRIPT', true);
define('ABORT_AFTER_CONFIG', true);
31
define('CACHE_DISABLE_ALL', true);
32
33
define('NO_OUTPUT_BUFFERING', true);

34
35
36
37
38
39
require_once(__DIR__ .'/../../../../config.php');
require_once(__DIR__.'/../../../../lib/clilib.php');
require_once(__DIR__.'/../../../../lib/behat/lib.php');
require_once(__DIR__.'/../../../../lib/behat/classes/behat_command.php');
require_once(__DIR__.'/../../../../lib/behat/classes/behat_config_manager.php');

40
41
42
43
44
45
46
error_reporting(E_ALL | E_STRICT);
ini_set('display_errors', '1');
ini_set('log_errors', '1');

list($options, $unrecognised) = cli_get_params(
    array(
        'stop-on-failure' => 0,
47
48
49
50
51
        'verbose'  => false,
        'replace'  => false,
        'help'     => false,
        'tags'     => '',
        'profile'  => '',
52
        'feature'  => '',
53
        'suite'    => '',
54
55
        'fromrun'  => 1,
        'torun'    => 0,
56
        'single-run' => false,
57
        'rerun' => 0,
58
        'auto-rerun' => 0,
59
60
61
62
63
    ),
    array(
        'h' => 'help',
        't' => 'tags',
        'p' => 'profile',
64
        's' => 'single-run',
65
66
67
    )
);

68
69
70
// Checking run.php CLI script usage.
$help = "
Behat utilities to run behat tests in parallel
71
72
73
74

Usage:
  php run.php [--BEHAT_OPTION=\"value\"] [--feature=\"value\"] [--replace] [--fromrun=value --torun=value] [--help]

75
Options:
76
77
--BEHAT_OPTION     Any combination of behat option specified in http://behat.readthedocs.org/en/v2.5/guides/6.cli.html
--feature          Only execute specified feature file (Absolute path of feature file).
78
--suite            Specified theme scenarios will be executed.
79
--replace          Replace args string with run process number, useful for output.
80
81
--fromrun          Execute run starting from (Used for parallel runs on different vms)
--torun            Execute run till (Used for parallel runs on different vms)
82
--rerun            Re-run scenarios that failed during last execution.
83
--auto-rerun       Automatically re-run scenarios that failed during last execution.
84

85
-h, --help         Print out this help
86
87

Example from Moodle root directory:
88
\$ php admin/tool/behat/cli/run.php --tags=\"@javascript\"
89
90
91
92
93
94
95
96
97

More info in http://docs.moodle.org/dev/Acceptance_testing#Running_tests
";

if (!empty($options['help'])) {
    echo $help;
    exit(0);
}

98
$parallelrun = behat_config_manager::get_behat_run_config_value('parallel');
99

100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
// Check if the options provided are valid to run behat.
if ($parallelrun === false) {
    // Parallel run should not have fromrun or torun options greater than 1.
    if (($options['fromrun'] > 1) || ($options['torun'] > 1)) {
        echo "Test site is not initialized  for parallel run." . PHP_EOL;
        exit(1);
    }
} else {
    // Ensure fromrun is within limits of initialized test site.
    if (!empty($options['fromrun']) && ($options['fromrun'] > $parallelrun)) {
        echo "From run (" . $options['fromrun'] . ") is more than site with parallel runs (" . $parallelrun . ")" . PHP_EOL;
        exit(1);
    }

    // Default torun is maximum parallel runs and should be less than equal to parallelruns.
    if (empty($options['torun'])) {
        $options['torun'] = $parallelrun;
    } else {
        if ($options['torun'] > $parallelrun) {
            echo "To run (" . $options['torun'] . ") is more than site with parallel runs (" . $parallelrun . ")" . PHP_EOL;
            exit(1);
        }
    }
123
}
124

125
// Capture signals and ensure we clean symlinks.
126
127
128
129
130
if (extension_loaded('pcntl')) {
    $disabled = explode(',', ini_get('disable_functions'));
    if (!in_array('pcntl_signal', $disabled)) {
        pcntl_signal(SIGTERM, "signal_handler");
        pcntl_signal(SIGINT, "signal_handler");
131
132
133
134
135
    }
}

$time = microtime(true);
array_walk($unrecognised, function (&$v) {
136
    if ($x = preg_filter("#^(-+\w+)=(.+)#", "\$1=\"\$2\"", $v)) {
137
138
139
140
141
        $v = $x;
    } else if (!preg_match("#^-#", $v)) {
        $v = escapeshellarg($v);
    }
});
142
$extraopts = $unrecognised;
143

144
145
if ($options['profile']) {
    $profile = $options['profile'];
146
147
148
149

    // If profile passed is not set, then exit.
    if (!isset($CFG->behat_config[$profile]) && !isset($CFG->behat_profiles[$profile]) &&
        !(isset($options['replace']) && (strpos($options['profile'], $options['replace']) >= 0 ))) {
150
        echo "Invalid profile passed: " . $profile . PHP_EOL;
151
152
        exit(1);
    }
153

154
    $extraopts['profile'] = '--profile="' . $profile . '"';
155
156
157
158
159
160
161
162
    // By default, profile tags will be used.
    if (!empty($CFG->behat_config[$profile]['filters']['tags'])) {
        $tags = $CFG->behat_config[$profile]['filters']['tags'];
    }
}

// Command line tags have precedence (std behat behavior).
if ($options['tags']) {
163
    $tags = $options['tags'];
164
    $extraopts['tags'] = '--tags="' . $tags . '"';
165
166
}

167
168
// Add suite option if specified.
if ($options['suite']) {
169
    $extraopts['suite'] = '--suite="' . $options['suite'] . '"';
170
171
}

172
173
// Feature should be added to last, for behat command.
if ($options['feature']) {
174
    $extraopts['feature'] = $options['feature'];
175
176
177
178
179
180
    // Only run 1 process as process.
    // Feature file is picked from absolute path provided, so no need to check for behat.yml.
    $options['torun'] = $options['fromrun'];
}

// Set of options to pass to behat.
181
$extraoptstr = implode(' ', $extraopts);
182

183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
// If rerun is passed then ensure we just run the failed processes.
$lastfailedstatus = 0;
$lasttorun = $options['torun'];
$lastfromrun = $options['fromrun'];
if ($options['rerun']) {
    // Get last combined failed status.
    $lastfailedstatus = behat_config_manager::get_behat_run_config_value('lastcombinedfailedstatus');
    $lasttorun = behat_config_manager::get_behat_run_config_value('lasttorun');
    $lastfromrun = behat_config_manager::get_behat_run_config_value('lastfromrun');

    if ($lastfailedstatus !== false) {
        $extraoptstr .= ' --rerun';
    }

    // If torun is less than last torun, then just set this to min last to run and similar for fromrun.
    if ($options['torun'] < $lasttorun) {
        $options['torun'];
    }
    if ($options['fromrun'] > $lastfromrun) {
        $options['fromrun'];
    }
    unset($options['rerun']);
}

$cmds = array();
$exitcodes = array();
$status = 0;
$verbose = empty($options['verbose']) ? false : true;

// Execute behat run commands.
213
214
215
if (empty($parallelrun)) {
    $cwd = getcwd();
    chdir(__DIR__);
216
    $runtestscommand = behat_command::get_behat_command(false, false, true);
217
    $runtestscommand .= ' --config ' . behat_config_manager::get_behat_cli_config_filepath();
218
    $runtestscommand .= ' ' . $extraoptstr;
219
220
    $cmds['singlerun'] = $runtestscommand;

221
    echo "Running single behat site:" . PHP_EOL;
222
    passthru("php $runtestscommand", $status);
223
    $exitcodes['singlerun'] = $status;
224
    chdir($cwd);
225
} else {
226

227
    echo "Running " . ($options['torun'] - $options['fromrun'] + 1) . " parallel behat sites:" . PHP_EOL;
228

229
230
    for ($i = $options['fromrun']; $i <= $options['torun']; $i++) {
        $lastfailed = 1 & $lastfailedstatus >> ($i - 1);
231

232
233
234
235
        // Bypass if not failed in last run.
        if ($lastfailedstatus && !$lastfailed && ($i <= $lasttorun) && ($i >= $lastfromrun)) {
            continue;
        }
236

237
        $CFG->behatrunprocess = $i;
238

239
240
        // Options parameters to be added to each run.
        $myopts = !empty($options['replace']) ? str_replace($options['replace'], $i, $extraoptstr) : $extraoptstr;
241

242
243
        $behatcommand = behat_command::get_behat_command(false, false, true);
        $behatconfigpath = behat_config_manager::get_behat_cli_config_filepath($i);
244

245
246
247
        // Command to execute behat run.
        $cmds[BEHAT_PARALLEL_SITE_NAME . $i] = $behatcommand . ' --config ' . $behatconfigpath . " " . $myopts;
        echo "[" . BEHAT_PARALLEL_SITE_NAME . $i . "] " . $cmds[BEHAT_PARALLEL_SITE_NAME . $i] . PHP_EOL;
248
    }
249

250
251
252
253
    if (empty($cmds)) {
        echo "No commands to execute " . PHP_EOL;
        exit(1);
    }
254

255
256
257
258
259
    // Create site symlink if necessary.
    if (!behat_config_manager::create_parallel_site_links($options['fromrun'], $options['torun'])) {
        echo "Check permissions. If on windows, make sure you are running this command as admin" . PHP_EOL;
        exit(1);
    }
260

261
262
263
    // Save torun and from run, so it can be used to detect if it was executed in last run.
    behat_config_manager::set_behat_run_config_value('lasttorun', $options['torun']);
    behat_config_manager::set_behat_run_config_value('lastfromrun', $options['fromrun']);
264

265
266
267
268
269
    // Keep no delay by default, between each parallel, let user decide.
    if (!defined('BEHAT_PARALLEL_START_DELAY')) {
        define('BEHAT_PARALLEL_START_DELAY', 0);
    }

270
    // Execute all commands, relative to moodle root directory.
271
    $processes = cli_execute_parallel($cmds, __DIR__ . "/../../../../", BEHAT_PARALLEL_START_DELAY);
272
    $stoponfail = empty($options['stop-on-failure']) ? false : true;
273

274
275
    // Print header.
    print_process_start_info($processes);
276

277
278
279
280
281
282
    // Print combined run o/p from processes.
    $exitcodes = print_combined_run_output($processes, $stoponfail);
    // Time to finish run.
    $time = round(microtime(true) - $time, 1);
    echo "Finished in " . gmdate("G\h i\m s\s", $time) . PHP_EOL . PHP_EOL;
    ksort($exitcodes);
283

284
285
286
287
288
289
290
    // Print exit info from each run.
    // Status bits contains pass/fail status of parallel runs.
    foreach ($exitcodes as $name => $exitcode) {
        if ($exitcode) {
            $runno = str_replace(BEHAT_PARALLEL_SITE_NAME, '', $name);
            $status |= (1 << ($runno - 1));
        }
291
    }
292

293
294
295
    // Print each process information.
    print_each_process_info($processes, $verbose, $status);
}
296

297
298
299
// Save final exit code containing which run failed.
behat_config_manager::set_behat_run_config_value('lastcombinedfailedstatus', $status);

300
// Show exit code from each process, if any process failed and how to rerun failed process.
301
if ($verbose || $status) {
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
    // Check if status of last run is failure and rerun is suggested.
    if (!empty($options['auto-rerun']) && $status) {
        // Rerun for the number of tries passed.
        for ($i = 0; $i < $options['auto-rerun']; $i++) {

            // Run individual commands, to avoid parallel failures.
            foreach ($exitcodes as $behatrunname => $exitcode) {
                // If not failed in last run, then skip.
                if ($exitcode == 0) {
                    continue;
                }

                // This was a failure.
                echo "*** Re-running behat run: $behatrunname ***" . PHP_EOL;
                if ($verbose) {
                    echo "Executing: " . $cmds[$behatrunname] . " --rerun" . PHP_EOL;
                }

                passthru("php $cmds[$behatrunname] --rerun", $rerunstatus);

                // Update exit code.
                $exitcodes[$behatrunname] = $rerunstatus;
            }
        }

        // Update status after auto-rerun finished.
328
        $status = 0;
329
330
331
332
333
334
335
336
337
338
339
340
341
        foreach ($exitcodes as $name => $exitcode) {
            if ($exitcode) {
                if (!empty($parallelrun)) {
                    $runno = str_replace(BEHAT_PARALLEL_SITE_NAME, '', $name);
                } else {
                    $runno = 1;
                }
                $status |= (1 << ($runno - 1));
            }
        }
    }

    // Show final o/p with re-run commands.
342
    if ($status) {
343
        if (!empty($parallelrun)) {
344
345
346
347
            // Echo exit codes.
            echo "Exit codes for each behat run: " . PHP_EOL;
            foreach ($exitcodes as $run => $exitcode) {
                echo $run . ": " . $exitcode . PHP_EOL;
348
            }
349
350
351
352
353
            unset($extraopts['fromrun']);
            unset($extraopts['torun']);
            if (!empty($options['replace'])) {
                $extraopts['replace'] = '--replace="' . $options['replace'] . '"';
            }
354
        }
355
356
357
358
359

        echo "To re-run failed processes, you can use following command:" . PHP_EOL;
        $extraopts['rerun'] = '--rerun';
        $extraoptstr = implode(' ', $extraopts);
        echo behat_command::get_behat_command(true, true, true) . " " . $extraoptstr . PHP_EOL;
360
    }
361
362
    echo PHP_EOL;
}
363

364
365
366
// Remove site symlink if necessary.
behat_config_manager::drop_parallel_site_links();

367
exit($status);
368
369
370
371
372
373
374
375
376
377
378
379
380
381

/**
 * Signal handler for terminal exit.
 *
 * @param int $signal signal number.
 */
function signal_handler($signal) {
    switch ($signal) {
        case SIGTERM:
        case SIGKILL:
        case SIGINT:
            // Remove site symlink if necessary.
            behat_config_manager::drop_parallel_site_links();
            exit(1);
382
    }
383
}
384

385
386
387
388
389
390
391
392
393
394
395
396
397
398
/**
 * Prints header from the first process.
 *
 * @param array $processes list of processes to loop though.
 */
function print_process_start_info($processes) {
    $printed = false;
    // Keep looping though processes, till we get first process o/p.
    while (!$printed) {
        usleep(10000);
        foreach ($processes as $name => $process) {
            // Exit if any process has stopped.
            if (!$process->isRunning()) {
                $printed = true;
399
400
                break;
            }
401
402
403
404
405
406
407

            $op = explode(PHP_EOL, $process->getOutput());
            if (count($op) >= 3) {
                foreach ($op as $line) {
                    if (trim($line) && (strpos($line, '.') !== 0)) {
                        echo $line . PHP_EOL;
                    }
408
                }
409
                $printed = true;
410
411
412
413
414
            }
        }
    }
}

415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
/**
 * Loop though all processes and print combined o/p
 *
 * @param array $processes list of processes to loop though.
 * @param bool $stoponfail Stop all processes and exit if failed.
 * @return array list of exit codes from all processes.
 */
function print_combined_run_output($processes, $stoponfail = false) {
    $exitcodes = array();
    $maxdotsonline = 70;
    $remainingprintlen = $maxdotsonline;
    $progresscount = 0;
    while (count($exitcodes) != count($processes)) {
        usleep(10000);
        foreach ($processes as $name => $process) {
            if ($process->isRunning()) {
                $op = $process->getIncrementalOutput();
                if (trim($op)) {
                    $update = preg_filter('#^\s*([FS\.\-]+)(?:\s+\d+)?\s*$#', '$1', $op);
                    // Exit process if anything fails.
                    if ($stoponfail && (strpos($update, 'F') !== false)) {
                        $process->stop(0);
                    }

                    $strlentoprint = strlen($update);

                    // If not enough dots printed on line then just print.
                    if ($strlentoprint < $remainingprintlen) {
                        echo $update;
                        $remainingprintlen = $remainingprintlen - $strlentoprint;
                    } else if ($strlentoprint == $remainingprintlen) {
                        $progresscount += $maxdotsonline;
                        echo $update ." " . $progresscount . PHP_EOL;
                        $remainingprintlen = $maxdotsonline;
                    } else {
                        while ($part = substr($update, 0, $remainingprintlen) > 0) {
                            $progresscount += $maxdotsonline;
                            echo $part . " " . $progresscount . PHP_EOL;
                            $update = substr($update, $remainingprintlen);
                            $remainingprintlen = $maxdotsonline;
                        }
                    }
                }
            } else {
                $exitcodes[$name] = $process->getExitCode();
                if ($stoponfail && ($exitcodes[$name] != 0)) {
                    foreach ($processes as $l => $p) {
                        $exitcodes[$l] = -1;
                        $process->stop(0);
                    }
                }
            }
        }
468
    }
469

470
471
472
473
474
475
476
477
478
479
    echo PHP_EOL;
    return $exitcodes;
}

/**
 * Loop though all processes and print combined o/p
 *
 * @param array $processes list of processes to loop though.
 * @param bool $verbose Show verbose output for each process.
 */
480
function print_each_process_info($processes, $verbose = false, $status = 0) {
481
482
483
484
485
    foreach ($processes as $name => $process) {
        echo "**************** [" . $name . "] ****************" . PHP_EOL;
        if ($verbose) {
            echo $process->getOutput();
            echo $process->getErrorOutput();
486
487
488
489
490
491
492
493
494

        } else if ($status) {
            // Only show failed o/p.
            $runno = str_replace(BEHAT_PARALLEL_SITE_NAME, '', $name);
            if ((1 << ($runno - 1)) & $status) {
                echo $process->getOutput();
                echo $process->getErrorOutput();
            } else {
                echo get_status_lines_from_run_op($process);
495
            }
496
497
498

        } else {
            echo get_status_lines_from_run_op($process);
499
        }
500
        echo PHP_EOL;
501
502
    }
}
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523

/**
 * Extract status information from behat o/p and return.
 * @param Symfony\Component\Process\Process $process
 * @return string
 */
function get_status_lines_from_run_op(Symfony\Component\Process\Process $process) {
    $statusstr = '';
    $op = explode(PHP_EOL, $process->getOutput());
    foreach ($op as $line) {
        // Don't print progress .
        if (trim($line) && (strpos($line, '.') !== 0) && (strpos($line, 'Moodle ') !== 0) &&
            (strpos($line, 'Server OS ') !== 0) && (strpos($line, 'Started at ') !== 0) &&
            (strpos($line, 'Browser specific fixes ') !== 0)) {
            $statusstr .= $line . PHP_EOL;
        }
    }

    return $statusstr;
}