050071151f3cd5c289915260970b36948c5bee50
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;
35 /*function __construct($a = null,$b = array(),$c = null ) {
36 parent::__construct($a,$b,$c);
40 global $wgContLang, $wgNamespaceProtection, $wgNamespaceAliases;
42 $wgContLang = Language
::factory( 'en' );
45 if ( $this->getCliArg( 'regex=' ) ) {
46 $this->regex
= $this->getCliArg( 'regex=' );
52 $this->keepUploads
= $this->getCliArg( 'keep-uploads' );
54 $tmpGlobals = array();
56 $tmpGlobals['wgScript'] = '/index.php';
57 $tmpGlobals['wgScriptPath'] = '/';
58 $tmpGlobals['wgArticlePath'] = '/wiki/$1';
59 $tmpGlobals['wgStyleSheetPath'] = '/skins';
60 $tmpGlobals['wgStylePath'] = '/skins';
61 $tmpGlobals['wgThumbnailScriptPath'] = false;
62 $tmpGlobals['wgLocalFileRepo'] = array(
63 'class' => 'LocalRepo',
65 'directory' => wfTempDir() . '/test-repo',
66 'url' => 'http://example.com/images',
67 'deletedDir' => wfTempDir() . '/test-repo/delete',
69 'transformVia404' => false,
72 $tmpGlobals['wgEnableParserCache'] = false;
73 $tmpGlobals['wgHooks'] = $wgHooks;
74 $tmpGlobals['wgDeferredUpdateList'] = array();
75 $tmpGlobals['wgMemc'] = wfGetMainCache();
76 $tmpGlobals['messageMemc'] = wfGetMessageCacheStorage();
77 $tmpGlobals['parserMemc'] = wfGetParserCacheStorage();
79 // $tmpGlobals['wgContLang'] = new StubContLang;
80 $tmpGlobals['wgUser'] = new User
;
81 $context = new RequestContext();
82 $tmpGlobals['wgLang'] = $context->getLang();
83 $tmpGlobals['wgOut'] = $context->getOutput();
84 $tmpGlobals['wgParser'] = new StubObject( 'wgParser', $GLOBALS['wgParserConf']['class'], array( $GLOBALS['wgParserConf'] ) );
85 $tmpGlobals['wgRequest'] = $context->getRequest();
87 if ( $GLOBALS['wgStyleDirectory'] === false ) {
88 $tmpGlobals['wgStyleDirectory'] = "$IP/skins";
92 foreach ( $tmpGlobals as $var => $val ) {
93 if ( array_key_exists( $var, $GLOBALS ) ) {
94 $this->savedInitialGlobals
[$var] = $GLOBALS[$var];
97 $GLOBALS[$var] = $val;
100 $this->savedWeirdGlobals
['mw_namespace_protection'] = $wgNamespaceProtection[NS_MEDIAWIKI
];
101 $this->savedWeirdGlobals
['image_alias'] = $wgNamespaceAliases['Image'];
102 $this->savedWeirdGlobals
['image_talk_alias'] = $wgNamespaceAliases['Image_talk'];
104 $wgNamespaceProtection[NS_MEDIAWIKI
] = 'editinterface';
105 $wgNamespaceAliases['Image'] = NS_FILE
;
106 $wgNamespaceAliases['Image_talk'] = NS_FILE_TALK
;
110 public function tearDown() {
112 foreach ( $this->savedInitialGlobals
as $var => $val ) {
113 $GLOBALS[$var] = $val;
116 global $wgNamespaceProtection, $wgNamespaceAliases;
118 $wgNamespaceProtection[NS_MEDIAWIKI
] = $this->savedWeirdGlobals
['mw_namespace_protection'];
119 $wgNamespaceAliases['Image'] = $this->savedWeirdGlobals
['image_alias'];
120 $wgNamespaceAliases['Image_talk'] = $this->savedWeirdGlobals
['image_talk_alias'];
123 function addDBData() {
124 # Hack: insert a few Wikipedia in-project interwiki prefixes,
125 # for testing inter-language links
126 $this->db
->insert( 'interwiki', array(
127 array( 'iw_prefix' => 'wikipedia',
128 'iw_url' => 'http://en.wikipedia.org/wiki/$1',
132 array( 'iw_prefix' => 'meatball',
133 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
137 array( 'iw_prefix' => 'zh',
138 'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
142 array( 'iw_prefix' => 'es',
143 'iw_url' => 'http://es.wikipedia.org/wiki/$1',
147 array( 'iw_prefix' => 'fr',
148 'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
152 array( 'iw_prefix' => 'ru',
153 'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
158 * @todo Fixme! Why are we inserting duplicate data here? Shouldn't
159 * need this IGNORE or shouldn't need the insert at all.
161 ), __METHOD__
, array( 'IGNORE' ) );
164 # Update certain things in site_stats
165 $this->db
->insert( 'site_stats',
166 array( 'ss_row_id' => 1, 'ss_images' => 2, 'ss_good_articles' => 1 ),
167 __METHOD__
, array( 'IGNORE' ) );
169 # Reinitialise the LocalisationCache to match the database state
170 Language
::getLocalisationCache()->unloadAll();
172 # Clear the message cache
173 MessageCache
::singleton()->clear();
175 $this->uploadDir
= $this->setupUploadDir();
177 $user = User
::newFromId( 0 );
178 LinkCache
::singleton()->clear(); # Avoids the odd failure at creating the nullRevision
180 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Foobar.jpg' ) );
181 $image->recordUpload2( '', 'Upload of some lame file', 'Some lame file', array(
186 'media_type' => MEDIATYPE_BITMAP
,
187 'mime' => 'image/jpeg',
188 'metadata' => serialize( array() ),
189 'sha1' => wfBaseConvert( '', 16, 36, 31 ),
191 ), $this->db
->timestamp( '20010115123500' ), $user );
193 # This image will be blacklisted in [[MediaWiki:Bad image list]]
194 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Bad.jpg' ) );
195 $image->recordUpload2( '', 'zomgnotcensored', 'Borderline image', array(
200 'media_type' => MEDIATYPE_BITMAP
,
201 'mime' => 'image/jpeg',
202 'metadata' => serialize( array() ),
203 'sha1' => wfBaseConvert( '', 16, 36, 31 ),
205 ), $this->db
->timestamp( '20010115123500' ), $user );
212 //ParserTest setup/teardown functions
215 * Set up the global variables for a consistent environment for each test.
216 * Ideally this should replace the global configuration entirely.
218 protected function setupGlobals( $opts = '', $config = '' ) {
219 # Find out values for some special options.
221 self
::getOptionValue( 'language', $opts, 'en' );
223 self
::getOptionValue( 'variant', $opts, false );
225 self
::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
226 $linkHolderBatchSize =
227 self
::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
230 'wgServer' => 'http://Britney-Spears',
231 'wgScript' => '/index.php',
232 'wgScriptPath' => '/',
233 'wgArticlePath' => '/wiki/$1',
234 'wgExtensionAssetsPath' => '/extensions',
235 'wgActionPaths' => array(),
236 'wgLocalFileRepo' => array(
237 'class' => 'LocalRepo',
239 'directory' => $this->uploadDir
,
240 'url' => 'http://example.com/images',
242 'transformVia404' => false,
244 'wgEnableUploads' => self
::getOptionValue( 'wgEnableUploads', $opts, true ),
245 'wgStylePath' => '/skins',
246 'wgStyleSheetPath' => '/skins',
247 'wgSitename' => 'MediaWiki',
248 'wgLanguageCode' => $lang,
249 'wgDBprefix' => $this->db
->getType() != 'oracle' ?
'unittest_' : 'ut_',
250 'wgRawHtml' => isset( $opts['rawhtml'] ),
252 'wgContLang' => null,
253 'wgNamespacesWithSubpages' => array( 0 => isset( $opts['subpage'] ) ),
254 'wgMaxTocLevel' => $maxtoclevel,
255 'wgCapitalLinks' => true,
256 'wgNoFollowLinks' => true,
257 'wgNoFollowDomainExceptions' => array(),
258 'wgThumbnailScriptPath' => false,
259 'wgUseImageResize' => false,
260 'wgUseTeX' => isset( $opts['math'] ),
261 'wgMathDirectory' => $this->uploadDir
. '/math',
262 'wgLocaltimezone' => 'UTC',
263 'wgAllowExternalImages' => true,
264 'wgUseTidy' => false,
265 'wgDefaultLanguageVariant' => $variant,
266 'wgVariantArticlePath' => false,
267 'wgGroupPermissions' => array( '*' => array(
268 'createaccount' => true,
271 'createpage' => true,
272 'createtalk' => true,
274 'wgNamespaceProtection' => array( NS_MEDIAWIKI
=> 'editinterface' ),
275 'wgDefaultExternalStore' => array(),
276 'wgForeignFileRepos' => array(),
277 'wgLinkHolderBatchSize' => $linkHolderBatchSize,
278 'wgExperimentalHtmlIds' => false,
279 'wgExternalLinkTarget' => false,
280 'wgAlwaysUseTidy' => false,
282 'wgCleanupPresentationalAttributes' => true,
283 'wgWellFormedXml' => true,
284 'wgAllowMicrodataAttributes' => true,
285 'wgAdaptiveMessageCache' => true,
286 'wgUseDatabaseMessages' => true,
290 $configLines = explode( "\n", $config );
292 foreach ( $configLines as $line ) {
293 list( $var, $value ) = explode( '=', $line, 2 );
295 $settings[$var] = eval( "return $value;" ); //???
299 $this->savedGlobals
= array();
301 foreach ( $settings as $var => $val ) {
302 if ( array_key_exists( $var, $GLOBALS ) ) {
303 $this->savedGlobals
[$var] = $GLOBALS[$var];
306 $GLOBALS[$var] = $val;
309 $langObj = Language
::factory( $lang );
310 $GLOBALS['wgContLang'] = $langObj;
311 $context = new RequestContext();
312 $GLOBALS['wgLang'] = $context->getLang();
314 $GLOBALS['wgMemc'] = new EmptyBagOStuff
;
315 $GLOBALS['wgOut'] = $context->getOutput();
319 $wgHooks['ParserTestParser'][] = 'ParserTestParserHook::setup';
320 $wgHooks['ParserGetVariableValueTs'][] = 'ParserTest::getFakeTimestamp';
322 MagicWord
::clearCache();
324 # Publish the articles after we have the final language set
325 $this->publishTestArticles();
327 # The entries saved into RepoGroup cache with previous globals will be wrong.
328 RepoGroup
::destroySingleton();
329 MessageCache
::singleton()->destroyInstance();
332 $wgUser = new User();
336 * Create a dummy uploads directory which will contain a couple
337 * of files in order to pass existence tests.
339 * @return String: the directory
341 protected function setupUploadDir() {
344 if ( $this->keepUploads
) {
345 $dir = wfTempDir() . '/mwParser-images';
347 if ( is_dir( $dir ) ) {
351 $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
354 // wfDebug( "Creating upload directory $dir\n" );
355 if ( file_exists( $dir ) ) {
356 wfDebug( "Already exists!\n" );
360 wfMkdirParents( $dir . '/3/3a', null, __METHOD__
);
361 copy( "$IP/skins/monobook/headbg.jpg", "$dir/3/3a/Foobar.jpg" );
362 wfMkdirParents( $dir . '/0/09', null, __METHOD__
);
363 copy( "$IP/skins/monobook/headbg.jpg", "$dir/0/09/Bad.jpg" );
369 * Restore default values and perform any necessary clean-up
370 * after each test runs.
372 protected function teardownGlobals() {
373 RepoGroup
::destroySingleton();
374 LinkCache
::singleton()->clear();
376 foreach ( $this->savedGlobals
as $var => $val ) {
377 $GLOBALS[$var] = $val;
380 $this->teardownUploadDir( $this->uploadDir
);
384 * Remove the dummy uploads directory
386 private function teardownUploadDir( $dir ) {
387 if ( $this->keepUploads
) {
391 // delete the files first, then the dirs.
394 "$dir/3/3a/Foobar.jpg",
395 "$dir/thumb/3/3a/Foobar.jpg/180px-Foobar.jpg",
396 "$dir/thumb/3/3a/Foobar.jpg/200px-Foobar.jpg",
397 "$dir/thumb/3/3a/Foobar.jpg/640px-Foobar.jpg",
398 "$dir/thumb/3/3a/Foobar.jpg/120px-Foobar.jpg",
402 "$dir/math/f/a/5/fa50b8b616463173474302ca3e63586b.png",
412 "$dir/thumb/3/3a/Foobar.jpg",
429 * Delete the specified files, if they exist.
430 * @param $files Array: full paths to files to delete.
432 private static function deleteFiles( $files ) {
433 foreach ( $files as $file ) {
434 if ( file_exists( $file ) ) {
441 * Delete the specified directories, if they exist. Must be empty.
442 * @param $dirs Array: full paths to directories to delete.
444 private static function deleteDirs( $dirs ) {
445 foreach ( $dirs as $dir ) {
446 if ( is_dir( $dir ) ) {
452 public function parserTestProvider() {
453 if ( $this->file
=== false ) {
454 global $wgParserTestFiles;
455 $this->file
= $wgParserTestFiles[0];
457 return new TestFileIterator( $this->file
, $this );
461 * Set the file from whose tests will be run by this instance
463 public function setParserTestFile( $filename ) {
464 $this->file
= $filename;
467 /** @dataProvider parserTestProvider */
468 public function testParserTest( $desc, $input, $result, $opts, $config ) {
469 if ( !preg_match( '/' . $this->regex
. '/', $desc ) ) return; //$this->markTestSkipped( 'Filtered out by the user' );
471 wfDebug( "Running parser test: $desc\n" );
473 $opts = $this->parseOptions( $opts );
474 $this->setupGlobals( $opts, $config );
477 $options = ParserOptions
::newFromUser( $user );
479 if ( isset( $opts['title'] ) ) {
480 $titleText = $opts['title'];
483 $titleText = 'Parser test';
486 $local = isset( $opts['local'] );
487 $preprocessor = isset( $opts['preprocessor'] ) ?
$opts['preprocessor'] : null;
488 $parser = $this->getParser( $preprocessor );
490 $title = Title
::newFromText( $titleText );
492 if ( isset( $opts['pst'] ) ) {
493 $out = $parser->preSaveTransform( $input, $title, $user, $options );
494 } elseif ( isset( $opts['msg'] ) ) {
495 $out = $parser->transformMsg( $input, $options, $title );
496 } elseif ( isset( $opts['section'] ) ) {
497 $section = $opts['section'];
498 $out = $parser->getSection( $input, $section );
499 } elseif ( isset( $opts['replace'] ) ) {
500 $section = $opts['replace'][0];
501 $replace = $opts['replace'][1];
502 $out = $parser->replaceSection( $input, $section, $replace );
503 } elseif ( isset( $opts['comment'] ) ) {
504 $out = Linker
::formatComment( $input, $title, $local );
505 } elseif ( isset( $opts['preload'] ) ) {
506 $out = $parser->getpreloadText( $input, $title, $options );
508 $output = $parser->parse( $input, $title, $options, true, true, 1337 );
509 $out = $output->getText();
511 if ( isset( $opts['showtitle'] ) ) {
512 if ( $output->getTitleText() ) {
513 $title = $output->getTitleText();
516 $out = "$title\n$out";
519 if ( isset( $opts['ill'] ) ) {
520 $out = $this->tidy( implode( ' ', $output->getLanguageLinks() ) );
521 } elseif ( isset( $opts['cat'] ) ) {
524 $wgOut->addCategoryLinks( $output->getCategories() );
525 $cats = $wgOut->getCategoryLinks();
527 if ( isset( $cats['normal'] ) ) {
528 $out = $this->tidy( implode( ' ', $cats['normal'] ) );
533 $parser->mPreprocessor
= null;
535 $result = $this->tidy( $result );
538 $this->teardownGlobals();
540 $this->assertEquals( $result, $out, $desc );
544 * Run a fuzz test series
545 * Draw input from a set of test files
547 * @todo @fixme Needs some work to not eat memory until the world explodes
551 function testFuzzTests() {
552 global $wgParserTestFiles;
554 $files = $wgParserTestFiles;
556 if( $this->getCliArg( 'file=' ) ) {
557 $files = array( $this->getCliArg( 'file=' ) );
560 $dict = $this->getFuzzInput( $files );
561 $dictSize = strlen( $dict );
562 $logMaxLength = log( $this->maxFuzzTestLength
);
564 ini_set( 'memory_limit', $this->memoryLimit
* 1048576 );
567 $opts = ParserOptions
::newFromUser( $user );
568 $title = Title
::makeTitle( NS_MAIN
, 'Parser_test' );
574 // Generate test input
575 mt_srand( ++
$this->fuzzSeed
);
576 $totalLength = mt_rand( 1, $this->maxFuzzTestLength
);
579 while ( strlen( $input ) < $totalLength ) {
580 $logHairLength = mt_rand( 0, 1000000 ) / 1000000 * $logMaxLength;
581 $hairLength = min( intval( exp( $logHairLength ) ), $dictSize );
582 $offset = mt_rand( 0, $dictSize - $hairLength );
583 $input .= substr( $dict, $offset, $hairLength );
586 $this->setupGlobals();
587 $parser = $this->getParser();
591 $parser->parse( $input, $title, $opts );
592 $this->assertTrue( true, "Test $id, fuzz seed {$this->fuzzSeed}" );
593 } catch ( Exception
$exception ) {
594 $input_dump = sprintf( "string(%d) \"%s\"\n", strlen( $input ), $input );
596 $this->assertTrue( false, "Test $id, fuzz seed {$this->fuzzSeed}. \n\nInput: $input_dump\n\nError: {$exception->getMessage()}\n\nBacktrace: {$exception->getTraceAsString()}" );
599 $this->teardownGlobals();
600 $parser->__destruct();
602 if ( $id %
100 == 0 ) {
603 $usage = intval( memory_get_usage( true ) / $this->memoryLimit
/ 1048576 * 100 );
604 //echo "{$this->fuzzSeed}: $numSuccess/$numTotal (mem: $usage%)\n";
606 $ret = "Out of memory:\n";
607 $memStats = $this->getMemoryBreakdown();
609 foreach ( $memStats as $name => $usage ) {
610 $ret .= "$name: $usage\n";
613 throw new MWException( $ret );
622 //Various getter functions
625 * Get an input dictionary from a set of parser test files
627 function getFuzzInput( $filenames ) {
630 foreach ( $filenames as $filename ) {
631 $contents = file_get_contents( $filename );
632 preg_match_all( '/!!\s*input\n(.*?)\n!!\s*result/s', $contents, $matches );
634 foreach ( $matches[1] as $match ) {
635 $dict .= $match . "\n";
643 * Get a memory usage breakdown
645 function getMemoryBreakdown() {
648 foreach ( $GLOBALS as $name => $value ) {
649 $memStats['$' . $name] = strlen( serialize( $value ) );
652 $classes = get_declared_classes();
654 foreach ( $classes as $class ) {
655 $rc = new ReflectionClass( $class );
656 $props = $rc->getStaticProperties();
657 $memStats[$class] = strlen( serialize( $props ) );
658 $methods = $rc->getMethods();
660 foreach ( $methods as $method ) {
661 $memStats[$class] +
= strlen( serialize( $method->getStaticVariables() ) );
665 $functions = get_defined_functions();
667 foreach ( $functions['user'] as $function ) {
668 $rf = new ReflectionFunction( $function );
669 $memStats["$function()"] = strlen( serialize( $rf->getStaticVariables() ) );
678 * Get a Parser object
680 function getParser( $preprocessor = null ) {
681 global $wgParserConf;
683 $class = $wgParserConf['class'];
684 $parser = new $class( array( 'preprocessorClass' => $preprocessor ) +
$wgParserConf );
686 wfRunHooks( 'ParserTestParser', array( &$parser ) );
691 //Various action functions
693 public function addArticle( $name, $text, $line ) {
694 self
::$articles[$name] = $text;
697 public function publishTestArticles() {
698 if ( empty( self
::$articles ) ) {
702 foreach ( self
::$articles as $name => $text ) {
703 $title = Title
::newFromText( $name );
705 if ( $title->getArticleID( Title
::GAID_FOR_UPDATE
) == 0 ) {
706 ParserTest
::addArticle( $name, $text );
712 * Steal a callback function from the primary parser, save it for
713 * application to our scary parser. If the hook is not installed,
714 * abort processing of this file.
716 * @param $name String
717 * @return Bool true if tag hook is present
719 public function requireHook( $name ) {
721 $wgParser->firstCallInit( ); // make sure hooks are loaded.
722 return isset( $wgParser->mTagHooks
[$name] );
725 public function requireFunctionHook( $name ) {
727 $wgParser->firstCallInit( ); // make sure hooks are loaded.
728 return isset( $wgParser->mFunctionHooks
[$name] );
730 //Various "cleanup" functions
733 * Run the "tidy" command on text if the $wgUseTidy
736 * @param $text String: the text to tidy
739 protected function tidy( $text ) {
743 $text = MWTidy
::tidy( $text );
750 * Remove last character if it is a newline
752 public function removeEndingNewline( $s ) {
753 if ( substr( $s, -1 ) === "\n" ) {
754 return substr( $s, 0, -1 );
761 public function showRunFile( $file ) {
765 //Test options parser functions
767 protected function parseOptions( $instring ) {
773 // foo=bar,"baz quux"
797 \[\[[^]]*\]\] # Link target
805 if ( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER
) ) {
806 foreach ( $matches as $bits ) {
807 array_shift( $bits );
808 $key = strtolower( array_shift( $bits ) );
809 if ( count( $bits ) == 0 ) {
811 } elseif ( count( $bits ) == 1 ) {
812 $opts[$key] = $this->cleanupOption( array_shift( $bits ) );
815 $opts[$key] = array_map( array( $this, 'cleanupOption' ), $bits );
822 protected function cleanupOption( $opt ) {
823 if ( substr( $opt, 0, 1 ) == '"' ) {
824 return substr( $opt, 1, -1 );
827 if ( substr( $opt, 0, 2 ) == '[[' ) {
828 return substr( $opt, 2, -2 );
834 * Use a regex to find out the value of an option
835 * @param $key String: name of option val to retrieve
836 * @param $opts Options array to look in
837 * @param $default Mixed: default value returned if not found
839 protected static function getOptionValue( $key, $opts, $default ) {
840 $key = strtolower( $key );
842 if ( isset( $opts[$key] ) ) {