Debian Codegraph @

tests/parser/ParserTestPrinter.php

raw symbols SCIP
1 <?php
2 /**
3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
17 *
18 * @file
19 * @ingroup Testing
20 */
21
22 use MediaWiki\Parser\Sanitizer;
23 use MediaWiki\Shell\Shell;
24 use MediaWiki\Tests\AnsiTermColorer;
25 use MediaWiki\Tests\DummyTermColorer;
26 use Wikimedia\Parsoid\ParserTests\Test as ParserTest;
27 use Wikimedia\Parsoid\ParserTests\TestMode as ParserTestMode;
28
29 /**
30 * This is a TestRecorder responsible for printing information about progress,
31 * success and failure to the console. It is specific to the parserTests.php
32 * frontend.
33 */
34 class ParserTestPrinter extends TestRecorder {
35 /** @var int */
36 private $total;
37 /** @var int */
38 private $success;
39 /** @var int */
40 private $skipped;
41 /** @var AnsiTermColorer|DummyTermColorer */
42 private $term;
43 /** @var bool */
44 private $showDiffs;
45 /** @var bool */
46 private $showProgress;
47 /** @var bool */
48 private $showFailure;
49 /** @var bool */
50 private $showOutput;
51 /** @var bool */
52 private $useDwdiff;
53 /** @var bool */
54 private $markWhitespace;
55 /** @var string */
56 private $xmlError;
57
58 public function __construct( $term, $options ) {
59 $this->term = $term;
60 $options += [
61 'showDiffs' => true,
62 'showProgress' => true,
63 'showFailure' => true,
64 'showOutput' => false,
65 'useDwdiff' => false,
66 'markWhitespace' => false,
67 ];
68 $this->showDiffs = $options['showDiffs'];
69 $this->showProgress = $options['showProgress'];
70 $this->showFailure = $options['showFailure'];
71 $this->showOutput = $options['showOutput'];
72 $this->useDwdiff = $options['useDwdiff'];
73 $this->markWhitespace = $options['markWhitespace'];
74 }
75
76 public function start() {
77 $this->total = 0;
78 $this->success = 0;
79 $this->skipped = 0;
80 }
81
82 public function startTest( ParserTest $test, ParserTestMode $mode ) {
83 if ( $this->showProgress ) {
84 $fake = new ParserTestResult( $test, $mode, '', '' );
85 $this->showTesting( $fake->getDescription() );
86 }
87 }
88
89 /**
90 * @param string $desc Test description
91 */
92 private function showTesting( string $desc ) {
93 self::print( "Running test $desc... " );
94 }
95
96 /**
97 * Show "Reading tests from ..."
98 *
99 * @param string $path
100 * @param-taint $path none
101 */
102 public function startSuite( string $path ) {
103 print $this->term->color( 1 ) .
104 "Running parser tests from \"$path\"..." .
105 $this->term->reset() .
106 "\n";
107 }
108
109 public function endSuite( string $path ) {
110 print "\n";
111 }
112
113 public function record( ParserTestResult $result ): void {
114 $this->total++;
115 $this->success += ( $result->isSuccess() ? 1 : 0 );
116
117 if ( $result->isSuccess() ) {
118 $this->showSuccess();
119 } else {
120 $this->showFailure( $result );
121 }
122 }
123
124 /**
125 * Print a happy success message.
126 */
127 private function showSuccess(): void {
128 if ( $this->showProgress ) {
129 print $this->term->color( '1;32' ) . 'PASSED' . $this->term->reset() . "\n";
130 }
131 }
132
133 /**
134 * Helper function to ensure the phan SecurityCheckPlugin does not register
135 * false "XSS" positives on parser test output, as this is a CLI tool.
136 *
137 * @param string $str Output string
138 * @param-taint $str none
139 */
140 private static function print( string $str ) {
141 print $str;
142 }
143
144 /**
145 * Print a failure message and provide some explanatory output
146 * about what went wrong if so configured.
147 *
148 * @param ParserTestResult $testResult
149 */
150 private function showFailure( ParserTestResult $testResult ): void {
151 if ( $this->showFailure ) {
152 if ( !$this->showProgress ) {
153 # In quiet mode we didn't show the 'Testing' message before the
154 # test, in case it succeeded. Show it now:
155 $this->showTesting( $testResult->getDescription() );
156 }
157
158 print $this->term->color( '31' ) . 'FAILED!' . $this->term->reset() . "\n";
159
160 print "{$testResult->test->filename}:{$testResult->test->lineNumStart}\n";
161
162 if ( $this->showOutput ) {
163 self::print( "--- Expected ---\n{$testResult->expected}\n" );
164 self::print( "--- Actual ---\n{$testResult->actual}\n" );
165 }
166
167 if ( $this->showDiffs ) {
168 self::print( $this->quickDiff( $testResult->expected, $testResult->actual ) );
169 if ( !$this->wellFormed( $testResult->actual ) ) {
170 self::print( "XML error: $this->xmlError\n" );
171 }
172 }
173 }
174 }
175
176 /**
177 * Run given strings through a diff and return the (colorized) output.
178 * Requires writable /tmp directory and a 'diff' command in the PATH.
179 *
180 * @param string $input
181 * @param string $output
182 * @param string $inFileTail Tailing for the input file name
183 * @param string $outFileTail Tailing for the output file name
184 * @return string
185 */
186 private function quickDiff( $input, $output,
187 $inFileTail = 'expected', $outFileTail = 'actual'
188 ) {
189 if ( $this->markWhitespace ) {
190 $pairs = [
191 "\n" => '',
192 ' ' => '·',
193 "\t" => '→'
194 ];
195 $input = strtr( $input, $pairs );
196 $output = strtr( $output, $pairs );
197 }
198
199 $infile = tempnam( wfTempDir(), "mwParser-$inFileTail" );
200 $this->dumpToFile( $input, $infile );
201
202 $outfile = tempnam( wfTempDir(), "mwParser-$outFileTail" );
203 $this->dumpToFile( $output, $outfile );
204
205 global $wgDiff3;
206 // we assume that people with diff3 also have usual diff
207 if ( $this->useDwdiff ) {
208 $shellCommand = 'dwdiff -Pc';
209 } else {
210 $shellCommand = ( wfIsWindows() && !$wgDiff3 ) ? 'fc' : 'diff -au';
211 }
212
213 $result = Shell::command()
214 ->unsafeParams( $shellCommand )
215 ->params( $infile, $outfile )
216 ->execute();
217 $diff = $result->getStdout();
218
219 unlink( $infile );
220 unlink( $outfile );
221
222 if ( $this->useDwdiff ) {
223 return $diff;
224 } else {
225 return $this->colorDiff( $diff );
226 }
227 }
228
229 /**
230 * Write the given string to a file, adding a final newline.
231 *
232 * @param string $data
233 * @param string $filename
234 */
235 private function dumpToFile( $data, $filename ) {
236 $file = fopen( $filename, "wt" );
237 fwrite( $file, $data . "\n" );
238 fclose( $file );
239 }
240
241 /**
242 * Colorize unified diff output if set for ANSI color output.
243 * Subtractions are colored blue, additions red.
244 *
245 * @param string $text
246 * @return string
247 */
248 private function colorDiff( $text ) {
249 return preg_replace(
250 [ '/^(-.*)$/m', '/^(\+.*)$/m' ],
251 [ $this->term->color( '34' ) . '$1' . $this->term->reset(),
252 $this->term->color( '31' ) . '$1' . $this->term->reset() ],
253 $text );
254 }
255
256 private function wellFormed( $text ) {
257 $html =
258 Sanitizer::hackDocType() .
259 '<html>' .
260 $text .
261 '</html>';
262
263 $parser = xml_parser_create( "UTF-8" );
264
265 # case folding violates XML standard, turn it off
266 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, 0 );
267
268 if ( !xml_parse( $parser, $html, true ) ) {
269 $err = xml_error_string( xml_get_error_code( $parser ) );
270 $position = xml_get_current_byte_index( $parser );
271 $fragment = $this->extractFragment( $html, $position );
272 $this->xmlError = "$err at byte $position:\n$fragment";
273
274 return false;
275 }
276
277 return true;
278 }
279
280 private function extractFragment( $text, $position ) {
281 $start = max( 0, $position - 10 );
282 $before = $position - $start;
283 $fragment = '...' .
284 $this->term->color( '34' ) .
285 substr( $text, $start, $before ) .
286 $this->term->color( '0' ) .
287 $this->term->color( '31' ) .
288 $this->term->color( '1' ) .
289 substr( $text, $position, 1 ) .
290 $this->term->color( '0' ) .
291 $this->term->color( '34' ) .
292 substr( $text, $position + 1, 9 ) .
293 $this->term->color( '0' ) .
294 '...';
295 $display = str_replace( "\n", ' ', $fragment );
296 $caret = ' ' .
297 str_repeat( ' ', $before ) .
298 $this->term->color( '31' ) .
299 '^' .
300 $this->term->color( '0' );
301
302 return "$display\n$caret";
303 }
304
305 /**
306 * Show a warning to the user
307 * @param string $message
308 */
309 public function warning( string $message ) {
310 echo "$message\n";
311 }
312
313 /**
314 * Mark a test skipped
315 * @param ParserTest $test
316 * @param ParserTestMode $mode
317 * @param string $subtest
318 */
319 public function skipped( ParserTest $test, ParserTestMode $mode, string $subtest ) {
320 if ( $this->showProgress ) {
321 print $this->term->color( '1;33' ) . 'SKIPPED' . $this->term->reset() . "\n";
322 }
323 $this->skipped++;
324 }
325
326 public function report() {
327 if ( $this->total > 0 ) {
328 $this->reportPercentage( $this->success, $this->total );
329 } else {
330 print $this->term->color( '31' ) . "No tests found." . $this->term->reset() . "\n";
331 }
332 }
333
334 /**
335 * @param int $success Number of passed tests
336 * @param int $total Number of total tests
337 * @return bool True if and only if all tests passed
338 */
339 private function reportPercentage( $success, $total ) {
340 $ratio = wfPercent( 100 * $success / $total );
341 self::print( $this->term->color( '1' ) . "Passed $success of $total tests ($ratio)" );
342 if ( $this->skipped ) {
343 self::print( ", skipped {$this->skipped}" );
344 }
345 print "... ";
346
347 if ( $success == $total ) {
348 print $this->term->color( '32' ) . "ALL TESTS PASSED!";
349 } else {
350 $failed = $total - $success;
351 self::print( $this->term->color( '31' ) . "$failed tests failed!" );
352 }
353
354 print $this->term->reset() . "\n";
355
356 return ( $success == $total );
357 }
358 }