Merge "Message tweaks to new login and create acct forms"
[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 $runParsoid = false;
20 public $regex = '';
21 public $showProgress = true;
22 public $savedWeirdGlobals = array();
23 public $savedGlobals = array();
24 public $hooks = array();
25 public $functionHooks = array();
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 $wgNamespaceAliases;
36 global $wgHooks, $IP;
37
38 parent::setUp();
39
40 //Setup CLI arguments
41 if ( $this->getCliArg( 'regex=' ) ) {
42 $this->regex = $this->getCliArg( 'regex=' );
43 } else {
44 # Matches anything
45 $this->regex = '';
46 }
47
48 $this->keepUploads = $this->getCliArg( 'keep-uploads' );
49
50 $tmpGlobals = array();
51
52 $tmpGlobals['wgLanguageCode'] = 'en';
53 $tmpGlobals['wgContLang'] = Language::factory( 'en' );
54 $tmpGlobals['wgSitename'] = 'MediaWiki';
55 $tmpGlobals['wgServer'] = 'http://example.org';
56 $tmpGlobals['wgScript'] = '/index.php';
57 $tmpGlobals['wgScriptPath'] = '/';
58 $tmpGlobals['wgArticlePath'] = '/wiki/$1';
59 $tmpGlobals['wgActionPaths'] = array();
60 $tmpGlobals['wgVariantArticlePath'] = false;
61 $tmpGlobals['wgExtensionAssetsPath'] = '/extensions';
62 $tmpGlobals['wgStyleSheetPath'] = '/skins';
63 $tmpGlobals['wgStylePath'] = '/skins';
64 $tmpGlobals['wgEnableUploads'] = true;
65 $tmpGlobals['wgThumbnailScriptPath'] = false;
66 $tmpGlobals['wgLocalFileRepo'] = array(
67 'class' => 'LocalRepo',
68 'name' => 'local',
69 'url' => 'http://example.com/images',
70 'hashLevels' => 2,
71 'transformVia404' => false,
72 'backend' => 'local-backend'
73 );
74 $tmpGlobals['wgForeignFileRepos'] = array();
75 $tmpGlobals['wgDefaultExternalStore'] = array();
76 $tmpGlobals['wgEnableParserCache'] = false;
77 $tmpGlobals['wgCapitalLinks'] = true;
78 $tmpGlobals['wgNoFollowLinks'] = true;
79 $tmpGlobals['wgNoFollowDomainExceptions'] = array();
80 $tmpGlobals['wgExternalLinkTarget'] = false;
81 $tmpGlobals['wgThumbnailScriptPath'] = false;
82 $tmpGlobals['wgUseImageResize'] = true;
83 $tmpGlobals['wgAllowExternalImages'] = true;
84 $tmpGlobals['wgRawHtml'] = false;
85 $tmpGlobals['wgUseTidy'] = false;
86 $tmpGlobals['wgAlwaysUseTidy'] = false;
87 $tmpGlobals['wgHtml5'] = true;
88 $tmpGlobals['wgWellFormedXml'] = true;
89 $tmpGlobals['wgAllowMicrodataAttributes'] = true;
90 $tmpGlobals['wgExperimentalHtmlIds'] = false;
91 $tmpGlobals['wgAdaptiveMessageCache'] = true;
92 $tmpGlobals['wgUseDatabaseMessages'] = true;
93 $tmpGlobals['wgLocaltimezone'] = 'UTC';
94 $tmpGlobals['wgDeferredUpdateList'] = array();
95 $tmpGlobals['wgGroupPermissions'] = array(
96 '*' => array(
97 'createaccount' => true,
98 'read' => true,
99 'edit' => true,
100 'createpage' => true,
101 'createtalk' => true,
102 ) );
103 $tmpGlobals['wgNamespaceProtection'] = array( NS_MEDIAWIKI => 'editinterface' );
104 $tmpGlobals['wgMemc'] = new EmptyBagOStuff;
105 $tmpGlobals['messageMemc'] = wfGetMessageCacheStorage();
106 $tmpGlobals['parserMemc'] = wfGetParserCacheStorage();
107
108 $tmpGlobals['wgParser'] = new StubObject( 'wgParser', $GLOBALS['wgParserConf']['class'], array( $GLOBALS['wgParserConf'] ) );
109
110 if ( $GLOBALS['wgStyleDirectory'] === false ) {
111 $tmpGlobals['wgStyleDirectory'] = "$IP/skins";
112 }
113
114 $tmpHooks = $wgHooks;
115 $tmpHooks['ParserTestParser'][] = 'ParserTestParserHook::setup';
116 $tmpHooks['ParserGetVariableValueTs'][] = 'ParserTest::getFakeTimestamp';
117 $tmpGlobals['wgHooks'] = $tmpHooks;
118
119 $this->setMwGlobals( $tmpGlobals );
120
121 $this->savedWeirdGlobals['image_alias'] = $wgNamespaceAliases['Image'];
122 $this->savedWeirdGlobals['image_talk_alias'] = $wgNamespaceAliases['Image_talk'];
123
124 $wgNamespaceAliases['Image'] = NS_FILE;
125 $wgNamespaceAliases['Image_talk'] = NS_FILE_TALK;
126 }
127
128 protected function tearDown() {
129 global $wgNamespaceAliases;
130
131 $wgNamespaceAliases['Image'] = $this->savedWeirdGlobals['image_alias'];
132 $wgNamespaceAliases['Image_talk'] = $this->savedWeirdGlobals['image_talk_alias'];
133
134 // Restore backends
135 RepoGroup::destroySingleton();
136 FileBackendGroup::destroySingleton();
137
138 parent::tearDown();
139 }
140
141 function addDBData() {
142 $this->tablesUsed[] = 'site_stats';
143 $this->tablesUsed[] = 'interwiki';
144 # disabled for performance
145 #$this->tablesUsed[] = 'image';
146
147 # Hack: insert a few Wikipedia in-project interwiki prefixes,
148 # for testing inter-language links
149 $this->db->insert( 'interwiki', array(
150 array( 'iw_prefix' => 'wikipedia',
151 'iw_url' => 'http://en.wikipedia.org/wiki/$1',
152 'iw_api' => '',
153 'iw_wikiid' => '',
154 'iw_local' => 0 ),
155 array( 'iw_prefix' => 'meatball',
156 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
157 'iw_api' => '',
158 'iw_wikiid' => '',
159 'iw_local' => 0 ),
160 array( 'iw_prefix' => 'zh',
161 'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
162 'iw_api' => '',
163 'iw_wikiid' => '',
164 'iw_local' => 1 ),
165 array( 'iw_prefix' => 'es',
166 'iw_url' => 'http://es.wikipedia.org/wiki/$1',
167 'iw_api' => '',
168 'iw_wikiid' => '',
169 'iw_local' => 1 ),
170 array( 'iw_prefix' => 'fr',
171 'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
172 'iw_api' => '',
173 'iw_wikiid' => '',
174 'iw_local' => 1 ),
175 array( 'iw_prefix' => 'ru',
176 'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
177 'iw_api' => '',
178 'iw_wikiid' => '',
179 'iw_local' => 1 ),
180 /**
181 * @todo Fixme! Why are we inserting duplicate data here? Shouldn't
182 * need this IGNORE or shouldn't need the insert at all.
183 */
184 ), __METHOD__, array( 'IGNORE' )
185 );
186
187 # Update certain things in site_stats
188 $this->db->insert( 'site_stats',
189 array( 'ss_row_id' => 1, 'ss_images' => 2, 'ss_good_articles' => 1 ),
190 __METHOD__
191 );
192
193 # Clear the message cache
194 MessageCache::singleton()->clear();
195
196 $user = User::newFromId( 0 );
197 LinkCache::singleton()->clear(); # Avoids the odd failure at creating the nullRevision
198
199 # Upload DB table entries for files.
200 # We will upload the actual files later. Note that if anything causes LocalFile::load()
201 # to be triggered before then, it will break via maybeUpgrade() setting the fileExists
202 # member to false and storing it in cache.
203 # note that the size/width/height/bits/etc of the file
204 # are actually set by inspecting the file itself; the arguments
205 # to recordUpload2 have no effect. That said, we try to make things
206 # match up so it is less confusing to readers of the code & tests.
207 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Foobar.jpg' ) );
208 if ( !$this->db->selectField( 'image', '1', array( 'img_name' => $image->getName() ) ) ) {
209 $image->recordUpload2(
210 '', // archive name
211 'Upload of some lame file',
212 'Some lame file',
213 array(
214 'size' => 7881,
215 'width' => 1941,
216 'height' => 220,
217 'bits' => 8,
218 'media_type' => MEDIATYPE_BITMAP,
219 'mime' => 'image/jpeg',
220 'metadata' => serialize( array() ),
221 'sha1' => wfBaseConvert( '1', 16, 36, 31 ),
222 'fileExists' => true ),
223 $this->db->timestamp( '20010115123500' ), $user
224 );
225 }
226
227 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Thumb.png' ) );
228 if ( !$this->db->selectField( 'image', '1', array( 'img_name' => $image->getName() ) ) ) {
229 $image->recordUpload2(
230 '', // archive name
231 'Upload of some lame thumbnail',
232 'Some lame thumbnail',
233 array(
234 'size' => 22589,
235 'width' => 135,
236 'height' => 135,
237 'bits' => 8,
238 'media_type' => MEDIATYPE_BITMAP,
239 'mime' => 'image/png',
240 'metadata' => serialize( array() ),
241 'sha1' => wfBaseConvert( '2', 16, 36, 31 ),
242 'fileExists' => true ),
243 $this->db->timestamp( '20130225203040' ), $user
244 );
245 }
246
247 # This image will be blacklisted in [[MediaWiki:Bad image list]]
248 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Bad.jpg' ) );
249 if ( !$this->db->selectField( 'image', '1', array( 'img_name' => $image->getName() ) ) ) {
250 $image->recordUpload2(
251 '', // archive name
252 'zomgnotcensored',
253 'Borderline image',
254 array(
255 'size' => 12345,
256 'width' => 320,
257 'height' => 240,
258 'bits' => 24,
259 'media_type' => MEDIATYPE_BITMAP,
260 'mime' => 'image/jpeg',
261 'metadata' => serialize( array() ),
262 'sha1' => wfBaseConvert( '3', 16, 36, 31 ),
263 'fileExists' => true ),
264 $this->db->timestamp( '20010115123500' ), $user
265 );
266 }
267 }
268
269 //ParserTest setup/teardown functions
270
271 /**
272 * Set up the global variables for a consistent environment for each test.
273 * Ideally this should replace the global configuration entirely.
274 */
275 protected function setupGlobals( $opts = array(), $config = '' ) {
276 global $wgFileBackends;
277 # Find out values for some special options.
278 $lang =
279 self::getOptionValue( 'language', $opts, 'en' );
280 $variant =
281 self::getOptionValue( 'variant', $opts, false );
282 $maxtoclevel =
283 self::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
284 $linkHolderBatchSize =
285 self::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
286
287 $uploadDir = $this->getUploadDir();
288 if ( $this->getCliArg( 'use-filebackend=' ) ) {
289 if ( self::$backendToUse ) {
290 $backend = self::$backendToUse;
291 } else {
292 $name = $this->getCliArg( 'use-filebackend=' );
293 $useConfig = array();
294 foreach ( $wgFileBackends as $conf ) {
295 if ( $conf['name'] == $name ) {
296 $useConfig = $conf;
297 }
298 }
299 $useConfig['name'] = 'local-backend'; // swap name
300 $class = $conf['class'];
301 self::$backendToUse = new $class( $useConfig );
302 $backend = self::$backendToUse;
303 }
304 } else {
305 $backend = new FSFileBackend( array(
306 'name' => 'local-backend',
307 'lockManager' => 'nullLockManager',
308 'containerPaths' => array(
309 'local-public' => "$uploadDir",
310 'local-thumb' => "$uploadDir/thumb",
311 )
312 ) );
313 }
314
315 $settings = array(
316 'wgLocalFileRepo' => array(
317 'class' => 'LocalRepo',
318 'name' => 'local',
319 'url' => 'http://example.com/images',
320 'hashLevels' => 2,
321 'transformVia404' => false,
322 'backend' => $backend
323 ),
324 'wgEnableUploads' => self::getOptionValue( 'wgEnableUploads', $opts, true ),
325 'wgLanguageCode' => $lang,
326 'wgDBprefix' => $this->db->getType() != 'oracle' ? 'unittest_' : 'ut_',
327 'wgRawHtml' => isset( $opts['rawhtml'] ),
328 'wgNamespacesWithSubpages' => array( NS_MAIN => isset( $opts['subpage'] ) ),
329 'wgMaxTocLevel' => $maxtoclevel,
330 'wgUseTeX' => isset( $opts['math'] ),
331 'wgMathDirectory' => $uploadDir . '/math',
332 'wgDefaultLanguageVariant' => $variant,
333 'wgLinkHolderBatchSize' => $linkHolderBatchSize,
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 $langObj = Language::factory( $lang );
352 $settings['wgContLang'] = $langObj;
353 $settings['wgLang'] = $langObj;
354
355 $context = new RequestContext();
356 $settings['wgOut'] = $context->getOutput();
357 $settings['wgUser'] = $context->getUser();
358 $settings['wgRequest'] = $context->getRequest();
359
360 foreach ( $settings as $var => $val ) {
361 if ( array_key_exists( $var, $GLOBALS ) ) {
362 $this->savedGlobals[$var] = $GLOBALS[$var];
363 }
364
365 $GLOBALS[$var] = $val;
366 }
367
368 MagicWord::clearCache();
369 RepoGroup::destroySingleton();
370 FileBackendGroup::destroySingleton();
371
372 # Create dummy files in storage
373 $this->setupUploads();
374
375 # Publish the articles after we have the final language set
376 $this->publishTestArticles();
377
378 # The entries saved into RepoGroup cache with previous globals will be wrong.
379 RepoGroup::destroySingleton();
380 FileBackendGroup::destroySingleton();
381 MessageCache::destroyInstance();
382
383 return $context;
384 }
385
386 /**
387 * Get an FS upload directory (only applies to FSFileBackend)
388 *
389 * @return String: the directory
390 */
391 protected function getUploadDir() {
392 if ( $this->keepUploads ) {
393 $dir = wfTempDir() . '/mwParser-images';
394
395 if ( is_dir( $dir ) ) {
396 return $dir;
397 }
398 } else {
399 $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
400 }
401
402 // wfDebug( "Creating upload directory $dir\n" );
403 if ( file_exists( $dir ) ) {
404 wfDebug( "Already exists!\n" );
405
406 return $dir;
407 }
408
409 return $dir;
410 }
411
412 /**
413 * Create a dummy uploads directory which will contain a couple
414 * of files in order to pass existence tests.
415 *
416 * @return String: the directory
417 */
418 protected function setupUploads() {
419 global $IP;
420
421 $base = $this->getBaseDir();
422 $backend = RepoGroup::singleton()->getLocalRepo()->getBackend();
423 $backend->prepare( array( 'dir' => "$base/local-public/3/3a" ) );
424 $backend->store( array(
425 'src' => "$IP/skins/monobook/headbg.jpg", 'dst' => "$base/local-public/3/3a/Foobar.jpg"
426 ) );
427 $backend->prepare( array( 'dir' => "$base/local-public/e/ea" ) );
428 $backend->store( array(
429 'src' => "$IP/skins/monobook/wiki.png", 'dst' => "$base/local-public/e/ea/Thumb.png"
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/e/ea/Thumb.png",
481
482 "$base/local-public/0/09/Bad.jpg",
483
484 "$base/local-public/math/f/a/5/fa50b8b616463173474302ca3e63586b.png",
485 )
486 );
487 }
488
489 /**
490 * Delete the specified files, if they exist.
491 * @param $files Array: full paths to files to delete.
492 */
493 private static function deleteFiles( $files ) {
494 $backend = RepoGroup::singleton()->getLocalRepo()->getBackend();
495 foreach ( $files as $file ) {
496 $backend->delete( array( 'src' => $file ), array( 'force' => 1 ) );
497 }
498 foreach ( $files as $file ) {
499 $tmp = $file;
500 while ( $tmp = FileBackend::parentStoragePath( $tmp ) ) {
501 if ( !$backend->clean( array( 'dir' => $tmp ) )->isOK() ) {
502 break;
503 }
504 }
505 }
506 }
507
508 protected function getBaseDir() {
509 return 'mwstore://local-backend';
510 }
511
512 public function parserTestProvider() {
513 if ( $this->file === false ) {
514 global $wgParserTestFiles;
515 $this->file = $wgParserTestFiles[0];
516 }
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 //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
801 //Various "cleanup" functions
802
803 /**
804 * Run the "tidy" command on text if the $wgUseTidy
805 * global is true
806 *
807 * @param $text String: the text to tidy
808 * @return String
809 */
810 protected function tidy( $text ) {
811 global $wgUseTidy;
812
813 if ( $wgUseTidy ) {
814 $text = MWTidy::tidy( $text );
815 }
816
817 return $text;
818 }
819
820 /**
821 * Remove last character if it is a newline
822 */
823 public function removeEndingNewline( $s ) {
824 if ( substr( $s, -1 ) === "\n" ) {
825 return substr( $s, 0, -1 );
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
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
898 return $opt;
899 }
900
901 /**
902 * Use a regex to find out the value of an option
903 * @param $key String: name of option val to retrieve
904 * @param $opts Options array to look in
905 * @param $default Mixed: default value returned if not found
906 */
907 protected static function getOptionValue( $key, $opts, $default ) {
908 $key = strtolower( $key );
909
910 if ( isset( $opts[$key] ) ) {
911 return $opts[$key];
912 } else {
913 return $default;
914 }
915 }
916 }