2 # Copyright (C) 2004, 2010 Brion Vibber <brion@pobox.com>
3 # http://www.mediawiki.org/
5 # This program is free software; you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 2 of the License, or
8 # (at your option) any later version.
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
15 # You should have received a copy of the GNU General Public License along
16 # with this program; if not, write to the Free Software Foundation, Inc.,
17 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 # http://www.gnu.org/copyleft/gpl.html
21 * @todo Make this more independent of the configuration (and if possible the database)
24 * @ingroup Maintenance
28 * @ingroup Maintenance
32 * boolean $color whereas output should be colorized
37 * boolean $showOutput Show test output
42 * boolean $useTemporaryTables Use temporary tables for the temporary database
44 private $useTemporaryTables = true;
47 * boolean $databaseSetupDone True if the database has been set up
49 private $databaseSetupDone = false;
52 * string $oldTablePrefix Original table prefix
54 private $oldTablePrefix;
56 private $maxFuzzTestLength = 300;
57 private $fuzzSeed = 0;
58 private $memoryLimit = 50;
61 * Sets terminal colorization and diff/quick modes depending on OS and
62 * command-line options (--color and --quick).
64 public function ParserTest( $options = array() ) {
65 # Only colorize output if stdout is a terminal.
66 $this->color = !wfIsWindows() && posix_isatty( 1 );
68 if ( isset( $options['color'] ) ) {
69 switch( $options['color'] ) {
80 $this->term = $this->color
81 ? new AnsiTermColorer()
82 : new DummyTermColorer();
84 $this->showDiffs = !isset( $options['quick'] );
85 $this->showProgress = !isset( $options['quiet'] );
86 $this->showFailure = !(
87 isset( $options['quiet'] )
88 && ( isset( $options['record'] )
89 || isset( $options['compare'] ) ) ); // redundant output
91 $this->showOutput = isset( $options['show-output'] );
94 if ( isset( $options['regex'] ) ) {
95 if ( isset( $options['record'] ) ) {
96 echo "Warning: --record cannot be used with --regex, disabling --record\n";
97 unset( $options['record'] );
99 $this->regex = $options['regex'];
105 $this->setupRecorder( $options );
106 $this->keepUploads = isset( $options['keep-uploads'] );
108 if ( isset( $options['seed'] ) ) {
109 $this->fuzzSeed = intval( $options['seed'] ) - 1;
112 $this->runDisabled = isset( $options['run-disabled'] );
114 $this->hooks = array();
115 $this->functionHooks = array();
118 public function setupRecorder ( $options ) {
119 if ( isset( $options['record'] ) ) {
120 $this->recorder = new DbTestRecorder( $this );
121 $this->recorder->version = isset( $options['setversion'] ) ?
122 $options['setversion'] : SpecialVersion::getVersion();
123 } elseif ( isset( $options['compare'] ) ) {
124 $this->recorder = new DbTestPreviewer( $this );
125 } elseif ( isset( $options['upload'] ) ) {
126 $this->recorder = new RemoteTestRecorder( $this );
128 $this->recorder = new TestRecorder( $this );
133 * Remove last character if it is a newline
135 public function chomp( $s ) {
136 if ( substr( $s, -1 ) === "\n" ) {
137 return substr( $s, 0, -1 );
145 * Run a fuzz test series
146 * Draw input from a set of test files
148 function fuzzTest( $filenames ) {
149 $GLOBALS['wgContLang'] = Language::factory( 'en' );
150 $dict = $this->getFuzzInput( $filenames );
151 $dictSize = strlen( $dict );
152 $logMaxLength = log( $this->maxFuzzTestLength );
153 $this->setupDatabase();
154 ini_set( 'memory_limit', $this->memoryLimit * 1048576 );
159 $opts = ParserOptions::newFromUser( $user );
160 $title = Title::makeTitle( NS_MAIN, 'Parser_test' );
163 // Generate test input
164 mt_srand( ++$this->fuzzSeed );
165 $totalLength = mt_rand( 1, $this->maxFuzzTestLength );
168 while ( strlen( $input ) < $totalLength ) {
169 $logHairLength = mt_rand( 0, 1000000 ) / 1000000 * $logMaxLength;
170 $hairLength = min( intval( exp( $logHairLength ) ), $dictSize );
171 $offset = mt_rand( 0, $dictSize - $hairLength );
172 $input .= substr( $dict, $offset, $hairLength );
175 $this->setupGlobals();
176 $parser = $this->getParser();
180 $parser->parse( $input, $title, $opts );
182 } catch ( Exception $exception ) {
187 echo "Test failed with seed {$this->fuzzSeed}\n";
197 $this->teardownGlobals();
198 $parser->__destruct();
200 if ( $numTotal % 100 == 0 ) {
201 $usage = intval( memory_get_usage( true ) / $this->memoryLimit / 1048576 * 100 );
202 echo "{$this->fuzzSeed}: $numSuccess/$numTotal (mem: $usage%)\n";
204 echo "Out of memory:\n";
205 $memStats = $this->getMemoryBreakdown();
207 foreach ( $memStats as $name => $usage ) {
208 echo "$name: $usage\n";
217 * Get an input dictionary from a set of parser test files
219 function getFuzzInput( $filenames ) {
222 foreach ( $filenames as $filename ) {
223 $contents = file_get_contents( $filename );
224 preg_match_all( '/!!\s*input\n(.*?)\n!!\s*result/s', $contents, $matches );
226 foreach ( $matches[1] as $match ) {
227 $dict .= $match . "\n";
235 * Get a memory usage breakdown
237 function getMemoryBreakdown() {
240 foreach ( $GLOBALS as $name => $value ) {
241 $memStats['$' . $name] = strlen( serialize( $value ) );
244 $classes = get_declared_classes();
246 foreach ( $classes as $class ) {
247 $rc = new ReflectionClass( $class );
248 $props = $rc->getStaticProperties();
249 $memStats[$class] = strlen( serialize( $props ) );
250 $methods = $rc->getMethods();
252 foreach ( $methods as $method ) {
253 $memStats[$class] += strlen( serialize( $method->getStaticVariables() ) );
257 $functions = get_defined_functions();
259 foreach ( $functions['user'] as $function ) {
260 $rf = new ReflectionFunction( $function );
261 $memStats["$function()"] = strlen( serialize( $rf->getStaticVariables() ) );
274 * Run a series of tests listed in the given text files.
275 * Each test consists of a brief description, wikitext input,
276 * and the expected HTML output.
278 * Prints status updates on stdout and counts up the total
279 * number and percentage of passed tests.
281 * @param $filenames Array of strings
282 * @return Boolean: true if passed all tests, false if any tests failed.
284 public function runTestsFromFiles( $filenames ) {
285 $GLOBALS['wgContLang'] = Language::factory( 'en' );
286 $this->recorder->start();
287 $this->setupDatabase();
290 foreach ( $filenames as $filename ) {
291 $tests = new TestFileIterator( $filename, $this );
292 $ok = $this->runTests( $tests ) && $ok;
295 $this->teardownDatabase();
296 $this->recorder->report();
297 $this->recorder->end();
302 function runTests( $tests ) {
305 foreach ( $tests as $i => $t ) {
307 $this->runTest( $t['test'], $t['input'], $t['result'], $t['options'], $t['config'] );
308 $ok = $ok && $result;
309 $this->recorder->record( $t['test'], $result );
312 if ( $this->showProgress ) {
320 * Get a Parser object
322 function getParser( $preprocessor = null ) {
323 global $wgParserConf;
325 $class = $wgParserConf['class'];
326 $parser = new $class( array( 'preprocessorClass' => $preprocessor ) + $wgParserConf );
328 foreach ( $this->hooks as $tag => $callback ) {
329 $parser->setHook( $tag, $callback );
332 foreach ( $this->functionHooks as $tag => $bits ) {
333 list( $callback, $flags ) = $bits;
334 $parser->setFunctionHook( $tag, $callback, $flags );
337 wfRunHooks( 'ParserTestParser', array( &$parser ) );
343 * Run a given wikitext input through a freshly-constructed wiki parser,
344 * and compare the output against the expected results.
345 * Prints status and explanatory messages to stdout.
347 * @param $desc String: test's description
348 * @param $input String: wikitext to try rendering
349 * @param $result String: result to output
350 * @param $opts Array: test's options
351 * @param $config String: overrides for global variables, one per line
354 public function runTest( $desc, $input, $result, $opts, $config ) {
355 if ( $this->showProgress ) {
356 $this->showTesting( $desc );
359 $opts = $this->parseOptions( $opts );
360 $this->setupGlobals( $opts, $config );
363 $options = ParserOptions::newFromUser( $user );
365 if ( isset( $opts['title'] ) ) {
366 $titleText = $opts['title'];
369 $titleText = 'Parser test';
372 $noxml = isset( $opts['noxml'] );
373 $local = isset( $opts['local'] );
374 $preprocessor = isset( $opts['preprocessor'] ) ? $opts['preprocessor'] : null;
375 $parser = $this->getParser( $preprocessor );
376 $title = Title::newFromText( $titleText );
378 if ( isset( $opts['pst'] ) ) {
379 $out = $parser->preSaveTransform( $input, $title, $user, $options );
380 } elseif ( isset( $opts['msg'] ) ) {
381 $out = $parser->transformMsg( $input, $options );
382 } elseif ( isset( $opts['section'] ) ) {
383 $section = $opts['section'];
384 $out = $parser->getSection( $input, $section );
385 } elseif ( isset( $opts['replace'] ) ) {
386 $section = $opts['replace'][0];
387 $replace = $opts['replace'][1];
388 $out = $parser->replaceSection( $input, $section, $replace );
389 } elseif ( isset( $opts['comment'] ) ) {
390 $linker = $user->getSkin();
391 $out = $linker->formatComment( $input, $title, $local );
392 } elseif ( isset( $opts['preload'] ) ) {
393 $out = $parser->getpreloadText( $input, $title, $options );
395 $output = $parser->parse( $input, $title, $options, true, true, 1337 );
396 $out = $output->getText();
398 if ( isset( $opts['showtitle'] ) ) {
399 if ( $output->getTitleText() ) {
400 $title = $output->getTitleText();
403 $out = "$title\n$out";
406 if ( isset( $opts['ill'] ) ) {
407 $out = $this->tidy( implode( ' ', $output->getLanguageLinks() ) );
408 } elseif ( isset( $opts['cat'] ) ) {
411 $wgOut->addCategoryLinks( $output->getCategories() );
412 $cats = $wgOut->getCategoryLinks();
414 if ( isset( $cats['normal'] ) ) {
415 $out = $this->tidy( implode( ' ', $cats['normal'] ) );
421 $result = $this->tidy( $result );
425 $this->teardownGlobals();
427 if ( $result === $out && ( $noxml === true || $this->wellFormed( $out ) ) ) {
428 return $this->showSuccess( $desc );
430 return $this->showFailure( $desc, $result, $out );
435 * Use a regex to find out the value of an option
436 * @param $key String: name of option val to retrieve
437 * @param $opts Options array to look in
438 * @param $default Mixed: default value returned if not found
440 private static function getOptionValue( $key, $opts, $default ) {
441 $key = strtolower( $key );
443 if ( isset( $opts[$key] ) ) {
450 private function parseOptions( $instring ) {
452 $lines = explode( "\n", $instring );
457 // foo=bar,"baz quux"
481 \[\[[^]]*\]\] # Link target
489 if ( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER ) ) {
490 foreach ( $matches as $bits ) {
491 $match = array_shift( $bits );
492 $key = strtolower( array_shift( $bits ) );
493 if ( count( $bits ) == 0 ) {
495 } elseif ( count( $bits ) == 1 ) {
496 $opts[$key] = $this->cleanupOption( array_shift( $bits ) );
499 $opts[$key] = array_map( array( $this, 'cleanupOption' ), $bits );
506 private function cleanupOption( $opt ) {
507 if ( substr( $opt, 0, 1 ) == '"' ) {
508 return substr( $opt, 1, -1 );
511 if ( substr( $opt, 0, 2 ) == '[[' ) {
512 return substr( $opt, 2, -2 );
518 * Set up the global variables for a consistent environment for each test.
519 * Ideally this should replace the global configuration entirely.
521 private function setupGlobals( $opts = '', $config = '' ) {
524 # Find out values for some special options.
526 self::getOptionValue( 'language', $opts, 'en' );
528 self::getOptionValue( 'variant', $opts, false );
530 self::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
531 $linkHolderBatchSize =
532 self::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
535 'wgServer' => 'http://Britney-Spears',
536 'wgScript' => '/index.php',
537 'wgScriptPath' => '/',
538 'wgArticlePath' => '/wiki/$1',
539 'wgActionPaths' => array(),
540 'wgLocalFileRepo' => array(
541 'class' => 'LocalRepo',
543 'directory' => $this->uploadDir,
544 'url' => 'http://example.com/images',
546 'transformVia404' => false,
548 'wgEnableUploads' => self::getOptionValue( 'wgEnableUploads', $opts, true ),
549 'wgStylePath' => '/skins',
550 'wgStyleSheetPath' => '/skins',
551 'wgSitename' => 'MediaWiki',
552 'wgLanguageCode' => $lang,
553 'wgDBprefix' => $wgDBtype != 'oracle' ? 'parsertest_' : 'pt_',
554 'wgRawHtml' => isset( $opts['rawhtml'] ),
556 'wgContLang' => null,
557 'wgNamespacesWithSubpages' => array( 0 => isset( $opts['subpage'] ) ),
558 'wgMaxTocLevel' => $maxtoclevel,
559 'wgCapitalLinks' => true,
560 'wgNoFollowLinks' => true,
561 'wgNoFollowDomainExceptions' => array(),
562 'wgThumbnailScriptPath' => false,
563 'wgUseImageResize' => false,
564 'wgUseTeX' => isset( $opts['math'] ),
565 'wgMathDirectory' => $this->uploadDir . '/math',
566 'wgLocaltimezone' => 'UTC',
567 'wgAllowExternalImages' => true,
568 'wgUseTidy' => false,
569 'wgDefaultLanguageVariant' => $variant,
570 'wgVariantArticlePath' => false,
571 'wgGroupPermissions' => array( '*' => array(
572 'createaccount' => true,
575 'createpage' => true,
576 'createtalk' => true,
578 'wgNamespaceProtection' => array( NS_MEDIAWIKI => 'editinterface' ),
579 'wgDefaultExternalStore' => array(),
580 'wgForeignFileRepos' => array(),
581 'wgLinkHolderBatchSize' => $linkHolderBatchSize,
582 'wgExperimentalHtmlIds' => false,
583 'wgExternalLinkTarget' => false,
584 'wgAlwaysUseTidy' => false,
586 'wgWellFormedXml' => true,
587 'wgAllowMicrodataAttributes' => true,
591 $configLines = explode( "\n", $config );
593 foreach ( $configLines as $line ) {
594 list( $var, $value ) = explode( '=', $line, 2 );
596 $settings[$var] = eval( "return $value;" );
600 $this->savedGlobals = array();
602 foreach ( $settings as $var => $val ) {
603 if ( array_key_exists( $var, $GLOBALS ) ) {
604 $this->savedGlobals[$var] = $GLOBALS[$var];
607 $GLOBALS[$var] = $val;
610 $langObj = Language::factory( $lang );
611 $GLOBALS['wgLang'] = $langObj;
612 $GLOBALS['wgContLang'] = $langObj;
613 $GLOBALS['wgMemc'] = new FakeMemCachedClient;
614 $GLOBALS['wgOut'] = new OutputPage;
618 $wgHooks['ParserTestParser'][] = 'ParserTestParserHook::setup';
619 $wgHooks['ParserTestParser'][] = 'ParserTestStaticParserHook::setup';
620 $wgHooks['ParserGetVariableValueTs'][] = 'ParserTest::getFakeTimestamp';
622 MagicWord::clearCache();
625 $wgUser = new User();
629 * List of temporary tables to create, without prefix.
630 * Some of these probably aren't necessary.
632 private function listTables() {
635 $tables = array( 'user', 'user_properties', 'page', 'page_restrictions',
636 'protected_titles', 'revision', 'text', 'pagelinks', 'imagelinks',
637 'categorylinks', 'templatelinks', 'externallinks', 'langlinks', 'iwlinks',
638 'site_stats', 'hitcounter', 'ipblocks', 'image', 'oldimage',
639 'recentchanges', 'watchlist', 'math', 'interwiki', 'logging',
640 'querycache', 'objectcache', 'job', 'l10n_cache', 'redirect', 'querycachetwo',
641 'archive', 'user_groups', 'page_props', 'category', 'msg_resource', 'msg_resource_links'
644 if ( in_array( $wgDBtype, array( 'mysql', 'sqlite' ) ) )
645 array_push( $tables, 'searchindex' );
647 // Allow extensions to add to the list of tables to duplicate;
648 // may be necessary if they hook into page save or other code
649 // which will require them while running tests.
650 wfRunHooks( 'ParserTestTables', array( &$tables ) );
656 * Set up a temporary set of wiki tables to work with for the tests.
657 * Currently this will only be done once per run, and any changes to
658 * the db will be visible to later tests in the run.
660 public function setupDatabase() {
661 global $wgDBprefix, $wgDBtype;
663 if ( $this->databaseSetupDone ) {
667 if ( $wgDBprefix === 'parsertest_' || ( $wgDBtype == 'oracle' && $wgDBprefix === 'pt_' ) ) {
668 throw new MWException( 'setupDatabase should be called before setupGlobals' );
671 $this->databaseSetupDone = true;
672 $this->oldTablePrefix = $wgDBprefix;
674 # SqlBagOStuff broke when using temporary tables on r40209 (bug 15892).
675 # It seems to have been fixed since (r55079?).
676 # If it fails, $wgCaches[CACHE_DB] = new HashBagOStuff(); should work around it.
678 # CREATE TEMPORARY TABLE breaks if there is more than one server
679 if ( wfGetLB()->getServerCount() != 1 ) {
680 $this->useTemporaryTables = false;
683 $temporary = $this->useTemporaryTables || $wgDBtype == 'postgres';
685 $db = wfGetDB( DB_MASTER );
686 $tables = $this->listTables();
688 foreach ( $tables as $tbl ) {
689 # Clean up from previous aborted run. So that table escaping
690 # works correctly across DB engines, we need to change the pre-
691 # fix back and forth so tableName() works right.
692 $this->changePrefix( $this->oldTablePrefix );
693 $oldTableName = $db->tableName( $tbl );
694 $this->changePrefix( $wgDBtype != 'oracle' ? 'parsertest_' : 'pt_' );
695 $newTableName = $db->tableName( $tbl );
697 if ( $wgDBtype == 'mysql' ) {
698 $db->query( "DROP TABLE IF EXISTS $newTableName" );
699 } elseif ( in_array( $wgDBtype, array( 'postgres', 'oracle' ) ) ) {
700 /* DROPs wouldn't work due to Foreign Key Constraints (bug 14990, r58669)
701 * Use "DROP TABLE IF EXISTS $newTableName CASCADE" for postgres? That
702 * syntax would also work for mysql.
704 } elseif ( $db->tableExists( $tbl ) ) {
705 $db->query( "DROP TABLE $newTableName" );
709 $db->duplicateTableStructure( $oldTableName, $newTableName, $temporary );
712 if ( $wgDBtype == 'oracle' )
713 $db->query( 'BEGIN FILL_WIKI_INFO; END;' );
715 $this->changePrefix( $wgDBtype != 'oracle' ? 'parsertest_' : 'pt_' );
717 # Hack: insert a few Wikipedia in-project interwiki prefixes,
718 # for testing inter-language links
719 $db->insert( 'interwiki', array(
720 array( 'iw_prefix' => 'wikipedia',
721 'iw_url' => 'http://en.wikipedia.org/wiki/$1',
725 array( 'iw_prefix' => 'meatball',
726 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
730 array( 'iw_prefix' => 'zh',
731 'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
735 array( 'iw_prefix' => 'es',
736 'iw_url' => 'http://es.wikipedia.org/wiki/$1',
740 array( 'iw_prefix' => 'fr',
741 'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
745 array( 'iw_prefix' => 'ru',
746 'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
753 if ( $wgDBtype == 'oracle' ) {
754 # Insert 0 user to prevent FK violations
757 $db->insert( 'user', array(
759 'user_name' => 'Anonymous' ) );
762 # Update certain things in site_stats
763 $db->insert( 'site_stats', array( 'ss_row_id' => 1, 'ss_images' => 2, 'ss_good_articles' => 1 ) );
765 # Reinitialise the LocalisationCache to match the database state
766 Language::getLocalisationCache()->unloadAll();
768 # Make a new message cache
769 global $wgMessageCache, $wgMemc;
770 $wgMessageCache = new MessageCache( $wgMemc, true, 3600 );
772 $this->uploadDir = $this->setupUploadDir();
773 $user = User::createNew( 'WikiSysop' );
774 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Foobar.jpg' ) );
775 $image->recordUpload2( '', 'Upload of some lame file', 'Some lame file', array(
780 'media_type' => MEDIATYPE_BITMAP,
781 'mime' => 'image/jpeg',
782 'metadata' => serialize( array() ),
783 'sha1' => sha1( '' ),
785 ), $db->timestamp( '20010115123500' ), $user );
787 # This image will be blacklisted in [[MediaWiki:Bad image list]]
788 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Bad.jpg' ) );
789 $image->recordUpload2( '', 'zomgnotcensored', 'Borderline image', array(
794 'media_type' => MEDIATYPE_BITMAP,
795 'mime' => 'image/jpeg',
796 'metadata' => serialize( array() ),
797 'sha1' => sha1( '' ),
799 ), $db->timestamp( '20010115123500' ), $user );
803 * Change the table prefix on all open DB connections/
805 protected function changePrefix( $prefix ) {
807 wfGetLBFactory()->forEachLB( array( $this, 'changeLBPrefix' ), array( $prefix ) );
808 $wgDBprefix = $prefix;
811 public function changeLBPrefix( $lb, $prefix ) {
812 $lb->forEachOpenConnection( array( $this, 'changeDBPrefix' ), array( $prefix ) );
815 public function changeDBPrefix( $db, $prefix ) {
816 $db->tablePrefix( $prefix );
819 public function teardownDatabase() {
822 if ( !$this->databaseSetupDone ) {
825 $this->teardownUploadDir( $this->uploadDir );
827 $this->changePrefix( $this->oldTablePrefix );
828 $this->databaseSetupDone = false;
830 if ( $this->useTemporaryTables ) {
831 # Don't need to do anything
835 $tables = $this->listTables();
836 $db = wfGetDB( DB_MASTER );
838 foreach ( $tables as $table ) {
839 $sql = $wgDBtype == 'oracle' ? "DROP TABLE pt_$table DROP CONSTRAINTS" : "DROP TABLE `parsertest_$table`";
843 if ( $wgDBtype == 'oracle' )
844 $db->query( 'BEGIN FILL_WIKI_INFO; END;' );
848 * Create a dummy uploads directory which will contain a couple
849 * of files in order to pass existence tests.
851 * @return String: the directory
853 private function setupUploadDir() {
856 if ( $this->keepUploads ) {
857 $dir = wfTempDir() . '/mwParser-images';
859 if ( is_dir( $dir ) ) {
863 $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
866 // wfDebug( "Creating upload directory $dir\n" );
867 if ( file_exists( $dir ) ) {
868 wfDebug( "Already exists!\n" );
872 wfMkdirParents( $dir . '/3/3a' );
873 copy( "$IP/skins/monobook/headbg.jpg", "$dir/3/3a/Foobar.jpg" );
874 wfMkdirParents( $dir . '/0/09' );
875 copy( "$IP/skins/monobook/headbg.jpg", "$dir/0/09/Bad.jpg" );
881 * Restore default values and perform any necessary clean-up
882 * after each test runs.
884 private function teardownGlobals() {
885 RepoGroup::destroySingleton();
886 LinkCache::singleton()->clear();
888 foreach ( $this->savedGlobals as $var => $val ) {
889 $GLOBALS[$var] = $val;
894 * Remove the dummy uploads directory
896 private function teardownUploadDir( $dir ) {
897 if ( $this->keepUploads ) {
901 // delete the files first, then the dirs.
904 "$dir/3/3a/Foobar.jpg",
905 "$dir/thumb/3/3a/Foobar.jpg/180px-Foobar.jpg",
906 "$dir/thumb/3/3a/Foobar.jpg/200px-Foobar.jpg",
907 "$dir/thumb/3/3a/Foobar.jpg/640px-Foobar.jpg",
908 "$dir/thumb/3/3a/Foobar.jpg/120px-Foobar.jpg",
912 "$dir/math/f/a/5/fa50b8b616463173474302ca3e63586b.png",
922 "$dir/thumb/3/3a/Foobar.jpg",
939 * Delete the specified files, if they exist.
940 * @param $files Array: full paths to files to delete.
942 private static function deleteFiles( $files ) {
943 foreach ( $files as $file ) {
944 if ( file_exists( $file ) ) {
951 * Delete the specified directories, if they exist. Must be empty.
952 * @param $dirs Array: full paths to directories to delete.
954 private static function deleteDirs( $dirs ) {
955 foreach ( $dirs as $dir ) {
956 if ( is_dir( $dir ) ) {
963 * "Running test $desc..."
965 protected function showTesting( $desc ) {
966 print "Running test $desc... ";
970 * Print a happy success message.
972 * @param $desc String: the test name
975 protected function showSuccess( $desc ) {
976 if ( $this->showProgress ) {
977 print $this->term->color( '1;32' ) . 'PASSED' . $this->term->reset() . "\n";
984 * Print a failure message and provide some explanatory output
985 * about what went wrong if so configured.
987 * @param $desc String: the test name
988 * @param $result String: expected HTML output
989 * @param $html String: actual HTML output
992 protected function showFailure( $desc, $result, $html ) {
993 if ( $this->showFailure ) {
994 if ( !$this->showProgress ) {
995 # In quiet mode we didn't show the 'Testing' message before the
996 # test, in case it succeeded. Show it now:
997 $this->showTesting( $desc );
1000 print $this->term->color( '31' ) . 'FAILED!' . $this->term->reset() . "\n";
1002 if ( $this->showOutput ) {
1003 print "--- Expected ---\n$result\n--- Actual ---\n$html\n";
1006 if ( $this->showDiffs ) {
1007 print $this->quickDiff( $result, $html );
1008 if ( !$this->wellFormed( $html ) ) {
1009 print "XML error: $this->mXmlError\n";
1018 * Run given strings through a diff and return the (colorized) output.
1019 * Requires writable /tmp directory and a 'diff' command in the PATH.
1021 * @param $input String
1022 * @param $output String
1023 * @param $inFileTail String: tailing for the input file name
1024 * @param $outFileTail String: tailing for the output file name
1027 protected function quickDiff( $input, $output, $inFileTail = 'expected', $outFileTail = 'actual' ) {
1028 $prefix = wfTempDir() . "/mwParser-" . mt_rand();
1030 $infile = "$prefix-$inFileTail";
1031 $this->dumpToFile( $input, $infile );
1033 $outfile = "$prefix-$outFileTail";
1034 $this->dumpToFile( $output, $outfile );
1036 $diff = `diff -au $infile $outfile`;
1040 return $this->colorDiff( $diff );
1044 * Write the given string to a file, adding a final newline.
1046 * @param $data String
1047 * @param $filename String
1049 private function dumpToFile( $data, $filename ) {
1050 $file = fopen( $filename, "wt" );
1051 fwrite( $file, $data . "\n" );
1056 * Colorize unified diff output if set for ANSI color output.
1057 * Subtractions are colored blue, additions red.
1059 * @param $text String
1062 protected function colorDiff( $text ) {
1063 return preg_replace(
1064 array( '/^(-.*)$/m', '/^(\+.*)$/m' ),
1065 array( $this->term->color( 34 ) . '$1' . $this->term->reset(),
1066 $this->term->color( 31 ) . '$1' . $this->term->reset() ),
1071 * Show "Reading tests from ..."
1073 * @param $path String
1075 public function showRunFile( $path ) {
1076 print $this->term->color( 1 ) .
1077 "Reading tests from \"$path\"..." .
1078 $this->term->reset() .
1083 * Insert a temporary test article
1084 * @param $name String: the title, including any prefix
1085 * @param $text String: the article text
1086 * @param $line Integer: the input line number, for reporting errors
1088 public function addArticle( $name, $text, $line ) {
1089 global $wgCapitalLinks;
1090 $oldCapitalLinks = $wgCapitalLinks;
1091 $wgCapitalLinks = true; // We only need this from SetupGlobals() See r70917#c8637
1093 $title = Title::newFromText( $name );
1095 if ( is_null( $title ) ) {
1096 wfDie( "invalid title at line $line\n" );
1099 $aid = $title->getArticleID( Title::GAID_FOR_UPDATE );
1102 wfDie( "duplicate article '$name' at line $line\n" );
1105 $art = new Article( $title );
1106 $art->insertNewArticle( $text, '', false, false );
1108 $wgCapitalLinks = $oldCapitalLinks;
1112 * Steal a callback function from the primary parser, save it for
1113 * application to our scary parser. If the hook is not installed,
1114 * abort processing of this file.
1116 * @param $name String
1117 * @return Bool true if tag hook is present
1119 public function requireHook( $name ) {
1122 $wgParser->firstCallInit( ); // make sure hooks are loaded.
1124 if ( isset( $wgParser->mTagHooks[$name] ) ) {
1125 $this->hooks[$name] = $wgParser->mTagHooks[$name];
1127 echo " This test suite requires the '$name' hook extension, skipping.\n";
1135 * Steal a callback function from the primary parser, save it for
1136 * application to our scary parser. If the hook is not installed,
1137 * abort processing of this file.
1139 * @param $name String
1140 * @return Bool true if function hook is present
1142 public function requireFunctionHook( $name ) {
1145 $wgParser->firstCallInit( ); // make sure hooks are loaded.
1147 if ( isset( $wgParser->mFunctionHooks[$name] ) ) {
1148 $this->functionHooks[$name] = $wgParser->mFunctionHooks[$name];
1150 echo " This test suite requires the '$name' function hook extension, skipping.\n";
1158 * Run the "tidy" command on text if the $wgUseTidy
1161 * @param $text String: the text to tidy
1165 private function tidy( $text ) {
1169 $text = MWTidy::tidy( $text );
1175 private function wellFormed( $text ) {
1177 Sanitizer::hackDocType() .
1182 $parser = xml_parser_create( "UTF-8" );
1184 # case folding violates XML standard, turn it off
1185 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
1187 if ( !xml_parse( $parser, $html, true ) ) {
1188 $err = xml_error_string( xml_get_error_code( $parser ) );
1189 $position = xml_get_current_byte_index( $parser );
1190 $fragment = $this->extractFragment( $html, $position );
1191 $this->mXmlError = "$err at byte $position:\n$fragment";
1192 xml_parser_free( $parser );
1197 xml_parser_free( $parser );
1202 private function extractFragment( $text, $position ) {
1203 $start = max( 0, $position - 10 );
1204 $before = $position - $start;
1206 $this->term->color( 34 ) .
1207 substr( $text, $start, $before ) .
1208 $this->term->color( 0 ) .
1209 $this->term->color( 31 ) .
1210 $this->term->color( 1 ) .
1211 substr( $text, $position, 1 ) .
1212 $this->term->color( 0 ) .
1213 $this->term->color( 34 ) .
1214 substr( $text, $position + 1, 9 ) .
1215 $this->term->color( 0 ) .
1217 $display = str_replace( "\n", ' ', $fragment );
1219 str_repeat( ' ', $before ) .
1220 $this->term->color( 31 ) .
1222 $this->term->color( 0 );
1224 return "$display\n$caret";
1227 static function getFakeTimestamp( &$parser, &$ts ) {