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)
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 * Our connection to the database
57 * string $oldTablePrefix Original table prefix
59 private $oldTablePrefix;
61 private $maxFuzzTestLength = 300;
62 private $fuzzSeed = 0;
63 private $memoryLimit = 50;
64 private $uploadDir = null;
67 private $savedGlobals = array();
69 * Sets terminal colorization and diff/quick modes depending on OS and
70 * command-line options (--color and --quick).
72 public function __construct( $options = array() ) {
73 # Only colorize output if stdout is a terminal.
74 $this->color = !wfIsWindows() && posix_isatty( 1 );
76 if ( isset( $options['color'] ) ) {
77 switch( $options['color'] ) {
88 $this->term = $this->color
89 ? new AnsiTermColorer()
90 : new DummyTermColorer();
92 $this->showDiffs = !isset( $options['quick'] );
93 $this->showProgress = !isset( $options['quiet'] );
94 $this->showFailure = !(
95 isset( $options['quiet'] )
96 && ( isset( $options['record'] )
97 || isset( $options['compare'] ) ) ); // redundant output
99 $this->showOutput = isset( $options['show-output'] );
102 if ( isset( $options['regex'] ) ) {
103 if ( isset( $options['record'] ) ) {
104 echo "Warning: --record cannot be used with --regex, disabling --record\n";
105 unset( $options['record'] );
107 $this->regex = $options['regex'];
113 $this->setupRecorder( $options );
114 $this->keepUploads = isset( $options['keep-uploads'] );
116 if ( isset( $options['seed'] ) ) {
117 $this->fuzzSeed = intval( $options['seed'] ) - 1;
120 $this->runDisabled = isset( $options['run-disabled'] );
122 $this->hooks = array();
123 $this->functionHooks = array();
127 static function setUp() {
128 global $wgParser, $wgParserConf, $IP, $messageMemc, $wgMemc, $wgDeferredUpdateList,
129 $wgUser, $wgLang, $wgOut, $wgRequest, $wgStyleDirectory, $wgEnableParserCache,
130 $wgMessageCache, $wgUseDatabaseMessages, $wgMsgCacheExpiry, $parserMemc,
131 $wgNamespaceAliases, $wgNamespaceProtection, $wgLocalFileRepo,
132 $wgThumbnailScriptPath, $wgScriptPath,
133 $wgArticlePath, $wgStyleSheetPath, $wgScript, $wgStylePath;
135 $wgScript = '/index.php';
137 $wgArticlePath = '/wiki/$1';
138 $wgStyleSheetPath = '/skins';
139 $wgStylePath = '/skins';
140 $wgThumbnailScriptPath = false;
141 $wgLocalFileRepo = array(
142 'class' => 'LocalRepo',
144 'directory' => wfTempDir() . '/test-repo',
145 'url' => 'http://example.com/images',
146 'deletedDir' => wfTempDir() . '/test-repo/delete',
148 'transformVia404' => false,
150 $wgNamespaceProtection[NS_MEDIAWIKI] = 'editinterface';
151 $wgNamespaceAliases['Image'] = NS_FILE;
152 $wgNamespaceAliases['Image_talk'] = NS_FILE_TALK;
155 $wgEnableParserCache = false;
156 $wgDeferredUpdateList = array();
157 $wgMemc = &wfGetMainCache();
158 $messageMemc = &wfGetMessageCacheStorage();
159 $parserMemc = &wfGetParserCacheStorage();
161 // $wgContLang = new StubContLang;
163 $wgLang = new StubUserLang;
164 $wgOut = new StubObject( 'wgOut', 'OutputPage' );
165 $wgParser = new StubObject( 'wgParser', $wgParserConf['class'], array( $wgParserConf ) );
166 $wgRequest = new WebRequest;
168 $wgMessageCache = new StubObject( 'wgMessageCache', 'MessageCache',
169 array( $messageMemc, $wgUseDatabaseMessages,
170 $wgMsgCacheExpiry ) );
171 if ( $wgStyleDirectory === false ) {
172 $wgStyleDirectory = "$IP/skins";
177 public function setupRecorder ( $options ) {
178 if ( isset( $options['record'] ) ) {
179 $this->recorder = new DbTestRecorder( $this );
180 $this->recorder->version = isset( $options['setversion'] ) ?
181 $options['setversion'] : SpecialVersion::getVersion();
182 } elseif ( isset( $options['compare'] ) ) {
183 $this->recorder = new DbTestPreviewer( $this );
184 } elseif ( isset( $options['upload'] ) ) {
185 $this->recorder = new RemoteTestRecorder( $this );
187 $this->recorder = new TestRecorder( $this );
192 * Remove last character if it is a newline
195 static public function chomp( $s ) {
196 if ( substr( $s, -1 ) === "\n" ) {
197 return substr( $s, 0, -1 );
205 * Run a fuzz test series
206 * Draw input from a set of test files
208 function fuzzTest( $filenames ) {
209 $GLOBALS['wgContLang'] = Language::factory( 'en' );
210 $dict = $this->getFuzzInput( $filenames );
211 $dictSize = strlen( $dict );
212 $logMaxLength = log( $this->maxFuzzTestLength );
213 $this->setupDatabase();
214 ini_set( 'memory_limit', $this->memoryLimit * 1048576 );
219 $opts = ParserOptions::newFromUser( $user );
220 $title = Title::makeTitle( NS_MAIN, 'Parser_test' );
223 // Generate test input
224 mt_srand( ++$this->fuzzSeed );
225 $totalLength = mt_rand( 1, $this->maxFuzzTestLength );
228 while ( strlen( $input ) < $totalLength ) {
229 $logHairLength = mt_rand( 0, 1000000 ) / 1000000 * $logMaxLength;
230 $hairLength = min( intval( exp( $logHairLength ) ), $dictSize );
231 $offset = mt_rand( 0, $dictSize - $hairLength );
232 $input .= substr( $dict, $offset, $hairLength );
235 $this->setupGlobals();
236 $parser = $this->getParser();
240 $parser->parse( $input, $title, $opts );
242 } catch ( Exception $exception ) {
247 echo "Test failed with seed {$this->fuzzSeed}\n";
257 $this->teardownGlobals();
258 $parser->__destruct();
260 if ( $numTotal % 100 == 0 ) {
261 $usage = intval( memory_get_usage( true ) / $this->memoryLimit / 1048576 * 100 );
262 echo "{$this->fuzzSeed}: $numSuccess/$numTotal (mem: $usage%)\n";
264 echo "Out of memory:\n";
265 $memStats = $this->getMemoryBreakdown();
267 foreach ( $memStats as $name => $usage ) {
268 echo "$name: $usage\n";
277 * Get an input dictionary from a set of parser test files
279 function getFuzzInput( $filenames ) {
282 foreach ( $filenames as $filename ) {
283 $contents = file_get_contents( $filename );
284 preg_match_all( '/!!\s*input\n(.*?)\n!!\s*result/s', $contents, $matches );
286 foreach ( $matches[1] as $match ) {
287 $dict .= $match . "\n";
295 * Get a memory usage breakdown
297 function getMemoryBreakdown() {
300 foreach ( $GLOBALS as $name => $value ) {
301 $memStats['$' . $name] = strlen( serialize( $value ) );
304 $classes = get_declared_classes();
306 foreach ( $classes as $class ) {
307 $rc = new ReflectionClass( $class );
308 $props = $rc->getStaticProperties();
309 $memStats[$class] = strlen( serialize( $props ) );
310 $methods = $rc->getMethods();
312 foreach ( $methods as $method ) {
313 $memStats[$class] += strlen( serialize( $method->getStaticVariables() ) );
317 $functions = get_defined_functions();
319 foreach ( $functions['user'] as $function ) {
320 $rf = new ReflectionFunction( $function );
321 $memStats["$function()"] = strlen( serialize( $rf->getStaticVariables() ) );
334 * Run a series of tests listed in the given text files.
335 * Each test consists of a brief description, wikitext input,
336 * and the expected HTML output.
338 * Prints status updates on stdout and counts up the total
339 * number and percentage of passed tests.
341 * @param $filenames Array of strings
342 * @return Boolean: true if passed all tests, false if any tests failed.
344 public function runTestsFromFiles( $filenames ) {
346 $GLOBALS['wgContLang'] = Language::factory( 'en' );
347 $this->recorder->start();
349 $this->setupDatabase();
352 foreach ( $filenames as $filename ) {
353 $tests = new TestFileIterator( $filename, $this );
354 $ok = $this->runTests( $tests ) && $ok;
357 $this->teardownDatabase();
358 $this->recorder->report();
359 } catch (DBError $e) {
360 echo $e->getMessage();
362 $this->recorder->end();
367 function runTests( $tests ) {
370 foreach ( $tests as $t ) {
372 $this->runTest( $t['test'], $t['input'], $t['result'], $t['options'], $t['config'] );
373 $ok = $ok && $result;
374 $this->recorder->record( $t['test'], $result );
377 if ( $this->showProgress ) {
385 * Get a Parser object
387 function getParser( $preprocessor = null ) {
388 global $wgParserConf;
390 $class = $wgParserConf['class'];
391 $parser = new $class( array( 'preprocessorClass' => $preprocessor ) + $wgParserConf );
393 foreach ( $this->hooks as $tag => $callback ) {
394 $parser->setHook( $tag, $callback );
397 foreach ( $this->functionHooks as $tag => $bits ) {
398 list( $callback, $flags ) = $bits;
399 $parser->setFunctionHook( $tag, $callback, $flags );
402 wfRunHooks( 'ParserTestParser', array( &$parser ) );
408 * Run a given wikitext input through a freshly-constructed wiki parser,
409 * and compare the output against the expected results.
410 * Prints status and explanatory messages to stdout.
412 * @param $desc String: test's description
413 * @param $input String: wikitext to try rendering
414 * @param $result String: result to output
415 * @param $opts Array: test's options
416 * @param $config String: overrides for global variables, one per line
419 public function runTest( $desc, $input, $result, $opts, $config ) {
420 if ( $this->showProgress ) {
421 $this->showTesting( $desc );
424 $opts = $this->parseOptions( $opts );
425 $this->setupGlobals( $opts, $config );
428 $options = ParserOptions::newFromUser( $user );
430 if ( isset( $opts['title'] ) ) {
431 $titleText = $opts['title'];
434 $titleText = 'Parser test';
437 $local = isset( $opts['local'] );
438 $preprocessor = isset( $opts['preprocessor'] ) ? $opts['preprocessor'] : null;
439 $parser = $this->getParser( $preprocessor );
440 $title = Title::newFromText( $titleText );
442 if ( isset( $opts['pst'] ) ) {
443 $out = $parser->preSaveTransform( $input, $title, $user, $options );
444 } elseif ( isset( $opts['msg'] ) ) {
445 $out = $parser->transformMsg( $input, $options );
446 } elseif ( isset( $opts['section'] ) ) {
447 $section = $opts['section'];
448 $out = $parser->getSection( $input, $section );
449 } elseif ( isset( $opts['replace'] ) ) {
450 $section = $opts['replace'][0];
451 $replace = $opts['replace'][1];
452 $out = $parser->replaceSection( $input, $section, $replace );
453 } elseif ( isset( $opts['comment'] ) ) {
454 $linker = $user->getSkin();
455 $out = $linker->formatComment( $input, $title, $local );
456 } elseif ( isset( $opts['preload'] ) ) {
457 $out = $parser->getpreloadText( $input, $title, $options );
459 $output = $parser->parse( $input, $title, $options, true, true, 1337 );
460 $out = $output->getText();
462 if ( isset( $opts['showtitle'] ) ) {
463 if ( $output->getTitleText() ) {
464 $title = $output->getTitleText();
467 $out = "$title\n$out";
470 if ( isset( $opts['ill'] ) ) {
471 $out = $this->tidy( implode( ' ', $output->getLanguageLinks() ) );
472 } elseif ( isset( $opts['cat'] ) ) {
475 $wgOut->addCategoryLinks( $output->getCategories() );
476 $cats = $wgOut->getCategoryLinks();
478 if ( isset( $cats['normal'] ) ) {
479 $out = $this->tidy( implode( ' ', $cats['normal'] ) );
485 $result = $this->tidy( $result );
488 $this->teardownGlobals();
489 return $this->showTestResult( $desc, $result, $out );
495 function showTestResult( $desc, $result, $out ) {
496 if ( $result === $out ) {
497 $this->showSuccess( $desc );
500 $this->showFailure( $desc, $result, $out );
506 * Use a regex to find out the value of an option
507 * @param $key String: name of option val to retrieve
508 * @param $opts Options array to look in
509 * @param $default Mixed: default value returned if not found
511 private static function getOptionValue( $key, $opts, $default ) {
512 $key = strtolower( $key );
514 if ( isset( $opts[$key] ) ) {
521 private function parseOptions( $instring ) {
527 // foo=bar,"baz quux"
551 \[\[[^]]*\]\] # Link target
559 if ( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER ) ) {
560 foreach ( $matches as $bits ) {
561 array_shift( $bits );
562 $key = strtolower( array_shift( $bits ) );
563 if ( count( $bits ) == 0 ) {
565 } elseif ( count( $bits ) == 1 ) {
566 $opts[$key] = $this->cleanupOption( array_shift( $bits ) );
569 $opts[$key] = array_map( array( $this, 'cleanupOption' ), $bits );
576 private function cleanupOption( $opt ) {
577 if ( substr( $opt, 0, 1 ) == '"' ) {
578 return substr( $opt, 1, -1 );
581 if ( substr( $opt, 0, 2 ) == '[[' ) {
582 return substr( $opt, 2, -2 );
588 * Set up the global variables for a consistent environment for each test.
589 * Ideally this should replace the global configuration entirely.
591 private function setupGlobals( $opts = '', $config = '' ) {
592 # Find out values for some special options.
594 self::getOptionValue( 'language', $opts, 'en' );
596 self::getOptionValue( 'variant', $opts, false );
598 self::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
599 $linkHolderBatchSize =
600 self::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
603 'wgServer' => 'http://Britney-Spears',
604 'wgScript' => '/index.php',
605 'wgScriptPath' => '/',
606 'wgArticlePath' => '/wiki/$1',
607 'wgActionPaths' => array(),
608 'wgLocalFileRepo' => array(
609 'class' => 'LocalRepo',
611 'directory' => $this->uploadDir,
612 'url' => 'http://example.com/images',
614 'transformVia404' => false,
616 'wgEnableUploads' => self::getOptionValue( 'wgEnableUploads', $opts, true ),
617 'wgStylePath' => '/skins',
618 'wgStyleSheetPath' => '/skins',
619 'wgSitename' => 'MediaWiki',
620 'wgLanguageCode' => $lang,
621 'wgDBprefix' => $this->db->getType() != 'oracle' ? 'parsertest_' : 'pt_',
622 'wgRawHtml' => isset( $opts['rawhtml'] ),
624 'wgContLang' => null,
625 'wgNamespacesWithSubpages' => array( 0 => isset( $opts['subpage'] ) ),
626 'wgMaxTocLevel' => $maxtoclevel,
627 'wgCapitalLinks' => true,
628 'wgNoFollowLinks' => true,
629 'wgNoFollowDomainExceptions' => array(),
630 'wgThumbnailScriptPath' => false,
631 'wgUseImageResize' => false,
632 'wgUseTeX' => isset( $opts['math'] ),
633 'wgMathDirectory' => $this->uploadDir . '/math',
634 'wgLocaltimezone' => 'UTC',
635 'wgAllowExternalImages' => true,
636 'wgUseTidy' => false,
637 'wgDefaultLanguageVariant' => $variant,
638 'wgVariantArticlePath' => false,
639 'wgGroupPermissions' => array( '*' => array(
640 'createaccount' => true,
643 'createpage' => true,
644 'createtalk' => true,
646 'wgNamespaceProtection' => array( NS_MEDIAWIKI => 'editinterface' ),
647 'wgDefaultExternalStore' => array(),
648 'wgForeignFileRepos' => array(),
649 'wgLinkHolderBatchSize' => $linkHolderBatchSize,
650 'wgExperimentalHtmlIds' => false,
651 'wgExternalLinkTarget' => false,
652 'wgAlwaysUseTidy' => false,
654 'wgWellFormedXml' => true,
655 'wgAllowMicrodataAttributes' => true,
659 $configLines = explode( "\n", $config );
661 foreach ( $configLines as $line ) {
662 list( $var, $value ) = explode( '=', $line, 2 );
664 $settings[$var] = eval( "return $value;" );
668 $this->savedGlobals = array();
670 foreach ( $settings as $var => $val ) {
671 if ( array_key_exists( $var, $GLOBALS ) ) {
672 $this->savedGlobals[$var] = $GLOBALS[$var];
675 $GLOBALS[$var] = $val;
678 $langObj = Language::factory( $lang );
679 $GLOBALS['wgLang'] = $langObj;
680 $GLOBALS['wgContLang'] = $langObj;
681 $GLOBALS['wgMemc'] = new FakeMemCachedClient;
682 $GLOBALS['wgOut'] = new OutputPage;
686 $wgHooks['ParserTestParser'][] = 'ParserTestParserHook::setup';
687 $wgHooks['ParserTestParser'][] = 'ParserTestStaticParserHook::setup';
688 $wgHooks['ParserGetVariableValueTs'][] = 'ParserTest::getFakeTimestamp';
690 MagicWord::clearCache();
693 $wgUser = new User();
697 * List of temporary tables to create, without prefix.
698 * Some of these probably aren't necessary.
700 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( $this->db->getType(), 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() {
729 if ( $this->databaseSetupDone ) {
733 $this->db = wfGetDB( DB_MASTER );
734 $dbType = $this->db->getType();
736 if ( $wgDBprefix === 'parsertest_' || ( $dbType == 'oracle' && $wgDBprefix === 'pt_' ) ) {
737 throw new MWException( 'setupDatabase should be called before setupGlobals' );
740 $this->databaseSetupDone = true;
741 $this->oldTablePrefix = $wgDBprefix;
743 # SqlBagOStuff broke when using temporary tables on r40209 (bug 15892).
744 # It seems to have been fixed since (r55079?).
745 # If it fails, $wgCaches[CACHE_DB] = new HashBagOStuff(); should work around it.
747 # CREATE TEMPORARY TABLE breaks if there is more than one server
748 if ( wfGetLB()->getServerCount() != 1 ) {
749 $this->useTemporaryTables = false;
752 $temporary = $this->useTemporaryTables || $dbType == 'postgres';
753 $tables = $this->listTables();
755 foreach ( $tables as $tbl ) {
756 # Clean up from previous aborted run. So that table escaping
757 # works correctly across DB engines, we need to change the pre-
758 # fix back and forth so tableName() works right.
759 $this->changePrefix( $this->oldTablePrefix );
760 $oldTableName = $this->db->tableName( $tbl );
761 $this->changePrefix( $dbType != 'oracle' ? 'parsertest_' : 'pt_' );
762 $newTableName = $this->db->tableName( $tbl );
764 if ( $dbType == 'mysql' ) {
765 $this->db->query( "DROP TABLE IF EXISTS $newTableName" );
766 } elseif ( in_array( $dbType, array( 'postgres', 'oracle' ) ) ) {
767 /* DROPs wouldn't work due to Foreign Key Constraints (bug 14990, r58669)
768 * Use "DROP TABLE IF EXISTS $newTableName CASCADE" for postgres? That
769 * syntax would also work for mysql.
771 } elseif ( $this->db->tableExists( $tbl ) ) {
772 $this->db->query( "DROP TABLE $newTableName" );
776 $this->db->duplicateTableStructure( $oldTableName, $newTableName, $temporary );
779 if ( $dbType == 'oracle' )
780 $this->db->query( 'BEGIN FILL_WIKI_INFO; END;' );
782 $this->changePrefix( $dbType != 'oracle' ? 'parsertest_' : 'pt_' );
784 if ( $dbType == 'oracle' ) {
785 # Insert 0 user to prevent FK violations
788 $this->db->insert( 'user', array(
790 'user_name' => 'Anonymous' ) );
793 # Hack: insert a few Wikipedia in-project interwiki prefixes,
794 # for testing inter-language links
795 $this->db->insert( 'interwiki', array(
796 array( 'iw_prefix' => 'wikipedia',
797 'iw_url' => 'http://en.wikipedia.org/wiki/$1',
801 array( 'iw_prefix' => 'meatball',
802 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
806 array( 'iw_prefix' => 'zh',
807 'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
811 array( 'iw_prefix' => 'es',
812 'iw_url' => 'http://es.wikipedia.org/wiki/$1',
816 array( 'iw_prefix' => 'fr',
817 'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
821 array( 'iw_prefix' => 'ru',
822 'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
829 # Update certain things in site_stats
830 $this->db->insert( 'site_stats', array( 'ss_row_id' => 1, 'ss_images' => 2, 'ss_good_articles' => 1 ) );
832 # Reinitialise the LocalisationCache to match the database state
833 Language::getLocalisationCache()->unloadAll();
835 # Make a new message cache
836 global $wgMessageCache, $wgMemc;
837 $wgMessageCache = new MessageCache( $wgMemc, true, 3600 );
839 $this->uploadDir = $this->setupUploadDir();
840 $user = User::createNew( 'WikiSysop' );
841 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Foobar.jpg' ) );
842 $image->recordUpload2( '', 'Upload of some lame file', 'Some lame file', array(
847 'media_type' => MEDIATYPE_BITMAP,
848 'mime' => 'image/jpeg',
849 'metadata' => serialize( array() ),
850 'sha1' => wfBaseConvert( '', 16, 36, 31 ),
852 ), $this->db->timestamp( '20010115123500' ), $user );
854 # This image will be blacklisted in [[MediaWiki:Bad image list]]
855 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Bad.jpg' ) );
856 $image->recordUpload2( '', 'zomgnotcensored', 'Borderline image', array(
861 'media_type' => MEDIATYPE_BITMAP,
862 'mime' => 'image/jpeg',
863 'metadata' => serialize( array() ),
864 'sha1' => wfBaseConvert( '', 16, 36, 31 ),
866 ), $this->db->timestamp( '20010115123500' ), $user );
870 * Change the table prefix on all open DB connections/
872 protected function changePrefix( $prefix ) {
874 wfGetLBFactory()->forEachLB( array( $this, 'changeLBPrefix' ), array( $prefix ) );
875 $wgDBprefix = $prefix;
878 public function changeLBPrefix( $lb, $prefix ) {
879 $lb->forEachOpenConnection( array( $this, 'changeDBPrefix' ), array( $prefix ) );
882 public function changeDBPrefix( $db, $prefix ) {
883 $db->tablePrefix( $prefix );
886 public function teardownDatabase() {
887 if ( !$this->databaseSetupDone ) {
888 $this->teardownGlobals();
891 $this->teardownUploadDir( $this->uploadDir );
893 $this->changePrefix( $this->oldTablePrefix );
894 $this->databaseSetupDone = false;
896 if ( $this->useTemporaryTables ) {
897 # Don't need to do anything
898 $this->teardownGlobals();
902 $tables = $this->listTables();
904 foreach ( $tables as $table ) {
905 $sql = $this->db->getType() == 'oracle' ? "DROP TABLE pt_$table DROP CONSTRAINTS" : "DROP TABLE `parsertest_$table`";
906 $this->db->query( $sql );
909 if ( $this->db->getType() == 'oracle' )
910 $this->db->query( 'BEGIN FILL_WIKI_INFO; END;' );
912 $this->teardownGlobals();
916 * Create a dummy uploads directory which will contain a couple
917 * of files in order to pass existence tests.
919 * @return String: the directory
921 private function setupUploadDir() {
924 if ( $this->keepUploads ) {
925 $dir = wfTempDir() . '/mwParser-images';
927 if ( is_dir( $dir ) ) {
931 $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
934 // wfDebug( "Creating upload directory $dir\n" );
935 if ( file_exists( $dir ) ) {
936 wfDebug( "Already exists!\n" );
940 wfMkdirParents( $dir . '/3/3a' );
941 copy( "$IP/skins/monobook/headbg.jpg", "$dir/3/3a/Foobar.jpg" );
942 wfMkdirParents( $dir . '/0/09' );
943 copy( "$IP/skins/monobook/headbg.jpg", "$dir/0/09/Bad.jpg" );
949 * Restore default values and perform any necessary clean-up
950 * after each test runs.
952 private function teardownGlobals() {
953 RepoGroup::destroySingleton();
954 LinkCache::singleton()->clear();
956 foreach ( $this->savedGlobals as $var => $val ) {
957 $GLOBALS[$var] = $val;
962 * Remove the dummy uploads directory
964 private function teardownUploadDir( $dir ) {
965 if ( $this->keepUploads ) {
969 // delete the files first, then the dirs.
972 "$dir/3/3a/Foobar.jpg",
973 "$dir/thumb/3/3a/Foobar.jpg/180px-Foobar.jpg",
974 "$dir/thumb/3/3a/Foobar.jpg/200px-Foobar.jpg",
975 "$dir/thumb/3/3a/Foobar.jpg/640px-Foobar.jpg",
976 "$dir/thumb/3/3a/Foobar.jpg/120px-Foobar.jpg",
980 "$dir/math/f/a/5/fa50b8b616463173474302ca3e63586b.png",
990 "$dir/thumb/3/3a/Foobar.jpg",
1007 * Delete the specified files, if they exist.
1008 * @param $files Array: full paths to files to delete.
1010 private static function deleteFiles( $files ) {
1011 foreach ( $files as $file ) {
1012 if ( file_exists( $file ) ) {
1019 * Delete the specified directories, if they exist. Must be empty.
1020 * @param $dirs Array: full paths to directories to delete.
1022 private static function deleteDirs( $dirs ) {
1023 foreach ( $dirs as $dir ) {
1024 if ( is_dir( $dir ) ) {
1031 * "Running test $desc..."
1033 protected function showTesting( $desc ) {
1034 print "Running test $desc... ";
1038 * Print a happy success message.
1040 * @param $desc String: the test name
1043 protected function showSuccess( $desc ) {
1044 if ( $this->showProgress ) {
1045 print $this->term->color( '1;32' ) . 'PASSED' . $this->term->reset() . "\n";
1052 * Print a failure message and provide some explanatory output
1053 * about what went wrong if so configured.
1055 * @param $desc String: the test name
1056 * @param $result String: expected HTML output
1057 * @param $html String: actual HTML output
1060 protected function showFailure( $desc, $result, $html ) {
1061 if ( $this->showFailure ) {
1062 if ( !$this->showProgress ) {
1063 # In quiet mode we didn't show the 'Testing' message before the
1064 # test, in case it succeeded. Show it now:
1065 $this->showTesting( $desc );
1068 print $this->term->color( '31' ) . 'FAILED!' . $this->term->reset() . "\n";
1070 if ( $this->showOutput ) {
1071 print "--- Expected ---\n$result\n--- Actual ---\n$html\n";
1074 if ( $this->showDiffs ) {
1075 print $this->quickDiff( $result, $html );
1076 if ( !$this->wellFormed( $html ) ) {
1077 print "XML error: $this->mXmlError\n";
1086 * Run given strings through a diff and return the (colorized) output.
1087 * Requires writable /tmp directory and a 'diff' command in the PATH.
1089 * @param $input String
1090 * @param $output String
1091 * @param $inFileTail String: tailing for the input file name
1092 * @param $outFileTail String: tailing for the output file name
1095 protected function quickDiff( $input, $output, $inFileTail = 'expected', $outFileTail = 'actual' ) {
1096 $prefix = wfTempDir() . "/mwParser-" . mt_rand();
1098 $infile = "$prefix-$inFileTail";
1099 $this->dumpToFile( $input, $infile );
1101 $outfile = "$prefix-$outFileTail";
1102 $this->dumpToFile( $output, $outfile );
1104 $diff = `diff -au $infile $outfile`;
1108 return $this->colorDiff( $diff );
1112 * Write the given string to a file, adding a final newline.
1114 * @param $data String
1115 * @param $filename String
1117 private function dumpToFile( $data, $filename ) {
1118 $file = fopen( $filename, "wt" );
1119 fwrite( $file, $data . "\n" );
1124 * Colorize unified diff output if set for ANSI color output.
1125 * Subtractions are colored blue, additions red.
1127 * @param $text String
1130 protected function colorDiff( $text ) {
1131 return preg_replace(
1132 array( '/^(-.*)$/m', '/^(\+.*)$/m' ),
1133 array( $this->term->color( 34 ) . '$1' . $this->term->reset(),
1134 $this->term->color( 31 ) . '$1' . $this->term->reset() ),
1139 * Show "Reading tests from ..."
1141 * @param $path String
1143 public function showRunFile( $path ) {
1144 print $this->term->color( 1 ) .
1145 "Reading tests from \"$path\"..." .
1146 $this->term->reset() .
1151 * Insert a temporary test article
1152 * @param $name String: the title, including any prefix
1153 * @param $text String: the article text
1154 * @param $line Integer: the input line number, for reporting errors
1156 static public function addArticle( $name, $text, $line = 'unknown' ) {
1157 global $wgCapitalLinks;
1159 $text = self::chomp($text);
1161 $oldCapitalLinks = $wgCapitalLinks;
1162 $wgCapitalLinks = true; // We only need this from SetupGlobals() See r70917#c8637
1164 $name = self::chomp( $name );
1165 $title = Title::newFromText( $name );
1167 if ( is_null( $title ) ) {
1168 wfDie( "invalid title ('$name' => '$title') at line $line\n" );
1171 $aid = $title->getArticleID( Title::GAID_FOR_UPDATE );
1174 debug_print_backtrace();
1175 wfDie( "duplicate article '$name' at line $line\n" );
1178 $art = new Article( $title );
1179 $art->doEdit( $text, '', EDIT_NEW );
1181 $wgCapitalLinks = $oldCapitalLinks;
1185 * Steal a callback function from the primary parser, save it for
1186 * application to our scary parser. If the hook is not installed,
1187 * abort processing of this file.
1189 * @param $name String
1190 * @return Bool true if tag hook is present
1192 public function requireHook( $name ) {
1195 $wgParser->firstCallInit( ); // make sure hooks are loaded.
1197 if ( isset( $wgParser->mTagHooks[$name] ) ) {
1198 $this->hooks[$name] = $wgParser->mTagHooks[$name];
1200 echo " This test suite requires the '$name' hook extension, skipping.\n";
1208 * Steal a callback function from the primary parser, save it for
1209 * application to our scary parser. If the hook is not installed,
1210 * abort processing of this file.
1212 * @param $name String
1213 * @return Bool true if function hook is present
1215 public function requireFunctionHook( $name ) {
1218 $wgParser->firstCallInit( ); // make sure hooks are loaded.
1220 if ( isset( $wgParser->mFunctionHooks[$name] ) ) {
1221 $this->functionHooks[$name] = $wgParser->mFunctionHooks[$name];
1223 echo " This test suite requires the '$name' function hook extension, skipping.\n";
1231 * Run the "tidy" command on text if the $wgUseTidy
1234 * @param $text String: the text to tidy
1238 private function tidy( $text ) {
1242 $text = MWTidy::tidy( $text );
1248 private function wellFormed( $text ) {
1250 Sanitizer::hackDocType() .
1255 $parser = xml_parser_create( "UTF-8" );
1257 # case folding violates XML standard, turn it off
1258 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
1260 if ( !xml_parse( $parser, $html, true ) ) {
1261 $err = xml_error_string( xml_get_error_code( $parser ) );
1262 $position = xml_get_current_byte_index( $parser );
1263 $fragment = $this->extractFragment( $html, $position );
1264 $this->mXmlError = "$err at byte $position:\n$fragment";
1265 xml_parser_free( $parser );
1270 xml_parser_free( $parser );
1275 private function extractFragment( $text, $position ) {
1276 $start = max( 0, $position - 10 );
1277 $before = $position - $start;
1279 $this->term->color( 34 ) .
1280 substr( $text, $start, $before ) .
1281 $this->term->color( 0 ) .
1282 $this->term->color( 31 ) .
1283 $this->term->color( 1 ) .
1284 substr( $text, $position, 1 ) .
1285 $this->term->color( 0 ) .
1286 $this->term->color( 34 ) .
1287 substr( $text, $position + 1, 9 ) .
1288 $this->term->color( 0 ) .
1290 $display = str_replace( "\n", ' ', $fragment );
1292 str_repeat( ' ', $before ) .
1293 $this->term->color( 31 ) .
1295 $this->term->color( 0 );
1297 return "$display\n$caret";
1300 static function getFakeTimestamp( &$parser, &$ts ) {