MediaWiki  REL1_19
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;
00144 
00145                 $wgScript = '/index.php';
00146                 $wgScriptPath = '/';
00147                 $wgArticlePath = '/wiki/$1';
00148                 $wgStyleSheetPath = '/skins';
00149                 $wgStylePath = '/skins';
00150                 $wgExtensionAssetsPath = '/extensions';
00151                 $wgThumbnailScriptPath = false;
00152                 $wgLocalFileRepo = array(
00153                         'class'           => 'LocalRepo',
00154                         'name'            => 'local',
00155                         'url'             => 'http://example.com/images',
00156                         'hashLevels'      => 2,
00157                         'transformVia404' => false,
00158                         'backend'         => new FSFileBackend( array(
00159                                 'name'        => 'local-backend',
00160                                 'lockManager' => 'fsLockManager',
00161                                 'containerPaths' => array(
00162                                         'local-public'  => wfTempDir() . '/test-repo/public',
00163                                         'local-thumb'   => wfTempDir() . '/test-repo/thumb',
00164                                         'local-temp'    => wfTempDir() . '/test-repo/temp',
00165                                         'local-deleted' => wfTempDir() . '/test-repo/deleted',
00166                                 )
00167                         ) )
00168                 );
00169                 $wgNamespaceProtection[NS_MEDIAWIKI] = 'editinterface';
00170                 $wgNamespaceAliases['Image'] = NS_FILE;
00171                 $wgNamespaceAliases['Image_talk'] = NS_FILE_TALK;
00172 
00173                 // XXX: tests won't run without this (for CACHE_DB)
00174                 if ( $wgMainCacheType === CACHE_DB ) {
00175                         $wgMainCacheType = CACHE_NONE;
00176                 }
00177                 if ( $wgMessageCacheType === CACHE_DB ) {
00178                         $wgMessageCacheType = CACHE_NONE;
00179                 }
00180                 if ( $wgParserCacheType === CACHE_DB ) {
00181                         $wgParserCacheType = CACHE_NONE;
00182                 }
00183 
00184                 $wgEnableParserCache = false;
00185                 DeferredUpdates::clearPendingUpdates();
00186                 $wgMemc = wfGetMainCache(); // checks $wgMainCacheType
00187                 $messageMemc = wfGetMessageCacheStorage();
00188                 $parserMemc = wfGetParserCacheStorage();
00189 
00190                 // $wgContLang = new StubContLang;
00191                 $wgUser = new User;
00192                 $context = new RequestContext;
00193                 $wgLang = $context->getLanguage();
00194                 $wgOut = $context->getOutput();
00195                 $wgParser = new StubObject( 'wgParser', $wgParserConf['class'], array( $wgParserConf ) );
00196                 $wgRequest = $context->getRequest();
00197 
00198                 if ( $wgStyleDirectory === false ) {
00199                         $wgStyleDirectory   = "$IP/skins";
00200                 }
00201 
00202         }
00203 
00204         public function setupRecorder ( $options ) {
00205                 if ( isset( $options['record'] ) ) {
00206                         $this->recorder = new DbTestRecorder( $this );
00207                         $this->recorder->version = isset( $options['setversion'] ) ?
00208                                         $options['setversion'] : SpecialVersion::getVersion();
00209                 } elseif ( isset( $options['compare'] ) ) {
00210                         $this->recorder = new DbTestPreviewer( $this );
00211                 } else {
00212                         $this->recorder = new TestRecorder( $this );
00213                 }
00214         }
00215 
00220         static public function chomp( $s ) {
00221                 if ( substr( $s, -1 ) === "\n" ) {
00222                         return substr( $s, 0, -1 );
00223                 }
00224                 else {
00225                         return $s;
00226                 }
00227         }
00228 
00233         function fuzzTest( $filenames ) {
00234                 $GLOBALS['wgContLang'] = Language::factory( 'en' );
00235                 $dict = $this->getFuzzInput( $filenames );
00236                 $dictSize = strlen( $dict );
00237                 $logMaxLength = log( $this->maxFuzzTestLength );
00238                 $this->setupDatabase();
00239                 ini_set( 'memory_limit', $this->memoryLimit * 1048576 );
00240 
00241                 $numTotal = 0;
00242                 $numSuccess = 0;
00243                 $user = new User;
00244                 $opts = ParserOptions::newFromUser( $user );
00245                 $title = Title::makeTitle( NS_MAIN, 'Parser_test' );
00246 
00247                 while ( true ) {
00248                         // Generate test input
00249                         mt_srand( ++$this->fuzzSeed );
00250                         $totalLength = mt_rand( 1, $this->maxFuzzTestLength );
00251                         $input = '';
00252 
00253                         while ( strlen( $input ) < $totalLength ) {
00254                                 $logHairLength = mt_rand( 0, 1000000 ) / 1000000 * $logMaxLength;
00255                                 $hairLength = min( intval( exp( $logHairLength ) ), $dictSize );
00256                                 $offset = mt_rand( 0, $dictSize - $hairLength );
00257                                 $input .= substr( $dict, $offset, $hairLength );
00258                         }
00259 
00260                         $this->setupGlobals();
00261                         $parser = $this->getParser();
00262 
00263                         // Run the test
00264                         try {
00265                                 $parser->parse( $input, $title, $opts );
00266                                 $fail = false;
00267                         } catch ( Exception $exception ) {
00268                                 $fail = true;
00269                         }
00270 
00271                         if ( $fail ) {
00272                                 echo "Test failed with seed {$this->fuzzSeed}\n";
00273                                 echo "Input:\n";
00274                                 printf( "string(%d) \"%s\"\n\n", strlen( $input ), $input );
00275                                 echo "$exception\n";
00276                         } else {
00277                                 $numSuccess++;
00278                         }
00279 
00280                         $numTotal++;
00281                         $this->teardownGlobals();
00282                         $parser->__destruct();
00283 
00284                         if ( $numTotal % 100 == 0 ) {
00285                                 $usage = intval( memory_get_usage( true ) / $this->memoryLimit / 1048576 * 100 );
00286                                 echo "{$this->fuzzSeed}: $numSuccess/$numTotal (mem: $usage%)\n";
00287                                 if ( $usage > 90 ) {
00288                                         echo "Out of memory:\n";
00289                                         $memStats = $this->getMemoryBreakdown();
00290 
00291                                         foreach ( $memStats as $name => $usage ) {
00292                                                 echo "$name: $usage\n";
00293                                         }
00294                                         $this->abort();
00295                                 }
00296                         }
00297                 }
00298         }
00299 
00303         function getFuzzInput( $filenames ) {
00304                 $dict = '';
00305 
00306                 foreach ( $filenames as $filename ) {
00307                         $contents = file_get_contents( $filename );
00308                         preg_match_all( '/!!\s*input\n(.*?)\n!!\s*result/s', $contents, $matches );
00309 
00310                         foreach ( $matches[1] as $match ) {
00311                                 $dict .= $match . "\n";
00312                         }
00313                 }
00314 
00315                 return $dict;
00316         }
00317 
00321         function getMemoryBreakdown() {
00322                 $memStats = array();
00323 
00324                 foreach ( $GLOBALS as $name => $value ) {
00325                         $memStats['$' . $name] = strlen( serialize( $value ) );
00326                 }
00327 
00328                 $classes = get_declared_classes();
00329 
00330                 foreach ( $classes as $class ) {
00331                         $rc = new ReflectionClass( $class );
00332                         $props = $rc->getStaticProperties();
00333                         $memStats[$class] = strlen( serialize( $props ) );
00334                         $methods = $rc->getMethods();
00335 
00336                         foreach ( $methods as $method ) {
00337                                 $memStats[$class] += strlen( serialize( $method->getStaticVariables() ) );
00338                         }
00339                 }
00340 
00341                 $functions = get_defined_functions();
00342 
00343                 foreach ( $functions['user'] as $function ) {
00344                         $rf = new ReflectionFunction( $function );
00345                         $memStats["$function()"] = strlen( serialize( $rf->getStaticVariables() ) );
00346                 }
00347 
00348                 asort( $memStats );
00349 
00350                 return $memStats;
00351         }
00352 
00353         function abort() {
00354                 $this->abort();
00355         }
00356 
00368         public function runTestsFromFiles( $filenames ) {
00369                 $ok = false;
00370                 $GLOBALS['wgContLang'] = Language::factory( 'en' );
00371                 $this->recorder->start();
00372                 try {
00373                         $this->setupDatabase();
00374                         $ok = true;
00375 
00376                         foreach ( $filenames as $filename ) {
00377                                 $tests = new TestFileIterator( $filename, $this );
00378                                 $ok = $this->runTests( $tests ) && $ok;
00379                         }
00380 
00381                         $this->teardownDatabase();
00382                         $this->recorder->report();
00383                 } catch (DBError $e) {
00384                         echo $e->getMessage();
00385                 }
00386                 $this->recorder->end();
00387 
00388                 return $ok;
00389         }
00390 
00391         function runTests( $tests ) {
00392                 $ok = true;
00393 
00394                 foreach ( $tests as $t ) {
00395                         $result =
00396                                 $this->runTest( $t['test'], $t['input'], $t['result'], $t['options'], $t['config'] );
00397                         $ok = $ok && $result;
00398                         $this->recorder->record( $t['test'], $result );
00399                 }
00400 
00401                 if ( $this->showProgress ) {
00402                         print "\n";
00403                 }
00404 
00405                 return $ok;
00406         }
00407 
00411         function getParser( $preprocessor = null ) {
00412                 global $wgParserConf;
00413 
00414                 $class = $wgParserConf['class'];
00415                 $parser = new $class( array( 'preprocessorClass' => $preprocessor ) + $wgParserConf );
00416 
00417                 foreach ( $this->hooks as $tag => $callback ) {
00418                         $parser->setHook( $tag, $callback );
00419                 }
00420 
00421                 foreach ( $this->functionHooks as $tag => $bits ) {
00422                         list( $callback, $flags ) = $bits;
00423                         $parser->setFunctionHook( $tag, $callback, $flags );
00424                 }
00425 
00426                 wfRunHooks( 'ParserTestParser', array( &$parser ) );
00427 
00428                 return $parser;
00429         }
00430 
00443         public function runTest( $desc, $input, $result, $opts, $config ) {
00444                 if ( $this->showProgress ) {
00445                         $this->showTesting( $desc );
00446                 }
00447 
00448                 $opts = $this->parseOptions( $opts );
00449                 $context = $this->setupGlobals( $opts, $config );
00450 
00451                 $user = $context->getUser();
00452                 $options = ParserOptions::newFromContext( $context );
00453 
00454                 if ( isset( $opts['title'] ) ) {
00455                         $titleText = $opts['title'];
00456                 }
00457                 else {
00458                         $titleText = 'Parser test';
00459                 }
00460 
00461                 $local = isset( $opts['local'] );
00462                 $preprocessor = isset( $opts['preprocessor'] ) ? $opts['preprocessor'] : null;
00463                 $parser = $this->getParser( $preprocessor );
00464                 $title = Title::newFromText( $titleText );
00465 
00466                 if ( isset( $opts['pst'] ) ) {
00467                         $out = $parser->preSaveTransform( $input, $title, $user, $options );
00468                 } elseif ( isset( $opts['msg'] ) ) {
00469                         $out = $parser->transformMsg( $input, $options, $title );
00470                 } elseif ( isset( $opts['section'] ) ) {
00471                         $section = $opts['section'];
00472                         $out = $parser->getSection( $input, $section );
00473                 } elseif ( isset( $opts['replace'] ) ) {
00474                         $section = $opts['replace'][0];
00475                         $replace = $opts['replace'][1];
00476                         $out = $parser->replaceSection( $input, $section, $replace );
00477                 } elseif ( isset( $opts['comment'] ) ) {
00478                         $out = Linker::formatComment( $input, $title, $local );
00479                 } elseif ( isset( $opts['preload'] ) ) {
00480                         $out = $parser->getpreloadText( $input, $title, $options );
00481                 } else {
00482                         $output = $parser->parse( $input, $title, $options, true, true, 1337 );
00483                         $out = $output->getText();
00484 
00485                         if ( isset( $opts['showtitle'] ) ) {
00486                                 if ( $output->getTitleText() ) {
00487                                         $title = $output->getTitleText();
00488                                 }
00489 
00490                                 $out = "$title\n$out";
00491                         }
00492 
00493                         if ( isset( $opts['ill'] ) ) {
00494                                 $out = $this->tidy( implode( ' ', $output->getLanguageLinks() ) );
00495                         } elseif ( isset( $opts['cat'] ) ) {
00496                                 $outputPage = $context->getOutput();
00497                                 $outputPage->addCategoryLinks( $output->getCategories() );
00498                                 $cats = $outputPage->getCategoryLinks();
00499 
00500                                 if ( isset( $cats['normal'] ) ) {
00501                                         $out = $this->tidy( implode( ' ', $cats['normal'] ) );
00502                                 } else {
00503                                         $out = '';
00504                                 }
00505                         }
00506 
00507                         $result = $this->tidy( $result );
00508                 }
00509 
00510                 $this->teardownGlobals();
00511                 return $this->showTestResult( $desc, $result, $out );
00512         }
00513 
00517         function showTestResult( $desc, $result, $out ) {
00518                 if ( $result === $out ) {
00519                         $this->showSuccess( $desc );
00520                         return true;
00521                 } else {
00522                         $this->showFailure( $desc, $result, $out );
00523                         return false;
00524                 }
00525         }
00526 
00533         private static function getOptionValue( $key, $opts, $default ) {
00534                 $key = strtolower( $key );
00535 
00536                 if ( isset( $opts[$key] ) ) {
00537                         return $opts[$key];
00538                 } else {
00539                         return $default;
00540                 }
00541         }
00542 
00543         private function parseOptions( $instring ) {
00544                 $opts = array();
00545                 // foo
00546                 // foo=bar
00547                 // foo="bar baz"
00548                 // foo=[[bar baz]]
00549                 // foo=bar,"baz quux"
00550                 $regex = '/\b
00551                         ([\w-]+)                                                # Key
00552                         \b
00553                         (?:\s*
00554                                 =                                               # First sub-value
00555                                 \s*
00556                                 (
00557                                         "
00558                                                 [^"]*                   # Quoted val
00559                                         "
00560                                 |
00561                                         \[\[
00562                                                 [^]]*                   # Link target
00563                                         \]\]
00564                                 |
00565                                         [\w-]+                          # Plain word
00566                                 )
00567                                 (?:\s*
00568                                         ,                                       # Sub-vals 1..N
00569                                         \s*
00570                                         (
00571                                                 "[^"]*"                 # Quoted val
00572                                         |
00573                                                 \[\[[^]]*\]\]   # Link target
00574                                         |
00575                                                 [\w-]+                  # Plain word
00576                                         )
00577                                 )*
00578                         )?
00579                         /x';
00580 
00581                 if ( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER ) ) {
00582                         foreach ( $matches as $bits ) {
00583                                 array_shift( $bits );
00584                                 $key = strtolower( array_shift( $bits ) );
00585                                 if ( count( $bits ) == 0 ) {
00586                                         $opts[$key] = true;
00587                                 } elseif ( count( $bits ) == 1 ) {
00588                                         $opts[$key] = $this->cleanupOption( array_shift( $bits ) );
00589                                 } else {
00590                                         // Array!
00591                                         $opts[$key] = array_map( array( $this, 'cleanupOption' ), $bits );
00592                                 }
00593                         }
00594                 }
00595                 return $opts;
00596         }
00597 
00598         private function cleanupOption( $opt ) {
00599                 if ( substr( $opt, 0, 1 ) == '"' ) {
00600                         return substr( $opt, 1, -1 );
00601                 }
00602 
00603                 if ( substr( $opt, 0, 2 ) == '[[' ) {
00604                         return substr( $opt, 2, -2 );
00605                 }
00606                 return $opt;
00607         }
00608 
00613         private function setupGlobals( $opts = '', $config = '' ) {
00614                 # Find out values for some special options.
00615                 $lang =
00616                         self::getOptionValue( 'language', $opts, 'en' );
00617                 $variant =
00618                         self::getOptionValue( 'variant', $opts, false );
00619                 $maxtoclevel =
00620                         self::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
00621                 $linkHolderBatchSize =
00622                         self::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
00623 
00624                 $settings = array(
00625                         'wgServer' => 'http://Britney-Spears',
00626                         'wgScript' => '/index.php',
00627                         'wgScriptPath' => '/',
00628                         'wgArticlePath' => '/wiki/$1',
00629                         'wgActionPaths' => array(),
00630                         'wgLocalFileRepo' => array(
00631                                 'class' => 'LocalRepo',
00632                                 'name' => 'local',
00633                                 'url' => 'http://example.com/images',
00634                                 'hashLevels' => 2,
00635                                 'transformVia404' => false,
00636                                 'backend'         => new FSFileBackend( array(
00637                                         'name'        => 'local-backend',
00638                                         'lockManager' => 'fsLockManager',
00639                                         'containerPaths' => array(
00640                                                 'local-public'  => $this->uploadDir,
00641                                                 'local-thumb'   => $this->uploadDir . '/thumb',
00642                                                 'local-temp'    => $this->uploadDir . '/temp',
00643                                                 'local-deleted' => $this->uploadDir . '/delete',
00644                                         )
00645                                 ) )
00646                         ),
00647                         'wgEnableUploads' => self::getOptionValue( 'wgEnableUploads', $opts, true ),
00648                         'wgStylePath' => '/skins',
00649                         'wgStyleSheetPath' => '/skins',
00650                         'wgSitename' => 'MediaWiki',
00651                         'wgLanguageCode' => $lang,
00652                         'wgDBprefix' => $this->db->getType() != 'oracle' ? 'parsertest_' : 'pt_',
00653                         'wgRawHtml' => isset( $opts['rawhtml'] ),
00654                         'wgLang' => null,
00655                         'wgContLang' => null,
00656                         'wgNamespacesWithSubpages' => array( 0 => isset( $opts['subpage'] ) ),
00657                         'wgMaxTocLevel' => $maxtoclevel,
00658                         'wgCapitalLinks' => true,
00659                         'wgNoFollowLinks' => true,
00660                         'wgNoFollowDomainExceptions' => array(),
00661                         'wgThumbnailScriptPath' => false,
00662                         'wgUseImageResize' => false,
00663                         'wgLocaltimezone' => 'UTC',
00664                         'wgAllowExternalImages' => true,
00665                         'wgUseTidy' => false,
00666                         'wgDefaultLanguageVariant' => $variant,
00667                         'wgVariantArticlePath' => false,
00668                         'wgGroupPermissions' => array( '*' => array(
00669                                 'createaccount' => true,
00670                                 'read'          => true,
00671                                 'edit'          => true,
00672                                 'createpage'    => true,
00673                                 'createtalk'    => true,
00674                         ) ),
00675                         'wgNamespaceProtection' => array( NS_MEDIAWIKI => 'editinterface' ),
00676                         'wgDefaultExternalStore' => array(),
00677                         'wgForeignFileRepos' => array(),
00678                         'wgLinkHolderBatchSize' => $linkHolderBatchSize,
00679                         'wgExperimentalHtmlIds' => false,
00680                         'wgExternalLinkTarget' => false,
00681                         'wgAlwaysUseTidy' => false,
00682                         'wgHtml5' => true,
00683                         'wgCleanupPresentationalAttributes' => true,
00684                         'wgWellFormedXml' => true,
00685                         'wgAllowMicrodataAttributes' => true,
00686                         'wgAdaptiveMessageCache' => true,
00687                         'wgDisableLangConversion' => false,
00688                         'wgDisableTitleConversion' => false,
00689                 );
00690 
00691                 if ( $config ) {
00692                         $configLines = explode( "\n", $config );
00693 
00694                         foreach ( $configLines as $line ) {
00695                                 list( $var, $value ) = explode( '=', $line, 2 );
00696 
00697                                 $settings[$var] = eval( "return $value;" );
00698                         }
00699                 }
00700 
00701                 $this->savedGlobals = array();
00702 
00703                 foreach ( $settings as $var => $val ) {
00704                         if ( array_key_exists( $var, $GLOBALS ) ) {
00705                                 $this->savedGlobals[$var] = $GLOBALS[$var];
00706                         }
00707 
00708                         $GLOBALS[$var] = $val;
00709                 }
00710 
00711                 $GLOBALS['wgContLang'] = Language::factory( $lang );
00712                 $GLOBALS['wgMemc'] = new EmptyBagOStuff;
00713 
00714                 $context = new RequestContext();
00715                 $GLOBALS['wgLang'] = $context->getLanguage();
00716                 $GLOBALS['wgOut'] = $context->getOutput();
00717 
00718                 $GLOBALS['wgUser'] = new User();
00719 
00720                 global $wgHooks;
00721 
00722                 $wgHooks['ParserTestParser'][] = 'ParserTestParserHook::setup';
00723                 $wgHooks['ParserGetVariableValueTs'][] = 'ParserTest::getFakeTimestamp';
00724 
00725                 MagicWord::clearCache();
00726 
00727                 return $context;
00728         }
00729 
00734         private function listTables() {
00735                 $tables = array( 'user', 'user_properties', 'user_former_groups', 'page', 'page_restrictions',
00736                         'protected_titles', 'revision', 'text', 'pagelinks', 'imagelinks',
00737                         'categorylinks', 'templatelinks', 'externallinks', 'langlinks', 'iwlinks',
00738                         'site_stats', 'hitcounter',     'ipblocks', 'image', 'oldimage',
00739                         'recentchanges', 'watchlist', 'interwiki', 'logging',
00740                         'querycache', 'objectcache', 'job', 'l10n_cache', 'redirect', 'querycachetwo',
00741                         'archive', 'user_groups', 'page_props', 'category', 'msg_resource', 'msg_resource_links'
00742                 );
00743 
00744                 if ( in_array( $this->db->getType(), array( 'mysql', 'sqlite', 'oracle' ) ) ) {
00745                         array_push( $tables, 'searchindex' );
00746                 }
00747 
00748                 // Allow extensions to add to the list of tables to duplicate;
00749                 // may be necessary if they hook into page save or other code
00750                 // which will require them while running tests.
00751                 wfRunHooks( 'ParserTestTables', array( &$tables ) );
00752 
00753                 return $tables;
00754         }
00755 
00761         public function setupDatabase() {
00762                 global $wgDBprefix;
00763 
00764                 if ( $this->databaseSetupDone ) {
00765                         return;
00766                 }
00767 
00768                 $this->db = wfGetDB( DB_MASTER );
00769                 $dbType = $this->db->getType();
00770 
00771                 if ( $wgDBprefix === 'parsertest_' || ( $dbType == 'oracle' && $wgDBprefix === 'pt_' ) ) {
00772                         throw new MWException( 'setupDatabase should be called before setupGlobals' );
00773                 }
00774 
00775                 $this->databaseSetupDone = true;
00776                 $this->oldTablePrefix = $wgDBprefix;
00777 
00778                 # SqlBagOStuff broke when using temporary tables on r40209 (bug 15892).
00779                 # It seems to have been fixed since (r55079?), but regressed at some point before r85701.
00780                 # This works around it for now...
00781                 ObjectCache::$instances[CACHE_DB] = new HashBagOStuff;
00782 
00783                 # CREATE TEMPORARY TABLE breaks if there is more than one server
00784                 if ( wfGetLB()->getServerCount() != 1 ) {
00785                         $this->useTemporaryTables = false;
00786                 }
00787 
00788                 $temporary = $this->useTemporaryTables || $dbType == 'postgres';
00789                 $prefix = $dbType != 'oracle' ? 'parsertest_' : 'pt_';
00790 
00791                 $this->dbClone = new CloneDatabase( $this->db, $this->listTables(), $prefix );
00792                 $this->dbClone->useTemporaryTables( $temporary );
00793                 $this->dbClone->cloneTableStructure();
00794 
00795                 if ( $dbType == 'oracle' ) {
00796                         $this->db->query( 'BEGIN FILL_WIKI_INFO; END;' );
00797                         # Insert 0 user to prevent FK violations
00798 
00799                         # Anonymous user
00800                         $this->db->insert( 'user', array(
00801                                 'user_id'         => 0,
00802                                 'user_name'       => 'Anonymous' ) );
00803                 }
00804 
00805                 # Hack: insert a few Wikipedia in-project interwiki prefixes,
00806                 # for testing inter-language links
00807                 $this->db->insert( 'interwiki', array(
00808                         array( 'iw_prefix' => 'wikipedia',
00809                                    'iw_url'    => 'http://en.wikipedia.org/wiki/$1',
00810                                    'iw_api'    => '',
00811                                    'iw_wikiid' => '',
00812                                    'iw_local'  => 0 ),
00813                         array( 'iw_prefix' => 'meatball',
00814                                    'iw_url'    => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
00815                                    'iw_api'    => '',
00816                                    'iw_wikiid' => '',
00817                                    'iw_local'  => 0 ),
00818                         array( 'iw_prefix' => 'zh',
00819                                    'iw_url'    => 'http://zh.wikipedia.org/wiki/$1',
00820                                    'iw_api'    => '',
00821                                    'iw_wikiid' => '',
00822                                    'iw_local'  => 1 ),
00823                         array( 'iw_prefix' => 'es',
00824                                    'iw_url'    => 'http://es.wikipedia.org/wiki/$1',
00825                                    'iw_api'    => '',
00826                                    'iw_wikiid' => '',
00827                                    'iw_local'  => 1 ),
00828                         array( 'iw_prefix' => 'fr',
00829                                    'iw_url'    => 'http://fr.wikipedia.org/wiki/$1',
00830                                    'iw_api'    => '',
00831                                    'iw_wikiid' => '',
00832                                    'iw_local'  => 1 ),
00833                         array( 'iw_prefix' => 'ru',
00834                                    'iw_url'    => 'http://ru.wikipedia.org/wiki/$1',
00835                                    'iw_api'    => '',
00836                                    'iw_wikiid' => '',
00837                                    'iw_local'  => 1 ),
00838                         ) );
00839 
00840                 # Update certain things in site_stats
00841                 $this->db->insert( 'site_stats', array( 'ss_row_id' => 1, 'ss_images' => 2, 'ss_good_articles' => 1 ) );
00842 
00843                 # Reinitialise the LocalisationCache to match the database state
00844                 Language::getLocalisationCache()->unloadAll();
00845 
00846                 # Clear the message cache
00847                 MessageCache::singleton()->clear();
00848 
00849                 $this->uploadDir = $this->setupUploadDir();
00850                 $user = User::createNew( 'WikiSysop' );
00851                 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Foobar.jpg' ) );
00852                 $image->recordUpload2( '', 'Upload of some lame file', 'Some lame file', array(
00853                         'size'        => 12345,
00854                         'width'       => 1941,
00855                         'height'      => 220,
00856                         'bits'        => 24,
00857                         'media_type'  => MEDIATYPE_BITMAP,
00858                         'mime'        => 'image/jpeg',
00859                         'metadata'    => serialize( array() ),
00860                         'sha1'        => wfBaseConvert( '', 16, 36, 31 ),
00861                         'fileExists'  => true
00862                         ), $this->db->timestamp( '20010115123500' ), $user );
00863 
00864                 # This image will be blacklisted in [[MediaWiki:Bad image list]]
00865                 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Bad.jpg' ) );
00866                 $image->recordUpload2( '', 'zomgnotcensored', 'Borderline image', array(
00867                         'size'        => 12345,
00868                         'width'       => 320,
00869                         'height'      => 240,
00870                         'bits'        => 24,
00871                         'media_type'  => MEDIATYPE_BITMAP,
00872                         'mime'        => 'image/jpeg',
00873                         'metadata'    => serialize( array() ),
00874                         'sha1'        => wfBaseConvert( '', 16, 36, 31 ),
00875                         'fileExists'  => true
00876                         ), $this->db->timestamp( '20010115123500' ), $user );
00877         }
00878 
00879         public function teardownDatabase() {
00880                 if ( !$this->databaseSetupDone ) {
00881                         $this->teardownGlobals();
00882                         return;
00883                 }
00884                 $this->teardownUploadDir( $this->uploadDir );
00885 
00886                 $this->dbClone->destroy();
00887                 $this->databaseSetupDone = false;
00888 
00889                 if ( $this->useTemporaryTables ) {
00890                         if( $this->db->getType() == 'sqlite' ) {
00891                                 # Under SQLite the searchindex table is virtual and need
00892                                 # to be explicitly destroyed. See bug 29912
00893                                 # See also MediaWikiTestCase::destroyDB()
00894                                 wfDebug( __METHOD__ . " explicitly destroying sqlite virtual table parsertest_searchindex\n" );
00895                                 $this->db->query( "DROP TABLE `parsertest_searchindex`" );
00896                         }
00897                         # Don't need to do anything
00898                         $this->teardownGlobals();
00899                         return;
00900                 }
00901 
00902                 $tables = $this->listTables();
00903 
00904                 foreach ( $tables as $table ) {
00905                         $sql = $this->db->getType() == 'oracle' ? "DROP TABLE pt_$table DROP CONSTRAINTS" : "DROP TABLE `parsertest_$table`";
00906                         $this->db->query( $sql );
00907                 }
00908 
00909                 if ( $this->db->getType() == 'oracle' )
00910                         $this->db->query( 'BEGIN FILL_WIKI_INFO; END;' );
00911 
00912                 $this->teardownGlobals();
00913         }
00914 
00921         private function setupUploadDir() {
00922                 global $IP;
00923 
00924                 if ( $this->keepUploads ) {
00925                         $dir = wfTempDir() . '/mwParser-images';
00926 
00927                         if ( is_dir( $dir ) ) {
00928                                 return $dir;
00929                         }
00930                 } else {
00931                         $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
00932                 }
00933 
00934                 // wfDebug( "Creating upload directory $dir\n" );
00935                 if ( file_exists( $dir ) ) {
00936                         wfDebug( "Already exists!\n" );
00937                         return $dir;
00938                 }
00939 
00940                 wfMkdirParents( $dir . '/3/3a', null, __METHOD__ );
00941                 copy( "$IP/skins/monobook/headbg.jpg", "$dir/3/3a/Foobar.jpg" );
00942                 wfMkdirParents( $dir . '/0/09', null, __METHOD__ );
00943                 copy( "$IP/skins/monobook/headbg.jpg", "$dir/0/09/Bad.jpg" );
00944 
00945                 return $dir;
00946         }
00947 
00952         private function teardownGlobals() {
00953                 RepoGroup::destroySingleton();
00954                 LinkCache::singleton()->clear();
00955 
00956                 foreach ( $this->savedGlobals as $var => $val ) {
00957                         $GLOBALS[$var] = $val;
00958                 }
00959         }
00960 
00964         private function teardownUploadDir( $dir ) {
00965                 if ( $this->keepUploads ) {
00966                         return;
00967                 }
00968 
00969                 // delete the files first, then the dirs.
00970                 self::deleteFiles(
00971                         array (
00972                                 "$dir/3/3a/Foobar.jpg",
00973                                 "$dir/thumb/3/3a/Foobar.jpg/180px-Foobar.jpg",
00974                                 "$dir/thumb/3/3a/Foobar.jpg/200px-Foobar.jpg",
00975                                 "$dir/thumb/3/3a/Foobar.jpg/640px-Foobar.jpg",
00976                                 "$dir/thumb/3/3a/Foobar.jpg/120px-Foobar.jpg",
00977 
00978                                 "$dir/0/09/Bad.jpg",
00979 
00980                                 "$dir/math/f/a/5/fa50b8b616463173474302ca3e63586b.png",
00981                         )
00982                 );
00983 
00984                 self::deleteDirs(
00985                         array (
00986                                 "$dir/3/3a",
00987                                 "$dir/3",
00988                                 "$dir/thumb/6/65",
00989                                 "$dir/thumb/6",
00990                                 "$dir/thumb/3/3a/Foobar.jpg",
00991                                 "$dir/thumb/3/3a",
00992                                 "$dir/thumb/3",
00993 
00994                                 "$dir/0/09/",
00995                                 "$dir/0/",
00996                                 "$dir/thumb",
00997                                 "$dir/math/f/a/5",
00998                                 "$dir/math/f/a",
00999                                 "$dir/math/f",
01000                                 "$dir/math",
01001                                 "$dir",
01002                         )
01003                 );
01004         }
01005 
01010         private static function deleteFiles( $files ) {
01011                 foreach ( $files as $file ) {
01012                         if ( file_exists( $file ) ) {
01013                                 unlink( $file );
01014                         }
01015                 }
01016         }
01017 
01022         private static function deleteDirs( $dirs ) {
01023                 foreach ( $dirs as $dir ) {
01024                         if ( is_dir( $dir ) ) {
01025                                 rmdir( $dir );
01026                         }
01027                 }
01028         }
01029 
01033         protected function showTesting( $desc ) {
01034                 print "Running test $desc... ";
01035         }
01036 
01043         protected function showSuccess( $desc ) {
01044                 if ( $this->showProgress ) {
01045                         print $this->term->color( '1;32' ) . 'PASSED' . $this->term->reset() . "\n";
01046                 }
01047 
01048                 return true;
01049         }
01050 
01060         protected function showFailure( $desc, $result, $html ) {
01061                 if ( $this->showFailure ) {
01062                         if ( !$this->showProgress ) {
01063                                 # In quiet mode we didn't show the 'Testing' message before the
01064                                 # test, in case it succeeded. Show it now:
01065                                 $this->showTesting( $desc );
01066                         }
01067 
01068                         print $this->term->color( '31' ) . 'FAILED!' . $this->term->reset() . "\n";
01069 
01070                         if ( $this->showOutput ) {
01071                                 print "--- Expected ---\n$result\n--- Actual ---\n$html\n";
01072                         }
01073 
01074                         if ( $this->showDiffs ) {
01075                                 print $this->quickDiff( $result, $html );
01076                                 if ( !$this->wellFormed( $html ) ) {
01077                                         print "XML error: $this->mXmlError\n";
01078                                 }
01079                         }
01080                 }
01081 
01082                 return false;
01083         }
01084 
01095         protected function quickDiff( $input, $output, $inFileTail = 'expected', $outFileTail = 'actual' ) {
01096                 # Windows, or at least the fc utility, is retarded
01097                 $slash = wfIsWindows() ? '\\' : '/';
01098                 $prefix = wfTempDir() . "{$slash}mwParser-" . mt_rand();
01099 
01100                 $infile = "$prefix-$inFileTail";
01101                 $this->dumpToFile( $input, $infile );
01102 
01103                 $outfile = "$prefix-$outFileTail";
01104                 $this->dumpToFile( $output, $outfile );
01105 
01106                 $shellInfile = wfEscapeShellArg($infile);
01107                 $shellOutfile = wfEscapeShellArg($outfile);
01108 
01109                 global $wgDiff3;
01110                 // we assume that people with diff3 also have usual diff
01111                 $diff = ( wfIsWindows() && !$wgDiff3 )
01112                         ? `fc $shellInfile $shellOutfile`
01113                         : `diff -au $shellInfile $shellOutfile`;
01114                 unlink( $infile );
01115                 unlink( $outfile );
01116 
01117                 return $this->colorDiff( $diff );
01118         }
01119 
01126         private function dumpToFile( $data, $filename ) {
01127                 $file = fopen( $filename, "wt" );
01128                 fwrite( $file, $data . "\n" );
01129                 fclose( $file );
01130         }
01131 
01139         protected function colorDiff( $text ) {
01140                 return preg_replace(
01141                         array( '/^(-.*)$/m', '/^(\+.*)$/m' ),
01142                         array( $this->term->color( 34 ) . '$1' . $this->term->reset(),
01143                                    $this->term->color( 31 ) . '$1' . $this->term->reset() ),
01144                         $text );
01145         }
01146 
01152         public function showRunFile( $path ) {
01153                 print $this->term->color( 1 ) .
01154                         "Reading tests from \"$path\"..." .
01155                         $this->term->reset() .
01156                         "\n";
01157         }
01158 
01166         static public function addArticle( $name, $text, $line = 'unknown', $ignoreDuplicate = '' ) {
01167                 global $wgCapitalLinks;
01168 
01169                 $oldCapitalLinks = $wgCapitalLinks;
01170                 $wgCapitalLinks = true; // We only need this from SetupGlobals() See r70917#c8637
01171 
01172                 $text = self::chomp( $text );
01173                 $name = self::chomp( $name );
01174 
01175                 $title = Title::newFromText( $name );
01176 
01177                 if ( is_null( $title ) ) {
01178                         throw new MWException( "invalid title '$name' at line $line\n" );
01179                 }
01180 
01181                 $page = WikiPage::factory( $title );
01182                 $page->loadPageData( 'fromdbmaster' );
01183 
01184                 if ( $page->exists() ) {
01185                         if ( $ignoreDuplicate == 'ignoreduplicate' ) {
01186                                 return;
01187                         } else {
01188                                 throw new MWException( "duplicate article '$name' at line $line\n" );
01189                         }
01190                 }
01191 
01192                 $page->doEdit( $text, '', EDIT_NEW );
01193 
01194                 $wgCapitalLinks = $oldCapitalLinks;
01195         }
01196 
01205         public function requireHook( $name ) {
01206                 global $wgParser;
01207 
01208                 $wgParser->firstCallInit( ); // make sure hooks are loaded.
01209 
01210                 if ( isset( $wgParser->mTagHooks[$name] ) ) {
01211                         $this->hooks[$name] = $wgParser->mTagHooks[$name];
01212                 } else {
01213                         echo "   This test suite requires the '$name' hook extension, skipping.\n";
01214                         return false;
01215                 }
01216 
01217                 return true;
01218         }
01219 
01228         public function requireFunctionHook( $name ) {
01229                 global $wgParser;
01230 
01231                 $wgParser->firstCallInit( ); // make sure hooks are loaded.
01232 
01233                 if ( isset( $wgParser->mFunctionHooks[$name] ) ) {
01234                         $this->functionHooks[$name] = $wgParser->mFunctionHooks[$name];
01235                 } else {
01236                         echo "   This test suite requires the '$name' function hook extension, skipping.\n";
01237                         return false;
01238                 }
01239 
01240                 return true;
01241         }
01242 
01250         private function tidy( $text ) {
01251                 global $wgUseTidy;
01252 
01253                 if ( $wgUseTidy ) {
01254                         $text = MWTidy::tidy( $text );
01255                 }
01256 
01257                 return $text;
01258         }
01259 
01260         private function wellFormed( $text ) {
01261                 $html =
01262                         Sanitizer::hackDocType() .
01263                         '<html>' .
01264                         $text .
01265                         '</html>';
01266 
01267                 $parser = xml_parser_create( "UTF-8" );
01268 
01269                 # case folding violates XML standard, turn it off
01270                 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
01271 
01272                 if ( !xml_parse( $parser, $html, true ) ) {
01273                         $err = xml_error_string( xml_get_error_code( $parser ) );
01274                         $position = xml_get_current_byte_index( $parser );
01275                         $fragment = $this->extractFragment( $html, $position );
01276                         $this->mXmlError = "$err at byte $position:\n$fragment";
01277                         xml_parser_free( $parser );
01278 
01279                         return false;
01280                 }
01281 
01282                 xml_parser_free( $parser );
01283 
01284                 return true;
01285         }
01286 
01287         private function extractFragment( $text, $position ) {
01288                 $start = max( 0, $position - 10 );
01289                 $before = $position - $start;
01290                 $fragment = '...' .
01291                         $this->term->color( 34 ) .
01292                         substr( $text, $start, $before ) .
01293                         $this->term->color( 0 ) .
01294                         $this->term->color( 31 ) .
01295                         $this->term->color( 1 ) .
01296                         substr( $text, $position, 1 ) .
01297                         $this->term->color( 0 ) .
01298                         $this->term->color( 34 ) .
01299                         substr( $text, $position + 1, 9 ) .
01300                         $this->term->color( 0 ) .
01301                         '...';
01302                 $display = str_replace( "\n", ' ', $fragment );
01303                 $caret = '   ' .
01304                         str_repeat( ' ', $before ) .
01305                         $this->term->color( 31 ) .
01306                         '^' .
01307                         $this->term->color( 0 );
01308 
01309                 return "$display\n$caret";
01310         }
01311 
01312         static function getFakeTimestamp( &$parser, &$ts ) {
01313                 $ts = 123;
01314                 return true;
01315         }
01316 }