Start work on porting ParserTests completely into PHPunit.
[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 global $wgParser, $wgParserConf, $IP, $messageMemc, $wgMemc, $wgDeferredUpdateList,
24 $wgUser, $wgLang, $wgOut, $wgRequest, $wgStyleDirectory, $wgEnableParserCache,
25 $wgMessageCache, $wgUseDatabaseMessages, $wgMsgCacheExpiry, $parserMemc,
26 $wgNamespaceAliases, $wgNamespaceProtection, $wgLocalFileRepo,
27 $wgThumbnailScriptPath, $wgScriptPath,
28 $wgArticlePath, $wgStyleSheetPath, $wgScript, $wgStylePath;
29
30 $wgScript = '/index.php';
31 $wgScriptPath = '/';
32 $wgArticlePath = '/wiki/$1';
33 $wgStyleSheetPath = '/skins';
34 $wgStylePath = '/skins';
35 $wgThumbnailScriptPath = false;
36 $wgLocalFileRepo = array(
37 'class' => 'LocalRepo',
38 'name' => 'local',
39 'directory' => wfTempDir() . '/test-repo',
40 'url' => 'http://example.com/images',
41 'deletedDir' => wfTempDir() . '/test-repo/delete',
42 'hashLevels' => 2,
43 'transformVia404' => false,
44 );
45 $wgNamespaceProtection[NS_MEDIAWIKI] = 'editinterface';
46 $wgNamespaceAliases['Image'] = NS_FILE;
47 $wgNamespaceAliases['Image_talk'] = NS_FILE_TALK;
48
49
50 $wgEnableParserCache = false;
51 $wgDeferredUpdateList = array();
52 $wgMemc = &wfGetMainCache();
53 $messageMemc = &wfGetMessageCacheStorage();
54 $parserMemc = &wfGetParserCacheStorage();
55
56 // $wgContLang = new StubContLang;
57 $wgUser = new User;
58 $wgLang = new StubUserLang;
59 $wgOut = new StubObject( 'wgOut', 'OutputPage' );
60 $wgParser = new StubObject( 'wgParser', $wgParserConf['class'], array( $wgParserConf ) );
61 $wgRequest = new WebRequest;
62
63 $wgMessageCache = new StubObject( 'wgMessageCache', 'MessageCache',
64 array( $messageMemc, $wgUseDatabaseMessages,
65 $wgMsgCacheExpiry ) );
66 if ( $wgStyleDirectory === false ) {
67 $wgStyleDirectory = "$IP/skins";
68 }
69 }
70
71 /**
72 * Set up the global variables for a consistent environment for each test.
73 * Ideally this should replace the global configuration entirely.
74 */
75 protected function setupGlobals( $opts = '', $config = '' ) {
76 # Find out values for some special options.
77 $lang =
78 self::getOptionValue( 'language', $opts, 'en' );
79 $variant =
80 self::getOptionValue( 'variant', $opts, false );
81 $maxtoclevel =
82 self::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
83 $linkHolderBatchSize =
84 self::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
85
86 $settings = array(
87 'wgServer' => 'http://Britney-Spears',
88 'wgScript' => '/index.php',
89 'wgScriptPath' => '/',
90 'wgArticlePath' => '/wiki/$1',
91 'wgActionPaths' => array(),
92 'wgLocalFileRepo' => array(
93 'class' => 'LocalRepo',
94 'name' => 'local',
95 'directory' => $this->uploadDir,
96 'url' => 'http://example.com/images',
97 'hashLevels' => 2,
98 'transformVia404' => false,
99 ),
100 'wgEnableUploads' => self::getOptionValue( 'wgEnableUploads', $opts, true ),
101 'wgStylePath' => '/skins',
102 'wgStyleSheetPath' => '/skins',
103 'wgSitename' => 'MediaWiki',
104 'wgLanguageCode' => $lang,
105 'wgDBprefix' => $this->db->getType() != 'oracle' ? 'unittest_' : 'ut_',
106 'wgRawHtml' => isset( $opts['rawhtml'] ),
107 'wgLang' => null,
108 'wgContLang' => null,
109 'wgNamespacesWithSubpages' => array( 0 => isset( $opts['subpage'] ) ),
110 'wgMaxTocLevel' => $maxtoclevel,
111 'wgCapitalLinks' => true,
112 'wgNoFollowLinks' => true,
113 'wgNoFollowDomainExceptions' => array(),
114 'wgThumbnailScriptPath' => false,
115 'wgUseImageResize' => false,
116 'wgUseTeX' => isset( $opts['math'] ),
117 'wgMathDirectory' => $this->uploadDir . '/math',
118 'wgLocaltimezone' => 'UTC',
119 'wgAllowExternalImages' => true,
120 'wgUseTidy' => false,
121 'wgDefaultLanguageVariant' => $variant,
122 'wgVariantArticlePath' => false,
123 'wgGroupPermissions' => array( '*' => array(
124 'createaccount' => true,
125 'read' => true,
126 'edit' => true,
127 'createpage' => true,
128 'createtalk' => true,
129 ) ),
130 'wgNamespaceProtection' => array( NS_MEDIAWIKI => 'editinterface' ),
131 'wgDefaultExternalStore' => array(),
132 'wgForeignFileRepos' => array(),
133 'wgLinkHolderBatchSize' => $linkHolderBatchSize,
134 'wgExperimentalHtmlIds' => false,
135 'wgExternalLinkTarget' => false,
136 'wgAlwaysUseTidy' => false,
137 'wgHtml5' => true,
138 'wgWellFormedXml' => true,
139 'wgAllowMicrodataAttributes' => true,
140 'wgAdaptiveMessageCache' => true
141 );
142
143 if ( $config ) {
144 $configLines = explode( "\n", $config );
145
146 foreach ( $configLines as $line ) {
147 list( $var, $value ) = explode( '=', $line, 2 );
148
149 $settings[$var] = eval( "return $value;" ); //???
150 }
151 }
152
153 $this->savedGlobals = array();
154
155 foreach ( $settings as $var => $val ) {
156 if ( array_key_exists( $var, $GLOBALS ) ) {
157 $this->savedGlobals[$var] = $GLOBALS[$var];
158 }
159
160 $GLOBALS[$var] = $val;
161 }
162
163 $langObj = Language::factory( $lang );
164 $GLOBALS['wgLang'] = $langObj;
165 $GLOBALS['wgContLang'] = $langObj;
166 $GLOBALS['wgMemc'] = new FakeMemCachedClient;
167 $GLOBALS['wgOut'] = new OutputPage;
168
169 global $wgHooks;
170
171 $wgHooks['ParserTestParser'][] = 'ParserTestParserHook::setup';
172 $wgHooks['ParserTestParser'][] = 'ParserTestStaticParserHook::setup';
173 $wgHooks['ParserGetVariableValueTs'][] = 'ParserTest::getFakeTimestamp';
174
175 MagicWord::clearCache();
176
177 global $wgUser;
178 $wgUser = new User();
179 }
180
181 /**
182 * Restore default values and perform any necessary clean-up
183 * after each test runs.
184 */
185 protected function teardownGlobals() {
186 RepoGroup::destroySingleton();
187 LinkCache::singleton()->clear();
188
189 foreach ( $this->savedGlobals as $var => $val ) {
190 $GLOBALS[$var] = $val;
191 }
192 }
193
194 function addDBData() {
195 # Hack: insert a few Wikipedia in-project interwiki prefixes,
196 # for testing inter-language links
197 $this->db->insert( 'interwiki', array(
198 array( 'iw_prefix' => 'wikipedia',
199 'iw_url' => 'http://en.wikipedia.org/wiki/$1',
200 'iw_api' => '',
201 'iw_wikiid' => '',
202 'iw_local' => 0 ),
203 array( 'iw_prefix' => 'meatball',
204 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
205 'iw_api' => '',
206 'iw_wikiid' => '',
207 'iw_local' => 0 ),
208 array( 'iw_prefix' => 'zh',
209 'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
210 'iw_api' => '',
211 'iw_wikiid' => '',
212 'iw_local' => 1 ),
213 array( 'iw_prefix' => 'es',
214 'iw_url' => 'http://es.wikipedia.org/wiki/$1',
215 'iw_api' => '',
216 'iw_wikiid' => '',
217 'iw_local' => 1 ),
218 array( 'iw_prefix' => 'fr',
219 'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
220 'iw_api' => '',
221 'iw_wikiid' => '',
222 'iw_local' => 1 ),
223 array( 'iw_prefix' => 'ru',
224 'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
225 'iw_api' => '',
226 'iw_wikiid' => '',
227 'iw_local' => 1 ),
228 ) );
229
230
231 # Update certain things in site_stats
232 $this->db->insert( 'site_stats', array( 'ss_row_id' => 1, 'ss_images' => 2, 'ss_good_articles' => 1 ) );
233
234 # Reinitialise the LocalisationCache to match the database state
235 Language::getLocalisationCache()->unloadAll();
236
237 # Make a new message cache
238 global $wgMessageCache, $wgMemc;
239 $wgMessageCache = new MessageCache( $wgMemc, true, 3600 );
240
241 $this->uploadDir = $this->setupUploadDir();
242
243 $user = User::newFromId( 0 );
244
245 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Foobar.jpg' ) );
246 $image->recordUpload2( '', 'Upload of some lame file', 'Some lame file', array(
247 'size' => 12345,
248 'width' => 1941,
249 'height' => 220,
250 'bits' => 24,
251 'media_type' => MEDIATYPE_BITMAP,
252 'mime' => 'image/jpeg',
253 'metadata' => serialize( array() ),
254 'sha1' => wfBaseConvert( '', 16, 36, 31 ),
255 'fileExists' => true
256 ), $this->db->timestamp( '20010115123500' ), $user );
257
258 # This image will be blacklisted in [[MediaWiki:Bad image list]]
259 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Bad.jpg' ) );
260 $image->recordUpload2( '', 'zomgnotcensored', 'Borderline image', array(
261 'size' => 12345,
262 'width' => 320,
263 'height' => 240,
264 'bits' => 24,
265 'media_type' => MEDIATYPE_BITMAP,
266 'mime' => 'image/jpeg',
267 'metadata' => serialize( array() ),
268 'sha1' => wfBaseConvert( '', 16, 36, 31 ),
269 'fileExists' => true
270 ), $this->db->timestamp( '20010115123500' ), $user );
271
272 }
273
274 public function testParserTests() {
275
276 //global $IP;
277 //$wgParserTestFiles = array( "$IP/tests/parser/testparserTests.txt" );
278
279 global $wgParserTestFiles;
280
281 foreach( $wgParserTestFiles as $file ) {
282
283 $iter = new ParserTestFileIterator( $file, $this );
284
285 foreach ( $iter as $t ) {
286
287 $result = $this->doRunTest( $t['test'], $t['input'], $t['result'], $t['options'], $t['config'] );
288
289 //$this->recorder->record( $t['test'], $result );
290 }
291
292 }
293
294
295 }
296
297
298 /**
299 * Run a given wikitext input through a freshly-constructed wiki parser,
300 * and compare the output against the expected results.
301 * Prints status and explanatory messages to stdout.
302 *
303 * @param $desc String: test's description
304 * @param $input String: wikitext to try rendering
305 * @param $result String: result to output
306 * @param $opts Array: test's options
307 * @param $config String: overrides for global variables, one per line
308 * @return Boolean
309 */
310 protected function doRunTest( $desc, $input, $result, $opts, $config ) {
311
312 $opts = $this->parseOptions( $opts );
313 $this->setupGlobals( $opts, $config );
314
315 $user = new User();
316 $options = ParserOptions::newFromUser( $user );
317
318 if ( isset( $opts['title'] ) ) {
319 $titleText = $opts['title'];
320 }
321 else {
322 $titleText = 'Parser test';
323 }
324
325 $local = isset( $opts['local'] );
326 $preprocessor = isset( $opts['preprocessor'] ) ? $opts['preprocessor'] : null;
327 $parser = $this->getParser( $preprocessor );
328 $title = Title::newFromText( $titleText );
329
330 if ( isset( $opts['pst'] ) ) {
331 $out = $parser->preSaveTransform( $input, $title, $user, $options );
332 } elseif ( isset( $opts['msg'] ) ) {
333 $out = $parser->transformMsg( $input, $options );
334 } elseif ( isset( $opts['section'] ) ) {
335 $section = $opts['section'];
336 $out = $parser->getSection( $input, $section );
337 } elseif ( isset( $opts['replace'] ) ) {
338 $section = $opts['replace'][0];
339 $replace = $opts['replace'][1];
340 $out = $parser->replaceSection( $input, $section, $replace );
341 } elseif ( isset( $opts['comment'] ) ) {
342 $linker = $user->getSkin();
343 $out = $linker->formatComment( $input, $title, $local );
344 } elseif ( isset( $opts['preload'] ) ) {
345 $out = $parser->getpreloadText( $input, $title, $options );
346 } else {
347 $output = $parser->parse( $input, $title, $options, true, true, 1337 );
348 $out = $output->getText();
349
350 if ( isset( $opts['showtitle'] ) ) {
351 if ( $output->getTitleText() ) {
352 $title = $output->getTitleText();
353 }
354
355 $out = "$title\n$out";
356 }
357
358 if ( isset( $opts['ill'] ) ) {
359 $out = $this->tidy( implode( ' ', $output->getLanguageLinks() ) );
360 } elseif ( isset( $opts['cat'] ) ) {
361 global $wgOut;
362
363 $wgOut->addCategoryLinks( $output->getCategories() );
364 $cats = $wgOut->getCategoryLinks();
365
366 if ( isset( $cats['normal'] ) ) {
367 $out = $this->tidy( implode( ' ', $cats['normal'] ) );
368 } else {
369 $out = '';
370 }
371 }
372
373 $result = $this->tidy( $result );
374 }
375
376 $this->teardownGlobals();
377
378 $this->assertEquals( $result, $out, $desc );
379 }
380
381 /**
382 * Get a Parser object
383 */
384 function getParser( $preprocessor = null ) {
385 global $wgParserConf;
386
387 $class = $wgParserConf['class'];
388 $parser = new $class( array( 'preprocessorClass' => $preprocessor ) + $wgParserConf );
389
390 foreach ( $this->hooks as $tag => $callback ) {
391 $parser->setHook( $tag, $callback );
392 }
393
394 foreach ( $this->functionHooks as $tag => $bits ) {
395 list( $callback, $flags ) = $bits;
396 $parser->setFunctionHook( $tag, $callback, $flags );
397 }
398
399 wfRunHooks( 'ParserTestParser', array( &$parser ) );
400
401 return $parser;
402 }
403
404 /*
405 * Run the "tidy" command on text if the $wgUseTidy
406 * global is true
407 *
408 * @param $text String: the text to tidy
409 * @return String
410 * @static
411 */
412 protected function tidy( $text ) {
413 global $wgUseTidy;
414
415 if ( $wgUseTidy ) {
416 $text = MWTidy::tidy( $text );
417 }
418
419 return $text;
420 }
421
422
423 /**
424 * Create a dummy uploads directory which will contain a couple
425 * of files in order to pass existence tests.
426 *
427 * @return String: the directory
428 */
429 protected function setupUploadDir() {
430 global $IP;
431
432 if ( $this->keepUploads ) {
433 $dir = wfTempDir() . '/mwParser-images';
434
435 if ( is_dir( $dir ) ) {
436 return $dir;
437 }
438 } else {
439 $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
440 }
441
442 // wfDebug( "Creating upload directory $dir\n" );
443 if ( file_exists( $dir ) ) {
444 wfDebug( "Already exists!\n" );
445 return $dir;
446 }
447
448 wfMkdirParents( $dir . '/3/3a' );
449 copy( "$IP/skins/monobook/headbg.jpg", "$dir/3/3a/Foobar.jpg" );
450 wfMkdirParents( $dir . '/0/09' );
451 copy( "$IP/skins/monobook/headbg.jpg", "$dir/0/09/Bad.jpg" );
452
453 return $dir;
454 }
455
456 /**
457 * Insert a temporary test article
458 * @param $name String: the title, including any prefix
459 * @param $text String: the article text
460 * @param $line Integer: the input line number, for reporting errors
461 */
462 public function addArticle( $name, $text, $line = 'unknown' ) {
463 global $wgCapitalLinks;
464
465 $text = $this->removeEndingNewline($text);
466
467 $oldCapitalLinks = $wgCapitalLinks;
468 $wgCapitalLinks = true; // We only need this from SetupGlobals() See r70917#c8637
469
470 $name = $this->removeEndingNewline( $name );
471 $title = Title::newFromText( $name );
472
473 if ( is_null( $title ) ) {
474 wfDie( "invalid title ('$name' => '$title') at line $line\n" );
475 }
476
477 $aid = $title->getArticleID( Title::GAID_FOR_UPDATE );
478
479 if ( $aid != 0 ) {
480 debug_print_backtrace();
481 wfDie( "duplicate article '$name' at line $line\n" );
482 }
483
484 $art = new Article( $title );
485 $art->doEdit( $text, '', EDIT_NEW );
486
487 $wgCapitalLinks = $oldCapitalLinks;
488 }
489
490 /**
491 * Remove last character if it is a newline
492 */
493 public function removeEndingNewline( $s ) {
494 if ( substr( $s, -1 ) === "\n" ) {
495 return substr( $s, 0, -1 );
496 }
497 else {
498 return $s;
499 }
500 }
501
502 /**
503 * Steal a callback function from the primary parser, save it for
504 * application to our scary parser. If the hook is not installed,
505 * abort processing of this file.
506 *
507 * @param $name String
508 * @return Bool true if tag hook is present
509 */
510 public function requireHook( $name ) {
511 global $wgParser;
512
513 $wgParser->firstCallInit( ); // make sure hooks are loaded.
514
515 if ( isset( $wgParser->mTagHooks[$name] ) ) {
516 $this->hooks[$name] = $wgParser->mTagHooks[$name];
517 } else {
518 echo " This test suite requires the '$name' hook extension, skipping.\n";
519 return false;
520 }
521
522 return true;
523 }
524
525 protected function parseOptions( $instring ) {
526 $opts = array();
527 // foo
528 // foo=bar
529 // foo="bar baz"
530 // foo=[[bar baz]]
531 // foo=bar,"baz quux"
532 $regex = '/\b
533 ([\w-]+) # Key
534 \b
535 (?:\s*
536 = # First sub-value
537 \s*
538 (
539 "
540 [^"]* # Quoted val
541 "
542 |
543 \[\[
544 [^]]* # Link target
545 \]\]
546 |
547 [\w-]+ # Plain word
548 )
549 (?:\s*
550 , # Sub-vals 1..N
551 \s*
552 (
553 "[^"]*" # Quoted val
554 |
555 \[\[[^]]*\]\] # Link target
556 |
557 [\w-]+ # Plain word
558 )
559 )*
560 )?
561 /x';
562
563 if ( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER ) ) {
564 foreach ( $matches as $bits ) {
565 array_shift( $bits );
566 $key = strtolower( array_shift( $bits ) );
567 if ( count( $bits ) == 0 ) {
568 $opts[$key] = true;
569 } elseif ( count( $bits ) == 1 ) {
570 $opts[$key] = $this->cleanupOption( array_shift( $bits ) );
571 } else {
572 // Array!
573 $opts[$key] = array_map( array( $this, 'cleanupOption' ), $bits );
574 }
575 }
576 }
577 return $opts;
578 }
579
580 protected function cleanupOption( $opt ) {
581 if ( substr( $opt, 0, 1 ) == '"' ) {
582 return substr( $opt, 1, -1 );
583 }
584
585 if ( substr( $opt, 0, 2 ) == '[[' ) {
586 return substr( $opt, 2, -2 );
587 }
588 return $opt;
589 }
590
591 /**
592 * Use a regex to find out the value of an option
593 * @param $key String: name of option val to retrieve
594 * @param $opts Options array to look in
595 * @param $default Mixed: default value returned if not found
596 */
597 protected static function getOptionValue( $key, $opts, $default ) {
598 $key = strtolower( $key );
599
600 if ( isset( $opts[$key] ) ) {
601 return $opts[$key];
602 } else {
603 return $default;
604 }
605 }
606 }
607