This repository has been archived by the owner on Jan 23, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathphpt-tests-runner
443 lines (414 loc) · 13.3 KB
/
phpt-tests-runner
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
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
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
#!/usr/bin/env php
<?php
/**
* @package PHPT Tests runner
* @author Nazar Mokrynskyi <[email protected]>
* @license 0BSD
*/
/**
* @param string $text
*
* @return string
*/
function colorize ($text) {
if (has_color_support()) {
$callback = function ($matches) {
$color_codes = [
'g' => 32, // Green
'y' => 33, // Yellow
'r' => 31, // Red
];
$color = $color_codes[$matches[1]];
$text = $matches[2];
return "\033[{$color}m$text\033[0m";
};
} else {
$callback = function ($matches) {
return $matches[2];
};
}
return preg_replace_callback(
'#<([gyr])>(.*)</\1>#Us',
$callback,
$text
);
}
/**
* Returns true if ANSI escape sequences are supported.
*
* Based on code of Fabien Potencier:
* \Symfony\Component\Console\Output\StreamOutput::hasColorSupport()
*
* @param bool|null $set_to
*
* @return bool true if ANSI escape sequences are supported.
*/
function has_color_support ($set_to = null) {
static $result;
if ($set_to !== null) {
$result = $set_to;
}
if ($result !== null) {
return $result;
}
if (strpos(PHP_OS, 'WIN') === false) {
$result = function_exists('posix_isatty') && @posix_isatty(STDOUT);
} else {
$result =
PHP_WINDOWS_VERSION_MAJOR.'.'.PHP_WINDOWS_VERSION_MINOR.'.'.PHP_WINDOWS_VERSION_BUILD === '10.0.10586' ||
getenv('ANSICON') !== false ||
getenv('ConEmuANSI') === 'ON' ||
getenv('TERM') === 'xterm';
}
return $result;
}
/**
* Output something to console
*
* Will colorize stuff in process
*
* @param bool $clean Clean current line before output
* @param string $text
*/
function out ($text, $clean = false) {
if ($clean) {
echo "\r";
}
echo colorize($text);
}
/**
* Output something to console and add new line at the end
*
* Will colorize stuff in process
*
* @param bool $clean Clean current line before output
* @param string $text
*/
function line ($text = '', $clean = false) {
out($text, $clean);
echo "\n";
}
/**
* @param string $binary
* @param string $test_file
* @param string $base_text
*
* @return string `skipped`, `success` or `error`
*/
function run_test ($binary, $test_file, $base_text) {
out("<y>$base_text ...</y>");
$test_file = realpath($test_file);
@unlink("$test_file.exp");
@unlink("$test_file.out");
@unlink("$test_file.diff");
$parsed_test = parse_test($test_file);
/**
* Check required sections
*/
if (!isset($parsed_test['FILE'])) {
line("<r>$base_text ERROR</r>", true);
line('--FILE-- section MUST be present');
return 'error';
}
$output_sections = ['EXPECT', 'EXPECTF', 'EXPECTREGEX'];
if (!array_intersect(array_keys($parsed_test), $output_sections)) {
line("<r>$base_text ERROR</r>", true);
line('One of the following sections MUST be present: '.implode(',', $output_sections));
return 'error';
}
$php_arguments = [
'-d variables_order=EGPCS',
'-d error_reporting='.E_ALL,
'-d display_errors=1',
'-d xdebug.default_enable=0'
];
if (isset($parsed_test['INI'])) {
foreach (explode("\n", trim($parsed_test['INI'])) as $line) {
list($key, $value) = array_map('trim', explode('=', $line, 2));
$php_arguments[] = "-d $key=$value";
}
}
$script_arguments = $parsed_test['ARGS'] ?? '';
$working_dir = dirname($test_file);
if (isset($parsed_test['SKIPIF'])) {
$result = execute_code($binary, $working_dir, $parsed_test['SKIPIF'], $php_arguments, $script_arguments, $test_file);
if (stripos($result, 'skip') === 0) {
line("<y>$base_text SKIPPED</y>", true);
line(ltrim(substr($result, 4)));
return 'skipped';
}
}
$started_time = microtime(true);
$output = rtrim(execute_code($binary, $working_dir, $parsed_test['FILE'], $php_arguments, $script_arguments, $test_file, true));
$result = compare_output(PHP_BINARY, $output, $base_text, $test_file, $php_arguments, $script_arguments, $parsed_test, $started_time);
isset($parsed_test['CLEAN']) && execute_code($binary, $working_dir, $parsed_test['CLEAN'], $php_arguments, $script_arguments, $test_file);
if ($result === 'success') {
unlink("$test_file.test_code.php");
}
return $result;
}
/**
* @param string $test_file
*
* @return string[]
*/
function parse_test ($test_file) {
$result = [];
$current_key = null;
foreach (file($test_file) as $line) {
if (preg_match("/^--(SKIPIF|INI|ARGS|FILE|EXPECT|EXPECTF|EXPECTREGEX|CLEAN)--\n$/", $line, $match)) {
$current_key = $match[1];
$result[$current_key] = '';
} elseif ($current_key) {
if (!isset($result[$current_key])) {
$result[$current_key] = '';
}
$result[$current_key] .= $line;
}
}
return $result;
}
/**
* @param string $binary
* @param string $working_dir
* @param string $code
* @param string[] $php_arguments
* @param string $script_arguments
* @param string $test_file
* @param bool $keep_file
*
* @return string
*/
function execute_code ($binary, $working_dir, $code, $php_arguments, $script_arguments, $test_file, $keep_file = false) {
if ($keep_file) {
$tmp_code_file = "$test_file.test_code.php";
} else {
$tmp_code_file = tempnam($working_dir, basename($test_file));
}
file_put_contents($tmp_code_file, $code);
putenv("TEST_FILE=\"$test_file\"");
$arguments = implode(' ', $php_arguments);
$prepared_file = escapeshellarg($tmp_code_file);
$output = shell_exec("$binary $arguments -f $prepared_file -- $script_arguments 2>&1");
if (!$keep_file) {
unlink($tmp_code_file);
}
return $output;
}
/**
* @param float $started In seconds
*
* @return string
*/
function time_since_started ($started) {
return round((microtime(true) - $started) * 1000, 2).' ms';
}
/**
* @param string $binary
* @param string $output
* @param string $base_text
* @param string $test_file
* @param array $php_arguments
* @param string $script_arguments
* @param string[] $parsed_test
* @param float $started_time
*
* @return string `success` or `error`
*/
function compare_output ($binary, $output, $base_text, $test_file, $php_arguments, $script_arguments, $parsed_test, $started_time) {
$working_dir = dirname($test_file);
$execution_time = time_since_started($started_time);
if (isset($parsed_test['EXPECT'])) {
$expect = rtrim(execute_code($binary, $working_dir, $parsed_test['EXPECT'], $php_arguments, $script_arguments, $test_file));
if ($expect === $output) {
line("<g>$base_text SUCCESS</g> $execution_time", true);
return 'success';
}
} elseif (isset($parsed_test['EXPECTF'])) {
$expect = rtrim(execute_code($binary, $working_dir, $parsed_test['EXPECTF'], $php_arguments, $script_arguments, $test_file));
$regex = str_replace(
[
'%s',
'%S',
'%a',
'%A',
'%w',
'%i',
'%d',
'%x',
'%f',
'%c'
],
[
'[^\r\n]+',
'[^\r\n]*',
'.+',
'.*',
'\s*',
'[+-]?\d+',
'\d+',
'[0-9a-fA-F]+',
'[+-]?\.?\d+\.?\d*(?:[Ee][+-]?\d+)?',
'.'
],
preg_quote($expect, '/')
);
if (preg_match("/^$regex\$/s", $output)) {
line("<g>$base_text SUCCESS</g> $execution_time", true);
return 'success';
}
} else {
$expect = rtrim(execute_code($binary, $working_dir, $parsed_test['EXPECREGEX'], $php_arguments, $script_arguments, $test_file));
$regex = preg_quote($expect, '/');
if (preg_match("/^$regex\$/s", $output)) {
line("<g>$base_text SUCCESS</g> $execution_time", true);
return 'success';
}
}
line("<r>$base_text ERROR:</r> $execution_time", true);
$diff = preg_replace_callback(
'/^([-+]).*$/m',
function ($match) {
return $match[1] === '-' ? "<r>$match[0]</r>" : "<g>$match[0]</g>";
},
compute_diff($test_file, $expect, $output)
);
line($diff);
return 'error';
}
function compute_diff ($test_file, $expect, $output) {
$exp_file = "$test_file.exp";
$out_file = "$test_file.out";
file_put_contents($exp_file, $expect."\n");
file_put_contents($out_file, $output."\n");
$diff = rtrim(
shell_exec(
"diff --old-line-format='-%3dn %L' --new-line-format='+%3dn %L' --from-file=".escapeshellarg($exp_file).' '.escapeshellarg($out_file)
)
);
file_put_contents("$test_file.diff", $diff);
return $diff;
}
/**
* @param string|string[] $target
*
* @return string[]
*/
function find_tests ($target) {
if (is_array($target)) {
return array_merge(...array_map('find_tests', $target));
}
if (is_dir($target)) {
$iterator = new RegexIterator(
new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($target)
),
'/.*\.phpt$/',
RecursiveRegexIterator::GET_MATCH
);
return array_merge(...array_values(iterator_to_array($iterator)));
}
return file_exists($target) ? [$target] : [];
}
$options = getopt('hb:cC', []);
$targets = array_filter(
array_slice($argv, 1),
function ($path) {
return is_dir($path) || (is_file($path) && substr($path, -5) === '.phpt');
}
);
line("<g>PHPT Tests runner</g>\n");
if (isset($options['c'])) {
has_color_support(true);
} elseif (isset($options['C'])) {
has_color_support(false);
}
if (!$targets || isset($options['h'])) {
line(
<<<HTML
<y>Usage:</y>
phpt-tests-runner [-h] [-c] [-C] [-b binary] [files] [directories]
<y>Arguments:</y>
<g>-h</g> Print this help message
<g>-b</g> Specify custom PHP binary to be used (current is used by default)
<g>-c</g> Force colored output
<g>-C</g> Force no colored output
<y>Examples:</y>
Execute tests from tests directory:
<g>phpt-tests-runner tests</g>
Execute tests single test:
<g>phpt-tests-runner tests/sample.phpt</g>
Execute tests from tests directory, but skip slow tests using environment variable:
<g>SKIP_SLOW_TESTS=1 phpt-tests-runner tests</g>
<y>PHPT Format:</y>
This runner uses modification of PHPT format used by PHP itself, so that it can run many original PHPT tests without any changes.
PHPT test if text file with *.phpt extension.
Each file contains sections followed by section contents, everything before first section is ignored, you can use it for storing test description.
Required sections are <g>--FILE--</g> and one of [<g>--EXPECT--</g>, <g>--EXPECTF--</g>, <g>--EXPECTREGEX--</g>].
<y>PHPT sections supported:</y>
<g>--FILE--</g> The test source code
<g>--EXPECT--</g> The expected output from the test script (will be executed as PHP script, so it might be code as well as plain text)
<g>--EXPECTF--</g> Similar to <g>--EXPECT--</g>, but it uses substitution tags for strings, spaces, digits, which may vary between test runs
The following is a list of all tags and what they are used to represent:
<g>%s</g> One or more of anything (character or white space) except the end of line character
<g>%S</g> Zero or more of anything (character or white space) except the end of line character
<g>%a</g> One or more of anything (character or white space) including the end of line character
<g>%A</g> Zero or more of anything (character or white space) including the end of line character
<g>%w</g> Zero or more white space characters
<g>%i</g> A signed integer value, for example +3142, -3142
<g>%d</g> An unsigned integer value, for example 123456
<g>%x</g> One or more hexadecimal character. That is, characters in the range 0-9, a-f, A-F
<g>%f</g> A floating point number, for example: 3.142, -3.142, 3.142E-10, 3.142e+10
<g>%c</g> A single character of any sort (.)
<g>--EXPECTREGEX--</g> Similar to <g>--EXPECT--</g>, but is treated as regular expression
<g>--SKIPIF--</g> If output of execution starts with `skip` then test will be skipped
<g>--INI--</g> Specific php.ini setting for the test, one per line
<g>--ARGS--</g> A single line defining the arguments passed to php
<g>--CLEAN--</g> Code that is executed after a test completes
<y>PHPT tests examples:</y>
Examples can be found at <<g>https://qa.php.net/phpt_details.php</g>> (taking into account differences here)
<y>Main differences from original PHPT tests files:</y>
1. <g>--TEST--</g> is not required and not even used (files names are used instead)
2. Only sub-set of sections supported and only sub-set of <g>--EXPECTF--</g> tags
3. <g>--EXPECT*--</g> sections are interpreted as code and its output is used as expected result
HTML
);
exit;
}
$tests = find_tests($targets);
sort($tests, SORT_NATURAL);
$tests_count = count($tests);
if (!$tests_count) {
line('<r>No tests found, there is nothing to do here</r>');
exit(1);
}
line("<y>$tests_count tests found</y>, running them:");
$max_length = 0;
foreach ($tests as $test_file) {
$max_length = max($max_length, strlen($test_file));
}
$binary = $options['b'] ?? PHP_BINARY;
$results = [
'skipped' => 0,
'success' => 0,
'error' => 0
];
$started_time = microtime(true);
foreach ($tests as $index => $test_file) {
$base_text = sprintf("%' 3d/$tests_count %s", $index + 1, str_pad($test_file, $max_length));
$results[run_test($binary, $test_file, $base_text)]++;
}
line("\nResults:");
if ($results['skipped']) {
line(sprintf("<y>%' 3d/$tests_count tests (%' 6.2f%%) skipped</y>", $results['skipped'], $results['skipped'] / $tests_count * 100));
}
if ($results['success']) {
line(sprintf("<g>%' 3d/$tests_count tests (%' 6.2f%%) succeed</g>", $results['success'], $results['success'] / $tests_count * 100));
}
if ($results['error']) {
line(sprintf("<r>%' 3d/$tests_count tests (%' 6.2f%%) failed</r>", $results['error'], $results['error'] / $tests_count * 100));
}
line(sprintf('Time: %s', time_since_started($started_time)));
if ($results['error']) {
exit(1);
}