Merge "Read full memcached response before manipulating data"
[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 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Foobar.jpg' ) );
191 if ( !$this->db->selectField( 'image', '1', array( 'img_name' => $image->getName() ) ) ) {
192 $image->recordUpload2(
193 '', // archive name
194 'Upload of some lame file',
195 'Some lame file',
196 array(
197 'size' => 12345,
198 'width' => 1941,
199 'height' => 220,
200 'bits' => 24,
201 'media_type' => MEDIATYPE_BITMAP,
202 'mime' => 'image/jpeg',
203 'metadata' => serialize( array() ),
204 'sha1' => wfBaseConvert( '', 16, 36, 31 ),
205 'fileExists' => true ),
206 $this->db->timestamp( '20010115123500' ), $user
207 );
208 }
209
210 # This image will be blacklisted in [[MediaWiki:Bad image list]]
211 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Bad.jpg' ) );
212 if ( !$this->db->selectField( 'image', '1', array( 'img_name' => $image->getName() ) ) ) {
213 $image->recordUpload2(
214 '', // archive name
215 'zomgnotcensored',
216 'Borderline image',
217 array(
218 'size' => 12345,
219 'width' => 320,
220 'height' => 240,
221 'bits' => 24,
222 'media_type' => MEDIATYPE_BITMAP,
223 'mime' => 'image/jpeg',
224 'metadata' => serialize( array() ),
225 'sha1' => wfBaseConvert( '', 16, 36, 31 ),
226 'fileExists' => true ),
227 $this->db->timestamp( '20010115123500' ), $user
228 );
229 }
230 }
231
232 //ParserTest setup/teardown functions
233
234 /**
235 * Set up the global variables for a consistent environment for each test.
236 * Ideally this should replace the global configuration entirely.
237 */
238 protected function setupGlobals( $opts = array(), $config = '' ) {
239 global $wgFileBackends;
240 # Find out values for some special options.
241 $lang =
242 self::getOptionValue( 'language', $opts, 'en' );
243 $variant =
244 self::getOptionValue( 'variant', $opts, false );
245 $maxtoclevel =
246 self::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
247 $linkHolderBatchSize =
248 self::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
249
250 $uploadDir = $this->getUploadDir();
251 if ( $this->getCliArg( 'use-filebackend=' ) ) {
252 if ( self::$backendToUse ) {
253 $backend = self::$backendToUse;
254 } else {
255 $name = $this->getCliArg( 'use-filebackend=' );
256 $useConfig = array();
257 foreach ( $wgFileBackends as $conf ) {
258 if ( $conf['name'] == $name ) {
259 $useConfig = $conf;
260 }
261 }
262 $useConfig['name'] = 'local-backend'; // swap name
263 $class = $conf['class'];
264 self::$backendToUse = new $class( $useConfig );
265 $backend = self::$backendToUse;
266 }
267 } else {
268 $backend = new FSFileBackend( array(
269 'name' => 'local-backend',
270 'lockManager' => 'nullLockManager',
271 'containerPaths' => array(
272 'local-public' => "$uploadDir",
273 'local-thumb' => "$uploadDir/thumb",
274 )
275 ) );
276 }
277
278 $settings = array(
279 'wgServer' => 'http://example.org',
280 'wgScript' => '/index.php',
281 'wgScriptPath' => '/',
282 'wgArticlePath' => '/wiki/$1',
283 'wgExtensionAssetsPath' => '/extensions',
284 'wgActionPaths' => array(),
285 'wgLocalFileRepo' => array(
286 'class' => 'LocalRepo',
287 'name' => 'local',
288 'url' => 'http://example.com/images',
289 'hashLevels' => 2,
290 'transformVia404' => false,
291 'backend' => $backend
292 ),
293 'wgEnableUploads' => self::getOptionValue( 'wgEnableUploads', $opts, true ),
294 'wgStylePath' => '/skins',
295 'wgStyleSheetPath' => '/skins',
296 'wgSitename' => 'MediaWiki',
297 'wgLanguageCode' => $lang,
298 'wgDBprefix' => $this->db->getType() != 'oracle' ? 'unittest_' : 'ut_',
299 'wgRawHtml' => isset( $opts['rawhtml'] ),
300 'wgLang' => null,
301 'wgContLang' => null,
302 'wgNamespacesWithSubpages' => array( NS_MAIN => isset( $opts['subpage'] ) ),
303 'wgMaxTocLevel' => $maxtoclevel,
304 'wgCapitalLinks' => true,
305 'wgNoFollowLinks' => true,
306 'wgNoFollowDomainExceptions' => array(),
307 'wgThumbnailScriptPath' => false,
308 'wgUseImageResize' => true,
309 'wgUseTeX' => isset( $opts['math'] ),
310 'wgMathDirectory' => $uploadDir . '/math',
311 'wgLocaltimezone' => 'UTC',
312 'wgAllowExternalImages' => true,
313 'wgUseTidy' => false,
314 'wgDefaultLanguageVariant' => $variant,
315 'wgVariantArticlePath' => false,
316 'wgGroupPermissions' => array( '*' => array(
317 'createaccount' => true,
318 'read' => true,
319 'edit' => true,
320 'createpage' => true,
321 'createtalk' => true,
322 ) ),
323 'wgNamespaceProtection' => array( NS_MEDIAWIKI => 'editinterface' ),
324 'wgDefaultExternalStore' => array(),
325 'wgForeignFileRepos' => array(),
326 'wgLinkHolderBatchSize' => $linkHolderBatchSize,
327 'wgExperimentalHtmlIds' => false,
328 'wgExternalLinkTarget' => false,
329 'wgAlwaysUseTidy' => false,
330 'wgHtml5' => true,
331 'wgWellFormedXml' => true,
332 'wgAllowMicrodataAttributes' => true,
333 'wgAdaptiveMessageCache' => true,
334 'wgUseDatabaseMessages' => true,
335 );
336
337 if ( $config ) {
338 $configLines = explode( "\n", $config );
339
340 foreach ( $configLines as $line ) {
341 list( $var, $value ) = explode( '=', $line, 2 );
342
343 $settings[$var] = eval( "return $value;" ); //???
344 }
345 }
346
347 $this->savedGlobals = array();
348
349 /** @since 1.20 */
350 wfRunHooks( 'ParserTestGlobals', array( &$settings ) );
351
352 foreach ( $settings as $var => $val ) {
353 if ( array_key_exists( $var, $GLOBALS ) ) {
354 $this->savedGlobals[$var] = $GLOBALS[$var];
355 }
356
357 $GLOBALS[$var] = $val;
358 }
359
360 $langObj = Language::factory( $lang );
361 $GLOBALS['wgContLang'] = $langObj;
362 $context = new RequestContext();
363 $GLOBALS['wgLang'] = $context->getLanguage();
364
365 $GLOBALS['wgMemc'] = new EmptyBagOStuff;
366 $GLOBALS['wgOut'] = $context->getOutput();
367 $GLOBALS['wgUser'] = $context->getUser();
368
369 global $wgHooks;
370
371 $wgHooks['ParserTestParser'][] = 'ParserTestParserHook::setup';
372 $wgHooks['ParserGetVariableValueTs'][] = 'ParserTest::getFakeTimestamp';
373
374 MagicWord::clearCache();
375 RepoGroup::destroySingleton();
376 FileBackendGroup::destroySingleton();
377
378 # Create dummy files in storage
379 $this->setupUploads();
380
381 # Publish the articles after we have the final language set
382 $this->publishTestArticles();
383
384 # The entries saved into RepoGroup cache with previous globals will be wrong.
385 RepoGroup::destroySingleton();
386 FileBackendGroup::destroySingleton();
387 MessageCache::destroyInstance();
388
389 return $context;
390 }
391
392 /**
393 * Get an FS upload directory (only applies to FSFileBackend)
394 *
395 * @return String: the directory
396 */
397 protected function getUploadDir() {
398 if ( $this->keepUploads ) {
399 $dir = wfTempDir() . '/mwParser-images';
400
401 if ( is_dir( $dir ) ) {
402 return $dir;
403 }
404 } else {
405 $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
406 }
407
408 // wfDebug( "Creating upload directory $dir\n" );
409 if ( file_exists( $dir ) ) {
410 wfDebug( "Already exists!\n" );
411 return $dir;
412 }
413
414 return $dir;
415 }
416
417 /**
418 * Create a dummy uploads directory which will contain a couple
419 * of files in order to pass existence tests.
420 *
421 * @return String: the directory
422 */
423 protected function setupUploads() {
424 global $IP;
425
426 $base = $this->getBaseDir();
427 $backend = RepoGroup::singleton()->getLocalRepo()->getBackend();
428 $backend->prepare( array( 'dir' => "$base/local-public/3/3a" ) );
429 $backend->store( array(
430 'src' => "$IP/skins/monobook/headbg.jpg", 'dst' => "$base/local-public/3/3a/Foobar.jpg"
431 ) );
432 $backend->prepare( array( 'dir' => "$base/local-public/0/09" ) );
433 $backend->store( array(
434 'src' => "$IP/skins/monobook/headbg.jpg", 'dst' => "$base/local-public/0/09/Bad.jpg"
435 ) );
436 }
437
438 /**
439 * Restore default values and perform any necessary clean-up
440 * after each test runs.
441 */
442 protected function teardownGlobals() {
443 $this->teardownUploads();
444
445 foreach ( $this->savedGlobals as $var => $val ) {
446 $GLOBALS[$var] = $val;
447 }
448
449 RepoGroup::destroySingleton();
450 LinkCache::singleton()->clear();
451 }
452
453 /**
454 * Remove the dummy uploads directory
455 */
456 private function teardownUploads() {
457 if ( $this->keepUploads ) {
458 return;
459 }
460
461 $base = $this->getBaseDir();
462 // delete the files first, then the dirs.
463 self::deleteFiles(
464 array(
465 "$base/local-public/3/3a/Foobar.jpg",
466 "$base/local-thumb/3/3a/Foobar.jpg/180px-Foobar.jpg",
467 "$base/local-thumb/3/3a/Foobar.jpg/200px-Foobar.jpg",
468 "$base/local-thumb/3/3a/Foobar.jpg/640px-Foobar.jpg",
469 "$base/local-thumb/3/3a/Foobar.jpg/120px-Foobar.jpg",
470 "$base/local-thumb/3/3a/Foobar.jpg/1280px-Foobar.jpg",
471 "$base/local-thumb/3/3a/Foobar.jpg/20px-Foobar.jpg",
472 "$base/local-thumb/3/3a/Foobar.jpg/270px-Foobar.jpg",
473 "$base/local-thumb/3/3a/Foobar.jpg/300px-Foobar.jpg",
474 "$base/local-thumb/3/3a/Foobar.jpg/30px-Foobar.jpg",
475 "$base/local-thumb/3/3a/Foobar.jpg/360px-Foobar.jpg",
476 "$base/local-thumb/3/3a/Foobar.jpg/400px-Foobar.jpg",
477 "$base/local-thumb/3/3a/Foobar.jpg/40px-Foobar.jpg",
478 "$base/local-thumb/3/3a/Foobar.jpg/70px-Foobar.jpg",
479 "$base/local-thumb/3/3a/Foobar.jpg/960px-Foobar.jpg",
480
481 "$base/local-public/0/09/Bad.jpg",
482 "$base/local-thumb/0/09/Bad.jpg",
483
484 "$base/local-public/math/f/a/5/fa50b8b616463173474302ca3e63586b.png",
485 )
486 );
487 }
488
489 /**
490 * Delete the specified files, if they exist.
491 * @param $files Array: full paths to files to delete.
492 */
493 private static function deleteFiles( $files ) {
494 $backend = RepoGroup::singleton()->getLocalRepo()->getBackend();
495 foreach ( $files as $file ) {
496 $backend->delete( array( 'src' => $file ), array( 'force' => 1 ) );
497 }
498 foreach ( $files as $file ) {
499 $tmp = $file;
500 while ( $tmp = FileBackend::parentStoragePath( $tmp ) ) {
501 if ( !$backend->clean( array( 'dir' => $tmp ) )->isOK() ) {
502 break;
503 }
504 }
505 }
506 }
507
508 protected function getBaseDir() {
509 return 'mwstore://local-backend';
510 }
511
512 public function parserTestProvider() {
513 if ( $this->file === false ) {
514 global $wgParserTestFiles;
515 $this->file = $wgParserTestFiles[0];
516 }
517 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
695 //Various getter functions
696
697 /**
698 * Get an input dictionary from a set of parser test files
699 */
700 function getFuzzInput( $filenames ) {
701 $dict = '';
702
703 foreach ( $filenames as $filename ) {
704 $contents = file_get_contents( $filename );
705 preg_match_all( '/!!\s*input\n(.*?)\n!!\s*result/s', $contents, $matches );
706
707 foreach ( $matches[1] as $match ) {
708 $dict .= $match . "\n";
709 }
710 }
711
712 return $dict;
713 }
714
715 /**
716 * Get a memory usage breakdown
717 */
718 function getMemoryBreakdown() {
719 $memStats = array();
720
721 foreach ( $GLOBALS as $name => $value ) {
722 $memStats['$' . $name] = strlen( serialize( $value ) );
723 }
724
725 $classes = get_declared_classes();
726
727 foreach ( $classes as $class ) {
728 $rc = new ReflectionClass( $class );
729 $props = $rc->getStaticProperties();
730 $memStats[$class] = strlen( serialize( $props ) );
731 $methods = $rc->getMethods();
732
733 foreach ( $methods as $method ) {
734 $memStats[$class] += strlen( serialize( $method->getStaticVariables() ) );
735 }
736 }
737
738 $functions = get_defined_functions();
739
740 foreach ( $functions['user'] as $function ) {
741 $rf = new ReflectionFunction( $function );
742 $memStats["$function()"] = strlen( serialize( $rf->getStaticVariables() ) );
743 }
744
745 asort( $memStats );
746
747 return $memStats;
748 }
749
750 /**
751 * Get a Parser object
752 */
753 function getParser( $preprocessor = null ) {
754 global $wgParserConf;
755
756 $class = $wgParserConf['class'];
757 $parser = new $class( array( 'preprocessorClass' => $preprocessor ) + $wgParserConf );
758
759 wfRunHooks( 'ParserTestParser', array( &$parser ) );
760
761 return $parser;
762 }
763
764 //Various action functions
765
766 public function addArticle( $name, $text, $line ) {
767 self::$articles[$name] = array( $text, $line );
768 }
769
770 public function publishTestArticles() {
771 if ( empty( self::$articles ) ) {
772 return;
773 }
774
775 foreach ( self::$articles as $name => $info ) {
776 list( $text, $line ) = $info;
777 ParserTest::addArticle( $name, $text, $line, 'ignoreduplicate' );
778 }
779 }
780
781 /**
782 * Steal a callback function from the primary parser, save it for
783 * application to our scary parser. If the hook is not installed,
784 * abort processing of this file.
785 *
786 * @param $name String
787 * @return Bool true if tag hook is present
788 */
789 public function requireHook( $name ) {
790 global $wgParser;
791 $wgParser->firstCallInit(); // make sure hooks are loaded.
792 return isset( $wgParser->mTagHooks[$name] );
793 }
794
795 public function requireFunctionHook( $name ) {
796 global $wgParser;
797 $wgParser->firstCallInit(); // make sure hooks are loaded.
798 return isset( $wgParser->mFunctionHooks[$name] );
799 }
800
801 //Various "cleanup" functions
802
803 /**
804 * Run the "tidy" command on text if the $wgUseTidy
805 * global is true
806 *
807 * @param $text String: the text to tidy
808 * @return String
809 */
810 protected function tidy( $text ) {
811 global $wgUseTidy;
812
813 if ( $wgUseTidy ) {
814 $text = MWTidy::tidy( $text );
815 }
816
817 return $text;
818 }
819
820 /**
821 * Remove last character if it is a newline
822 */
823 public function removeEndingNewline( $s ) {
824 if ( substr( $s, -1 ) === "\n" ) {
825 return substr( $s, 0, -1 );
826 } else {
827 return $s;
828 }
829 }
830
831 //Test options parser functions
832
833 protected function parseOptions( $instring ) {
834 $opts = array();
835 // foo
836 // foo=bar
837 // foo="bar baz"
838 // foo=[[bar baz]]
839 // foo=bar,"baz quux"
840 $regex = '/\b
841 ([\w-]+) # Key
842 \b
843 (?:\s*
844 = # First sub-value
845 \s*
846 (
847 "
848 [^"]* # Quoted val
849 "
850 |
851 \[\[
852 [^]]* # Link target
853 \]\]
854 |
855 [\w-]+ # Plain word
856 )
857 (?:\s*
858 , # Sub-vals 1..N
859 \s*
860 (
861 "[^"]*" # Quoted val
862 |
863 \[\[[^]]*\]\] # Link target
864 |
865 [\w-]+ # Plain word
866 )
867 )*
868 )?
869 /x';
870
871 if ( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER ) ) {
872 foreach ( $matches as $bits ) {
873 array_shift( $bits );
874 $key = strtolower( array_shift( $bits ) );
875 if ( count( $bits ) == 0 ) {
876 $opts[$key] = true;
877 } elseif ( count( $bits ) == 1 ) {
878 $opts[$key] = $this->cleanupOption( array_shift( $bits ) );
879 } else {
880 // Array!
881 $opts[$key] = array_map( array( $this, 'cleanupOption' ), $bits );
882 }
883 }
884 }
885 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 return $opt;
897 }
898
899 /**
900 * Use a regex to find out the value of an option
901 * @param $key String: name of option val to retrieve
902 * @param $opts Options array to look in
903 * @param $default Mixed: default value returned if not found
904 */
905 protected static function getOptionValue( $key, $opts, $default ) {
906 $key = strtolower( $key );
907
908 if ( isset( $opts[$key] ) ) {
909 return $opts[$key];
910 } else {
911 return $default;
912 }
913 }
914 }