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' )
173 # Update certain things in site_stats
174 $this->db
->insert( 'site_stats',
175 array( 'ss_row_id' => 1, 'ss_images' => 2, 'ss_good_articles' => 1 ),
179 # Reinitialise the LocalisationCache to match the database state
180 Language
::getLocalisationCache()->unloadAll();
182 # Clear the message cache
183 MessageCache
::singleton()->clear();
185 $user = User
::newFromId( 0 );
186 LinkCache
::singleton()->clear(); # Avoids the odd failure at creating the nullRevision
188 # Upload DB table entries for files.
189 # We will upload the actual files later. Note that if anything causes LocalFile::load()
190 # to be triggered before then, it will break via maybeUpgrade() setting the fileExists
191 # member to false and storing it in cache.
192 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Foobar.jpg' ) );
193 if ( !$this->db
->selectField( 'image', '1', array( 'img_name' => $image->getName() ) ) ) {
194 $image->recordUpload2(
196 'Upload of some lame file',
203 'media_type' => MEDIATYPE_BITMAP
,
204 'mime' => 'image/jpeg',
205 'metadata' => serialize( array() ),
206 'sha1' => wfBaseConvert( '', 16, 36, 31 ),
207 'fileExists' => true ),
208 $this->db
->timestamp( '20010115123500' ), $user
212 # This image will be blacklisted in [[MediaWiki:Bad image list]]
213 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Bad.jpg' ) );
214 if ( !$this->db
->selectField( 'image', '1', array( 'img_name' => $image->getName() ) ) ) {
215 $image->recordUpload2(
224 'media_type' => MEDIATYPE_BITMAP
,
225 'mime' => 'image/jpeg',
226 'metadata' => serialize( array() ),
227 'sha1' => wfBaseConvert( '', 16, 36, 31 ),
228 'fileExists' => true ),
229 $this->db
->timestamp( '20010115123500' ), $user
237 //ParserTest setup/teardown functions
240 * Set up the global variables for a consistent environment for each test.
241 * Ideally this should replace the global configuration entirely.
243 protected function setupGlobals( $opts = '', $config = '' ) {
244 global $wgFileBackends;
245 # Find out values for some special options.
247 self
::getOptionValue( 'language', $opts, 'en' );
249 self
::getOptionValue( 'variant', $opts, false );
251 self
::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
252 $linkHolderBatchSize =
253 self
::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
255 $uploadDir = $this->getUploadDir();
256 if ( $this->getCliArg( 'use-filebackend=' ) ) {
257 if ( self
::$backendToUse ) {
258 $backend = self
::$backendToUse;
260 $name = $this->getCliArg( 'use-filebackend=' );
261 $useConfig = array();
262 foreach ( $wgFileBackends as $conf ) {
263 if ( $conf['name'] == $name ) {
267 $useConfig['name'] = 'local-backend'; // swap name
268 $class = $conf['class'];
269 self
::$backendToUse = new $class( $useConfig );
270 $backend = self
::$backendToUse;
273 $backend = new FSFileBackend( array(
274 'name' => 'local-backend',
275 'lockManager' => 'nullLockManager',
276 'containerPaths' => array(
277 'local-public' => "$uploadDir",
278 'local-thumb' => "$uploadDir/thumb",
284 'wgServer' => 'http://Britney-Spears',
285 'wgScript' => '/index.php',
286 'wgScriptPath' => '/',
287 'wgArticlePath' => '/wiki/$1',
288 'wgExtensionAssetsPath' => '/extensions',
289 'wgActionPaths' => array(),
290 'wgLocalFileRepo' => array(
291 'class' => 'LocalRepo',
293 'url' => 'http://example.com/images',
295 'transformVia404' => false,
296 'backend' => $backend
298 'wgEnableUploads' => self
::getOptionValue( 'wgEnableUploads', $opts, true ),
299 'wgStylePath' => '/skins',
300 'wgStyleSheetPath' => '/skins',
301 'wgSitename' => 'MediaWiki',
302 'wgLanguageCode' => $lang,
303 'wgDBprefix' => $this->db
->getType() != 'oracle' ?
'unittest_' : 'ut_',
304 'wgRawHtml' => isset( $opts['rawhtml'] ),
306 'wgContLang' => null,
307 'wgNamespacesWithSubpages' => array( 0 => isset( $opts['subpage'] ) ),
308 'wgMaxTocLevel' => $maxtoclevel,
309 'wgCapitalLinks' => true,
310 'wgNoFollowLinks' => true,
311 'wgNoFollowDomainExceptions' => array(),
312 'wgThumbnailScriptPath' => false,
313 'wgUseImageResize' => true,
314 'wgUseTeX' => isset( $opts['math'] ),
315 'wgMathDirectory' => $uploadDir . '/math',
316 'wgLocaltimezone' => 'UTC',
317 'wgAllowExternalImages' => true,
318 'wgUseTidy' => false,
319 'wgDefaultLanguageVariant' => $variant,
320 'wgVariantArticlePath' => false,
321 'wgGroupPermissions' => array( '*' => array(
322 'createaccount' => true,
325 'createpage' => true,
326 'createtalk' => true,
328 'wgNamespaceProtection' => array( NS_MEDIAWIKI
=> 'editinterface' ),
329 'wgDefaultExternalStore' => array(),
330 'wgForeignFileRepos' => array(),
331 'wgLinkHolderBatchSize' => $linkHolderBatchSize,
332 'wgExperimentalHtmlIds' => false,
333 'wgExternalLinkTarget' => false,
334 'wgAlwaysUseTidy' => false,
336 'wgWellFormedXml' => true,
337 'wgAllowMicrodataAttributes' => true,
338 'wgAdaptiveMessageCache' => true,
339 'wgUseDatabaseMessages' => true,
343 $configLines = explode( "\n", $config );
345 foreach ( $configLines as $line ) {
346 list( $var, $value ) = explode( '=', $line, 2 );
348 $settings[$var] = eval( "return $value;" ); //???
352 $this->savedGlobals
= array();
355 wfRunHooks( 'ParserTestGlobals', array( &$settings ) );
357 foreach ( $settings as $var => $val ) {
358 if ( array_key_exists( $var, $GLOBALS ) ) {
359 $this->savedGlobals
[$var] = $GLOBALS[$var];
362 $GLOBALS[$var] = $val;
365 $langObj = Language
::factory( $lang );
366 $GLOBALS['wgContLang'] = $langObj;
367 $context = new RequestContext();
368 $GLOBALS['wgLang'] = $context->getLanguage();
370 $GLOBALS['wgMemc'] = new EmptyBagOStuff
;
371 $GLOBALS['wgOut'] = $context->getOutput();
372 $GLOBALS['wgUser'] = $context->getUser();
376 $wgHooks['ParserTestParser'][] = 'ParserTestParserHook::setup';
377 $wgHooks['ParserGetVariableValueTs'][] = 'ParserTest::getFakeTimestamp';
379 MagicWord
::clearCache();
380 RepoGroup
::destroySingleton();
381 FileBackendGroup
::destroySingleton();
383 # Create dummy files in storage
384 $this->setupUploads();
386 # Publish the articles after we have the final language set
387 $this->publishTestArticles();
389 # The entries saved into RepoGroup cache with previous globals will be wrong.
390 RepoGroup
::destroySingleton();
391 FileBackendGroup
::destroySingleton();
392 MessageCache
::destroyInstance();
398 * Get an FS upload directory (only applies to FSFileBackend)
400 * @return String: the directory
402 protected function getUploadDir() {
403 if ( $this->keepUploads
) {
404 $dir = wfTempDir() . '/mwParser-images';
406 if ( is_dir( $dir ) ) {
410 $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
413 // wfDebug( "Creating upload directory $dir\n" );
414 if ( file_exists( $dir ) ) {
415 wfDebug( "Already exists!\n" );
423 * Create a dummy uploads directory which will contain a couple
424 * of files in order to pass existence tests.
426 * @return String: the directory
428 protected function setupUploads() {
431 $base = $this->getBaseDir();
432 $backend = RepoGroup
::singleton()->getLocalRepo()->getBackend();
433 $backend->prepare( array( 'dir' => "$base/local-public/3/3a" ) );
434 $backend->store( array(
435 'src' => "$IP/skins/monobook/headbg.jpg", 'dst' => "$base/local-public/3/3a/Foobar.jpg"
437 $backend->prepare( array( 'dir' => "$base/local-public/0/09" ) );
438 $backend->store( array(
439 'src' => "$IP/skins/monobook/headbg.jpg", 'dst' => "$base/local-public/0/09/Bad.jpg"
444 * Restore default values and perform any necessary clean-up
445 * after each test runs.
447 protected function teardownGlobals() {
448 $this->teardownUploads();
450 foreach ( $this->savedGlobals
as $var => $val ) {
451 $GLOBALS[$var] = $val;
454 RepoGroup
::destroySingleton();
455 LinkCache
::singleton()->clear();
459 * Remove the dummy uploads directory
461 private function teardownUploads() {
462 if ( $this->keepUploads
) {
466 $base = $this->getBaseDir();
467 // delete the files first, then the dirs.
470 "$base/local-public/3/3a/Foobar.jpg",
471 "$base/local-thumb/3/3a/Foobar.jpg/180px-Foobar.jpg",
472 "$base/local-thumb/3/3a/Foobar.jpg/200px-Foobar.jpg",
473 "$base/local-thumb/3/3a/Foobar.jpg/640px-Foobar.jpg",
474 "$base/local-thumb/3/3a/Foobar.jpg/120px-Foobar.jpg",
475 "$base/local-thumb/3/3a/Foobar.jpg/1280px-Foobar.jpg",
476 "$base/local-thumb/3/3a/Foobar.jpg/20px-Foobar.jpg",
477 "$base/local-thumb/3/3a/Foobar.jpg/270px-Foobar.jpg",
478 "$base/local-thumb/3/3a/Foobar.jpg/300px-Foobar.jpg",
479 "$base/local-thumb/3/3a/Foobar.jpg/30px-Foobar.jpg",
480 "$base/local-thumb/3/3a/Foobar.jpg/360px-Foobar.jpg",
481 "$base/local-thumb/3/3a/Foobar.jpg/400px-Foobar.jpg",
482 "$base/local-thumb/3/3a/Foobar.jpg/40px-Foobar.jpg",
483 "$base/local-thumb/3/3a/Foobar.jpg/70px-Foobar.jpg",
484 "$base/local-thumb/3/3a/Foobar.jpg/960px-Foobar.jpg",
486 "$base/local-public/0/09/Bad.jpg",
487 "$base/local-thumb/0/09/Bad.jpg",
489 "$base/local-public/math/f/a/5/fa50b8b616463173474302ca3e63586b.png",
495 * Delete the specified files, if they exist.
496 * @param $files Array: full paths to files to delete.
498 private static function deleteFiles( $files ) {
499 $backend = RepoGroup
::singleton()->getLocalRepo()->getBackend();
500 foreach ( $files as $file ) {
501 $backend->delete( array( 'src' => $file ), array( 'force' => 1 ) );
503 foreach ( $files as $file ) {
505 while ( $tmp = FileBackend
::parentStoragePath( $tmp ) ) {
506 if ( !$backend->clean( array( 'dir' => $tmp ) )->isOK() ) {
513 protected function getBaseDir() {
514 return 'mwstore://local-backend';
517 public function parserTestProvider() {
518 if ( $this->file
=== false ) {
519 global $wgParserTestFiles;
520 $this->file
= $wgParserTestFiles[0];
522 return new TestFileIterator( $this->file
, $this );
526 * Set the file from whose tests will be run by this instance
528 public function setParserTestFile( $filename ) {
529 $this->file
= $filename;
534 * @dataProvider parserTestProvider
536 public function testParserTest( $desc, $input, $result, $opts, $config ) {
537 if ( $this->regex
!= '' && !preg_match( '/' . $this->regex
. '/', $desc ) ) {
538 $this->assertTrue( true ); // XXX: don't flood output with "test made no assertions"
539 //$this->markTestSkipped( 'Filtered out by the user' );
543 if ( !$this->isWikitextNS( NS_MAIN
) ) {
544 // parser tests frequently assume that the main namespace contains wikitext.
545 // @todo: When setting up pages, force the content model. Only skip if
546 // $wgtContentModelUseDB is false.
547 $this->markTestSkipped( "Main namespace does not support wikitext,"
548 . "skipping parser test: $desc" );
551 wfDebug( "Running parser test: $desc\n" );
553 $opts = $this->parseOptions( $opts );
554 $context = $this->setupGlobals( $opts, $config );
556 $user = $context->getUser();
557 $options = ParserOptions
::newFromContext( $context );
559 if ( isset( $opts['title'] ) ) {
560 $titleText = $opts['title'];
563 $titleText = 'Parser test';
566 $local = isset( $opts['local'] );
567 $preprocessor = isset( $opts['preprocessor'] ) ?
$opts['preprocessor'] : null;
568 $parser = $this->getParser( $preprocessor );
570 $title = Title
::newFromText( $titleText );
572 if ( isset( $opts['pst'] ) ) {
573 $out = $parser->preSaveTransform( $input, $title, $user, $options );
574 } elseif ( isset( $opts['msg'] ) ) {
575 $out = $parser->transformMsg( $input, $options, $title );
576 } elseif ( isset( $opts['section'] ) ) {
577 $section = $opts['section'];
578 $out = $parser->getSection( $input, $section );
579 } elseif ( isset( $opts['replace'] ) ) {
580 $section = $opts['replace'][0];
581 $replace = $opts['replace'][1];
582 $out = $parser->replaceSection( $input, $section, $replace );
583 } elseif ( isset( $opts['comment'] ) ) {
584 $out = Linker
::formatComment( $input, $title, $local );
585 } elseif ( isset( $opts['preload'] ) ) {
586 $out = $parser->getpreloadText( $input, $title, $options );
588 $output = $parser->parse( $input, $title, $options, true, true, 1337 );
589 $out = $output->getText();
591 if ( isset( $opts['showtitle'] ) ) {
592 if ( $output->getTitleText() ) {
593 $title = $output->getTitleText();
596 $out = "$title\n$out";
599 if ( isset( $opts['ill'] ) ) {
600 $out = $this->tidy( implode( ' ', $output->getLanguageLinks() ) );
601 } elseif ( isset( $opts['cat'] ) ) {
602 $outputPage = $context->getOutput();
603 $outputPage->addCategoryLinks( $output->getCategories() );
604 $cats = $outputPage->getCategoryLinks();
606 if ( isset( $cats['normal'] ) ) {
607 $out = $this->tidy( implode( ' ', $cats['normal'] ) );
612 $parser->mPreprocessor
= null;
614 $result = $this->tidy( $result );
617 $this->teardownGlobals();
619 $this->assertEquals( $result, $out, $desc );
623 * Run a fuzz test series
624 * Draw input from a set of test files
626 * @todo fixme Needs some work to not eat memory until the world explodes
630 function testFuzzTests() {
631 global $wgParserTestFiles;
633 $files = $wgParserTestFiles;
635 if( $this->getCliArg( 'file=' ) ) {
636 $files = array( $this->getCliArg( 'file=' ) );
639 $dict = $this->getFuzzInput( $files );
640 $dictSize = strlen( $dict );
641 $logMaxLength = log( $this->maxFuzzTestLength
);
643 ini_set( 'memory_limit', $this->memoryLimit
* 1048576 );
646 $opts = ParserOptions
::newFromUser( $user );
647 $title = Title
::makeTitle( NS_MAIN
, 'Parser_test' );
653 // Generate test input
654 mt_srand( ++
$this->fuzzSeed
);
655 $totalLength = mt_rand( 1, $this->maxFuzzTestLength
);
658 while ( strlen( $input ) < $totalLength ) {
659 $logHairLength = mt_rand( 0, 1000000 ) / 1000000 * $logMaxLength;
660 $hairLength = min( intval( exp( $logHairLength ) ), $dictSize );
661 $offset = mt_rand( 0, $dictSize - $hairLength );
662 $input .= substr( $dict, $offset, $hairLength );
665 $this->setupGlobals();
666 $parser = $this->getParser();
670 $parser->parse( $input, $title, $opts );
671 $this->assertTrue( true, "Test $id, fuzz seed {$this->fuzzSeed}" );
672 } catch ( Exception
$exception ) {
673 $input_dump = sprintf( "string(%d) \"%s\"\n", strlen( $input ), $input );
675 $this->assertTrue( false, "Test $id, fuzz seed {$this->fuzzSeed}. \n\nInput: $input_dump\n\nError: {$exception->getMessage()}\n\nBacktrace: {$exception->getTraceAsString()}" );
678 $this->teardownGlobals();
679 $parser->__destruct();
681 if ( $id %
100 == 0 ) {
682 $usage = intval( memory_get_usage( true ) / $this->memoryLimit
/ 1048576 * 100 );
683 //echo "{$this->fuzzSeed}: $numSuccess/$numTotal (mem: $usage%)\n";
685 $ret = "Out of memory:\n";
686 $memStats = $this->getMemoryBreakdown();
688 foreach ( $memStats as $name => $usage ) {
689 $ret .= "$name: $usage\n";
692 throw new MWException( $ret );
701 //Various getter functions
704 * Get an input dictionary from a set of parser test files
706 function getFuzzInput( $filenames ) {
709 foreach ( $filenames as $filename ) {
710 $contents = file_get_contents( $filename );
711 preg_match_all( '/!!\s*input\n(.*?)\n!!\s*result/s', $contents, $matches );
713 foreach ( $matches[1] as $match ) {
714 $dict .= $match . "\n";
722 * Get a memory usage breakdown
724 function getMemoryBreakdown() {
727 foreach ( $GLOBALS as $name => $value ) {
728 $memStats['$' . $name] = strlen( serialize( $value ) );
731 $classes = get_declared_classes();
733 foreach ( $classes as $class ) {
734 $rc = new ReflectionClass( $class );
735 $props = $rc->getStaticProperties();
736 $memStats[$class] = strlen( serialize( $props ) );
737 $methods = $rc->getMethods();
739 foreach ( $methods as $method ) {
740 $memStats[$class] +
= strlen( serialize( $method->getStaticVariables() ) );
744 $functions = get_defined_functions();
746 foreach ( $functions['user'] as $function ) {
747 $rf = new ReflectionFunction( $function );
748 $memStats["$function()"] = strlen( serialize( $rf->getStaticVariables() ) );
757 * Get a Parser object
759 function getParser( $preprocessor = null ) {
760 global $wgParserConf;
762 $class = $wgParserConf['class'];
763 $parser = new $class( array( 'preprocessorClass' => $preprocessor ) +
$wgParserConf );
765 wfRunHooks( 'ParserTestParser', array( &$parser ) );
770 //Various action functions
772 public function addArticle( $name, $text, $line ) {
773 self
::$articles[$name] = array( $text, $line );
776 public function publishTestArticles() {
777 if ( empty( self
::$articles ) ) {
781 foreach ( self
::$articles as $name => $info ) {
782 list( $text, $line ) = $info;
783 ParserTest
::addArticle( $name, $text, $line, 'ignoreduplicate' );
788 * Steal a callback function from the primary parser, save it for
789 * application to our scary parser. If the hook is not installed,
790 * abort processing of this file.
792 * @param $name String
793 * @return Bool true if tag hook is present
795 public function requireHook( $name ) {
797 $wgParser->firstCallInit( ); // make sure hooks are loaded.
798 return isset( $wgParser->mTagHooks
[$name] );
801 public function requireFunctionHook( $name ) {
803 $wgParser->firstCallInit( ); // make sure hooks are loaded.
804 return isset( $wgParser->mFunctionHooks
[$name] );
806 //Various "cleanup" functions
809 * Run the "tidy" command on text if the $wgUseTidy
812 * @param $text String: the text to tidy
815 protected function tidy( $text ) {
819 $text = MWTidy
::tidy( $text );
826 * Remove last character if it is a newline
828 public function removeEndingNewline( $s ) {
829 if ( substr( $s, -1 ) === "\n" ) {
830 return substr( $s, 0, -1 );
837 //Test options parser functions
839 protected function parseOptions( $instring ) {
845 // foo=bar,"baz quux"
869 \[\[[^]]*\]\] # Link target
877 if ( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER
) ) {
878 foreach ( $matches as $bits ) {
879 array_shift( $bits );
880 $key = strtolower( array_shift( $bits ) );
881 if ( count( $bits ) == 0 ) {
883 } elseif ( count( $bits ) == 1 ) {
884 $opts[$key] = $this->cleanupOption( array_shift( $bits ) );
887 $opts[$key] = array_map( array( $this, 'cleanupOption' ), $bits );
894 protected function cleanupOption( $opt ) {
895 if ( substr( $opt, 0, 1 ) == '"' ) {
896 return substr( $opt, 1, -1 );
899 if ( substr( $opt, 0, 2 ) == '[[' ) {
900 return substr( $opt, 2, -2 );
906 * Use a regex to find out the value of an option
907 * @param $key String: name of option val to retrieve
908 * @param $opts Options array to look in
909 * @param $default Mixed: default value returned if not found
911 protected static function getOptionValue( $key, $opts, $default ) {
912 $key = strtolower( $key );
914 if ( isset( $opts[$key] ) ) {