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, $IP;
30 $wgContLang = Language
::factory( 'en' );
33 if ( $this->getCliArg( 'regex=' ) ) {
34 $this->regex
= $this->getCliArg( 'regex=' );
40 $this->keepUploads
= $this->getCliArg( 'keep-uploads' );
42 $tmpGlobals = array();
44 $tmpGlobals['wgScript'] = '/index.php';
45 $tmpGlobals['wgScriptPath'] = '/';
46 $tmpGlobals['wgArticlePath'] = '/wiki/$1';
47 $tmpGlobals['wgStyleSheetPath'] = '/skins';
48 $tmpGlobals['wgStylePath'] = '/skins';
49 $tmpGlobals['wgThumbnailScriptPath'] = false;
50 $tmpGlobals['wgLocalFileRepo'] = array(
51 'class' => 'LocalRepo',
53 'directory' => wfTempDir() . '/test-repo',
54 'url' => 'http://example.com/images',
55 'deletedDir' => wfTempDir() . '/test-repo/delete',
57 'transformVia404' => false,
60 $tmpGlobals['wgEnableParserCache'] = false;
61 $tmpGlobals['wgDeferredUpdateList'] = array();
62 $tmpGlobals['wgMemc'] = &wfGetMainCache();
63 $messageMemc = &wfGetMessageCacheStorage();
64 $tmpGlobals['parserMemc'] = &wfGetParserCacheStorage();
66 // $tmpGlobals['wgContLang'] = new StubContLang;
67 $tmpGlobals['wgUser'] = new User
;
68 $tmpGlobals['wgLang'] = new StubUserLang
;
69 $tmpGlobals['wgOut'] = new StubObject( 'wgOut', 'OutputPage' );
70 $tmpGlobals['wgParser'] = new StubObject( 'wgParser', $GLOBALS['wgParserConf']['class'], array( $GLOBALS['wgParserConf'] ) );
71 $tmpGlobals['wgRequest'] = new WebRequest
;
73 $tmpGlobals['wgMessageCache'] = new StubObject( 'wgMessageCache', 'MessageCache',
74 array( $messageMemc, $wgUseDatabaseMessages,
75 $wgMsgCacheExpiry ) );
76 if ( $GLOBALS['wgStyleDirectory'] === false ) {
77 $tmpGlobals['wgStyleDirectory'] = "$IP/skins";
81 foreach ( $tmpGlobals as $var => $val ) {
82 if ( array_key_exists( $var, $GLOBALS ) ) {
83 $this->savedInitialGlobals
[$var] = $GLOBALS[$var];
86 $GLOBALS[$var] = $val;
89 $this->savedWeirdGlobals
['mw_namespace_protection'] = $wgNamespaceProtection[NS_MEDIAWIKI
];
90 $this->savedWeirdGlobals
['image_alias'] = $wgNamespaceAliases['Image'];
91 $this->savedWeirdGlobals
['image_talk_alias'] = $wgNamespaceAliases['Image_talk'];
93 $wgNamespaceProtection[NS_MEDIAWIKI
] = 'editinterface';
94 $wgNamespaceAliases['Image'] = NS_FILE
;
95 $wgNamespaceAliases['Image_talk'] = NS_FILE_TALK
;
99 public function tearDown() {
101 foreach ( $this->savedInitialGlobals
as $var => $val ) {
102 $GLOBALS[$var] = $val;
105 global $wgNamespaceProtection, $wgNamespaceAliases;
107 $wgNamespaceProtection[NS_MEDIAWIKI
] = $this->savedWeirdGlobals
['mw_namespace_protection'];
108 $wgNamespaceAliases['Image'] = $this->savedWeirdGlobals
['image_alias'];
109 $wgNamespaceAliases['Image_talk'] = $this->savedWeirdGlobals
['image_talk_alias'];
112 function addDBData() {
113 # Hack: insert a few Wikipedia in-project interwiki prefixes,
114 # for testing inter-language links
115 $this->db
->insert( 'interwiki', array(
116 array( 'iw_prefix' => 'wikipedia',
117 'iw_url' => 'http://en.wikipedia.org/wiki/$1',
121 array( 'iw_prefix' => 'meatball',
122 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
126 array( 'iw_prefix' => 'zh',
127 'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
131 array( 'iw_prefix' => 'es',
132 'iw_url' => 'http://es.wikipedia.org/wiki/$1',
136 array( 'iw_prefix' => 'fr',
137 'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
141 array( 'iw_prefix' => 'ru',
142 'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
149 # Update certain things in site_stats
150 $this->db
->insert( 'site_stats', array( 'ss_row_id' => 1, 'ss_images' => 2, 'ss_good_articles' => 1 ) );
152 # Reinitialise the LocalisationCache to match the database state
153 Language
::getLocalisationCache()->unloadAll();
155 # Make a new message cache
156 global $wgMessageCache, $wgMemc;
157 $wgMessageCache = new MessageCache( $wgMemc, true, 3600 );
159 $this->uploadDir
= $this->setupUploadDir();
161 $user = User
::newFromId( 0 );
163 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Foobar.jpg' ) );
164 $image->recordUpload2( '', 'Upload of some lame file', 'Some lame file', array(
169 'media_type' => MEDIATYPE_BITMAP
,
170 'mime' => 'image/jpeg',
171 'metadata' => serialize( array() ),
172 'sha1' => wfBaseConvert( '', 16, 36, 31 ),
174 ), $this->db
->timestamp( '20010115123500' ), $user );
176 # This image will be blacklisted in [[MediaWiki:Bad image list]]
177 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Bad.jpg' ) );
178 $image->recordUpload2( '', 'zomgnotcensored', 'Borderline image', array(
183 'media_type' => MEDIATYPE_BITMAP
,
184 'mime' => 'image/jpeg',
185 'metadata' => serialize( array() ),
186 'sha1' => wfBaseConvert( '', 16, 36, 31 ),
188 ), $this->db
->timestamp( '20010115123500' ), $user );
195 //ParserTest setup/teardown functions
198 * Set up the global variables for a consistent environment for each test.
199 * Ideally this should replace the global configuration entirely.
201 protected function setupGlobals( $opts = '', $config = '' ) {
202 # Find out values for some special options.
204 self
::getOptionValue( 'language', $opts, 'en' );
206 self
::getOptionValue( 'variant', $opts, false );
208 self
::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
209 $linkHolderBatchSize =
210 self
::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
213 'wgServer' => 'http://Britney-Spears',
214 'wgScript' => '/index.php',
215 'wgScriptPath' => '/',
216 'wgArticlePath' => '/wiki/$1',
217 'wgActionPaths' => array(),
218 'wgLocalFileRepo' => array(
219 'class' => 'LocalRepo',
221 'directory' => $this->uploadDir
,
222 'url' => 'http://example.com/images',
224 'transformVia404' => false,
226 'wgEnableUploads' => self
::getOptionValue( 'wgEnableUploads', $opts, true ),
227 'wgStylePath' => '/skins',
228 'wgStyleSheetPath' => '/skins',
229 'wgSitename' => 'MediaWiki',
230 'wgLanguageCode' => $lang,
231 'wgDBprefix' => $this->db
->getType() != 'oracle' ?
'unittest_' : 'ut_',
232 'wgRawHtml' => isset( $opts['rawhtml'] ),
234 'wgContLang' => null,
235 'wgNamespacesWithSubpages' => array( 0 => isset( $opts['subpage'] ) ),
236 'wgMaxTocLevel' => $maxtoclevel,
237 'wgCapitalLinks' => true,
238 'wgNoFollowLinks' => true,
239 'wgNoFollowDomainExceptions' => array(),
240 'wgThumbnailScriptPath' => false,
241 'wgUseImageResize' => false,
242 'wgUseTeX' => isset( $opts['math'] ),
243 'wgMathDirectory' => $this->uploadDir
. '/math',
244 'wgLocaltimezone' => 'UTC',
245 'wgAllowExternalImages' => true,
246 'wgUseTidy' => false,
247 'wgDefaultLanguageVariant' => $variant,
248 'wgVariantArticlePath' => false,
249 'wgGroupPermissions' => array( '*' => array(
250 'createaccount' => true,
253 'createpage' => true,
254 'createtalk' => true,
256 'wgNamespaceProtection' => array( NS_MEDIAWIKI
=> 'editinterface' ),
257 'wgDefaultExternalStore' => array(),
258 'wgForeignFileRepos' => array(),
259 'wgLinkHolderBatchSize' => $linkHolderBatchSize,
260 'wgExperimentalHtmlIds' => false,
261 'wgExternalLinkTarget' => false,
262 'wgAlwaysUseTidy' => false,
264 'wgWellFormedXml' => true,
265 'wgAllowMicrodataAttributes' => true,
266 'wgAdaptiveMessageCache' => true
270 $configLines = explode( "\n", $config );
272 foreach ( $configLines as $line ) {
273 list( $var, $value ) = explode( '=', $line, 2 );
275 $settings[$var] = eval( "return $value;" ); //???
279 $this->savedGlobals
= array();
281 foreach ( $settings as $var => $val ) {
282 if ( array_key_exists( $var, $GLOBALS ) ) {
283 $this->savedGlobals
[$var] = $GLOBALS[$var];
286 $GLOBALS[$var] = $val;
289 $langObj = Language
::factory( $lang );
290 $GLOBALS['wgLang'] = $langObj;
291 $GLOBALS['wgContLang'] = $langObj;
292 $GLOBALS['wgMemc'] = new FakeMemCachedClient
;
293 $GLOBALS['wgOut'] = new OutputPage
;
297 $wgHooks['ParserTestParser'][] = 'ParserTestParserHook::setup';
298 $wgHooks['ParserTestParser'][] = 'ParserTestStaticParserHook::setup';
299 $wgHooks['ParserGetVariableValueTs'][] = 'ParserTest::getFakeTimestamp';
301 MagicWord
::clearCache();
304 $wgUser = new User();
308 * Restore default values and perform any necessary clean-up
309 * after each test runs.
311 protected function teardownGlobals() {
312 RepoGroup
::destroySingleton();
313 LinkCache
::singleton()->clear();
315 foreach ( $this->savedGlobals
as $var => $val ) {
316 $GLOBALS[$var] = $val;
321 * Create a dummy uploads directory which will contain a couple
322 * of files in order to pass existence tests.
324 * @return String: the directory
326 protected function setupUploadDir() {
329 if ( $this->keepUploads
) {
330 $dir = wfTempDir() . '/mwParser-images';
332 if ( is_dir( $dir ) ) {
336 $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
339 // wfDebug( "Creating upload directory $dir\n" );
340 if ( file_exists( $dir ) ) {
341 wfDebug( "Already exists!\n" );
345 wfMkdirParents( $dir . '/3/3a' );
346 copy( "$IP/skins/monobook/headbg.jpg", "$dir/3/3a/Foobar.jpg" );
347 wfMkdirParents( $dir . '/0/09' );
348 copy( "$IP/skins/monobook/headbg.jpg", "$dir/0/09/Bad.jpg" );
359 public function testParserTests() {
361 global $wgParserTestFiles;
363 $files = $wgParserTestFiles;
365 if( $this->getCliArg( 'file=' ) ) {
366 $files = array( $this->getCliArg( 'file=' ) );
369 foreach( $files as $file ) {
371 $iter = new ParserTestFileIterator( $file, $this );
373 foreach ( $iter as $t ) {
378 $input = $t['input'];
379 $result = $t['result'];
380 $opts = $t['options'];
381 $config = $t['config'];
384 $opts = $this->parseOptions( $opts );
385 $this->setupGlobals( $opts, $config );
388 $options = ParserOptions
::newFromUser( $user );
390 if ( isset( $opts['title'] ) ) {
391 $titleText = $opts['title'];
394 $titleText = 'Parser test';
397 $local = isset( $opts['local'] );
398 $preprocessor = isset( $opts['preprocessor'] ) ?
$opts['preprocessor'] : null;
399 $parser = $this->getParser( $preprocessor );
400 $title = Title
::newFromText( $titleText );
402 if ( isset( $opts['pst'] ) ) {
403 $out = $parser->preSaveTransform( $input, $title, $user, $options );
404 } elseif ( isset( $opts['msg'] ) ) {
405 $out = $parser->transformMsg( $input, $options );
406 } elseif ( isset( $opts['section'] ) ) {
407 $section = $opts['section'];
408 $out = $parser->getSection( $input, $section );
409 } elseif ( isset( $opts['replace'] ) ) {
410 $section = $opts['replace'][0];
411 $replace = $opts['replace'][1];
412 $out = $parser->replaceSection( $input, $section, $replace );
413 } elseif ( isset( $opts['comment'] ) ) {
414 $linker = $user->getSkin();
415 $out = $linker->formatComment( $input, $title, $local );
416 } elseif ( isset( $opts['preload'] ) ) {
417 $out = $parser->getpreloadText( $input, $title, $options );
419 $output = $parser->parse( $input, $title, $options, true, true, 1337 );
420 $out = $output->getText();
422 if ( isset( $opts['showtitle'] ) ) {
423 if ( $output->getTitleText() ) {
424 $title = $output->getTitleText();
427 $out = "$title\n$out";
430 if ( isset( $opts['ill'] ) ) {
431 $out = $this->tidy( implode( ' ', $output->getLanguageLinks() ) );
432 } elseif ( isset( $opts['cat'] ) ) {
435 $wgOut->addCategoryLinks( $output->getCategories() );
436 $cats = $wgOut->getCategoryLinks();
438 if ( isset( $cats['normal'] ) ) {
439 $out = $this->tidy( implode( ' ', $cats['normal'] ) );
445 $result = $this->tidy( $result );
448 $this->teardownGlobals();
450 $this->assertEquals( $result, $out, $desc );
453 catch( Exception
$e ) {
454 $this->assertTrue( false, $t['test'] . ' (failed: ' . $e->getMessage() . ')' );
464 * Run a fuzz test series
465 * Draw input from a set of test files
467 function testFuzzTests() {
469 $this->markTestIncomplete( 'Breaks tesla due to memory restrictions' );
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 );
551 //Various getter functions
554 * Get an input dictionary from a set of parser test files
556 function getFuzzInput( $filenames ) {
559 foreach ( $filenames as $filename ) {
560 $contents = file_get_contents( $filename );
561 preg_match_all( '/!!\s*input\n(.*?)\n!!\s*result/s', $contents, $matches );
563 foreach ( $matches[1] as $match ) {
564 $dict .= $match . "\n";
572 * Get a memory usage breakdown
574 function getMemoryBreakdown() {
577 foreach ( $GLOBALS as $name => $value ) {
578 $memStats['$' . $name] = strlen( serialize( $value ) );
581 $classes = get_declared_classes();
583 foreach ( $classes as $class ) {
584 $rc = new ReflectionClass( $class );
585 $props = $rc->getStaticProperties();
586 $memStats[$class] = strlen( serialize( $props ) );
587 $methods = $rc->getMethods();
589 foreach ( $methods as $method ) {
590 $memStats[$class] +
= strlen( serialize( $method->getStaticVariables() ) );
594 $functions = get_defined_functions();
596 foreach ( $functions['user'] as $function ) {
597 $rf = new ReflectionFunction( $function );
598 $memStats["$function()"] = strlen( serialize( $rf->getStaticVariables() ) );
607 * Get a Parser object
609 function getParser( $preprocessor = null ) {
610 global $wgParserConf;
612 $class = $wgParserConf['class'];
613 $parser = new $class( array( 'preprocessorClass' => $preprocessor ) +
$wgParserConf );
615 foreach ( $this->hooks
as $tag => $callback ) {
616 $parser->setHook( $tag, $callback );
619 foreach ( $this->functionHooks
as $tag => $bits ) {
620 list( $callback, $flags ) = $bits;
621 $parser->setFunctionHook( $tag, $callback, $flags );
624 wfRunHooks( 'ParserTestParser', array( &$parser ) );
635 //Various action functions
638 * Insert a temporary test article
639 * @param $name String: the title, including any prefix
640 * @param $text String: the article text
641 * @param $line Integer: the input line number, for reporting errors
643 public function addArticle( $name, $text, $line = 'unknown' ) {
644 global $wgCapitalLinks;
646 $text = $this->removeEndingNewline($text);
648 $oldCapitalLinks = $wgCapitalLinks;
649 $wgCapitalLinks = true; // We only need this from SetupGlobals() See r70917#c8637
651 $name = $this->removeEndingNewline( $name );
652 $title = Title
::newFromText( $name );
654 if ( is_null( $title ) ) {
655 throw new MWException( "invalid title ('$name' => '$title') at line $line\n" );
658 $aid = $title->getArticleID( Title
::GAID_FOR_UPDATE
);
661 debug_print_backtrace();
662 throw new MWException( "duplicate article '$name' at line $line\n" );
665 $art = new Article( $title );
666 $art->doEdit( $text, '', EDIT_NEW
);
668 $wgCapitalLinks = $oldCapitalLinks;
672 * Steal a callback function from the primary parser, save it for
673 * application to our scary parser. If the hook is not installed,
674 * abort processing of this file.
676 * @param $name String
677 * @return Bool true if tag hook is present
679 public function requireHook( $name ) {
682 $wgParser->firstCallInit( ); // make sure hooks are loaded.
684 if ( isset( $wgParser->mTagHooks
[$name] ) ) {
685 $this->hooks
[$name] = $wgParser->mTagHooks
[$name];
687 echo " This test suite requires the '$name' hook extension, skipping.\n";
698 //Various "cleanup" functions
701 * Run the "tidy" command on text if the $wgUseTidy
704 * @param $text String: the text to tidy
708 protected function tidy( $text ) {
712 $text = MWTidy
::tidy( $text );
719 * Remove last character if it is a newline
721 public function removeEndingNewline( $s ) {
722 if ( substr( $s, -1 ) === "\n" ) {
723 return substr( $s, 0, -1 );
735 //Test options parser functions
737 protected function parseOptions( $instring ) {
743 // foo=bar,"baz quux"
767 \[\[[^]]*\]\] # Link target
775 if ( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER
) ) {
776 foreach ( $matches as $bits ) {
777 array_shift( $bits );
778 $key = strtolower( array_shift( $bits ) );
779 if ( count( $bits ) == 0 ) {
781 } elseif ( count( $bits ) == 1 ) {
782 $opts[$key] = $this->cleanupOption( array_shift( $bits ) );
785 $opts[$key] = array_map( array( $this, 'cleanupOption' ), $bits );
792 protected function cleanupOption( $opt ) {
793 if ( substr( $opt, 0, 1 ) == '"' ) {
794 return substr( $opt, 1, -1 );
797 if ( substr( $opt, 0, 2 ) == '[[' ) {
798 return substr( $opt, 2, -2 );
804 * Use a regex to find out the value of an option
805 * @param $key String: name of option val to retrieve
806 * @param $opts Options array to look in
807 * @param $default Mixed: default value returned if not found
809 protected static function getOptionValue( $key, $opts, $default ) {
810 $key = strtolower( $key );
812 if ( isset( $opts[$key] ) ) {