2 # Copyright (C) 2004, 2010 Brion Vibber <brion@pobox.com>
3 # http://www.mediawiki.org/
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.
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.
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
21 * @todo Make this more independent of the configuration (and if possible the database)
24 * @ingroup Maintenance
28 * @ingroup Maintenance
32 * boolean $color whereas output should be colorized
37 * boolean $showOutput Show test output
42 * boolean $useTemporaryTables Use temporary tables for the temporary database
44 private $useTemporaryTables = true;
47 * boolean $databaseSetupDone True if the database has been set up
49 private $databaseSetupDone = false;
52 * string $oldTablePrefix Original table prefix
54 private $oldTablePrefix;
56 private $maxFuzzTestLength = 300;
57 private $fuzzSeed = 0;
58 private $memoryLimit = 50;
61 * Sets terminal colorization and diff/quick modes depending on OS and
62 * command-line options (--color and --quick).
64 public function ParserTest() {
67 # Only colorize output if stdout is a terminal.
68 $this->color = !wfIsWindows() && posix_isatty( 1 );
70 if ( isset( $options['color'] ) ) {
71 switch( $options['color'] ) {
81 $this->term = $this->color
82 ? new AnsiTermColorer()
83 : new DummyTermColorer();
85 $this->showDiffs = !isset( $options['quick'] );
86 $this->showProgress = !isset( $options['quiet'] );
87 $this->showFailure = !(
88 isset( $options['quiet'] )
89 && ( isset( $options['record'] )
90 || isset( $options['compare'] ) ) ); // redundant output
92 $this->showOutput = isset( $options['show-output'] );
95 if ( isset( $options['regex'] ) ) {
96 if ( isset( $options['record'] ) ) {
97 echo "Warning: --record cannot be used with --regex, disabling --record\n";
98 unset( $options['record'] );
100 $this->regex = $options['regex'];
106 $this->setupRecorder();
107 $this->keepUploads = isset( $options['keep-uploads'] );
109 if ( isset( $options['seed'] ) ) {
110 $this->fuzzSeed = intval( $options['seed'] ) - 1;
113 $this->runDisabled = isset( $options['run-disabled'] );
115 $this->hooks = array();
116 $this->functionHooks = array();
119 public function setupRecorder() {
121 if ( isset( $options['record'] ) ) {
122 $this->recorder = new DbTestRecorder( $this );
123 } elseif ( isset( $options['compare'] ) ) {
124 $this->recorder = new DbTestPreviewer( $this );
125 } elseif ( isset( $options['upload'] ) ) {
126 $this->recorder = new RemoteTestRecorder( $this );
128 $this->recorder = new TestRecorder( $this );
133 * Remove last character if it is a newline
135 public function chomp( $s ) {
136 if ( substr( $s, -1 ) === "\n" ) {
137 return substr( $s, 0, -1 );
145 * Run a fuzz test series
146 * Draw input from a set of test files
148 function fuzzTest( $filenames ) {
149 $dict = $this->getFuzzInput( $filenames );
150 $dictSize = strlen( $dict );
151 $logMaxLength = log( $this->maxFuzzTestLength );
152 $this->setupDatabase();
153 ini_set( 'memory_limit', $this->memoryLimit * 1048576 );
158 $opts = ParserOptions::newFromUser( $user );
159 $title = Title::makeTitle( NS_MAIN, 'Parser_test' );
162 // Generate test input
163 mt_srand( ++$this->fuzzSeed );
164 $totalLength = mt_rand( 1, $this->maxFuzzTestLength );
166 while ( strlen( $input ) < $totalLength ) {
167 $logHairLength = mt_rand( 0, 1000000 ) / 1000000 * $logMaxLength;
168 $hairLength = min( intval( exp( $logHairLength ) ), $dictSize );
169 $offset = mt_rand( 0, $dictSize - $hairLength );
170 $input .= substr( $dict, $offset, $hairLength );
173 $this->setupGlobals();
174 $parser = $this->getParser();
177 $parser->parse( $input, $title, $opts );
179 } catch ( Exception $exception ) {
184 echo "Test failed with seed {$this->fuzzSeed}\n";
193 $this->teardownGlobals();
194 $parser->__destruct();
196 if ( $numTotal % 100 == 0 ) {
197 $usage = intval( memory_get_usage( true ) / $this->memoryLimit / 1048576 * 100 );
198 echo "{$this->fuzzSeed}: $numSuccess/$numTotal (mem: $usage%)\n";
200 echo "Out of memory:\n";
201 $memStats = $this->getMemoryBreakdown();
202 foreach ( $memStats as $name => $usage ) {
203 echo "$name: $usage\n";
212 * Get an input dictionary from a set of parser test files
214 function getFuzzInput( $filenames ) {
216 foreach ( $filenames as $filename ) {
217 $contents = file_get_contents( $filename );
218 preg_match_all( '/!!\s*input\n(.*?)\n!!\s*result/s', $contents, $matches );
219 foreach ( $matches[1] as $match ) {
220 $dict .= $match . "\n";
227 * Get a memory usage breakdown
229 function getMemoryBreakdown() {
231 foreach ( $GLOBALS as $name => $value ) {
232 $memStats['$' . $name] = strlen( serialize( $value ) );
234 $classes = get_declared_classes();
235 foreach ( $classes as $class ) {
236 $rc = new ReflectionClass( $class );
237 $props = $rc->getStaticProperties();
238 $memStats[$class] = strlen( serialize( $props ) );
239 $methods = $rc->getMethods();
240 foreach ( $methods as $method ) {
241 $memStats[$class] += strlen( serialize( $method->getStaticVariables() ) );
244 $functions = get_defined_functions();
245 foreach ( $functions['user'] as $function ) {
246 $rf = new ReflectionFunction( $function );
247 $memStats["$function()"] = strlen( serialize( $rf->getStaticVariables() ) );
258 * Run a series of tests listed in the given text files.
259 * Each test consists of a brief description, wikitext input,
260 * and the expected HTML output.
262 * Prints status updates on stdout and counts up the total
263 * number and percentage of passed tests.
265 * @param $filenames Array of strings
266 * @return Boolean: true if passed all tests, false if any tests failed.
268 public function runTestsFromFiles( $filenames ) {
269 $this->recorder->start();
270 $this->setupDatabase();
272 foreach ( $filenames as $filename ) {
273 $tests = new TestFileIterator( $filename, $this );
274 $ok = $this->runTests( $tests ) && $ok;
276 $this->teardownDatabase();
277 $this->recorder->report();
278 $this->recorder->end();
282 function runTests( $tests ) {
284 foreach ( $tests as $i => $t ) {
286 $this->runTest( $t['test'], $t['input'], $t['result'], $t['options'], $t['config'] );
287 $ok = $ok && $result;
288 $this->recorder->record( $t['test'], $result );
290 if ( $this->showProgress ) {
297 * Get a Parser object
299 function getParser( $preprocessor = null ) {
300 global $wgParserConf;
301 $class = $wgParserConf['class'];
302 $parser = new $class( array( 'preprocessorClass' => $preprocessor ) + $wgParserConf );
303 foreach ( $this->hooks as $tag => $callback ) {
304 $parser->setHook( $tag, $callback );
306 foreach ( $this->functionHooks as $tag => $bits ) {
307 list( $callback, $flags ) = $bits;
308 $parser->setFunctionHook( $tag, $callback, $flags );
310 wfRunHooks( 'ParserTestParser', array( &$parser ) );
315 * Run a given wikitext input through a freshly-constructed wiki parser,
316 * and compare the output against the expected results.
317 * Prints status and explanatory messages to stdout.
319 * @param $desc String: test's description
320 * @param $input String: wikitext to try rendering
321 * @param $result String: result to output
322 * @param $opts Array: test's options
323 * @param $config String: overrides for global variables, one per line
326 public function runTest( $desc, $input, $result, $opts, $config ) {
327 if ( $this->showProgress ) {
328 $this->showTesting( $desc );
331 $opts = $this->parseOptions( $opts );
332 $this->setupGlobals( $opts, $config );
335 $options = ParserOptions::newFromUser( $user );
338 if ( isset( $opts['title'] ) ) {
339 $titleText = $opts['title'];
342 $titleText = 'Parser test';
345 $noxml = isset( $opts['noxml'] );
346 $local = isset( $opts['local'] );
347 $preprocessor = isset( $opts['preprocessor'] ) ? $opts['preprocessor'] : null;
348 $parser = $this->getParser( $preprocessor );
349 $title = Title::newFromText( $titleText );
352 if ( isset( $opts['pst'] ) ) {
353 $out = $parser->preSaveTransform( $input, $title, $user, $options );
354 } elseif ( isset( $opts['msg'] ) ) {
355 $out = $parser->transformMsg( $input, $options );
356 } elseif ( isset( $opts['section'] ) ) {
357 $section = $opts['section'];
358 $out = $parser->getSection( $input, $section );
359 } elseif ( isset( $opts['replace'] ) ) {
360 $section = $opts['replace'][0];
361 $replace = $opts['replace'][1];
362 $out = $parser->replaceSection( $input, $section, $replace );
363 } elseif ( isset( $opts['comment'] ) ) {
364 $linker = $user->getSkin();
365 $out = $linker->formatComment( $input, $title, $local );
366 } elseif ( isset( $opts['preload'] ) ) {
367 $out = $parser->getpreloadText( $input, $title, $options );
369 $output = $parser->parse( $input, $title, $options, true, true, 1337 );
370 $out = $output->getText();
372 if ( isset( $opts['showtitle'] ) ) {
373 if ( $output->getTitleText() ) $title = $output->getTitleText();
374 $out = "$title\n$out";
376 if ( isset( $opts['ill'] ) ) {
377 $out = $this->tidy( implode( ' ', $output->getLanguageLinks() ) );
378 } elseif ( isset( $opts['cat'] ) ) {
380 $wgOut->addCategoryLinks( $output->getCategories() );
381 $cats = $wgOut->getCategoryLinks();
382 if ( isset( $cats['normal'] ) ) {
383 $out = $this->tidy( implode( ' ', $cats['normal'] ) );
389 $result = $this->tidy( $result );
393 $this->teardownGlobals();
395 if ( $result === $out && ( $noxml === true || $this->wellFormed( $out ) ) ) {
396 return $this->showSuccess( $desc );
398 return $this->showFailure( $desc, $result, $out );
404 * Use a regex to find out the value of an option
405 * @param $key String: name of option val to retrieve
406 * @param $opts Options array to look in
407 * @param $default Mixed: default value returned if not found
409 private static function getOptionValue( $key, $opts, $default ) {
410 $key = strtolower( $key );
411 if ( isset( $opts[$key] ) ) {
418 private function parseOptions( $instring ) {
420 $lines = explode( "\n", $instring );
425 // foo=bar,"baz quux"
449 \[\[[^]]*\]\] # Link target
457 if ( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER ) ) {
458 foreach ( $matches as $bits ) {
459 $match = array_shift( $bits );
460 $key = strtolower( array_shift( $bits ) );
461 if ( count( $bits ) == 0 ) {
463 } elseif ( count( $bits ) == 1 ) {
464 $opts[$key] = $this->cleanupOption( array_shift( $bits ) );
467 $opts[$key] = array_map( array( $this, 'cleanupOption' ), $bits );
474 private function cleanupOption( $opt ) {
475 if ( substr( $opt, 0, 1 ) == '"' ) {
476 return substr( $opt, 1, -1 );
478 if ( substr( $opt, 0, 2 ) == '[[' ) {
479 return substr( $opt, 2, -2 );
485 * Set up the global variables for a consistent environment for each test.
486 * Ideally this should replace the global configuration entirely.
488 private function setupGlobals( $opts = '', $config = '' ) {
490 if ( !isset( $this->uploadDir ) ) {
491 $this->uploadDir = $this->setupUploadDir();
494 # Find out values for some special options.
496 self::getOptionValue( 'language', $opts, 'en' );
498 self::getOptionValue( 'variant', $opts, false );
500 self::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
501 $linkHolderBatchSize =
502 self::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
505 'wgServer' => 'http://localhost',
506 'wgScript' => '/index.php',
507 'wgScriptPath' => '/',
508 'wgArticlePath' => '/wiki/$1',
509 'wgActionPaths' => array(),
510 'wgLocalFileRepo' => array(
511 'class' => 'LocalRepo',
513 'directory' => $this->uploadDir,
514 'url' => 'http://example.com/images',
516 'transformVia404' => false,
518 'wgEnableUploads' => true,
519 'wgStyleSheetPath' => '/skins',
520 'wgSitename' => 'MediaWiki',
521 'wgServerName' => 'Britney-Spears',
522 'wgLanguageCode' => $lang,
523 'wgContLanguageCode' => $lang,
524 'wgDBprefix' => $wgDBtype != 'oracle' ? 'parsertest_' : 'pt_',
525 'wgRawHtml' => isset( $opts['rawhtml'] ),
527 'wgContLang' => null,
528 'wgNamespacesWithSubpages' => array( 0 => isset( $opts['subpage'] ) ),
529 'wgMaxTocLevel' => $maxtoclevel,
530 'wgCapitalLinks' => true,
531 'wgNoFollowLinks' => true,
532 'wgNoFollowDomainExceptions' => array(),
533 'wgThumbnailScriptPath' => false,
534 'wgUseImageResize' => false,
535 'wgUseTeX' => isset( $opts['math'] ),
536 'wgMathDirectory' => $this->uploadDir . '/math',
537 'wgLocaltimezone' => 'UTC',
538 'wgAllowExternalImages' => true,
539 'wgUseTidy' => false,
540 'wgDefaultLanguageVariant' => $variant,
541 'wgVariantArticlePath' => false,
542 'wgGroupPermissions' => array( '*' => array(
543 'createaccount' => true,
546 'createpage' => true,
547 'createtalk' => true,
549 'wgNamespaceProtection' => array( NS_MEDIAWIKI => 'editinterface' ),
550 'wgDefaultExternalStore' => array(),
551 'wgForeignFileRepos' => array(),
552 'wgLinkHolderBatchSize' => $linkHolderBatchSize,
553 'wgExperimentalHtmlIds' => false,
554 'wgExternalLinkTarget' => false,
555 'wgAlwaysUseTidy' => false,
557 'wgWellFormedXml' => true,
558 'wgAllowMicrodataAttributes' => true,
562 $configLines = explode( "\n", $config );
564 foreach ( $configLines as $line ) {
565 list( $var, $value ) = explode( '=', $line, 2 );
567 $settings[$var] = eval( "return $value;" );
571 $this->savedGlobals = array();
572 foreach ( $settings as $var => $val ) {
573 if ( array_key_exists( $var, $GLOBALS ) ) {
574 $this->savedGlobals[$var] = $GLOBALS[$var];
576 $GLOBALS[$var] = $val;
578 $langObj = Language::factory( $lang );
579 $GLOBALS['wgLang'] = $langObj;
580 $GLOBALS['wgContLang'] = $langObj;
581 $GLOBALS['wgMemc'] = new FakeMemCachedClient;
582 $GLOBALS['wgOut'] = new OutputPage;
585 $wgHooks['ParserTestParser'][] = 'ParserTestParserHook::setup';
586 $wgHooks['ParserTestParser'][] = 'ParserTestStaticParserHook::setup';
587 $wgHooks['ParserGetVariableValueTs'][] = 'ParserTest::getFakeTimestamp';
589 MagicWord::clearCache();
592 $wgUser = new User();
596 * List of temporary tables to create, without prefix.
597 * Some of these probably aren't necessary.
599 private function listTables() {
601 $tables = array( 'user', 'page', 'page_restrictions',
602 'protected_titles', 'revision', 'text', 'pagelinks', 'imagelinks',
603 'categorylinks', 'templatelinks', 'externallinks', 'langlinks', 'iwlinks',
604 'site_stats', 'hitcounter', 'ipblocks', 'image', 'oldimage',
605 'recentchanges', 'watchlist', 'math', 'interwiki',
606 'querycache', 'objectcache', 'job', 'l10n_cache', 'redirect', 'querycachetwo',
607 'archive', 'user_groups', 'page_props', 'category',
610 if ( $wgDBtype === 'mysql' )
611 array_push( $tables, 'searchindex' );
613 // Allow extensions to add to the list of tables to duplicate;
614 // may be necessary if they hook into page save or other code
615 // which will require them while running tests.
616 wfRunHooks( 'ParserTestTables', array( &$tables ) );
622 * Set up a temporary set of wiki tables to work with for the tests.
623 * Currently this will only be done once per run, and any changes to
624 * the db will be visible to later tests in the run.
626 public function setupDatabase() {
627 global $wgDBprefix, $wgDBtype;
628 if ( $this->databaseSetupDone ) {
631 if ( $wgDBprefix === 'parsertest_' || ( $wgDBtype == 'oracle' && $wgDBprefix === 'pt_' ) ) {
632 throw new MWException( 'setupDatabase should be called before setupGlobals' );
634 $this->databaseSetupDone = true;
635 $this->oldTablePrefix = $wgDBprefix;
637 # SqlBagOStuff broke when using temporary tables on r40209 (bug 15892).
638 # It seems to have been fixed since (r55079?).
639 # If it fails, $wgCaches[CACHE_DB] = new HashBagOStuff(); should work around it.
641 # CREATE TEMPORARY TABLE breaks if there is more than one server
642 if ( wfGetLB()->getServerCount() != 1 ) {
643 $this->useTemporaryTables = false;
646 $temporary = $this->useTemporaryTables || $wgDBtype == 'postgres';
648 $db = wfGetDB( DB_MASTER );
649 $tables = $this->listTables();
651 foreach ( $tables as $tbl ) {
652 # Clean up from previous aborted run. So that table escaping
653 # works correctly across DB engines, we need to change the pre-
654 # fix back and forth so tableName() works right.
655 $this->changePrefix( $this->oldTablePrefix );
656 $oldTableName = $db->tableName( $tbl );
657 $this->changePrefix( $wgDBtype != 'oracle' ? 'parsertest_' : 'pt_' );
658 $newTableName = $db->tableName( $tbl );
660 if ( $db->tableExists( $tbl ) && $wgDBtype != 'postgres' && $wgDBtype != 'oracle' ) {
661 $db->query( "DROP TABLE $newTableName" );
664 $db->duplicateTableStructure( $oldTableName, $newTableName, $temporary );
666 if ( $wgDBtype == 'oracle' )
667 $db->query( 'BEGIN FILL_WIKI_INFO; END;' );
669 $this->changePrefix( $wgDBtype != 'oracle' ? 'parsertest_' : 'pt_' );
671 # Hack: insert a few Wikipedia in-project interwiki prefixes,
672 # for testing inter-language links
673 $db->insert( 'interwiki', array(
674 array( 'iw_prefix' => 'wikipedia',
675 'iw_url' => 'http://en.wikipedia.org/wiki/$1',
677 array( 'iw_prefix' => 'meatball',
678 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
680 array( 'iw_prefix' => 'zh',
681 'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
683 array( 'iw_prefix' => 'es',
684 'iw_url' => 'http://es.wikipedia.org/wiki/$1',
686 array( 'iw_prefix' => 'fr',
687 'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
689 array( 'iw_prefix' => 'ru',
690 'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
695 if ( $wgDBtype == 'oracle' ) {
696 # Insert 0 and 1 user_ids to prevent FK violations
699 $db->insert( 'user', array(
701 'user_name' => 'Anonymous' ) );
703 # Hack-on-Hack: Insert a test user to be able to insert an image
704 $db->insert( 'user', array(
706 'user_name' => 'Tester' ) );
709 # Hack: Insert an image to work with
710 $db->insert( 'image', array(
711 'img_name' => 'Foobar.jpg',
713 'img_description' => 'Some lame file',
715 'img_user_text' => 'WikiSysop',
716 'img_timestamp' => $db->timestamp( '20010115123500' ),
720 'img_media_type' => MEDIATYPE_BITMAP,
721 'img_major_mime' => "image",
722 'img_minor_mime' => "jpeg",
723 'img_metadata' => serialize( array() ),
726 # This image will be blacklisted in [[MediaWiki:Bad image list]]
727 $db->insert( 'image', array(
728 'img_name' => 'Bad.jpg',
730 'img_description' => 'zomgnotcensored',
732 'img_user_text' => 'WikiSysop',
733 'img_timestamp' => $db->timestamp( '20010115123500' ),
737 'img_media_type' => MEDIATYPE_BITMAP,
738 'img_major_mime' => "image",
739 'img_minor_mime' => "jpeg",
740 'img_metadata' => serialize( array() ),
743 # Update certain things in site_stats
744 $db->insert( 'site_stats', array( 'ss_row_id' => 1, 'ss_images' => 2, 'ss_good_articles' => 1 ) );
746 # Reinitialise the LocalisationCache to match the database state
747 Language::getLocalisationCache()->unloadAll();
749 # Make a new message cache
750 global $wgMessageCache, $wgMemc;
751 $wgMessageCache = new MessageCache( $wgMemc, true, 3600, '' );
755 * Change the table prefix on all open DB connections/
757 protected function changePrefix( $prefix ) {
759 wfGetLBFactory()->forEachLB( array( $this, 'changeLBPrefix' ), array( $prefix ) );
760 $wgDBprefix = $prefix;
763 public function changeLBPrefix( $lb, $prefix ) {
764 $lb->forEachOpenConnection( array( $this, 'changeDBPrefix' ), array( $prefix ) );
767 public function changeDBPrefix( $db, $prefix ) {
768 $db->tablePrefix( $prefix );
771 public function teardownDatabase() {
773 if ( !$this->databaseSetupDone ) {
776 $this->changePrefix( $this->oldTablePrefix );
777 $this->databaseSetupDone = false;
778 if ( $this->useTemporaryTables ) {
779 # Don't need to do anything
783 $tables = $this->listTables();
784 $db = wfGetDB( DB_MASTER );
785 foreach ( $tables as $table ) {
786 $sql = $wgDBtype == 'oracle' ? "DROP TABLE pt_$table DROP CONSTRAINTS" : "DROP TABLE `parsertest_$table`";
789 if ($wgDBtype == 'oracle')
790 $db->query('BEGIN FILL_WIKI_INFO; END;');
794 * Create a dummy uploads directory which will contain a couple
795 * of files in order to pass existence tests.
797 * @return String: the directory
799 private function setupUploadDir() {
801 if ( $this->keepUploads ) {
802 $dir = wfTempDir() . '/mwParser-images';
803 if ( is_dir( $dir ) ) {
807 $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
810 wfDebug( "Creating upload directory $dir\n" );
811 if ( file_exists( $dir ) ) {
812 wfDebug( "Already exists!\n" );
815 wfMkdirParents( $dir . '/3/3a' );
816 copy( "$IP/skins/monobook/headbg.jpg", "$dir/3/3a/Foobar.jpg" );
818 wfMkdirParents( $dir . '/0/09' );
819 copy( "$IP/skins/monobook/headbg.jpg", "$dir/0/09/Bad.jpg" );
824 * Restore default values and perform any necessary clean-up
825 * after each test runs.
827 private function teardownGlobals() {
828 RepoGroup::destroySingleton();
829 LinkCache::singleton()->clear();
830 foreach ( $this->savedGlobals as $var => $val ) {
831 $GLOBALS[$var] = $val;
833 if ( isset( $this->uploadDir ) ) {
834 $this->teardownUploadDir( $this->uploadDir );
835 unset( $this->uploadDir );
840 * Remove the dummy uploads directory
842 private function teardownUploadDir( $dir ) {
843 if ( $this->keepUploads ) {
847 // delete the files first, then the dirs.
850 "$dir/3/3a/Foobar.jpg",
851 "$dir/thumb/3/3a/Foobar.jpg/180px-Foobar.jpg",
852 "$dir/thumb/3/3a/Foobar.jpg/200px-Foobar.jpg",
853 "$dir/thumb/3/3a/Foobar.jpg/640px-Foobar.jpg",
854 "$dir/thumb/3/3a/Foobar.jpg/120px-Foobar.jpg",
858 "$dir/math/f/a/5/fa50b8b616463173474302ca3e63586b.png",
868 "$dir/thumb/3/3a/Foobar.jpg",
885 * Delete the specified files, if they exist.
886 * @param $files Array: full paths to files to delete.
888 private static function deleteFiles( $files ) {
889 foreach ( $files as $file ) {
890 if ( file_exists( $file ) ) {
897 * Delete the specified directories, if they exist. Must be empty.
898 * @param $dirs Array: full paths to directories to delete.
900 private static function deleteDirs( $dirs ) {
901 foreach ( $dirs as $dir ) {
902 if ( is_dir( $dir ) ) {
909 * "Running test $desc..."
911 protected function showTesting( $desc ) {
912 print "Running test $desc... ";
916 * Print a happy success message.
918 * @param $desc String: the test name
921 protected function showSuccess( $desc ) {
922 if ( $this->showProgress ) {
923 print $this->term->color( '1;32' ) . 'PASSED' . $this->term->reset() . "\n";
929 * Print a failure message and provide some explanatory output
930 * about what went wrong if so configured.
932 * @param $desc String: the test name
933 * @param $result String: expected HTML output
934 * @param $html String: actual HTML output
937 protected function showFailure( $desc, $result, $html ) {
938 if ( $this->showFailure ) {
939 if ( !$this->showProgress ) {
940 # In quiet mode we didn't show the 'Testing' message before the
941 # test, in case it succeeded. Show it now:
942 $this->showTesting( $desc );
944 print $this->term->color( '31' ) . 'FAILED!' . $this->term->reset() . "\n";
945 if ( $this->showOutput ) {
946 print "--- Expected ---\n$result\n--- Actual ---\n$html\n";
948 if ( $this->showDiffs ) {
949 print $this->quickDiff( $result, $html );
950 if ( !$this->wellFormed( $html ) ) {
951 print "XML error: $this->mXmlError\n";
959 * Run given strings through a diff and return the (colorized) output.
960 * Requires writable /tmp directory and a 'diff' command in the PATH.
962 * @param $input String
963 * @param $output String
964 * @param $inFileTail String: tailing for the input file name
965 * @param $outFileTail String: tailing for the output file name
968 protected function quickDiff( $input, $output, $inFileTail = 'expected', $outFileTail = 'actual' ) {
969 $prefix = wfTempDir() . "/mwParser-" . mt_rand();
971 $infile = "$prefix-$inFileTail";
972 $this->dumpToFile( $input, $infile );
974 $outfile = "$prefix-$outFileTail";
975 $this->dumpToFile( $output, $outfile );
977 $diff = `diff -au $infile $outfile`;
981 return $this->colorDiff( $diff );
985 * Write the given string to a file, adding a final newline.
987 * @param $data String
988 * @param $filename String
990 private function dumpToFile( $data, $filename ) {
991 $file = fopen( $filename, "wt" );
992 fwrite( $file, $data . "\n" );
997 * Colorize unified diff output if set for ANSI color output.
998 * Subtractions are colored blue, additions red.
1000 * @param $text String
1003 protected function colorDiff( $text ) {
1004 return preg_replace(
1005 array( '/^(-.*)$/m', '/^(\+.*)$/m' ),
1006 array( $this->term->color( 34 ) . '$1' . $this->term->reset(),
1007 $this->term->color( 31 ) . '$1' . $this->term->reset() ),
1012 * Show "Reading tests from ..."
1014 * @param $path String
1016 public function showRunFile( $path ) {
1017 print $this->term->color( 1 ) .
1018 "Reading tests from \"$path\"..." .
1019 $this->term->reset() .
1024 * Insert a temporary test article
1025 * @param $name String: the title, including any prefix
1026 * @param $text String: the article text
1027 * @param $line Integer: the input line number, for reporting errors
1029 public function addArticle( $name, $text, $line ) {
1030 $this->setupGlobals();
1031 $title = Title::newFromText( $name );
1032 if ( is_null( $title ) ) {
1033 wfDie( "invalid title at line $line\n" );
1036 $aid = $title->getArticleID( GAID_FOR_UPDATE );
1038 wfDie( "duplicate article '$name' at line $line\n" );
1041 $art = new Article( $title );
1042 $art->doEdit( $text, '', EDIT_NEW | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY,
1043 false, null, false, false, '', true );
1045 $this->teardownGlobals();
1049 * Steal a callback function from the primary parser, save it for
1050 * application to our scary parser. If the hook is not installed,
1051 * abort processing of this file.
1053 * @param $name String
1054 * @return Bool true if tag hook is present
1056 public function requireHook( $name ) {
1058 $wgParser->firstCallInit( ); // make sure hooks are loaded.
1059 if ( isset( $wgParser->mTagHooks[$name] ) ) {
1060 $this->hooks[$name] = $wgParser->mTagHooks[$name];
1062 echo " This test suite requires the '$name' hook extension, skipping.\n";
1069 * Steal a callback function from the primary parser, save it for
1070 * application to our scary parser. If the hook is not installed,
1071 * abort processing of this file.
1073 * @param $name String
1074 * @return Bool true if function hook is present
1076 public function requireFunctionHook( $name ) {
1078 $wgParser->firstCallInit( ); // make sure hooks are loaded.
1079 if ( isset( $wgParser->mFunctionHooks[$name] ) ) {
1080 $this->functionHooks[$name] = $wgParser->mFunctionHooks[$name];
1082 echo " This test suite requires the '$name' function hook extension, skipping.\n";
1089 * Run the "tidy" command on text if the $wgUseTidy
1092 * @param $text String: the text to tidy
1096 private function tidy( $text ) {
1099 $text = Parser::tidy( $text );
1104 private function wellFormed( $text ) {
1106 Sanitizer::hackDocType() .
1111 $parser = xml_parser_create( "UTF-8" );
1113 # case folding violates XML standard, turn it off
1114 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
1116 if ( !xml_parse( $parser, $html, true ) ) {
1117 $err = xml_error_string( xml_get_error_code( $parser ) );
1118 $position = xml_get_current_byte_index( $parser );
1119 $fragment = $this->extractFragment( $html, $position );
1120 $this->mXmlError = "$err at byte $position:\n$fragment";
1121 xml_parser_free( $parser );
1124 xml_parser_free( $parser );
1128 private function extractFragment( $text, $position ) {
1129 $start = max( 0, $position - 10 );
1130 $before = $position - $start;
1132 $this->term->color( 34 ) .
1133 substr( $text, $start, $before ) .
1134 $this->term->color( 0 ) .
1135 $this->term->color( 31 ) .
1136 $this->term->color( 1 ) .
1137 substr( $text, $position, 1 ) .
1138 $this->term->color( 0 ) .
1139 $this->term->color( 34 ) .
1140 substr( $text, $position + 1, 9 ) .
1141 $this->term->color( 0 ) .
1143 $display = str_replace( "\n", ' ', $fragment );
1145 str_repeat( ' ', $before ) .
1146 $this->term->color( 31 ) .
1148 $this->term->color( 0 );
1149 return "$display\n$caret";
1152 static function getFakeTimestamp( &$parser, &$ts ) {
1158 class AnsiTermColorer {
1159 function __construct() {
1163 * Return ANSI terminal escape code for changing text attribs/color
1165 * @param $color String: semicolon-separated list of attribute/color codes
1168 public function color( $color ) {
1169 global $wgCommandLineDarkBg;
1170 $light = $wgCommandLineDarkBg ? "1;" : "0;";
1171 return "\x1b[{$light}{$color}m";
1175 * Return ANSI terminal escape code for restoring default text attributes
1179 public function reset() {
1180 return $this->color( 0 );
1184 /* A colour-less terminal */
1185 class DummyTermColorer {
1186 public function color( $color ) {
1190 public function reset() {
1195 class TestRecorder {
1199 function __construct( $parent ) {
1200 $this->parent = $parent;
1201 $this->term = $parent->term;
1209 function record( $test, $result ) {
1211 $this->success += ( $result ? 1 : 0 );
1219 if ( $this->total > 0 ) {
1220 $this->reportPercentage( $this->success, $this->total );
1222 wfDie( "No tests found.\n" );
1226 function reportPercentage( $success, $total ) {
1227 $ratio = wfPercent( 100 * $success / $total );
1228 print $this->term->color( 1 ) . "Passed $success of $total tests ($ratio)... ";
1229 if ( $success == $total ) {
1230 print $this->term->color( 32 ) . "ALL TESTS PASSED!";
1232 $failed = $total - $success ;
1233 print $this->term->color( 31 ) . "$failed tests failed!";
1235 print $this->term->reset() . "\n";
1236 return ( $success == $total );
1240 class DbTestPreviewer extends TestRecorder {
1241 protected $lb; // /< Database load balancer
1242 protected $db; // /< Database connection to the main DB
1243 protected $curRun; // /< run ID number for the current run
1244 protected $prevRun; // /< run ID number for the previous run, if any
1245 protected $results; // /< Result array
1248 * This should be called before the table prefix is changed
1250 function __construct( $parent ) {
1251 parent::__construct( $parent );
1252 $this->lb = wfGetLBFactory()->newMainLB();
1253 // This connection will have the wiki's table prefix, not parsertest_
1254 $this->db = $this->lb->getConnection( DB_MASTER );
1258 * Set up result recording; insert a record for the run with the date
1259 * and all that fun stuff
1264 if ( ! $this->db->tableExists( 'testrun' )
1265 or ! $this->db->tableExists( 'testitem' ) )
1267 print "WARNING> `testrun` table not found in database.\n";
1268 $this->prevRun = false;
1270 // We'll make comparisons against the previous run later...
1271 $this->prevRun = $this->db->selectField( 'testrun', 'MAX(tr_id)' );
1273 $this->results = array();
1276 function record( $test, $result ) {
1277 parent::record( $test, $result );
1278 $this->results[$test] = $result;
1282 if ( $this->prevRun ) {
1283 // f = fail, p = pass, n = nonexistent
1284 // codes show before then after
1286 'fp' => 'previously failing test(s) now PASSING! :)',
1287 'pn' => 'previously PASSING test(s) removed o_O',
1288 'np' => 'new PASSING test(s) :)',
1290 'pf' => 'previously passing test(s) now FAILING! :(',
1291 'fn' => 'previously FAILING test(s) removed O_o',
1292 'nf' => 'new FAILING test(s) :(',
1293 'ff' => 'still FAILING test(s) :(',
1296 $prevResults = array();
1298 $res = $this->db->select( 'testitem', array( 'ti_name', 'ti_success' ),
1299 array( 'ti_run' => $this->prevRun ), __METHOD__ );
1300 foreach ( $res as $row ) {
1301 if ( !$this->parent->regex
1302 || preg_match( "/{$this->parent->regex}/i", $row->ti_name ) )
1304 $prevResults[$row->ti_name] = $row->ti_success;
1308 $combined = array_keys( $this->results + $prevResults );
1310 # Determine breakdown by change type
1311 $breakdown = array();
1312 foreach ( $combined as $test ) {
1313 if ( !isset( $prevResults[$test] ) ) {
1315 } elseif ( $prevResults[$test] == 1 ) {
1317 } else /* if ( $prevResults[$test] == 0 )*/ {
1320 if ( !isset( $this->results[$test] ) ) {
1322 } elseif ( $this->results[$test] == 1 ) {
1324 } else /*if ( $this->results[$test] == 0 ) */ {
1327 $code = $before . $after;
1328 if ( isset( $table[$code] ) ) {
1329 $breakdown[$code][$test] = $this->getTestStatusInfo( $test, $after );
1334 foreach ( $table as $code => $label ) {
1335 if ( !empty( $breakdown[$code] ) ) {
1336 $count = count( $breakdown[$code] );
1337 printf( "\n%4d %s\n", $count, $label );
1338 foreach ( $breakdown[$code] as $differing_test_name => $statusInfo ) {
1339 print " * $differing_test_name [$statusInfo]\n";
1344 print "No previous test runs to compare against.\n";
1351 ** Returns a string giving information about when a test last had a status change.
1352 ** Could help to track down when regressions were introduced, as distinct from tests
1353 ** which have never passed (which are more change requests than regressions).
1355 private function getTestStatusInfo( $testname, $after ) {
1357 // If we're looking at a test that has just been removed, then say when it first appeared.
1358 if ( $after == 'n' ) {
1359 $changedRun = $this->db->selectField ( 'testitem',
1361 array( 'ti_name' => $testname ),
1363 $appear = $this->db->selectRow ( 'testrun',
1364 array( 'tr_date', 'tr_mw_version' ),
1365 array( 'tr_id' => $changedRun ),
1367 return "First recorded appearance: "
1368 . date( "d-M-Y H:i:s", strtotime ( $appear->tr_date ) )
1369 . ", " . $appear->tr_mw_version;
1372 // Otherwise, this test has previous recorded results.
1373 // See when this test last had a different result to what we're seeing now.
1375 'ti_name' => $testname,
1376 'ti_success' => ( $after == 'f' ? "1" : "0" ) );
1377 if ( $this->curRun ) {
1378 $conds[] = "ti_run != " . $this->db->addQuotes ( $this->curRun );
1381 $changedRun = $this->db->selectField ( 'testitem', 'MAX(ti_run)', $conds, __METHOD__ );
1383 // If no record of ever having had a different result.
1384 if ( is_null ( $changedRun ) ) {
1385 if ( $after == "f" ) {
1386 return "Has never passed";
1388 return "Has never failed";
1392 // Otherwise, we're looking at a test whose status has changed.
1393 // (i.e. it used to work, but now doesn't; or used to fail, but is now fixed.)
1394 // In this situation, give as much info as we can as to when it changed status.
1395 $pre = $this->db->selectRow ( 'testrun',
1396 array( 'tr_date', 'tr_mw_version' ),
1397 array( 'tr_id' => $changedRun ),
1399 $post = $this->db->selectRow ( 'testrun',
1400 array( 'tr_date', 'tr_mw_version' ),
1401 array( "tr_id > " . $this->db->addQuotes ( $changedRun ) ),
1403 array( "LIMIT" => 1, "ORDER BY" => 'tr_id' )
1407 $postDate = date( "d-M-Y H:i:s", strtotime ( $post->tr_date ) ) . ", {$post->tr_mw_version}";
1411 return ( $after == "f" ? "Introduced" : "Fixed" ) . " between "
1412 . date( "d-M-Y H:i:s", strtotime ( $pre->tr_date ) ) . ", " . $pre->tr_mw_version
1418 * Commit transaction and clean up for result recording
1421 $this->lb->commitMasterChanges();
1422 $this->lb->closeAll();
1428 class DbTestRecorder extends DbTestPreviewer {
1430 * Set up result recording; insert a record for the run with the date
1431 * and all that fun stuff
1434 global $wgDBtype, $options;
1437 if ( ! $this->db->tableExists( 'testrun' )
1438 or ! $this->db->tableExists( 'testitem' ) )
1440 print "WARNING> `testrun` table not found in database. Trying to create table.\n";
1441 if ( $wgDBtype === 'postgres' )
1442 $this->db->sourceFile( dirname( __FILE__ ) . '/testRunner.postgres.sql' );
1443 elseif ( $wgDBtype === 'oracle' )
1444 $this->db->sourceFile( dirname( __FILE__ ) . '/testRunner.ora.sql' );
1446 $this->db->sourceFile( dirname( __FILE__ ) . '/testRunner.sql' );
1447 echo "OK, resuming.\n";
1452 $this->db->insert( 'testrun',
1454 'tr_date' => $this->db->timestamp(),
1455 'tr_mw_version' => isset( $options['setversion'] ) ?
1456 $options['setversion'] : SpecialVersion::getVersion(),
1457 'tr_php_version' => phpversion(),
1458 'tr_db_version' => $this->db->getServerVersion(),
1459 'tr_uname' => php_uname()
1462 if ( $wgDBtype === 'postgres' )
1463 $this->curRun = $this->db->currentSequenceValue( 'testrun_id_seq' );
1465 $this->curRun = $this->db->insertId();
1469 * Record an individual test item's success or failure to the db
1471 * @param $test String
1472 * @param $result Boolean
1474 function record( $test, $result ) {
1475 parent::record( $test, $result );
1476 $this->db->insert( 'testitem',
1478 'ti_run' => $this->curRun,
1480 'ti_success' => $result ? 1 : 0,
1486 class RemoteTestRecorder extends TestRecorder {
1489 $this->results = array();
1490 $this->ping( 'running' );
1493 function record( $test, $result ) {
1494 parent::record( $test, $result );
1495 $this->results[$test] = (bool)$result;
1499 $this->ping( 'complete', $this->results );
1504 * Inform a CodeReview instance that we've started or completed a test run...
1506 * @param $status string: "running" - tell it we've started
1507 * "complete" - provide test results array
1508 * "abort" - something went horribly awry
1509 * @param $results array of test name => true/false
1511 function ping( $status, $results = false ) {
1512 global $wgParserTestRemote, $IP;
1514 $remote = $wgParserTestRemote;
1515 $revId = SpecialVersion::getSvnRevision( $IP );
1516 $jsonResults = FormatJson::encode( $results );
1519 print "Can't do remote upload without configuring \$wgParserTestRemote!\n";
1523 // Generate a hash MAC to validate our credentials
1530 if ( $status == "complete" ) {
1531 $message[] = $jsonResults;
1533 $hmac = hash_hmac( "sha1", implode( "|", $message ), $remote['secret'] );
1536 'action' => 'codetestupload',
1538 'repo' => $remote['repo'],
1539 'suite' => $remote['suite'],
1541 'status' => $status,
1544 if ( $status == "complete" ) {
1545 $postData['results'] = $jsonResults;
1547 $response = $this->post( $remote['api-url'], $postData );
1549 if ( $response === false ) {
1550 print "CodeReview info upload failed to reach server.\n";
1553 $responseData = FormatJson::decode( $response, true );
1554 if ( !is_array( $responseData ) ) {
1555 print "CodeReview API response not recognized...\n";
1556 wfDebug( "Unrecognized CodeReview API response: $response\n" );
1559 if ( isset( $responseData['error'] ) ) {
1560 $code = $responseData['error']['code'];
1561 $info = $responseData['error']['info'];
1562 print "CodeReview info upload failed: $code $info\n";
1567 function post( $url, $data ) {
1568 return Http::post( $url, array( 'postData' => $data ) );
1572 class TestFileIterator implements Iterator {
1581 function __construct( $file, $parser = null ) {
1584 $this->file = $file;
1585 $this->fh = fopen( $this->file, "rt" );
1587 wfDie( "Couldn't open file '$file'\n" );
1590 $this->parser = $parser;
1592 if ( $this->parser ) $this->parser->showRunFile( wfRelativePath( $this->file, $IP ) );
1593 $this->lineNum = $this->index = 0;
1596 function setParser( ParserTest $parser ) {
1597 $this->parser = $parser;
1601 if ( fseek( $this->fh, 0 ) ) {
1602 wfDie( "Couldn't fseek to the start of '$this->file'\n" );
1612 function current() {
1617 return $this->index;
1621 if ( $this->readNextTest() ) {
1630 return $this->eof != true;
1633 function readNextTest() {
1637 while ( false !== ( $line = fgets( $this->fh ) ) ) {
1640 if ( preg_match( '/^!!\s*(\w+)/', $line, $matches ) ) {
1641 $section = strtolower( $matches[1] );
1642 if ( $section == 'endarticle' ) {
1643 if ( !isset( $data['text'] ) ) {
1644 wfDie( "'endarticle' without 'text' at line {$this->lineNum} of $this->file\n" );
1646 if ( !isset( $data['article'] ) ) {
1647 wfDie( "'endarticle' without 'article' at line {$this->lineNum} of $this->file\n" );
1649 if ( $this->parser ) {
1650 $this->parser->addArticle( $this->parser->chomp( $data['article'] ), $this->parser->chomp( $data['text'] ),
1657 if ( $section == 'endhooks' ) {
1658 if ( !isset( $data['hooks'] ) ) {
1659 wfDie( "'endhooks' without 'hooks' at line {$this->lineNum} of $this->file\n" );
1661 foreach ( explode( "\n", $data['hooks'] ) as $line ) {
1662 $line = trim( $line );
1664 if ( $this->parser && !$this->parser->requireHook( $line ) ) {
1673 if ( $section == 'endfunctionhooks' ) {
1674 if ( !isset( $data['functionhooks'] ) ) {
1675 wfDie( "'endfunctionhooks' without 'functionhooks' at line {$this->lineNum} of $this->file\n" );
1677 foreach ( explode( "\n", $data['functionhooks'] ) as $line ) {
1678 $line = trim( $line );
1680 if ( $this->parser && !$this->parser->requireFunctionHook( $line ) ) {
1689 if ( $section == 'end' ) {
1690 if ( !isset( $data['test'] ) ) {
1691 wfDie( "'end' without 'test' at line {$this->lineNum} of $this->file\n" );
1693 if ( !isset( $data['input'] ) ) {
1694 wfDie( "'end' without 'input' at line {$this->lineNum} of $this->file\n" );
1696 if ( !isset( $data['result'] ) ) {
1697 wfDie( "'end' without 'result' at line {$this->lineNum} of $this->file\n" );
1699 if ( !isset( $data['options'] ) ) {
1700 $data['options'] = '';
1702 if ( !isset( $data['config'] ) )
1703 $data['config'] = '';
1706 && ( ( preg_match( '/\\bdisabled\\b/i', $data['options'] ) && !$this->parser->runDisabled )
1707 || !preg_match( "/" . $this->parser->regex . "/i", $data['test'] ) ) ) {
1713 if ( $this->parser &&
1714 preg_match( '/\\bmath\\b/i', $data['options'] ) && !$this->parser->savedGlobals['wgUseTeX'] ) {
1715 # don't run math tests if $wgUseTeX is set to false in LocalSettings
1721 if ( $this->parser ) {
1722 $this->test = array(
1723 'test' => $this->parser->chomp( $data['test'] ),
1724 'input' => $this->parser->chomp( $data['input'] ),
1725 'result' => $this->parser->chomp( $data['result'] ),
1726 'options' => $this->parser->chomp( $data['options'] ),
1727 'config' => $this->parser->chomp( $data['config'] ) );
1729 $this->test['test'] = $data['test'];
1733 if ( isset ( $data[$section] ) ) {
1734 wfDie( "duplicate section '$section' at line {$this->lineNum} of $this->file\n" );
1736 $data[$section] = '';
1740 $data[$section] .= $line;