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