/
Test.php
325 lines (296 loc) · 9.1 KB
/
Test.php
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
<?php
/**
* Lithium: the most rad php framework
*
* @copyright Copyright 2012, Union of RAD (http://union-of-rad.org)
* @license http://opensource.org/licenses/bsd-license.php The BSD License
*/
namespace lithium\console\command;
use lithium\core\Libraries;
use lithium\test\Dispatcher;
use lithium\test\Unit;
/**
* Runs a given set of tests and outputs the results.
*
* @see lithium\test
*/
class Test extends \lithium\console\Command {
/**
* Used as the exit code for errors where no test was mapped to file.
*/
const EXIT_NO_TEST = 4;
/**
* List of filters to apply before/during/after test run, separated by commas.
*
* For example:
* {{{
* lithium test lithium/tests/cases/core/ObjectTest.php --filters=Coverage
* lithium test lithium/tests/cases/core/ObjectTest.php --filters=Coverage,Profiler
* }}}
*
* @var string Name of a filter or a comma separated list of filter names. Builtin filters:
* - `Affected`: Adds tests to the run affected by the classes covered by current tests.
* - `Complexity`: Calculates the cyclomatic complexity of class methods, and shows
* worst-offenders and statistics.
* - `Coverage`: Runs code coverage analysis for the executed tests.
* - `Profiler`: Tracks timing and memory usage information for each test method.
*/
public $filters;
/**
* Format to use for rendering results. Any other format than `txt` will
* cause the command to enter quiet mode, surpressing headers and any other
* decoration.
*
* @var string Either `txt` or `json`.
*/
public $format = 'txt';
/**
* Enable verbose output especially for the `txt` format.
*
* @var boolean
*/
public $verbose = false;
/**
* Enable plain to prevent any headers or similar decoration being output.
* Good for command calls embedded into other scripts.
*
* @var boolean
*/
public $plain = false;
/**
* An array of closures, mapped by type, which are set up to handle different test output
* formats.
*
* @var array
*/
protected $_handlers = array();
/**
* Initializes the output handlers.
*
* @see lithium\console\command\Test::$_handlers
* @return void
*/
protected function _init() {
parent::_init();
$command = $this;
$this->_handlers += array(
'txt' => function($runner, $path) use ($command) {
if (!$command->plain) {
$command->header('Test');
$command->out(null, 1);
}
$colorize = function($result) {
switch (trim($result)) {
case '.':
return $result;
case 'pass':
return "{:green}{$result}{:end}";
case 'F':
case 'fail':
return "{:red}{$result}{:end}";
case 'E':
case 'exception':
return "{:purple}{$result}{:end}";
case 'S':
case 'skip':
return "{:cyan}{$result}{:end}";
default:
return "{:yellow}{$result}{:end}";
}
};
if ($command->verbose) {
$reporter = function($result) use ($command, $colorize) {
$command->out(sprintf(
'[%s] on line %4s in %s::%s()',
$colorize(sprintf('%9s', $result['result'])),
isset($result['line']) ? $result['line'] : '??',
isset($result['class']) ? $result['class'] : '??',
isset($result['method']) ? $result['method'] : '??'
));
};
} else {
$i = 0;
$columns = 60;
$reporter = function($result) use ($command, &$i, $columns, $colorize) {
$shorten = array('fail', 'skip', 'exception');
if ($result['result'] == 'pass') {
$symbol = '.';
} elseif (in_array($result['result'], $shorten)) {
$symbol = strtoupper($result['result'][0]);
} else {
$symbol = '?';
}
$command->out($colorize($symbol), false);
$i++;
if ($i % $columns === 0) {
$command->out();
}
};
}
$report = $runner(compact('reporter'));
if (!$command->plain) {
$stats = $report->stats();
$command->out(null, 2);
$command->out($report->render('result', $stats));
$command->out($report->render('errors', $stats));
if ($command->verbose) {
$command->out($report->render('skips', $stats));
}
foreach ($report->filters() as $filter => $options) {
$data = $report->results['filters'][$filter];
$command->out($report->render($options['name'], compact('data')));
}
}
return $report;
},
'json' => function($runner, $path) use ($command) {
$report = $runner();
if ($results = $report->filters()) {
$filters = array();
foreach ($results as $filter => $options) {
$filters[$options['name']] = $report->results['filters'][$filter];
}
}
$command->out($report->render('stats', $report->stats() + compact('filters')));
return $report;
}
);
}
/**
* Runs tests given a path to a directory or file containing tests. The path to the
* test(s) may be absolute or relative to the current working directory.
*
* {{{
* li3 test lithium/tests/cases/core/ObjectTest.php
* li3 test lithium/tests/cases/core
* }}}
*
* If you are in the working directory of an application or plugin and wish to run all tests,
* simply execute the following:
*
* {{{
* li3 test tests/cases
* }}}
*
* If you are in the working directory of an application and wish to run a plugin, execute one
* of the following:
*
* {{{
* li3 test libraries/<plugin>/tests/cases
* li3 test <plugin>/tests/cases
* }}}
*
*
* This will run `<library>/tests/cases/<package>/<class>Test.php`:
*
* {{{
* li3 test <library>/<package>/<class>.php
* }}}
*
* @param string $path Absolute or relative path to tests or a file which
* corresponding test should be run.
* @return boolean Will exit with status `1` if one or more tests failed otherwise with `0`.
*/
public function run($path = null) {
if (!$path = $this->_path($path)) {
return false;
}
if (stripos($path, 'test') === false) {
if (!$path = Unit::get($path)) {
var_dump('?');
$this->error('Cannot map path to test path.');
return static::EXIT_NO_TEST;
}
}
$handlers = $this->_handlers;
if (!isset($handlers[$this->format]) || !is_callable($handlers[$this->format])) {
$this->error(sprintf('No handler for format `%s`... ', $this->format));
return false;
}
$filters = $this->filters ? array_map('trim', explode(',', $this->filters)) : array();
$params = compact('filters') + array('format' => $this->format);
$runner = function($options = array()) use ($path, $params) {
error_reporting(E_ALL | E_STRICT | E_DEPRECATED);
return Dispatcher::run($path, $params + $options);
};
$report = $handlers[$this->format]($runner, $path);
$stats = $report->stats();
return $stats['success'];
}
/**
* Finds a library for given path.
*
* @param string $path Normalized (to slashes) absolute or relative path.
* @return string the name of the library
*/
protected function _library($path) {
foreach (Libraries::get() as $name => $library) {
if (strpos($path, $library['path']) !== 0) {
continue;
}
return $name;
}
}
/**
* Validates and gets a fully-namespaced class path from an absolute or
* relative physical path to a directory or file. The final class path may
* be partial in that in doesn't contain the class name.
*
* This method can be thought of the reverse of `Libraries::path()`.
*
* {{{
* lithium/tests/cases/core/ObjectTest.php -> lithium\tests\cases\core\ObjectTest
* lithium/tests/cases/core -> lithium\tests\cases\core
* lithium/core/Object.php -> lithium\core\Object
* lithium/core/ -> lithium\core
* lithium/core -> lithium\core
* }}}
*
* @see lithium\core\Libraries::path()
* @param string $path The directory of or file path to one or more classes.
* @return string Returns a fully-namespaced class path, or `false`, if an error occurs.
*/
protected function _path($path) {
$path = rtrim(str_replace('\\', '/', $path), '/');
if (!$path) {
$this->error('Please provide a path to tests.');
return false;
}
if ($path[0] == '/') {
$library = $this->_library($path);
}
if ($path[0] != '/') {
$libraries = array_reduce(Libraries::get(), function($v, $w) {
$v[] = basename($w['path']);
return $v;
});
$library = basename($this->request->env('working'));
$parts = explode('/', str_replace("../", "", $path));
$plugin = array_shift($parts);
if ($plugin == 'libraries') {
$plugin = array_shift($parts);
}
if (in_array($plugin, $libraries)) {
$library = $plugin;
$path = join('/', $parts);
}
}
if (empty($library)) {
$this->error("No library found in path `{$path}`.");
return false;
}
if (!$config = Libraries::get($library)) {
$this->error("Library `{$library}` does not exist.");
return false;
}
$path = str_replace($config['path'], null, $path);
$realpath = $config['path'] . '/' . $path;
if (!realpath($realpath)) {
$this->error("Path `{$realpath}` not found.");
return false;
}
$class = str_replace(".php", "", str_replace('/', '\\', ltrim($path, '/')));
return $config['prefix'] . $class;
}
}
?>