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 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Foobar.jpg' ) );
191 if ( !$this->db
->selectField( 'image', '1', array( 'img_name' => $image->getName() ) ) ) {
192 $image->recordUpload2(
194 'Upload of some lame file',
201 'media_type' => MEDIATYPE_BITMAP
,
202 'mime' => 'image/jpeg',
203 'metadata' => serialize( array() ),
204 'sha1' => wfBaseConvert( '', 16, 36, 31 ),
205 'fileExists' => true ),
206 $this->db
->timestamp( '20010115123500' ), $user
210 # This image will be blacklisted in [[MediaWiki:Bad image list]]
211 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Bad.jpg' ) );
212 if ( !$this->db
->selectField( 'image', '1', array( 'img_name' => $image->getName() ) ) ) {
213 $image->recordUpload2(
222 'media_type' => MEDIATYPE_BITMAP
,
223 'mime' => 'image/jpeg',
224 'metadata' => serialize( array() ),
225 'sha1' => wfBaseConvert( '', 16, 36, 31 ),
226 'fileExists' => true ),
227 $this->db
->timestamp( '20010115123500' ), $user
232 //ParserTest setup/teardown functions
235 * Set up the global variables for a consistent environment for each test.
236 * Ideally this should replace the global configuration entirely.
238 protected function setupGlobals( $opts = array(), $config = '' ) {
239 global $wgFileBackends;
240 # Find out values for some special options.
242 self
::getOptionValue( 'language', $opts, 'en' );
244 self
::getOptionValue( 'variant', $opts, false );
246 self
::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
247 $linkHolderBatchSize =
248 self
::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
250 $uploadDir = $this->getUploadDir();
251 if ( $this->getCliArg( 'use-filebackend=' ) ) {
252 if ( self
::$backendToUse ) {
253 $backend = self
::$backendToUse;
255 $name = $this->getCliArg( 'use-filebackend=' );
256 $useConfig = array();
257 foreach ( $wgFileBackends as $conf ) {
258 if ( $conf['name'] == $name ) {
262 $useConfig['name'] = 'local-backend'; // swap name
263 $class = $conf['class'];
264 self
::$backendToUse = new $class( $useConfig );
265 $backend = self
::$backendToUse;
268 $backend = new FSFileBackend( array(
269 'name' => 'local-backend',
270 'lockManager' => 'nullLockManager',
271 'containerPaths' => array(
272 'local-public' => "$uploadDir",
273 'local-thumb' => "$uploadDir/thumb",
279 'wgServer' => 'http://example.org',
280 'wgScript' => '/index.php',
281 'wgScriptPath' => '/',
282 'wgArticlePath' => '/wiki/$1',
283 'wgExtensionAssetsPath' => '/extensions',
284 'wgActionPaths' => array(),
285 'wgLocalFileRepo' => array(
286 'class' => 'LocalRepo',
288 'url' => 'http://example.com/images',
290 'transformVia404' => false,
291 'backend' => $backend
293 'wgEnableUploads' => self
::getOptionValue( 'wgEnableUploads', $opts, true ),
294 'wgStylePath' => '/skins',
295 'wgStyleSheetPath' => '/skins',
296 'wgSitename' => 'MediaWiki',
297 'wgLanguageCode' => $lang,
298 'wgDBprefix' => $this->db
->getType() != 'oracle' ?
'unittest_' : 'ut_',
299 'wgRawHtml' => isset( $opts['rawhtml'] ),
301 'wgContLang' => null,
302 'wgNamespacesWithSubpages' => array( NS_MAIN
=> isset( $opts['subpage'] ) ),
303 'wgMaxTocLevel' => $maxtoclevel,
304 'wgCapitalLinks' => true,
305 'wgNoFollowLinks' => true,
306 'wgNoFollowDomainExceptions' => array(),
307 'wgThumbnailScriptPath' => false,
308 'wgUseImageResize' => true,
309 'wgUseTeX' => isset( $opts['math'] ),
310 'wgMathDirectory' => $uploadDir . '/math',
311 'wgLocaltimezone' => 'UTC',
312 'wgAllowExternalImages' => true,
313 'wgUseTidy' => false,
314 'wgDefaultLanguageVariant' => $variant,
315 'wgVariantArticlePath' => false,
316 'wgGroupPermissions' => array( '*' => array(
317 'createaccount' => true,
320 'createpage' => true,
321 'createtalk' => true,
323 'wgNamespaceProtection' => array( NS_MEDIAWIKI
=> 'editinterface' ),
324 'wgDefaultExternalStore' => array(),
325 'wgForeignFileRepos' => array(),
326 'wgLinkHolderBatchSize' => $linkHolderBatchSize,
327 'wgExperimentalHtmlIds' => false,
328 'wgExternalLinkTarget' => false,
329 'wgAlwaysUseTidy' => false,
331 'wgWellFormedXml' => true,
332 'wgAllowMicrodataAttributes' => true,
333 'wgAdaptiveMessageCache' => true,
334 'wgUseDatabaseMessages' => true,
338 $configLines = explode( "\n", $config );
340 foreach ( $configLines as $line ) {
341 list( $var, $value ) = explode( '=', $line, 2 );
343 $settings[$var] = eval( "return $value;" ); //???
347 $this->savedGlobals
= array();
350 wfRunHooks( 'ParserTestGlobals', array( &$settings ) );
352 foreach ( $settings as $var => $val ) {
353 if ( array_key_exists( $var, $GLOBALS ) ) {
354 $this->savedGlobals
[$var] = $GLOBALS[$var];
357 $GLOBALS[$var] = $val;
360 $langObj = Language
::factory( $lang );
361 $GLOBALS['wgContLang'] = $langObj;
362 $context = new RequestContext();
363 $GLOBALS['wgLang'] = $context->getLanguage();
365 $GLOBALS['wgMemc'] = new EmptyBagOStuff
;
366 $GLOBALS['wgOut'] = $context->getOutput();
367 $GLOBALS['wgUser'] = $context->getUser();
371 $wgHooks['ParserTestParser'][] = 'ParserTestParserHook::setup';
372 $wgHooks['ParserGetVariableValueTs'][] = 'ParserTest::getFakeTimestamp';
374 MagicWord
::clearCache();
375 RepoGroup
::destroySingleton();
376 FileBackendGroup
::destroySingleton();
378 # Create dummy files in storage
379 $this->setupUploads();
381 # Publish the articles after we have the final language set
382 $this->publishTestArticles();
384 # The entries saved into RepoGroup cache with previous globals will be wrong.
385 RepoGroup
::destroySingleton();
386 FileBackendGroup
::destroySingleton();
387 MessageCache
::destroyInstance();
393 * Get an FS upload directory (only applies to FSFileBackend)
395 * @return String: the directory
397 protected function getUploadDir() {
398 if ( $this->keepUploads
) {
399 $dir = wfTempDir() . '/mwParser-images';
401 if ( is_dir( $dir ) ) {
405 $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
408 // wfDebug( "Creating upload directory $dir\n" );
409 if ( file_exists( $dir ) ) {
410 wfDebug( "Already exists!\n" );
418 * Create a dummy uploads directory which will contain a couple
419 * of files in order to pass existence tests.
421 * @return String: the directory
423 protected function setupUploads() {
426 $base = $this->getBaseDir();
427 $backend = RepoGroup
::singleton()->getLocalRepo()->getBackend();
428 $backend->prepare( array( 'dir' => "$base/local-public/3/3a" ) );
429 $backend->store( array(
430 'src' => "$IP/skins/monobook/headbg.jpg", 'dst' => "$base/local-public/3/3a/Foobar.jpg"
432 $backend->prepare( array( 'dir' => "$base/local-public/0/09" ) );
433 $backend->store( array(
434 'src' => "$IP/skins/monobook/headbg.jpg", 'dst' => "$base/local-public/0/09/Bad.jpg"
439 * Restore default values and perform any necessary clean-up
440 * after each test runs.
442 protected function teardownGlobals() {
443 $this->teardownUploads();
445 foreach ( $this->savedGlobals
as $var => $val ) {
446 $GLOBALS[$var] = $val;
449 RepoGroup
::destroySingleton();
450 LinkCache
::singleton()->clear();
454 * Remove the dummy uploads directory
456 private function teardownUploads() {
457 if ( $this->keepUploads
) {
461 $base = $this->getBaseDir();
462 // delete the files first, then the dirs.
465 "$base/local-public/3/3a/Foobar.jpg",
466 "$base/local-thumb/3/3a/Foobar.jpg/180px-Foobar.jpg",
467 "$base/local-thumb/3/3a/Foobar.jpg/200px-Foobar.jpg",
468 "$base/local-thumb/3/3a/Foobar.jpg/640px-Foobar.jpg",
469 "$base/local-thumb/3/3a/Foobar.jpg/120px-Foobar.jpg",
470 "$base/local-thumb/3/3a/Foobar.jpg/1280px-Foobar.jpg",
471 "$base/local-thumb/3/3a/Foobar.jpg/20px-Foobar.jpg",
472 "$base/local-thumb/3/3a/Foobar.jpg/270px-Foobar.jpg",
473 "$base/local-thumb/3/3a/Foobar.jpg/300px-Foobar.jpg",
474 "$base/local-thumb/3/3a/Foobar.jpg/30px-Foobar.jpg",
475 "$base/local-thumb/3/3a/Foobar.jpg/360px-Foobar.jpg",
476 "$base/local-thumb/3/3a/Foobar.jpg/400px-Foobar.jpg",
477 "$base/local-thumb/3/3a/Foobar.jpg/40px-Foobar.jpg",
478 "$base/local-thumb/3/3a/Foobar.jpg/70px-Foobar.jpg",
479 "$base/local-thumb/3/3a/Foobar.jpg/960px-Foobar.jpg",
481 "$base/local-public/0/09/Bad.jpg",
482 "$base/local-thumb/0/09/Bad.jpg",
484 "$base/local-public/math/f/a/5/fa50b8b616463173474302ca3e63586b.png",
490 * Delete the specified files, if they exist.
491 * @param $files Array: full paths to files to delete.
493 private static function deleteFiles( $files ) {
494 $backend = RepoGroup
::singleton()->getLocalRepo()->getBackend();
495 foreach ( $files as $file ) {
496 $backend->delete( array( 'src' => $file ), array( 'force' => 1 ) );
498 foreach ( $files as $file ) {
500 while ( $tmp = FileBackend
::parentStoragePath( $tmp ) ) {
501 if ( !$backend->clean( array( 'dir' => $tmp ) )->isOK() ) {
508 protected function getBaseDir() {
509 return 'mwstore://local-backend';
512 public function parserTestProvider() {
513 if ( $this->file
=== false ) {
514 global $wgParserTestFiles;
515 $this->file
= $wgParserTestFiles[0];
517 return new TestFileIterator( $this->file
, $this );
521 * Set the file from whose tests will be run by this instance
523 public function setParserTestFile( $filename ) {
524 $this->file
= $filename;
529 * @dataProvider parserTestProvider
531 public function testParserTest( $desc, $input, $result, $opts, $config ) {
532 if ( $this->regex
!= '' && !preg_match( '/' . $this->regex
. '/', $desc ) ) {
533 $this->assertTrue( true ); // XXX: don't flood output with "test made no assertions"
534 //$this->markTestSkipped( 'Filtered out by the user' );
538 if ( !$this->isWikitextNS( NS_MAIN
) ) {
539 // parser tests frequently assume that the main namespace contains wikitext.
540 // @todo: When setting up pages, force the content model. Only skip if
541 // $wgtContentModelUseDB is false.
542 $this->markTestSkipped( "Main namespace does not support wikitext,"
543 . "skipping parser test: $desc" );
546 wfDebug( "Running parser test: $desc\n" );
548 $opts = $this->parseOptions( $opts );
549 $context = $this->setupGlobals( $opts, $config );
551 $user = $context->getUser();
552 $options = ParserOptions
::newFromContext( $context );
554 if ( isset( $opts['title'] ) ) {
555 $titleText = $opts['title'];
557 $titleText = 'Parser test';
560 $local = isset( $opts['local'] );
561 $preprocessor = isset( $opts['preprocessor'] ) ?
$opts['preprocessor'] : null;
562 $parser = $this->getParser( $preprocessor );
564 $title = Title
::newFromText( $titleText );
566 if ( isset( $opts['pst'] ) ) {
567 $out = $parser->preSaveTransform( $input, $title, $user, $options );
568 } elseif ( isset( $opts['msg'] ) ) {
569 $out = $parser->transformMsg( $input, $options, $title );
570 } elseif ( isset( $opts['section'] ) ) {
571 $section = $opts['section'];
572 $out = $parser->getSection( $input, $section );
573 } elseif ( isset( $opts['replace'] ) ) {
574 $section = $opts['replace'][0];
575 $replace = $opts['replace'][1];
576 $out = $parser->replaceSection( $input, $section, $replace );
577 } elseif ( isset( $opts['comment'] ) ) {
578 $out = Linker
::formatComment( $input, $title, $local );
579 } elseif ( isset( $opts['preload'] ) ) {
580 $out = $parser->getpreloadText( $input, $title, $options );
582 $output = $parser->parse( $input, $title, $options, true, true, 1337 );
583 $out = $output->getText();
585 if ( isset( $opts['showtitle'] ) ) {
586 if ( $output->getTitleText() ) {
587 $title = $output->getTitleText();
590 $out = "$title\n$out";
593 if ( isset( $opts['ill'] ) ) {
594 $out = $this->tidy( implode( ' ', $output->getLanguageLinks() ) );
595 } elseif ( isset( $opts['cat'] ) ) {
596 $outputPage = $context->getOutput();
597 $outputPage->addCategoryLinks( $output->getCategories() );
598 $cats = $outputPage->getCategoryLinks();
600 if ( isset( $cats['normal'] ) ) {
601 $out = $this->tidy( implode( ' ', $cats['normal'] ) );
606 $parser->mPreprocessor
= null;
608 $result = $this->tidy( $result );
611 $this->teardownGlobals();
613 $this->assertEquals( $result, $out, $desc );
617 * Run a fuzz test series
618 * Draw input from a set of test files
620 * @todo fixme Needs some work to not eat memory until the world explodes
624 function testFuzzTests() {
625 global $wgParserTestFiles;
627 $files = $wgParserTestFiles;
629 if ( $this->getCliArg( 'file=' ) ) {
630 $files = array( $this->getCliArg( 'file=' ) );
633 $dict = $this->getFuzzInput( $files );
634 $dictSize = strlen( $dict );
635 $logMaxLength = log( $this->maxFuzzTestLength
);
637 ini_set( 'memory_limit', $this->memoryLimit
* 1048576 );
640 $opts = ParserOptions
::newFromUser( $user );
641 $title = Title
::makeTitle( NS_MAIN
, 'Parser_test' );
647 // Generate test input
648 mt_srand( ++
$this->fuzzSeed
);
649 $totalLength = mt_rand( 1, $this->maxFuzzTestLength
);
652 while ( strlen( $input ) < $totalLength ) {
653 $logHairLength = mt_rand( 0, 1000000 ) / 1000000 * $logMaxLength;
654 $hairLength = min( intval( exp( $logHairLength ) ), $dictSize );
655 $offset = mt_rand( 0, $dictSize - $hairLength );
656 $input .= substr( $dict, $offset, $hairLength );
659 $this->setupGlobals();
660 $parser = $this->getParser();
664 $parser->parse( $input, $title, $opts );
665 $this->assertTrue( true, "Test $id, fuzz seed {$this->fuzzSeed}" );
666 } catch ( Exception
$exception ) {
667 $input_dump = sprintf( "string(%d) \"%s\"\n", strlen( $input ), $input );
669 $this->assertTrue( false, "Test $id, fuzz seed {$this->fuzzSeed}. \n\nInput: $input_dump\n\nError: {$exception->getMessage()}\n\nBacktrace: {$exception->getTraceAsString()}" );
672 $this->teardownGlobals();
673 $parser->__destruct();
675 if ( $id %
100 == 0 ) {
676 $usage = intval( memory_get_usage( true ) / $this->memoryLimit
/ 1048576 * 100 );
677 //echo "{$this->fuzzSeed}: $numSuccess/$numTotal (mem: $usage%)\n";
679 $ret = "Out of memory:\n";
680 $memStats = $this->getMemoryBreakdown();
682 foreach ( $memStats as $name => $usage ) {
683 $ret .= "$name: $usage\n";
686 throw new MWException( $ret );
695 //Various getter functions
698 * Get an input dictionary from a set of parser test files
700 function getFuzzInput( $filenames ) {
703 foreach ( $filenames as $filename ) {
704 $contents = file_get_contents( $filename );
705 preg_match_all( '/!!\s*input\n(.*?)\n!!\s*result/s', $contents, $matches );
707 foreach ( $matches[1] as $match ) {
708 $dict .= $match . "\n";
716 * Get a memory usage breakdown
718 function getMemoryBreakdown() {
721 foreach ( $GLOBALS as $name => $value ) {
722 $memStats['$' . $name] = strlen( serialize( $value ) );
725 $classes = get_declared_classes();
727 foreach ( $classes as $class ) {
728 $rc = new ReflectionClass( $class );
729 $props = $rc->getStaticProperties();
730 $memStats[$class] = strlen( serialize( $props ) );
731 $methods = $rc->getMethods();
733 foreach ( $methods as $method ) {
734 $memStats[$class] +
= strlen( serialize( $method->getStaticVariables() ) );
738 $functions = get_defined_functions();
740 foreach ( $functions['user'] as $function ) {
741 $rf = new ReflectionFunction( $function );
742 $memStats["$function()"] = strlen( serialize( $rf->getStaticVariables() ) );
751 * Get a Parser object
753 function getParser( $preprocessor = null ) {
754 global $wgParserConf;
756 $class = $wgParserConf['class'];
757 $parser = new $class( array( 'preprocessorClass' => $preprocessor ) +
$wgParserConf );
759 wfRunHooks( 'ParserTestParser', array( &$parser ) );
764 //Various action functions
766 public function addArticle( $name, $text, $line ) {
767 self
::$articles[$name] = array( $text, $line );
770 public function publishTestArticles() {
771 if ( empty( self
::$articles ) ) {
775 foreach ( self
::$articles as $name => $info ) {
776 list( $text, $line ) = $info;
777 ParserTest
::addArticle( $name, $text, $line, 'ignoreduplicate' );
782 * Steal a callback function from the primary parser, save it for
783 * application to our scary parser. If the hook is not installed,
784 * abort processing of this file.
786 * @param $name String
787 * @return Bool true if tag hook is present
789 public function requireHook( $name ) {
791 $wgParser->firstCallInit(); // make sure hooks are loaded.
792 return isset( $wgParser->mTagHooks
[$name] );
795 public function requireFunctionHook( $name ) {
797 $wgParser->firstCallInit(); // make sure hooks are loaded.
798 return isset( $wgParser->mFunctionHooks
[$name] );
801 //Various "cleanup" functions
804 * Run the "tidy" command on text if the $wgUseTidy
807 * @param $text String: the text to tidy
810 protected function tidy( $text ) {
814 $text = MWTidy
::tidy( $text );
821 * Remove last character if it is a newline
823 public function removeEndingNewline( $s ) {
824 if ( substr( $s, -1 ) === "\n" ) {
825 return substr( $s, 0, -1 );
831 //Test options parser functions
833 protected function parseOptions( $instring ) {
839 // foo=bar,"baz quux"
863 \[\[[^]]*\]\] # Link target
871 if ( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER
) ) {
872 foreach ( $matches as $bits ) {
873 array_shift( $bits );
874 $key = strtolower( array_shift( $bits ) );
875 if ( count( $bits ) == 0 ) {
877 } elseif ( count( $bits ) == 1 ) {
878 $opts[$key] = $this->cleanupOption( array_shift( $bits ) );
881 $opts[$key] = array_map( array( $this, 'cleanupOption' ), $bits );
888 protected function cleanupOption( $opt ) {
889 if ( substr( $opt, 0, 1 ) == '"' ) {
890 return substr( $opt, 1, -1 );
893 if ( substr( $opt, 0, 2 ) == '[[' ) {
894 return substr( $opt, 2, -2 );
900 * Use a regex to find out the value of an option
901 * @param $key String: name of option val to retrieve
902 * @param $opts Options array to look in
903 * @param $default Mixed: default value returned if not found
905 protected static function getOptionValue( $key, $opts, $default ) {
906 $key = strtolower( $key );
908 if ( isset( $opts[$key] ) ) {