3 require_once( dirname( __FILE__
) . '/NewParserHelpers.php' );
8 class NewParserTest
extends MediaWikiTestCase
{
11 public $keepUploads = false;
12 public $runDisabled = false;
14 public $showProgress = true;
15 public $savedGlobals = array();
16 public $hooks = array();
17 public $functionHooks = array();
20 public $maxFuzzTestLength = 300;
22 public $memoryLimit = 50;
26 //PHPUnit + MediaWikiTestCase functions
30 $wgContLang = Language
::factory( 'en' );
35 if ( $this->getCliArg( 'regex=' ) ) {
36 $this->regex
= $this->getCliArg( 'regex=' );
42 $this->keepUploads
= $this->getCliArg( 'keep-uploads' );
46 global $wgParser, $wgParserConf, $IP, $messageMemc, $wgMemc, $wgDeferredUpdateList,
47 $wgUser, $wgLang, $wgOut, $wgRequest, $wgStyleDirectory, $wgEnableParserCache,
48 $wgMessageCache, $wgUseDatabaseMessages, $wgMsgCacheExpiry, $parserMemc,
49 $wgNamespaceAliases, $wgNamespaceProtection, $wgLocalFileRepo,
50 $wgThumbnailScriptPath, $wgScriptPath,
51 $wgArticlePath, $wgStyleSheetPath, $wgScript, $wgStylePath;
53 $wgScript = '/index.php';
55 $wgArticlePath = '/wiki/$1';
56 $wgStyleSheetPath = '/skins';
57 $wgStylePath = '/skins';
58 $wgThumbnailScriptPath = false;
59 $wgLocalFileRepo = array(
60 'class' => 'LocalRepo',
62 'directory' => wfTempDir() . '/test-repo',
63 'url' => 'http://example.com/images',
64 'deletedDir' => wfTempDir() . '/test-repo/delete',
66 'transformVia404' => false,
68 $wgNamespaceProtection[NS_MEDIAWIKI
] = 'editinterface';
69 $wgNamespaceAliases['Image'] = NS_FILE
;
70 $wgNamespaceAliases['Image_talk'] = NS_FILE_TALK
;
73 $wgEnableParserCache = false;
74 $wgDeferredUpdateList = array();
75 $wgMemc = &wfGetMainCache();
76 $messageMemc = &wfGetMessageCacheStorage();
77 $parserMemc = &wfGetParserCacheStorage();
79 // $wgContLang = new StubContLang;
81 $wgLang = new StubUserLang
;
82 $wgOut = new StubObject( 'wgOut', 'OutputPage' );
83 $wgParser = new StubObject( 'wgParser', $wgParserConf['class'], array( $wgParserConf ) );
84 $wgRequest = new WebRequest
;
86 $wgMessageCache = new StubObject( 'wgMessageCache', 'MessageCache',
87 array( $messageMemc, $wgUseDatabaseMessages,
88 $wgMsgCacheExpiry ) );
89 if ( $wgStyleDirectory === false ) {
90 $wgStyleDirectory = "$IP/skins";
95 public function tearDown() {
98 function addDBData() {
99 # Hack: insert a few Wikipedia in-project interwiki prefixes,
100 # for testing inter-language links
101 $this->db
->insert( 'interwiki', array(
102 array( 'iw_prefix' => 'wikipedia',
103 'iw_url' => 'http://en.wikipedia.org/wiki/$1',
107 array( 'iw_prefix' => 'meatball',
108 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
112 array( 'iw_prefix' => 'zh',
113 'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
117 array( 'iw_prefix' => 'es',
118 'iw_url' => 'http://es.wikipedia.org/wiki/$1',
122 array( 'iw_prefix' => 'fr',
123 'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
127 array( 'iw_prefix' => 'ru',
128 'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
135 # Update certain things in site_stats
136 $this->db
->insert( 'site_stats', array( 'ss_row_id' => 1, 'ss_images' => 2, 'ss_good_articles' => 1 ) );
138 # Reinitialise the LocalisationCache to match the database state
139 Language
::getLocalisationCache()->unloadAll();
141 # Make a new message cache
142 global $wgMessageCache, $wgMemc;
143 $wgMessageCache = new MessageCache( $wgMemc, true, 3600 );
145 $this->uploadDir
= $this->setupUploadDir();
147 $user = User
::newFromId( 0 );
149 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Foobar.jpg' ) );
150 $image->recordUpload2( '', 'Upload of some lame file', 'Some lame file', array(
155 'media_type' => MEDIATYPE_BITMAP
,
156 'mime' => 'image/jpeg',
157 'metadata' => serialize( array() ),
158 'sha1' => wfBaseConvert( '', 16, 36, 31 ),
160 ), $this->db
->timestamp( '20010115123500' ), $user );
162 # This image will be blacklisted in [[MediaWiki:Bad image list]]
163 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Bad.jpg' ) );
164 $image->recordUpload2( '', 'zomgnotcensored', 'Borderline image', array(
169 'media_type' => MEDIATYPE_BITMAP
,
170 'mime' => 'image/jpeg',
171 'metadata' => serialize( array() ),
172 'sha1' => wfBaseConvert( '', 16, 36, 31 ),
174 ), $this->db
->timestamp( '20010115123500' ), $user );
181 //ParserTest setup/teardown functions
184 * Set up the global variables for a consistent environment for each test.
185 * Ideally this should replace the global configuration entirely.
187 protected function setupGlobals( $opts = '', $config = '' ) {
188 # Find out values for some special options.
190 self
::getOptionValue( 'language', $opts, 'en' );
192 self
::getOptionValue( 'variant', $opts, false );
194 self
::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
195 $linkHolderBatchSize =
196 self
::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
199 'wgServer' => 'http://Britney-Spears',
200 'wgScript' => '/index.php',
201 'wgScriptPath' => '/',
202 'wgArticlePath' => '/wiki/$1',
203 'wgActionPaths' => array(),
204 'wgLocalFileRepo' => array(
205 'class' => 'LocalRepo',
207 'directory' => $this->uploadDir
,
208 'url' => 'http://example.com/images',
210 'transformVia404' => false,
212 'wgEnableUploads' => self
::getOptionValue( 'wgEnableUploads', $opts, true ),
213 'wgStylePath' => '/skins',
214 'wgStyleSheetPath' => '/skins',
215 'wgSitename' => 'MediaWiki',
216 'wgLanguageCode' => $lang,
217 'wgDBprefix' => $this->db
->getType() != 'oracle' ?
'unittest_' : 'ut_',
218 'wgRawHtml' => isset( $opts['rawhtml'] ),
220 'wgContLang' => null,
221 'wgNamespacesWithSubpages' => array( 0 => isset( $opts['subpage'] ) ),
222 'wgMaxTocLevel' => $maxtoclevel,
223 'wgCapitalLinks' => true,
224 'wgNoFollowLinks' => true,
225 'wgNoFollowDomainExceptions' => array(),
226 'wgThumbnailScriptPath' => false,
227 'wgUseImageResize' => false,
228 'wgUseTeX' => isset( $opts['math'] ),
229 'wgMathDirectory' => $this->uploadDir
. '/math',
230 'wgLocaltimezone' => 'UTC',
231 'wgAllowExternalImages' => true,
232 'wgUseTidy' => false,
233 'wgDefaultLanguageVariant' => $variant,
234 'wgVariantArticlePath' => false,
235 'wgGroupPermissions' => array( '*' => array(
236 'createaccount' => true,
239 'createpage' => true,
240 'createtalk' => true,
242 'wgNamespaceProtection' => array( NS_MEDIAWIKI
=> 'editinterface' ),
243 'wgDefaultExternalStore' => array(),
244 'wgForeignFileRepos' => array(),
245 'wgLinkHolderBatchSize' => $linkHolderBatchSize,
246 'wgExperimentalHtmlIds' => false,
247 'wgExternalLinkTarget' => false,
248 'wgAlwaysUseTidy' => false,
250 'wgWellFormedXml' => true,
251 'wgAllowMicrodataAttributes' => true,
252 'wgAdaptiveMessageCache' => true
256 $configLines = explode( "\n", $config );
258 foreach ( $configLines as $line ) {
259 list( $var, $value ) = explode( '=', $line, 2 );
261 $settings[$var] = eval( "return $value;" ); //???
265 $this->savedGlobals
= array();
267 foreach ( $settings as $var => $val ) {
268 if ( array_key_exists( $var, $GLOBALS ) ) {
269 $this->savedGlobals
[$var] = $GLOBALS[$var];
272 $GLOBALS[$var] = $val;
275 $langObj = Language
::factory( $lang );
276 $GLOBALS['wgLang'] = $langObj;
277 $GLOBALS['wgContLang'] = $langObj;
278 $GLOBALS['wgMemc'] = new FakeMemCachedClient
;
279 $GLOBALS['wgOut'] = new OutputPage
;
283 $wgHooks['ParserTestParser'][] = 'ParserTestParserHook::setup';
284 $wgHooks['ParserTestParser'][] = 'ParserTestStaticParserHook::setup';
285 $wgHooks['ParserGetVariableValueTs'][] = 'ParserTest::getFakeTimestamp';
287 MagicWord
::clearCache();
290 $wgUser = new User();
294 * Restore default values and perform any necessary clean-up
295 * after each test runs.
297 protected function teardownGlobals() {
298 RepoGroup
::destroySingleton();
299 LinkCache
::singleton()->clear();
301 foreach ( $this->savedGlobals
as $var => $val ) {
302 $GLOBALS[$var] = $val;
307 * Create a dummy uploads directory which will contain a couple
308 * of files in order to pass existence tests.
310 * @return String: the directory
312 protected function setupUploadDir() {
315 if ( $this->keepUploads
) {
316 $dir = wfTempDir() . '/mwParser-images';
318 if ( is_dir( $dir ) ) {
322 $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
325 // wfDebug( "Creating upload directory $dir\n" );
326 if ( file_exists( $dir ) ) {
327 wfDebug( "Already exists!\n" );
331 wfMkdirParents( $dir . '/3/3a' );
332 copy( "$IP/skins/monobook/headbg.jpg", "$dir/3/3a/Foobar.jpg" );
333 wfMkdirParents( $dir . '/0/09' );
334 copy( "$IP/skins/monobook/headbg.jpg", "$dir/0/09/Bad.jpg" );
345 public function testParserTests() {
347 global $wgParserTestFiles;
349 $files = $wgParserTestFiles;
351 if( $this->getCliArg( 'file=' ) ) {
352 $files = array( $this->getCliArg( 'file=' ) );
355 foreach( $files as $file ) {
357 $iter = new ParserTestFileIterator( $file, $this );
359 foreach ( $iter as $t ) {
364 $input = $t['input'];
365 $result = $t['result'];
366 $opts = $t['options'];
367 $config = $t['config'];
370 $opts = $this->parseOptions( $opts );
371 $this->setupGlobals( $opts, $config );
374 $options = ParserOptions
::newFromUser( $user );
376 if ( isset( $opts['title'] ) ) {
377 $titleText = $opts['title'];
380 $titleText = 'Parser test';
383 $local = isset( $opts['local'] );
384 $preprocessor = isset( $opts['preprocessor'] ) ?
$opts['preprocessor'] : null;
385 $parser = $this->getParser( $preprocessor );
386 $title = Title
::newFromText( $titleText );
388 if ( isset( $opts['pst'] ) ) {
389 $out = $parser->preSaveTransform( $input, $title, $user, $options );
390 } elseif ( isset( $opts['msg'] ) ) {
391 $out = $parser->transformMsg( $input, $options );
392 } elseif ( isset( $opts['section'] ) ) {
393 $section = $opts['section'];
394 $out = $parser->getSection( $input, $section );
395 } elseif ( isset( $opts['replace'] ) ) {
396 $section = $opts['replace'][0];
397 $replace = $opts['replace'][1];
398 $out = $parser->replaceSection( $input, $section, $replace );
399 } elseif ( isset( $opts['comment'] ) ) {
400 $linker = $user->getSkin();
401 $out = $linker->formatComment( $input, $title, $local );
402 } elseif ( isset( $opts['preload'] ) ) {
403 $out = $parser->getpreloadText( $input, $title, $options );
405 $output = $parser->parse( $input, $title, $options, true, true, 1337 );
406 $out = $output->getText();
408 if ( isset( $opts['showtitle'] ) ) {
409 if ( $output->getTitleText() ) {
410 $title = $output->getTitleText();
413 $out = "$title\n$out";
416 if ( isset( $opts['ill'] ) ) {
417 $out = $this->tidy( implode( ' ', $output->getLanguageLinks() ) );
418 } elseif ( isset( $opts['cat'] ) ) {
421 $wgOut->addCategoryLinks( $output->getCategories() );
422 $cats = $wgOut->getCategoryLinks();
424 if ( isset( $cats['normal'] ) ) {
425 $out = $this->tidy( implode( ' ', $cats['normal'] ) );
431 $result = $this->tidy( $result );
434 $this->teardownGlobals();
436 $this->assertEquals( $result, $out, $desc );
439 catch( Exception
$e ) {
440 $this->assertTrue( false, $t['test'] . ' (failed: ' . $e->getMessage() . ')' );
450 * Run a fuzz test series
451 * Draw input from a set of test files
453 function testFuzzTests() {
455 global $wgParserTestFiles;
457 $files = $wgParserTestFiles;
459 if( $this->getCliArg( 'file=' ) ) {
460 $files = array( $this->getCliArg( 'file=' ) );
463 $dict = $this->getFuzzInput( $files );
464 $dictSize = strlen( $dict );
465 $logMaxLength = log( $this->maxFuzzTestLength
);
467 ini_set( 'memory_limit', $this->memoryLimit
* 1048576 );
470 $opts = ParserOptions
::newFromUser( $user );
471 $title = Title
::makeTitle( NS_MAIN
, 'Parser_test' );
477 // Generate test input
478 mt_srand( ++
$this->fuzzSeed
);
479 $totalLength = mt_rand( 1, $this->maxFuzzTestLength
);
482 while ( strlen( $input ) < $totalLength ) {
483 $logHairLength = mt_rand( 0, 1000000 ) / 1000000 * $logMaxLength;
484 $hairLength = min( intval( exp( $logHairLength ) ), $dictSize );
485 $offset = mt_rand( 0, $dictSize - $hairLength );
486 $input .= substr( $dict, $offset, $hairLength );
489 $this->setupGlobals();
490 $parser = $this->getParser();
494 $parser->parse( $input, $title, $opts );
495 $this->assertTrue( true, "Test $id, fuzz seed {$this->fuzzSeed}" );
496 } catch ( Exception
$exception ) {
500 $input_dump = ob_get_contents();
503 $this->assertTrue( false, "Test $id, fuzz seed {$this->fuzzSeed}. \n\nInput: $input_dump\n\nError: {$exception->getMessage()}\n\nBacktrace: {$exception->getTraceAsString()}" );
506 $this->teardownGlobals();
507 $parser->__destruct();
509 if ( $id %
100 == 0 ) {
510 $usage = intval( memory_get_usage( true ) / $this->memoryLimit
/ 1048576 * 100 );
511 //echo "{$this->fuzzSeed}: $numSuccess/$numTotal (mem: $usage%)\n";
513 $ret = "Out of memory:\n";
514 $memStats = $this->getMemoryBreakdown();
516 foreach ( $memStats as $name => $usage ) {
517 $ret .= "$name: $usage\n";
520 throw new MWException( $ret );
536 //Various getter functions
539 * Get an input dictionary from a set of parser test files
541 function getFuzzInput( $filenames ) {
544 foreach ( $filenames as $filename ) {
545 $contents = file_get_contents( $filename );
546 preg_match_all( '/!!\s*input\n(.*?)\n!!\s*result/s', $contents, $matches );
548 foreach ( $matches[1] as $match ) {
549 $dict .= $match . "\n";
557 * Get a memory usage breakdown
559 function getMemoryBreakdown() {
562 foreach ( $GLOBALS as $name => $value ) {
563 $memStats['$' . $name] = strlen( serialize( $value ) );
566 $classes = get_declared_classes();
568 foreach ( $classes as $class ) {
569 $rc = new ReflectionClass( $class );
570 $props = $rc->getStaticProperties();
571 $memStats[$class] = strlen( serialize( $props ) );
572 $methods = $rc->getMethods();
574 foreach ( $methods as $method ) {
575 $memStats[$class] +
= strlen( serialize( $method->getStaticVariables() ) );
579 $functions = get_defined_functions();
581 foreach ( $functions['user'] as $function ) {
582 $rf = new ReflectionFunction( $function );
583 $memStats["$function()"] = strlen( serialize( $rf->getStaticVariables() ) );
592 * Get a Parser object
594 function getParser( $preprocessor = null ) {
595 global $wgParserConf;
597 $class = $wgParserConf['class'];
598 $parser = new $class( array( 'preprocessorClass' => $preprocessor ) +
$wgParserConf );
600 foreach ( $this->hooks
as $tag => $callback ) {
601 $parser->setHook( $tag, $callback );
604 foreach ( $this->functionHooks
as $tag => $bits ) {
605 list( $callback, $flags ) = $bits;
606 $parser->setFunctionHook( $tag, $callback, $flags );
609 wfRunHooks( 'ParserTestParser', array( &$parser ) );
620 //Various action functions
623 * Insert a temporary test article
624 * @param $name String: the title, including any prefix
625 * @param $text String: the article text
626 * @param $line Integer: the input line number, for reporting errors
628 public function addArticle( $name, $text, $line = 'unknown' ) {
629 global $wgCapitalLinks;
631 $text = $this->removeEndingNewline($text);
633 $oldCapitalLinks = $wgCapitalLinks;
634 $wgCapitalLinks = true; // We only need this from SetupGlobals() See r70917#c8637
636 $name = $this->removeEndingNewline( $name );
637 $title = Title
::newFromText( $name );
639 if ( is_null( $title ) ) {
640 throw new MWException( "invalid title ('$name' => '$title') at line $line\n" );
643 $aid = $title->getArticleID( Title
::GAID_FOR_UPDATE
);
646 debug_print_backtrace();
647 throw new MWException( "duplicate article '$name' at line $line\n" );
650 $art = new Article( $title );
651 $art->doEdit( $text, '', EDIT_NEW
);
653 $wgCapitalLinks = $oldCapitalLinks;
657 * Steal a callback function from the primary parser, save it for
658 * application to our scary parser. If the hook is not installed,
659 * abort processing of this file.
661 * @param $name String
662 * @return Bool true if tag hook is present
664 public function requireHook( $name ) {
667 $wgParser->firstCallInit( ); // make sure hooks are loaded.
669 if ( isset( $wgParser->mTagHooks
[$name] ) ) {
670 $this->hooks
[$name] = $wgParser->mTagHooks
[$name];
672 echo " This test suite requires the '$name' hook extension, skipping.\n";
683 //Various "cleanup" functions
686 * Run the "tidy" command on text if the $wgUseTidy
689 * @param $text String: the text to tidy
693 protected function tidy( $text ) {
697 $text = MWTidy
::tidy( $text );
704 * Remove last character if it is a newline
706 public function removeEndingNewline( $s ) {
707 if ( substr( $s, -1 ) === "\n" ) {
708 return substr( $s, 0, -1 );
720 //Test options parser functions
722 protected function parseOptions( $instring ) {
728 // foo=bar,"baz quux"
752 \[\[[^]]*\]\] # Link target
760 if ( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER
) ) {
761 foreach ( $matches as $bits ) {
762 array_shift( $bits );
763 $key = strtolower( array_shift( $bits ) );
764 if ( count( $bits ) == 0 ) {
766 } elseif ( count( $bits ) == 1 ) {
767 $opts[$key] = $this->cleanupOption( array_shift( $bits ) );
770 $opts[$key] = array_map( array( $this, 'cleanupOption' ), $bits );
777 protected function cleanupOption( $opt ) {
778 if ( substr( $opt, 0, 1 ) == '"' ) {
779 return substr( $opt, 1, -1 );
782 if ( substr( $opt, 0, 2 ) == '[[' ) {
783 return substr( $opt, 2, -2 );
789 * Use a regex to find out the value of an option
790 * @param $key String: name of option val to retrieve
791 * @param $opts Options array to look in
792 * @param $default Mixed: default value returned if not found
794 protected static function getOptionValue( $key, $opts, $default ) {
795 $key = strtolower( $key );
797 if ( isset( $opts[$key] ) ) {