Add parsertest specific help to PHPUnit.php
[lhc/web/wiklou.git] / tests / phpunit / includes / parser / NewParserTest.php
1 <?php
2
3 require_once( dirname( __FILE__ ) . '/NewParserHelpers.php' );
4
5 /**
6 * @group Database
7 */
8 class NewParserTest extends MediaWikiTestCase {
9
10 public $uploadDir;
11 public $keepUploads = false;
12 public $runDisabled = false;
13 public $regex = '';
14 public $showProgress = true;
15 public $savedGlobals = array();
16 public $hooks = array();
17 public $functionHooks = array();
18
19 function setUp() {
20 global $wgContLang;
21 $wgContLang = Language::factory( 'en' );
22
23
24
25 //Setup CLI arguments
26 if ( $this->getCliArg( 'regex=' ) ) {
27 $this->regex = $this->getCliArg( 'regex=' );
28 } else {
29 # Matches anything
30 $this->regex = '';
31 }
32
33 $this->keepUploads = $this->getCliArg( 'keep-uploads' );
34
35
36
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;
43
44 $wgScript = '/index.php';
45 $wgScriptPath = '/';
46 $wgArticlePath = '/wiki/$1';
47 $wgStyleSheetPath = '/skins';
48 $wgStylePath = '/skins';
49 $wgThumbnailScriptPath = false;
50 $wgLocalFileRepo = array(
51 'class' => 'LocalRepo',
52 'name' => 'local',
53 'directory' => wfTempDir() . '/test-repo',
54 'url' => 'http://example.com/images',
55 'deletedDir' => wfTempDir() . '/test-repo/delete',
56 'hashLevels' => 2,
57 'transformVia404' => false,
58 );
59 $wgNamespaceProtection[NS_MEDIAWIKI] = 'editinterface';
60 $wgNamespaceAliases['Image'] = NS_FILE;
61 $wgNamespaceAliases['Image_talk'] = NS_FILE_TALK;
62
63
64 $wgEnableParserCache = false;
65 $wgDeferredUpdateList = array();
66 $wgMemc = &wfGetMainCache();
67 $messageMemc = &wfGetMessageCacheStorage();
68 $parserMemc = &wfGetParserCacheStorage();
69
70 // $wgContLang = new StubContLang;
71 $wgUser = new User;
72 $wgLang = new StubUserLang;
73 $wgOut = new StubObject( 'wgOut', 'OutputPage' );
74 $wgParser = new StubObject( 'wgParser', $wgParserConf['class'], array( $wgParserConf ) );
75 $wgRequest = new WebRequest;
76
77 $wgMessageCache = new StubObject( 'wgMessageCache', 'MessageCache',
78 array( $messageMemc, $wgUseDatabaseMessages,
79 $wgMsgCacheExpiry ) );
80 if ( $wgStyleDirectory === false ) {
81 $wgStyleDirectory = "$IP/skins";
82 }
83
84 }
85
86 /**
87 * Set up the global variables for a consistent environment for each test.
88 * Ideally this should replace the global configuration entirely.
89 */
90 protected function setupGlobals( $opts = '', $config = '' ) {
91 # Find out values for some special options.
92 $lang =
93 self::getOptionValue( 'language', $opts, 'en' );
94 $variant =
95 self::getOptionValue( 'variant', $opts, false );
96 $maxtoclevel =
97 self::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
98 $linkHolderBatchSize =
99 self::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
100
101 $settings = array(
102 'wgServer' => 'http://Britney-Spears',
103 'wgScript' => '/index.php',
104 'wgScriptPath' => '/',
105 'wgArticlePath' => '/wiki/$1',
106 'wgActionPaths' => array(),
107 'wgLocalFileRepo' => array(
108 'class' => 'LocalRepo',
109 'name' => 'local',
110 'directory' => $this->uploadDir,
111 'url' => 'http://example.com/images',
112 'hashLevels' => 2,
113 'transformVia404' => false,
114 ),
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'] ),
122 'wgLang' => null,
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,
140 'read' => true,
141 'edit' => true,
142 'createpage' => true,
143 'createtalk' => true,
144 ) ),
145 'wgNamespaceProtection' => array( NS_MEDIAWIKI => 'editinterface' ),
146 'wgDefaultExternalStore' => array(),
147 'wgForeignFileRepos' => array(),
148 'wgLinkHolderBatchSize' => $linkHolderBatchSize,
149 'wgExperimentalHtmlIds' => false,
150 'wgExternalLinkTarget' => false,
151 'wgAlwaysUseTidy' => false,
152 'wgHtml5' => true,
153 'wgWellFormedXml' => true,
154 'wgAllowMicrodataAttributes' => true,
155 'wgAdaptiveMessageCache' => true
156 );
157
158 if ( $config ) {
159 $configLines = explode( "\n", $config );
160
161 foreach ( $configLines as $line ) {
162 list( $var, $value ) = explode( '=', $line, 2 );
163
164 $settings[$var] = eval( "return $value;" ); //???
165 }
166 }
167
168 $this->savedGlobals = array();
169
170 foreach ( $settings as $var => $val ) {
171 if ( array_key_exists( $var, $GLOBALS ) ) {
172 $this->savedGlobals[$var] = $GLOBALS[$var];
173 }
174
175 $GLOBALS[$var] = $val;
176 }
177
178 $langObj = Language::factory( $lang );
179 $GLOBALS['wgLang'] = $langObj;
180 $GLOBALS['wgContLang'] = $langObj;
181 $GLOBALS['wgMemc'] = new FakeMemCachedClient;
182 $GLOBALS['wgOut'] = new OutputPage;
183
184 global $wgHooks;
185
186 $wgHooks['ParserTestParser'][] = 'ParserTestParserHook::setup';
187 $wgHooks['ParserTestParser'][] = 'ParserTestStaticParserHook::setup';
188 $wgHooks['ParserGetVariableValueTs'][] = 'ParserTest::getFakeTimestamp';
189
190 MagicWord::clearCache();
191
192 global $wgUser;
193 $wgUser = new User();
194 }
195
196 /**
197 * Restore default values and perform any necessary clean-up
198 * after each test runs.
199 */
200 protected function teardownGlobals() {
201 RepoGroup::destroySingleton();
202 LinkCache::singleton()->clear();
203
204 foreach ( $this->savedGlobals as $var => $val ) {
205 $GLOBALS[$var] = $val;
206 }
207 }
208
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',
215 'iw_api' => '',
216 'iw_wikiid' => '',
217 'iw_local' => 0 ),
218 array( 'iw_prefix' => 'meatball',
219 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
220 'iw_api' => '',
221 'iw_wikiid' => '',
222 'iw_local' => 0 ),
223 array( 'iw_prefix' => 'zh',
224 'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
225 'iw_api' => '',
226 'iw_wikiid' => '',
227 'iw_local' => 1 ),
228 array( 'iw_prefix' => 'es',
229 'iw_url' => 'http://es.wikipedia.org/wiki/$1',
230 'iw_api' => '',
231 'iw_wikiid' => '',
232 'iw_local' => 1 ),
233 array( 'iw_prefix' => 'fr',
234 'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
235 'iw_api' => '',
236 'iw_wikiid' => '',
237 'iw_local' => 1 ),
238 array( 'iw_prefix' => 'ru',
239 'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
240 'iw_api' => '',
241 'iw_wikiid' => '',
242 'iw_local' => 1 ),
243 ) );
244
245
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 ) );
248
249 # Reinitialise the LocalisationCache to match the database state
250 Language::getLocalisationCache()->unloadAll();
251
252 # Make a new message cache
253 global $wgMessageCache, $wgMemc;
254 $wgMessageCache = new MessageCache( $wgMemc, true, 3600 );
255
256 $this->uploadDir = $this->setupUploadDir();
257
258 $user = User::newFromId( 0 );
259
260 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Foobar.jpg' ) );
261 $image->recordUpload2( '', 'Upload of some lame file', 'Some lame file', array(
262 'size' => 12345,
263 'width' => 1941,
264 'height' => 220,
265 'bits' => 24,
266 'media_type' => MEDIATYPE_BITMAP,
267 'mime' => 'image/jpeg',
268 'metadata' => serialize( array() ),
269 'sha1' => wfBaseConvert( '', 16, 36, 31 ),
270 'fileExists' => true
271 ), $this->db->timestamp( '20010115123500' ), $user );
272
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(
276 'size' => 12345,
277 'width' => 320,
278 'height' => 240,
279 'bits' => 24,
280 'media_type' => MEDIATYPE_BITMAP,
281 'mime' => 'image/jpeg',
282 'metadata' => serialize( array() ),
283 'sha1' => wfBaseConvert( '', 16, 36, 31 ),
284 'fileExists' => true
285 ), $this->db->timestamp( '20010115123500' ), $user );
286
287 }
288
289 public function testParserTests() {
290
291 global $wgParserTestFiles;
292
293 $files = $wgParserTestFiles;
294
295 if( $this->getCliArg( 'file=' ) ) {
296 $files = array( $this->getCliArg( 'file=' ) );
297 }
298
299 foreach( $files as $file ) {
300
301 $iter = new ParserTestFileIterator( $file, $this );
302
303 foreach ( $iter as $t ) {
304
305 $result = $this->doRunTest( $t['test'], $t['input'], $t['result'], $t['options'], $t['config'] );
306
307 //$this->recorder->record( $t['test'], $result );
308 }
309
310 }
311
312
313 }
314
315
316 /**
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.
320 *
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
326 * @return Boolean
327 */
328 protected function doRunTest( $desc, $input, $result, $opts, $config ) {
329
330 $opts = $this->parseOptions( $opts );
331 $this->setupGlobals( $opts, $config );
332
333 $user = new User();
334 $options = ParserOptions::newFromUser( $user );
335
336 if ( isset( $opts['title'] ) ) {
337 $titleText = $opts['title'];
338 }
339 else {
340 $titleText = 'Parser test';
341 }
342
343 $local = isset( $opts['local'] );
344 $preprocessor = isset( $opts['preprocessor'] ) ? $opts['preprocessor'] : null;
345 $parser = $this->getParser( $preprocessor );
346 $title = Title::newFromText( $titleText );
347
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 );
364 } else {
365 $output = $parser->parse( $input, $title, $options, true, true, 1337 );
366 $out = $output->getText();
367
368 if ( isset( $opts['showtitle'] ) ) {
369 if ( $output->getTitleText() ) {
370 $title = $output->getTitleText();
371 }
372
373 $out = "$title\n$out";
374 }
375
376 if ( isset( $opts['ill'] ) ) {
377 $out = $this->tidy( implode( ' ', $output->getLanguageLinks() ) );
378 } elseif ( isset( $opts['cat'] ) ) {
379 global $wgOut;
380
381 $wgOut->addCategoryLinks( $output->getCategories() );
382 $cats = $wgOut->getCategoryLinks();
383
384 if ( isset( $cats['normal'] ) ) {
385 $out = $this->tidy( implode( ' ', $cats['normal'] ) );
386 } else {
387 $out = '';
388 }
389 }
390
391 $result = $this->tidy( $result );
392 }
393
394 $this->teardownGlobals();
395
396 $this->assertEquals( $result, $out, $desc );
397 }
398
399 /**
400 * Get a Parser object
401 */
402 function getParser( $preprocessor = null ) {
403 global $wgParserConf;
404
405 $class = $wgParserConf['class'];
406 $parser = new $class( array( 'preprocessorClass' => $preprocessor ) + $wgParserConf );
407
408 foreach ( $this->hooks as $tag => $callback ) {
409 $parser->setHook( $tag, $callback );
410 }
411
412 foreach ( $this->functionHooks as $tag => $bits ) {
413 list( $callback, $flags ) = $bits;
414 $parser->setFunctionHook( $tag, $callback, $flags );
415 }
416
417 wfRunHooks( 'ParserTestParser', array( &$parser ) );
418
419 return $parser;
420 }
421
422 /*
423 * Run the "tidy" command on text if the $wgUseTidy
424 * global is true
425 *
426 * @param $text String: the text to tidy
427 * @return String
428 * @static
429 */
430 protected function tidy( $text ) {
431 global $wgUseTidy;
432
433 if ( $wgUseTidy ) {
434 $text = MWTidy::tidy( $text );
435 }
436
437 return $text;
438 }
439
440
441 /**
442 * Create a dummy uploads directory which will contain a couple
443 * of files in order to pass existence tests.
444 *
445 * @return String: the directory
446 */
447 protected function setupUploadDir() {
448 global $IP;
449
450 if ( $this->keepUploads ) {
451 $dir = wfTempDir() . '/mwParser-images';
452
453 if ( is_dir( $dir ) ) {
454 return $dir;
455 }
456 } else {
457 $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
458 }
459
460 // wfDebug( "Creating upload directory $dir\n" );
461 if ( file_exists( $dir ) ) {
462 wfDebug( "Already exists!\n" );
463 return $dir;
464 }
465
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" );
470
471 return $dir;
472 }
473
474 /**
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
479 */
480 public function addArticle( $name, $text, $line = 'unknown' ) {
481 global $wgCapitalLinks;
482
483 $text = $this->removeEndingNewline($text);
484
485 $oldCapitalLinks = $wgCapitalLinks;
486 $wgCapitalLinks = true; // We only need this from SetupGlobals() See r70917#c8637
487
488 $name = $this->removeEndingNewline( $name );
489 $title = Title::newFromText( $name );
490
491 if ( is_null( $title ) ) {
492 wfDie( "invalid title ('$name' => '$title') at line $line\n" );
493 }
494
495 $aid = $title->getArticleID( Title::GAID_FOR_UPDATE );
496
497 if ( $aid != 0 ) {
498 debug_print_backtrace();
499 wfDie( "duplicate article '$name' at line $line\n" );
500 }
501
502 $art = new Article( $title );
503 $art->doEdit( $text, '', EDIT_NEW );
504
505 $wgCapitalLinks = $oldCapitalLinks;
506 }
507
508 /**
509 * Remove last character if it is a newline
510 */
511 public function removeEndingNewline( $s ) {
512 if ( substr( $s, -1 ) === "\n" ) {
513 return substr( $s, 0, -1 );
514 }
515 else {
516 return $s;
517 }
518 }
519
520 /**
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.
524 *
525 * @param $name String
526 * @return Bool true if tag hook is present
527 */
528 public function requireHook( $name ) {
529 global $wgParser;
530
531 $wgParser->firstCallInit( ); // make sure hooks are loaded.
532
533 if ( isset( $wgParser->mTagHooks[$name] ) ) {
534 $this->hooks[$name] = $wgParser->mTagHooks[$name];
535 } else {
536 echo " This test suite requires the '$name' hook extension, skipping.\n";
537 return false;
538 }
539
540 return true;
541 }
542
543 protected function parseOptions( $instring ) {
544 $opts = array();
545 // foo
546 // foo=bar
547 // foo="bar baz"
548 // foo=[[bar baz]]
549 // foo=bar,"baz quux"
550 $regex = '/\b
551 ([\w-]+) # Key
552 \b
553 (?:\s*
554 = # First sub-value
555 \s*
556 (
557 "
558 [^"]* # Quoted val
559 "
560 |
561 \[\[
562 [^]]* # Link target
563 \]\]
564 |
565 [\w-]+ # Plain word
566 )
567 (?:\s*
568 , # Sub-vals 1..N
569 \s*
570 (
571 "[^"]*" # Quoted val
572 |
573 \[\[[^]]*\]\] # Link target
574 |
575 [\w-]+ # Plain word
576 )
577 )*
578 )?
579 /x';
580
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 ) {
586 $opts[$key] = true;
587 } elseif ( count( $bits ) == 1 ) {
588 $opts[$key] = $this->cleanupOption( array_shift( $bits ) );
589 } else {
590 // Array!
591 $opts[$key] = array_map( array( $this, 'cleanupOption' ), $bits );
592 }
593 }
594 }
595 return $opts;
596 }
597
598 protected function cleanupOption( $opt ) {
599 if ( substr( $opt, 0, 1 ) == '"' ) {
600 return substr( $opt, 1, -1 );
601 }
602
603 if ( substr( $opt, 0, 2 ) == '[[' ) {
604 return substr( $opt, 2, -2 );
605 }
606 return $opt;
607 }
608
609 /**
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
614 */
615 protected static function getOptionValue( $key, $opts, $default ) {
616 $key = strtolower( $key );
617
618 if ( isset( $opts[$key] ) ) {
619 return $opts[$key];
620 } else {
621 return $default;
622 }
623 }
624 }
625