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'] = new WebRequest
;
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 ),
169 * @todo Fixme! Same as above!
174 # Reinitialise the LocalisationCache to match the database state
175 Language
::getLocalisationCache()->unloadAll();
177 # Clear the message cache
178 MessageCache
::singleton()->clear();
180 $this->uploadDir
= $this->setupUploadDir();
182 $user = User
::newFromId( 0 );
183 LinkCache
::singleton()->clear(); # Avoids the odd failure at creating the nullRevision
185 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Foobar.jpg' ) );
186 $image->recordUpload2( '', 'Upload of some lame file', 'Some lame file', array(
191 'media_type' => MEDIATYPE_BITMAP
,
192 'mime' => 'image/jpeg',
193 'metadata' => serialize( array() ),
194 'sha1' => wfBaseConvert( '', 16, 36, 31 ),
196 ), $this->db
->timestamp( '20010115123500' ), $user );
198 # This image will be blacklisted in [[MediaWiki:Bad image list]]
199 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Bad.jpg' ) );
200 $image->recordUpload2( '', 'zomgnotcensored', 'Borderline image', array(
205 'media_type' => MEDIATYPE_BITMAP
,
206 'mime' => 'image/jpeg',
207 'metadata' => serialize( array() ),
208 'sha1' => wfBaseConvert( '', 16, 36, 31 ),
210 ), $this->db
->timestamp( '20010115123500' ), $user );
217 //ParserTest setup/teardown functions
220 * Set up the global variables for a consistent environment for each test.
221 * Ideally this should replace the global configuration entirely.
223 protected function setupGlobals( $opts = '', $config = '' ) {
224 # Find out values for some special options.
226 self
::getOptionValue( 'language', $opts, 'en' );
228 self
::getOptionValue( 'variant', $opts, false );
230 self
::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
231 $linkHolderBatchSize =
232 self
::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
235 'wgServer' => 'http://Britney-Spears',
236 'wgScript' => '/index.php',
237 'wgScriptPath' => '/',
238 'wgArticlePath' => '/wiki/$1',
239 'wgActionPaths' => array(),
240 'wgLocalFileRepo' => array(
241 'class' => 'LocalRepo',
243 'directory' => $this->uploadDir
,
244 'url' => 'http://example.com/images',
246 'transformVia404' => false,
248 'wgEnableUploads' => self
::getOptionValue( 'wgEnableUploads', $opts, true ),
249 'wgStylePath' => '/skins',
250 'wgStyleSheetPath' => '/skins',
251 'wgSitename' => 'MediaWiki',
252 'wgLanguageCode' => $lang,
253 'wgDBprefix' => $this->db
->getType() != 'oracle' ?
'unittest_' : 'ut_',
254 'wgRawHtml' => isset( $opts['rawhtml'] ),
256 'wgContLang' => null,
257 'wgNamespacesWithSubpages' => array( 0 => isset( $opts['subpage'] ) ),
258 'wgMaxTocLevel' => $maxtoclevel,
259 'wgCapitalLinks' => true,
260 'wgNoFollowLinks' => true,
261 'wgNoFollowDomainExceptions' => array(),
262 'wgThumbnailScriptPath' => false,
263 'wgUseImageResize' => false,
264 'wgUseTeX' => isset( $opts['math'] ),
265 'wgMathDirectory' => $this->uploadDir
. '/math',
266 'wgLocaltimezone' => 'UTC',
267 'wgAllowExternalImages' => true,
268 'wgUseTidy' => false,
269 'wgDefaultLanguageVariant' => $variant,
270 'wgVariantArticlePath' => false,
271 'wgGroupPermissions' => array( '*' => array(
272 'createaccount' => true,
275 'createpage' => true,
276 'createtalk' => true,
278 'wgNamespaceProtection' => array( NS_MEDIAWIKI
=> 'editinterface' ),
279 'wgDefaultExternalStore' => array(),
280 'wgForeignFileRepos' => array(),
281 'wgLinkHolderBatchSize' => $linkHolderBatchSize,
282 'wgExperimentalHtmlIds' => false,
283 'wgExternalLinkTarget' => false,
284 'wgAlwaysUseTidy' => false,
286 'wgWellFormedXml' => true,
287 'wgAllowMicrodataAttributes' => true,
288 'wgAdaptiveMessageCache' => true,
289 'wgUseDatabaseMessages' => true,
293 $configLines = explode( "\n", $config );
295 foreach ( $configLines as $line ) {
296 list( $var, $value ) = explode( '=', $line, 2 );
298 $settings[$var] = eval( "return $value;" ); //???
302 $this->savedGlobals
= array();
304 foreach ( $settings as $var => $val ) {
305 if ( array_key_exists( $var, $GLOBALS ) ) {
306 $this->savedGlobals
[$var] = $GLOBALS[$var];
309 $GLOBALS[$var] = $val;
312 $langObj = Language
::factory( $lang );
313 $GLOBALS['wgContLang'] = $langObj;
314 $context = new RequestContext();
315 $GLOBALS['wgLang'] = $context->getLang();
317 $GLOBALS['wgMemc'] = new EmptyBagOStuff
;
318 $GLOBALS['wgOut'] = $context->getOutput();
322 $wgHooks['ParserTestParser'][] = 'ParserTestParserHook::setup';
323 $wgHooks['ParserTestParser'][] = 'ParserTestStaticParserHook::setup';
324 $wgHooks['ParserGetVariableValueTs'][] = 'ParserTest::getFakeTimestamp';
326 MagicWord
::clearCache();
328 # Publish the articles after we have the final language set
329 $this->publishTestArticles();
331 # The entries saved into RepoGroup cache with previous globals will be wrong.
332 RepoGroup
::destroySingleton();
333 MessageCache
::singleton()->destroyInstance();
336 $wgUser = new User();
340 * Create a dummy uploads directory which will contain a couple
341 * of files in order to pass existence tests.
343 * @return String: the directory
345 protected function setupUploadDir() {
348 if ( $this->keepUploads
) {
349 $dir = wfTempDir() . '/mwParser-images';
351 if ( is_dir( $dir ) ) {
355 $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
358 // wfDebug( "Creating upload directory $dir\n" );
359 if ( file_exists( $dir ) ) {
360 wfDebug( "Already exists!\n" );
364 wfMkdirParents( $dir . '/3/3a' );
365 copy( "$IP/skins/monobook/headbg.jpg", "$dir/3/3a/Foobar.jpg" );
366 wfMkdirParents( $dir . '/0/09' );
367 copy( "$IP/skins/monobook/headbg.jpg", "$dir/0/09/Bad.jpg" );
373 * Restore default values and perform any necessary clean-up
374 * after each test runs.
376 protected function teardownGlobals() {
377 RepoGroup
::destroySingleton();
378 LinkCache
::singleton()->clear();
380 foreach ( $this->savedGlobals
as $var => $val ) {
381 $GLOBALS[$var] = $val;
384 $this->teardownUploadDir( $this->uploadDir
);
388 * Remove the dummy uploads directory
390 private function teardownUploadDir( $dir ) {
391 if ( $this->keepUploads
) {
395 // delete the files first, then the dirs.
398 "$dir/3/3a/Foobar.jpg",
399 "$dir/thumb/3/3a/Foobar.jpg/180px-Foobar.jpg",
400 "$dir/thumb/3/3a/Foobar.jpg/200px-Foobar.jpg",
401 "$dir/thumb/3/3a/Foobar.jpg/640px-Foobar.jpg",
402 "$dir/thumb/3/3a/Foobar.jpg/120px-Foobar.jpg",
406 "$dir/math/f/a/5/fa50b8b616463173474302ca3e63586b.png",
416 "$dir/thumb/3/3a/Foobar.jpg",
433 * Delete the specified files, if they exist.
434 * @param $files Array: full paths to files to delete.
436 private static function deleteFiles( $files ) {
437 foreach ( $files as $file ) {
438 if ( file_exists( $file ) ) {
445 * Delete the specified directories, if they exist. Must be empty.
446 * @param $dirs Array: full paths to directories to delete.
448 private static function deleteDirs( $dirs ) {
449 foreach ( $dirs as $dir ) {
450 if ( is_dir( $dir ) ) {
456 public function parserTestProvider() {
457 if ( $this->file
=== false ) {
458 global $wgParserTestFiles;
459 $this->file
= $wgParserTestFiles[0];
461 return new TestFileIterator( $this->file
, $this );
465 * Set the file from whose tests will be run by this instance
467 public function setParserTestFile( $filename ) {
468 $this->file
= $filename;
471 /** @dataProvider parserTestProvider */
472 public function testParserTest( $desc, $input, $result, $opts, $config ) {
473 if ( !preg_match( '/' . $this->regex
. '/', $desc ) ) return; //$this->markTestSkipped( 'Filtered out by the user' );
475 wfDebug( "Running parser test: $desc\n" );
477 $opts = $this->parseOptions( $opts );
478 $this->setupGlobals( $opts, $config );
481 $options = ParserOptions
::newFromUser( $user );
483 if ( isset( $opts['title'] ) ) {
484 $titleText = $opts['title'];
487 $titleText = 'Parser test';
490 $local = isset( $opts['local'] );
491 $preprocessor = isset( $opts['preprocessor'] ) ?
$opts['preprocessor'] : null;
492 $parser = $this->getParser( $preprocessor );
494 $title = Title
::newFromText( $titleText );
496 if ( isset( $opts['pst'] ) ) {
497 $out = $parser->preSaveTransform( $input, $title, $user, $options );
498 } elseif ( isset( $opts['msg'] ) ) {
499 $out = $parser->transformMsg( $input, $options, $title );
500 } elseif ( isset( $opts['section'] ) ) {
501 $section = $opts['section'];
502 $out = $parser->getSection( $input, $section );
503 } elseif ( isset( $opts['replace'] ) ) {
504 $section = $opts['replace'][0];
505 $replace = $opts['replace'][1];
506 $out = $parser->replaceSection( $input, $section, $replace );
507 } elseif ( isset( $opts['comment'] ) ) {
508 $linker = $user->getSkin();
509 $out = $linker->formatComment( $input, $title, $local );
510 } elseif ( isset( $opts['preload'] ) ) {
511 $out = $parser->getpreloadText( $input, $title, $options );
513 $output = $parser->parse( $input, $title, $options, true, true, 1337 );
514 $out = $output->getText();
516 if ( isset( $opts['showtitle'] ) ) {
517 if ( $output->getTitleText() ) {
518 $title = $output->getTitleText();
521 $out = "$title\n$out";
524 if ( isset( $opts['ill'] ) ) {
525 $out = $this->tidy( implode( ' ', $output->getLanguageLinks() ) );
526 } elseif ( isset( $opts['cat'] ) ) {
529 $wgOut->addCategoryLinks( $output->getCategories() );
530 $cats = $wgOut->getCategoryLinks();
532 if ( isset( $cats['normal'] ) ) {
533 $out = $this->tidy( implode( ' ', $cats['normal'] ) );
538 $parser->mPreprocessor
= null;
540 $result = $this->tidy( $result );
543 $this->teardownGlobals();
545 $this->assertEquals( $result, $out, $desc );
549 * Run a fuzz test series
550 * Draw input from a set of test files
552 function testFuzzTests() {
554 $this->markTestIncomplete( 'Breaks tesla due to memory restrictions' );
556 global $wgParserTestFiles;
558 $files = $wgParserTestFiles;
560 if( $this->getCliArg( 'file=' ) ) {
561 $files = array( $this->getCliArg( 'file=' ) );
564 $dict = $this->getFuzzInput( $files );
565 $dictSize = strlen( $dict );
566 $logMaxLength = log( $this->maxFuzzTestLength
);
568 ini_set( 'memory_limit', $this->memoryLimit
* 1048576 );
571 $opts = ParserOptions
::newFromUser( $user );
572 $title = Title
::makeTitle( NS_MAIN
, 'Parser_test' );
578 // Generate test input
579 mt_srand( ++
$this->fuzzSeed
);
580 $totalLength = mt_rand( 1, $this->maxFuzzTestLength
);
583 while ( strlen( $input ) < $totalLength ) {
584 $logHairLength = mt_rand( 0, 1000000 ) / 1000000 * $logMaxLength;
585 $hairLength = min( intval( exp( $logHairLength ) ), $dictSize );
586 $offset = mt_rand( 0, $dictSize - $hairLength );
587 $input .= substr( $dict, $offset, $hairLength );
590 $this->setupGlobals();
591 $parser = $this->getParser();
595 $parser->parse( $input, $title, $opts );
596 $this->assertTrue( true, "Test $id, fuzz seed {$this->fuzzSeed}" );
597 } catch ( Exception
$exception ) {
598 $input_dump = sprintf( "string(%d) \"%s\"\n", strlen( $input ), $input );
600 $this->assertTrue( false, "Test $id, fuzz seed {$this->fuzzSeed}. \n\nInput: $input_dump\n\nError: {$exception->getMessage()}\n\nBacktrace: {$exception->getTraceAsString()}" );
603 $this->teardownGlobals();
604 $parser->__destruct();
606 if ( $id %
100 == 0 ) {
607 $usage = intval( memory_get_usage( true ) / $this->memoryLimit
/ 1048576 * 100 );
608 //echo "{$this->fuzzSeed}: $numSuccess/$numTotal (mem: $usage%)\n";
610 $ret = "Out of memory:\n";
611 $memStats = $this->getMemoryBreakdown();
613 foreach ( $memStats as $name => $usage ) {
614 $ret .= "$name: $usage\n";
617 throw new MWException( $ret );
626 //Various getter functions
629 * Get an input dictionary from a set of parser test files
631 function getFuzzInput( $filenames ) {
634 foreach ( $filenames as $filename ) {
635 $contents = file_get_contents( $filename );
636 preg_match_all( '/!!\s*input\n(.*?)\n!!\s*result/s', $contents, $matches );
638 foreach ( $matches[1] as $match ) {
639 $dict .= $match . "\n";
647 * Get a memory usage breakdown
649 function getMemoryBreakdown() {
652 foreach ( $GLOBALS as $name => $value ) {
653 $memStats['$' . $name] = strlen( serialize( $value ) );
656 $classes = get_declared_classes();
658 foreach ( $classes as $class ) {
659 $rc = new ReflectionClass( $class );
660 $props = $rc->getStaticProperties();
661 $memStats[$class] = strlen( serialize( $props ) );
662 $methods = $rc->getMethods();
664 foreach ( $methods as $method ) {
665 $memStats[$class] +
= strlen( serialize( $method->getStaticVariables() ) );
669 $functions = get_defined_functions();
671 foreach ( $functions['user'] as $function ) {
672 $rf = new ReflectionFunction( $function );
673 $memStats["$function()"] = strlen( serialize( $rf->getStaticVariables() ) );
682 * Get a Parser object
684 function getParser( $preprocessor = null ) {
685 global $wgParserConf;
687 $class = $wgParserConf['class'];
688 $parser = new $class( array( 'preprocessorClass' => $preprocessor ) +
$wgParserConf );
690 wfRunHooks( 'ParserTestParser', array( &$parser ) );
695 //Various action functions
697 public function addArticle( $name, $text, $line ) {
698 self
::$articles[$name] = $text;
701 public function publishTestArticles() {
702 if ( empty( self
::$articles ) ) {
706 foreach ( self
::$articles as $name => $text ) {
707 $title = Title
::newFromText( $name );
709 if ( $title->getArticleID( Title
::GAID_FOR_UPDATE
) == 0 ) {
710 ParserTest
::addArticle( $name, $text );
716 * Steal a callback function from the primary parser, save it for
717 * application to our scary parser. If the hook is not installed,
718 * abort processing of this file.
720 * @param $name String
721 * @return Bool true if tag hook is present
723 public function requireHook( $name ) {
725 $wgParser->firstCallInit( ); // make sure hooks are loaded.
726 return isset( $wgParser->mTagHooks
[$name] );
729 public function requireFunctionHook( $name ) {
731 $wgParser->firstCallInit( ); // make sure hooks are loaded.
732 return isset( $wgParser->mFunctionHooks
[$name] );
734 //Various "cleanup" functions
737 * Run the "tidy" command on text if the $wgUseTidy
740 * @param $text String: the text to tidy
743 protected function tidy( $text ) {
747 $text = MWTidy
::tidy( $text );
754 * Remove last character if it is a newline
756 public function removeEndingNewline( $s ) {
757 if ( substr( $s, -1 ) === "\n" ) {
758 return substr( $s, 0, -1 );
765 public function showRunFile( $file ) {
769 //Test options parser functions
771 protected function parseOptions( $instring ) {
777 // foo=bar,"baz quux"
801 \[\[[^]]*\]\] # Link target
809 if ( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER
) ) {
810 foreach ( $matches as $bits ) {
811 array_shift( $bits );
812 $key = strtolower( array_shift( $bits ) );
813 if ( count( $bits ) == 0 ) {
815 } elseif ( count( $bits ) == 1 ) {
816 $opts[$key] = $this->cleanupOption( array_shift( $bits ) );
819 $opts[$key] = array_map( array( $this, 'cleanupOption' ), $bits );
826 protected function cleanupOption( $opt ) {
827 if ( substr( $opt, 0, 1 ) == '"' ) {
828 return substr( $opt, 1, -1 );
831 if ( substr( $opt, 0, 2 ) == '[[' ) {
832 return substr( $opt, 2, -2 );
838 * Use a regex to find out the value of an option
839 * @param $key String: name of option val to retrieve
840 * @param $opts Options array to look in
841 * @param $default Mixed: default value returned if not found
843 protected static function getOptionValue( $key, $opts, $default ) {
844 $key = strtolower( $key );
846 if ( isset( $opts[$key] ) ) {