MediaWiki  REL1_22
parserTest.inc
Go to the documentation of this file.
00001 <?php
00034 class ParserTest {
00038     private $color;
00039 
00043     private $showOutput;
00044 
00048     private $useTemporaryTables = true;
00049 
00053     private $databaseSetupDone = false;
00054 
00059     private $db;
00060 
00065     private $dbClone;
00066 
00070     private $oldTablePrefix;
00071 
00072     private $maxFuzzTestLength = 300;
00073     private $fuzzSeed = 0;
00074     private $memoryLimit = 50;
00075     private $uploadDir = null;
00076 
00077     public $regex = "";
00078     private $savedGlobals = array();
00079 
00084     public function __construct( $options = array() ) {
00085         # Only colorize output if stdout is a terminal.
00086         $this->color = !wfIsWindows() && Maintenance::posix_isatty( 1 );
00087 
00088         if ( isset( $options['color'] ) ) {
00089             switch ( $options['color'] ) {
00090                 case 'no':
00091                     $this->color = false;
00092                     break;
00093                 case 'yes':
00094                 default:
00095                     $this->color = true;
00096                     break;
00097             }
00098         }
00099 
00100         $this->term = $this->color
00101             ? new AnsiTermColorer()
00102             : new DummyTermColorer();
00103 
00104         $this->showDiffs = !isset( $options['quick'] );
00105         $this->showProgress = !isset( $options['quiet'] );
00106         $this->showFailure = !(
00107             isset( $options['quiet'] )
00108                 && ( isset( $options['record'] )
00109                 || isset( $options['compare'] ) ) ); // redundant output
00110 
00111         $this->showOutput = isset( $options['show-output'] );
00112 
00113         if ( isset( $options['filter'] ) ) {
00114             $options['regex'] = $options['filter'];
00115         }
00116 
00117         if ( isset( $options['regex'] ) ) {
00118             if ( isset( $options['record'] ) ) {
00119                 echo "Warning: --record cannot be used with --regex, disabling --record\n";
00120                 unset( $options['record'] );
00121             }
00122             $this->regex = $options['regex'];
00123         } else {
00124             # Matches anything
00125             $this->regex = '';
00126         }
00127 
00128         $this->setupRecorder( $options );
00129         $this->keepUploads = isset( $options['keep-uploads'] );
00130 
00131         if ( isset( $options['seed'] ) ) {
00132             $this->fuzzSeed = intval( $options['seed'] ) - 1;
00133         }
00134 
00135         $this->runDisabled = isset( $options['run-disabled'] );
00136         $this->runParsoid = isset( $options['run-parsoid'] );
00137 
00138         $this->hooks = array();
00139         $this->functionHooks = array();
00140         self::setUp();
00141     }
00142 
00143     static function setUp() {
00144         global $wgParser, $wgParserConf, $IP, $messageMemc, $wgMemc,
00145             $wgUser, $wgLang, $wgOut, $wgRequest, $wgStyleDirectory, $wgEnableParserCache,
00146             $wgExtraNamespaces, $wgNamespaceAliases, $wgNamespaceProtection, $wgLocalFileRepo,
00147             $parserMemc, $wgThumbnailScriptPath, $wgScriptPath,
00148             $wgArticlePath, $wgScript, $wgStylePath, $wgExtensionAssetsPath,
00149             $wgMainCacheType, $wgMessageCacheType, $wgParserCacheType, $wgLockManagers;
00150 
00151         $wgScript = '/index.php';
00152         $wgScriptPath = '/';
00153         $wgArticlePath = '/wiki/$1';
00154         $wgStylePath = '/skins';
00155         $wgExtensionAssetsPath = '/extensions';
00156         $wgThumbnailScriptPath = false;
00157         $wgLockManagers = array( array(
00158             'name' => 'fsLockManager',
00159             'class' => 'FSLockManager',
00160             'lockDirectory' => wfTempDir() . '/test-repo/lockdir',
00161         ), array(
00162             'name' => 'nullLockManager',
00163             'class' => 'NullLockManager',
00164         ) );
00165         $wgLocalFileRepo = array(
00166             'class' => 'LocalRepo',
00167             'name' => 'local',
00168             'url' => 'http://example.com/images',
00169             'hashLevels' => 2,
00170             'transformVia404' => false,
00171             'backend' => new FSFileBackend( array(
00172                 'name' => 'local-backend',
00173                 'lockManager' => 'fsLockManager',
00174                 'containerPaths' => array(
00175                     'local-public' => wfTempDir() . '/test-repo/public',
00176                     'local-thumb' => wfTempDir() . '/test-repo/thumb',
00177                     'local-temp' => wfTempDir() . '/test-repo/temp',
00178                     'local-deleted' => wfTempDir() . '/test-repo/deleted',
00179                 )
00180             ) )
00181         );
00182         $wgNamespaceProtection[NS_MEDIAWIKI] = 'editinterface';
00183         $wgNamespaceAliases['Image'] = NS_FILE;
00184         $wgNamespaceAliases['Image_talk'] = NS_FILE_TALK;
00185         # add a namespace shadowing a interwiki link, to test
00186         # proper precedence when resolving links. (bug 51680)
00187         $wgExtraNamespaces[100] = 'MemoryAlpha';
00188 
00189         // XXX: tests won't run without this (for CACHE_DB)
00190         if ( $wgMainCacheType === CACHE_DB ) {
00191             $wgMainCacheType = CACHE_NONE;
00192         }
00193         if ( $wgMessageCacheType === CACHE_DB ) {
00194             $wgMessageCacheType = CACHE_NONE;
00195         }
00196         if ( $wgParserCacheType === CACHE_DB ) {
00197             $wgParserCacheType = CACHE_NONE;
00198         }
00199 
00200         $wgEnableParserCache = false;
00201         DeferredUpdates::clearPendingUpdates();
00202         $wgMemc = wfGetMainCache(); // checks $wgMainCacheType
00203         $messageMemc = wfGetMessageCacheStorage();
00204         $parserMemc = wfGetParserCacheStorage();
00205 
00206         // $wgContLang = new StubContLang;
00207         $wgUser = new User;
00208         $context = new RequestContext;
00209         $wgLang = $context->getLanguage();
00210         $wgOut = $context->getOutput();
00211         $wgParser = new StubObject( 'wgParser', $wgParserConf['class'], array( $wgParserConf ) );
00212         $wgRequest = $context->getRequest();
00213 
00214         if ( $wgStyleDirectory === false ) {
00215             $wgStyleDirectory = "$IP/skins";
00216         }
00217 
00218         self::setupInterwikis();
00219     }
00220 
00230     public static function setupInterwikis() {
00231         # Hack: insert a few Wikipedia in-project interwiki prefixes,
00232         # for testing inter-language links
00233         Hooks::register( 'InterwikiLoadPrefix', function ( $prefix, &$iwData ) {
00234             static $testInterwikis = array(
00235                 'wikipedia' => array(
00236                     'iw_url' => 'http://en.wikipedia.org/wiki/$1',
00237                     'iw_api' => '',
00238                     'iw_wikiid' => '',
00239                     'iw_local' => 0 ),
00240                 'meatball' => array(
00241                     'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
00242                     'iw_api' => '',
00243                     'iw_wikiid' => '',
00244                     'iw_local' => 0 ),
00245                 'memoryalpha' => array(
00246                     'iw_url' => 'http://www.memory-alpha.org/en/index.php/$1',
00247                     'iw_api' => '',
00248                     'iw_wikiid' => '',
00249                     'iw_local' => 0 ),
00250                 'zh' => array(
00251                     'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
00252                     'iw_api' => '',
00253                     'iw_wikiid' => '',
00254                     'iw_local' => 1 ),
00255                 'es' => array(
00256                     'iw_url' => 'http://es.wikipedia.org/wiki/$1',
00257                     'iw_api' => '',
00258                     'iw_wikiid' => '',
00259                     'iw_local' => 1 ),
00260                 'fr' => array(
00261                     'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
00262                     'iw_api' => '',
00263                     'iw_wikiid' => '',
00264                     'iw_local' => 1 ),
00265                 'ru' => array(
00266                     'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
00267                     'iw_api' => '',
00268                     'iw_wikiid' => '',
00269                     'iw_local' => 1 ),
00270             );
00271             if ( array_key_exists( $prefix, $testInterwikis ) ) {
00272                 $iwData = $testInterwikis[$prefix];
00273             }
00274 
00275             // We only want to rely on the above fixtures
00276             return false;
00277         } );// hooks::register
00278     }
00279 
00283     public static function tearDownInterwikis() {
00284         Hooks::clear( 'InterwikiLoadPrefix' );
00285     }
00286 
00287     public function setupRecorder( $options ) {
00288         if ( isset( $options['record'] ) ) {
00289             $this->recorder = new DbTestRecorder( $this );
00290             $this->recorder->version = isset( $options['setversion'] ) ?
00291                 $options['setversion'] : SpecialVersion::getVersion();
00292         } elseif ( isset( $options['compare'] ) ) {
00293             $this->recorder = new DbTestPreviewer( $this );
00294         } else {
00295             $this->recorder = new TestRecorder( $this );
00296         }
00297     }
00298 
00303     public static function chomp( $s ) {
00304         if ( substr( $s, -1 ) === "\n" ) {
00305             return substr( $s, 0, -1 );
00306         } else {
00307             return $s;
00308         }
00309     }
00310 
00315     function fuzzTest( $filenames ) {
00316         $GLOBALS['wgContLang'] = Language::factory( 'en' );
00317         $dict = $this->getFuzzInput( $filenames );
00318         $dictSize = strlen( $dict );
00319         $logMaxLength = log( $this->maxFuzzTestLength );
00320         $this->setupDatabase();
00321         ini_set( 'memory_limit', $this->memoryLimit * 1048576 );
00322 
00323         $numTotal = 0;
00324         $numSuccess = 0;
00325         $user = new User;
00326         $opts = ParserOptions::newFromUser( $user );
00327         $title = Title::makeTitle( NS_MAIN, 'Parser_test' );
00328 
00329         while ( true ) {
00330             // Generate test input
00331             mt_srand( ++$this->fuzzSeed );
00332             $totalLength = mt_rand( 1, $this->maxFuzzTestLength );
00333             $input = '';
00334 
00335             while ( strlen( $input ) < $totalLength ) {
00336                 $logHairLength = mt_rand( 0, 1000000 ) / 1000000 * $logMaxLength;
00337                 $hairLength = min( intval( exp( $logHairLength ) ), $dictSize );
00338                 $offset = mt_rand( 0, $dictSize - $hairLength );
00339                 $input .= substr( $dict, $offset, $hairLength );
00340             }
00341 
00342             $this->setupGlobals();
00343             $parser = $this->getParser();
00344 
00345             // Run the test
00346             try {
00347                 $parser->parse( $input, $title, $opts );
00348                 $fail = false;
00349             } catch ( Exception $exception ) {
00350                 $fail = true;
00351             }
00352 
00353             if ( $fail ) {
00354                 echo "Test failed with seed {$this->fuzzSeed}\n";
00355                 echo "Input:\n";
00356                 printf( "string(%d) \"%s\"\n\n", strlen( $input ), $input );
00357                 echo "$exception\n";
00358             } else {
00359                 $numSuccess++;
00360             }
00361 
00362             $numTotal++;
00363             $this->teardownGlobals();
00364             $parser->__destruct();
00365 
00366             if ( $numTotal % 100 == 0 ) {
00367                 $usage = intval( memory_get_usage( true ) / $this->memoryLimit / 1048576 * 100 );
00368                 echo "{$this->fuzzSeed}: $numSuccess/$numTotal (mem: $usage%)\n";
00369                 if ( $usage > 90 ) {
00370                     echo "Out of memory:\n";
00371                     $memStats = $this->getMemoryBreakdown();
00372 
00373                     foreach ( $memStats as $name => $usage ) {
00374                         echo "$name: $usage\n";
00375                     }
00376                     $this->abort();
00377                 }
00378             }
00379         }
00380     }
00381 
00385     function getFuzzInput( $filenames ) {
00386         $dict = '';
00387 
00388         foreach ( $filenames as $filename ) {
00389             $contents = file_get_contents( $filename );
00390             preg_match_all( '/!!\s*input\n(.*?)\n!!\s*result/s', $contents, $matches );
00391 
00392             foreach ( $matches[1] as $match ) {
00393                 $dict .= $match . "\n";
00394             }
00395         }
00396 
00397         return $dict;
00398     }
00399 
00403     function getMemoryBreakdown() {
00404         $memStats = array();
00405 
00406         foreach ( $GLOBALS as $name => $value ) {
00407             $memStats['$' . $name] = strlen( serialize( $value ) );
00408         }
00409 
00410         $classes = get_declared_classes();
00411 
00412         foreach ( $classes as $class ) {
00413             $rc = new ReflectionClass( $class );
00414             $props = $rc->getStaticProperties();
00415             $memStats[$class] = strlen( serialize( $props ) );
00416             $methods = $rc->getMethods();
00417 
00418             foreach ( $methods as $method ) {
00419                 $memStats[$class] += strlen( serialize( $method->getStaticVariables() ) );
00420             }
00421         }
00422 
00423         $functions = get_defined_functions();
00424 
00425         foreach ( $functions['user'] as $function ) {
00426             $rf = new ReflectionFunction( $function );
00427             $memStats["$function()"] = strlen( serialize( $rf->getStaticVariables() ) );
00428         }
00429 
00430         asort( $memStats );
00431 
00432         return $memStats;
00433     }
00434 
00435     function abort() {
00436         $this->abort();
00437     }
00438 
00450     public function runTestsFromFiles( $filenames ) {
00451         $ok = false;
00452 
00453         // be sure, ParserTest::addArticle has correct language set,
00454         // so that system messages gets into the right language cache
00455         $GLOBALS['wgLanguageCode'] = 'en';
00456         $GLOBALS['wgContLang'] = Language::factory( 'en' );
00457 
00458         $this->recorder->start();
00459         try {
00460             $this->setupDatabase();
00461             $ok = true;
00462 
00463             foreach ( $filenames as $filename ) {
00464                 $tests = new TestFileIterator( $filename, $this );
00465                 $ok = $this->runTests( $tests ) && $ok;
00466             }
00467 
00468             $this->teardownDatabase();
00469             $this->recorder->report();
00470         } catch ( DBError $e ) {
00471             echo $e->getMessage();
00472         }
00473         $this->recorder->end();
00474 
00475         return $ok;
00476     }
00477 
00478     function runTests( $tests ) {
00479         $ok = true;
00480 
00481         foreach ( $tests as $t ) {
00482             $result =
00483                 $this->runTest( $t['test'], $t['input'], $t['result'], $t['options'], $t['config'] );
00484             $ok = $ok && $result;
00485             $this->recorder->record( $t['test'], $result );
00486         }
00487 
00488         if ( $this->showProgress ) {
00489             print "\n";
00490         }
00491 
00492         return $ok;
00493     }
00494 
00501     function getParser( $preprocessor = null ) {
00502         global $wgParserConf;
00503 
00504         $class = $wgParserConf['class'];
00505         $parser = new $class( array( 'preprocessorClass' => $preprocessor ) + $wgParserConf );
00506 
00507         foreach ( $this->hooks as $tag => $callback ) {
00508             $parser->setHook( $tag, $callback );
00509         }
00510 
00511         foreach ( $this->functionHooks as $tag => $bits ) {
00512             list( $callback, $flags ) = $bits;
00513             $parser->setFunctionHook( $tag, $callback, $flags );
00514         }
00515 
00516         wfRunHooks( 'ParserTestParser', array( &$parser ) );
00517 
00518         return $parser;
00519     }
00520 
00533     public function runTest( $desc, $input, $result, $opts, $config ) {
00534         if ( $this->showProgress ) {
00535             $this->showTesting( $desc );
00536         }
00537 
00538         $opts = $this->parseOptions( $opts );
00539         $context = $this->setupGlobals( $opts, $config );
00540 
00541         $user = $context->getUser();
00542         $options = ParserOptions::newFromContext( $context );
00543 
00544         if ( isset( $opts['title'] ) ) {
00545             $titleText = $opts['title'];
00546         } else {
00547             $titleText = 'Parser test';
00548         }
00549 
00550         $local = isset( $opts['local'] );
00551         $preprocessor = isset( $opts['preprocessor'] ) ? $opts['preprocessor'] : null;
00552         $parser = $this->getParser( $preprocessor );
00553         $title = Title::newFromText( $titleText );
00554 
00555         if ( isset( $opts['pst'] ) ) {
00556             $out = $parser->preSaveTransform( $input, $title, $user, $options );
00557         } elseif ( isset( $opts['msg'] ) ) {
00558             $out = $parser->transformMsg( $input, $options, $title );
00559         } elseif ( isset( $opts['section'] ) ) {
00560             $section = $opts['section'];
00561             $out = $parser->getSection( $input, $section );
00562         } elseif ( isset( $opts['replace'] ) ) {
00563             $section = $opts['replace'][0];
00564             $replace = $opts['replace'][1];
00565             $out = $parser->replaceSection( $input, $section, $replace );
00566         } elseif ( isset( $opts['comment'] ) ) {
00567             $out = Linker::formatComment( $input, $title, $local );
00568         } elseif ( isset( $opts['preload'] ) ) {
00569             $out = $parser->getPreloadText( $input, $title, $options );
00570         } else {
00571             $output = $parser->parse( $input, $title, $options, true, true, 1337 );
00572             $output->setTOCEnabled( !isset( $opts['notoc'] ) );
00573             $out = $output->getText();
00574 
00575             if ( isset( $opts['showtitle'] ) ) {
00576                 if ( $output->getTitleText() ) {
00577                     $title = $output->getTitleText();
00578                 }
00579 
00580                 $out = "$title\n$out";
00581             }
00582 
00583             if ( isset( $opts['ill'] ) ) {
00584                 $out = $this->tidy( implode( ' ', $output->getLanguageLinks() ) );
00585             } elseif ( isset( $opts['cat'] ) ) {
00586                 $outputPage = $context->getOutput();
00587                 $outputPage->addCategoryLinks( $output->getCategories() );
00588                 $cats = $outputPage->getCategoryLinks();
00589 
00590                 if ( isset( $cats['normal'] ) ) {
00591                     $out = $this->tidy( implode( ' ', $cats['normal'] ) );
00592                 } else {
00593                     $out = '';
00594                 }
00595             }
00596 
00597             $result = $this->tidy( $result );
00598         }
00599 
00600         $this->teardownGlobals();
00601 
00602         $testResult = new ParserTestResult( $desc );
00603         $testResult->expected = $result;
00604         $testResult->actual = $out;
00605 
00606         return $this->showTestResult( $testResult );
00607     }
00608 
00612     function showTestResult( ParserTestResult $testResult ) {
00613         if ( $testResult->isSuccess() ) {
00614             $this->showSuccess( $testResult );
00615             return true;
00616         } else {
00617             $this->showFailure( $testResult );
00618             return false;
00619         }
00620     }
00621 
00628     private static function getOptionValue( $key, $opts, $default ) {
00629         $key = strtolower( $key );
00630 
00631         if ( isset( $opts[$key] ) ) {
00632             return $opts[$key];
00633         } else {
00634             return $default;
00635         }
00636     }
00637 
00638     private function parseOptions( $instring ) {
00639         $opts = array();
00640         // foo
00641         // foo=bar
00642         // foo="bar baz"
00643         // foo=[[bar baz]]
00644         // foo=bar,"baz quux"
00645         $regex = '/\b
00646             ([\w-]+)                        # Key
00647             \b
00648             (?:\s*
00649                 =                       # First sub-value
00650                 \s*
00651                 (
00652                     "
00653                         [^"]*           # Quoted val
00654                     "
00655                 |
00656                     \[\[
00657                         [^]]*           # Link target
00658                     \]\]
00659                 |
00660                     [\w-]+              # Plain word
00661                 )
00662                 (?:\s*
00663                     ,                   # Sub-vals 1..N
00664                     \s*
00665                     (
00666                         "[^"]*"         # Quoted val
00667                     |
00668                         \[\[[^]]*\]\]   # Link target
00669                     |
00670                         [\w-]+          # Plain word
00671                     )
00672                 )*
00673             )?
00674             /x';
00675 
00676         if ( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER ) ) {
00677             foreach ( $matches as $bits ) {
00678                 array_shift( $bits );
00679                 $key = strtolower( array_shift( $bits ) );
00680                 if ( count( $bits ) == 0 ) {
00681                     $opts[$key] = true;
00682                 } elseif ( count( $bits ) == 1 ) {
00683                     $opts[$key] = $this->cleanupOption( array_shift( $bits ) );
00684                 } else {
00685                     // Array!
00686                     $opts[$key] = array_map( array( $this, 'cleanupOption' ), $bits );
00687                 }
00688             }
00689         }
00690         return $opts;
00691     }
00692 
00693     private function cleanupOption( $opt ) {
00694         if ( substr( $opt, 0, 1 ) == '"' ) {
00695             return substr( $opt, 1, -1 );
00696         }
00697 
00698         if ( substr( $opt, 0, 2 ) == '[[' ) {
00699             return substr( $opt, 2, -2 );
00700         }
00701         return $opt;
00702     }
00703 
00708     private function setupGlobals( $opts = '', $config = '' ) {
00709         # Find out values for some special options.
00710         $lang =
00711             self::getOptionValue( 'language', $opts, 'en' );
00712         $variant =
00713             self::getOptionValue( 'variant', $opts, false );
00714         $maxtoclevel =
00715             self::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
00716         $linkHolderBatchSize =
00717             self::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
00718 
00719         $settings = array(
00720             'wgServer' => 'http://example.org',
00721             'wgScript' => '/index.php',
00722             'wgScriptPath' => '/',
00723             'wgArticlePath' => '/wiki/$1',
00724             'wgActionPaths' => array(),
00725             'wgLockManagers' => array( array(
00726                 'name' => 'fsLockManager',
00727                 'class' => 'FSLockManager',
00728                 'lockDirectory' => $this->uploadDir . '/lockdir',
00729             ), array(
00730                 'name' => 'nullLockManager',
00731                 'class' => 'NullLockManager',
00732             ) ),
00733             'wgLocalFileRepo' => array(
00734                 'class' => 'LocalRepo',
00735                 'name' => 'local',
00736                 'url' => 'http://example.com/images',
00737                 'hashLevels' => 2,
00738                 'transformVia404' => false,
00739                 'backend' => new FSFileBackend( array(
00740                     'name' => 'local-backend',
00741                     'lockManager' => 'fsLockManager',
00742                     'containerPaths' => array(
00743                         'local-public' => $this->uploadDir,
00744                         'local-thumb' => $this->uploadDir . '/thumb',
00745                         'local-temp' => $this->uploadDir . '/temp',
00746                         'local-deleted' => $this->uploadDir . '/delete',
00747                     )
00748                 ) )
00749             ),
00750             'wgEnableUploads' => self::getOptionValue( 'wgEnableUploads', $opts, true ),
00751             'wgStylePath' => '/skins',
00752             'wgSitename' => 'MediaWiki',
00753             'wgLanguageCode' => $lang,
00754             'wgDBprefix' => $this->db->getType() != 'oracle' ? 'parsertest_' : 'pt_',
00755             'wgRawHtml' => self::getOptionValue( 'wgRawHtml', $opts, false ),
00756             'wgLang' => null,
00757             'wgContLang' => null,
00758             'wgNamespacesWithSubpages' => array( 0 => isset( $opts['subpage'] ) ),
00759             'wgMaxTocLevel' => $maxtoclevel,
00760             'wgCapitalLinks' => true,
00761             'wgNoFollowLinks' => true,
00762             'wgNoFollowDomainExceptions' => array(),
00763             'wgThumbnailScriptPath' => false,
00764             'wgUseImageResize' => true,
00765             'wgSVGConverter' => 'null',
00766             'wgSVGConverters' => array( 'null' => 'echo "1">$output' ),
00767             'wgLocaltimezone' => 'UTC',
00768             'wgAllowExternalImages' => self::getOptionValue( 'wgAllowExternalImages', $opts, true ),
00769             'wgUseTidy' => false,
00770             'wgDefaultLanguageVariant' => $variant,
00771             'wgVariantArticlePath' => false,
00772             'wgGroupPermissions' => array( '*' => array(
00773                 'createaccount' => true,
00774                 'read' => true,
00775                 'edit' => true,
00776                 'createpage' => true,
00777                 'createtalk' => true,
00778             ) ),
00779             'wgNamespaceProtection' => array( NS_MEDIAWIKI => 'editinterface' ),
00780             'wgDefaultExternalStore' => array(),
00781             'wgForeignFileRepos' => array(),
00782             'wgLinkHolderBatchSize' => $linkHolderBatchSize,
00783             'wgExperimentalHtmlIds' => false,
00784             'wgExternalLinkTarget' => false,
00785             'wgAlwaysUseTidy' => false,
00786             'wgHtml5' => true,
00787             'wgWellFormedXml' => true,
00788             'wgAllowMicrodataAttributes' => true,
00789             'wgAdaptiveMessageCache' => true,
00790             'wgDisableLangConversion' => false,
00791             'wgDisableTitleConversion' => false,
00792         );
00793 
00794         if ( $config ) {
00795             $configLines = explode( "\n", $config );
00796 
00797             foreach ( $configLines as $line ) {
00798                 list( $var, $value ) = explode( '=', $line, 2 );
00799 
00800                 $settings[$var] = eval( "return $value;" );
00801             }
00802         }
00803 
00804         $this->savedGlobals = array();
00805 
00807         wfRunHooks( 'ParserTestGlobals', array( &$settings ) );
00808 
00809         foreach ( $settings as $var => $val ) {
00810             if ( array_key_exists( $var, $GLOBALS ) ) {
00811                 $this->savedGlobals[$var] = $GLOBALS[$var];
00812             }
00813 
00814             $GLOBALS[$var] = $val;
00815         }
00816 
00817         $GLOBALS['wgContLang'] = Language::factory( $lang );
00818         $GLOBALS['wgMemc'] = new EmptyBagOStuff;
00819 
00820         $context = new RequestContext();
00821         $GLOBALS['wgLang'] = $context->getLanguage();
00822         $GLOBALS['wgOut'] = $context->getOutput();
00823 
00824         $GLOBALS['wgUser'] = new User();
00825 
00826         global $wgHooks;
00827 
00828         $wgHooks['ParserTestParser'][] = 'ParserTestParserHook::setup';
00829         $wgHooks['ParserGetVariableValueTs'][] = 'ParserTest::getFakeTimestamp';
00830 
00831         MagicWord::clearCache();
00832 
00833         return $context;
00834     }
00835 
00840     private function listTables() {
00841         $tables = array( 'user', 'user_properties', 'user_former_groups', 'page', 'page_restrictions',
00842             'protected_titles', 'revision', 'text', 'pagelinks', 'imagelinks',
00843             'categorylinks', 'templatelinks', 'externallinks', 'langlinks', 'iwlinks',
00844             'site_stats', 'hitcounter', 'ipblocks', 'image', 'oldimage',
00845             'recentchanges', 'watchlist', 'interwiki', 'logging',
00846             'querycache', 'objectcache', 'job', 'l10n_cache', 'redirect', 'querycachetwo',
00847             'archive', 'user_groups', 'page_props', 'category', 'msg_resource', 'msg_resource_links'
00848         );
00849 
00850         if ( in_array( $this->db->getType(), array( 'mysql', 'sqlite', 'oracle' ) ) ) {
00851             array_push( $tables, 'searchindex' );
00852         }
00853 
00854         // Allow extensions to add to the list of tables to duplicate;
00855         // may be necessary if they hook into page save or other code
00856         // which will require them while running tests.
00857         wfRunHooks( 'ParserTestTables', array( &$tables ) );
00858 
00859         return $tables;
00860     }
00861 
00867     public function setupDatabase() {
00868         global $wgDBprefix;
00869 
00870         if ( $this->databaseSetupDone ) {
00871             return;
00872         }
00873 
00874         $this->db = wfGetDB( DB_MASTER );
00875         $dbType = $this->db->getType();
00876 
00877         if ( $wgDBprefix === 'parsertest_' || ( $dbType == 'oracle' && $wgDBprefix === 'pt_' ) ) {
00878             throw new MWException( 'setupDatabase should be called before setupGlobals' );
00879         }
00880 
00881         $this->databaseSetupDone = true;
00882         $this->oldTablePrefix = $wgDBprefix;
00883 
00884         # SqlBagOStuff broke when using temporary tables on r40209 (bug 15892).
00885         # It seems to have been fixed since (r55079?), but regressed at some point before r85701.
00886         # This works around it for now...
00887         ObjectCache::$instances[CACHE_DB] = new HashBagOStuff;
00888 
00889         # CREATE TEMPORARY TABLE breaks if there is more than one server
00890         if ( wfGetLB()->getServerCount() != 1 ) {
00891             $this->useTemporaryTables = false;
00892         }
00893 
00894         $temporary = $this->useTemporaryTables || $dbType == 'postgres';
00895         $prefix = $dbType != 'oracle' ? 'parsertest_' : 'pt_';
00896 
00897         $this->dbClone = new CloneDatabase( $this->db, $this->listTables(), $prefix );
00898         $this->dbClone->useTemporaryTables( $temporary );
00899         $this->dbClone->cloneTableStructure();
00900 
00901         if ( $dbType == 'oracle' ) {
00902             $this->db->query( 'BEGIN FILL_WIKI_INFO; END;' );
00903             # Insert 0 user to prevent FK violations
00904 
00905             # Anonymous user
00906             $this->db->insert( 'user', array(
00907                 'user_id' => 0,
00908                 'user_name' => 'Anonymous' ) );
00909         }
00910 
00911         # Update certain things in site_stats
00912         $this->db->insert( 'site_stats',
00913             array( 'ss_row_id' => 1, 'ss_images' => 2, 'ss_good_articles' => 1 ) );
00914 
00915         # Reinitialise the LocalisationCache to match the database state
00916         Language::getLocalisationCache()->unloadAll();
00917 
00918         # Clear the message cache
00919         MessageCache::singleton()->clear();
00920 
00921         // Remember to update newParserTests.php after changing the below
00922         // (and it uses a slightly different syntax just for teh lulz)
00923         $this->uploadDir = $this->setupUploadDir();
00924         $user = User::createNew( 'WikiSysop' );
00925         $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Foobar.jpg' ) );
00926         # note that the size/width/height/bits/etc of the file
00927         # are actually set by inspecting the file itself; the arguments
00928         # to recordUpload2 have no effect.  That said, we try to make things
00929         # match up so it is less confusing to readers of the code & tests.
00930         $image->recordUpload2( '', 'Upload of some lame file', 'Some lame file', array(
00931             'size' => 7881,
00932             'width' => 1941,
00933             'height' => 220,
00934             'bits' => 8,
00935             'media_type' => MEDIATYPE_BITMAP,
00936             'mime' => 'image/jpeg',
00937             'metadata' => serialize( array() ),
00938             'sha1' => wfBaseConvert( '1', 16, 36, 31 ),
00939             'fileExists' => true
00940         ), $this->db->timestamp( '20010115123500' ), $user );
00941 
00942         $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Thumb.png' ) );
00943         # again, note that size/width/height below are ignored; see above.
00944         $image->recordUpload2( '', 'Upload of some lame thumbnail', 'Some lame thumbnail', array(
00945             'size' => 22589,
00946             'width' => 135,
00947             'height' => 135,
00948             'bits' => 8,
00949             'media_type' => MEDIATYPE_BITMAP,
00950             'mime' => 'image/png',
00951             'metadata' => serialize( array() ),
00952             'sha1' => wfBaseConvert( '2', 16, 36, 31 ),
00953             'fileExists' => true
00954         ), $this->db->timestamp( '20130225203040' ), $user );
00955 
00956         $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Foobar.svg' ) );
00957         $image->recordUpload2( '', 'Upload of some lame SVG', 'Some lame SVG', array(
00958                 'size'        => 12345,
00959                 'width'       => 240,
00960                 'height'      => 180,
00961                 'bits'        => 24,
00962                 'media_type'  => MEDIATYPE_DRAWING,
00963                 'mime'        => 'image/svg+xml',
00964                 'metadata'    => serialize( array() ),
00965                 'sha1'        => wfBaseConvert( '', 16, 36, 31 ),
00966                 'fileExists'  => true
00967         ), $this->db->timestamp( '20010115123500' ), $user );
00968 
00969         # This image will be blacklisted in [[MediaWiki:Bad image list]]
00970         $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Bad.jpg' ) );
00971         $image->recordUpload2( '', 'zomgnotcensored', 'Borderline image', array(
00972             'size' => 12345,
00973             'width' => 320,
00974             'height' => 240,
00975             'bits' => 24,
00976             'media_type' => MEDIATYPE_BITMAP,
00977             'mime' => 'image/jpeg',
00978             'metadata' => serialize( array() ),
00979             'sha1' => wfBaseConvert( '3', 16, 36, 31 ),
00980             'fileExists' => true
00981         ), $this->db->timestamp( '20010115123500' ), $user );
00982     }
00983 
00984     public function teardownDatabase() {
00985         if ( !$this->databaseSetupDone ) {
00986             $this->teardownGlobals();
00987             return;
00988         }
00989         $this->teardownUploadDir( $this->uploadDir );
00990 
00991         $this->dbClone->destroy();
00992         $this->databaseSetupDone = false;
00993 
00994         if ( $this->useTemporaryTables ) {
00995             if ( $this->db->getType() == 'sqlite' ) {
00996                 # Under SQLite the searchindex table is virtual and need
00997                 # to be explicitly destroyed. See bug 29912
00998                 # See also MediaWikiTestCase::destroyDB()
00999                 wfDebug( __METHOD__ . " explicitly destroying sqlite virtual table parsertest_searchindex\n" );
01000                 $this->db->query( "DROP TABLE `parsertest_searchindex`" );
01001             }
01002             # Don't need to do anything
01003             $this->teardownGlobals();
01004             return;
01005         }
01006 
01007         $tables = $this->listTables();
01008 
01009         foreach ( $tables as $table ) {
01010             if ( $this->db->getType() == 'oracle' ) {
01011                 $this->db->query( "DROP TABLE pt_$table DROP CONSTRAINTS" );
01012             } else {
01013                 $this->db->query( "DROP TABLE `parsertest_$table`" );
01014             }
01015         }
01016 
01017         if ( $this->db->getType() == 'oracle' ) {
01018             $this->db->query( 'BEGIN FILL_WIKI_INFO; END;' );
01019         }
01020 
01021         $this->teardownGlobals();
01022     }
01023 
01030     private function setupUploadDir() {
01031         global $IP;
01032 
01033         if ( $this->keepUploads ) {
01034             $dir = wfTempDir() . '/mwParser-images';
01035 
01036             if ( is_dir( $dir ) ) {
01037                 return $dir;
01038             }
01039         } else {
01040             $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
01041         }
01042 
01043         // wfDebug( "Creating upload directory $dir\n" );
01044         if ( file_exists( $dir ) ) {
01045             wfDebug( "Already exists!\n" );
01046             return $dir;
01047         }
01048 
01049         wfMkdirParents( $dir . '/3/3a', null, __METHOD__ );
01050         copy( "$IP/skins/monobook/headbg.jpg", "$dir/3/3a/Foobar.jpg" );
01051         wfMkdirParents( $dir . '/e/ea', null, __METHOD__ );
01052         copy( "$IP/skins/monobook/wiki.png", "$dir/e/ea/Thumb.png" );
01053         wfMkdirParents( $dir . '/0/09', null, __METHOD__ );
01054         copy( "$IP/skins/monobook/headbg.jpg", "$dir/0/09/Bad.jpg" );
01055         wfMkdirParents( $dir . '/f/ff', null, __METHOD__ );
01056         copy( "$IP/skins/monobook/headbg.jpg", "$dir/f/ff/Foobar.svg" );
01057         file_put_contents( "$dir/f/ff/Foobar.svg",
01058             '<?xml version="1.0" encoding="utf-8"?>' .
01059             '<svg xmlns="http://www.w3.org/2000/svg" />' );
01060         return $dir;
01061     }
01062 
01067     private function teardownGlobals() {
01068         RepoGroup::destroySingleton();
01069         FileBackendGroup::destroySingleton();
01070         LockManagerGroup::destroySingletons();
01071         LinkCache::singleton()->clear();
01072 
01073         foreach ( $this->savedGlobals as $var => $val ) {
01074             $GLOBALS[$var] = $val;
01075         }
01076     }
01077 
01081     private function teardownUploadDir( $dir ) {
01082         if ( $this->keepUploads ) {
01083             return;
01084         }
01085 
01086         // delete the files first, then the dirs.
01087         self::deleteFiles(
01088             array(
01089                 "$dir/3/3a/Foobar.jpg",
01090                 "$dir/thumb/3/3a/Foobar.jpg/180px-Foobar.jpg",
01091                 "$dir/thumb/3/3a/Foobar.jpg/200px-Foobar.jpg",
01092                 "$dir/thumb/3/3a/Foobar.jpg/640px-Foobar.jpg",
01093                 "$dir/thumb/3/3a/Foobar.jpg/120px-Foobar.jpg",
01094                 "$dir/thumb/3/3a/Foobar.jpg/1280px-Foobar.jpg",
01095                 "$dir/thumb/3/3a/Foobar.jpg/20px-Foobar.jpg",
01096                 "$dir/thumb/3/3a/Foobar.jpg/270px-Foobar.jpg",
01097                 "$dir/thumb/3/3a/Foobar.jpg/300px-Foobar.jpg",
01098                 "$dir/thumb/3/3a/Foobar.jpg/30px-Foobar.jpg",
01099                 "$dir/thumb/3/3a/Foobar.jpg/360px-Foobar.jpg",
01100                 "$dir/thumb/3/3a/Foobar.jpg/400px-Foobar.jpg",
01101                 "$dir/thumb/3/3a/Foobar.jpg/40px-Foobar.jpg",
01102                 "$dir/thumb/3/3a/Foobar.jpg/70px-Foobar.jpg",
01103                 "$dir/thumb/3/3a/Foobar.jpg/960px-Foobar.jpg",
01104 
01105                 "$dir/e/ea/Thumb.png",
01106 
01107                 "$dir/0/09/Bad.jpg",
01108 
01109                 "$dir/f/ff/Foobar.svg",
01110                 "$dir/thumb/f/ff/Foobar.svg/180px-Foobar.svg.png",
01111                 "$dir/thumb/f/ff/Foobar.svg/360px-Foobar.svg.png",
01112                 "$dir/thumb/f/ff/Foobar.svg/langde-270px-Foobar.svg.png",
01113                 "$dir/thumb/f/ff/Foobar.svg/270px-Foobar.svg.png",
01114                 "$dir/thumb/f/ff/Foobar.svg/langde-180px-Foobar.svg.png",
01115                 "$dir/thumb/f/ff/Foobar.svg/langde-360px-Foobar.svg.png",
01116 
01117                 "$dir/math/f/a/5/fa50b8b616463173474302ca3e63586b.png",
01118             )
01119         );
01120 
01121         self::deleteDirs(
01122             array(
01123                 "$dir/3/3a",
01124                 "$dir/3",
01125                 "$dir/thumb/6/65",
01126                 "$dir/thumb/6",
01127                 "$dir/thumb/3/3a/Foobar.jpg",
01128                 "$dir/thumb/3/3a",
01129                 "$dir/thumb/3",
01130                 "$dir/e/ea",
01131                 "$dir/e",
01132                 "$dir/f/ff/",
01133                 "$dir/f/",
01134                 "$dir/thumb/f/ff/Foobar.svg",
01135                 "$dir/thumb/f/ff/",
01136                 "$dir/thumb/f/",
01137                 "$dir/0/09/",
01138                 "$dir/0/",
01139                 "$dir/thumb",
01140                 "$dir/math/f/a/5",
01141                 "$dir/math/f/a",
01142                 "$dir/math/f",
01143                 "$dir/math",
01144                 "$dir",
01145             )
01146         );
01147     }
01148 
01153     private static function deleteFiles( $files ) {
01154         foreach ( $files as $file ) {
01155             if ( file_exists( $file ) ) {
01156                 unlink( $file );
01157             }
01158         }
01159     }
01160 
01165     private static function deleteDirs( $dirs ) {
01166         foreach ( $dirs as $dir ) {
01167             if ( is_dir( $dir ) ) {
01168                 rmdir( $dir );
01169             }
01170         }
01171     }
01172 
01176     protected function showTesting( $desc ) {
01177         print "Running test $desc... ";
01178     }
01179 
01188     protected function showSuccess( ParserTestResult $testResult ) {
01189         if ( $this->showProgress ) {
01190             print $this->term->color( '1;32' ) . 'PASSED' . $this->term->reset() . "\n";
01191         }
01192 
01193         return true;
01194     }
01195 
01205     protected function showFailure( ParserTestResult $testResult ) {
01206         if ( $this->showFailure ) {
01207             if ( !$this->showProgress ) {
01208                 # In quiet mode we didn't show the 'Testing' message before the
01209                 # test, in case it succeeded. Show it now:
01210                 $this->showTesting( $testResult->description );
01211             }
01212 
01213             print $this->term->color( '31' ) . 'FAILED!' . $this->term->reset() . "\n";
01214 
01215             if ( $this->showOutput ) {
01216                 print "--- Expected ---\n{$testResult->expected}\n";
01217                 print "--- Actual ---\n{$testResult->actual}\n";
01218             }
01219 
01220             if ( $this->showDiffs ) {
01221                 print $this->quickDiff( $testResult->expected, $testResult->actual );
01222                 if ( !$this->wellFormed( $testResult->actual ) ) {
01223                     print "XML error: $this->mXmlError\n";
01224                 }
01225             }
01226         }
01227 
01228         return false;
01229     }
01230 
01241     protected function quickDiff( $input, $output,
01242         $inFileTail = 'expected', $outFileTail = 'actual'
01243     ) {
01244         # Windows, or at least the fc utility, is retarded
01245         $slash = wfIsWindows() ? '\\' : '/';
01246         $prefix = wfTempDir() . "{$slash}mwParser-" . mt_rand();
01247 
01248         $infile = "$prefix-$inFileTail";
01249         $this->dumpToFile( $input, $infile );
01250 
01251         $outfile = "$prefix-$outFileTail";
01252         $this->dumpToFile( $output, $outfile );
01253 
01254         $shellInfile = wfEscapeShellArg( $infile );
01255         $shellOutfile = wfEscapeShellArg( $outfile );
01256 
01257         global $wgDiff3;
01258         // we assume that people with diff3 also have usual diff
01259         $shellCommand = ( wfIsWindows() && !$wgDiff3 ) ? 'fc' : 'diff -au';
01260 
01261         $diff = wfShellExec( "$shellCommand $shellInfile $shellOutfile" );
01262 
01263         unlink( $infile );
01264         unlink( $outfile );
01265 
01266         return $this->colorDiff( $diff );
01267     }
01268 
01275     private function dumpToFile( $data, $filename ) {
01276         $file = fopen( $filename, "wt" );
01277         fwrite( $file, $data . "\n" );
01278         fclose( $file );
01279     }
01280 
01288     protected function colorDiff( $text ) {
01289         return preg_replace(
01290             array( '/^(-.*)$/m', '/^(\+.*)$/m' ),
01291             array( $this->term->color( 34 ) . '$1' . $this->term->reset(),
01292                 $this->term->color( 31 ) . '$1' . $this->term->reset() ),
01293             $text );
01294     }
01295 
01301     public function showRunFile( $path ) {
01302         print $this->term->color( 1 ) .
01303             "Reading tests from \"$path\"..." .
01304             $this->term->reset() .
01305             "\n";
01306     }
01307 
01315     public static function addArticle( $name, $text, $line = 'unknown', $ignoreDuplicate = '' ) {
01316         global $wgCapitalLinks;
01317 
01318         $oldCapitalLinks = $wgCapitalLinks;
01319         $wgCapitalLinks = true; // We only need this from SetupGlobals() See r70917#c8637
01320 
01321         $text = self::chomp( $text );
01322         $name = self::chomp( $name );
01323 
01324         $title = Title::newFromText( $name );
01325 
01326         if ( is_null( $title ) ) {
01327             throw new MWException( "invalid title '$name' at line $line\n" );
01328         }
01329 
01330         $page = WikiPage::factory( $title );
01331         $page->loadPageData( 'fromdbmaster' );
01332 
01333         if ( $page->exists() ) {
01334             if ( $ignoreDuplicate == 'ignoreduplicate' ) {
01335                 return;
01336             } else {
01337                 throw new MWException( "duplicate article '$name' at line $line\n" );
01338             }
01339         }
01340 
01341         $page->doEditContent( ContentHandler::makeContent( $text, $title ), '', EDIT_NEW );
01342 
01343         $wgCapitalLinks = $oldCapitalLinks;
01344     }
01345 
01354     public function requireHook( $name ) {
01355         global $wgParser;
01356 
01357         $wgParser->firstCallInit(); // make sure hooks are loaded.
01358 
01359         if ( isset( $wgParser->mTagHooks[$name] ) ) {
01360             $this->hooks[$name] = $wgParser->mTagHooks[$name];
01361         } else {
01362             echo "   This test suite requires the '$name' hook extension, skipping.\n";
01363             return false;
01364         }
01365 
01366         return true;
01367     }
01368 
01377     public function requireFunctionHook( $name ) {
01378         global $wgParser;
01379 
01380         $wgParser->firstCallInit(); // make sure hooks are loaded.
01381 
01382         if ( isset( $wgParser->mFunctionHooks[$name] ) ) {
01383             $this->functionHooks[$name] = $wgParser->mFunctionHooks[$name];
01384         } else {
01385             echo "   This test suite requires the '$name' function hook extension, skipping.\n";
01386             return false;
01387         }
01388 
01389         return true;
01390     }
01391 
01399     private function tidy( $text ) {
01400         global $wgUseTidy;
01401 
01402         if ( $wgUseTidy ) {
01403             $text = MWTidy::tidy( $text );
01404         }
01405 
01406         return $text;
01407     }
01408 
01409     private function wellFormed( $text ) {
01410         $html =
01411             Sanitizer::hackDocType() .
01412                 '<html>' .
01413                 $text .
01414                 '</html>';
01415 
01416         $parser = xml_parser_create( "UTF-8" );
01417 
01418         # case folding violates XML standard, turn it off
01419         xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
01420 
01421         if ( !xml_parse( $parser, $html, true ) ) {
01422             $err = xml_error_string( xml_get_error_code( $parser ) );
01423             $position = xml_get_current_byte_index( $parser );
01424             $fragment = $this->extractFragment( $html, $position );
01425             $this->mXmlError = "$err at byte $position:\n$fragment";
01426             xml_parser_free( $parser );
01427 
01428             return false;
01429         }
01430 
01431         xml_parser_free( $parser );
01432 
01433         return true;
01434     }
01435 
01436     private function extractFragment( $text, $position ) {
01437         $start = max( 0, $position - 10 );
01438         $before = $position - $start;
01439         $fragment = '...' .
01440             $this->term->color( 34 ) .
01441             substr( $text, $start, $before ) .
01442             $this->term->color( 0 ) .
01443             $this->term->color( 31 ) .
01444             $this->term->color( 1 ) .
01445             substr( $text, $position, 1 ) .
01446             $this->term->color( 0 ) .
01447             $this->term->color( 34 ) .
01448             substr( $text, $position + 1, 9 ) .
01449             $this->term->color( 0 ) .
01450             '...';
01451         $display = str_replace( "\n", ' ', $fragment );
01452         $caret = '   ' .
01453             str_repeat( ' ', $before ) .
01454             $this->term->color( 31 ) .
01455             '^' .
01456             $this->term->color( 0 );
01457 
01458         return "$display\n$caret";
01459     }
01460 
01461     static function getFakeTimestamp( &$parser, &$ts ) {
01462         $ts = 123; //parsed as '1970-01-01T00:02:03Z'
01463         return true;
01464     }
01465 }