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
58 * Database clone helper
64 * string $oldTablePrefix Original table prefix
66 private $oldTablePrefix;
68 private $maxFuzzTestLength = 300;
69 private $fuzzSeed = 0;
70 private $memoryLimit = 50;
71 private $uploadDir = null;
74 private $savedGlobals = array();
76 * Sets terminal colorization and diff/quick modes depending on OS and
77 * command-line options (--color and --quick).
79 public function __construct( $options = array() ) {
80 # Only colorize output if stdout is a terminal.
81 $this->color = !wfIsWindows() && Maintenance::posix_isatty( 1 );
83 if ( isset( $options['color'] ) ) {
84 switch( $options['color'] ) {
95 $this->term = $this->color
96 ? new AnsiTermColorer()
97 : new DummyTermColorer();
99 $this->showDiffs = !isset( $options['quick'] );
100 $this->showProgress = !isset( $options['quiet'] );
101 $this->showFailure = !(
102 isset( $options['quiet'] )
103 && ( isset( $options['record'] )
104 || isset( $options['compare'] ) ) ); // redundant output
106 $this->showOutput = isset( $options['show-output'] );
109 if ( isset( $options['regex'] ) ) {
110 if ( isset( $options['record'] ) ) {
111 echo "Warning: --record cannot be used with --regex, disabling --record\n";
112 unset( $options['record'] );
114 $this->regex = $options['regex'];
120 $this->setupRecorder( $options );
121 $this->keepUploads = isset( $options['keep-uploads'] );
123 if ( isset( $options['seed'] ) ) {
124 $this->fuzzSeed = intval( $options['seed'] ) - 1;
127 $this->runDisabled = isset( $options['run-disabled'] );
129 $this->hooks = array();
130 $this->functionHooks = array();
134 static function setUp() {
135 global $wgParser, $wgParserConf, $IP, $messageMemc, $wgMemc,
136 $wgUser, $wgLang, $wgOut, $wgRequest, $wgStyleDirectory, $wgEnableParserCache,
137 $wgNamespaceAliases, $wgNamespaceProtection, $wgLocalFileRepo,
138 $parserMemc, $wgThumbnailScriptPath, $wgScriptPath,
139 $wgArticlePath, $wgStyleSheetPath, $wgScript, $wgStylePath, $wgExtensionAssetsPath,
140 $wgMainCacheType, $wgMessageCacheType, $wgParserCacheType;
142 $wgScript = '/index.php';
144 $wgArticlePath = '/wiki/$1';
145 $wgStyleSheetPath = '/skins';
146 $wgStylePath = '/skins';
147 $wgExtensionAssetsPath = '/extensions';
148 $wgThumbnailScriptPath = false;
149 $wgLocalFileRepo = array(
150 'class' => 'LocalRepo',
152 'directory' => wfTempDir() . '/test-repo',
153 'url' => 'http://example.com/images',
154 'deletedDir' => wfTempDir() . '/test-repo/delete',
156 'transformVia404' => false,
158 $wgNamespaceProtection[NS_MEDIAWIKI] = 'editinterface';
159 $wgNamespaceAliases['Image'] = NS_FILE;
160 $wgNamespaceAliases['Image_talk'] = NS_FILE_TALK;
162 // XXX: tests won't run without this (for CACHE_DB)
163 if ( $wgMainCacheType === CACHE_DB ) {
164 $wgMainCacheType = CACHE_NONE;
166 if ( $wgMessageCacheType === CACHE_DB ) {
167 $wgMessageCacheType = CACHE_NONE;
169 if ( $wgParserCacheType === CACHE_DB ) {
170 $wgParserCacheType = CACHE_NONE;
173 $wgEnableParserCache = false;
174 DeferredUpdates::clearPendingUpdates();
175 $wgMemc = wfGetMainCache(); // checks $wgMainCacheType
176 $messageMemc = wfGetMessageCacheStorage();
177 $parserMemc = wfGetParserCacheStorage();
179 // $wgContLang = new StubContLang;
181 $context = new RequestContext;
182 $wgLang = $context->getLang();
183 $wgOut = $context->getOutput();
184 $wgParser = new StubObject( 'wgParser', $wgParserConf['class'], array( $wgParserConf ) );
185 $wgRequest = $context->getRequest();
187 if ( $wgStyleDirectory === false ) {
188 $wgStyleDirectory = "$IP/skins";
193 public function setupRecorder ( $options ) {
194 if ( isset( $options['record'] ) ) {
195 $this->recorder = new DbTestRecorder( $this );
196 $this->recorder->version = isset( $options['setversion'] ) ?
197 $options['setversion'] : SpecialVersion::getVersion();
198 } elseif ( isset( $options['compare'] ) ) {
199 $this->recorder = new DbTestPreviewer( $this );
201 $this->recorder = new TestRecorder( $this );
206 * Remove last character if it is a newline
209 static public function chomp( $s ) {
210 if ( substr( $s, -1 ) === "\n" ) {
211 return substr( $s, 0, -1 );
219 * Run a fuzz test series
220 * Draw input from a set of test files
222 function fuzzTest( $filenames ) {
223 $GLOBALS['wgContLang'] = Language::factory( 'en' );
224 $dict = $this->getFuzzInput( $filenames );
225 $dictSize = strlen( $dict );
226 $logMaxLength = log( $this->maxFuzzTestLength );
227 $this->setupDatabase();
228 ini_set( 'memory_limit', $this->memoryLimit * 1048576 );
233 $opts = ParserOptions::newFromUser( $user );
234 $title = Title::makeTitle( NS_MAIN, 'Parser_test' );
237 // Generate test input
238 mt_srand( ++$this->fuzzSeed );
239 $totalLength = mt_rand( 1, $this->maxFuzzTestLength );
242 while ( strlen( $input ) < $totalLength ) {
243 $logHairLength = mt_rand( 0, 1000000 ) / 1000000 * $logMaxLength;
244 $hairLength = min( intval( exp( $logHairLength ) ), $dictSize );
245 $offset = mt_rand( 0, $dictSize - $hairLength );
246 $input .= substr( $dict, $offset, $hairLength );
249 $this->setupGlobals();
250 $parser = $this->getParser();
254 $parser->parse( $input, $title, $opts );
256 } catch ( Exception $exception ) {
261 echo "Test failed with seed {$this->fuzzSeed}\n";
263 printf( "string(%d) \"%s\"\n\n", strlen( $input ), $input );
270 $this->teardownGlobals();
271 $parser->__destruct();
273 if ( $numTotal % 100 == 0 ) {
274 $usage = intval( memory_get_usage( true ) / $this->memoryLimit / 1048576 * 100 );
275 echo "{$this->fuzzSeed}: $numSuccess/$numTotal (mem: $usage%)\n";
277 echo "Out of memory:\n";
278 $memStats = $this->getMemoryBreakdown();
280 foreach ( $memStats as $name => $usage ) {
281 echo "$name: $usage\n";
290 * Get an input dictionary from a set of parser test files
292 function getFuzzInput( $filenames ) {
295 foreach ( $filenames as $filename ) {
296 $contents = file_get_contents( $filename );
297 preg_match_all( '/!!\s*input\n(.*?)\n!!\s*result/s', $contents, $matches );
299 foreach ( $matches[1] as $match ) {
300 $dict .= $match . "\n";
308 * Get a memory usage breakdown
310 function getMemoryBreakdown() {
313 foreach ( $GLOBALS as $name => $value ) {
314 $memStats['$' . $name] = strlen( serialize( $value ) );
317 $classes = get_declared_classes();
319 foreach ( $classes as $class ) {
320 $rc = new ReflectionClass( $class );
321 $props = $rc->getStaticProperties();
322 $memStats[$class] = strlen( serialize( $props ) );
323 $methods = $rc->getMethods();
325 foreach ( $methods as $method ) {
326 $memStats[$class] += strlen( serialize( $method->getStaticVariables() ) );
330 $functions = get_defined_functions();
332 foreach ( $functions['user'] as $function ) {
333 $rf = new ReflectionFunction( $function );
334 $memStats["$function()"] = strlen( serialize( $rf->getStaticVariables() ) );
347 * Run a series of tests listed in the given text files.
348 * Each test consists of a brief description, wikitext input,
349 * and the expected HTML output.
351 * Prints status updates on stdout and counts up the total
352 * number and percentage of passed tests.
354 * @param $filenames Array of strings
355 * @return Boolean: true if passed all tests, false if any tests failed.
357 public function runTestsFromFiles( $filenames ) {
359 $GLOBALS['wgContLang'] = Language::factory( 'en' );
360 $this->recorder->start();
362 $this->setupDatabase();
365 foreach ( $filenames as $filename ) {
366 $tests = new TestFileIterator( $filename, $this );
367 $ok = $this->runTests( $tests ) && $ok;
370 $this->teardownDatabase();
371 $this->recorder->report();
372 } catch (DBError $e) {
373 echo $e->getMessage();
375 $this->recorder->end();
380 function runTests( $tests ) {
383 foreach ( $tests as $t ) {
385 $this->runTest( $t['test'], $t['input'], $t['result'], $t['options'], $t['config'] );
386 $ok = $ok && $result;
387 $this->recorder->record( $t['test'], $result );
390 if ( $this->showProgress ) {
398 * Get a Parser object
400 function getParser( $preprocessor = null ) {
401 global $wgParserConf;
403 $class = $wgParserConf['class'];
404 $parser = new $class( array( 'preprocessorClass' => $preprocessor ) + $wgParserConf );
406 foreach ( $this->hooks as $tag => $callback ) {
407 $parser->setHook( $tag, $callback );
410 foreach ( $this->functionHooks as $tag => $bits ) {
411 list( $callback, $flags ) = $bits;
412 $parser->setFunctionHook( $tag, $callback, $flags );
415 wfRunHooks( 'ParserTestParser', array( &$parser ) );
421 * Run a given wikitext input through a freshly-constructed wiki parser,
422 * and compare the output against the expected results.
423 * Prints status and explanatory messages to stdout.
425 * @param $desc String: test's description
426 * @param $input String: wikitext to try rendering
427 * @param $result String: result to output
428 * @param $opts Array: test's options
429 * @param $config String: overrides for global variables, one per line
432 public function runTest( $desc, $input, $result, $opts, $config ) {
433 if ( $this->showProgress ) {
434 $this->showTesting( $desc );
437 $opts = $this->parseOptions( $opts );
438 $this->setupGlobals( $opts, $config );
441 $options = ParserOptions::newFromUser( $user );
443 if ( isset( $opts['title'] ) ) {
444 $titleText = $opts['title'];
447 $titleText = 'Parser test';
450 $local = isset( $opts['local'] );
451 $preprocessor = isset( $opts['preprocessor'] ) ? $opts['preprocessor'] : null;
452 $parser = $this->getParser( $preprocessor );
453 $title = Title::newFromText( $titleText );
455 if ( isset( $opts['pst'] ) ) {
456 $out = $parser->preSaveTransform( $input, $title, $user, $options );
457 } elseif ( isset( $opts['msg'] ) ) {
458 $out = $parser->transformMsg( $input, $options, $title );
459 } elseif ( isset( $opts['section'] ) ) {
460 $section = $opts['section'];
461 $out = $parser->getSection( $input, $section );
462 } elseif ( isset( $opts['replace'] ) ) {
463 $section = $opts['replace'][0];
464 $replace = $opts['replace'][1];
465 $out = $parser->replaceSection( $input, $section, $replace );
466 } elseif ( isset( $opts['comment'] ) ) {
467 $out = Linker::formatComment( $input, $title, $local );
468 } elseif ( isset( $opts['preload'] ) ) {
469 $out = $parser->getpreloadText( $input, $title, $options );
471 $output = $parser->parse( $input, $title, $options, true, true, 1337 );
472 $out = $output->getText();
474 if ( isset( $opts['showtitle'] ) ) {
475 if ( $output->getTitleText() ) {
476 $title = $output->getTitleText();
479 $out = "$title\n$out";
482 if ( isset( $opts['ill'] ) ) {
483 $out = $this->tidy( implode( ' ', $output->getLanguageLinks() ) );
484 } elseif ( isset( $opts['cat'] ) ) {
487 $wgOut->addCategoryLinks( $output->getCategories() );
488 $cats = $wgOut->getCategoryLinks();
490 if ( isset( $cats['normal'] ) ) {
491 $out = $this->tidy( implode( ' ', $cats['normal'] ) );
497 $result = $this->tidy( $result );
500 $this->teardownGlobals();
501 return $this->showTestResult( $desc, $result, $out );
507 function showTestResult( $desc, $result, $out ) {
508 if ( $result === $out ) {
509 $this->showSuccess( $desc );
512 $this->showFailure( $desc, $result, $out );
518 * Use a regex to find out the value of an option
519 * @param $key String: name of option val to retrieve
520 * @param $opts Options array to look in
521 * @param $default Mixed: default value returned if not found
523 private static function getOptionValue( $key, $opts, $default ) {
524 $key = strtolower( $key );
526 if ( isset( $opts[$key] ) ) {
533 private function parseOptions( $instring ) {
539 // foo=bar,"baz quux"
563 \[\[[^]]*\]\] # Link target
571 if ( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER ) ) {
572 foreach ( $matches as $bits ) {
573 array_shift( $bits );
574 $key = strtolower( array_shift( $bits ) );
575 if ( count( $bits ) == 0 ) {
577 } elseif ( count( $bits ) == 1 ) {
578 $opts[$key] = $this->cleanupOption( array_shift( $bits ) );
581 $opts[$key] = array_map( array( $this, 'cleanupOption' ), $bits );
588 private function cleanupOption( $opt ) {
589 if ( substr( $opt, 0, 1 ) == '"' ) {
590 return substr( $opt, 1, -1 );
593 if ( substr( $opt, 0, 2 ) == '[[' ) {
594 return substr( $opt, 2, -2 );
600 * Set up the global variables for a consistent environment for each test.
601 * Ideally this should replace the global configuration entirely.
603 private function setupGlobals( $opts = '', $config = '' ) {
604 # Find out values for some special options.
606 self::getOptionValue( 'language', $opts, 'en' );
608 self::getOptionValue( 'variant', $opts, false );
610 self::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
611 $linkHolderBatchSize =
612 self::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
615 'wgServer' => 'http://Britney-Spears',
616 'wgScript' => '/index.php',
617 'wgScriptPath' => '/',
618 'wgArticlePath' => '/wiki/$1',
619 'wgActionPaths' => array(),
620 'wgLocalFileRepo' => array(
621 'class' => 'LocalRepo',
623 'directory' => $this->uploadDir,
624 'url' => 'http://example.com/images',
626 'transformVia404' => false,
628 'wgEnableUploads' => self::getOptionValue( 'wgEnableUploads', $opts, true ),
629 'wgStylePath' => '/skins',
630 'wgStyleSheetPath' => '/skins',
631 'wgSitename' => 'MediaWiki',
632 'wgLanguageCode' => $lang,
633 'wgDBprefix' => $this->db->getType() != 'oracle' ? 'parsertest_' : 'pt_',
634 'wgRawHtml' => isset( $opts['rawhtml'] ),
636 'wgContLang' => null,
637 'wgNamespacesWithSubpages' => array( 0 => isset( $opts['subpage'] ) ),
638 'wgMaxTocLevel' => $maxtoclevel,
639 'wgCapitalLinks' => true,
640 'wgNoFollowLinks' => true,
641 'wgNoFollowDomainExceptions' => array(),
642 'wgThumbnailScriptPath' => false,
643 'wgUseImageResize' => false,
644 'wgLocaltimezone' => 'UTC',
645 'wgAllowExternalImages' => true,
646 'wgUseTidy' => false,
647 'wgDefaultLanguageVariant' => $variant,
648 'wgVariantArticlePath' => false,
649 'wgGroupPermissions' => array( '*' => array(
650 'createaccount' => true,
653 'createpage' => true,
654 'createtalk' => true,
656 'wgNamespaceProtection' => array( NS_MEDIAWIKI => 'editinterface' ),
657 'wgDefaultExternalStore' => array(),
658 'wgForeignFileRepos' => array(),
659 'wgLinkHolderBatchSize' => $linkHolderBatchSize,
660 'wgExperimentalHtmlIds' => false,
661 'wgExternalLinkTarget' => false,
662 'wgAlwaysUseTidy' => false,
664 'wgCleanupPresentationalAttributes' => true,
665 'wgWellFormedXml' => true,
666 'wgAllowMicrodataAttributes' => true,
667 'wgAdaptiveMessageCache' => true,
668 'wgDisableLangConversion' => false,
669 'wgDisableTitleConversion' => false,
673 $configLines = explode( "\n", $config );
675 foreach ( $configLines as $line ) {
676 list( $var, $value ) = explode( '=', $line, 2 );
678 $settings[$var] = eval( "return $value;" );
682 $this->savedGlobals = array();
684 foreach ( $settings as $var => $val ) {
685 if ( array_key_exists( $var, $GLOBALS ) ) {
686 $this->savedGlobals[$var] = $GLOBALS[$var];
689 $GLOBALS[$var] = $val;
692 $GLOBALS['wgContLang'] = Language::factory( $lang );
693 $GLOBALS['wgMemc'] = new EmptyBagOStuff;
695 $context = new RequestContext();
696 $GLOBALS['wgLang'] = $context->getLang();
697 $GLOBALS['wgOut'] = $context->getOutput();
699 $GLOBALS['wgUser'] = new User();
703 $wgHooks['ParserTestParser'][] = 'ParserTestParserHook::setup';
704 $wgHooks['ParserGetVariableValueTs'][] = 'ParserTest::getFakeTimestamp';
706 MagicWord::clearCache();
710 * List of temporary tables to create, without prefix.
711 * Some of these probably aren't necessary.
713 private function listTables() {
714 $tables = array( 'user', 'user_properties', 'page', 'page_restrictions',
715 'protected_titles', 'revision', 'text', 'pagelinks', 'imagelinks',
716 'categorylinks', 'templatelinks', 'externallinks', 'langlinks', 'iwlinks',
717 'site_stats', 'hitcounter', 'ipblocks', 'image', 'oldimage',
718 'recentchanges', 'watchlist', 'interwiki', 'logging',
719 'querycache', 'objectcache', 'job', 'l10n_cache', 'redirect', 'querycachetwo',
720 'archive', 'user_groups', 'page_props', 'category', 'msg_resource', 'msg_resource_links'
723 if ( in_array( $this->db->getType(), array( 'mysql', 'sqlite', 'oracle' ) ) ) {
724 array_push( $tables, 'searchindex' );
727 // Allow extensions to add to the list of tables to duplicate;
728 // may be necessary if they hook into page save or other code
729 // which will require them while running tests.
730 wfRunHooks( 'ParserTestTables', array( &$tables ) );
736 * Set up a temporary set of wiki tables to work with for the tests.
737 * Currently this will only be done once per run, and any changes to
738 * the db will be visible to later tests in the run.
740 public function setupDatabase() {
743 if ( $this->databaseSetupDone ) {
747 $this->db = wfGetDB( DB_MASTER );
748 $dbType = $this->db->getType();
750 if ( $wgDBprefix === 'parsertest_' || ( $dbType == 'oracle' && $wgDBprefix === 'pt_' ) ) {
751 throw new MWException( 'setupDatabase should be called before setupGlobals' );
754 $this->databaseSetupDone = true;
755 $this->oldTablePrefix = $wgDBprefix;
757 # SqlBagOStuff broke when using temporary tables on r40209 (bug 15892).
758 # It seems to have been fixed since (r55079?), but regressed at some point before r85701.
759 # This works around it for now...
760 ObjectCache::$instances[CACHE_DB] = new HashBagOStuff;
762 # CREATE TEMPORARY TABLE breaks if there is more than one server
763 if ( wfGetLB()->getServerCount() != 1 ) {
764 $this->useTemporaryTables = false;
767 $temporary = $this->useTemporaryTables || $dbType == 'postgres';
768 $tables = $this->listTables();
769 $prefix = $dbType != 'oracle' ? 'parsertest_' : 'pt_';
771 $this->dbClone = new CloneDatabase( $this->db, $this->listTables(), $prefix );
772 $this->dbClone->useTemporaryTables( $temporary );
773 $this->dbClone->cloneTableStructure();
775 if ( $dbType == 'oracle' ) {
776 $this->db->query( 'BEGIN FILL_WIKI_INFO; END;' );
777 # Insert 0 user to prevent FK violations
780 $this->db->insert( 'user', array(
782 'user_name' => 'Anonymous' ) );
785 # Hack: insert a few Wikipedia in-project interwiki prefixes,
786 # for testing inter-language links
787 $this->db->insert( 'interwiki', array(
788 array( 'iw_prefix' => 'wikipedia',
789 'iw_url' => 'http://en.wikipedia.org/wiki/$1',
793 array( 'iw_prefix' => 'meatball',
794 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
798 array( 'iw_prefix' => 'zh',
799 'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
803 array( 'iw_prefix' => 'es',
804 'iw_url' => 'http://es.wikipedia.org/wiki/$1',
808 array( 'iw_prefix' => 'fr',
809 'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
813 array( 'iw_prefix' => 'ru',
814 'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
821 # Update certain things in site_stats
822 $this->db->insert( 'site_stats', array( 'ss_row_id' => 1, 'ss_images' => 2, 'ss_good_articles' => 1 ) );
824 # Reinitialise the LocalisationCache to match the database state
825 Language::getLocalisationCache()->unloadAll();
827 # Clear the message cache
828 MessageCache::singleton()->clear();
830 $this->uploadDir = $this->setupUploadDir();
831 $user = User::createNew( 'WikiSysop' );
832 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Foobar.jpg' ) );
833 $image->recordUpload2( '', 'Upload of some lame file', 'Some lame file', array(
838 'media_type' => MEDIATYPE_BITMAP,
839 'mime' => 'image/jpeg',
840 'metadata' => serialize( array() ),
841 'sha1' => wfBaseConvert( '', 16, 36, 31 ),
843 ), $this->db->timestamp( '20010115123500' ), $user );
845 # This image will be blacklisted in [[MediaWiki:Bad image list]]
846 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Bad.jpg' ) );
847 $image->recordUpload2( '', 'zomgnotcensored', 'Borderline image', array(
852 'media_type' => MEDIATYPE_BITMAP,
853 'mime' => 'image/jpeg',
854 'metadata' => serialize( array() ),
855 'sha1' => wfBaseConvert( '', 16, 36, 31 ),
857 ), $this->db->timestamp( '20010115123500' ), $user );
860 public function teardownDatabase() {
861 if ( !$this->databaseSetupDone ) {
862 $this->teardownGlobals();
865 $this->teardownUploadDir( $this->uploadDir );
867 $this->dbClone->destroy();
868 $this->databaseSetupDone = false;
870 if ( $this->useTemporaryTables ) {
871 # Don't need to do anything
872 $this->teardownGlobals();
876 $tables = $this->listTables();
878 foreach ( $tables as $table ) {
879 $sql = $this->db->getType() == 'oracle' ? "DROP TABLE pt_$table DROP CONSTRAINTS" : "DROP TABLE `parsertest_$table`";
880 $this->db->query( $sql );
883 if ( $this->db->getType() == 'oracle' )
884 $this->db->query( 'BEGIN FILL_WIKI_INFO; END;' );
886 $this->teardownGlobals();
890 * Create a dummy uploads directory which will contain a couple
891 * of files in order to pass existence tests.
893 * @return String: the directory
895 private function setupUploadDir() {
898 if ( $this->keepUploads ) {
899 $dir = wfTempDir() . '/mwParser-images';
901 if ( is_dir( $dir ) ) {
905 $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
908 // wfDebug( "Creating upload directory $dir\n" );
909 if ( file_exists( $dir ) ) {
910 wfDebug( "Already exists!\n" );
914 wfMkdirParents( $dir . '/3/3a', null, __METHOD__ );
915 copy( "$IP/skins/monobook/headbg.jpg", "$dir/3/3a/Foobar.jpg" );
916 wfMkdirParents( $dir . '/0/09', null, __METHOD__ );
917 copy( "$IP/skins/monobook/headbg.jpg", "$dir/0/09/Bad.jpg" );
923 * Restore default values and perform any necessary clean-up
924 * after each test runs.
926 private function teardownGlobals() {
927 RepoGroup::destroySingleton();
928 LinkCache::singleton()->clear();
930 foreach ( $this->savedGlobals as $var => $val ) {
931 $GLOBALS[$var] = $val;
936 * Remove the dummy uploads directory
938 private function teardownUploadDir( $dir ) {
939 if ( $this->keepUploads ) {
943 // delete the files first, then the dirs.
946 "$dir/3/3a/Foobar.jpg",
947 "$dir/thumb/3/3a/Foobar.jpg/180px-Foobar.jpg",
948 "$dir/thumb/3/3a/Foobar.jpg/200px-Foobar.jpg",
949 "$dir/thumb/3/3a/Foobar.jpg/640px-Foobar.jpg",
950 "$dir/thumb/3/3a/Foobar.jpg/120px-Foobar.jpg",
954 "$dir/math/f/a/5/fa50b8b616463173474302ca3e63586b.png",
964 "$dir/thumb/3/3a/Foobar.jpg",
981 * Delete the specified files, if they exist.
982 * @param $files Array: full paths to files to delete.
984 private static function deleteFiles( $files ) {
985 foreach ( $files as $file ) {
986 if ( file_exists( $file ) ) {
993 * Delete the specified directories, if they exist. Must be empty.
994 * @param $dirs Array: full paths to directories to delete.
996 private static function deleteDirs( $dirs ) {
997 foreach ( $dirs as $dir ) {
998 if ( is_dir( $dir ) ) {
1005 * "Running test $desc..."
1007 protected function showTesting( $desc ) {
1008 print "Running test $desc... ";
1012 * Print a happy success message.
1014 * @param $desc String: the test name
1017 protected function showSuccess( $desc ) {
1018 if ( $this->showProgress ) {
1019 print $this->term->color( '1;32' ) . 'PASSED' . $this->term->reset() . "\n";
1026 * Print a failure message and provide some explanatory output
1027 * about what went wrong if so configured.
1029 * @param $desc String: the test name
1030 * @param $result String: expected HTML output
1031 * @param $html String: actual HTML output
1034 protected function showFailure( $desc, $result, $html ) {
1035 if ( $this->showFailure ) {
1036 if ( !$this->showProgress ) {
1037 # In quiet mode we didn't show the 'Testing' message before the
1038 # test, in case it succeeded. Show it now:
1039 $this->showTesting( $desc );
1042 print $this->term->color( '31' ) . 'FAILED!' . $this->term->reset() . "\n";
1044 if ( $this->showOutput ) {
1045 print "--- Expected ---\n$result\n--- Actual ---\n$html\n";
1048 if ( $this->showDiffs ) {
1049 print $this->quickDiff( $result, $html );
1050 if ( !$this->wellFormed( $html ) ) {
1051 print "XML error: $this->mXmlError\n";
1060 * Run given strings through a diff and return the (colorized) output.
1061 * Requires writable /tmp directory and a 'diff' command in the PATH.
1063 * @param $input String
1064 * @param $output String
1065 * @param $inFileTail String: tailing for the input file name
1066 * @param $outFileTail String: tailing for the output file name
1069 protected function quickDiff( $input, $output, $inFileTail = 'expected', $outFileTail = 'actual' ) {
1070 # Windows, or at least the fc utility, is retarded
1071 $slash = wfIsWindows() ? '\\' : '/';
1072 $prefix = wfTempDir() . "{$slash}mwParser-" . mt_rand();
1074 $infile = "$prefix-$inFileTail";
1075 $this->dumpToFile( $input, $infile );
1077 $outfile = "$prefix-$outFileTail";
1078 $this->dumpToFile( $output, $outfile );
1080 $shellInfile = wfEscapeShellArg($infile);
1081 $shellOutfile = wfEscapeShellArg($outfile);
1084 // we assume that people with diff3 also have usual diff
1085 $diff = ( wfIsWindows() && !$wgDiff3 )
1086 ? `fc $shellInfile $shellOutfile`
1087 : `diff -au $shellInfile $shellOutfile`;
1091 return $this->colorDiff( $diff );
1095 * Write the given string to a file, adding a final newline.
1097 * @param $data String
1098 * @param $filename String
1100 private function dumpToFile( $data, $filename ) {
1101 $file = fopen( $filename, "wt" );
1102 fwrite( $file, $data . "\n" );
1107 * Colorize unified diff output if set for ANSI color output.
1108 * Subtractions are colored blue, additions red.
1110 * @param $text String
1113 protected function colorDiff( $text ) {
1114 return preg_replace(
1115 array( '/^(-.*)$/m', '/^(\+.*)$/m' ),
1116 array( $this->term->color( 34 ) . '$1' . $this->term->reset(),
1117 $this->term->color( 31 ) . '$1' . $this->term->reset() ),
1122 * Show "Reading tests from ..."
1124 * @param $path String
1126 public function showRunFile( $path ) {
1127 print $this->term->color( 1 ) .
1128 "Reading tests from \"$path\"..." .
1129 $this->term->reset() .
1134 * Insert a temporary test article
1135 * @param $name String: the title, including any prefix
1136 * @param $text String: the article text
1137 * @param $line Integer: the input line number, for reporting errors
1139 static public function addArticle( $name, $text, $line = 'unknown' ) {
1140 global $wgCapitalLinks;
1142 $text = self::chomp($text);
1144 $oldCapitalLinks = $wgCapitalLinks;
1145 $wgCapitalLinks = true; // We only need this from SetupGlobals() See r70917#c8637
1147 $name = self::chomp( $name );
1148 $title = Title::newFromText( $name );
1150 if ( is_null( $title ) ) {
1151 throw new MWException( "invalid title ('$name' => '$title') at line $line\n" );
1154 $aid = $title->getArticleID( Title::GAID_FOR_UPDATE );
1157 throw new MWException( "duplicate article '$name' at line $line\n" );
1160 $art = new Article( $title );
1161 $art->doEdit( $text, '', EDIT_NEW );
1163 $wgCapitalLinks = $oldCapitalLinks;
1167 * Steal a callback function from the primary parser, save it for
1168 * application to our scary parser. If the hook is not installed,
1169 * abort processing of this file.
1171 * @param $name String
1172 * @return Bool true if tag hook is present
1174 public function requireHook( $name ) {
1177 $wgParser->firstCallInit( ); // make sure hooks are loaded.
1179 if ( isset( $wgParser->mTagHooks[$name] ) ) {
1180 $this->hooks[$name] = $wgParser->mTagHooks[$name];
1182 echo " This test suite requires the '$name' hook extension, skipping.\n";
1190 * Steal a callback function from the primary parser, save it for
1191 * application to our scary parser. If the hook is not installed,
1192 * abort processing of this file.
1194 * @param $name String
1195 * @return Bool true if function hook is present
1197 public function requireFunctionHook( $name ) {
1200 $wgParser->firstCallInit( ); // make sure hooks are loaded.
1202 if ( isset( $wgParser->mFunctionHooks[$name] ) ) {
1203 $this->functionHooks[$name] = $wgParser->mFunctionHooks[$name];
1205 echo " This test suite requires the '$name' function hook extension, skipping.\n";
1213 * Run the "tidy" command on text if the $wgUseTidy
1216 * @param $text String: the text to tidy
1219 private function tidy( $text ) {
1223 $text = MWTidy::tidy( $text );
1229 private function wellFormed( $text ) {
1231 Sanitizer::hackDocType() .
1236 $parser = xml_parser_create( "UTF-8" );
1238 # case folding violates XML standard, turn it off
1239 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
1241 if ( !xml_parse( $parser, $html, true ) ) {
1242 $err = xml_error_string( xml_get_error_code( $parser ) );
1243 $position = xml_get_current_byte_index( $parser );
1244 $fragment = $this->extractFragment( $html, $position );
1245 $this->mXmlError = "$err at byte $position:\n$fragment";
1246 xml_parser_free( $parser );
1251 xml_parser_free( $parser );
1256 private function extractFragment( $text, $position ) {
1257 $start = max( 0, $position - 10 );
1258 $before = $position - $start;
1260 $this->term->color( 34 ) .
1261 substr( $text, $start, $before ) .
1262 $this->term->color( 0 ) .
1263 $this->term->color( 31 ) .
1264 $this->term->color( 1 ) .
1265 substr( $text, $position, 1 ) .
1266 $this->term->color( 0 ) .
1267 $this->term->color( 34 ) .
1268 substr( $text, $position + 1, 9 ) .
1269 $this->term->color( 0 ) .
1271 $display = str_replace( "\n", ' ', $fragment );
1273 str_repeat( ' ', $before ) .
1274 $this->term->color( 31 ) .
1276 $this->term->color( 0 );
1278 return "$display\n$caret";
1281 static function getFakeTimestamp( &$parser, &$ts ) {