tests: Don't set wgStyleSheetPath in addition to wgStylePath
[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['wgStylePath'] = '/skins';
63 $tmpGlobals['wgEnableUploads'] = true;
64 $tmpGlobals['wgThumbnailScriptPath'] = false;
65 $tmpGlobals['wgLocalFileRepo'] = array(
66 'class' => 'LocalRepo',
67 'name' => 'local',
68 'url' => 'http://example.com/images',
69 'hashLevels' => 2,
70 'transformVia404' => false,
71 'backend' => 'local-backend'
72 );
73 $tmpGlobals['wgForeignFileRepos'] = array();
74 $tmpGlobals['wgDefaultExternalStore'] = array();
75 $tmpGlobals['wgEnableParserCache'] = false;
76 $tmpGlobals['wgCapitalLinks'] = true;
77 $tmpGlobals['wgNoFollowLinks'] = true;
78 $tmpGlobals['wgNoFollowDomainExceptions'] = array();
79 $tmpGlobals['wgExternalLinkTarget'] = false;
80 $tmpGlobals['wgThumbnailScriptPath'] = false;
81 $tmpGlobals['wgUseImageResize'] = true;
82 $tmpGlobals['wgAllowExternalImages'] = true;
83 $tmpGlobals['wgRawHtml'] = false;
84 $tmpGlobals['wgUseTidy'] = false;
85 $tmpGlobals['wgAlwaysUseTidy'] = false;
86 $tmpGlobals['wgHtml5'] = true;
87 $tmpGlobals['wgWellFormedXml'] = true;
88 $tmpGlobals['wgAllowMicrodataAttributes'] = true;
89 $tmpGlobals['wgExperimentalHtmlIds'] = false;
90 $tmpGlobals['wgAdaptiveMessageCache'] = true;
91 $tmpGlobals['wgUseDatabaseMessages'] = true;
92 $tmpGlobals['wgLocaltimezone'] = 'UTC';
93 $tmpGlobals['wgDeferredUpdateList'] = array();
94 $tmpGlobals['wgGroupPermissions'] = array(
95 '*' => array(
96 'createaccount' => true,
97 'read' => true,
98 'edit' => true,
99 'createpage' => true,
100 'createtalk' => true,
101 ) );
102 $tmpGlobals['wgNamespaceProtection'] = array( NS_MEDIAWIKI => 'editinterface' );
103 $tmpGlobals['wgMemc'] = new EmptyBagOStuff;
104 $tmpGlobals['messageMemc'] = wfGetMessageCacheStorage();
105 $tmpGlobals['parserMemc'] = wfGetParserCacheStorage();
106
107 $tmpGlobals['wgParser'] = new StubObject( 'wgParser', $GLOBALS['wgParserConf']['class'], array( $GLOBALS['wgParserConf'] ) );
108
109 if ( $GLOBALS['wgStyleDirectory'] === false ) {
110 $tmpGlobals['wgStyleDirectory'] = "$IP/skins";
111 }
112
113 $tmpHooks = $wgHooks;
114 $tmpHooks['ParserTestParser'][] = 'ParserTestParserHook::setup';
115 $tmpHooks['ParserGetVariableValueTs'][] = 'ParserTest::getFakeTimestamp';
116 $tmpGlobals['wgHooks'] = $tmpHooks;
117
118 $this->setMwGlobals( $tmpGlobals );
119
120 $this->savedWeirdGlobals['image_alias'] = $wgNamespaceAliases['Image'];
121 $this->savedWeirdGlobals['image_talk_alias'] = $wgNamespaceAliases['Image_talk'];
122
123 $wgNamespaceAliases['Image'] = NS_FILE;
124 $wgNamespaceAliases['Image_talk'] = NS_FILE_TALK;
125 }
126
127 protected function tearDown() {
128 global $wgNamespaceAliases;
129
130 $wgNamespaceAliases['Image'] = $this->savedWeirdGlobals['image_alias'];
131 $wgNamespaceAliases['Image_talk'] = $this->savedWeirdGlobals['image_talk_alias'];
132
133 // Restore backends
134 RepoGroup::destroySingleton();
135 FileBackendGroup::destroySingleton();
136
137 parent::tearDown();
138 }
139
140 function addDBData() {
141 $this->tablesUsed[] = 'site_stats';
142 $this->tablesUsed[] = 'interwiki';
143 # disabled for performance
144 #$this->tablesUsed[] = 'image';
145
146 # Hack: insert a few Wikipedia in-project interwiki prefixes,
147 # for testing inter-language links
148 $this->db->insert( 'interwiki', array(
149 array( 'iw_prefix' => 'wikipedia',
150 'iw_url' => 'http://en.wikipedia.org/wiki/$1',
151 'iw_api' => '',
152 'iw_wikiid' => '',
153 'iw_local' => 0 ),
154 array( 'iw_prefix' => 'meatball',
155 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
156 'iw_api' => '',
157 'iw_wikiid' => '',
158 'iw_local' => 0 ),
159 array( 'iw_prefix' => 'zh',
160 'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
161 'iw_api' => '',
162 'iw_wikiid' => '',
163 'iw_local' => 1 ),
164 array( 'iw_prefix' => 'es',
165 'iw_url' => 'http://es.wikipedia.org/wiki/$1',
166 'iw_api' => '',
167 'iw_wikiid' => '',
168 'iw_local' => 1 ),
169 array( 'iw_prefix' => 'fr',
170 'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
171 'iw_api' => '',
172 'iw_wikiid' => '',
173 'iw_local' => 1 ),
174 array( 'iw_prefix' => 'ru',
175 'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
176 'iw_api' => '',
177 'iw_wikiid' => '',
178 'iw_local' => 1 ),
179 /**
180 * @todo Fixme! Why are we inserting duplicate data here? Shouldn't
181 * need this IGNORE or shouldn't need the insert at all.
182 */
183 ), __METHOD__, array( 'IGNORE' )
184 );
185
186 # Update certain things in site_stats
187 $this->db->insert( 'site_stats',
188 array( 'ss_row_id' => 1, 'ss_images' => 2, 'ss_good_articles' => 1 ),
189 __METHOD__
190 );
191
192 # Clear the message cache
193 MessageCache::singleton()->clear();
194
195 $user = User::newFromId( 0 );
196 LinkCache::singleton()->clear(); # Avoids the odd failure at creating the nullRevision
197
198 # Upload DB table entries for files.
199 # We will upload the actual files later. Note that if anything causes LocalFile::load()
200 # to be triggered before then, it will break via maybeUpgrade() setting the fileExists
201 # member to false and storing it in cache.
202 # note that the size/width/height/bits/etc of the file
203 # are actually set by inspecting the file itself; the arguments
204 # to recordUpload2 have no effect. That said, we try to make things
205 # match up so it is less confusing to readers of the code & tests.
206 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Foobar.jpg' ) );
207 if ( !$this->db->selectField( 'image', '1', array( 'img_name' => $image->getName() ) ) ) {
208 $image->recordUpload2(
209 '', // archive name
210 'Upload of some lame file',
211 'Some lame file',
212 array(
213 'size' => 7881,
214 'width' => 1941,
215 'height' => 220,
216 'bits' => 8,
217 'media_type' => MEDIATYPE_BITMAP,
218 'mime' => 'image/jpeg',
219 'metadata' => serialize( array() ),
220 'sha1' => wfBaseConvert( '1', 16, 36, 31 ),
221 'fileExists' => true ),
222 $this->db->timestamp( '20010115123500' ), $user
223 );
224 }
225
226 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Thumb.png' ) );
227 if ( !$this->db->selectField( 'image', '1', array( 'img_name' => $image->getName() ) ) ) {
228 $image->recordUpload2(
229 '', // archive name
230 'Upload of some lame thumbnail',
231 'Some lame thumbnail',
232 array(
233 'size' => 22589,
234 'width' => 135,
235 'height' => 135,
236 'bits' => 8,
237 'media_type' => MEDIATYPE_BITMAP,
238 'mime' => 'image/png',
239 'metadata' => serialize( array() ),
240 'sha1' => wfBaseConvert( '2', 16, 36, 31 ),
241 'fileExists' => true ),
242 $this->db->timestamp( '20130225203040' ), $user
243 );
244 }
245
246 # This image will be blacklisted in [[MediaWiki:Bad image list]]
247 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Bad.jpg' ) );
248 if ( !$this->db->selectField( 'image', '1', array( 'img_name' => $image->getName() ) ) ) {
249 $image->recordUpload2(
250 '', // archive name
251 'zomgnotcensored',
252 'Borderline image',
253 array(
254 'size' => 12345,
255 'width' => 320,
256 'height' => 240,
257 'bits' => 24,
258 'media_type' => MEDIATYPE_BITMAP,
259 'mime' => 'image/jpeg',
260 'metadata' => serialize( array() ),
261 'sha1' => wfBaseConvert( '3', 16, 36, 31 ),
262 'fileExists' => true ),
263 $this->db->timestamp( '20010115123500' ), $user
264 );
265 }
266 }
267
268 //ParserTest setup/teardown functions
269
270 /**
271 * Set up the global variables for a consistent environment for each test.
272 * Ideally this should replace the global configuration entirely.
273 */
274 protected function setupGlobals( $opts = array(), $config = '' ) {
275 global $wgFileBackends;
276 # Find out values for some special options.
277 $lang =
278 self::getOptionValue( 'language', $opts, 'en' );
279 $variant =
280 self::getOptionValue( 'variant', $opts, false );
281 $maxtoclevel =
282 self::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
283 $linkHolderBatchSize =
284 self::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
285
286 $uploadDir = $this->getUploadDir();
287 if ( $this->getCliArg( 'use-filebackend=' ) ) {
288 if ( self::$backendToUse ) {
289 $backend = self::$backendToUse;
290 } else {
291 $name = $this->getCliArg( 'use-filebackend=' );
292 $useConfig = array();
293 foreach ( $wgFileBackends as $conf ) {
294 if ( $conf['name'] == $name ) {
295 $useConfig = $conf;
296 }
297 }
298 $useConfig['name'] = 'local-backend'; // swap name
299 $class = $conf['class'];
300 self::$backendToUse = new $class( $useConfig );
301 $backend = self::$backendToUse;
302 }
303 } else {
304 $backend = new FSFileBackend( array(
305 'name' => 'local-backend',
306 'lockManager' => 'nullLockManager',
307 'containerPaths' => array(
308 'local-public' => "$uploadDir",
309 'local-thumb' => "$uploadDir/thumb",
310 )
311 ) );
312 }
313
314 $settings = array(
315 'wgLocalFileRepo' => array(
316 'class' => 'LocalRepo',
317 'name' => 'local',
318 'url' => 'http://example.com/images',
319 'hashLevels' => 2,
320 'transformVia404' => false,
321 'backend' => $backend
322 ),
323 'wgEnableUploads' => self::getOptionValue( 'wgEnableUploads', $opts, true ),
324 'wgLanguageCode' => $lang,
325 'wgDBprefix' => $this->db->getType() != 'oracle' ? 'unittest_' : 'ut_',
326 'wgRawHtml' => isset( $opts['rawhtml'] ),
327 'wgNamespacesWithSubpages' => array( NS_MAIN => isset( $opts['subpage'] ) ),
328 'wgMaxTocLevel' => $maxtoclevel,
329 'wgUseTeX' => isset( $opts['math'] ),
330 'wgMathDirectory' => $uploadDir . '/math',
331 'wgDefaultLanguageVariant' => $variant,
332 'wgLinkHolderBatchSize' => $linkHolderBatchSize,
333 );
334
335 if ( $config ) {
336 $configLines = explode( "\n", $config );
337
338 foreach ( $configLines as $line ) {
339 list( $var, $value ) = explode( '=', $line, 2 );
340
341 $settings[$var] = eval( "return $value;" ); //???
342 }
343 }
344
345 $this->savedGlobals = array();
346
347 /** @since 1.20 */
348 wfRunHooks( 'ParserTestGlobals', array( &$settings ) );
349
350 $langObj = Language::factory( $lang );
351 $settings['wgContLang'] = $langObj;
352 $settings['wgLang'] = $langObj;
353
354 $context = new RequestContext();
355 $settings['wgOut'] = $context->getOutput();
356 $settings['wgUser'] = $context->getUser();
357 $settings['wgRequest'] = $context->getRequest();
358
359 foreach ( $settings as $var => $val ) {
360 if ( array_key_exists( $var, $GLOBALS ) ) {
361 $this->savedGlobals[$var] = $GLOBALS[$var];
362 }
363
364 $GLOBALS[$var] = $val;
365 }
366
367 MagicWord::clearCache();
368 RepoGroup::destroySingleton();
369 FileBackendGroup::destroySingleton();
370
371 # Create dummy files in storage
372 $this->setupUploads();
373
374 # Publish the articles after we have the final language set
375 $this->publishTestArticles();
376
377 # The entries saved into RepoGroup cache with previous globals will be wrong.
378 RepoGroup::destroySingleton();
379 FileBackendGroup::destroySingleton();
380 MessageCache::destroyInstance();
381
382 return $context;
383 }
384
385 /**
386 * Get an FS upload directory (only applies to FSFileBackend)
387 *
388 * @return String: the directory
389 */
390 protected function getUploadDir() {
391 if ( $this->keepUploads ) {
392 $dir = wfTempDir() . '/mwParser-images';
393
394 if ( is_dir( $dir ) ) {
395 return $dir;
396 }
397 } else {
398 $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
399 }
400
401 // wfDebug( "Creating upload directory $dir\n" );
402 if ( file_exists( $dir ) ) {
403 wfDebug( "Already exists!\n" );
404
405 return $dir;
406 }
407
408 return $dir;
409 }
410
411 /**
412 * Create a dummy uploads directory which will contain a couple
413 * of files in order to pass existence tests.
414 *
415 * @return String: the directory
416 */
417 protected function setupUploads() {
418 global $IP;
419
420 $base = $this->getBaseDir();
421 $backend = RepoGroup::singleton()->getLocalRepo()->getBackend();
422 $backend->prepare( array( 'dir' => "$base/local-public/3/3a" ) );
423 $backend->store( array(
424 'src' => "$IP/skins/monobook/headbg.jpg", 'dst' => "$base/local-public/3/3a/Foobar.jpg"
425 ) );
426 $backend->prepare( array( 'dir' => "$base/local-public/e/ea" ) );
427 $backend->store( array(
428 'src' => "$IP/skins/monobook/wiki.png", 'dst' => "$base/local-public/e/ea/Thumb.png"
429 ) );
430 $backend->prepare( array( 'dir' => "$base/local-public/0/09" ) );
431 $backend->store( array(
432 'src' => "$IP/skins/monobook/headbg.jpg", 'dst' => "$base/local-public/0/09/Bad.jpg"
433 ) );
434 }
435
436 /**
437 * Restore default values and perform any necessary clean-up
438 * after each test runs.
439 */
440 protected function teardownGlobals() {
441 $this->teardownUploads();
442
443 foreach ( $this->savedGlobals as $var => $val ) {
444 $GLOBALS[$var] = $val;
445 }
446
447 RepoGroup::destroySingleton();
448 LinkCache::singleton()->clear();
449 }
450
451 /**
452 * Remove the dummy uploads directory
453 */
454 private function teardownUploads() {
455 if ( $this->keepUploads ) {
456 return;
457 }
458
459 $base = $this->getBaseDir();
460 // delete the files first, then the dirs.
461 self::deleteFiles(
462 array(
463 "$base/local-public/3/3a/Foobar.jpg",
464 "$base/local-thumb/3/3a/Foobar.jpg/180px-Foobar.jpg",
465 "$base/local-thumb/3/3a/Foobar.jpg/200px-Foobar.jpg",
466 "$base/local-thumb/3/3a/Foobar.jpg/640px-Foobar.jpg",
467 "$base/local-thumb/3/3a/Foobar.jpg/120px-Foobar.jpg",
468 "$base/local-thumb/3/3a/Foobar.jpg/1280px-Foobar.jpg",
469 "$base/local-thumb/3/3a/Foobar.jpg/20px-Foobar.jpg",
470 "$base/local-thumb/3/3a/Foobar.jpg/270px-Foobar.jpg",
471 "$base/local-thumb/3/3a/Foobar.jpg/300px-Foobar.jpg",
472 "$base/local-thumb/3/3a/Foobar.jpg/30px-Foobar.jpg",
473 "$base/local-thumb/3/3a/Foobar.jpg/360px-Foobar.jpg",
474 "$base/local-thumb/3/3a/Foobar.jpg/400px-Foobar.jpg",
475 "$base/local-thumb/3/3a/Foobar.jpg/40px-Foobar.jpg",
476 "$base/local-thumb/3/3a/Foobar.jpg/70px-Foobar.jpg",
477 "$base/local-thumb/3/3a/Foobar.jpg/960px-Foobar.jpg",
478
479 "$base/local-public/e/ea/Thumb.png",
480
481 "$base/local-public/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
517 return new TestFileIterator( $this->file, $this );
518 }
519
520 /**
521 * Set the file from whose tests will be run by this instance
522 */
523 public function setParserTestFile( $filename ) {
524 $this->file = $filename;
525 }
526
527 /**
528 * @group medium
529 * @dataProvider parserTestProvider
530 */
531 public function testParserTest( $desc, $input, $result, $opts, $config ) {
532 if ( $this->regex != '' && !preg_match( '/' . $this->regex . '/', $desc ) ) {
533 $this->assertTrue( true ); // XXX: don't flood output with "test made no assertions"
534 //$this->markTestSkipped( 'Filtered out by the user' );
535 return;
536 }
537
538 if ( !$this->isWikitextNS( NS_MAIN ) ) {
539 // parser tests frequently assume that the main namespace contains wikitext.
540 // @todo: When setting up pages, force the content model. Only skip if
541 // $wgtContentModelUseDB is false.
542 $this->markTestSkipped( "Main namespace does not support wikitext,"
543 . "skipping parser test: $desc" );
544 }
545
546 wfDebug( "Running parser test: $desc\n" );
547
548 $opts = $this->parseOptions( $opts );
549 $context = $this->setupGlobals( $opts, $config );
550
551 $user = $context->getUser();
552 $options = ParserOptions::newFromContext( $context );
553
554 if ( isset( $opts['title'] ) ) {
555 $titleText = $opts['title'];
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 //Various getter functions
695
696 /**
697 * Get an input dictionary from a set of parser test files
698 */
699 function getFuzzInput( $filenames ) {
700 $dict = '';
701
702 foreach ( $filenames as $filename ) {
703 $contents = file_get_contents( $filename );
704 preg_match_all( '/!!\s*input\n(.*?)\n!!\s*result/s', $contents, $matches );
705
706 foreach ( $matches[1] as $match ) {
707 $dict .= $match . "\n";
708 }
709 }
710
711 return $dict;
712 }
713
714 /**
715 * Get a memory usage breakdown
716 */
717 function getMemoryBreakdown() {
718 $memStats = array();
719
720 foreach ( $GLOBALS as $name => $value ) {
721 $memStats['$' . $name] = strlen( serialize( $value ) );
722 }
723
724 $classes = get_declared_classes();
725
726 foreach ( $classes as $class ) {
727 $rc = new ReflectionClass( $class );
728 $props = $rc->getStaticProperties();
729 $memStats[$class] = strlen( serialize( $props ) );
730 $methods = $rc->getMethods();
731
732 foreach ( $methods as $method ) {
733 $memStats[$class] += strlen( serialize( $method->getStaticVariables() ) );
734 }
735 }
736
737 $functions = get_defined_functions();
738
739 foreach ( $functions['user'] as $function ) {
740 $rf = new ReflectionFunction( $function );
741 $memStats["$function()"] = strlen( serialize( $rf->getStaticVariables() ) );
742 }
743
744 asort( $memStats );
745
746 return $memStats;
747 }
748
749 /**
750 * Get a Parser object
751 */
752 function getParser( $preprocessor = null ) {
753 global $wgParserConf;
754
755 $class = $wgParserConf['class'];
756 $parser = new $class( array( 'preprocessorClass' => $preprocessor ) + $wgParserConf );
757
758 wfRunHooks( 'ParserTestParser', array( &$parser ) );
759
760 return $parser;
761 }
762
763 //Various action functions
764
765 public function addArticle( $name, $text, $line ) {
766 self::$articles[$name] = array( $text, $line );
767 }
768
769 public function publishTestArticles() {
770 if ( empty( self::$articles ) ) {
771 return;
772 }
773
774 foreach ( self::$articles as $name => $info ) {
775 list( $text, $line ) = $info;
776 ParserTest::addArticle( $name, $text, $line, 'ignoreduplicate' );
777 }
778 }
779
780 /**
781 * Steal a callback function from the primary parser, save it for
782 * application to our scary parser. If the hook is not installed,
783 * abort processing of this file.
784 *
785 * @param $name String
786 * @return Bool true if tag hook is present
787 */
788 public function requireHook( $name ) {
789 global $wgParser;
790 $wgParser->firstCallInit(); // make sure hooks are loaded.
791 return isset( $wgParser->mTagHooks[$name] );
792 }
793
794 public function requireFunctionHook( $name ) {
795 global $wgParser;
796 $wgParser->firstCallInit(); // make sure hooks are loaded.
797 return isset( $wgParser->mFunctionHooks[$name] );
798 }
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 } else {
826 return $s;
827 }
828 }
829
830 //Test options parser functions
831
832 protected function parseOptions( $instring ) {
833 $opts = array();
834 // foo
835 // foo=bar
836 // foo="bar baz"
837 // foo=[[bar baz]]
838 // foo=bar,"baz quux"
839 $regex = '/\b
840 ([\w-]+) # Key
841 \b
842 (?:\s*
843 = # First sub-value
844 \s*
845 (
846 "
847 [^"]* # Quoted val
848 "
849 |
850 \[\[
851 [^]]* # Link target
852 \]\]
853 |
854 [\w-]+ # Plain word
855 )
856 (?:\s*
857 , # Sub-vals 1..N
858 \s*
859 (
860 "[^"]*" # Quoted val
861 |
862 \[\[[^]]*\]\] # Link target
863 |
864 [\w-]+ # Plain word
865 )
866 )*
867 )?
868 /x';
869
870 if ( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER ) ) {
871 foreach ( $matches as $bits ) {
872 array_shift( $bits );
873 $key = strtolower( array_shift( $bits ) );
874 if ( count( $bits ) == 0 ) {
875 $opts[$key] = true;
876 } elseif ( count( $bits ) == 1 ) {
877 $opts[$key] = $this->cleanupOption( array_shift( $bits ) );
878 } else {
879 // Array!
880 $opts[$key] = array_map( array( $this, 'cleanupOption' ), $bits );
881 }
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
897 return $opt;
898 }
899
900 /**
901 * Use a regex to find out the value of an option
902 * @param $key String: name of option val to retrieve
903 * @param $opts Options array to look in
904 * @param $default Mixed: default value returned if not found
905 */
906 protected static function getOptionValue( $key, $opts, $default ) {
907 $key = strtolower( $key );
908
909 if ( isset( $opts[$key] ) ) {
910 return $opts[$key];
911 } else {
912 return $default;
913 }
914 }
915 }