d81d69f4022075cb1ac29be3715bd9d057fbcfbc
6 class NewParserTest
extends MediaWikiTestCase
{
9 public $keepUploads = false;
10 public $runDisabled = false;
12 public $showProgress = true;
13 public $savedInitialGlobals = array();
14 public $savedWeirdGlobals = array();
15 public $savedGlobals = array();
16 public $hooks = array();
17 public $functionHooks = array();
20 public $maxFuzzTestLength = 300;
22 public $memoryLimit = 50;
26 //PHPUnit + MediaWikiTestCase functions
29 global $wgContLang, $wgUseDatabaseMessages, $wgMsgCacheExpiry, $wgNamespaceProtection, $wgNamespaceAliases;
30 $wgContLang = Language
::factory( 'en' );
35 if ( $this->getCliArg( 'regex=' ) ) {
36 $this->regex
= $this->getCliArg( 'regex=' );
42 $this->keepUploads
= $this->getCliArg( 'keep-uploads' );
44 $tmpGlobals = array();
46 $tmpGlobals['wgScript'] = '/index.php';
47 $tmpGlobals['wgScriptPath'] = '/';
48 $tmpGlobals['wgArticlePath'] = '/wiki/$1';
49 $tmpGlobals['wgStyleSheetPath'] = '/skins';
50 $tmpGlobals['wgStylePath'] = '/skins';
51 $tmpGlobals['wgThumbnailScriptPath'] = false;
52 $tmpGlobals['wgLocalFileRepo'] = array(
53 'class' => 'LocalRepo',
55 'directory' => wfTempDir() . '/test-repo',
56 'url' => 'http://example.com/images',
57 'deletedDir' => wfTempDir() . '/test-repo/delete',
59 'transformVia404' => false,
62 $tmpGlobals['wgEnableParserCache'] = false;
63 $tmpGlobals['wgDeferredUpdateList'] = array();
64 $tmpGlobals['wgMemc'] = &wfGetMainCache();
65 $messageMemc = &wfGetMessageCacheStorage();
66 $tmpGlobals['parserMemc'] = &wfGetParserCacheStorage();
68 // $tmpGlobals['wgContLang'] = new StubContLang;
69 $tmpGlobals['wgUser'] = new User
;
70 $tmpGlobals['wgLang'] = new StubUserLang
;
71 $tmpGlobals['wgOut'] = new StubObject( 'wgOut', 'OutputPage' );
72 $tmpGlobals['wgParser'] = new StubObject( 'wgParser', $GLOBALS['wgParserConf']['class'], array( $GLOBALS['wgParserConf'] ) );
73 $tmpGlobals['wgRequest'] = new WebRequest
;
75 $tmpGlobals['wgMessageCache'] = new StubObject( 'wgMessageCache', 'MessageCache',
76 array( $messageMemc, $wgUseDatabaseMessages,
77 $wgMsgCacheExpiry ) );
78 if ( $GLOBALS['wgStyleDirectory'] === false ) {
79 $tmpGlobals['wgStyleDirectory'] = "$IP/skins";
83 foreach ( $tmpGlobals as $var => $val ) {
84 if ( array_key_exists( $var, $GLOBALS ) ) {
85 $this->savedInitialGlobals
[$var] = $GLOBALS[$var];
88 $GLOBALS[$var] = $val;
91 $this->savedWeirdGlobals
['mw_namespace_protection'] = $wgNamespaceProtection[NS_MEDIAWIKI
];
92 $this->savedWeirdGlobals
['image_alias'] = $wgNamespaceAliases['Image'];
93 $this->savedWeirdGlobals
['image_talk_alias'] = $wgNamespaceAliases['Image_talk'];
95 $wgNamespaceProtection[NS_MEDIAWIKI
] = 'editinterface';
96 $wgNamespaceAliases['Image'] = NS_FILE
;
97 $wgNamespaceAliases['Image_talk'] = NS_FILE_TALK
;
101 public function tearDown() {
103 foreach ( $this->savedInitialGlobals
as $var => $val ) {
104 $GLOBALS[$var] = $val;
107 global $wgNamespaceProtection, $wgNamespaceAliases;
109 $wgNamespaceProtection[NS_MEDIAWIKI
] = $this->savedWeirdGlobals
['mw_namespace_protection'];
110 $wgNamespaceAliases['Image'] = $this->savedWeirdGlobals
['image_alias'];
111 $wgNamespaceAliases['Image_talk'] = $this->savedWeirdGlobals
['image_talk_alias'];
114 function addDBData() {
115 # Hack: insert a few Wikipedia in-project interwiki prefixes,
116 # for testing inter-language links
117 $this->db
->insert( 'interwiki', array(
118 array( 'iw_prefix' => 'wikipedia',
119 'iw_url' => 'http://en.wikipedia.org/wiki/$1',
123 array( 'iw_prefix' => 'meatball',
124 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
128 array( 'iw_prefix' => 'zh',
129 'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
133 array( 'iw_prefix' => 'es',
134 'iw_url' => 'http://es.wikipedia.org/wiki/$1',
138 array( 'iw_prefix' => 'fr',
139 'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
143 array( 'iw_prefix' => 'ru',
144 'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
151 # Update certain things in site_stats
152 $this->db
->insert( 'site_stats', array( 'ss_row_id' => 1, 'ss_images' => 2, 'ss_good_articles' => 1 ) );
154 # Reinitialise the LocalisationCache to match the database state
155 Language
::getLocalisationCache()->unloadAll();
157 # Make a new message cache
158 global $wgMessageCache, $wgMemc;
159 $wgMessageCache = new MessageCache( $wgMemc, true, 3600 );
161 $this->uploadDir
= $this->setupUploadDir();
163 $user = User
::newFromId( 0 );
165 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Foobar.jpg' ) );
166 $image->recordUpload2( '', 'Upload of some lame file', 'Some lame file', array(
171 'media_type' => MEDIATYPE_BITMAP
,
172 'mime' => 'image/jpeg',
173 'metadata' => serialize( array() ),
174 'sha1' => wfBaseConvert( '', 16, 36, 31 ),
176 ), $this->db
->timestamp( '20010115123500' ), $user );
178 # This image will be blacklisted in [[MediaWiki:Bad image list]]
179 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Bad.jpg' ) );
180 $image->recordUpload2( '', 'zomgnotcensored', 'Borderline image', array(
185 'media_type' => MEDIATYPE_BITMAP
,
186 'mime' => 'image/jpeg',
187 'metadata' => serialize( array() ),
188 'sha1' => wfBaseConvert( '', 16, 36, 31 ),
190 ), $this->db
->timestamp( '20010115123500' ), $user );
197 //ParserTest setup/teardown functions
200 * Set up the global variables for a consistent environment for each test.
201 * Ideally this should replace the global configuration entirely.
203 protected function setupGlobals( $opts = '', $config = '' ) {
204 # Find out values for some special options.
206 self
::getOptionValue( 'language', $opts, 'en' );
208 self
::getOptionValue( 'variant', $opts, false );
210 self
::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
211 $linkHolderBatchSize =
212 self
::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
215 'wgServer' => 'http://Britney-Spears',
216 'wgScript' => '/index.php',
217 'wgScriptPath' => '/',
218 'wgArticlePath' => '/wiki/$1',
219 'wgActionPaths' => array(),
220 'wgLocalFileRepo' => array(
221 'class' => 'LocalRepo',
223 'directory' => $this->uploadDir
,
224 'url' => 'http://example.com/images',
226 'transformVia404' => false,
228 'wgEnableUploads' => self
::getOptionValue( 'wgEnableUploads', $opts, true ),
229 'wgStylePath' => '/skins',
230 'wgStyleSheetPath' => '/skins',
231 'wgSitename' => 'MediaWiki',
232 'wgLanguageCode' => $lang,
233 'wgDBprefix' => $this->db
->getType() != 'oracle' ?
'unittest_' : 'ut_',
234 'wgRawHtml' => isset( $opts['rawhtml'] ),
236 'wgContLang' => null,
237 'wgNamespacesWithSubpages' => array( 0 => isset( $opts['subpage'] ) ),
238 'wgMaxTocLevel' => $maxtoclevel,
239 'wgCapitalLinks' => true,
240 'wgNoFollowLinks' => true,
241 'wgNoFollowDomainExceptions' => array(),
242 'wgThumbnailScriptPath' => false,
243 'wgUseImageResize' => false,
244 'wgUseTeX' => isset( $opts['math'] ),
245 'wgMathDirectory' => $this->uploadDir
. '/math',
246 'wgLocaltimezone' => 'UTC',
247 'wgAllowExternalImages' => true,
248 'wgUseTidy' => false,
249 'wgDefaultLanguageVariant' => $variant,
250 'wgVariantArticlePath' => false,
251 'wgGroupPermissions' => array( '*' => array(
252 'createaccount' => true,
255 'createpage' => true,
256 'createtalk' => true,
258 'wgNamespaceProtection' => array( NS_MEDIAWIKI
=> 'editinterface' ),
259 'wgDefaultExternalStore' => array(),
260 'wgForeignFileRepos' => array(),
261 'wgLinkHolderBatchSize' => $linkHolderBatchSize,
262 'wgExperimentalHtmlIds' => false,
263 'wgExternalLinkTarget' => false,
264 'wgAlwaysUseTidy' => false,
266 'wgWellFormedXml' => true,
267 'wgAllowMicrodataAttributes' => true,
268 'wgAdaptiveMessageCache' => true
272 $configLines = explode( "\n", $config );
274 foreach ( $configLines as $line ) {
275 list( $var, $value ) = explode( '=', $line, 2 );
277 $settings[$var] = eval( "return $value;" ); //???
281 $this->savedGlobals
= array();
283 foreach ( $settings as $var => $val ) {
284 if ( array_key_exists( $var, $GLOBALS ) ) {
285 $this->savedGlobals
[$var] = $GLOBALS[$var];
288 $GLOBALS[$var] = $val;
291 $langObj = Language
::factory( $lang );
292 $GLOBALS['wgLang'] = $langObj;
293 $GLOBALS['wgContLang'] = $langObj;
294 $GLOBALS['wgMemc'] = new FakeMemCachedClient
;
295 $GLOBALS['wgOut'] = new OutputPage
;
299 $wgHooks['ParserTestParser'][] = 'ParserTestParserHook::setup';
300 $wgHooks['ParserTestParser'][] = 'ParserTestStaticParserHook::setup';
301 $wgHooks['ParserGetVariableValueTs'][] = 'ParserTest::getFakeTimestamp';
303 MagicWord
::clearCache();
306 $wgUser = new User();
310 * Restore default values and perform any necessary clean-up
311 * after each test runs.
313 protected function teardownGlobals() {
314 RepoGroup
::destroySingleton();
315 LinkCache
::singleton()->clear();
317 foreach ( $this->savedGlobals
as $var => $val ) {
318 $GLOBALS[$var] = $val;
323 * Create a dummy uploads directory which will contain a couple
324 * of files in order to pass existence tests.
326 * @return String: the directory
328 protected function setupUploadDir() {
331 if ( $this->keepUploads
) {
332 $dir = wfTempDir() . '/mwParser-images';
334 if ( is_dir( $dir ) ) {
338 $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
341 // wfDebug( "Creating upload directory $dir\n" );
342 if ( file_exists( $dir ) ) {
343 wfDebug( "Already exists!\n" );
347 wfMkdirParents( $dir . '/3/3a' );
348 copy( "$IP/skins/monobook/headbg.jpg", "$dir/3/3a/Foobar.jpg" );
349 wfMkdirParents( $dir . '/0/09' );
350 copy( "$IP/skins/monobook/headbg.jpg", "$dir/0/09/Bad.jpg" );
361 public function testParserTests() {
363 global $wgParserTestFiles;
365 $files = $wgParserTestFiles;
367 if( $this->getCliArg( 'file=' ) ) {
368 $files = array( $this->getCliArg( 'file=' ) );
371 foreach( $files as $file ) {
373 $iter = new ParserTestFileIterator( $file, $this );
375 foreach ( $iter as $t ) {
380 $input = $t['input'];
381 $result = $t['result'];
382 $opts = $t['options'];
383 $config = $t['config'];
386 $opts = $this->parseOptions( $opts );
387 $this->setupGlobals( $opts, $config );
390 $options = ParserOptions
::newFromUser( $user );
392 if ( isset( $opts['title'] ) ) {
393 $titleText = $opts['title'];
396 $titleText = 'Parser test';
399 $local = isset( $opts['local'] );
400 $preprocessor = isset( $opts['preprocessor'] ) ?
$opts['preprocessor'] : null;
401 $parser = $this->getParser( $preprocessor );
402 $title = Title
::newFromText( $titleText );
404 if ( isset( $opts['pst'] ) ) {
405 $out = $parser->preSaveTransform( $input, $title, $user, $options );
406 } elseif ( isset( $opts['msg'] ) ) {
407 $out = $parser->transformMsg( $input, $options );
408 } elseif ( isset( $opts['section'] ) ) {
409 $section = $opts['section'];
410 $out = $parser->getSection( $input, $section );
411 } elseif ( isset( $opts['replace'] ) ) {
412 $section = $opts['replace'][0];
413 $replace = $opts['replace'][1];
414 $out = $parser->replaceSection( $input, $section, $replace );
415 } elseif ( isset( $opts['comment'] ) ) {
416 $linker = $user->getSkin();
417 $out = $linker->formatComment( $input, $title, $local );
418 } elseif ( isset( $opts['preload'] ) ) {
419 $out = $parser->getpreloadText( $input, $title, $options );
421 $output = $parser->parse( $input, $title, $options, true, true, 1337 );
422 $out = $output->getText();
424 if ( isset( $opts['showtitle'] ) ) {
425 if ( $output->getTitleText() ) {
426 $title = $output->getTitleText();
429 $out = "$title\n$out";
432 if ( isset( $opts['ill'] ) ) {
433 $out = $this->tidy( implode( ' ', $output->getLanguageLinks() ) );
434 } elseif ( isset( $opts['cat'] ) ) {
437 $wgOut->addCategoryLinks( $output->getCategories() );
438 $cats = $wgOut->getCategoryLinks();
440 if ( isset( $cats['normal'] ) ) {
441 $out = $this->tidy( implode( ' ', $cats['normal'] ) );
447 $result = $this->tidy( $result );
450 $this->teardownGlobals();
452 $this->assertEquals( $result, $out, $desc );
455 catch( Exception
$e ) {
456 $this->assertTrue( false, $t['test'] . ' (failed: ' . $e->getMessage() . ')' );
466 * Run a fuzz test series
467 * Draw input from a set of test files
469 function testFuzzTests() {
471 global $wgParserTestFiles;
473 $files = $wgParserTestFiles;
475 if( $this->getCliArg( 'file=' ) ) {
476 $files = array( $this->getCliArg( 'file=' ) );
479 $dict = $this->getFuzzInput( $files );
480 $dictSize = strlen( $dict );
481 $logMaxLength = log( $this->maxFuzzTestLength
);
483 ini_set( 'memory_limit', $this->memoryLimit
* 1048576 );
486 $opts = ParserOptions
::newFromUser( $user );
487 $title = Title
::makeTitle( NS_MAIN
, 'Parser_test' );
493 // Generate test input
494 mt_srand( ++
$this->fuzzSeed
);
495 $totalLength = mt_rand( 1, $this->maxFuzzTestLength
);
498 while ( strlen( $input ) < $totalLength ) {
499 $logHairLength = mt_rand( 0, 1000000 ) / 1000000 * $logMaxLength;
500 $hairLength = min( intval( exp( $logHairLength ) ), $dictSize );
501 $offset = mt_rand( 0, $dictSize - $hairLength );
502 $input .= substr( $dict, $offset, $hairLength );
505 $this->setupGlobals();
506 $parser = $this->getParser();
510 $parser->parse( $input, $title, $opts );
511 $this->assertTrue( true, "Test $id, fuzz seed {$this->fuzzSeed}" );
512 } catch ( Exception
$exception ) {
516 $input_dump = ob_get_contents();
519 $this->assertTrue( false, "Test $id, fuzz seed {$this->fuzzSeed}. \n\nInput: $input_dump\n\nError: {$exception->getMessage()}\n\nBacktrace: {$exception->getTraceAsString()}" );
522 $this->teardownGlobals();
523 $parser->__destruct();
525 if ( $id %
100 == 0 ) {
526 $usage = intval( memory_get_usage( true ) / $this->memoryLimit
/ 1048576 * 100 );
527 //echo "{$this->fuzzSeed}: $numSuccess/$numTotal (mem: $usage%)\n";
529 $ret = "Out of memory:\n";
530 $memStats = $this->getMemoryBreakdown();
532 foreach ( $memStats as $name => $usage ) {
533 $ret .= "$name: $usage\n";
536 throw new MWException( $ret );
552 //Various getter functions
555 * Get an input dictionary from a set of parser test files
557 function getFuzzInput( $filenames ) {
560 foreach ( $filenames as $filename ) {
561 $contents = file_get_contents( $filename );
562 preg_match_all( '/!!\s*input\n(.*?)\n!!\s*result/s', $contents, $matches );
564 foreach ( $matches[1] as $match ) {
565 $dict .= $match . "\n";
573 * Get a memory usage breakdown
575 function getMemoryBreakdown() {
578 foreach ( $GLOBALS as $name => $value ) {
579 $memStats['$' . $name] = strlen( serialize( $value ) );
582 $classes = get_declared_classes();
584 foreach ( $classes as $class ) {
585 $rc = new ReflectionClass( $class );
586 $props = $rc->getStaticProperties();
587 $memStats[$class] = strlen( serialize( $props ) );
588 $methods = $rc->getMethods();
590 foreach ( $methods as $method ) {
591 $memStats[$class] +
= strlen( serialize( $method->getStaticVariables() ) );
595 $functions = get_defined_functions();
597 foreach ( $functions['user'] as $function ) {
598 $rf = new ReflectionFunction( $function );
599 $memStats["$function()"] = strlen( serialize( $rf->getStaticVariables() ) );
608 * Get a Parser object
610 function getParser( $preprocessor = null ) {
611 global $wgParserConf;
613 $class = $wgParserConf['class'];
614 $parser = new $class( array( 'preprocessorClass' => $preprocessor ) +
$wgParserConf );
616 foreach ( $this->hooks
as $tag => $callback ) {
617 $parser->setHook( $tag, $callback );
620 foreach ( $this->functionHooks
as $tag => $bits ) {
621 list( $callback, $flags ) = $bits;
622 $parser->setFunctionHook( $tag, $callback, $flags );
625 wfRunHooks( 'ParserTestParser', array( &$parser ) );
636 //Various action functions
639 * Insert a temporary test article
640 * @param $name String: the title, including any prefix
641 * @param $text String: the article text
642 * @param $line Integer: the input line number, for reporting errors
644 public function addArticle( $name, $text, $line = 'unknown' ) {
645 global $wgCapitalLinks;
647 $text = $this->removeEndingNewline($text);
649 $oldCapitalLinks = $wgCapitalLinks;
650 $wgCapitalLinks = true; // We only need this from SetupGlobals() See r70917#c8637
652 $name = $this->removeEndingNewline( $name );
653 $title = Title
::newFromText( $name );
655 if ( is_null( $title ) ) {
656 throw new MWException( "invalid title ('$name' => '$title') at line $line\n" );
659 $aid = $title->getArticleID( Title
::GAID_FOR_UPDATE
);
662 debug_print_backtrace();
663 throw new MWException( "duplicate article '$name' at line $line\n" );
666 $art = new Article( $title );
667 $art->doEdit( $text, '', EDIT_NEW
);
669 $wgCapitalLinks = $oldCapitalLinks;
673 * Steal a callback function from the primary parser, save it for
674 * application to our scary parser. If the hook is not installed,
675 * abort processing of this file.
677 * @param $name String
678 * @return Bool true if tag hook is present
680 public function requireHook( $name ) {
683 $wgParser->firstCallInit( ); // make sure hooks are loaded.
685 if ( isset( $wgParser->mTagHooks
[$name] ) ) {
686 $this->hooks
[$name] = $wgParser->mTagHooks
[$name];
688 echo " This test suite requires the '$name' hook extension, skipping.\n";
699 //Various "cleanup" functions
702 * Run the "tidy" command on text if the $wgUseTidy
705 * @param $text String: the text to tidy
709 protected function tidy( $text ) {
713 $text = MWTidy
::tidy( $text );
720 * Remove last character if it is a newline
722 public function removeEndingNewline( $s ) {
723 if ( substr( $s, -1 ) === "\n" ) {
724 return substr( $s, 0, -1 );
736 //Test options parser functions
738 protected function parseOptions( $instring ) {
744 // foo=bar,"baz quux"
768 \[\[[^]]*\]\] # Link target
776 if ( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER
) ) {
777 foreach ( $matches as $bits ) {
778 array_shift( $bits );
779 $key = strtolower( array_shift( $bits ) );
780 if ( count( $bits ) == 0 ) {
782 } elseif ( count( $bits ) == 1 ) {
783 $opts[$key] = $this->cleanupOption( array_shift( $bits ) );
786 $opts[$key] = array_map( array( $this, 'cleanupOption' ), $bits );
793 protected function cleanupOption( $opt ) {
794 if ( substr( $opt, 0, 1 ) == '"' ) {
795 return substr( $opt, 1, -1 );
798 if ( substr( $opt, 0, 2 ) == '[[' ) {
799 return substr( $opt, 2, -2 );
805 * Use a regex to find out the value of an option
806 * @param $key String: name of option val to retrieve
807 * @param $opts Options array to look in
808 * @param $default Mixed: default value returned if not found
810 protected static function getOptionValue( $key, $opts, $default ) {
811 $key = strtolower( $key );
813 if ( isset( $opts[$key] ) ) {