4 * Although marked as a stub, can work independently.
10 class NewParserTest
extends MediaWikiTestCase
{
12 static protected $articles = array(); // Array of test articles defined by the tests
13 /* The dataProvider is run on a different instance than the test, so it must be static
14 * When running tests from several files, all tests will see all articles.
18 public $keepUploads = false;
19 public $runDisabled = false;
21 public $showProgress = true;
22 public $savedInitialGlobals = array();
23 public $savedWeirdGlobals = array();
24 public $savedGlobals = array();
25 public $hooks = array();
26 public $functionHooks = array();
29 public $maxFuzzTestLength = 300;
31 public $memoryLimit = 50;
33 protected $file = false;
36 global $wgContLang, $wgNamespaceProtection, $wgNamespaceAliases;
38 $wgContLang = Language
::factory( 'en' );
41 if ( $this->getCliArg( 'regex=' ) ) {
42 $this->regex
= $this->getCliArg( 'regex=' );
48 $this->keepUploads
= $this->getCliArg( 'keep-uploads' );
50 $tmpGlobals = array();
52 $tmpGlobals['wgScript'] = '/index.php';
53 $tmpGlobals['wgScriptPath'] = '/';
54 $tmpGlobals['wgArticlePath'] = '/wiki/$1';
55 $tmpGlobals['wgStyleSheetPath'] = '/skins';
56 $tmpGlobals['wgStylePath'] = '/skins';
57 $tmpGlobals['wgThumbnailScriptPath'] = false;
58 $tmpGlobals['wgLocalFileRepo'] = array(
59 'class' => 'LocalRepo',
61 'url' => 'http://example.com/images',
63 'transformVia404' => false,
64 'backend' => 'local-backend'
66 $tmpGlobals['wgForeignFileRepos'] = array();
67 $tmpGlobals['wgEnableParserCache'] = false;
68 $tmpGlobals['wgHooks'] = $wgHooks;
69 $tmpGlobals['wgDeferredUpdateList'] = array();
70 $tmpGlobals['wgMemc'] = wfGetMainCache();
71 $tmpGlobals['messageMemc'] = wfGetMessageCacheStorage();
72 $tmpGlobals['parserMemc'] = wfGetParserCacheStorage();
74 // $tmpGlobals['wgContLang'] = new StubContLang;
75 $tmpGlobals['wgUser'] = new User
;
76 $context = new RequestContext();
77 $tmpGlobals['wgLang'] = $context->getLanguage();
78 $tmpGlobals['wgOut'] = $context->getOutput();
79 $tmpGlobals['wgParser'] = new StubObject( 'wgParser', $GLOBALS['wgParserConf']['class'], array( $GLOBALS['wgParserConf'] ) );
80 $tmpGlobals['wgRequest'] = $context->getRequest();
82 if ( $GLOBALS['wgStyleDirectory'] === false ) {
83 $tmpGlobals['wgStyleDirectory'] = "$IP/skins";
87 foreach ( $tmpGlobals as $var => $val ) {
88 if ( array_key_exists( $var, $GLOBALS ) ) {
89 $this->savedInitialGlobals
[$var] = $GLOBALS[$var];
92 $GLOBALS[$var] = $val;
95 $this->savedWeirdGlobals
['mw_namespace_protection'] = $wgNamespaceProtection[NS_MEDIAWIKI
];
96 $this->savedWeirdGlobals
['image_alias'] = $wgNamespaceAliases['Image'];
97 $this->savedWeirdGlobals
['image_talk_alias'] = $wgNamespaceAliases['Image_talk'];
99 $wgNamespaceProtection[NS_MEDIAWIKI
] = 'editinterface';
100 $wgNamespaceAliases['Image'] = NS_FILE
;
101 $wgNamespaceAliases['Image_talk'] = NS_FILE_TALK
;
104 public function tearDown() {
105 foreach ( $this->savedInitialGlobals
as $var => $val ) {
106 $GLOBALS[$var] = $val;
109 global $wgNamespaceProtection, $wgNamespaceAliases;
111 $wgNamespaceProtection[NS_MEDIAWIKI
] = $this->savedWeirdGlobals
['mw_namespace_protection'];
112 $wgNamespaceAliases['Image'] = $this->savedWeirdGlobals
['image_alias'];
113 $wgNamespaceAliases['Image_talk'] = $this->savedWeirdGlobals
['image_talk_alias'];
116 RepoGroup
::destroySingleton();
117 FileBackendGroup
::destroySingleton();
120 function addDBData() {
121 $this->tablesUsed
[] = 'image';
122 # Hack: insert a few Wikipedia in-project interwiki prefixes,
123 # for testing inter-language links
124 $this->db
->insert( 'interwiki', array(
125 array( 'iw_prefix' => 'wikipedia',
126 'iw_url' => 'http://en.wikipedia.org/wiki/$1',
130 array( 'iw_prefix' => 'meatball',
131 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
135 array( 'iw_prefix' => 'zh',
136 'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
140 array( 'iw_prefix' => 'es',
141 'iw_url' => 'http://es.wikipedia.org/wiki/$1',
145 array( 'iw_prefix' => 'fr',
146 'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
150 array( 'iw_prefix' => 'ru',
151 'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
156 * @todo Fixme! Why are we inserting duplicate data here? Shouldn't
157 * need this IGNORE or shouldn't need the insert at all.
159 ), __METHOD__
, array( 'IGNORE' ) );
162 # Update certain things in site_stats
163 $this->db
->insert( 'site_stats',
164 array( 'ss_row_id' => 1, 'ss_images' => 2, 'ss_good_articles' => 1 ),
165 __METHOD__
, array( 'IGNORE' ) );
167 # Reinitialise the LocalisationCache to match the database state
168 Language
::getLocalisationCache()->unloadAll();
170 # Clear the message cache
171 MessageCache
::singleton()->clear();
173 $this->uploadDir
= $this->setupUploadDir();
175 $user = User
::newFromId( 0 );
176 LinkCache
::singleton()->clear(); # Avoids the odd failure at creating the nullRevision
178 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Foobar.jpg' ) );
179 $image->recordUpload2( '', 'Upload of some lame file', 'Some lame file', array(
184 'media_type' => MEDIATYPE_BITMAP
,
185 'mime' => 'image/jpeg',
186 'metadata' => serialize( array() ),
187 'sha1' => wfBaseConvert( '', 16, 36, 31 ),
189 ), $this->db
->timestamp( '20010115123500' ), $user );
191 # This image will be blacklisted in [[MediaWiki:Bad image list]]
192 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Bad.jpg' ) );
193 $image->recordUpload2( '', 'zomgnotcensored', 'Borderline image', array(
198 'media_type' => MEDIATYPE_BITMAP
,
199 'mime' => 'image/jpeg',
200 'metadata' => serialize( array() ),
201 'sha1' => wfBaseConvert( '', 16, 36, 31 ),
203 ), $this->db
->timestamp( '20010115123500' ), $user );
210 //ParserTest setup/teardown functions
213 * Set up the global variables for a consistent environment for each test.
214 * Ideally this should replace the global configuration entirely.
216 protected function setupGlobals( $opts = '', $config = '' ) {
217 # Find out values for some special options.
219 self
::getOptionValue( 'language', $opts, 'en' );
221 self
::getOptionValue( 'variant', $opts, false );
223 self
::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
224 $linkHolderBatchSize =
225 self
::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
228 'wgServer' => 'http://Britney-Spears',
229 'wgScript' => '/index.php',
230 'wgScriptPath' => '/',
231 'wgArticlePath' => '/wiki/$1',
232 'wgExtensionAssetsPath' => '/extensions',
233 'wgActionPaths' => array(),
234 'wgLocalFileRepo' => array(
235 'class' => 'LocalRepo',
237 'url' => 'http://example.com/images',
239 'transformVia404' => false,
240 'backend' => new FSFileBackend( array(
241 'name' => 'local-backend',
242 'lockManager' => 'nullLockManager',
243 'containerPaths' => array(
244 'local-public' => "$this->uploadDir",
245 'local-thumb' => "$this->uploadDir/thumb",
246 'local-temp' => "$this->uploadDir/temp",
250 'wgEnableUploads' => self
::getOptionValue( 'wgEnableUploads', $opts, true ),
251 'wgStylePath' => '/skins',
252 'wgStyleSheetPath' => '/skins',
253 'wgSitename' => 'MediaWiki',
254 'wgLanguageCode' => $lang,
255 'wgDBprefix' => $this->db
->getType() != 'oracle' ?
'unittest_' : 'ut_',
256 'wgRawHtml' => isset( $opts['rawhtml'] ),
258 'wgContLang' => null,
259 'wgNamespacesWithSubpages' => array( 0 => isset( $opts['subpage'] ) ),
260 'wgMaxTocLevel' => $maxtoclevel,
261 'wgCapitalLinks' => true,
262 'wgNoFollowLinks' => true,
263 'wgNoFollowDomainExceptions' => array(),
264 'wgThumbnailScriptPath' => false,
265 'wgUseImageResize' => false,
266 'wgUseTeX' => isset( $opts['math'] ),
267 'wgMathDirectory' => $this->uploadDir
. '/math',
268 'wgLocaltimezone' => 'UTC',
269 'wgAllowExternalImages' => true,
270 'wgUseTidy' => false,
271 'wgDefaultLanguageVariant' => $variant,
272 'wgVariantArticlePath' => false,
273 'wgGroupPermissions' => array( '*' => array(
274 'createaccount' => true,
277 'createpage' => true,
278 'createtalk' => true,
280 'wgNamespaceProtection' => array( NS_MEDIAWIKI
=> 'editinterface' ),
281 'wgDefaultExternalStore' => array(),
282 'wgForeignFileRepos' => array(),
283 'wgLinkHolderBatchSize' => $linkHolderBatchSize,
284 'wgExperimentalHtmlIds' => false,
285 'wgExternalLinkTarget' => false,
286 'wgAlwaysUseTidy' => false,
288 'wgCleanupPresentationalAttributes' => true,
289 'wgWellFormedXml' => true,
290 'wgAllowMicrodataAttributes' => true,
291 'wgAdaptiveMessageCache' => true,
292 'wgUseDatabaseMessages' => true,
296 $configLines = explode( "\n", $config );
298 foreach ( $configLines as $line ) {
299 list( $var, $value ) = explode( '=', $line, 2 );
301 $settings[$var] = eval( "return $value;" ); //???
305 $this->savedGlobals
= array();
307 foreach ( $settings as $var => $val ) {
308 if ( array_key_exists( $var, $GLOBALS ) ) {
309 $this->savedGlobals
[$var] = $GLOBALS[$var];
312 $GLOBALS[$var] = $val;
315 $langObj = Language
::factory( $lang );
316 $GLOBALS['wgContLang'] = $langObj;
317 $context = new RequestContext();
318 $GLOBALS['wgLang'] = $context->getLanguage();
320 $GLOBALS['wgMemc'] = new EmptyBagOStuff
;
321 $GLOBALS['wgOut'] = $context->getOutput();
322 $GLOBALS['wgUser'] = $context->getUser();
326 $wgHooks['ParserTestParser'][] = 'ParserTestParserHook::setup';
327 $wgHooks['ParserGetVariableValueTs'][] = 'ParserTest::getFakeTimestamp';
329 MagicWord
::clearCache();
330 RepoGroup
::destroySingleton();
331 FileBackendGroup
::destroySingleton();
333 # Publish the articles after we have the final language set
334 $this->publishTestArticles();
336 # The entries saved into RepoGroup cache with previous globals will be wrong.
337 RepoGroup
::destroySingleton();
338 FileBackendGroup
::destroySingleton();
339 MessageCache
::singleton()->destroyInstance();
345 * Create a dummy uploads directory which will contain a couple
346 * of files in order to pass existence tests.
348 * @return String: the directory
350 protected function setupUploadDir() {
353 if ( $this->keepUploads
) {
354 $dir = wfTempDir() . '/mwParser-images';
356 if ( is_dir( $dir ) ) {
360 $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
363 // wfDebug( "Creating upload directory $dir\n" );
364 if ( file_exists( $dir ) ) {
365 wfDebug( "Already exists!\n" );
369 wfMkdirParents( $dir . '/3/3a', null, __METHOD__
);
370 copy( "$IP/skins/monobook/headbg.jpg", "$dir/3/3a/Foobar.jpg" );
371 wfMkdirParents( $dir . '/0/09', null, __METHOD__
);
372 copy( "$IP/skins/monobook/headbg.jpg", "$dir/0/09/Bad.jpg" );
378 * Restore default values and perform any necessary clean-up
379 * after each test runs.
381 protected function teardownGlobals() {
382 foreach ( $this->savedGlobals
as $var => $val ) {
383 $GLOBALS[$var] = $val;
386 RepoGroup
::destroySingleton();
387 LinkCache
::singleton()->clear();
389 $this->teardownUploadDir( $this->uploadDir
);
393 * Remove the dummy uploads directory
395 private function teardownUploadDir( $dir ) {
396 if ( $this->keepUploads
) {
400 // delete the files first, then the dirs.
403 "$dir/3/3a/Foobar.jpg",
404 "$dir/thumb/3/3a/Foobar.jpg/180px-Foobar.jpg",
405 "$dir/thumb/3/3a/Foobar.jpg/200px-Foobar.jpg",
406 "$dir/thumb/3/3a/Foobar.jpg/640px-Foobar.jpg",
407 "$dir/thumb/3/3a/Foobar.jpg/120px-Foobar.jpg",
411 "$dir/math/f/a/5/fa50b8b616463173474302ca3e63586b.png",
421 "$dir/thumb/3/3a/Foobar.jpg",
438 * Delete the specified files, if they exist.
439 * @param $files Array: full paths to files to delete.
441 private static function deleteFiles( $files ) {
442 foreach ( $files as $file ) {
443 if ( file_exists( $file ) ) {
450 * Delete the specified directories, if they exist. Must be empty.
451 * @param $dirs Array: full paths to directories to delete.
453 private static function deleteDirs( $dirs ) {
454 foreach ( $dirs as $dir ) {
455 if ( is_dir( $dir ) ) {
461 public function parserTestProvider() {
462 if ( $this->file
=== false ) {
463 global $wgParserTestFiles;
464 $this->file
= $wgParserTestFiles[0];
466 return new TestFileIterator( $this->file
, $this );
470 * Set the file from whose tests will be run by this instance
472 public function setParserTestFile( $filename ) {
473 $this->file
= $filename;
476 /** @dataProvider parserTestProvider */
477 public function testParserTest( $desc, $input, $result, $opts, $config ) {
478 if ( !preg_match( '/' . $this->regex
. '/', $desc ) ) return; //$this->markTestSkipped( 'Filtered out by the user' );
480 wfDebug( "Running parser test: $desc\n" );
482 $opts = $this->parseOptions( $opts );
483 $context = $this->setupGlobals( $opts, $config );
485 $user = $context->getUser();
486 $options = ParserOptions
::newFromContext( $context );
488 if ( isset( $opts['title'] ) ) {
489 $titleText = $opts['title'];
492 $titleText = 'Parser test';
495 $local = isset( $opts['local'] );
496 $preprocessor = isset( $opts['preprocessor'] ) ?
$opts['preprocessor'] : null;
497 $parser = $this->getParser( $preprocessor );
499 $title = Title
::newFromText( $titleText );
501 if ( isset( $opts['pst'] ) ) {
502 $out = $parser->preSaveTransform( $input, $title, $user, $options );
503 } elseif ( isset( $opts['msg'] ) ) {
504 $out = $parser->transformMsg( $input, $options, $title );
505 } elseif ( isset( $opts['section'] ) ) {
506 $section = $opts['section'];
507 $out = $parser->getSection( $input, $section );
508 } elseif ( isset( $opts['replace'] ) ) {
509 $section = $opts['replace'][0];
510 $replace = $opts['replace'][1];
511 $out = $parser->replaceSection( $input, $section, $replace );
512 } elseif ( isset( $opts['comment'] ) ) {
513 $out = Linker
::formatComment( $input, $title, $local );
514 } elseif ( isset( $opts['preload'] ) ) {
515 $out = $parser->getpreloadText( $input, $title, $options );
517 $output = $parser->parse( $input, $title, $options, true, true, 1337 );
518 $out = $output->getText();
520 if ( isset( $opts['showtitle'] ) ) {
521 if ( $output->getTitleText() ) {
522 $title = $output->getTitleText();
525 $out = "$title\n$out";
528 if ( isset( $opts['ill'] ) ) {
529 $out = $this->tidy( implode( ' ', $output->getLanguageLinks() ) );
530 } elseif ( isset( $opts['cat'] ) ) {
531 $outputPage = $context->getOutput();
532 $outputPage->addCategoryLinks( $output->getCategories() );
533 $cats = $outputPage->getCategoryLinks();
535 if ( isset( $cats['normal'] ) ) {
536 $out = $this->tidy( implode( ' ', $cats['normal'] ) );
541 $parser->mPreprocessor
= null;
543 $result = $this->tidy( $result );
546 $this->teardownGlobals();
548 $this->assertEquals( $result, $out, $desc );
552 * Run a fuzz test series
553 * Draw input from a set of test files
555 * @todo @fixme Needs some work to not eat memory until the world explodes
559 function testFuzzTests() {
560 global $wgParserTestFiles;
562 $files = $wgParserTestFiles;
564 if( $this->getCliArg( 'file=' ) ) {
565 $files = array( $this->getCliArg( 'file=' ) );
568 $dict = $this->getFuzzInput( $files );
569 $dictSize = strlen( $dict );
570 $logMaxLength = log( $this->maxFuzzTestLength
);
572 ini_set( 'memory_limit', $this->memoryLimit
* 1048576 );
575 $opts = ParserOptions
::newFromUser( $user );
576 $title = Title
::makeTitle( NS_MAIN
, 'Parser_test' );
582 // Generate test input
583 mt_srand( ++
$this->fuzzSeed
);
584 $totalLength = mt_rand( 1, $this->maxFuzzTestLength
);
587 while ( strlen( $input ) < $totalLength ) {
588 $logHairLength = mt_rand( 0, 1000000 ) / 1000000 * $logMaxLength;
589 $hairLength = min( intval( exp( $logHairLength ) ), $dictSize );
590 $offset = mt_rand( 0, $dictSize - $hairLength );
591 $input .= substr( $dict, $offset, $hairLength );
594 $this->setupGlobals();
595 $parser = $this->getParser();
599 $parser->parse( $input, $title, $opts );
600 $this->assertTrue( true, "Test $id, fuzz seed {$this->fuzzSeed}" );
601 } catch ( Exception
$exception ) {
602 $input_dump = sprintf( "string(%d) \"%s\"\n", strlen( $input ), $input );
604 $this->assertTrue( false, "Test $id, fuzz seed {$this->fuzzSeed}. \n\nInput: $input_dump\n\nError: {$exception->getMessage()}\n\nBacktrace: {$exception->getTraceAsString()}" );
607 $this->teardownGlobals();
608 $parser->__destruct();
610 if ( $id %
100 == 0 ) {
611 $usage = intval( memory_get_usage( true ) / $this->memoryLimit
/ 1048576 * 100 );
612 //echo "{$this->fuzzSeed}: $numSuccess/$numTotal (mem: $usage%)\n";
614 $ret = "Out of memory:\n";
615 $memStats = $this->getMemoryBreakdown();
617 foreach ( $memStats as $name => $usage ) {
618 $ret .= "$name: $usage\n";
621 throw new MWException( $ret );
630 //Various getter functions
633 * Get an input dictionary from a set of parser test files
635 function getFuzzInput( $filenames ) {
638 foreach ( $filenames as $filename ) {
639 $contents = file_get_contents( $filename );
640 preg_match_all( '/!!\s*input\n(.*?)\n!!\s*result/s', $contents, $matches );
642 foreach ( $matches[1] as $match ) {
643 $dict .= $match . "\n";
651 * Get a memory usage breakdown
653 function getMemoryBreakdown() {
656 foreach ( $GLOBALS as $name => $value ) {
657 $memStats['$' . $name] = strlen( serialize( $value ) );
660 $classes = get_declared_classes();
662 foreach ( $classes as $class ) {
663 $rc = new ReflectionClass( $class );
664 $props = $rc->getStaticProperties();
665 $memStats[$class] = strlen( serialize( $props ) );
666 $methods = $rc->getMethods();
668 foreach ( $methods as $method ) {
669 $memStats[$class] +
= strlen( serialize( $method->getStaticVariables() ) );
673 $functions = get_defined_functions();
675 foreach ( $functions['user'] as $function ) {
676 $rf = new ReflectionFunction( $function );
677 $memStats["$function()"] = strlen( serialize( $rf->getStaticVariables() ) );
686 * Get a Parser object
688 function getParser( $preprocessor = null ) {
689 global $wgParserConf;
691 $class = $wgParserConf['class'];
692 $parser = new $class( array( 'preprocessorClass' => $preprocessor ) +
$wgParserConf );
694 wfRunHooks( 'ParserTestParser', array( &$parser ) );
699 //Various action functions
701 public function addArticle( $name, $text, $line ) {
702 self
::$articles[$name] = $text;
705 public function publishTestArticles() {
706 if ( empty( self
::$articles ) ) {
710 foreach ( self
::$articles as $name => $text ) {
711 $title = Title
::newFromText( $name );
713 if ( $title->getArticleID( Title
::GAID_FOR_UPDATE
) == 0 ) {
714 ParserTest
::addArticle( $name, $text );
720 * Steal a callback function from the primary parser, save it for
721 * application to our scary parser. If the hook is not installed,
722 * abort processing of this file.
724 * @param $name String
725 * @return Bool true if tag hook is present
727 public function requireHook( $name ) {
729 $wgParser->firstCallInit( ); // make sure hooks are loaded.
730 return isset( $wgParser->mTagHooks
[$name] );
733 public function requireFunctionHook( $name ) {
735 $wgParser->firstCallInit( ); // make sure hooks are loaded.
736 return isset( $wgParser->mFunctionHooks
[$name] );
738 //Various "cleanup" functions
741 * Run the "tidy" command on text if the $wgUseTidy
744 * @param $text String: the text to tidy
747 protected function tidy( $text ) {
751 $text = MWTidy
::tidy( $text );
758 * Remove last character if it is a newline
760 public function removeEndingNewline( $s ) {
761 if ( substr( $s, -1 ) === "\n" ) {
762 return substr( $s, 0, -1 );
769 public function showRunFile( $file ) {
773 //Test options parser functions
775 protected function parseOptions( $instring ) {
781 // foo=bar,"baz quux"
805 \[\[[^]]*\]\] # Link target
813 if ( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER
) ) {
814 foreach ( $matches as $bits ) {
815 array_shift( $bits );
816 $key = strtolower( array_shift( $bits ) );
817 if ( count( $bits ) == 0 ) {
819 } elseif ( count( $bits ) == 1 ) {
820 $opts[$key] = $this->cleanupOption( array_shift( $bits ) );
823 $opts[$key] = array_map( array( $this, 'cleanupOption' ), $bits );
830 protected function cleanupOption( $opt ) {
831 if ( substr( $opt, 0, 1 ) == '"' ) {
832 return substr( $opt, 1, -1 );
835 if ( substr( $opt, 0, 2 ) == '[[' ) {
836 return substr( $opt, 2, -2 );
842 * Use a regex to find out the value of an option
843 * @param $key String: name of option val to retrieve
844 * @param $opts Options array to look in
845 * @param $default Mixed: default value returned if not found
847 protected static function getOptionValue( $key, $opts, $default ) {
848 $key = strtolower( $key );
850 if ( isset( $opts[$key] ) ) {