Remove superfluous re- from confirmemail_body_set
[mediawiki.git] / tests / phpunit / includes / parser / NewParserTest.php
blob89103a255870deeb7bb08ceb1e748ed938a15d82
1 <?php
3 /**
4 * Although marked as a stub, can work independently.
6 * @group Database
7 * @group Parser
8 * @group Stub
9 */
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;
20 public $regex = '';
21 public $showProgress = true;
22 public $savedWeirdGlobals = array();
23 public $savedGlobals = array();
24 public $hooks = array();
25 public $functionHooks = array();
27 //Fuzz test
28 public $maxFuzzTestLength = 300;
29 public $fuzzSeed = 0;
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;
41 global $wgHooks, $IP;
43 parent::setUp();
45 //Setup CLI arguments
46 if ( $this->getCliArg( 'regex=' ) ) {
47 $this->regex = $this->getCliArg( 'regex=' );
48 } else {
49 # Matches anything
50 $this->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',
72 'name' => 'local',
73 'url' => 'http://example.com/images',
74 'hashLevels' => 2,
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(
99 '*' => array(
100 'createaccount' => true,
101 'read' => true,
102 'edit' => true,
103 'createpage' => true,
104 'createtalk' => true,
105 ) );
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;
136 $this->setMwGlobals( $tmpGlobals );
138 $this->savedWeirdGlobals['image_alias'] = $wgNamespaceAliases['Image'];
139 $this->savedWeirdGlobals['image_talk_alias'] = $wgNamespaceAliases['Image_talk'];
141 $wgNamespaceAliases['Image'] = NS_FILE;
142 $wgNamespaceAliases['Image_talk'] = NS_FILE_TALK;
145 protected function tearDown() {
146 global $wgNamespaceAliases;
148 $wgNamespaceAliases['Image'] = $this->savedWeirdGlobals['image_alias'];
149 $wgNamespaceAliases['Image_talk'] = $this->savedWeirdGlobals['image_talk_alias'];
151 // Restore backends
152 RepoGroup::destroySingleton();
153 FileBackendGroup::destroySingleton();
155 // Remove temporary pages from the link cache
156 LinkCache::singleton()->clear();
158 // Restore message cache (temporary pages and $wgUseDatabaseMessages)
159 MessageCache::destroyInstance();
161 parent::tearDown();
164 function addDBData() {
165 $this->tablesUsed[] = 'site_stats';
166 # disabled for performance
167 #$this->tablesUsed[] = 'image';
169 # Update certain things in site_stats
170 $this->db->insert( 'site_stats',
171 array( 'ss_row_id' => 1, 'ss_images' => 2, 'ss_good_articles' => 1 ),
172 __METHOD__
175 $user = User::newFromId( 0 );
176 LinkCache::singleton()->clear(); # Avoids the odd failure at creating the nullRevision
178 # Upload DB table entries for files.
179 # We will upload the actual files later. Note that if anything causes LocalFile::load()
180 # to be triggered before then, it will break via maybeUpgrade() setting the fileExists
181 # member to false and storing it in cache.
182 # note that the size/width/height/bits/etc of the file
183 # are actually set by inspecting the file itself; the arguments
184 # to recordUpload2 have no effect. That said, we try to make things
185 # match up so it is less confusing to readers of the code & tests.
186 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Foobar.jpg' ) );
187 if ( !$this->db->selectField( 'image', '1', array( 'img_name' => $image->getName() ) ) ) {
188 $image->recordUpload2(
189 '', // archive name
190 'Upload of some lame file',
191 'Some lame file',
192 array(
193 'size' => 7881,
194 'width' => 1941,
195 'height' => 220,
196 'bits' => 8,
197 'media_type' => MEDIATYPE_BITMAP,
198 'mime' => 'image/jpeg',
199 'metadata' => serialize( array() ),
200 'sha1' => wfBaseConvert( '1', 16, 36, 31 ),
201 'fileExists' => true ),
202 $this->db->timestamp( '20010115123500' ), $user
206 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Thumb.png' ) );
207 if ( !$this->db->selectField( 'image', '1', array( 'img_name' => $image->getName() ) ) ) {
208 $image->recordUpload2(
209 '', // archive name
210 'Upload of some lame thumbnail',
211 'Some lame thumbnail',
212 array(
213 'size' => 22589,
214 'width' => 135,
215 'height' => 135,
216 'bits' => 8,
217 'media_type' => MEDIATYPE_BITMAP,
218 'mime' => 'image/png',
219 'metadata' => serialize( array() ),
220 'sha1' => wfBaseConvert( '2', 16, 36, 31 ),
221 'fileExists' => true ),
222 $this->db->timestamp( '20130225203040' ), $user
226 # This image will be blacklisted in [[MediaWiki:Bad image list]]
227 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Bad.jpg' ) );
228 if ( !$this->db->selectField( 'image', '1', array( 'img_name' => $image->getName() ) ) ) {
229 $image->recordUpload2(
230 '', // archive name
231 'zomgnotcensored',
232 'Borderline image',
233 array(
234 'size' => 12345,
235 'width' => 320,
236 'height' => 240,
237 'bits' => 24,
238 'media_type' => MEDIATYPE_BITMAP,
239 'mime' => 'image/jpeg',
240 'metadata' => serialize( array() ),
241 'sha1' => wfBaseConvert( '3', 16, 36, 31 ),
242 'fileExists' => true ),
243 $this->db->timestamp( '20010115123500' ), $user
246 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Foobar.svg' ) );
247 if ( !$this->db->selectField( 'image', '1', array( 'img_name' => $image->getName() ) ) ) {
248 $image->recordUpload2( '', 'Upload of some lame SVG', 'Some lame SVG', array(
249 'size' => 12345,
250 'width' => 200,
251 'height' => 200,
252 'bits' => 24,
253 'media_type' => MEDIATYPE_DRAWING,
254 'mime' => 'image/svg+xml',
255 'metadata' => serialize( array() ),
256 'sha1' => wfBaseConvert( '', 16, 36, 31 ),
257 'fileExists' => true
258 ), $this->db->timestamp( '20010115123500' ), $user );
262 //ParserTest setup/teardown functions
265 * Set up the global variables for a consistent environment for each test.
266 * Ideally this should replace the global configuration entirely.
268 protected function setupGlobals( $opts = array(), $config = '' ) {
269 global $wgFileBackends;
270 # Find out values for some special options.
271 $lang =
272 self::getOptionValue( 'language', $opts, 'en' );
273 $variant =
274 self::getOptionValue( 'variant', $opts, false );
275 $maxtoclevel =
276 self::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
277 $linkHolderBatchSize =
278 self::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
280 $uploadDir = $this->getUploadDir();
281 if ( $this->getCliArg( 'use-filebackend=' ) ) {
282 if ( self::$backendToUse ) {
283 $backend = self::$backendToUse;
284 } else {
285 $name = $this->getCliArg( 'use-filebackend=' );
286 $useConfig = array();
287 foreach ( $wgFileBackends as $conf ) {
288 if ( $conf['name'] == $name ) {
289 $useConfig = $conf;
292 $useConfig['name'] = 'local-backend'; // swap name
293 $class = $conf['class'];
294 self::$backendToUse = new $class( $useConfig );
295 $backend = self::$backendToUse;
297 } else {
298 # Replace with a mock. We do not care about generating real
299 # files on the filesystem, just need to expose the file
300 # informations.
301 $backend = new MockFileBackend( array(
302 'name' => 'local-backend',
303 'lockManager' => 'nullLockManager',
304 'containerPaths' => array(
305 'local-public' => "$uploadDir",
306 'local-thumb' => "$uploadDir/thumb",
308 ) );
311 $settings = array(
312 'wgLocalFileRepo' => array(
313 'class' => 'LocalRepo',
314 'name' => 'local',
315 'url' => 'http://example.com/images',
316 'hashLevels' => 2,
317 'transformVia404' => false,
318 'backend' => $backend
320 'wgEnableUploads' => self::getOptionValue( 'wgEnableUploads', $opts, true ),
321 'wgLanguageCode' => $lang,
322 'wgDBprefix' => $this->db->getType() != 'oracle' ? 'unittest_' : 'ut_',
323 'wgRawHtml' => self::getOptionValue( 'wgRawHtml', $opts, false ),
324 'wgNamespacesWithSubpages' => array( NS_MAIN => isset( $opts['subpage'] ) ),
325 'wgAllowExternalImages' => self::getOptionValue( 'wgAllowExternalImages', $opts, true ),
326 'wgMaxTocLevel' => $maxtoclevel,
327 'wgUseTeX' => isset( $opts['math'] ) || isset( $opts['texvc'] ),
328 'wgMathDirectory' => $uploadDir . '/math',
329 'wgDefaultLanguageVariant' => $variant,
330 'wgLinkHolderBatchSize' => $linkHolderBatchSize,
333 if ( $config ) {
334 $configLines = explode( "\n", $config );
336 foreach ( $configLines as $line ) {
337 list( $var, $value ) = explode( '=', $line, 2 );
339 $settings[$var] = eval( "return $value;" ); //???
343 $this->savedGlobals = array();
345 /** @since 1.20 */
346 wfRunHooks( 'ParserTestGlobals', array( &$settings ) );
348 $langObj = Language::factory( $lang );
349 $settings['wgContLang'] = $langObj;
350 $settings['wgLang'] = $langObj;
352 $context = new RequestContext();
353 $settings['wgOut'] = $context->getOutput();
354 $settings['wgUser'] = $context->getUser();
355 $settings['wgRequest'] = $context->getRequest();
357 foreach ( $settings as $var => $val ) {
358 if ( array_key_exists( $var, $GLOBALS ) ) {
359 $this->savedGlobals[$var] = $GLOBALS[$var];
362 $GLOBALS[$var] = $val;
365 MagicWord::clearCache();
367 # The entries saved into RepoGroup cache with previous globals will be wrong.
368 RepoGroup::destroySingleton();
369 FileBackendGroup::destroySingleton();
371 # Create dummy files in storage
372 $this->setupUploads();
374 # Publish the articles after we have the final language set
375 $this->publishTestArticles();
377 MessageCache::destroyInstance();
379 return $context;
383 * Get an FS upload directory (only applies to FSFileBackend)
385 * @return String: the directory
387 protected function getUploadDir() {
388 if ( $this->keepUploads ) {
389 $dir = wfTempDir() . '/mwParser-images';
391 if ( is_dir( $dir ) ) {
392 return $dir;
394 } else {
395 $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
398 // wfDebug( "Creating upload directory $dir\n" );
399 if ( file_exists( $dir ) ) {
400 wfDebug( "Already exists!\n" );
402 return $dir;
405 return $dir;
409 * Create a dummy uploads directory which will contain a couple
410 * of files in order to pass existence tests.
412 * @return String: the directory
414 protected function setupUploads() {
415 global $IP;
417 $base = $this->getBaseDir();
418 $backend = RepoGroup::singleton()->getLocalRepo()->getBackend();
419 $backend->prepare( array( 'dir' => "$base/local-public/3/3a" ) );
420 $backend->store( array(
421 'src' => "$IP/skins/monobook/headbg.jpg", 'dst' => "$base/local-public/3/3a/Foobar.jpg"
422 ) );
423 $backend->prepare( array( 'dir' => "$base/local-public/e/ea" ) );
424 $backend->store( array(
425 'src' => "$IP/skins/monobook/wiki.png", 'dst' => "$base/local-public/e/ea/Thumb.png"
426 ) );
427 $backend->prepare( array( 'dir' => "$base/local-public/0/09" ) );
428 $backend->store( array(
429 'src' => "$IP/skins/monobook/headbg.jpg", 'dst' => "$base/local-public/0/09/Bad.jpg"
430 ) );
432 // No helpful SVG file to copy, so make one ourselves
433 $tmpDir = wfTempDir();
434 $tempFsFile = new TempFSFile( "$tmpDir/Foobar.svg" );
435 $tempFsFile->autocollect(); // destroy file when $tempFsFile leaves scope
436 file_put_contents( "$tmpDir/Foobar.svg",
437 '<?xml version="1.0" encoding="utf-8"?>' .
438 '<svg xmlns="http://www.w3.org/2000/svg" width="200" height="200"><text>Foo</text></svg>' );
440 $backend->prepare( array( 'dir' => "$base/local-public/f/ff" ) );
441 $backend->quickStore( array(
442 'src' => "$tmpDir/Foobar.svg", 'dst' => "$base/local-public/f/ff/Foobar.svg"
443 ) );
447 * Restore default values and perform any necessary clean-up
448 * after each test runs.
450 protected function teardownGlobals() {
451 $this->teardownUploads();
453 foreach ( $this->savedGlobals as $var => $val ) {
454 $GLOBALS[$var] = $val;
459 * Remove the dummy uploads directory
461 private function teardownUploads() {
462 if ( $this->keepUploads ) {
463 return;
466 $backend = RepoGroup::singleton()->getLocalRepo()->getBackend();
467 if ( $backend instanceof MockFileBackend ) {
468 # In memory backend, so dont bother cleaning them up.
469 return;
472 $base = $this->getBaseDir();
473 // delete the files first, then the dirs.
474 self::deleteFiles(
475 array(
476 "$base/local-public/3/3a/Foobar.jpg",
477 "$base/local-thumb/3/3a/Foobar.jpg/180px-Foobar.jpg",
478 "$base/local-thumb/3/3a/Foobar.jpg/200px-Foobar.jpg",
479 "$base/local-thumb/3/3a/Foobar.jpg/640px-Foobar.jpg",
480 "$base/local-thumb/3/3a/Foobar.jpg/120px-Foobar.jpg",
481 "$base/local-thumb/3/3a/Foobar.jpg/1280px-Foobar.jpg",
482 "$base/local-thumb/3/3a/Foobar.jpg/20px-Foobar.jpg",
483 "$base/local-thumb/3/3a/Foobar.jpg/270px-Foobar.jpg",
484 "$base/local-thumb/3/3a/Foobar.jpg/300px-Foobar.jpg",
485 "$base/local-thumb/3/3a/Foobar.jpg/30px-Foobar.jpg",
486 "$base/local-thumb/3/3a/Foobar.jpg/360px-Foobar.jpg",
487 "$base/local-thumb/3/3a/Foobar.jpg/400px-Foobar.jpg",
488 "$base/local-thumb/3/3a/Foobar.jpg/40px-Foobar.jpg",
489 "$base/local-thumb/3/3a/Foobar.jpg/70px-Foobar.jpg",
490 "$base/local-thumb/3/3a/Foobar.jpg/960px-Foobar.jpg",
492 "$base/local-public/e/ea/Thumb.png",
494 "$base/local-public/0/09/Bad.jpg",
496 "$base/local-public/f/ff/Foobar.svg",
497 "$base/local-thumb/f/ff/Foobar.svg/180px-Foobar.svg.jpg",
498 "$base/local-thumb/f/ff/Foobar.svg/270px-Foobar.svg.jpg",
499 "$base/local-thumb/f/ff/Foobar.svg/360px-Foobar.svg.jpg",
500 "$base/local-thumb/f/ff/Foobar.svg/langde-180px-Foobar.svg.jpg",
501 "$base/local-thumb/f/ff/Foobar.svg/langde-270px-Foobar.svg.jpg",
502 "$base/local-thumb/f/ff/Foobar.svg/langde-360px-Foobar.svg.jpg",
504 "$base/local-public/math/f/a/5/fa50b8b616463173474302ca3e63586b.png",
510 * Delete the specified files, if they exist.
511 * @param $files Array: full paths to files to delete.
513 private static function deleteFiles( $files ) {
514 $backend = RepoGroup::singleton()->getLocalRepo()->getBackend();
515 foreach ( $files as $file ) {
516 $backend->delete( array( 'src' => $file ), array( 'force' => 1 ) );
518 foreach ( $files as $file ) {
519 $tmp = $file;
520 while ( $tmp = FileBackend::parentStoragePath( $tmp ) ) {
521 if ( !$backend->clean( array( 'dir' => $tmp ) )->isOK() ) {
522 break;
528 protected function getBaseDir() {
529 return 'mwstore://local-backend';
532 public function parserTestProvider() {
533 if ( $this->file === false ) {
534 global $wgParserTestFiles;
535 $this->file = $wgParserTestFiles[0];
538 return new TestFileIterator( $this->file, $this );
542 * Set the file from whose tests will be run by this instance
544 public function setParserTestFile( $filename ) {
545 $this->file = $filename;
549 * @group medium
550 * @dataProvider parserTestProvider
552 public function testParserTest( $desc, $input, $result, $opts, $config ) {
553 if ( $this->regex != '' && !preg_match( '/' . $this->regex . '/', $desc ) ) {
554 $this->assertTrue( true ); // XXX: don't flood output with "test made no assertions"
555 //$this->markTestSkipped( 'Filtered out by the user' );
556 return;
559 if ( !$this->isWikitextNS( NS_MAIN ) ) {
560 // parser tests frequently assume that the main namespace contains wikitext.
561 // @todo When setting up pages, force the content model. Only skip if
562 // $wgtContentModelUseDB is false.
563 $this->markTestSkipped( "Main namespace does not support wikitext,"
564 . "skipping parser test: $desc" );
567 wfDebug( "Running parser test: $desc\n" );
569 $opts = $this->parseOptions( $opts );
570 $context = $this->setupGlobals( $opts, $config );
572 $user = $context->getUser();
573 $options = ParserOptions::newFromContext( $context );
575 if ( isset( $opts['title'] ) ) {
576 $titleText = $opts['title'];
577 } else {
578 $titleText = 'Parser test';
581 $local = isset( $opts['local'] );
582 $preprocessor = isset( $opts['preprocessor'] ) ? $opts['preprocessor'] : null;
583 $parser = $this->getParser( $preprocessor );
585 $title = Title::newFromText( $titleText );
587 # Parser test requiring math. Make sure texvc is executable
588 # or just skip such tests.
589 if ( isset( $opts['math'] ) || isset( $opts['texvc'] ) ) {
590 global $wgTexvc;
592 if ( !isset( $wgTexvc ) ) {
593 $this->markTestSkipped( "SKIPPED: \$wgTexvc is not set" );
594 } elseif ( !is_executable( $wgTexvc ) ) {
595 $this->markTestSkipped( "SKIPPED: texvc binary does not exist"
596 . " or is not executable.\n"
597 . "Current configuration is:\n\$wgTexvc = '$wgTexvc'" );
601 if ( isset( $opts['pst'] ) ) {
602 $out = $parser->preSaveTransform( $input, $title, $user, $options );
603 } elseif ( isset( $opts['msg'] ) ) {
604 $out = $parser->transformMsg( $input, $options, $title );
605 } elseif ( isset( $opts['section'] ) ) {
606 $section = $opts['section'];
607 $out = $parser->getSection( $input, $section );
608 } elseif ( isset( $opts['replace'] ) ) {
609 $section = $opts['replace'][0];
610 $replace = $opts['replace'][1];
611 $out = $parser->replaceSection( $input, $section, $replace );
612 } elseif ( isset( $opts['comment'] ) ) {
613 $out = Linker::formatComment( $input, $title, $local );
614 } elseif ( isset( $opts['preload'] ) ) {
615 $out = $parser->getPreloadText( $input, $title, $options );
616 } else {
617 $output = $parser->parse( $input, $title, $options, true, true, 1337 );
618 $out = $output->getText();
620 if ( isset( $opts['showtitle'] ) ) {
621 if ( $output->getTitleText() ) {
622 $title = $output->getTitleText();
625 $out = "$title\n$out";
628 if ( isset( $opts['ill'] ) ) {
629 $out = $this->tidy( implode( ' ', $output->getLanguageLinks() ) );
630 } elseif ( isset( $opts['cat'] ) ) {
631 $outputPage = $context->getOutput();
632 $outputPage->addCategoryLinks( $output->getCategories() );
633 $cats = $outputPage->getCategoryLinks();
635 if ( isset( $cats['normal'] ) ) {
636 $out = $this->tidy( implode( ' ', $cats['normal'] ) );
637 } else {
638 $out = '';
641 $parser->mPreprocessor = null;
643 $result = $this->tidy( $result );
646 $this->teardownGlobals();
648 $this->assertEquals( $result, $out, $desc );
652 * Run a fuzz test series
653 * Draw input from a set of test files
655 * @todo fixme Needs some work to not eat memory until the world explodes
657 * @group ParserFuzz
659 function testFuzzTests() {
660 global $wgParserTestFiles;
662 $files = $wgParserTestFiles;
664 if ( $this->getCliArg( 'file=' ) ) {
665 $files = array( $this->getCliArg( 'file=' ) );
668 $dict = $this->getFuzzInput( $files );
669 $dictSize = strlen( $dict );
670 $logMaxLength = log( $this->maxFuzzTestLength );
672 ini_set( 'memory_limit', $this->memoryLimit * 1048576 );
674 $user = new User;
675 $opts = ParserOptions::newFromUser( $user );
676 $title = Title::makeTitle( NS_MAIN, 'Parser_test' );
678 $id = 1;
680 while ( true ) {
682 // Generate test input
683 mt_srand( ++$this->fuzzSeed );
684 $totalLength = mt_rand( 1, $this->maxFuzzTestLength );
685 $input = '';
687 while ( strlen( $input ) < $totalLength ) {
688 $logHairLength = mt_rand( 0, 1000000 ) / 1000000 * $logMaxLength;
689 $hairLength = min( intval( exp( $logHairLength ) ), $dictSize );
690 $offset = mt_rand( 0, $dictSize - $hairLength );
691 $input .= substr( $dict, $offset, $hairLength );
694 $this->setupGlobals();
695 $parser = $this->getParser();
697 // Run the test
698 try {
699 $parser->parse( $input, $title, $opts );
700 $this->assertTrue( true, "Test $id, fuzz seed {$this->fuzzSeed}" );
701 } catch ( Exception $exception ) {
702 $input_dump = sprintf( "string(%d) \"%s\"\n", strlen( $input ), $input );
704 $this->assertTrue( false, "Test $id, fuzz seed {$this->fuzzSeed}. \n\n" .
705 "Input: $input_dump\n\nError: {$exception->getMessage()}\n\n" .
706 "Backtrace: {$exception->getTraceAsString()}" );
709 $this->teardownGlobals();
710 $parser->__destruct();
712 if ( $id % 100 == 0 ) {
713 $usage = intval( memory_get_usage( true ) / $this->memoryLimit / 1048576 * 100 );
714 //echo "{$this->fuzzSeed}: $numSuccess/$numTotal (mem: $usage%)\n";
715 if ( $usage > 90 ) {
716 $ret = "Out of memory:\n";
717 $memStats = $this->getMemoryBreakdown();
719 foreach ( $memStats as $name => $usage ) {
720 $ret .= "$name: $usage\n";
723 throw new MWException( $ret );
727 $id++;
731 //Various getter functions
734 * Get an input dictionary from a set of parser test files
736 function getFuzzInput( $filenames ) {
737 $dict = '';
739 foreach ( $filenames as $filename ) {
740 $contents = file_get_contents( $filename );
741 preg_match_all( '/!!\s*input\n(.*?)\n!!\s*result/s', $contents, $matches );
743 foreach ( $matches[1] as $match ) {
744 $dict .= $match . "\n";
748 return $dict;
752 * Get a memory usage breakdown
754 function getMemoryBreakdown() {
755 $memStats = array();
757 foreach ( $GLOBALS as $name => $value ) {
758 $memStats['$' . $name] = strlen( serialize( $value ) );
761 $classes = get_declared_classes();
763 foreach ( $classes as $class ) {
764 $rc = new ReflectionClass( $class );
765 $props = $rc->getStaticProperties();
766 $memStats[$class] = strlen( serialize( $props ) );
767 $methods = $rc->getMethods();
769 foreach ( $methods as $method ) {
770 $memStats[$class] += strlen( serialize( $method->getStaticVariables() ) );
774 $functions = get_defined_functions();
776 foreach ( $functions['user'] as $function ) {
777 $rf = new ReflectionFunction( $function );
778 $memStats["$function()"] = strlen( serialize( $rf->getStaticVariables() ) );
781 asort( $memStats );
783 return $memStats;
787 * Get a Parser object
789 function getParser( $preprocessor = null ) {
790 global $wgParserConf;
792 $class = $wgParserConf['class'];
793 $parser = new $class( array( 'preprocessorClass' => $preprocessor ) + $wgParserConf );
795 wfRunHooks( 'ParserTestParser', array( &$parser ) );
797 return $parser;
800 //Various action functions
802 public function addArticle( $name, $text, $line ) {
803 self::$articles[$name] = array( $text, $line );
806 public function publishTestArticles() {
807 if ( empty( self::$articles ) ) {
808 return;
811 foreach ( self::$articles as $name => $info ) {
812 list( $text, $line ) = $info;
813 ParserTest::addArticle( $name, $text, $line, 'ignoreduplicate' );
818 * Steal a callback function from the primary parser, save it for
819 * application to our scary parser. If the hook is not installed,
820 * abort processing of this file.
822 * @param $name String
823 * @return Bool true if tag hook is present
825 public function requireHook( $name ) {
826 global $wgParser;
827 $wgParser->firstCallInit(); // make sure hooks are loaded.
828 return isset( $wgParser->mTagHooks[$name] );
831 public function requireFunctionHook( $name ) {
832 global $wgParser;
833 $wgParser->firstCallInit(); // make sure hooks are loaded.
834 return isset( $wgParser->mFunctionHooks[$name] );
837 //Various "cleanup" functions
840 * Run the "tidy" command on text if the $wgUseTidy
841 * global is true
843 * @param $text String: the text to tidy
844 * @return String
846 protected function tidy( $text ) {
847 global $wgUseTidy;
849 if ( $wgUseTidy ) {
850 $text = MWTidy::tidy( $text );
853 return $text;
857 * Remove last character if it is a newline
859 public function removeEndingNewline( $s ) {
860 if ( substr( $s, -1 ) === "\n" ) {
861 return substr( $s, 0, -1 );
862 } else {
863 return $s;
867 //Test options parser functions
869 protected function parseOptions( $instring ) {
870 $opts = array();
871 // foo
872 // foo=bar
873 // foo="bar baz"
874 // foo=[[bar baz]]
875 // foo=bar,"baz quux"
876 $regex = '/\b
877 ([\w-]+) # Key
879 (?:\s*
880 = # First sub-value
884 [^"]* # Quoted val
887 \[\[
888 [^]]* # Link target
889 \]\]
891 [\w-]+ # Plain word
893 (?:\s*
894 , # Sub-vals 1..N
897 "[^"]*" # Quoted val
899 \[\[[^]]*\]\] # Link target
901 [\w-]+ # Plain word
905 /x';
907 if ( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER ) ) {
908 foreach ( $matches as $bits ) {
909 array_shift( $bits );
910 $key = strtolower( array_shift( $bits ) );
911 if ( count( $bits ) == 0 ) {
912 $opts[$key] = true;
913 } elseif ( count( $bits ) == 1 ) {
914 $opts[$key] = $this->cleanupOption( array_shift( $bits ) );
915 } else {
916 // Array!
917 $opts[$key] = array_map( array( $this, 'cleanupOption' ), $bits );
922 return $opts;
925 protected function cleanupOption( $opt ) {
926 if ( substr( $opt, 0, 1 ) == '"' ) {
927 return substr( $opt, 1, -1 );
930 if ( substr( $opt, 0, 2 ) == '[[' ) {
931 return substr( $opt, 2, -2 );
934 return $opt;
938 * Use a regex to find out the value of an option
939 * @param $key String: name of option val to retrieve
940 * @param $opts Options array to look in
941 * @param $default Mixed: default value returned if not found
943 protected static function getOptionValue( $key, $opts, $default ) {
944 $key = strtolower( $key );
946 if ( isset( $opts[$key] ) ) {
947 return $opts[$key];
948 } else {
949 return $default;