Merge "Move list generation out of TablePager::getLimitSelect()"
[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 foreach ( $tmpGlobals as $var => $val ) {
90 if ( array_key_exists( $var, $GLOBALS ) ) {
91 $this->savedInitialGlobals[$var] = $GLOBALS[$var];
92 }
93
94 $GLOBALS[$var] = $val;
95 }
96
97 $this->savedWeirdGlobals['mw_namespace_protection'] = $wgNamespaceProtection[NS_MEDIAWIKI];
98 $this->savedWeirdGlobals['image_alias'] = $wgNamespaceAliases['Image'];
99 $this->savedWeirdGlobals['image_talk_alias'] = $wgNamespaceAliases['Image_talk'];
100
101 $wgNamespaceProtection[NS_MEDIAWIKI] = 'editinterface';
102 $wgNamespaceAliases['Image'] = NS_FILE;
103 $wgNamespaceAliases['Image_talk'] = NS_FILE_TALK;
104 }
105
106 protected function tearDown() {
107 foreach ( $this->savedInitialGlobals as $var => $val ) {
108 $GLOBALS[$var] = $val;
109 }
110
111 global $wgNamespaceProtection, $wgNamespaceAliases;
112
113 $wgNamespaceProtection[NS_MEDIAWIKI] = $this->savedWeirdGlobals['mw_namespace_protection'];
114 $wgNamespaceAliases['Image'] = $this->savedWeirdGlobals['image_alias'];
115 $wgNamespaceAliases['Image_talk'] = $this->savedWeirdGlobals['image_talk_alias'];
116
117 // Restore backends
118 RepoGroup::destroySingleton();
119 FileBackendGroup::destroySingleton();
120
121 parent::tearDown();
122 }
123
124 function addDBData() {
125 $this->tablesUsed[] = 'site_stats';
126 $this->tablesUsed[] = 'interwiki';
127 # disabled for performance
128 #$this->tablesUsed[] = 'image';
129
130 # Hack: insert a few Wikipedia in-project interwiki prefixes,
131 # for testing inter-language links
132 $this->db->insert( 'interwiki', array(
133 array( 'iw_prefix' => 'wikipedia',
134 'iw_url' => 'http://en.wikipedia.org/wiki/$1',
135 'iw_api' => '',
136 'iw_wikiid' => '',
137 'iw_local' => 0 ),
138 array( 'iw_prefix' => 'meatball',
139 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
140 'iw_api' => '',
141 'iw_wikiid' => '',
142 'iw_local' => 0 ),
143 array( 'iw_prefix' => 'zh',
144 'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
145 'iw_api' => '',
146 'iw_wikiid' => '',
147 'iw_local' => 1 ),
148 array( 'iw_prefix' => 'es',
149 'iw_url' => 'http://es.wikipedia.org/wiki/$1',
150 'iw_api' => '',
151 'iw_wikiid' => '',
152 'iw_local' => 1 ),
153 array( 'iw_prefix' => 'fr',
154 'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
155 'iw_api' => '',
156 'iw_wikiid' => '',
157 'iw_local' => 1 ),
158 array( 'iw_prefix' => 'ru',
159 'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
160 'iw_api' => '',
161 'iw_wikiid' => '',
162 'iw_local' => 1 ),
163 /**
164 * @todo Fixme! Why are we inserting duplicate data here? Shouldn't
165 * need this IGNORE or shouldn't need the insert at all.
166 */
167 ), __METHOD__, array( 'IGNORE' )
168 );
169
170 # Update certain things in site_stats
171 $this->db->insert( 'site_stats',
172 array( 'ss_row_id' => 1, 'ss_images' => 2, 'ss_good_articles' => 1 ),
173 __METHOD__
174 );
175
176 # Reinitialise the LocalisationCache to match the database state
177 Language::getLocalisationCache()->unloadAll();
178
179 # Clear the message cache
180 MessageCache::singleton()->clear();
181
182 $user = User::newFromId( 0 );
183 LinkCache::singleton()->clear(); # Avoids the odd failure at creating the nullRevision
184
185 # Upload DB table entries for files.
186 # We will upload the actual files later. Note that if anything causes LocalFile::load()
187 # to be triggered before then, it will break via maybeUpgrade() setting the fileExists
188 # member to false and storing it in cache.
189 # note that the size/width/height/bits/etc of the file
190 # are actually set by inspecting the file itself; the arguments
191 # to recordUpload2 have no effect. That said, we try to make things
192 # match up so it is less confusing to readers of the code & tests.
193 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Foobar.jpg' ) );
194 if ( !$this->db->selectField( 'image', '1', array( 'img_name' => $image->getName() ) ) ) {
195 $image->recordUpload2(
196 '', // archive name
197 'Upload of some lame file',
198 'Some lame file',
199 array(
200 'size' => 7881,
201 'width' => 1941,
202 'height' => 220,
203 'bits' => 8,
204 'media_type' => MEDIATYPE_BITMAP,
205 'mime' => 'image/jpeg',
206 'metadata' => serialize( array() ),
207 'sha1' => wfBaseConvert( '1', 16, 36, 31 ),
208 'fileExists' => true ),
209 $this->db->timestamp( '20010115123500' ), $user
210 );
211 }
212
213 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Thumb.png' ) );
214 if ( !$this->db->selectField( 'image', '1', array( 'img_name' => $image->getName() ) ) ) {
215 $image->recordUpload2(
216 '', // archive name
217 'Upload of some lame thumbnail',
218 'Some lame thumbnail',
219 array(
220 'size' => 22589,
221 'width' => 135,
222 'height' => 135,
223 'bits' => 8,
224 'media_type' => MEDIATYPE_BITMAP,
225 'mime' => 'image/png',
226 'metadata' => serialize( array() ),
227 'sha1' => wfBaseConvert( '2', 16, 36, 31 ),
228 'fileExists' => true ),
229 $this->db->timestamp( '20130225203040' ), $user
230 );
231 }
232
233 # This image will be blacklisted in [[MediaWiki:Bad image list]]
234 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Bad.jpg' ) );
235 if ( !$this->db->selectField( 'image', '1', array( 'img_name' => $image->getName() ) ) ) {
236 $image->recordUpload2(
237 '', // archive name
238 'zomgnotcensored',
239 'Borderline image',
240 array(
241 'size' => 12345,
242 'width' => 320,
243 'height' => 240,
244 'bits' => 24,
245 'media_type' => MEDIATYPE_BITMAP,
246 'mime' => 'image/jpeg',
247 'metadata' => serialize( array() ),
248 'sha1' => wfBaseConvert( '3', 16, 36, 31 ),
249 'fileExists' => true ),
250 $this->db->timestamp( '20010115123500' ), $user
251 );
252 }
253 }
254
255 //ParserTest setup/teardown functions
256
257 /**
258 * Set up the global variables for a consistent environment for each test.
259 * Ideally this should replace the global configuration entirely.
260 */
261 protected function setupGlobals( $opts = array(), $config = '' ) {
262 global $wgFileBackends;
263 # Find out values for some special options.
264 $lang =
265 self::getOptionValue( 'language', $opts, 'en' );
266 $variant =
267 self::getOptionValue( 'variant', $opts, false );
268 $maxtoclevel =
269 self::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
270 $linkHolderBatchSize =
271 self::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
272
273 $uploadDir = $this->getUploadDir();
274 if ( $this->getCliArg( 'use-filebackend=' ) ) {
275 if ( self::$backendToUse ) {
276 $backend = self::$backendToUse;
277 } else {
278 $name = $this->getCliArg( 'use-filebackend=' );
279 $useConfig = array();
280 foreach ( $wgFileBackends as $conf ) {
281 if ( $conf['name'] == $name ) {
282 $useConfig = $conf;
283 }
284 }
285 $useConfig['name'] = 'local-backend'; // swap name
286 $class = $conf['class'];
287 self::$backendToUse = new $class( $useConfig );
288 $backend = self::$backendToUse;
289 }
290 } else {
291 $backend = new FSFileBackend( array(
292 'name' => 'local-backend',
293 'lockManager' => 'nullLockManager',
294 'containerPaths' => array(
295 'local-public' => "$uploadDir",
296 'local-thumb' => "$uploadDir/thumb",
297 )
298 ) );
299 }
300
301 $settings = array(
302 'wgServer' => 'http://example.org',
303 'wgScript' => '/index.php',
304 'wgScriptPath' => '/',
305 'wgArticlePath' => '/wiki/$1',
306 'wgExtensionAssetsPath' => '/extensions',
307 'wgActionPaths' => array(),
308 'wgLocalFileRepo' => array(
309 'class' => 'LocalRepo',
310 'name' => 'local',
311 'url' => 'http://example.com/images',
312 'hashLevels' => 2,
313 'transformVia404' => false,
314 'backend' => $backend
315 ),
316 'wgEnableUploads' => self::getOptionValue( 'wgEnableUploads', $opts, true ),
317 'wgStylePath' => '/skins',
318 'wgStyleSheetPath' => '/skins',
319 'wgSitename' => 'MediaWiki',
320 'wgLanguageCode' => $lang,
321 'wgDBprefix' => $this->db->getType() != 'oracle' ? 'unittest_' : 'ut_',
322 'wgRawHtml' => isset( $opts['rawhtml'] ),
323 'wgLang' => null,
324 'wgContLang' => null,
325 'wgNamespacesWithSubpages' => array( NS_MAIN => isset( $opts['subpage'] ) ),
326 'wgMaxTocLevel' => $maxtoclevel,
327 'wgCapitalLinks' => true,
328 'wgNoFollowLinks' => true,
329 'wgNoFollowDomainExceptions' => array(),
330 'wgThumbnailScriptPath' => false,
331 'wgUseImageResize' => true,
332 'wgUseTeX' => isset( $opts['math'] ),
333 'wgMathDirectory' => $uploadDir . '/math',
334 'wgLocaltimezone' => 'UTC',
335 'wgAllowExternalImages' => true,
336 'wgUseTidy' => false,
337 'wgDefaultLanguageVariant' => $variant,
338 'wgVariantArticlePath' => false,
339 'wgGroupPermissions' => array( '*' => array(
340 'createaccount' => true,
341 'read' => true,
342 'edit' => true,
343 'createpage' => true,
344 'createtalk' => true,
345 ) ),
346 'wgNamespaceProtection' => array( NS_MEDIAWIKI => 'editinterface' ),
347 'wgDefaultExternalStore' => array(),
348 'wgForeignFileRepos' => array(),
349 'wgLinkHolderBatchSize' => $linkHolderBatchSize,
350 'wgExperimentalHtmlIds' => false,
351 'wgExternalLinkTarget' => false,
352 'wgAlwaysUseTidy' => false,
353 'wgHtml5' => true,
354 'wgWellFormedXml' => true,
355 'wgAllowMicrodataAttributes' => true,
356 'wgAdaptiveMessageCache' => true,
357 'wgUseDatabaseMessages' => true,
358 );
359
360 if ( $config ) {
361 $configLines = explode( "\n", $config );
362
363 foreach ( $configLines as $line ) {
364 list( $var, $value ) = explode( '=', $line, 2 );
365
366 $settings[$var] = eval( "return $value;" ); //???
367 }
368 }
369
370 $this->savedGlobals = array();
371
372 /** @since 1.20 */
373 wfRunHooks( 'ParserTestGlobals', array( &$settings ) );
374
375 foreach ( $settings as $var => $val ) {
376 if ( array_key_exists( $var, $GLOBALS ) ) {
377 $this->savedGlobals[$var] = $GLOBALS[$var];
378 }
379
380 $GLOBALS[$var] = $val;
381 }
382
383 $langObj = Language::factory( $lang );
384 $GLOBALS['wgContLang'] = $langObj;
385 $context = new RequestContext();
386 $GLOBALS['wgLang'] = $context->getLanguage();
387
388 $GLOBALS['wgMemc'] = new EmptyBagOStuff;
389 $GLOBALS['wgOut'] = $context->getOutput();
390 $GLOBALS['wgUser'] = $context->getUser();
391
392 global $wgHooks;
393
394 $wgHooks['ParserTestParser'][] = 'ParserTestParserHook::setup';
395 $wgHooks['ParserGetVariableValueTs'][] = 'ParserTest::getFakeTimestamp';
396
397 MagicWord::clearCache();
398 RepoGroup::destroySingleton();
399 FileBackendGroup::destroySingleton();
400
401 # Create dummy files in storage
402 $this->setupUploads();
403
404 # Publish the articles after we have the final language set
405 $this->publishTestArticles();
406
407 # The entries saved into RepoGroup cache with previous globals will be wrong.
408 RepoGroup::destroySingleton();
409 FileBackendGroup::destroySingleton();
410 MessageCache::destroyInstance();
411
412 return $context;
413 }
414
415 /**
416 * Get an FS upload directory (only applies to FSFileBackend)
417 *
418 * @return String: the directory
419 */
420 protected function getUploadDir() {
421 if ( $this->keepUploads ) {
422 $dir = wfTempDir() . '/mwParser-images';
423
424 if ( is_dir( $dir ) ) {
425 return $dir;
426 }
427 } else {
428 $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
429 }
430
431 // wfDebug( "Creating upload directory $dir\n" );
432 if ( file_exists( $dir ) ) {
433 wfDebug( "Already exists!\n" );
434
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
547 return new TestFileIterator( $this->file, $this );
548 }
549
550 /**
551 * Set the file from whose tests will be run by this instance
552 */
553 public function setParserTestFile( $filename ) {
554 $this->file = $filename;
555 }
556
557 /**
558 * @group medium
559 * @dataProvider parserTestProvider
560 */
561 public function testParserTest( $desc, $input, $result, $opts, $config ) {
562 if ( $this->regex != '' && !preg_match( '/' . $this->regex . '/', $desc ) ) {
563 $this->assertTrue( true ); // XXX: don't flood output with "test made no assertions"
564 //$this->markTestSkipped( 'Filtered out by the user' );
565 return;
566 }
567
568 if ( !$this->isWikitextNS( NS_MAIN ) ) {
569 // parser tests frequently assume that the main namespace contains wikitext.
570 // @todo: When setting up pages, force the content model. Only skip if
571 // $wgtContentModelUseDB is false.
572 $this->markTestSkipped( "Main namespace does not support wikitext,"
573 . "skipping parser test: $desc" );
574 }
575
576 wfDebug( "Running parser test: $desc\n" );
577
578 $opts = $this->parseOptions( $opts );
579 $context = $this->setupGlobals( $opts, $config );
580
581 $user = $context->getUser();
582 $options = ParserOptions::newFromContext( $context );
583
584 if ( isset( $opts['title'] ) ) {
585 $titleText = $opts['title'];
586 } else {
587 $titleText = 'Parser test';
588 }
589
590 $local = isset( $opts['local'] );
591 $preprocessor = isset( $opts['preprocessor'] ) ? $opts['preprocessor'] : null;
592 $parser = $this->getParser( $preprocessor );
593
594 $title = Title::newFromText( $titleText );
595
596 if ( isset( $opts['pst'] ) ) {
597 $out = $parser->preSaveTransform( $input, $title, $user, $options );
598 } elseif ( isset( $opts['msg'] ) ) {
599 $out = $parser->transformMsg( $input, $options, $title );
600 } elseif ( isset( $opts['section'] ) ) {
601 $section = $opts['section'];
602 $out = $parser->getSection( $input, $section );
603 } elseif ( isset( $opts['replace'] ) ) {
604 $section = $opts['replace'][0];
605 $replace = $opts['replace'][1];
606 $out = $parser->replaceSection( $input, $section, $replace );
607 } elseif ( isset( $opts['comment'] ) ) {
608 $out = Linker::formatComment( $input, $title, $local );
609 } elseif ( isset( $opts['preload'] ) ) {
610 $out = $parser->getPreloadText( $input, $title, $options );
611 } else {
612 $output = $parser->parse( $input, $title, $options, true, true, 1337 );
613 $out = $output->getText();
614
615 if ( isset( $opts['showtitle'] ) ) {
616 if ( $output->getTitleText() ) {
617 $title = $output->getTitleText();
618 }
619
620 $out = "$title\n$out";
621 }
622
623 if ( isset( $opts['ill'] ) ) {
624 $out = $this->tidy( implode( ' ', $output->getLanguageLinks() ) );
625 } elseif ( isset( $opts['cat'] ) ) {
626 $outputPage = $context->getOutput();
627 $outputPage->addCategoryLinks( $output->getCategories() );
628 $cats = $outputPage->getCategoryLinks();
629
630 if ( isset( $cats['normal'] ) ) {
631 $out = $this->tidy( implode( ' ', $cats['normal'] ) );
632 } else {
633 $out = '';
634 }
635 }
636 $parser->mPreprocessor = null;
637
638 $result = $this->tidy( $result );
639 }
640
641 $this->teardownGlobals();
642
643 $this->assertEquals( $result, $out, $desc );
644 }
645
646 /**
647 * Run a fuzz test series
648 * Draw input from a set of test files
649 *
650 * @todo fixme Needs some work to not eat memory until the world explodes
651 *
652 * @group ParserFuzz
653 */
654 function testFuzzTests() {
655 global $wgParserTestFiles;
656
657 $files = $wgParserTestFiles;
658
659 if ( $this->getCliArg( 'file=' ) ) {
660 $files = array( $this->getCliArg( 'file=' ) );
661 }
662
663 $dict = $this->getFuzzInput( $files );
664 $dictSize = strlen( $dict );
665 $logMaxLength = log( $this->maxFuzzTestLength );
666
667 ini_set( 'memory_limit', $this->memoryLimit * 1048576 );
668
669 $user = new User;
670 $opts = ParserOptions::newFromUser( $user );
671 $title = Title::makeTitle( NS_MAIN, 'Parser_test' );
672
673 $id = 1;
674
675 while ( true ) {
676
677 // Generate test input
678 mt_srand( ++$this->fuzzSeed );
679 $totalLength = mt_rand( 1, $this->maxFuzzTestLength );
680 $input = '';
681
682 while ( strlen( $input ) < $totalLength ) {
683 $logHairLength = mt_rand( 0, 1000000 ) / 1000000 * $logMaxLength;
684 $hairLength = min( intval( exp( $logHairLength ) ), $dictSize );
685 $offset = mt_rand( 0, $dictSize - $hairLength );
686 $input .= substr( $dict, $offset, $hairLength );
687 }
688
689 $this->setupGlobals();
690 $parser = $this->getParser();
691
692 // Run the test
693 try {
694 $parser->parse( $input, $title, $opts );
695 $this->assertTrue( true, "Test $id, fuzz seed {$this->fuzzSeed}" );
696 } catch ( Exception $exception ) {
697 $input_dump = sprintf( "string(%d) \"%s\"\n", strlen( $input ), $input );
698
699 $this->assertTrue( false, "Test $id, fuzz seed {$this->fuzzSeed}. \n\nInput: $input_dump\n\nError: {$exception->getMessage()}\n\nBacktrace: {$exception->getTraceAsString()}" );
700 }
701
702 $this->teardownGlobals();
703 $parser->__destruct();
704
705 if ( $id % 100 == 0 ) {
706 $usage = intval( memory_get_usage( true ) / $this->memoryLimit / 1048576 * 100 );
707 //echo "{$this->fuzzSeed}: $numSuccess/$numTotal (mem: $usage%)\n";
708 if ( $usage > 90 ) {
709 $ret = "Out of memory:\n";
710 $memStats = $this->getMemoryBreakdown();
711
712 foreach ( $memStats as $name => $usage ) {
713 $ret .= "$name: $usage\n";
714 }
715
716 throw new MWException( $ret );
717 }
718 }
719
720 $id++;
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
915 return $opts;
916 }
917
918 protected function cleanupOption( $opt ) {
919 if ( substr( $opt, 0, 1 ) == '"' ) {
920 return substr( $opt, 1, -1 );
921 }
922
923 if ( substr( $opt, 0, 2 ) == '[[' ) {
924 return substr( $opt, 2, -2 );
925 }
926
927 return $opt;
928 }
929
930 /**
931 * Use a regex to find out the value of an option
932 * @param $key String: name of option val to retrieve
933 * @param $opts Options array to look in
934 * @param $default Mixed: default value returned if not found
935 */
936 protected static function getOptionValue( $key, $opts, $default ) {
937 $key = strtolower( $key );
938
939 if ( isset( $opts[$key] ) ) {
940 return $opts[$key];
941 } else {
942 return $default;
943 }
944 }
945 }