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 $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 $wgNamespaceAliases;
41 if ( $this->getCliArg( 'regex=' ) ) {
42 $this->regex
= $this->getCliArg( 'regex=' );
48 $this->keepUploads
= $this->getCliArg( 'keep-uploads' );
50 $tmpGlobals = array();
52 $tmpGlobals['wgLanguageCode'] = 'en';
53 $tmpGlobals['wgContLang'] = Language
::factory( 'en' );
54 $tmpGlobals['wgSitename'] = 'MediaWiki';
55 $tmpGlobals['wgServer'] = 'http://example.org';
56 $tmpGlobals['wgScript'] = '/index.php';
57 $tmpGlobals['wgScriptPath'] = '/';
58 $tmpGlobals['wgArticlePath'] = '/wiki/$1';
59 $tmpGlobals['wgActionPaths'] = array();
60 $tmpGlobals['wgVariantArticlePath'] = false;
61 $tmpGlobals['wgExtensionAssetsPath'] = '/extensions';
62 $tmpGlobals['wgStyleSheetPath'] = '/skins';
63 $tmpGlobals['wgStylePath'] = '/skins';
64 $tmpGlobals['wgEnableUploads'] = true;
65 $tmpGlobals['wgThumbnailScriptPath'] = false;
66 $tmpGlobals['wgLocalFileRepo'] = array(
67 'class' => 'LocalRepo',
69 'url' => 'http://example.com/images',
71 'transformVia404' => false,
72 'backend' => 'local-backend'
74 $tmpGlobals['wgForeignFileRepos'] = array();
75 $tmpGlobals['wgDefaultExternalStore'] = array();
76 $tmpGlobals['wgEnableParserCache'] = false;
77 $tmpGlobals['wgCapitalLinks'] = true;
78 $tmpGlobals['wgNoFollowLinks'] = true;
79 $tmpGlobals['wgNoFollowDomainExceptions'] = array();
80 $tmpGlobals['wgExternalLinkTarget'] = false;
81 $tmpGlobals['wgThumbnailScriptPath'] = false;
82 $tmpGlobals['wgUseImageResize'] = true;
83 $tmpGlobals['wgAllowExternalImages'] = true;
84 $tmpGlobals['wgRawHtml'] = false;
85 $tmpGlobals['wgUseTidy'] = false;
86 $tmpGlobals['wgAlwaysUseTidy'] = false;
87 $tmpGlobals['wgHtml5'] = true;
88 $tmpGlobals['wgWellFormedXml'] = true;
89 $tmpGlobals['wgAllowMicrodataAttributes'] = true;
90 $tmpGlobals['wgExperimentalHtmlIds'] = false;
91 $tmpGlobals['wgAdaptiveMessageCache'] = true;
92 $tmpGlobals['wgUseDatabaseMessages'] = true;
93 $tmpGlobals['wgLocaltimezone'] = 'UTC';
94 $tmpGlobals['wgDeferredUpdateList'] = array();
95 $tmpGlobals['wgGroupPermissions'] = array(
97 'createaccount' => true,
100 'createpage' => true,
101 'createtalk' => true,
103 $tmpGlobals['wgNamespaceProtection'] = array( NS_MEDIAWIKI
=> 'editinterface' );
104 $tmpGlobals['wgMemc'] = new EmptyBagOStuff
;
105 $tmpGlobals['messageMemc'] = wfGetMessageCacheStorage();
106 $tmpGlobals['parserMemc'] = wfGetParserCacheStorage();
108 $tmpGlobals['wgParser'] = new StubObject( 'wgParser', $GLOBALS['wgParserConf']['class'], array( $GLOBALS['wgParserConf'] ) );
110 if ( $GLOBALS['wgStyleDirectory'] === false ) {
111 $tmpGlobals['wgStyleDirectory'] = "$IP/skins";
114 $tmpHooks = $wgHooks;
115 $tmpHooks['ParserTestParser'][] = 'ParserTestParserHook::setup';
116 $tmpHooks['ParserGetVariableValueTs'][] = 'ParserTest::getFakeTimestamp';
117 $tmpGlobals['wgHooks'] = $tmpHooks;
119 $this->setMwGlobals( $tmpGlobals );
121 $this->savedWeirdGlobals
['image_alias'] = $wgNamespaceAliases['Image'];
122 $this->savedWeirdGlobals
['image_talk_alias'] = $wgNamespaceAliases['Image_talk'];
124 $wgNamespaceAliases['Image'] = NS_FILE
;
125 $wgNamespaceAliases['Image_talk'] = NS_FILE_TALK
;
128 protected function tearDown() {
129 global $wgNamespaceAliases;
131 $wgNamespaceAliases['Image'] = $this->savedWeirdGlobals
['image_alias'];
132 $wgNamespaceAliases['Image_talk'] = $this->savedWeirdGlobals
['image_talk_alias'];
135 RepoGroup
::destroySingleton();
136 FileBackendGroup
::destroySingleton();
141 function addDBData() {
142 $this->tablesUsed
[] = 'site_stats';
143 $this->tablesUsed
[] = 'interwiki';
144 # disabled for performance
145 #$this->tablesUsed[] = 'image';
147 # Hack: insert a few Wikipedia in-project interwiki prefixes,
148 # for testing inter-language links
149 $this->db
->insert( 'interwiki', array(
150 array( 'iw_prefix' => 'wikipedia',
151 'iw_url' => 'http://en.wikipedia.org/wiki/$1',
155 array( 'iw_prefix' => 'meatball',
156 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
160 array( 'iw_prefix' => 'zh',
161 'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
165 array( 'iw_prefix' => 'es',
166 'iw_url' => 'http://es.wikipedia.org/wiki/$1',
170 array( 'iw_prefix' => 'fr',
171 'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
175 array( 'iw_prefix' => 'ru',
176 'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
181 * @todo Fixme! Why are we inserting duplicate data here? Shouldn't
182 * need this IGNORE or shouldn't need the insert at all.
184 ), __METHOD__
, array( 'IGNORE' )
187 # Update certain things in site_stats
188 $this->db
->insert( 'site_stats',
189 array( 'ss_row_id' => 1, 'ss_images' => 2, 'ss_good_articles' => 1 ),
193 # Clear the message cache
194 MessageCache
::singleton()->clear();
196 $user = User
::newFromId( 0 );
197 LinkCache
::singleton()->clear(); # Avoids the odd failure at creating the nullRevision
199 # Upload DB table entries for files.
200 # We will upload the actual files later. Note that if anything causes LocalFile::load()
201 # to be triggered before then, it will break via maybeUpgrade() setting the fileExists
202 # member to false and storing it in cache.
203 # note that the size/width/height/bits/etc of the file
204 # are actually set by inspecting the file itself; the arguments
205 # to recordUpload2 have no effect. That said, we try to make things
206 # match up so it is less confusing to readers of the code & tests.
207 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Foobar.jpg' ) );
208 if ( !$this->db
->selectField( 'image', '1', array( 'img_name' => $image->getName() ) ) ) {
209 $image->recordUpload2(
211 'Upload of some lame file',
218 'media_type' => MEDIATYPE_BITMAP
,
219 'mime' => 'image/jpeg',
220 'metadata' => serialize( array() ),
221 'sha1' => wfBaseConvert( '1', 16, 36, 31 ),
222 'fileExists' => true ),
223 $this->db
->timestamp( '20010115123500' ), $user
227 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Thumb.png' ) );
228 if ( !$this->db
->selectField( 'image', '1', array( 'img_name' => $image->getName() ) ) ) {
229 $image->recordUpload2(
231 'Upload of some lame thumbnail',
232 'Some lame thumbnail',
238 'media_type' => MEDIATYPE_BITMAP
,
239 'mime' => 'image/png',
240 'metadata' => serialize( array() ),
241 'sha1' => wfBaseConvert( '2', 16, 36, 31 ),
242 'fileExists' => true ),
243 $this->db
->timestamp( '20130225203040' ), $user
247 # This image will be blacklisted in [[MediaWiki:Bad image list]]
248 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Bad.jpg' ) );
249 if ( !$this->db
->selectField( 'image', '1', array( 'img_name' => $image->getName() ) ) ) {
250 $image->recordUpload2(
259 'media_type' => MEDIATYPE_BITMAP
,
260 'mime' => 'image/jpeg',
261 'metadata' => serialize( array() ),
262 'sha1' => wfBaseConvert( '3', 16, 36, 31 ),
263 'fileExists' => true ),
264 $this->db
->timestamp( '20010115123500' ), $user
269 //ParserTest setup/teardown functions
272 * Set up the global variables for a consistent environment for each test.
273 * Ideally this should replace the global configuration entirely.
275 protected function setupGlobals( $opts = array(), $config = '' ) {
276 global $wgFileBackends;
277 # Find out values for some special options.
279 self
::getOptionValue( 'language', $opts, 'en' );
281 self
::getOptionValue( 'variant', $opts, false );
283 self
::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
284 $linkHolderBatchSize =
285 self
::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
287 $uploadDir = $this->getUploadDir();
288 if ( $this->getCliArg( 'use-filebackend=' ) ) {
289 if ( self
::$backendToUse ) {
290 $backend = self
::$backendToUse;
292 $name = $this->getCliArg( 'use-filebackend=' );
293 $useConfig = array();
294 foreach ( $wgFileBackends as $conf ) {
295 if ( $conf['name'] == $name ) {
299 $useConfig['name'] = 'local-backend'; // swap name
300 $class = $conf['class'];
301 self
::$backendToUse = new $class( $useConfig );
302 $backend = self
::$backendToUse;
305 $backend = new FSFileBackend( array(
306 'name' => 'local-backend',
307 'lockManager' => 'nullLockManager',
308 'containerPaths' => array(
309 'local-public' => "$uploadDir",
310 'local-thumb' => "$uploadDir/thumb",
316 'wgLocalFileRepo' => array(
317 'class' => 'LocalRepo',
319 'url' => 'http://example.com/images',
321 'transformVia404' => false,
322 'backend' => $backend
324 'wgEnableUploads' => self
::getOptionValue( 'wgEnableUploads', $opts, true ),
325 'wgLanguageCode' => $lang,
326 'wgDBprefix' => $this->db
->getType() != 'oracle' ?
'unittest_' : 'ut_',
327 'wgRawHtml' => isset( $opts['rawhtml'] ),
328 'wgNamespacesWithSubpages' => array( NS_MAIN
=> isset( $opts['subpage'] ) ),
329 'wgMaxTocLevel' => $maxtoclevel,
330 'wgUseTeX' => isset( $opts['math'] ),
331 'wgMathDirectory' => $uploadDir . '/math',
332 'wgDefaultLanguageVariant' => $variant,
333 'wgLinkHolderBatchSize' => $linkHolderBatchSize,
337 $configLines = explode( "\n", $config );
339 foreach ( $configLines as $line ) {
340 list( $var, $value ) = explode( '=', $line, 2 );
342 $settings[$var] = eval( "return $value;" ); //???
346 $this->savedGlobals
= array();
349 wfRunHooks( 'ParserTestGlobals', array( &$settings ) );
351 $langObj = Language
::factory( $lang );
352 $settings['wgContLang'] = $langObj;
353 $settings['wgLang'] = $langObj;
355 $context = new RequestContext();
356 $settings['wgOut'] = $context->getOutput();
357 $settings['wgUser'] = $context->getUser();
358 $settings['wgRequest'] = $context->getRequest();
360 foreach ( $settings as $var => $val ) {
361 if ( array_key_exists( $var, $GLOBALS ) ) {
362 $this->savedGlobals
[$var] = $GLOBALS[$var];
365 $GLOBALS[$var] = $val;
368 MagicWord
::clearCache();
369 RepoGroup
::destroySingleton();
370 FileBackendGroup
::destroySingleton();
372 # Create dummy files in storage
373 $this->setupUploads();
375 # Publish the articles after we have the final language set
376 $this->publishTestArticles();
378 # The entries saved into RepoGroup cache with previous globals will be wrong.
379 RepoGroup
::destroySingleton();
380 FileBackendGroup
::destroySingleton();
381 MessageCache
::destroyInstance();
387 * Get an FS upload directory (only applies to FSFileBackend)
389 * @return String: the directory
391 protected function getUploadDir() {
392 if ( $this->keepUploads
) {
393 $dir = wfTempDir() . '/mwParser-images';
395 if ( is_dir( $dir ) ) {
399 $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
402 // wfDebug( "Creating upload directory $dir\n" );
403 if ( file_exists( $dir ) ) {
404 wfDebug( "Already exists!\n" );
413 * Create a dummy uploads directory which will contain a couple
414 * of files in order to pass existence tests.
416 * @return String: the directory
418 protected function setupUploads() {
421 $base = $this->getBaseDir();
422 $backend = RepoGroup
::singleton()->getLocalRepo()->getBackend();
423 $backend->prepare( array( 'dir' => "$base/local-public/3/3a" ) );
424 $backend->store( array(
425 'src' => "$IP/skins/monobook/headbg.jpg", 'dst' => "$base/local-public/3/3a/Foobar.jpg"
427 $backend->prepare( array( 'dir' => "$base/local-public/e/ea" ) );
428 $backend->store( array(
429 'src' => "$IP/skins/monobook/wiki.png", 'dst' => "$base/local-public/e/ea/Thumb.png"
431 $backend->prepare( array( 'dir' => "$base/local-public/0/09" ) );
432 $backend->store( array(
433 'src' => "$IP/skins/monobook/headbg.jpg", 'dst' => "$base/local-public/0/09/Bad.jpg"
438 * Restore default values and perform any necessary clean-up
439 * after each test runs.
441 protected function teardownGlobals() {
442 $this->teardownUploads();
444 foreach ( $this->savedGlobals
as $var => $val ) {
445 $GLOBALS[$var] = $val;
448 RepoGroup
::destroySingleton();
449 LinkCache
::singleton()->clear();
453 * Remove the dummy uploads directory
455 private function teardownUploads() {
456 if ( $this->keepUploads
) {
460 $base = $this->getBaseDir();
461 // delete the files first, then the dirs.
464 "$base/local-public/3/3a/Foobar.jpg",
465 "$base/local-thumb/3/3a/Foobar.jpg/180px-Foobar.jpg",
466 "$base/local-thumb/3/3a/Foobar.jpg/200px-Foobar.jpg",
467 "$base/local-thumb/3/3a/Foobar.jpg/640px-Foobar.jpg",
468 "$base/local-thumb/3/3a/Foobar.jpg/120px-Foobar.jpg",
469 "$base/local-thumb/3/3a/Foobar.jpg/1280px-Foobar.jpg",
470 "$base/local-thumb/3/3a/Foobar.jpg/20px-Foobar.jpg",
471 "$base/local-thumb/3/3a/Foobar.jpg/270px-Foobar.jpg",
472 "$base/local-thumb/3/3a/Foobar.jpg/300px-Foobar.jpg",
473 "$base/local-thumb/3/3a/Foobar.jpg/30px-Foobar.jpg",
474 "$base/local-thumb/3/3a/Foobar.jpg/360px-Foobar.jpg",
475 "$base/local-thumb/3/3a/Foobar.jpg/400px-Foobar.jpg",
476 "$base/local-thumb/3/3a/Foobar.jpg/40px-Foobar.jpg",
477 "$base/local-thumb/3/3a/Foobar.jpg/70px-Foobar.jpg",
478 "$base/local-thumb/3/3a/Foobar.jpg/960px-Foobar.jpg",
480 "$base/local-public/e/ea/Thumb.png",
482 "$base/local-public/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];
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 );
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 );
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 );
902 * Use a regex to find out the value of an option
903 * @param $key String: name of option val to retrieve
904 * @param $opts Options array to look in
905 * @param $default Mixed: default value returned if not found
907 protected static function getOptionValue( $key, $opts, $default ) {
908 $key = strtolower( $key );
910 if ( isset( $opts[$key] ) ) {