6 * @group Stub (can also work independently)
8 class NewParserTest
extends MediaWikiTestCase
{
10 static protected $articles = array(); // Array of test articles defined by the tests
11 /* The dataProvider is run on a different instance than the test, so it must be static
12 * When running tests from several files, all tests will see all articles.
16 public $keepUploads = false;
17 public $runDisabled = false;
19 public $showProgress = true;
20 public $savedInitialGlobals = array();
21 public $savedWeirdGlobals = array();
22 public $savedGlobals = array();
23 public $hooks = array();
24 public $functionHooks = array();
27 public $maxFuzzTestLength = 300;
29 public $memoryLimit = 50;
31 protected $file = false;
33 /*function __construct($a = null,$b = array(),$c = null ) {
34 parent::__construct($a,$b,$c);
38 global $wgContLang, $wgNamespaceProtection, $wgNamespaceAliases;
40 $wgContLang = Language
::factory( 'en' );
43 if ( $this->getCliArg( 'regex=' ) ) {
44 $this->regex
= $this->getCliArg( 'regex=' );
50 $this->keepUploads
= $this->getCliArg( 'keep-uploads' );
52 $tmpGlobals = array();
54 $tmpGlobals['wgScript'] = '/index.php';
55 $tmpGlobals['wgScriptPath'] = '/';
56 $tmpGlobals['wgArticlePath'] = '/wiki/$1';
57 $tmpGlobals['wgStyleSheetPath'] = '/skins';
58 $tmpGlobals['wgStylePath'] = '/skins';
59 $tmpGlobals['wgThumbnailScriptPath'] = false;
60 $tmpGlobals['wgLocalFileRepo'] = array(
61 'class' => 'LocalRepo',
63 'directory' => wfTempDir() . '/test-repo',
64 'url' => 'http://example.com/images',
65 'deletedDir' => wfTempDir() . '/test-repo/delete',
67 'transformVia404' => false,
70 $tmpGlobals['wgEnableParserCache'] = false;
71 $tmpGlobals['wgHooks'] = $wgHooks;
72 $tmpGlobals['wgDeferredUpdateList'] = array();
73 $tmpGlobals['wgMemc'] = wfGetMainCache();
74 $tmpGlobals['messageMemc'] = wfGetMessageCacheStorage();
75 $tmpGlobals['parserMemc'] = wfGetParserCacheStorage();
77 // $tmpGlobals['wgContLang'] = new StubContLang;
78 $tmpGlobals['wgUser'] = new User
;
79 $context = new RequestContext();
80 $tmpGlobals['wgLang'] = $context->lang
;
81 $tmpGlobals['wgOut'] = $context->output
;
82 $tmpGlobals['wgParser'] = new StubObject( 'wgParser', $GLOBALS['wgParserConf']['class'], array( $GLOBALS['wgParserConf'] ) );
83 $tmpGlobals['wgRequest'] = new WebRequest
;
85 if ( $GLOBALS['wgStyleDirectory'] === false ) {
86 $tmpGlobals['wgStyleDirectory'] = "$IP/skins";
90 foreach ( $tmpGlobals as $var => $val ) {
91 if ( array_key_exists( $var, $GLOBALS ) ) {
92 $this->savedInitialGlobals
[$var] = $GLOBALS[$var];
95 $GLOBALS[$var] = $val;
98 $this->savedWeirdGlobals
['mw_namespace_protection'] = $wgNamespaceProtection[NS_MEDIAWIKI
];
99 $this->savedWeirdGlobals
['image_alias'] = $wgNamespaceAliases['Image'];
100 $this->savedWeirdGlobals
['image_talk_alias'] = $wgNamespaceAliases['Image_talk'];
102 $wgNamespaceProtection[NS_MEDIAWIKI
] = 'editinterface';
103 $wgNamespaceAliases['Image'] = NS_FILE
;
104 $wgNamespaceAliases['Image_talk'] = NS_FILE_TALK
;
108 public function tearDown() {
110 foreach ( $this->savedInitialGlobals
as $var => $val ) {
111 $GLOBALS[$var] = $val;
114 global $wgNamespaceProtection, $wgNamespaceAliases;
116 $wgNamespaceProtection[NS_MEDIAWIKI
] = $this->savedWeirdGlobals
['mw_namespace_protection'];
117 $wgNamespaceAliases['Image'] = $this->savedWeirdGlobals
['image_alias'];
118 $wgNamespaceAliases['Image_talk'] = $this->savedWeirdGlobals
['image_talk_alias'];
121 function addDBData() {
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 ),
167 * @todo Fixme! Same as above!
172 # Reinitialise the LocalisationCache to match the database state
173 Language
::getLocalisationCache()->unloadAll();
175 # Clear the message cache
176 MessageCache
::singleton()->clear();
178 $this->uploadDir
= $this->setupUploadDir();
180 $user = User
::newFromId( 0 );
181 LinkCache
::singleton()->clear(); # Avoids the odd failure at creating the nullRevision
183 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Foobar.jpg' ) );
184 $image->recordUpload2( '', 'Upload of some lame file', 'Some lame file', array(
189 'media_type' => MEDIATYPE_BITMAP
,
190 'mime' => 'image/jpeg',
191 'metadata' => serialize( array() ),
192 'sha1' => wfBaseConvert( '', 16, 36, 31 ),
194 ), $this->db
->timestamp( '20010115123500' ), $user );
196 # This image will be blacklisted in [[MediaWiki:Bad image list]]
197 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Bad.jpg' ) );
198 $image->recordUpload2( '', 'zomgnotcensored', 'Borderline image', array(
203 'media_type' => MEDIATYPE_BITMAP
,
204 'mime' => 'image/jpeg',
205 'metadata' => serialize( array() ),
206 'sha1' => wfBaseConvert( '', 16, 36, 31 ),
208 ), $this->db
->timestamp( '20010115123500' ), $user );
215 //ParserTest setup/teardown functions
218 * Set up the global variables for a consistent environment for each test.
219 * Ideally this should replace the global configuration entirely.
221 protected function setupGlobals( $opts = '', $config = '' ) {
222 # Find out values for some special options.
224 self
::getOptionValue( 'language', $opts, 'en' );
226 self
::getOptionValue( 'variant', $opts, false );
228 self
::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
229 $linkHolderBatchSize =
230 self
::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
233 'wgServer' => 'http://Britney-Spears',
234 'wgScript' => '/index.php',
235 'wgScriptPath' => '/',
236 'wgArticlePath' => '/wiki/$1',
237 'wgActionPaths' => array(),
238 'wgLocalFileRepo' => array(
239 'class' => 'LocalRepo',
241 'directory' => $this->uploadDir
,
242 'url' => 'http://example.com/images',
244 'transformVia404' => false,
246 'wgEnableUploads' => self
::getOptionValue( 'wgEnableUploads', $opts, true ),
247 'wgStylePath' => '/skins',
248 'wgStyleSheetPath' => '/skins',
249 'wgSitename' => 'MediaWiki',
250 'wgLanguageCode' => $lang,
251 'wgDBprefix' => $this->db
->getType() != 'oracle' ?
'unittest_' : 'ut_',
252 'wgRawHtml' => isset( $opts['rawhtml'] ),
254 'wgContLang' => null,
255 'wgNamespacesWithSubpages' => array( 0 => isset( $opts['subpage'] ) ),
256 'wgMaxTocLevel' => $maxtoclevel,
257 'wgCapitalLinks' => true,
258 'wgNoFollowLinks' => true,
259 'wgNoFollowDomainExceptions' => array(),
260 'wgThumbnailScriptPath' => false,
261 'wgUseImageResize' => false,
262 'wgUseTeX' => isset( $opts['math'] ),
263 'wgMathDirectory' => $this->uploadDir
. '/math',
264 'wgLocaltimezone' => 'UTC',
265 'wgAllowExternalImages' => true,
266 'wgUseTidy' => false,
267 'wgDefaultLanguageVariant' => $variant,
268 'wgVariantArticlePath' => false,
269 'wgGroupPermissions' => array( '*' => array(
270 'createaccount' => true,
273 'createpage' => true,
274 'createtalk' => true,
276 'wgNamespaceProtection' => array( NS_MEDIAWIKI
=> 'editinterface' ),
277 'wgDefaultExternalStore' => array(),
278 'wgForeignFileRepos' => array(),
279 'wgLinkHolderBatchSize' => $linkHolderBatchSize,
280 'wgExperimentalHtmlIds' => false,
281 'wgExternalLinkTarget' => false,
282 'wgAlwaysUseTidy' => false,
284 'wgWellFormedXml' => true,
285 'wgAllowMicrodataAttributes' => true,
286 'wgAdaptiveMessageCache' => true,
287 'wgUseDatabaseMessages' => true,
291 $configLines = explode( "\n", $config );
293 foreach ( $configLines as $line ) {
294 list( $var, $value ) = explode( '=', $line, 2 );
296 $settings[$var] = eval( "return $value;" ); //???
300 $this->savedGlobals
= array();
302 foreach ( $settings as $var => $val ) {
303 if ( array_key_exists( $var, $GLOBALS ) ) {
304 $this->savedGlobals
[$var] = $GLOBALS[$var];
307 $GLOBALS[$var] = $val;
310 $langObj = Language
::factory( $lang );
311 $GLOBALS['wgContLang'] = $langObj;
312 $context = new RequestContext();
313 $GLOBALS['wgLang'] = $context->lang
;
315 $GLOBALS['wgMemc'] = new EmptyBagOStuff
;
316 $GLOBALS['wgOut'] = $context->output
;
320 $wgHooks['ParserTestParser'][] = 'ParserTestParserHook::setup';
321 $wgHooks['ParserTestParser'][] = 'ParserTestStaticParserHook::setup';
322 $wgHooks['ParserGetVariableValueTs'][] = 'ParserTest::getFakeTimestamp';
324 MagicWord
::clearCache();
326 # Publish the articles after we have the final language set
327 $this->publishTestArticles();
329 # The entries saved into RepoGroup cache with previous globals will be wrong.
330 RepoGroup
::destroySingleton();
331 MessageCache
::singleton()->destroyInstance();
334 $wgUser = new User();
338 * Restore default values and perform any necessary clean-up
339 * after each test runs.
341 protected function teardownGlobals() {
342 RepoGroup
::destroySingleton();
343 LinkCache
::singleton()->clear();
345 foreach ( $this->savedGlobals
as $var => $val ) {
346 $GLOBALS[$var] = $val;
351 * Create a dummy uploads directory which will contain a couple
352 * of files in order to pass existence tests.
354 * @return String: the directory
356 protected function setupUploadDir() {
359 if ( $this->keepUploads
) {
360 $dir = wfTempDir() . '/mwParser-images';
362 if ( is_dir( $dir ) ) {
366 $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
369 // wfDebug( "Creating upload directory $dir\n" );
370 if ( file_exists( $dir ) ) {
371 wfDebug( "Already exists!\n" );
375 wfMkdirParents( $dir . '/3/3a' );
376 copy( "$IP/skins/monobook/headbg.jpg", "$dir/3/3a/Foobar.jpg" );
377 wfMkdirParents( $dir . '/0/09' );
378 copy( "$IP/skins/monobook/headbg.jpg", "$dir/0/09/Bad.jpg" );
383 public function parserTestProvider() {
384 if ( $this->file
=== false ) {
385 global $wgParserTestFiles;
386 $this->file
= $wgParserTestFiles[0];
388 return new TestFileIterator( $this->file
, $this );
392 * Set the file from whose tests will be run by this instance
394 public function setParserTestFile( $filename ) {
395 $this->file
= $filename;
398 /** @dataProvider parserTestProvider */
399 public function testParserTest( $desc, $input, $result, $opts, $config ) {
400 if ( !preg_match( '/' . $this->regex
. '/', $desc ) ) return; //$this->markTestSkipped( 'Filtered out by the user' );
402 wfDebug( "Running parser test: $desc\n" );
404 $opts = $this->parseOptions( $opts );
405 $this->setupGlobals( $opts, $config );
408 $options = ParserOptions
::newFromUser( $user );
410 if ( isset( $opts['title'] ) ) {
411 $titleText = $opts['title'];
414 $titleText = 'Parser test';
417 $local = isset( $opts['local'] );
418 $preprocessor = isset( $opts['preprocessor'] ) ?
$opts['preprocessor'] : null;
419 $parser = $this->getParser( $preprocessor );
421 $title = Title
::newFromText( $titleText );
423 if ( isset( $opts['pst'] ) ) {
424 $out = $parser->preSaveTransform( $input, $title, $user, $options );
425 } elseif ( isset( $opts['msg'] ) ) {
426 $out = $parser->transformMsg( $input, $options );
427 } elseif ( isset( $opts['section'] ) ) {
428 $section = $opts['section'];
429 $out = $parser->getSection( $input, $section );
430 } elseif ( isset( $opts['replace'] ) ) {
431 $section = $opts['replace'][0];
432 $replace = $opts['replace'][1];
433 $out = $parser->replaceSection( $input, $section, $replace );
434 } elseif ( isset( $opts['comment'] ) ) {
435 $linker = $user->getSkin();
436 $out = $linker->formatComment( $input, $title, $local );
437 } elseif ( isset( $opts['preload'] ) ) {
438 $out = $parser->getpreloadText( $input, $title, $options );
440 $output = $parser->parse( $input, $title, $options, true, true, 1337 );
441 $out = $output->getText();
443 if ( isset( $opts['showtitle'] ) ) {
444 if ( $output->getTitleText() ) {
445 $title = $output->getTitleText();
448 $out = "$title\n$out";
451 if ( isset( $opts['ill'] ) ) {
452 $out = $this->tidy( implode( ' ', $output->getLanguageLinks() ) );
453 } elseif ( isset( $opts['cat'] ) ) {
456 $wgOut->addCategoryLinks( $output->getCategories() );
457 $cats = $wgOut->getCategoryLinks();
459 if ( isset( $cats['normal'] ) ) {
460 $out = $this->tidy( implode( ' ', $cats['normal'] ) );
465 $parser->mPreprocessor
= null;
467 $result = $this->tidy( $result );
470 $this->teardownGlobals();
472 $this->assertEquals( $result, $out, $desc );
476 * Run a fuzz test series
477 * Draw input from a set of test files
479 function testFuzzTests() {
481 $this->markTestIncomplete( 'Breaks tesla due to memory restrictions' );
483 global $wgParserTestFiles;
485 $files = $wgParserTestFiles;
487 if( $this->getCliArg( 'file=' ) ) {
488 $files = array( $this->getCliArg( 'file=' ) );
491 $dict = $this->getFuzzInput( $files );
492 $dictSize = strlen( $dict );
493 $logMaxLength = log( $this->maxFuzzTestLength
);
495 ini_set( 'memory_limit', $this->memoryLimit
* 1048576 );
498 $opts = ParserOptions
::newFromUser( $user );
499 $title = Title
::makeTitle( NS_MAIN
, 'Parser_test' );
505 // Generate test input
506 mt_srand( ++
$this->fuzzSeed
);
507 $totalLength = mt_rand( 1, $this->maxFuzzTestLength
);
510 while ( strlen( $input ) < $totalLength ) {
511 $logHairLength = mt_rand( 0, 1000000 ) / 1000000 * $logMaxLength;
512 $hairLength = min( intval( exp( $logHairLength ) ), $dictSize );
513 $offset = mt_rand( 0, $dictSize - $hairLength );
514 $input .= substr( $dict, $offset, $hairLength );
517 $this->setupGlobals();
518 $parser = $this->getParser();
522 $parser->parse( $input, $title, $opts );
523 $this->assertTrue( true, "Test $id, fuzz seed {$this->fuzzSeed}" );
524 } catch ( Exception
$exception ) {
525 $input_dump = sprintf( "string(%d) \"%s\"\n", strlen( $input ), $input );
527 $this->assertTrue( false, "Test $id, fuzz seed {$this->fuzzSeed}. \n\nInput: $input_dump\n\nError: {$exception->getMessage()}\n\nBacktrace: {$exception->getTraceAsString()}" );
530 $this->teardownGlobals();
531 $parser->__destruct();
533 if ( $id %
100 == 0 ) {
534 $usage = intval( memory_get_usage( true ) / $this->memoryLimit
/ 1048576 * 100 );
535 //echo "{$this->fuzzSeed}: $numSuccess/$numTotal (mem: $usage%)\n";
537 $ret = "Out of memory:\n";
538 $memStats = $this->getMemoryBreakdown();
540 foreach ( $memStats as $name => $usage ) {
541 $ret .= "$name: $usage\n";
544 throw new MWException( $ret );
553 //Various getter functions
556 * Get an input dictionary from a set of parser test files
558 function getFuzzInput( $filenames ) {
561 foreach ( $filenames as $filename ) {
562 $contents = file_get_contents( $filename );
563 preg_match_all( '/!!\s*input\n(.*?)\n!!\s*result/s', $contents, $matches );
565 foreach ( $matches[1] as $match ) {
566 $dict .= $match . "\n";
574 * Get a memory usage breakdown
576 function getMemoryBreakdown() {
579 foreach ( $GLOBALS as $name => $value ) {
580 $memStats['$' . $name] = strlen( serialize( $value ) );
583 $classes = get_declared_classes();
585 foreach ( $classes as $class ) {
586 $rc = new ReflectionClass( $class );
587 $props = $rc->getStaticProperties();
588 $memStats[$class] = strlen( serialize( $props ) );
589 $methods = $rc->getMethods();
591 foreach ( $methods as $method ) {
592 $memStats[$class] +
= strlen( serialize( $method->getStaticVariables() ) );
596 $functions = get_defined_functions();
598 foreach ( $functions['user'] as $function ) {
599 $rf = new ReflectionFunction( $function );
600 $memStats["$function()"] = strlen( serialize( $rf->getStaticVariables() ) );
609 * Get a Parser object
611 function getParser( $preprocessor = null ) {
612 global $wgParserConf;
614 $class = $wgParserConf['class'];
615 $parser = new $class( array( 'preprocessorClass' => $preprocessor ) +
$wgParserConf );
617 wfRunHooks( 'ParserTestParser', array( &$parser ) );
622 //Various action functions
624 public function addArticle( $name, $text, $line ) {
625 self
::$articles[$name] = $text;
628 public function publishTestArticles() {
629 if ( empty( self
::$articles ) ) {
633 foreach ( self
::$articles as $name => $text ) {
634 $title = Title
::newFromText( $name );
636 if ( $title->getArticleID( Title
::GAID_FOR_UPDATE
) == 0 ) {
637 ParserTest
::addArticle( $name, $text );
643 * Steal a callback function from the primary parser, save it for
644 * application to our scary parser. If the hook is not installed,
645 * abort processing of this file.
647 * @param $name String
648 * @return Bool true if tag hook is present
650 public function requireHook( $name ) {
652 $wgParser->firstCallInit( ); // make sure hooks are loaded.
653 return isset( $wgParser->mTagHooks
[$name] );
656 public function requireFunctionHook( $name ) {
658 $wgParser->firstCallInit( ); // make sure hooks are loaded.
659 return isset( $wgParser->mFunctionHooks
[$name] );
661 //Various "cleanup" functions
664 * Run the "tidy" command on text if the $wgUseTidy
667 * @param $text String: the text to tidy
671 protected function tidy( $text ) {
675 $text = MWTidy
::tidy( $text );
682 * Remove last character if it is a newline
684 public function removeEndingNewline( $s ) {
685 if ( substr( $s, -1 ) === "\n" ) {
686 return substr( $s, 0, -1 );
693 public function showRunFile( $file ) {
697 //Test options parser functions
699 protected function parseOptions( $instring ) {
705 // foo=bar,"baz quux"
729 \[\[[^]]*\]\] # Link target
737 if ( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER
) ) {
738 foreach ( $matches as $bits ) {
739 array_shift( $bits );
740 $key = strtolower( array_shift( $bits ) );
741 if ( count( $bits ) == 0 ) {
743 } elseif ( count( $bits ) == 1 ) {
744 $opts[$key] = $this->cleanupOption( array_shift( $bits ) );
747 $opts[$key] = array_map( array( $this, 'cleanupOption' ), $bits );
754 protected function cleanupOption( $opt ) {
755 if ( substr( $opt, 0, 1 ) == '"' ) {
756 return substr( $opt, 1, -1 );
759 if ( substr( $opt, 0, 2 ) == '[[' ) {
760 return substr( $opt, 2, -2 );
766 * Use a regex to find out the value of an option
767 * @param $key String: name of option val to retrieve
768 * @param $opts Options array to look in
769 * @param $default Mixed: default value returned if not found
771 protected static function getOptionValue( $key, $opts, $default ) {
772 $key = strtolower( $key );
774 if ( isset( $opts[$key] ) ) {