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;
59 private $uploadDir = null;
62 private $savedGlobals = array();
64 * Sets terminal colorization and diff/quick modes depending on OS and
65 * command-line options (--color and --quick).
67 public function ParserTest( $options = array() ) {
68 # Only colorize output if stdout is a terminal.
69 $this->color = !wfIsWindows() && posix_isatty( 1 );
71 if ( isset( $options['color'] ) ) {
72 switch( $options['color'] ) {
83 $this->term = $this->color
84 ? new AnsiTermColorer()
85 : new DummyTermColorer();
87 $this->showDiffs = !isset( $options['quick'] );
88 $this->showProgress = !isset( $options['quiet'] );
89 $this->showFailure = !(
90 isset( $options['quiet'] )
91 && ( isset( $options['record'] )
92 || isset( $options['compare'] ) ) ); // redundant output
94 $this->showOutput = isset( $options['show-output'] );
97 if ( isset( $options['regex'] ) ) {
98 if ( isset( $options['record'] ) ) {
99 echo "Warning: --record cannot be used with --regex, disabling --record\n";
100 unset( $options['record'] );
102 $this->regex = $options['regex'];
108 $this->setupRecorder( $options );
109 $this->keepUploads = isset( $options['keep-uploads'] );
111 if ( isset( $options['seed'] ) ) {
112 $this->fuzzSeed = intval( $options['seed'] ) - 1;
115 $this->runDisabled = isset( $options['run-disabled'] );
117 $this->hooks = array();
118 $this->functionHooks = array();
122 static function setUp() {
123 global $wgParser, $wgParserConf, $IP, $messageMemc, $wgMemc, $wgDeferredUpdateList,
124 $wgUser, $wgLang, $wgOut, $wgRequest, $wgStyleDirectory, $wgEnableParserCache,
125 $wgMessageCache, $wgUseDatabaseMessages, $wgMsgCacheExpiry, $parserMemc,
126 $wgNamespaceAliases, $wgNamespaceProtection, $wgLocalFileRepo,
127 $wgThumbnailScriptPath, $wgScriptPath,
128 $wgArticlePath, $wgStyleSheetPath, $wgScript, $wgStylePath;
130 $wgScript = '/index.php';
132 $wgArticlePath = '/wiki/$1';
133 $wgStyleSheetPath = '/skins';
134 $wgStylePath = '/skins';
135 $wgThumbnailScriptPath = false;
136 $wgLocalFileRepo = array(
137 'class' => 'LocalRepo',
139 'directory' => wfTempDir() . '/test-repo',
140 'url' => 'http://example.com/images',
141 'deletedDir' => wfTempDir() . '/test-repo/delete',
143 'transformVia404' => false,
145 $wgNamespaceProtection[NS_MEDIAWIKI] = 'editinterface';
146 $wgNamespaceAliases['Image'] = NS_FILE;
147 $wgNamespaceAliases['Image_talk'] = NS_FILE_TALK;
150 $wgEnableParserCache = false;
151 $wgDeferredUpdateList = array();
152 $wgMemc = &wfGetMainCache();
153 $messageMemc = &wfGetMessageCacheStorage();
154 $parserMemc = &wfGetParserCacheStorage();
156 // $wgContLang = new StubContLang;
158 $wgLang = new StubUserLang;
159 $wgOut = new StubObject( 'wgOut', 'OutputPage' );
160 $wgParser = new StubObject( 'wgParser', $wgParserConf['class'], array( $wgParserConf ) );
161 $wgRequest = new WebRequest;
163 $wgMessageCache = new StubObject( 'wgMessageCache', 'MessageCache',
164 array( $messageMemc, $wgUseDatabaseMessages,
165 $wgMsgCacheExpiry ) );
166 if ( $wgStyleDirectory === false ) {
167 $wgStyleDirectory = "$IP/skins";
172 public function setupRecorder ( $options ) {
173 if ( isset( $options['record'] ) ) {
174 $this->recorder = new DbTestRecorder( $this );
175 $this->recorder->version = isset( $options['setversion'] ) ?
176 $options['setversion'] : SpecialVersion::getVersion();
177 } elseif ( isset( $options['compare'] ) ) {
178 $this->recorder = new DbTestPreviewer( $this );
179 } elseif ( isset( $options['upload'] ) ) {
180 $this->recorder = new RemoteTestRecorder( $this );
182 $this->recorder = new TestRecorder( $this );
187 * Remove last character if it is a newline
190 static public function chomp( $s ) {
191 if ( substr( $s, -1 ) === "\n" ) {
192 return substr( $s, 0, -1 );
200 * Run a fuzz test series
201 * Draw input from a set of test files
203 function fuzzTest( $filenames ) {
204 $GLOBALS['wgContLang'] = Language::factory( 'en' );
205 $dict = $this->getFuzzInput( $filenames );
206 $dictSize = strlen( $dict );
207 $logMaxLength = log( $this->maxFuzzTestLength );
208 $this->setupDatabase();
209 ini_set( 'memory_limit', $this->memoryLimit * 1048576 );
214 $opts = ParserOptions::newFromUser( $user );
215 $title = Title::makeTitle( NS_MAIN, 'Parser_test' );
218 // Generate test input
219 mt_srand( ++$this->fuzzSeed );
220 $totalLength = mt_rand( 1, $this->maxFuzzTestLength );
223 while ( strlen( $input ) < $totalLength ) {
224 $logHairLength = mt_rand( 0, 1000000 ) / 1000000 * $logMaxLength;
225 $hairLength = min( intval( exp( $logHairLength ) ), $dictSize );
226 $offset = mt_rand( 0, $dictSize - $hairLength );
227 $input .= substr( $dict, $offset, $hairLength );
230 $this->setupGlobals();
231 $parser = $this->getParser();
235 $parser->parse( $input, $title, $opts );
237 } catch ( Exception $exception ) {
242 echo "Test failed with seed {$this->fuzzSeed}\n";
252 $this->teardownGlobals();
253 $parser->__destruct();
255 if ( $numTotal % 100 == 0 ) {
256 $usage = intval( memory_get_usage( true ) / $this->memoryLimit / 1048576 * 100 );
257 echo "{$this->fuzzSeed}: $numSuccess/$numTotal (mem: $usage%)\n";
259 echo "Out of memory:\n";
260 $memStats = $this->getMemoryBreakdown();
262 foreach ( $memStats as $name => $usage ) {
263 echo "$name: $usage\n";
272 * Get an input dictionary from a set of parser test files
274 function getFuzzInput( $filenames ) {
277 foreach ( $filenames as $filename ) {
278 $contents = file_get_contents( $filename );
279 preg_match_all( '/!!\s*input\n(.*?)\n!!\s*result/s', $contents, $matches );
281 foreach ( $matches[1] as $match ) {
282 $dict .= $match . "\n";
290 * Get a memory usage breakdown
292 function getMemoryBreakdown() {
295 foreach ( $GLOBALS as $name => $value ) {
296 $memStats['$' . $name] = strlen( serialize( $value ) );
299 $classes = get_declared_classes();
301 foreach ( $classes as $class ) {
302 $rc = new ReflectionClass( $class );
303 $props = $rc->getStaticProperties();
304 $memStats[$class] = strlen( serialize( $props ) );
305 $methods = $rc->getMethods();
307 foreach ( $methods as $method ) {
308 $memStats[$class] += strlen( serialize( $method->getStaticVariables() ) );
312 $functions = get_defined_functions();
314 foreach ( $functions['user'] as $function ) {
315 $rf = new ReflectionFunction( $function );
316 $memStats["$function()"] = strlen( serialize( $rf->getStaticVariables() ) );
329 * Run a series of tests listed in the given text files.
330 * Each test consists of a brief description, wikitext input,
331 * and the expected HTML output.
333 * Prints status updates on stdout and counts up the total
334 * number and percentage of passed tests.
336 * @param $filenames Array of strings
337 * @return Boolean: true if passed all tests, false if any tests failed.
339 public function runTestsFromFiles( $filenames ) {
341 $GLOBALS['wgContLang'] = Language::factory( 'en' );
342 $this->recorder->start();
344 $this->setupDatabase();
347 foreach ( $filenames as $filename ) {
348 $tests = new TestFileIterator( $filename, $this );
349 $ok = $this->runTests( $tests ) && $ok;
352 $this->teardownDatabase();
353 $this->recorder->report();
354 } catch (DBError $e) {
355 echo $e->getMessage();
357 $this->recorder->end();
362 function runTests( $tests ) {
365 foreach ( $tests as $t ) {
367 $this->runTest( $t['test'], $t['input'], $t['result'], $t['options'], $t['config'] );
368 $ok = $ok && $result;
369 $this->recorder->record( $t['test'], $result );
372 if ( $this->showProgress ) {
380 * Get a Parser object
382 function getParser( $preprocessor = null ) {
383 global $wgParserConf;
385 $class = $wgParserConf['class'];
386 $parser = new $class( array( 'preprocessorClass' => $preprocessor ) + $wgParserConf );
388 foreach ( $this->hooks as $tag => $callback ) {
389 $parser->setHook( $tag, $callback );
392 foreach ( $this->functionHooks as $tag => $bits ) {
393 list( $callback, $flags ) = $bits;
394 $parser->setFunctionHook( $tag, $callback, $flags );
397 wfRunHooks( 'ParserTestParser', array( &$parser ) );
403 * Run a given wikitext input through a freshly-constructed wiki parser,
404 * and compare the output against the expected results.
405 * Prints status and explanatory messages to stdout.
407 * @param $desc String: test's description
408 * @param $input String: wikitext to try rendering
409 * @param $result String: result to output
410 * @param $opts Array: test's options
411 * @param $config String: overrides for global variables, one per line
414 public function runTest( $desc, $input, $result, $opts, $config ) {
415 if ( $this->showProgress ) {
416 $this->showTesting( $desc );
419 $opts = $this->parseOptions( $opts );
420 $this->setupGlobals( $opts, $config );
423 $options = ParserOptions::newFromUser( $user );
425 if ( isset( $opts['title'] ) ) {
426 $titleText = $opts['title'];
429 $titleText = 'Parser test';
432 $noxml = isset( $opts['noxml'] );
433 $local = isset( $opts['local'] );
434 $preprocessor = isset( $opts['preprocessor'] ) ? $opts['preprocessor'] : null;
435 $parser = $this->getParser( $preprocessor );
436 $title = Title::newFromText( $titleText );
438 if ( isset( $opts['pst'] ) ) {
439 $out = $parser->preSaveTransform( $input, $title, $user, $options );
440 } elseif ( isset( $opts['msg'] ) ) {
441 $out = $parser->transformMsg( $input, $options );
442 } elseif ( isset( $opts['section'] ) ) {
443 $section = $opts['section'];
444 $out = $parser->getSection( $input, $section );
445 } elseif ( isset( $opts['replace'] ) ) {
446 $section = $opts['replace'][0];
447 $replace = $opts['replace'][1];
448 $out = $parser->replaceSection( $input, $section, $replace );
449 } elseif ( isset( $opts['comment'] ) ) {
450 $linker = $user->getSkin();
451 $out = $linker->formatComment( $input, $title, $local );
452 } elseif ( isset( $opts['preload'] ) ) {
453 $out = $parser->getpreloadText( $input, $title, $options );
455 $output = $parser->parse( $input, $title, $options, true, true, 1337 );
456 $out = $output->getText();
458 if ( isset( $opts['showtitle'] ) ) {
459 if ( $output->getTitleText() ) {
460 $title = $output->getTitleText();
463 $out = "$title\n$out";
466 if ( isset( $opts['ill'] ) ) {
467 $out = $this->tidy( implode( ' ', $output->getLanguageLinks() ) );
468 } elseif ( isset( $opts['cat'] ) ) {
471 $wgOut->addCategoryLinks( $output->getCategories() );
472 $cats = $wgOut->getCategoryLinks();
474 if ( isset( $cats['normal'] ) ) {
475 $out = $this->tidy( implode( ' ', $cats['normal'] ) );
481 $result = $this->tidy( $result );
484 $this->teardownGlobals();
485 return $this->showTestResult( $desc, $result, $out );
491 function showTestResult( $desc, $result, $out ) {
492 if ( $result === $out ) {
493 $this->showSuccess( $desc );
496 $this->showFailure( $desc, $result, $out );
502 * Use a regex to find out the value of an option
503 * @param $key String: name of option val to retrieve
504 * @param $opts Options array to look in
505 * @param $default Mixed: default value returned if not found
507 private static function getOptionValue( $key, $opts, $default ) {
508 $key = strtolower( $key );
510 if ( isset( $opts[$key] ) ) {
517 private function parseOptions( $instring ) {
523 // foo=bar,"baz quux"
547 \[\[[^]]*\]\] # Link target
555 if ( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER ) ) {
556 foreach ( $matches as $bits ) {
557 array_shift( $bits );
558 $key = strtolower( array_shift( $bits ) );
559 if ( count( $bits ) == 0 ) {
561 } elseif ( count( $bits ) == 1 ) {
562 $opts[$key] = $this->cleanupOption( array_shift( $bits ) );
565 $opts[$key] = array_map( array( $this, 'cleanupOption' ), $bits );
572 private function cleanupOption( $opt ) {
573 if ( substr( $opt, 0, 1 ) == '"' ) {
574 return substr( $opt, 1, -1 );
577 if ( substr( $opt, 0, 2 ) == '[[' ) {
578 return substr( $opt, 2, -2 );
584 * Set up the global variables for a consistent environment for each test.
585 * Ideally this should replace the global configuration entirely.
587 private function setupGlobals( $opts = '', $config = '' ) {
590 # Find out values for some special options.
592 self::getOptionValue( 'language', $opts, 'en' );
594 self::getOptionValue( 'variant', $opts, false );
596 self::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
597 $linkHolderBatchSize =
598 self::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
601 'wgServer' => 'http://Britney-Spears',
602 'wgScript' => '/index.php',
603 'wgScriptPath' => '/',
604 'wgArticlePath' => '/wiki/$1',
605 'wgActionPaths' => array(),
606 'wgLocalFileRepo' => array(
607 'class' => 'LocalRepo',
609 'directory' => $this->uploadDir,
610 'url' => 'http://example.com/images',
612 'transformVia404' => false,
614 'wgEnableUploads' => self::getOptionValue( 'wgEnableUploads', $opts, true ),
615 'wgStylePath' => '/skins',
616 'wgStyleSheetPath' => '/skins',
617 'wgSitename' => 'MediaWiki',
618 'wgLanguageCode' => $lang,
619 'wgDBprefix' => $wgDBtype != 'oracle' ? 'parsertest_' : 'pt_',
620 'wgRawHtml' => isset( $opts['rawhtml'] ),
622 'wgContLang' => null,
623 'wgNamespacesWithSubpages' => array( 0 => isset( $opts['subpage'] ) ),
624 'wgMaxTocLevel' => $maxtoclevel,
625 'wgCapitalLinks' => true,
626 'wgNoFollowLinks' => true,
627 'wgNoFollowDomainExceptions' => array(),
628 'wgThumbnailScriptPath' => false,
629 'wgUseImageResize' => false,
630 'wgUseTeX' => isset( $opts['math'] ),
631 'wgMathDirectory' => $this->uploadDir . '/math',
632 'wgLocaltimezone' => 'UTC',
633 'wgAllowExternalImages' => true,
634 'wgUseTidy' => false,
635 'wgDefaultLanguageVariant' => $variant,
636 'wgVariantArticlePath' => false,
637 'wgGroupPermissions' => array( '*' => array(
638 'createaccount' => true,
641 'createpage' => true,
642 'createtalk' => true,
644 'wgNamespaceProtection' => array( NS_MEDIAWIKI => 'editinterface' ),
645 'wgDefaultExternalStore' => array(),
646 'wgForeignFileRepos' => array(),
647 'wgLinkHolderBatchSize' => $linkHolderBatchSize,
648 'wgExperimentalHtmlIds' => false,
649 'wgExternalLinkTarget' => false,
650 'wgAlwaysUseTidy' => false,
652 'wgWellFormedXml' => true,
653 'wgAllowMicrodataAttributes' => true,
657 $configLines = explode( "\n", $config );
659 foreach ( $configLines as $line ) {
660 list( $var, $value ) = explode( '=', $line, 2 );
662 $settings[$var] = eval( "return $value;" );
666 $this->savedGlobals = array();
668 foreach ( $settings as $var => $val ) {
669 if ( array_key_exists( $var, $GLOBALS ) ) {
670 $this->savedGlobals[$var] = $GLOBALS[$var];
673 $GLOBALS[$var] = $val;
676 $langObj = Language::factory( $lang );
677 $GLOBALS['wgLang'] = $langObj;
678 $GLOBALS['wgContLang'] = $langObj;
679 $GLOBALS['wgMemc'] = new FakeMemCachedClient;
680 $GLOBALS['wgOut'] = new OutputPage;
684 $wgHooks['ParserTestParser'][] = 'ParserTestParserHook::setup';
685 $wgHooks['ParserTestParser'][] = 'ParserTestStaticParserHook::setup';
686 $wgHooks['ParserGetVariableValueTs'][] = 'ParserTest::getFakeTimestamp';
688 MagicWord::clearCache();
691 $wgUser = new User();
695 * List of temporary tables to create, without prefix.
696 * Some of these probably aren't necessary.
698 private function listTables() {
701 $tables = array( 'user', 'user_properties', 'page', 'page_restrictions',
702 'protected_titles', 'revision', 'text', 'pagelinks', 'imagelinks',
703 'categorylinks', 'templatelinks', 'externallinks', 'langlinks', 'iwlinks',
704 'site_stats', 'hitcounter', 'ipblocks', 'image', 'oldimage',
705 'recentchanges', 'watchlist', 'math', 'interwiki', 'logging',
706 'querycache', 'objectcache', 'job', 'l10n_cache', 'redirect', 'querycachetwo',
707 'archive', 'user_groups', 'page_props', 'category', 'msg_resource', 'msg_resource_links'
710 if ( in_array( $wgDBtype, array( 'mysql', 'sqlite', 'oracle' ) ) )
711 array_push( $tables, 'searchindex' );
713 // Allow extensions to add to the list of tables to duplicate;
714 // may be necessary if they hook into page save or other code
715 // which will require them while running tests.
716 wfRunHooks( 'ParserTestTables', array( &$tables ) );
722 * Set up a temporary set of wiki tables to work with for the tests.
723 * Currently this will only be done once per run, and any changes to
724 * the db will be visible to later tests in the run.
726 public function setupDatabase() {
727 global $wgDBprefix, $wgDBtype;
729 if ( $this->databaseSetupDone ) {
733 if ( $wgDBprefix === 'parsertest_' || ( $wgDBtype == 'oracle' && $wgDBprefix === 'pt_' ) ) {
734 throw new MWException( 'setupDatabase should be called before setupGlobals' );
737 $this->databaseSetupDone = true;
738 $this->oldTablePrefix = $wgDBprefix;
740 # SqlBagOStuff broke when using temporary tables on r40209 (bug 15892).
741 # It seems to have been fixed since (r55079?).
742 # If it fails, $wgCaches[CACHE_DB] = new HashBagOStuff(); should work around it.
744 # CREATE TEMPORARY TABLE breaks if there is more than one server
745 if ( wfGetLB()->getServerCount() != 1 ) {
746 $this->useTemporaryTables = false;
749 $temporary = $this->useTemporaryTables || $wgDBtype == 'postgres';
751 $db = wfGetDB( DB_MASTER );
752 $tables = $this->listTables();
754 foreach ( $tables as $tbl ) {
755 # Clean up from previous aborted run. So that table escaping
756 # works correctly across DB engines, we need to change the pre-
757 # fix back and forth so tableName() works right.
758 $this->changePrefix( $this->oldTablePrefix );
759 $oldTableName = $db->tableName( $tbl );
760 $this->changePrefix( $wgDBtype != 'oracle' ? 'parsertest_' : 'pt_' );
761 $newTableName = $db->tableName( $tbl );
763 if ( $wgDBtype == 'mysql' ) {
764 $db->query( "DROP TABLE IF EXISTS $newTableName" );
765 } elseif ( in_array( $wgDBtype, array( 'postgres', 'oracle' ) ) ) {
766 /* DROPs wouldn't work due to Foreign Key Constraints (bug 14990, r58669)
767 * Use "DROP TABLE IF EXISTS $newTableName CASCADE" for postgres? That
768 * syntax would also work for mysql.
770 } elseif ( $db->tableExists( $tbl ) ) {
771 $db->query( "DROP TABLE $newTableName" );
775 $db->duplicateTableStructure( $oldTableName, $newTableName, $temporary );
778 if ( $wgDBtype == 'oracle' )
779 $db->query( 'BEGIN FILL_WIKI_INFO; END;' );
781 $this->changePrefix( $wgDBtype != 'oracle' ? 'parsertest_' : 'pt_' );
783 if ( $wgDBtype == 'oracle' ) {
784 # Insert 0 user to prevent FK violations
787 $db->insert( 'user', array(
789 'user_name' => 'Anonymous' ) );
792 # Hack: insert a few Wikipedia in-project interwiki prefixes,
793 # for testing inter-language links
794 $db->insert( 'interwiki', array(
795 array( 'iw_prefix' => 'wikipedia',
796 'iw_url' => 'http://en.wikipedia.org/wiki/$1',
800 array( 'iw_prefix' => 'meatball',
801 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
805 array( 'iw_prefix' => 'zh',
806 'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
810 array( 'iw_prefix' => 'es',
811 'iw_url' => 'http://es.wikipedia.org/wiki/$1',
815 array( 'iw_prefix' => 'fr',
816 'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
820 array( 'iw_prefix' => 'ru',
821 'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
828 # Update certain things in site_stats
829 $db->insert( 'site_stats', array( 'ss_row_id' => 1, 'ss_images' => 2, 'ss_good_articles' => 1 ) );
831 # Reinitialise the LocalisationCache to match the database state
832 Language::getLocalisationCache()->unloadAll();
834 # Make a new message cache
835 global $wgMessageCache, $wgMemc;
836 $wgMessageCache = new MessageCache( $wgMemc, true, 3600 );
838 $this->uploadDir = $this->setupUploadDir();
839 $user = User::createNew( 'WikiSysop' );
840 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Foobar.jpg' ) );
841 $image->recordUpload2( '', 'Upload of some lame file', 'Some lame file', array(
846 'media_type' => MEDIATYPE_BITMAP,
847 'mime' => 'image/jpeg',
848 'metadata' => serialize( array() ),
849 'sha1' => wfBaseConvert( '', 16, 36, 31 ),
851 ), $db->timestamp( '20010115123500' ), $user );
853 # This image will be blacklisted in [[MediaWiki:Bad image list]]
854 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Bad.jpg' ) );
855 $image->recordUpload2( '', 'zomgnotcensored', 'Borderline image', array(
860 'media_type' => MEDIATYPE_BITMAP,
861 'mime' => 'image/jpeg',
862 'metadata' => serialize( array() ),
863 'sha1' => wfBaseConvert( '', 16, 36, 31 ),
865 ), $db->timestamp( '20010115123500' ), $user );
869 * Change the table prefix on all open DB connections/
871 protected function changePrefix( $prefix ) {
873 wfGetLBFactory()->forEachLB( array( $this, 'changeLBPrefix' ), array( $prefix ) );
874 $wgDBprefix = $prefix;
877 public function changeLBPrefix( $lb, $prefix ) {
878 $lb->forEachOpenConnection( array( $this, 'changeDBPrefix' ), array( $prefix ) );
881 public function changeDBPrefix( $db, $prefix ) {
882 $db->tablePrefix( $prefix );
885 public function teardownDatabase() {
888 if ( !$this->databaseSetupDone ) {
889 $this->teardownGlobals();
892 $this->teardownUploadDir( $this->uploadDir );
894 $this->changePrefix( $this->oldTablePrefix );
895 $this->databaseSetupDone = false;
897 if ( $this->useTemporaryTables ) {
898 # Don't need to do anything
899 $this->teardownGlobals();
903 $tables = $this->listTables();
904 $db = wfGetDB( DB_MASTER );
906 foreach ( $tables as $table ) {
907 $sql = $wgDBtype == 'oracle' ? "DROP TABLE pt_$table DROP CONSTRAINTS" : "DROP TABLE `parsertest_$table`";
911 if ( $wgDBtype == 'oracle' )
912 $db->query( 'BEGIN FILL_WIKI_INFO; END;' );
914 $this->teardownGlobals();
918 * Create a dummy uploads directory which will contain a couple
919 * of files in order to pass existence tests.
921 * @return String: the directory
923 private function setupUploadDir() {
926 if ( $this->keepUploads ) {
927 $dir = wfTempDir() . '/mwParser-images';
929 if ( is_dir( $dir ) ) {
933 $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
936 // wfDebug( "Creating upload directory $dir\n" );
937 if ( file_exists( $dir ) ) {
938 wfDebug( "Already exists!\n" );
942 wfMkdirParents( $dir . '/3/3a' );
943 copy( "$IP/skins/monobook/headbg.jpg", "$dir/3/3a/Foobar.jpg" );
944 wfMkdirParents( $dir . '/0/09' );
945 copy( "$IP/skins/monobook/headbg.jpg", "$dir/0/09/Bad.jpg" );
951 * Restore default values and perform any necessary clean-up
952 * after each test runs.
954 private function teardownGlobals() {
955 RepoGroup::destroySingleton();
956 LinkCache::singleton()->clear();
958 foreach ( $this->savedGlobals as $var => $val ) {
959 $GLOBALS[$var] = $val;
964 * Remove the dummy uploads directory
966 private function teardownUploadDir( $dir ) {
967 if ( $this->keepUploads ) {
971 // delete the files first, then the dirs.
974 "$dir/3/3a/Foobar.jpg",
975 "$dir/thumb/3/3a/Foobar.jpg/180px-Foobar.jpg",
976 "$dir/thumb/3/3a/Foobar.jpg/200px-Foobar.jpg",
977 "$dir/thumb/3/3a/Foobar.jpg/640px-Foobar.jpg",
978 "$dir/thumb/3/3a/Foobar.jpg/120px-Foobar.jpg",
982 "$dir/math/f/a/5/fa50b8b616463173474302ca3e63586b.png",
992 "$dir/thumb/3/3a/Foobar.jpg",
1009 * Delete the specified files, if they exist.
1010 * @param $files Array: full paths to files to delete.
1012 private static function deleteFiles( $files ) {
1013 foreach ( $files as $file ) {
1014 if ( file_exists( $file ) ) {
1021 * Delete the specified directories, if they exist. Must be empty.
1022 * @param $dirs Array: full paths to directories to delete.
1024 private static function deleteDirs( $dirs ) {
1025 foreach ( $dirs as $dir ) {
1026 if ( is_dir( $dir ) ) {
1033 * "Running test $desc..."
1035 protected function showTesting( $desc ) {
1036 print "Running test $desc... ";
1040 * Print a happy success message.
1042 * @param $desc String: the test name
1045 protected function showSuccess( $desc ) {
1046 if ( $this->showProgress ) {
1047 print $this->term->color( '1;32' ) . 'PASSED' . $this->term->reset() . "\n";
1054 * Print a failure message and provide some explanatory output
1055 * about what went wrong if so configured.
1057 * @param $desc String: the test name
1058 * @param $result String: expected HTML output
1059 * @param $html String: actual HTML output
1062 protected function showFailure( $desc, $result, $html ) {
1063 if ( $this->showFailure ) {
1064 if ( !$this->showProgress ) {
1065 # In quiet mode we didn't show the 'Testing' message before the
1066 # test, in case it succeeded. Show it now:
1067 $this->showTesting( $desc );
1070 print $this->term->color( '31' ) . 'FAILED!' . $this->term->reset() . "\n";
1072 if ( $this->showOutput ) {
1073 print "--- Expected ---\n$result\n--- Actual ---\n$html\n";
1076 if ( $this->showDiffs ) {
1077 print $this->quickDiff( $result, $html );
1078 if ( !$this->wellFormed( $html ) ) {
1079 print "XML error: $this->mXmlError\n";
1088 * Run given strings through a diff and return the (colorized) output.
1089 * Requires writable /tmp directory and a 'diff' command in the PATH.
1091 * @param $input String
1092 * @param $output String
1093 * @param $inFileTail String: tailing for the input file name
1094 * @param $outFileTail String: tailing for the output file name
1097 protected function quickDiff( $input, $output, $inFileTail = 'expected', $outFileTail = 'actual' ) {
1098 $prefix = wfTempDir() . "/mwParser-" . mt_rand();
1100 $infile = "$prefix-$inFileTail";
1101 $this->dumpToFile( $input, $infile );
1103 $outfile = "$prefix-$outFileTail";
1104 $this->dumpToFile( $output, $outfile );
1106 $diff = `diff -au $infile $outfile`;
1110 return $this->colorDiff( $diff );
1114 * Write the given string to a file, adding a final newline.
1116 * @param $data String
1117 * @param $filename String
1119 private function dumpToFile( $data, $filename ) {
1120 $file = fopen( $filename, "wt" );
1121 fwrite( $file, $data . "\n" );
1126 * Colorize unified diff output if set for ANSI color output.
1127 * Subtractions are colored blue, additions red.
1129 * @param $text String
1132 protected function colorDiff( $text ) {
1133 return preg_replace(
1134 array( '/^(-.*)$/m', '/^(\+.*)$/m' ),
1135 array( $this->term->color( 34 ) . '$1' . $this->term->reset(),
1136 $this->term->color( 31 ) . '$1' . $this->term->reset() ),
1141 * Show "Reading tests from ..."
1143 * @param $path String
1145 public function showRunFile( $path ) {
1146 print $this->term->color( 1 ) .
1147 "Reading tests from \"$path\"..." .
1148 $this->term->reset() .
1153 * Insert a temporary test article
1154 * @param $name String: the title, including any prefix
1155 * @param $text String: the article text
1156 * @param $line Integer: the input line number, for reporting errors
1158 static public function addArticle( $name, $text, $line = 'unknown' ) {
1159 global $wgCapitalLinks;
1161 $text = self::chomp($text);
1163 $oldCapitalLinks = $wgCapitalLinks;
1164 $wgCapitalLinks = true; // We only need this from SetupGlobals() See r70917#c8637
1166 $name = self::chomp( $name );
1167 $title = Title::newFromText( $name );
1169 if ( is_null( $title ) ) {
1170 wfDie( "invalid title ('$name' => '$title') at line $line\n" );
1173 $aid = $title->getArticleID( Title::GAID_FOR_UPDATE );
1176 debug_print_backtrace();
1177 wfDie( "duplicate article '$name' at line $line\n" );
1180 $art = new Article( $title );
1181 $art->insertNewArticle( $text, '', false, false );
1183 $wgCapitalLinks = $oldCapitalLinks;
1187 * Steal a callback function from the primary parser, save it for
1188 * application to our scary parser. If the hook is not installed,
1189 * abort processing of this file.
1191 * @param $name String
1192 * @return Bool true if tag hook is present
1194 public function requireHook( $name ) {
1197 $wgParser->firstCallInit( ); // make sure hooks are loaded.
1199 if ( isset( $wgParser->mTagHooks[$name] ) ) {
1200 $this->hooks[$name] = $wgParser->mTagHooks[$name];
1202 echo " This test suite requires the '$name' hook extension, skipping.\n";
1210 * Steal a callback function from the primary parser, save it for
1211 * application to our scary parser. If the hook is not installed,
1212 * abort processing of this file.
1214 * @param $name String
1215 * @return Bool true if function hook is present
1217 public function requireFunctionHook( $name ) {
1220 $wgParser->firstCallInit( ); // make sure hooks are loaded.
1222 if ( isset( $wgParser->mFunctionHooks[$name] ) ) {
1223 $this->functionHooks[$name] = $wgParser->mFunctionHooks[$name];
1225 echo " This test suite requires the '$name' function hook extension, skipping.\n";
1233 * Run the "tidy" command on text if the $wgUseTidy
1236 * @param $text String: the text to tidy
1240 private function tidy( $text ) {
1244 $text = MWTidy::tidy( $text );
1250 private function wellFormed( $text ) {
1252 Sanitizer::hackDocType() .
1257 $parser = xml_parser_create( "UTF-8" );
1259 # case folding violates XML standard, turn it off
1260 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
1262 if ( !xml_parse( $parser, $html, true ) ) {
1263 $err = xml_error_string( xml_get_error_code( $parser ) );
1264 $position = xml_get_current_byte_index( $parser );
1265 $fragment = $this->extractFragment( $html, $position );
1266 $this->mXmlError = "$err at byte $position:\n$fragment";
1267 xml_parser_free( $parser );
1272 xml_parser_free( $parser );
1277 private function extractFragment( $text, $position ) {
1278 $start = max( 0, $position - 10 );
1279 $before = $position - $start;
1281 $this->term->color( 34 ) .
1282 substr( $text, $start, $before ) .
1283 $this->term->color( 0 ) .
1284 $this->term->color( 31 ) .
1285 $this->term->color( 1 ) .
1286 substr( $text, $position, 1 ) .
1287 $this->term->color( 0 ) .
1288 $this->term->color( 34 ) .
1289 substr( $text, $position + 1, 9 ) .
1290 $this->term->color( 0 ) .
1292 $display = str_replace( "\n", ' ', $fragment );
1294 str_repeat( ' ', $before ) .
1295 $this->term->color( 31 ) .
1297 $this->term->color( 0 );
1299 return "$display\n$caret";
1302 static function getFakeTimestamp( &$parser, &$ts ) {