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['wgWellFormedXml'] = true;
87 $tmpGlobals['wgAllowMicrodataAttributes'] = true;
88 $tmpGlobals['wgExperimentalHtmlIds'] = false;
89 $tmpGlobals['wgAdaptiveMessageCache'] = true;
90 $tmpGlobals['wgUseDatabaseMessages'] = true;
91 $tmpGlobals['wgLocaltimezone'] = 'UTC';
92 $tmpGlobals['wgDeferredUpdateList'] = array();
93 $tmpGlobals['wgGroupPermissions'] = array(
95 'createaccount' => true,
101 $tmpGlobals['wgNamespaceProtection'] = array( NS_MEDIAWIKI
=> 'editinterface' );
103 $tmpGlobals['wgParser'] = new StubObject( 'wgParser', $GLOBALS['wgParserConf']['class'], array( $GLOBALS['wgParserConf'] ) );
105 if ( $GLOBALS['wgStyleDirectory'] === false ) {
106 $tmpGlobals['wgStyleDirectory'] = "$IP/skins";
109 # Replace all media handlers with a mock. We do not need to generate
110 # actual thumbnails to do parser testing, we only care about receiving
111 # a ThumbnailImage properly initialized.
112 global $wgMediaHandlers;
113 foreach( $wgMediaHandlers as $type => $handler ) {
114 $tmpGlobals['wgMediaHandlers'][$type] = 'MockBitmapHandler';
117 $tmpHooks = $wgHooks;
118 $tmpHooks['ParserTestParser'][] = 'ParserTestParserHook::setup';
119 $tmpHooks['ParserGetVariableValueTs'][] = 'ParserTest::getFakeTimestamp';
120 $tmpGlobals['wgHooks'] = $tmpHooks;
122 $this->setMwGlobals( $tmpGlobals );
124 $this->savedWeirdGlobals
['image_alias'] = $wgNamespaceAliases['Image'];
125 $this->savedWeirdGlobals
['image_talk_alias'] = $wgNamespaceAliases['Image_talk'];
127 $wgNamespaceAliases['Image'] = NS_FILE
;
128 $wgNamespaceAliases['Image_talk'] = NS_FILE_TALK
;
131 protected function tearDown() {
132 global $wgNamespaceAliases;
134 $wgNamespaceAliases['Image'] = $this->savedWeirdGlobals
['image_alias'];
135 $wgNamespaceAliases['Image_talk'] = $this->savedWeirdGlobals
['image_talk_alias'];
138 RepoGroup
::destroySingleton();
139 FileBackendGroup
::destroySingleton();
141 // Remove temporary pages from the link cache
142 LinkCache
::singleton()->clear();
144 // Restore message cache (temporary pages and $wgUseDatabaseMessages)
145 MessageCache
::destroyInstance();
150 function addDBData() {
151 $this->tablesUsed
[] = 'site_stats';
152 $this->tablesUsed
[] = 'interwiki';
153 # disabled for performance
154 #$this->tablesUsed[] = 'image';
156 # Hack: insert a few Wikipedia in-project interwiki prefixes,
157 # for testing inter-language links
158 $this->db
->insert( 'interwiki', array(
159 array( 'iw_prefix' => 'wikipedia',
160 'iw_url' => 'http://en.wikipedia.org/wiki/$1',
164 array( 'iw_prefix' => 'meatball',
165 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
169 array( 'iw_prefix' => 'zh',
170 'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
174 array( 'iw_prefix' => 'es',
175 'iw_url' => 'http://es.wikipedia.org/wiki/$1',
179 array( 'iw_prefix' => 'fr',
180 'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
184 array( 'iw_prefix' => 'ru',
185 'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
190 * @todo Fixme! Why are we inserting duplicate data here? Shouldn't
191 * need this IGNORE or shouldn't need the insert at all.
193 ), __METHOD__
, array( 'IGNORE' )
196 # Update certain things in site_stats
197 $this->db
->insert( 'site_stats',
198 array( 'ss_row_id' => 1, 'ss_images' => 2, 'ss_good_articles' => 1 ),
202 $user = User
::newFromId( 0 );
203 LinkCache
::singleton()->clear(); # Avoids the odd failure at creating the nullRevision
205 # Upload DB table entries for files.
206 # We will upload the actual files later. Note that if anything causes LocalFile::load()
207 # to be triggered before then, it will break via maybeUpgrade() setting the fileExists
208 # member to false and storing it in cache.
209 # note that the size/width/height/bits/etc of the file
210 # are actually set by inspecting the file itself; the arguments
211 # to recordUpload2 have no effect. That said, we try to make things
212 # match up so it is less confusing to readers of the code & tests.
213 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Foobar.jpg' ) );
214 if ( !$this->db
->selectField( 'image', '1', array( 'img_name' => $image->getName() ) ) ) {
215 $image->recordUpload2(
217 'Upload of some lame file',
224 'media_type' => MEDIATYPE_BITMAP
,
225 'mime' => 'image/jpeg',
226 'metadata' => serialize( array() ),
227 'sha1' => wfBaseConvert( '1', 16, 36, 31 ),
228 'fileExists' => true ),
229 $this->db
->timestamp( '20010115123500' ), $user
233 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Thumb.png' ) );
234 if ( !$this->db
->selectField( 'image', '1', array( 'img_name' => $image->getName() ) ) ) {
235 $image->recordUpload2(
237 'Upload of some lame thumbnail',
238 'Some lame thumbnail',
244 'media_type' => MEDIATYPE_BITMAP
,
245 'mime' => 'image/png',
246 'metadata' => serialize( array() ),
247 'sha1' => wfBaseConvert( '2', 16, 36, 31 ),
248 'fileExists' => true ),
249 $this->db
->timestamp( '20130225203040' ), $user
253 # This image will be blacklisted in [[MediaWiki:Bad image list]]
254 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Bad.jpg' ) );
255 if ( !$this->db
->selectField( 'image', '1', array( 'img_name' => $image->getName() ) ) ) {
256 $image->recordUpload2(
265 'media_type' => MEDIATYPE_BITMAP
,
266 'mime' => 'image/jpeg',
267 'metadata' => serialize( array() ),
268 'sha1' => wfBaseConvert( '3', 16, 36, 31 ),
269 'fileExists' => true ),
270 $this->db
->timestamp( '20010115123500' ), $user
275 //ParserTest setup/teardown functions
278 * Set up the global variables for a consistent environment for each test.
279 * Ideally this should replace the global configuration entirely.
281 protected function setupGlobals( $opts = array(), $config = '' ) {
282 global $wgFileBackends;
283 # Find out values for some special options.
285 self
::getOptionValue( 'language', $opts, 'en' );
287 self
::getOptionValue( 'variant', $opts, false );
289 self
::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
290 $linkHolderBatchSize =
291 self
::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
293 $uploadDir = $this->getUploadDir();
294 if ( $this->getCliArg( 'use-filebackend=' ) ) {
295 if ( self
::$backendToUse ) {
296 $backend = self
::$backendToUse;
298 $name = $this->getCliArg( 'use-filebackend=' );
299 $useConfig = array();
300 foreach ( $wgFileBackends as $conf ) {
301 if ( $conf['name'] == $name ) {
305 $useConfig['name'] = 'local-backend'; // swap name
306 $class = $conf['class'];
307 self
::$backendToUse = new $class( $useConfig );
308 $backend = self
::$backendToUse;
311 # Replace with a mock. We do not care about generating real
312 # files on the filesystem, just need to expose the file
314 $backend = new MockFileBackend( array(
315 'name' => 'local-backend',
316 'lockManager' => 'nullLockManager',
317 'containerPaths' => array(
318 'local-public' => "$uploadDir",
319 'local-thumb' => "$uploadDir/thumb",
325 'wgLocalFileRepo' => array(
326 'class' => 'LocalRepo',
328 'url' => 'http://example.com/images',
330 'transformVia404' => false,
331 'backend' => $backend
333 'wgEnableUploads' => self
::getOptionValue( 'wgEnableUploads', $opts, true ),
334 'wgLanguageCode' => $lang,
335 'wgDBprefix' => $this->db
->getType() != 'oracle' ?
'unittest_' : 'ut_',
336 'wgRawHtml' => isset( $opts['rawhtml'] ),
337 'wgNamespacesWithSubpages' => array( NS_MAIN
=> isset( $opts['subpage'] ) ),
338 'wgMaxTocLevel' => $maxtoclevel,
339 'wgUseTeX' => isset( $opts['math'] ),
340 'wgMathDirectory' => $uploadDir . '/math',
341 'wgDefaultLanguageVariant' => $variant,
342 'wgLinkHolderBatchSize' => $linkHolderBatchSize,
346 $configLines = explode( "\n", $config );
348 foreach ( $configLines as $line ) {
349 list( $var, $value ) = explode( '=', $line, 2 );
351 $settings[$var] = eval( "return $value;" ); //???
355 $this->savedGlobals
= array();
358 wfRunHooks( 'ParserTestGlobals', array( &$settings ) );
360 $langObj = Language
::factory( $lang );
361 $settings['wgContLang'] = $langObj;
362 $settings['wgLang'] = $langObj;
364 $context = new RequestContext();
365 $settings['wgOut'] = $context->getOutput();
366 $settings['wgUser'] = $context->getUser();
367 $settings['wgRequest'] = $context->getRequest();
369 foreach ( $settings as $var => $val ) {
370 if ( array_key_exists( $var, $GLOBALS ) ) {
371 $this->savedGlobals
[$var] = $GLOBALS[$var];
374 $GLOBALS[$var] = $val;
377 MagicWord
::clearCache();
379 # The entries saved into RepoGroup cache with previous globals will be wrong.
380 RepoGroup
::destroySingleton();
381 FileBackendGroup
::destroySingleton();
383 # Create dummy files in storage
384 $this->setupUploads();
386 # Publish the articles after we have the final language set
387 $this->publishTestArticles();
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" );
421 * Create a dummy uploads directory which will contain a couple
422 * of files in order to pass existence tests.
424 * @return String: the directory
426 protected function setupUploads() {
429 $base = $this->getBaseDir();
430 $backend = RepoGroup
::singleton()->getLocalRepo()->getBackend();
431 $backend->prepare( array( 'dir' => "$base/local-public/3/3a" ) );
432 $backend->store( array(
433 'src' => "$IP/skins/monobook/headbg.jpg", 'dst' => "$base/local-public/3/3a/Foobar.jpg"
435 $backend->prepare( array( 'dir' => "$base/local-public/e/ea" ) );
436 $backend->store( array(
437 'src' => "$IP/skins/monobook/wiki.png", 'dst' => "$base/local-public/e/ea/Thumb.png"
439 $backend->prepare( array( 'dir' => "$base/local-public/0/09" ) );
440 $backend->store( array(
441 'src' => "$IP/skins/monobook/headbg.jpg", 'dst' => "$base/local-public/0/09/Bad.jpg"
446 * Restore default values and perform any necessary clean-up
447 * after each test runs.
449 protected function teardownGlobals() {
450 $this->teardownUploads();
452 foreach ( $this->savedGlobals
as $var => $val ) {
453 $GLOBALS[$var] = $val;
458 * Remove the dummy uploads directory
460 private function teardownUploads() {
461 if ( $this->keepUploads
) {
465 $backend = RepoGroup
::singleton()->getLocalRepo()->getBackend();
466 if( $backend instanceof MockFileBackend
) {
467 # In memory backend, so dont bother cleaning them up.
471 $base = $this->getBaseDir();
472 // delete the files first, then the dirs.
475 "$base/local-public/3/3a/Foobar.jpg",
476 "$base/local-thumb/3/3a/Foobar.jpg/180px-Foobar.jpg",
477 "$base/local-thumb/3/3a/Foobar.jpg/200px-Foobar.jpg",
478 "$base/local-thumb/3/3a/Foobar.jpg/640px-Foobar.jpg",
479 "$base/local-thumb/3/3a/Foobar.jpg/120px-Foobar.jpg",
480 "$base/local-thumb/3/3a/Foobar.jpg/1280px-Foobar.jpg",
481 "$base/local-thumb/3/3a/Foobar.jpg/20px-Foobar.jpg",
482 "$base/local-thumb/3/3a/Foobar.jpg/270px-Foobar.jpg",
483 "$base/local-thumb/3/3a/Foobar.jpg/300px-Foobar.jpg",
484 "$base/local-thumb/3/3a/Foobar.jpg/30px-Foobar.jpg",
485 "$base/local-thumb/3/3a/Foobar.jpg/360px-Foobar.jpg",
486 "$base/local-thumb/3/3a/Foobar.jpg/400px-Foobar.jpg",
487 "$base/local-thumb/3/3a/Foobar.jpg/40px-Foobar.jpg",
488 "$base/local-thumb/3/3a/Foobar.jpg/70px-Foobar.jpg",
489 "$base/local-thumb/3/3a/Foobar.jpg/960px-Foobar.jpg",
491 "$base/local-public/e/ea/Thumb.png",
493 "$base/local-public/0/09/Bad.jpg",
495 "$base/local-public/math/f/a/5/fa50b8b616463173474302ca3e63586b.png",
501 * Delete the specified files, if they exist.
502 * @param $files Array: full paths to files to delete.
504 private static function deleteFiles( $files ) {
505 $backend = RepoGroup
::singleton()->getLocalRepo()->getBackend();
506 foreach ( $files as $file ) {
507 $backend->delete( array( 'src' => $file ), array( 'force' => 1 ) );
509 foreach ( $files as $file ) {
511 while ( $tmp = FileBackend
::parentStoragePath( $tmp ) ) {
512 if ( !$backend->clean( array( 'dir' => $tmp ) )->isOK() ) {
519 protected function getBaseDir() {
520 return 'mwstore://local-backend';
523 public function parserTestProvider() {
524 if ( $this->file
=== false ) {
525 global $wgParserTestFiles;
526 $this->file
= $wgParserTestFiles[0];
529 return new TestFileIterator( $this->file
, $this );
533 * Set the file from whose tests will be run by this instance
535 public function setParserTestFile( $filename ) {
536 $this->file
= $filename;
541 * @dataProvider parserTestProvider
543 public function testParserTest( $desc, $input, $result, $opts, $config ) {
544 if ( $this->regex
!= '' && !preg_match( '/' . $this->regex
. '/', $desc ) ) {
545 $this->assertTrue( true ); // XXX: don't flood output with "test made no assertions"
546 //$this->markTestSkipped( 'Filtered out by the user' );
550 if ( !$this->isWikitextNS( NS_MAIN
) ) {
551 // parser tests frequently assume that the main namespace contains wikitext.
552 // @todo When setting up pages, force the content model. Only skip if
553 // $wgtContentModelUseDB is false.
554 $this->markTestSkipped( "Main namespace does not support wikitext,"
555 . "skipping parser test: $desc" );
558 wfDebug( "Running parser test: $desc\n" );
560 $opts = $this->parseOptions( $opts );
561 $context = $this->setupGlobals( $opts, $config );
563 $user = $context->getUser();
564 $options = ParserOptions
::newFromContext( $context );
566 if ( isset( $opts['title'] ) ) {
567 $titleText = $opts['title'];
569 $titleText = 'Parser test';
572 $local = isset( $opts['local'] );
573 $preprocessor = isset( $opts['preprocessor'] ) ?
$opts['preprocessor'] : null;
574 $parser = $this->getParser( $preprocessor );
576 $title = Title
::newFromText( $titleText );
578 if ( isset( $opts['pst'] ) ) {
579 $out = $parser->preSaveTransform( $input, $title, $user, $options );
580 } elseif ( isset( $opts['msg'] ) ) {
581 $out = $parser->transformMsg( $input, $options, $title );
582 } elseif ( isset( $opts['section'] ) ) {
583 $section = $opts['section'];
584 $out = $parser->getSection( $input, $section );
585 } elseif ( isset( $opts['replace'] ) ) {
586 $section = $opts['replace'][0];
587 $replace = $opts['replace'][1];
588 $out = $parser->replaceSection( $input, $section, $replace );
589 } elseif ( isset( $opts['comment'] ) ) {
590 $out = Linker
::formatComment( $input, $title, $local );
591 } elseif ( isset( $opts['preload'] ) ) {
592 $out = $parser->getPreloadText( $input, $title, $options );
594 $output = $parser->parse( $input, $title, $options, true, true, 1337 );
595 $out = $output->getText();
597 if ( isset( $opts['showtitle'] ) ) {
598 if ( $output->getTitleText() ) {
599 $title = $output->getTitleText();
602 $out = "$title\n$out";
605 if ( isset( $opts['ill'] ) ) {
606 $out = $this->tidy( implode( ' ', $output->getLanguageLinks() ) );
607 } elseif ( isset( $opts['cat'] ) ) {
608 $outputPage = $context->getOutput();
609 $outputPage->addCategoryLinks( $output->getCategories() );
610 $cats = $outputPage->getCategoryLinks();
612 if ( isset( $cats['normal'] ) ) {
613 $out = $this->tidy( implode( ' ', $cats['normal'] ) );
618 $parser->mPreprocessor
= null;
620 $result = $this->tidy( $result );
623 $this->teardownGlobals();
625 $this->assertEquals( $result, $out, $desc );
629 * Run a fuzz test series
630 * Draw input from a set of test files
632 * @todo fixme Needs some work to not eat memory until the world explodes
636 function testFuzzTests() {
637 global $wgParserTestFiles;
639 $files = $wgParserTestFiles;
641 if ( $this->getCliArg( 'file=' ) ) {
642 $files = array( $this->getCliArg( 'file=' ) );
645 $dict = $this->getFuzzInput( $files );
646 $dictSize = strlen( $dict );
647 $logMaxLength = log( $this->maxFuzzTestLength
);
649 ini_set( 'memory_limit', $this->memoryLimit
* 1048576 );
652 $opts = ParserOptions
::newFromUser( $user );
653 $title = Title
::makeTitle( NS_MAIN
, 'Parser_test' );
659 // Generate test input
660 mt_srand( ++
$this->fuzzSeed
);
661 $totalLength = mt_rand( 1, $this->maxFuzzTestLength
);
664 while ( strlen( $input ) < $totalLength ) {
665 $logHairLength = mt_rand( 0, 1000000 ) / 1000000 * $logMaxLength;
666 $hairLength = min( intval( exp( $logHairLength ) ), $dictSize );
667 $offset = mt_rand( 0, $dictSize - $hairLength );
668 $input .= substr( $dict, $offset, $hairLength );
671 $this->setupGlobals();
672 $parser = $this->getParser();
676 $parser->parse( $input, $title, $opts );
677 $this->assertTrue( true, "Test $id, fuzz seed {$this->fuzzSeed}" );
678 } catch ( Exception
$exception ) {
679 $input_dump = sprintf( "string(%d) \"%s\"\n", strlen( $input ), $input );
681 $this->assertTrue( false, "Test $id, fuzz seed {$this->fuzzSeed}. \n\nInput: $input_dump\n\nError: {$exception->getMessage()}\n\nBacktrace: {$exception->getTraceAsString()}" );
684 $this->teardownGlobals();
685 $parser->__destruct();
687 if ( $id %
100 == 0 ) {
688 $usage = intval( memory_get_usage( true ) / $this->memoryLimit
/ 1048576 * 100 );
689 //echo "{$this->fuzzSeed}: $numSuccess/$numTotal (mem: $usage%)\n";
691 $ret = "Out of memory:\n";
692 $memStats = $this->getMemoryBreakdown();
694 foreach ( $memStats as $name => $usage ) {
695 $ret .= "$name: $usage\n";
698 throw new MWException( $ret );
706 //Various getter functions
709 * Get an input dictionary from a set of parser test files
711 function getFuzzInput( $filenames ) {
714 foreach ( $filenames as $filename ) {
715 $contents = file_get_contents( $filename );
716 preg_match_all( '/!!\s*input\n(.*?)\n!!\s*result/s', $contents, $matches );
718 foreach ( $matches[1] as $match ) {
719 $dict .= $match . "\n";
727 * Get a memory usage breakdown
729 function getMemoryBreakdown() {
732 foreach ( $GLOBALS as $name => $value ) {
733 $memStats['$' . $name] = strlen( serialize( $value ) );
736 $classes = get_declared_classes();
738 foreach ( $classes as $class ) {
739 $rc = new ReflectionClass( $class );
740 $props = $rc->getStaticProperties();
741 $memStats[$class] = strlen( serialize( $props ) );
742 $methods = $rc->getMethods();
744 foreach ( $methods as $method ) {
745 $memStats[$class] +
= strlen( serialize( $method->getStaticVariables() ) );
749 $functions = get_defined_functions();
751 foreach ( $functions['user'] as $function ) {
752 $rf = new ReflectionFunction( $function );
753 $memStats["$function()"] = strlen( serialize( $rf->getStaticVariables() ) );
762 * Get a Parser object
764 function getParser( $preprocessor = null ) {
765 global $wgParserConf;
767 $class = $wgParserConf['class'];
768 $parser = new $class( array( 'preprocessorClass' => $preprocessor ) +
$wgParserConf );
770 wfRunHooks( 'ParserTestParser', array( &$parser ) );
775 //Various action functions
777 public function addArticle( $name, $text, $line ) {
778 self
::$articles[$name] = array( $text, $line );
781 public function publishTestArticles() {
782 if ( empty( self
::$articles ) ) {
786 foreach ( self
::$articles as $name => $info ) {
787 list( $text, $line ) = $info;
788 ParserTest
::addArticle( $name, $text, $line, 'ignoreduplicate' );
793 * Steal a callback function from the primary parser, save it for
794 * application to our scary parser. If the hook is not installed,
795 * abort processing of this file.
797 * @param $name String
798 * @return Bool true if tag hook is present
800 public function requireHook( $name ) {
802 $wgParser->firstCallInit(); // make sure hooks are loaded.
803 return isset( $wgParser->mTagHooks
[$name] );
806 public function requireFunctionHook( $name ) {
808 $wgParser->firstCallInit(); // make sure hooks are loaded.
809 return isset( $wgParser->mFunctionHooks
[$name] );
812 //Various "cleanup" functions
815 * Run the "tidy" command on text if the $wgUseTidy
818 * @param $text String: the text to tidy
821 protected function tidy( $text ) {
825 $text = MWTidy
::tidy( $text );
832 * Remove last character if it is a newline
834 public function removeEndingNewline( $s ) {
835 if ( substr( $s, -1 ) === "\n" ) {
836 return substr( $s, 0, -1 );
842 //Test options parser functions
844 protected function parseOptions( $instring ) {
850 // foo=bar,"baz quux"
874 \[\[[^]]*\]\] # Link target
882 if ( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER
) ) {
883 foreach ( $matches as $bits ) {
884 array_shift( $bits );
885 $key = strtolower( array_shift( $bits ) );
886 if ( count( $bits ) == 0 ) {
888 } elseif ( count( $bits ) == 1 ) {
889 $opts[$key] = $this->cleanupOption( array_shift( $bits ) );
892 $opts[$key] = array_map( array( $this, 'cleanupOption' ), $bits );
900 protected function cleanupOption( $opt ) {
901 if ( substr( $opt, 0, 1 ) == '"' ) {
902 return substr( $opt, 1, -1 );
905 if ( substr( $opt, 0, 2 ) == '[[' ) {
906 return substr( $opt, 2, -2 );
913 * Use a regex to find out the value of an option
914 * @param $key String: name of option val to retrieve
915 * @param $opts Options array to look in
916 * @param $default Mixed: default value returned if not found
918 protected static function getOptionValue( $key, $opts, $default ) {
919 $key = strtolower( $key );
921 if ( isset( $opts[$key] ) ) {