3 require_once( dirname( __FILE__
) . '/NewParserHelpers.php' );
8 class NewParserTest
extends MediaWikiTestCase
{
11 public $keepUploads = false;
12 public $runDisabled = false;
14 public $showProgress = true;
15 public $savedGlobals = array();
16 public $hooks = array();
17 public $functionHooks = array();
21 $wgContLang = Language
::factory( 'en' );
26 if ( $this->getCliArg( 'regex=' ) ) {
27 $this->regex
= $this->getCliArg( 'regex=' );
33 $this->keepUploads
= $this->getCliArg( 'keep-uploads' );
37 global $wgParser, $wgParserConf, $IP, $messageMemc, $wgMemc, $wgDeferredUpdateList,
38 $wgUser, $wgLang, $wgOut, $wgRequest, $wgStyleDirectory, $wgEnableParserCache,
39 $wgMessageCache, $wgUseDatabaseMessages, $wgMsgCacheExpiry, $parserMemc,
40 $wgNamespaceAliases, $wgNamespaceProtection, $wgLocalFileRepo,
41 $wgThumbnailScriptPath, $wgScriptPath,
42 $wgArticlePath, $wgStyleSheetPath, $wgScript, $wgStylePath;
44 $wgScript = '/index.php';
46 $wgArticlePath = '/wiki/$1';
47 $wgStyleSheetPath = '/skins';
48 $wgStylePath = '/skins';
49 $wgThumbnailScriptPath = false;
50 $wgLocalFileRepo = array(
51 'class' => 'LocalRepo',
53 'directory' => wfTempDir() . '/test-repo',
54 'url' => 'http://example.com/images',
55 'deletedDir' => wfTempDir() . '/test-repo/delete',
57 'transformVia404' => false,
59 $wgNamespaceProtection[NS_MEDIAWIKI
] = 'editinterface';
60 $wgNamespaceAliases['Image'] = NS_FILE
;
61 $wgNamespaceAliases['Image_talk'] = NS_FILE_TALK
;
64 $wgEnableParserCache = false;
65 $wgDeferredUpdateList = array();
66 $wgMemc = &wfGetMainCache();
67 $messageMemc = &wfGetMessageCacheStorage();
68 $parserMemc = &wfGetParserCacheStorage();
70 // $wgContLang = new StubContLang;
72 $wgLang = new StubUserLang
;
73 $wgOut = new StubObject( 'wgOut', 'OutputPage' );
74 $wgParser = new StubObject( 'wgParser', $wgParserConf['class'], array( $wgParserConf ) );
75 $wgRequest = new WebRequest
;
77 $wgMessageCache = new StubObject( 'wgMessageCache', 'MessageCache',
78 array( $messageMemc, $wgUseDatabaseMessages,
79 $wgMsgCacheExpiry ) );
80 if ( $wgStyleDirectory === false ) {
81 $wgStyleDirectory = "$IP/skins";
87 * Set up the global variables for a consistent environment for each test.
88 * Ideally this should replace the global configuration entirely.
90 protected function setupGlobals( $opts = '', $config = '' ) {
91 # Find out values for some special options.
93 self
::getOptionValue( 'language', $opts, 'en' );
95 self
::getOptionValue( 'variant', $opts, false );
97 self
::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
98 $linkHolderBatchSize =
99 self
::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
102 'wgServer' => 'http://Britney-Spears',
103 'wgScript' => '/index.php',
104 'wgScriptPath' => '/',
105 'wgArticlePath' => '/wiki/$1',
106 'wgActionPaths' => array(),
107 'wgLocalFileRepo' => array(
108 'class' => 'LocalRepo',
110 'directory' => $this->uploadDir
,
111 'url' => 'http://example.com/images',
113 'transformVia404' => false,
115 'wgEnableUploads' => self
::getOptionValue( 'wgEnableUploads', $opts, true ),
116 'wgStylePath' => '/skins',
117 'wgStyleSheetPath' => '/skins',
118 'wgSitename' => 'MediaWiki',
119 'wgLanguageCode' => $lang,
120 'wgDBprefix' => $this->db
->getType() != 'oracle' ?
'unittest_' : 'ut_',
121 'wgRawHtml' => isset( $opts['rawhtml'] ),
123 'wgContLang' => null,
124 'wgNamespacesWithSubpages' => array( 0 => isset( $opts['subpage'] ) ),
125 'wgMaxTocLevel' => $maxtoclevel,
126 'wgCapitalLinks' => true,
127 'wgNoFollowLinks' => true,
128 'wgNoFollowDomainExceptions' => array(),
129 'wgThumbnailScriptPath' => false,
130 'wgUseImageResize' => false,
131 'wgUseTeX' => isset( $opts['math'] ),
132 'wgMathDirectory' => $this->uploadDir
. '/math',
133 'wgLocaltimezone' => 'UTC',
134 'wgAllowExternalImages' => true,
135 'wgUseTidy' => false,
136 'wgDefaultLanguageVariant' => $variant,
137 'wgVariantArticlePath' => false,
138 'wgGroupPermissions' => array( '*' => array(
139 'createaccount' => true,
142 'createpage' => true,
143 'createtalk' => true,
145 'wgNamespaceProtection' => array( NS_MEDIAWIKI
=> 'editinterface' ),
146 'wgDefaultExternalStore' => array(),
147 'wgForeignFileRepos' => array(),
148 'wgLinkHolderBatchSize' => $linkHolderBatchSize,
149 'wgExperimentalHtmlIds' => false,
150 'wgExternalLinkTarget' => false,
151 'wgAlwaysUseTidy' => false,
153 'wgWellFormedXml' => true,
154 'wgAllowMicrodataAttributes' => true,
155 'wgAdaptiveMessageCache' => true
159 $configLines = explode( "\n", $config );
161 foreach ( $configLines as $line ) {
162 list( $var, $value ) = explode( '=', $line, 2 );
164 $settings[$var] = eval( "return $value;" ); //???
168 $this->savedGlobals
= array();
170 foreach ( $settings as $var => $val ) {
171 if ( array_key_exists( $var, $GLOBALS ) ) {
172 $this->savedGlobals
[$var] = $GLOBALS[$var];
175 $GLOBALS[$var] = $val;
178 $langObj = Language
::factory( $lang );
179 $GLOBALS['wgLang'] = $langObj;
180 $GLOBALS['wgContLang'] = $langObj;
181 $GLOBALS['wgMemc'] = new FakeMemCachedClient
;
182 $GLOBALS['wgOut'] = new OutputPage
;
186 $wgHooks['ParserTestParser'][] = 'ParserTestParserHook::setup';
187 $wgHooks['ParserTestParser'][] = 'ParserTestStaticParserHook::setup';
188 $wgHooks['ParserGetVariableValueTs'][] = 'ParserTest::getFakeTimestamp';
190 MagicWord
::clearCache();
193 $wgUser = new User();
197 * Restore default values and perform any necessary clean-up
198 * after each test runs.
200 protected function teardownGlobals() {
201 RepoGroup
::destroySingleton();
202 LinkCache
::singleton()->clear();
204 foreach ( $this->savedGlobals
as $var => $val ) {
205 $GLOBALS[$var] = $val;
209 function addDBData() {
210 # Hack: insert a few Wikipedia in-project interwiki prefixes,
211 # for testing inter-language links
212 $this->db
->insert( 'interwiki', array(
213 array( 'iw_prefix' => 'wikipedia',
214 'iw_url' => 'http://en.wikipedia.org/wiki/$1',
218 array( 'iw_prefix' => 'meatball',
219 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
223 array( 'iw_prefix' => 'zh',
224 'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
228 array( 'iw_prefix' => 'es',
229 'iw_url' => 'http://es.wikipedia.org/wiki/$1',
233 array( 'iw_prefix' => 'fr',
234 'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
238 array( 'iw_prefix' => 'ru',
239 'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
246 # Update certain things in site_stats
247 $this->db
->insert( 'site_stats', array( 'ss_row_id' => 1, 'ss_images' => 2, 'ss_good_articles' => 1 ) );
249 # Reinitialise the LocalisationCache to match the database state
250 Language
::getLocalisationCache()->unloadAll();
252 # Make a new message cache
253 global $wgMessageCache, $wgMemc;
254 $wgMessageCache = new MessageCache( $wgMemc, true, 3600 );
256 $this->uploadDir
= $this->setupUploadDir();
258 $user = User
::newFromId( 0 );
260 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Foobar.jpg' ) );
261 $image->recordUpload2( '', 'Upload of some lame file', 'Some lame file', array(
266 'media_type' => MEDIATYPE_BITMAP
,
267 'mime' => 'image/jpeg',
268 'metadata' => serialize( array() ),
269 'sha1' => wfBaseConvert( '', 16, 36, 31 ),
271 ), $this->db
->timestamp( '20010115123500' ), $user );
273 # This image will be blacklisted in [[MediaWiki:Bad image list]]
274 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Bad.jpg' ) );
275 $image->recordUpload2( '', 'zomgnotcensored', 'Borderline image', array(
280 'media_type' => MEDIATYPE_BITMAP
,
281 'mime' => 'image/jpeg',
282 'metadata' => serialize( array() ),
283 'sha1' => wfBaseConvert( '', 16, 36, 31 ),
285 ), $this->db
->timestamp( '20010115123500' ), $user );
289 public function testParserTests() {
291 global $wgParserTestFiles;
293 $files = $wgParserTestFiles;
295 if( $this->getCliArg( 'file=' ) ) {
296 $files = array( $this->getCliArg( 'file=' ) );
299 foreach( $files as $file ) {
301 $iter = new ParserTestFileIterator( $file, $this );
303 foreach ( $iter as $t ) {
305 $result = $this->doRunTest( $t['test'], $t['input'], $t['result'], $t['options'], $t['config'] );
307 //$this->recorder->record( $t['test'], $result );
317 * Run a given wikitext input through a freshly-constructed wiki parser,
318 * and compare the output against the expected results.
319 * Prints status and explanatory messages to stdout.
321 * @param $desc String: test's description
322 * @param $input String: wikitext to try rendering
323 * @param $result String: result to output
324 * @param $opts Array: test's options
325 * @param $config String: overrides for global variables, one per line
328 protected function doRunTest( $desc, $input, $result, $opts, $config ) {
330 $opts = $this->parseOptions( $opts );
331 $this->setupGlobals( $opts, $config );
334 $options = ParserOptions
::newFromUser( $user );
336 if ( isset( $opts['title'] ) ) {
337 $titleText = $opts['title'];
340 $titleText = 'Parser test';
343 $local = isset( $opts['local'] );
344 $preprocessor = isset( $opts['preprocessor'] ) ?
$opts['preprocessor'] : null;
345 $parser = $this->getParser( $preprocessor );
346 $title = Title
::newFromText( $titleText );
348 if ( isset( $opts['pst'] ) ) {
349 $out = $parser->preSaveTransform( $input, $title, $user, $options );
350 } elseif ( isset( $opts['msg'] ) ) {
351 $out = $parser->transformMsg( $input, $options );
352 } elseif ( isset( $opts['section'] ) ) {
353 $section = $opts['section'];
354 $out = $parser->getSection( $input, $section );
355 } elseif ( isset( $opts['replace'] ) ) {
356 $section = $opts['replace'][0];
357 $replace = $opts['replace'][1];
358 $out = $parser->replaceSection( $input, $section, $replace );
359 } elseif ( isset( $opts['comment'] ) ) {
360 $linker = $user->getSkin();
361 $out = $linker->formatComment( $input, $title, $local );
362 } elseif ( isset( $opts['preload'] ) ) {
363 $out = $parser->getpreloadText( $input, $title, $options );
365 $output = $parser->parse( $input, $title, $options, true, true, 1337 );
366 $out = $output->getText();
368 if ( isset( $opts['showtitle'] ) ) {
369 if ( $output->getTitleText() ) {
370 $title = $output->getTitleText();
373 $out = "$title\n$out";
376 if ( isset( $opts['ill'] ) ) {
377 $out = $this->tidy( implode( ' ', $output->getLanguageLinks() ) );
378 } elseif ( isset( $opts['cat'] ) ) {
381 $wgOut->addCategoryLinks( $output->getCategories() );
382 $cats = $wgOut->getCategoryLinks();
384 if ( isset( $cats['normal'] ) ) {
385 $out = $this->tidy( implode( ' ', $cats['normal'] ) );
391 $result = $this->tidy( $result );
394 $this->teardownGlobals();
396 $this->assertEquals( $result, $out, $desc );
400 * Get a Parser object
402 function getParser( $preprocessor = null ) {
403 global $wgParserConf;
405 $class = $wgParserConf['class'];
406 $parser = new $class( array( 'preprocessorClass' => $preprocessor ) +
$wgParserConf );
408 foreach ( $this->hooks
as $tag => $callback ) {
409 $parser->setHook( $tag, $callback );
412 foreach ( $this->functionHooks
as $tag => $bits ) {
413 list( $callback, $flags ) = $bits;
414 $parser->setFunctionHook( $tag, $callback, $flags );
417 wfRunHooks( 'ParserTestParser', array( &$parser ) );
423 * Run the "tidy" command on text if the $wgUseTidy
426 * @param $text String: the text to tidy
430 protected function tidy( $text ) {
434 $text = MWTidy
::tidy( $text );
442 * Create a dummy uploads directory which will contain a couple
443 * of files in order to pass existence tests.
445 * @return String: the directory
447 protected function setupUploadDir() {
450 if ( $this->keepUploads
) {
451 $dir = wfTempDir() . '/mwParser-images';
453 if ( is_dir( $dir ) ) {
457 $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
460 // wfDebug( "Creating upload directory $dir\n" );
461 if ( file_exists( $dir ) ) {
462 wfDebug( "Already exists!\n" );
466 wfMkdirParents( $dir . '/3/3a' );
467 copy( "$IP/skins/monobook/headbg.jpg", "$dir/3/3a/Foobar.jpg" );
468 wfMkdirParents( $dir . '/0/09' );
469 copy( "$IP/skins/monobook/headbg.jpg", "$dir/0/09/Bad.jpg" );
475 * Insert a temporary test article
476 * @param $name String: the title, including any prefix
477 * @param $text String: the article text
478 * @param $line Integer: the input line number, for reporting errors
480 public function addArticle( $name, $text, $line = 'unknown' ) {
481 global $wgCapitalLinks;
483 $text = $this->removeEndingNewline($text);
485 $oldCapitalLinks = $wgCapitalLinks;
486 $wgCapitalLinks = true; // We only need this from SetupGlobals() See r70917#c8637
488 $name = $this->removeEndingNewline( $name );
489 $title = Title
::newFromText( $name );
491 if ( is_null( $title ) ) {
492 wfDie( "invalid title ('$name' => '$title') at line $line\n" );
495 $aid = $title->getArticleID( Title
::GAID_FOR_UPDATE
);
498 debug_print_backtrace();
499 wfDie( "duplicate article '$name' at line $line\n" );
502 $art = new Article( $title );
503 $art->doEdit( $text, '', EDIT_NEW
);
505 $wgCapitalLinks = $oldCapitalLinks;
509 * Remove last character if it is a newline
511 public function removeEndingNewline( $s ) {
512 if ( substr( $s, -1 ) === "\n" ) {
513 return substr( $s, 0, -1 );
521 * Steal a callback function from the primary parser, save it for
522 * application to our scary parser. If the hook is not installed,
523 * abort processing of this file.
525 * @param $name String
526 * @return Bool true if tag hook is present
528 public function requireHook( $name ) {
531 $wgParser->firstCallInit( ); // make sure hooks are loaded.
533 if ( isset( $wgParser->mTagHooks
[$name] ) ) {
534 $this->hooks
[$name] = $wgParser->mTagHooks
[$name];
536 echo " This test suite requires the '$name' hook extension, skipping.\n";
543 protected function parseOptions( $instring ) {
549 // foo=bar,"baz quux"
573 \[\[[^]]*\]\] # Link target
581 if ( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER
) ) {
582 foreach ( $matches as $bits ) {
583 array_shift( $bits );
584 $key = strtolower( array_shift( $bits ) );
585 if ( count( $bits ) == 0 ) {
587 } elseif ( count( $bits ) == 1 ) {
588 $opts[$key] = $this->cleanupOption( array_shift( $bits ) );
591 $opts[$key] = array_map( array( $this, 'cleanupOption' ), $bits );
598 protected function cleanupOption( $opt ) {
599 if ( substr( $opt, 0, 1 ) == '"' ) {
600 return substr( $opt, 1, -1 );
603 if ( substr( $opt, 0, 2 ) == '[[' ) {
604 return substr( $opt, 2, -2 );
610 * Use a regex to find out the value of an option
611 * @param $key String: name of option val to retrieve
612 * @param $opts Options array to look in
613 * @param $default Mixed: default value returned if not found
615 protected static function getOptionValue( $key, $opts, $default ) {
616 $key = strtolower( $key );
618 if ( isset( $opts[$key] ) ) {