MediaWiki  REL1_20
parserTest.inc
Go to the documentation of this file.
00001 <?php
00002 # Copyright (C) 2004, 2010 Brion Vibber <[email protected]>
00003 # http://www.mediawiki.org/
00004 #
00005 # This program is free software; you can redistribute it and/or modify
00006 # it under the terms of the GNU General Public License as published by
00007 # the Free Software Foundation; either version 2 of the License, or
00008 # (at your option) any later version.
00009 #
00010 # This program is distributed in the hope that it will be useful,
00011 # but WITHOUT ANY WARRANTY; without even the implied warranty of
00012 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
00013 # GNU General Public License for more details.
00014 #
00015 # You should have received a copy of the GNU General Public License along
00016 # with this program; if not, write to the Free Software Foundation, Inc.,
00017 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
00018 # http://www.gnu.org/copyleft/gpl.html
00019 
00030 class ParserTest {
00034         private $color;
00035 
00039         private $showOutput;
00040 
00044         private $useTemporaryTables = true;
00045 
00049         private $databaseSetupDone = false;
00050 
00055         private $db;
00056 
00061         private $dbClone;
00062 
00066         private $oldTablePrefix;
00067 
00068         private $maxFuzzTestLength = 300;
00069         private $fuzzSeed = 0;
00070         private $memoryLimit = 50;
00071         private $uploadDir = null;
00072 
00073         public $regex = "";
00074         private $savedGlobals = array();
00079         public function __construct( $options = array() ) {
00080                 # Only colorize output if stdout is a terminal.
00081                 $this->color = !wfIsWindows() && Maintenance::posix_isatty( 1 );
00082 
00083                 if ( isset( $options['color'] ) ) {
00084                         switch( $options['color'] ) {
00085                         case 'no':
00086                                 $this->color = false;
00087                                 break;
00088                         case 'yes':
00089                         default:
00090                                 $this->color = true;
00091                                 break;
00092                         }
00093                 }
00094 
00095                 $this->term = $this->color
00096                         ? new AnsiTermColorer()
00097                         : new DummyTermColorer();
00098 
00099                 $this->showDiffs = !isset( $options['quick'] );
00100                 $this->showProgress = !isset( $options['quiet'] );
00101                 $this->showFailure = !(
00102                         isset( $options['quiet'] )
00103                         && ( isset( $options['record'] )
00104                                 || isset( $options['compare'] ) ) ); // redundant output
00105 
00106                 $this->showOutput = isset( $options['show-output'] );
00107 
00108                 if ( isset( $options['filter'] ) ) {
00109                         $options['regex'] = $options['filter'];
00110                 }
00111 
00112                 if ( isset( $options['regex'] ) ) {
00113                         if ( isset( $options['record'] ) ) {
00114                                 echo "Warning: --record cannot be used with --regex, disabling --record\n";
00115                                 unset( $options['record'] );
00116                         }
00117                         $this->regex = $options['regex'];
00118                 } else {
00119                         # Matches anything
00120                         $this->regex = '';
00121                 }
00122 
00123                 $this->setupRecorder( $options );
00124                 $this->keepUploads = isset( $options['keep-uploads'] );
00125 
00126                 if ( isset( $options['seed'] ) ) {
00127                         $this->fuzzSeed = intval( $options['seed'] ) - 1;
00128                 }
00129 
00130                 $this->runDisabled = isset( $options['run-disabled'] );
00131 
00132                 $this->hooks = array();
00133                 $this->functionHooks = array();
00134                 self::setUp();
00135         }
00136 
00137         static function setUp() {
00138                 global $wgParser, $wgParserConf, $IP, $messageMemc, $wgMemc,
00139                         $wgUser, $wgLang, $wgOut, $wgRequest, $wgStyleDirectory, $wgEnableParserCache,
00140                         $wgNamespaceAliases, $wgNamespaceProtection, $wgLocalFileRepo,
00141                         $parserMemc, $wgThumbnailScriptPath, $wgScriptPath,
00142                         $wgArticlePath, $wgStyleSheetPath, $wgScript, $wgStylePath, $wgExtensionAssetsPath,
00143                         $wgMainCacheType, $wgMessageCacheType, $wgParserCacheType, $wgLockManagers;
00144 
00145                 $wgScript = '/index.php';
00146                 $wgScriptPath = '/';
00147                 $wgArticlePath = '/wiki/$1';
00148                 $wgStyleSheetPath = '/skins';
00149                 $wgStylePath = '/skins';
00150                 $wgExtensionAssetsPath = '/extensions';
00151                 $wgThumbnailScriptPath = false;
00152                 $wgLockManagers = array( array(
00153                         'name'          => 'fsLockManager',
00154                         'class'         => 'FSLockManager',
00155                         'lockDirectory' => wfTempDir() . '/test-repo/lockdir',
00156                 ) );
00157                 $wgLocalFileRepo = array(
00158                         'class'           => 'LocalRepo',
00159                         'name'            => 'local',
00160                         'url'             => 'http://example.com/images',
00161                         'hashLevels'      => 2,
00162                         'transformVia404' => false,
00163                         'backend'         => new FSFileBackend( array(
00164                                 'name'        => 'local-backend',
00165                                 'lockManager' => 'fsLockManager',
00166                                 'containerPaths' => array(
00167                                         'local-public'  => wfTempDir() . '/test-repo/public',
00168                                         'local-thumb'   => wfTempDir() . '/test-repo/thumb',
00169                                         'local-temp'    => wfTempDir() . '/test-repo/temp',
00170                                         'local-deleted' => wfTempDir() . '/test-repo/deleted',
00171                                 )
00172                         ) )
00173                 );
00174                 $wgNamespaceProtection[NS_MEDIAWIKI] = 'editinterface';
00175                 $wgNamespaceAliases['Image'] = NS_FILE;
00176                 $wgNamespaceAliases['Image_talk'] = NS_FILE_TALK;
00177 
00178                 // XXX: tests won't run without this (for CACHE_DB)
00179                 if ( $wgMainCacheType === CACHE_DB ) {
00180                         $wgMainCacheType = CACHE_NONE;
00181                 }
00182                 if ( $wgMessageCacheType === CACHE_DB ) {
00183                         $wgMessageCacheType = CACHE_NONE;
00184                 }
00185                 if ( $wgParserCacheType === CACHE_DB ) {
00186                         $wgParserCacheType = CACHE_NONE;
00187                 }
00188 
00189                 $wgEnableParserCache = false;
00190                 DeferredUpdates::clearPendingUpdates();
00191                 $wgMemc = wfGetMainCache(); // checks $wgMainCacheType
00192                 $messageMemc = wfGetMessageCacheStorage();
00193                 $parserMemc = wfGetParserCacheStorage();
00194 
00195                 // $wgContLang = new StubContLang;
00196                 $wgUser = new User;
00197                 $context = new RequestContext;
00198                 $wgLang = $context->getLanguage();
00199                 $wgOut = $context->getOutput();
00200                 $wgParser = new StubObject( 'wgParser', $wgParserConf['class'], array( $wgParserConf ) );
00201                 $wgRequest = $context->getRequest();
00202 
00203                 if ( $wgStyleDirectory === false ) {
00204                         $wgStyleDirectory   = "$IP/skins";
00205                 }
00206 
00207         }
00208 
00209         public function setupRecorder ( $options ) {
00210                 if ( isset( $options['record'] ) ) {
00211                         $this->recorder = new DbTestRecorder( $this );
00212                         $this->recorder->version = isset( $options['setversion'] ) ?
00213                                         $options['setversion'] : SpecialVersion::getVersion();
00214                 } elseif ( isset( $options['compare'] ) ) {
00215                         $this->recorder = new DbTestPreviewer( $this );
00216                 } else {
00217                         $this->recorder = new TestRecorder( $this );
00218                 }
00219         }
00220 
00225         static public function chomp( $s ) {
00226                 if ( substr( $s, -1 ) === "\n" ) {
00227                         return substr( $s, 0, -1 );
00228                 }
00229                 else {
00230                         return $s;
00231                 }
00232         }
00233 
00238         function fuzzTest( $filenames ) {
00239                 $GLOBALS['wgContLang'] = Language::factory( 'en' );
00240                 $dict = $this->getFuzzInput( $filenames );
00241                 $dictSize = strlen( $dict );
00242                 $logMaxLength = log( $this->maxFuzzTestLength );
00243                 $this->setupDatabase();
00244                 ini_set( 'memory_limit', $this->memoryLimit * 1048576 );
00245 
00246                 $numTotal = 0;
00247                 $numSuccess = 0;
00248                 $user = new User;
00249                 $opts = ParserOptions::newFromUser( $user );
00250                 $title = Title::makeTitle( NS_MAIN, 'Parser_test' );
00251 
00252                 while ( true ) {
00253                         // Generate test input
00254                         mt_srand( ++$this->fuzzSeed );
00255                         $totalLength = mt_rand( 1, $this->maxFuzzTestLength );
00256                         $input = '';
00257 
00258                         while ( strlen( $input ) < $totalLength ) {
00259                                 $logHairLength = mt_rand( 0, 1000000 ) / 1000000 * $logMaxLength;
00260                                 $hairLength = min( intval( exp( $logHairLength ) ), $dictSize );
00261                                 $offset = mt_rand( 0, $dictSize - $hairLength );
00262                                 $input .= substr( $dict, $offset, $hairLength );
00263                         }
00264 
00265                         $this->setupGlobals();
00266                         $parser = $this->getParser();
00267 
00268                         // Run the test
00269                         try {
00270                                 $parser->parse( $input, $title, $opts );
00271                                 $fail = false;
00272                         } catch ( Exception $exception ) {
00273                                 $fail = true;
00274                         }
00275 
00276                         if ( $fail ) {
00277                                 echo "Test failed with seed {$this->fuzzSeed}\n";
00278                                 echo "Input:\n";
00279                                 printf( "string(%d) \"%s\"\n\n", strlen( $input ), $input );
00280                                 echo "$exception\n";
00281                         } else {
00282                                 $numSuccess++;
00283                         }
00284 
00285                         $numTotal++;
00286                         $this->teardownGlobals();
00287                         $parser->__destruct();
00288 
00289                         if ( $numTotal % 100 == 0 ) {
00290                                 $usage = intval( memory_get_usage( true ) / $this->memoryLimit / 1048576 * 100 );
00291                                 echo "{$this->fuzzSeed}: $numSuccess/$numTotal (mem: $usage%)\n";
00292                                 if ( $usage > 90 ) {
00293                                         echo "Out of memory:\n";
00294                                         $memStats = $this->getMemoryBreakdown();
00295 
00296                                         foreach ( $memStats as $name => $usage ) {
00297                                                 echo "$name: $usage\n";
00298                                         }
00299                                         $this->abort();
00300                                 }
00301                         }
00302                 }
00303         }
00304 
00308         function getFuzzInput( $filenames ) {
00309                 $dict = '';
00310 
00311                 foreach ( $filenames as $filename ) {
00312                         $contents = file_get_contents( $filename );
00313                         preg_match_all( '/!!\s*input\n(.*?)\n!!\s*result/s', $contents, $matches );
00314 
00315                         foreach ( $matches[1] as $match ) {
00316                                 $dict .= $match . "\n";
00317                         }
00318                 }
00319 
00320                 return $dict;
00321         }
00322 
00326         function getMemoryBreakdown() {
00327                 $memStats = array();
00328 
00329                 foreach ( $GLOBALS as $name => $value ) {
00330                         $memStats['$' . $name] = strlen( serialize( $value ) );
00331                 }
00332 
00333                 $classes = get_declared_classes();
00334 
00335                 foreach ( $classes as $class ) {
00336                         $rc = new ReflectionClass( $class );
00337                         $props = $rc->getStaticProperties();
00338                         $memStats[$class] = strlen( serialize( $props ) );
00339                         $methods = $rc->getMethods();
00340 
00341                         foreach ( $methods as $method ) {
00342                                 $memStats[$class] += strlen( serialize( $method->getStaticVariables() ) );
00343                         }
00344                 }
00345 
00346                 $functions = get_defined_functions();
00347 
00348                 foreach ( $functions['user'] as $function ) {
00349                         $rf = new ReflectionFunction( $function );
00350                         $memStats["$function()"] = strlen( serialize( $rf->getStaticVariables() ) );
00351                 }
00352 
00353                 asort( $memStats );
00354 
00355                 return $memStats;
00356         }
00357 
00358         function abort() {
00359                 $this->abort();
00360         }
00361 
00373         public function runTestsFromFiles( $filenames ) {
00374                 $ok = false;
00375                 $GLOBALS['wgContLang'] = Language::factory( 'en' );
00376                 $this->recorder->start();
00377                 try {
00378                         $this->setupDatabase();
00379                         $ok = true;
00380 
00381                         foreach ( $filenames as $filename ) {
00382                                 $tests = new TestFileIterator( $filename, $this );
00383                                 $ok = $this->runTests( $tests ) && $ok;
00384                         }
00385 
00386                         $this->teardownDatabase();
00387                         $this->recorder->report();
00388                 } catch (DBError $e) {
00389                         echo $e->getMessage();
00390                 }
00391                 $this->recorder->end();
00392 
00393                 return $ok;
00394         }
00395 
00396         function runTests( $tests ) {
00397                 $ok = true;
00398 
00399                 foreach ( $tests as $t ) {
00400                         $result =
00401                                 $this->runTest( $t['test'], $t['input'], $t['result'], $t['options'], $t['config'] );
00402                         $ok = $ok && $result;
00403                         $this->recorder->record( $t['test'], $result );
00404                 }
00405 
00406                 if ( $this->showProgress ) {
00407                         print "\n";
00408                 }
00409 
00410                 return $ok;
00411         }
00412 
00416         function getParser( $preprocessor = null ) {
00417                 global $wgParserConf;
00418 
00419                 $class = $wgParserConf['class'];
00420                 $parser = new $class( array( 'preprocessorClass' => $preprocessor ) + $wgParserConf );
00421 
00422                 foreach ( $this->hooks as $tag => $callback ) {
00423                         $parser->setHook( $tag, $callback );
00424                 }
00425 
00426                 foreach ( $this->functionHooks as $tag => $bits ) {
00427                         list( $callback, $flags ) = $bits;
00428                         $parser->setFunctionHook( $tag, $callback, $flags );
00429                 }
00430 
00431                 wfRunHooks( 'ParserTestParser', array( &$parser ) );
00432 
00433                 return $parser;
00434         }
00435 
00448         public function runTest( $desc, $input, $result, $opts, $config ) {
00449                 if ( $this->showProgress ) {
00450                         $this->showTesting( $desc );
00451                 }
00452 
00453                 $opts = $this->parseOptions( $opts );
00454                 $context = $this->setupGlobals( $opts, $config );
00455 
00456                 $user = $context->getUser();
00457                 $options = ParserOptions::newFromContext( $context );
00458 
00459                 if ( isset( $opts['title'] ) ) {
00460                         $titleText = $opts['title'];
00461                 }
00462                 else {
00463                         $titleText = 'Parser test';
00464                 }
00465 
00466                 $local = isset( $opts['local'] );
00467                 $preprocessor = isset( $opts['preprocessor'] ) ? $opts['preprocessor'] : null;
00468                 $parser = $this->getParser( $preprocessor );
00469                 $title = Title::newFromText( $titleText );
00470 
00471                 if ( isset( $opts['pst'] ) ) {
00472                         $out = $parser->preSaveTransform( $input, $title, $user, $options );
00473                 } elseif ( isset( $opts['msg'] ) ) {
00474                         $out = $parser->transformMsg( $input, $options, $title );
00475                 } elseif ( isset( $opts['section'] ) ) {
00476                         $section = $opts['section'];
00477                         $out = $parser->getSection( $input, $section );
00478                 } elseif ( isset( $opts['replace'] ) ) {
00479                         $section = $opts['replace'][0];
00480                         $replace = $opts['replace'][1];
00481                         $out = $parser->replaceSection( $input, $section, $replace );
00482                 } elseif ( isset( $opts['comment'] ) ) {
00483                         $out = Linker::formatComment( $input, $title, $local );
00484                 } elseif ( isset( $opts['preload'] ) ) {
00485                         $out = $parser->getpreloadText( $input, $title, $options );
00486                 } else {
00487                         $output = $parser->parse( $input, $title, $options, true, true, 1337 );
00488                         $out = $output->getText();
00489 
00490                         if ( isset( $opts['showtitle'] ) ) {
00491                                 if ( $output->getTitleText() ) {
00492                                         $title = $output->getTitleText();
00493                                 }
00494 
00495                                 $out = "$title\n$out";
00496                         }
00497 
00498                         if ( isset( $opts['ill'] ) ) {
00499                                 $out = $this->tidy( implode( ' ', $output->getLanguageLinks() ) );
00500                         } elseif ( isset( $opts['cat'] ) ) {
00501                                 $outputPage = $context->getOutput();
00502                                 $outputPage->addCategoryLinks( $output->getCategories() );
00503                                 $cats = $outputPage->getCategoryLinks();
00504 
00505                                 if ( isset( $cats['normal'] ) ) {
00506                                         $out = $this->tidy( implode( ' ', $cats['normal'] ) );
00507                                 } else {
00508                                         $out = '';
00509                                 }
00510                         }
00511 
00512                         $result = $this->tidy( $result );
00513                 }
00514 
00515                 $this->teardownGlobals();
00516                 return $this->showTestResult( $desc, $result, $out );
00517         }
00518 
00522         function showTestResult( $desc, $result, $out ) {
00523                 if ( $result === $out ) {
00524                         $this->showSuccess( $desc );
00525                         return true;
00526                 } else {
00527                         $this->showFailure( $desc, $result, $out );
00528                         return false;
00529                 }
00530         }
00531 
00538         private static function getOptionValue( $key, $opts, $default ) {
00539                 $key = strtolower( $key );
00540 
00541                 if ( isset( $opts[$key] ) ) {
00542                         return $opts[$key];
00543                 } else {
00544                         return $default;
00545                 }
00546         }
00547 
00548         private function parseOptions( $instring ) {
00549                 $opts = array();
00550                 // foo
00551                 // foo=bar
00552                 // foo="bar baz"
00553                 // foo=[[bar baz]]
00554                 // foo=bar,"baz quux"
00555                 $regex = '/\b
00556                         ([\w-]+)                                                # Key
00557                         \b
00558                         (?:\s*
00559                                 =                                               # First sub-value
00560                                 \s*
00561                                 (
00562                                         "
00563                                                 [^"]*                   # Quoted val
00564                                         "
00565                                 |
00566                                         \[\[
00567                                                 [^]]*                   # Link target
00568                                         \]\]
00569                                 |
00570                                         [\w-]+                          # Plain word
00571                                 )
00572                                 (?:\s*
00573                                         ,                                       # Sub-vals 1..N
00574                                         \s*
00575                                         (
00576                                                 "[^"]*"                 # Quoted val
00577                                         |
00578                                                 \[\[[^]]*\]\]   # Link target
00579                                         |
00580                                                 [\w-]+                  # Plain word
00581                                         )
00582                                 )*
00583                         )?
00584                         /x';
00585 
00586                 if ( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER ) ) {
00587                         foreach ( $matches as $bits ) {
00588                                 array_shift( $bits );
00589                                 $key = strtolower( array_shift( $bits ) );
00590                                 if ( count( $bits ) == 0 ) {
00591                                         $opts[$key] = true;
00592                                 } elseif ( count( $bits ) == 1 ) {
00593                                         $opts[$key] = $this->cleanupOption( array_shift( $bits ) );
00594                                 } else {
00595                                         // Array!
00596                                         $opts[$key] = array_map( array( $this, 'cleanupOption' ), $bits );
00597                                 }
00598                         }
00599                 }
00600                 return $opts;
00601         }
00602 
00603         private function cleanupOption( $opt ) {
00604                 if ( substr( $opt, 0, 1 ) == '"' ) {
00605                         return substr( $opt, 1, -1 );
00606                 }
00607 
00608                 if ( substr( $opt, 0, 2 ) == '[[' ) {
00609                         return substr( $opt, 2, -2 );
00610                 }
00611                 return $opt;
00612         }
00613 
00618         private function setupGlobals( $opts = '', $config = '' ) {
00619                 # Find out values for some special options.
00620                 $lang =
00621                         self::getOptionValue( 'language', $opts, 'en' );
00622                 $variant =
00623                         self::getOptionValue( 'variant', $opts, false );
00624                 $maxtoclevel =
00625                         self::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
00626                 $linkHolderBatchSize =
00627                         self::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
00628 
00629                 $settings = array(
00630                         'wgServer' => 'http://Britney-Spears',
00631                         'wgScript' => '/index.php',
00632                         'wgScriptPath' => '/',
00633                         'wgArticlePath' => '/wiki/$1',
00634                         'wgActionPaths' => array(),
00635                         'wgLockManagers' => array(
00636                                 'name'          => 'fsLockManager',
00637                                 'class'         => 'FSLockManager',
00638                                 'lockDirectory' => $this->uploadDir . '/lockdir',
00639                         ),
00640                         'wgLocalFileRepo' => array(
00641                                 'class' => 'LocalRepo',
00642                                 'name' => 'local',
00643                                 'url' => 'http://example.com/images',
00644                                 'hashLevels' => 2,
00645                                 'transformVia404' => false,
00646                                 'backend'         => new FSFileBackend( array(
00647                                         'name'        => 'local-backend',
00648                                         'lockManager' => 'fsLockManager',
00649                                         'containerPaths' => array(
00650                                                 'local-public'  => $this->uploadDir,
00651                                                 'local-thumb'   => $this->uploadDir . '/thumb',
00652                                                 'local-temp'    => $this->uploadDir . '/temp',
00653                                                 'local-deleted' => $this->uploadDir . '/delete',
00654                                         )
00655                                 ) )
00656                         ),
00657                         'wgEnableUploads' => self::getOptionValue( 'wgEnableUploads', $opts, true ),
00658                         'wgStylePath' => '/skins',
00659                         'wgStyleSheetPath' => '/skins',
00660                         'wgSitename' => 'MediaWiki',
00661                         'wgLanguageCode' => $lang,
00662                         'wgDBprefix' => $this->db->getType() != 'oracle' ? 'parsertest_' : 'pt_',
00663                         'wgRawHtml' => isset( $opts['rawhtml'] ),
00664                         'wgLang' => null,
00665                         'wgContLang' => null,
00666                         'wgNamespacesWithSubpages' => array( 0 => isset( $opts['subpage'] ) ),
00667                         'wgMaxTocLevel' => $maxtoclevel,
00668                         'wgCapitalLinks' => true,
00669                         'wgNoFollowLinks' => true,
00670                         'wgNoFollowDomainExceptions' => array(),
00671                         'wgThumbnailScriptPath' => false,
00672                         'wgUseImageResize' => false,
00673                         'wgLocaltimezone' => 'UTC',
00674                         'wgAllowExternalImages' => true,
00675                         'wgUseTidy' => false,
00676                         'wgDefaultLanguageVariant' => $variant,
00677                         'wgVariantArticlePath' => false,
00678                         'wgGroupPermissions' => array( '*' => array(
00679                                 'createaccount' => true,
00680                                 'read'          => true,
00681                                 'edit'          => true,
00682                                 'createpage'    => true,
00683                                 'createtalk'    => true,
00684                         ) ),
00685                         'wgNamespaceProtection' => array( NS_MEDIAWIKI => 'editinterface' ),
00686                         'wgDefaultExternalStore' => array(),
00687                         'wgForeignFileRepos' => array(),
00688                         'wgLinkHolderBatchSize' => $linkHolderBatchSize,
00689                         'wgExperimentalHtmlIds' => false,
00690                         'wgExternalLinkTarget' => false,
00691                         'wgAlwaysUseTidy' => false,
00692                         'wgHtml5' => true,
00693                         'wgWellFormedXml' => true,
00694                         'wgAllowMicrodataAttributes' => true,
00695                         'wgAdaptiveMessageCache' => true,
00696                         'wgDisableLangConversion' => false,
00697                         'wgDisableTitleConversion' => false,
00698                 );
00699 
00700                 if ( $config ) {
00701                         $configLines = explode( "\n", $config );
00702 
00703                         foreach ( $configLines as $line ) {
00704                                 list( $var, $value ) = explode( '=', $line, 2 );
00705 
00706                                 $settings[$var] = eval( "return $value;" );
00707                         }
00708                 }
00709 
00710                 $this->savedGlobals = array();
00711 
00713                 wfRunHooks( 'ParserTestGlobals', array( &$settings ) );
00714 
00715                 foreach ( $settings as $var => $val ) {
00716                         if ( array_key_exists( $var, $GLOBALS ) ) {
00717                                 $this->savedGlobals[$var] = $GLOBALS[$var];
00718                         }
00719 
00720                         $GLOBALS[$var] = $val;
00721                 }
00722 
00723                 $GLOBALS['wgContLang'] = Language::factory( $lang );
00724                 $GLOBALS['wgMemc'] = new EmptyBagOStuff;
00725 
00726                 $context = new RequestContext();
00727                 $GLOBALS['wgLang'] = $context->getLanguage();
00728                 $GLOBALS['wgOut'] = $context->getOutput();
00729 
00730                 $GLOBALS['wgUser'] = new User();
00731 
00732                 global $wgHooks;
00733 
00734                 $wgHooks['ParserTestParser'][] = 'ParserTestParserHook::setup';
00735                 $wgHooks['ParserGetVariableValueTs'][] = 'ParserTest::getFakeTimestamp';
00736 
00737                 MagicWord::clearCache();
00738 
00739                 return $context;
00740         }
00741 
00746         private function listTables() {
00747                 $tables = array( 'user', 'user_properties', 'user_former_groups', 'page', 'page_restrictions',
00748                         'protected_titles', 'revision', 'text', 'pagelinks', 'imagelinks',
00749                         'categorylinks', 'templatelinks', 'externallinks', 'langlinks', 'iwlinks',
00750                         'site_stats', 'hitcounter',     'ipblocks', 'image', 'oldimage',
00751                         'recentchanges', 'watchlist', 'interwiki', 'logging',
00752                         'querycache', 'objectcache', 'job', 'l10n_cache', 'redirect', 'querycachetwo',
00753                         'archive', 'user_groups', 'page_props', 'category', 'msg_resource', 'msg_resource_links'
00754                 );
00755 
00756                 if ( in_array( $this->db->getType(), array( 'mysql', 'sqlite', 'oracle' ) ) ) {
00757                         array_push( $tables, 'searchindex' );
00758                 }
00759 
00760                 // Allow extensions to add to the list of tables to duplicate;
00761                 // may be necessary if they hook into page save or other code
00762                 // which will require them while running tests.
00763                 wfRunHooks( 'ParserTestTables', array( &$tables ) );
00764 
00765                 return $tables;
00766         }
00767 
00773         public function setupDatabase() {
00774                 global $wgDBprefix;
00775 
00776                 if ( $this->databaseSetupDone ) {
00777                         return;
00778                 }
00779 
00780                 $this->db = wfGetDB( DB_MASTER );
00781                 $dbType = $this->db->getType();
00782 
00783                 if ( $wgDBprefix === 'parsertest_' || ( $dbType == 'oracle' && $wgDBprefix === 'pt_' ) ) {
00784                         throw new MWException( 'setupDatabase should be called before setupGlobals' );
00785                 }
00786 
00787                 $this->databaseSetupDone = true;
00788                 $this->oldTablePrefix = $wgDBprefix;
00789 
00790                 # SqlBagOStuff broke when using temporary tables on r40209 (bug 15892).
00791                 # It seems to have been fixed since (r55079?), but regressed at some point before r85701.
00792                 # This works around it for now...
00793                 ObjectCache::$instances[CACHE_DB] = new HashBagOStuff;
00794 
00795                 # CREATE TEMPORARY TABLE breaks if there is more than one server
00796                 if ( wfGetLB()->getServerCount() != 1 ) {
00797                         $this->useTemporaryTables = false;
00798                 }
00799 
00800                 $temporary = $this->useTemporaryTables || $dbType == 'postgres';
00801                 $prefix = $dbType != 'oracle' ? 'parsertest_' : 'pt_';
00802 
00803                 $this->dbClone = new CloneDatabase( $this->db, $this->listTables(), $prefix );
00804                 $this->dbClone->useTemporaryTables( $temporary );
00805                 $this->dbClone->cloneTableStructure();
00806 
00807                 if ( $dbType == 'oracle' ) {
00808                         $this->db->query( 'BEGIN FILL_WIKI_INFO; END;' );
00809                         # Insert 0 user to prevent FK violations
00810 
00811                         # Anonymous user
00812                         $this->db->insert( 'user', array(
00813                                 'user_id'         => 0,
00814                                 'user_name'       => 'Anonymous' ) );
00815                 }
00816 
00817                 # Hack: insert a few Wikipedia in-project interwiki prefixes,
00818                 # for testing inter-language links
00819                 $this->db->insert( 'interwiki', array(
00820                         array( 'iw_prefix' => 'wikipedia',
00821                                    'iw_url'    => 'http://en.wikipedia.org/wiki/$1',
00822                                    'iw_api'    => '',
00823                                    'iw_wikiid' => '',
00824                                    'iw_local'  => 0 ),
00825                         array( 'iw_prefix' => 'meatball',
00826                                    'iw_url'    => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
00827                                    'iw_api'    => '',
00828                                    'iw_wikiid' => '',
00829                                    'iw_local'  => 0 ),
00830                         array( 'iw_prefix' => 'zh',
00831                                    'iw_url'    => 'http://zh.wikipedia.org/wiki/$1',
00832                                    'iw_api'    => '',
00833                                    'iw_wikiid' => '',
00834                                    'iw_local'  => 1 ),
00835                         array( 'iw_prefix' => 'es',
00836                                    'iw_url'    => 'http://es.wikipedia.org/wiki/$1',
00837                                    'iw_api'    => '',
00838                                    'iw_wikiid' => '',
00839                                    'iw_local'  => 1 ),
00840                         array( 'iw_prefix' => 'fr',
00841                                    'iw_url'    => 'http://fr.wikipedia.org/wiki/$1',
00842                                    'iw_api'    => '',
00843                                    'iw_wikiid' => '',
00844                                    'iw_local'  => 1 ),
00845                         array( 'iw_prefix' => 'ru',
00846                                    'iw_url'    => 'http://ru.wikipedia.org/wiki/$1',
00847                                    'iw_api'    => '',
00848                                    'iw_wikiid' => '',
00849                                    'iw_local'  => 1 ),
00850                         ) );
00851 
00852                 # Update certain things in site_stats
00853                 $this->db->insert( 'site_stats', array( 'ss_row_id' => 1, 'ss_images' => 2, 'ss_good_articles' => 1 ) );
00854 
00855                 # Reinitialise the LocalisationCache to match the database state
00856                 Language::getLocalisationCache()->unloadAll();
00857 
00858                 # Clear the message cache
00859                 MessageCache::singleton()->clear();
00860 
00861                 $this->uploadDir = $this->setupUploadDir();
00862                 $user = User::createNew( 'WikiSysop' );
00863                 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Foobar.jpg' ) );
00864                 $image->recordUpload2( '', 'Upload of some lame file', 'Some lame file', array(
00865                         'size'        => 12345,
00866                         'width'       => 1941,
00867                         'height'      => 220,
00868                         'bits'        => 24,
00869                         'media_type'  => MEDIATYPE_BITMAP,
00870                         'mime'        => 'image/jpeg',
00871                         'metadata'    => serialize( array() ),
00872                         'sha1'        => wfBaseConvert( '', 16, 36, 31 ),
00873                         'fileExists'  => true
00874                         ), $this->db->timestamp( '20010115123500' ), $user );
00875 
00876                 # This image will be blacklisted in [[MediaWiki:Bad image list]]
00877                 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Bad.jpg' ) );
00878                 $image->recordUpload2( '', 'zomgnotcensored', 'Borderline image', array(
00879                         'size'        => 12345,
00880                         'width'       => 320,
00881                         'height'      => 240,
00882                         'bits'        => 24,
00883                         'media_type'  => MEDIATYPE_BITMAP,
00884                         'mime'        => 'image/jpeg',
00885                         'metadata'    => serialize( array() ),
00886                         'sha1'        => wfBaseConvert( '', 16, 36, 31 ),
00887                         'fileExists'  => true
00888                         ), $this->db->timestamp( '20010115123500' ), $user );
00889         }
00890 
00891         public function teardownDatabase() {
00892                 if ( !$this->databaseSetupDone ) {
00893                         $this->teardownGlobals();
00894                         return;
00895                 }
00896                 $this->teardownUploadDir( $this->uploadDir );
00897 
00898                 $this->dbClone->destroy();
00899                 $this->databaseSetupDone = false;
00900 
00901                 if ( $this->useTemporaryTables ) {
00902                         if( $this->db->getType() == 'sqlite' ) {
00903                                 # Under SQLite the searchindex table is virtual and need
00904                                 # to be explicitly destroyed. See bug 29912
00905                                 # See also MediaWikiTestCase::destroyDB()
00906                                 wfDebug( __METHOD__ . " explicitly destroying sqlite virtual table parsertest_searchindex\n" );
00907                                 $this->db->query( "DROP TABLE `parsertest_searchindex`" );
00908                         }
00909                         # Don't need to do anything
00910                         $this->teardownGlobals();
00911                         return;
00912                 }
00913 
00914                 $tables = $this->listTables();
00915 
00916                 foreach ( $tables as $table ) {
00917                         $sql = $this->db->getType() == 'oracle' ? "DROP TABLE pt_$table DROP CONSTRAINTS" : "DROP TABLE `parsertest_$table`";
00918                         $this->db->query( $sql );
00919                 }
00920 
00921                 if ( $this->db->getType() == 'oracle' )
00922                         $this->db->query( 'BEGIN FILL_WIKI_INFO; END;' );
00923 
00924                 $this->teardownGlobals();
00925         }
00926 
00933         private function setupUploadDir() {
00934                 global $IP;
00935 
00936                 if ( $this->keepUploads ) {
00937                         $dir = wfTempDir() . '/mwParser-images';
00938 
00939                         if ( is_dir( $dir ) ) {
00940                                 return $dir;
00941                         }
00942                 } else {
00943                         $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
00944                 }
00945 
00946                 // wfDebug( "Creating upload directory $dir\n" );
00947                 if ( file_exists( $dir ) ) {
00948                         wfDebug( "Already exists!\n" );
00949                         return $dir;
00950                 }
00951 
00952                 wfMkdirParents( $dir . '/3/3a', null, __METHOD__ );
00953                 copy( "$IP/skins/monobook/headbg.jpg", "$dir/3/3a/Foobar.jpg" );
00954                 wfMkdirParents( $dir . '/0/09', null, __METHOD__ );
00955                 copy( "$IP/skins/monobook/headbg.jpg", "$dir/0/09/Bad.jpg" );
00956 
00957                 return $dir;
00958         }
00959 
00964         private function teardownGlobals() {
00965                 RepoGroup::destroySingleton();
00966                 FileBackendGroup::destroySingleton();
00967                 LockManagerGroup::destroySingleton();
00968                 LinkCache::singleton()->clear();
00969 
00970                 foreach ( $this->savedGlobals as $var => $val ) {
00971                         $GLOBALS[$var] = $val;
00972                 }
00973         }
00974 
00978         private function teardownUploadDir( $dir ) {
00979                 if ( $this->keepUploads ) {
00980                         return;
00981                 }
00982 
00983                 // delete the files first, then the dirs.
00984                 self::deleteFiles(
00985                         array (
00986                                 "$dir/3/3a/Foobar.jpg",
00987                                 "$dir/thumb/3/3a/Foobar.jpg/180px-Foobar.jpg",
00988                                 "$dir/thumb/3/3a/Foobar.jpg/200px-Foobar.jpg",
00989                                 "$dir/thumb/3/3a/Foobar.jpg/640px-Foobar.jpg",
00990                                 "$dir/thumb/3/3a/Foobar.jpg/120px-Foobar.jpg",
00991 
00992                                 "$dir/0/09/Bad.jpg",
00993 
00994                                 "$dir/math/f/a/5/fa50b8b616463173474302ca3e63586b.png",
00995                         )
00996                 );
00997 
00998                 self::deleteDirs(
00999                         array (
01000                                 "$dir/3/3a",
01001                                 "$dir/3",
01002                                 "$dir/thumb/6/65",
01003                                 "$dir/thumb/6",
01004                                 "$dir/thumb/3/3a/Foobar.jpg",
01005                                 "$dir/thumb/3/3a",
01006                                 "$dir/thumb/3",
01007 
01008                                 "$dir/0/09/",
01009                                 "$dir/0/",
01010                                 "$dir/thumb",
01011                                 "$dir/math/f/a/5",
01012                                 "$dir/math/f/a",
01013                                 "$dir/math/f",
01014                                 "$dir/math",
01015                                 "$dir",
01016                         )
01017                 );
01018         }
01019 
01024         private static function deleteFiles( $files ) {
01025                 foreach ( $files as $file ) {
01026                         if ( file_exists( $file ) ) {
01027                                 unlink( $file );
01028                         }
01029                 }
01030         }
01031 
01036         private static function deleteDirs( $dirs ) {
01037                 foreach ( $dirs as $dir ) {
01038                         if ( is_dir( $dir ) ) {
01039                                 rmdir( $dir );
01040                         }
01041                 }
01042         }
01043 
01047         protected function showTesting( $desc ) {
01048                 print "Running test $desc... ";
01049         }
01050 
01057         protected function showSuccess( $desc ) {
01058                 if ( $this->showProgress ) {
01059                         print $this->term->color( '1;32' ) . 'PASSED' . $this->term->reset() . "\n";
01060                 }
01061 
01062                 return true;
01063         }
01064 
01074         protected function showFailure( $desc, $result, $html ) {
01075                 if ( $this->showFailure ) {
01076                         if ( !$this->showProgress ) {
01077                                 # In quiet mode we didn't show the 'Testing' message before the
01078                                 # test, in case it succeeded. Show it now:
01079                                 $this->showTesting( $desc );
01080                         }
01081 
01082                         print $this->term->color( '31' ) . 'FAILED!' . $this->term->reset() . "\n";
01083 
01084                         if ( $this->showOutput ) {
01085                                 print "--- Expected ---\n$result\n--- Actual ---\n$html\n";
01086                         }
01087 
01088                         if ( $this->showDiffs ) {
01089                                 print $this->quickDiff( $result, $html );
01090                                 if ( !$this->wellFormed( $html ) ) {
01091                                         print "XML error: $this->mXmlError\n";
01092                                 }
01093                         }
01094                 }
01095 
01096                 return false;
01097         }
01098 
01109         protected function quickDiff( $input, $output, $inFileTail = 'expected', $outFileTail = 'actual' ) {
01110                 # Windows, or at least the fc utility, is retarded
01111                 $slash = wfIsWindows() ? '\\' : '/';
01112                 $prefix = wfTempDir() . "{$slash}mwParser-" . mt_rand();
01113 
01114                 $infile = "$prefix-$inFileTail";
01115                 $this->dumpToFile( $input, $infile );
01116 
01117                 $outfile = "$prefix-$outFileTail";
01118                 $this->dumpToFile( $output, $outfile );
01119 
01120                 $shellInfile = wfEscapeShellArg($infile);
01121                 $shellOutfile = wfEscapeShellArg($outfile);
01122 
01123                 global $wgDiff3;
01124                 // we assume that people with diff3 also have usual diff
01125                 $diff = ( wfIsWindows() && !$wgDiff3 )
01126                         ? `fc $shellInfile $shellOutfile`
01127                         : `diff -au $shellInfile $shellOutfile`;
01128                 unlink( $infile );
01129                 unlink( $outfile );
01130 
01131                 return $this->colorDiff( $diff );
01132         }
01133 
01140         private function dumpToFile( $data, $filename ) {
01141                 $file = fopen( $filename, "wt" );
01142                 fwrite( $file, $data . "\n" );
01143                 fclose( $file );
01144         }
01145 
01153         protected function colorDiff( $text ) {
01154                 return preg_replace(
01155                         array( '/^(-.*)$/m', '/^(\+.*)$/m' ),
01156                         array( $this->term->color( 34 ) . '$1' . $this->term->reset(),
01157                                    $this->term->color( 31 ) . '$1' . $this->term->reset() ),
01158                         $text );
01159         }
01160 
01166         public function showRunFile( $path ) {
01167                 print $this->term->color( 1 ) .
01168                         "Reading tests from \"$path\"..." .
01169                         $this->term->reset() .
01170                         "\n";
01171         }
01172 
01180         static public function addArticle( $name, $text, $line = 'unknown', $ignoreDuplicate = '' ) {
01181                 global $wgCapitalLinks;
01182 
01183                 $oldCapitalLinks = $wgCapitalLinks;
01184                 $wgCapitalLinks = true; // We only need this from SetupGlobals() See r70917#c8637
01185 
01186                 $text = self::chomp( $text );
01187                 $name = self::chomp( $name );
01188 
01189                 $title = Title::newFromText( $name );
01190 
01191                 if ( is_null( $title ) ) {
01192                         throw new MWException( "invalid title '$name' at line $line\n" );
01193                 }
01194 
01195                 $page = WikiPage::factory( $title );
01196                 $page->loadPageData( 'fromdbmaster' );
01197 
01198                 if ( $page->exists() ) {
01199                         if ( $ignoreDuplicate == 'ignoreduplicate' ) {
01200                                 return;
01201                         } else {
01202                                 throw new MWException( "duplicate article '$name' at line $line\n" );
01203                         }
01204                 }
01205 
01206                 $page->doEdit( $text, '', EDIT_NEW );
01207 
01208                 $wgCapitalLinks = $oldCapitalLinks;
01209         }
01210 
01219         public function requireHook( $name ) {
01220                 global $wgParser;
01221 
01222                 $wgParser->firstCallInit( ); // make sure hooks are loaded.
01223 
01224                 if ( isset( $wgParser->mTagHooks[$name] ) ) {
01225                         $this->hooks[$name] = $wgParser->mTagHooks[$name];
01226                 } else {
01227                         echo "   This test suite requires the '$name' hook extension, skipping.\n";
01228                         return false;
01229                 }
01230 
01231                 return true;
01232         }
01233 
01242         public function requireFunctionHook( $name ) {
01243                 global $wgParser;
01244 
01245                 $wgParser->firstCallInit( ); // make sure hooks are loaded.
01246 
01247                 if ( isset( $wgParser->mFunctionHooks[$name] ) ) {
01248                         $this->functionHooks[$name] = $wgParser->mFunctionHooks[$name];
01249                 } else {
01250                         echo "   This test suite requires the '$name' function hook extension, skipping.\n";
01251                         return false;
01252                 }
01253 
01254                 return true;
01255         }
01256 
01264         private function tidy( $text ) {
01265                 global $wgUseTidy;
01266 
01267                 if ( $wgUseTidy ) {
01268                         $text = MWTidy::tidy( $text );
01269                 }
01270 
01271                 return $text;
01272         }
01273 
01274         private function wellFormed( $text ) {
01275                 $html =
01276                         Sanitizer::hackDocType() .
01277                         '<html>' .
01278                         $text .
01279                         '</html>';
01280 
01281                 $parser = xml_parser_create( "UTF-8" );
01282 
01283                 # case folding violates XML standard, turn it off
01284                 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
01285 
01286                 if ( !xml_parse( $parser, $html, true ) ) {
01287                         $err = xml_error_string( xml_get_error_code( $parser ) );
01288                         $position = xml_get_current_byte_index( $parser );
01289                         $fragment = $this->extractFragment( $html, $position );
01290                         $this->mXmlError = "$err at byte $position:\n$fragment";
01291                         xml_parser_free( $parser );
01292 
01293                         return false;
01294                 }
01295 
01296                 xml_parser_free( $parser );
01297 
01298                 return true;
01299         }
01300 
01301         private function extractFragment( $text, $position ) {
01302                 $start = max( 0, $position - 10 );
01303                 $before = $position - $start;
01304                 $fragment = '...' .
01305                         $this->term->color( 34 ) .
01306                         substr( $text, $start, $before ) .
01307                         $this->term->color( 0 ) .
01308                         $this->term->color( 31 ) .
01309                         $this->term->color( 1 ) .
01310                         substr( $text, $position, 1 ) .
01311                         $this->term->color( 0 ) .
01312                         $this->term->color( 34 ) .
01313                         substr( $text, $position + 1, 9 ) .
01314                         $this->term->color( 0 ) .
01315                         '...';
01316                 $display = str_replace( "\n", ' ', $fragment );
01317                 $caret = '   ' .
01318                         str_repeat( ' ', $before ) .
01319                         $this->term->color( 31 ) .
01320                         '^' .
01321                         $this->term->color( 0 );
01322 
01323                 return "$display\n$caret";
01324         }
01325 
01326         static function getFakeTimestamp( &$parser, &$ts ) {
01327                 $ts = 123;
01328                 return true;
01329         }
01330 }