4 * Although marked as a stub, can work independently.
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.
15 static protected $backendToUse;
17 public $keepUploads = false;
18 public $runDisabled = false;
19 public $runParsoid = false;
21 public $showProgress = true;
22 public $savedInitialGlobals = array();
23 public $savedWeirdGlobals = array();
24 public $savedGlobals = array();
25 public $hooks = array();
26 public $functionHooks = array();
29 public $maxFuzzTestLength = 300;
31 public $memoryLimit = 50;
33 protected $file = false;
35 protected function setUp() {
36 global $wgNamespaceProtection, $wgNamespaceAliases;
42 if ( $this->getCliArg( 'regex=' ) ) {
43 $this->regex
= $this->getCliArg( 'regex=' );
49 $this->keepUploads
= $this->getCliArg( 'keep-uploads' );
51 $tmpGlobals = array();
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',
64 'url' => 'http://example.com/images',
66 'transformVia404' => false,
67 'backend' => 'local-backend'
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();
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();
85 if ( $GLOBALS['wgStyleDirectory'] === false ) {
86 $tmpGlobals['wgStyleDirectory'] = "$IP/skins";
90 foreach ( $tmpGlobals as $var => $val ) {
91 if ( array_key_exists( $var, $GLOBALS ) ) {
92 $this->savedInitialGlobals
[$var] = $GLOBALS[$var];
95 $GLOBALS[$var] = $val;
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'];
102 $wgNamespaceProtection[NS_MEDIAWIKI
] = 'editinterface';
103 $wgNamespaceAliases['Image'] = NS_FILE
;
104 $wgNamespaceAliases['Image_talk'] = NS_FILE_TALK
;
107 protected function tearDown() {
108 foreach ( $this->savedInitialGlobals
as $var => $val ) {
109 $GLOBALS[$var] = $val;
112 global $wgNamespaceProtection, $wgNamespaceAliases;
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'];
119 RepoGroup
::destroySingleton();
120 FileBackendGroup
::destroySingleton();
125 function addDBData() {
126 $this->tablesUsed
[] = 'site_stats';
127 $this->tablesUsed
[] = 'interwiki';
128 # disabled for performance
129 #$this->tablesUsed[] = 'image';
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',
139 array( 'iw_prefix' => 'meatball',
140 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
144 array( 'iw_prefix' => 'zh',
145 'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
149 array( 'iw_prefix' => 'es',
150 'iw_url' => 'http://es.wikipedia.org/wiki/$1',
154 array( 'iw_prefix' => 'fr',
155 'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
159 array( 'iw_prefix' => 'ru',
160 'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
165 * @todo Fixme! Why are we inserting duplicate data here? Shouldn't
166 * need this IGNORE or shouldn't need the insert at all.
168 ), __METHOD__
, array( 'IGNORE' )
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 ),
177 # Reinitialise the LocalisationCache to match the database state
178 Language
::getLocalisationCache()->unloadAll();
180 # Clear the message cache
181 MessageCache
::singleton()->clear();
183 $user = User
::newFromId( 0 );
184 LinkCache
::singleton()->clear(); # Avoids the odd failure at creating the nullRevision
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 # note that the size/width/height/bits/etc of the file
191 # are actually set by inspecting the file itself; the arguments
192 # to recordUpload2 have no effect. That said, we try to make things
193 # match up so it is less confusing to readers of the code & tests.
194 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Foobar.jpg' ) );
195 if ( !$this->db
->selectField( 'image', '1', array( 'img_name' => $image->getName() ) ) ) {
196 $image->recordUpload2(
198 'Upload of some lame file',
205 'media_type' => MEDIATYPE_BITMAP
,
206 'mime' => 'image/jpeg',
207 'metadata' => serialize( array() ),
208 'sha1' => wfBaseConvert( '1', 16, 36, 31 ),
209 'fileExists' => true ),
210 $this->db
->timestamp( '20010115123500' ), $user
214 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Thumb.png' ) );
215 if ( !$this->db
->selectField( 'image', '1', array( 'img_name' => $image->getName() ) ) ) {
216 $image->recordUpload2(
218 'Upload of some lame thumbnail',
219 'Some lame thumbnail',
225 'media_type' => MEDIATYPE_BITMAP
,
226 'mime' => 'image/png',
227 'metadata' => serialize( array() ),
228 'sha1' => wfBaseConvert( '2', 16, 36, 31 ),
229 'fileExists' => true ),
230 $this->db
->timestamp( '20130225203040' ), $user
234 # This image will be blacklisted in [[MediaWiki:Bad image list]]
235 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Bad.jpg' ) );
236 if ( !$this->db
->selectField( 'image', '1', array( 'img_name' => $image->getName() ) ) ) {
237 $image->recordUpload2(
246 'media_type' => MEDIATYPE_BITMAP
,
247 'mime' => 'image/jpeg',
248 'metadata' => serialize( array() ),
249 'sha1' => wfBaseConvert( '3', 16, 36, 31 ),
250 'fileExists' => true ),
251 $this->db
->timestamp( '20010115123500' ), $user
256 //ParserTest setup/teardown functions
259 * Set up the global variables for a consistent environment for each test.
260 * Ideally this should replace the global configuration entirely.
262 protected function setupGlobals( $opts = array(), $config = '' ) {
263 global $wgFileBackends;
264 # Find out values for some special options.
266 self
::getOptionValue( 'language', $opts, 'en' );
268 self
::getOptionValue( 'variant', $opts, false );
270 self
::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
271 $linkHolderBatchSize =
272 self
::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
274 $uploadDir = $this->getUploadDir();
275 if ( $this->getCliArg( 'use-filebackend=' ) ) {
276 if ( self
::$backendToUse ) {
277 $backend = self
::$backendToUse;
279 $name = $this->getCliArg( 'use-filebackend=' );
280 $useConfig = array();
281 foreach ( $wgFileBackends as $conf ) {
282 if ( $conf['name'] == $name ) {
286 $useConfig['name'] = 'local-backend'; // swap name
287 $class = $conf['class'];
288 self
::$backendToUse = new $class( $useConfig );
289 $backend = self
::$backendToUse;
292 $backend = new FSFileBackend( array(
293 'name' => 'local-backend',
294 'lockManager' => 'nullLockManager',
295 'containerPaths' => array(
296 'local-public' => "$uploadDir",
297 'local-thumb' => "$uploadDir/thumb",
303 'wgServer' => 'http://example.org',
304 'wgScript' => '/index.php',
305 'wgScriptPath' => '/',
306 'wgArticlePath' => '/wiki/$1',
307 'wgExtensionAssetsPath' => '/extensions',
308 'wgActionPaths' => array(),
309 'wgLocalFileRepo' => array(
310 'class' => 'LocalRepo',
312 'url' => 'http://example.com/images',
314 'transformVia404' => false,
315 'backend' => $backend
317 'wgEnableUploads' => self
::getOptionValue( 'wgEnableUploads', $opts, true ),
318 'wgStylePath' => '/skins',
319 'wgStyleSheetPath' => '/skins',
320 'wgSitename' => 'MediaWiki',
321 'wgLanguageCode' => $lang,
322 'wgDBprefix' => $this->db
->getType() != 'oracle' ?
'unittest_' : 'ut_',
323 'wgRawHtml' => isset( $opts['rawhtml'] ),
325 'wgContLang' => null,
326 'wgNamespacesWithSubpages' => array( NS_MAIN
=> isset( $opts['subpage'] ) ),
327 'wgMaxTocLevel' => $maxtoclevel,
328 'wgCapitalLinks' => true,
329 'wgNoFollowLinks' => true,
330 'wgNoFollowDomainExceptions' => array(),
331 'wgThumbnailScriptPath' => false,
332 'wgUseImageResize' => true,
333 'wgUseTeX' => isset( $opts['math'] ),
334 'wgMathDirectory' => $uploadDir . '/math',
335 'wgLocaltimezone' => 'UTC',
336 'wgAllowExternalImages' => true,
337 'wgUseTidy' => false,
338 'wgDefaultLanguageVariant' => $variant,
339 'wgVariantArticlePath' => false,
340 'wgGroupPermissions' => array( '*' => array(
341 'createaccount' => true,
344 'createpage' => true,
345 'createtalk' => true,
347 'wgNamespaceProtection' => array( NS_MEDIAWIKI
=> 'editinterface' ),
348 'wgDefaultExternalStore' => array(),
349 'wgForeignFileRepos' => array(),
350 'wgLinkHolderBatchSize' => $linkHolderBatchSize,
351 'wgExperimentalHtmlIds' => false,
352 'wgExternalLinkTarget' => false,
353 'wgAlwaysUseTidy' => false,
355 'wgWellFormedXml' => true,
356 'wgAllowMicrodataAttributes' => true,
357 'wgAdaptiveMessageCache' => true,
358 'wgUseDatabaseMessages' => true,
362 $configLines = explode( "\n", $config );
364 foreach ( $configLines as $line ) {
365 list( $var, $value ) = explode( '=', $line, 2 );
367 $settings[$var] = eval( "return $value;" ); //???
371 $this->savedGlobals
= array();
374 wfRunHooks( 'ParserTestGlobals', array( &$settings ) );
376 foreach ( $settings as $var => $val ) {
377 if ( array_key_exists( $var, $GLOBALS ) ) {
378 $this->savedGlobals
[$var] = $GLOBALS[$var];
381 $GLOBALS[$var] = $val;
384 $langObj = Language
::factory( $lang );
385 $GLOBALS['wgContLang'] = $langObj;
386 $context = new RequestContext();
387 $GLOBALS['wgLang'] = $context->getLanguage();
389 $GLOBALS['wgMemc'] = new EmptyBagOStuff
;
390 $GLOBALS['wgOut'] = $context->getOutput();
391 $GLOBALS['wgUser'] = $context->getUser();
395 $wgHooks['ParserTestParser'][] = 'ParserTestParserHook::setup';
396 $wgHooks['ParserGetVariableValueTs'][] = 'ParserTest::getFakeTimestamp';
398 MagicWord
::clearCache();
399 RepoGroup
::destroySingleton();
400 FileBackendGroup
::destroySingleton();
402 # Create dummy files in storage
403 $this->setupUploads();
405 # Publish the articles after we have the final language set
406 $this->publishTestArticles();
408 # The entries saved into RepoGroup cache with previous globals will be wrong.
409 RepoGroup
::destroySingleton();
410 FileBackendGroup
::destroySingleton();
411 MessageCache
::destroyInstance();
417 * Get an FS upload directory (only applies to FSFileBackend)
419 * @return String: the directory
421 protected function getUploadDir() {
422 if ( $this->keepUploads
) {
423 $dir = wfTempDir() . '/mwParser-images';
425 if ( is_dir( $dir ) ) {
429 $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
432 // wfDebug( "Creating upload directory $dir\n" );
433 if ( file_exists( $dir ) ) {
434 wfDebug( "Already exists!\n" );
442 * Create a dummy uploads directory which will contain a couple
443 * of files in order to pass existence tests.
445 * @return String: the directory
447 protected function setupUploads() {
450 $base = $this->getBaseDir();
451 $backend = RepoGroup
::singleton()->getLocalRepo()->getBackend();
452 $backend->prepare( array( 'dir' => "$base/local-public/3/3a" ) );
453 $backend->store( array(
454 'src' => "$IP/skins/monobook/headbg.jpg", 'dst' => "$base/local-public/3/3a/Foobar.jpg"
456 $backend->prepare( array( 'dir' => "$base/local-public/e/ea" ) );
457 $backend->store( array(
458 'src' => "$IP/skins/monobook/wiki.png", 'dst' => "$base/local-public/e/ea/Thumb.png"
460 $backend->prepare( array( 'dir' => "$base/local-public/0/09" ) );
461 $backend->store( array(
462 'src' => "$IP/skins/monobook/headbg.jpg", 'dst' => "$base/local-public/0/09/Bad.jpg"
467 * Restore default values and perform any necessary clean-up
468 * after each test runs.
470 protected function teardownGlobals() {
471 $this->teardownUploads();
473 foreach ( $this->savedGlobals
as $var => $val ) {
474 $GLOBALS[$var] = $val;
477 RepoGroup
::destroySingleton();
478 LinkCache
::singleton()->clear();
482 * Remove the dummy uploads directory
484 private function teardownUploads() {
485 if ( $this->keepUploads
) {
489 $base = $this->getBaseDir();
490 // delete the files first, then the dirs.
493 "$base/local-public/3/3a/Foobar.jpg",
494 "$base/local-thumb/3/3a/Foobar.jpg/180px-Foobar.jpg",
495 "$base/local-thumb/3/3a/Foobar.jpg/200px-Foobar.jpg",
496 "$base/local-thumb/3/3a/Foobar.jpg/640px-Foobar.jpg",
497 "$base/local-thumb/3/3a/Foobar.jpg/120px-Foobar.jpg",
498 "$base/local-thumb/3/3a/Foobar.jpg/1280px-Foobar.jpg",
499 "$base/local-thumb/3/3a/Foobar.jpg/20px-Foobar.jpg",
500 "$base/local-thumb/3/3a/Foobar.jpg/270px-Foobar.jpg",
501 "$base/local-thumb/3/3a/Foobar.jpg/300px-Foobar.jpg",
502 "$base/local-thumb/3/3a/Foobar.jpg/30px-Foobar.jpg",
503 "$base/local-thumb/3/3a/Foobar.jpg/360px-Foobar.jpg",
504 "$base/local-thumb/3/3a/Foobar.jpg/400px-Foobar.jpg",
505 "$base/local-thumb/3/3a/Foobar.jpg/40px-Foobar.jpg",
506 "$base/local-thumb/3/3a/Foobar.jpg/70px-Foobar.jpg",
507 "$base/local-thumb/3/3a/Foobar.jpg/960px-Foobar.jpg",
509 "$base/local-public/e/ea/Thumb.png",
511 "$base/local-public/0/09/Bad.jpg",
513 "$base/local-public/math/f/a/5/fa50b8b616463173474302ca3e63586b.png",
519 * Delete the specified files, if they exist.
520 * @param $files Array: full paths to files to delete.
522 private static function deleteFiles( $files ) {
523 $backend = RepoGroup
::singleton()->getLocalRepo()->getBackend();
524 foreach ( $files as $file ) {
525 $backend->delete( array( 'src' => $file ), array( 'force' => 1 ) );
527 foreach ( $files as $file ) {
529 while ( $tmp = FileBackend
::parentStoragePath( $tmp ) ) {
530 if ( !$backend->clean( array( 'dir' => $tmp ) )->isOK() ) {
537 protected function getBaseDir() {
538 return 'mwstore://local-backend';
541 public function parserTestProvider() {
542 if ( $this->file
=== false ) {
543 global $wgParserTestFiles;
544 $this->file
= $wgParserTestFiles[0];
546 return new TestFileIterator( $this->file
, $this );
550 * Set the file from whose tests will be run by this instance
552 public function setParserTestFile( $filename ) {
553 $this->file
= $filename;
558 * @dataProvider parserTestProvider
560 public function testParserTest( $desc, $input, $result, $opts, $config ) {
561 if ( $this->regex
!= '' && !preg_match( '/' . $this->regex
. '/', $desc ) ) {
562 $this->assertTrue( true ); // XXX: don't flood output with "test made no assertions"
563 //$this->markTestSkipped( 'Filtered out by the user' );
567 if ( !$this->isWikitextNS( NS_MAIN
) ) {
568 // parser tests frequently assume that the main namespace contains wikitext.
569 // @todo: When setting up pages, force the content model. Only skip if
570 // $wgtContentModelUseDB is false.
571 $this->markTestSkipped( "Main namespace does not support wikitext,"
572 . "skipping parser test: $desc" );
575 wfDebug( "Running parser test: $desc\n" );
577 $opts = $this->parseOptions( $opts );
578 $context = $this->setupGlobals( $opts, $config );
580 $user = $context->getUser();
581 $options = ParserOptions
::newFromContext( $context );
583 if ( isset( $opts['title'] ) ) {
584 $titleText = $opts['title'];
586 $titleText = 'Parser test';
589 $local = isset( $opts['local'] );
590 $preprocessor = isset( $opts['preprocessor'] ) ?
$opts['preprocessor'] : null;
591 $parser = $this->getParser( $preprocessor );
593 $title = Title
::newFromText( $titleText );
595 if ( isset( $opts['pst'] ) ) {
596 $out = $parser->preSaveTransform( $input, $title, $user, $options );
597 } elseif ( isset( $opts['msg'] ) ) {
598 $out = $parser->transformMsg( $input, $options, $title );
599 } elseif ( isset( $opts['section'] ) ) {
600 $section = $opts['section'];
601 $out = $parser->getSection( $input, $section );
602 } elseif ( isset( $opts['replace'] ) ) {
603 $section = $opts['replace'][0];
604 $replace = $opts['replace'][1];
605 $out = $parser->replaceSection( $input, $section, $replace );
606 } elseif ( isset( $opts['comment'] ) ) {
607 $out = Linker
::formatComment( $input, $title, $local );
608 } elseif ( isset( $opts['preload'] ) ) {
609 $out = $parser->getPreloadText( $input, $title, $options );
611 $output = $parser->parse( $input, $title, $options, true, true, 1337 );
612 $out = $output->getText();
614 if ( isset( $opts['showtitle'] ) ) {
615 if ( $output->getTitleText() ) {
616 $title = $output->getTitleText();
619 $out = "$title\n$out";
622 if ( isset( $opts['ill'] ) ) {
623 $out = $this->tidy( implode( ' ', $output->getLanguageLinks() ) );
624 } elseif ( isset( $opts['cat'] ) ) {
625 $outputPage = $context->getOutput();
626 $outputPage->addCategoryLinks( $output->getCategories() );
627 $cats = $outputPage->getCategoryLinks();
629 if ( isset( $cats['normal'] ) ) {
630 $out = $this->tidy( implode( ' ', $cats['normal'] ) );
635 $parser->mPreprocessor
= null;
637 $result = $this->tidy( $result );
640 $this->teardownGlobals();
642 $this->assertEquals( $result, $out, $desc );
646 * Run a fuzz test series
647 * Draw input from a set of test files
649 * @todo fixme Needs some work to not eat memory until the world explodes
653 function testFuzzTests() {
654 global $wgParserTestFiles;
656 $files = $wgParserTestFiles;
658 if ( $this->getCliArg( 'file=' ) ) {
659 $files = array( $this->getCliArg( 'file=' ) );
662 $dict = $this->getFuzzInput( $files );
663 $dictSize = strlen( $dict );
664 $logMaxLength = log( $this->maxFuzzTestLength
);
666 ini_set( 'memory_limit', $this->memoryLimit
* 1048576 );
669 $opts = ParserOptions
::newFromUser( $user );
670 $title = Title
::makeTitle( NS_MAIN
, 'Parser_test' );
676 // Generate test input
677 mt_srand( ++
$this->fuzzSeed
);
678 $totalLength = mt_rand( 1, $this->maxFuzzTestLength
);
681 while ( strlen( $input ) < $totalLength ) {
682 $logHairLength = mt_rand( 0, 1000000 ) / 1000000 * $logMaxLength;
683 $hairLength = min( intval( exp( $logHairLength ) ), $dictSize );
684 $offset = mt_rand( 0, $dictSize - $hairLength );
685 $input .= substr( $dict, $offset, $hairLength );
688 $this->setupGlobals();
689 $parser = $this->getParser();
693 $parser->parse( $input, $title, $opts );
694 $this->assertTrue( true, "Test $id, fuzz seed {$this->fuzzSeed}" );
695 } catch ( Exception
$exception ) {
696 $input_dump = sprintf( "string(%d) \"%s\"\n", strlen( $input ), $input );
698 $this->assertTrue( false, "Test $id, fuzz seed {$this->fuzzSeed}. \n\nInput: $input_dump\n\nError: {$exception->getMessage()}\n\nBacktrace: {$exception->getTraceAsString()}" );
701 $this->teardownGlobals();
702 $parser->__destruct();
704 if ( $id %
100 == 0 ) {
705 $usage = intval( memory_get_usage( true ) / $this->memoryLimit
/ 1048576 * 100 );
706 //echo "{$this->fuzzSeed}: $numSuccess/$numTotal (mem: $usage%)\n";
708 $ret = "Out of memory:\n";
709 $memStats = $this->getMemoryBreakdown();
711 foreach ( $memStats as $name => $usage ) {
712 $ret .= "$name: $usage\n";
715 throw new MWException( $ret );
724 //Various getter functions
727 * Get an input dictionary from a set of parser test files
729 function getFuzzInput( $filenames ) {
732 foreach ( $filenames as $filename ) {
733 $contents = file_get_contents( $filename );
734 preg_match_all( '/!!\s*input\n(.*?)\n!!\s*result/s', $contents, $matches );
736 foreach ( $matches[1] as $match ) {
737 $dict .= $match . "\n";
745 * Get a memory usage breakdown
747 function getMemoryBreakdown() {
750 foreach ( $GLOBALS as $name => $value ) {
751 $memStats['$' . $name] = strlen( serialize( $value ) );
754 $classes = get_declared_classes();
756 foreach ( $classes as $class ) {
757 $rc = new ReflectionClass( $class );
758 $props = $rc->getStaticProperties();
759 $memStats[$class] = strlen( serialize( $props ) );
760 $methods = $rc->getMethods();
762 foreach ( $methods as $method ) {
763 $memStats[$class] +
= strlen( serialize( $method->getStaticVariables() ) );
767 $functions = get_defined_functions();
769 foreach ( $functions['user'] as $function ) {
770 $rf = new ReflectionFunction( $function );
771 $memStats["$function()"] = strlen( serialize( $rf->getStaticVariables() ) );
780 * Get a Parser object
782 function getParser( $preprocessor = null ) {
783 global $wgParserConf;
785 $class = $wgParserConf['class'];
786 $parser = new $class( array( 'preprocessorClass' => $preprocessor ) +
$wgParserConf );
788 wfRunHooks( 'ParserTestParser', array( &$parser ) );
793 //Various action functions
795 public function addArticle( $name, $text, $line ) {
796 self
::$articles[$name] = array( $text, $line );
799 public function publishTestArticles() {
800 if ( empty( self
::$articles ) ) {
804 foreach ( self
::$articles as $name => $info ) {
805 list( $text, $line ) = $info;
806 ParserTest
::addArticle( $name, $text, $line, 'ignoreduplicate' );
811 * Steal a callback function from the primary parser, save it for
812 * application to our scary parser. If the hook is not installed,
813 * abort processing of this file.
815 * @param $name String
816 * @return Bool true if tag hook is present
818 public function requireHook( $name ) {
820 $wgParser->firstCallInit(); // make sure hooks are loaded.
821 return isset( $wgParser->mTagHooks
[$name] );
824 public function requireFunctionHook( $name ) {
826 $wgParser->firstCallInit(); // make sure hooks are loaded.
827 return isset( $wgParser->mFunctionHooks
[$name] );
830 //Various "cleanup" functions
833 * Run the "tidy" command on text if the $wgUseTidy
836 * @param $text String: the text to tidy
839 protected function tidy( $text ) {
843 $text = MWTidy
::tidy( $text );
850 * Remove last character if it is a newline
852 public function removeEndingNewline( $s ) {
853 if ( substr( $s, -1 ) === "\n" ) {
854 return substr( $s, 0, -1 );
860 //Test options parser functions
862 protected function parseOptions( $instring ) {
868 // foo=bar,"baz quux"
892 \[\[[^]]*\]\] # Link target
900 if ( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER
) ) {
901 foreach ( $matches as $bits ) {
902 array_shift( $bits );
903 $key = strtolower( array_shift( $bits ) );
904 if ( count( $bits ) == 0 ) {
906 } elseif ( count( $bits ) == 1 ) {
907 $opts[$key] = $this->cleanupOption( array_shift( $bits ) );
910 $opts[$key] = array_map( array( $this, 'cleanupOption' ), $bits );
917 protected function cleanupOption( $opt ) {
918 if ( substr( $opt, 0, 1 ) == '"' ) {
919 return substr( $opt, 1, -1 );
922 if ( substr( $opt, 0, 2 ) == '[[' ) {
923 return substr( $opt, 2, -2 );
929 * Use a regex to find out the value of an option
930 * @param $key String: name of option val to retrieve
931 * @param $opts Options array to look in
932 * @param $default Mixed: default value returned if not found
934 protected static function getOptionValue( $key, $opts, $default ) {
935 $key = strtolower( $key );
937 if ( isset( $opts[$key] ) ) {