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