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