ab8e77b172059fdc36e5082a3f00b2b96831406d
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 public static function setUpBeforeClass() {
35 // Inject ParserTest well-known interwikis
36 ParserTest
::setupInterwikis();
39 protected function setUp() {
40 global $wgNamespaceAliases, $wgContLang;
46 if ( $this->getCliArg( 'regex=' ) ) {
47 $this->regex
= $this->getCliArg( 'regex=' );
53 $this->keepUploads
= $this->getCliArg( 'keep-uploads' );
55 $tmpGlobals = array();
57 $tmpGlobals['wgLanguageCode'] = 'en';
58 $tmpGlobals['wgContLang'] = Language
::factory( 'en' );
59 $tmpGlobals['wgSitename'] = 'MediaWiki';
60 $tmpGlobals['wgServer'] = 'http://example.org';
61 $tmpGlobals['wgScript'] = '/index.php';
62 $tmpGlobals['wgScriptPath'] = '/';
63 $tmpGlobals['wgArticlePath'] = '/wiki/$1';
64 $tmpGlobals['wgActionPaths'] = array();
65 $tmpGlobals['wgVariantArticlePath'] = false;
66 $tmpGlobals['wgExtensionAssetsPath'] = '/extensions';
67 $tmpGlobals['wgStylePath'] = '/skins';
68 $tmpGlobals['wgEnableUploads'] = true;
69 $tmpGlobals['wgThumbnailScriptPath'] = false;
70 $tmpGlobals['wgLocalFileRepo'] = array(
71 'class' => 'LocalRepo',
73 'url' => 'http://example.com/images',
75 'transformVia404' => false,
76 'backend' => 'local-backend'
78 $tmpGlobals['wgForeignFileRepos'] = array();
79 $tmpGlobals['wgDefaultExternalStore'] = array();
80 $tmpGlobals['wgEnableParserCache'] = false;
81 $tmpGlobals['wgCapitalLinks'] = true;
82 $tmpGlobals['wgNoFollowLinks'] = true;
83 $tmpGlobals['wgNoFollowDomainExceptions'] = array();
84 $tmpGlobals['wgExternalLinkTarget'] = false;
85 $tmpGlobals['wgThumbnailScriptPath'] = false;
86 $tmpGlobals['wgUseImageResize'] = true;
87 $tmpGlobals['wgAllowExternalImages'] = true;
88 $tmpGlobals['wgRawHtml'] = false;
89 $tmpGlobals['wgUseTidy'] = false;
90 $tmpGlobals['wgAlwaysUseTidy'] = false;
91 $tmpGlobals['wgWellFormedXml'] = true;
92 $tmpGlobals['wgAllowMicrodataAttributes'] = true;
93 $tmpGlobals['wgExperimentalHtmlIds'] = false;
94 $tmpGlobals['wgAdaptiveMessageCache'] = true;
95 $tmpGlobals['wgUseDatabaseMessages'] = true;
96 $tmpGlobals['wgLocaltimezone'] = 'UTC';
97 $tmpGlobals['wgDeferredUpdateList'] = array();
98 $tmpGlobals['wgGroupPermissions'] = array(
100 'createaccount' => true,
103 'createpage' => true,
104 'createtalk' => true,
106 $tmpGlobals['wgNamespaceProtection'] = array( NS_MEDIAWIKI
=> 'editinterface' );
108 $tmpGlobals['wgParser'] = new StubObject(
109 'wgParser', $GLOBALS['wgParserConf']['class'],
110 array( $GLOBALS['wgParserConf'] ) );
112 $tmpGlobals['wgFileExtensions'][] = 'svg';
113 $tmpGlobals['wgSVGConverter'] = 'rsvg';
114 $tmpGlobals['wgSVGConverters']['rsvg'] =
115 '$path/rsvg-convert -w $width -h $height $input -o $output';
117 if ( $GLOBALS['wgStyleDirectory'] === false ) {
118 $tmpGlobals['wgStyleDirectory'] = "$IP/skins";
121 # Replace all media handlers with a mock. We do not need to generate
122 # actual thumbnails to do parser testing, we only care about receiving
123 # a ThumbnailImage properly initialized.
124 global $wgMediaHandlers;
125 foreach ( $wgMediaHandlers as $type => $handler ) {
126 $tmpGlobals['wgMediaHandlers'][$type] = 'MockBitmapHandler';
128 // Vector images have to be handled slightly differently
129 $tmpGlobals['wgMediaHandlers']['image/svg+xml'] = 'MockSvgHandler';
131 $tmpHooks = $wgHooks;
132 $tmpHooks['ParserTestParser'][] = 'ParserTestParserHook::setup';
133 $tmpHooks['ParserGetVariableValueTs'][] = 'ParserTest::getFakeTimestamp';
134 $tmpGlobals['wgHooks'] = $tmpHooks;
135 # add a namespace shadowing a interwiki link, to test
136 # proper precedence when resolving links. (bug 51680)
137 $tmpGlobals['wgExtraNamespaces'] = array( 100 => 'MemoryAlpha' );
139 $this->setMwGlobals( $tmpGlobals );
141 $this->savedWeirdGlobals
['image_alias'] = $wgNamespaceAliases['Image'];
142 $this->savedWeirdGlobals
['image_talk_alias'] = $wgNamespaceAliases['Image_talk'];
144 $wgNamespaceAliases['Image'] = NS_FILE
;
145 $wgNamespaceAliases['Image_talk'] = NS_FILE_TALK
;
147 MWNamespace
::getCanonicalNamespaces( true ); # reset namespace cache
148 $wgContLang->resetNamespaces(); # reset namespace cache
151 protected function tearDown() {
152 global $wgNamespaceAliases, $wgContLang;
154 $wgNamespaceAliases['Image'] = $this->savedWeirdGlobals
['image_alias'];
155 $wgNamespaceAliases['Image_talk'] = $this->savedWeirdGlobals
['image_talk_alias'];
158 RepoGroup
::destroySingleton();
159 FileBackendGroup
::destroySingleton();
161 // Remove temporary pages from the link cache
162 LinkCache
::singleton()->clear();
164 // Restore message cache (temporary pages and $wgUseDatabaseMessages)
165 MessageCache
::destroyInstance();
169 MWNamespace
::getCanonicalNamespaces( true ); # reset namespace cache
170 $wgContLang->resetNamespaces(); # reset namespace cache
173 public static function tearDownAfterClass() {
174 ParserTest
::tearDownInterwikis();
175 parent
::tearDownAfterClass();
178 function addDBData() {
179 $this->tablesUsed
[] = 'site_stats';
180 # disabled for performance
181 #$this->tablesUsed[] = 'image';
183 # Update certain things in site_stats
184 $this->db
->insert( 'site_stats',
185 array( 'ss_row_id' => 1, 'ss_images' => 2, 'ss_good_articles' => 1 ),
189 $user = User
::newFromId( 0 );
190 LinkCache
::singleton()->clear(); # Avoids the odd failure at creating the nullRevision
192 # Upload DB table entries for files.
193 # We will upload the actual files later. Note that if anything causes LocalFile::load()
194 # to be triggered before then, it will break via maybeUpgrade() setting the fileExists
195 # member to false and storing it in cache.
196 # note that the size/width/height/bits/etc of the file
197 # are actually set by inspecting the file itself; the arguments
198 # to recordUpload2 have no effect. That said, we try to make things
199 # match up so it is less confusing to readers of the code & tests.
200 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Foobar.jpg' ) );
201 if ( !$this->db
->selectField( 'image', '1', array( 'img_name' => $image->getName() ) ) ) {
202 $image->recordUpload2(
204 'Upload of some lame file',
211 'media_type' => MEDIATYPE_BITMAP
,
212 'mime' => 'image/jpeg',
213 'metadata' => serialize( array() ),
214 'sha1' => wfBaseConvert( '1', 16, 36, 31 ),
215 'fileExists' => true ),
216 $this->db
->timestamp( '20010115123500' ), $user
220 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Thumb.png' ) );
221 if ( !$this->db
->selectField( 'image', '1', array( 'img_name' => $image->getName() ) ) ) {
222 $image->recordUpload2(
224 'Upload of some lame thumbnail',
225 'Some lame thumbnail',
231 'media_type' => MEDIATYPE_BITMAP
,
232 'mime' => 'image/png',
233 'metadata' => serialize( array() ),
234 'sha1' => wfBaseConvert( '2', 16, 36, 31 ),
235 'fileExists' => true ),
236 $this->db
->timestamp( '20130225203040' ), $user
240 # This image will be blacklisted in [[MediaWiki:Bad image list]]
241 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Bad.jpg' ) );
242 if ( !$this->db
->selectField( 'image', '1', array( 'img_name' => $image->getName() ) ) ) {
243 $image->recordUpload2(
252 'media_type' => MEDIATYPE_BITMAP
,
253 'mime' => 'image/jpeg',
254 'metadata' => serialize( array() ),
255 'sha1' => wfBaseConvert( '3', 16, 36, 31 ),
256 'fileExists' => true ),
257 $this->db
->timestamp( '20010115123500' ), $user
260 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Foobar.svg' ) );
261 if ( !$this->db
->selectField( 'image', '1', array( 'img_name' => $image->getName() ) ) ) {
262 $image->recordUpload2( '', 'Upload of some lame SVG', 'Some lame SVG', array(
267 'media_type' => MEDIATYPE_DRAWING
,
268 'mime' => 'image/svg+xml',
269 'metadata' => serialize( array() ),
270 'sha1' => wfBaseConvert( '', 16, 36, 31 ),
272 ), $this->db
->timestamp( '20010115123500' ), $user );
276 //ParserTest setup/teardown functions
279 * Set up the global variables for a consistent environment for each test.
280 * Ideally this should replace the global configuration entirely.
282 protected function setupGlobals( $opts = array(), $config = '' ) {
283 global $wgFileBackends;
284 # Find out values for some special options.
286 self
::getOptionValue( 'language', $opts, 'en' );
288 self
::getOptionValue( 'variant', $opts, false );
290 self
::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
291 $linkHolderBatchSize =
292 self
::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
294 $uploadDir = $this->getUploadDir();
295 if ( $this->getCliArg( 'use-filebackend=' ) ) {
296 if ( self
::$backendToUse ) {
297 $backend = self
::$backendToUse;
299 $name = $this->getCliArg( 'use-filebackend=' );
300 $useConfig = array();
301 foreach ( $wgFileBackends as $conf ) {
302 if ( $conf['name'] == $name ) {
306 $useConfig['name'] = 'local-backend'; // swap name
307 $class = $conf['class'];
308 self
::$backendToUse = new $class( $useConfig );
309 $backend = self
::$backendToUse;
312 # Replace with a mock. We do not care about generating real
313 # files on the filesystem, just need to expose the file
315 $backend = new MockFileBackend( array(
316 'name' => 'local-backend',
317 'lockManager' => 'nullLockManager',
318 'containerPaths' => array(
319 'local-public' => "$uploadDir",
320 'local-thumb' => "$uploadDir/thumb",
326 'wgLocalFileRepo' => array(
327 'class' => 'LocalRepo',
329 'url' => 'http://example.com/images',
331 'transformVia404' => false,
332 'backend' => $backend
334 'wgEnableUploads' => self
::getOptionValue( 'wgEnableUploads', $opts, true ),
335 'wgLanguageCode' => $lang,
336 'wgDBprefix' => $this->db
->getType() != 'oracle' ?
'unittest_' : 'ut_',
337 'wgRawHtml' => self
::getOptionValue( 'wgRawHtml', $opts, false ),
338 'wgNamespacesWithSubpages' => array( NS_MAIN
=> isset( $opts['subpage'] ) ),
339 'wgAllowExternalImages' => self
::getOptionValue( 'wgAllowExternalImages', $opts, true ),
340 'wgMaxTocLevel' => $maxtoclevel,
341 'wgUseTeX' => isset( $opts['math'] ) ||
isset( $opts['texvc'] ),
342 'wgMathDirectory' => $uploadDir . '/math',
343 'wgDefaultLanguageVariant' => $variant,
344 'wgLinkHolderBatchSize' => $linkHolderBatchSize,
348 $configLines = explode( "\n", $config );
350 foreach ( $configLines as $line ) {
351 list( $var, $value ) = explode( '=', $line, 2 );
353 $settings[$var] = eval( "return $value;" ); //???
357 $this->savedGlobals
= array();
360 wfRunHooks( 'ParserTestGlobals', array( &$settings ) );
362 $langObj = Language
::factory( $lang );
363 $settings['wgContLang'] = $langObj;
364 $settings['wgLang'] = $langObj;
366 $context = new RequestContext();
367 $settings['wgOut'] = $context->getOutput();
368 $settings['wgUser'] = $context->getUser();
369 $settings['wgRequest'] = $context->getRequest();
371 foreach ( $settings as $var => $val ) {
372 if ( array_key_exists( $var, $GLOBALS ) ) {
373 $this->savedGlobals
[$var] = $GLOBALS[$var];
376 $GLOBALS[$var] = $val;
379 MagicWord
::clearCache();
381 # The entries saved into RepoGroup cache with previous globals will be wrong.
382 RepoGroup
::destroySingleton();
383 FileBackendGroup
::destroySingleton();
385 # Create dummy files in storage
386 $this->setupUploads();
388 # Publish the articles after we have the final language set
389 $this->publishTestArticles();
391 MessageCache
::destroyInstance();
397 * Get an FS upload directory (only applies to FSFileBackend)
399 * @return String: the directory
401 protected function getUploadDir() {
402 if ( $this->keepUploads
) {
403 $dir = wfTempDir() . '/mwParser-images';
405 if ( is_dir( $dir ) ) {
409 $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
412 // wfDebug( "Creating upload directory $dir\n" );
413 if ( file_exists( $dir ) ) {
414 wfDebug( "Already exists!\n" );
423 * Create a dummy uploads directory which will contain a couple
424 * of files in order to pass existence tests.
426 * @return String: the directory
428 protected function setupUploads() {
431 $base = $this->getBaseDir();
432 $backend = RepoGroup
::singleton()->getLocalRepo()->getBackend();
433 $backend->prepare( array( 'dir' => "$base/local-public/3/3a" ) );
434 $backend->store( array(
435 'src' => "$IP/skins/monobook/headbg.jpg", 'dst' => "$base/local-public/3/3a/Foobar.jpg"
437 $backend->prepare( array( 'dir' => "$base/local-public/e/ea" ) );
438 $backend->store( array(
439 'src' => "$IP/skins/monobook/wiki.png", 'dst' => "$base/local-public/e/ea/Thumb.png"
441 $backend->prepare( array( 'dir' => "$base/local-public/0/09" ) );
442 $backend->store( array(
443 'src' => "$IP/skins/monobook/headbg.jpg", 'dst' => "$base/local-public/0/09/Bad.jpg"
446 // No helpful SVG file to copy, so make one ourselves
447 $tmpDir = wfTempDir();
448 $tempFsFile = new TempFSFile( "$tmpDir/Foobar.svg" );
449 $tempFsFile->autocollect(); // destroy file when $tempFsFile leaves scope
450 file_put_contents( "$tmpDir/Foobar.svg",
451 '<?xml version="1.0" encoding="utf-8"?>' .
452 '<svg xmlns="http://www.w3.org/2000/svg" width="200" height="200"><text>Foo</text></svg>' );
454 $backend->prepare( array( 'dir' => "$base/local-public/f/ff" ) );
455 $backend->quickStore( array(
456 'src' => "$tmpDir/Foobar.svg", 'dst' => "$base/local-public/f/ff/Foobar.svg"
461 * Restore default values and perform any necessary clean-up
462 * after each test runs.
464 protected function teardownGlobals() {
465 $this->teardownUploads();
467 foreach ( $this->savedGlobals
as $var => $val ) {
468 $GLOBALS[$var] = $val;
473 * Remove the dummy uploads directory
475 private function teardownUploads() {
476 if ( $this->keepUploads
) {
480 $backend = RepoGroup
::singleton()->getLocalRepo()->getBackend();
481 if ( $backend instanceof MockFileBackend
) {
482 # In memory backend, so dont bother cleaning them up.
486 $base = $this->getBaseDir();
487 // delete the files first, then the dirs.
490 "$base/local-public/3/3a/Foobar.jpg",
491 "$base/local-thumb/3/3a/Foobar.jpg/180px-Foobar.jpg",
492 "$base/local-thumb/3/3a/Foobar.jpg/200px-Foobar.jpg",
493 "$base/local-thumb/3/3a/Foobar.jpg/640px-Foobar.jpg",
494 "$base/local-thumb/3/3a/Foobar.jpg/120px-Foobar.jpg",
495 "$base/local-thumb/3/3a/Foobar.jpg/1280px-Foobar.jpg",
496 "$base/local-thumb/3/3a/Foobar.jpg/20px-Foobar.jpg",
497 "$base/local-thumb/3/3a/Foobar.jpg/270px-Foobar.jpg",
498 "$base/local-thumb/3/3a/Foobar.jpg/300px-Foobar.jpg",
499 "$base/local-thumb/3/3a/Foobar.jpg/30px-Foobar.jpg",
500 "$base/local-thumb/3/3a/Foobar.jpg/360px-Foobar.jpg",
501 "$base/local-thumb/3/3a/Foobar.jpg/400px-Foobar.jpg",
502 "$base/local-thumb/3/3a/Foobar.jpg/40px-Foobar.jpg",
503 "$base/local-thumb/3/3a/Foobar.jpg/70px-Foobar.jpg",
504 "$base/local-thumb/3/3a/Foobar.jpg/960px-Foobar.jpg",
506 "$base/local-public/e/ea/Thumb.png",
508 "$base/local-public/0/09/Bad.jpg",
510 "$base/local-public/f/ff/Foobar.svg",
511 "$base/local-thumb/f/ff/Foobar.svg/180px-Foobar.svg.jpg",
512 "$base/local-thumb/f/ff/Foobar.svg/270px-Foobar.svg.jpg",
513 "$base/local-thumb/f/ff/Foobar.svg/360px-Foobar.svg.jpg",
514 "$base/local-thumb/f/ff/Foobar.svg/langde-180px-Foobar.svg.jpg",
515 "$base/local-thumb/f/ff/Foobar.svg/langde-270px-Foobar.svg.jpg",
516 "$base/local-thumb/f/ff/Foobar.svg/langde-360px-Foobar.svg.jpg",
518 "$base/local-public/math/f/a/5/fa50b8b616463173474302ca3e63586b.png",
524 * Delete the specified files, if they exist.
525 * @param $files Array: full paths to files to delete.
527 private static function deleteFiles( $files ) {
528 $backend = RepoGroup
::singleton()->getLocalRepo()->getBackend();
529 foreach ( $files as $file ) {
530 $backend->delete( array( 'src' => $file ), array( 'force' => 1 ) );
532 foreach ( $files as $file ) {
534 while ( $tmp = FileBackend
::parentStoragePath( $tmp ) ) {
535 if ( !$backend->clean( array( 'dir' => $tmp ) )->isOK() ) {
542 protected function getBaseDir() {
543 return 'mwstore://local-backend';
546 public function parserTestProvider() {
547 if ( $this->file
=== false ) {
548 global $wgParserTestFiles;
549 $this->file
= $wgParserTestFiles[0];
552 return new TestFileIterator( $this->file
, $this );
556 * Set the file from whose tests will be run by this instance
558 public function setParserTestFile( $filename ) {
559 $this->file
= $filename;
564 * @dataProvider parserTestProvider
566 public function testParserTest( $desc, $input, $result, $opts, $config ) {
567 if ( $this->regex
!= '' && !preg_match( '/' . $this->regex
. '/', $desc ) ) {
568 $this->assertTrue( true ); // XXX: don't flood output with "test made no assertions"
569 //$this->markTestSkipped( 'Filtered out by the user' );
573 if ( !$this->isWikitextNS( NS_MAIN
) ) {
574 // parser tests frequently assume that the main namespace contains wikitext.
575 // @todo When setting up pages, force the content model. Only skip if
576 // $wgtContentModelUseDB is false.
577 $this->markTestSkipped( "Main namespace does not support wikitext,"
578 . "skipping parser test: $desc" );
581 wfDebug( "Running parser test: $desc\n" );
583 $opts = $this->parseOptions( $opts );
584 $context = $this->setupGlobals( $opts, $config );
586 $user = $context->getUser();
587 $options = ParserOptions
::newFromContext( $context );
589 if ( isset( $opts['title'] ) ) {
590 $titleText = $opts['title'];
592 $titleText = 'Parser test';
595 $local = isset( $opts['local'] );
596 $preprocessor = isset( $opts['preprocessor'] ) ?
$opts['preprocessor'] : null;
597 $parser = $this->getParser( $preprocessor );
599 $title = Title
::newFromText( $titleText );
601 # Parser test requiring math. Make sure texvc is executable
602 # or just skip such tests.
603 if ( isset( $opts['math'] ) ||
isset( $opts['texvc'] ) ) {
606 if ( !isset( $wgTexvc ) ) {
607 $this->markTestSkipped( "SKIPPED: \$wgTexvc is not set" );
608 } elseif ( !is_executable( $wgTexvc ) ) {
609 $this->markTestSkipped( "SKIPPED: texvc binary does not exist"
610 . " or is not executable.\n"
611 . "Current configuration is:\n\$wgTexvc = '$wgTexvc'" );
615 if ( isset( $opts['pst'] ) ) {
616 $out = $parser->preSaveTransform( $input, $title, $user, $options );
617 } elseif ( isset( $opts['msg'] ) ) {
618 $out = $parser->transformMsg( $input, $options, $title );
619 } elseif ( isset( $opts['section'] ) ) {
620 $section = $opts['section'];
621 $out = $parser->getSection( $input, $section );
622 } elseif ( isset( $opts['replace'] ) ) {
623 $section = $opts['replace'][0];
624 $replace = $opts['replace'][1];
625 $out = $parser->replaceSection( $input, $section, $replace );
626 } elseif ( isset( $opts['comment'] ) ) {
627 $out = Linker
::formatComment( $input, $title, $local );
628 } elseif ( isset( $opts['preload'] ) ) {
629 $out = $parser->getPreloadText( $input, $title, $options );
631 $output = $parser->parse( $input, $title, $options, true, true, 1337 );
632 $out = $output->getText();
634 if ( isset( $opts['showtitle'] ) ) {
635 if ( $output->getTitleText() ) {
636 $title = $output->getTitleText();
639 $out = "$title\n$out";
642 if ( isset( $opts['ill'] ) ) {
643 $out = $this->tidy( implode( ' ', $output->getLanguageLinks() ) );
644 } elseif ( isset( $opts['cat'] ) ) {
645 $outputPage = $context->getOutput();
646 $outputPage->addCategoryLinks( $output->getCategories() );
647 $cats = $outputPage->getCategoryLinks();
649 if ( isset( $cats['normal'] ) ) {
650 $out = $this->tidy( implode( ' ', $cats['normal'] ) );
655 $parser->mPreprocessor
= null;
657 $result = $this->tidy( $result );
660 $this->teardownGlobals();
662 $this->assertEquals( $result, $out, $desc );
666 * Run a fuzz test series
667 * Draw input from a set of test files
669 * @todo fixme Needs some work to not eat memory until the world explodes
673 function testFuzzTests() {
674 global $wgParserTestFiles;
676 $files = $wgParserTestFiles;
678 if ( $this->getCliArg( 'file=' ) ) {
679 $files = array( $this->getCliArg( 'file=' ) );
682 $dict = $this->getFuzzInput( $files );
683 $dictSize = strlen( $dict );
684 $logMaxLength = log( $this->maxFuzzTestLength
);
686 ini_set( 'memory_limit', $this->memoryLimit
* 1048576 );
689 $opts = ParserOptions
::newFromUser( $user );
690 $title = Title
::makeTitle( NS_MAIN
, 'Parser_test' );
696 // Generate test input
697 mt_srand( ++
$this->fuzzSeed
);
698 $totalLength = mt_rand( 1, $this->maxFuzzTestLength
);
701 while ( strlen( $input ) < $totalLength ) {
702 $logHairLength = mt_rand( 0, 1000000 ) / 1000000 * $logMaxLength;
703 $hairLength = min( intval( exp( $logHairLength ) ), $dictSize );
704 $offset = mt_rand( 0, $dictSize - $hairLength );
705 $input .= substr( $dict, $offset, $hairLength );
708 $this->setupGlobals();
709 $parser = $this->getParser();
713 $parser->parse( $input, $title, $opts );
714 $this->assertTrue( true, "Test $id, fuzz seed {$this->fuzzSeed}" );
715 } catch ( Exception
$exception ) {
716 $input_dump = sprintf( "string(%d) \"%s\"\n", strlen( $input ), $input );
718 $this->assertTrue( false, "Test $id, fuzz seed {$this->fuzzSeed}. \n\n" .
719 "Input: $input_dump\n\nError: {$exception->getMessage()}\n\n" .
720 "Backtrace: {$exception->getTraceAsString()}" );
723 $this->teardownGlobals();
724 $parser->__destruct();
726 if ( $id %
100 == 0 ) {
727 $usage = intval( memory_get_usage( true ) / $this->memoryLimit
/ 1048576 * 100 );
728 //echo "{$this->fuzzSeed}: $numSuccess/$numTotal (mem: $usage%)\n";
730 $ret = "Out of memory:\n";
731 $memStats = $this->getMemoryBreakdown();
733 foreach ( $memStats as $name => $usage ) {
734 $ret .= "$name: $usage\n";
737 throw new MWException( $ret );
745 //Various getter functions
748 * Get an input dictionary from a set of parser test files
750 function getFuzzInput( $filenames ) {
753 foreach ( $filenames as $filename ) {
754 $contents = file_get_contents( $filename );
755 preg_match_all( '/!!\s*input\n(.*?)\n!!\s*result/s', $contents, $matches );
757 foreach ( $matches[1] as $match ) {
758 $dict .= $match . "\n";
766 * Get a memory usage breakdown
768 function getMemoryBreakdown() {
771 foreach ( $GLOBALS as $name => $value ) {
772 $memStats['$' . $name] = strlen( serialize( $value ) );
775 $classes = get_declared_classes();
777 foreach ( $classes as $class ) {
778 $rc = new ReflectionClass( $class );
779 $props = $rc->getStaticProperties();
780 $memStats[$class] = strlen( serialize( $props ) );
781 $methods = $rc->getMethods();
783 foreach ( $methods as $method ) {
784 $memStats[$class] +
= strlen( serialize( $method->getStaticVariables() ) );
788 $functions = get_defined_functions();
790 foreach ( $functions['user'] as $function ) {
791 $rf = new ReflectionFunction( $function );
792 $memStats["$function()"] = strlen( serialize( $rf->getStaticVariables() ) );
801 * Get a Parser object
803 function getParser( $preprocessor = null ) {
804 global $wgParserConf;
806 $class = $wgParserConf['class'];
807 $parser = new $class( array( 'preprocessorClass' => $preprocessor ) +
$wgParserConf );
809 wfRunHooks( 'ParserTestParser', array( &$parser ) );
814 //Various action functions
816 public function addArticle( $name, $text, $line ) {
817 self
::$articles[$name] = array( $text, $line );
820 public function publishTestArticles() {
821 if ( empty( self
::$articles ) ) {
825 foreach ( self
::$articles as $name => $info ) {
826 list( $text, $line ) = $info;
827 ParserTest
::addArticle( $name, $text, $line, 'ignoreduplicate' );
832 * Steal a callback function from the primary parser, save it for
833 * application to our scary parser. If the hook is not installed,
834 * abort processing of this file.
836 * @param $name String
837 * @return Bool true if tag hook is present
839 public function requireHook( $name ) {
841 $wgParser->firstCallInit(); // make sure hooks are loaded.
842 return isset( $wgParser->mTagHooks
[$name] );
845 public function requireFunctionHook( $name ) {
847 $wgParser->firstCallInit(); // make sure hooks are loaded.
848 return isset( $wgParser->mFunctionHooks
[$name] );
851 //Various "cleanup" functions
854 * Run the "tidy" command on text if the $wgUseTidy
857 * @param $text String: the text to tidy
860 protected function tidy( $text ) {
864 $text = MWTidy
::tidy( $text );
871 * Remove last character if it is a newline
873 public function removeEndingNewline( $s ) {
874 if ( substr( $s, -1 ) === "\n" ) {
875 return substr( $s, 0, -1 );
881 //Test options parser functions
883 protected function parseOptions( $instring ) {
889 // foo=bar,"baz quux"
913 \[\[[^]]*\]\] # Link target
921 if ( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER
) ) {
922 foreach ( $matches as $bits ) {
923 array_shift( $bits );
924 $key = strtolower( array_shift( $bits ) );
925 if ( count( $bits ) == 0 ) {
927 } elseif ( count( $bits ) == 1 ) {
928 $opts[$key] = $this->cleanupOption( array_shift( $bits ) );
931 $opts[$key] = array_map( array( $this, 'cleanupOption' ), $bits );
939 protected function cleanupOption( $opt ) {
940 if ( substr( $opt, 0, 1 ) == '"' ) {
941 return substr( $opt, 1, -1 );
944 if ( substr( $opt, 0, 2 ) == '[[' ) {
945 return substr( $opt, 2, -2 );
952 * Use a regex to find out the value of an option
953 * @param $key String: name of option val to retrieve
954 * @param $opts Options array to look in
955 * @param $default Mixed: default value returned if not found
957 protected static function getOptionValue( $key, $opts, $default ) {
958 $key = strtolower( $key );
960 if ( isset( $opts[$key] ) ) {