b337beeaeb6943b2981bddd7f3a128d0df990c3d
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;
24 //PHPUnit + MediaWikiTestCase functions
27 global $wgContLang, $wgNamespaceProtection, $wgNamespaceAliases, $IP;
28 $wgContLang = Language
::factory( 'en' );
31 if ( $this->getCliArg( 'regex=' ) ) {
32 $this->regex
= $this->getCliArg( 'regex=' );
38 $this->keepUploads
= $this->getCliArg( 'keep-uploads' );
40 $tmpGlobals = array();
42 $tmpGlobals['wgScript'] = '/index.php';
43 $tmpGlobals['wgScriptPath'] = '/';
44 $tmpGlobals['wgArticlePath'] = '/wiki/$1';
45 $tmpGlobals['wgStyleSheetPath'] = '/skins';
46 $tmpGlobals['wgStylePath'] = '/skins';
47 $tmpGlobals['wgThumbnailScriptPath'] = false;
48 $tmpGlobals['wgLocalFileRepo'] = array(
49 'class' => 'LocalRepo',
51 'directory' => wfTempDir() . '/test-repo',
52 'url' => 'http://example.com/images',
53 'deletedDir' => wfTempDir() . '/test-repo/delete',
55 'transformVia404' => false,
58 $tmpGlobals['wgEnableParserCache'] = false;
59 $tmpGlobals['wgHooks'] = array();
60 $tmpGlobals['wgDeferredUpdateList'] = array();
61 $tmpGlobals['wgMemc'] = &wfGetMainCache();
62 $tmpGlobals['messageMemc'] = &wfGetMessageCacheStorage();
63 $tmpGlobals['parserMemc'] = &wfGetParserCacheStorage();
65 // $tmpGlobals['wgContLang'] = new StubContLang;
66 $tmpGlobals['wgUser'] = new User
;
67 $tmpGlobals['wgLang'] = new StubUserLang
;
68 $tmpGlobals['wgOut'] = new StubObject( 'wgOut', 'OutputPage' );
69 $tmpGlobals['wgParser'] = new StubObject( 'wgParser', $GLOBALS['wgParserConf']['class'], array( $GLOBALS['wgParserConf'] ) );
70 $tmpGlobals['wgRequest'] = new WebRequest
;
72 if ( $GLOBALS['wgStyleDirectory'] === false ) {
73 $tmpGlobals['wgStyleDirectory'] = "$IP/skins";
77 foreach ( $tmpGlobals as $var => $val ) {
78 if ( array_key_exists( $var, $GLOBALS ) ) {
79 $this->savedInitialGlobals
[$var] = $GLOBALS[$var];
82 $GLOBALS[$var] = $val;
85 $this->savedWeirdGlobals
['mw_namespace_protection'] = $wgNamespaceProtection[NS_MEDIAWIKI
];
86 $this->savedWeirdGlobals
['image_alias'] = $wgNamespaceAliases['Image'];
87 $this->savedWeirdGlobals
['image_talk_alias'] = $wgNamespaceAliases['Image_talk'];
89 $wgNamespaceProtection[NS_MEDIAWIKI
] = 'editinterface';
90 $wgNamespaceAliases['Image'] = NS_FILE
;
91 $wgNamespaceAliases['Image_talk'] = NS_FILE_TALK
;
95 public function tearDown() {
97 foreach ( $this->savedInitialGlobals
as $var => $val ) {
98 $GLOBALS[$var] = $val;
101 global $wgNamespaceProtection, $wgNamespaceAliases;
103 $wgNamespaceProtection[NS_MEDIAWIKI
] = $this->savedWeirdGlobals
['mw_namespace_protection'];
104 $wgNamespaceAliases['Image'] = $this->savedWeirdGlobals
['image_alias'];
105 $wgNamespaceAliases['Image_talk'] = $this->savedWeirdGlobals
['image_talk_alias'];
108 function addDBData() {
109 # Hack: insert a few Wikipedia in-project interwiki prefixes,
110 # for testing inter-language links
111 $this->db
->insert( 'interwiki', array(
112 array( 'iw_prefix' => 'wikipedia',
113 'iw_url' => 'http://en.wikipedia.org/wiki/$1',
117 array( 'iw_prefix' => 'meatball',
118 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
122 array( 'iw_prefix' => 'zh',
123 'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
127 array( 'iw_prefix' => 'es',
128 'iw_url' => 'http://es.wikipedia.org/wiki/$1',
132 array( 'iw_prefix' => 'fr',
133 'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
137 array( 'iw_prefix' => 'ru',
138 'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
145 # Update certain things in site_stats
146 $this->db
->insert( 'site_stats', array( 'ss_row_id' => 1, 'ss_images' => 2, 'ss_good_articles' => 1 ) );
148 # Reinitialise the LocalisationCache to match the database state
149 Language
::getLocalisationCache()->unloadAll();
151 # Clear the message cache
152 MessageCache
::singleton()->clear();
154 $this->uploadDir
= $this->setupUploadDir();
156 $user = User
::newFromId( 0 );
158 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Foobar.jpg' ) );
159 $image->recordUpload2( '', 'Upload of some lame file', 'Some lame file', array(
164 'media_type' => MEDIATYPE_BITMAP
,
165 'mime' => 'image/jpeg',
166 'metadata' => serialize( array() ),
167 'sha1' => wfBaseConvert( '', 16, 36, 31 ),
169 ), $this->db
->timestamp( '20010115123500' ), $user );
171 # This image will be blacklisted in [[MediaWiki:Bad image list]]
172 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Bad.jpg' ) );
173 $image->recordUpload2( '', 'zomgnotcensored', 'Borderline image', array(
178 'media_type' => MEDIATYPE_BITMAP
,
179 'mime' => 'image/jpeg',
180 'metadata' => serialize( array() ),
181 'sha1' => wfBaseConvert( '', 16, 36, 31 ),
183 ), $this->db
->timestamp( '20010115123500' ), $user );
190 //ParserTest setup/teardown functions
193 * Set up the global variables for a consistent environment for each test.
194 * Ideally this should replace the global configuration entirely.
196 protected function setupGlobals( $opts = '', $config = '' ) {
197 # Find out values for some special options.
199 self
::getOptionValue( 'language', $opts, 'en' );
201 self
::getOptionValue( 'variant', $opts, false );
203 self
::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
204 $linkHolderBatchSize =
205 self
::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
208 'wgServer' => 'http://Britney-Spears',
209 'wgScript' => '/index.php',
210 'wgScriptPath' => '/',
211 'wgArticlePath' => '/wiki/$1',
212 'wgActionPaths' => array(),
213 'wgLocalFileRepo' => array(
214 'class' => 'LocalRepo',
216 'directory' => $this->uploadDir
,
217 'url' => 'http://example.com/images',
219 'transformVia404' => false,
221 'wgEnableUploads' => self
::getOptionValue( 'wgEnableUploads', $opts, true ),
222 'wgStylePath' => '/skins',
223 'wgStyleSheetPath' => '/skins',
224 'wgSitename' => 'MediaWiki',
225 'wgLanguageCode' => $lang,
226 'wgDBprefix' => $this->db
->getType() != 'oracle' ?
'unittest_' : 'ut_',
227 'wgRawHtml' => isset( $opts['rawhtml'] ),
229 'wgContLang' => null,
230 'wgNamespacesWithSubpages' => array( 0 => isset( $opts['subpage'] ) ),
231 'wgMaxTocLevel' => $maxtoclevel,
232 'wgCapitalLinks' => true,
233 'wgNoFollowLinks' => true,
234 'wgNoFollowDomainExceptions' => array(),
235 'wgThumbnailScriptPath' => false,
236 'wgUseImageResize' => false,
237 'wgUseTeX' => isset( $opts['math'] ),
238 'wgMathDirectory' => $this->uploadDir
. '/math',
239 'wgLocaltimezone' => 'UTC',
240 'wgAllowExternalImages' => true,
241 'wgUseTidy' => false,
242 'wgDefaultLanguageVariant' => $variant,
243 'wgVariantArticlePath' => false,
244 'wgGroupPermissions' => array( '*' => array(
245 'createaccount' => true,
248 'createpage' => true,
249 'createtalk' => true,
251 'wgNamespaceProtection' => array( NS_MEDIAWIKI
=> 'editinterface' ),
252 'wgDefaultExternalStore' => array(),
253 'wgForeignFileRepos' => array(),
254 'wgLinkHolderBatchSize' => $linkHolderBatchSize,
255 'wgExperimentalHtmlIds' => false,
256 'wgExternalLinkTarget' => false,
257 'wgAlwaysUseTidy' => false,
259 'wgWellFormedXml' => true,
260 'wgAllowMicrodataAttributes' => true,
261 'wgAdaptiveMessageCache' => true
265 $configLines = explode( "\n", $config );
267 foreach ( $configLines as $line ) {
268 list( $var, $value ) = explode( '=', $line, 2 );
270 $settings[$var] = eval( "return $value;" ); //???
274 $this->savedGlobals
= array();
276 foreach ( $settings as $var => $val ) {
277 if ( array_key_exists( $var, $GLOBALS ) ) {
278 $this->savedGlobals
[$var] = $GLOBALS[$var];
281 $GLOBALS[$var] = $val;
284 $langObj = Language
::factory( $lang );
285 $GLOBALS['wgLang'] = $langObj;
286 $GLOBALS['wgContLang'] = $langObj;
287 $GLOBALS['wgMemc'] = new FakeMemCachedClient
;
288 $GLOBALS['wgOut'] = new OutputPage
;
292 $wgHooks['ParserTestParser'][] = 'ParserTestParserHook::setup';
293 $wgHooks['ParserTestParser'][] = 'ParserTestStaticParserHook::setup';
294 $wgHooks['ParserGetVariableValueTs'][] = 'ParserTest::getFakeTimestamp';
296 MagicWord
::clearCache();
299 $wgUser = new User();
303 * Restore default values and perform any necessary clean-up
304 * after each test runs.
306 protected function teardownGlobals() {
307 RepoGroup
::destroySingleton();
308 LinkCache
::singleton()->clear();
310 foreach ( $this->savedGlobals
as $var => $val ) {
311 $GLOBALS[$var] = $val;
316 * Create a dummy uploads directory which will contain a couple
317 * of files in order to pass existence tests.
319 * @return String: the directory
321 protected function setupUploadDir() {
324 if ( $this->keepUploads
) {
325 $dir = wfTempDir() . '/mwParser-images';
327 if ( is_dir( $dir ) ) {
331 $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
334 // wfDebug( "Creating upload directory $dir\n" );
335 if ( file_exists( $dir ) ) {
336 wfDebug( "Already exists!\n" );
340 wfMkdirParents( $dir . '/3/3a' );
341 copy( "$IP/skins/monobook/headbg.jpg", "$dir/3/3a/Foobar.jpg" );
342 wfMkdirParents( $dir . '/0/09' );
343 copy( "$IP/skins/monobook/headbg.jpg", "$dir/0/09/Bad.jpg" );
354 public function testParserTests() {
356 global $wgParserTestFiles;
358 $files = $wgParserTestFiles;
360 if( $this->getCliArg( 'file=' ) ) {
361 $files = array( $this->getCliArg( 'file=' ) );
364 foreach( $files as $file ) {
366 $iter = new ParserTestFileIterator( $file, $this );
368 foreach ( $iter as $t ) {
373 $input = $t['input'];
374 $result = $t['result'];
375 $opts = $t['options'];
376 $config = $t['config'];
379 $opts = $this->parseOptions( $opts );
380 $this->setupGlobals( $opts, $config );
383 $options = ParserOptions
::newFromUser( $user );
385 if ( isset( $opts['title'] ) ) {
386 $titleText = $opts['title'];
389 $titleText = 'Parser test';
392 $local = isset( $opts['local'] );
393 $preprocessor = isset( $opts['preprocessor'] ) ?
$opts['preprocessor'] : null;
394 $parser = $this->getParser( $preprocessor );
395 $title = Title
::newFromText( $titleText );
397 if ( isset( $opts['pst'] ) ) {
398 $out = $parser->preSaveTransform( $input, $title, $user, $options );
399 } elseif ( isset( $opts['msg'] ) ) {
400 $out = $parser->transformMsg( $input, $options );
401 } elseif ( isset( $opts['section'] ) ) {
402 $section = $opts['section'];
403 $out = $parser->getSection( $input, $section );
404 } elseif ( isset( $opts['replace'] ) ) {
405 $section = $opts['replace'][0];
406 $replace = $opts['replace'][1];
407 $out = $parser->replaceSection( $input, $section, $replace );
408 } elseif ( isset( $opts['comment'] ) ) {
409 $linker = $user->getSkin();
410 $out = $linker->formatComment( $input, $title, $local );
411 } elseif ( isset( $opts['preload'] ) ) {
412 $out = $parser->getpreloadText( $input, $title, $options );
414 $output = $parser->parse( $input, $title, $options, true, true, 1337 );
415 $out = $output->getText();
417 if ( isset( $opts['showtitle'] ) ) {
418 if ( $output->getTitleText() ) {
419 $title = $output->getTitleText();
422 $out = "$title\n$out";
425 if ( isset( $opts['ill'] ) ) {
426 $out = $this->tidy( implode( ' ', $output->getLanguageLinks() ) );
427 } elseif ( isset( $opts['cat'] ) ) {
430 $wgOut->addCategoryLinks( $output->getCategories() );
431 $cats = $wgOut->getCategoryLinks();
433 if ( isset( $cats['normal'] ) ) {
434 $out = $this->tidy( implode( ' ', $cats['normal'] ) );
439 $parser->mPreprocessor
= null;
441 $result = $this->tidy( $result );
444 $this->teardownGlobals();
446 $this->assertEquals( $result, $out, $desc );
449 catch( Exception
$e ) {
450 $this->assertTrue( false, $t['test'] . ' (failed: ' . $e->getMessage() . ')' );
460 * Run a fuzz test series
461 * Draw input from a set of test files
463 function testFuzzTests() {
465 $this->markTestIncomplete( 'Breaks tesla due to memory restrictions' );
467 global $wgParserTestFiles;
469 $files = $wgParserTestFiles;
471 if( $this->getCliArg( 'file=' ) ) {
472 $files = array( $this->getCliArg( 'file=' ) );
475 $dict = $this->getFuzzInput( $files );
476 $dictSize = strlen( $dict );
477 $logMaxLength = log( $this->maxFuzzTestLength
);
479 ini_set( 'memory_limit', $this->memoryLimit
* 1048576 );
482 $opts = ParserOptions
::newFromUser( $user );
483 $title = Title
::makeTitle( NS_MAIN
, 'Parser_test' );
489 // Generate test input
490 mt_srand( ++
$this->fuzzSeed
);
491 $totalLength = mt_rand( 1, $this->maxFuzzTestLength
);
494 while ( strlen( $input ) < $totalLength ) {
495 $logHairLength = mt_rand( 0, 1000000 ) / 1000000 * $logMaxLength;
496 $hairLength = min( intval( exp( $logHairLength ) ), $dictSize );
497 $offset = mt_rand( 0, $dictSize - $hairLength );
498 $input .= substr( $dict, $offset, $hairLength );
501 $this->setupGlobals();
502 $parser = $this->getParser();
506 $parser->parse( $input, $title, $opts );
507 $this->assertTrue( true, "Test $id, fuzz seed {$this->fuzzSeed}" );
508 } catch ( Exception
$exception ) {
509 $input_dump = sprintf( "string(%d) \"%s\"\n", strlen( $input ), $input );
511 $this->assertTrue( false, "Test $id, fuzz seed {$this->fuzzSeed}. \n\nInput: $input_dump\n\nError: {$exception->getMessage()}\n\nBacktrace: {$exception->getTraceAsString()}" );
514 $this->teardownGlobals();
515 $parser->__destruct();
517 if ( $id %
100 == 0 ) {
518 $usage = intval( memory_get_usage( true ) / $this->memoryLimit
/ 1048576 * 100 );
519 //echo "{$this->fuzzSeed}: $numSuccess/$numTotal (mem: $usage%)\n";
521 $ret = "Out of memory:\n";
522 $memStats = $this->getMemoryBreakdown();
524 foreach ( $memStats as $name => $usage ) {
525 $ret .= "$name: $usage\n";
528 throw new MWException( $ret );
537 //Various getter functions
540 * Get an input dictionary from a set of parser test files
542 function getFuzzInput( $filenames ) {
545 foreach ( $filenames as $filename ) {
546 $contents = file_get_contents( $filename );
547 preg_match_all( '/!!\s*input\n(.*?)\n!!\s*result/s', $contents, $matches );
549 foreach ( $matches[1] as $match ) {
550 $dict .= $match . "\n";
558 * Get a memory usage breakdown
560 function getMemoryBreakdown() {
563 foreach ( $GLOBALS as $name => $value ) {
564 $memStats['$' . $name] = strlen( serialize( $value ) );
567 $classes = get_declared_classes();
569 foreach ( $classes as $class ) {
570 $rc = new ReflectionClass( $class );
571 $props = $rc->getStaticProperties();
572 $memStats[$class] = strlen( serialize( $props ) );
573 $methods = $rc->getMethods();
575 foreach ( $methods as $method ) {
576 $memStats[$class] +
= strlen( serialize( $method->getStaticVariables() ) );
580 $functions = get_defined_functions();
582 foreach ( $functions['user'] as $function ) {
583 $rf = new ReflectionFunction( $function );
584 $memStats["$function()"] = strlen( serialize( $rf->getStaticVariables() ) );
593 * Get a Parser object
595 function getParser( $preprocessor = null ) {
596 global $wgParserConf;
598 $class = $wgParserConf['class'];
599 $parser = new $class( array( 'preprocessorClass' => $preprocessor ) +
$wgParserConf );
601 foreach ( $this->hooks
as $tag => $callback ) {
602 $parser->setHook( $tag, $callback );
605 foreach ( $this->functionHooks
as $tag => $bits ) {
606 list( $callback, $flags ) = $bits;
607 $parser->setFunctionHook( $tag, $callback, $flags );
610 wfRunHooks( 'ParserTestParser', array( &$parser ) );
615 //Various action functions
618 * Insert a temporary test article
619 * @param $name String: the title, including any prefix
620 * @param $text String: the article text
621 * @param $line Integer: the input line number, for reporting errors
623 public function addArticle( $name, $text, $line = 'unknown' ) {
624 global $wgCapitalLinks;
626 $text = $this->removeEndingNewline($text);
628 $oldCapitalLinks = $wgCapitalLinks;
629 $wgCapitalLinks = true; // We only need this from SetupGlobals() See r70917#c8637
631 $name = $this->removeEndingNewline( $name );
632 $title = Title
::newFromText( $name );
634 if ( is_null( $title ) ) {
635 throw new MWException( "invalid title ('$name' => '$title') at line $line\n" );
638 $aid = $title->getArticleID( Title
::GAID_FOR_UPDATE
);
641 debug_print_backtrace();
642 throw new MWException( "duplicate article '$name' at line $line\n" );
645 $art = new Article( $title );
646 $art->doEdit( $text, '', EDIT_NEW
);
648 $wgCapitalLinks = $oldCapitalLinks;
652 * Steal a callback function from the primary parser, save it for
653 * application to our scary parser. If the hook is not installed,
654 * abort processing of this file.
656 * @param $name String
657 * @return Bool true if tag hook is present
659 public function requireHook( $name ) {
662 $wgParser->firstCallInit( ); // make sure hooks are loaded.
664 if ( isset( $wgParser->mTagHooks
[$name] ) ) {
665 $this->hooks
[$name] = $wgParser->mTagHooks
[$name];
667 echo " This test suite requires the '$name' hook extension, skipping.\n";
674 //Various "cleanup" functions
677 * Run the "tidy" command on text if the $wgUseTidy
680 * @param $text String: the text to tidy
684 protected function tidy( $text ) {
688 $text = MWTidy
::tidy( $text );
695 * Remove last character if it is a newline
697 public function removeEndingNewline( $s ) {
698 if ( substr( $s, -1 ) === "\n" ) {
699 return substr( $s, 0, -1 );
706 //Test options parser functions
708 protected function parseOptions( $instring ) {
714 // foo=bar,"baz quux"
738 \[\[[^]]*\]\] # Link target
746 if ( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER
) ) {
747 foreach ( $matches as $bits ) {
748 array_shift( $bits );
749 $key = strtolower( array_shift( $bits ) );
750 if ( count( $bits ) == 0 ) {
752 } elseif ( count( $bits ) == 1 ) {
753 $opts[$key] = $this->cleanupOption( array_shift( $bits ) );
756 $opts[$key] = array_map( array( $this, 'cleanupOption' ), $bits );
763 protected function cleanupOption( $opt ) {
764 if ( substr( $opt, 0, 1 ) == '"' ) {
765 return substr( $opt, 1, -1 );
768 if ( substr( $opt, 0, 2 ) == '[[' ) {
769 return substr( $opt, 2, -2 );
775 * Use a regex to find out the value of an option
776 * @param $key String: name of option val to retrieve
777 * @param $opts Options array to look in
778 * @param $default Mixed: default value returned if not found
780 protected static function getOptionValue( $key, $opts, $default ) {
781 $key = strtolower( $key );
783 if ( isset( $opts[$key] ) ) {