Add, update, tweak documentation
[lhc/web/wiklou.git] / tests / phpunit / includes / parser / NewParserTest.php
1 <?php
2
3 /**
4 * Although marked as a stub, can work independently.
5 *
6 * @group Database
7 * @group Parser
8 * @group Stub
9 */
10 class NewParserTest extends MediaWikiTestCase {
11
12 static protected $articles = array(); // Array of test articles defined by the tests
13 /* The dataProvider is run on a different instance than the test, so it must be static
14 * When running tests from several files, all tests will see all articles.
15 */
16
17 public $uploadDir;
18 public $keepUploads = false;
19 public $runDisabled = false;
20 public $regex = '';
21 public $showProgress = true;
22 public $savedInitialGlobals = array();
23 public $savedWeirdGlobals = array();
24 public $savedGlobals = array();
25 public $hooks = array();
26 public $functionHooks = array();
27
28 //Fuzz test
29 public $maxFuzzTestLength = 300;
30 public $fuzzSeed = 0;
31 public $memoryLimit = 50;
32
33 protected $file = false;
34
35 /*function __construct($a = null,$b = array(),$c = null ) {
36 parent::__construct($a,$b,$c);
37 }*/
38
39 function setUp() {
40 global $wgContLang, $wgNamespaceProtection, $wgNamespaceAliases;
41 global $wgHooks, $IP;
42 $wgContLang = Language::factory( 'en' );
43
44 //Setup CLI arguments
45 if ( $this->getCliArg( 'regex=' ) ) {
46 $this->regex = $this->getCliArg( 'regex=' );
47 } else {
48 # Matches anything
49 $this->regex = '';
50 }
51
52 $this->keepUploads = $this->getCliArg( 'keep-uploads' );
53
54 $tmpGlobals = array();
55
56 $tmpGlobals['wgScript'] = '/index.php';
57 $tmpGlobals['wgScriptPath'] = '/';
58 $tmpGlobals['wgArticlePath'] = '/wiki/$1';
59 $tmpGlobals['wgStyleSheetPath'] = '/skins';
60 $tmpGlobals['wgStylePath'] = '/skins';
61 $tmpGlobals['wgThumbnailScriptPath'] = false;
62 $tmpGlobals['wgLocalFileRepo'] = array(
63 'class' => 'LocalRepo',
64 'name' => 'local',
65 'directory' => wfTempDir() . '/test-repo',
66 'url' => 'http://example.com/images',
67 'deletedDir' => wfTempDir() . '/test-repo/delete',
68 'hashLevels' => 2,
69 'transformVia404' => false,
70 );
71
72 $tmpGlobals['wgEnableParserCache'] = false;
73 $tmpGlobals['wgHooks'] = $wgHooks;
74 $tmpGlobals['wgDeferredUpdateList'] = array();
75 $tmpGlobals['wgMemc'] = wfGetMainCache();
76 $tmpGlobals['messageMemc'] = wfGetMessageCacheStorage();
77 $tmpGlobals['parserMemc'] = wfGetParserCacheStorage();
78
79 // $tmpGlobals['wgContLang'] = new StubContLang;
80 $tmpGlobals['wgUser'] = new User;
81 $context = new RequestContext();
82 $tmpGlobals['wgLang'] = $context->getLang();
83 $tmpGlobals['wgOut'] = $context->getOutput();
84 $tmpGlobals['wgParser'] = new StubObject( 'wgParser', $GLOBALS['wgParserConf']['class'], array( $GLOBALS['wgParserConf'] ) );
85 $tmpGlobals['wgRequest'] = $context->getRequest();
86
87 if ( $GLOBALS['wgStyleDirectory'] === false ) {
88 $tmpGlobals['wgStyleDirectory'] = "$IP/skins";
89 }
90
91
92 foreach ( $tmpGlobals as $var => $val ) {
93 if ( array_key_exists( $var, $GLOBALS ) ) {
94 $this->savedInitialGlobals[$var] = $GLOBALS[$var];
95 }
96
97 $GLOBALS[$var] = $val;
98 }
99
100 $this->savedWeirdGlobals['mw_namespace_protection'] = $wgNamespaceProtection[NS_MEDIAWIKI];
101 $this->savedWeirdGlobals['image_alias'] = $wgNamespaceAliases['Image'];
102 $this->savedWeirdGlobals['image_talk_alias'] = $wgNamespaceAliases['Image_talk'];
103
104 $wgNamespaceProtection[NS_MEDIAWIKI] = 'editinterface';
105 $wgNamespaceAliases['Image'] = NS_FILE;
106 $wgNamespaceAliases['Image_talk'] = NS_FILE_TALK;
107
108 }
109
110 public function tearDown() {
111
112 foreach ( $this->savedInitialGlobals as $var => $val ) {
113 $GLOBALS[$var] = $val;
114 }
115
116 global $wgNamespaceProtection, $wgNamespaceAliases;
117
118 $wgNamespaceProtection[NS_MEDIAWIKI] = $this->savedWeirdGlobals['mw_namespace_protection'];
119 $wgNamespaceAliases['Image'] = $this->savedWeirdGlobals['image_alias'];
120 $wgNamespaceAliases['Image_talk'] = $this->savedWeirdGlobals['image_talk_alias'];
121 }
122
123 function addDBData() {
124 # Hack: insert a few Wikipedia in-project interwiki prefixes,
125 # for testing inter-language links
126 $this->db->insert( 'interwiki', array(
127 array( 'iw_prefix' => 'wikipedia',
128 'iw_url' => 'http://en.wikipedia.org/wiki/$1',
129 'iw_api' => '',
130 'iw_wikiid' => '',
131 'iw_local' => 0 ),
132 array( 'iw_prefix' => 'meatball',
133 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
134 'iw_api' => '',
135 'iw_wikiid' => '',
136 'iw_local' => 0 ),
137 array( 'iw_prefix' => 'zh',
138 'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
139 'iw_api' => '',
140 'iw_wikiid' => '',
141 'iw_local' => 1 ),
142 array( 'iw_prefix' => 'es',
143 'iw_url' => 'http://es.wikipedia.org/wiki/$1',
144 'iw_api' => '',
145 'iw_wikiid' => '',
146 'iw_local' => 1 ),
147 array( 'iw_prefix' => 'fr',
148 'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
149 'iw_api' => '',
150 'iw_wikiid' => '',
151 'iw_local' => 1 ),
152 array( 'iw_prefix' => 'ru',
153 'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
154 'iw_api' => '',
155 'iw_wikiid' => '',
156 'iw_local' => 1 ),
157 /**
158 * @todo Fixme! Why are we inserting duplicate data here? Shouldn't
159 * need this IGNORE or shouldn't need the insert at all.
160 */
161 ), __METHOD__, array( 'IGNORE' ) );
162
163
164 # Update certain things in site_stats
165 $this->db->insert( 'site_stats',
166 array( 'ss_row_id' => 1, 'ss_images' => 2, 'ss_good_articles' => 1 ),
167 __METHOD__, array( 'IGNORE' ) );
168
169 # Reinitialise the LocalisationCache to match the database state
170 Language::getLocalisationCache()->unloadAll();
171
172 # Clear the message cache
173 MessageCache::singleton()->clear();
174
175 $this->uploadDir = $this->setupUploadDir();
176
177 $user = User::newFromId( 0 );
178 LinkCache::singleton()->clear(); # Avoids the odd failure at creating the nullRevision
179
180 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Foobar.jpg' ) );
181 $image->recordUpload2( '', 'Upload of some lame file', 'Some lame file', array(
182 'size' => 12345,
183 'width' => 1941,
184 'height' => 220,
185 'bits' => 24,
186 'media_type' => MEDIATYPE_BITMAP,
187 'mime' => 'image/jpeg',
188 'metadata' => serialize( array() ),
189 'sha1' => wfBaseConvert( '', 16, 36, 31 ),
190 'fileExists' => true
191 ), $this->db->timestamp( '20010115123500' ), $user );
192
193 # This image will be blacklisted in [[MediaWiki:Bad image list]]
194 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Bad.jpg' ) );
195 $image->recordUpload2( '', 'zomgnotcensored', 'Borderline image', array(
196 'size' => 12345,
197 'width' => 320,
198 'height' => 240,
199 'bits' => 24,
200 'media_type' => MEDIATYPE_BITMAP,
201 'mime' => 'image/jpeg',
202 'metadata' => serialize( array() ),
203 'sha1' => wfBaseConvert( '', 16, 36, 31 ),
204 'fileExists' => true
205 ), $this->db->timestamp( '20010115123500' ), $user );
206
207 }
208
209
210
211
212 //ParserTest setup/teardown functions
213
214 /**
215 * Set up the global variables for a consistent environment for each test.
216 * Ideally this should replace the global configuration entirely.
217 */
218 protected function setupGlobals( $opts = '', $config = '' ) {
219 # Find out values for some special options.
220 $lang =
221 self::getOptionValue( 'language', $opts, 'en' );
222 $variant =
223 self::getOptionValue( 'variant', $opts, false );
224 $maxtoclevel =
225 self::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
226 $linkHolderBatchSize =
227 self::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
228
229 $settings = array(
230 'wgServer' => 'http://Britney-Spears',
231 'wgScript' => '/index.php',
232 'wgScriptPath' => '/',
233 'wgArticlePath' => '/wiki/$1',
234 'wgExtensionAssetsPath' => '/extensions',
235 'wgActionPaths' => array(),
236 'wgLocalFileRepo' => array(
237 'class' => 'LocalRepo',
238 'name' => 'local',
239 'directory' => $this->uploadDir,
240 'url' => 'http://example.com/images',
241 'hashLevels' => 2,
242 'transformVia404' => false,
243 ),
244 'wgEnableUploads' => self::getOptionValue( 'wgEnableUploads', $opts, true ),
245 'wgStylePath' => '/skins',
246 'wgStyleSheetPath' => '/skins',
247 'wgSitename' => 'MediaWiki',
248 'wgLanguageCode' => $lang,
249 'wgDBprefix' => $this->db->getType() != 'oracle' ? 'unittest_' : 'ut_',
250 'wgRawHtml' => isset( $opts['rawhtml'] ),
251 'wgLang' => null,
252 'wgContLang' => null,
253 'wgNamespacesWithSubpages' => array( 0 => isset( $opts['subpage'] ) ),
254 'wgMaxTocLevel' => $maxtoclevel,
255 'wgCapitalLinks' => true,
256 'wgNoFollowLinks' => true,
257 'wgNoFollowDomainExceptions' => array(),
258 'wgThumbnailScriptPath' => false,
259 'wgUseImageResize' => false,
260 'wgUseTeX' => isset( $opts['math'] ),
261 'wgMathDirectory' => $this->uploadDir . '/math',
262 'wgLocaltimezone' => 'UTC',
263 'wgAllowExternalImages' => true,
264 'wgUseTidy' => false,
265 'wgDefaultLanguageVariant' => $variant,
266 'wgVariantArticlePath' => false,
267 'wgGroupPermissions' => array( '*' => array(
268 'createaccount' => true,
269 'read' => true,
270 'edit' => true,
271 'createpage' => true,
272 'createtalk' => true,
273 ) ),
274 'wgNamespaceProtection' => array( NS_MEDIAWIKI => 'editinterface' ),
275 'wgDefaultExternalStore' => array(),
276 'wgForeignFileRepos' => array(),
277 'wgLinkHolderBatchSize' => $linkHolderBatchSize,
278 'wgExperimentalHtmlIds' => false,
279 'wgExternalLinkTarget' => false,
280 'wgAlwaysUseTidy' => false,
281 'wgHtml5' => true,
282 'wgCleanupPresentationalAttributes' => true,
283 'wgWellFormedXml' => true,
284 'wgAllowMicrodataAttributes' => true,
285 'wgAdaptiveMessageCache' => true,
286 'wgUseDatabaseMessages' => true,
287 );
288
289 if ( $config ) {
290 $configLines = explode( "\n", $config );
291
292 foreach ( $configLines as $line ) {
293 list( $var, $value ) = explode( '=', $line, 2 );
294
295 $settings[$var] = eval( "return $value;" ); //???
296 }
297 }
298
299 $this->savedGlobals = array();
300
301 foreach ( $settings as $var => $val ) {
302 if ( array_key_exists( $var, $GLOBALS ) ) {
303 $this->savedGlobals[$var] = $GLOBALS[$var];
304 }
305
306 $GLOBALS[$var] = $val;
307 }
308
309 $langObj = Language::factory( $lang );
310 $GLOBALS['wgContLang'] = $langObj;
311 $context = new RequestContext();
312 $GLOBALS['wgLang'] = $context->getLang();
313
314 $GLOBALS['wgMemc'] = new EmptyBagOStuff;
315 $GLOBALS['wgOut'] = $context->getOutput();
316
317 global $wgHooks;
318
319 $wgHooks['ParserTestParser'][] = 'ParserTestParserHook::setup';
320 $wgHooks['ParserGetVariableValueTs'][] = 'ParserTest::getFakeTimestamp';
321
322 MagicWord::clearCache();
323
324 # Publish the articles after we have the final language set
325 $this->publishTestArticles();
326
327 # The entries saved into RepoGroup cache with previous globals will be wrong.
328 RepoGroup::destroySingleton();
329 MessageCache::singleton()->destroyInstance();
330
331 global $wgUser;
332 $wgUser = new User();
333 }
334
335 /**
336 * Create a dummy uploads directory which will contain a couple
337 * of files in order to pass existence tests.
338 *
339 * @return String: the directory
340 */
341 protected function setupUploadDir() {
342 global $IP;
343
344 if ( $this->keepUploads ) {
345 $dir = wfTempDir() . '/mwParser-images';
346
347 if ( is_dir( $dir ) ) {
348 return $dir;
349 }
350 } else {
351 $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
352 }
353
354 // wfDebug( "Creating upload directory $dir\n" );
355 if ( file_exists( $dir ) ) {
356 wfDebug( "Already exists!\n" );
357 return $dir;
358 }
359
360 wfMkdirParents( $dir . '/3/3a', null, __METHOD__ );
361 copy( "$IP/skins/monobook/headbg.jpg", "$dir/3/3a/Foobar.jpg" );
362 wfMkdirParents( $dir . '/0/09', null, __METHOD__ );
363 copy( "$IP/skins/monobook/headbg.jpg", "$dir/0/09/Bad.jpg" );
364
365 return $dir;
366 }
367
368 /**
369 * Restore default values and perform any necessary clean-up
370 * after each test runs.
371 */
372 protected function teardownGlobals() {
373 RepoGroup::destroySingleton();
374 LinkCache::singleton()->clear();
375
376 foreach ( $this->savedGlobals as $var => $val ) {
377 $GLOBALS[$var] = $val;
378 }
379
380 $this->teardownUploadDir( $this->uploadDir );
381 }
382
383 /**
384 * Remove the dummy uploads directory
385 */
386 private function teardownUploadDir( $dir ) {
387 if ( $this->keepUploads ) {
388 return;
389 }
390
391 // delete the files first, then the dirs.
392 self::deleteFiles(
393 array (
394 "$dir/3/3a/Foobar.jpg",
395 "$dir/thumb/3/3a/Foobar.jpg/180px-Foobar.jpg",
396 "$dir/thumb/3/3a/Foobar.jpg/200px-Foobar.jpg",
397 "$dir/thumb/3/3a/Foobar.jpg/640px-Foobar.jpg",
398 "$dir/thumb/3/3a/Foobar.jpg/120px-Foobar.jpg",
399
400 "$dir/0/09/Bad.jpg",
401
402 "$dir/math/f/a/5/fa50b8b616463173474302ca3e63586b.png",
403 )
404 );
405
406 self::deleteDirs(
407 array (
408 "$dir/3/3a",
409 "$dir/3",
410 "$dir/thumb/6/65",
411 "$dir/thumb/6",
412 "$dir/thumb/3/3a/Foobar.jpg",
413 "$dir/thumb/3/3a",
414 "$dir/thumb/3",
415
416 "$dir/0/09/",
417 "$dir/0/",
418 "$dir/thumb",
419 "$dir/math/f/a/5",
420 "$dir/math/f/a",
421 "$dir/math/f",
422 "$dir/math",
423 "$dir",
424 )
425 );
426 }
427
428 /**
429 * Delete the specified files, if they exist.
430 * @param $files Array: full paths to files to delete.
431 */
432 private static function deleteFiles( $files ) {
433 foreach ( $files as $file ) {
434 if ( file_exists( $file ) ) {
435 unlink( $file );
436 }
437 }
438 }
439
440 /**
441 * Delete the specified directories, if they exist. Must be empty.
442 * @param $dirs Array: full paths to directories to delete.
443 */
444 private static function deleteDirs( $dirs ) {
445 foreach ( $dirs as $dir ) {
446 if ( is_dir( $dir ) ) {
447 rmdir( $dir );
448 }
449 }
450 }
451
452 public function parserTestProvider() {
453 if ( $this->file === false ) {
454 global $wgParserTestFiles;
455 $this->file = $wgParserTestFiles[0];
456 }
457 return new TestFileIterator( $this->file, $this );
458 }
459
460 /**
461 * Set the file from whose tests will be run by this instance
462 */
463 public function setParserTestFile( $filename ) {
464 $this->file = $filename;
465 }
466
467 /** @dataProvider parserTestProvider */
468 public function testParserTest( $desc, $input, $result, $opts, $config ) {
469 if ( !preg_match( '/' . $this->regex . '/', $desc ) ) return; //$this->markTestSkipped( 'Filtered out by the user' );
470
471 wfDebug( "Running parser test: $desc\n" );
472
473 $opts = $this->parseOptions( $opts );
474 $this->setupGlobals( $opts, $config );
475
476 $user = new User();
477 $options = ParserOptions::newFromUser( $user );
478
479 if ( isset( $opts['title'] ) ) {
480 $titleText = $opts['title'];
481 }
482 else {
483 $titleText = 'Parser test';
484 }
485
486 $local = isset( $opts['local'] );
487 $preprocessor = isset( $opts['preprocessor'] ) ? $opts['preprocessor'] : null;
488 $parser = $this->getParser( $preprocessor );
489
490 $title = Title::newFromText( $titleText );
491
492 if ( isset( $opts['pst'] ) ) {
493 $out = $parser->preSaveTransform( $input, $title, $user, $options );
494 } elseif ( isset( $opts['msg'] ) ) {
495 $out = $parser->transformMsg( $input, $options, $title );
496 } elseif ( isset( $opts['section'] ) ) {
497 $section = $opts['section'];
498 $out = $parser->getSection( $input, $section );
499 } elseif ( isset( $opts['replace'] ) ) {
500 $section = $opts['replace'][0];
501 $replace = $opts['replace'][1];
502 $out = $parser->replaceSection( $input, $section, $replace );
503 } elseif ( isset( $opts['comment'] ) ) {
504 $out = Linker::formatComment( $input, $title, $local );
505 } elseif ( isset( $opts['preload'] ) ) {
506 $out = $parser->getpreloadText( $input, $title, $options );
507 } else {
508 $output = $parser->parse( $input, $title, $options, true, true, 1337 );
509 $out = $output->getText();
510
511 if ( isset( $opts['showtitle'] ) ) {
512 if ( $output->getTitleText() ) {
513 $title = $output->getTitleText();
514 }
515
516 $out = "$title\n$out";
517 }
518
519 if ( isset( $opts['ill'] ) ) {
520 $out = $this->tidy( implode( ' ', $output->getLanguageLinks() ) );
521 } elseif ( isset( $opts['cat'] ) ) {
522 global $wgOut;
523
524 $wgOut->addCategoryLinks( $output->getCategories() );
525 $cats = $wgOut->getCategoryLinks();
526
527 if ( isset( $cats['normal'] ) ) {
528 $out = $this->tidy( implode( ' ', $cats['normal'] ) );
529 } else {
530 $out = '';
531 }
532 }
533 $parser->mPreprocessor = null;
534
535 $result = $this->tidy( $result );
536 }
537
538 $this->teardownGlobals();
539
540 $this->assertEquals( $result, $out, $desc );
541 }
542
543 /**
544 * Run a fuzz test series
545 * Draw input from a set of test files
546 *
547 * @todo @fixme Needs some work to not eat memory until the world explodes
548 *
549 * @group Broken
550 */
551 function testFuzzTests() {
552 global $wgParserTestFiles;
553
554 $files = $wgParserTestFiles;
555
556 if( $this->getCliArg( 'file=' ) ) {
557 $files = array( $this->getCliArg( 'file=' ) );
558 }
559
560 $dict = $this->getFuzzInput( $files );
561 $dictSize = strlen( $dict );
562 $logMaxLength = log( $this->maxFuzzTestLength );
563
564 ini_set( 'memory_limit', $this->memoryLimit * 1048576 );
565
566 $user = new User;
567 $opts = ParserOptions::newFromUser( $user );
568 $title = Title::makeTitle( NS_MAIN, 'Parser_test' );
569
570 $id = 1;
571
572 while ( true ) {
573
574 // Generate test input
575 mt_srand( ++$this->fuzzSeed );
576 $totalLength = mt_rand( 1, $this->maxFuzzTestLength );
577 $input = '';
578
579 while ( strlen( $input ) < $totalLength ) {
580 $logHairLength = mt_rand( 0, 1000000 ) / 1000000 * $logMaxLength;
581 $hairLength = min( intval( exp( $logHairLength ) ), $dictSize );
582 $offset = mt_rand( 0, $dictSize - $hairLength );
583 $input .= substr( $dict, $offset, $hairLength );
584 }
585
586 $this->setupGlobals();
587 $parser = $this->getParser();
588
589 // Run the test
590 try {
591 $parser->parse( $input, $title, $opts );
592 $this->assertTrue( true, "Test $id, fuzz seed {$this->fuzzSeed}" );
593 } catch ( Exception $exception ) {
594 $input_dump = sprintf( "string(%d) \"%s\"\n", strlen( $input ), $input );
595
596 $this->assertTrue( false, "Test $id, fuzz seed {$this->fuzzSeed}. \n\nInput: $input_dump\n\nError: {$exception->getMessage()}\n\nBacktrace: {$exception->getTraceAsString()}" );
597 }
598
599 $this->teardownGlobals();
600 $parser->__destruct();
601
602 if ( $id % 100 == 0 ) {
603 $usage = intval( memory_get_usage( true ) / $this->memoryLimit / 1048576 * 100 );
604 //echo "{$this->fuzzSeed}: $numSuccess/$numTotal (mem: $usage%)\n";
605 if ( $usage > 90 ) {
606 $ret = "Out of memory:\n";
607 $memStats = $this->getMemoryBreakdown();
608
609 foreach ( $memStats as $name => $usage ) {
610 $ret .= "$name: $usage\n";
611 }
612
613 throw new MWException( $ret );
614 }
615 }
616
617 $id++;
618
619 }
620 }
621
622 //Various getter functions
623
624 /**
625 * Get an input dictionary from a set of parser test files
626 */
627 function getFuzzInput( $filenames ) {
628 $dict = '';
629
630 foreach ( $filenames as $filename ) {
631 $contents = file_get_contents( $filename );
632 preg_match_all( '/!!\s*input\n(.*?)\n!!\s*result/s', $contents, $matches );
633
634 foreach ( $matches[1] as $match ) {
635 $dict .= $match . "\n";
636 }
637 }
638
639 return $dict;
640 }
641
642 /**
643 * Get a memory usage breakdown
644 */
645 function getMemoryBreakdown() {
646 $memStats = array();
647
648 foreach ( $GLOBALS as $name => $value ) {
649 $memStats['$' . $name] = strlen( serialize( $value ) );
650 }
651
652 $classes = get_declared_classes();
653
654 foreach ( $classes as $class ) {
655 $rc = new ReflectionClass( $class );
656 $props = $rc->getStaticProperties();
657 $memStats[$class] = strlen( serialize( $props ) );
658 $methods = $rc->getMethods();
659
660 foreach ( $methods as $method ) {
661 $memStats[$class] += strlen( serialize( $method->getStaticVariables() ) );
662 }
663 }
664
665 $functions = get_defined_functions();
666
667 foreach ( $functions['user'] as $function ) {
668 $rf = new ReflectionFunction( $function );
669 $memStats["$function()"] = strlen( serialize( $rf->getStaticVariables() ) );
670 }
671
672 asort( $memStats );
673
674 return $memStats;
675 }
676
677 /**
678 * Get a Parser object
679 */
680 function getParser( $preprocessor = null ) {
681 global $wgParserConf;
682
683 $class = $wgParserConf['class'];
684 $parser = new $class( array( 'preprocessorClass' => $preprocessor ) + $wgParserConf );
685
686 wfRunHooks( 'ParserTestParser', array( &$parser ) );
687
688 return $parser;
689 }
690
691 //Various action functions
692
693 public function addArticle( $name, $text, $line ) {
694 self::$articles[$name] = $text;
695 }
696
697 public function publishTestArticles() {
698 if ( empty( self::$articles ) ) {
699 return;
700 }
701
702 foreach ( self::$articles as $name => $text ) {
703 $title = Title::newFromText( $name );
704
705 if ( $title->getArticleID( Title::GAID_FOR_UPDATE ) == 0 ) {
706 ParserTest::addArticle( $name, $text );
707 }
708 }
709 }
710
711 /**
712 * Steal a callback function from the primary parser, save it for
713 * application to our scary parser. If the hook is not installed,
714 * abort processing of this file.
715 *
716 * @param $name String
717 * @return Bool true if tag hook is present
718 */
719 public function requireHook( $name ) {
720 global $wgParser;
721 $wgParser->firstCallInit( ); // make sure hooks are loaded.
722 return isset( $wgParser->mTagHooks[$name] );
723 }
724
725 public function requireFunctionHook( $name ) {
726 global $wgParser;
727 $wgParser->firstCallInit( ); // make sure hooks are loaded.
728 return isset( $wgParser->mFunctionHooks[$name] );
729 }
730 //Various "cleanup" functions
731
732 /**
733 * Run the "tidy" command on text if the $wgUseTidy
734 * global is true
735 *
736 * @param $text String: the text to tidy
737 * @return String
738 */
739 protected function tidy( $text ) {
740 global $wgUseTidy;
741
742 if ( $wgUseTidy ) {
743 $text = MWTidy::tidy( $text );
744 }
745
746 return $text;
747 }
748
749 /**
750 * Remove last character if it is a newline
751 */
752 public function removeEndingNewline( $s ) {
753 if ( substr( $s, -1 ) === "\n" ) {
754 return substr( $s, 0, -1 );
755 }
756 else {
757 return $s;
758 }
759 }
760
761 public function showRunFile( $file ) {
762 /* NOP */
763 }
764
765 //Test options parser functions
766
767 protected function parseOptions( $instring ) {
768 $opts = array();
769 // foo
770 // foo=bar
771 // foo="bar baz"
772 // foo=[[bar baz]]
773 // foo=bar,"baz quux"
774 $regex = '/\b
775 ([\w-]+) # Key
776 \b
777 (?:\s*
778 = # First sub-value
779 \s*
780 (
781 "
782 [^"]* # Quoted val
783 "
784 |
785 \[\[
786 [^]]* # Link target
787 \]\]
788 |
789 [\w-]+ # Plain word
790 )
791 (?:\s*
792 , # Sub-vals 1..N
793 \s*
794 (
795 "[^"]*" # Quoted val
796 |
797 \[\[[^]]*\]\] # Link target
798 |
799 [\w-]+ # Plain word
800 )
801 )*
802 )?
803 /x';
804
805 if ( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER ) ) {
806 foreach ( $matches as $bits ) {
807 array_shift( $bits );
808 $key = strtolower( array_shift( $bits ) );
809 if ( count( $bits ) == 0 ) {
810 $opts[$key] = true;
811 } elseif ( count( $bits ) == 1 ) {
812 $opts[$key] = $this->cleanupOption( array_shift( $bits ) );
813 } else {
814 // Array!
815 $opts[$key] = array_map( array( $this, 'cleanupOption' ), $bits );
816 }
817 }
818 }
819 return $opts;
820 }
821
822 protected function cleanupOption( $opt ) {
823 if ( substr( $opt, 0, 1 ) == '"' ) {
824 return substr( $opt, 1, -1 );
825 }
826
827 if ( substr( $opt, 0, 2 ) == '[[' ) {
828 return substr( $opt, 2, -2 );
829 }
830 return $opt;
831 }
832
833 /**
834 * Use a regex to find out the value of an option
835 * @param $key String: name of option val to retrieve
836 * @param $opts Options array to look in
837 * @param $default Mixed: default value returned if not found
838 */
839 protected static function getOptionValue( $key, $opts, $default ) {
840 $key = strtolower( $key );
841
842 if ( isset( $opts[$key] ) ) {
843 return $opts[$key];
844 } else {
845 return $default;
846 }
847 }
848 }