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, $wgUseDatabaseMessages, $wgMsgCacheExpiry, $wgNamespaceProtection, $wgNamespaceAliases, $IP, $messageMemc;
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['wgDeferredUpdateList'] = array();
60 $tmpGlobals['wgMemc'] = &wfGetMainCache();
61 $messageMemc = &wfGetMessageCacheStorage();
62 $tmpGlobals['parserMemc'] = &wfGetParserCacheStorage();
64 // $tmpGlobals['wgContLang'] = new StubContLang;
65 $tmpGlobals['wgUser'] = new User
;
66 $tmpGlobals['wgLang'] = new StubUserLang
;
67 $tmpGlobals['wgOut'] = new StubObject( 'wgOut', 'OutputPage' );
68 $tmpGlobals['wgParser'] = new StubObject( 'wgParser', $GLOBALS['wgParserConf']['class'], array( $GLOBALS['wgParserConf'] ) );
69 $tmpGlobals['wgRequest'] = new WebRequest
;
71 $tmpGlobals['wgMessageCache'] = new StubObject( 'wgMessageCache', 'MessageCache',
72 array( $messageMemc, $wgUseDatabaseMessages,
73 $wgMsgCacheExpiry ) );
74 if ( $GLOBALS['wgStyleDirectory'] === false ) {
75 $tmpGlobals['wgStyleDirectory'] = "$IP/skins";
79 foreach ( $tmpGlobals as $var => $val ) {
80 if ( array_key_exists( $var, $GLOBALS ) ) {
81 $this->savedInitialGlobals
[$var] = $GLOBALS[$var];
84 $GLOBALS[$var] = $val;
87 $this->savedWeirdGlobals
['mw_namespace_protection'] = $wgNamespaceProtection[NS_MEDIAWIKI
];
88 $this->savedWeirdGlobals
['image_alias'] = $wgNamespaceAliases['Image'];
89 $this->savedWeirdGlobals
['image_talk_alias'] = $wgNamespaceAliases['Image_talk'];
91 $wgNamespaceProtection[NS_MEDIAWIKI
] = 'editinterface';
92 $wgNamespaceAliases['Image'] = NS_FILE
;
93 $wgNamespaceAliases['Image_talk'] = NS_FILE_TALK
;
97 public function tearDown() {
99 foreach ( $this->savedInitialGlobals
as $var => $val ) {
100 $GLOBALS[$var] = $val;
103 global $wgNamespaceProtection, $wgNamespaceAliases;
105 $wgNamespaceProtection[NS_MEDIAWIKI
] = $this->savedWeirdGlobals
['mw_namespace_protection'];
106 $wgNamespaceAliases['Image'] = $this->savedWeirdGlobals
['image_alias'];
107 $wgNamespaceAliases['Image_talk'] = $this->savedWeirdGlobals
['image_talk_alias'];
110 function addDBData() {
111 # Hack: insert a few Wikipedia in-project interwiki prefixes,
112 # for testing inter-language links
113 $this->db
->insert( 'interwiki', array(
114 array( 'iw_prefix' => 'wikipedia',
115 'iw_url' => 'http://en.wikipedia.org/wiki/$1',
119 array( 'iw_prefix' => 'meatball',
120 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
124 array( 'iw_prefix' => 'zh',
125 'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
129 array( 'iw_prefix' => 'es',
130 'iw_url' => 'http://es.wikipedia.org/wiki/$1',
134 array( 'iw_prefix' => 'fr',
135 'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
139 array( 'iw_prefix' => 'ru',
140 'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
147 # Update certain things in site_stats
148 $this->db
->insert( 'site_stats', array( 'ss_row_id' => 1, 'ss_images' => 2, 'ss_good_articles' => 1 ) );
150 # Reinitialise the LocalisationCache to match the database state
151 Language
::getLocalisationCache()->unloadAll();
153 # Make a new message cache
154 global $wgMessageCache, $wgMemc;
155 $wgMessageCache = new MessageCache( $wgMemc, true, 3600 );
157 $this->uploadDir
= $this->setupUploadDir();
159 $user = User
::newFromId( 0 );
161 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Foobar.jpg' ) );
162 $image->recordUpload2( '', 'Upload of some lame file', 'Some lame file', array(
167 'media_type' => MEDIATYPE_BITMAP
,
168 'mime' => 'image/jpeg',
169 'metadata' => serialize( array() ),
170 'sha1' => wfBaseConvert( '', 16, 36, 31 ),
172 ), $this->db
->timestamp( '20010115123500' ), $user );
174 # This image will be blacklisted in [[MediaWiki:Bad image list]]
175 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Bad.jpg' ) );
176 $image->recordUpload2( '', 'zomgnotcensored', 'Borderline image', array(
181 'media_type' => MEDIATYPE_BITMAP
,
182 'mime' => 'image/jpeg',
183 'metadata' => serialize( array() ),
184 'sha1' => wfBaseConvert( '', 16, 36, 31 ),
186 ), $this->db
->timestamp( '20010115123500' ), $user );
193 //ParserTest setup/teardown functions
196 * Set up the global variables for a consistent environment for each test.
197 * Ideally this should replace the global configuration entirely.
199 protected function setupGlobals( $opts = '', $config = '' ) {
200 # Find out values for some special options.
202 self
::getOptionValue( 'language', $opts, 'en' );
204 self
::getOptionValue( 'variant', $opts, false );
206 self
::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
207 $linkHolderBatchSize =
208 self
::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
211 'wgServer' => 'http://Britney-Spears',
212 'wgScript' => '/index.php',
213 'wgScriptPath' => '/',
214 'wgArticlePath' => '/wiki/$1',
215 'wgActionPaths' => array(),
216 'wgLocalFileRepo' => array(
217 'class' => 'LocalRepo',
219 'directory' => $this->uploadDir
,
220 'url' => 'http://example.com/images',
222 'transformVia404' => false,
224 'wgEnableUploads' => self
::getOptionValue( 'wgEnableUploads', $opts, true ),
225 'wgStylePath' => '/skins',
226 'wgStyleSheetPath' => '/skins',
227 'wgSitename' => 'MediaWiki',
228 'wgLanguageCode' => $lang,
229 'wgDBprefix' => $this->db
->getType() != 'oracle' ?
'unittest_' : 'ut_',
230 'wgRawHtml' => isset( $opts['rawhtml'] ),
232 'wgContLang' => null,
233 'wgNamespacesWithSubpages' => array( 0 => isset( $opts['subpage'] ) ),
234 'wgMaxTocLevel' => $maxtoclevel,
235 'wgCapitalLinks' => true,
236 'wgNoFollowLinks' => true,
237 'wgNoFollowDomainExceptions' => array(),
238 'wgThumbnailScriptPath' => false,
239 'wgUseImageResize' => false,
240 'wgUseTeX' => isset( $opts['math'] ),
241 'wgMathDirectory' => $this->uploadDir
. '/math',
242 'wgLocaltimezone' => 'UTC',
243 'wgAllowExternalImages' => true,
244 'wgUseTidy' => false,
245 'wgDefaultLanguageVariant' => $variant,
246 'wgVariantArticlePath' => false,
247 'wgGroupPermissions' => array( '*' => array(
248 'createaccount' => true,
251 'createpage' => true,
252 'createtalk' => true,
254 'wgNamespaceProtection' => array( NS_MEDIAWIKI
=> 'editinterface' ),
255 'wgDefaultExternalStore' => array(),
256 'wgForeignFileRepos' => array(),
257 'wgLinkHolderBatchSize' => $linkHolderBatchSize,
258 'wgExperimentalHtmlIds' => false,
259 'wgExternalLinkTarget' => false,
260 'wgAlwaysUseTidy' => false,
262 'wgWellFormedXml' => true,
263 'wgAllowMicrodataAttributes' => true,
264 'wgAdaptiveMessageCache' => true
268 $configLines = explode( "\n", $config );
270 foreach ( $configLines as $line ) {
271 list( $var, $value ) = explode( '=', $line, 2 );
273 $settings[$var] = eval( "return $value;" ); //???
277 $this->savedGlobals
= array();
279 foreach ( $settings as $var => $val ) {
280 if ( array_key_exists( $var, $GLOBALS ) ) {
281 $this->savedGlobals
[$var] = $GLOBALS[$var];
284 $GLOBALS[$var] = $val;
287 $langObj = Language
::factory( $lang );
288 $GLOBALS['wgLang'] = $langObj;
289 $GLOBALS['wgContLang'] = $langObj;
290 $GLOBALS['wgMemc'] = new FakeMemCachedClient
;
291 $GLOBALS['wgOut'] = new OutputPage
;
295 $wgHooks['ParserTestParser'][] = 'ParserTestParserHook::setup';
296 $wgHooks['ParserTestParser'][] = 'ParserTestStaticParserHook::setup';
297 $wgHooks['ParserGetVariableValueTs'][] = 'ParserTest::getFakeTimestamp';
299 MagicWord
::clearCache();
302 $wgUser = new User();
306 * Restore default values and perform any necessary clean-up
307 * after each test runs.
309 protected function teardownGlobals() {
310 RepoGroup
::destroySingleton();
311 LinkCache
::singleton()->clear();
313 foreach ( $this->savedGlobals
as $var => $val ) {
314 $GLOBALS[$var] = $val;
319 * Create a dummy uploads directory which will contain a couple
320 * of files in order to pass existence tests.
322 * @return String: the directory
324 protected function setupUploadDir() {
327 if ( $this->keepUploads
) {
328 $dir = wfTempDir() . '/mwParser-images';
330 if ( is_dir( $dir ) ) {
334 $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
337 // wfDebug( "Creating upload directory $dir\n" );
338 if ( file_exists( $dir ) ) {
339 wfDebug( "Already exists!\n" );
343 wfMkdirParents( $dir . '/3/3a' );
344 copy( "$IP/skins/monobook/headbg.jpg", "$dir/3/3a/Foobar.jpg" );
345 wfMkdirParents( $dir . '/0/09' );
346 copy( "$IP/skins/monobook/headbg.jpg", "$dir/0/09/Bad.jpg" );
357 public function testParserTests() {
359 global $wgParserTestFiles;
361 $files = $wgParserTestFiles;
363 if( $this->getCliArg( 'file=' ) ) {
364 $files = array( $this->getCliArg( 'file=' ) );
367 foreach( $files as $file ) {
369 $iter = new ParserTestFileIterator( $file, $this );
371 foreach ( $iter as $t ) {
376 $input = $t['input'];
377 $result = $t['result'];
378 $opts = $t['options'];
379 $config = $t['config'];
382 $opts = $this->parseOptions( $opts );
383 $this->setupGlobals( $opts, $config );
386 $options = ParserOptions
::newFromUser( $user );
388 if ( isset( $opts['title'] ) ) {
389 $titleText = $opts['title'];
392 $titleText = 'Parser test';
395 $local = isset( $opts['local'] );
396 $preprocessor = isset( $opts['preprocessor'] ) ?
$opts['preprocessor'] : null;
397 $parser = $this->getParser( $preprocessor );
398 $title = Title
::newFromText( $titleText );
400 if ( isset( $opts['pst'] ) ) {
401 $out = $parser->preSaveTransform( $input, $title, $user, $options );
402 } elseif ( isset( $opts['msg'] ) ) {
403 $out = $parser->transformMsg( $input, $options );
404 } elseif ( isset( $opts['section'] ) ) {
405 $section = $opts['section'];
406 $out = $parser->getSection( $input, $section );
407 } elseif ( isset( $opts['replace'] ) ) {
408 $section = $opts['replace'][0];
409 $replace = $opts['replace'][1];
410 $out = $parser->replaceSection( $input, $section, $replace );
411 } elseif ( isset( $opts['comment'] ) ) {
412 $linker = $user->getSkin();
413 $out = $linker->formatComment( $input, $title, $local );
414 } elseif ( isset( $opts['preload'] ) ) {
415 $out = $parser->getpreloadText( $input, $title, $options );
417 $output = $parser->parse( $input, $title, $options, true, true, 1337 );
418 $out = $output->getText();
420 if ( isset( $opts['showtitle'] ) ) {
421 if ( $output->getTitleText() ) {
422 $title = $output->getTitleText();
425 $out = "$title\n$out";
428 if ( isset( $opts['ill'] ) ) {
429 $out = $this->tidy( implode( ' ', $output->getLanguageLinks() ) );
430 } elseif ( isset( $opts['cat'] ) ) {
433 $wgOut->addCategoryLinks( $output->getCategories() );
434 $cats = $wgOut->getCategoryLinks();
436 if ( isset( $cats['normal'] ) ) {
437 $out = $this->tidy( implode( ' ', $cats['normal'] ) );
443 $result = $this->tidy( $result );
446 $this->teardownGlobals();
448 $this->assertEquals( $result, $out, $desc );
451 catch( Exception
$e ) {
452 $this->assertTrue( false, $t['test'] . ' (failed: ' . $e->getMessage() . ')' );
462 * Run a fuzz test series
463 * Draw input from a set of test files
465 function testFuzzTests() {
467 $this->markTestIncomplete( 'Breaks tesla due to memory restrictions' );
469 global $wgParserTestFiles;
471 $files = $wgParserTestFiles;
473 if( $this->getCliArg( 'file=' ) ) {
474 $files = array( $this->getCliArg( 'file=' ) );
477 $dict = $this->getFuzzInput( $files );
478 $dictSize = strlen( $dict );
479 $logMaxLength = log( $this->maxFuzzTestLength
);
481 ini_set( 'memory_limit', $this->memoryLimit
* 1048576 );
484 $opts = ParserOptions
::newFromUser( $user );
485 $title = Title
::makeTitle( NS_MAIN
, 'Parser_test' );
491 // Generate test input
492 mt_srand( ++
$this->fuzzSeed
);
493 $totalLength = mt_rand( 1, $this->maxFuzzTestLength
);
496 while ( strlen( $input ) < $totalLength ) {
497 $logHairLength = mt_rand( 0, 1000000 ) / 1000000 * $logMaxLength;
498 $hairLength = min( intval( exp( $logHairLength ) ), $dictSize );
499 $offset = mt_rand( 0, $dictSize - $hairLength );
500 $input .= substr( $dict, $offset, $hairLength );
503 $this->setupGlobals();
504 $parser = $this->getParser();
508 $parser->parse( $input, $title, $opts );
509 $this->assertTrue( true, "Test $id, fuzz seed {$this->fuzzSeed}" );
510 } catch ( Exception
$exception ) {
514 $input_dump = ob_get_contents();
517 $this->assertTrue( false, "Test $id, fuzz seed {$this->fuzzSeed}. \n\nInput: $input_dump\n\nError: {$exception->getMessage()}\n\nBacktrace: {$exception->getTraceAsString()}" );
520 $this->teardownGlobals();
521 $parser->__destruct();
523 if ( $id %
100 == 0 ) {
524 $usage = intval( memory_get_usage( true ) / $this->memoryLimit
/ 1048576 * 100 );
525 //echo "{$this->fuzzSeed}: $numSuccess/$numTotal (mem: $usage%)\n";
527 $ret = "Out of memory:\n";
528 $memStats = $this->getMemoryBreakdown();
530 foreach ( $memStats as $name => $usage ) {
531 $ret .= "$name: $usage\n";
534 throw new MWException( $ret );
543 //Various getter functions
546 * Get an input dictionary from a set of parser test files
548 function getFuzzInput( $filenames ) {
551 foreach ( $filenames as $filename ) {
552 $contents = file_get_contents( $filename );
553 preg_match_all( '/!!\s*input\n(.*?)\n!!\s*result/s', $contents, $matches );
555 foreach ( $matches[1] as $match ) {
556 $dict .= $match . "\n";
564 * Get a memory usage breakdown
566 function getMemoryBreakdown() {
569 foreach ( $GLOBALS as $name => $value ) {
570 $memStats['$' . $name] = strlen( serialize( $value ) );
573 $classes = get_declared_classes();
575 foreach ( $classes as $class ) {
576 $rc = new ReflectionClass( $class );
577 $props = $rc->getStaticProperties();
578 $memStats[$class] = strlen( serialize( $props ) );
579 $methods = $rc->getMethods();
581 foreach ( $methods as $method ) {
582 $memStats[$class] +
= strlen( serialize( $method->getStaticVariables() ) );
586 $functions = get_defined_functions();
588 foreach ( $functions['user'] as $function ) {
589 $rf = new ReflectionFunction( $function );
590 $memStats["$function()"] = strlen( serialize( $rf->getStaticVariables() ) );
599 * Get a Parser object
601 function getParser( $preprocessor = null ) {
602 global $wgParserConf;
604 $class = $wgParserConf['class'];
605 $parser = new $class( array( 'preprocessorClass' => $preprocessor ) +
$wgParserConf );
607 foreach ( $this->hooks
as $tag => $callback ) {
608 $parser->setHook( $tag, $callback );
611 foreach ( $this->functionHooks
as $tag => $bits ) {
612 list( $callback, $flags ) = $bits;
613 $parser->setFunctionHook( $tag, $callback, $flags );
616 wfRunHooks( 'ParserTestParser', array( &$parser ) );
621 //Various action functions
624 * Insert a temporary test article
625 * @param $name String: the title, including any prefix
626 * @param $text String: the article text
627 * @param $line Integer: the input line number, for reporting errors
629 public function addArticle( $name, $text, $line = 'unknown' ) {
630 global $wgCapitalLinks;
632 $text = $this->removeEndingNewline($text);
634 $oldCapitalLinks = $wgCapitalLinks;
635 $wgCapitalLinks = true; // We only need this from SetupGlobals() See r70917#c8637
637 $name = $this->removeEndingNewline( $name );
638 $title = Title
::newFromText( $name );
640 if ( is_null( $title ) ) {
641 throw new MWException( "invalid title ('$name' => '$title') at line $line\n" );
644 $aid = $title->getArticleID( Title
::GAID_FOR_UPDATE
);
647 debug_print_backtrace();
648 throw new MWException( "duplicate article '$name' at line $line\n" );
651 $art = new Article( $title );
652 $art->doEdit( $text, '', EDIT_NEW
);
654 $wgCapitalLinks = $oldCapitalLinks;
658 * Steal a callback function from the primary parser, save it for
659 * application to our scary parser. If the hook is not installed,
660 * abort processing of this file.
662 * @param $name String
663 * @return Bool true if tag hook is present
665 public function requireHook( $name ) {
668 $wgParser->firstCallInit( ); // make sure hooks are loaded.
670 if ( isset( $wgParser->mTagHooks
[$name] ) ) {
671 $this->hooks
[$name] = $wgParser->mTagHooks
[$name];
673 echo " This test suite requires the '$name' hook extension, skipping.\n";
680 //Various "cleanup" functions
683 * Run the "tidy" command on text if the $wgUseTidy
686 * @param $text String: the text to tidy
690 protected function tidy( $text ) {
694 $text = MWTidy
::tidy( $text );
701 * Remove last character if it is a newline
703 public function removeEndingNewline( $s ) {
704 if ( substr( $s, -1 ) === "\n" ) {
705 return substr( $s, 0, -1 );
712 //Test options parser functions
714 protected function parseOptions( $instring ) {
720 // foo=bar,"baz quux"
744 \[\[[^]]*\]\] # Link target
752 if ( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER
) ) {
753 foreach ( $matches as $bits ) {
754 array_shift( $bits );
755 $key = strtolower( array_shift( $bits ) );
756 if ( count( $bits ) == 0 ) {
758 } elseif ( count( $bits ) == 1 ) {
759 $opts[$key] = $this->cleanupOption( array_shift( $bits ) );
762 $opts[$key] = array_map( array( $this, 'cleanupOption' ), $bits );
769 protected function cleanupOption( $opt ) {
770 if ( substr( $opt, 0, 1 ) == '"' ) {
771 return substr( $opt, 1, -1 );
774 if ( substr( $opt, 0, 2 ) == '[[' ) {
775 return substr( $opt, 2, -2 );
781 * Use a regex to find out the value of an option
782 * @param $key String: name of option val to retrieve
783 * @param $opts Options array to look in
784 * @param $default Mixed: default value returned if not found
786 protected static function getOptionValue( $key, $opts, $default ) {
787 $key = strtolower( $key );
789 if ( isset( $opts[$key] ) ) {