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  $infile = tempnam( wfTempDir(), "mwParser-$inFileTail" );
172  $this->dumpToFile( $input, $infile );
173 
174  $outfile = tempnam( wfTempDir(), "mwParser-$outFileTail" );
175  $this->dumpToFile( $output, $outfile );
176 
177  global $wgDiff3;
178  // we assume that people with diff3 also have usual diff
179  if ( $this->useDwdiff ) {
180  $shellCommand = 'dwdiff -Pc';
181  } else {
182  $shellCommand = ( wfIsWindows() && !$wgDiff3 ) ? 'fc' : 'diff -au';
183  }
184 
185  $result = Shell::command()
186  ->unsafeParams( $shellCommand )
187  ->params( $infile, $outfile )
188  ->execute();
189  $diff = $result->getStdout();
190 
191  unlink( $infile );
192  unlink( $outfile );
193 
194  if ( $this->useDwdiff ) {
195  return $diff;
196  } else {
197  return $this->colorDiff( $diff );
198  }
199  }
200 
207  private function dumpToFile( $data, $filename ) {
208  $file = fopen( $filename, "wt" );
209  fwrite( $file, $data . "\n" );
210  fclose( $file );
211  }
212 
220  private function colorDiff( $text ) {
221  return preg_replace(
222  [ '/^(-.*)$/m', '/^(\+.*)$/m' ],
223  [ $this->term->color( 34 ) . '$1' . $this->term->reset(),
224  $this->term->color( 31 ) . '$1' . $this->term->reset() ],
225  $text );
226  }
227 
228  private function wellFormed( $text ) {
229  $html =
231  '<html>' .
232  $text .
233  '</html>';
234 
235  $parser = xml_parser_create( "UTF-8" );
236 
237  # case folding violates XML standard, turn it off
238  xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
239 
240  if ( !xml_parse( $parser, $html, true ) ) {
241  $err = xml_error_string( xml_get_error_code( $parser ) );
242  $position = xml_get_current_byte_index( $parser );
243  $fragment = $this->extractFragment( $html, $position );
244  $this->xmlError = "$err at byte $position:\n$fragment";
245  xml_parser_free( $parser );
246 
247  return false;
248  }
249 
250  xml_parser_free( $parser );
251 
252  return true;
253  }
254 
255  private function extractFragment( $text, $position ) {
256  $start = max( 0, $position - 10 );
257  $before = $position - $start;
258  $fragment = '...' .
259  $this->term->color( 34 ) .
260  substr( $text, $start, $before ) .
261  $this->term->color( 0 ) .
262  $this->term->color( 31 ) .
263  $this->term->color( 1 ) .
264  substr( $text, $position, 1 ) .
265  $this->term->color( 0 ) .
266  $this->term->color( 34 ) .
267  substr( $text, $position + 1, 9 ) .
268  $this->term->color( 0 ) .
269  '...';
270  $display = str_replace( "\n", ' ', $fragment );
271  $caret = ' ' .
272  str_repeat( ' ', $before ) .
273  $this->term->color( 31 ) .
274  '^' .
275  $this->term->color( 0 );
276 
277  return "$display\n$caret";
278  }
279 
284  public function warning( $message ) {
285  echo "$message\n";
286  }
287 
293  public function skipped( $test, $subtest ) {
294  if ( $this->showProgress ) {
295  print $this->term->color( '1;33' ) . 'SKIPPED' . $this->term->reset() . "\n";
296  }
297  $this->skipped++;
298  }
299 
300  public function report() {
301  if ( $this->total > 0 ) {
302  $this->reportPercentage( $this->success, $this->total );
303  } else {
304  print $this->term->color( 31 ) . "No tests found." . $this->term->reset() . "\n";
305  }
306  }
307 
308  private function reportPercentage( $success, $total ) {
309  $ratio = wfPercent( 100 * $success / $total );
310  print $this->term->color( 1 ) . "Passed $success of $total tests ($ratio)";
311  if ( $this->skipped ) {
312  print ", skipped {$this->skipped}";
313  }
314  print "... ";
315 
316  if ( $success == $total ) {
317  print $this->term->color( 32 ) . "ALL TESTS PASSED!";
318  } else {
319  $failed = $total - $success;
320  print $this->term->color( 31 ) . "$failed tests failed!";
321  }
322 
323  print $this->term->reset() . "\n";
324 
325  return ( $success == $total );
326  }
327 }
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:1972
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:2065
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:1781
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:2205
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. 'ImgAuthModifyHeaders':Executed just before a file is streamed to a user via img_auth.php, allowing headers to be modified beforehand. $title:LinkTarget object & $headers:HTTP headers(name=> value, names are case insensitive). Two headers get special handling:If-Modified-Since(value must be a valid HTTP date) and Range(must be of the form "bytes=(\*-\*)") will be honored when streaming the file. '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:1970
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:1972
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.