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 # Reinitialise the LocalisationCache to match the database state
194 Language
::getLocalisationCache()->unloadAll();
196 # Clear the message cache
197 MessageCache
::singleton()->clear();
199 $user = User
::newFromId( 0 );
200 LinkCache
::singleton()->clear(); # Avoids the odd failure at creating the nullRevision
202 # Upload DB table entries for files.
203 # We will upload the actual files later. Note that if anything causes LocalFile::load()
204 # to be triggered before then, it will break via maybeUpgrade() setting the fileExists
205 # member to false and storing it in cache.
206 # note that the size/width/height/bits/etc of the file
207 # are actually set by inspecting the file itself; the arguments
208 # to recordUpload2 have no effect. That said, we try to make things
209 # match up so it is less confusing to readers of the code & tests.
210 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Foobar.jpg' ) );
211 if ( !$this->db
->selectField( 'image', '1', array( 'img_name' => $image->getName() ) ) ) {
212 $image->recordUpload2(
214 'Upload of some lame file',
221 'media_type' => MEDIATYPE_BITMAP
,
222 'mime' => 'image/jpeg',
223 'metadata' => serialize( array() ),
224 'sha1' => wfBaseConvert( '1', 16, 36, 31 ),
225 'fileExists' => true ),
226 $this->db
->timestamp( '20010115123500' ), $user
230 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Thumb.png' ) );
231 if ( !$this->db
->selectField( 'image', '1', array( 'img_name' => $image->getName() ) ) ) {
232 $image->recordUpload2(
234 'Upload of some lame thumbnail',
235 'Some lame thumbnail',
241 'media_type' => MEDIATYPE_BITMAP
,
242 'mime' => 'image/png',
243 'metadata' => serialize( array() ),
244 'sha1' => wfBaseConvert( '2', 16, 36, 31 ),
245 'fileExists' => true ),
246 $this->db
->timestamp( '20130225203040' ), $user
250 # This image will be blacklisted in [[MediaWiki:Bad image list]]
251 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Bad.jpg' ) );
252 if ( !$this->db
->selectField( 'image', '1', array( 'img_name' => $image->getName() ) ) ) {
253 $image->recordUpload2(
262 'media_type' => MEDIATYPE_BITMAP
,
263 'mime' => 'image/jpeg',
264 'metadata' => serialize( array() ),
265 'sha1' => wfBaseConvert( '3', 16, 36, 31 ),
266 'fileExists' => true ),
267 $this->db
->timestamp( '20010115123500' ), $user
272 //ParserTest setup/teardown functions
275 * Set up the global variables for a consistent environment for each test.
276 * Ideally this should replace the global configuration entirely.
278 protected function setupGlobals( $opts = array(), $config = '' ) {
279 global $wgFileBackends;
280 # Find out values for some special options.
282 self
::getOptionValue( 'language', $opts, 'en' );
284 self
::getOptionValue( 'variant', $opts, false );
286 self
::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
287 $linkHolderBatchSize =
288 self
::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
290 $uploadDir = $this->getUploadDir();
291 if ( $this->getCliArg( 'use-filebackend=' ) ) {
292 if ( self
::$backendToUse ) {
293 $backend = self
::$backendToUse;
295 $name = $this->getCliArg( 'use-filebackend=' );
296 $useConfig = array();
297 foreach ( $wgFileBackends as $conf ) {
298 if ( $conf['name'] == $name ) {
302 $useConfig['name'] = 'local-backend'; // swap name
303 $class = $conf['class'];
304 self
::$backendToUse = new $class( $useConfig );
305 $backend = self
::$backendToUse;
308 $backend = new FSFileBackend( array(
309 'name' => 'local-backend',
310 'lockManager' => 'nullLockManager',
311 'containerPaths' => array(
312 'local-public' => "$uploadDir",
313 'local-thumb' => "$uploadDir/thumb",
319 'wgLocalFileRepo' => array(
320 'class' => 'LocalRepo',
322 'url' => 'http://example.com/images',
324 'transformVia404' => false,
325 'backend' => $backend
327 'wgEnableUploads' => self
::getOptionValue( 'wgEnableUploads', $opts, true ),
328 'wgLanguageCode' => $lang,
329 'wgDBprefix' => $this->db
->getType() != 'oracle' ?
'unittest_' : 'ut_',
330 'wgRawHtml' => isset( $opts['rawhtml'] ),
331 'wgNamespacesWithSubpages' => array( NS_MAIN
=> isset( $opts['subpage'] ) ),
332 'wgMaxTocLevel' => $maxtoclevel,
333 'wgUseTeX' => isset( $opts['math'] ),
334 'wgMathDirectory' => $uploadDir . '/math',
335 'wgDefaultLanguageVariant' => $variant,
336 'wgLinkHolderBatchSize' => $linkHolderBatchSize,
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 $langObj = Language
::factory( $lang );
355 $settings['wgContLang'] = $langObj;
356 $settings['wgLang'] = $langObj;
358 $context = new RequestContext();
359 $settings['wgOut'] = $context->getOutput();
360 $settings['wgUser'] = $context->getUser();
361 $settings['wgRequest'] = $context->getRequest();
363 foreach ( $settings as $var => $val ) {
364 if ( array_key_exists( $var, $GLOBALS ) ) {
365 $this->savedGlobals
[$var] = $GLOBALS[$var];
368 $GLOBALS[$var] = $val;
371 MagicWord
::clearCache();
372 RepoGroup
::destroySingleton();
373 FileBackendGroup
::destroySingleton();
375 # Create dummy files in storage
376 $this->setupUploads();
378 # Publish the articles after we have the final language set
379 $this->publishTestArticles();
381 # The entries saved into RepoGroup cache with previous globals will be wrong.
382 RepoGroup
::destroySingleton();
383 FileBackendGroup
::destroySingleton();
384 MessageCache
::destroyInstance();
390 * Get an FS upload directory (only applies to FSFileBackend)
392 * @return String: the directory
394 protected function getUploadDir() {
395 if ( $this->keepUploads
) {
396 $dir = wfTempDir() . '/mwParser-images';
398 if ( is_dir( $dir ) ) {
402 $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
405 // wfDebug( "Creating upload directory $dir\n" );
406 if ( file_exists( $dir ) ) {
407 wfDebug( "Already exists!\n" );
416 * Create a dummy uploads directory which will contain a couple
417 * of files in order to pass existence tests.
419 * @return String: the directory
421 protected function setupUploads() {
424 $base = $this->getBaseDir();
425 $backend = RepoGroup
::singleton()->getLocalRepo()->getBackend();
426 $backend->prepare( array( 'dir' => "$base/local-public/3/3a" ) );
427 $backend->store( array(
428 'src' => "$IP/skins/monobook/headbg.jpg", 'dst' => "$base/local-public/3/3a/Foobar.jpg"
430 $backend->prepare( array( 'dir' => "$base/local-public/e/ea" ) );
431 $backend->store( array(
432 'src' => "$IP/skins/monobook/wiki.png", 'dst' => "$base/local-public/e/ea/Thumb.png"
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/e/ea/Thumb.png",
485 "$base/local-public/0/09/Bad.jpg",
487 "$base/local-public/math/f/a/5/fa50b8b616463173474302ca3e63586b.png",
493 * Delete the specified files, if they exist.
494 * @param $files Array: full paths to files to delete.
496 private static function deleteFiles( $files ) {
497 $backend = RepoGroup
::singleton()->getLocalRepo()->getBackend();
498 foreach ( $files as $file ) {
499 $backend->delete( array( 'src' => $file ), array( 'force' => 1 ) );
501 foreach ( $files as $file ) {
503 while ( $tmp = FileBackend
::parentStoragePath( $tmp ) ) {
504 if ( !$backend->clean( array( 'dir' => $tmp ) )->isOK() ) {
511 protected function getBaseDir() {
512 return 'mwstore://local-backend';
515 public function parserTestProvider() {
516 if ( $this->file
=== false ) {
517 global $wgParserTestFiles;
518 $this->file
= $wgParserTestFiles[0];
521 return new TestFileIterator( $this->file
, $this );
525 * Set the file from whose tests will be run by this instance
527 public function setParserTestFile( $filename ) {
528 $this->file
= $filename;
533 * @dataProvider parserTestProvider
535 public function testParserTest( $desc, $input, $result, $opts, $config ) {
536 if ( $this->regex
!= '' && !preg_match( '/' . $this->regex
. '/', $desc ) ) {
537 $this->assertTrue( true ); // XXX: don't flood output with "test made no assertions"
538 //$this->markTestSkipped( 'Filtered out by the user' );
542 if ( !$this->isWikitextNS( NS_MAIN
) ) {
543 // parser tests frequently assume that the main namespace contains wikitext.
544 // @todo: When setting up pages, force the content model. Only skip if
545 // $wgtContentModelUseDB is false.
546 $this->markTestSkipped( "Main namespace does not support wikitext,"
547 . "skipping parser test: $desc" );
550 wfDebug( "Running parser test: $desc\n" );
552 $opts = $this->parseOptions( $opts );
553 $context = $this->setupGlobals( $opts, $config );
555 $user = $context->getUser();
556 $options = ParserOptions
::newFromContext( $context );
558 if ( isset( $opts['title'] ) ) {
559 $titleText = $opts['title'];
561 $titleText = 'Parser test';
564 $local = isset( $opts['local'] );
565 $preprocessor = isset( $opts['preprocessor'] ) ?
$opts['preprocessor'] : null;
566 $parser = $this->getParser( $preprocessor );
568 $title = Title
::newFromText( $titleText );
570 if ( isset( $opts['pst'] ) ) {
571 $out = $parser->preSaveTransform( $input, $title, $user, $options );
572 } elseif ( isset( $opts['msg'] ) ) {
573 $out = $parser->transformMsg( $input, $options, $title );
574 } elseif ( isset( $opts['section'] ) ) {
575 $section = $opts['section'];
576 $out = $parser->getSection( $input, $section );
577 } elseif ( isset( $opts['replace'] ) ) {
578 $section = $opts['replace'][0];
579 $replace = $opts['replace'][1];
580 $out = $parser->replaceSection( $input, $section, $replace );
581 } elseif ( isset( $opts['comment'] ) ) {
582 $out = Linker
::formatComment( $input, $title, $local );
583 } elseif ( isset( $opts['preload'] ) ) {
584 $out = $parser->getPreloadText( $input, $title, $options );
586 $output = $parser->parse( $input, $title, $options, true, true, 1337 );
587 $out = $output->getText();
589 if ( isset( $opts['showtitle'] ) ) {
590 if ( $output->getTitleText() ) {
591 $title = $output->getTitleText();
594 $out = "$title\n$out";
597 if ( isset( $opts['ill'] ) ) {
598 $out = $this->tidy( implode( ' ', $output->getLanguageLinks() ) );
599 } elseif ( isset( $opts['cat'] ) ) {
600 $outputPage = $context->getOutput();
601 $outputPage->addCategoryLinks( $output->getCategories() );
602 $cats = $outputPage->getCategoryLinks();
604 if ( isset( $cats['normal'] ) ) {
605 $out = $this->tidy( implode( ' ', $cats['normal'] ) );
610 $parser->mPreprocessor
= null;
612 $result = $this->tidy( $result );
615 $this->teardownGlobals();
617 $this->assertEquals( $result, $out, $desc );
621 * Run a fuzz test series
622 * Draw input from a set of test files
624 * @todo fixme Needs some work to not eat memory until the world explodes
628 function testFuzzTests() {
629 global $wgParserTestFiles;
631 $files = $wgParserTestFiles;
633 if ( $this->getCliArg( 'file=' ) ) {
634 $files = array( $this->getCliArg( 'file=' ) );
637 $dict = $this->getFuzzInput( $files );
638 $dictSize = strlen( $dict );
639 $logMaxLength = log( $this->maxFuzzTestLength
);
641 ini_set( 'memory_limit', $this->memoryLimit
* 1048576 );
644 $opts = ParserOptions
::newFromUser( $user );
645 $title = Title
::makeTitle( NS_MAIN
, 'Parser_test' );
651 // Generate test input
652 mt_srand( ++
$this->fuzzSeed
);
653 $totalLength = mt_rand( 1, $this->maxFuzzTestLength
);
656 while ( strlen( $input ) < $totalLength ) {
657 $logHairLength = mt_rand( 0, 1000000 ) / 1000000 * $logMaxLength;
658 $hairLength = min( intval( exp( $logHairLength ) ), $dictSize );
659 $offset = mt_rand( 0, $dictSize - $hairLength );
660 $input .= substr( $dict, $offset, $hairLength );
663 $this->setupGlobals();
664 $parser = $this->getParser();
668 $parser->parse( $input, $title, $opts );
669 $this->assertTrue( true, "Test $id, fuzz seed {$this->fuzzSeed}" );
670 } catch ( Exception
$exception ) {
671 $input_dump = sprintf( "string(%d) \"%s\"\n", strlen( $input ), $input );
673 $this->assertTrue( false, "Test $id, fuzz seed {$this->fuzzSeed}. \n\nInput: $input_dump\n\nError: {$exception->getMessage()}\n\nBacktrace: {$exception->getTraceAsString()}" );
676 $this->teardownGlobals();
677 $parser->__destruct();
679 if ( $id %
100 == 0 ) {
680 $usage = intval( memory_get_usage( true ) / $this->memoryLimit
/ 1048576 * 100 );
681 //echo "{$this->fuzzSeed}: $numSuccess/$numTotal (mem: $usage%)\n";
683 $ret = "Out of memory:\n";
684 $memStats = $this->getMemoryBreakdown();
686 foreach ( $memStats as $name => $usage ) {
687 $ret .= "$name: $usage\n";
690 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] );
804 //Various "cleanup" functions
807 * Run the "tidy" command on text if the $wgUseTidy
810 * @param $text String: the text to tidy
813 protected function tidy( $text ) {
817 $text = MWTidy
::tidy( $text );
824 * Remove last character if it is a newline
826 public function removeEndingNewline( $s ) {
827 if ( substr( $s, -1 ) === "\n" ) {
828 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 );
892 protected function cleanupOption( $opt ) {
893 if ( substr( $opt, 0, 1 ) == '"' ) {
894 return substr( $opt, 1, -1 );
897 if ( substr( $opt, 0, 2 ) == '[[' ) {
898 return substr( $opt, 2, -2 );
905 * Use a regex to find out the value of an option
906 * @param $key String: name of option val to retrieve
907 * @param $opts Options array to look in
908 * @param $default Mixed: default value returned if not found
910 protected static function getOptionValue( $key, $opts, $default ) {
911 $key = strtolower( $key );
913 if ( isset( $opts[$key] ) ) {