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['wgStylePath'] = '/skins';
63 $tmpGlobals['wgEnableUploads'] = true;
64 $tmpGlobals['wgThumbnailScriptPath'] = false;
65 $tmpGlobals['wgLocalFileRepo'] = array(
66 'class' => 'LocalRepo',
68 'url' => 'http://example.com/images',
70 'transformVia404' => false,
71 'backend' => 'local-backend'
73 $tmpGlobals['wgForeignFileRepos'] = array();
74 $tmpGlobals['wgDefaultExternalStore'] = array();
75 $tmpGlobals['wgEnableParserCache'] = false;
76 $tmpGlobals['wgCapitalLinks'] = true;
77 $tmpGlobals['wgNoFollowLinks'] = true;
78 $tmpGlobals['wgNoFollowDomainExceptions'] = array();
79 $tmpGlobals['wgExternalLinkTarget'] = false;
80 $tmpGlobals['wgThumbnailScriptPath'] = false;
81 $tmpGlobals['wgUseImageResize'] = true;
82 $tmpGlobals['wgAllowExternalImages'] = true;
83 $tmpGlobals['wgRawHtml'] = false;
84 $tmpGlobals['wgUseTidy'] = false;
85 $tmpGlobals['wgAlwaysUseTidy'] = false;
86 $tmpGlobals['wgHtml5'] = true;
87 $tmpGlobals['wgWellFormedXml'] = true;
88 $tmpGlobals['wgAllowMicrodataAttributes'] = true;
89 $tmpGlobals['wgExperimentalHtmlIds'] = false;
90 $tmpGlobals['wgAdaptiveMessageCache'] = true;
91 $tmpGlobals['wgUseDatabaseMessages'] = true;
92 $tmpGlobals['wgLocaltimezone'] = 'UTC';
93 $tmpGlobals['wgDeferredUpdateList'] = array();
94 $tmpGlobals['wgGroupPermissions'] = array(
96 'createaccount' => true,
100 'createtalk' => true,
102 $tmpGlobals['wgNamespaceProtection'] = array( NS_MEDIAWIKI
=> 'editinterface' );
103 $tmpGlobals['wgMemc'] = new EmptyBagOStuff
;
104 $tmpGlobals['messageMemc'] = wfGetMessageCacheStorage();
105 $tmpGlobals['parserMemc'] = wfGetParserCacheStorage();
107 $tmpGlobals['wgParser'] = new StubObject( 'wgParser', $GLOBALS['wgParserConf']['class'], array( $GLOBALS['wgParserConf'] ) );
109 if ( $GLOBALS['wgStyleDirectory'] === false ) {
110 $tmpGlobals['wgStyleDirectory'] = "$IP/skins";
113 $tmpHooks = $wgHooks;
114 $tmpHooks['ParserTestParser'][] = 'ParserTestParserHook::setup';
115 $tmpHooks['ParserGetVariableValueTs'][] = 'ParserTest::getFakeTimestamp';
116 $tmpGlobals['wgHooks'] = $tmpHooks;
118 $this->setMwGlobals( $tmpGlobals );
120 $this->savedWeirdGlobals
['image_alias'] = $wgNamespaceAliases['Image'];
121 $this->savedWeirdGlobals
['image_talk_alias'] = $wgNamespaceAliases['Image_talk'];
123 $wgNamespaceAliases['Image'] = NS_FILE
;
124 $wgNamespaceAliases['Image_talk'] = NS_FILE_TALK
;
127 protected function tearDown() {
128 global $wgNamespaceAliases;
130 $wgNamespaceAliases['Image'] = $this->savedWeirdGlobals
['image_alias'];
131 $wgNamespaceAliases['Image_talk'] = $this->savedWeirdGlobals
['image_talk_alias'];
134 RepoGroup
::destroySingleton();
135 FileBackendGroup
::destroySingleton();
140 function addDBData() {
141 $this->tablesUsed
[] = 'site_stats';
142 $this->tablesUsed
[] = 'interwiki';
143 # disabled for performance
144 #$this->tablesUsed[] = 'image';
146 # Hack: insert a few Wikipedia in-project interwiki prefixes,
147 # for testing inter-language links
148 $this->db
->insert( 'interwiki', array(
149 array( 'iw_prefix' => 'wikipedia',
150 'iw_url' => 'http://en.wikipedia.org/wiki/$1',
154 array( 'iw_prefix' => 'meatball',
155 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
159 array( 'iw_prefix' => 'zh',
160 'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
164 array( 'iw_prefix' => 'es',
165 'iw_url' => 'http://es.wikipedia.org/wiki/$1',
169 array( 'iw_prefix' => 'fr',
170 'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
174 array( 'iw_prefix' => 'ru',
175 'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
180 * @todo Fixme! Why are we inserting duplicate data here? Shouldn't
181 * need this IGNORE or shouldn't need the insert at all.
183 ), __METHOD__
, array( 'IGNORE' )
186 # Update certain things in site_stats
187 $this->db
->insert( 'site_stats',
188 array( 'ss_row_id' => 1, 'ss_images' => 2, 'ss_good_articles' => 1 ),
192 # Clear the message cache
193 MessageCache
::singleton()->clear();
195 $user = User
::newFromId( 0 );
196 LinkCache
::singleton()->clear(); # Avoids the odd failure at creating the nullRevision
198 # Upload DB table entries for files.
199 # We will upload the actual files later. Note that if anything causes LocalFile::load()
200 # to be triggered before then, it will break via maybeUpgrade() setting the fileExists
201 # member to false and storing it in cache.
202 # note that the size/width/height/bits/etc of the file
203 # are actually set by inspecting the file itself; the arguments
204 # to recordUpload2 have no effect. That said, we try to make things
205 # match up so it is less confusing to readers of the code & tests.
206 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Foobar.jpg' ) );
207 if ( !$this->db
->selectField( 'image', '1', array( 'img_name' => $image->getName() ) ) ) {
208 $image->recordUpload2(
210 'Upload of some lame file',
217 'media_type' => MEDIATYPE_BITMAP
,
218 'mime' => 'image/jpeg',
219 'metadata' => serialize( array() ),
220 'sha1' => wfBaseConvert( '1', 16, 36, 31 ),
221 'fileExists' => true ),
222 $this->db
->timestamp( '20010115123500' ), $user
226 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Thumb.png' ) );
227 if ( !$this->db
->selectField( 'image', '1', array( 'img_name' => $image->getName() ) ) ) {
228 $image->recordUpload2(
230 'Upload of some lame thumbnail',
231 'Some lame thumbnail',
237 'media_type' => MEDIATYPE_BITMAP
,
238 'mime' => 'image/png',
239 'metadata' => serialize( array() ),
240 'sha1' => wfBaseConvert( '2', 16, 36, 31 ),
241 'fileExists' => true ),
242 $this->db
->timestamp( '20130225203040' ), $user
246 # This image will be blacklisted in [[MediaWiki:Bad image list]]
247 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Bad.jpg' ) );
248 if ( !$this->db
->selectField( 'image', '1', array( 'img_name' => $image->getName() ) ) ) {
249 $image->recordUpload2(
258 'media_type' => MEDIATYPE_BITMAP
,
259 'mime' => 'image/jpeg',
260 'metadata' => serialize( array() ),
261 'sha1' => wfBaseConvert( '3', 16, 36, 31 ),
262 'fileExists' => true ),
263 $this->db
->timestamp( '20010115123500' ), $user
268 //ParserTest setup/teardown functions
271 * Set up the global variables for a consistent environment for each test.
272 * Ideally this should replace the global configuration entirely.
274 protected function setupGlobals( $opts = array(), $config = '' ) {
275 global $wgFileBackends;
276 # Find out values for some special options.
278 self
::getOptionValue( 'language', $opts, 'en' );
280 self
::getOptionValue( 'variant', $opts, false );
282 self
::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
283 $linkHolderBatchSize =
284 self
::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
286 $uploadDir = $this->getUploadDir();
287 if ( $this->getCliArg( 'use-filebackend=' ) ) {
288 if ( self
::$backendToUse ) {
289 $backend = self
::$backendToUse;
291 $name = $this->getCliArg( 'use-filebackend=' );
292 $useConfig = array();
293 foreach ( $wgFileBackends as $conf ) {
294 if ( $conf['name'] == $name ) {
298 $useConfig['name'] = 'local-backend'; // swap name
299 $class = $conf['class'];
300 self
::$backendToUse = new $class( $useConfig );
301 $backend = self
::$backendToUse;
304 $backend = new FSFileBackend( array(
305 'name' => 'local-backend',
306 'lockManager' => 'nullLockManager',
307 'containerPaths' => array(
308 'local-public' => "$uploadDir",
309 'local-thumb' => "$uploadDir/thumb",
315 'wgLocalFileRepo' => array(
316 'class' => 'LocalRepo',
318 'url' => 'http://example.com/images',
320 'transformVia404' => false,
321 'backend' => $backend
323 'wgEnableUploads' => self
::getOptionValue( 'wgEnableUploads', $opts, true ),
324 'wgLanguageCode' => $lang,
325 'wgDBprefix' => $this->db
->getType() != 'oracle' ?
'unittest_' : 'ut_',
326 'wgRawHtml' => isset( $opts['rawhtml'] ),
327 'wgNamespacesWithSubpages' => array( NS_MAIN
=> isset( $opts['subpage'] ) ),
328 'wgMaxTocLevel' => $maxtoclevel,
329 'wgUseTeX' => isset( $opts['math'] ),
330 'wgMathDirectory' => $uploadDir . '/math',
331 'wgDefaultLanguageVariant' => $variant,
332 'wgLinkHolderBatchSize' => $linkHolderBatchSize,
336 $configLines = explode( "\n", $config );
338 foreach ( $configLines as $line ) {
339 list( $var, $value ) = explode( '=', $line, 2 );
341 $settings[$var] = eval( "return $value;" ); //???
345 $this->savedGlobals
= array();
348 wfRunHooks( 'ParserTestGlobals', array( &$settings ) );
350 $langObj = Language
::factory( $lang );
351 $settings['wgContLang'] = $langObj;
352 $settings['wgLang'] = $langObj;
354 $context = new RequestContext();
355 $settings['wgOut'] = $context->getOutput();
356 $settings['wgUser'] = $context->getUser();
357 $settings['wgRequest'] = $context->getRequest();
359 foreach ( $settings as $var => $val ) {
360 if ( array_key_exists( $var, $GLOBALS ) ) {
361 $this->savedGlobals
[$var] = $GLOBALS[$var];
364 $GLOBALS[$var] = $val;
367 MagicWord
::clearCache();
368 RepoGroup
::destroySingleton();
369 FileBackendGroup
::destroySingleton();
371 # Create dummy files in storage
372 $this->setupUploads();
374 # Publish the articles after we have the final language set
375 $this->publishTestArticles();
377 # The entries saved into RepoGroup cache with previous globals will be wrong.
378 RepoGroup
::destroySingleton();
379 FileBackendGroup
::destroySingleton();
380 MessageCache
::destroyInstance();
386 * Get an FS upload directory (only applies to FSFileBackend)
388 * @return String: the directory
390 protected function getUploadDir() {
391 if ( $this->keepUploads
) {
392 $dir = wfTempDir() . '/mwParser-images';
394 if ( is_dir( $dir ) ) {
398 $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
401 // wfDebug( "Creating upload directory $dir\n" );
402 if ( file_exists( $dir ) ) {
403 wfDebug( "Already exists!\n" );
412 * Create a dummy uploads directory which will contain a couple
413 * of files in order to pass existence tests.
415 * @return String: the directory
417 protected function setupUploads() {
420 $base = $this->getBaseDir();
421 $backend = RepoGroup
::singleton()->getLocalRepo()->getBackend();
422 $backend->prepare( array( 'dir' => "$base/local-public/3/3a" ) );
423 $backend->store( array(
424 'src' => "$IP/skins/monobook/headbg.jpg", 'dst' => "$base/local-public/3/3a/Foobar.jpg"
426 $backend->prepare( array( 'dir' => "$base/local-public/e/ea" ) );
427 $backend->store( array(
428 'src' => "$IP/skins/monobook/wiki.png", 'dst' => "$base/local-public/e/ea/Thumb.png"
430 $backend->prepare( array( 'dir' => "$base/local-public/0/09" ) );
431 $backend->store( array(
432 'src' => "$IP/skins/monobook/headbg.jpg", 'dst' => "$base/local-public/0/09/Bad.jpg"
437 * Restore default values and perform any necessary clean-up
438 * after each test runs.
440 protected function teardownGlobals() {
441 $this->teardownUploads();
443 foreach ( $this->savedGlobals
as $var => $val ) {
444 $GLOBALS[$var] = $val;
447 RepoGroup
::destroySingleton();
448 LinkCache
::singleton()->clear();
452 * Remove the dummy uploads directory
454 private function teardownUploads() {
455 if ( $this->keepUploads
) {
459 $base = $this->getBaseDir();
460 // delete the files first, then the dirs.
463 "$base/local-public/3/3a/Foobar.jpg",
464 "$base/local-thumb/3/3a/Foobar.jpg/180px-Foobar.jpg",
465 "$base/local-thumb/3/3a/Foobar.jpg/200px-Foobar.jpg",
466 "$base/local-thumb/3/3a/Foobar.jpg/640px-Foobar.jpg",
467 "$base/local-thumb/3/3a/Foobar.jpg/120px-Foobar.jpg",
468 "$base/local-thumb/3/3a/Foobar.jpg/1280px-Foobar.jpg",
469 "$base/local-thumb/3/3a/Foobar.jpg/20px-Foobar.jpg",
470 "$base/local-thumb/3/3a/Foobar.jpg/270px-Foobar.jpg",
471 "$base/local-thumb/3/3a/Foobar.jpg/300px-Foobar.jpg",
472 "$base/local-thumb/3/3a/Foobar.jpg/30px-Foobar.jpg",
473 "$base/local-thumb/3/3a/Foobar.jpg/360px-Foobar.jpg",
474 "$base/local-thumb/3/3a/Foobar.jpg/400px-Foobar.jpg",
475 "$base/local-thumb/3/3a/Foobar.jpg/40px-Foobar.jpg",
476 "$base/local-thumb/3/3a/Foobar.jpg/70px-Foobar.jpg",
477 "$base/local-thumb/3/3a/Foobar.jpg/960px-Foobar.jpg",
479 "$base/local-public/e/ea/Thumb.png",
481 "$base/local-public/0/09/Bad.jpg",
483 "$base/local-public/math/f/a/5/fa50b8b616463173474302ca3e63586b.png",
489 * Delete the specified files, if they exist.
490 * @param $files Array: full paths to files to delete.
492 private static function deleteFiles( $files ) {
493 $backend = RepoGroup
::singleton()->getLocalRepo()->getBackend();
494 foreach ( $files as $file ) {
495 $backend->delete( array( 'src' => $file ), array( 'force' => 1 ) );
497 foreach ( $files as $file ) {
499 while ( $tmp = FileBackend
::parentStoragePath( $tmp ) ) {
500 if ( !$backend->clean( array( 'dir' => $tmp ) )->isOK() ) {
507 protected function getBaseDir() {
508 return 'mwstore://local-backend';
511 public function parserTestProvider() {
512 if ( $this->file
=== false ) {
513 global $wgParserTestFiles;
514 $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 );
694 //Various getter functions
697 * Get an input dictionary from a set of parser test files
699 function getFuzzInput( $filenames ) {
702 foreach ( $filenames as $filename ) {
703 $contents = file_get_contents( $filename );
704 preg_match_all( '/!!\s*input\n(.*?)\n!!\s*result/s', $contents, $matches );
706 foreach ( $matches[1] as $match ) {
707 $dict .= $match . "\n";
715 * Get a memory usage breakdown
717 function getMemoryBreakdown() {
720 foreach ( $GLOBALS as $name => $value ) {
721 $memStats['$' . $name] = strlen( serialize( $value ) );
724 $classes = get_declared_classes();
726 foreach ( $classes as $class ) {
727 $rc = new ReflectionClass( $class );
728 $props = $rc->getStaticProperties();
729 $memStats[$class] = strlen( serialize( $props ) );
730 $methods = $rc->getMethods();
732 foreach ( $methods as $method ) {
733 $memStats[$class] +
= strlen( serialize( $method->getStaticVariables() ) );
737 $functions = get_defined_functions();
739 foreach ( $functions['user'] as $function ) {
740 $rf = new ReflectionFunction( $function );
741 $memStats["$function()"] = strlen( serialize( $rf->getStaticVariables() ) );
750 * Get a Parser object
752 function getParser( $preprocessor = null ) {
753 global $wgParserConf;
755 $class = $wgParserConf['class'];
756 $parser = new $class( array( 'preprocessorClass' => $preprocessor ) +
$wgParserConf );
758 wfRunHooks( 'ParserTestParser', array( &$parser ) );
763 //Various action functions
765 public function addArticle( $name, $text, $line ) {
766 self
::$articles[$name] = array( $text, $line );
769 public function publishTestArticles() {
770 if ( empty( self
::$articles ) ) {
774 foreach ( self
::$articles as $name => $info ) {
775 list( $text, $line ) = $info;
776 ParserTest
::addArticle( $name, $text, $line, 'ignoreduplicate' );
781 * Steal a callback function from the primary parser, save it for
782 * application to our scary parser. If the hook is not installed,
783 * abort processing of this file.
785 * @param $name String
786 * @return Bool true if tag hook is present
788 public function requireHook( $name ) {
790 $wgParser->firstCallInit(); // make sure hooks are loaded.
791 return isset( $wgParser->mTagHooks
[$name] );
794 public function requireFunctionHook( $name ) {
796 $wgParser->firstCallInit(); // make sure hooks are loaded.
797 return isset( $wgParser->mFunctionHooks
[$name] );
800 //Various "cleanup" functions
803 * Run the "tidy" command on text if the $wgUseTidy
806 * @param $text String: the text to tidy
809 protected function tidy( $text ) {
813 $text = MWTidy
::tidy( $text );
820 * Remove last character if it is a newline
822 public function removeEndingNewline( $s ) {
823 if ( substr( $s, -1 ) === "\n" ) {
824 return substr( $s, 0, -1 );
830 //Test options parser functions
832 protected function parseOptions( $instring ) {
838 // foo=bar,"baz quux"
862 \[\[[^]]*\]\] # Link target
870 if ( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER
) ) {
871 foreach ( $matches as $bits ) {
872 array_shift( $bits );
873 $key = strtolower( array_shift( $bits ) );
874 if ( count( $bits ) == 0 ) {
876 } elseif ( count( $bits ) == 1 ) {
877 $opts[$key] = $this->cleanupOption( array_shift( $bits ) );
880 $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 );
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] ) ) {