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;
39 $wgLanguageCode = 'en';
40 $wgContLang = Language
::factory( 'en' );
43 if ( $this->getCliArg( 'regex=' ) ) {
44 $this->regex
= $this->getCliArg( 'regex=' );
50 $this->keepUploads
= $this->getCliArg( 'keep-uploads' );
52 $tmpGlobals = array();
54 $tmpGlobals['wgScript'] = '/index.php';
55 $tmpGlobals['wgScriptPath'] = '/';
56 $tmpGlobals['wgArticlePath'] = '/wiki/$1';
57 $tmpGlobals['wgStyleSheetPath'] = '/skins';
58 $tmpGlobals['wgStylePath'] = '/skins';
59 $tmpGlobals['wgThumbnailScriptPath'] = false;
60 $tmpGlobals['wgLocalFileRepo'] = array(
61 'class' => 'LocalRepo',
63 'url' => 'http://example.com/images',
65 'transformVia404' => false,
66 'backend' => 'local-backend'
68 $tmpGlobals['wgForeignFileRepos'] = array();
69 $tmpGlobals['wgEnableParserCache'] = false;
70 $tmpGlobals['wgHooks'] = $wgHooks;
71 $tmpGlobals['wgDeferredUpdateList'] = array();
72 $tmpGlobals['wgMemc'] = wfGetMainCache();
73 $tmpGlobals['messageMemc'] = wfGetMessageCacheStorage();
74 $tmpGlobals['parserMemc'] = wfGetParserCacheStorage();
76 // $tmpGlobals['wgContLang'] = new StubContLang;
77 $tmpGlobals['wgUser'] = new User
;
78 $context = new RequestContext();
79 $tmpGlobals['wgLang'] = $context->getLanguage();
80 $tmpGlobals['wgOut'] = $context->getOutput();
81 $tmpGlobals['wgParser'] = new StubObject( 'wgParser', $GLOBALS['wgParserConf']['class'], array( $GLOBALS['wgParserConf'] ) );
82 $tmpGlobals['wgRequest'] = $context->getRequest();
84 if ( $GLOBALS['wgStyleDirectory'] === false ) {
85 $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();
122 function addDBData() {
123 $this->tablesUsed
[] = 'site_stats';
124 $this->tablesUsed
[] = 'interwiki';
125 # disabled for performance
126 #$this->tablesUsed[] = 'image';
128 # Hack: insert a few Wikipedia in-project interwiki prefixes,
129 # for testing inter-language links
130 $this->db
->insert( 'interwiki', array(
131 array( 'iw_prefix' => 'wikipedia',
132 'iw_url' => 'http://en.wikipedia.org/wiki/$1',
136 array( 'iw_prefix' => 'meatball',
137 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
141 array( 'iw_prefix' => 'zh',
142 'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
146 array( 'iw_prefix' => 'es',
147 'iw_url' => 'http://es.wikipedia.org/wiki/$1',
151 array( 'iw_prefix' => 'fr',
152 'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
156 array( 'iw_prefix' => 'ru',
157 'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
162 * @todo Fixme! Why are we inserting duplicate data here? Shouldn't
163 * need this IGNORE or shouldn't need the insert at all.
165 ), __METHOD__
, array( 'IGNORE' )
169 # Update certain things in site_stats
170 $this->db
->insert( 'site_stats',
171 array( 'ss_row_id' => 1, 'ss_images' => 2, 'ss_good_articles' => 1 ),
175 # Reinitialise the LocalisationCache to match the database state
176 Language
::getLocalisationCache()->unloadAll();
178 # Clear the message cache
179 MessageCache
::singleton()->clear();
181 $user = User
::newFromId( 0 );
182 LinkCache
::singleton()->clear(); # Avoids the odd failure at creating the nullRevision
184 # Upload DB table entries for files.
185 # We will upload the actual files later. Note that if anything causes LocalFile::load()
186 # to be triggered before then, it will break via maybeUpgrade() setting the fileExists
187 # member to false and storing it in cache.
188 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Foobar.jpg' ) );
189 if ( !$this->db
->selectField( 'image', '1', array( 'img_name' => $image->getName() ) ) ) {
190 $image->recordUpload2(
192 'Upload of some lame file',
199 'media_type' => MEDIATYPE_BITMAP
,
200 'mime' => 'image/jpeg',
201 'metadata' => serialize( array() ),
202 'sha1' => wfBaseConvert( '', 16, 36, 31 ),
203 'fileExists' => true ),
204 $this->db
->timestamp( '20010115123500' ), $user
208 # This image will be blacklisted in [[MediaWiki:Bad image list]]
209 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Bad.jpg' ) );
210 if ( !$this->db
->selectField( 'image', '1', array( 'img_name' => $image->getName() ) ) ) {
211 $image->recordUpload2(
220 'media_type' => MEDIATYPE_BITMAP
,
221 'mime' => 'image/jpeg',
222 'metadata' => serialize( array() ),
223 'sha1' => wfBaseConvert( '', 16, 36, 31 ),
224 'fileExists' => true ),
225 $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 'wgCleanupPresentationalAttributes' => true,
333 'wgWellFormedXml' => true,
334 'wgAllowMicrodataAttributes' => true,
335 'wgAdaptiveMessageCache' => true,
336 'wgUseDatabaseMessages' => true,
340 $configLines = explode( "\n", $config );
342 foreach ( $configLines as $line ) {
343 list( $var, $value ) = explode( '=', $line, 2 );
345 $settings[$var] = eval( "return $value;" ); //???
349 $this->savedGlobals
= array();
352 wfRunHooks( 'ParserTestGlobals', array( &$settings ) );
354 foreach ( $settings as $var => $val ) {
355 if ( array_key_exists( $var, $GLOBALS ) ) {
356 $this->savedGlobals
[$var] = $GLOBALS[$var];
359 $GLOBALS[$var] = $val;
362 $langObj = Language
::factory( $lang );
363 $GLOBALS['wgContLang'] = $langObj;
364 $context = new RequestContext();
365 $GLOBALS['wgLang'] = $context->getLanguage();
367 $GLOBALS['wgMemc'] = new EmptyBagOStuff
;
368 $GLOBALS['wgOut'] = $context->getOutput();
369 $GLOBALS['wgUser'] = $context->getUser();
373 $wgHooks['ParserTestParser'][] = 'ParserTestParserHook::setup';
374 $wgHooks['ParserGetVariableValueTs'][] = 'ParserTest::getFakeTimestamp';
376 MagicWord
::clearCache();
377 RepoGroup
::destroySingleton();
378 FileBackendGroup
::destroySingleton();
380 # Create dummy files in storage
381 $this->setupUploads();
383 # Publish the articles after we have the final language set
384 $this->publishTestArticles();
386 # The entries saved into RepoGroup cache with previous globals will be wrong.
387 RepoGroup
::destroySingleton();
388 FileBackendGroup
::destroySingleton();
389 MessageCache
::destroyInstance();
395 * Get an FS upload directory (only applies to FSFileBackend)
397 * @return String: the directory
399 protected function getUploadDir() {
400 if ( $this->keepUploads
) {
401 $dir = wfTempDir() . '/mwParser-images';
403 if ( is_dir( $dir ) ) {
407 $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
410 // wfDebug( "Creating upload directory $dir\n" );
411 if ( file_exists( $dir ) ) {
412 wfDebug( "Already exists!\n" );
420 * Create a dummy uploads directory which will contain a couple
421 * of files in order to pass existence tests.
423 * @return String: the directory
425 protected function setupUploads() {
428 $base = $this->getBaseDir();
429 $backend = RepoGroup
::singleton()->getLocalRepo()->getBackend();
430 $backend->prepare( array( 'dir' => "$base/local-public/3/3a" ) );
431 $backend->store( array(
432 'src' => "$IP/skins/monobook/headbg.jpg", 'dst' => "$base/local-public/3/3a/Foobar.jpg"
434 $backend->prepare( array( 'dir' => "$base/local-public/0/09" ) );
435 $backend->store( array(
436 'src' => "$IP/skins/monobook/headbg.jpg", 'dst' => "$base/local-public/0/09/Bad.jpg"
441 * Restore default values and perform any necessary clean-up
442 * after each test runs.
444 protected function teardownGlobals() {
445 $this->teardownUploads();
447 foreach ( $this->savedGlobals
as $var => $val ) {
448 $GLOBALS[$var] = $val;
451 RepoGroup
::destroySingleton();
452 LinkCache
::singleton()->clear();
456 * Remove the dummy uploads directory
458 private function teardownUploads() {
459 if ( $this->keepUploads
) {
463 $base = $this->getBaseDir();
464 // delete the files first, then the dirs.
467 "$base/local-public/3/3a/Foobar.jpg",
468 "$base/local-thumb/3/3a/Foobar.jpg/180px-Foobar.jpg",
469 "$base/local-thumb/3/3a/Foobar.jpg/200px-Foobar.jpg",
470 "$base/local-thumb/3/3a/Foobar.jpg/640px-Foobar.jpg",
471 "$base/local-thumb/3/3a/Foobar.jpg/120px-Foobar.jpg",
472 "$base/local-thumb/3/3a/Foobar.jpg/1280px-Foobar.jpg",
473 "$base/local-thumb/3/3a/Foobar.jpg/20px-Foobar.jpg",
474 "$base/local-thumb/3/3a/Foobar.jpg/270px-Foobar.jpg",
475 "$base/local-thumb/3/3a/Foobar.jpg/300px-Foobar.jpg",
476 "$base/local-thumb/3/3a/Foobar.jpg/30px-Foobar.jpg",
477 "$base/local-thumb/3/3a/Foobar.jpg/360px-Foobar.jpg",
478 "$base/local-thumb/3/3a/Foobar.jpg/400px-Foobar.jpg",
479 "$base/local-thumb/3/3a/Foobar.jpg/40px-Foobar.jpg",
480 "$base/local-thumb/3/3a/Foobar.jpg/70px-Foobar.jpg",
481 "$base/local-thumb/3/3a/Foobar.jpg/960px-Foobar.jpg",
483 "$base/local-public/0/09/Bad.jpg",
484 "$base/local-thumb/0/09/Bad.jpg",
486 "$base/local-public/math/f/a/5/fa50b8b616463173474302ca3e63586b.png",
492 * Delete the specified files, if they exist.
493 * @param $files Array: full paths to files to delete.
495 private static function deleteFiles( $files ) {
496 $backend = RepoGroup
::singleton()->getLocalRepo()->getBackend();
497 foreach ( $files as $file ) {
498 $backend->delete( array( 'src' => $file ), array( 'force' => 1 ) );
500 foreach ( $files as $file ) {
502 while ( $tmp = FileBackend
::parentStoragePath( $tmp ) ) {
503 if ( !$backend->clean( array( 'dir' => $tmp ) )->isOK() ) {
510 protected function getBaseDir() {
511 return 'mwstore://local-backend';
514 public function parserTestProvider() {
515 if ( $this->file
=== false ) {
516 global $wgParserTestFiles;
517 $this->file
= $wgParserTestFiles[0];
519 return new TestFileIterator( $this->file
, $this );
523 * Set the file from whose tests will be run by this instance
525 public function setParserTestFile( $filename ) {
526 $this->file
= $filename;
531 * @dataProvider parserTestProvider
533 public function testParserTest( $desc, $input, $result, $opts, $config ) {
534 if ( $this->regex
!= '' && !preg_match( '/' . $this->regex
. '/', $desc ) ) {
535 $this->assertTrue( true ); // XXX: don't flood output with "test made no assertions"
536 //$this->markTestSkipped( 'Filtered out by the user' );
540 if ( !$this->isWikitextNS( NS_MAIN
) ) {
541 // parser tests frequently assume that the main namespace contains wikitext.
542 // @todo: When setting up pages, force the content model. Only skip if
543 // $wgtContentModelUseDB is false.
544 $this->markTestSkipped( "Main namespace does not support wikitext,"
545 . "skipping parser test: $desc" );
548 wfDebug( "Running parser test: $desc\n" );
550 $opts = $this->parseOptions( $opts );
551 $context = $this->setupGlobals( $opts, $config );
553 $user = $context->getUser();
554 $options = ParserOptions
::newFromContext( $context );
556 if ( isset( $opts['title'] ) ) {
557 $titleText = $opts['title'];
560 $titleText = 'Parser test';
563 $local = isset( $opts['local'] );
564 $preprocessor = isset( $opts['preprocessor'] ) ?
$opts['preprocessor'] : null;
565 $parser = $this->getParser( $preprocessor );
567 $title = Title
::newFromText( $titleText );
569 if ( isset( $opts['pst'] ) ) {
570 $out = $parser->preSaveTransform( $input, $title, $user, $options );
571 } elseif ( isset( $opts['msg'] ) ) {
572 $out = $parser->transformMsg( $input, $options, $title );
573 } elseif ( isset( $opts['section'] ) ) {
574 $section = $opts['section'];
575 $out = $parser->getSection( $input, $section );
576 } elseif ( isset( $opts['replace'] ) ) {
577 $section = $opts['replace'][0];
578 $replace = $opts['replace'][1];
579 $out = $parser->replaceSection( $input, $section, $replace );
580 } elseif ( isset( $opts['comment'] ) ) {
581 $out = Linker
::formatComment( $input, $title, $local );
582 } elseif ( isset( $opts['preload'] ) ) {
583 $out = $parser->getpreloadText( $input, $title, $options );
585 $output = $parser->parse( $input, $title, $options, true, true, 1337 );
586 $out = $output->getText();
588 if ( isset( $opts['showtitle'] ) ) {
589 if ( $output->getTitleText() ) {
590 $title = $output->getTitleText();
593 $out = "$title\n$out";
596 if ( isset( $opts['ill'] ) ) {
597 $out = $this->tidy( implode( ' ', $output->getLanguageLinks() ) );
598 } elseif ( isset( $opts['cat'] ) ) {
599 $outputPage = $context->getOutput();
600 $outputPage->addCategoryLinks( $output->getCategories() );
601 $cats = $outputPage->getCategoryLinks();
603 if ( isset( $cats['normal'] ) ) {
604 $out = $this->tidy( implode( ' ', $cats['normal'] ) );
609 $parser->mPreprocessor
= null;
611 $result = $this->tidy( $result );
614 $this->teardownGlobals();
616 $this->assertEquals( $result, $out, $desc );
620 * Run a fuzz test series
621 * Draw input from a set of test files
623 * @todo fixme Needs some work to not eat memory until the world explodes
627 function testFuzzTests() {
628 global $wgParserTestFiles;
630 $files = $wgParserTestFiles;
632 if( $this->getCliArg( 'file=' ) ) {
633 $files = array( $this->getCliArg( 'file=' ) );
636 $dict = $this->getFuzzInput( $files );
637 $dictSize = strlen( $dict );
638 $logMaxLength = log( $this->maxFuzzTestLength
);
640 ini_set( 'memory_limit', $this->memoryLimit
* 1048576 );
643 $opts = ParserOptions
::newFromUser( $user );
644 $title = Title
::makeTitle( NS_MAIN
, 'Parser_test' );
650 // Generate test input
651 mt_srand( ++
$this->fuzzSeed
);
652 $totalLength = mt_rand( 1, $this->maxFuzzTestLength
);
655 while ( strlen( $input ) < $totalLength ) {
656 $logHairLength = mt_rand( 0, 1000000 ) / 1000000 * $logMaxLength;
657 $hairLength = min( intval( exp( $logHairLength ) ), $dictSize );
658 $offset = mt_rand( 0, $dictSize - $hairLength );
659 $input .= substr( $dict, $offset, $hairLength );
662 $this->setupGlobals();
663 $parser = $this->getParser();
667 $parser->parse( $input, $title, $opts );
668 $this->assertTrue( true, "Test $id, fuzz seed {$this->fuzzSeed}" );
669 } catch ( Exception
$exception ) {
670 $input_dump = sprintf( "string(%d) \"%s\"\n", strlen( $input ), $input );
672 $this->assertTrue( false, "Test $id, fuzz seed {$this->fuzzSeed}. \n\nInput: $input_dump\n\nError: {$exception->getMessage()}\n\nBacktrace: {$exception->getTraceAsString()}" );
675 $this->teardownGlobals();
676 $parser->__destruct();
678 if ( $id %
100 == 0 ) {
679 $usage = intval( memory_get_usage( true ) / $this->memoryLimit
/ 1048576 * 100 );
680 //echo "{$this->fuzzSeed}: $numSuccess/$numTotal (mem: $usage%)\n";
682 $ret = "Out of memory:\n";
683 $memStats = $this->getMemoryBreakdown();
685 foreach ( $memStats as $name => $usage ) {
686 $ret .= "$name: $usage\n";
689 throw new MWException( $ret );
698 //Various getter functions
701 * Get an input dictionary from a set of parser test files
703 function getFuzzInput( $filenames ) {
706 foreach ( $filenames as $filename ) {
707 $contents = file_get_contents( $filename );
708 preg_match_all( '/!!\s*input\n(.*?)\n!!\s*result/s', $contents, $matches );
710 foreach ( $matches[1] as $match ) {
711 $dict .= $match . "\n";
719 * Get a memory usage breakdown
721 function getMemoryBreakdown() {
724 foreach ( $GLOBALS as $name => $value ) {
725 $memStats['$' . $name] = strlen( serialize( $value ) );
728 $classes = get_declared_classes();
730 foreach ( $classes as $class ) {
731 $rc = new ReflectionClass( $class );
732 $props = $rc->getStaticProperties();
733 $memStats[$class] = strlen( serialize( $props ) );
734 $methods = $rc->getMethods();
736 foreach ( $methods as $method ) {
737 $memStats[$class] +
= strlen( serialize( $method->getStaticVariables() ) );
741 $functions = get_defined_functions();
743 foreach ( $functions['user'] as $function ) {
744 $rf = new ReflectionFunction( $function );
745 $memStats["$function()"] = strlen( serialize( $rf->getStaticVariables() ) );
754 * Get a Parser object
756 function getParser( $preprocessor = null ) {
757 global $wgParserConf;
759 $class = $wgParserConf['class'];
760 $parser = new $class( array( 'preprocessorClass' => $preprocessor ) +
$wgParserConf );
762 wfRunHooks( 'ParserTestParser', array( &$parser ) );
767 //Various action functions
769 public function addArticle( $name, $text, $line ) {
770 self
::$articles[$name] = array( $text, $line );
773 public function publishTestArticles() {
774 if ( empty( self
::$articles ) ) {
778 foreach ( self
::$articles as $name => $info ) {
779 list( $text, $line ) = $info;
780 ParserTest
::addArticle( $name, $text, $line, 'ignoreduplicate' );
785 * Steal a callback function from the primary parser, save it for
786 * application to our scary parser. If the hook is not installed,
787 * abort processing of this file.
789 * @param $name String
790 * @return Bool true if tag hook is present
792 public function requireHook( $name ) {
794 $wgParser->firstCallInit( ); // make sure hooks are loaded.
795 return isset( $wgParser->mTagHooks
[$name] );
798 public function requireFunctionHook( $name ) {
800 $wgParser->firstCallInit( ); // make sure hooks are loaded.
801 return isset( $wgParser->mFunctionHooks
[$name] );
803 //Various "cleanup" functions
806 * Run the "tidy" command on text if the $wgUseTidy
809 * @param $text String: the text to tidy
812 protected function tidy( $text ) {
816 $text = MWTidy
::tidy( $text );
823 * Remove last character if it is a newline
825 public function removeEndingNewline( $s ) {
826 if ( substr( $s, -1 ) === "\n" ) {
827 return substr( $s, 0, -1 );
834 //Test options parser functions
836 protected function parseOptions( $instring ) {
842 // foo=bar,"baz quux"
866 \[\[[^]]*\]\] # Link target
874 if ( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER
) ) {
875 foreach ( $matches as $bits ) {
876 array_shift( $bits );
877 $key = strtolower( array_shift( $bits ) );
878 if ( count( $bits ) == 0 ) {
880 } elseif ( count( $bits ) == 1 ) {
881 $opts[$key] = $this->cleanupOption( array_shift( $bits ) );
884 $opts[$key] = array_map( array( $this, 'cleanupOption' ), $bits );
891 protected function cleanupOption( $opt ) {
892 if ( substr( $opt, 0, 1 ) == '"' ) {
893 return substr( $opt, 1, -1 );
896 if ( substr( $opt, 0, 2 ) == '[[' ) {
897 return substr( $opt, 2, -2 );
903 * Use a regex to find out the value of an option
904 * @param $key String: name of option val to retrieve
905 * @param $opts Options array to look in
906 * @param $default Mixed: default value returned if not found
908 protected static function getOptionValue( $key, $opts, $default ) {
909 $key = strtolower( $key );
911 if ( isset( $opts[$key] ) ) {