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( $options = array() ) {
65 # Only colorize output if stdout is a terminal.
66 $this->color = !wfIsWindows() && posix_isatty( 1 );
68 if ( isset( $options['color'] ) ) {
69 switch( $options['color'] ) {
79 $this->term = $this->color
80 ? new AnsiTermColorer()
81 : new DummyTermColorer();
83 $this->showDiffs = !isset( $options['quick'] );
84 $this->showProgress = !isset( $options['quiet'] );
85 $this->showFailure = !(
86 isset( $options['quiet'] )
87 && ( isset( $options['record'] )
88 || isset( $options['compare'] ) ) ); // redundant output
90 $this->showOutput = isset( $options['show-output'] );
93 if ( isset( $options['regex'] ) ) {
94 if ( isset( $options['record'] ) ) {
95 echo "Warning: --record cannot be used with --regex, disabling --record\n";
96 unset( $options['record'] );
98 $this->regex = $options['regex'];
104 $this->setupRecorder( $options );
105 $this->keepUploads = isset( $options['keep-uploads'] );
107 if ( isset( $options['seed'] ) ) {
108 $this->fuzzSeed = intval( $options['seed'] ) - 1;
111 $this->runDisabled = isset( $options['run-disabled'] );
113 $this->hooks = array();
114 $this->functionHooks = array();
117 public function setupRecorder ( $options ) {
118 if ( isset( $options['record'] ) ) {
119 $this->recorder = new DbTestRecorder( $this );
120 $this->recorder->version = isset( $options['setversion'] ) ?
121 $options['setversion'] : SpecialVersion::getVersion();
122 } elseif ( isset( $options['compare'] ) ) {
123 $this->recorder = new DbTestPreviewer( $this );
124 } elseif ( isset( $options['upload'] ) ) {
125 $this->recorder = new RemoteTestRecorder( $this );
127 $this->recorder = new TestRecorder( $this );
132 * Remove last character if it is a newline
134 public function chomp( $s ) {
135 if ( substr( $s, -1 ) === "\n" ) {
136 return substr( $s, 0, -1 );
144 * Run a fuzz test series
145 * Draw input from a set of test files
147 function fuzzTest( $filenames ) {
148 $dict = $this->getFuzzInput( $filenames );
149 $dictSize = strlen( $dict );
150 $logMaxLength = log( $this->maxFuzzTestLength );
151 $this->setupDatabase();
152 ini_set( 'memory_limit', $this->memoryLimit * 1048576 );
157 $opts = ParserOptions::newFromUser( $user );
158 $title = Title::makeTitle( NS_MAIN, 'Parser_test' );
161 // Generate test input
162 mt_srand( ++$this->fuzzSeed );
163 $totalLength = mt_rand( 1, $this->maxFuzzTestLength );
165 while ( strlen( $input ) < $totalLength ) {
166 $logHairLength = mt_rand( 0, 1000000 ) / 1000000 * $logMaxLength;
167 $hairLength = min( intval( exp( $logHairLength ) ), $dictSize );
168 $offset = mt_rand( 0, $dictSize - $hairLength );
169 $input .= substr( $dict, $offset, $hairLength );
172 $this->setupGlobals();
173 $parser = $this->getParser();
176 $parser->parse( $input, $title, $opts );
178 } catch ( Exception $exception ) {
183 echo "Test failed with seed {$this->fuzzSeed}\n";
192 $this->teardownGlobals();
193 $parser->__destruct();
195 if ( $numTotal % 100 == 0 ) {
196 $usage = intval( memory_get_usage( true ) / $this->memoryLimit / 1048576 * 100 );
197 echo "{$this->fuzzSeed}: $numSuccess/$numTotal (mem: $usage%)\n";
199 echo "Out of memory:\n";
200 $memStats = $this->getMemoryBreakdown();
201 foreach ( $memStats as $name => $usage ) {
202 echo "$name: $usage\n";
211 * Get an input dictionary from a set of parser test files
213 function getFuzzInput( $filenames ) {
215 foreach ( $filenames as $filename ) {
216 $contents = file_get_contents( $filename );
217 preg_match_all( '/!!\s*input\n(.*?)\n!!\s*result/s', $contents, $matches );
218 foreach ( $matches[1] as $match ) {
219 $dict .= $match . "\n";
226 * Get a memory usage breakdown
228 function getMemoryBreakdown() {
230 foreach ( $GLOBALS as $name => $value ) {
231 $memStats['$' . $name] = strlen( serialize( $value ) );
233 $classes = get_declared_classes();
234 foreach ( $classes as $class ) {
235 $rc = new ReflectionClass( $class );
236 $props = $rc->getStaticProperties();
237 $memStats[$class] = strlen( serialize( $props ) );
238 $methods = $rc->getMethods();
239 foreach ( $methods as $method ) {
240 $memStats[$class] += strlen( serialize( $method->getStaticVariables() ) );
243 $functions = get_defined_functions();
244 foreach ( $functions['user'] as $function ) {
245 $rf = new ReflectionFunction( $function );
246 $memStats["$function()"] = strlen( serialize( $rf->getStaticVariables() ) );
257 * Run a series of tests listed in the given text files.
258 * Each test consists of a brief description, wikitext input,
259 * and the expected HTML output.
261 * Prints status updates on stdout and counts up the total
262 * number and percentage of passed tests.
264 * @param $filenames Array of strings
265 * @return Boolean: true if passed all tests, false if any tests failed.
267 public function runTestsFromFiles( $filenames ) {
268 $this->recorder->start();
269 $this->setupDatabase();
271 foreach ( $filenames as $filename ) {
272 $tests = new TestFileIterator( $filename, $this );
273 $ok = $this->runTests( $tests ) && $ok;
275 $this->teardownDatabase();
276 $this->recorder->report();
277 $this->recorder->end();
281 function runTests( $tests ) {
283 foreach ( $tests as $i => $t ) {
285 $this->runTest( $t['test'], $t['input'], $t['result'], $t['options'], $t['config'] );
286 $ok = $ok && $result;
287 $this->recorder->record( $t['test'], $result );
289 if ( $this->showProgress ) {
296 * Get a Parser object
298 function getParser( $preprocessor = null ) {
299 global $wgParserConf;
300 $class = $wgParserConf['class'];
301 $parser = new $class( array( 'preprocessorClass' => $preprocessor ) + $wgParserConf );
302 foreach ( $this->hooks as $tag => $callback ) {
303 $parser->setHook( $tag, $callback );
305 foreach ( $this->functionHooks as $tag => $bits ) {
306 list( $callback, $flags ) = $bits;
307 $parser->setFunctionHook( $tag, $callback, $flags );
309 wfRunHooks( 'ParserTestParser', array( &$parser ) );
314 * Run a given wikitext input through a freshly-constructed wiki parser,
315 * and compare the output against the expected results.
316 * Prints status and explanatory messages to stdout.
318 * @param $desc String: test's description
319 * @param $input String: wikitext to try rendering
320 * @param $result String: result to output
321 * @param $opts Array: test's options
322 * @param $config String: overrides for global variables, one per line
325 public function runTest( $desc, $input, $result, $opts, $config ) {
326 if ( $this->showProgress ) {
327 $this->showTesting( $desc );
330 $opts = $this->parseOptions( $opts );
331 $this->setupGlobals( $opts, $config );
334 $options = ParserOptions::newFromUser( $user );
337 if ( isset( $opts['title'] ) ) {
338 $titleText = $opts['title'];
341 $titleText = 'Parser test';
344 $noxml = isset( $opts['noxml'] );
345 $local = isset( $opts['local'] );
346 $preprocessor = isset( $opts['preprocessor'] ) ? $opts['preprocessor'] : null;
347 $parser = $this->getParser( $preprocessor );
348 $title = Title::newFromText( $titleText );
351 if ( isset( $opts['pst'] ) ) {
352 $out = $parser->preSaveTransform( $input, $title, $user, $options );
353 } elseif ( isset( $opts['msg'] ) ) {
354 $out = $parser->transformMsg( $input, $options );
355 } elseif ( isset( $opts['section'] ) ) {
356 $section = $opts['section'];
357 $out = $parser->getSection( $input, $section );
358 } elseif ( isset( $opts['replace'] ) ) {
359 $section = $opts['replace'][0];
360 $replace = $opts['replace'][1];
361 $out = $parser->replaceSection( $input, $section, $replace );
362 } elseif ( isset( $opts['comment'] ) ) {
363 $linker = $user->getSkin();
364 $out = $linker->formatComment( $input, $title, $local );
365 } elseif ( isset( $opts['preload'] ) ) {
366 $out = $parser->getpreloadText( $input, $title, $options );
368 $output = $parser->parse( $input, $title, $options, true, true, 1337 );
369 $out = $output->getText();
371 if ( isset( $opts['showtitle'] ) ) {
372 if ( $output->getTitleText() ) $title = $output->getTitleText();
373 $out = "$title\n$out";
375 if ( isset( $opts['ill'] ) ) {
376 $out = $this->tidy( implode( ' ', $output->getLanguageLinks() ) );
377 } elseif ( isset( $opts['cat'] ) ) {
379 $wgOut->addCategoryLinks( $output->getCategories() );
380 $cats = $wgOut->getCategoryLinks();
381 if ( isset( $cats['normal'] ) ) {
382 $out = $this->tidy( implode( ' ', $cats['normal'] ) );
388 $result = $this->tidy( $result );
392 $this->teardownGlobals();
394 if ( $result === $out && ( $noxml === true || $this->wellFormed( $out ) ) ) {
395 return $this->showSuccess( $desc );
397 return $this->showFailure( $desc, $result, $out );
403 * Use a regex to find out the value of an option
404 * @param $key String: name of option val to retrieve
405 * @param $opts Options array to look in
406 * @param $default Mixed: default value returned if not found
408 private static function getOptionValue( $key, $opts, $default ) {
409 $key = strtolower( $key );
410 if ( isset( $opts[$key] ) ) {
417 private function parseOptions( $instring ) {
419 $lines = explode( "\n", $instring );
424 // foo=bar,"baz quux"
448 \[\[[^]]*\]\] # Link target
456 if ( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER ) ) {
457 foreach ( $matches as $bits ) {
458 $match = array_shift( $bits );
459 $key = strtolower( array_shift( $bits ) );
460 if ( count( $bits ) == 0 ) {
462 } elseif ( count( $bits ) == 1 ) {
463 $opts[$key] = $this->cleanupOption( array_shift( $bits ) );
466 $opts[$key] = array_map( array( $this, 'cleanupOption' ), $bits );
473 private function cleanupOption( $opt ) {
474 if ( substr( $opt, 0, 1 ) == '"' ) {
475 return substr( $opt, 1, -1 );
477 if ( substr( $opt, 0, 2 ) == '[[' ) {
478 return substr( $opt, 2, -2 );
484 * Set up the global variables for a consistent environment for each test.
485 * Ideally this should replace the global configuration entirely.
487 private function setupGlobals( $opts = '', $config = '' ) {
489 if ( !isset( $this->uploadDir ) ) {
490 $this->uploadDir = $this->setupUploadDir();
493 # Find out values for some special options.
495 self::getOptionValue( 'language', $opts, 'en' );
497 self::getOptionValue( 'variant', $opts, false );
499 self::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
500 $linkHolderBatchSize =
501 self::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
504 'wgServer' => 'http://localhost',
505 'wgScript' => '/index.php',
506 'wgScriptPath' => '/',
507 'wgArticlePath' => '/wiki/$1',
508 'wgActionPaths' => array(),
509 'wgLocalFileRepo' => array(
510 'class' => 'LocalRepo',
512 'directory' => $this->uploadDir,
513 'url' => 'http://example.com/images',
515 'transformVia404' => false,
517 'wgEnableUploads' => true,
518 'wgStyleSheetPath' => '/skins',
519 'wgSitename' => 'MediaWiki',
520 'wgServerName' => 'Britney-Spears',
521 'wgLanguageCode' => $lang,
522 'wgContLanguageCode' => $lang,
523 'wgDBprefix' => $wgDBtype != 'oracle' ? 'parsertest_' : 'pt_',
524 'wgRawHtml' => isset( $opts['rawhtml'] ),
526 'wgContLang' => null,
527 'wgNamespacesWithSubpages' => array( 0 => isset( $opts['subpage'] ) ),
528 'wgMaxTocLevel' => $maxtoclevel,
529 'wgCapitalLinks' => true,
530 'wgNoFollowLinks' => true,
531 'wgNoFollowDomainExceptions' => array(),
532 'wgThumbnailScriptPath' => false,
533 'wgUseImageResize' => false,
534 'wgUseTeX' => isset( $opts['math'] ),
535 'wgMathDirectory' => $this->uploadDir . '/math',
536 'wgLocaltimezone' => 'UTC',
537 'wgAllowExternalImages' => true,
538 'wgUseTidy' => false,
539 'wgDefaultLanguageVariant' => $variant,
540 'wgVariantArticlePath' => false,
541 'wgGroupPermissions' => array( '*' => array(
542 'createaccount' => true,
545 'createpage' => true,
546 'createtalk' => true,
548 'wgNamespaceProtection' => array( NS_MEDIAWIKI => 'editinterface' ),
549 'wgDefaultExternalStore' => array(),
550 'wgForeignFileRepos' => array(),
551 'wgLinkHolderBatchSize' => $linkHolderBatchSize,
552 'wgExperimentalHtmlIds' => false,
553 'wgExternalLinkTarget' => false,
554 'wgAlwaysUseTidy' => false,
556 'wgWellFormedXml' => true,
557 'wgAllowMicrodataAttributes' => true,
561 $configLines = explode( "\n", $config );
563 foreach ( $configLines as $line ) {
564 list( $var, $value ) = explode( '=', $line, 2 );
566 $settings[$var] = eval( "return $value;" );
570 $this->savedGlobals = array();
571 foreach ( $settings as $var => $val ) {
572 if ( array_key_exists( $var, $GLOBALS ) ) {
573 $this->savedGlobals[$var] = $GLOBALS[$var];
575 $GLOBALS[$var] = $val;
577 $langObj = Language::factory( $lang );
578 $GLOBALS['wgLang'] = $langObj;
579 $GLOBALS['wgContLang'] = $langObj;
580 $GLOBALS['wgMemc'] = new FakeMemCachedClient;
581 $GLOBALS['wgOut'] = new OutputPage;
584 $wgHooks['ParserTestParser'][] = 'ParserTestParserHook::setup';
585 $wgHooks['ParserTestParser'][] = 'ParserTestStaticParserHook::setup';
586 $wgHooks['ParserGetVariableValueTs'][] = 'ParserTest::getFakeTimestamp';
588 MagicWord::clearCache();
591 $wgUser = new User();
595 * List of temporary tables to create, without prefix.
596 * Some of these probably aren't necessary.
598 private function listTables() {
600 $tables = array( 'user', 'page', 'page_restrictions',
601 'protected_titles', 'revision', 'text', 'pagelinks', 'imagelinks',
602 'categorylinks', 'templatelinks', 'externallinks', 'langlinks', 'iwlinks',
603 'site_stats', 'hitcounter', 'ipblocks', 'image', 'oldimage',
604 'recentchanges', 'watchlist', 'math', 'interwiki',
605 'querycache', 'objectcache', 'job', 'l10n_cache', 'redirect', 'querycachetwo',
606 'archive', 'user_groups', 'page_props', 'category',
609 if ( $wgDBtype === 'mysql' )
610 array_push( $tables, 'searchindex' );
612 // Allow extensions to add to the list of tables to duplicate;
613 // may be necessary if they hook into page save or other code
614 // which will require them while running tests.
615 wfRunHooks( 'ParserTestTables', array( &$tables ) );
621 * Set up a temporary set of wiki tables to work with for the tests.
622 * Currently this will only be done once per run, and any changes to
623 * the db will be visible to later tests in the run.
625 public function setupDatabase() {
626 global $wgDBprefix, $wgDBtype;
627 if ( $this->databaseSetupDone ) {
630 if ( $wgDBprefix === 'parsertest_' || ( $wgDBtype == 'oracle' && $wgDBprefix === 'pt_' ) ) {
631 throw new MWException( 'setupDatabase should be called before setupGlobals' );
633 $this->databaseSetupDone = true;
634 $this->oldTablePrefix = $wgDBprefix;
636 # SqlBagOStuff broke when using temporary tables on r40209 (bug 15892).
637 # It seems to have been fixed since (r55079?).
638 # If it fails, $wgCaches[CACHE_DB] = new HashBagOStuff(); should work around it.
640 # CREATE TEMPORARY TABLE breaks if there is more than one server
641 if ( wfGetLB()->getServerCount() != 1 ) {
642 $this->useTemporaryTables = false;
645 $temporary = $this->useTemporaryTables || $wgDBtype == 'postgres';
647 $db = wfGetDB( DB_MASTER );
648 $tables = $this->listTables();
650 foreach ( $tables as $tbl ) {
651 # Clean up from previous aborted run. So that table escaping
652 # works correctly across DB engines, we need to change the pre-
653 # fix back and forth so tableName() works right.
654 $this->changePrefix( $this->oldTablePrefix );
655 $oldTableName = $db->tableName( $tbl );
656 $this->changePrefix( $wgDBtype != 'oracle' ? 'parsertest_' : 'pt_' );
657 $newTableName = $db->tableName( $tbl );
659 if ( $db->tableExists( $tbl ) && $wgDBtype != 'postgres' && $wgDBtype != 'oracle' ) {
660 $db->query( "DROP TABLE $newTableName" );
663 $db->duplicateTableStructure( $oldTableName, $newTableName, $temporary );
665 if ( $wgDBtype == 'oracle' )
666 $db->query( 'BEGIN FILL_WIKI_INFO; END;' );
668 $this->changePrefix( $wgDBtype != 'oracle' ? 'parsertest_' : 'pt_' );
670 # Hack: insert a few Wikipedia in-project interwiki prefixes,
671 # for testing inter-language links
672 $db->insert( 'interwiki', array(
673 array( 'iw_prefix' => 'wikipedia',
674 'iw_url' => 'http://en.wikipedia.org/wiki/$1',
678 array( 'iw_prefix' => 'meatball',
679 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
683 array( 'iw_prefix' => 'zh',
684 'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
688 array( 'iw_prefix' => 'es',
689 'iw_url' => 'http://es.wikipedia.org/wiki/$1',
693 array( 'iw_prefix' => 'fr',
694 'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
698 array( 'iw_prefix' => 'ru',
699 'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
706 if ( $wgDBtype == 'oracle' ) {
707 # Insert 0 and 1 user_ids to prevent FK violations
710 $db->insert( 'user', array(
712 'user_name' => 'Anonymous' ) );
714 # Hack-on-Hack: Insert a test user to be able to insert an image
715 $db->insert( 'user', array(
717 'user_name' => 'Tester' ) );
720 # Hack: Insert an image to work with
721 $db->insert( 'image', array(
722 'img_name' => 'Foobar.jpg',
724 'img_description' => 'Some lame file',
726 'img_user_text' => 'WikiSysop',
727 'img_timestamp' => $db->timestamp( '20010115123500' ),
731 'img_media_type' => MEDIATYPE_BITMAP,
732 'img_major_mime' => "image",
733 'img_minor_mime' => "jpeg",
734 'img_metadata' => serialize( array() ),
737 # This image will be blacklisted in [[MediaWiki:Bad image list]]
738 $db->insert( 'image', array(
739 'img_name' => 'Bad.jpg',
741 'img_description' => 'zomgnotcensored',
743 'img_user_text' => 'WikiSysop',
744 'img_timestamp' => $db->timestamp( '20010115123500' ),
748 'img_media_type' => MEDIATYPE_BITMAP,
749 'img_major_mime' => "image",
750 'img_minor_mime' => "jpeg",
751 'img_metadata' => serialize( array() ),
754 # Update certain things in site_stats
755 $db->insert( 'site_stats', array( 'ss_row_id' => 1, 'ss_images' => 2, 'ss_good_articles' => 1 ) );
757 # Reinitialise the LocalisationCache to match the database state
758 Language::getLocalisationCache()->unloadAll();
760 # Make a new message cache
761 global $wgMessageCache, $wgMemc;
762 $wgMessageCache = new MessageCache( $wgMemc, true, 3600, '' );
766 * Change the table prefix on all open DB connections/
768 protected function changePrefix( $prefix ) {
770 wfGetLBFactory()->forEachLB( array( $this, 'changeLBPrefix' ), array( $prefix ) );
771 $wgDBprefix = $prefix;
774 public function changeLBPrefix( $lb, $prefix ) {
775 $lb->forEachOpenConnection( array( $this, 'changeDBPrefix' ), array( $prefix ) );
778 public function changeDBPrefix( $db, $prefix ) {
779 $db->tablePrefix( $prefix );
782 public function teardownDatabase() {
784 if ( !$this->databaseSetupDone ) {
787 $this->changePrefix( $this->oldTablePrefix );
788 $this->databaseSetupDone = false;
789 if ( $this->useTemporaryTables ) {
790 # Don't need to do anything
794 $tables = $this->listTables();
795 $db = wfGetDB( DB_MASTER );
796 foreach ( $tables as $table ) {
797 $sql = $wgDBtype == 'oracle' ? "DROP TABLE pt_$table DROP CONSTRAINTS" : "DROP TABLE `parsertest_$table`";
800 if ($wgDBtype == 'oracle')
801 $db->query('BEGIN FILL_WIKI_INFO; END;');
805 * Create a dummy uploads directory which will contain a couple
806 * of files in order to pass existence tests.
808 * @return String: the directory
810 private function setupUploadDir() {
812 if ( $this->keepUploads ) {
813 $dir = wfTempDir() . '/mwParser-images';
814 if ( is_dir( $dir ) ) {
818 $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
821 wfDebug( "Creating upload directory $dir\n" );
822 if ( file_exists( $dir ) ) {
823 wfDebug( "Already exists!\n" );
826 wfMkdirParents( $dir . '/3/3a' );
827 copy( "$IP/skins/monobook/headbg.jpg", "$dir/3/3a/Foobar.jpg" );
829 wfMkdirParents( $dir . '/0/09' );
830 copy( "$IP/skins/monobook/headbg.jpg", "$dir/0/09/Bad.jpg" );
835 * Restore default values and perform any necessary clean-up
836 * after each test runs.
838 private function teardownGlobals() {
839 RepoGroup::destroySingleton();
840 LinkCache::singleton()->clear();
841 foreach ( $this->savedGlobals as $var => $val ) {
842 $GLOBALS[$var] = $val;
844 if ( isset( $this->uploadDir ) ) {
845 $this->teardownUploadDir( $this->uploadDir );
846 unset( $this->uploadDir );
851 * Remove the dummy uploads directory
853 private function teardownUploadDir( $dir ) {
854 if ( $this->keepUploads ) {
858 // delete the files first, then the dirs.
861 "$dir/3/3a/Foobar.jpg",
862 "$dir/thumb/3/3a/Foobar.jpg/180px-Foobar.jpg",
863 "$dir/thumb/3/3a/Foobar.jpg/200px-Foobar.jpg",
864 "$dir/thumb/3/3a/Foobar.jpg/640px-Foobar.jpg",
865 "$dir/thumb/3/3a/Foobar.jpg/120px-Foobar.jpg",
869 "$dir/math/f/a/5/fa50b8b616463173474302ca3e63586b.png",
879 "$dir/thumb/3/3a/Foobar.jpg",
896 * Delete the specified files, if they exist.
897 * @param $files Array: full paths to files to delete.
899 private static function deleteFiles( $files ) {
900 foreach ( $files as $file ) {
901 if ( file_exists( $file ) ) {
908 * Delete the specified directories, if they exist. Must be empty.
909 * @param $dirs Array: full paths to directories to delete.
911 private static function deleteDirs( $dirs ) {
912 foreach ( $dirs as $dir ) {
913 if ( is_dir( $dir ) ) {
920 * "Running test $desc..."
922 protected function showTesting( $desc ) {
923 print "Running test $desc... ";
927 * Print a happy success message.
929 * @param $desc String: the test name
932 protected function showSuccess( $desc ) {
933 if ( $this->showProgress ) {
934 print $this->term->color( '1;32' ) . 'PASSED' . $this->term->reset() . "\n";
940 * Print a failure message and provide some explanatory output
941 * about what went wrong if so configured.
943 * @param $desc String: the test name
944 * @param $result String: expected HTML output
945 * @param $html String: actual HTML output
948 protected function showFailure( $desc, $result, $html ) {
949 if ( $this->showFailure ) {
950 if ( !$this->showProgress ) {
951 # In quiet mode we didn't show the 'Testing' message before the
952 # test, in case it succeeded. Show it now:
953 $this->showTesting( $desc );
955 print $this->term->color( '31' ) . 'FAILED!' . $this->term->reset() . "\n";
956 if ( $this->showOutput ) {
957 print "--- Expected ---\n$result\n--- Actual ---\n$html\n";
959 if ( $this->showDiffs ) {
960 print $this->quickDiff( $result, $html );
961 if ( !$this->wellFormed( $html ) ) {
962 print "XML error: $this->mXmlError\n";
970 * Run given strings through a diff and return the (colorized) output.
971 * Requires writable /tmp directory and a 'diff' command in the PATH.
973 * @param $input String
974 * @param $output String
975 * @param $inFileTail String: tailing for the input file name
976 * @param $outFileTail String: tailing for the output file name
979 protected function quickDiff( $input, $output, $inFileTail = 'expected', $outFileTail = 'actual' ) {
980 $prefix = wfTempDir() . "/mwParser-" . mt_rand();
982 $infile = "$prefix-$inFileTail";
983 $this->dumpToFile( $input, $infile );
985 $outfile = "$prefix-$outFileTail";
986 $this->dumpToFile( $output, $outfile );
988 $diff = `diff -au $infile $outfile`;
992 return $this->colorDiff( $diff );
996 * Write the given string to a file, adding a final newline.
998 * @param $data String
999 * @param $filename String
1001 private function dumpToFile( $data, $filename ) {
1002 $file = fopen( $filename, "wt" );
1003 fwrite( $file, $data . "\n" );
1008 * Colorize unified diff output if set for ANSI color output.
1009 * Subtractions are colored blue, additions red.
1011 * @param $text String
1014 protected function colorDiff( $text ) {
1015 return preg_replace(
1016 array( '/^(-.*)$/m', '/^(\+.*)$/m' ),
1017 array( $this->term->color( 34 ) . '$1' . $this->term->reset(),
1018 $this->term->color( 31 ) . '$1' . $this->term->reset() ),
1023 * Show "Reading tests from ..."
1025 * @param $path String
1027 public function showRunFile( $path ) {
1028 print $this->term->color( 1 ) .
1029 "Reading tests from \"$path\"..." .
1030 $this->term->reset() .
1035 * Insert a temporary test article
1036 * @param $name String: the title, including any prefix
1037 * @param $text String: the article text
1038 * @param $line Integer: the input line number, for reporting errors
1040 public function addArticle( $name, $text, $line ) {
1041 $this->setupGlobals();
1042 $title = Title::newFromText( $name );
1043 if ( is_null( $title ) ) {
1044 wfDie( "invalid title at line $line\n" );
1047 $aid = $title->getArticleID( GAID_FOR_UPDATE );
1049 wfDie( "duplicate article '$name' at line $line\n" );
1052 $art = new Article( $title );
1053 $art->doEdit( $text, '', EDIT_NEW | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY,
1054 false, null, false, false, '', true );
1056 $this->teardownGlobals();
1060 * Steal a callback function from the primary parser, save it for
1061 * application to our scary parser. If the hook is not installed,
1062 * abort processing of this file.
1064 * @param $name String
1065 * @return Bool true if tag hook is present
1067 public function requireHook( $name ) {
1069 $wgParser->firstCallInit( ); // make sure hooks are loaded.
1070 if ( isset( $wgParser->mTagHooks[$name] ) ) {
1071 $this->hooks[$name] = $wgParser->mTagHooks[$name];
1073 echo " This test suite requires the '$name' hook extension, skipping.\n";
1080 * Steal a callback function from the primary parser, save it for
1081 * application to our scary parser. If the hook is not installed,
1082 * abort processing of this file.
1084 * @param $name String
1085 * @return Bool true if function hook is present
1087 public function requireFunctionHook( $name ) {
1089 $wgParser->firstCallInit( ); // make sure hooks are loaded.
1090 if ( isset( $wgParser->mFunctionHooks[$name] ) ) {
1091 $this->functionHooks[$name] = $wgParser->mFunctionHooks[$name];
1093 echo " This test suite requires the '$name' function hook extension, skipping.\n";
1100 * Run the "tidy" command on text if the $wgUseTidy
1103 * @param $text String: the text to tidy
1107 private function tidy( $text ) {
1110 $text = Parser::tidy( $text );
1115 private function wellFormed( $text ) {
1117 Sanitizer::hackDocType() .
1122 $parser = xml_parser_create( "UTF-8" );
1124 # case folding violates XML standard, turn it off
1125 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
1127 if ( !xml_parse( $parser, $html, true ) ) {
1128 $err = xml_error_string( xml_get_error_code( $parser ) );
1129 $position = xml_get_current_byte_index( $parser );
1130 $fragment = $this->extractFragment( $html, $position );
1131 $this->mXmlError = "$err at byte $position:\n$fragment";
1132 xml_parser_free( $parser );
1135 xml_parser_free( $parser );
1139 private function extractFragment( $text, $position ) {
1140 $start = max( 0, $position - 10 );
1141 $before = $position - $start;
1143 $this->term->color( 34 ) .
1144 substr( $text, $start, $before ) .
1145 $this->term->color( 0 ) .
1146 $this->term->color( 31 ) .
1147 $this->term->color( 1 ) .
1148 substr( $text, $position, 1 ) .
1149 $this->term->color( 0 ) .
1150 $this->term->color( 34 ) .
1151 substr( $text, $position + 1, 9 ) .
1152 $this->term->color( 0 ) .
1154 $display = str_replace( "\n", ' ', $fragment );
1156 str_repeat( ' ', $before ) .
1157 $this->term->color( 31 ) .
1159 $this->term->color( 0 );
1160 return "$display\n$caret";
1163 static function getFakeTimestamp( &$parser, &$ts ) {
1169 class AnsiTermColorer {
1170 function __construct() {
1174 * Return ANSI terminal escape code for changing text attribs/color
1176 * @param $color String: semicolon-separated list of attribute/color codes
1179 public function color( $color ) {
1180 global $wgCommandLineDarkBg;
1181 $light = $wgCommandLineDarkBg ? "1;" : "0;";
1182 return "\x1b[{$light}{$color}m";
1186 * Return ANSI terminal escape code for restoring default text attributes
1190 public function reset() {
1191 return $this->color( 0 );
1195 /* A colour-less terminal */
1196 class DummyTermColorer {
1197 public function color( $color ) {
1201 public function reset() {
1206 class TestRecorder {
1210 function __construct( $parent ) {
1211 $this->parent = $parent;
1212 $this->term = $parent->term;
1220 function record( $test, $result ) {
1222 $this->success += ( $result ? 1 : 0 );
1230 if ( $this->total > 0 ) {
1231 $this->reportPercentage( $this->success, $this->total );
1233 wfDie( "No tests found.\n" );
1237 function reportPercentage( $success, $total ) {
1238 $ratio = wfPercent( 100 * $success / $total );
1239 print $this->term->color( 1 ) . "Passed $success of $total tests ($ratio)... ";
1240 if ( $success == $total ) {
1241 print $this->term->color( 32 ) . "ALL TESTS PASSED!";
1243 $failed = $total - $success ;
1244 print $this->term->color( 31 ) . "$failed tests failed!";
1246 print $this->term->reset() . "\n";
1247 return ( $success == $total );
1251 class DbTestPreviewer extends TestRecorder {
1252 protected $lb; // /< Database load balancer
1253 protected $db; // /< Database connection to the main DB
1254 protected $curRun; // /< run ID number for the current run
1255 protected $prevRun; // /< run ID number for the previous run, if any
1256 protected $results; // /< Result array
1259 * This should be called before the table prefix is changed
1261 function __construct( $parent ) {
1262 parent::__construct( $parent );
1263 $this->lb = wfGetLBFactory()->newMainLB();
1264 // This connection will have the wiki's table prefix, not parsertest_
1265 $this->db = $this->lb->getConnection( DB_MASTER );
1269 * Set up result recording; insert a record for the run with the date
1270 * and all that fun stuff
1275 if ( ! $this->db->tableExists( 'testrun' )
1276 or ! $this->db->tableExists( 'testitem' ) )
1278 print "WARNING> `testrun` table not found in database.\n";
1279 $this->prevRun = false;
1281 // We'll make comparisons against the previous run later...
1282 $this->prevRun = $this->db->selectField( 'testrun', 'MAX(tr_id)' );
1284 $this->results = array();
1287 function record( $test, $result ) {
1288 parent::record( $test, $result );
1289 $this->results[$test] = $result;
1293 if ( $this->prevRun ) {
1294 // f = fail, p = pass, n = nonexistent
1295 // codes show before then after
1297 'fp' => 'previously failing test(s) now PASSING! :)',
1298 'pn' => 'previously PASSING test(s) removed o_O',
1299 'np' => 'new PASSING test(s) :)',
1301 'pf' => 'previously passing test(s) now FAILING! :(',
1302 'fn' => 'previously FAILING test(s) removed O_o',
1303 'nf' => 'new FAILING test(s) :(',
1304 'ff' => 'still FAILING test(s) :(',
1307 $prevResults = array();
1309 $res = $this->db->select( 'testitem', array( 'ti_name', 'ti_success' ),
1310 array( 'ti_run' => $this->prevRun ), __METHOD__ );
1311 foreach ( $res as $row ) {
1312 if ( !$this->parent->regex
1313 || preg_match( "/{$this->parent->regex}/i", $row->ti_name ) )
1315 $prevResults[$row->ti_name] = $row->ti_success;
1319 $combined = array_keys( $this->results + $prevResults );
1321 # Determine breakdown by change type
1322 $breakdown = array();
1323 foreach ( $combined as $test ) {
1324 if ( !isset( $prevResults[$test] ) ) {
1326 } elseif ( $prevResults[$test] == 1 ) {
1328 } else /* if ( $prevResults[$test] == 0 )*/ {
1331 if ( !isset( $this->results[$test] ) ) {
1333 } elseif ( $this->results[$test] == 1 ) {
1335 } else /*if ( $this->results[$test] == 0 ) */ {
1338 $code = $before . $after;
1339 if ( isset( $table[$code] ) ) {
1340 $breakdown[$code][$test] = $this->getTestStatusInfo( $test, $after );
1345 foreach ( $table as $code => $label ) {
1346 if ( !empty( $breakdown[$code] ) ) {
1347 $count = count( $breakdown[$code] );
1348 printf( "\n%4d %s\n", $count, $label );
1349 foreach ( $breakdown[$code] as $differing_test_name => $statusInfo ) {
1350 print " * $differing_test_name [$statusInfo]\n";
1355 print "No previous test runs to compare against.\n";
1362 ** Returns a string giving information about when a test last had a status change.
1363 ** Could help to track down when regressions were introduced, as distinct from tests
1364 ** which have never passed (which are more change requests than regressions).
1366 private function getTestStatusInfo( $testname, $after ) {
1368 // If we're looking at a test that has just been removed, then say when it first appeared.
1369 if ( $after == 'n' ) {
1370 $changedRun = $this->db->selectField ( 'testitem',
1372 array( 'ti_name' => $testname ),
1374 $appear = $this->db->selectRow ( 'testrun',
1375 array( 'tr_date', 'tr_mw_version' ),
1376 array( 'tr_id' => $changedRun ),
1378 return "First recorded appearance: "
1379 . date( "d-M-Y H:i:s", strtotime ( $appear->tr_date ) )
1380 . ", " . $appear->tr_mw_version;
1383 // Otherwise, this test has previous recorded results.
1384 // See when this test last had a different result to what we're seeing now.
1386 'ti_name' => $testname,
1387 'ti_success' => ( $after == 'f' ? "1" : "0" ) );
1388 if ( $this->curRun ) {
1389 $conds[] = "ti_run != " . $this->db->addQuotes ( $this->curRun );
1392 $changedRun = $this->db->selectField ( 'testitem', 'MAX(ti_run)', $conds, __METHOD__ );
1394 // If no record of ever having had a different result.
1395 if ( is_null ( $changedRun ) ) {
1396 if ( $after == "f" ) {
1397 return "Has never passed";
1399 return "Has never failed";
1403 // Otherwise, we're looking at a test whose status has changed.
1404 // (i.e. it used to work, but now doesn't; or used to fail, but is now fixed.)
1405 // In this situation, give as much info as we can as to when it changed status.
1406 $pre = $this->db->selectRow ( 'testrun',
1407 array( 'tr_date', 'tr_mw_version' ),
1408 array( 'tr_id' => $changedRun ),
1410 $post = $this->db->selectRow ( 'testrun',
1411 array( 'tr_date', 'tr_mw_version' ),
1412 array( "tr_id > " . $this->db->addQuotes ( $changedRun ) ),
1414 array( "LIMIT" => 1, "ORDER BY" => 'tr_id' )
1418 $postDate = date( "d-M-Y H:i:s", strtotime ( $post->tr_date ) ) . ", {$post->tr_mw_version}";
1422 return ( $after == "f" ? "Introduced" : "Fixed" ) . " between "
1423 . date( "d-M-Y H:i:s", strtotime ( $pre->tr_date ) ) . ", " . $pre->tr_mw_version
1429 * Commit transaction and clean up for result recording
1432 $this->lb->commitMasterChanges();
1433 $this->lb->closeAll();
1439 class DbTestRecorder extends DbTestPreviewer {
1443 * Set up result recording; insert a record for the run with the date
1444 * and all that fun stuff
1450 if ( ! $this->db->tableExists( 'testrun' )
1451 or ! $this->db->tableExists( 'testitem' ) )
1453 print "WARNING> `testrun` table not found in database. Trying to create table.\n";
1454 if ( $wgDBtype === 'postgres' )
1455 $this->db->sourceFile( dirname( __FILE__ ) . '/testRunner.postgres.sql' );
1456 elseif ( $wgDBtype === 'oracle' )
1457 $this->db->sourceFile( dirname( __FILE__ ) . '/testRunner.ora.sql' );
1459 $this->db->sourceFile( dirname( __FILE__ ) . '/testRunner.sql' );
1460 echo "OK, resuming.\n";
1465 $this->db->insert( 'testrun',
1467 'tr_date' => $this->db->timestamp(),
1468 'tr_mw_version' => $this->version,
1469 'tr_php_version' => phpversion(),
1470 'tr_db_version' => $this->db->getServerVersion(),
1471 'tr_uname' => php_uname()
1474 if ( $wgDBtype === 'postgres' )
1475 $this->curRun = $this->db->currentSequenceValue( 'testrun_id_seq' );
1477 $this->curRun = $this->db->insertId();
1481 * Record an individual test item's success or failure to the db
1483 * @param $test String
1484 * @param $result Boolean
1486 function record( $test, $result ) {
1487 parent::record( $test, $result );
1488 $this->db->insert( 'testitem',
1490 'ti_run' => $this->curRun,
1492 'ti_success' => $result ? 1 : 0,
1498 class RemoteTestRecorder extends TestRecorder {
1501 $this->results = array();
1502 $this->ping( 'running' );
1505 function record( $test, $result ) {
1506 parent::record( $test, $result );
1507 $this->results[$test] = (bool)$result;
1511 $this->ping( 'complete', $this->results );
1516 * Inform a CodeReview instance that we've started or completed a test run...
1518 * @param $status string: "running" - tell it we've started
1519 * "complete" - provide test results array
1520 * "abort" - something went horribly awry
1521 * @param $results array of test name => true/false
1523 function ping( $status, $results = false ) {
1524 global $wgParserTestRemote, $IP;
1526 $remote = $wgParserTestRemote;
1527 $revId = SpecialVersion::getSvnRevision( $IP );
1528 $jsonResults = FormatJson::encode( $results );
1531 print "Can't do remote upload without configuring \$wgParserTestRemote!\n";
1535 // Generate a hash MAC to validate our credentials
1542 if ( $status == "complete" ) {
1543 $message[] = $jsonResults;
1545 $hmac = hash_hmac( "sha1", implode( "|", $message ), $remote['secret'] );
1548 'action' => 'codetestupload',
1550 'repo' => $remote['repo'],
1551 'suite' => $remote['suite'],
1553 'status' => $status,
1556 if ( $status == "complete" ) {
1557 $postData['results'] = $jsonResults;
1559 $response = $this->post( $remote['api-url'], $postData );
1561 if ( $response === false ) {
1562 print "CodeReview info upload failed to reach server.\n";
1565 $responseData = FormatJson::decode( $response, true );
1566 if ( !is_array( $responseData ) ) {
1567 print "CodeReview API response not recognized...\n";
1568 wfDebug( "Unrecognized CodeReview API response: $response\n" );
1571 if ( isset( $responseData['error'] ) ) {
1572 $code = $responseData['error']['code'];
1573 $info = $responseData['error']['info'];
1574 print "CodeReview info upload failed: $code $info\n";
1579 function post( $url, $data ) {
1580 return Http::post( $url, array( 'postData' => $data ) );
1584 class TestFileIterator implements Iterator {
1593 function __construct( $file, $parser = null ) {
1596 $this->file = $file;
1597 $this->fh = fopen( $this->file, "rt" );
1599 wfDie( "Couldn't open file '$file'\n" );
1602 $this->parser = $parser;
1604 if ( $this->parser ) $this->parser->showRunFile( wfRelativePath( $this->file, $IP ) );
1605 $this->lineNum = $this->index = 0;
1608 function setParser( ParserTest $parser ) {
1609 $this->parser = $parser;
1613 if ( fseek( $this->fh, 0 ) ) {
1614 wfDie( "Couldn't fseek to the start of '$this->file'\n" );
1624 function current() {
1629 return $this->index;
1633 if ( $this->readNextTest() ) {
1642 return $this->eof != true;
1645 function readNextTest() {
1649 while ( false !== ( $line = fgets( $this->fh ) ) ) {
1652 if ( preg_match( '/^!!\s*(\w+)/', $line, $matches ) ) {
1653 $section = strtolower( $matches[1] );
1654 if ( $section == 'endarticle' ) {
1655 if ( !isset( $data['text'] ) ) {
1656 wfDie( "'endarticle' without 'text' at line {$this->lineNum} of $this->file\n" );
1658 if ( !isset( $data['article'] ) ) {
1659 wfDie( "'endarticle' without 'article' at line {$this->lineNum} of $this->file\n" );
1661 if ( $this->parser ) {
1662 $this->parser->addArticle( $this->parser->chomp( $data['article'] ), $this->parser->chomp( $data['text'] ),
1669 if ( $section == 'endhooks' ) {
1670 if ( !isset( $data['hooks'] ) ) {
1671 wfDie( "'endhooks' without 'hooks' at line {$this->lineNum} of $this->file\n" );
1673 foreach ( explode( "\n", $data['hooks'] ) as $line ) {
1674 $line = trim( $line );
1676 if ( $this->parser && !$this->parser->requireHook( $line ) ) {
1685 if ( $section == 'endfunctionhooks' ) {
1686 if ( !isset( $data['functionhooks'] ) ) {
1687 wfDie( "'endfunctionhooks' without 'functionhooks' at line {$this->lineNum} of $this->file\n" );
1689 foreach ( explode( "\n", $data['functionhooks'] ) as $line ) {
1690 $line = trim( $line );
1692 if ( $this->parser && !$this->parser->requireFunctionHook( $line ) ) {
1701 if ( $section == 'end' ) {
1702 if ( !isset( $data['test'] ) ) {
1703 wfDie( "'end' without 'test' at line {$this->lineNum} of $this->file\n" );
1705 if ( !isset( $data['input'] ) ) {
1706 wfDie( "'end' without 'input' at line {$this->lineNum} of $this->file\n" );
1708 if ( !isset( $data['result'] ) ) {
1709 wfDie( "'end' without 'result' at line {$this->lineNum} of $this->file\n" );
1711 if ( !isset( $data['options'] ) ) {
1712 $data['options'] = '';
1714 if ( !isset( $data['config'] ) )
1715 $data['config'] = '';
1718 && ( ( preg_match( '/\\bdisabled\\b/i', $data['options'] ) && !$this->parser->runDisabled )
1719 || !preg_match( "/" . $this->parser->regex . "/i", $data['test'] ) ) ) {
1725 if ( $this->parser &&
1726 preg_match( '/\\bmath\\b/i', $data['options'] ) && !$this->parser->savedGlobals['wgUseTeX'] ) {
1727 # don't run math tests if $wgUseTeX is set to false in LocalSettings
1733 if ( $this->parser ) {
1734 $this->test = array(
1735 'test' => $this->parser->chomp( $data['test'] ),
1736 'input' => $this->parser->chomp( $data['input'] ),
1737 'result' => $this->parser->chomp( $data['result'] ),
1738 'options' => $this->parser->chomp( $data['options'] ),
1739 'config' => $this->parser->chomp( $data['config'] ) );
1741 $this->test['test'] = $data['test'];
1745 if ( isset ( $data[$section] ) ) {
1746 wfDie( "duplicate section '$section' at line {$this->lineNum} of $this->file\n" );
1748 $data[$section] = '';
1752 $data[$section] .= $line;