Merge branch 'MDL-32509' of git://github.com/danpoltawski/moodle
[moodle.git] / lib / simpletestlib / autorun.php
blobbc906e7b9dc72f084db34039366e2a9a09a2d152
1 <?php
2 /**
3 * Autorunner which runs all tests cases found in a file
4 * that includes this module.
5 * @package SimpleTest
6 * @version $Id: autorun.php 2037 2011-11-30 17:58:21Z pp11 $
7 */
9 defined('MOODLE_INTERNAL') || die(); // moodle hack - allow execution ONLY via out UIs!!!
11 /**#@+
12 * include simpletest files
14 require_once dirname(__FILE__) . '/unit_tester.php';
15 require_once dirname(__FILE__) . '/mock_objects.php';
16 require_once dirname(__FILE__) . '/collector.php';
17 require_once dirname(__FILE__) . '/default_reporter.php';
18 /**#@-*/
20 $GLOBALS['SIMPLETEST_AUTORUNNER_INITIAL_CLASSES'] = get_declared_classes();
21 $GLOBALS['SIMPLETEST_AUTORUNNER_INITIAL_PATH'] = getcwd();
22 register_shutdown_function('simpletest_autorun');
24 /**
25 * Exit handler to run all recent test cases and exit system if in CLI
27 function simpletest_autorun() {
28 chdir($GLOBALS['SIMPLETEST_AUTORUNNER_INITIAL_PATH']);
29 if (tests_have_run()) {
30 return;
32 $result = run_local_tests();
33 if (SimpleReporter::inCli()) {
34 exit($result ? 0 : 1);
38 /**
39 * run all recent test cases if no test has
40 * so far been run. Uses the DefaultReporter which can have
41 * it's output controlled with SimpleTest::prefer().
42 * @return boolean/null false if there were test failures, true if
43 * there were no failures, null if tests are
44 * already running
46 function run_local_tests() {
47 try {
48 if (tests_have_run()) {
49 return;
51 $candidates = capture_new_classes();
52 $loader = new SimpleFileLoader();
53 $suite = $loader->createSuiteFromClasses(
54 basename(initial_file()),
55 $loader->selectRunnableTests($candidates));
56 return $suite->run(new DefaultReporter());
57 } catch (Exception $stack_frame_fix) {
58 print $stack_frame_fix->getMessage();
59 return false;
63 /**
64 * Checks the current test context to see if a test has
65 * ever been run.
66 * @return boolean True if tests have run.
68 function tests_have_run() {
69 if ($context = SimpleTest::getContext()) {
70 return (boolean)$context->getTest();
72 return false;
75 /**
76 * The first autorun file.
77 * @return string Filename of first autorun script.
79 function initial_file() {
80 static $file = false;
81 if (! $file) {
82 if (isset($_SERVER, $_SERVER['SCRIPT_FILENAME'])) {
83 $file = $_SERVER['SCRIPT_FILENAME'];
84 } else {
85 $included_files = get_included_files();
86 $file = reset($included_files);
89 return $file;
92 /**
93 * Every class since the first autorun include. This
94 * is safe enough if require_once() is always used.
95 * @return array Class names.
97 function capture_new_classes() {
98 global $SIMPLETEST_AUTORUNNER_INITIAL_CLASSES;
99 return array_map('strtolower', array_diff(get_declared_classes(),
100 $SIMPLETEST_AUTORUNNER_INITIAL_CLASSES ?
101 $SIMPLETEST_AUTORUNNER_INITIAL_CLASSES : array()));