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