Fixes for r39727
[lhc/web/wiklou.git] / maintenance / parserTests.inc
1 <?php
2 # Copyright (C) 2004 Brion Vibber <brion@pobox.com>
3 # http://www.mediawiki.org/
4 #
5 # This program is free software; you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 2 of the License, or
8 # (at your option) any later version.
9 #
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License along
16 # with this program; if not, write to the Free Software Foundation, Inc.,
17 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 # http://www.gnu.org/copyleft/gpl.html
19
20 /**
21 * @todo Make this more independent of the configuration (and if possible the database)
22 * @todo document
23 * @file
24 * @ingroup Maintenance
25 */
26
27 /** */
28 $options = array( 'quick', 'color', 'quiet', 'help', 'show-output', 'record' );
29 $optionsWithArgs = array( 'regex' );
30
31 require_once( 'commandLine.inc' );
32 require_once( "$IP/maintenance/parserTestsParserHook.php" );
33 require_once( "$IP/maintenance/parserTestsStaticParserHook.php" );
34 require_once( "$IP/maintenance/parserTestsParserTime.php" );
35
36 /**
37 * @ingroup Maintenance
38 */
39 class ParserTest {
40 /**
41 * boolean $color whereas output should be colorized
42 */
43 private $color;
44
45 /**
46 * boolean $showOutput Show test output
47 */
48 private $showOutput;
49
50 /**
51 * boolean $useTemporaryTables Use temporary tables for the temporary database
52 */
53 private $useTemporaryTables = true;
54
55 /**
56 * boolean $databaseSetupDone True if the database has been set up
57 */
58 private $databaseSetupDone = false;
59
60 /**
61 * string $oldTablePrefix Original table prefix
62 */
63 private $oldTablePrefix;
64
65 /**
66 * Sets terminal colorization and diff/quick modes depending on OS and
67 * command-line options (--color and --quick).
68 */
69 public function ParserTest() {
70 global $options;
71
72 # Only colorize output if stdout is a terminal.
73 $this->color = !wfIsWindows() && posix_isatty(1);
74
75 if( isset( $options['color'] ) ) {
76 switch( $options['color'] ) {
77 case 'no':
78 $this->color = false;
79 break;
80 case 'yes':
81 default:
82 $this->color = true;
83 break;
84 }
85 }
86 $this->term = $this->color
87 ? new AnsiTermColorer()
88 : new DummyTermColorer();
89
90 $this->showDiffs = !isset( $options['quick'] );
91 $this->showProgress = !isset( $options['quiet'] );
92 $this->showFailure = !(
93 isset( $options['quiet'] )
94 && ( isset( $options['record'] )
95 || isset( $options['compare'] ) ) ); // redundant output
96
97 $this->showOutput = isset( $options['show-output'] );
98
99
100 if (isset($options['regex'])) {
101 if ( isset( $options['record'] ) ) {
102 echo "Warning: --record cannot be used with --regex, disabling --record\n";
103 unset( $options['record'] );
104 }
105 $this->regex = $options['regex'];
106 } else {
107 # Matches anything
108 $this->regex = '';
109 }
110
111 if( isset( $options['record'] ) ) {
112 $this->recorder = new DbTestRecorder( $this );
113 } elseif( isset( $options['compare'] ) ) {
114 $this->recorder = new DbTestPreviewer( $this );
115 } else {
116 $this->recorder = new TestRecorder( $this );
117 }
118 $this->keepUploads = isset( $options['keep-uploads'] );
119
120 $this->hooks = array();
121 $this->functionHooks = array();
122 }
123
124 /**
125 * Remove last character if it is a newline
126 */
127 private function chomp($s) {
128 if (substr($s, -1) === "\n") {
129 return substr($s, 0, -1);
130 }
131 else {
132 return $s;
133 }
134 }
135
136 /**
137 * Run a series of tests listed in the given text files.
138 * Each test consists of a brief description, wikitext input,
139 * and the expected HTML output.
140 *
141 * Prints status updates on stdout and counts up the total
142 * number and percentage of passed tests.
143 *
144 * @param array of strings $filenames
145 * @return bool True if passed all tests, false if any tests failed.
146 */
147 public function runTestsFromFiles( $filenames ) {
148 $this->recorder->start();
149 $this->setupDatabase();
150 $ok = true;
151 foreach( $filenames as $filename ) {
152 $ok = $this->runFile( $filename ) && $ok;
153 }
154 $this->teardownDatabase();
155 $this->recorder->report();
156 $this->recorder->end();
157 return $ok;
158 }
159
160 private function runFile( $filename ) {
161 $infile = fopen( $filename, 'rt' );
162 if( !$infile ) {
163 wfDie( "Couldn't open $filename\n" );
164 } else {
165 global $IP;
166 $relative = wfRelativePath( $filename, $IP );
167 $this->showRunFile( $relative );
168 }
169
170 $data = array();
171 $section = null;
172 $n = 0;
173 $ok = true;
174 while( false !== ($line = fgets( $infile ) ) ) {
175 $n++;
176 $matches = array();
177 if( preg_match( '/^!!\s*(\w+)/', $line, $matches ) ) {
178 $section = strtolower( $matches[1] );
179 if( $section == 'endarticle') {
180 if( !isset( $data['text'] ) ) {
181 wfDie( "'endarticle' without 'text' at line $n of $filename\n" );
182 }
183 if( !isset( $data['article'] ) ) {
184 wfDie( "'endarticle' without 'article' at line $n of $filename\n" );
185 }
186 $this->addArticle($this->chomp($data['article']), $this->chomp($data['text']), $n);
187 $data = array();
188 $section = null;
189 continue;
190 }
191 if( $section == 'endhooks' ) {
192 if( !isset( $data['hooks'] ) ) {
193 wfDie( "'endhooks' without 'hooks' at line $n of $filename\n" );
194 }
195 foreach( explode( "\n", $data['hooks'] ) as $line ) {
196 $line = trim( $line );
197 if( $line ) {
198 $this->requireHook( $line );
199 }
200 }
201 $data = array();
202 $section = null;
203 continue;
204 }
205 if( $section == 'endfunctionhooks' ) {
206 if( !isset( $data['functionhooks'] ) ) {
207 wfDie( "'endfunctionhooks' without 'functionhooks' at line $n of $filename\n" );
208 }
209 foreach( explode( "\n", $data['functionhooks'] ) as $line ) {
210 $line = trim( $line );
211 if( $line ) {
212 $this->requireFunctionHook( $line );
213 }
214 }
215 $data = array();
216 $section = null;
217 continue;
218 }
219 if( $section == 'end' ) {
220 if( !isset( $data['test'] ) ) {
221 wfDie( "'end' without 'test' at line $n of $filename\n" );
222 }
223 if( !isset( $data['input'] ) ) {
224 wfDie( "'end' without 'input' at line $n of $filename\n" );
225 }
226 if( !isset( $data['result'] ) ) {
227 wfDie( "'end' without 'result' at line $n of $filename\n" );
228 }
229 if( !isset( $data['options'] ) ) {
230 $data['options'] = '';
231 }
232 else {
233 $data['options'] = $this->chomp( $data['options'] );
234 }
235 if (preg_match('/\\bdisabled\\b/i', $data['options'])
236 || !preg_match("/{$this->regex}/i", $data['test'])) {
237 # disabled test
238 $data = array();
239 $section = null;
240 continue;
241 }
242 $result = $this->runTest(
243 $this->chomp( $data['test'] ),
244 $this->chomp( $data['input'] ),
245 $this->chomp( $data['result'] ),
246 $this->chomp( $data['options'] ) );
247 $ok = $ok && $result;
248 $this->recorder->record( $this->chomp( $data['test'] ), $result );
249 $data = array();
250 $section = null;
251 continue;
252 }
253 if ( isset ($data[$section] ) ) {
254 wfDie( "duplicate section '$section' at line $n of $filename\n" );
255 }
256 $data[$section] = '';
257 continue;
258 }
259 if( $section ) {
260 $data[$section] .= $line;
261 }
262 }
263 if ( $this->showProgress ) {
264 print "\n";
265 }
266 return $ok;
267 }
268
269 /**
270 * Run a given wikitext input through a freshly-constructed wiki parser,
271 * and compare the output against the expected results.
272 * Prints status and explanatory messages to stdout.
273 *
274 * @param string $input Wikitext to try rendering
275 * @param string $result Result to output
276 * @return bool
277 */
278 private function runTest( $desc, $input, $result, $opts ) {
279 global $wgParserConf;
280 if( $this->showProgress ) {
281 $this->showTesting( $desc );
282 }
283
284 $this->setupGlobals($opts);
285
286 $user = new User();
287 $options = ParserOptions::newFromUser( $user );
288
289 if (preg_match('/\\bmath\\b/i', $opts)) {
290 # XXX this should probably be done by the ParserOptions
291 $options->setUseTex(true);
292 }
293
294 $m = array();
295 if (preg_match('/title=\[\[(.*)\]\]/', $opts, $m)) {
296 $titleText = $m[1];
297 }
298 else {
299 $titleText = 'Parser test';
300 }
301
302 $noxml = (bool)preg_match( '~\\b noxml \\b~x', $opts );
303
304 $class = $wgParserConf['class'];
305 $parser = new $class( $wgParserConf );
306 foreach( $this->hooks as $tag => $callback ) {
307 $parser->setHook( $tag, $callback );
308 }
309 foreach( $this->functionHooks as $tag => $bits ) {
310 list( $callback, $flags ) = $bits;
311 $parser->setFunctionHook( $tag, $callback, $flags );
312 }
313 wfRunHooks( 'ParserTestParser', array( &$parser ) );
314
315 $title =& Title::makeTitle( NS_MAIN, $titleText );
316
317 $matches = array();
318 if (preg_match('/\\bpst\\b/i', $opts)) {
319 $out = $parser->preSaveTransform( $input, $title, $user, $options );
320 } elseif (preg_match('/\\bmsg\\b/i', $opts)) {
321 $out = $parser->transformMsg( $input, $options );
322 } elseif( preg_match( '/\\bsection=([\w-]+)\b/i', $opts, $matches ) ) {
323 $section = $matches[1];
324 $out = $parser->getSection( $input, $section );
325 } elseif( preg_match( '/\\breplace=([\w-]+),"(.*?)"/i', $opts, $matches ) ) {
326 $section = $matches[1];
327 $replace = $matches[2];
328 $out = $parser->replaceSection( $input, $section, $replace );
329 } else {
330 $output = $parser->parse( $input, $title, $options, true, true, 1337 );
331 $out = $output->getText();
332
333 if (preg_match('/\\bill\\b/i', $opts)) {
334 $out = $this->tidy( implode( ' ', $output->getLanguageLinks() ) );
335 } else if (preg_match('/\\bcat\\b/i', $opts)) {
336 global $wgOut;
337 $wgOut->addCategoryLinks($output->getCategories());
338 $cats = $wgOut->getCategoryLinks();
339 if ( isset( $cats['normal'] ) ) {
340 $out = $this->tidy( implode( ' ', $cats['normal'] ) );
341 } else {
342 $out = '';
343 }
344 }
345
346 $result = $this->tidy($result);
347 }
348
349 $this->teardownGlobals();
350
351 if( $result === $out && ( $noxml === true || $this->wellFormed( $out ) ) ) {
352 return $this->showSuccess( $desc );
353 } else {
354 return $this->showFailure( $desc, $result, $out );
355 }
356 }
357
358
359 /**
360 * Use a regex to find out the value of an option
361 * @param $regex A regex, the first group will be the value returned
362 * @param $opts Options line to look in
363 * @param $defaults Default value returned if the regex does not match
364 */
365 private static function getOptionValue( $regex, $opts, $default ) {
366 $m = array();
367 if( preg_match( $regex, $opts, $m ) ) {
368 return $m[1];
369 } else {
370 return $default;
371 }
372 }
373
374 /**
375 * Set up the global variables for a consistent environment for each test.
376 * Ideally this should replace the global configuration entirely.
377 */
378 private function setupGlobals($opts = '') {
379 if( !isset( $this->uploadDir ) ) {
380 $this->uploadDir = $this->setupUploadDir();
381 }
382
383 # Find out values for some special options.
384 $lang =
385 self::getOptionValue( '/language=([a-z]+(?:_[a-z]+)?)/', $opts, 'en' );
386 $variant =
387 self::getOptionValue( '/variant=([a-z]+(?:-[a-z]+)?)/', $opts, false );
388 $maxtoclevel =
389 self::getOptionValue( '/wgMaxTocLevel=(\d+)/', $opts, 999 );
390
391 $settings = array(
392 'wgServer' => 'http://localhost',
393 'wgScript' => '/index.php',
394 'wgScriptPath' => '/',
395 'wgArticlePath' => '/wiki/$1',
396 'wgActionPaths' => array(),
397 'wgLocalFileRepo' => array(
398 'class' => 'LocalRepo',
399 'name' => 'local',
400 'directory' => $this->uploadDir,
401 'url' => 'http://example.com/images',
402 'hashLevels' => 2,
403 'transformVia404' => false,
404 ),
405 'wgEnableUploads' => true,
406 'wgStyleSheetPath' => '/skins',
407 'wgSitename' => 'MediaWiki',
408 'wgServerName' => 'Britney Spears',
409 'wgLanguageCode' => $lang,
410 'wgContLanguageCode' => $lang,
411 'wgDBprefix' => 'parsertest_',
412 'wgRawHtml' => preg_match('/\\brawhtml\\b/i', $opts),
413 'wgLang' => null,
414 'wgContLang' => null,
415 'wgNamespacesWithSubpages' => array( 0 => preg_match('/\\bsubpage\\b/i', $opts)),
416 'wgMaxTocLevel' => $maxtoclevel,
417 'wgCapitalLinks' => true,
418 'wgNoFollowLinks' => true,
419 'wgThumbnailScriptPath' => false,
420 'wgUseTeX' => false,
421 'wgLocaltimezone' => 'UTC',
422 'wgAllowExternalImages' => true,
423 'wgUseTidy' => false,
424 'wgDefaultLanguageVariant' => $variant,
425 'wgVariantArticlePath' => false,
426 'wgGroupPermissions' => array( '*' => array(
427 'createaccount' => true,
428 'read' => true,
429 'edit' => true,
430 'createpage' => true,
431 'createtalk' => true,
432 ) ),
433 'wgDefaultExternalStore' => array(),
434 'wgForeignFileRepos' => array(),
435 );
436 $this->savedGlobals = array();
437 foreach( $settings as $var => $val ) {
438 $this->savedGlobals[$var] = $GLOBALS[$var];
439 $GLOBALS[$var] = $val;
440 }
441 $langObj = Language::factory( $lang );
442 $GLOBALS['wgLang'] = $langObj;
443 $GLOBALS['wgContLang'] = $langObj;
444
445 //$GLOBALS['wgMessageCache'] = new MessageCache( new BagOStuff(), false, 0, $GLOBALS['wgDBname'] );
446
447 global $wgUser;
448 $wgUser = new User();
449 }
450
451 /**
452 * List of temporary tables to create, without prefix.
453 * Some of these probably aren't necessary.
454 */
455 private function listTables() {
456 global $wgDBtype;
457 $tables = array('user', 'page', 'page_restrictions',
458 'protected_titles', 'revision', 'text', 'pagelinks', 'imagelinks',
459 'categorylinks', 'templatelinks', 'externallinks', 'langlinks',
460 'site_stats', 'hitcounter', 'ipblocks', 'image', 'oldimage',
461 'recentchanges', 'watchlist', 'math', 'interwiki',
462 'querycache', 'objectcache', 'job', 'redirect', 'querycachetwo',
463 'archive', 'user_groups', 'page_props', 'category'
464 );
465
466 if ($wgDBtype === 'mysql')
467 array_push( $tables, 'searchindex' );
468
469 // Allow extensions to add to the list of tables to duplicate;
470 // may be necessary if they hook into page save or other code
471 // which will require them while running tests.
472 wfRunHooks( 'ParserTestTables', array( &$tables ) );
473
474 return $tables;
475 }
476
477 /**
478 * Set up a temporary set of wiki tables to work with for the tests.
479 * Currently this will only be done once per run, and any changes to
480 * the db will be visible to later tests in the run.
481 */
482 private function setupDatabase() {
483 global $wgDBprefix;
484 if ( $this->databaseSetupDone ) {
485 return;
486 }
487 if ( $wgDBprefix === 'parsertest_' ) {
488 throw new MWException( 'setupDatabase should be called before setupGlobals' );
489 }
490 $this->databaseSetupDone = true;
491 $this->oldTablePrefix = $wgDBprefix;
492
493 # CREATE TEMPORARY TABLE breaks if there is more than one server
494 if ( wfGetLB()->getServerCount() != 1 ) {
495 $this->useTemporaryTables = false;
496 }
497
498 $temporary = $this->useTemporaryTables ? 'TEMPORARY' : '';
499
500 $db = wfGetDB( DB_MASTER );
501 $tables = $this->listTables();
502
503 if (!(strcmp($db->getServerVersion(), '4.1') < 0 and stristr($db->getSoftwareLink(), 'MySQL'))) {
504 # Database that supports CREATE TABLE ... LIKE
505 global $wgDBtype;
506 if( $wgDBtype == 'postgres' ) {
507 $def = 'INCLUDING DEFAULTS';
508 } else {
509 $def = '';
510 }
511 foreach ($tables as $tbl) {
512 # Clean up from previous aborted run. So that table escaping
513 # works correctly across DB engines, we need to change the pre-
514 # fix back and forth so tableName() works right.
515 $this->changePrefix( $this->oldTablePrefix );
516 $oldTableName = $db->tableName( $tbl );
517 $this->changePrefix( 'parsertest_' );
518 $newTableName = $db->tableName( $tbl );
519
520 if ( $db->tableExists( $tbl ) ) {
521 $db->query("DROP TABLE $newTableName");
522 }
523 # Create new table
524 $db->query("CREATE $temporary TABLE $newTableName (LIKE $oldTableName $def)");
525 }
526 } else {
527 # Hack for MySQL versions < 4.1, which don't support
528 # "CREATE TABLE ... LIKE". Note that
529 # "CREATE TEMPORARY TABLE ... SELECT * FROM ... LIMIT 0"
530 # would not create the indexes we need....
531 #
532 # Note that we don't bother changing around the prefixes here be-
533 # cause we know we're using MySQL anyway.
534 foreach ($tables as $tbl) {
535 $oldTableName = $db->tableName( $tbl );
536 $res = $db->query("SHOW CREATE TABLE $oldTableName");
537 $row = $db->fetchRow($res);
538 $create = $row[1];
539 $create_tmp = preg_replace('/CREATE TABLE `(.*?)`/',
540 "CREATE $temporary TABLE `parsertest_$tbl`", $create);
541 if ($create === $create_tmp) {
542 # Couldn't do replacement
543 wfDie("could not create temporary table $tbl");
544 }
545 $db->query($create_tmp);
546 }
547 }
548
549 $this->changePrefix( 'parsertest_' );
550
551 # Hack: insert a few Wikipedia in-project interwiki prefixes,
552 # for testing inter-language links
553 $db->insert( 'interwiki', array(
554 array( 'iw_prefix' => 'Wikipedia',
555 'iw_url' => 'http://en.wikipedia.org/wiki/$1',
556 'iw_local' => 0 ),
557 array( 'iw_prefix' => 'MeatBall',
558 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
559 'iw_local' => 0 ),
560 array( 'iw_prefix' => 'zh',
561 'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
562 'iw_local' => 1 ),
563 array( 'iw_prefix' => 'es',
564 'iw_url' => 'http://es.wikipedia.org/wiki/$1',
565 'iw_local' => 1 ),
566 array( 'iw_prefix' => 'fr',
567 'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
568 'iw_local' => 1 ),
569 array( 'iw_prefix' => 'ru',
570 'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
571 'iw_local' => 1 ),
572 ) );
573
574 # Hack: Insert an image to work with
575 $db->insert( 'image', array(
576 'img_name' => 'Foobar.jpg',
577 'img_size' => 12345,
578 'img_description' => 'Some lame file',
579 'img_user' => 1,
580 'img_user_text' => 'WikiSysop',
581 'img_timestamp' => $db->timestamp( '20010115123500' ),
582 'img_width' => 1941,
583 'img_height' => 220,
584 'img_bits' => 24,
585 'img_media_type' => MEDIATYPE_BITMAP,
586 'img_major_mime' => "image",
587 'img_minor_mime' => "jpeg",
588 'img_metadata' => serialize( array() ),
589 ) );
590
591 # Update certain things in site_stats
592 $db->insert( 'site_stats', array( 'ss_row_id' => 1, 'ss_images' => 1, 'ss_good_articles' => 1 ) );
593 }
594
595 /**
596 * Change the table prefix on all open DB connections/
597 */
598 protected function changePrefix( $prefix ) {
599 global $wgDBprefix;
600 wfGetLBFactory()->forEachLB( array( $this, 'changeLBPrefix' ), array( $prefix ) );
601 $wgDBprefix = $prefix;
602 }
603
604 public function changeLBPrefix( $lb, $prefix ) {
605 $lb->forEachOpenConnection( array( $this, 'changeDBPrefix' ), array( $prefix ) );
606 }
607
608 public function changeDBPrefix( $db, $prefix ) {
609 $db->tablePrefix( $prefix );
610 }
611
612 private function teardownDatabase() {
613 global $wgDBprefix;
614 if ( !$this->databaseSetupDone ) {
615 return;
616 }
617 $this->changePrefix( $this->oldTablePrefix );
618 $this->databaseSetupDone = false;
619 if ( $this->useTemporaryTables ) {
620 # Don't need to do anything
621 return;
622 }
623
624 $tables = $this->listTables();
625 $db = wfGetDB( DB_MASTER );
626 foreach ( $tables as $table ) {
627 $db->query( "DROP TABLE `parsertest_$table`" );
628 }
629 }
630
631 /**
632 * Create a dummy uploads directory which will contain a couple
633 * of files in order to pass existence tests.
634 * @return string The directory
635 */
636 private function setupUploadDir() {
637 global $IP;
638 if ( $this->keepUploads ) {
639 $dir = wfTempDir() . '/mwParser-images';
640 if ( is_dir( $dir ) ) {
641 return $dir;
642 }
643 } else {
644 $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
645 }
646
647 wfDebug( "Creating upload directory $dir\n" );
648 mkdir( $dir );
649 mkdir( $dir . '/3' );
650 mkdir( $dir . '/3/3a' );
651 copy( "$IP/skins/monobook/headbg.jpg", "$dir/3/3a/Foobar.jpg" );
652 return $dir;
653 }
654
655 /**
656 * Restore default values and perform any necessary clean-up
657 * after each test runs.
658 */
659 private function teardownGlobals() {
660 RepoGroup::destroySingleton();
661 foreach( $this->savedGlobals as $var => $val ) {
662 $GLOBALS[$var] = $val;
663 }
664 if( isset( $this->uploadDir ) ) {
665 $this->teardownUploadDir( $this->uploadDir );
666 unset( $this->uploadDir );
667 }
668 }
669
670 /**
671 * Remove the dummy uploads directory
672 */
673 private function teardownUploadDir( $dir ) {
674 if ( $this->keepUploads ) {
675 return;
676 }
677
678 // delete the files first, then the dirs.
679 self::deleteFiles(
680 array (
681 "$dir/3/3a/Foobar.jpg",
682 "$dir/thumb/3/3a/Foobar.jpg/180px-Foobar.jpg",
683 "$dir/thumb/3/3a/Foobar.jpg/200px-Foobar.jpg",
684 "$dir/thumb/3/3a/Foobar.jpg/640px-Foobar.jpg",
685 "$dir/thumb/3/3a/Foobar.jpg/120px-Foobar.jpg",
686 )
687 );
688
689 self::deleteDirs(
690 array (
691 "$dir/3/3a",
692 "$dir/3",
693 "$dir/thumb/6/65",
694 "$dir/thumb/6",
695 "$dir/thumb/3/3a/Foobar.jpg",
696 "$dir/thumb/3/3a",
697 "$dir/thumb/3",
698 "$dir/thumb",
699 "$dir",
700 )
701 );
702 }
703
704 /**
705 * Delete the specified files, if they exist.
706 * @param array $files full paths to files to delete.
707 */
708 private static function deleteFiles( $files ) {
709 foreach( $files as $file ) {
710 if( file_exists( $file ) ) {
711 unlink( $file );
712 }
713 }
714 }
715
716 /**
717 * Delete the specified directories, if they exist. Must be empty.
718 * @param array $dirs full paths to directories to delete.
719 */
720 private static function deleteDirs( $dirs ) {
721 foreach( $dirs as $dir ) {
722 if( is_dir( $dir ) ) {
723 rmdir( $dir );
724 }
725 }
726 }
727
728 /**
729 * "Running test $desc..."
730 */
731 protected function showTesting( $desc ) {
732 print "Running test $desc... ";
733 }
734
735 /**
736 * Print a happy success message.
737 *
738 * @param string $desc The test name
739 * @return bool
740 */
741 protected function showSuccess( $desc ) {
742 if( $this->showProgress ) {
743 print $this->term->color( '1;32' ) . 'PASSED' . $this->term->reset() . "\n";
744 }
745 return true;
746 }
747
748 /**
749 * Print a failure message and provide some explanatory output
750 * about what went wrong if so configured.
751 *
752 * @param string $desc The test name
753 * @param string $result Expected HTML output
754 * @param string $html Actual HTML output
755 * @return bool
756 */
757 protected function showFailure( $desc, $result, $html ) {
758 if( $this->showFailure ) {
759 if( !$this->showProgress ) {
760 # In quiet mode we didn't show the 'Testing' message before the
761 # test, in case it succeeded. Show it now:
762 $this->showTesting( $desc );
763 }
764 print $this->term->color( '31' ) . 'FAILED!' . $this->term->reset() . "\n";
765 if ( $this->showOutput ) {
766 print "--- Expected ---\n$result\n--- Actual ---\n$html\n";
767 }
768 if( $this->showDiffs ) {
769 print $this->quickDiff( $result, $html );
770 if( !$this->wellFormed( $html ) ) {
771 print "XML error: $this->mXmlError\n";
772 }
773 }
774 }
775 return false;
776 }
777
778 /**
779 * Run given strings through a diff and return the (colorized) output.
780 * Requires writable /tmp directory and a 'diff' command in the PATH.
781 *
782 * @param string $input
783 * @param string $output
784 * @param string $inFileTail Tailing for the input file name
785 * @param string $outFileTail Tailing for the output file name
786 * @return string
787 */
788 protected function quickDiff( $input, $output, $inFileTail='expected', $outFileTail='actual' ) {
789 $prefix = wfTempDir() . "/mwParser-" . mt_rand();
790
791 $infile = "$prefix-$inFileTail";
792 $this->dumpToFile( $input, $infile );
793
794 $outfile = "$prefix-$outFileTail";
795 $this->dumpToFile( $output, $outfile );
796
797 $diff = `diff -au $infile $outfile`;
798 unlink( $infile );
799 unlink( $outfile );
800
801 return $this->colorDiff( $diff );
802 }
803
804 /**
805 * Write the given string to a file, adding a final newline.
806 *
807 * @param string $data
808 * @param string $filename
809 */
810 private function dumpToFile( $data, $filename ) {
811 $file = fopen( $filename, "wt" );
812 fwrite( $file, $data . "\n" );
813 fclose( $file );
814 }
815
816 /**
817 * Colorize unified diff output if set for ANSI color output.
818 * Subtractions are colored blue, additions red.
819 *
820 * @param string $text
821 * @return string
822 */
823 protected function colorDiff( $text ) {
824 return preg_replace(
825 array( '/^(-.*)$/m', '/^(\+.*)$/m' ),
826 array( $this->term->color( 34 ) . '$1' . $this->term->reset(),
827 $this->term->color( 31 ) . '$1' . $this->term->reset() ),
828 $text );
829 }
830
831 /**
832 * Show "Reading tests from ..."
833 *
834 * @param String $path
835 */
836 protected function showRunFile( $path ){
837 print $this->term->color( 1 ) .
838 "Reading tests from \"$path\"..." .
839 $this->term->reset() .
840 "\n";
841 }
842
843 /**
844 * Insert a temporary test article
845 * @param string $name the title, including any prefix
846 * @param string $text the article text
847 * @param int $line the input line number, for reporting errors
848 */
849 private function addArticle($name, $text, $line) {
850 $this->setupGlobals();
851 $title = Title::newFromText( $name );
852 if ( is_null($title) ) {
853 wfDie( "invalid title at line $line\n" );
854 }
855
856 $aid = $title->getArticleID( GAID_FOR_UPDATE );
857 if ($aid != 0) {
858 wfDie( "duplicate article at line $line\n" );
859 }
860
861 $art = new Article($title);
862 $art->insertNewArticle($text, '', false, false );
863 $this->teardownGlobals();
864 }
865
866 /**
867 * Steal a callback function from the primary parser, save it for
868 * application to our scary parser. If the hook is not installed,
869 * die a painful dead to warn the others.
870 * @param string $name
871 */
872 private function requireHook( $name ) {
873 global $wgParser;
874 if( isset( $wgParser->mTagHooks[$name] ) ) {
875 $this->hooks[$name] = $wgParser->mTagHooks[$name];
876 } else {
877 wfDie( "This test suite requires the '$name' hook extension.\n" );
878 }
879 }
880
881 /**
882 * Steal a callback function from the primary parser, save it for
883 * application to our scary parser. If the hook is not installed,
884 * die a painful dead to warn the others.
885 * @param string $name
886 */
887 private function requireFunctionHook( $name ) {
888 global $wgParser;
889 if( isset( $wgParser->mFunctionHooks[$name] ) ) {
890 $this->functionHooks[$name] = $wgParser->mFunctionHooks[$name];
891 } else {
892 wfDie( "This test suite requires the '$name' function hook extension.\n" );
893 }
894 }
895
896 /*
897 * Run the "tidy" command on text if the $wgUseTidy
898 * global is true
899 *
900 * @param string $text the text to tidy
901 * @return string
902 * @static
903 */
904 private function tidy( $text ) {
905 global $wgUseTidy;
906 if ($wgUseTidy) {
907 $text = Parser::tidy($text);
908 }
909 return $text;
910 }
911
912 private function wellFormed( $text ) {
913 $html =
914 Sanitizer::hackDocType() .
915 '<html>' .
916 $text .
917 '</html>';
918
919 $parser = xml_parser_create( "UTF-8" );
920
921 # case folding violates XML standard, turn it off
922 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
923
924 if( !xml_parse( $parser, $html, true ) ) {
925 $err = xml_error_string( xml_get_error_code( $parser ) );
926 $position = xml_get_current_byte_index( $parser );
927 $fragment = $this->extractFragment( $html, $position );
928 $this->mXmlError = "$err at byte $position:\n$fragment";
929 xml_parser_free( $parser );
930 return false;
931 }
932 xml_parser_free( $parser );
933 return true;
934 }
935
936 private function extractFragment( $text, $position ) {
937 $start = max( 0, $position - 10 );
938 $before = $position - $start;
939 $fragment = '...' .
940 $this->term->color( 34 ) .
941 substr( $text, $start, $before ) .
942 $this->term->color( 0 ) .
943 $this->term->color( 31 ) .
944 $this->term->color( 1 ) .
945 substr( $text, $position, 1 ) .
946 $this->term->color( 0 ) .
947 $this->term->color( 34 ) .
948 substr( $text, $position + 1, 9 ) .
949 $this->term->color( 0 ) .
950 '...';
951 $display = str_replace( "\n", ' ', $fragment );
952 $caret = ' ' .
953 str_repeat( ' ', $before ) .
954 $this->term->color( 31 ) .
955 '^' .
956 $this->term->color( 0 );
957 return "$display\n$caret";
958 }
959 }
960
961 class AnsiTermColorer {
962 function __construct() {
963 }
964
965 /**
966 * Return ANSI terminal escape code for changing text attribs/color
967 *
968 * @param string $color Semicolon-separated list of attribute/color codes
969 * @return string
970 */
971 public function color( $color ) {
972 global $wgCommandLineDarkBg;
973 $light = $wgCommandLineDarkBg ? "1;" : "0;";
974 return "\x1b[{$light}{$color}m";
975 }
976
977 /**
978 * Return ANSI terminal escape code for restoring default text attributes
979 *
980 * @return string
981 */
982 public function reset() {
983 return $this->color( 0 );
984 }
985 }
986
987 /* A colour-less terminal */
988 class DummyTermColorer {
989 public function color( $color ) {
990 return '';
991 }
992
993 public function reset() {
994 return '';
995 }
996 }
997
998 class TestRecorder {
999 var $parent;
1000 var $term;
1001
1002 function __construct( $parent ) {
1003 $this->parent = $parent;
1004 $this->term = $parent->term;
1005 }
1006
1007 function start() {
1008 $this->total = 0;
1009 $this->success = 0;
1010 }
1011
1012 function record( $test, $result ) {
1013 $this->total++;
1014 $this->success += ($result ? 1 : 0);
1015 }
1016
1017 function end() {
1018 // dummy
1019 }
1020
1021 function report() {
1022 if( $this->total > 0 ) {
1023 $this->reportPercentage( $this->success, $this->total );
1024 } else {
1025 wfDie( "No tests found.\n" );
1026 }
1027 }
1028
1029 function reportPercentage( $success, $total ) {
1030 $ratio = wfPercent( 100 * $success / $total );
1031 print $this->term->color( 1 ) . "Passed $success of $total tests ($ratio)... ";
1032 if( $success == $total ) {
1033 print $this->term->color( 32 ) . "ALL TESTS PASSED!";
1034 } else {
1035 $failed = $total - $success ;
1036 print $this->term->color( 31 ) . "$failed tests failed!";
1037 }
1038 print $this->term->reset() . "\n";
1039 return ($success == $total);
1040 }
1041 }
1042
1043 class DbTestPreviewer extends TestRecorder {
1044 protected $lb; ///< Database load balancer
1045 protected $db; ///< Database connection to the main DB
1046 protected $curRun; ///< run ID number for the current run
1047 protected $prevRun; ///< run ID number for the previous run, if any
1048 protected $results; ///< Result array
1049
1050 /**
1051 * This should be called before the table prefix is changed
1052 */
1053 function __construct( $parent ) {
1054 parent::__construct( $parent );
1055 $this->lb = wfGetLBFactory()->newMainLB();
1056 // This connection will have the wiki's table prefix, not parsertest_
1057 $this->db = $this->lb->getConnection( DB_MASTER );
1058 }
1059
1060 /**
1061 * Set up result recording; insert a record for the run with the date
1062 * and all that fun stuff
1063 */
1064 function start() {
1065 global $wgDBtype, $wgDBprefix;
1066 parent::start();
1067
1068 if( ! $this->db->tableExists( 'testrun' )
1069 or ! $this->db->tableExists( 'testitem' ) )
1070 {
1071 print "WARNING> `testrun` table not found in database.\n";
1072 $this->prevRun = false;
1073 } else {
1074 // We'll make comparisons against the previous run later...
1075 $this->prevRun = $this->db->selectField( 'testrun', 'MAX(tr_id)' );
1076 }
1077 $this->results = array();
1078 }
1079
1080 function record( $test, $result ) {
1081 parent::record( $test, $result );
1082 $this->results[$test] = $result;
1083 }
1084
1085 function report() {
1086 if( $this->prevRun ) {
1087 // f = fail, p = pass, n = nonexistent
1088 // codes show before then after
1089 $table = array(
1090 'fp' => 'previously failing test(s) now PASSING! :)',
1091 'pn' => 'previously PASSING test(s) removed o_O',
1092 'np' => 'new PASSING test(s) :)',
1093
1094 'pf' => 'previously passing test(s) now FAILING! :(',
1095 'fn' => 'previously FAILING test(s) removed O_o',
1096 'nf' => 'new FAILING test(s) :(',
1097 'ff' => 'still FAILING test(s) :(',
1098 );
1099
1100 $prevResults = array();
1101
1102 $res = $this->db->select( 'testitem', array( 'ti_name', 'ti_success' ),
1103 array( 'ti_run' => $this->prevRun ), __METHOD__ );
1104 foreach ( $res as $row ) {
1105 if ( !$this->parent->regex
1106 || preg_match( "/{$this->parent->regex}/i", $row->ti_name ) )
1107 {
1108 $prevResults[$row->ti_name] = $row->ti_success;
1109 }
1110 }
1111
1112 $combined = array_keys( $this->results + $prevResults );
1113
1114 # Determine breakdown by change type
1115 $breakdown = array();
1116 foreach ( $combined as $test ) {
1117 if ( !isset( $prevResults[$test] ) ) {
1118 $before = 'n';
1119 } elseif ( $prevResults[$test] == 1 ) {
1120 $before = 'p';
1121 } else /* if ( $prevResults[$test] == 0 )*/ {
1122 $before = 'f';
1123 }
1124 if ( !isset( $this->results[$test] ) ) {
1125 $after = 'n';
1126 } elseif ( $this->results[$test] == 1 ) {
1127 $after = 'p';
1128 } else /*if ( $this->results[$test] == 0 ) */ {
1129 $after = 'f';
1130 }
1131 $code = $before . $after;
1132 if ( isset( $table[$code] ) ) {
1133 $breakdown[$code][$test] = $this->getTestStatusInfo( $test, $after );
1134 }
1135 }
1136
1137 # Write out results
1138 foreach ( $table as $code => $label ) {
1139 if( !empty( $breakdown[$code] ) ) {
1140 $count = count($breakdown[$code]);
1141 printf( "\n%4d %s\n", $count, $label );
1142 foreach ($breakdown[$code] as $differing_test_name => $statusInfo) {
1143 print " * $differing_test_name [$statusInfo]\n";
1144 }
1145 }
1146 }
1147 } else {
1148 print "No previous test runs to compare against.\n";
1149 }
1150 print "\n";
1151 parent::report();
1152 }
1153
1154 /**
1155 ** Returns a string giving information about when a test last had a status change.
1156 ** Could help to track down when regressions were introduced, as distinct from tests
1157 ** which have never passed (which are more change requests than regressions).
1158 */
1159 private function getTestStatusInfo($testname, $after) {
1160
1161 // If we're looking at a test that has just been removed, then say when it first appeared.
1162 if ( $after == 'n' ) {
1163 $changedRun = $this->db->selectField ( 'testitem',
1164 'MIN(ti_run)',
1165 array( 'ti_name' => $testname ),
1166 __METHOD__ );
1167 $appear = $this->db->selectRow ( 'testrun',
1168 array( 'tr_date', 'tr_mw_version' ),
1169 array( 'tr_id' => $changedRun ),
1170 __METHOD__ );
1171 return "First recorded appearance: "
1172 . date( "d-M-Y H:i:s", strtotime ( $appear->tr_date ) )
1173 . ", " . $appear->tr_mw_version;
1174 }
1175
1176 // Otherwise, this test has previous recorded results.
1177 // See when this test last had a different result to what we're seeing now.
1178 $conds = array(
1179 'ti_name' => $testname,
1180 'ti_success' => ($after == 'f' ? "1" : "0") );
1181 if ( $this->curRun ) {
1182 $conds[] = "ti_run != " . $this->db->addQuotes ( $this->curRun );
1183 }
1184
1185 $changedRun = $this->db->selectField ( 'testitem', 'MAX(ti_run)', $conds, __METHOD__ );
1186
1187 // If no record of ever having had a different result.
1188 if ( is_null ( $changedRun ) ) {
1189 if ($after == "f") {
1190 return "Has never passed";
1191 } else {
1192 return "Has never failed";
1193 }
1194 }
1195
1196 // Otherwise, we're looking at a test whose status has changed.
1197 // (i.e. it used to work, but now doesn't; or used to fail, but is now fixed.)
1198 // In this situation, give as much info as we can as to when it changed status.
1199 $pre = $this->db->selectRow ( 'testrun',
1200 array( 'tr_date', 'tr_mw_version' ),
1201 array( 'tr_id' => $changedRun ),
1202 __METHOD__ );
1203 $post = $this->db->selectRow ( 'testrun',
1204 array( 'tr_date', 'tr_mw_version' ),
1205 array( "tr_id > " . $this->db->addQuotes ( $changedRun) ),
1206 __METHOD__,
1207 array( "LIMIT" => 1, "ORDER BY" => 'tr_id' )
1208 );
1209
1210 if ( $post ) {
1211 $postDate = date( "d-M-Y H:i:s", strtotime ( $post->tr_date ) ) . ", {$post->tr_mw_version}";
1212 } else {
1213 $postDate = 'now';
1214 }
1215 return ( $after == "f" ? "Introduced" : "Fixed" ) . " between "
1216 . date( "d-M-Y H:i:s", strtotime ( $pre->tr_date ) ) . ", " . $pre->tr_mw_version
1217 . " and $postDate";
1218
1219 }
1220
1221 /**
1222 * Commit transaction and clean up for result recording
1223 */
1224 function end() {
1225 $this->lb->commitMasterChanges();
1226 $this->lb->closeAll();
1227 parent::end();
1228 }
1229
1230 }
1231
1232 class DbTestRecorder extends DbTestPreviewer {
1233 /**
1234 * Set up result recording; insert a record for the run with the date
1235 * and all that fun stuff
1236 */
1237 function start() {
1238 global $wgDBtype, $wgDBprefix;
1239 $this->db->begin();
1240
1241 if( ! $this->db->tableExists( 'testrun' )
1242 or ! $this->db->tableExists( 'testitem' ) )
1243 {
1244 print "WARNING> `testrun` table not found in database. Trying to create table.\n";
1245 if ($wgDBtype === 'postgres')
1246 $this->db->sourceFile( dirname(__FILE__) . '/testRunner.postgres.sql' );
1247 else
1248 $this->db->sourceFile( dirname(__FILE__) . '/testRunner.sql' );
1249 echo "OK, resuming.\n";
1250 }
1251
1252 parent::start();
1253
1254 $this->db->insert( 'testrun',
1255 array(
1256 'tr_date' => $this->db->timestamp(),
1257 'tr_mw_version' => SpecialVersion::getVersion(),
1258 'tr_php_version' => phpversion(),
1259 'tr_db_version' => $this->db->getServerVersion(),
1260 'tr_uname' => php_uname()
1261 ),
1262 __METHOD__ );
1263 if ($wgDBtype === 'postgres')
1264 $this->curRun = $this->db->currentSequenceValue('testrun_id_seq');
1265 else
1266 $this->curRun = $this->db->insertId();
1267 }
1268
1269 /**
1270 * Record an individual test item's success or failure to the db
1271 * @param string $test
1272 * @param bool $result
1273 */
1274 function record( $test, $result ) {
1275 parent::record( $test, $result );
1276 $this->db->insert( 'testitem',
1277 array(
1278 'ti_run' => $this->curRun,
1279 'ti_name' => $test,
1280 'ti_success' => $result ? 1 : 0,
1281 ),
1282 __METHOD__ );
1283 }
1284 }