MediaWiki  1.30.0
ParserTestPrinter.php
Go to the documentation of this file.
1 <?php
28  private $total;
29  private $success;
30  private $skipped;
31  private $term;
32  private $showDiffs;
33  private $showProgress;
34  private $showFailure;
35  private $showOutput;
36  private $useDwdiff;
37  private $markWhitespace;
38  private $xmlError;
39 
40  function __construct( $term, $options ) {
41  $this->term = $term;
42  $options += [
43  'showDiffs' => true,
44  'showProgress' => true,
45  'showFailure' => true,
46  'showOutput' => false,
47  'useDwdiff' => false,
48  'markWhitespace' => false,
49  ];
50  $this->showDiffs = $options['showDiffs'];
51  $this->showProgress = $options['showProgress'];
52  $this->showFailure = $options['showFailure'];
53  $this->showOutput = $options['showOutput'];
54  $this->useDwdiff = $options['useDwdiff'];
55  $this->markWhitespace = $options['markWhitespace'];
56  }
57 
58  public function start() {
59  $this->total = 0;
60  $this->success = 0;
61  $this->skipped = 0;
62  }
63 
64  public function startTest( $test ) {
65  if ( $this->showProgress ) {
66  $this->showTesting( $test['desc'] );
67  }
68  }
69 
70  private function showTesting( $desc ) {
71  print "Running test $desc... ";
72  }
73 
79  public function startSuite( $path ) {
80  print $this->term->color( 1 ) .
81  "Running parser tests from \"$path\"..." .
82  $this->term->reset() .
83  "\n";
84  }
85 
86  public function endSuite( $path ) {
87  print "\n";
88  }
89 
90  public function record( $test, ParserTestResult $result ) {
91  $this->total++;
92  $this->success += ( $result->isSuccess() ? 1 : 0 );
93 
94  if ( $result->isSuccess() ) {
95  $this->showSuccess( $result );
96  } else {
97  $this->showFailure( $result );
98  }
99  }
100 
107  private function showSuccess( ParserTestResult $testResult ) {
108  if ( $this->showProgress ) {
109  print $this->term->color( '1;32' ) . 'PASSED' . $this->term->reset() . "\n";
110  }
111  }
112 
120  private function showFailure( ParserTestResult $testResult ) {
121  if ( $this->showFailure ) {
122  if ( !$this->showProgress ) {
123  # In quiet mode we didn't show the 'Testing' message before the
124  # test, in case it succeeded. Show it now:
125  $this->showTesting( $testResult->getDescription() );
126  }
127 
128  print $this->term->color( '31' ) . 'FAILED!' . $this->term->reset() . "\n";
129 
130  if ( $this->showOutput ) {
131  print "--- Expected ---\n{$testResult->expected}\n";
132  print "--- Actual ---\n{$testResult->actual}\n";
133  }
134 
135  if ( $this->showDiffs ) {
136  print $this->quickDiff( $testResult->expected, $testResult->actual );
137  if ( !$this->wellFormed( $testResult->actual ) ) {
138  print "XML error: $this->xmlError\n";
139  }
140  }
141  }
142 
143  return false;
144  }
145 
156  private function quickDiff( $input, $output,
157  $inFileTail = 'expected', $outFileTail = 'actual'
158  ) {
159  if ( $this->markWhitespace ) {
160  $pairs = [
161  "\n" => '¶',
162  ' ' => '·',
163  "\t" => '→'
164  ];
165  $input = strtr( $input, $pairs );
166  $output = strtr( $output, $pairs );
167  }
168 
169  # Windows, or at least the fc utility, is retarded
170  $slash = wfIsWindows() ? '\\' : '/';
171  $prefix = wfTempDir() . "{$slash}mwParser-" . mt_rand();
172 
173  $infile = "$prefix-$inFileTail";
174  $this->dumpToFile( $input, $infile );
175 
176  $outfile = "$prefix-$outFileTail";
177  $this->dumpToFile( $output, $outfile );
178 
179  $shellInfile = wfEscapeShellArg( $infile );
180  $shellOutfile = wfEscapeShellArg( $outfile );
181 
183  // we assume that people with diff3 also have usual diff
184  if ( $this->useDwdiff ) {
185  $shellCommand = 'dwdiff -Pc';
186  } else {
187  $shellCommand = ( wfIsWindows() && !$wgDiff3 ) ? 'fc' : 'diff -au';
188  }
189 
190  $diff = wfShellExec( "$shellCommand $shellInfile $shellOutfile" );
191 
192  unlink( $infile );
193  unlink( $outfile );
194 
195  if ( $this->useDwdiff ) {
196  return $diff;
197  } else {
198  return $this->colorDiff( $diff );
199  }
200  }
201 
208  private function dumpToFile( $data, $filename ) {
209  $file = fopen( $filename, "wt" );
210  fwrite( $file, $data . "\n" );
211  fclose( $file );
212  }
213 
221  private function colorDiff( $text ) {
222  return preg_replace(
223  [ '/^(-.*)$/m', '/^(\+.*)$/m' ],
224  [ $this->term->color( 34 ) . '$1' . $this->term->reset(),
225  $this->term->color( 31 ) . '$1' . $this->term->reset() ],
226  $text );
227  }
228 
229  private function wellFormed( $text ) {
230  $html =
231  Sanitizer::hackDocType() .
232  '<html>' .
233  $text .
234  '</html>';
235 
236  $parser = xml_parser_create( "UTF-8" );
237 
238  # case folding violates XML standard, turn it off
239  xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
240 
241  if ( !xml_parse( $parser, $html, true ) ) {
242  $err = xml_error_string( xml_get_error_code( $parser ) );
243  $position = xml_get_current_byte_index( $parser );
244  $fragment = $this->extractFragment( $html, $position );
245  $this->xmlError = "$err at byte $position:\n$fragment";
246  xml_parser_free( $parser );
247 
248  return false;
249  }
250 
251  xml_parser_free( $parser );
252 
253  return true;
254  }
255 
256  private function extractFragment( $text, $position ) {
257  $start = max( 0, $position - 10 );
258  $before = $position - $start;
259  $fragment = '...' .
260  $this->term->color( 34 ) .
261  substr( $text, $start, $before ) .
262  $this->term->color( 0 ) .
263  $this->term->color( 31 ) .
264  $this->term->color( 1 ) .
265  substr( $text, $position, 1 ) .
266  $this->term->color( 0 ) .
267  $this->term->color( 34 ) .
268  substr( $text, $position + 1, 9 ) .
269  $this->term->color( 0 ) .
270  '...';
271  $display = str_replace( "\n", ' ', $fragment );
272  $caret = ' ' .
273  str_repeat( ' ', $before ) .
274  $this->term->color( 31 ) .
275  '^' .
276  $this->term->color( 0 );
277 
278  return "$display\n$caret";
279  }
280 
285  public function warning( $message ) {
286  echo "$message\n";
287  }
288 
294  public function skipped( $test, $subtest ) {
295  if ( $this->showProgress ) {
296  print $this->term->color( '1;33' ) . 'SKIPPED' . $this->term->reset() . "\n";
297  }
298  $this->skipped++;
299  }
300 
301  public function report() {
302  if ( $this->total > 0 ) {
303  $this->reportPercentage( $this->success, $this->total );
304  } else {
305  print $this->term->color( 31 ) . "No tests found." . $this->term->reset() . "\n";
306  }
307  }
308 
309  private function reportPercentage( $success, $total ) {
310  $ratio = wfPercent( 100 * $success / $total );
311  print $this->term->color( 1 ) . "Passed $success of $total tests ($ratio)";
312  if ( $this->skipped ) {
313  print ", skipped {$this->skipped}";
314  }
315  print "... ";
316 
317  if ( $success == $total ) {
318  print $this->term->color( 32 ) . "ALL TESTS PASSED!";
319  } else {
320  $failed = $total - $success;
321  print $this->term->color( 31 ) . "$failed tests failed!";
322  }
323 
324  print $this->term->reset() . "\n";
325 
326  return ( $success == $total );
327  }
328 }
ParserTestPrinter
This is a TestRecorder responsible for printing information about progress, success and failure to th...
Definition: ParserTestPrinter.php:27
wfPercent
wfPercent( $nr, $acc=2, $round=true)
Definition: GlobalFunctions.php:2194
ParserTestResult
Represent the result of a parser test.
Definition: ParserTestResult.php:14
$wgDiff3
$wgDiff3
Path to the GNU diff3 utility.
Definition: DefaultSettings.php:6562
$result
The index of the header message $result[1]=The index of the body text message $result[2 through n]=Parameters passed to body text message. Please note the header message cannot receive/use parameters. 'ImportHandleLogItemXMLTag':When parsing a XML tag in a log item. Return false to stop further processing of the tag $reader:XMLReader object $logInfo:Array of information 'ImportHandlePageXMLTag':When parsing a XML tag in a page. Return false to stop further processing of the tag $reader:XMLReader object & $pageInfo:Array of information 'ImportHandleRevisionXMLTag':When parsing a XML tag in a page revision. Return false to stop further processing of the tag $reader:XMLReader object $pageInfo:Array of page information $revisionInfo:Array of revision information 'ImportHandleToplevelXMLTag':When parsing a top level XML tag. Return false to stop further processing of the tag $reader:XMLReader object 'ImportHandleUploadXMLTag':When parsing a XML tag in a file upload. Return false to stop further processing of the tag $reader:XMLReader object $revisionInfo:Array of information 'ImportLogInterwikiLink':Hook to change the interwiki link used in log entries and edit summaries for transwiki imports. & $fullInterwikiPrefix:Interwiki prefix, may contain colons. & $pageTitle:String that contains page title. 'ImportSources':Called when reading from the $wgImportSources configuration variable. Can be used to lazy-load the import sources list. & $importSources:The value of $wgImportSources. Modify as necessary. See the comment in DefaultSettings.php for the detail of how to structure this array. 'InfoAction':When building information to display on the action=info page. $context:IContextSource object & $pageInfo:Array of information 'InitializeArticleMaybeRedirect':MediaWiki check to see if title is a redirect. & $title:Title object for the current page & $request:WebRequest & $ignoreRedirect:boolean to skip redirect check & $target:Title/string of redirect target & $article:Article object 'InternalParseBeforeLinks':during Parser 's internalParse method before links but after nowiki/noinclude/includeonly/onlyinclude and other processings. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InternalParseBeforeSanitize':during Parser 's internalParse method just before the parser removes unwanted/dangerous HTML tags and after nowiki/noinclude/includeonly/onlyinclude and other processings. Ideal for syntax-extensions after template/parser function execution which respect nowiki and HTML-comments. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InterwikiLoadPrefix':When resolving if a given prefix is an interwiki or not. Return true without providing an interwiki to continue interwiki search. $prefix:interwiki prefix we are looking for. & $iwData:output array describing the interwiki with keys iw_url, iw_local, iw_trans and optionally iw_api and iw_wikiid. 'InvalidateEmailComplete':Called after a user 's email has been invalidated successfully. $user:user(object) whose email is being invalidated 'IRCLineURL':When constructing the URL to use in an IRC notification. Callee may modify $url and $query, URL will be constructed as $url . $query & $url:URL to index.php & $query:Query string $rc:RecentChange object that triggered url generation 'IsFileCacheable':Override the result of Article::isFileCacheable()(if true) & $article:article(object) being checked 'IsTrustedProxy':Override the result of IP::isTrustedProxy() & $ip:IP being check & $result:Change this value to override the result of IP::isTrustedProxy() 'IsUploadAllowedFromUrl':Override the result of UploadFromUrl::isAllowedUrl() $url:URL used to upload from & $allowed:Boolean indicating if uploading is allowed for given URL 'isValidEmailAddr':Override the result of Sanitizer::validateEmail(), for instance to return false if the domain name doesn 't match your organization. $addr:The e-mail address entered by the user & $result:Set this and return false to override the internal checks 'isValidPassword':Override the result of User::isValidPassword() $password:The password entered by the user & $result:Set this and return false to override the internal checks $user:User the password is being validated for 'Language::getMessagesFileName':$code:The language code or the language we 're looking for a messages file for & $file:The messages file path, you can override this to change the location. 'LanguageGetMagic':DEPRECATED! Use $magicWords in a file listed in $wgExtensionMessagesFiles instead. Use this to define synonyms of magic words depending of the language & $magicExtensions:associative array of magic words synonyms $lang:language code(string) 'LanguageGetNamespaces':Provide custom ordering for namespaces or remove namespaces. Do not use this hook to add namespaces. Use CanonicalNamespaces for that. & $namespaces:Array of namespaces indexed by their numbers 'LanguageGetSpecialPageAliases':DEPRECATED! Use $specialPageAliases in a file listed in $wgExtensionMessagesFiles instead. Use to define aliases of special pages names depending of the language & $specialPageAliases:associative array of magic words synonyms $lang:language code(string) 'LanguageGetTranslatedLanguageNames':Provide translated language names. & $names:array of language code=> language name $code:language of the preferred translations 'LanguageLinks':Manipulate a page 's language links. This is called in various places to allow extensions to define the effective language links for a page. $title:The page 's Title. & $links:Array with elements of the form "language:title" in the order that they will be output. & $linkFlags:Associative array mapping prefixed links to arrays of flags. Currently unused, but planned to provide support for marking individual language links in the UI, e.g. for featured articles. 'LanguageSelector':Hook to change the language selector available on a page. $out:The output page. $cssClassName:CSS class name of the language selector. 'LinkBegin':DEPRECATED! Use HtmlPageLinkRendererBegin instead. Used when generating internal and interwiki links in Linker::link(), before processing starts. Return false to skip default processing and return $ret. See documentation for Linker::link() for details on the expected meanings of parameters. $skin:the Skin object $target:the Title that the link is pointing to & $html:the contents that the< a > tag should have(raw HTML) $result
Definition: hooks.txt:1963
ParserTestPrinter\$showFailure
$showFailure
Definition: ParserTestPrinter.php:34
ParserTestPrinter\record
record( $test, ParserTestResult $result)
Called after each test.
Definition: ParserTestPrinter.php:90
$output
static configuration should be added through ResourceLoaderGetConfigVars instead can be used to get the real title after the basic globals have been set but before ordinary actions take place $output
Definition: hooks.txt:2198
ParserTestPrinter\quickDiff
quickDiff( $input, $output, $inFileTail='expected', $outFileTail='actual')
Run given strings through a diff and return the (colorized) output.
Definition: ParserTestPrinter.php:156
php
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:35
ParserTestPrinter\$showDiffs
$showDiffs
Definition: ParserTestPrinter.php:32
ParserTestPrinter\report
report()
Called before finishing the test run.
Definition: ParserTestPrinter.php:301
ParserTestPrinter\showSuccess
showSuccess(ParserTestResult $testResult)
Print a happy success message.
Definition: ParserTestPrinter.php:107
$html
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses just before the function returns a value If you return an< a > element with HTML attributes $attribs and contents $html will be returned If you return $ret will be returned and may include noclasses & $html
Definition: hooks.txt:1965
ParserTestPrinter\$showOutput
$showOutput
Definition: ParserTestPrinter.php:35
$input
if(is_array( $mode)) switch( $mode) $input
Definition: postprocess-phan.php:141
ParserTestPrinter\wellFormed
wellFormed( $text)
Definition: ParserTestPrinter.php:229
TestRecorder
Interface to record parser test results.
Definition: TestRecorder.php:35
ParserTestPrinter\$useDwdiff
$useDwdiff
Definition: ParserTestPrinter.php:36
ParserTestPrinter\$success
$success
Definition: ParserTestPrinter.php:29
$parser
do that in ParserLimitReportFormat instead $parser
Definition: hooks.txt:2572
ParserTestPrinter\colorDiff
colorDiff( $text)
Colorize unified diff output if set for ANSI color output.
Definition: ParserTestPrinter.php:221
global
when a variable name is used in a it is silently declared as a new masking the global
Definition: design.txt:93
ParserTestPrinter\startSuite
startSuite( $path)
Show "Reading tests from ...".
Definition: ParserTestPrinter.php:79
ParserTestPrinter\$markWhitespace
$markWhitespace
Definition: ParserTestPrinter.php:37
ParserTestPrinter\startTest
startTest( $test)
Called before starting a test.
Definition: ParserTestPrinter.php:64
ParserTestPrinter\dumpToFile
dumpToFile( $data, $filename)
Write the given string to a file, adding a final newline.
Definition: ParserTestPrinter.php:208
wfIsWindows
wfIsWindows()
Check if the operating system is Windows.
Definition: GlobalFunctions.php:2079
ParserTestPrinter\$skipped
$skipped
Definition: ParserTestPrinter.php:30
wfEscapeShellArg
wfEscapeShellArg()
Version of escapeshellarg() that works better on Windows.
Definition: GlobalFunctions.php:2243
ParserTestPrinter\showFailure
showFailure(ParserTestResult $testResult)
Print a failure message and provide some explanatory output about what went wrong if so configured.
Definition: ParserTestPrinter.php:120
ParserTestPrinter\$total
$total
Definition: ParserTestPrinter.php:28
ParserTestPrinter\endSuite
endSuite( $path)
Called after ending an input file.
Definition: ParserTestPrinter.php:86
wfTempDir
wfTempDir()
Tries to get the system directory for temporary files.
Definition: GlobalFunctions.php:2107
$options
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped & $options
Definition: hooks.txt:1965
$path
$path
Definition: NoLocalSettings.php:26
ParserTestPrinter\start
start()
Called at beginning of the parser test run.
Definition: ParserTestPrinter.php:58
ParserTestPrinter\__construct
__construct( $term, $options)
Definition: ParserTestPrinter.php:40
ParserTestResult\getDescription
getDescription()
Definition: ParserTestResult.php:41
ParserTestPrinter\reportPercentage
reportPercentage( $success, $total)
Definition: ParserTestPrinter.php:309
ParserTestPrinter\extractFragment
extractFragment( $text, $position)
Definition: ParserTestPrinter.php:256
ParserTestPrinter\$term
$term
Definition: ParserTestPrinter.php:31
term
which are not or by specifying more than one search term(only pages containing all of the search terms will appear in the result).</td >< td >
Definition: All_system_messages.txt:3005
ParserTestPrinter\warning
warning( $message)
Show a warning to the user.
Definition: ParserTestPrinter.php:285
ParserTestPrinter\$showProgress
$showProgress
Definition: ParserTestPrinter.php:33
ParserTestPrinter\$xmlError
$xmlError
Definition: ParserTestPrinter.php:38
ParserTestPrinter\showTesting
showTesting( $desc)
Definition: ParserTestPrinter.php:70
ParserTestPrinter\skipped
skipped( $test, $subtest)
Mark a test skipped.
Definition: ParserTestPrinter.php:294
wfShellExec
wfShellExec( $cmd, &$retval=null, $environ=[], $limits=[], $options=[])
Execute a shell command, with time and memory limits mirrored from the PHP configuration if supported...
Definition: GlobalFunctions.php:2283