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