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