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";
89 foreach ( $tmpGlobals as $var => $val ) {
90 if ( array_key_exists( $var, $GLOBALS ) ) {
91 $this->savedInitialGlobals
[$var] = $GLOBALS[$var];
94 $GLOBALS[$var] = $val;
97 $this->savedWeirdGlobals
['mw_namespace_protection'] = $wgNamespaceProtection[NS_MEDIAWIKI
];
98 $this->savedWeirdGlobals
['image_alias'] = $wgNamespaceAliases['Image'];
99 $this->savedWeirdGlobals
['image_talk_alias'] = $wgNamespaceAliases['Image_talk'];
101 $wgNamespaceProtection[NS_MEDIAWIKI
] = 'editinterface';
102 $wgNamespaceAliases['Image'] = NS_FILE
;
103 $wgNamespaceAliases['Image_talk'] = NS_FILE_TALK
;
106 protected function tearDown() {
107 foreach ( $this->savedInitialGlobals
as $var => $val ) {
108 $GLOBALS[$var] = $val;
111 global $wgNamespaceProtection, $wgNamespaceAliases;
113 $wgNamespaceProtection[NS_MEDIAWIKI
] = $this->savedWeirdGlobals
['mw_namespace_protection'];
114 $wgNamespaceAliases['Image'] = $this->savedWeirdGlobals
['image_alias'];
115 $wgNamespaceAliases['Image_talk'] = $this->savedWeirdGlobals
['image_talk_alias'];
118 RepoGroup
::destroySingleton();
119 FileBackendGroup
::destroySingleton();
124 function addDBData() {
125 $this->tablesUsed
[] = 'site_stats';
126 $this->tablesUsed
[] = 'interwiki';
127 # disabled for performance
128 #$this->tablesUsed[] = 'image';
130 # Hack: insert a few Wikipedia in-project interwiki prefixes,
131 # for testing inter-language links
132 $this->db
->insert( 'interwiki', array(
133 array( 'iw_prefix' => 'wikipedia',
134 'iw_url' => 'http://en.wikipedia.org/wiki/$1',
138 array( 'iw_prefix' => 'meatball',
139 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
143 array( 'iw_prefix' => 'zh',
144 'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
148 array( 'iw_prefix' => 'es',
149 'iw_url' => 'http://es.wikipedia.org/wiki/$1',
153 array( 'iw_prefix' => 'fr',
154 'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
158 array( 'iw_prefix' => 'ru',
159 'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
164 * @todo Fixme! Why are we inserting duplicate data here? Shouldn't
165 * need this IGNORE or shouldn't need the insert at all.
167 ), __METHOD__
, array( 'IGNORE' )
170 # Update certain things in site_stats
171 $this->db
->insert( 'site_stats',
172 array( 'ss_row_id' => 1, 'ss_images' => 2, 'ss_good_articles' => 1 ),
176 # Reinitialise the LocalisationCache to match the database state
177 Language
::getLocalisationCache()->unloadAll();
179 # Clear the message cache
180 MessageCache
::singleton()->clear();
182 $user = User
::newFromId( 0 );
183 LinkCache
::singleton()->clear(); # Avoids the odd failure at creating the nullRevision
185 # Upload DB table entries for files.
186 # We will upload the actual files later. Note that if anything causes LocalFile::load()
187 # to be triggered before then, it will break via maybeUpgrade() setting the fileExists
188 # member to false and storing it in cache.
189 # note that the size/width/height/bits/etc of the file
190 # are actually set by inspecting the file itself; the arguments
191 # to recordUpload2 have no effect. That said, we try to make things
192 # match up so it is less confusing to readers of the code & tests.
193 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Foobar.jpg' ) );
194 if ( !$this->db
->selectField( 'image', '1', array( 'img_name' => $image->getName() ) ) ) {
195 $image->recordUpload2(
197 'Upload of some lame file',
204 'media_type' => MEDIATYPE_BITMAP
,
205 'mime' => 'image/jpeg',
206 'metadata' => serialize( array() ),
207 'sha1' => wfBaseConvert( '1', 16, 36, 31 ),
208 'fileExists' => true ),
209 $this->db
->timestamp( '20010115123500' ), $user
213 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Thumb.png' ) );
214 if ( !$this->db
->selectField( 'image', '1', array( 'img_name' => $image->getName() ) ) ) {
215 $image->recordUpload2(
217 'Upload of some lame thumbnail',
218 'Some lame thumbnail',
224 'media_type' => MEDIATYPE_BITMAP
,
225 'mime' => 'image/png',
226 'metadata' => serialize( array() ),
227 'sha1' => wfBaseConvert( '2', 16, 36, 31 ),
228 'fileExists' => true ),
229 $this->db
->timestamp( '20130225203040' ), $user
233 # This image will be blacklisted in [[MediaWiki:Bad image list]]
234 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Bad.jpg' ) );
235 if ( !$this->db
->selectField( 'image', '1', array( 'img_name' => $image->getName() ) ) ) {
236 $image->recordUpload2(
245 'media_type' => MEDIATYPE_BITMAP
,
246 'mime' => 'image/jpeg',
247 'metadata' => serialize( array() ),
248 'sha1' => wfBaseConvert( '3', 16, 36, 31 ),
249 'fileExists' => true ),
250 $this->db
->timestamp( '20010115123500' ), $user
255 //ParserTest setup/teardown functions
258 * Set up the global variables for a consistent environment for each test.
259 * Ideally this should replace the global configuration entirely.
261 protected function setupGlobals( $opts = array(), $config = '' ) {
262 global $wgFileBackends;
263 # Find out values for some special options.
265 self
::getOptionValue( 'language', $opts, 'en' );
267 self
::getOptionValue( 'variant', $opts, false );
269 self
::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
270 $linkHolderBatchSize =
271 self
::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
273 $uploadDir = $this->getUploadDir();
274 if ( $this->getCliArg( 'use-filebackend=' ) ) {
275 if ( self
::$backendToUse ) {
276 $backend = self
::$backendToUse;
278 $name = $this->getCliArg( 'use-filebackend=' );
279 $useConfig = array();
280 foreach ( $wgFileBackends as $conf ) {
281 if ( $conf['name'] == $name ) {
285 $useConfig['name'] = 'local-backend'; // swap name
286 $class = $conf['class'];
287 self
::$backendToUse = new $class( $useConfig );
288 $backend = self
::$backendToUse;
291 $backend = new FSFileBackend( array(
292 'name' => 'local-backend',
293 'lockManager' => 'nullLockManager',
294 'containerPaths' => array(
295 'local-public' => "$uploadDir",
296 'local-thumb' => "$uploadDir/thumb",
302 'wgServer' => 'http://example.org',
303 'wgScript' => '/index.php',
304 'wgScriptPath' => '/',
305 'wgArticlePath' => '/wiki/$1',
306 'wgExtensionAssetsPath' => '/extensions',
307 'wgActionPaths' => array(),
308 'wgLocalFileRepo' => array(
309 'class' => 'LocalRepo',
311 'url' => 'http://example.com/images',
313 'transformVia404' => false,
314 'backend' => $backend
316 'wgEnableUploads' => self
::getOptionValue( 'wgEnableUploads', $opts, true ),
317 'wgStylePath' => '/skins',
318 'wgStyleSheetPath' => '/skins',
319 'wgSitename' => 'MediaWiki',
320 'wgLanguageCode' => $lang,
321 'wgDBprefix' => $this->db
->getType() != 'oracle' ?
'unittest_' : 'ut_',
322 'wgRawHtml' => isset( $opts['rawhtml'] ),
324 'wgContLang' => null,
325 'wgNamespacesWithSubpages' => array( NS_MAIN
=> isset( $opts['subpage'] ) ),
326 'wgMaxTocLevel' => $maxtoclevel,
327 'wgCapitalLinks' => true,
328 'wgNoFollowLinks' => true,
329 'wgNoFollowDomainExceptions' => array(),
330 'wgThumbnailScriptPath' => false,
331 'wgUseImageResize' => true,
332 'wgUseTeX' => isset( $opts['math'] ),
333 'wgMathDirectory' => $uploadDir . '/math',
334 'wgLocaltimezone' => 'UTC',
335 'wgAllowExternalImages' => true,
336 'wgUseTidy' => false,
337 'wgDefaultLanguageVariant' => $variant,
338 'wgVariantArticlePath' => false,
339 'wgGroupPermissions' => array( '*' => array(
340 'createaccount' => true,
343 'createpage' => true,
344 'createtalk' => true,
346 'wgNamespaceProtection' => array( NS_MEDIAWIKI
=> 'editinterface' ),
347 'wgDefaultExternalStore' => array(),
348 'wgForeignFileRepos' => array(),
349 'wgLinkHolderBatchSize' => $linkHolderBatchSize,
350 'wgExperimentalHtmlIds' => false,
351 'wgExternalLinkTarget' => false,
352 'wgAlwaysUseTidy' => false,
354 'wgWellFormedXml' => true,
355 'wgAllowMicrodataAttributes' => true,
356 'wgAdaptiveMessageCache' => true,
357 'wgUseDatabaseMessages' => true,
361 $configLines = explode( "\n", $config );
363 foreach ( $configLines as $line ) {
364 list( $var, $value ) = explode( '=', $line, 2 );
366 $settings[$var] = eval( "return $value;" ); //???
370 $this->savedGlobals
= array();
373 wfRunHooks( 'ParserTestGlobals', array( &$settings ) );
375 foreach ( $settings as $var => $val ) {
376 if ( array_key_exists( $var, $GLOBALS ) ) {
377 $this->savedGlobals
[$var] = $GLOBALS[$var];
380 $GLOBALS[$var] = $val;
383 $langObj = Language
::factory( $lang );
384 $GLOBALS['wgContLang'] = $langObj;
385 $context = new RequestContext();
386 $GLOBALS['wgLang'] = $context->getLanguage();
388 $GLOBALS['wgMemc'] = new EmptyBagOStuff
;
389 $GLOBALS['wgOut'] = $context->getOutput();
390 $GLOBALS['wgUser'] = $context->getUser();
394 $wgHooks['ParserTestParser'][] = 'ParserTestParserHook::setup';
395 $wgHooks['ParserGetVariableValueTs'][] = 'ParserTest::getFakeTimestamp';
397 MagicWord
::clearCache();
398 RepoGroup
::destroySingleton();
399 FileBackendGroup
::destroySingleton();
401 # Create dummy files in storage
402 $this->setupUploads();
404 # Publish the articles after we have the final language set
405 $this->publishTestArticles();
407 # The entries saved into RepoGroup cache with previous globals will be wrong.
408 RepoGroup
::destroySingleton();
409 FileBackendGroup
::destroySingleton();
410 MessageCache
::destroyInstance();
416 * Get an FS upload directory (only applies to FSFileBackend)
418 * @return String: the directory
420 protected function getUploadDir() {
421 if ( $this->keepUploads
) {
422 $dir = wfTempDir() . '/mwParser-images';
424 if ( is_dir( $dir ) ) {
428 $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
431 // wfDebug( "Creating upload directory $dir\n" );
432 if ( file_exists( $dir ) ) {
433 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];
547 return new TestFileIterator( $this->file
, $this );
551 * Set the file from whose tests will be run by this instance
553 public function setParserTestFile( $filename ) {
554 $this->file
= $filename;
559 * @dataProvider parserTestProvider
561 public function testParserTest( $desc, $input, $result, $opts, $config ) {
562 if ( $this->regex
!= '' && !preg_match( '/' . $this->regex
. '/', $desc ) ) {
563 $this->assertTrue( true ); // XXX: don't flood output with "test made no assertions"
564 //$this->markTestSkipped( 'Filtered out by the user' );
568 if ( !$this->isWikitextNS( NS_MAIN
) ) {
569 // parser tests frequently assume that the main namespace contains wikitext.
570 // @todo: When setting up pages, force the content model. Only skip if
571 // $wgtContentModelUseDB is false.
572 $this->markTestSkipped( "Main namespace does not support wikitext,"
573 . "skipping parser test: $desc" );
576 wfDebug( "Running parser test: $desc\n" );
578 $opts = $this->parseOptions( $opts );
579 $context = $this->setupGlobals( $opts, $config );
581 $user = $context->getUser();
582 $options = ParserOptions
::newFromContext( $context );
584 if ( isset( $opts['title'] ) ) {
585 $titleText = $opts['title'];
587 $titleText = 'Parser test';
590 $local = isset( $opts['local'] );
591 $preprocessor = isset( $opts['preprocessor'] ) ?
$opts['preprocessor'] : null;
592 $parser = $this->getParser( $preprocessor );
594 $title = Title
::newFromText( $titleText );
596 if ( isset( $opts['pst'] ) ) {
597 $out = $parser->preSaveTransform( $input, $title, $user, $options );
598 } elseif ( isset( $opts['msg'] ) ) {
599 $out = $parser->transformMsg( $input, $options, $title );
600 } elseif ( isset( $opts['section'] ) ) {
601 $section = $opts['section'];
602 $out = $parser->getSection( $input, $section );
603 } elseif ( isset( $opts['replace'] ) ) {
604 $section = $opts['replace'][0];
605 $replace = $opts['replace'][1];
606 $out = $parser->replaceSection( $input, $section, $replace );
607 } elseif ( isset( $opts['comment'] ) ) {
608 $out = Linker
::formatComment( $input, $title, $local );
609 } elseif ( isset( $opts['preload'] ) ) {
610 $out = $parser->getPreloadText( $input, $title, $options );
612 $output = $parser->parse( $input, $title, $options, true, true, 1337 );
613 $out = $output->getText();
615 if ( isset( $opts['showtitle'] ) ) {
616 if ( $output->getTitleText() ) {
617 $title = $output->getTitleText();
620 $out = "$title\n$out";
623 if ( isset( $opts['ill'] ) ) {
624 $out = $this->tidy( implode( ' ', $output->getLanguageLinks() ) );
625 } elseif ( isset( $opts['cat'] ) ) {
626 $outputPage = $context->getOutput();
627 $outputPage->addCategoryLinks( $output->getCategories() );
628 $cats = $outputPage->getCategoryLinks();
630 if ( isset( $cats['normal'] ) ) {
631 $out = $this->tidy( implode( ' ', $cats['normal'] ) );
636 $parser->mPreprocessor
= null;
638 $result = $this->tidy( $result );
641 $this->teardownGlobals();
643 $this->assertEquals( $result, $out, $desc );
647 * Run a fuzz test series
648 * Draw input from a set of test files
650 * @todo fixme Needs some work to not eat memory until the world explodes
654 function testFuzzTests() {
655 global $wgParserTestFiles;
657 $files = $wgParserTestFiles;
659 if ( $this->getCliArg( 'file=' ) ) {
660 $files = array( $this->getCliArg( 'file=' ) );
663 $dict = $this->getFuzzInput( $files );
664 $dictSize = strlen( $dict );
665 $logMaxLength = log( $this->maxFuzzTestLength
);
667 ini_set( 'memory_limit', $this->memoryLimit
* 1048576 );
670 $opts = ParserOptions
::newFromUser( $user );
671 $title = Title
::makeTitle( NS_MAIN
, 'Parser_test' );
677 // Generate test input
678 mt_srand( ++
$this->fuzzSeed
);
679 $totalLength = mt_rand( 1, $this->maxFuzzTestLength
);
682 while ( strlen( $input ) < $totalLength ) {
683 $logHairLength = mt_rand( 0, 1000000 ) / 1000000 * $logMaxLength;
684 $hairLength = min( intval( exp( $logHairLength ) ), $dictSize );
685 $offset = mt_rand( 0, $dictSize - $hairLength );
686 $input .= substr( $dict, $offset, $hairLength );
689 $this->setupGlobals();
690 $parser = $this->getParser();
694 $parser->parse( $input, $title, $opts );
695 $this->assertTrue( true, "Test $id, fuzz seed {$this->fuzzSeed}" );
696 } catch ( Exception
$exception ) {
697 $input_dump = sprintf( "string(%d) \"%s\"\n", strlen( $input ), $input );
699 $this->assertTrue( false, "Test $id, fuzz seed {$this->fuzzSeed}. \n\nInput: $input_dump\n\nError: {$exception->getMessage()}\n\nBacktrace: {$exception->getTraceAsString()}" );
702 $this->teardownGlobals();
703 $parser->__destruct();
705 if ( $id %
100 == 0 ) {
706 $usage = intval( memory_get_usage( true ) / $this->memoryLimit
/ 1048576 * 100 );
707 //echo "{$this->fuzzSeed}: $numSuccess/$numTotal (mem: $usage%)\n";
709 $ret = "Out of memory:\n";
710 $memStats = $this->getMemoryBreakdown();
712 foreach ( $memStats as $name => $usage ) {
713 $ret .= "$name: $usage\n";
716 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 );
918 protected function cleanupOption( $opt ) {
919 if ( substr( $opt, 0, 1 ) == '"' ) {
920 return substr( $opt, 1, -1 );
923 if ( substr( $opt, 0, 2 ) == '[[' ) {
924 return substr( $opt, 2, -2 );
931 * Use a regex to find out the value of an option
932 * @param $key String: name of option val to retrieve
933 * @param $opts Options array to look in
934 * @param $default Mixed: default value returned if not found
936 protected static function getOptionValue( $key, $opts, $default ) {
937 $key = strtolower( $key );
939 if ( isset( $opts[$key] ) ) {