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' );
151 $tmpGlobals['wgLocalInterwikis'] = array( 'local', 'mi' );
152 # "extra language links"
153 # see https://gerrit.wikimedia.org/r/111390
154 $tmpGlobals['wgExtraInterlanguageLinkPrefixes'] = array( 'mul' );
157 $this->djVuSupport
= new DjVuSupport();
159 $this->setMwGlobals( $tmpGlobals );
161 $this->savedWeirdGlobals
['image_alias'] = $wgNamespaceAliases['Image'];
162 $this->savedWeirdGlobals
['image_talk_alias'] = $wgNamespaceAliases['Image_talk'];
164 $wgNamespaceAliases['Image'] = NS_FILE
;
165 $wgNamespaceAliases['Image_talk'] = NS_FILE_TALK
;
167 MWNamespace
::getCanonicalNamespaces( true ); # reset namespace cache
168 $wgContLang->resetNamespaces(); # reset namespace cache
171 protected function tearDown() {
172 global $wgNamespaceAliases, $wgContLang;
174 $wgNamespaceAliases['Image'] = $this->savedWeirdGlobals
['image_alias'];
175 $wgNamespaceAliases['Image_talk'] = $this->savedWeirdGlobals
['image_talk_alias'];
178 RepoGroup
::destroySingleton();
179 FileBackendGroup
::destroySingleton();
181 // Remove temporary pages from the link cache
182 LinkCache
::singleton()->clear();
184 // Restore message cache (temporary pages and $wgUseDatabaseMessages)
185 MessageCache
::destroyInstance();
189 MWNamespace
::getCanonicalNamespaces( true ); # reset namespace cache
190 $wgContLang->resetNamespaces(); # reset namespace cache
193 public static function tearDownAfterClass() {
194 ParserTest
::tearDownInterwikis();
195 parent
::tearDownAfterClass();
198 function addDBData() {
199 $this->tablesUsed
[] = 'site_stats';
200 # disabled for performance
201 #$this->tablesUsed[] = 'image';
203 # Update certain things in site_stats
204 $this->db
->insert( 'site_stats',
205 array( 'ss_row_id' => 1, 'ss_images' => 2, 'ss_good_articles' => 1 ),
209 $user = User
::newFromId( 0 );
210 LinkCache
::singleton()->clear(); # Avoids the odd failure at creating the nullRevision
212 # Upload DB table entries for files.
213 # We will upload the actual files later. Note that if anything causes LocalFile::load()
214 # to be triggered before then, it will break via maybeUpgrade() setting the fileExists
215 # member to false and storing it in cache.
216 # note that the size/width/height/bits/etc of the file
217 # are actually set by inspecting the file itself; the arguments
218 # to recordUpload2 have no effect. That said, we try to make things
219 # match up so it is less confusing to readers of the code & tests.
220 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Foobar.jpg' ) );
221 if ( !$this->db
->selectField( 'image', '1', array( 'img_name' => $image->getName() ) ) ) {
222 $image->recordUpload2(
224 'Upload of some lame file',
231 'media_type' => MEDIATYPE_BITMAP
,
232 'mime' => 'image/jpeg',
233 'metadata' => serialize( array() ),
234 'sha1' => wfBaseConvert( '1', 16, 36, 31 ),
235 'fileExists' => true ),
236 $this->db
->timestamp( '20010115123500' ), $user
240 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Thumb.png' ) );
241 if ( !$this->db
->selectField( 'image', '1', array( 'img_name' => $image->getName() ) ) ) {
242 $image->recordUpload2(
244 'Upload of some lame thumbnail',
245 'Some lame thumbnail',
251 'media_type' => MEDIATYPE_BITMAP
,
252 'mime' => 'image/png',
253 'metadata' => serialize( array() ),
254 'sha1' => wfBaseConvert( '2', 16, 36, 31 ),
255 'fileExists' => true ),
256 $this->db
->timestamp( '20130225203040' ), $user
260 # This image will be blacklisted in [[MediaWiki:Bad image list]]
261 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Bad.jpg' ) );
262 if ( !$this->db
->selectField( 'image', '1', array( 'img_name' => $image->getName() ) ) ) {
263 $image->recordUpload2(
272 'media_type' => MEDIATYPE_BITMAP
,
273 'mime' => 'image/jpeg',
274 'metadata' => serialize( array() ),
275 'sha1' => wfBaseConvert( '3', 16, 36, 31 ),
276 'fileExists' => true ),
277 $this->db
->timestamp( '20010115123500' ), $user
280 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Foobar.svg' ) );
281 if ( !$this->db
->selectField( 'image', '1', array( 'img_name' => $image->getName() ) ) ) {
282 $image->recordUpload2( '', 'Upload of some lame SVG', 'Some lame SVG', array(
287 'media_type' => MEDIATYPE_DRAWING
,
288 'mime' => 'image/svg+xml',
289 'metadata' => serialize( array() ),
290 'sha1' => wfBaseConvert( '', 16, 36, 31 ),
292 ), $this->db
->timestamp( '20010115123500' ), $user );
296 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'LoremIpsum.djvu' ) );
297 if ( !$this->db
->selectField( 'image', '1', array( 'img_name' => $image->getName() ) ) ) {
298 $image->recordUpload2( '', 'Upload a DjVu', 'A DjVu', array(
303 'media_type' => MEDIATYPE_BITMAP
,
304 'mime' => 'image/vnd.djvu',
305 'metadata' => '<?xml version="1.0" ?>
306 <!DOCTYPE DjVuXML PUBLIC "-//W3C//DTD DjVuXML 1.1//EN" "pubtext/DjVuXML-s.dtd">
309 <BODY><OBJECT height="3508" width="2480">
310 <PARAM name="DPI" value="300" />
311 <PARAM name="GAMMA" value="2.2" />
313 <OBJECT height="3508" width="2480">
314 <PARAM name="DPI" value="300" />
315 <PARAM name="GAMMA" value="2.2" />
317 <OBJECT height="3508" width="2480">
318 <PARAM name="DPI" value="300" />
319 <PARAM name="GAMMA" value="2.2" />
321 <OBJECT height="3508" width="2480">
322 <PARAM name="DPI" value="300" />
323 <PARAM name="GAMMA" value="2.2" />
325 <OBJECT height="3508" width="2480">
326 <PARAM name="DPI" value="300" />
327 <PARAM name="GAMMA" value="2.2" />
331 'sha1' => wfBaseConvert( '', 16, 36, 31 ),
333 ), $this->db
->timestamp( '20140115123600' ), $user );
337 //ParserTest setup/teardown functions
340 * Set up the global variables for a consistent environment for each test.
341 * Ideally this should replace the global configuration entirely.
343 protected function setupGlobals( $opts = array(), $config = '' ) {
344 global $wgFileBackends;
345 # Find out values for some special options.
347 self
::getOptionValue( 'language', $opts, 'en' );
349 self
::getOptionValue( 'variant', $opts, false );
351 self
::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
352 $linkHolderBatchSize =
353 self
::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
355 $uploadDir = $this->getUploadDir();
356 if ( $this->getCliArg( 'use-filebackend=' ) ) {
357 if ( self
::$backendToUse ) {
358 $backend = self
::$backendToUse;
360 $name = $this->getCliArg( 'use-filebackend=' );
361 $useConfig = array();
362 foreach ( $wgFileBackends as $conf ) {
363 if ( $conf['name'] == $name ) {
367 $useConfig['name'] = 'local-backend'; // swap name
368 unset( $useConfig['lockManager'] );
369 unset( $useConfig['fileJournal'] );
370 $class = $useConfig['class'];
371 self
::$backendToUse = new $class( $useConfig );
372 $backend = self
::$backendToUse;
375 # Replace with a mock. We do not care about generating real
376 # files on the filesystem, just need to expose the file
378 $backend = new MockFileBackend( array(
379 'name' => 'local-backend',
380 'wikiId' => wfWikiId()
385 'wgLocalFileRepo' => array(
386 'class' => 'LocalRepo',
388 'url' => 'http://example.com/images',
390 'transformVia404' => false,
391 'backend' => $backend
393 'wgEnableUploads' => self
::getOptionValue( 'wgEnableUploads', $opts, true ),
394 'wgLanguageCode' => $lang,
395 'wgDBprefix' => $this->db
->getType() != 'oracle' ?
'unittest_' : 'ut_',
396 'wgRawHtml' => self
::getOptionValue( 'wgRawHtml', $opts, false ),
397 'wgNamespacesWithSubpages' => array( NS_MAIN
=> isset( $opts['subpage'] ) ),
398 'wgAllowExternalImages' => self
::getOptionValue( 'wgAllowExternalImages', $opts, true ),
399 'wgThumbLimits' => array( self
::getOptionValue( 'thumbsize', $opts, 180 ) ),
400 'wgMaxTocLevel' => $maxtoclevel,
401 'wgUseTeX' => isset( $opts['math'] ) ||
isset( $opts['texvc'] ),
402 'wgMathDirectory' => $uploadDir . '/math',
403 'wgDefaultLanguageVariant' => $variant,
404 'wgLinkHolderBatchSize' => $linkHolderBatchSize,
408 $configLines = explode( "\n", $config );
410 foreach ( $configLines as $line ) {
411 list( $var, $value ) = explode( '=', $line, 2 );
413 $settings[$var] = eval( "return $value;" ); //???
417 $this->savedGlobals
= array();
420 wfRunHooks( 'ParserTestGlobals', array( &$settings ) );
422 $langObj = Language
::factory( $lang );
423 $settings['wgContLang'] = $langObj;
424 $settings['wgLang'] = $langObj;
426 $context = new RequestContext();
427 $settings['wgOut'] = $context->getOutput();
428 $settings['wgUser'] = $context->getUser();
429 $settings['wgRequest'] = $context->getRequest();
431 // We (re)set $wgThumbLimits to a single-element array above.
432 $context->getUser()->setOption( 'thumbsize', 0 );
434 foreach ( $settings as $var => $val ) {
435 if ( array_key_exists( $var, $GLOBALS ) ) {
436 $this->savedGlobals
[$var] = $GLOBALS[$var];
439 $GLOBALS[$var] = $val;
442 MagicWord
::clearCache();
444 # The entries saved into RepoGroup cache with previous globals will be wrong.
445 RepoGroup
::destroySingleton();
446 FileBackendGroup
::destroySingleton();
448 # Create dummy files in storage
449 $this->setupUploads();
451 # Publish the articles after we have the final language set
452 $this->publishTestArticles();
454 MessageCache
::destroyInstance();
460 * Get an FS upload directory (only applies to FSFileBackend)
462 * @return string The directory
464 protected function getUploadDir() {
465 if ( $this->keepUploads
) {
466 $dir = wfTempDir() . '/mwParser-images';
468 if ( is_dir( $dir ) ) {
472 $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
475 // wfDebug( "Creating upload directory $dir\n" );
476 if ( file_exists( $dir ) ) {
477 wfDebug( "Already exists!\n" );
486 * Create a dummy uploads directory which will contain a couple
487 * of files in order to pass existence tests.
489 * @return string The directory
491 protected function setupUploads() {
494 $base = $this->getBaseDir();
495 $backend = RepoGroup
::singleton()->getLocalRepo()->getBackend();
496 $backend->prepare( array( 'dir' => "$base/local-public/3/3a" ) );
497 $backend->store( array(
498 'src' => "$IP/tests/phpunit/data/parser/headbg.jpg",
499 'dst' => "$base/local-public/3/3a/Foobar.jpg"
501 $backend->prepare( array( 'dir' => "$base/local-public/e/ea" ) );
502 $backend->store( array(
503 'src' => "$IP/tests/phpunit/data/parser/wiki.png",
504 'dst' => "$base/local-public/e/ea/Thumb.png"
506 $backend->prepare( array( 'dir' => "$base/local-public/0/09" ) );
507 $backend->store( array(
508 'src' => "$IP/tests/phpunit/data/parser/headbg.jpg",
509 'dst' => "$base/local-public/0/09/Bad.jpg"
511 $backend->prepare( array( 'dir' => "$base/local-public/5/5f" ) );
512 $backend->store( array(
513 'src' => "$IP/tests/phpunit/data/parser/LoremIpsum.djvu",
514 'dst' => "$base/local-public/5/5f/LoremIpsum.djvu"
517 // No helpful SVG file to copy, so make one ourselves
518 $data = '<?xml version="1.0" encoding="utf-8"?>' .
519 '<svg xmlns="http://www.w3.org/2000/svg"' .
520 ' version="1.1" width="240" height="180"/>';
522 $backend->prepare( array( 'dir' => "$base/local-public/f/ff" ) );
523 $backend->quickCreate( array(
524 'content' => $data, 'dst' => "$base/local-public/f/ff/Foobar.svg"
529 * Restore default values and perform any necessary clean-up
530 * after each test runs.
532 protected function teardownGlobals() {
533 $this->teardownUploads();
535 foreach ( $this->savedGlobals
as $var => $val ) {
536 $GLOBALS[$var] = $val;
541 * Remove the dummy uploads directory
543 private function teardownUploads() {
544 if ( $this->keepUploads
) {
548 $backend = RepoGroup
::singleton()->getLocalRepo()->getBackend();
549 if ( $backend instanceof MockFileBackend
) {
550 # In memory backend, so dont bother cleaning them up.
554 $base = $this->getBaseDir();
555 // delete the files first, then the dirs.
558 "$base/local-public/3/3a/Foobar.jpg",
559 "$base/local-thumb/3/3a/Foobar.jpg/1000px-Foobar.jpg",
560 "$base/local-thumb/3/3a/Foobar.jpg/100px-Foobar.jpg",
561 "$base/local-thumb/3/3a/Foobar.jpg/120px-Foobar.jpg",
562 "$base/local-thumb/3/3a/Foobar.jpg/1280px-Foobar.jpg",
563 "$base/local-thumb/3/3a/Foobar.jpg/137px-Foobar.jpg",
564 "$base/local-thumb/3/3a/Foobar.jpg/1500px-Foobar.jpg",
565 "$base/local-thumb/3/3a/Foobar.jpg/177px-Foobar.jpg",
566 "$base/local-thumb/3/3a/Foobar.jpg/180px-Foobar.jpg",
567 "$base/local-thumb/3/3a/Foobar.jpg/200px-Foobar.jpg",
568 "$base/local-thumb/3/3a/Foobar.jpg/206px-Foobar.jpg",
569 "$base/local-thumb/3/3a/Foobar.jpg/20px-Foobar.jpg",
570 "$base/local-thumb/3/3a/Foobar.jpg/220px-Foobar.jpg",
571 "$base/local-thumb/3/3a/Foobar.jpg/265px-Foobar.jpg",
572 "$base/local-thumb/3/3a/Foobar.jpg/270px-Foobar.jpg",
573 "$base/local-thumb/3/3a/Foobar.jpg/274px-Foobar.jpg",
574 "$base/local-thumb/3/3a/Foobar.jpg/300px-Foobar.jpg",
575 "$base/local-thumb/3/3a/Foobar.jpg/30px-Foobar.jpg",
576 "$base/local-thumb/3/3a/Foobar.jpg/330px-Foobar.jpg",
577 "$base/local-thumb/3/3a/Foobar.jpg/353px-Foobar.jpg",
578 "$base/local-thumb/3/3a/Foobar.jpg/360px-Foobar.jpg",
579 "$base/local-thumb/3/3a/Foobar.jpg/400px-Foobar.jpg",
580 "$base/local-thumb/3/3a/Foobar.jpg/40px-Foobar.jpg",
581 "$base/local-thumb/3/3a/Foobar.jpg/440px-Foobar.jpg",
582 "$base/local-thumb/3/3a/Foobar.jpg/442px-Foobar.jpg",
583 "$base/local-thumb/3/3a/Foobar.jpg/450px-Foobar.jpg",
584 "$base/local-thumb/3/3a/Foobar.jpg/50px-Foobar.jpg",
585 "$base/local-thumb/3/3a/Foobar.jpg/600px-Foobar.jpg",
586 "$base/local-thumb/3/3a/Foobar.jpg/640px-Foobar.jpg",
587 "$base/local-thumb/3/3a/Foobar.jpg/70px-Foobar.jpg",
588 "$base/local-thumb/3/3a/Foobar.jpg/75px-Foobar.jpg",
589 "$base/local-thumb/3/3a/Foobar.jpg/960px-Foobar.jpg",
591 "$base/local-public/e/ea/Thumb.png",
593 "$base/local-public/0/09/Bad.jpg",
595 "$base/local-public/5/5f/LoremIpsum.djvu",
596 "$base/local-thumb/5/5f/LoremIpsum.djvu/page2-2480px-LoremIpsum.djvu.jpg",
597 "$base/local-thumb/5/5f/LoremIpsum.djvu/page2-3720px-LoremIpsum.djvu.jpg",
598 "$base/local-thumb/5/5f/LoremIpsum.djvu/page2-4960px-LoremIpsum.djvu.jpg",
600 "$base/local-public/f/ff/Foobar.svg",
601 "$base/local-thumb/f/ff/Foobar.svg/180px-Foobar.svg.png",
602 "$base/local-thumb/f/ff/Foobar.svg/2000px-Foobar.svg.png",
603 "$base/local-thumb/f/ff/Foobar.svg/270px-Foobar.svg.png",
604 "$base/local-thumb/f/ff/Foobar.svg/3000px-Foobar.svg.png",
605 "$base/local-thumb/f/ff/Foobar.svg/360px-Foobar.svg.png",
606 "$base/local-thumb/f/ff/Foobar.svg/4000px-Foobar.svg.png",
607 "$base/local-thumb/f/ff/Foobar.svg/langde-180px-Foobar.svg.png",
608 "$base/local-thumb/f/ff/Foobar.svg/langde-270px-Foobar.svg.png",
609 "$base/local-thumb/f/ff/Foobar.svg/langde-360px-Foobar.svg.png",
611 "$base/local-public/math/f/a/5/fa50b8b616463173474302ca3e63586b.png",
617 * Delete the specified files, if they exist.
618 * @param array $files Full paths to files to delete.
620 private static function deleteFiles( $files ) {
621 $backend = RepoGroup
::singleton()->getLocalRepo()->getBackend();
622 foreach ( $files as $file ) {
623 $backend->delete( array( 'src' => $file ), array( 'force' => 1 ) );
625 foreach ( $files as $file ) {
627 while ( $tmp = FileBackend
::parentStoragePath( $tmp ) ) {
628 if ( !$backend->clean( array( 'dir' => $tmp ) )->isOK() ) {
635 protected function getBaseDir() {
636 return 'mwstore://local-backend';
639 public function parserTestProvider() {
640 if ( $this->file
=== false ) {
641 global $wgParserTestFiles;
642 $this->file
= $wgParserTestFiles[0];
645 return new TestFileIterator( $this->file
, $this );
649 * Set the file from whose tests will be run by this instance
650 * @param string $filename
652 public function setParserTestFile( $filename ) {
653 $this->file
= $filename;
658 * @dataProvider parserTestProvider
659 * @param string $desc
660 * @param string $input
661 * @param string $result
663 * @param array $config
665 public function testParserTest( $desc, $input, $result, $opts, $config ) {
666 if ( $this->regex
!= '' && !preg_match( '/' . $this->regex
. '/', $desc ) ) {
667 $this->assertTrue( true ); // XXX: don't flood output with "test made no assertions"
668 //$this->markTestSkipped( 'Filtered out by the user' );
672 if ( !$this->isWikitextNS( NS_MAIN
) ) {
673 // parser tests frequently assume that the main namespace contains wikitext.
674 // @todo When setting up pages, force the content model. Only skip if
675 // $wgtContentModelUseDB is false.
676 $this->markTestSkipped( "Main namespace does not support wikitext,"
677 . "skipping parser test: $desc" );
680 wfDebug( "Running parser test: $desc\n" );
682 $opts = $this->parseOptions( $opts );
683 $context = $this->setupGlobals( $opts, $config );
685 $user = $context->getUser();
686 $options = ParserOptions
::newFromContext( $context );
688 if ( isset( $opts['title'] ) ) {
689 $titleText = $opts['title'];
691 $titleText = 'Parser test';
694 $local = isset( $opts['local'] );
695 $preprocessor = isset( $opts['preprocessor'] ) ?
$opts['preprocessor'] : null;
696 $parser = $this->getParser( $preprocessor );
698 $title = Title
::newFromText( $titleText );
700 # Parser test requiring math. Make sure texvc is executable
701 # or just skip such tests.
702 if ( isset( $opts['math'] ) ||
isset( $opts['texvc'] ) ) {
705 if ( !isset( $wgTexvc ) ) {
706 $this->markTestSkipped( "SKIPPED: \$wgTexvc is not set" );
707 } elseif ( !is_executable( $wgTexvc ) ) {
708 $this->markTestSkipped( "SKIPPED: texvc binary does not exist"
709 . " or is not executable.\n"
710 . "Current configuration is:\n\$wgTexvc = '$wgTexvc'" );
713 if ( isset( $opts['djvu'] ) ) {
714 if ( !$this->djVuSupport
->isEnabled() ) {
715 $this->markTestSkipped( "SKIPPED: djvu binaries do not exist or are not executable.\n" );
719 if ( isset( $opts['pst'] ) ) {
720 $out = $parser->preSaveTransform( $input, $title, $user, $options );
721 } elseif ( isset( $opts['msg'] ) ) {
722 $out = $parser->transformMsg( $input, $options, $title );
723 } elseif ( isset( $opts['section'] ) ) {
724 $section = $opts['section'];
725 $out = $parser->getSection( $input, $section );
726 } elseif ( isset( $opts['replace'] ) ) {
727 $section = $opts['replace'][0];
728 $replace = $opts['replace'][1];
729 $out = $parser->replaceSection( $input, $section, $replace );
730 } elseif ( isset( $opts['comment'] ) ) {
731 $out = Linker
::formatComment( $input, $title, $local );
732 } elseif ( isset( $opts['preload'] ) ) {
733 $out = $parser->getPreloadText( $input, $title, $options );
735 $output = $parser->parse( $input, $title, $options, true, true, 1337 );
736 $output->setTOCEnabled( !isset( $opts['notoc'] ) );
737 $out = $output->getText();
739 if ( isset( $opts['showtitle'] ) ) {
740 if ( $output->getTitleText() ) {
741 $title = $output->getTitleText();
744 $out = "$title\n$out";
747 if ( isset( $opts['ill'] ) ) {
748 $out = $this->tidy( implode( ' ', $output->getLanguageLinks() ) );
749 } elseif ( isset( $opts['cat'] ) ) {
750 $outputPage = $context->getOutput();
751 $outputPage->addCategoryLinks( $output->getCategories() );
752 $cats = $outputPage->getCategoryLinks();
754 if ( isset( $cats['normal'] ) ) {
755 $out = $this->tidy( implode( ' ', $cats['normal'] ) );
760 $parser->mPreprocessor
= null;
762 $result = $this->tidy( $result );
765 $this->teardownGlobals();
767 $this->assertEquals( $result, $out, $desc );
771 * Run a fuzz test series
772 * Draw input from a set of test files
774 * @todo fixme Needs some work to not eat memory until the world explodes
778 public function testFuzzTests() {
779 global $wgParserTestFiles;
781 $files = $wgParserTestFiles;
783 if ( $this->getCliArg( 'file=' ) ) {
784 $files = array( $this->getCliArg( 'file=' ) );
787 $dict = $this->getFuzzInput( $files );
788 $dictSize = strlen( $dict );
789 $logMaxLength = log( $this->maxFuzzTestLength
);
791 ini_set( 'memory_limit', $this->memoryLimit
* 1048576 );
794 $opts = ParserOptions
::newFromUser( $user );
795 $title = Title
::makeTitle( NS_MAIN
, 'Parser_test' );
801 // Generate test input
802 mt_srand( ++
$this->fuzzSeed
);
803 $totalLength = mt_rand( 1, $this->maxFuzzTestLength
);
806 while ( strlen( $input ) < $totalLength ) {
807 $logHairLength = mt_rand( 0, 1000000 ) / 1000000 * $logMaxLength;
808 $hairLength = min( intval( exp( $logHairLength ) ), $dictSize );
809 $offset = mt_rand( 0, $dictSize - $hairLength );
810 $input .= substr( $dict, $offset, $hairLength );
813 $this->setupGlobals();
814 $parser = $this->getParser();
818 $parser->parse( $input, $title, $opts );
819 $this->assertTrue( true, "Test $id, fuzz seed {$this->fuzzSeed}" );
820 } catch ( Exception
$exception ) {
821 $input_dump = sprintf( "string(%d) \"%s\"\n", strlen( $input ), $input );
823 $this->assertTrue( false, "Test $id, fuzz seed {$this->fuzzSeed}. \n\n" .
824 "Input: $input_dump\n\nError: {$exception->getMessage()}\n\n" .
825 "Backtrace: {$exception->getTraceAsString()}" );
828 $this->teardownGlobals();
829 $parser->__destruct();
831 if ( $id %
100 == 0 ) {
832 $usage = intval( memory_get_usage( true ) / $this->memoryLimit
/ 1048576 * 100 );
833 //echo "{$this->fuzzSeed}: $numSuccess/$numTotal (mem: $usage%)\n";
835 $ret = "Out of memory:\n";
836 $memStats = $this->getMemoryBreakdown();
838 foreach ( $memStats as $name => $usage ) {
839 $ret .= "$name: $usage\n";
842 throw new MWException( $ret );
850 //Various getter functions
853 * Get an input dictionary from a set of parser test files
854 * @param array $filenames
856 function getFuzzInput( $filenames ) {
859 foreach ( $filenames as $filename ) {
860 $contents = file_get_contents( $filename );
861 preg_match_all( '/!!\s*input\n(.*?)\n!!\s*result/s', $contents, $matches );
863 foreach ( $matches[1] as $match ) {
864 $dict .= $match . "\n";
872 * Get a memory usage breakdown
874 function getMemoryBreakdown() {
877 foreach ( $GLOBALS as $name => $value ) {
878 $memStats['$' . $name] = strlen( serialize( $value ) );
881 $classes = get_declared_classes();
883 foreach ( $classes as $class ) {
884 $rc = new ReflectionClass( $class );
885 $props = $rc->getStaticProperties();
886 $memStats[$class] = strlen( serialize( $props ) );
887 $methods = $rc->getMethods();
889 foreach ( $methods as $method ) {
890 $memStats[$class] +
= strlen( serialize( $method->getStaticVariables() ) );
894 $functions = get_defined_functions();
896 foreach ( $functions['user'] as $function ) {
897 $rf = new ReflectionFunction( $function );
898 $memStats["$function()"] = strlen( serialize( $rf->getStaticVariables() ) );
907 * Get a Parser object
908 * @param Preprocessor $preprocessor
910 function getParser( $preprocessor = null ) {
911 global $wgParserConf;
913 $class = $wgParserConf['class'];
914 $parser = new $class( array( 'preprocessorClass' => $preprocessor ) +
$wgParserConf );
916 wfRunHooks( 'ParserTestParser', array( &$parser ) );
921 //Various action functions
923 public function addArticle( $name, $text, $line ) {
924 self
::$articles[$name] = array( $text, $line );
927 public function publishTestArticles() {
928 if ( empty( self
::$articles ) ) {
932 foreach ( self
::$articles as $name => $info ) {
933 list( $text, $line ) = $info;
934 ParserTest
::addArticle( $name, $text, $line, 'ignoreduplicate' );
939 * Steal a callback function from the primary parser, save it for
940 * application to our scary parser. If the hook is not installed,
941 * abort processing of this file.
943 * @param string $name
944 * @return bool True if tag hook is present
946 public function requireHook( $name ) {
948 $wgParser->firstCallInit(); // make sure hooks are loaded.
949 return isset( $wgParser->mTagHooks
[$name] );
952 public function requireFunctionHook( $name ) {
954 $wgParser->firstCallInit(); // make sure hooks are loaded.
955 return isset( $wgParser->mFunctionHooks
[$name] );
958 public function requireTransparentHook( $name ) {
960 $wgParser->firstCallInit(); // make sure hooks are loaded.
961 return isset( $wgParser->mTransparentTagHooks
[$name] );
964 //Various "cleanup" functions
967 * Run the "tidy" command on text if the $wgUseTidy
970 * @param string $text The text to tidy
973 protected function tidy( $text ) {
977 $text = MWTidy
::tidy( $text );
984 * Remove last character if it is a newline
987 public function removeEndingNewline( $s ) {
988 if ( substr( $s, -1 ) === "\n" ) {
989 return substr( $s, 0, -1 );
995 //Test options parser functions
997 protected function parseOptions( $instring ) {
1003 // foo=bar,"baz quux"
1025 "[^"]*" # Quoted val
1027 \[\[[^]]*\]\] # Link target
1035 if ( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER
) ) {
1036 foreach ( $matches as $bits ) {
1037 array_shift( $bits );
1038 $key = strtolower( array_shift( $bits ) );
1039 if ( count( $bits ) == 0 ) {
1041 } elseif ( count( $bits ) == 1 ) {
1042 $opts[$key] = $this->cleanupOption( array_shift( $bits ) );
1045 $opts[$key] = array_map( array( $this, 'cleanupOption' ), $bits );
1053 protected function cleanupOption( $opt ) {
1054 if ( substr( $opt, 0, 1 ) == '"' ) {
1055 return substr( $opt, 1, -1 );
1058 if ( substr( $opt, 0, 2 ) == '[[' ) {
1059 return substr( $opt, 2, -2 );
1066 * Use a regex to find out the value of an option
1067 * @param string $key Name of option val to retrieve
1068 * @param array $opts Options array to look in
1069 * @param mixed $default Default value returned if not found
1071 protected static function getOptionValue( $key, $opts, $default ) {
1072 $key = strtolower( $key );
1074 if ( isset( $opts[$key] ) ) {