4 * Although marked as a stub, can work independently.
12 class NewParserTest
extends MediaWikiTestCase
{
13 static protected $articles = array(); // Array of test articles defined by the tests
14 /* The data provider is run on a different instance than the test, so it must be static
15 * When running tests from several files, all tests will see all articles.
17 static protected $backendToUse;
19 public $keepUploads = false;
20 public $runDisabled = false;
21 public $runParsoid = false;
23 public $showProgress = true;
24 public $savedWeirdGlobals = array();
25 public $savedGlobals = array();
26 public $hooks = array();
27 public $functionHooks = array();
30 public $maxFuzzTestLength = 300;
32 public $memoryLimit = 50;
39 protected $file = false;
41 public static function setUpBeforeClass() {
42 // Inject ParserTest well-known interwikis
43 ParserTest
::setupInterwikis();
46 protected function setUp() {
47 global $wgNamespaceAliases, $wgContLang;
53 if ( $this->getCliArg( 'regex=' ) ) {
54 $this->regex
= $this->getCliArg( 'regex=' );
60 $this->keepUploads
= $this->getCliArg( 'keep-uploads' );
62 $tmpGlobals = array();
64 $tmpGlobals['wgLanguageCode'] = 'en';
65 $tmpGlobals['wgContLang'] = Language
::factory( 'en' );
66 $tmpGlobals['wgSitename'] = 'MediaWiki';
67 $tmpGlobals['wgServer'] = 'http://example.org';
68 $tmpGlobals['wgScript'] = '/index.php';
69 $tmpGlobals['wgScriptPath'] = '/';
70 $tmpGlobals['wgArticlePath'] = '/wiki/$1';
71 $tmpGlobals['wgActionPaths'] = array();
72 $tmpGlobals['wgVariantArticlePath'] = false;
73 $tmpGlobals['wgExtensionAssetsPath'] = '/extensions';
74 $tmpGlobals['wgStylePath'] = '/skins';
75 $tmpGlobals['wgEnableUploads'] = true;
76 $tmpGlobals['wgThumbnailScriptPath'] = false;
77 $tmpGlobals['wgLocalFileRepo'] = array(
78 'class' => 'LocalRepo',
80 'url' => 'http://example.com/images',
82 'transformVia404' => false,
83 'backend' => 'local-backend'
85 $tmpGlobals['wgForeignFileRepos'] = array();
86 $tmpGlobals['wgDefaultExternalStore'] = array();
87 $tmpGlobals['wgEnableParserCache'] = false;
88 $tmpGlobals['wgCapitalLinks'] = true;
89 $tmpGlobals['wgNoFollowLinks'] = true;
90 $tmpGlobals['wgNoFollowDomainExceptions'] = array();
91 $tmpGlobals['wgExternalLinkTarget'] = false;
92 $tmpGlobals['wgThumbnailScriptPath'] = false;
93 $tmpGlobals['wgUseImageResize'] = true;
94 $tmpGlobals['wgAllowExternalImages'] = true;
95 $tmpGlobals['wgRawHtml'] = false;
96 $tmpGlobals['wgUseTidy'] = false;
97 $tmpGlobals['wgAlwaysUseTidy'] = false;
98 $tmpGlobals['wgWellFormedXml'] = true;
99 $tmpGlobals['wgAllowMicrodataAttributes'] = true;
100 $tmpGlobals['wgExperimentalHtmlIds'] = false;
101 $tmpGlobals['wgAdaptiveMessageCache'] = true;
102 $tmpGlobals['wgUseDatabaseMessages'] = true;
103 $tmpGlobals['wgLocaltimezone'] = 'UTC';
104 $tmpGlobals['wgDeferredUpdateList'] = array();
105 $tmpGlobals['wgGroupPermissions'] = array(
107 'createaccount' => true,
110 'createpage' => true,
111 'createtalk' => true,
113 $tmpGlobals['wgNamespaceProtection'] = array( NS_MEDIAWIKI
=> 'editinterface' );
115 $tmpGlobals['wgParser'] = new StubObject(
116 'wgParser', $GLOBALS['wgParserConf']['class'],
117 array( $GLOBALS['wgParserConf'] ) );
119 $tmpGlobals['wgFileExtensions'][] = 'svg';
120 $tmpGlobals['wgSVGConverter'] = 'rsvg';
121 $tmpGlobals['wgSVGConverters']['rsvg'] =
122 '$path/rsvg-convert -w $width -h $height $input -o $output';
124 if ( $GLOBALS['wgStyleDirectory'] === false ) {
125 $tmpGlobals['wgStyleDirectory'] = "$IP/skins";
128 # Replace all media handlers with a mock. We do not need to generate
129 # actual thumbnails to do parser testing, we only care about receiving
130 # a ThumbnailImage properly initialized.
131 global $wgMediaHandlers;
132 foreach ( $wgMediaHandlers as $type => $handler ) {
133 $tmpGlobals['wgMediaHandlers'][$type] = 'MockBitmapHandler';
135 // Vector images have to be handled slightly differently
136 $tmpGlobals['wgMediaHandlers']['image/svg+xml'] = 'MockSvgHandler';
138 // DjVu images have to be handled slightly differently
139 $tmpGlobals['wgMediaHandlers']['image/vnd.djvu'] = 'MockDjVuHandler';
141 $tmpHooks = $wgHooks;
142 $tmpHooks['ParserTestParser'][] = 'ParserTestParserHook::setup';
143 $tmpHooks['ParserGetVariableValueTs'][] = 'ParserTest::getFakeTimestamp';
144 $tmpGlobals['wgHooks'] = $tmpHooks;
145 # add a namespace shadowing a interwiki link, to test
146 # proper precedence when resolving links. (bug 51680)
147 $tmpGlobals['wgExtraNamespaces'] = array( 100 => 'MemoryAlpha' );
150 $this->djVuSupport
= new DjVuSupport();
152 $this->setMwGlobals( $tmpGlobals );
154 $this->savedWeirdGlobals
['image_alias'] = $wgNamespaceAliases['Image'];
155 $this->savedWeirdGlobals
['image_talk_alias'] = $wgNamespaceAliases['Image_talk'];
157 $wgNamespaceAliases['Image'] = NS_FILE
;
158 $wgNamespaceAliases['Image_talk'] = NS_FILE_TALK
;
160 MWNamespace
::getCanonicalNamespaces( true ); # reset namespace cache
161 $wgContLang->resetNamespaces(); # reset namespace cache
164 protected function tearDown() {
165 global $wgNamespaceAliases, $wgContLang;
167 $wgNamespaceAliases['Image'] = $this->savedWeirdGlobals
['image_alias'];
168 $wgNamespaceAliases['Image_talk'] = $this->savedWeirdGlobals
['image_talk_alias'];
171 RepoGroup
::destroySingleton();
172 FileBackendGroup
::destroySingleton();
174 // Remove temporary pages from the link cache
175 LinkCache
::singleton()->clear();
177 // Restore message cache (temporary pages and $wgUseDatabaseMessages)
178 MessageCache
::destroyInstance();
182 MWNamespace
::getCanonicalNamespaces( true ); # reset namespace cache
183 $wgContLang->resetNamespaces(); # reset namespace cache
186 public static function tearDownAfterClass() {
187 ParserTest
::tearDownInterwikis();
188 parent
::tearDownAfterClass();
191 function addDBData() {
192 $this->tablesUsed
[] = 'site_stats';
193 # disabled for performance
194 #$this->tablesUsed[] = 'image';
196 # Update certain things in site_stats
197 $this->db
->insert( 'site_stats',
198 array( 'ss_row_id' => 1, 'ss_images' => 2, 'ss_good_articles' => 1 ),
202 $user = User
::newFromId( 0 );
203 LinkCache
::singleton()->clear(); # Avoids the odd failure at creating the nullRevision
205 # Upload DB table entries for files.
206 # We will upload the actual files later. Note that if anything causes LocalFile::load()
207 # to be triggered before then, it will break via maybeUpgrade() setting the fileExists
208 # member to false and storing it in cache.
209 # note that the size/width/height/bits/etc of the file
210 # are actually set by inspecting the file itself; the arguments
211 # to recordUpload2 have no effect. That said, we try to make things
212 # match up so it is less confusing to readers of the code & tests.
213 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Foobar.jpg' ) );
214 if ( !$this->db
->selectField( 'image', '1', array( 'img_name' => $image->getName() ) ) ) {
215 $image->recordUpload2(
217 'Upload of some lame file',
224 'media_type' => MEDIATYPE_BITMAP
,
225 'mime' => 'image/jpeg',
226 'metadata' => serialize( array() ),
227 'sha1' => wfBaseConvert( '1', 16, 36, 31 ),
228 'fileExists' => true ),
229 $this->db
->timestamp( '20010115123500' ), $user
233 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Thumb.png' ) );
234 if ( !$this->db
->selectField( 'image', '1', array( 'img_name' => $image->getName() ) ) ) {
235 $image->recordUpload2(
237 'Upload of some lame thumbnail',
238 'Some lame thumbnail',
244 'media_type' => MEDIATYPE_BITMAP
,
245 'mime' => 'image/png',
246 'metadata' => serialize( array() ),
247 'sha1' => wfBaseConvert( '2', 16, 36, 31 ),
248 'fileExists' => true ),
249 $this->db
->timestamp( '20130225203040' ), $user
253 # This image will be blacklisted in [[MediaWiki:Bad image list]]
254 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Bad.jpg' ) );
255 if ( !$this->db
->selectField( 'image', '1', array( 'img_name' => $image->getName() ) ) ) {
256 $image->recordUpload2(
265 'media_type' => MEDIATYPE_BITMAP
,
266 'mime' => 'image/jpeg',
267 'metadata' => serialize( array() ),
268 'sha1' => wfBaseConvert( '3', 16, 36, 31 ),
269 'fileExists' => true ),
270 $this->db
->timestamp( '20010115123500' ), $user
273 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Foobar.svg' ) );
274 if ( !$this->db
->selectField( 'image', '1', array( 'img_name' => $image->getName() ) ) ) {
275 $image->recordUpload2( '', 'Upload of some lame SVG', 'Some lame SVG', array(
280 'media_type' => MEDIATYPE_DRAWING
,
281 'mime' => 'image/svg+xml',
282 'metadata' => serialize( array() ),
283 'sha1' => wfBaseConvert( '', 16, 36, 31 ),
285 ), $this->db
->timestamp( '20010115123500' ), $user );
289 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'LoremIpsum.djvu' ) );
290 if ( !$this->db
->selectField( 'image', '1', array( 'img_name' => $image->getName() ) ) ) {
291 $image->recordUpload2( '', 'Upload a DjVu', 'A DjVu', array(
296 'media_type' => MEDIATYPE_BITMAP
,
297 'mime' => 'image/vnd.djvu',
298 'metadata' => '<?xml version="1.0" ?>
299 <!DOCTYPE DjVuXML PUBLIC "-//W3C//DTD DjVuXML 1.1//EN" "pubtext/DjVuXML-s.dtd">
302 <BODY><OBJECT height="3508" width="2480">
303 <PARAM name="DPI" value="300" />
304 <PARAM name="GAMMA" value="2.2" />
306 <OBJECT height="3508" width="2480">
307 <PARAM name="DPI" value="300" />
308 <PARAM name="GAMMA" value="2.2" />
310 <OBJECT height="3508" width="2480">
311 <PARAM name="DPI" value="300" />
312 <PARAM name="GAMMA" value="2.2" />
314 <OBJECT height="3508" width="2480">
315 <PARAM name="DPI" value="300" />
316 <PARAM name="GAMMA" value="2.2" />
318 <OBJECT height="3508" width="2480">
319 <PARAM name="DPI" value="300" />
320 <PARAM name="GAMMA" value="2.2" />
324 'sha1' => wfBaseConvert( '', 16, 36, 31 ),
326 ), $this->db
->timestamp( '20140115123600' ), $user );
330 //ParserTest setup/teardown functions
333 * Set up the global variables for a consistent environment for each test.
334 * Ideally this should replace the global configuration entirely.
336 protected function setupGlobals( $opts = array(), $config = '' ) {
337 global $wgFileBackends;
338 # Find out values for some special options.
340 self
::getOptionValue( 'language', $opts, 'en' );
342 self
::getOptionValue( 'variant', $opts, false );
344 self
::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
345 $linkHolderBatchSize =
346 self
::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
348 $uploadDir = $this->getUploadDir();
349 if ( $this->getCliArg( 'use-filebackend=' ) ) {
350 if ( self
::$backendToUse ) {
351 $backend = self
::$backendToUse;
353 $name = $this->getCliArg( 'use-filebackend=' );
354 $useConfig = array();
355 foreach ( $wgFileBackends as $conf ) {
356 if ( $conf['name'] == $name ) {
360 $useConfig['name'] = 'local-backend'; // swap name
361 unset( $useConfig['lockManager'] );
362 unset( $useConfig['fileJournal'] );
363 $class = $useConfig['class'];
364 self
::$backendToUse = new $class( $useConfig );
365 $backend = self
::$backendToUse;
368 # Replace with a mock. We do not care about generating real
369 # files on the filesystem, just need to expose the file
371 $backend = new MockFileBackend( array(
372 'name' => 'local-backend',
373 'wikiId' => wfWikiId()
378 'wgLocalFileRepo' => array(
379 'class' => 'LocalRepo',
381 'url' => 'http://example.com/images',
383 'transformVia404' => false,
384 'backend' => $backend
386 'wgEnableUploads' => self
::getOptionValue( 'wgEnableUploads', $opts, true ),
387 'wgLanguageCode' => $lang,
388 'wgDBprefix' => $this->db
->getType() != 'oracle' ?
'unittest_' : 'ut_',
389 'wgRawHtml' => self
::getOptionValue( 'wgRawHtml', $opts, false ),
390 'wgNamespacesWithSubpages' => array( NS_MAIN
=> isset( $opts['subpage'] ) ),
391 'wgAllowExternalImages' => self
::getOptionValue( 'wgAllowExternalImages', $opts, true ),
392 'wgThumbLimits' => array( self
::getOptionValue( 'thumbsize', $opts, 180 ) ),
393 'wgMaxTocLevel' => $maxtoclevel,
394 'wgUseTeX' => isset( $opts['math'] ) ||
isset( $opts['texvc'] ),
395 'wgMathDirectory' => $uploadDir . '/math',
396 'wgDefaultLanguageVariant' => $variant,
397 'wgLinkHolderBatchSize' => $linkHolderBatchSize,
401 $configLines = explode( "\n", $config );
403 foreach ( $configLines as $line ) {
404 list( $var, $value ) = explode( '=', $line, 2 );
406 $settings[$var] = eval( "return $value;" ); //???
410 $this->savedGlobals
= array();
413 wfRunHooks( 'ParserTestGlobals', array( &$settings ) );
415 $langObj = Language
::factory( $lang );
416 $settings['wgContLang'] = $langObj;
417 $settings['wgLang'] = $langObj;
419 $context = new RequestContext();
420 $settings['wgOut'] = $context->getOutput();
421 $settings['wgUser'] = $context->getUser();
422 $settings['wgRequest'] = $context->getRequest();
424 // We (re)set $wgThumbLimits to a single-element array above.
425 $context->getUser()->setOption( 'thumbsize', 0 );
427 foreach ( $settings as $var => $val ) {
428 if ( array_key_exists( $var, $GLOBALS ) ) {
429 $this->savedGlobals
[$var] = $GLOBALS[$var];
432 $GLOBALS[$var] = $val;
435 MagicWord
::clearCache();
437 # The entries saved into RepoGroup cache with previous globals will be wrong.
438 RepoGroup
::destroySingleton();
439 FileBackendGroup
::destroySingleton();
441 # Create dummy files in storage
442 $this->setupUploads();
444 # Publish the articles after we have the final language set
445 $this->publishTestArticles();
447 MessageCache
::destroyInstance();
453 * Get an FS upload directory (only applies to FSFileBackend)
455 * @return string The directory
457 protected function getUploadDir() {
458 if ( $this->keepUploads
) {
459 $dir = wfTempDir() . '/mwParser-images';
461 if ( is_dir( $dir ) ) {
465 $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
468 // wfDebug( "Creating upload directory $dir\n" );
469 if ( file_exists( $dir ) ) {
470 wfDebug( "Already exists!\n" );
479 * Create a dummy uploads directory which will contain a couple
480 * of files in order to pass existence tests.
482 * @return string The directory
484 protected function setupUploads() {
487 $base = $this->getBaseDir();
488 $backend = RepoGroup
::singleton()->getLocalRepo()->getBackend();
489 $backend->prepare( array( 'dir' => "$base/local-public/3/3a" ) );
490 $backend->store( array(
491 'src' => "$IP/skins/monobook/headbg.jpg", 'dst' => "$base/local-public/3/3a/Foobar.jpg"
493 $backend->prepare( array( 'dir' => "$base/local-public/e/ea" ) );
494 $backend->store( array(
495 'src' => "$IP/skins/monobook/wiki.png", 'dst' => "$base/local-public/e/ea/Thumb.png"
497 $backend->prepare( array( 'dir' => "$base/local-public/0/09" ) );
498 $backend->store( array(
499 'src' => "$IP/skins/monobook/headbg.jpg", 'dst' => "$base/local-public/0/09/Bad.jpg"
501 $backend->prepare( array( 'dir' => "$base/local-public/5/5f" ) );
502 $backend->store( array(
503 'src' => "$IP/tests/phpunit/data/media/LoremIpsum.djvu", 'dst' => "$base/local-public/5/5f/LoremIpsum.djvu"
506 // No helpful SVG file to copy, so make one ourselves
507 $data = '<?xml version="1.0" encoding="utf-8"?>' .
508 '<svg xmlns="http://www.w3.org/2000/svg"' .
509 ' version="1.1" width="240" height="180"/>';
511 $backend->prepare( array( 'dir' => "$base/local-public/f/ff" ) );
512 $backend->quickCreate( array(
513 'content' => $data, 'dst' => "$base/local-public/f/ff/Foobar.svg"
518 * Restore default values and perform any necessary clean-up
519 * after each test runs.
521 protected function teardownGlobals() {
522 $this->teardownUploads();
524 foreach ( $this->savedGlobals
as $var => $val ) {
525 $GLOBALS[$var] = $val;
530 * Remove the dummy uploads directory
532 private function teardownUploads() {
533 if ( $this->keepUploads
) {
537 $backend = RepoGroup
::singleton()->getLocalRepo()->getBackend();
538 if ( $backend instanceof MockFileBackend
) {
539 # In memory backend, so dont bother cleaning them up.
543 $base = $this->getBaseDir();
544 // delete the files first, then the dirs.
547 "$base/local-public/3/3a/Foobar.jpg",
548 "$base/local-thumb/3/3a/Foobar.jpg/1000px-Foobar.jpg",
549 "$base/local-thumb/3/3a/Foobar.jpg/100px-Foobar.jpg",
550 "$base/local-thumb/3/3a/Foobar.jpg/120px-Foobar.jpg",
551 "$base/local-thumb/3/3a/Foobar.jpg/1280px-Foobar.jpg",
552 "$base/local-thumb/3/3a/Foobar.jpg/137px-Foobar.jpg",
553 "$base/local-thumb/3/3a/Foobar.jpg/1500px-Foobar.jpg",
554 "$base/local-thumb/3/3a/Foobar.jpg/177px-Foobar.jpg",
555 "$base/local-thumb/3/3a/Foobar.jpg/180px-Foobar.jpg",
556 "$base/local-thumb/3/3a/Foobar.jpg/200px-Foobar.jpg",
557 "$base/local-thumb/3/3a/Foobar.jpg/206px-Foobar.jpg",
558 "$base/local-thumb/3/3a/Foobar.jpg/20px-Foobar.jpg",
559 "$base/local-thumb/3/3a/Foobar.jpg/220px-Foobar.jpg",
560 "$base/local-thumb/3/3a/Foobar.jpg/265px-Foobar.jpg",
561 "$base/local-thumb/3/3a/Foobar.jpg/270px-Foobar.jpg",
562 "$base/local-thumb/3/3a/Foobar.jpg/274px-Foobar.jpg",
563 "$base/local-thumb/3/3a/Foobar.jpg/300px-Foobar.jpg",
564 "$base/local-thumb/3/3a/Foobar.jpg/30px-Foobar.jpg",
565 "$base/local-thumb/3/3a/Foobar.jpg/330px-Foobar.jpg",
566 "$base/local-thumb/3/3a/Foobar.jpg/353px-Foobar.jpg",
567 "$base/local-thumb/3/3a/Foobar.jpg/360px-Foobar.jpg",
568 "$base/local-thumb/3/3a/Foobar.jpg/400px-Foobar.jpg",
569 "$base/local-thumb/3/3a/Foobar.jpg/40px-Foobar.jpg",
570 "$base/local-thumb/3/3a/Foobar.jpg/440px-Foobar.jpg",
571 "$base/local-thumb/3/3a/Foobar.jpg/442px-Foobar.jpg",
572 "$base/local-thumb/3/3a/Foobar.jpg/450px-Foobar.jpg",
573 "$base/local-thumb/3/3a/Foobar.jpg/50px-Foobar.jpg",
574 "$base/local-thumb/3/3a/Foobar.jpg/600px-Foobar.jpg",
575 "$base/local-thumb/3/3a/Foobar.jpg/640px-Foobar.jpg",
576 "$base/local-thumb/3/3a/Foobar.jpg/70px-Foobar.jpg",
577 "$base/local-thumb/3/3a/Foobar.jpg/75px-Foobar.jpg",
578 "$base/local-thumb/3/3a/Foobar.jpg/960px-Foobar.jpg",
580 "$base/local-public/e/ea/Thumb.png",
582 "$base/local-public/0/09/Bad.jpg",
584 "$base/local-public/5/5f/LoremIpsum.djvu",
585 "$base/local-thumb/5/5f/LoremIpsum.djvu/page2-2480px-LoremIpsum.djvu.jpg",
586 "$base/local-thumb/5/5f/LoremIpsum.djvu/page2-3720px-LoremIpsum.djvu.jpg",
587 "$base/local-thumb/5/5f/LoremIpsum.djvu/page2-4960px-LoremIpsum.djvu.jpg",
589 "$base/local-public/f/ff/Foobar.svg",
590 "$base/local-thumb/f/ff/Foobar.svg/180px-Foobar.svg.png",
591 "$base/local-thumb/f/ff/Foobar.svg/2000px-Foobar.svg.png",
592 "$base/local-thumb/f/ff/Foobar.svg/270px-Foobar.svg.png",
593 "$base/local-thumb/f/ff/Foobar.svg/3000px-Foobar.svg.png",
594 "$base/local-thumb/f/ff/Foobar.svg/360px-Foobar.svg.png",
595 "$base/local-thumb/f/ff/Foobar.svg/4000px-Foobar.svg.png",
596 "$base/local-thumb/f/ff/Foobar.svg/langde-180px-Foobar.svg.png",
597 "$base/local-thumb/f/ff/Foobar.svg/langde-270px-Foobar.svg.png",
598 "$base/local-thumb/f/ff/Foobar.svg/langde-360px-Foobar.svg.png",
600 "$base/local-public/math/f/a/5/fa50b8b616463173474302ca3e63586b.png",
606 * Delete the specified files, if they exist.
607 * @param array $files Full paths to files to delete.
609 private static function deleteFiles( $files ) {
610 $backend = RepoGroup
::singleton()->getLocalRepo()->getBackend();
611 foreach ( $files as $file ) {
612 $backend->delete( array( 'src' => $file ), array( 'force' => 1 ) );
614 foreach ( $files as $file ) {
616 while ( $tmp = FileBackend
::parentStoragePath( $tmp ) ) {
617 if ( !$backend->clean( array( 'dir' => $tmp ) )->isOK() ) {
624 protected function getBaseDir() {
625 return 'mwstore://local-backend';
628 public function parserTestProvider() {
629 if ( $this->file
=== false ) {
630 global $wgParserTestFiles;
631 $this->file
= $wgParserTestFiles[0];
634 return new TestFileIterator( $this->file
, $this );
638 * Set the file from whose tests will be run by this instance
639 * @param string $filename
641 public function setParserTestFile( $filename ) {
642 $this->file
= $filename;
647 * @dataProvider parserTestProvider
648 * @param string $desc
649 * @param string $input
650 * @param string $result
652 * @param array $config
654 public function testParserTest( $desc, $input, $result, $opts, $config ) {
655 if ( $this->regex
!= '' && !preg_match( '/' . $this->regex
. '/', $desc ) ) {
656 $this->assertTrue( true ); // XXX: don't flood output with "test made no assertions"
657 //$this->markTestSkipped( 'Filtered out by the user' );
661 if ( !$this->isWikitextNS( NS_MAIN
) ) {
662 // parser tests frequently assume that the main namespace contains wikitext.
663 // @todo When setting up pages, force the content model. Only skip if
664 // $wgtContentModelUseDB is false.
665 $this->markTestSkipped( "Main namespace does not support wikitext,"
666 . "skipping parser test: $desc" );
669 wfDebug( "Running parser test: $desc\n" );
671 $opts = $this->parseOptions( $opts );
672 $context = $this->setupGlobals( $opts, $config );
674 $user = $context->getUser();
675 $options = ParserOptions
::newFromContext( $context );
677 if ( isset( $opts['title'] ) ) {
678 $titleText = $opts['title'];
680 $titleText = 'Parser test';
683 $local = isset( $opts['local'] );
684 $preprocessor = isset( $opts['preprocessor'] ) ?
$opts['preprocessor'] : null;
685 $parser = $this->getParser( $preprocessor );
687 $title = Title
::newFromText( $titleText );
689 # Parser test requiring math. Make sure texvc is executable
690 # or just skip such tests.
691 if ( isset( $opts['math'] ) ||
isset( $opts['texvc'] ) ) {
694 if ( !isset( $wgTexvc ) ) {
695 $this->markTestSkipped( "SKIPPED: \$wgTexvc is not set" );
696 } elseif ( !is_executable( $wgTexvc ) ) {
697 $this->markTestSkipped( "SKIPPED: texvc binary does not exist"
698 . " or is not executable.\n"
699 . "Current configuration is:\n\$wgTexvc = '$wgTexvc'" );
702 if ( isset( $opts['djvu'] ) ) {
703 if ( !$this->djVuSupport
->isEnabled() ) {
704 $this->markTestSkipped( "SKIPPED: djvu binaries do not exist or are not executable.\n" );
708 if ( isset( $opts['pst'] ) ) {
709 $out = $parser->preSaveTransform( $input, $title, $user, $options );
710 } elseif ( isset( $opts['msg'] ) ) {
711 $out = $parser->transformMsg( $input, $options, $title );
712 } elseif ( isset( $opts['section'] ) ) {
713 $section = $opts['section'];
714 $out = $parser->getSection( $input, $section );
715 } elseif ( isset( $opts['replace'] ) ) {
716 $section = $opts['replace'][0];
717 $replace = $opts['replace'][1];
718 $out = $parser->replaceSection( $input, $section, $replace );
719 } elseif ( isset( $opts['comment'] ) ) {
720 $out = Linker
::formatComment( $input, $title, $local );
721 } elseif ( isset( $opts['preload'] ) ) {
722 $out = $parser->getPreloadText( $input, $title, $options );
724 $output = $parser->parse( $input, $title, $options, true, true, 1337 );
725 $output->setTOCEnabled( !isset( $opts['notoc'] ) );
726 $out = $output->getText();
728 if ( isset( $opts['showtitle'] ) ) {
729 if ( $output->getTitleText() ) {
730 $title = $output->getTitleText();
733 $out = "$title\n$out";
736 if ( isset( $opts['ill'] ) ) {
737 $out = $this->tidy( implode( ' ', $output->getLanguageLinks() ) );
738 } elseif ( isset( $opts['cat'] ) ) {
739 $outputPage = $context->getOutput();
740 $outputPage->addCategoryLinks( $output->getCategories() );
741 $cats = $outputPage->getCategoryLinks();
743 if ( isset( $cats['normal'] ) ) {
744 $out = $this->tidy( implode( ' ', $cats['normal'] ) );
749 $parser->mPreprocessor
= null;
751 $result = $this->tidy( $result );
754 $this->teardownGlobals();
756 $this->assertEquals( $result, $out, $desc );
760 * Run a fuzz test series
761 * Draw input from a set of test files
763 * @todo fixme Needs some work to not eat memory until the world explodes
767 public function testFuzzTests() {
768 global $wgParserTestFiles;
770 $files = $wgParserTestFiles;
772 if ( $this->getCliArg( 'file=' ) ) {
773 $files = array( $this->getCliArg( 'file=' ) );
776 $dict = $this->getFuzzInput( $files );
777 $dictSize = strlen( $dict );
778 $logMaxLength = log( $this->maxFuzzTestLength
);
780 ini_set( 'memory_limit', $this->memoryLimit
* 1048576 );
783 $opts = ParserOptions
::newFromUser( $user );
784 $title = Title
::makeTitle( NS_MAIN
, 'Parser_test' );
790 // Generate test input
791 mt_srand( ++
$this->fuzzSeed
);
792 $totalLength = mt_rand( 1, $this->maxFuzzTestLength
);
795 while ( strlen( $input ) < $totalLength ) {
796 $logHairLength = mt_rand( 0, 1000000 ) / 1000000 * $logMaxLength;
797 $hairLength = min( intval( exp( $logHairLength ) ), $dictSize );
798 $offset = mt_rand( 0, $dictSize - $hairLength );
799 $input .= substr( $dict, $offset, $hairLength );
802 $this->setupGlobals();
803 $parser = $this->getParser();
807 $parser->parse( $input, $title, $opts );
808 $this->assertTrue( true, "Test $id, fuzz seed {$this->fuzzSeed}" );
809 } catch ( Exception
$exception ) {
810 $input_dump = sprintf( "string(%d) \"%s\"\n", strlen( $input ), $input );
812 $this->assertTrue( false, "Test $id, fuzz seed {$this->fuzzSeed}. \n\n" .
813 "Input: $input_dump\n\nError: {$exception->getMessage()}\n\n" .
814 "Backtrace: {$exception->getTraceAsString()}" );
817 $this->teardownGlobals();
818 $parser->__destruct();
820 if ( $id %
100 == 0 ) {
821 $usage = intval( memory_get_usage( true ) / $this->memoryLimit
/ 1048576 * 100 );
822 //echo "{$this->fuzzSeed}: $numSuccess/$numTotal (mem: $usage%)\n";
824 $ret = "Out of memory:\n";
825 $memStats = $this->getMemoryBreakdown();
827 foreach ( $memStats as $name => $usage ) {
828 $ret .= "$name: $usage\n";
831 throw new MWException( $ret );
839 //Various getter functions
842 * Get an input dictionary from a set of parser test files
843 * @param array $filenames
845 function getFuzzInput( $filenames ) {
848 foreach ( $filenames as $filename ) {
849 $contents = file_get_contents( $filename );
850 preg_match_all( '/!!\s*input\n(.*?)\n!!\s*result/s', $contents, $matches );
852 foreach ( $matches[1] as $match ) {
853 $dict .= $match . "\n";
861 * Get a memory usage breakdown
863 function getMemoryBreakdown() {
866 foreach ( $GLOBALS as $name => $value ) {
867 $memStats['$' . $name] = strlen( serialize( $value ) );
870 $classes = get_declared_classes();
872 foreach ( $classes as $class ) {
873 $rc = new ReflectionClass( $class );
874 $props = $rc->getStaticProperties();
875 $memStats[$class] = strlen( serialize( $props ) );
876 $methods = $rc->getMethods();
878 foreach ( $methods as $method ) {
879 $memStats[$class] +
= strlen( serialize( $method->getStaticVariables() ) );
883 $functions = get_defined_functions();
885 foreach ( $functions['user'] as $function ) {
886 $rf = new ReflectionFunction( $function );
887 $memStats["$function()"] = strlen( serialize( $rf->getStaticVariables() ) );
896 * Get a Parser object
897 * @param Preprocessor $preprocessor
899 function getParser( $preprocessor = null ) {
900 global $wgParserConf;
902 $class = $wgParserConf['class'];
903 $parser = new $class( array( 'preprocessorClass' => $preprocessor ) +
$wgParserConf );
905 wfRunHooks( 'ParserTestParser', array( &$parser ) );
910 //Various action functions
912 public function addArticle( $name, $text, $line ) {
913 self
::$articles[$name] = array( $text, $line );
916 public function publishTestArticles() {
917 if ( empty( self
::$articles ) ) {
921 foreach ( self
::$articles as $name => $info ) {
922 list( $text, $line ) = $info;
923 ParserTest
::addArticle( $name, $text, $line, 'ignoreduplicate' );
928 * Steal a callback function from the primary parser, save it for
929 * application to our scary parser. If the hook is not installed,
930 * abort processing of this file.
932 * @param string $name
933 * @return bool True if tag hook is present
935 public function requireHook( $name ) {
937 $wgParser->firstCallInit(); // make sure hooks are loaded.
938 return isset( $wgParser->mTagHooks
[$name] );
941 public function requireFunctionHook( $name ) {
943 $wgParser->firstCallInit(); // make sure hooks are loaded.
944 return isset( $wgParser->mFunctionHooks
[$name] );
947 //Various "cleanup" functions
950 * Run the "tidy" command on text if the $wgUseTidy
953 * @param string $text The text to tidy
956 protected function tidy( $text ) {
960 $text = MWTidy
::tidy( $text );
967 * Remove last character if it is a newline
970 public function removeEndingNewline( $s ) {
971 if ( substr( $s, -1 ) === "\n" ) {
972 return substr( $s, 0, -1 );
978 //Test options parser functions
980 protected function parseOptions( $instring ) {
986 // foo=bar,"baz quux"
1008 "[^"]*" # Quoted val
1010 \[\[[^]]*\]\] # Link target
1018 if ( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER
) ) {
1019 foreach ( $matches as $bits ) {
1020 array_shift( $bits );
1021 $key = strtolower( array_shift( $bits ) );
1022 if ( count( $bits ) == 0 ) {
1024 } elseif ( count( $bits ) == 1 ) {
1025 $opts[$key] = $this->cleanupOption( array_shift( $bits ) );
1028 $opts[$key] = array_map( array( $this, 'cleanupOption' ), $bits );
1036 protected function cleanupOption( $opt ) {
1037 if ( substr( $opt, 0, 1 ) == '"' ) {
1038 return substr( $opt, 1, -1 );
1041 if ( substr( $opt, 0, 2 ) == '[[' ) {
1042 return substr( $opt, 2, -2 );
1049 * Use a regex to find out the value of an option
1050 * @param string $key Name of option val to retrieve
1051 * @param array $opts Options array to look in
1052 * @param mixed $default Default value returned if not found
1054 protected static function getOptionValue( $key, $opts, $default ) {
1055 $key = strtolower( $key );
1057 if ( isset( $opts[$key] ) ) {