MediaWiki  REL1_20
NewParserTest.php
Go to the documentation of this file.
00001 <?php
00002 
00010 class NewParserTest extends MediaWikiTestCase {
00011         static protected $articles = array();   // Array of test articles defined by the tests
00012         /* The dataProvider is run on a different instance than the test, so it must be static
00013          * When running tests from several files, all tests will see all articles.
00014          */
00015         static protected $backendToUse;
00016 
00017         public $keepUploads = false;
00018         public $runDisabled = false;
00019         public $regex = '';
00020         public $showProgress = true;
00021         public $savedInitialGlobals = array();
00022         public $savedWeirdGlobals = array();
00023         public $savedGlobals = array();
00024         public $hooks = array();
00025         public $functionHooks = array();
00026 
00027         //Fuzz test
00028         public $maxFuzzTestLength = 300;
00029         public $fuzzSeed = 0;
00030         public $memoryLimit = 50;
00031 
00032         protected $file = false;
00033 
00034         function setUp() {
00035                 global $wgContLang, $wgNamespaceProtection, $wgNamespaceAliases;
00036                 global $wgHooks, $IP;
00037                 $wgContLang = Language::factory( 'en' );
00038 
00039                 //Setup CLI arguments
00040                 if ( $this->getCliArg( 'regex=' ) ) {
00041                         $this->regex = $this->getCliArg( 'regex=' );
00042                 } else {
00043                         # Matches anything
00044                         $this->regex = '';
00045                 }
00046 
00047                 $this->keepUploads = $this->getCliArg( 'keep-uploads' );
00048 
00049                 $tmpGlobals = array();
00050 
00051                 $tmpGlobals['wgScript'] = '/index.php';
00052                 $tmpGlobals['wgScriptPath'] = '/';
00053                 $tmpGlobals['wgArticlePath'] = '/wiki/$1';
00054                 $tmpGlobals['wgStyleSheetPath'] = '/skins';
00055                 $tmpGlobals['wgStylePath'] = '/skins';
00056                 $tmpGlobals['wgThumbnailScriptPath'] = false;
00057                 $tmpGlobals['wgLocalFileRepo'] = array(
00058                         'class'           => 'LocalRepo',
00059                         'name'            => 'local',
00060                         'url'             => 'http://example.com/images',
00061                         'hashLevels'      => 2,
00062                         'transformVia404' => false,
00063                         'backend'         => 'local-backend'
00064                 );
00065                 $tmpGlobals['wgForeignFileRepos'] = array();
00066                 $tmpGlobals['wgEnableParserCache'] = false;
00067                 $tmpGlobals['wgHooks'] = $wgHooks;
00068                 $tmpGlobals['wgDeferredUpdateList'] = array();
00069                 $tmpGlobals['wgMemc'] = wfGetMainCache();
00070                 $tmpGlobals['messageMemc'] = wfGetMessageCacheStorage();
00071                 $tmpGlobals['parserMemc'] = wfGetParserCacheStorage();
00072 
00073                 // $tmpGlobals['wgContLang'] = new StubContLang;
00074                 $tmpGlobals['wgUser'] = new User;
00075                 $context = new RequestContext();
00076                 $tmpGlobals['wgLang'] = $context->getLanguage();
00077                 $tmpGlobals['wgOut'] = $context->getOutput();
00078                 $tmpGlobals['wgParser'] = new StubObject( 'wgParser', $GLOBALS['wgParserConf']['class'], array( $GLOBALS['wgParserConf'] ) );
00079                 $tmpGlobals['wgRequest'] = $context->getRequest();
00080 
00081                 if ( $GLOBALS['wgStyleDirectory'] === false ) {
00082                         $tmpGlobals['wgStyleDirectory'] = "$IP/skins";
00083                 }
00084 
00085 
00086                 foreach ( $tmpGlobals as $var => $val ) {
00087                         if ( array_key_exists( $var, $GLOBALS ) ) {
00088                                 $this->savedInitialGlobals[$var] = $GLOBALS[$var];
00089                         }
00090 
00091                         $GLOBALS[$var] = $val;
00092                 }
00093 
00094                 $this->savedWeirdGlobals['mw_namespace_protection'] = $wgNamespaceProtection[NS_MEDIAWIKI];
00095                 $this->savedWeirdGlobals['image_alias'] = $wgNamespaceAliases['Image'];
00096                 $this->savedWeirdGlobals['image_talk_alias'] = $wgNamespaceAliases['Image_talk'];
00097 
00098                 $wgNamespaceProtection[NS_MEDIAWIKI] = 'editinterface';
00099                 $wgNamespaceAliases['Image'] = NS_FILE;
00100                 $wgNamespaceAliases['Image_talk'] = NS_FILE_TALK;
00101         }
00102 
00103         public function tearDown() {
00104                 foreach ( $this->savedInitialGlobals as $var => $val ) {
00105                         $GLOBALS[$var] = $val;
00106                 }
00107 
00108                 global $wgNamespaceProtection, $wgNamespaceAliases;
00109 
00110                 $wgNamespaceProtection[NS_MEDIAWIKI] = $this->savedWeirdGlobals['mw_namespace_protection'];
00111                 $wgNamespaceAliases['Image'] = $this->savedWeirdGlobals['image_alias'];
00112                 $wgNamespaceAliases['Image_talk'] = $this->savedWeirdGlobals['image_talk_alias'];
00113 
00114                 // Restore backends
00115                 RepoGroup::destroySingleton();
00116                 FileBackendGroup::destroySingleton();
00117         }
00118 
00119         function addDBData() {
00120                 $this->tablesUsed[] = 'site_stats';
00121                 $this->tablesUsed[] = 'interwiki';
00122                 # disabled for performance
00123                 #$this->tablesUsed[] = 'image';
00124 
00125                 # Hack: insert a few Wikipedia in-project interwiki prefixes,
00126                 # for testing inter-language links
00127                 $this->db->insert( 'interwiki', array(
00128                         array( 'iw_prefix' => 'wikipedia',
00129                                    'iw_url'    => 'http://en.wikipedia.org/wiki/$1',
00130                                    'iw_api'    => '',
00131                                    'iw_wikiid' => '',
00132                                    'iw_local'  => 0 ),
00133                         array( 'iw_prefix' => 'meatball',
00134                                    'iw_url'    => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
00135                                    'iw_api'    => '',
00136                                    'iw_wikiid' => '',
00137                                    'iw_local'  => 0 ),
00138                         array( 'iw_prefix' => 'zh',
00139                                    'iw_url'    => 'http://zh.wikipedia.org/wiki/$1',
00140                                    'iw_api'    => '',
00141                                    'iw_wikiid' => '',
00142                                    'iw_local'  => 1 ),
00143                         array( 'iw_prefix' => 'es',
00144                                    'iw_url'    => 'http://es.wikipedia.org/wiki/$1',
00145                                    'iw_api'    => '',
00146                                    'iw_wikiid' => '',
00147                                    'iw_local'  => 1 ),
00148                         array( 'iw_prefix' => 'fr',
00149                                    'iw_url'    => 'http://fr.wikipedia.org/wiki/$1',
00150                                    'iw_api'    => '',
00151                                    'iw_wikiid' => '',
00152                                    'iw_local'  => 1 ),
00153                         array( 'iw_prefix' => 'ru',
00154                                    'iw_url'    => 'http://ru.wikipedia.org/wiki/$1',
00155                                    'iw_api'    => '',
00156                                    'iw_wikiid' => '',
00157                                    'iw_local'  => 1 ),
00162                         ), __METHOD__, array( 'IGNORE' )
00163                 );
00164 
00165 
00166                 # Update certain things in site_stats
00167                 $this->db->insert( 'site_stats',
00168                         array( 'ss_row_id' => 1, 'ss_images' => 2, 'ss_good_articles' => 1 ),
00169                         __METHOD__
00170                 );
00171 
00172                 # Reinitialise the LocalisationCache to match the database state
00173                 Language::getLocalisationCache()->unloadAll();
00174 
00175                 # Clear the message cache
00176                 MessageCache::singleton()->clear();
00177 
00178                 $user = User::newFromId( 0 );
00179                 LinkCache::singleton()->clear(); # Avoids the odd failure at creating the nullRevision
00180 
00181                 # Upload DB table entries for files.
00182                 # We will upload the actual files later. Note that if anything causes LocalFile::load()
00183                 # to be triggered before then, it will break via maybeUpgrade() setting the fileExists
00184                 # member to false and storing it in cache.
00185                 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Foobar.jpg' ) );
00186                 if ( !$this->db->selectField( 'image', '1', array( 'img_name' => $image->getName() ) ) ) {
00187                         $image->recordUpload2(
00188                                 '', // archive name
00189                                 'Upload of some lame file',
00190                                 'Some lame file',
00191                                 array(
00192                                         'size'        => 12345,
00193                                         'width'       => 1941,
00194                                         'height'      => 220,
00195                                         'bits'        => 24,
00196                                         'media_type'  => MEDIATYPE_BITMAP,
00197                                         'mime'        => 'image/jpeg',
00198                                         'metadata'    => serialize( array() ),
00199                                         'sha1'        => wfBaseConvert( '', 16, 36, 31 ),
00200                                         'fileExists'  => true ),
00201                                 $this->db->timestamp( '20010115123500' ), $user
00202                         );
00203                 }
00204 
00205                 # This image will be blacklisted in [[MediaWiki:Bad image list]]
00206                 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Bad.jpg' ) );
00207                 if ( !$this->db->selectField( 'image', '1', array( 'img_name' => $image->getName() ) ) ) {
00208                         $image->recordUpload2(
00209                                 '', // archive name
00210                                 'zomgnotcensored',
00211                                 'Borderline image',
00212                                 array(
00213                                         'size'        => 12345,
00214                                         'width'       => 320,
00215                                         'height'      => 240,
00216                                         'bits'        => 24,
00217                                         'media_type'  => MEDIATYPE_BITMAP,
00218                                         'mime'        => 'image/jpeg',
00219                                         'metadata'    => serialize( array() ),
00220                                         'sha1'        => wfBaseConvert( '', 16, 36, 31 ),
00221                                         'fileExists'  => true ),
00222                                 $this->db->timestamp( '20010115123500' ), $user
00223                         );
00224                 }
00225         }
00226 
00227 
00228 
00229 
00230         //ParserTest setup/teardown functions
00231 
00236         protected function setupGlobals( $opts = '', $config = '' ) {
00237                 global $wgFileBackends;
00238                 # Find out values for some special options.
00239                 $lang =
00240                         self::getOptionValue( 'language', $opts, 'en' );
00241                 $variant =
00242                         self::getOptionValue( 'variant', $opts, false );
00243                 $maxtoclevel =
00244                         self::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
00245                 $linkHolderBatchSize =
00246                         self::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
00247 
00248                 $uploadDir = $this->getUploadDir();
00249                 if ( $this->getCliArg( 'use-filebackend=' ) ) {
00250                         if ( self::$backendToUse ) {
00251                                 $backend = self::$backendToUse;
00252                         } else {
00253                                 $name = $this->getCliArg( 'use-filebackend=' );
00254                                 $useConfig = array();
00255                                 foreach ( $wgFileBackends as $conf ) {
00256                                         if ( $conf['name'] == $name ) {
00257                                                 $useConfig = $conf;
00258                                         }
00259                                 }
00260                                 $useConfig['name'] = 'local-backend'; // swap name
00261                                 $class = $conf['class'];
00262                                 self::$backendToUse = new $class( $useConfig );
00263                                 $backend = self::$backendToUse;
00264                         }
00265                 } else {
00266                         $backend = new FSFileBackend( array(
00267                                 'name'        => 'local-backend',
00268                                 'lockManager' => 'nullLockManager',
00269                                 'containerPaths' => array(
00270                                         'local-public' => "$uploadDir",
00271                                         'local-thumb'  => "$uploadDir/thumb",
00272                                 )
00273                         ) );
00274                 }
00275 
00276                 $settings = array(
00277                         'wgServer' => 'http://Britney-Spears',
00278                         'wgScript' => '/index.php',
00279                         'wgScriptPath' => '/',
00280                         'wgArticlePath' => '/wiki/$1',
00281                         'wgExtensionAssetsPath' => '/extensions',
00282                         'wgActionPaths' => array(),
00283                         'wgLocalFileRepo' => array(
00284                                 'class'           => 'LocalRepo',
00285                                 'name'            => 'local',
00286                                 'url'             => 'http://example.com/images',
00287                                 'hashLevels'      => 2,
00288                                 'transformVia404' => false,
00289                                 'backend'         => $backend
00290                         ),
00291                         'wgEnableUploads' => self::getOptionValue( 'wgEnableUploads', $opts, true ),
00292                         'wgStylePath' => '/skins',
00293                         'wgStyleSheetPath' => '/skins',
00294                         'wgSitename' => 'MediaWiki',
00295                         'wgLanguageCode' => $lang,
00296                         'wgDBprefix' => $this->db->getType() != 'oracle' ? 'unittest_' : 'ut_',
00297                         'wgRawHtml' => isset( $opts['rawhtml'] ),
00298                         'wgLang' => null,
00299                         'wgContLang' => null,
00300                         'wgNamespacesWithSubpages' => array( 0 => isset( $opts['subpage'] ) ),
00301                         'wgMaxTocLevel' => $maxtoclevel,
00302                         'wgCapitalLinks' => true,
00303                         'wgNoFollowLinks' => true,
00304                         'wgNoFollowDomainExceptions' => array(),
00305                         'wgThumbnailScriptPath' => false,
00306                         'wgUseImageResize' => false,
00307                         'wgUseTeX' => isset( $opts['math'] ),
00308                         'wgMathDirectory' => $uploadDir . '/math',
00309                         'wgLocaltimezone' => 'UTC',
00310                         'wgAllowExternalImages' => true,
00311                         'wgUseTidy' => false,
00312                         'wgDefaultLanguageVariant' => $variant,
00313                         'wgVariantArticlePath' => false,
00314                         'wgGroupPermissions' => array( '*' => array(
00315                                 'createaccount' => true,
00316                                 'read'          => true,
00317                                 'edit'          => true,
00318                                 'createpage'    => true,
00319                                 'createtalk'    => true,
00320                         ) ),
00321                         'wgNamespaceProtection' => array( NS_MEDIAWIKI => 'editinterface' ),
00322                         'wgDefaultExternalStore' => array(),
00323                         'wgForeignFileRepos' => array(),
00324                         'wgLinkHolderBatchSize' => $linkHolderBatchSize,
00325                         'wgExperimentalHtmlIds' => false,
00326                         'wgExternalLinkTarget' => false,
00327                         'wgAlwaysUseTidy' => false,
00328                         'wgHtml5' => true,
00329                         'wgWellFormedXml' => true,
00330                         'wgAllowMicrodataAttributes' => true,
00331                         'wgAdaptiveMessageCache' => true,
00332                         'wgUseDatabaseMessages' => true,
00333                 );
00334 
00335                 if ( $config ) {
00336                         $configLines = explode( "\n", $config );
00337 
00338                         foreach ( $configLines as $line ) {
00339                                 list( $var, $value ) = explode( '=', $line, 2 );
00340 
00341                                 $settings[$var] = eval( "return $value;" ); //???
00342                         }
00343                 }
00344 
00345                 $this->savedGlobals = array();
00346 
00348                 wfRunHooks( 'ParserTestGlobals', array( &$settings ) );
00349 
00350                 foreach ( $settings as $var => $val ) {
00351                         if ( array_key_exists( $var, $GLOBALS ) ) {
00352                                 $this->savedGlobals[$var] = $GLOBALS[$var];
00353                         }
00354 
00355                         $GLOBALS[$var] = $val;
00356                 }
00357 
00358                 $langObj = Language::factory( $lang );
00359                 $GLOBALS['wgContLang'] = $langObj;
00360                 $context = new RequestContext();
00361                 $GLOBALS['wgLang'] = $context->getLanguage();
00362 
00363                 $GLOBALS['wgMemc'] = new EmptyBagOStuff;
00364                 $GLOBALS['wgOut'] = $context->getOutput();
00365                 $GLOBALS['wgUser'] = $context->getUser();
00366 
00367                 global $wgHooks;
00368 
00369                 $wgHooks['ParserTestParser'][] = 'ParserTestParserHook::setup';
00370                 $wgHooks['ParserGetVariableValueTs'][] = 'ParserTest::getFakeTimestamp';
00371 
00372                 MagicWord::clearCache();
00373                 RepoGroup::destroySingleton();
00374                 FileBackendGroup::destroySingleton();
00375 
00376                 # Create dummy files in storage
00377                 $this->setupUploads();
00378 
00379                 # Publish the articles after we have the final language set
00380                 $this->publishTestArticles();
00381 
00382                 # The entries saved into RepoGroup cache with previous globals will be wrong.
00383                 RepoGroup::destroySingleton();
00384                 FileBackendGroup::destroySingleton();
00385                 MessageCache::destroyInstance();
00386 
00387                 return $context;
00388         }
00389 
00395         protected function getUploadDir() {
00396                 if ( $this->keepUploads ) {
00397                         $dir = wfTempDir() . '/mwParser-images';
00398 
00399                         if ( is_dir( $dir ) ) {
00400                                 return $dir;
00401                         }
00402                 } else {
00403                         $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
00404                 }
00405 
00406                 // wfDebug( "Creating upload directory $dir\n" );
00407                 if ( file_exists( $dir ) ) {
00408                         wfDebug( "Already exists!\n" );
00409                         return $dir;
00410                 }
00411 
00412                 return $dir;
00413         }
00414 
00421         protected function setupUploads() {
00422                 global $IP;
00423 
00424                 $base = $this->getBaseDir();
00425                 $backend = RepoGroup::singleton()->getLocalRepo()->getBackend();
00426                 $backend->prepare( array( 'dir' => "$base/local-public/3/3a" ) );
00427                 $backend->store( array(
00428                         'src' => "$IP/skins/monobook/headbg.jpg", 'dst' => "$base/local-public/3/3a/Foobar.jpg"
00429                 ) );
00430                 $backend->prepare( array( 'dir' => "$base/local-public/0/09" ) );
00431                 $backend->store( array(
00432                         'src' => "$IP/skins/monobook/headbg.jpg", 'dst' => "$base/local-public/0/09/Bad.jpg"
00433                 ) );
00434         }
00435 
00440         protected function teardownGlobals() {
00441                 $this->teardownUploads();
00442 
00443                 foreach ( $this->savedGlobals as $var => $val ) {
00444                         $GLOBALS[$var] = $val;
00445                 }
00446 
00447                 RepoGroup::destroySingleton();
00448                 LinkCache::singleton()->clear();
00449         }
00450 
00454         private function teardownUploads() {
00455                 if ( $this->keepUploads ) {
00456                         return;
00457                 }
00458 
00459                 $base = $this->getBaseDir();
00460                 // delete the files first, then the dirs.
00461                 self::deleteFiles(
00462                         array (
00463                                 "$base/local-public/3/3a/Foobar.jpg",
00464                                 "$base/local-thumb/3/3a/Foobar.jpg/180px-Foobar.jpg",
00465                                 "$base/local-thumb/3/3a/Foobar.jpg/200px-Foobar.jpg",
00466                                 "$base/local-thumb/3/3a/Foobar.jpg/640px-Foobar.jpg",
00467                                 "$base/local-thumb/3/3a/Foobar.jpg/120px-Foobar.jpg",
00468 
00469                                 "$base/local-public/0/09/Bad.jpg",
00470                                 "$base/local-thumb/0/09/Bad.jpg",
00471 
00472                                 "$base/local-public/math/f/a/5/fa50b8b616463173474302ca3e63586b.png",
00473                         )
00474                 );
00475         }
00476 
00481         private static function deleteFiles( $files ) {
00482                 $backend = RepoGroup::singleton()->getLocalRepo()->getBackend();
00483                 foreach ( $files as $file ) {
00484                         $backend->delete( array( 'src' => $file ), array( 'force' => 1 ) );
00485                 }
00486                 foreach ( $files as $file ) {
00487                         $tmp = $file;
00488                         while ( $tmp = FileBackend::parentStoragePath( $tmp ) ) {
00489                                 if ( !$backend->clean( array( 'dir' => $tmp ) )->isOK() ) {
00490                                         break;
00491                                 }
00492                         }
00493                 }
00494         }
00495 
00496         protected function getBaseDir() {
00497                 return 'mwstore://local-backend';
00498         }
00499 
00500         public function parserTestProvider() {
00501                 if ( $this->file === false ) {
00502                         global $wgParserTestFiles;
00503                         $this->file = $wgParserTestFiles[0];
00504                 }
00505                 return new TestFileIterator( $this->file, $this );
00506         }
00507 
00511         public function setParserTestFile( $filename ) {
00512                 $this->file = $filename;
00513         }
00514 
00519         public function testParserTest( $desc, $input, $result, $opts, $config ) {
00520                 if ( $this->regex != '' && !preg_match( '/' . $this->regex . '/', $desc ) ) {
00521                         $this->assertTrue( true ); // XXX: don't flood output with "test made no assertions"
00522                         //$this->markTestSkipped( 'Filtered out by the user' );
00523                         return;
00524                 }
00525 
00526                 wfDebug( "Running parser test: $desc\n" );
00527 
00528                 $opts = $this->parseOptions( $opts );
00529                 $context = $this->setupGlobals( $opts, $config );
00530 
00531                 $user = $context->getUser();
00532                 $options = ParserOptions::newFromContext( $context );
00533 
00534                 if ( isset( $opts['title'] ) ) {
00535                         $titleText = $opts['title'];
00536                 }
00537                 else {
00538                         $titleText = 'Parser test';
00539                 }
00540 
00541                 $local = isset( $opts['local'] );
00542                 $preprocessor = isset( $opts['preprocessor'] ) ? $opts['preprocessor'] : null;
00543                 $parser = $this->getParser( $preprocessor );
00544 
00545                 $title = Title::newFromText( $titleText );
00546 
00547                 if ( isset( $opts['pst'] ) ) {
00548                         $out = $parser->preSaveTransform( $input, $title, $user, $options );
00549                 } elseif ( isset( $opts['msg'] ) ) {
00550                         $out = $parser->transformMsg( $input, $options, $title );
00551                 } elseif ( isset( $opts['section'] ) ) {
00552                         $section = $opts['section'];
00553                         $out = $parser->getSection( $input, $section );
00554                 } elseif ( isset( $opts['replace'] ) ) {
00555                         $section = $opts['replace'][0];
00556                         $replace = $opts['replace'][1];
00557                         $out = $parser->replaceSection( $input, $section, $replace );
00558                 } elseif ( isset( $opts['comment'] ) ) {
00559                         $out = Linker::formatComment( $input, $title, $local );
00560                 } elseif ( isset( $opts['preload'] ) ) {
00561                         $out = $parser->getpreloadText( $input, $title, $options );
00562                 } else {
00563                         $output = $parser->parse( $input, $title, $options, true, true, 1337 );
00564                         $out = $output->getText();
00565 
00566                         if ( isset( $opts['showtitle'] ) ) {
00567                                 if ( $output->getTitleText() ) {
00568                                         $title = $output->getTitleText();
00569                                 }
00570 
00571                                 $out = "$title\n$out";
00572                         }
00573 
00574                         if ( isset( $opts['ill'] ) ) {
00575                                 $out = $this->tidy( implode( ' ', $output->getLanguageLinks() ) );
00576                         } elseif ( isset( $opts['cat'] ) ) {
00577                                 $outputPage = $context->getOutput();
00578                                 $outputPage->addCategoryLinks( $output->getCategories() );
00579                                 $cats = $outputPage->getCategoryLinks();
00580 
00581                                 if ( isset( $cats['normal'] ) ) {
00582                                         $out = $this->tidy( implode( ' ', $cats['normal'] ) );
00583                                 } else {
00584                                         $out = '';
00585                                 }
00586                         }
00587                         $parser->mPreprocessor = null;
00588 
00589                         $result = $this->tidy( $result );
00590                 }
00591 
00592                 $this->teardownGlobals();
00593 
00594                 $this->assertEquals( $result, $out, $desc );
00595         }
00596 
00605         function testFuzzTests() {
00606                 global $wgParserTestFiles;
00607 
00608                 $files = $wgParserTestFiles;
00609 
00610                 if( $this->getCliArg( 'file=' ) ) {
00611                         $files = array( $this->getCliArg( 'file=' ) );
00612                 }
00613 
00614                 $dict = $this->getFuzzInput( $files );
00615                 $dictSize = strlen( $dict );
00616                 $logMaxLength = log( $this->maxFuzzTestLength );
00617 
00618                 ini_set( 'memory_limit', $this->memoryLimit * 1048576 );
00619 
00620                 $user = new User;
00621                 $opts = ParserOptions::newFromUser( $user );
00622                 $title = Title::makeTitle( NS_MAIN, 'Parser_test' );
00623 
00624                 $id = 1;
00625 
00626                 while ( true ) {
00627 
00628                         // Generate test input
00629                         mt_srand( ++$this->fuzzSeed );
00630                         $totalLength = mt_rand( 1, $this->maxFuzzTestLength );
00631                         $input = '';
00632 
00633                         while ( strlen( $input ) < $totalLength ) {
00634                                 $logHairLength = mt_rand( 0, 1000000 ) / 1000000 * $logMaxLength;
00635                                 $hairLength = min( intval( exp( $logHairLength ) ), $dictSize );
00636                                 $offset = mt_rand( 0, $dictSize - $hairLength );
00637                                 $input .= substr( $dict, $offset, $hairLength );
00638                         }
00639 
00640                         $this->setupGlobals();
00641                         $parser = $this->getParser();
00642 
00643                         // Run the test
00644                         try {
00645                                 $parser->parse( $input, $title, $opts );
00646                                 $this->assertTrue( true, "Test $id, fuzz seed {$this->fuzzSeed}" );
00647                         } catch ( Exception $exception ) {
00648                                 $input_dump = sprintf( "string(%d) \"%s\"\n", strlen( $input ), $input );
00649 
00650                                 $this->assertTrue( false, "Test $id, fuzz seed {$this->fuzzSeed}. \n\nInput: $input_dump\n\nError: {$exception->getMessage()}\n\nBacktrace: {$exception->getTraceAsString()}" );
00651                         }
00652 
00653                         $this->teardownGlobals();
00654                         $parser->__destruct();
00655 
00656                         if ( $id % 100 == 0 ) {
00657                                 $usage = intval( memory_get_usage( true ) / $this->memoryLimit / 1048576 * 100 );
00658                                 //echo "{$this->fuzzSeed}: $numSuccess/$numTotal (mem: $usage%)\n";
00659                                 if ( $usage > 90 ) {
00660                                         $ret = "Out of memory:\n";
00661                                         $memStats = $this->getMemoryBreakdown();
00662 
00663                                         foreach ( $memStats as $name => $usage ) {
00664                                                 $ret .= "$name: $usage\n";
00665                                         }
00666 
00667                                         throw new MWException( $ret );
00668                                 }
00669                         }
00670 
00671                         $id++;
00672 
00673                 }
00674         }
00675 
00676         //Various getter functions
00677 
00681         function getFuzzInput( $filenames ) {
00682                 $dict = '';
00683 
00684                 foreach ( $filenames as $filename ) {
00685                         $contents = file_get_contents( $filename );
00686                         preg_match_all( '/!!\s*input\n(.*?)\n!!\s*result/s', $contents, $matches );
00687 
00688                         foreach ( $matches[1] as $match ) {
00689                                 $dict .= $match . "\n";
00690                         }
00691                 }
00692 
00693                 return $dict;
00694         }
00695 
00699         function getMemoryBreakdown() {
00700                 $memStats = array();
00701 
00702                 foreach ( $GLOBALS as $name => $value ) {
00703                         $memStats['$' . $name] = strlen( serialize( $value ) );
00704                 }
00705 
00706                 $classes = get_declared_classes();
00707 
00708                 foreach ( $classes as $class ) {
00709                         $rc = new ReflectionClass( $class );
00710                         $props = $rc->getStaticProperties();
00711                         $memStats[$class] = strlen( serialize( $props ) );
00712                         $methods = $rc->getMethods();
00713 
00714                         foreach ( $methods as $method ) {
00715                                 $memStats[$class] += strlen( serialize( $method->getStaticVariables() ) );
00716                         }
00717                 }
00718 
00719                 $functions = get_defined_functions();
00720 
00721                 foreach ( $functions['user'] as $function ) {
00722                         $rf = new ReflectionFunction( $function );
00723                         $memStats["$function()"] = strlen( serialize( $rf->getStaticVariables() ) );
00724                 }
00725 
00726                 asort( $memStats );
00727 
00728                 return $memStats;
00729         }
00730 
00734         function getParser( $preprocessor = null ) {
00735                 global $wgParserConf;
00736 
00737                 $class = $wgParserConf['class'];
00738                 $parser = new $class( array( 'preprocessorClass' => $preprocessor ) + $wgParserConf );
00739 
00740                 wfRunHooks( 'ParserTestParser', array( &$parser ) );
00741 
00742                 return $parser;
00743         }
00744 
00745         //Various action functions
00746 
00747         public function addArticle( $name, $text, $line ) {
00748                 self::$articles[$name] = array( $text, $line );
00749         }
00750 
00751         public function publishTestArticles() {
00752                 if ( empty( self::$articles ) ) {
00753                         return;
00754                 }
00755 
00756                 foreach ( self::$articles as $name => $info ) {
00757                         list( $text, $line ) = $info;
00758                         ParserTest::addArticle( $name, $text, $line, 'ignoreduplicate' );
00759                 }
00760         }
00761 
00770         public function requireHook( $name ) {
00771                 global $wgParser;
00772                 $wgParser->firstCallInit( ); // make sure hooks are loaded.
00773                 return isset( $wgParser->mTagHooks[$name] );
00774         }
00775 
00776         public function requireFunctionHook( $name ) {
00777                 global $wgParser;
00778                 $wgParser->firstCallInit( ); // make sure hooks are loaded.
00779                 return isset( $wgParser->mFunctionHooks[$name] );
00780         }
00781         //Various "cleanup" functions
00782 
00790         protected function tidy( $text ) {
00791                 global $wgUseTidy;
00792 
00793                 if ( $wgUseTidy ) {
00794                         $text = MWTidy::tidy( $text );
00795                 }
00796 
00797                 return $text;
00798         }
00799 
00803         public function removeEndingNewline( $s ) {
00804                 if ( substr( $s, -1 ) === "\n" ) {
00805                         return substr( $s, 0, -1 );
00806                 }
00807                 else {
00808                         return $s;
00809                 }
00810         }
00811 
00812         //Test options parser functions
00813 
00814         protected function parseOptions( $instring ) {
00815                 $opts = array();
00816                 // foo
00817                 // foo=bar
00818                 // foo="bar baz"
00819                 // foo=[[bar baz]]
00820                 // foo=bar,"baz quux"
00821                 $regex = '/\b
00822                         ([\w-]+)                                                # Key
00823                         \b
00824                         (?:\s*
00825                                 =                                               # First sub-value
00826                                 \s*
00827                                 (
00828                                         "
00829                                                 [^"]*                   # Quoted val
00830                                         "
00831                                 |
00832                                         \[\[
00833                                                 [^]]*                   # Link target
00834                                         \]\]
00835                                 |
00836                                         [\w-]+                          # Plain word
00837                                 )
00838                                 (?:\s*
00839                                         ,                                       # Sub-vals 1..N
00840                                         \s*
00841                                         (
00842                                                 "[^"]*"                 # Quoted val
00843                                         |
00844                                                 \[\[[^]]*\]\]   # Link target
00845                                         |
00846                                                 [\w-]+                  # Plain word
00847                                         )
00848                                 )*
00849                         )?
00850                         /x';
00851 
00852                 if ( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER ) ) {
00853                         foreach ( $matches as $bits ) {
00854                                 array_shift( $bits );
00855                                 $key = strtolower( array_shift( $bits ) );
00856                                 if ( count( $bits ) == 0 ) {
00857                                         $opts[$key] = true;
00858                                 } elseif ( count( $bits ) == 1 ) {
00859                                         $opts[$key] = $this->cleanupOption( array_shift( $bits ) );
00860                                 } else {
00861                                         // Array!
00862                                         $opts[$key] = array_map( array( $this, 'cleanupOption' ), $bits );
00863                                 }
00864                         }
00865                 }
00866                 return $opts;
00867         }
00868 
00869         protected function cleanupOption( $opt ) {
00870                 if ( substr( $opt, 0, 1 ) == '"' ) {
00871                         return substr( $opt, 1, -1 );
00872                 }
00873 
00874                 if ( substr( $opt, 0, 2 ) == '[[' ) {
00875                         return substr( $opt, 2, -2 );
00876                 }
00877                 return $opt;
00878         }
00879 
00886         protected static function getOptionValue( $key, $opts, $default ) {
00887                 $key = strtolower( $key );
00888 
00889                 if ( isset( $opts[$key] ) ) {
00890                         return $opts[$key];
00891                 } else {
00892                         return $default;
00893                 }
00894         }
00895 }