MediaWiki  master
ParserTestPrinter.php
Go to the documentation of this file.
1 <?php
23 
30  private $total;
31  private $success;
32  private $skipped;
33  private $term;
34  private $showDiffs;
35  private $showProgress;
36  private $showFailure;
37  private $showOutput;
38  private $useDwdiff;
39  private $markWhitespace;
40  private $xmlError;
41 
42  function __construct( $term, $options ) {
43  $this->term = $term;
44  $options += [
45  'showDiffs' => true,
46  'showProgress' => true,
47  'showFailure' => true,
48  'showOutput' => false,
49  'useDwdiff' => false,
50  'markWhitespace' => false,
51  ];
52  $this->showDiffs = $options['showDiffs'];
53  $this->showProgress = $options['showProgress'];
54  $this->showFailure = $options['showFailure'];
55  $this->showOutput = $options['showOutput'];
56  $this->useDwdiff = $options['useDwdiff'];
57  $this->markWhitespace = $options['markWhitespace'];
58  }
59 
60  public function start() {
61  $this->total = 0;
62  $this->success = 0;
63  $this->skipped = 0;
64  }
65 
66  public function startTest( $test ) {
67  if ( $this->showProgress ) {
68  $this->showTesting( $test['desc'] );
69  }
70  }
71 
72  private function showTesting( $desc ) {
73  print "Running test $desc... ";
74  }
75 
81  public function startSuite( $path ) {
82  print $this->term->color( 1 ) .
83  "Running parser tests from \"$path\"..." .
84  $this->term->reset() .
85  "\n";
86  }
87 
88  public function endSuite( $path ) {
89  print "\n";
90  }
91 
92  public function record( $test, ParserTestResult $result ) {
93  $this->total++;
94  $this->success += ( $result->isSuccess() ? 1 : 0 );
95 
96  if ( $result->isSuccess() ) {
97  $this->showSuccess( $result );
98  } else {
99  $this->showFailure( $result );
100  }
101  }
102 
109  private function showSuccess( ParserTestResult $testResult ) {
110  if ( $this->showProgress ) {
111  print $this->term->color( '1;32' ) . 'PASSED' . $this->term->reset() . "\n";
112  }
113  }
114 
122  private function showFailure( ParserTestResult $testResult ) {
123  if ( $this->showFailure ) {
124  if ( !$this->showProgress ) {
125  # In quiet mode we didn't show the 'Testing' message before the
126  # test, in case it succeeded. Show it now:
127  $this->showTesting( $testResult->getDescription() );
128  }
129 
130  print $this->term->color( '31' ) . 'FAILED!' . $this->term->reset() . "\n";
131 
132  if ( $this->showOutput ) {
133  print "--- Expected ---\n{$testResult->expected}\n";
134  print "--- Actual ---\n{$testResult->actual}\n";
135  }
136 
137  if ( $this->showDiffs ) {
138  print $this->quickDiff( $testResult->expected, $testResult->actual );
139  if ( !$this->wellFormed( $testResult->actual ) ) {
140  print "XML error: $this->xmlError\n";
141  }
142  }
143  }
144 
145  return false;
146  }
147 
158  private function quickDiff( $input, $output,
159  $inFileTail = 'expected', $outFileTail = 'actual'
160  ) {
161  if ( $this->markWhitespace ) {
162  $pairs = [
163  "\n" => '¶',
164  ' ' => '·',
165  "\t" => '→'
166  ];
167  $input = strtr( $input, $pairs );
168  $output = strtr( $output, $pairs );
169  }
170 
171  # Windows, or at least the fc utility, is retarded
172  $slash = wfIsWindows() ? '\\' : '/';
173  $prefix = wfTempDir() . "{$slash}mwParser-" . mt_rand();
174 
175  $infile = "$prefix-$inFileTail";
176  $this->dumpToFile( $input, $infile );
177 
178  $outfile = "$prefix-$outFileTail";
179  $this->dumpToFile( $output, $outfile );
180 
181  global $wgDiff3;
182  // we assume that people with diff3 also have usual diff
183  if ( $this->useDwdiff ) {
184  $shellCommand = 'dwdiff -Pc';
185  } else {
186  $shellCommand = ( wfIsWindows() && !$wgDiff3 ) ? 'fc' : 'diff -au';
187  }
188 
189  $result = Shell::command()
190  ->unsafeParams( $shellCommand )
191  ->params( $infile, $outfile )
192  ->execute();
193  $diff = $result->getStdout();
194 
195  unlink( $infile );
196  unlink( $outfile );
197 
198  if ( $this->useDwdiff ) {
199  return $diff;
200  } else {
201  return $this->colorDiff( $diff );
202  }
203  }
204 
211  private function dumpToFile( $data, $filename ) {
212  $file = fopen( $filename, "wt" );
213  fwrite( $file, $data . "\n" );
214  fclose( $file );
215  }
216 
224  private function colorDiff( $text ) {
225  return preg_replace(
226  [ '/^(-.*)$/m', '/^(\+.*)$/m' ],
227  [ $this->term->color( 34 ) . '$1' . $this->term->reset(),
228  $this->term->color( 31 ) . '$1' . $this->term->reset() ],
229  $text );
230  }
231 
232  private function wellFormed( $text ) {
233  $html =
235  '<html>' .
236  $text .
237  '</html>';
238 
239  $parser = xml_parser_create( "UTF-8" );
240 
241  # case folding violates XML standard, turn it off
242  xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
243 
244  if ( !xml_parse( $parser, $html, true ) ) {
245  $err = xml_error_string( xml_get_error_code( $parser ) );
246  $position = xml_get_current_byte_index( $parser );
247  $fragment = $this->extractFragment( $html, $position );
248  $this->xmlError = "$err at byte $position:\n$fragment";
249  xml_parser_free( $parser );
250 
251  return false;
252  }
253 
254  xml_parser_free( $parser );
255 
256  return true;
257  }
258 
259  private function extractFragment( $text, $position ) {
260  $start = max( 0, $position - 10 );
261  $before = $position - $start;
262  $fragment = '...' .
263  $this->term->color( 34 ) .
264  substr( $text, $start, $before ) .
265  $this->term->color( 0 ) .
266  $this->term->color( 31 ) .
267  $this->term->color( 1 ) .
268  substr( $text, $position, 1 ) .
269  $this->term->color( 0 ) .
270  $this->term->color( 34 ) .
271  substr( $text, $position + 1, 9 ) .
272  $this->term->color( 0 ) .
273  '...';
274  $display = str_replace( "\n", ' ', $fragment );
275  $caret = ' ' .
276  str_repeat( ' ', $before ) .
277  $this->term->color( 31 ) .
278  '^' .
279  $this->term->color( 0 );
280 
281  return "$display\n$caret";
282  }
283 
288  public function warning( $message ) {
289  echo "$message\n";
290  }
291 
297  public function skipped( $test, $subtest ) {
298  if ( $this->showProgress ) {
299  print $this->term->color( '1;33' ) . 'SKIPPED' . $this->term->reset() . "\n";
300  }
301  $this->skipped++;
302  }
303 
304  public function report() {
305  if ( $this->total > 0 ) {
306  $this->reportPercentage( $this->success, $this->total );
307  } else {
308  print $this->term->color( 31 ) . "No tests found." . $this->term->reset() . "\n";
309  }
310  }
311 
312  private function reportPercentage( $success, $total ) {
313  $ratio = wfPercent( 100 * $success / $total );
314  print $this->term->color( 1 ) . "Passed $success of $total tests ($ratio)";
315  if ( $this->skipped ) {
316  print ", skipped {$this->skipped}";
317  }
318  print "... ";
319 
320  if ( $success == $total ) {
321  print $this->term->color( 32 ) . "ALL TESTS PASSED!";
322  } else {
323  $failed = $total - $success;
324  print $this->term->color( 31 ) . "$failed tests failed!";
325  }
326 
327  print $this->term->reset() . "\n";
328 
329  return ( $success == $total );
330  }
331 }
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:1982
$data
Utility to generate mapping file used in mw.Title (phpCharToUpper.json)
if(is_array( $mode)) switch( $mode) $input
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
if(PHP_SAPI !='cli-server') if(!isset( $_SERVER['SCRIPT_FILENAME'])) $file
Definition: router.php:42
quickDiff( $input, $output, $inFileTail='expected', $outFileTail='actual')
Run given strings through a diff and return the (colorized) output.
static hackDocType()
Hack up a private DOCTYPE with HTML&#39;s standard entity declarations.
Definition: Sanitizer.php:2017
wfIsWindows()
Check if the operating system is Windows.
see documentation in includes Linker php for Linker::makeImageLink or false for current used if you return false $parser
Definition: hooks.txt:1799
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 >
record( $test, ParserTestResult $result)
wfPercent( $nr, $acc=2, $round=true)
static configuration should be added through ResourceLoaderGetConfigVars instead can be used to get the real title e g db for database replication lag or jobqueue for job queue size converted to pseudo seconds It is possible to add more fields and they will be returned to the user in the API response after the basic globals have been set but before ordinary actions take place $output
Definition: hooks.txt:2217
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 'ImportHandleUnknownUser':When a user doesn 't exist locally, this hook is called to give extensions an opportunity to auto-create it. If the auto-creation is successful, return false. $name:User name '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. '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 '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 since 1.28! 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:1980
wfTempDir()
Tries to get the system directory for temporary files.
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:1982
This is a TestRecorder responsible for printing information about progress, success and failure to th...
showSuccess(ParserTestResult $testResult)
Print a happy success message.
colorDiff( $text)
Colorize unified diff output if set for ANSI color output.
isSuccess()
Whether the test passed.
startSuite( $path)
Show "Reading tests from ...".
$wgDiff3
Path to the GNU diff3 utility.
Interface to record parser test results.
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
reportPercentage( $success, $total)
showFailure(ParserTestResult $testResult)
Print a failure message and provide some explanatory output about what went wrong if so configured...
warning( $message)
Show a warning to the user.
dumpToFile( $data, $filename)
Write the given string to a file, adding a final newline.
skipped( $test, $subtest)
Mark a test skipped.
__construct( $term, $options)
extractFragment( $text, $position)
Represent the result of a parser test.