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