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