Merge "phpcs: Normalize methods declarations to "[final abstract] [visibility]"."
[lhc/web/wiklou.git] / tests / phpunit / includes / parser / NewParserTest.php
1 <?php
2
3 /**
4 * Although marked as a stub, can work independently.
5 *
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.
14 */
15 static protected $backendToUse;
16
17 public $keepUploads = false;
18 public $runDisabled = false;
19 public $regex = '';
20 public $showProgress = true;
21 public $savedInitialGlobals = array();
22 public $savedWeirdGlobals = array();
23 public $savedGlobals = array();
24 public $hooks = array();
25 public $functionHooks = array();
26
27 //Fuzz test
28 public $maxFuzzTestLength = 300;
29 public $fuzzSeed = 0;
30 public $memoryLimit = 50;
31
32 protected $file = false;
33
34 protected function setUp() {
35 global $wgContLang, $wgLanguageCode;
36 global $wgNamespaceProtection, $wgNamespaceAliases;
37 global $wgHooks, $IP;
38
39 parent::setUp();
40
41 $wgLanguageCode = 'en';
42 $wgContLang = Language::factory( 'en' );
43
44 //Setup CLI arguments
45 if ( $this->getCliArg( 'regex=' ) ) {
46 $this->regex = $this->getCliArg( 'regex=' );
47 } else {
48 # Matches anything
49 $this->regex = '';
50 }
51
52 $this->keepUploads = $this->getCliArg( 'keep-uploads' );
53
54 $tmpGlobals = array();
55
56 $tmpGlobals['wgScript'] = '/index.php';
57 $tmpGlobals['wgScriptPath'] = '/';
58 $tmpGlobals['wgArticlePath'] = '/wiki/$1';
59 $tmpGlobals['wgStyleSheetPath'] = '/skins';
60 $tmpGlobals['wgStylePath'] = '/skins';
61 $tmpGlobals['wgThumbnailScriptPath'] = false;
62 $tmpGlobals['wgLocalFileRepo'] = array(
63 'class' => 'LocalRepo',
64 'name' => 'local',
65 'url' => 'http://example.com/images',
66 'hashLevels' => 2,
67 'transformVia404' => false,
68 'backend' => 'local-backend'
69 );
70 $tmpGlobals['wgForeignFileRepos'] = array();
71 $tmpGlobals['wgEnableParserCache'] = false;
72 $tmpGlobals['wgHooks'] = $wgHooks;
73 $tmpGlobals['wgDeferredUpdateList'] = array();
74 $tmpGlobals['wgMemc'] = wfGetMainCache();
75 $tmpGlobals['messageMemc'] = wfGetMessageCacheStorage();
76 $tmpGlobals['parserMemc'] = wfGetParserCacheStorage();
77
78 // $tmpGlobals['wgContLang'] = new StubContLang;
79 $tmpGlobals['wgUser'] = new User;
80 $context = new RequestContext();
81 $tmpGlobals['wgLang'] = $context->getLanguage();
82 $tmpGlobals['wgOut'] = $context->getOutput();
83 $tmpGlobals['wgParser'] = new StubObject( 'wgParser', $GLOBALS['wgParserConf']['class'], array( $GLOBALS['wgParserConf'] ) );
84 $tmpGlobals['wgRequest'] = $context->getRequest();
85
86 if ( $GLOBALS['wgStyleDirectory'] === false ) {
87 $tmpGlobals['wgStyleDirectory'] = "$IP/skins";
88 }
89
90
91 foreach ( $tmpGlobals as $var => $val ) {
92 if ( array_key_exists( $var, $GLOBALS ) ) {
93 $this->savedInitialGlobals[$var] = $GLOBALS[$var];
94 }
95
96 $GLOBALS[$var] = $val;
97 }
98
99 $this->savedWeirdGlobals['mw_namespace_protection'] = $wgNamespaceProtection[NS_MEDIAWIKI];
100 $this->savedWeirdGlobals['image_alias'] = $wgNamespaceAliases['Image'];
101 $this->savedWeirdGlobals['image_talk_alias'] = $wgNamespaceAliases['Image_talk'];
102
103 $wgNamespaceProtection[NS_MEDIAWIKI] = 'editinterface';
104 $wgNamespaceAliases['Image'] = NS_FILE;
105 $wgNamespaceAliases['Image_talk'] = NS_FILE_TALK;
106 }
107
108 protected function tearDown() {
109 foreach ( $this->savedInitialGlobals as $var => $val ) {
110 $GLOBALS[$var] = $val;
111 }
112
113 global $wgNamespaceProtection, $wgNamespaceAliases;
114
115 $wgNamespaceProtection[NS_MEDIAWIKI] = $this->savedWeirdGlobals['mw_namespace_protection'];
116 $wgNamespaceAliases['Image'] = $this->savedWeirdGlobals['image_alias'];
117 $wgNamespaceAliases['Image_talk'] = $this->savedWeirdGlobals['image_talk_alias'];
118
119 // Restore backends
120 RepoGroup::destroySingleton();
121 FileBackendGroup::destroySingleton();
122
123 parent::tearDown();
124 }
125
126 function addDBData() {
127 $this->tablesUsed[] = 'site_stats';
128 $this->tablesUsed[] = 'interwiki';
129 # disabled for performance
130 #$this->tablesUsed[] = 'image';
131
132 # Hack: insert a few Wikipedia in-project interwiki prefixes,
133 # for testing inter-language links
134 $this->db->insert( 'interwiki', array(
135 array( 'iw_prefix' => 'wikipedia',
136 'iw_url' => 'http://en.wikipedia.org/wiki/$1',
137 'iw_api' => '',
138 'iw_wikiid' => '',
139 'iw_local' => 0 ),
140 array( 'iw_prefix' => 'meatball',
141 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
142 'iw_api' => '',
143 'iw_wikiid' => '',
144 'iw_local' => 0 ),
145 array( 'iw_prefix' => 'zh',
146 'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
147 'iw_api' => '',
148 'iw_wikiid' => '',
149 'iw_local' => 1 ),
150 array( 'iw_prefix' => 'es',
151 'iw_url' => 'http://es.wikipedia.org/wiki/$1',
152 'iw_api' => '',
153 'iw_wikiid' => '',
154 'iw_local' => 1 ),
155 array( 'iw_prefix' => 'fr',
156 'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
157 'iw_api' => '',
158 'iw_wikiid' => '',
159 'iw_local' => 1 ),
160 array( 'iw_prefix' => 'ru',
161 'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
162 'iw_api' => '',
163 'iw_wikiid' => '',
164 'iw_local' => 1 ),
165 /**
166 * @todo Fixme! Why are we inserting duplicate data here? Shouldn't
167 * need this IGNORE or shouldn't need the insert at all.
168 */
169 ), __METHOD__, array( 'IGNORE' )
170 );
171
172 # Update certain things in site_stats
173 $this->db->insert( 'site_stats',
174 array( 'ss_row_id' => 1, 'ss_images' => 2, 'ss_good_articles' => 1 ),
175 __METHOD__
176 );
177
178 # Reinitialise the LocalisationCache to match the database state
179 Language::getLocalisationCache()->unloadAll();
180
181 # Clear the message cache
182 MessageCache::singleton()->clear();
183
184 $user = User::newFromId( 0 );
185 LinkCache::singleton()->clear(); # Avoids the odd failure at creating the nullRevision
186
187 # Upload DB table entries for files.
188 # We will upload the actual files later. Note that if anything causes LocalFile::load()
189 # to be triggered before then, it will break via maybeUpgrade() setting the fileExists
190 # member to false and storing it in cache.
191 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Foobar.jpg' ) );
192 if ( !$this->db->selectField( 'image', '1', array( 'img_name' => $image->getName() ) ) ) {
193 $image->recordUpload2(
194 '', // archive name
195 'Upload of some lame file',
196 'Some lame file',
197 array(
198 'size' => 12345,
199 'width' => 1941,
200 'height' => 220,
201 'bits' => 24,
202 'media_type' => MEDIATYPE_BITMAP,
203 'mime' => 'image/jpeg',
204 'metadata' => serialize( array() ),
205 'sha1' => wfBaseConvert( '', 16, 36, 31 ),
206 'fileExists' => true ),
207 $this->db->timestamp( '20010115123500' ), $user
208 );
209 }
210
211 # This image will be blacklisted in [[MediaWiki:Bad image list]]
212 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Bad.jpg' ) );
213 if ( !$this->db->selectField( 'image', '1', array( 'img_name' => $image->getName() ) ) ) {
214 $image->recordUpload2(
215 '', // archive name
216 'zomgnotcensored',
217 'Borderline image',
218 array(
219 'size' => 12345,
220 'width' => 320,
221 'height' => 240,
222 'bits' => 24,
223 'media_type' => MEDIATYPE_BITMAP,
224 'mime' => 'image/jpeg',
225 'metadata' => serialize( array() ),
226 'sha1' => wfBaseConvert( '', 16, 36, 31 ),
227 'fileExists' => true ),
228 $this->db->timestamp( '20010115123500' ), $user
229 );
230 }
231 }
232
233 //ParserTest setup/teardown functions
234
235 /**
236 * Set up the global variables for a consistent environment for each test.
237 * Ideally this should replace the global configuration entirely.
238 */
239 protected function setupGlobals( $opts = '', $config = '' ) {
240 global $wgFileBackends;
241 # Find out values for some special options.
242 $lang =
243 self::getOptionValue( 'language', $opts, 'en' );
244 $variant =
245 self::getOptionValue( 'variant', $opts, false );
246 $maxtoclevel =
247 self::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
248 $linkHolderBatchSize =
249 self::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
250
251 $uploadDir = $this->getUploadDir();
252 if ( $this->getCliArg( 'use-filebackend=' ) ) {
253 if ( self::$backendToUse ) {
254 $backend = self::$backendToUse;
255 } else {
256 $name = $this->getCliArg( 'use-filebackend=' );
257 $useConfig = array();
258 foreach ( $wgFileBackends as $conf ) {
259 if ( $conf['name'] == $name ) {
260 $useConfig = $conf;
261 }
262 }
263 $useConfig['name'] = 'local-backend'; // swap name
264 $class = $conf['class'];
265 self::$backendToUse = new $class( $useConfig );
266 $backend = self::$backendToUse;
267 }
268 } else {
269 $backend = new FSFileBackend( array(
270 'name' => 'local-backend',
271 'lockManager' => 'nullLockManager',
272 'containerPaths' => array(
273 'local-public' => "$uploadDir",
274 'local-thumb' => "$uploadDir/thumb",
275 )
276 ) );
277 }
278
279 $settings = array(
280 'wgServer' => 'http://Britney-Spears',
281 'wgScript' => '/index.php',
282 'wgScriptPath' => '/',
283 'wgArticlePath' => '/wiki/$1',
284 'wgExtensionAssetsPath' => '/extensions',
285 'wgActionPaths' => array(),
286 'wgLocalFileRepo' => array(
287 'class' => 'LocalRepo',
288 'name' => 'local',
289 'url' => 'http://example.com/images',
290 'hashLevels' => 2,
291 'transformVia404' => false,
292 'backend' => $backend
293 ),
294 'wgEnableUploads' => self::getOptionValue( 'wgEnableUploads', $opts, true ),
295 'wgStylePath' => '/skins',
296 'wgStyleSheetPath' => '/skins',
297 'wgSitename' => 'MediaWiki',
298 'wgLanguageCode' => $lang,
299 'wgDBprefix' => $this->db->getType() != 'oracle' ? 'unittest_' : 'ut_',
300 'wgRawHtml' => isset( $opts['rawhtml'] ),
301 'wgLang' => null,
302 'wgContLang' => null,
303 'wgNamespacesWithSubpages' => array( 0 => isset( $opts['subpage'] ) ),
304 'wgMaxTocLevel' => $maxtoclevel,
305 'wgCapitalLinks' => true,
306 'wgNoFollowLinks' => true,
307 'wgNoFollowDomainExceptions' => array(),
308 'wgThumbnailScriptPath' => false,
309 'wgUseImageResize' => true,
310 'wgUseTeX' => isset( $opts['math'] ),
311 'wgMathDirectory' => $uploadDir . '/math',
312 'wgLocaltimezone' => 'UTC',
313 'wgAllowExternalImages' => true,
314 'wgUseTidy' => false,
315 'wgDefaultLanguageVariant' => $variant,
316 'wgVariantArticlePath' => false,
317 'wgGroupPermissions' => array( '*' => array(
318 'createaccount' => true,
319 'read' => true,
320 'edit' => true,
321 'createpage' => true,
322 'createtalk' => true,
323 ) ),
324 'wgNamespaceProtection' => array( NS_MEDIAWIKI => 'editinterface' ),
325 'wgDefaultExternalStore' => array(),
326 'wgForeignFileRepos' => array(),
327 'wgLinkHolderBatchSize' => $linkHolderBatchSize,
328 'wgExperimentalHtmlIds' => false,
329 'wgExternalLinkTarget' => false,
330 'wgAlwaysUseTidy' => false,
331 'wgHtml5' => true,
332 'wgWellFormedXml' => true,
333 'wgAllowMicrodataAttributes' => true,
334 'wgAdaptiveMessageCache' => true,
335 'wgUseDatabaseMessages' => true,
336 );
337
338 if ( $config ) {
339 $configLines = explode( "\n", $config );
340
341 foreach ( $configLines as $line ) {
342 list( $var, $value ) = explode( '=', $line, 2 );
343
344 $settings[$var] = eval( "return $value;" ); //???
345 }
346 }
347
348 $this->savedGlobals = array();
349
350 /** @since 1.20 */
351 wfRunHooks( 'ParserTestGlobals', array( &$settings ) );
352
353 foreach ( $settings as $var => $val ) {
354 if ( array_key_exists( $var, $GLOBALS ) ) {
355 $this->savedGlobals[$var] = $GLOBALS[$var];
356 }
357
358 $GLOBALS[$var] = $val;
359 }
360
361 $langObj = Language::factory( $lang );
362 $GLOBALS['wgContLang'] = $langObj;
363 $context = new RequestContext();
364 $GLOBALS['wgLang'] = $context->getLanguage();
365
366 $GLOBALS['wgMemc'] = new EmptyBagOStuff;
367 $GLOBALS['wgOut'] = $context->getOutput();
368 $GLOBALS['wgUser'] = $context->getUser();
369
370 global $wgHooks;
371
372 $wgHooks['ParserTestParser'][] = 'ParserTestParserHook::setup';
373 $wgHooks['ParserGetVariableValueTs'][] = 'ParserTest::getFakeTimestamp';
374
375 MagicWord::clearCache();
376 RepoGroup::destroySingleton();
377 FileBackendGroup::destroySingleton();
378
379 # Create dummy files in storage
380 $this->setupUploads();
381
382 # Publish the articles after we have the final language set
383 $this->publishTestArticles();
384
385 # The entries saved into RepoGroup cache with previous globals will be wrong.
386 RepoGroup::destroySingleton();
387 FileBackendGroup::destroySingleton();
388 MessageCache::destroyInstance();
389
390 return $context;
391 }
392
393 /**
394 * Get an FS upload directory (only applies to FSFileBackend)
395 *
396 * @return String: the directory
397 */
398 protected function getUploadDir() {
399 if ( $this->keepUploads ) {
400 $dir = wfTempDir() . '/mwParser-images';
401
402 if ( is_dir( $dir ) ) {
403 return $dir;
404 }
405 } else {
406 $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
407 }
408
409 // wfDebug( "Creating upload directory $dir\n" );
410 if ( file_exists( $dir ) ) {
411 wfDebug( "Already exists!\n" );
412 return $dir;
413 }
414
415 return $dir;
416 }
417
418 /**
419 * Create a dummy uploads directory which will contain a couple
420 * of files in order to pass existence tests.
421 *
422 * @return String: the directory
423 */
424 protected function setupUploads() {
425 global $IP;
426
427 $base = $this->getBaseDir();
428 $backend = RepoGroup::singleton()->getLocalRepo()->getBackend();
429 $backend->prepare( array( 'dir' => "$base/local-public/3/3a" ) );
430 $backend->store( array(
431 'src' => "$IP/skins/monobook/headbg.jpg", 'dst' => "$base/local-public/3/3a/Foobar.jpg"
432 ) );
433 $backend->prepare( array( 'dir' => "$base/local-public/0/09" ) );
434 $backend->store( array(
435 'src' => "$IP/skins/monobook/headbg.jpg", 'dst' => "$base/local-public/0/09/Bad.jpg"
436 ) );
437 }
438
439 /**
440 * Restore default values and perform any necessary clean-up
441 * after each test runs.
442 */
443 protected function teardownGlobals() {
444 $this->teardownUploads();
445
446 foreach ( $this->savedGlobals as $var => $val ) {
447 $GLOBALS[$var] = $val;
448 }
449
450 RepoGroup::destroySingleton();
451 LinkCache::singleton()->clear();
452 }
453
454 /**
455 * Remove the dummy uploads directory
456 */
457 private function teardownUploads() {
458 if ( $this->keepUploads ) {
459 return;
460 }
461
462 $base = $this->getBaseDir();
463 // delete the files first, then the dirs.
464 self::deleteFiles(
465 array(
466 "$base/local-public/3/3a/Foobar.jpg",
467 "$base/local-thumb/3/3a/Foobar.jpg/180px-Foobar.jpg",
468 "$base/local-thumb/3/3a/Foobar.jpg/200px-Foobar.jpg",
469 "$base/local-thumb/3/3a/Foobar.jpg/640px-Foobar.jpg",
470 "$base/local-thumb/3/3a/Foobar.jpg/120px-Foobar.jpg",
471 "$base/local-thumb/3/3a/Foobar.jpg/1280px-Foobar.jpg",
472 "$base/local-thumb/3/3a/Foobar.jpg/20px-Foobar.jpg",
473 "$base/local-thumb/3/3a/Foobar.jpg/270px-Foobar.jpg",
474 "$base/local-thumb/3/3a/Foobar.jpg/300px-Foobar.jpg",
475 "$base/local-thumb/3/3a/Foobar.jpg/30px-Foobar.jpg",
476 "$base/local-thumb/3/3a/Foobar.jpg/360px-Foobar.jpg",
477 "$base/local-thumb/3/3a/Foobar.jpg/400px-Foobar.jpg",
478 "$base/local-thumb/3/3a/Foobar.jpg/40px-Foobar.jpg",
479 "$base/local-thumb/3/3a/Foobar.jpg/70px-Foobar.jpg",
480 "$base/local-thumb/3/3a/Foobar.jpg/960px-Foobar.jpg",
481
482 "$base/local-public/0/09/Bad.jpg",
483 "$base/local-thumb/0/09/Bad.jpg",
484
485 "$base/local-public/math/f/a/5/fa50b8b616463173474302ca3e63586b.png",
486 )
487 );
488 }
489
490 /**
491 * Delete the specified files, if they exist.
492 * @param $files Array: full paths to files to delete.
493 */
494 private static function deleteFiles( $files ) {
495 $backend = RepoGroup::singleton()->getLocalRepo()->getBackend();
496 foreach ( $files as $file ) {
497 $backend->delete( array( 'src' => $file ), array( 'force' => 1 ) );
498 }
499 foreach ( $files as $file ) {
500 $tmp = $file;
501 while ( $tmp = FileBackend::parentStoragePath( $tmp ) ) {
502 if ( !$backend->clean( array( 'dir' => $tmp ) )->isOK() ) {
503 break;
504 }
505 }
506 }
507 }
508
509 protected function getBaseDir() {
510 return 'mwstore://local-backend';
511 }
512
513 public function parserTestProvider() {
514 if ( $this->file === false ) {
515 global $wgParserTestFiles;
516 $this->file = $wgParserTestFiles[0];
517 }
518 return new TestFileIterator( $this->file, $this );
519 }
520
521 /**
522 * Set the file from whose tests will be run by this instance
523 */
524 public function setParserTestFile( $filename ) {
525 $this->file = $filename;
526 }
527
528 /**
529 * @group medium
530 * @dataProvider parserTestProvider
531 */
532 public function testParserTest( $desc, $input, $result, $opts, $config ) {
533 if ( $this->regex != '' && !preg_match( '/' . $this->regex . '/', $desc ) ) {
534 $this->assertTrue( true ); // XXX: don't flood output with "test made no assertions"
535 //$this->markTestSkipped( 'Filtered out by the user' );
536 return;
537 }
538
539 if ( !$this->isWikitextNS( NS_MAIN ) ) {
540 // parser tests frequently assume that the main namespace contains wikitext.
541 // @todo: When setting up pages, force the content model. Only skip if
542 // $wgtContentModelUseDB is false.
543 $this->markTestSkipped( "Main namespace does not support wikitext,"
544 . "skipping parser test: $desc" );
545 }
546
547 wfDebug( "Running parser test: $desc\n" );
548
549 $opts = $this->parseOptions( $opts );
550 $context = $this->setupGlobals( $opts, $config );
551
552 $user = $context->getUser();
553 $options = ParserOptions::newFromContext( $context );
554
555 if ( isset( $opts['title'] ) ) {
556 $titleText = $opts['title'];
557 } else {
558 $titleText = 'Parser test';
559 }
560
561 $local = isset( $opts['local'] );
562 $preprocessor = isset( $opts['preprocessor'] ) ? $opts['preprocessor'] : null;
563 $parser = $this->getParser( $preprocessor );
564
565 $title = Title::newFromText( $titleText );
566
567 if ( isset( $opts['pst'] ) ) {
568 $out = $parser->preSaveTransform( $input, $title, $user, $options );
569 } elseif ( isset( $opts['msg'] ) ) {
570 $out = $parser->transformMsg( $input, $options, $title );
571 } elseif ( isset( $opts['section'] ) ) {
572 $section = $opts['section'];
573 $out = $parser->getSection( $input, $section );
574 } elseif ( isset( $opts['replace'] ) ) {
575 $section = $opts['replace'][0];
576 $replace = $opts['replace'][1];
577 $out = $parser->replaceSection( $input, $section, $replace );
578 } elseif ( isset( $opts['comment'] ) ) {
579 $out = Linker::formatComment( $input, $title, $local );
580 } elseif ( isset( $opts['preload'] ) ) {
581 $out = $parser->getpreloadText( $input, $title, $options );
582 } else {
583 $output = $parser->parse( $input, $title, $options, true, true, 1337 );
584 $out = $output->getText();
585
586 if ( isset( $opts['showtitle'] ) ) {
587 if ( $output->getTitleText() ) {
588 $title = $output->getTitleText();
589 }
590
591 $out = "$title\n$out";
592 }
593
594 if ( isset( $opts['ill'] ) ) {
595 $out = $this->tidy( implode( ' ', $output->getLanguageLinks() ) );
596 } elseif ( isset( $opts['cat'] ) ) {
597 $outputPage = $context->getOutput();
598 $outputPage->addCategoryLinks( $output->getCategories() );
599 $cats = $outputPage->getCategoryLinks();
600
601 if ( isset( $cats['normal'] ) ) {
602 $out = $this->tidy( implode( ' ', $cats['normal'] ) );
603 } else {
604 $out = '';
605 }
606 }
607 $parser->mPreprocessor = null;
608
609 $result = $this->tidy( $result );
610 }
611
612 $this->teardownGlobals();
613
614 $this->assertEquals( $result, $out, $desc );
615 }
616
617 /**
618 * Run a fuzz test series
619 * Draw input from a set of test files
620 *
621 * @todo fixme Needs some work to not eat memory until the world explodes
622 *
623 * @group ParserFuzz
624 */
625 function testFuzzTests() {
626 global $wgParserTestFiles;
627
628 $files = $wgParserTestFiles;
629
630 if ( $this->getCliArg( 'file=' ) ) {
631 $files = array( $this->getCliArg( 'file=' ) );
632 }
633
634 $dict = $this->getFuzzInput( $files );
635 $dictSize = strlen( $dict );
636 $logMaxLength = log( $this->maxFuzzTestLength );
637
638 ini_set( 'memory_limit', $this->memoryLimit * 1048576 );
639
640 $user = new User;
641 $opts = ParserOptions::newFromUser( $user );
642 $title = Title::makeTitle( NS_MAIN, 'Parser_test' );
643
644 $id = 1;
645
646 while ( true ) {
647
648 // Generate test input
649 mt_srand( ++$this->fuzzSeed );
650 $totalLength = mt_rand( 1, $this->maxFuzzTestLength );
651 $input = '';
652
653 while ( strlen( $input ) < $totalLength ) {
654 $logHairLength = mt_rand( 0, 1000000 ) / 1000000 * $logMaxLength;
655 $hairLength = min( intval( exp( $logHairLength ) ), $dictSize );
656 $offset = mt_rand( 0, $dictSize - $hairLength );
657 $input .= substr( $dict, $offset, $hairLength );
658 }
659
660 $this->setupGlobals();
661 $parser = $this->getParser();
662
663 // Run the test
664 try {
665 $parser->parse( $input, $title, $opts );
666 $this->assertTrue( true, "Test $id, fuzz seed {$this->fuzzSeed}" );
667 } catch ( Exception $exception ) {
668 $input_dump = sprintf( "string(%d) \"%s\"\n", strlen( $input ), $input );
669
670 $this->assertTrue( false, "Test $id, fuzz seed {$this->fuzzSeed}. \n\nInput: $input_dump\n\nError: {$exception->getMessage()}\n\nBacktrace: {$exception->getTraceAsString()}" );
671 }
672
673 $this->teardownGlobals();
674 $parser->__destruct();
675
676 if ( $id % 100 == 0 ) {
677 $usage = intval( memory_get_usage( true ) / $this->memoryLimit / 1048576 * 100 );
678 //echo "{$this->fuzzSeed}: $numSuccess/$numTotal (mem: $usage%)\n";
679 if ( $usage > 90 ) {
680 $ret = "Out of memory:\n";
681 $memStats = $this->getMemoryBreakdown();
682
683 foreach ( $memStats as $name => $usage ) {
684 $ret .= "$name: $usage\n";
685 }
686
687 throw new MWException( $ret );
688 }
689 }
690
691 $id++;
692
693 }
694 }
695
696 //Various getter functions
697
698 /**
699 * Get an input dictionary from a set of parser test files
700 */
701 function getFuzzInput( $filenames ) {
702 $dict = '';
703
704 foreach ( $filenames as $filename ) {
705 $contents = file_get_contents( $filename );
706 preg_match_all( '/!!\s*input\n(.*?)\n!!\s*result/s', $contents, $matches );
707
708 foreach ( $matches[1] as $match ) {
709 $dict .= $match . "\n";
710 }
711 }
712
713 return $dict;
714 }
715
716 /**
717 * Get a memory usage breakdown
718 */
719 function getMemoryBreakdown() {
720 $memStats = array();
721
722 foreach ( $GLOBALS as $name => $value ) {
723 $memStats['$' . $name] = strlen( serialize( $value ) );
724 }
725
726 $classes = get_declared_classes();
727
728 foreach ( $classes as $class ) {
729 $rc = new ReflectionClass( $class );
730 $props = $rc->getStaticProperties();
731 $memStats[$class] = strlen( serialize( $props ) );
732 $methods = $rc->getMethods();
733
734 foreach ( $methods as $method ) {
735 $memStats[$class] += strlen( serialize( $method->getStaticVariables() ) );
736 }
737 }
738
739 $functions = get_defined_functions();
740
741 foreach ( $functions['user'] as $function ) {
742 $rf = new ReflectionFunction( $function );
743 $memStats["$function()"] = strlen( serialize( $rf->getStaticVariables() ) );
744 }
745
746 asort( $memStats );
747
748 return $memStats;
749 }
750
751 /**
752 * Get a Parser object
753 */
754 function getParser( $preprocessor = null ) {
755 global $wgParserConf;
756
757 $class = $wgParserConf['class'];
758 $parser = new $class( array( 'preprocessorClass' => $preprocessor ) + $wgParserConf );
759
760 wfRunHooks( 'ParserTestParser', array( &$parser ) );
761
762 return $parser;
763 }
764
765 //Various action functions
766
767 public function addArticle( $name, $text, $line ) {
768 self::$articles[$name] = array( $text, $line );
769 }
770
771 public function publishTestArticles() {
772 if ( empty( self::$articles ) ) {
773 return;
774 }
775
776 foreach ( self::$articles as $name => $info ) {
777 list( $text, $line ) = $info;
778 ParserTest::addArticle( $name, $text, $line, 'ignoreduplicate' );
779 }
780 }
781
782 /**
783 * Steal a callback function from the primary parser, save it for
784 * application to our scary parser. If the hook is not installed,
785 * abort processing of this file.
786 *
787 * @param $name String
788 * @return Bool true if tag hook is present
789 */
790 public function requireHook( $name ) {
791 global $wgParser;
792 $wgParser->firstCallInit(); // make sure hooks are loaded.
793 return isset( $wgParser->mTagHooks[$name] );
794 }
795
796 public function requireFunctionHook( $name ) {
797 global $wgParser;
798 $wgParser->firstCallInit(); // make sure hooks are loaded.
799 return isset( $wgParser->mFunctionHooks[$name] );
800 }
801
802 //Various "cleanup" functions
803
804 /**
805 * Run the "tidy" command on text if the $wgUseTidy
806 * global is true
807 *
808 * @param $text String: the text to tidy
809 * @return String
810 */
811 protected function tidy( $text ) {
812 global $wgUseTidy;
813
814 if ( $wgUseTidy ) {
815 $text = MWTidy::tidy( $text );
816 }
817
818 return $text;
819 }
820
821 /**
822 * Remove last character if it is a newline
823 */
824 public function removeEndingNewline( $s ) {
825 if ( substr( $s, -1 ) === "\n" ) {
826 return substr( $s, 0, -1 );
827 } else {
828 return $s;
829 }
830 }
831
832 //Test options parser functions
833
834 protected function parseOptions( $instring ) {
835 $opts = array();
836 // foo
837 // foo=bar
838 // foo="bar baz"
839 // foo=[[bar baz]]
840 // foo=bar,"baz quux"
841 $regex = '/\b
842 ([\w-]+) # Key
843 \b
844 (?:\s*
845 = # First sub-value
846 \s*
847 (
848 "
849 [^"]* # Quoted val
850 "
851 |
852 \[\[
853 [^]]* # Link target
854 \]\]
855 |
856 [\w-]+ # Plain word
857 )
858 (?:\s*
859 , # Sub-vals 1..N
860 \s*
861 (
862 "[^"]*" # Quoted val
863 |
864 \[\[[^]]*\]\] # Link target
865 |
866 [\w-]+ # Plain word
867 )
868 )*
869 )?
870 /x';
871
872 if ( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER ) ) {
873 foreach ( $matches as $bits ) {
874 array_shift( $bits );
875 $key = strtolower( array_shift( $bits ) );
876 if ( count( $bits ) == 0 ) {
877 $opts[$key] = true;
878 } elseif ( count( $bits ) == 1 ) {
879 $opts[$key] = $this->cleanupOption( array_shift( $bits ) );
880 } else {
881 // Array!
882 $opts[$key] = array_map( array( $this, 'cleanupOption' ), $bits );
883 }
884 }
885 }
886 return $opts;
887 }
888
889 protected function cleanupOption( $opt ) {
890 if ( substr( $opt, 0, 1 ) == '"' ) {
891 return substr( $opt, 1, -1 );
892 }
893
894 if ( substr( $opt, 0, 2 ) == '[[' ) {
895 return substr( $opt, 2, -2 );
896 }
897 return $opt;
898 }
899
900 /**
901 * Use a regex to find out the value of an option
902 * @param $key String: name of option val to retrieve
903 * @param $opts Options array to look in
904 * @param $default Mixed: default value returned if not found
905 */
906 protected static function getOptionValue( $key, $opts, $default ) {
907 $key = strtolower( $key );
908
909 if ( isset( $opts[$key] ) ) {
910 return $opts[$key];
911 } else {
912 return $default;
913 }
914 }
915 }