/
CliTester.php
279 lines (229 loc) 路 7.77 KB
/
CliTester.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
<?php
/**
* This file is part of the Nette Tester.
* Copyright (c) 2009 David Grudl (https://davidgrudl.com)
*/
namespace Tester\Runner;
use Tester\CodeCoverage;
use Tester\Dumper;
use Tester\Environment;
/**
* CLI Tester.
*/
class CliTester
{
/** @var array */
private $options;
/** @var PhpInterpreter */
private $interpreter;
/** @return int|null */
public function run()
{
Environment::setupColors();
Environment::setupErrors();
ob_start();
$cmd = $this->loadOptions();
Environment::$debugMode = (bool) $this->options['--debug'];
if (isset($this->options['--colors'])) {
Environment::$useColors = (bool) $this->options['--colors'];
} elseif (in_array($this->options['-o'], ['tap', 'junit'], true)) {
Environment::$useColors = false;
}
if ($cmd->isEmpty() || $this->options['--help']) {
$cmd->help();
return;
}
$this->createPhpInterpreter();
if ($this->options['--info']) {
$job = new Job(new Test(__DIR__ . '/info.php'), $this->interpreter);
$job->run();
echo $job->getTest()->stdout;
return;
}
if ($this->options['--coverage']) {
$coverageFile = $this->prepareCodeCoverage();
}
$runner = $this->createRunner();
$runner->setEnvironmentVariable(Environment::RUNNER, '1');
$runner->setEnvironmentVariable(Environment::COLORS, (string) (int) Environment::$useColors);
if (isset($coverageFile)) {
$runner->setEnvironmentVariable(Environment::COVERAGE, $coverageFile);
}
if ($this->options['-o'] !== null) {
ob_clean();
}
ob_end_flush();
if ($this->options['--watch']) {
$this->watch($runner);
return;
}
$result = $runner->run();
if (isset($coverageFile) && preg_match('#\.(?:html?|xml)\z#', $coverageFile)) {
$this->finishCodeCoverage($coverageFile);
}
return $result ? 0 : 1;
}
/** @return CommandLine */
private function loadOptions()
{
echo <<<'XX'
_____ ___ ___ _____ ___ ___
|_ _/ __)( __/_ _/ __)| _ )
|_| \___ /___) |_| \___ |_|_\ v2.1.0
XX;
$cmd = new CommandLine(<<<'XX'
Usage:
tester.php [options] [<test file> | <directory>]...
Options:
-p <path> Specify PHP interpreter to run (default: php).
-c <path> Look for php.ini file (or look in directory) <path>.
-C Use system-wide php.ini.
-l | --log <path> Write log to file <path>.
-d <key=value>... Define INI entry 'key' with value 'value'.
-s Show information about skipped tests.
--stop-on-fail Stop execution upon the first failure.
-j <num> Run <num> jobs in parallel (default: 8).
-o <console|tap|junit|none> Specify output format.
-w | --watch <path> Watch directory.
-i | --info Show tests environment info and exit.
--setup <path> Script for runner setup.
--temp <path> Path to temporary directory. Default by sys_get_temp_dir().
--colors [1|0] Enable or disable colors.
--coverage <path> Generate code coverage report to file.
--coverage-src <path> Path to source code.
-h | --help This help.
XX
, [
'-c' => [CommandLine::REALPATH => true],
'--watch' => [CommandLine::REPEATABLE => true, CommandLine::REALPATH => true],
'--setup' => [CommandLine::REALPATH => true],
'--temp' => [CommandLine::REALPATH => true],
'paths' => [CommandLine::REPEATABLE => true, CommandLine::VALUE => getcwd()],
'--debug' => [],
'--coverage-src' => [CommandLine::REALPATH => true],
]);
if (isset($_SERVER['argv'])) {
if ($tmp = array_search('-log', $_SERVER['argv'], true)) {
$_SERVER['argv'][$tmp] = '--log';
}
if ($tmp = array_search('--tap', $_SERVER['argv'], true)) {
unset($_SERVER['argv'][$tmp]);
$_SERVER['argv'] = array_merge($_SERVER['argv'], ['-o', 'tap']);
}
if (array_search('-p', $_SERVER['argv'], true) === false) {
echo "Note: Default interpreter is CLI since Tester v2.0. It used to be CGI.\n";
}
}
$this->options = $cmd->parse();
if ($this->options['--temp'] === null) {
if (($temp = sys_get_temp_dir()) === '') {
echo "Note: System temporary directory is not set.\n";
} elseif (($real = realpath($temp)) === false) {
echo "Note: System temporary directory '$temp' does not exist.\n";
} else {
$this->options['--temp'] = rtrim($real, DIRECTORY_SEPARATOR);
}
}
return $cmd;
}
/** @return void */
private function createPhpInterpreter()
{
$args = $this->options['-C'] ? [] : ['-n'];
if ($this->options['-c']) {
array_push($args, '-c', $this->options['-c']);
} elseif (!$this->options['--info'] && !$this->options['-C']) {
echo "Note: No php.ini is used.\n";
}
if (in_array($this->options['-o'], ['tap', 'junit'], true)) {
array_push($args, '-d', 'html_errors=off');
}
foreach ($this->options['-d'] as $item) {
array_push($args, '-d', $item);
}
$this->interpreter = new PhpInterpreter($this->options['-p'], $args);
if ($error = $this->interpreter->getStartupError()) {
echo Dumper::color('red', "PHP startup error: $error") . "\n";
}
}
/** @return Runner */
private function createRunner()
{
$runner = new Runner($this->interpreter);
$runner->paths = $this->options['paths'];
$runner->threadCount = max(1, (int) $this->options['-j']);
$runner->stopOnFail = $this->options['--stop-on-fail'];
if ($this->options['--temp'] !== null) {
$runner->setTempDirectory($this->options['--temp']);
}
if ($this->options['-o'] !== 'none') {
switch ($this->options['-o']) {
case 'tap':
$runner->outputHandlers[] = new Output\TapPrinter;
break;
case 'junit':
$runner->outputHandlers[] = new Output\JUnitPrinter;
break;
default:
$runner->outputHandlers[] = new Output\ConsolePrinter($runner, (bool) $this->options['-s']);
}
}
if ($this->options['--log']) {
echo "Log: {$this->options['--log']}\n";
$runner->outputHandlers[] = new Output\Logger($runner, $this->options['--log']);
}
if ($this->options['--setup']) {
(function () use ($runner) {
require func_get_arg(0);
})($this->options['--setup']);
}
return $runner;
}
/** @return string */
private function prepareCodeCoverage()
{
if (!$this->interpreter->canMeasureCodeCoverage()) {
throw new \Exception("Code coverage functionality requires Xdebug extension or phpdbg SAPI (used {$this->interpreter->getCommandLine()})");
}
file_put_contents($this->options['--coverage'], '');
$file = realpath($this->options['--coverage']);
echo "Code coverage: {$file}\n";
return $file;
}
/** @return void */
private function finishCodeCoverage($file)
{
if (!in_array($this->options['-o'], ['none', 'tap', 'junit'], true)) {
echo 'Generating code coverage report... ';
}
if (pathinfo($file, PATHINFO_EXTENSION) === 'xml') {
$generator = new CodeCoverage\Generators\CloverXMLGenerator($file, $this->options['--coverage-src']);
} else {
$generator = new CodeCoverage\Generators\HtmlGenerator($file, $this->options['--coverage-src']);
}
$generator->render($file);
echo round($generator->getCoveredPercent()) . "% covered\n";
}
/** @return void */
private function watch(Runner $runner)
{
$prev = [];
$counter = 0;
while (true) {
$state = [];
foreach ($this->options['--watch'] as $directory) {
foreach (new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($directory)) as $file) {
if (substr($file->getExtension(), 0, 3) === 'php' && substr($file->getBasename(), 0, 1) !== '.') {
$state[(string) $file] = md5_file((string) $file);
}
}
}
if ($state !== $prev) {
$prev = $state;
$runner->run();
}
echo 'Watching ' . implode(', ', $this->options['--watch']) . ' ' . str_repeat('.', ++$counter % 5) . " \r";
sleep(2);
}
}
}