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 $tmpGlobals['wgLang'] = new StubUserLang
;
80 $tmpGlobals['wgOut'] = new StubObject( 'wgOut', 'OutputPage' );
81 $tmpGlobals['wgParser'] = new StubObject( 'wgParser', $GLOBALS['wgParserConf']['class'], array( $GLOBALS['wgParserConf'] ) );
82 $tmpGlobals['wgRequest'] = new WebRequest
;
84 if ( $GLOBALS['wgStyleDirectory'] === false ) {
85 $tmpGlobals['wgStyleDirectory'] = "$IP/skins";
89 foreach ( $tmpGlobals as $var => $val ) {
90 if ( array_key_exists( $var, $GLOBALS ) ) {
91 $this->savedInitialGlobals
[$var] = $GLOBALS[$var];
94 $GLOBALS[$var] = $val;
97 $this->savedWeirdGlobals
['mw_namespace_protection'] = $wgNamespaceProtection[NS_MEDIAWIKI
];
98 $this->savedWeirdGlobals
['image_alias'] = $wgNamespaceAliases['Image'];
99 $this->savedWeirdGlobals
['image_talk_alias'] = $wgNamespaceAliases['Image_talk'];
101 $wgNamespaceProtection[NS_MEDIAWIKI
] = 'editinterface';
102 $wgNamespaceAliases['Image'] = NS_FILE
;
103 $wgNamespaceAliases['Image_talk'] = NS_FILE_TALK
;
107 public function tearDown() {
109 foreach ( $this->savedInitialGlobals
as $var => $val ) {
110 $GLOBALS[$var] = $val;
113 global $wgNamespaceProtection, $wgNamespaceAliases;
115 $wgNamespaceProtection[NS_MEDIAWIKI
] = $this->savedWeirdGlobals
['mw_namespace_protection'];
116 $wgNamespaceAliases['Image'] = $this->savedWeirdGlobals
['image_alias'];
117 $wgNamespaceAliases['Image_talk'] = $this->savedWeirdGlobals
['image_talk_alias'];
120 function addDBData() {
121 # Hack: insert a few Wikipedia in-project interwiki prefixes,
122 # for testing inter-language links
123 $this->db
->insert( 'interwiki', array(
124 array( 'iw_prefix' => 'wikipedia',
125 'iw_url' => 'http://en.wikipedia.org/wiki/$1',
129 array( 'iw_prefix' => 'meatball',
130 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
134 array( 'iw_prefix' => 'zh',
135 'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
139 array( 'iw_prefix' => 'es',
140 'iw_url' => 'http://es.wikipedia.org/wiki/$1',
144 array( 'iw_prefix' => 'fr',
145 'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
149 array( 'iw_prefix' => 'ru',
150 'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
157 # Update certain things in site_stats
158 $this->db
->insert( 'site_stats', array( 'ss_row_id' => 1, 'ss_images' => 2, 'ss_good_articles' => 1 ) );
160 # Reinitialise the LocalisationCache to match the database state
161 Language
::getLocalisationCache()->unloadAll();
163 # Clear the message cache
164 MessageCache
::singleton()->clear();
166 $this->uploadDir
= $this->setupUploadDir();
168 $user = User
::newFromId( 0 );
169 LinkCache
::singleton()->clear(); # Avoids the odd failure at creating the nullRevision
171 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Foobar.jpg' ) );
172 $image->recordUpload2( '', 'Upload of some lame file', 'Some lame file', array(
177 'media_type' => MEDIATYPE_BITMAP
,
178 'mime' => 'image/jpeg',
179 'metadata' => serialize( array() ),
180 'sha1' => wfBaseConvert( '', 16, 36, 31 ),
182 ), $this->db
->timestamp( '20010115123500' ), $user );
184 # This image will be blacklisted in [[MediaWiki:Bad image list]]
185 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Bad.jpg' ) );
186 $image->recordUpload2( '', 'zomgnotcensored', 'Borderline image', 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 );
203 //ParserTest setup/teardown functions
206 * Set up the global variables for a consistent environment for each test.
207 * Ideally this should replace the global configuration entirely.
209 protected function setupGlobals( $opts = '', $config = '' ) {
210 # Find out values for some special options.
212 self
::getOptionValue( 'language', $opts, 'en' );
214 self
::getOptionValue( 'variant', $opts, false );
216 self
::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
217 $linkHolderBatchSize =
218 self
::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
221 'wgServer' => 'http://Britney-Spears',
222 'wgScript' => '/index.php',
223 'wgScriptPath' => '/',
224 'wgArticlePath' => '/wiki/$1',
225 'wgActionPaths' => array(),
226 'wgLocalFileRepo' => array(
227 'class' => 'LocalRepo',
229 'directory' => $this->uploadDir
,
230 'url' => 'http://example.com/images',
232 'transformVia404' => false,
234 'wgEnableUploads' => self
::getOptionValue( 'wgEnableUploads', $opts, true ),
235 'wgStylePath' => '/skins',
236 'wgStyleSheetPath' => '/skins',
237 'wgSitename' => 'MediaWiki',
238 'wgLanguageCode' => $lang,
239 'wgDBprefix' => $this->db
->getType() != 'oracle' ?
'unittest_' : 'ut_',
240 'wgRawHtml' => isset( $opts['rawhtml'] ),
242 'wgContLang' => null,
243 'wgNamespacesWithSubpages' => array( 0 => isset( $opts['subpage'] ) ),
244 'wgMaxTocLevel' => $maxtoclevel,
245 'wgCapitalLinks' => true,
246 'wgNoFollowLinks' => true,
247 'wgNoFollowDomainExceptions' => array(),
248 'wgThumbnailScriptPath' => false,
249 'wgUseImageResize' => false,
250 'wgUseTeX' => isset( $opts['math'] ),
251 'wgMathDirectory' => $this->uploadDir
. '/math',
252 'wgLocaltimezone' => 'UTC',
253 'wgAllowExternalImages' => true,
254 'wgUseTidy' => false,
255 'wgDefaultLanguageVariant' => $variant,
256 'wgVariantArticlePath' => false,
257 'wgGroupPermissions' => array( '*' => array(
258 'createaccount' => true,
261 'createpage' => true,
262 'createtalk' => true,
264 'wgNamespaceProtection' => array( NS_MEDIAWIKI
=> 'editinterface' ),
265 'wgDefaultExternalStore' => array(),
266 'wgForeignFileRepos' => array(),
267 'wgLinkHolderBatchSize' => $linkHolderBatchSize,
268 'wgExperimentalHtmlIds' => false,
269 'wgExternalLinkTarget' => false,
270 'wgAlwaysUseTidy' => false,
272 'wgWellFormedXml' => true,
273 'wgAllowMicrodataAttributes' => true,
274 'wgAdaptiveMessageCache' => true,
275 'wgUseDatabaseMessages' => true,
279 $configLines = explode( "\n", $config );
281 foreach ( $configLines as $line ) {
282 list( $var, $value ) = explode( '=', $line, 2 );
284 $settings[$var] = eval( "return $value;" ); //???
288 $this->savedGlobals
= array();
290 foreach ( $settings as $var => $val ) {
291 if ( array_key_exists( $var, $GLOBALS ) ) {
292 $this->savedGlobals
[$var] = $GLOBALS[$var];
295 $GLOBALS[$var] = $val;
298 $langObj = Language
::factory( $lang );
299 $GLOBALS['wgContLang'] = $langObj;
301 $context = new RequestContext();
302 $GLOBALS['wgLang'] = $context->lang
;
303 $GLOBALS['wgContLang'] = $context->lang
;
304 $GLOBALS['wgMemc'] = new EmptyBagOStuff
;
305 $GLOBALS['wgOut'] = new $context->output
;
309 $wgHooks['ParserTestParser'][] = 'ParserTestParserHook::setup';
310 $wgHooks['ParserTestParser'][] = 'ParserTestStaticParserHook::setup';
311 $wgHooks['ParserGetVariableValueTs'][] = 'ParserTest::getFakeTimestamp';
313 MagicWord
::clearCache();
315 # Publish the articles after we have the final language set
316 $this->publishTestArticles();
318 # The entries saved into RepoGroup cache with previous globals will be wrong.
319 RepoGroup
::destroySingleton();
320 MessageCache
::singleton()->destroyInstance();
323 $wgUser = new User();
327 * Restore default values and perform any necessary clean-up
328 * after each test runs.
330 protected function teardownGlobals() {
331 RepoGroup
::destroySingleton();
332 LinkCache
::singleton()->clear();
334 foreach ( $this->savedGlobals
as $var => $val ) {
335 $GLOBALS[$var] = $val;
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" );
372 public function parserTestProvider() {
373 if ( $this->file
=== false ) {
374 global $wgParserTestFiles;
375 $this->file
= $wgParserTestFiles[0];
377 return new TestFileIterator( $this->file
, $this );
381 * Set the file from whose tests will be run by this instance
383 public function setParserTestFile( $filename ) {
384 $this->file
= $filename;
387 /** @dataProvider parserTestProvider */
388 public function testParserTest( $desc, $input, $result, $opts, $config ) {
389 if ( !preg_match( '/' . $this->regex
. '/', $desc ) ) return; //$this->markTestSkipped( 'Filtered out by the user' );
391 wfDebug( "Running parser test: $desc\n" );
393 $opts = $this->parseOptions( $opts );
394 $this->setupGlobals( $opts, $config );
397 $options = ParserOptions
::newFromUser( $user );
399 if ( isset( $opts['title'] ) ) {
400 $titleText = $opts['title'];
403 $titleText = 'Parser test';
406 $local = isset( $opts['local'] );
407 $preprocessor = isset( $opts['preprocessor'] ) ?
$opts['preprocessor'] : null;
408 $parser = $this->getParser( $preprocessor );
410 $title = Title
::newFromText( $titleText );
412 if ( isset( $opts['pst'] ) ) {
413 $out = $parser->preSaveTransform( $input, $title, $user, $options );
414 } elseif ( isset( $opts['msg'] ) ) {
415 $out = $parser->transformMsg( $input, $options );
416 } elseif ( isset( $opts['section'] ) ) {
417 $section = $opts['section'];
418 $out = $parser->getSection( $input, $section );
419 } elseif ( isset( $opts['replace'] ) ) {
420 $section = $opts['replace'][0];
421 $replace = $opts['replace'][1];
422 $out = $parser->replaceSection( $input, $section, $replace );
423 } elseif ( isset( $opts['comment'] ) ) {
424 $linker = $user->getSkin();
425 $out = $linker->formatComment( $input, $title, $local );
426 } elseif ( isset( $opts['preload'] ) ) {
427 $out = $parser->getpreloadText( $input, $title, $options );
429 $output = $parser->parse( $input, $title, $options, true, true, 1337 );
430 $out = $output->getText();
432 if ( isset( $opts['showtitle'] ) ) {
433 if ( $output->getTitleText() ) {
434 $title = $output->getTitleText();
437 $out = "$title\n$out";
440 if ( isset( $opts['ill'] ) ) {
441 $out = $this->tidy( implode( ' ', $output->getLanguageLinks() ) );
442 } elseif ( isset( $opts['cat'] ) ) {
445 $wgOut->addCategoryLinks( $output->getCategories() );
446 $cats = $wgOut->getCategoryLinks();
448 if ( isset( $cats['normal'] ) ) {
449 $out = $this->tidy( implode( ' ', $cats['normal'] ) );
454 $parser->mPreprocessor
= null;
456 $result = $this->tidy( $result );
459 $this->teardownGlobals();
461 $this->assertEquals( $result, $out, $desc );
465 * Run a fuzz test series
466 * Draw input from a set of test files
468 function testFuzzTests() {
470 $this->markTestIncomplete( 'Breaks tesla due to memory restrictions' );
472 global $wgParserTestFiles;
474 $files = $wgParserTestFiles;
476 if( $this->getCliArg( 'file=' ) ) {
477 $files = array( $this->getCliArg( 'file=' ) );
480 $dict = $this->getFuzzInput( $files );
481 $dictSize = strlen( $dict );
482 $logMaxLength = log( $this->maxFuzzTestLength
);
484 ini_set( 'memory_limit', $this->memoryLimit
* 1048576 );
487 $opts = ParserOptions
::newFromUser( $user );
488 $title = Title
::makeTitle( NS_MAIN
, 'Parser_test' );
494 // Generate test input
495 mt_srand( ++
$this->fuzzSeed
);
496 $totalLength = mt_rand( 1, $this->maxFuzzTestLength
);
499 while ( strlen( $input ) < $totalLength ) {
500 $logHairLength = mt_rand( 0, 1000000 ) / 1000000 * $logMaxLength;
501 $hairLength = min( intval( exp( $logHairLength ) ), $dictSize );
502 $offset = mt_rand( 0, $dictSize - $hairLength );
503 $input .= substr( $dict, $offset, $hairLength );
506 $this->setupGlobals();
507 $parser = $this->getParser();
511 $parser->parse( $input, $title, $opts );
512 $this->assertTrue( true, "Test $id, fuzz seed {$this->fuzzSeed}" );
513 } catch ( Exception
$exception ) {
514 $input_dump = sprintf( "string(%d) \"%s\"\n", strlen( $input ), $input );
516 $this->assertTrue( false, "Test $id, fuzz seed {$this->fuzzSeed}. \n\nInput: $input_dump\n\nError: {$exception->getMessage()}\n\nBacktrace: {$exception->getTraceAsString()}" );
519 $this->teardownGlobals();
520 $parser->__destruct();
522 if ( $id %
100 == 0 ) {
523 $usage = intval( memory_get_usage( true ) / $this->memoryLimit
/ 1048576 * 100 );
524 //echo "{$this->fuzzSeed}: $numSuccess/$numTotal (mem: $usage%)\n";
526 $ret = "Out of memory:\n";
527 $memStats = $this->getMemoryBreakdown();
529 foreach ( $memStats as $name => $usage ) {
530 $ret .= "$name: $usage\n";
533 throw new MWException( $ret );
542 //Various getter functions
545 * Get an input dictionary from a set of parser test files
547 function getFuzzInput( $filenames ) {
550 foreach ( $filenames as $filename ) {
551 $contents = file_get_contents( $filename );
552 preg_match_all( '/!!\s*input\n(.*?)\n!!\s*result/s', $contents, $matches );
554 foreach ( $matches[1] as $match ) {
555 $dict .= $match . "\n";
563 * Get a memory usage breakdown
565 function getMemoryBreakdown() {
568 foreach ( $GLOBALS as $name => $value ) {
569 $memStats['$' . $name] = strlen( serialize( $value ) );
572 $classes = get_declared_classes();
574 foreach ( $classes as $class ) {
575 $rc = new ReflectionClass( $class );
576 $props = $rc->getStaticProperties();
577 $memStats[$class] = strlen( serialize( $props ) );
578 $methods = $rc->getMethods();
580 foreach ( $methods as $method ) {
581 $memStats[$class] +
= strlen( serialize( $method->getStaticVariables() ) );
585 $functions = get_defined_functions();
587 foreach ( $functions['user'] as $function ) {
588 $rf = new ReflectionFunction( $function );
589 $memStats["$function()"] = strlen( serialize( $rf->getStaticVariables() ) );
598 * Get a Parser object
600 function getParser( $preprocessor = null ) {
601 global $wgParserConf;
603 $class = $wgParserConf['class'];
604 $parser = new $class( array( 'preprocessorClass' => $preprocessor ) +
$wgParserConf );
606 wfRunHooks( 'ParserTestParser', array( &$parser ) );
611 //Various action functions
613 public function addArticle( $name, $text, $line ) {
614 self
::$articles[$name] = $text;
617 public function publishTestArticles() {
618 if ( empty( self
::$articles ) ) {
622 foreach ( self
::$articles as $name => $text ) {
623 $title = Title
::newFromText( $name );
625 if ( $title->getArticleID( Title
::GAID_FOR_UPDATE
) == 0 ) {
626 ParserTest
::addArticle( $name, $text );
632 * Steal a callback function from the primary parser, save it for
633 * application to our scary parser. If the hook is not installed,
634 * abort processing of this file.
636 * @param $name String
637 * @return Bool true if tag hook is present
639 public function requireHook( $name ) {
641 $wgParser->firstCallInit( ); // make sure hooks are loaded.
642 return isset( $wgParser->mTagHooks
[$name] );
645 public function requireFunctionHook( $name ) {
647 $wgParser->firstCallInit( ); // make sure hooks are loaded.
648 return isset( $wgParser->mFunctionHooks
[$name] );
650 //Various "cleanup" functions
653 * Run the "tidy" command on text if the $wgUseTidy
656 * @param $text String: the text to tidy
660 protected function tidy( $text ) {
664 $text = MWTidy
::tidy( $text );
671 * Remove last character if it is a newline
673 public function removeEndingNewline( $s ) {
674 if ( substr( $s, -1 ) === "\n" ) {
675 return substr( $s, 0, -1 );
682 public function showRunFile( $file ) {
686 //Test options parser functions
688 protected function parseOptions( $instring ) {
694 // foo=bar,"baz quux"
718 \[\[[^]]*\]\] # Link target
726 if ( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER
) ) {
727 foreach ( $matches as $bits ) {
728 array_shift( $bits );
729 $key = strtolower( array_shift( $bits ) );
730 if ( count( $bits ) == 0 ) {
732 } elseif ( count( $bits ) == 1 ) {
733 $opts[$key] = $this->cleanupOption( array_shift( $bits ) );
736 $opts[$key] = array_map( array( $this, 'cleanupOption' ), $bits );
743 protected function cleanupOption( $opt ) {
744 if ( substr( $opt, 0, 1 ) == '"' ) {
745 return substr( $opt, 1, -1 );
748 if ( substr( $opt, 0, 2 ) == '[[' ) {
749 return substr( $opt, 2, -2 );
755 * Use a regex to find out the value of an option
756 * @param $key String: name of option val to retrieve
757 * @param $opts Options array to look in
758 * @param $default Mixed: default value returned if not found
760 protected static function getOptionValue( $key, $opts, $default ) {
761 $key = strtolower( $key );
763 if ( isset( $opts[$key] ) ) {