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();
28 public $transparentHooks = array();
31 public $maxFuzzTestLength = 300;
33 public $memoryLimit = 50;
40 protected $file = false;
42 public static function setUpBeforeClass() {
43 // Inject ParserTest well-known interwikis
44 ParserTest
::setupInterwikis();
47 protected function setUp() {
48 global $wgNamespaceAliases, $wgContLang;
54 if ( $this->getCliArg( 'regex=' ) ) {
55 $this->regex
= $this->getCliArg( 'regex=' );
61 $this->keepUploads
= $this->getCliArg( 'keep-uploads' );
63 $tmpGlobals = array();
65 $tmpGlobals['wgLanguageCode'] = 'en';
66 $tmpGlobals['wgContLang'] = Language
::factory( 'en' );
67 $tmpGlobals['wgSitename'] = 'MediaWiki';
68 $tmpGlobals['wgServer'] = 'http://example.org';
69 $tmpGlobals['wgServerName'] = 'example.org';
70 $tmpGlobals['wgScript'] = '/index.php';
71 $tmpGlobals['wgScriptPath'] = '/';
72 $tmpGlobals['wgArticlePath'] = '/wiki/$1';
73 $tmpGlobals['wgActionPaths'] = array();
74 $tmpGlobals['wgVariantArticlePath'] = false;
75 $tmpGlobals['wgExtensionAssetsPath'] = '/extensions';
76 $tmpGlobals['wgStylePath'] = '/skins';
77 $tmpGlobals['wgEnableUploads'] = true;
78 $tmpGlobals['wgThumbnailScriptPath'] = false;
79 $tmpGlobals['wgLocalFileRepo'] = array(
80 'class' => 'LocalRepo',
82 'url' => 'http://example.com/images',
84 'transformVia404' => false,
85 'backend' => 'local-backend'
87 $tmpGlobals['wgForeignFileRepos'] = array();
88 $tmpGlobals['wgDefaultExternalStore'] = array();
89 $tmpGlobals['wgEnableParserCache'] = false;
90 $tmpGlobals['wgCapitalLinks'] = true;
91 $tmpGlobals['wgNoFollowLinks'] = true;
92 $tmpGlobals['wgNoFollowDomainExceptions'] = array();
93 $tmpGlobals['wgExternalLinkTarget'] = false;
94 $tmpGlobals['wgThumbnailScriptPath'] = false;
95 $tmpGlobals['wgUseImageResize'] = true;
96 $tmpGlobals['wgAllowExternalImages'] = true;
97 $tmpGlobals['wgRawHtml'] = false;
98 $tmpGlobals['wgUseTidy'] = false;
99 $tmpGlobals['wgAlwaysUseTidy'] = false;
100 $tmpGlobals['wgWellFormedXml'] = true;
101 $tmpGlobals['wgAllowMicrodataAttributes'] = true;
102 $tmpGlobals['wgExperimentalHtmlIds'] = false;
103 $tmpGlobals['wgAdaptiveMessageCache'] = true;
104 $tmpGlobals['wgUseDatabaseMessages'] = true;
105 $tmpGlobals['wgLocaltimezone'] = 'UTC';
106 $tmpGlobals['wgDeferredUpdateList'] = array();
107 $tmpGlobals['wgGroupPermissions'] = array(
109 'createaccount' => true,
112 'createpage' => true,
113 'createtalk' => true,
115 $tmpGlobals['wgNamespaceProtection'] = array( NS_MEDIAWIKI
=> 'editinterface' );
117 $tmpGlobals['wgParser'] = new StubObject(
118 'wgParser', $GLOBALS['wgParserConf']['class'],
119 array( $GLOBALS['wgParserConf'] ) );
121 $tmpGlobals['wgFileExtensions'][] = 'svg';
122 $tmpGlobals['wgSVGConverter'] = 'rsvg';
123 $tmpGlobals['wgSVGConverters']['rsvg'] =
124 '$path/rsvg-convert -w $width -h $height $input -o $output';
126 if ( $GLOBALS['wgStyleDirectory'] === false ) {
127 $tmpGlobals['wgStyleDirectory'] = "$IP/skins";
130 # Replace all media handlers with a mock. We do not need to generate
131 # actual thumbnails to do parser testing, we only care about receiving
132 # a ThumbnailImage properly initialized.
133 global $wgMediaHandlers;
134 foreach ( $wgMediaHandlers as $type => $handler ) {
135 $tmpGlobals['wgMediaHandlers'][$type] = 'MockBitmapHandler';
137 // Vector images have to be handled slightly differently
138 $tmpGlobals['wgMediaHandlers']['image/svg+xml'] = 'MockSvgHandler';
140 // DjVu images have to be handled slightly differently
141 $tmpGlobals['wgMediaHandlers']['image/vnd.djvu'] = 'MockDjVuHandler';
143 $tmpHooks = $wgHooks;
144 $tmpHooks['ParserTestParser'][] = 'ParserTestParserHook::setup';
145 $tmpHooks['ParserGetVariableValueTs'][] = 'ParserTest::getFakeTimestamp';
146 $tmpGlobals['wgHooks'] = $tmpHooks;
147 # add a namespace shadowing a interwiki link, to test
148 # proper precedence when resolving links. (bug 51680)
149 $tmpGlobals['wgExtraNamespaces'] = array( 100 => 'MemoryAlpha' );
152 $this->djVuSupport
= new DjVuSupport();
154 $this->setMwGlobals( $tmpGlobals );
156 $this->savedWeirdGlobals
['image_alias'] = $wgNamespaceAliases['Image'];
157 $this->savedWeirdGlobals
['image_talk_alias'] = $wgNamespaceAliases['Image_talk'];
159 $wgNamespaceAliases['Image'] = NS_FILE
;
160 $wgNamespaceAliases['Image_talk'] = NS_FILE_TALK
;
162 MWNamespace
::getCanonicalNamespaces( true ); # reset namespace cache
163 $wgContLang->resetNamespaces(); # reset namespace cache
166 protected function tearDown() {
167 global $wgNamespaceAliases, $wgContLang;
169 $wgNamespaceAliases['Image'] = $this->savedWeirdGlobals
['image_alias'];
170 $wgNamespaceAliases['Image_talk'] = $this->savedWeirdGlobals
['image_talk_alias'];
173 RepoGroup
::destroySingleton();
174 FileBackendGroup
::destroySingleton();
176 // Remove temporary pages from the link cache
177 LinkCache
::singleton()->clear();
179 // Restore message cache (temporary pages and $wgUseDatabaseMessages)
180 MessageCache
::destroyInstance();
184 MWNamespace
::getCanonicalNamespaces( true ); # reset namespace cache
185 $wgContLang->resetNamespaces(); # reset namespace cache
188 public static function tearDownAfterClass() {
189 ParserTest
::tearDownInterwikis();
190 parent
::tearDownAfterClass();
193 function addDBData() {
194 $this->tablesUsed
[] = 'site_stats';
195 # disabled for performance
196 #$this->tablesUsed[] = 'image';
198 # Update certain things in site_stats
199 $this->db
->insert( 'site_stats',
200 array( 'ss_row_id' => 1, 'ss_images' => 2, 'ss_good_articles' => 1 ),
204 $user = User
::newFromId( 0 );
205 LinkCache
::singleton()->clear(); # Avoids the odd failure at creating the nullRevision
207 # Upload DB table entries for files.
208 # We will upload the actual files later. Note that if anything causes LocalFile::load()
209 # to be triggered before then, it will break via maybeUpgrade() setting the fileExists
210 # member to false and storing it in cache.
211 # note that the size/width/height/bits/etc of the file
212 # are actually set by inspecting the file itself; the arguments
213 # to recordUpload2 have no effect. That said, we try to make things
214 # match up so it is less confusing to readers of the code & tests.
215 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Foobar.jpg' ) );
216 if ( !$this->db
->selectField( 'image', '1', array( 'img_name' => $image->getName() ) ) ) {
217 $image->recordUpload2(
219 'Upload of some lame file',
226 'media_type' => MEDIATYPE_BITMAP
,
227 'mime' => 'image/jpeg',
228 'metadata' => serialize( array() ),
229 'sha1' => wfBaseConvert( '1', 16, 36, 31 ),
230 'fileExists' => true ),
231 $this->db
->timestamp( '20010115123500' ), $user
235 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Thumb.png' ) );
236 if ( !$this->db
->selectField( 'image', '1', array( 'img_name' => $image->getName() ) ) ) {
237 $image->recordUpload2(
239 'Upload of some lame thumbnail',
240 'Some lame thumbnail',
246 'media_type' => MEDIATYPE_BITMAP
,
247 'mime' => 'image/png',
248 'metadata' => serialize( array() ),
249 'sha1' => wfBaseConvert( '2', 16, 36, 31 ),
250 'fileExists' => true ),
251 $this->db
->timestamp( '20130225203040' ), $user
255 # This image will be blacklisted in [[MediaWiki:Bad image list]]
256 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Bad.jpg' ) );
257 if ( !$this->db
->selectField( 'image', '1', array( 'img_name' => $image->getName() ) ) ) {
258 $image->recordUpload2(
267 'media_type' => MEDIATYPE_BITMAP
,
268 'mime' => 'image/jpeg',
269 'metadata' => serialize( array() ),
270 'sha1' => wfBaseConvert( '3', 16, 36, 31 ),
271 'fileExists' => true ),
272 $this->db
->timestamp( '20010115123500' ), $user
275 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Foobar.svg' ) );
276 if ( !$this->db
->selectField( 'image', '1', array( 'img_name' => $image->getName() ) ) ) {
277 $image->recordUpload2( '', 'Upload of some lame SVG', 'Some lame SVG', array(
282 'media_type' => MEDIATYPE_DRAWING
,
283 'mime' => 'image/svg+xml',
284 'metadata' => serialize( array() ),
285 'sha1' => wfBaseConvert( '', 16, 36, 31 ),
287 ), $this->db
->timestamp( '20010115123500' ), $user );
291 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'LoremIpsum.djvu' ) );
292 if ( !$this->db
->selectField( 'image', '1', array( 'img_name' => $image->getName() ) ) ) {
293 $image->recordUpload2( '', 'Upload a DjVu', 'A DjVu', array(
298 'media_type' => MEDIATYPE_BITMAP
,
299 'mime' => 'image/vnd.djvu',
300 'metadata' => '<?xml version="1.0" ?>
301 <!DOCTYPE DjVuXML PUBLIC "-//W3C//DTD DjVuXML 1.1//EN" "pubtext/DjVuXML-s.dtd">
304 <BODY><OBJECT height="3508" width="2480">
305 <PARAM name="DPI" value="300" />
306 <PARAM name="GAMMA" value="2.2" />
308 <OBJECT height="3508" width="2480">
309 <PARAM name="DPI" value="300" />
310 <PARAM name="GAMMA" value="2.2" />
312 <OBJECT height="3508" width="2480">
313 <PARAM name="DPI" value="300" />
314 <PARAM name="GAMMA" value="2.2" />
316 <OBJECT height="3508" width="2480">
317 <PARAM name="DPI" value="300" />
318 <PARAM name="GAMMA" value="2.2" />
320 <OBJECT height="3508" width="2480">
321 <PARAM name="DPI" value="300" />
322 <PARAM name="GAMMA" value="2.2" />
326 'sha1' => wfBaseConvert( '', 16, 36, 31 ),
328 ), $this->db
->timestamp( '20140115123600' ), $user );
332 //ParserTest setup/teardown functions
335 * Set up the global variables for a consistent environment for each test.
336 * Ideally this should replace the global configuration entirely.
338 protected function setupGlobals( $opts = array(), $config = '' ) {
339 global $wgFileBackends;
340 # Find out values for some special options.
342 self
::getOptionValue( 'language', $opts, 'en' );
344 self
::getOptionValue( 'variant', $opts, false );
346 self
::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
347 $linkHolderBatchSize =
348 self
::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
350 $uploadDir = $this->getUploadDir();
351 if ( $this->getCliArg( 'use-filebackend=' ) ) {
352 if ( self
::$backendToUse ) {
353 $backend = self
::$backendToUse;
355 $name = $this->getCliArg( 'use-filebackend=' );
356 $useConfig = array();
357 foreach ( $wgFileBackends as $conf ) {
358 if ( $conf['name'] == $name ) {
362 $useConfig['name'] = 'local-backend'; // swap name
363 unset( $useConfig['lockManager'] );
364 unset( $useConfig['fileJournal'] );
365 $class = $useConfig['class'];
366 self
::$backendToUse = new $class( $useConfig );
367 $backend = self
::$backendToUse;
370 # Replace with a mock. We do not care about generating real
371 # files on the filesystem, just need to expose the file
373 $backend = new MockFileBackend( array(
374 'name' => 'local-backend',
375 'wikiId' => wfWikiId()
380 'wgLocalFileRepo' => array(
381 'class' => 'LocalRepo',
383 'url' => 'http://example.com/images',
385 'transformVia404' => false,
386 'backend' => $backend
388 'wgEnableUploads' => self
::getOptionValue( 'wgEnableUploads', $opts, true ),
389 'wgLanguageCode' => $lang,
390 'wgDBprefix' => $this->db
->getType() != 'oracle' ?
'unittest_' : 'ut_',
391 'wgRawHtml' => self
::getOptionValue( 'wgRawHtml', $opts, false ),
392 'wgNamespacesWithSubpages' => array( NS_MAIN
=> isset( $opts['subpage'] ) ),
393 'wgAllowExternalImages' => self
::getOptionValue( 'wgAllowExternalImages', $opts, true ),
394 'wgThumbLimits' => array( self
::getOptionValue( 'thumbsize', $opts, 180 ) ),
395 'wgMaxTocLevel' => $maxtoclevel,
396 'wgUseTeX' => isset( $opts['math'] ) ||
isset( $opts['texvc'] ),
397 'wgMathDirectory' => $uploadDir . '/math',
398 'wgDefaultLanguageVariant' => $variant,
399 'wgLinkHolderBatchSize' => $linkHolderBatchSize,
403 $configLines = explode( "\n", $config );
405 foreach ( $configLines as $line ) {
406 list( $var, $value ) = explode( '=', $line, 2 );
408 $settings[$var] = eval( "return $value;" ); //???
412 $this->savedGlobals
= array();
415 wfRunHooks( 'ParserTestGlobals', array( &$settings ) );
417 $langObj = Language
::factory( $lang );
418 $settings['wgContLang'] = $langObj;
419 $settings['wgLang'] = $langObj;
421 $context = new RequestContext();
422 $settings['wgOut'] = $context->getOutput();
423 $settings['wgUser'] = $context->getUser();
424 $settings['wgRequest'] = $context->getRequest();
426 // We (re)set $wgThumbLimits to a single-element array above.
427 $context->getUser()->setOption( 'thumbsize', 0 );
429 foreach ( $settings as $var => $val ) {
430 if ( array_key_exists( $var, $GLOBALS ) ) {
431 $this->savedGlobals
[$var] = $GLOBALS[$var];
434 $GLOBALS[$var] = $val;
437 MagicWord
::clearCache();
439 # The entries saved into RepoGroup cache with previous globals will be wrong.
440 RepoGroup
::destroySingleton();
441 FileBackendGroup
::destroySingleton();
443 # Create dummy files in storage
444 $this->setupUploads();
446 # Publish the articles after we have the final language set
447 $this->publishTestArticles();
449 MessageCache
::destroyInstance();
455 * Get an FS upload directory (only applies to FSFileBackend)
457 * @return string The directory
459 protected function getUploadDir() {
460 if ( $this->keepUploads
) {
461 $dir = wfTempDir() . '/mwParser-images';
463 if ( is_dir( $dir ) ) {
467 $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
470 // wfDebug( "Creating upload directory $dir\n" );
471 if ( file_exists( $dir ) ) {
472 wfDebug( "Already exists!\n" );
481 * Create a dummy uploads directory which will contain a couple
482 * of files in order to pass existence tests.
484 * @return string The directory
486 protected function setupUploads() {
489 $base = $this->getBaseDir();
490 $backend = RepoGroup
::singleton()->getLocalRepo()->getBackend();
491 $backend->prepare( array( 'dir' => "$base/local-public/3/3a" ) );
492 $backend->store( array(
493 'src' => "$IP/tests/phpunit/data/parser/headbg.jpg", 'dst' => "$base/local-public/3/3a/Foobar.jpg"
495 $backend->prepare( array( 'dir' => "$base/local-public/e/ea" ) );
496 $backend->store( array(
497 'src' => "$IP/tests/phpunit/data/parser/wiki.png", 'dst' => "$base/local-public/e/ea/Thumb.png"
499 $backend->prepare( array( 'dir' => "$base/local-public/0/09" ) );
500 $backend->store( array(
501 'src' => "$IP/tests/phpunit/data/parser/headbg.jpg", 'dst' => "$base/local-public/0/09/Bad.jpg"
503 $backend->prepare( array( 'dir' => "$base/local-public/5/5f" ) );
504 $backend->store( array(
505 'src' => "$IP/tests/phpunit/data/parser/LoremIpsum.djvu", 'dst' => "$base/local-public/5/5f/LoremIpsum.djvu"
508 // No helpful SVG file to copy, so make one ourselves
509 $data = '<?xml version="1.0" encoding="utf-8"?>' .
510 '<svg xmlns="http://www.w3.org/2000/svg"' .
511 ' version="1.1" width="240" height="180"/>';
513 $backend->prepare( array( 'dir' => "$base/local-public/f/ff" ) );
514 $backend->quickCreate( array(
515 'content' => $data, 'dst' => "$base/local-public/f/ff/Foobar.svg"
520 * Restore default values and perform any necessary clean-up
521 * after each test runs.
523 protected function teardownGlobals() {
524 $this->teardownUploads();
526 foreach ( $this->savedGlobals
as $var => $val ) {
527 $GLOBALS[$var] = $val;
532 * Remove the dummy uploads directory
534 private function teardownUploads() {
535 if ( $this->keepUploads
) {
539 $backend = RepoGroup
::singleton()->getLocalRepo()->getBackend();
540 if ( $backend instanceof MockFileBackend
) {
541 # In memory backend, so dont bother cleaning them up.
545 $base = $this->getBaseDir();
546 // delete the files first, then the dirs.
549 "$base/local-public/3/3a/Foobar.jpg",
550 "$base/local-thumb/3/3a/Foobar.jpg/1000px-Foobar.jpg",
551 "$base/local-thumb/3/3a/Foobar.jpg/100px-Foobar.jpg",
552 "$base/local-thumb/3/3a/Foobar.jpg/120px-Foobar.jpg",
553 "$base/local-thumb/3/3a/Foobar.jpg/1280px-Foobar.jpg",
554 "$base/local-thumb/3/3a/Foobar.jpg/137px-Foobar.jpg",
555 "$base/local-thumb/3/3a/Foobar.jpg/1500px-Foobar.jpg",
556 "$base/local-thumb/3/3a/Foobar.jpg/177px-Foobar.jpg",
557 "$base/local-thumb/3/3a/Foobar.jpg/180px-Foobar.jpg",
558 "$base/local-thumb/3/3a/Foobar.jpg/200px-Foobar.jpg",
559 "$base/local-thumb/3/3a/Foobar.jpg/206px-Foobar.jpg",
560 "$base/local-thumb/3/3a/Foobar.jpg/20px-Foobar.jpg",
561 "$base/local-thumb/3/3a/Foobar.jpg/220px-Foobar.jpg",
562 "$base/local-thumb/3/3a/Foobar.jpg/265px-Foobar.jpg",
563 "$base/local-thumb/3/3a/Foobar.jpg/270px-Foobar.jpg",
564 "$base/local-thumb/3/3a/Foobar.jpg/274px-Foobar.jpg",
565 "$base/local-thumb/3/3a/Foobar.jpg/300px-Foobar.jpg",
566 "$base/local-thumb/3/3a/Foobar.jpg/30px-Foobar.jpg",
567 "$base/local-thumb/3/3a/Foobar.jpg/330px-Foobar.jpg",
568 "$base/local-thumb/3/3a/Foobar.jpg/353px-Foobar.jpg",
569 "$base/local-thumb/3/3a/Foobar.jpg/360px-Foobar.jpg",
570 "$base/local-thumb/3/3a/Foobar.jpg/400px-Foobar.jpg",
571 "$base/local-thumb/3/3a/Foobar.jpg/40px-Foobar.jpg",
572 "$base/local-thumb/3/3a/Foobar.jpg/440px-Foobar.jpg",
573 "$base/local-thumb/3/3a/Foobar.jpg/442px-Foobar.jpg",
574 "$base/local-thumb/3/3a/Foobar.jpg/450px-Foobar.jpg",
575 "$base/local-thumb/3/3a/Foobar.jpg/50px-Foobar.jpg",
576 "$base/local-thumb/3/3a/Foobar.jpg/600px-Foobar.jpg",
577 "$base/local-thumb/3/3a/Foobar.jpg/640px-Foobar.jpg",
578 "$base/local-thumb/3/3a/Foobar.jpg/70px-Foobar.jpg",
579 "$base/local-thumb/3/3a/Foobar.jpg/75px-Foobar.jpg",
580 "$base/local-thumb/3/3a/Foobar.jpg/960px-Foobar.jpg",
582 "$base/local-public/e/ea/Thumb.png",
584 "$base/local-public/0/09/Bad.jpg",
586 "$base/local-public/5/5f/LoremIpsum.djvu",
587 "$base/local-thumb/5/5f/LoremIpsum.djvu/page2-2480px-LoremIpsum.djvu.jpg",
588 "$base/local-thumb/5/5f/LoremIpsum.djvu/page2-3720px-LoremIpsum.djvu.jpg",
589 "$base/local-thumb/5/5f/LoremIpsum.djvu/page2-4960px-LoremIpsum.djvu.jpg",
591 "$base/local-public/f/ff/Foobar.svg",
592 "$base/local-thumb/f/ff/Foobar.svg/180px-Foobar.svg.png",
593 "$base/local-thumb/f/ff/Foobar.svg/2000px-Foobar.svg.png",
594 "$base/local-thumb/f/ff/Foobar.svg/270px-Foobar.svg.png",
595 "$base/local-thumb/f/ff/Foobar.svg/3000px-Foobar.svg.png",
596 "$base/local-thumb/f/ff/Foobar.svg/360px-Foobar.svg.png",
597 "$base/local-thumb/f/ff/Foobar.svg/4000px-Foobar.svg.png",
598 "$base/local-thumb/f/ff/Foobar.svg/langde-180px-Foobar.svg.png",
599 "$base/local-thumb/f/ff/Foobar.svg/langde-270px-Foobar.svg.png",
600 "$base/local-thumb/f/ff/Foobar.svg/langde-360px-Foobar.svg.png",
602 "$base/local-public/math/f/a/5/fa50b8b616463173474302ca3e63586b.png",
608 * Delete the specified files, if they exist.
609 * @param array $files Full paths to files to delete.
611 private static function deleteFiles( $files ) {
612 $backend = RepoGroup
::singleton()->getLocalRepo()->getBackend();
613 foreach ( $files as $file ) {
614 $backend->delete( array( 'src' => $file ), array( 'force' => 1 ) );
616 foreach ( $files as $file ) {
618 while ( $tmp = FileBackend
::parentStoragePath( $tmp ) ) {
619 if ( !$backend->clean( array( 'dir' => $tmp ) )->isOK() ) {
626 protected function getBaseDir() {
627 return 'mwstore://local-backend';
630 public function parserTestProvider() {
631 if ( $this->file
=== false ) {
632 global $wgParserTestFiles;
633 $this->file
= $wgParserTestFiles[0];
636 return new TestFileIterator( $this->file
, $this );
640 * Set the file from whose tests will be run by this instance
641 * @param string $filename
643 public function setParserTestFile( $filename ) {
644 $this->file
= $filename;
649 * @dataProvider parserTestProvider
650 * @param string $desc
651 * @param string $input
652 * @param string $result
654 * @param array $config
656 public function testParserTest( $desc, $input, $result, $opts, $config ) {
657 if ( $this->regex
!= '' && !preg_match( '/' . $this->regex
. '/', $desc ) ) {
658 $this->assertTrue( true ); // XXX: don't flood output with "test made no assertions"
659 //$this->markTestSkipped( 'Filtered out by the user' );
663 if ( !$this->isWikitextNS( NS_MAIN
) ) {
664 // parser tests frequently assume that the main namespace contains wikitext.
665 // @todo When setting up pages, force the content model. Only skip if
666 // $wgtContentModelUseDB is false.
667 $this->markTestSkipped( "Main namespace does not support wikitext,"
668 . "skipping parser test: $desc" );
671 wfDebug( "Running parser test: $desc\n" );
673 $opts = $this->parseOptions( $opts );
674 $context = $this->setupGlobals( $opts, $config );
676 $user = $context->getUser();
677 $options = ParserOptions
::newFromContext( $context );
679 if ( isset( $opts['title'] ) ) {
680 $titleText = $opts['title'];
682 $titleText = 'Parser test';
685 $local = isset( $opts['local'] );
686 $preprocessor = isset( $opts['preprocessor'] ) ?
$opts['preprocessor'] : null;
687 $parser = $this->getParser( $preprocessor );
689 $title = Title
::newFromText( $titleText );
691 # Parser test requiring math. Make sure texvc is executable
692 # or just skip such tests.
693 if ( isset( $opts['math'] ) ||
isset( $opts['texvc'] ) ) {
696 if ( !isset( $wgTexvc ) ) {
697 $this->markTestSkipped( "SKIPPED: \$wgTexvc is not set" );
698 } elseif ( !is_executable( $wgTexvc ) ) {
699 $this->markTestSkipped( "SKIPPED: texvc binary does not exist"
700 . " or is not executable.\n"
701 . "Current configuration is:\n\$wgTexvc = '$wgTexvc'" );
704 if ( isset( $opts['djvu'] ) ) {
705 if ( !$this->djVuSupport
->isEnabled() ) {
706 $this->markTestSkipped( "SKIPPED: djvu binaries do not exist or are not executable.\n" );
710 if ( isset( $opts['pst'] ) ) {
711 $out = $parser->preSaveTransform( $input, $title, $user, $options );
712 } elseif ( isset( $opts['msg'] ) ) {
713 $out = $parser->transformMsg( $input, $options, $title );
714 } elseif ( isset( $opts['section'] ) ) {
715 $section = $opts['section'];
716 $out = $parser->getSection( $input, $section );
717 } elseif ( isset( $opts['replace'] ) ) {
718 $section = $opts['replace'][0];
719 $replace = $opts['replace'][1];
720 $out = $parser->replaceSection( $input, $section, $replace );
721 } elseif ( isset( $opts['comment'] ) ) {
722 $out = Linker
::formatComment( $input, $title, $local );
723 } elseif ( isset( $opts['preload'] ) ) {
724 $out = $parser->getPreloadText( $input, $title, $options );
726 $output = $parser->parse( $input, $title, $options, true, true, 1337 );
727 $output->setTOCEnabled( !isset( $opts['notoc'] ) );
728 $out = $output->getText();
730 if ( isset( $opts['showtitle'] ) ) {
731 if ( $output->getTitleText() ) {
732 $title = $output->getTitleText();
735 $out = "$title\n$out";
738 if ( isset( $opts['ill'] ) ) {
739 $out = $this->tidy( implode( ' ', $output->getLanguageLinks() ) );
740 } elseif ( isset( $opts['cat'] ) ) {
741 $outputPage = $context->getOutput();
742 $outputPage->addCategoryLinks( $output->getCategories() );
743 $cats = $outputPage->getCategoryLinks();
745 if ( isset( $cats['normal'] ) ) {
746 $out = $this->tidy( implode( ' ', $cats['normal'] ) );
751 $parser->mPreprocessor
= null;
753 $result = $this->tidy( $result );
756 $this->teardownGlobals();
758 $this->assertEquals( $result, $out, $desc );
762 * Run a fuzz test series
763 * Draw input from a set of test files
765 * @todo fixme Needs some work to not eat memory until the world explodes
769 public function testFuzzTests() {
770 global $wgParserTestFiles;
772 $files = $wgParserTestFiles;
774 if ( $this->getCliArg( 'file=' ) ) {
775 $files = array( $this->getCliArg( 'file=' ) );
778 $dict = $this->getFuzzInput( $files );
779 $dictSize = strlen( $dict );
780 $logMaxLength = log( $this->maxFuzzTestLength
);
782 ini_set( 'memory_limit', $this->memoryLimit
* 1048576 );
785 $opts = ParserOptions
::newFromUser( $user );
786 $title = Title
::makeTitle( NS_MAIN
, 'Parser_test' );
792 // Generate test input
793 mt_srand( ++
$this->fuzzSeed
);
794 $totalLength = mt_rand( 1, $this->maxFuzzTestLength
);
797 while ( strlen( $input ) < $totalLength ) {
798 $logHairLength = mt_rand( 0, 1000000 ) / 1000000 * $logMaxLength;
799 $hairLength = min( intval( exp( $logHairLength ) ), $dictSize );
800 $offset = mt_rand( 0, $dictSize - $hairLength );
801 $input .= substr( $dict, $offset, $hairLength );
804 $this->setupGlobals();
805 $parser = $this->getParser();
809 $parser->parse( $input, $title, $opts );
810 $this->assertTrue( true, "Test $id, fuzz seed {$this->fuzzSeed}" );
811 } catch ( Exception
$exception ) {
812 $input_dump = sprintf( "string(%d) \"%s\"\n", strlen( $input ), $input );
814 $this->assertTrue( false, "Test $id, fuzz seed {$this->fuzzSeed}. \n\n" .
815 "Input: $input_dump\n\nError: {$exception->getMessage()}\n\n" .
816 "Backtrace: {$exception->getTraceAsString()}" );
819 $this->teardownGlobals();
820 $parser->__destruct();
822 if ( $id %
100 == 0 ) {
823 $usage = intval( memory_get_usage( true ) / $this->memoryLimit
/ 1048576 * 100 );
824 //echo "{$this->fuzzSeed}: $numSuccess/$numTotal (mem: $usage%)\n";
826 $ret = "Out of memory:\n";
827 $memStats = $this->getMemoryBreakdown();
829 foreach ( $memStats as $name => $usage ) {
830 $ret .= "$name: $usage\n";
833 throw new MWException( $ret );
841 //Various getter functions
844 * Get an input dictionary from a set of parser test files
845 * @param array $filenames
847 function getFuzzInput( $filenames ) {
850 foreach ( $filenames as $filename ) {
851 $contents = file_get_contents( $filename );
852 preg_match_all( '/!!\s*input\n(.*?)\n!!\s*result/s', $contents, $matches );
854 foreach ( $matches[1] as $match ) {
855 $dict .= $match . "\n";
863 * Get a memory usage breakdown
865 function getMemoryBreakdown() {
868 foreach ( $GLOBALS as $name => $value ) {
869 $memStats['$' . $name] = strlen( serialize( $value ) );
872 $classes = get_declared_classes();
874 foreach ( $classes as $class ) {
875 $rc = new ReflectionClass( $class );
876 $props = $rc->getStaticProperties();
877 $memStats[$class] = strlen( serialize( $props ) );
878 $methods = $rc->getMethods();
880 foreach ( $methods as $method ) {
881 $memStats[$class] +
= strlen( serialize( $method->getStaticVariables() ) );
885 $functions = get_defined_functions();
887 foreach ( $functions['user'] as $function ) {
888 $rf = new ReflectionFunction( $function );
889 $memStats["$function()"] = strlen( serialize( $rf->getStaticVariables() ) );
898 * Get a Parser object
899 * @param Preprocessor $preprocessor
901 function getParser( $preprocessor = null ) {
902 global $wgParserConf;
904 $class = $wgParserConf['class'];
905 $parser = new $class( array( 'preprocessorClass' => $preprocessor ) +
$wgParserConf );
907 wfRunHooks( 'ParserTestParser', array( &$parser ) );
912 //Various action functions
914 public function addArticle( $name, $text, $line ) {
915 self
::$articles[$name] = array( $text, $line );
918 public function publishTestArticles() {
919 if ( empty( self
::$articles ) ) {
923 foreach ( self
::$articles as $name => $info ) {
924 list( $text, $line ) = $info;
925 ParserTest
::addArticle( $name, $text, $line, 'ignoreduplicate' );
930 * Steal a callback function from the primary parser, save it for
931 * application to our scary parser. If the hook is not installed,
932 * abort processing of this file.
934 * @param string $name
935 * @return bool True if tag hook is present
937 public function requireHook( $name ) {
939 $wgParser->firstCallInit(); // make sure hooks are loaded.
940 return isset( $wgParser->mTagHooks
[$name] );
943 public function requireFunctionHook( $name ) {
945 $wgParser->firstCallInit(); // make sure hooks are loaded.
946 return isset( $wgParser->mFunctionHooks
[$name] );
949 public function requireTransparentHook( $name ) {
951 $wgParser->firstCallInit(); // make sure hooks are loaded.
952 return isset( $wgParser->mTransparentTagHooks
[$name] );
955 //Various "cleanup" functions
958 * Run the "tidy" command on text if the $wgUseTidy
961 * @param string $text The text to tidy
964 protected function tidy( $text ) {
968 $text = MWTidy
::tidy( $text );
975 * Remove last character if it is a newline
978 public function removeEndingNewline( $s ) {
979 if ( substr( $s, -1 ) === "\n" ) {
980 return substr( $s, 0, -1 );
986 //Test options parser functions
988 protected function parseOptions( $instring ) {
994 // foo=bar,"baz quux"
1016 "[^"]*" # Quoted val
1018 \[\[[^]]*\]\] # Link target
1026 if ( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER
) ) {
1027 foreach ( $matches as $bits ) {
1028 array_shift( $bits );
1029 $key = strtolower( array_shift( $bits ) );
1030 if ( count( $bits ) == 0 ) {
1032 } elseif ( count( $bits ) == 1 ) {
1033 $opts[$key] = $this->cleanupOption( array_shift( $bits ) );
1036 $opts[$key] = array_map( array( $this, 'cleanupOption' ), $bits );
1044 protected function cleanupOption( $opt ) {
1045 if ( substr( $opt, 0, 1 ) == '"' ) {
1046 return substr( $opt, 1, -1 );
1049 if ( substr( $opt, 0, 2 ) == '[[' ) {
1050 return substr( $opt, 2, -2 );
1057 * Use a regex to find out the value of an option
1058 * @param string $key Name of option val to retrieve
1059 * @param array $opts Options array to look in
1060 * @param mixed $default Default value returned if not found
1062 protected static function getOptionValue( $key, $opts, $default ) {
1063 $key = strtolower( $key );
1065 if ( isset( $opts[$key] ) ) {