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;
20 public $showProgress = true;
21 public $savedInitialGlobals = array();
22 public $savedWeirdGlobals = array();
23 public $savedGlobals = array();
24 public $hooks = array();
25 public $functionHooks = array();
28 public $maxFuzzTestLength = 300;
30 public $memoryLimit = 50;
32 protected $file = false;
34 protected function setUp() {
35 global $wgContLang, $wgLanguageCode;
36 global $wgNamespaceProtection, $wgNamespaceAliases;
41 $wgLanguageCode = 'en';
42 $wgContLang = Language
::factory( 'en' );
45 if ( $this->getCliArg( 'regex=' ) ) {
46 $this->regex
= $this->getCliArg( 'regex=' );
52 $this->keepUploads
= $this->getCliArg( 'keep-uploads' );
54 $tmpGlobals = array();
56 $tmpGlobals['wgScript'] = '/index.php';
57 $tmpGlobals['wgScriptPath'] = '/';
58 $tmpGlobals['wgArticlePath'] = '/wiki/$1';
59 $tmpGlobals['wgStyleSheetPath'] = '/skins';
60 $tmpGlobals['wgStylePath'] = '/skins';
61 $tmpGlobals['wgThumbnailScriptPath'] = false;
62 $tmpGlobals['wgLocalFileRepo'] = array(
63 'class' => 'LocalRepo',
65 'url' => 'http://example.com/images',
67 'transformVia404' => false,
68 'backend' => 'local-backend'
70 $tmpGlobals['wgForeignFileRepos'] = array();
71 $tmpGlobals['wgEnableParserCache'] = false;
72 $tmpGlobals['wgHooks'] = $wgHooks;
73 $tmpGlobals['wgDeferredUpdateList'] = array();
74 $tmpGlobals['wgMemc'] = wfGetMainCache();
75 $tmpGlobals['messageMemc'] = wfGetMessageCacheStorage();
76 $tmpGlobals['parserMemc'] = wfGetParserCacheStorage();
78 // $tmpGlobals['wgContLang'] = new StubContLang;
79 $tmpGlobals['wgUser'] = new User
;
80 $context = new RequestContext();
81 $tmpGlobals['wgLang'] = $context->getLanguage();
82 $tmpGlobals['wgOut'] = $context->getOutput();
83 $tmpGlobals['wgParser'] = new StubObject( 'wgParser', $GLOBALS['wgParserConf']['class'], array( $GLOBALS['wgParserConf'] ) );
84 $tmpGlobals['wgRequest'] = $context->getRequest();
86 if ( $GLOBALS['wgStyleDirectory'] === false ) {
87 $tmpGlobals['wgStyleDirectory'] = "$IP/skins";
91 foreach ( $tmpGlobals as $var => $val ) {
92 if ( array_key_exists( $var, $GLOBALS ) ) {
93 $this->savedInitialGlobals
[$var] = $GLOBALS[$var];
96 $GLOBALS[$var] = $val;
99 $this->savedWeirdGlobals
['mw_namespace_protection'] = $wgNamespaceProtection[NS_MEDIAWIKI
];
100 $this->savedWeirdGlobals
['image_alias'] = $wgNamespaceAliases['Image'];
101 $this->savedWeirdGlobals
['image_talk_alias'] = $wgNamespaceAliases['Image_talk'];
103 $wgNamespaceProtection[NS_MEDIAWIKI
] = 'editinterface';
104 $wgNamespaceAliases['Image'] = NS_FILE
;
105 $wgNamespaceAliases['Image_talk'] = NS_FILE_TALK
;
108 protected function tearDown() {
109 foreach ( $this->savedInitialGlobals
as $var => $val ) {
110 $GLOBALS[$var] = $val;
113 global $wgNamespaceProtection, $wgNamespaceAliases;
115 $wgNamespaceProtection[NS_MEDIAWIKI
] = $this->savedWeirdGlobals
['mw_namespace_protection'];
116 $wgNamespaceAliases['Image'] = $this->savedWeirdGlobals
['image_alias'];
117 $wgNamespaceAliases['Image_talk'] = $this->savedWeirdGlobals
['image_talk_alias'];
120 RepoGroup
::destroySingleton();
121 FileBackendGroup
::destroySingleton();
126 function addDBData() {
127 $this->tablesUsed
[] = 'site_stats';
128 $this->tablesUsed
[] = 'interwiki';
129 # disabled for performance
130 #$this->tablesUsed[] = 'image';
132 # Hack: insert a few Wikipedia in-project interwiki prefixes,
133 # for testing inter-language links
134 $this->db
->insert( 'interwiki', array(
135 array( 'iw_prefix' => 'wikipedia',
136 'iw_url' => 'http://en.wikipedia.org/wiki/$1',
140 array( 'iw_prefix' => 'meatball',
141 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
145 array( 'iw_prefix' => 'zh',
146 'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
150 array( 'iw_prefix' => 'es',
151 'iw_url' => 'http://es.wikipedia.org/wiki/$1',
155 array( 'iw_prefix' => 'fr',
156 'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
160 array( 'iw_prefix' => 'ru',
161 'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
166 * @todo Fixme! Why are we inserting duplicate data here? Shouldn't
167 * need this IGNORE or shouldn't need the insert at all.
169 ), __METHOD__
, array( 'IGNORE' )
172 # Update certain things in site_stats
173 $this->db
->insert( 'site_stats',
174 array( 'ss_row_id' => 1, 'ss_images' => 2, 'ss_good_articles' => 1 ),
178 # Reinitialise the LocalisationCache to match the database state
179 Language
::getLocalisationCache()->unloadAll();
181 # Clear the message cache
182 MessageCache
::singleton()->clear();
184 $user = User
::newFromId( 0 );
185 LinkCache
::singleton()->clear(); # Avoids the odd failure at creating the nullRevision
187 # Upload DB table entries for files.
188 # We will upload the actual files later. Note that if anything causes LocalFile::load()
189 # to be triggered before then, it will break via maybeUpgrade() setting the fileExists
190 # member to false and storing it in cache.
191 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Foobar.jpg' ) );
192 if ( !$this->db
->selectField( 'image', '1', array( 'img_name' => $image->getName() ) ) ) {
193 $image->recordUpload2(
195 'Upload of some lame file',
202 'media_type' => MEDIATYPE_BITMAP
,
203 'mime' => 'image/jpeg',
204 'metadata' => serialize( array() ),
205 'sha1' => wfBaseConvert( '', 16, 36, 31 ),
206 'fileExists' => true ),
207 $this->db
->timestamp( '20010115123500' ), $user
211 # This image will be blacklisted in [[MediaWiki:Bad image list]]
212 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Bad.jpg' ) );
213 if ( !$this->db
->selectField( 'image', '1', array( 'img_name' => $image->getName() ) ) ) {
214 $image->recordUpload2(
223 'media_type' => MEDIATYPE_BITMAP
,
224 'mime' => 'image/jpeg',
225 'metadata' => serialize( array() ),
226 'sha1' => wfBaseConvert( '', 16, 36, 31 ),
227 'fileExists' => true ),
228 $this->db
->timestamp( '20010115123500' ), $user
233 //ParserTest setup/teardown functions
236 * Set up the global variables for a consistent environment for each test.
237 * Ideally this should replace the global configuration entirely.
239 protected function setupGlobals( $opts = '', $config = '' ) {
240 global $wgFileBackends;
241 # Find out values for some special options.
243 self
::getOptionValue( 'language', $opts, 'en' );
245 self
::getOptionValue( 'variant', $opts, false );
247 self
::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
248 $linkHolderBatchSize =
249 self
::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
251 $uploadDir = $this->getUploadDir();
252 if ( $this->getCliArg( 'use-filebackend=' ) ) {
253 if ( self
::$backendToUse ) {
254 $backend = self
::$backendToUse;
256 $name = $this->getCliArg( 'use-filebackend=' );
257 $useConfig = array();
258 foreach ( $wgFileBackends as $conf ) {
259 if ( $conf['name'] == $name ) {
263 $useConfig['name'] = 'local-backend'; // swap name
264 $class = $conf['class'];
265 self
::$backendToUse = new $class( $useConfig );
266 $backend = self
::$backendToUse;
269 $backend = new FSFileBackend( array(
270 'name' => 'local-backend',
271 'lockManager' => 'nullLockManager',
272 'containerPaths' => array(
273 'local-public' => "$uploadDir",
274 'local-thumb' => "$uploadDir/thumb",
280 'wgServer' => 'http://Britney-Spears',
281 'wgScript' => '/index.php',
282 'wgScriptPath' => '/',
283 'wgArticlePath' => '/wiki/$1',
284 'wgExtensionAssetsPath' => '/extensions',
285 'wgActionPaths' => array(),
286 'wgLocalFileRepo' => array(
287 'class' => 'LocalRepo',
289 'url' => 'http://example.com/images',
291 'transformVia404' => false,
292 'backend' => $backend
294 'wgEnableUploads' => self
::getOptionValue( 'wgEnableUploads', $opts, true ),
295 'wgStylePath' => '/skins',
296 'wgStyleSheetPath' => '/skins',
297 'wgSitename' => 'MediaWiki',
298 'wgLanguageCode' => $lang,
299 'wgDBprefix' => $this->db
->getType() != 'oracle' ?
'unittest_' : 'ut_',
300 'wgRawHtml' => isset( $opts['rawhtml'] ),
302 'wgContLang' => null,
303 'wgNamespacesWithSubpages' => array( 0 => isset( $opts['subpage'] ) ),
304 'wgMaxTocLevel' => $maxtoclevel,
305 'wgCapitalLinks' => true,
306 'wgNoFollowLinks' => true,
307 'wgNoFollowDomainExceptions' => array(),
308 'wgThumbnailScriptPath' => false,
309 'wgUseImageResize' => true,
310 'wgUseTeX' => isset( $opts['math'] ),
311 'wgMathDirectory' => $uploadDir . '/math',
312 'wgLocaltimezone' => 'UTC',
313 'wgAllowExternalImages' => true,
314 'wgUseTidy' => false,
315 'wgDefaultLanguageVariant' => $variant,
316 'wgVariantArticlePath' => false,
317 'wgGroupPermissions' => array( '*' => array(
318 'createaccount' => true,
321 'createpage' => true,
322 'createtalk' => true,
324 'wgNamespaceProtection' => array( NS_MEDIAWIKI
=> 'editinterface' ),
325 'wgDefaultExternalStore' => array(),
326 'wgForeignFileRepos' => array(),
327 'wgLinkHolderBatchSize' => $linkHolderBatchSize,
328 'wgExperimentalHtmlIds' => false,
329 'wgExternalLinkTarget' => false,
330 'wgAlwaysUseTidy' => false,
332 'wgWellFormedXml' => true,
333 'wgAllowMicrodataAttributes' => true,
334 'wgAdaptiveMessageCache' => true,
335 'wgUseDatabaseMessages' => true,
339 $configLines = explode( "\n", $config );
341 foreach ( $configLines as $line ) {
342 list( $var, $value ) = explode( '=', $line, 2 );
344 $settings[$var] = eval( "return $value;" ); //???
348 $this->savedGlobals
= array();
351 wfRunHooks( 'ParserTestGlobals', array( &$settings ) );
353 foreach ( $settings as $var => $val ) {
354 if ( array_key_exists( $var, $GLOBALS ) ) {
355 $this->savedGlobals
[$var] = $GLOBALS[$var];
358 $GLOBALS[$var] = $val;
361 $langObj = Language
::factory( $lang );
362 $GLOBALS['wgContLang'] = $langObj;
363 $context = new RequestContext();
364 $GLOBALS['wgLang'] = $context->getLanguage();
366 $GLOBALS['wgMemc'] = new EmptyBagOStuff
;
367 $GLOBALS['wgOut'] = $context->getOutput();
368 $GLOBALS['wgUser'] = $context->getUser();
372 $wgHooks['ParserTestParser'][] = 'ParserTestParserHook::setup';
373 $wgHooks['ParserGetVariableValueTs'][] = 'ParserTest::getFakeTimestamp';
375 MagicWord
::clearCache();
376 RepoGroup
::destroySingleton();
377 FileBackendGroup
::destroySingleton();
379 # Create dummy files in storage
380 $this->setupUploads();
382 # Publish the articles after we have the final language set
383 $this->publishTestArticles();
385 # The entries saved into RepoGroup cache with previous globals will be wrong.
386 RepoGroup
::destroySingleton();
387 FileBackendGroup
::destroySingleton();
388 MessageCache
::destroyInstance();
394 * Get an FS upload directory (only applies to FSFileBackend)
396 * @return String: the directory
398 protected function getUploadDir() {
399 if ( $this->keepUploads
) {
400 $dir = wfTempDir() . '/mwParser-images';
402 if ( is_dir( $dir ) ) {
406 $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
409 // wfDebug( "Creating upload directory $dir\n" );
410 if ( file_exists( $dir ) ) {
411 wfDebug( "Already exists!\n" );
419 * Create a dummy uploads directory which will contain a couple
420 * of files in order to pass existence tests.
422 * @return String: the directory
424 protected function setupUploads() {
427 $base = $this->getBaseDir();
428 $backend = RepoGroup
::singleton()->getLocalRepo()->getBackend();
429 $backend->prepare( array( 'dir' => "$base/local-public/3/3a" ) );
430 $backend->store( array(
431 'src' => "$IP/skins/monobook/headbg.jpg", 'dst' => "$base/local-public/3/3a/Foobar.jpg"
433 $backend->prepare( array( 'dir' => "$base/local-public/0/09" ) );
434 $backend->store( array(
435 'src' => "$IP/skins/monobook/headbg.jpg", 'dst' => "$base/local-public/0/09/Bad.jpg"
440 * Restore default values and perform any necessary clean-up
441 * after each test runs.
443 protected function teardownGlobals() {
444 $this->teardownUploads();
446 foreach ( $this->savedGlobals
as $var => $val ) {
447 $GLOBALS[$var] = $val;
450 RepoGroup
::destroySingleton();
451 LinkCache
::singleton()->clear();
455 * Remove the dummy uploads directory
457 private function teardownUploads() {
458 if ( $this->keepUploads
) {
462 $base = $this->getBaseDir();
463 // delete the files first, then the dirs.
466 "$base/local-public/3/3a/Foobar.jpg",
467 "$base/local-thumb/3/3a/Foobar.jpg/180px-Foobar.jpg",
468 "$base/local-thumb/3/3a/Foobar.jpg/200px-Foobar.jpg",
469 "$base/local-thumb/3/3a/Foobar.jpg/640px-Foobar.jpg",
470 "$base/local-thumb/3/3a/Foobar.jpg/120px-Foobar.jpg",
471 "$base/local-thumb/3/3a/Foobar.jpg/1280px-Foobar.jpg",
472 "$base/local-thumb/3/3a/Foobar.jpg/20px-Foobar.jpg",
473 "$base/local-thumb/3/3a/Foobar.jpg/270px-Foobar.jpg",
474 "$base/local-thumb/3/3a/Foobar.jpg/300px-Foobar.jpg",
475 "$base/local-thumb/3/3a/Foobar.jpg/30px-Foobar.jpg",
476 "$base/local-thumb/3/3a/Foobar.jpg/360px-Foobar.jpg",
477 "$base/local-thumb/3/3a/Foobar.jpg/400px-Foobar.jpg",
478 "$base/local-thumb/3/3a/Foobar.jpg/40px-Foobar.jpg",
479 "$base/local-thumb/3/3a/Foobar.jpg/70px-Foobar.jpg",
480 "$base/local-thumb/3/3a/Foobar.jpg/960px-Foobar.jpg",
482 "$base/local-public/0/09/Bad.jpg",
483 "$base/local-thumb/0/09/Bad.jpg",
485 "$base/local-public/math/f/a/5/fa50b8b616463173474302ca3e63586b.png",
491 * Delete the specified files, if they exist.
492 * @param $files Array: full paths to files to delete.
494 private static function deleteFiles( $files ) {
495 $backend = RepoGroup
::singleton()->getLocalRepo()->getBackend();
496 foreach ( $files as $file ) {
497 $backend->delete( array( 'src' => $file ), array( 'force' => 1 ) );
499 foreach ( $files as $file ) {
501 while ( $tmp = FileBackend
::parentStoragePath( $tmp ) ) {
502 if ( !$backend->clean( array( 'dir' => $tmp ) )->isOK() ) {
509 protected function getBaseDir() {
510 return 'mwstore://local-backend';
513 public function parserTestProvider() {
514 if ( $this->file
=== false ) {
515 global $wgParserTestFiles;
516 $this->file
= $wgParserTestFiles[0];
518 return new TestFileIterator( $this->file
, $this );
522 * Set the file from whose tests will be run by this instance
524 public function setParserTestFile( $filename ) {
525 $this->file
= $filename;
530 * @dataProvider parserTestProvider
532 public function testParserTest( $desc, $input, $result, $opts, $config ) {
533 if ( $this->regex
!= '' && !preg_match( '/' . $this->regex
. '/', $desc ) ) {
534 $this->assertTrue( true ); // XXX: don't flood output with "test made no assertions"
535 //$this->markTestSkipped( 'Filtered out by the user' );
539 if ( !$this->isWikitextNS( NS_MAIN
) ) {
540 // parser tests frequently assume that the main namespace contains wikitext.
541 // @todo: When setting up pages, force the content model. Only skip if
542 // $wgtContentModelUseDB is false.
543 $this->markTestSkipped( "Main namespace does not support wikitext,"
544 . "skipping parser test: $desc" );
547 wfDebug( "Running parser test: $desc\n" );
549 $opts = $this->parseOptions( $opts );
550 $context = $this->setupGlobals( $opts, $config );
552 $user = $context->getUser();
553 $options = ParserOptions
::newFromContext( $context );
555 if ( isset( $opts['title'] ) ) {
556 $titleText = $opts['title'];
558 $titleText = 'Parser test';
561 $local = isset( $opts['local'] );
562 $preprocessor = isset( $opts['preprocessor'] ) ?
$opts['preprocessor'] : null;
563 $parser = $this->getParser( $preprocessor );
565 $title = Title
::newFromText( $titleText );
567 if ( isset( $opts['pst'] ) ) {
568 $out = $parser->preSaveTransform( $input, $title, $user, $options );
569 } elseif ( isset( $opts['msg'] ) ) {
570 $out = $parser->transformMsg( $input, $options, $title );
571 } elseif ( isset( $opts['section'] ) ) {
572 $section = $opts['section'];
573 $out = $parser->getSection( $input, $section );
574 } elseif ( isset( $opts['replace'] ) ) {
575 $section = $opts['replace'][0];
576 $replace = $opts['replace'][1];
577 $out = $parser->replaceSection( $input, $section, $replace );
578 } elseif ( isset( $opts['comment'] ) ) {
579 $out = Linker
::formatComment( $input, $title, $local );
580 } elseif ( isset( $opts['preload'] ) ) {
581 $out = $parser->getpreloadText( $input, $title, $options );
583 $output = $parser->parse( $input, $title, $options, true, true, 1337 );
584 $out = $output->getText();
586 if ( isset( $opts['showtitle'] ) ) {
587 if ( $output->getTitleText() ) {
588 $title = $output->getTitleText();
591 $out = "$title\n$out";
594 if ( isset( $opts['ill'] ) ) {
595 $out = $this->tidy( implode( ' ', $output->getLanguageLinks() ) );
596 } elseif ( isset( $opts['cat'] ) ) {
597 $outputPage = $context->getOutput();
598 $outputPage->addCategoryLinks( $output->getCategories() );
599 $cats = $outputPage->getCategoryLinks();
601 if ( isset( $cats['normal'] ) ) {
602 $out = $this->tidy( implode( ' ', $cats['normal'] ) );
607 $parser->mPreprocessor
= null;
609 $result = $this->tidy( $result );
612 $this->teardownGlobals();
614 $this->assertEquals( $result, $out, $desc );
618 * Run a fuzz test series
619 * Draw input from a set of test files
621 * @todo fixme Needs some work to not eat memory until the world explodes
625 function testFuzzTests() {
626 global $wgParserTestFiles;
628 $files = $wgParserTestFiles;
630 if ( $this->getCliArg( 'file=' ) ) {
631 $files = array( $this->getCliArg( 'file=' ) );
634 $dict = $this->getFuzzInput( $files );
635 $dictSize = strlen( $dict );
636 $logMaxLength = log( $this->maxFuzzTestLength
);
638 ini_set( 'memory_limit', $this->memoryLimit
* 1048576 );
641 $opts = ParserOptions
::newFromUser( $user );
642 $title = Title
::makeTitle( NS_MAIN
, 'Parser_test' );
648 // Generate test input
649 mt_srand( ++
$this->fuzzSeed
);
650 $totalLength = mt_rand( 1, $this->maxFuzzTestLength
);
653 while ( strlen( $input ) < $totalLength ) {
654 $logHairLength = mt_rand( 0, 1000000 ) / 1000000 * $logMaxLength;
655 $hairLength = min( intval( exp( $logHairLength ) ), $dictSize );
656 $offset = mt_rand( 0, $dictSize - $hairLength );
657 $input .= substr( $dict, $offset, $hairLength );
660 $this->setupGlobals();
661 $parser = $this->getParser();
665 $parser->parse( $input, $title, $opts );
666 $this->assertTrue( true, "Test $id, fuzz seed {$this->fuzzSeed}" );
667 } catch ( Exception
$exception ) {
668 $input_dump = sprintf( "string(%d) \"%s\"\n", strlen( $input ), $input );
670 $this->assertTrue( false, "Test $id, fuzz seed {$this->fuzzSeed}. \n\nInput: $input_dump\n\nError: {$exception->getMessage()}\n\nBacktrace: {$exception->getTraceAsString()}" );
673 $this->teardownGlobals();
674 $parser->__destruct();
676 if ( $id %
100 == 0 ) {
677 $usage = intval( memory_get_usage( true ) / $this->memoryLimit
/ 1048576 * 100 );
678 //echo "{$this->fuzzSeed}: $numSuccess/$numTotal (mem: $usage%)\n";
680 $ret = "Out of memory:\n";
681 $memStats = $this->getMemoryBreakdown();
683 foreach ( $memStats as $name => $usage ) {
684 $ret .= "$name: $usage\n";
687 throw new MWException( $ret );
696 //Various getter functions
699 * Get an input dictionary from a set of parser test files
701 function getFuzzInput( $filenames ) {
704 foreach ( $filenames as $filename ) {
705 $contents = file_get_contents( $filename );
706 preg_match_all( '/!!\s*input\n(.*?)\n!!\s*result/s', $contents, $matches );
708 foreach ( $matches[1] as $match ) {
709 $dict .= $match . "\n";
717 * Get a memory usage breakdown
719 function getMemoryBreakdown() {
722 foreach ( $GLOBALS as $name => $value ) {
723 $memStats['$' . $name] = strlen( serialize( $value ) );
726 $classes = get_declared_classes();
728 foreach ( $classes as $class ) {
729 $rc = new ReflectionClass( $class );
730 $props = $rc->getStaticProperties();
731 $memStats[$class] = strlen( serialize( $props ) );
732 $methods = $rc->getMethods();
734 foreach ( $methods as $method ) {
735 $memStats[$class] +
= strlen( serialize( $method->getStaticVariables() ) );
739 $functions = get_defined_functions();
741 foreach ( $functions['user'] as $function ) {
742 $rf = new ReflectionFunction( $function );
743 $memStats["$function()"] = strlen( serialize( $rf->getStaticVariables() ) );
752 * Get a Parser object
754 function getParser( $preprocessor = null ) {
755 global $wgParserConf;
757 $class = $wgParserConf['class'];
758 $parser = new $class( array( 'preprocessorClass' => $preprocessor ) +
$wgParserConf );
760 wfRunHooks( 'ParserTestParser', array( &$parser ) );
765 //Various action functions
767 public function addArticle( $name, $text, $line ) {
768 self
::$articles[$name] = array( $text, $line );
771 public function publishTestArticles() {
772 if ( empty( self
::$articles ) ) {
776 foreach ( self
::$articles as $name => $info ) {
777 list( $text, $line ) = $info;
778 ParserTest
::addArticle( $name, $text, $line, 'ignoreduplicate' );
783 * Steal a callback function from the primary parser, save it for
784 * application to our scary parser. If the hook is not installed,
785 * abort processing of this file.
787 * @param $name String
788 * @return Bool true if tag hook is present
790 public function requireHook( $name ) {
792 $wgParser->firstCallInit(); // make sure hooks are loaded.
793 return isset( $wgParser->mTagHooks
[$name] );
796 public function requireFunctionHook( $name ) {
798 $wgParser->firstCallInit(); // make sure hooks are loaded.
799 return isset( $wgParser->mFunctionHooks
[$name] );
802 //Various "cleanup" functions
805 * Run the "tidy" command on text if the $wgUseTidy
808 * @param $text String: the text to tidy
811 protected function tidy( $text ) {
815 $text = MWTidy
::tidy( $text );
822 * Remove last character if it is a newline
824 public function removeEndingNewline( $s ) {
825 if ( substr( $s, -1 ) === "\n" ) {
826 return substr( $s, 0, -1 );
832 //Test options parser functions
834 protected function parseOptions( $instring ) {
840 // foo=bar,"baz quux"
864 \[\[[^]]*\]\] # Link target
872 if ( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER
) ) {
873 foreach ( $matches as $bits ) {
874 array_shift( $bits );
875 $key = strtolower( array_shift( $bits ) );
876 if ( count( $bits ) == 0 ) {
878 } elseif ( count( $bits ) == 1 ) {
879 $opts[$key] = $this->cleanupOption( array_shift( $bits ) );
882 $opts[$key] = array_map( array( $this, 'cleanupOption' ), $bits );
889 protected function cleanupOption( $opt ) {
890 if ( substr( $opt, 0, 1 ) == '"' ) {
891 return substr( $opt, 1, -1 );
894 if ( substr( $opt, 0, 2 ) == '[[' ) {
895 return substr( $opt, 2, -2 );
901 * Use a regex to find out the value of an option
902 * @param $key String: name of option val to retrieve
903 * @param $opts Options array to look in
904 * @param $default Mixed: default value returned if not found
906 protected static function getOptionValue( $key, $opts, $default ) {
907 $key = strtolower( $key );
909 if ( isset( $opts[$key] ) ) {