4 * Although marked as a stub, can work independently.
10 class NewParserTest
extends MediaWikiTestCase
{
11 static protected $articles = array(); // Array of test articles defined by the tests
12 /* The data provider is run on a different instance than the test, so it must be static
13 * When running tests from several files, all tests will see all articles.
15 static protected $backendToUse;
17 public $keepUploads = false;
18 public $runDisabled = false;
19 public $runParsoid = false;
21 public $showProgress = true;
22 public $savedWeirdGlobals = array();
23 public $savedGlobals = array();
24 public $hooks = array();
25 public $functionHooks = array();
28 public $maxFuzzTestLength = 300;
30 public $memoryLimit = 50;
32 protected $file = false;
34 protected function setUp() {
35 global $wgNamespaceAliases;
41 if ( $this->getCliArg( 'regex=' ) ) {
42 $this->regex
= $this->getCliArg( 'regex=' );
48 $this->keepUploads
= $this->getCliArg( 'keep-uploads' );
50 $tmpGlobals = array();
52 $tmpGlobals['wgLanguageCode'] = 'en';
53 $tmpGlobals['wgContLang'] = Language
::factory( 'en' );
54 $tmpGlobals['wgSitename'] = 'MediaWiki';
55 $tmpGlobals['wgServer'] = 'http://example.org';
56 $tmpGlobals['wgScript'] = '/index.php';
57 $tmpGlobals['wgScriptPath'] = '/';
58 $tmpGlobals['wgArticlePath'] = '/wiki/$1';
59 $tmpGlobals['wgActionPaths'] = array();
60 $tmpGlobals['wgVariantArticlePath'] = false;
61 $tmpGlobals['wgExtensionAssetsPath'] = '/extensions';
62 $tmpGlobals['wgStylePath'] = '/skins';
63 $tmpGlobals['wgEnableUploads'] = true;
64 $tmpGlobals['wgThumbnailScriptPath'] = false;
65 $tmpGlobals['wgLocalFileRepo'] = array(
66 'class' => 'LocalRepo',
68 'url' => 'http://example.com/images',
70 'transformVia404' => false,
71 'backend' => 'local-backend'
73 $tmpGlobals['wgForeignFileRepos'] = array();
74 $tmpGlobals['wgDefaultExternalStore'] = array();
75 $tmpGlobals['wgEnableParserCache'] = false;
76 $tmpGlobals['wgCapitalLinks'] = true;
77 $tmpGlobals['wgNoFollowLinks'] = true;
78 $tmpGlobals['wgNoFollowDomainExceptions'] = array();
79 $tmpGlobals['wgExternalLinkTarget'] = false;
80 $tmpGlobals['wgThumbnailScriptPath'] = false;
81 $tmpGlobals['wgUseImageResize'] = true;
82 $tmpGlobals['wgAllowExternalImages'] = true;
83 $tmpGlobals['wgRawHtml'] = false;
84 $tmpGlobals['wgUseTidy'] = false;
85 $tmpGlobals['wgAlwaysUseTidy'] = false;
86 $tmpGlobals['wgWellFormedXml'] = true;
87 $tmpGlobals['wgAllowMicrodataAttributes'] = true;
88 $tmpGlobals['wgExperimentalHtmlIds'] = false;
89 $tmpGlobals['wgAdaptiveMessageCache'] = true;
90 $tmpGlobals['wgUseDatabaseMessages'] = true;
91 $tmpGlobals['wgLocaltimezone'] = 'UTC';
92 $tmpGlobals['wgDeferredUpdateList'] = array();
93 $tmpGlobals['wgGroupPermissions'] = array(
95 'createaccount' => true,
101 $tmpGlobals['wgNamespaceProtection'] = array( NS_MEDIAWIKI
=> 'editinterface' );
103 $tmpGlobals['wgParser'] = new StubObject( 'wgParser', $GLOBALS['wgParserConf']['class'], array( $GLOBALS['wgParserConf'] ) );
105 $tmpGlobals['wgFileExtensions'][] = 'svg';
106 $tmpGlobals['wgSVGConverter'] = 'rsvg';
107 $tmpGlobals['wgSVGConverters']['rsvg'] = '$path/rsvg-convert -w $width -h $height $input -o $output';
109 if ( $GLOBALS['wgStyleDirectory'] === false ) {
110 $tmpGlobals['wgStyleDirectory'] = "$IP/skins";
113 # Replace all media handlers with a mock. We do not need to generate
114 # actual thumbnails to do parser testing, we only care about receiving
115 # a ThumbnailImage properly initialized.
116 global $wgMediaHandlers;
117 foreach ( $wgMediaHandlers as $type => $handler ) {
118 $tmpGlobals['wgMediaHandlers'][$type] = 'MockBitmapHandler';
120 // Vector images have to be handled slightly differently
121 $tmpGlobals['wgMediaHandlers']['image/svg+xml'] = 'MockSvgHandler';
123 $tmpHooks = $wgHooks;
124 $tmpHooks['ParserTestParser'][] = 'ParserTestParserHook::setup';
125 $tmpHooks['ParserGetVariableValueTs'][] = 'ParserTest::getFakeTimestamp';
126 $tmpGlobals['wgHooks'] = $tmpHooks;
128 $this->setMwGlobals( $tmpGlobals );
130 $this->savedWeirdGlobals
['image_alias'] = $wgNamespaceAliases['Image'];
131 $this->savedWeirdGlobals
['image_talk_alias'] = $wgNamespaceAliases['Image_talk'];
133 $wgNamespaceAliases['Image'] = NS_FILE
;
134 $wgNamespaceAliases['Image_talk'] = NS_FILE_TALK
;
137 protected function tearDown() {
138 global $wgNamespaceAliases;
140 $wgNamespaceAliases['Image'] = $this->savedWeirdGlobals
['image_alias'];
141 $wgNamespaceAliases['Image_talk'] = $this->savedWeirdGlobals
['image_talk_alias'];
144 RepoGroup
::destroySingleton();
145 FileBackendGroup
::destroySingleton();
147 // Remove temporary pages from the link cache
148 LinkCache
::singleton()->clear();
150 // Restore message cache (temporary pages and $wgUseDatabaseMessages)
151 MessageCache
::destroyInstance();
156 function addDBData() {
157 $this->tablesUsed
[] = 'site_stats';
158 $this->tablesUsed
[] = 'interwiki';
159 # disabled for performance
160 #$this->tablesUsed[] = 'image';
162 # Hack: insert a few Wikipedia in-project interwiki prefixes,
163 # for testing inter-language links
164 $this->db
->insert( 'interwiki', array(
165 array( 'iw_prefix' => 'wikipedia',
166 'iw_url' => 'http://en.wikipedia.org/wiki/$1',
170 array( 'iw_prefix' => 'meatball',
171 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
175 array( 'iw_prefix' => 'zh',
176 'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
180 array( 'iw_prefix' => 'es',
181 'iw_url' => 'http://es.wikipedia.org/wiki/$1',
185 array( 'iw_prefix' => 'fr',
186 'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
190 array( 'iw_prefix' => 'ru',
191 'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
196 * @todo Fixme! Why are we inserting duplicate data here? Shouldn't
197 * need this IGNORE or shouldn't need the insert at all.
199 ), __METHOD__
, array( 'IGNORE' )
202 # Update certain things in site_stats
203 $this->db
->insert( 'site_stats',
204 array( 'ss_row_id' => 1, 'ss_images' => 2, 'ss_good_articles' => 1 ),
208 $user = User
::newFromId( 0 );
209 LinkCache
::singleton()->clear(); # Avoids the odd failure at creating the nullRevision
211 # Upload DB table entries for files.
212 # We will upload the actual files later. Note that if anything causes LocalFile::load()
213 # to be triggered before then, it will break via maybeUpgrade() setting the fileExists
214 # member to false and storing it in cache.
215 # note that the size/width/height/bits/etc of the file
216 # are actually set by inspecting the file itself; the arguments
217 # to recordUpload2 have no effect. That said, we try to make things
218 # match up so it is less confusing to readers of the code & tests.
219 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Foobar.jpg' ) );
220 if ( !$this->db
->selectField( 'image', '1', array( 'img_name' => $image->getName() ) ) ) {
221 $image->recordUpload2(
223 'Upload of some lame file',
230 'media_type' => MEDIATYPE_BITMAP
,
231 'mime' => 'image/jpeg',
232 'metadata' => serialize( array() ),
233 'sha1' => wfBaseConvert( '1', 16, 36, 31 ),
234 'fileExists' => true ),
235 $this->db
->timestamp( '20010115123500' ), $user
239 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Thumb.png' ) );
240 if ( !$this->db
->selectField( 'image', '1', array( 'img_name' => $image->getName() ) ) ) {
241 $image->recordUpload2(
243 'Upload of some lame thumbnail',
244 'Some lame thumbnail',
250 'media_type' => MEDIATYPE_BITMAP
,
251 'mime' => 'image/png',
252 'metadata' => serialize( array() ),
253 'sha1' => wfBaseConvert( '2', 16, 36, 31 ),
254 'fileExists' => true ),
255 $this->db
->timestamp( '20130225203040' ), $user
259 # This image will be blacklisted in [[MediaWiki:Bad image list]]
260 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Bad.jpg' ) );
261 if ( !$this->db
->selectField( 'image', '1', array( 'img_name' => $image->getName() ) ) ) {
262 $image->recordUpload2(
271 'media_type' => MEDIATYPE_BITMAP
,
272 'mime' => 'image/jpeg',
273 'metadata' => serialize( array() ),
274 'sha1' => wfBaseConvert( '3', 16, 36, 31 ),
275 'fileExists' => true ),
276 $this->db
->timestamp( '20010115123500' ), $user
279 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Foobar.svg' ) );
280 if ( !$this->db
->selectField( 'image', '1', array( 'img_name' => $image->getName() ) ) ) {
281 $image->recordUpload2( '', 'Upload of some lame SVG', 'Some lame SVG', array(
286 'media_type' => MEDIATYPE_DRAWING
,
287 'mime' => 'image/svg+xml',
288 'metadata' => serialize( array() ),
289 'sha1' => wfBaseConvert( '', 16, 36, 31 ),
291 ), $this->db
->timestamp( '20010115123500' ), $user );
295 //ParserTest setup/teardown functions
298 * Set up the global variables for a consistent environment for each test.
299 * Ideally this should replace the global configuration entirely.
301 protected function setupGlobals( $opts = array(), $config = '' ) {
302 global $wgFileBackends;
303 # Find out values for some special options.
305 self
::getOptionValue( 'language', $opts, 'en' );
307 self
::getOptionValue( 'variant', $opts, false );
309 self
::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
310 $linkHolderBatchSize =
311 self
::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
313 $uploadDir = $this->getUploadDir();
314 if ( $this->getCliArg( 'use-filebackend=' ) ) {
315 if ( self
::$backendToUse ) {
316 $backend = self
::$backendToUse;
318 $name = $this->getCliArg( 'use-filebackend=' );
319 $useConfig = array();
320 foreach ( $wgFileBackends as $conf ) {
321 if ( $conf['name'] == $name ) {
325 $useConfig['name'] = 'local-backend'; // swap name
326 $class = $conf['class'];
327 self
::$backendToUse = new $class( $useConfig );
328 $backend = self
::$backendToUse;
331 # Replace with a mock. We do not care about generating real
332 # files on the filesystem, just need to expose the file
334 $backend = new MockFileBackend( array(
335 'name' => 'local-backend',
336 'lockManager' => 'nullLockManager',
337 'containerPaths' => array(
338 'local-public' => "$uploadDir",
339 'local-thumb' => "$uploadDir/thumb",
345 'wgLocalFileRepo' => array(
346 'class' => 'LocalRepo',
348 'url' => 'http://example.com/images',
350 'transformVia404' => false,
351 'backend' => $backend
353 'wgEnableUploads' => self
::getOptionValue( 'wgEnableUploads', $opts, true ),
354 'wgLanguageCode' => $lang,
355 'wgDBprefix' => $this->db
->getType() != 'oracle' ?
'unittest_' : 'ut_',
356 'wgRawHtml' => isset( $opts['rawhtml'] ),
357 'wgNamespacesWithSubpages' => array( NS_MAIN
=> isset( $opts['subpage'] ) ),
358 'wgMaxTocLevel' => $maxtoclevel,
359 'wgUseTeX' => isset( $opts['math'] ),
360 'wgMathDirectory' => $uploadDir . '/math',
361 'wgDefaultLanguageVariant' => $variant,
362 'wgLinkHolderBatchSize' => $linkHolderBatchSize,
366 $configLines = explode( "\n", $config );
368 foreach ( $configLines as $line ) {
369 list( $var, $value ) = explode( '=', $line, 2 );
371 $settings[$var] = eval( "return $value;" ); //???
375 $this->savedGlobals
= array();
378 wfRunHooks( 'ParserTestGlobals', array( &$settings ) );
380 $langObj = Language
::factory( $lang );
381 $settings['wgContLang'] = $langObj;
382 $settings['wgLang'] = $langObj;
384 $context = new RequestContext();
385 $settings['wgOut'] = $context->getOutput();
386 $settings['wgUser'] = $context->getUser();
387 $settings['wgRequest'] = $context->getRequest();
389 foreach ( $settings as $var => $val ) {
390 if ( array_key_exists( $var, $GLOBALS ) ) {
391 $this->savedGlobals
[$var] = $GLOBALS[$var];
394 $GLOBALS[$var] = $val;
397 MagicWord
::clearCache();
399 # The entries saved into RepoGroup cache with previous globals will be wrong.
400 RepoGroup
::destroySingleton();
401 FileBackendGroup
::destroySingleton();
403 # Create dummy files in storage
404 $this->setupUploads();
406 # Publish the articles after we have the final language set
407 $this->publishTestArticles();
409 MessageCache
::destroyInstance();
415 * Get an FS upload directory (only applies to FSFileBackend)
417 * @return String: the directory
419 protected function getUploadDir() {
420 if ( $this->keepUploads
) {
421 $dir = wfTempDir() . '/mwParser-images';
423 if ( is_dir( $dir ) ) {
427 $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
430 // wfDebug( "Creating upload directory $dir\n" );
431 if ( file_exists( $dir ) ) {
432 wfDebug( "Already exists!\n" );
441 * Create a dummy uploads directory which will contain a couple
442 * of files in order to pass existence tests.
444 * @return String: the directory
446 protected function setupUploads() {
449 $base = $this->getBaseDir();
450 $backend = RepoGroup
::singleton()->getLocalRepo()->getBackend();
451 $backend->prepare( array( 'dir' => "$base/local-public/3/3a" ) );
452 $backend->store( array(
453 'src' => "$IP/skins/monobook/headbg.jpg", 'dst' => "$base/local-public/3/3a/Foobar.jpg"
455 $backend->prepare( array( 'dir' => "$base/local-public/e/ea" ) );
456 $backend->store( array(
457 'src' => "$IP/skins/monobook/wiki.png", 'dst' => "$base/local-public/e/ea/Thumb.png"
459 $backend->prepare( array( 'dir' => "$base/local-public/0/09" ) );
460 $backend->store( array(
461 'src' => "$IP/skins/monobook/headbg.jpg", 'dst' => "$base/local-public/0/09/Bad.jpg"
464 // No helpful SVG file to copy, so make one ourselves
465 $tmpDir = wfTempDir();
466 $tempFsFile = new TempFSFile( "$tmpDir/Foobar.svg" );
467 $tempFsFile->autocollect(); // destroy file when $tempFsFile leaves scope
468 file_put_contents( "$tmpDir/Foobar.svg",
469 '<?xml version="1.0" encoding="utf-8"?>' .
470 '<svg xmlns="http://www.w3.org/2000/svg" width="200" height="200"><text>Foo</text></svg>' );
472 $backend->prepare( array( 'dir' => "$base/local-public/f/ff" ) );
473 $backend->quickStore( array(
474 'src' => "$tmpDir/Foobar.svg", 'dst' => "$base/local-public/f/ff/Foobar.svg"
479 * Restore default values and perform any necessary clean-up
480 * after each test runs.
482 protected function teardownGlobals() {
483 $this->teardownUploads();
485 foreach ( $this->savedGlobals
as $var => $val ) {
486 $GLOBALS[$var] = $val;
491 * Remove the dummy uploads directory
493 private function teardownUploads() {
494 if ( $this->keepUploads
) {
498 $backend = RepoGroup
::singleton()->getLocalRepo()->getBackend();
499 if ( $backend instanceof MockFileBackend
) {
500 # In memory backend, so dont bother cleaning them up.
504 $base = $this->getBaseDir();
505 // delete the files first, then the dirs.
508 "$base/local-public/3/3a/Foobar.jpg",
509 "$base/local-thumb/3/3a/Foobar.jpg/180px-Foobar.jpg",
510 "$base/local-thumb/3/3a/Foobar.jpg/200px-Foobar.jpg",
511 "$base/local-thumb/3/3a/Foobar.jpg/640px-Foobar.jpg",
512 "$base/local-thumb/3/3a/Foobar.jpg/120px-Foobar.jpg",
513 "$base/local-thumb/3/3a/Foobar.jpg/1280px-Foobar.jpg",
514 "$base/local-thumb/3/3a/Foobar.jpg/20px-Foobar.jpg",
515 "$base/local-thumb/3/3a/Foobar.jpg/270px-Foobar.jpg",
516 "$base/local-thumb/3/3a/Foobar.jpg/300px-Foobar.jpg",
517 "$base/local-thumb/3/3a/Foobar.jpg/30px-Foobar.jpg",
518 "$base/local-thumb/3/3a/Foobar.jpg/360px-Foobar.jpg",
519 "$base/local-thumb/3/3a/Foobar.jpg/400px-Foobar.jpg",
520 "$base/local-thumb/3/3a/Foobar.jpg/40px-Foobar.jpg",
521 "$base/local-thumb/3/3a/Foobar.jpg/70px-Foobar.jpg",
522 "$base/local-thumb/3/3a/Foobar.jpg/960px-Foobar.jpg",
524 "$base/local-public/e/ea/Thumb.png",
526 "$base/local-public/0/09/Bad.jpg",
528 "$base/local-public/f/ff/Foobar.svg",
529 "$base/local-thumb/f/ff/Foobar.svg/180px-Foobar.svg.jpg",
530 "$base/local-thumb/f/ff/Foobar.svg/270px-Foobar.svg.jpg",
531 "$base/local-thumb/f/ff/Foobar.svg/360px-Foobar.svg.jpg",
532 "$base/local-thumb/f/ff/Foobar.svg/langde-180px-Foobar.svg.jpg",
533 "$base/local-thumb/f/ff/Foobar.svg/langde-270px-Foobar.svg.jpg",
534 "$base/local-thumb/f/ff/Foobar.svg/langde-360px-Foobar.svg.jpg",
536 "$base/local-public/math/f/a/5/fa50b8b616463173474302ca3e63586b.png",
542 * Delete the specified files, if they exist.
543 * @param $files Array: full paths to files to delete.
545 private static function deleteFiles( $files ) {
546 $backend = RepoGroup
::singleton()->getLocalRepo()->getBackend();
547 foreach ( $files as $file ) {
548 $backend->delete( array( 'src' => $file ), array( 'force' => 1 ) );
550 foreach ( $files as $file ) {
552 while ( $tmp = FileBackend
::parentStoragePath( $tmp ) ) {
553 if ( !$backend->clean( array( 'dir' => $tmp ) )->isOK() ) {
560 protected function getBaseDir() {
561 return 'mwstore://local-backend';
564 public function parserTestProvider() {
565 if ( $this->file
=== false ) {
566 global $wgParserTestFiles;
567 $this->file
= $wgParserTestFiles[0];
570 return new TestFileIterator( $this->file
, $this );
574 * Set the file from whose tests will be run by this instance
576 public function setParserTestFile( $filename ) {
577 $this->file
= $filename;
582 * @dataProvider parserTestProvider
584 public function testParserTest( $desc, $input, $result, $opts, $config ) {
585 if ( $this->regex
!= '' && !preg_match( '/' . $this->regex
. '/', $desc ) ) {
586 $this->assertTrue( true ); // XXX: don't flood output with "test made no assertions"
587 //$this->markTestSkipped( 'Filtered out by the user' );
591 if ( !$this->isWikitextNS( NS_MAIN
) ) {
592 // parser tests frequently assume that the main namespace contains wikitext.
593 // @todo When setting up pages, force the content model. Only skip if
594 // $wgtContentModelUseDB is false.
595 $this->markTestSkipped( "Main namespace does not support wikitext,"
596 . "skipping parser test: $desc" );
599 wfDebug( "Running parser test: $desc\n" );
601 $opts = $this->parseOptions( $opts );
602 $context = $this->setupGlobals( $opts, $config );
604 $user = $context->getUser();
605 $options = ParserOptions
::newFromContext( $context );
607 if ( isset( $opts['title'] ) ) {
608 $titleText = $opts['title'];
610 $titleText = 'Parser test';
613 $local = isset( $opts['local'] );
614 $preprocessor = isset( $opts['preprocessor'] ) ?
$opts['preprocessor'] : null;
615 $parser = $this->getParser( $preprocessor );
617 $title = Title
::newFromText( $titleText );
619 if ( isset( $opts['pst'] ) ) {
620 $out = $parser->preSaveTransform( $input, $title, $user, $options );
621 } elseif ( isset( $opts['msg'] ) ) {
622 $out = $parser->transformMsg( $input, $options, $title );
623 } elseif ( isset( $opts['section'] ) ) {
624 $section = $opts['section'];
625 $out = $parser->getSection( $input, $section );
626 } elseif ( isset( $opts['replace'] ) ) {
627 $section = $opts['replace'][0];
628 $replace = $opts['replace'][1];
629 $out = $parser->replaceSection( $input, $section, $replace );
630 } elseif ( isset( $opts['comment'] ) ) {
631 $out = Linker
::formatComment( $input, $title, $local );
632 } elseif ( isset( $opts['preload'] ) ) {
633 $out = $parser->getPreloadText( $input, $title, $options );
635 $output = $parser->parse( $input, $title, $options, true, true, 1337 );
636 $out = $output->getText();
638 if ( isset( $opts['showtitle'] ) ) {
639 if ( $output->getTitleText() ) {
640 $title = $output->getTitleText();
643 $out = "$title\n$out";
646 if ( isset( $opts['ill'] ) ) {
647 $out = $this->tidy( implode( ' ', $output->getLanguageLinks() ) );
648 } elseif ( isset( $opts['cat'] ) ) {
649 $outputPage = $context->getOutput();
650 $outputPage->addCategoryLinks( $output->getCategories() );
651 $cats = $outputPage->getCategoryLinks();
653 if ( isset( $cats['normal'] ) ) {
654 $out = $this->tidy( implode( ' ', $cats['normal'] ) );
659 $parser->mPreprocessor
= null;
661 $result = $this->tidy( $result );
664 $this->teardownGlobals();
666 $this->assertEquals( $result, $out, $desc );
670 * Run a fuzz test series
671 * Draw input from a set of test files
673 * @todo fixme Needs some work to not eat memory until the world explodes
677 function testFuzzTests() {
678 global $wgParserTestFiles;
680 $files = $wgParserTestFiles;
682 if ( $this->getCliArg( 'file=' ) ) {
683 $files = array( $this->getCliArg( 'file=' ) );
686 $dict = $this->getFuzzInput( $files );
687 $dictSize = strlen( $dict );
688 $logMaxLength = log( $this->maxFuzzTestLength
);
690 ini_set( 'memory_limit', $this->memoryLimit
* 1048576 );
693 $opts = ParserOptions
::newFromUser( $user );
694 $title = Title
::makeTitle( NS_MAIN
, 'Parser_test' );
700 // Generate test input
701 mt_srand( ++
$this->fuzzSeed
);
702 $totalLength = mt_rand( 1, $this->maxFuzzTestLength
);
705 while ( strlen( $input ) < $totalLength ) {
706 $logHairLength = mt_rand( 0, 1000000 ) / 1000000 * $logMaxLength;
707 $hairLength = min( intval( exp( $logHairLength ) ), $dictSize );
708 $offset = mt_rand( 0, $dictSize - $hairLength );
709 $input .= substr( $dict, $offset, $hairLength );
712 $this->setupGlobals();
713 $parser = $this->getParser();
717 $parser->parse( $input, $title, $opts );
718 $this->assertTrue( true, "Test $id, fuzz seed {$this->fuzzSeed}" );
719 } catch ( Exception
$exception ) {
720 $input_dump = sprintf( "string(%d) \"%s\"\n", strlen( $input ), $input );
722 $this->assertTrue( false, "Test $id, fuzz seed {$this->fuzzSeed}. \n\nInput: $input_dump\n\nError: {$exception->getMessage()}\n\nBacktrace: {$exception->getTraceAsString()}" );
725 $this->teardownGlobals();
726 $parser->__destruct();
728 if ( $id %
100 == 0 ) {
729 $usage = intval( memory_get_usage( true ) / $this->memoryLimit
/ 1048576 * 100 );
730 //echo "{$this->fuzzSeed}: $numSuccess/$numTotal (mem: $usage%)\n";
732 $ret = "Out of memory:\n";
733 $memStats = $this->getMemoryBreakdown();
735 foreach ( $memStats as $name => $usage ) {
736 $ret .= "$name: $usage\n";
739 throw new MWException( $ret );
747 //Various getter functions
750 * Get an input dictionary from a set of parser test files
752 function getFuzzInput( $filenames ) {
755 foreach ( $filenames as $filename ) {
756 $contents = file_get_contents( $filename );
757 preg_match_all( '/!!\s*input\n(.*?)\n!!\s*result/s', $contents, $matches );
759 foreach ( $matches[1] as $match ) {
760 $dict .= $match . "\n";
768 * Get a memory usage breakdown
770 function getMemoryBreakdown() {
773 foreach ( $GLOBALS as $name => $value ) {
774 $memStats['$' . $name] = strlen( serialize( $value ) );
777 $classes = get_declared_classes();
779 foreach ( $classes as $class ) {
780 $rc = new ReflectionClass( $class );
781 $props = $rc->getStaticProperties();
782 $memStats[$class] = strlen( serialize( $props ) );
783 $methods = $rc->getMethods();
785 foreach ( $methods as $method ) {
786 $memStats[$class] +
= strlen( serialize( $method->getStaticVariables() ) );
790 $functions = get_defined_functions();
792 foreach ( $functions['user'] as $function ) {
793 $rf = new ReflectionFunction( $function );
794 $memStats["$function()"] = strlen( serialize( $rf->getStaticVariables() ) );
803 * Get a Parser object
805 function getParser( $preprocessor = null ) {
806 global $wgParserConf;
808 $class = $wgParserConf['class'];
809 $parser = new $class( array( 'preprocessorClass' => $preprocessor ) +
$wgParserConf );
811 wfRunHooks( 'ParserTestParser', array( &$parser ) );
816 //Various action functions
818 public function addArticle( $name, $text, $line ) {
819 self
::$articles[$name] = array( $text, $line );
822 public function publishTestArticles() {
823 if ( empty( self
::$articles ) ) {
827 foreach ( self
::$articles as $name => $info ) {
828 list( $text, $line ) = $info;
829 ParserTest
::addArticle( $name, $text, $line, 'ignoreduplicate' );
834 * Steal a callback function from the primary parser, save it for
835 * application to our scary parser. If the hook is not installed,
836 * abort processing of this file.
838 * @param $name String
839 * @return Bool true if tag hook is present
841 public function requireHook( $name ) {
843 $wgParser->firstCallInit(); // make sure hooks are loaded.
844 return isset( $wgParser->mTagHooks
[$name] );
847 public function requireFunctionHook( $name ) {
849 $wgParser->firstCallInit(); // make sure hooks are loaded.
850 return isset( $wgParser->mFunctionHooks
[$name] );
853 //Various "cleanup" functions
856 * Run the "tidy" command on text if the $wgUseTidy
859 * @param $text String: the text to tidy
862 protected function tidy( $text ) {
866 $text = MWTidy
::tidy( $text );
873 * Remove last character if it is a newline
875 public function removeEndingNewline( $s ) {
876 if ( substr( $s, -1 ) === "\n" ) {
877 return substr( $s, 0, -1 );
883 //Test options parser functions
885 protected function parseOptions( $instring ) {
891 // foo=bar,"baz quux"
915 \[\[[^]]*\]\] # Link target
923 if ( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER
) ) {
924 foreach ( $matches as $bits ) {
925 array_shift( $bits );
926 $key = strtolower( array_shift( $bits ) );
927 if ( count( $bits ) == 0 ) {
929 } elseif ( count( $bits ) == 1 ) {
930 $opts[$key] = $this->cleanupOption( array_shift( $bits ) );
933 $opts[$key] = array_map( array( $this, 'cleanupOption' ), $bits );
941 protected function cleanupOption( $opt ) {
942 if ( substr( $opt, 0, 1 ) == '"' ) {
943 return substr( $opt, 1, -1 );
946 if ( substr( $opt, 0, 2 ) == '[[' ) {
947 return substr( $opt, 2, -2 );
954 * Use a regex to find out the value of an option
955 * @param $key String: name of option val to retrieve
956 * @param $opts Options array to look in
957 * @param $default Mixed: default value returned if not found
959 protected static function getOptionValue( $key, $opts, $default ) {
960 $key = strtolower( $key );
962 if ( isset( $opts[$key] ) ) {