Merge "Installer: Remove wgResourceLoaderMaxQueryLength in LocalSettings"
[mediawiki.git] / tests / phpunit / includes / parser / NewParserTest.php
blob54c7fb57ac09750ecd88e4c09d412535cf85b850
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( 'wgParser', $GLOBALS['wgParserConf']['class'], array( $GLOBALS['wgParserConf'] ) );
110 $tmpGlobals['wgFileExtensions'][] = 'svg';
111 $tmpGlobals['wgSVGConverter'] = 'rsvg';
112 $tmpGlobals['wgSVGConverters']['rsvg'] = '$path/rsvg-convert -w $width -h $height $input -o $output';
114 if ( $GLOBALS['wgStyleDirectory'] === false ) {
115 $tmpGlobals['wgStyleDirectory'] = "$IP/skins";
118 # Replace all media handlers with a mock. We do not need to generate
119 # actual thumbnails to do parser testing, we only care about receiving
120 # a ThumbnailImage properly initialized.
121 global $wgMediaHandlers;
122 foreach ( $wgMediaHandlers as $type => $handler ) {
123 $tmpGlobals['wgMediaHandlers'][$type] = 'MockBitmapHandler';
125 // Vector images have to be handled slightly differently
126 $tmpGlobals['wgMediaHandlers']['image/svg+xml'] = 'MockSvgHandler';
128 $tmpHooks = $wgHooks;
129 $tmpHooks['ParserTestParser'][] = 'ParserTestParserHook::setup';
130 $tmpHooks['ParserGetVariableValueTs'][] = 'ParserTest::getFakeTimestamp';
131 $tmpGlobals['wgHooks'] = $tmpHooks;
133 $this->setMwGlobals( $tmpGlobals );
135 $this->savedWeirdGlobals['image_alias'] = $wgNamespaceAliases['Image'];
136 $this->savedWeirdGlobals['image_talk_alias'] = $wgNamespaceAliases['Image_talk'];
138 $wgNamespaceAliases['Image'] = NS_FILE;
139 $wgNamespaceAliases['Image_talk'] = NS_FILE_TALK;
142 protected function tearDown() {
143 global $wgNamespaceAliases;
145 $wgNamespaceAliases['Image'] = $this->savedWeirdGlobals['image_alias'];
146 $wgNamespaceAliases['Image_talk'] = $this->savedWeirdGlobals['image_talk_alias'];
148 // Restore backends
149 RepoGroup::destroySingleton();
150 FileBackendGroup::destroySingleton();
152 // Remove temporary pages from the link cache
153 LinkCache::singleton()->clear();
155 // Restore message cache (temporary pages and $wgUseDatabaseMessages)
156 MessageCache::destroyInstance();
158 parent::tearDown();
161 function addDBData() {
162 $this->tablesUsed[] = 'site_stats';
163 # disabled for performance
164 #$this->tablesUsed[] = 'image';
166 # Update certain things in site_stats
167 $this->db->insert( 'site_stats',
168 array( 'ss_row_id' => 1, 'ss_images' => 2, 'ss_good_articles' => 1 ),
169 __METHOD__
172 $user = User::newFromId( 0 );
173 LinkCache::singleton()->clear(); # Avoids the odd failure at creating the nullRevision
175 # Upload DB table entries for files.
176 # We will upload the actual files later. Note that if anything causes LocalFile::load()
177 # to be triggered before then, it will break via maybeUpgrade() setting the fileExists
178 # member to false and storing it in cache.
179 # note that the size/width/height/bits/etc of the file
180 # are actually set by inspecting the file itself; the arguments
181 # to recordUpload2 have no effect. That said, we try to make things
182 # match up so it is less confusing to readers of the code & tests.
183 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Foobar.jpg' ) );
184 if ( !$this->db->selectField( 'image', '1', array( 'img_name' => $image->getName() ) ) ) {
185 $image->recordUpload2(
186 '', // archive name
187 'Upload of some lame file',
188 'Some lame file',
189 array(
190 'size' => 7881,
191 'width' => 1941,
192 'height' => 220,
193 'bits' => 8,
194 'media_type' => MEDIATYPE_BITMAP,
195 'mime' => 'image/jpeg',
196 'metadata' => serialize( array() ),
197 'sha1' => wfBaseConvert( '1', 16, 36, 31 ),
198 'fileExists' => true ),
199 $this->db->timestamp( '20010115123500' ), $user
203 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Thumb.png' ) );
204 if ( !$this->db->selectField( 'image', '1', array( 'img_name' => $image->getName() ) ) ) {
205 $image->recordUpload2(
206 '', // archive name
207 'Upload of some lame thumbnail',
208 'Some lame thumbnail',
209 array(
210 'size' => 22589,
211 'width' => 135,
212 'height' => 135,
213 'bits' => 8,
214 'media_type' => MEDIATYPE_BITMAP,
215 'mime' => 'image/png',
216 'metadata' => serialize( array() ),
217 'sha1' => wfBaseConvert( '2', 16, 36, 31 ),
218 'fileExists' => true ),
219 $this->db->timestamp( '20130225203040' ), $user
223 # This image will be blacklisted in [[MediaWiki:Bad image list]]
224 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Bad.jpg' ) );
225 if ( !$this->db->selectField( 'image', '1', array( 'img_name' => $image->getName() ) ) ) {
226 $image->recordUpload2(
227 '', // archive name
228 'zomgnotcensored',
229 'Borderline image',
230 array(
231 'size' => 12345,
232 'width' => 320,
233 'height' => 240,
234 'bits' => 24,
235 'media_type' => MEDIATYPE_BITMAP,
236 'mime' => 'image/jpeg',
237 'metadata' => serialize( array() ),
238 'sha1' => wfBaseConvert( '3', 16, 36, 31 ),
239 'fileExists' => true ),
240 $this->db->timestamp( '20010115123500' ), $user
243 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Foobar.svg' ) );
244 if ( !$this->db->selectField( 'image', '1', array( 'img_name' => $image->getName() ) ) ) {
245 $image->recordUpload2( '', 'Upload of some lame SVG', 'Some lame SVG', array(
246 'size' => 12345,
247 'width' => 200,
248 'height' => 200,
249 'bits' => 24,
250 'media_type' => MEDIATYPE_DRAWING,
251 'mime' => 'image/svg+xml',
252 'metadata' => serialize( array() ),
253 'sha1' => wfBaseConvert( '', 16, 36, 31 ),
254 'fileExists' => true
255 ), $this->db->timestamp( '20010115123500' ), $user );
259 //ParserTest setup/teardown functions
262 * Set up the global variables for a consistent environment for each test.
263 * Ideally this should replace the global configuration entirely.
265 protected function setupGlobals( $opts = array(), $config = '' ) {
266 global $wgFileBackends;
267 # Find out values for some special options.
268 $lang =
269 self::getOptionValue( 'language', $opts, 'en' );
270 $variant =
271 self::getOptionValue( 'variant', $opts, false );
272 $maxtoclevel =
273 self::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
274 $linkHolderBatchSize =
275 self::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
277 $uploadDir = $this->getUploadDir();
278 if ( $this->getCliArg( 'use-filebackend=' ) ) {
279 if ( self::$backendToUse ) {
280 $backend = self::$backendToUse;
281 } else {
282 $name = $this->getCliArg( 'use-filebackend=' );
283 $useConfig = array();
284 foreach ( $wgFileBackends as $conf ) {
285 if ( $conf['name'] == $name ) {
286 $useConfig = $conf;
289 $useConfig['name'] = 'local-backend'; // swap name
290 $class = $conf['class'];
291 self::$backendToUse = new $class( $useConfig );
292 $backend = self::$backendToUse;
294 } else {
295 # Replace with a mock. We do not care about generating real
296 # files on the filesystem, just need to expose the file
297 # informations.
298 $backend = new MockFileBackend( array(
299 'name' => 'local-backend',
300 'lockManager' => 'nullLockManager',
301 'containerPaths' => array(
302 'local-public' => "$uploadDir",
303 'local-thumb' => "$uploadDir/thumb",
305 ) );
308 $settings = array(
309 'wgLocalFileRepo' => array(
310 'class' => 'LocalRepo',
311 'name' => 'local',
312 'url' => 'http://example.com/images',
313 'hashLevels' => 2,
314 'transformVia404' => false,
315 'backend' => $backend
317 'wgEnableUploads' => self::getOptionValue( 'wgEnableUploads', $opts, true ),
318 'wgLanguageCode' => $lang,
319 'wgDBprefix' => $this->db->getType() != 'oracle' ? 'unittest_' : 'ut_',
320 'wgRawHtml' => isset( $opts['rawhtml'] ),
321 'wgNamespacesWithSubpages' => array( NS_MAIN => isset( $opts['subpage'] ) ),
322 'wgMaxTocLevel' => $maxtoclevel,
323 'wgUseTeX' => isset( $opts['math'] ) || isset( $opts['texvc'] ),
324 'wgMathDirectory' => $uploadDir . '/math',
325 'wgDefaultLanguageVariant' => $variant,
326 'wgLinkHolderBatchSize' => $linkHolderBatchSize,
329 if ( $config ) {
330 $configLines = explode( "\n", $config );
332 foreach ( $configLines as $line ) {
333 list( $var, $value ) = explode( '=', $line, 2 );
335 $settings[$var] = eval( "return $value;" ); //???
339 $this->savedGlobals = array();
341 /** @since 1.20 */
342 wfRunHooks( 'ParserTestGlobals', array( &$settings ) );
344 $langObj = Language::factory( $lang );
345 $settings['wgContLang'] = $langObj;
346 $settings['wgLang'] = $langObj;
348 $context = new RequestContext();
349 $settings['wgOut'] = $context->getOutput();
350 $settings['wgUser'] = $context->getUser();
351 $settings['wgRequest'] = $context->getRequest();
353 foreach ( $settings as $var => $val ) {
354 if ( array_key_exists( $var, $GLOBALS ) ) {
355 $this->savedGlobals[$var] = $GLOBALS[$var];
358 $GLOBALS[$var] = $val;
361 MagicWord::clearCache();
363 # The entries saved into RepoGroup cache with previous globals will be wrong.
364 RepoGroup::destroySingleton();
365 FileBackendGroup::destroySingleton();
367 # Create dummy files in storage
368 $this->setupUploads();
370 # Publish the articles after we have the final language set
371 $this->publishTestArticles();
373 MessageCache::destroyInstance();
375 return $context;
379 * Get an FS upload directory (only applies to FSFileBackend)
381 * @return String: the directory
383 protected function getUploadDir() {
384 if ( $this->keepUploads ) {
385 $dir = wfTempDir() . '/mwParser-images';
387 if ( is_dir( $dir ) ) {
388 return $dir;
390 } else {
391 $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
394 // wfDebug( "Creating upload directory $dir\n" );
395 if ( file_exists( $dir ) ) {
396 wfDebug( "Already exists!\n" );
398 return $dir;
401 return $dir;
405 * Create a dummy uploads directory which will contain a couple
406 * of files in order to pass existence tests.
408 * @return String: the directory
410 protected function setupUploads() {
411 global $IP;
413 $base = $this->getBaseDir();
414 $backend = RepoGroup::singleton()->getLocalRepo()->getBackend();
415 $backend->prepare( array( 'dir' => "$base/local-public/3/3a" ) );
416 $backend->store( array(
417 'src' => "$IP/skins/monobook/headbg.jpg", 'dst' => "$base/local-public/3/3a/Foobar.jpg"
418 ) );
419 $backend->prepare( array( 'dir' => "$base/local-public/e/ea" ) );
420 $backend->store( array(
421 'src' => "$IP/skins/monobook/wiki.png", 'dst' => "$base/local-public/e/ea/Thumb.png"
422 ) );
423 $backend->prepare( array( 'dir' => "$base/local-public/0/09" ) );
424 $backend->store( array(
425 'src' => "$IP/skins/monobook/headbg.jpg", 'dst' => "$base/local-public/0/09/Bad.jpg"
426 ) );
428 // No helpful SVG file to copy, so make one ourselves
429 $tmpDir = wfTempDir();
430 $tempFsFile = new TempFSFile( "$tmpDir/Foobar.svg" );
431 $tempFsFile->autocollect(); // destroy file when $tempFsFile leaves scope
432 file_put_contents( "$tmpDir/Foobar.svg",
433 '<?xml version="1.0" encoding="utf-8"?>' .
434 '<svg xmlns="http://www.w3.org/2000/svg" width="200" height="200"><text>Foo</text></svg>' );
436 $backend->prepare( array( 'dir' => "$base/local-public/f/ff" ) );
437 $backend->quickStore( array(
438 'src' => "$tmpDir/Foobar.svg", 'dst' => "$base/local-public/f/ff/Foobar.svg"
439 ) );
443 * Restore default values and perform any necessary clean-up
444 * after each test runs.
446 protected function teardownGlobals() {
447 $this->teardownUploads();
449 foreach ( $this->savedGlobals as $var => $val ) {
450 $GLOBALS[$var] = $val;
455 * Remove the dummy uploads directory
457 private function teardownUploads() {
458 if ( $this->keepUploads ) {
459 return;
462 $backend = RepoGroup::singleton()->getLocalRepo()->getBackend();
463 if ( $backend instanceof MockFileBackend ) {
464 # In memory backend, so dont bother cleaning them up.
465 return;
468 $base = $this->getBaseDir();
469 // delete the files first, then the dirs.
470 self::deleteFiles(
471 array(
472 "$base/local-public/3/3a/Foobar.jpg",
473 "$base/local-thumb/3/3a/Foobar.jpg/180px-Foobar.jpg",
474 "$base/local-thumb/3/3a/Foobar.jpg/200px-Foobar.jpg",
475 "$base/local-thumb/3/3a/Foobar.jpg/640px-Foobar.jpg",
476 "$base/local-thumb/3/3a/Foobar.jpg/120px-Foobar.jpg",
477 "$base/local-thumb/3/3a/Foobar.jpg/1280px-Foobar.jpg",
478 "$base/local-thumb/3/3a/Foobar.jpg/20px-Foobar.jpg",
479 "$base/local-thumb/3/3a/Foobar.jpg/270px-Foobar.jpg",
480 "$base/local-thumb/3/3a/Foobar.jpg/300px-Foobar.jpg",
481 "$base/local-thumb/3/3a/Foobar.jpg/30px-Foobar.jpg",
482 "$base/local-thumb/3/3a/Foobar.jpg/360px-Foobar.jpg",
483 "$base/local-thumb/3/3a/Foobar.jpg/400px-Foobar.jpg",
484 "$base/local-thumb/3/3a/Foobar.jpg/40px-Foobar.jpg",
485 "$base/local-thumb/3/3a/Foobar.jpg/70px-Foobar.jpg",
486 "$base/local-thumb/3/3a/Foobar.jpg/960px-Foobar.jpg",
488 "$base/local-public/e/ea/Thumb.png",
490 "$base/local-public/0/09/Bad.jpg",
492 "$base/local-public/f/ff/Foobar.svg",
493 "$base/local-thumb/f/ff/Foobar.svg/180px-Foobar.svg.jpg",
494 "$base/local-thumb/f/ff/Foobar.svg/270px-Foobar.svg.jpg",
495 "$base/local-thumb/f/ff/Foobar.svg/360px-Foobar.svg.jpg",
496 "$base/local-thumb/f/ff/Foobar.svg/langde-180px-Foobar.svg.jpg",
497 "$base/local-thumb/f/ff/Foobar.svg/langde-270px-Foobar.svg.jpg",
498 "$base/local-thumb/f/ff/Foobar.svg/langde-360px-Foobar.svg.jpg",
500 "$base/local-public/math/f/a/5/fa50b8b616463173474302ca3e63586b.png",
506 * Delete the specified files, if they exist.
507 * @param $files Array: full paths to files to delete.
509 private static function deleteFiles( $files ) {
510 $backend = RepoGroup::singleton()->getLocalRepo()->getBackend();
511 foreach ( $files as $file ) {
512 $backend->delete( array( 'src' => $file ), array( 'force' => 1 ) );
514 foreach ( $files as $file ) {
515 $tmp = $file;
516 while ( $tmp = FileBackend::parentStoragePath( $tmp ) ) {
517 if ( !$backend->clean( array( 'dir' => $tmp ) )->isOK() ) {
518 break;
524 protected function getBaseDir() {
525 return 'mwstore://local-backend';
528 public function parserTestProvider() {
529 if ( $this->file === false ) {
530 global $wgParserTestFiles;
531 $this->file = $wgParserTestFiles[0];
534 return new TestFileIterator( $this->file, $this );
538 * Set the file from whose tests will be run by this instance
540 public function setParserTestFile( $filename ) {
541 $this->file = $filename;
545 * @group medium
546 * @dataProvider parserTestProvider
548 public function testParserTest( $desc, $input, $result, $opts, $config ) {
549 if ( $this->regex != '' && !preg_match( '/' . $this->regex . '/', $desc ) ) {
550 $this->assertTrue( true ); // XXX: don't flood output with "test made no assertions"
551 //$this->markTestSkipped( 'Filtered out by the user' );
552 return;
555 if ( !$this->isWikitextNS( NS_MAIN ) ) {
556 // parser tests frequently assume that the main namespace contains wikitext.
557 // @todo When setting up pages, force the content model. Only skip if
558 // $wgtContentModelUseDB is false.
559 $this->markTestSkipped( "Main namespace does not support wikitext,"
560 . "skipping parser test: $desc" );
563 wfDebug( "Running parser test: $desc\n" );
565 $opts = $this->parseOptions( $opts );
566 $context = $this->setupGlobals( $opts, $config );
568 $user = $context->getUser();
569 $options = ParserOptions::newFromContext( $context );
571 if ( isset( $opts['title'] ) ) {
572 $titleText = $opts['title'];
573 } else {
574 $titleText = 'Parser test';
577 $local = isset( $opts['local'] );
578 $preprocessor = isset( $opts['preprocessor'] ) ? $opts['preprocessor'] : null;
579 $parser = $this->getParser( $preprocessor );
581 $title = Title::newFromText( $titleText );
583 # Parser test requiring math. Make sure texvc is executable
584 # or just skip such tests.
585 if ( isset( $opts['math'] ) || isset( $opts['texvc'] ) ) {
586 global $wgTexvc;
588 if ( !isset( $wgTexvc ) ) {
589 $this->markTestSkipped( "SKIPPED: \$wgTexvc is not set" );
590 } elseif ( !is_executable( $wgTexvc ) ) {
591 $this->markTestSkipped( "SKIPPED: texvc binary does not exist"
592 . " or is not executable.\n"
593 . "Current configuration is:\n\$wgTexvc = '$wgTexvc'" );
597 if ( isset( $opts['pst'] ) ) {
598 $out = $parser->preSaveTransform( $input, $title, $user, $options );
599 } elseif ( isset( $opts['msg'] ) ) {
600 $out = $parser->transformMsg( $input, $options, $title );
601 } elseif ( isset( $opts['section'] ) ) {
602 $section = $opts['section'];
603 $out = $parser->getSection( $input, $section );
604 } elseif ( isset( $opts['replace'] ) ) {
605 $section = $opts['replace'][0];
606 $replace = $opts['replace'][1];
607 $out = $parser->replaceSection( $input, $section, $replace );
608 } elseif ( isset( $opts['comment'] ) ) {
609 $out = Linker::formatComment( $input, $title, $local );
610 } elseif ( isset( $opts['preload'] ) ) {
611 $out = $parser->getPreloadText( $input, $title, $options );
612 } else {
613 $output = $parser->parse( $input, $title, $options, true, true, 1337 );
614 $out = $output->getText();
616 if ( isset( $opts['showtitle'] ) ) {
617 if ( $output->getTitleText() ) {
618 $title = $output->getTitleText();
621 $out = "$title\n$out";
624 if ( isset( $opts['ill'] ) ) {
625 $out = $this->tidy( implode( ' ', $output->getLanguageLinks() ) );
626 } elseif ( isset( $opts['cat'] ) ) {
627 $outputPage = $context->getOutput();
628 $outputPage->addCategoryLinks( $output->getCategories() );
629 $cats = $outputPage->getCategoryLinks();
631 if ( isset( $cats['normal'] ) ) {
632 $out = $this->tidy( implode( ' ', $cats['normal'] ) );
633 } else {
634 $out = '';
637 $parser->mPreprocessor = null;
639 $result = $this->tidy( $result );
642 $this->teardownGlobals();
644 $this->assertEquals( $result, $out, $desc );
648 * Run a fuzz test series
649 * Draw input from a set of test files
651 * @todo fixme Needs some work to not eat memory until the world explodes
653 * @group ParserFuzz
655 function testFuzzTests() {
656 global $wgParserTestFiles;
658 $files = $wgParserTestFiles;
660 if ( $this->getCliArg( 'file=' ) ) {
661 $files = array( $this->getCliArg( 'file=' ) );
664 $dict = $this->getFuzzInput( $files );
665 $dictSize = strlen( $dict );
666 $logMaxLength = log( $this->maxFuzzTestLength );
668 ini_set( 'memory_limit', $this->memoryLimit * 1048576 );
670 $user = new User;
671 $opts = ParserOptions::newFromUser( $user );
672 $title = Title::makeTitle( NS_MAIN, 'Parser_test' );
674 $id = 1;
676 while ( true ) {
678 // Generate test input
679 mt_srand( ++$this->fuzzSeed );
680 $totalLength = mt_rand( 1, $this->maxFuzzTestLength );
681 $input = '';
683 while ( strlen( $input ) < $totalLength ) {
684 $logHairLength = mt_rand( 0, 1000000 ) / 1000000 * $logMaxLength;
685 $hairLength = min( intval( exp( $logHairLength ) ), $dictSize );
686 $offset = mt_rand( 0, $dictSize - $hairLength );
687 $input .= substr( $dict, $offset, $hairLength );
690 $this->setupGlobals();
691 $parser = $this->getParser();
693 // Run the test
694 try {
695 $parser->parse( $input, $title, $opts );
696 $this->assertTrue( true, "Test $id, fuzz seed {$this->fuzzSeed}" );
697 } catch ( Exception $exception ) {
698 $input_dump = sprintf( "string(%d) \"%s\"\n", strlen( $input ), $input );
700 $this->assertTrue( false, "Test $id, fuzz seed {$this->fuzzSeed}. \n\nInput: $input_dump\n\nError: {$exception->getMessage()}\n\nBacktrace: {$exception->getTraceAsString()}" );
703 $this->teardownGlobals();
704 $parser->__destruct();
706 if ( $id % 100 == 0 ) {
707 $usage = intval( memory_get_usage( true ) / $this->memoryLimit / 1048576 * 100 );
708 //echo "{$this->fuzzSeed}: $numSuccess/$numTotal (mem: $usage%)\n";
709 if ( $usage > 90 ) {
710 $ret = "Out of memory:\n";
711 $memStats = $this->getMemoryBreakdown();
713 foreach ( $memStats as $name => $usage ) {
714 $ret .= "$name: $usage\n";
717 throw new MWException( $ret );
721 $id++;
725 //Various getter functions
728 * Get an input dictionary from a set of parser test files
730 function getFuzzInput( $filenames ) {
731 $dict = '';
733 foreach ( $filenames as $filename ) {
734 $contents = file_get_contents( $filename );
735 preg_match_all( '/!!\s*input\n(.*?)\n!!\s*result/s', $contents, $matches );
737 foreach ( $matches[1] as $match ) {
738 $dict .= $match . "\n";
742 return $dict;
746 * Get a memory usage breakdown
748 function getMemoryBreakdown() {
749 $memStats = array();
751 foreach ( $GLOBALS as $name => $value ) {
752 $memStats['$' . $name] = strlen( serialize( $value ) );
755 $classes = get_declared_classes();
757 foreach ( $classes as $class ) {
758 $rc = new ReflectionClass( $class );
759 $props = $rc->getStaticProperties();
760 $memStats[$class] = strlen( serialize( $props ) );
761 $methods = $rc->getMethods();
763 foreach ( $methods as $method ) {
764 $memStats[$class] += strlen( serialize( $method->getStaticVariables() ) );
768 $functions = get_defined_functions();
770 foreach ( $functions['user'] as $function ) {
771 $rf = new ReflectionFunction( $function );
772 $memStats["$function()"] = strlen( serialize( $rf->getStaticVariables() ) );
775 asort( $memStats );
777 return $memStats;
781 * Get a Parser object
783 function getParser( $preprocessor = null ) {
784 global $wgParserConf;
786 $class = $wgParserConf['class'];
787 $parser = new $class( array( 'preprocessorClass' => $preprocessor ) + $wgParserConf );
789 wfRunHooks( 'ParserTestParser', array( &$parser ) );
791 return $parser;
794 //Various action functions
796 public function addArticle( $name, $text, $line ) {
797 self::$articles[$name] = array( $text, $line );
800 public function publishTestArticles() {
801 if ( empty( self::$articles ) ) {
802 return;
805 foreach ( self::$articles as $name => $info ) {
806 list( $text, $line ) = $info;
807 ParserTest::addArticle( $name, $text, $line, 'ignoreduplicate' );
812 * Steal a callback function from the primary parser, save it for
813 * application to our scary parser. If the hook is not installed,
814 * abort processing of this file.
816 * @param $name String
817 * @return Bool true if tag hook is present
819 public function requireHook( $name ) {
820 global $wgParser;
821 $wgParser->firstCallInit(); // make sure hooks are loaded.
822 return isset( $wgParser->mTagHooks[$name] );
825 public function requireFunctionHook( $name ) {
826 global $wgParser;
827 $wgParser->firstCallInit(); // make sure hooks are loaded.
828 return isset( $wgParser->mFunctionHooks[$name] );
831 //Various "cleanup" functions
834 * Run the "tidy" command on text if the $wgUseTidy
835 * global is true
837 * @param $text String: the text to tidy
838 * @return String
840 protected function tidy( $text ) {
841 global $wgUseTidy;
843 if ( $wgUseTidy ) {
844 $text = MWTidy::tidy( $text );
847 return $text;
851 * Remove last character if it is a newline
853 public function removeEndingNewline( $s ) {
854 if ( substr( $s, -1 ) === "\n" ) {
855 return substr( $s, 0, -1 );
856 } else {
857 return $s;
861 //Test options parser functions
863 protected function parseOptions( $instring ) {
864 $opts = array();
865 // foo
866 // foo=bar
867 // foo="bar baz"
868 // foo=[[bar baz]]
869 // foo=bar,"baz quux"
870 $regex = '/\b
871 ([\w-]+) # Key
873 (?:\s*
874 = # First sub-value
878 [^"]* # Quoted val
881 \[\[
882 [^]]* # Link target
883 \]\]
885 [\w-]+ # Plain word
887 (?:\s*
888 , # Sub-vals 1..N
891 "[^"]*" # Quoted val
893 \[\[[^]]*\]\] # Link target
895 [\w-]+ # Plain word
899 /x';
901 if ( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER ) ) {
902 foreach ( $matches as $bits ) {
903 array_shift( $bits );
904 $key = strtolower( array_shift( $bits ) );
905 if ( count( $bits ) == 0 ) {
906 $opts[$key] = true;
907 } elseif ( count( $bits ) == 1 ) {
908 $opts[$key] = $this->cleanupOption( array_shift( $bits ) );
909 } else {
910 // Array!
911 $opts[$key] = array_map( array( $this, 'cleanupOption' ), $bits );
916 return $opts;
919 protected function cleanupOption( $opt ) {
920 if ( substr( $opt, 0, 1 ) == '"' ) {
921 return substr( $opt, 1, -1 );
924 if ( substr( $opt, 0, 2 ) == '[[' ) {
925 return substr( $opt, 2, -2 );
928 return $opt;
932 * Use a regex to find out the value of an option
933 * @param $key String: name of option val to retrieve
934 * @param $opts Options array to look in
935 * @param $default Mixed: default value returned if not found
937 protected static function getOptionValue( $key, $opts, $default ) {
938 $key = strtolower( $key );
940 if ( isset( $opts[$key] ) ) {
941 return $opts[$key];
942 } else {
943 return $default;