3 * Helper code for the MediaWiki parser test suite. Some code is duplicated
4 * in PHPUnit's NewParserTests.php, so you'll probably want to update both
7 * Copyright © 2004, 2010 Brion Vibber <brion@pobox.com>
8 * http://www.mediawiki.org/
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation; either version 2 of the License, or
13 * (at your option) any later version.
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
20 * You should have received a copy of the GNU General Public License along
21 * with this program; if not, write to the Free Software Foundation, Inc.,
22 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
23 * http://www.gnu.org/copyleft/gpl.html
25 * @todo Make this more independent of the configuration (and if possible the database)
36 * boolean $color whereas output should be colorized
41 * boolean $showOutput Show test output
46 * boolean $useTemporaryTables Use temporary tables for the temporary database
48 private $useTemporaryTables = true;
51 * boolean $databaseSetupDone True if the database has been set up
53 private $databaseSetupDone = false;
56 * Our connection to the database
62 * Database clone helper
68 * string $oldTablePrefix Original table prefix
70 private $oldTablePrefix;
72 private $maxFuzzTestLength = 300;
73 private $fuzzSeed = 0;
74 private $memoryLimit = 50;
75 private $uploadDir = null;
78 private $savedGlobals = array();
81 * Sets terminal colorization and diff/quick modes depending on OS and
82 * command-line options (--color and --quick).
84 public function __construct( $options = array() ) {
85 # Only colorize output if stdout is a terminal.
86 $this->color = !wfIsWindows() && Maintenance::posix_isatty( 1 );
88 if ( isset( $options['color'] ) ) {
89 switch ( $options['color'] ) {
100 $this->term = $this->color
101 ? new AnsiTermColorer()
102 : new DummyTermColorer();
104 $this->showDiffs = !isset( $options['quick'] );
105 $this->showProgress = !isset( $options['quiet'] );
106 $this->showFailure = !(
107 isset( $options['quiet'] )
108 && ( isset( $options['record'] )
109 || isset( $options['compare'] ) ) ); // redundant output
111 $this->showOutput = isset( $options['show-output'] );
113 if ( isset( $options['filter'] ) ) {
114 $options['regex'] = $options['filter'];
117 if ( isset( $options['regex'] ) ) {
118 if ( isset( $options['record'] ) ) {
119 echo "Warning: --record cannot be used with --regex, disabling --record\n";
120 unset( $options['record'] );
122 $this->regex = $options['regex'];
128 $this->setupRecorder( $options );
129 $this->keepUploads = isset( $options['keep-uploads'] );
131 if ( isset( $options['seed'] ) ) {
132 $this->fuzzSeed = intval( $options['seed'] ) - 1;
135 $this->runDisabled = isset( $options['run-disabled'] );
136 $this->runParsoid = isset( $options['run-parsoid'] );
138 $this->hooks = array();
139 $this->functionHooks = array();
143 static function setUp() {
144 global $wgParser, $wgParserConf, $IP, $messageMemc, $wgMemc,
145 $wgUser, $wgLang, $wgOut, $wgRequest, $wgStyleDirectory, $wgEnableParserCache,
146 $wgNamespaceAliases, $wgNamespaceProtection, $wgLocalFileRepo,
147 $parserMemc, $wgThumbnailScriptPath, $wgScriptPath,
148 $wgArticlePath, $wgScript, $wgStylePath, $wgExtensionAssetsPath,
149 $wgMainCacheType, $wgMessageCacheType, $wgParserCacheType, $wgLockManagers;
151 $wgScript = '/index.php';
153 $wgArticlePath = '/wiki/$1';
154 $wgStylePath = '/skins';
155 $wgExtensionAssetsPath = '/extensions';
156 $wgThumbnailScriptPath = false;
157 $wgLockManagers = array( array(
158 'name' => 'fsLockManager',
159 'class' => 'FSLockManager',
160 'lockDirectory' => wfTempDir() . '/test-repo/lockdir',
162 'name' => 'nullLockManager',
163 'class' => 'NullLockManager',
165 $wgLocalFileRepo = array(
166 'class' => 'LocalRepo',
168 'url' => 'http://example.com/images',
170 'transformVia404' => false,
171 'backend' => new FSFileBackend( array(
172 'name' => 'local-backend',
173 'lockManager' => 'fsLockManager',
174 'containerPaths' => array(
175 'local-public' => wfTempDir() . '/test-repo/public',
176 'local-thumb' => wfTempDir() . '/test-repo/thumb',
177 'local-temp' => wfTempDir() . '/test-repo/temp',
178 'local-deleted' => wfTempDir() . '/test-repo/deleted',
182 $wgNamespaceProtection[NS_MEDIAWIKI] = 'editinterface';
183 $wgNamespaceAliases['Image'] = NS_FILE;
184 $wgNamespaceAliases['Image_talk'] = NS_FILE_TALK;
186 // XXX: tests won't run without this (for CACHE_DB)
187 if ( $wgMainCacheType === CACHE_DB ) {
188 $wgMainCacheType = CACHE_NONE;
190 if ( $wgMessageCacheType === CACHE_DB ) {
191 $wgMessageCacheType = CACHE_NONE;
193 if ( $wgParserCacheType === CACHE_DB ) {
194 $wgParserCacheType = CACHE_NONE;
197 $wgEnableParserCache = false;
198 DeferredUpdates::clearPendingUpdates();
199 $wgMemc = wfGetMainCache(); // checks $wgMainCacheType
200 $messageMemc = wfGetMessageCacheStorage();
201 $parserMemc = wfGetParserCacheStorage();
203 // $wgContLang = new StubContLang;
205 $context = new RequestContext;
206 $wgLang = $context->getLanguage();
207 $wgOut = $context->getOutput();
208 $wgParser = new StubObject( 'wgParser', $wgParserConf['class'], array( $wgParserConf ) );
209 $wgRequest = $context->getRequest();
211 if ( $wgStyleDirectory === false ) {
212 $wgStyleDirectory = "$IP/skins";
217 public function setupRecorder( $options ) {
218 if ( isset( $options['record'] ) ) {
219 $this->recorder = new DbTestRecorder( $this );
220 $this->recorder->version = isset( $options['setversion'] ) ?
221 $options['setversion'] : SpecialVersion::getVersion();
222 } elseif ( isset( $options['compare'] ) ) {
223 $this->recorder = new DbTestPreviewer( $this );
225 $this->recorder = new TestRecorder( $this );
230 * Remove last character if it is a newline
233 public static function chomp( $s ) {
234 if ( substr( $s, -1 ) === "\n" ) {
235 return substr( $s, 0, -1 );
242 * Run a fuzz test series
243 * Draw input from a set of test files
245 function fuzzTest( $filenames ) {
246 $GLOBALS['wgContLang'] = Language::factory( 'en' );
247 $dict = $this->getFuzzInput( $filenames );
248 $dictSize = strlen( $dict );
249 $logMaxLength = log( $this->maxFuzzTestLength );
250 $this->setupDatabase();
251 ini_set( 'memory_limit', $this->memoryLimit * 1048576 );
256 $opts = ParserOptions::newFromUser( $user );
257 $title = Title::makeTitle( NS_MAIN, 'Parser_test' );
260 // Generate test input
261 mt_srand( ++$this->fuzzSeed );
262 $totalLength = mt_rand( 1, $this->maxFuzzTestLength );
265 while ( strlen( $input ) < $totalLength ) {
266 $logHairLength = mt_rand( 0, 1000000 ) / 1000000 * $logMaxLength;
267 $hairLength = min( intval( exp( $logHairLength ) ), $dictSize );
268 $offset = mt_rand( 0, $dictSize - $hairLength );
269 $input .= substr( $dict, $offset, $hairLength );
272 $this->setupGlobals();
273 $parser = $this->getParser();
277 $parser->parse( $input, $title, $opts );
279 } catch ( Exception $exception ) {
284 echo "Test failed with seed {$this->fuzzSeed}\n";
286 printf( "string(%d) \"%s\"\n\n", strlen( $input ), $input );
293 $this->teardownGlobals();
294 $parser->__destruct();
296 if ( $numTotal % 100 == 0 ) {
297 $usage = intval( memory_get_usage( true ) / $this->memoryLimit / 1048576 * 100 );
298 echo "{$this->fuzzSeed}: $numSuccess/$numTotal (mem: $usage%)\n";
300 echo "Out of memory:\n";
301 $memStats = $this->getMemoryBreakdown();
303 foreach ( $memStats as $name => $usage ) {
304 echo "$name: $usage\n";
313 * Get an input dictionary from a set of parser test files
315 function getFuzzInput( $filenames ) {
318 foreach ( $filenames as $filename ) {
319 $contents = file_get_contents( $filename );
320 preg_match_all( '/!!\s*input\n(.*?)\n!!\s*result/s', $contents, $matches );
322 foreach ( $matches[1] as $match ) {
323 $dict .= $match . "\n";
331 * Get a memory usage breakdown
333 function getMemoryBreakdown() {
336 foreach ( $GLOBALS as $name => $value ) {
337 $memStats['$' . $name] = strlen( serialize( $value ) );
340 $classes = get_declared_classes();
342 foreach ( $classes as $class ) {
343 $rc = new ReflectionClass( $class );
344 $props = $rc->getStaticProperties();
345 $memStats[$class] = strlen( serialize( $props ) );
346 $methods = $rc->getMethods();
348 foreach ( $methods as $method ) {
349 $memStats[$class] += strlen( serialize( $method->getStaticVariables() ) );
353 $functions = get_defined_functions();
355 foreach ( $functions['user'] as $function ) {
356 $rf = new ReflectionFunction( $function );
357 $memStats["$function()"] = strlen( serialize( $rf->getStaticVariables() ) );
370 * Run a series of tests listed in the given text files.
371 * Each test consists of a brief description, wikitext input,
372 * and the expected HTML output.
374 * Prints status updates on stdout and counts up the total
375 * number and percentage of passed tests.
377 * @param $filenames Array of strings
378 * @return Boolean: true if passed all tests, false if any tests failed.
380 public function runTestsFromFiles( $filenames ) {
382 $GLOBALS['wgContLang'] = Language::factory( 'en' );
383 $this->recorder->start();
385 $this->setupDatabase();
388 foreach ( $filenames as $filename ) {
389 $tests = new TestFileIterator( $filename, $this );
390 $ok = $this->runTests( $tests ) && $ok;
393 $this->teardownDatabase();
394 $this->recorder->report();
395 } catch ( DBError $e ) {
396 echo $e->getMessage();
398 $this->recorder->end();
403 function runTests( $tests ) {
406 foreach ( $tests as $t ) {
408 $this->runTest( $t['test'], $t['input'], $t['result'], $t['options'], $t['config'] );
409 $ok = $ok && $result;
410 $this->recorder->record( $t['test'], $result );
413 if ( $this->showProgress ) {
421 * Get a Parser object
423 function getParser( $preprocessor = null ) {
424 global $wgParserConf;
426 $class = $wgParserConf['class'];
427 $parser = new $class( array( 'preprocessorClass' => $preprocessor ) + $wgParserConf );
429 foreach ( $this->hooks as $tag => $callback ) {
430 $parser->setHook( $tag, $callback );
433 foreach ( $this->functionHooks as $tag => $bits ) {
434 list( $callback, $flags ) = $bits;
435 $parser->setFunctionHook( $tag, $callback, $flags );
438 wfRunHooks( 'ParserTestParser', array( &$parser ) );
444 * Run a given wikitext input through a freshly-constructed wiki parser,
445 * and compare the output against the expected results.
446 * Prints status and explanatory messages to stdout.
448 * @param $desc String: test's description
449 * @param $input String: wikitext to try rendering
450 * @param $result String: result to output
451 * @param $opts Array: test's options
452 * @param $config String: overrides for global variables, one per line
455 public function runTest( $desc, $input, $result, $opts, $config ) {
456 if ( $this->showProgress ) {
457 $this->showTesting( $desc );
460 $opts = $this->parseOptions( $opts );
461 $context = $this->setupGlobals( $opts, $config );
463 $user = $context->getUser();
464 $options = ParserOptions::newFromContext( $context );
466 if ( isset( $opts['title'] ) ) {
467 $titleText = $opts['title'];
469 $titleText = 'Parser test';
472 $local = isset( $opts['local'] );
473 $preprocessor = isset( $opts['preprocessor'] ) ? $opts['preprocessor'] : null;
474 $parser = $this->getParser( $preprocessor );
475 $title = Title::newFromText( $titleText );
477 if ( isset( $opts['pst'] ) ) {
478 $out = $parser->preSaveTransform( $input, $title, $user, $options );
479 } elseif ( isset( $opts['msg'] ) ) {
480 $out = $parser->transformMsg( $input, $options, $title );
481 } elseif ( isset( $opts['section'] ) ) {
482 $section = $opts['section'];
483 $out = $parser->getSection( $input, $section );
484 } elseif ( isset( $opts['replace'] ) ) {
485 $section = $opts['replace'][0];
486 $replace = $opts['replace'][1];
487 $out = $parser->replaceSection( $input, $section, $replace );
488 } elseif ( isset( $opts['comment'] ) ) {
489 $out = Linker::formatComment( $input, $title, $local );
490 } elseif ( isset( $opts['preload'] ) ) {
491 $out = $parser->getPreloadText( $input, $title, $options );
493 $output = $parser->parse( $input, $title, $options, true, true, 1337 );
494 $out = $output->getText();
496 if ( isset( $opts['showtitle'] ) ) {
497 if ( $output->getTitleText() ) {
498 $title = $output->getTitleText();
501 $out = "$title\n$out";
504 if ( isset( $opts['ill'] ) ) {
505 $out = $this->tidy( implode( ' ', $output->getLanguageLinks() ) );
506 } elseif ( isset( $opts['cat'] ) ) {
507 $outputPage = $context->getOutput();
508 $outputPage->addCategoryLinks( $output->getCategories() );
509 $cats = $outputPage->getCategoryLinks();
511 if ( isset( $cats['normal'] ) ) {
512 $out = $this->tidy( implode( ' ', $cats['normal'] ) );
518 $result = $this->tidy( $result );
521 $this->teardownGlobals();
523 $testResult = new ParserTestResult( $desc );
524 $testResult->expected = $result;
525 $testResult->actual = $out;
527 return $this->showTestResult( $testResult );
531 * Refactored in 1.22 to use ParserTestResult
533 function showTestResult( ParserTestResult $testResult ) {
534 if ( $testResult->isSuccess() ) {
535 $this->showSuccess( $testResult );
538 $this->showFailure( $testResult );
544 * Use a regex to find out the value of an option
545 * @param $key String: name of option val to retrieve
546 * @param $opts Options array to look in
547 * @param $default Mixed: default value returned if not found
549 private static function getOptionValue( $key, $opts, $default ) {
550 $key = strtolower( $key );
552 if ( isset( $opts[$key] ) ) {
559 private function parseOptions( $instring ) {
565 // foo=bar,"baz quux"
589 \[\[[^]]*\]\] # Link target
597 if ( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER ) ) {
598 foreach ( $matches as $bits ) {
599 array_shift( $bits );
600 $key = strtolower( array_shift( $bits ) );
601 if ( count( $bits ) == 0 ) {
603 } elseif ( count( $bits ) == 1 ) {
604 $opts[$key] = $this->cleanupOption( array_shift( $bits ) );
607 $opts[$key] = array_map( array( $this, 'cleanupOption' ), $bits );
614 private function cleanupOption( $opt ) {
615 if ( substr( $opt, 0, 1 ) == '"' ) {
616 return substr( $opt, 1, -1 );
619 if ( substr( $opt, 0, 2 ) == '[[' ) {
620 return substr( $opt, 2, -2 );
626 * Set up the global variables for a consistent environment for each test.
627 * Ideally this should replace the global configuration entirely.
629 private function setupGlobals( $opts = '', $config = '' ) {
630 # Find out values for some special options.
632 self::getOptionValue( 'language', $opts, 'en' );
634 self::getOptionValue( 'variant', $opts, false );
636 self::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
637 $linkHolderBatchSize =
638 self::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
641 'wgServer' => 'http://example.org',
642 'wgScript' => '/index.php',
643 'wgScriptPath' => '/',
644 'wgArticlePath' => '/wiki/$1',
645 'wgActionPaths' => array(),
646 'wgLockManagers' => array( array(
647 'name' => 'fsLockManager',
648 'class' => 'FSLockManager',
649 'lockDirectory' => $this->uploadDir . '/lockdir',
651 'name' => 'nullLockManager',
652 'class' => 'NullLockManager',
654 'wgLocalFileRepo' => array(
655 'class' => 'LocalRepo',
657 'url' => 'http://example.com/images',
659 'transformVia404' => false,
660 'backend' => new FSFileBackend( array(
661 'name' => 'local-backend',
662 'lockManager' => 'fsLockManager',
663 'containerPaths' => array(
664 'local-public' => $this->uploadDir,
665 'local-thumb' => $this->uploadDir . '/thumb',
666 'local-temp' => $this->uploadDir . '/temp',
667 'local-deleted' => $this->uploadDir . '/delete',
671 'wgEnableUploads' => self::getOptionValue( 'wgEnableUploads', $opts, true ),
672 'wgStylePath' => '/skins',
673 'wgSitename' => 'MediaWiki',
674 'wgLanguageCode' => $lang,
675 'wgDBprefix' => $this->db->getType() != 'oracle' ? 'parsertest_' : 'pt_',
676 'wgRawHtml' => isset( $opts['rawhtml'] ),
678 'wgContLang' => null,
679 'wgNamespacesWithSubpages' => array( 0 => isset( $opts['subpage'] ) ),
680 'wgMaxTocLevel' => $maxtoclevel,
681 'wgCapitalLinks' => true,
682 'wgNoFollowLinks' => true,
683 'wgNoFollowDomainExceptions' => array(),
684 'wgThumbnailScriptPath' => false,
685 'wgUseImageResize' => true,
686 'wgSVGConverter' => 'null',
687 'wgSVGConverters' => array( 'null' => 'echo "1">$output' ),
688 'wgLocaltimezone' => 'UTC',
689 'wgAllowExternalImages' => true,
690 'wgUseTidy' => false,
691 'wgDefaultLanguageVariant' => $variant,
692 'wgVariantArticlePath' => false,
693 'wgGroupPermissions' => array( '*' => array(
694 'createaccount' => true,
697 'createpage' => true,
698 'createtalk' => true,
700 'wgNamespaceProtection' => array( NS_MEDIAWIKI => 'editinterface' ),
701 'wgDefaultExternalStore' => array(),
702 'wgForeignFileRepos' => array(),
703 'wgLinkHolderBatchSize' => $linkHolderBatchSize,
704 'wgExperimentalHtmlIds' => false,
705 'wgExternalLinkTarget' => false,
706 'wgAlwaysUseTidy' => false,
708 'wgWellFormedXml' => true,
709 'wgAllowMicrodataAttributes' => true,
710 'wgAdaptiveMessageCache' => true,
711 'wgDisableLangConversion' => false,
712 'wgDisableTitleConversion' => false,
716 $configLines = explode( "\n", $config );
718 foreach ( $configLines as $line ) {
719 list( $var, $value ) = explode( '=', $line, 2 );
721 $settings[$var] = eval( "return $value;" );
725 $this->savedGlobals = array();
728 wfRunHooks( 'ParserTestGlobals', array( &$settings ) );
730 foreach ( $settings as $var => $val ) {
731 if ( array_key_exists( $var, $GLOBALS ) ) {
732 $this->savedGlobals[$var] = $GLOBALS[$var];
735 $GLOBALS[$var] = $val;
738 $GLOBALS['wgContLang'] = Language::factory( $lang );
739 $GLOBALS['wgMemc'] = new EmptyBagOStuff;
741 $context = new RequestContext();
742 $GLOBALS['wgLang'] = $context->getLanguage();
743 $GLOBALS['wgOut'] = $context->getOutput();
745 $GLOBALS['wgUser'] = new User();
749 $wgHooks['ParserTestParser'][] = 'ParserTestParserHook::setup';
750 $wgHooks['ParserGetVariableValueTs'][] = 'ParserTest::getFakeTimestamp';
752 MagicWord::clearCache();
758 * List of temporary tables to create, without prefix.
759 * Some of these probably aren't necessary.
761 private function listTables() {
762 $tables = array( 'user', 'user_properties', 'user_former_groups', 'page', 'page_restrictions',
763 'protected_titles', 'revision', 'text', 'pagelinks', 'imagelinks',
764 'categorylinks', 'templatelinks', 'externallinks', 'langlinks', 'iwlinks',
765 'site_stats', 'hitcounter', 'ipblocks', 'image', 'oldimage',
766 'recentchanges', 'watchlist', 'interwiki', 'logging',
767 'querycache', 'objectcache', 'job', 'l10n_cache', 'redirect', 'querycachetwo',
768 'archive', 'user_groups', 'page_props', 'category', 'msg_resource', 'msg_resource_links'
771 if ( in_array( $this->db->getType(), array( 'mysql', 'sqlite', 'oracle' ) ) ) {
772 array_push( $tables, 'searchindex' );
775 // Allow extensions to add to the list of tables to duplicate;
776 // may be necessary if they hook into page save or other code
777 // which will require them while running tests.
778 wfRunHooks( 'ParserTestTables', array( &$tables ) );
784 * Set up a temporary set of wiki tables to work with for the tests.
785 * Currently this will only be done once per run, and any changes to
786 * the db will be visible to later tests in the run.
788 public function setupDatabase() {
791 if ( $this->databaseSetupDone ) {
795 $this->db = wfGetDB( DB_MASTER );
796 $dbType = $this->db->getType();
798 if ( $wgDBprefix === 'parsertest_' || ( $dbType == 'oracle' && $wgDBprefix === 'pt_' ) ) {
799 throw new MWException( 'setupDatabase should be called before setupGlobals' );
802 $this->databaseSetupDone = true;
803 $this->oldTablePrefix = $wgDBprefix;
805 # SqlBagOStuff broke when using temporary tables on r40209 (bug 15892).
806 # It seems to have been fixed since (r55079?), but regressed at some point before r85701.
807 # This works around it for now...
808 ObjectCache::$instances[CACHE_DB] = new HashBagOStuff;
810 # CREATE TEMPORARY TABLE breaks if there is more than one server
811 if ( wfGetLB()->getServerCount() != 1 ) {
812 $this->useTemporaryTables = false;
815 $temporary = $this->useTemporaryTables || $dbType == 'postgres';
816 $prefix = $dbType != 'oracle' ? 'parsertest_' : 'pt_';
818 $this->dbClone = new CloneDatabase( $this->db, $this->listTables(), $prefix );
819 $this->dbClone->useTemporaryTables( $temporary );
820 $this->dbClone->cloneTableStructure();
822 if ( $dbType == 'oracle' ) {
823 $this->db->query( 'BEGIN FILL_WIKI_INFO; END;' );
824 # Insert 0 user to prevent FK violations
827 $this->db->insert( 'user', array(
829 'user_name' => 'Anonymous' ) );
832 # Hack: insert a few Wikipedia in-project interwiki prefixes,
833 # for testing inter-language links
834 $this->db->insert( 'interwiki', array(
835 array( 'iw_prefix' => 'wikipedia',
836 'iw_url' => 'http://en.wikipedia.org/wiki/$1',
840 array( 'iw_prefix' => 'meatball',
841 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
845 array( 'iw_prefix' => 'zh',
846 'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
850 array( 'iw_prefix' => 'es',
851 'iw_url' => 'http://es.wikipedia.org/wiki/$1',
855 array( 'iw_prefix' => 'fr',
856 'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
860 array( 'iw_prefix' => 'ru',
861 'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
867 # Update certain things in site_stats
868 $this->db->insert( 'site_stats', array( 'ss_row_id' => 1, 'ss_images' => 2, 'ss_good_articles' => 1 ) );
870 # Reinitialise the LocalisationCache to match the database state
871 Language::getLocalisationCache()->unloadAll();
873 # Clear the message cache
874 MessageCache::singleton()->clear();
876 // Remember to update newParserTests.php after changing the below
877 // (and it uses a slightly different syntax just for teh lulz)
878 $this->uploadDir = $this->setupUploadDir();
879 $user = User::createNew( 'WikiSysop' );
880 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Foobar.jpg' ) );
881 # note that the size/width/height/bits/etc of the file
882 # are actually set by inspecting the file itself; the arguments
883 # to recordUpload2 have no effect. That said, we try to make things
884 # match up so it is less confusing to readers of the code & tests.
885 $image->recordUpload2( '', 'Upload of some lame file', 'Some lame file', array(
890 'media_type' => MEDIATYPE_BITMAP,
891 'mime' => 'image/jpeg',
892 'metadata' => serialize( array() ),
893 'sha1' => wfBaseConvert( '1', 16, 36, 31 ),
895 ), $this->db->timestamp( '20010115123500' ), $user );
897 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Thumb.png' ) );
898 # again, note that size/width/height below are ignored; see above.
899 $image->recordUpload2( '', 'Upload of some lame thumbnail', 'Some lame thumbnail', array(
904 'media_type' => MEDIATYPE_BITMAP,
905 'mime' => 'image/png',
906 'metadata' => serialize( array() ),
907 'sha1' => wfBaseConvert( '2', 16, 36, 31 ),
909 ), $this->db->timestamp( '20130225203040' ), $user );
911 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Foobar.svg' ) );
912 $image->recordUpload2( '', 'Upload of some lame SVG', 'Some lame SVG', array(
917 'media_type' => MEDIATYPE_DRAWING,
918 'mime' => 'image/svg+xml',
919 'metadata' => serialize( array() ),
920 'sha1' => wfBaseConvert( '', 16, 36, 31 ),
922 ), $this->db->timestamp( '20010115123500' ), $user );
924 # This image will be blacklisted in [[MediaWiki:Bad image list]]
925 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Bad.jpg' ) );
926 $image->recordUpload2( '', 'zomgnotcensored', 'Borderline image', array(
931 'media_type' => MEDIATYPE_BITMAP,
932 'mime' => 'image/jpeg',
933 'metadata' => serialize( array() ),
934 'sha1' => wfBaseConvert( '3', 16, 36, 31 ),
936 ), $this->db->timestamp( '20010115123500' ), $user );
939 public function teardownDatabase() {
940 if ( !$this->databaseSetupDone ) {
941 $this->teardownGlobals();
944 $this->teardownUploadDir( $this->uploadDir );
946 $this->dbClone->destroy();
947 $this->databaseSetupDone = false;
949 if ( $this->useTemporaryTables ) {
950 if ( $this->db->getType() == 'sqlite' ) {
951 # Under SQLite the searchindex table is virtual and need
952 # to be explicitly destroyed. See bug 29912
953 # See also MediaWikiTestCase::destroyDB()
954 wfDebug( __METHOD__ . " explicitly destroying sqlite virtual table parsertest_searchindex\n" );
955 $this->db->query( "DROP TABLE `parsertest_searchindex`" );
957 # Don't need to do anything
958 $this->teardownGlobals();
962 $tables = $this->listTables();
964 foreach ( $tables as $table ) {
965 $sql = $this->db->getType() == 'oracle' ? "DROP TABLE pt_$table DROP CONSTRAINTS" : "DROP TABLE `parsertest_$table`";
966 $this->db->query( $sql );
969 if ( $this->db->getType() == 'oracle' ) {
970 $this->db->query( 'BEGIN FILL_WIKI_INFO; END;' );
973 $this->teardownGlobals();
977 * Create a dummy uploads directory which will contain a couple
978 * of files in order to pass existence tests.
980 * @return String: the directory
982 private function setupUploadDir() {
985 if ( $this->keepUploads ) {
986 $dir = wfTempDir() . '/mwParser-images';
988 if ( is_dir( $dir ) ) {
992 $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
995 // wfDebug( "Creating upload directory $dir\n" );
996 if ( file_exists( $dir ) ) {
997 wfDebug( "Already exists!\n" );
1001 wfMkdirParents( $dir . '/3/3a', null, __METHOD__ );
1002 copy( "$IP/skins/monobook/headbg.jpg", "$dir/3/3a/Foobar.jpg" );
1003 wfMkdirParents( $dir . '/e/ea', null, __METHOD__ );
1004 copy( "$IP/skins/monobook/wiki.png", "$dir/e/ea/Thumb.png" );
1005 wfMkdirParents( $dir . '/0/09', null, __METHOD__ );
1006 copy( "$IP/skins/monobook/headbg.jpg", "$dir/0/09/Bad.jpg" );
1007 wfMkdirParents( $dir . '/f/ff', null, __METHOD__ );
1008 copy( "$IP/skins/monobook/headbg.jpg", "$dir/f/ff/Foobar.svg" );
1009 file_put_contents( "$dir/f/ff/Foobar.svg",
1010 '<?xml version="1.0" encoding="utf-8"?>' .
1011 '<svg xmlns="http://www.w3.org/2000/svg" />' );
1016 * Restore default values and perform any necessary clean-up
1017 * after each test runs.
1019 private function teardownGlobals() {
1020 RepoGroup::destroySingleton();
1021 FileBackendGroup::destroySingleton();
1022 LockManagerGroup::destroySingletons();
1023 LinkCache::singleton()->clear();
1025 foreach ( $this->savedGlobals as $var => $val ) {
1026 $GLOBALS[$var] = $val;
1031 * Remove the dummy uploads directory
1033 private function teardownUploadDir( $dir ) {
1034 if ( $this->keepUploads ) {
1038 // delete the files first, then the dirs.
1041 "$dir/3/3a/Foobar.jpg",
1042 "$dir/thumb/3/3a/Foobar.jpg/180px-Foobar.jpg",
1043 "$dir/thumb/3/3a/Foobar.jpg/200px-Foobar.jpg",
1044 "$dir/thumb/3/3a/Foobar.jpg/640px-Foobar.jpg",
1045 "$dir/thumb/3/3a/Foobar.jpg/120px-Foobar.jpg",
1046 "$dir/thumb/3/3a/Foobar.jpg/1280px-Foobar.jpg",
1047 "$dir/thumb/3/3a/Foobar.jpg/20px-Foobar.jpg",
1048 "$dir/thumb/3/3a/Foobar.jpg/270px-Foobar.jpg",
1049 "$dir/thumb/3/3a/Foobar.jpg/300px-Foobar.jpg",
1050 "$dir/thumb/3/3a/Foobar.jpg/30px-Foobar.jpg",
1051 "$dir/thumb/3/3a/Foobar.jpg/360px-Foobar.jpg",
1052 "$dir/thumb/3/3a/Foobar.jpg/400px-Foobar.jpg",
1053 "$dir/thumb/3/3a/Foobar.jpg/40px-Foobar.jpg",
1054 "$dir/thumb/3/3a/Foobar.jpg/70px-Foobar.jpg",
1055 "$dir/thumb/3/3a/Foobar.jpg/960px-Foobar.jpg",
1057 "$dir/e/ea/Thumb.png",
1059 "$dir/0/09/Bad.jpg",
1061 "$dir/f/ff/Foobar.svg",
1062 "$dir/thumb/f/ff/Foobar.svg/180px-Foobar.svg.png",
1063 "$dir/thumb/f/ff/Foobar.svg/360px-Foobar.svg.png",
1064 "$dir/thumb/f/ff/Foobar.svg/langde-270px-Foobar.svg.png",
1065 "$dir/thumb/f/ff/Foobar.svg/270px-Foobar.svg.png",
1066 "$dir/thumb/f/ff/Foobar.svg/langde-180px-Foobar.svg.png",
1067 "$dir/thumb/f/ff/Foobar.svg/langde-360px-Foobar.svg.png",
1069 "$dir/math/f/a/5/fa50b8b616463173474302ca3e63586b.png",
1079 "$dir/thumb/3/3a/Foobar.jpg",
1086 "$dir/thumb/f/ff/Foobar.svg",
1102 * Delete the specified files, if they exist.
1103 * @param $files Array: full paths to files to delete.
1105 private static function deleteFiles( $files ) {
1106 foreach ( $files as $file ) {
1107 if ( file_exists( $file ) ) {
1114 * Delete the specified directories, if they exist. Must be empty.
1115 * @param $dirs Array: full paths to directories to delete.
1117 private static function deleteDirs( $dirs ) {
1118 foreach ( $dirs as $dir ) {
1119 if ( is_dir( $dir ) ) {
1126 * "Running test $desc..."
1128 protected function showTesting( $desc ) {
1129 print "Running test $desc... ";
1133 * Print a happy success message.
1135 * Refactored in 1.22 to use ParserTestResult
1137 * @param $testResult ParserTestResult
1140 protected function showSuccess( ParserTestResult $testResult ) {
1141 if ( $this->showProgress ) {
1142 print $this->term->color( '1;32' ) . 'PASSED' . $this->term->reset() . "\n";
1149 * Print a failure message and provide some explanatory output
1150 * about what went wrong if so configured.
1152 * Refactored in 1.22 to use ParserTestResult
1154 * @param $testResult ParserTestResult
1157 protected function showFailure( ParserTestResult $testResult ) {
1158 if ( $this->showFailure ) {
1159 if ( !$this->showProgress ) {
1160 # In quiet mode we didn't show the 'Testing' message before the
1161 # test, in case it succeeded. Show it now:
1162 $this->showTesting( $testResult->description );
1165 print $this->term->color( '31' ) . 'FAILED!' . $this->term->reset() . "\n";
1167 if ( $this->showOutput ) {
1168 print "--- Expected ---\n{$testResult->expected}\n";
1169 print "--- Actual ---\n{$testResult->actual}\n";
1172 if ( $this->showDiffs ) {
1173 print $this->quickDiff( $testResult->expected, $testResult->actual );
1174 if ( !$this->wellFormed( $testResult->actual ) ) {
1175 print "XML error: $this->mXmlError\n";
1184 * Run given strings through a diff and return the (colorized) output.
1185 * Requires writable /tmp directory and a 'diff' command in the PATH.
1187 * @param $input String
1188 * @param $output String
1189 * @param $inFileTail String: tailing for the input file name
1190 * @param $outFileTail String: tailing for the output file name
1193 protected function quickDiff( $input, $output, $inFileTail = 'expected', $outFileTail = 'actual' ) {
1194 # Windows, or at least the fc utility, is retarded
1195 $slash = wfIsWindows() ? '\\' : '/';
1196 $prefix = wfTempDir() . "{$slash}mwParser-" . mt_rand();
1198 $infile = "$prefix-$inFileTail";
1199 $this->dumpToFile( $input, $infile );
1201 $outfile = "$prefix-$outFileTail";
1202 $this->dumpToFile( $output, $outfile );
1204 $shellInfile = wfEscapeShellArg( $infile );
1205 $shellOutfile = wfEscapeShellArg( $outfile );
1208 // we assume that people with diff3 also have usual diff
1209 $shellCommand = ( wfIsWindows() && !$wgDiff3 ) ? 'fc' : 'diff -au';
1211 $diff = wfShellExec( "$shellCommand $shellInfile $shellOutfile" );
1216 return $this->colorDiff( $diff );
1220 * Write the given string to a file, adding a final newline.
1222 * @param $data String
1223 * @param $filename String
1225 private function dumpToFile( $data, $filename ) {
1226 $file = fopen( $filename, "wt" );
1227 fwrite( $file, $data . "\n" );
1232 * Colorize unified diff output if set for ANSI color output.
1233 * Subtractions are colored blue, additions red.
1235 * @param $text String
1238 protected function colorDiff( $text ) {
1239 return preg_replace(
1240 array( '/^(-.*)$/m', '/^(\+.*)$/m' ),
1241 array( $this->term->color( 34 ) . '$1' . $this->term->reset(),
1242 $this->term->color( 31 ) . '$1' . $this->term->reset() ),
1247 * Show "Reading tests from ..."
1249 * @param $path String
1251 public function showRunFile( $path ) {
1252 print $this->term->color( 1 ) .
1253 "Reading tests from \"$path\"..." .
1254 $this->term->reset() .
1259 * Insert a temporary test article
1260 * @param $name String: the title, including any prefix
1261 * @param $text String: the article text
1262 * @param $line Integer: the input line number, for reporting errors
1263 * @param $ignoreDuplicate Boolean: whether to silently ignore duplicate pages
1265 public static function addArticle( $name, $text, $line = 'unknown', $ignoreDuplicate = '' ) {
1266 global $wgCapitalLinks;
1268 $oldCapitalLinks = $wgCapitalLinks;
1269 $wgCapitalLinks = true; // We only need this from SetupGlobals() See r70917#c8637
1271 $text = self::chomp( $text );
1272 $name = self::chomp( $name );
1274 $title = Title::newFromText( $name );
1276 if ( is_null( $title ) ) {
1277 throw new MWException( "invalid title '$name' at line $line\n" );
1280 $page = WikiPage::factory( $title );
1281 $page->loadPageData( 'fromdbmaster' );
1283 if ( $page->exists() ) {
1284 if ( $ignoreDuplicate == 'ignoreduplicate' ) {
1287 throw new MWException( "duplicate article '$name' at line $line\n" );
1291 $page->doEditContent( ContentHandler::makeContent( $text, $title ), '', EDIT_NEW );
1293 $wgCapitalLinks = $oldCapitalLinks;
1297 * Steal a callback function from the primary parser, save it for
1298 * application to our scary parser. If the hook is not installed,
1299 * abort processing of this file.
1301 * @param $name String
1302 * @return Bool true if tag hook is present
1304 public function requireHook( $name ) {
1307 $wgParser->firstCallInit(); // make sure hooks are loaded.
1309 if ( isset( $wgParser->mTagHooks[$name] ) ) {
1310 $this->hooks[$name] = $wgParser->mTagHooks[$name];
1312 echo " This test suite requires the '$name' hook extension, skipping.\n";
1320 * Steal a callback function from the primary parser, save it for
1321 * application to our scary parser. If the hook is not installed,
1322 * abort processing of this file.
1324 * @param $name String
1325 * @return Bool true if function hook is present
1327 public function requireFunctionHook( $name ) {
1330 $wgParser->firstCallInit(); // make sure hooks are loaded.
1332 if ( isset( $wgParser->mFunctionHooks[$name] ) ) {
1333 $this->functionHooks[$name] = $wgParser->mFunctionHooks[$name];
1335 echo " This test suite requires the '$name' function hook extension, skipping.\n";
1343 * Run the "tidy" command on text if the $wgUseTidy
1346 * @param $text String: the text to tidy
1349 private function tidy( $text ) {
1353 $text = MWTidy::tidy( $text );
1359 private function wellFormed( $text ) {
1361 Sanitizer::hackDocType() .
1366 $parser = xml_parser_create( "UTF-8" );
1368 # case folding violates XML standard, turn it off
1369 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
1371 if ( !xml_parse( $parser, $html, true ) ) {
1372 $err = xml_error_string( xml_get_error_code( $parser ) );
1373 $position = xml_get_current_byte_index( $parser );
1374 $fragment = $this->extractFragment( $html, $position );
1375 $this->mXmlError = "$err at byte $position:\n$fragment";
1376 xml_parser_free( $parser );
1381 xml_parser_free( $parser );
1386 private function extractFragment( $text, $position ) {
1387 $start = max( 0, $position - 10 );
1388 $before = $position - $start;
1390 $this->term->color( 34 ) .
1391 substr( $text, $start, $before ) .
1392 $this->term->color( 0 ) .
1393 $this->term->color( 31 ) .
1394 $this->term->color( 1 ) .
1395 substr( $text, $position, 1 ) .
1396 $this->term->color( 0 ) .
1397 $this->term->color( 34 ) .
1398 substr( $text, $position + 1, 9 ) .
1399 $this->term->color( 0 ) .
1401 $display = str_replace( "\n", ' ', $fragment );
1403 str_repeat( ' ', $before ) .
1404 $this->term->color( 31 ) .
1406 $this->term->color( 0 );
1408 return "$display\n$caret";
1411 static function getFakeTimestamp( &$parser, &$ts ) {