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