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 # "extra language links"
152 # see https://gerrit.wikimedia.org/r/111390
153 $tmpGlobals['wgExtraInterlanguageLinkPrefixes'] = array( 'mul' );
156 $this->djVuSupport
= new DjVuSupport();
158 $this->setMwGlobals( $tmpGlobals );
160 $this->savedWeirdGlobals
['image_alias'] = $wgNamespaceAliases['Image'];
161 $this->savedWeirdGlobals
['image_talk_alias'] = $wgNamespaceAliases['Image_talk'];
163 $wgNamespaceAliases['Image'] = NS_FILE
;
164 $wgNamespaceAliases['Image_talk'] = NS_FILE_TALK
;
166 MWNamespace
::getCanonicalNamespaces( true ); # reset namespace cache
167 $wgContLang->resetNamespaces(); # reset namespace cache
170 protected function tearDown() {
171 global $wgNamespaceAliases, $wgContLang;
173 $wgNamespaceAliases['Image'] = $this->savedWeirdGlobals
['image_alias'];
174 $wgNamespaceAliases['Image_talk'] = $this->savedWeirdGlobals
['image_talk_alias'];
177 RepoGroup
::destroySingleton();
178 FileBackendGroup
::destroySingleton();
180 // Remove temporary pages from the link cache
181 LinkCache
::singleton()->clear();
183 // Restore message cache (temporary pages and $wgUseDatabaseMessages)
184 MessageCache
::destroyInstance();
188 MWNamespace
::getCanonicalNamespaces( true ); # reset namespace cache
189 $wgContLang->resetNamespaces(); # reset namespace cache
192 public static function tearDownAfterClass() {
193 ParserTest
::tearDownInterwikis();
194 parent
::tearDownAfterClass();
197 function addDBData() {
198 $this->tablesUsed
[] = 'site_stats';
199 # disabled for performance
200 #$this->tablesUsed[] = 'image';
202 # Update certain things in site_stats
203 $this->db
->insert( 'site_stats',
204 array( 'ss_row_id' => 1, 'ss_images' => 2, 'ss_good_articles' => 1 ),
208 $user = User
::newFromId( 0 );
209 LinkCache
::singleton()->clear(); # Avoids the odd failure at creating the nullRevision
211 # Upload DB table entries for files.
212 # We will upload the actual files later. Note that if anything causes LocalFile::load()
213 # to be triggered before then, it will break via maybeUpgrade() setting the fileExists
214 # member to false and storing it in cache.
215 # note that the size/width/height/bits/etc of the file
216 # are actually set by inspecting the file itself; the arguments
217 # to recordUpload2 have no effect. That said, we try to make things
218 # match up so it is less confusing to readers of the code & tests.
219 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Foobar.jpg' ) );
220 if ( !$this->db
->selectField( 'image', '1', array( 'img_name' => $image->getName() ) ) ) {
221 $image->recordUpload2(
223 'Upload of some lame file',
230 'media_type' => MEDIATYPE_BITMAP
,
231 'mime' => 'image/jpeg',
232 'metadata' => serialize( array() ),
233 'sha1' => wfBaseConvert( '1', 16, 36, 31 ),
234 'fileExists' => true ),
235 $this->db
->timestamp( '20010115123500' ), $user
239 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Thumb.png' ) );
240 if ( !$this->db
->selectField( 'image', '1', array( 'img_name' => $image->getName() ) ) ) {
241 $image->recordUpload2(
243 'Upload of some lame thumbnail',
244 'Some lame thumbnail',
250 'media_type' => MEDIATYPE_BITMAP
,
251 'mime' => 'image/png',
252 'metadata' => serialize( array() ),
253 'sha1' => wfBaseConvert( '2', 16, 36, 31 ),
254 'fileExists' => true ),
255 $this->db
->timestamp( '20130225203040' ), $user
259 # This image will be blacklisted in [[MediaWiki:Bad image list]]
260 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Bad.jpg' ) );
261 if ( !$this->db
->selectField( 'image', '1', array( 'img_name' => $image->getName() ) ) ) {
262 $image->recordUpload2(
271 'media_type' => MEDIATYPE_BITMAP
,
272 'mime' => 'image/jpeg',
273 'metadata' => serialize( array() ),
274 'sha1' => wfBaseConvert( '3', 16, 36, 31 ),
275 'fileExists' => true ),
276 $this->db
->timestamp( '20010115123500' ), $user
279 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Foobar.svg' ) );
280 if ( !$this->db
->selectField( 'image', '1', array( 'img_name' => $image->getName() ) ) ) {
281 $image->recordUpload2( '', 'Upload of some lame SVG', 'Some lame SVG', array(
286 'media_type' => MEDIATYPE_DRAWING
,
287 'mime' => 'image/svg+xml',
288 'metadata' => serialize( array() ),
289 'sha1' => wfBaseConvert( '', 16, 36, 31 ),
291 ), $this->db
->timestamp( '20010115123500' ), $user );
295 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'LoremIpsum.djvu' ) );
296 if ( !$this->db
->selectField( 'image', '1', array( 'img_name' => $image->getName() ) ) ) {
297 $image->recordUpload2( '', 'Upload a DjVu', 'A DjVu', array(
302 'media_type' => MEDIATYPE_BITMAP
,
303 'mime' => 'image/vnd.djvu',
304 'metadata' => '<?xml version="1.0" ?>
305 <!DOCTYPE DjVuXML PUBLIC "-//W3C//DTD DjVuXML 1.1//EN" "pubtext/DjVuXML-s.dtd">
308 <BODY><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" />
324 <OBJECT height="3508" width="2480">
325 <PARAM name="DPI" value="300" />
326 <PARAM name="GAMMA" value="2.2" />
330 'sha1' => wfBaseConvert( '', 16, 36, 31 ),
332 ), $this->db
->timestamp( '20140115123600' ), $user );
336 //ParserTest setup/teardown functions
339 * Set up the global variables for a consistent environment for each test.
340 * Ideally this should replace the global configuration entirely.
342 protected function setupGlobals( $opts = array(), $config = '' ) {
343 global $wgFileBackends;
344 # Find out values for some special options.
346 self
::getOptionValue( 'language', $opts, 'en' );
348 self
::getOptionValue( 'variant', $opts, false );
350 self
::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
351 $linkHolderBatchSize =
352 self
::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
354 $uploadDir = $this->getUploadDir();
355 if ( $this->getCliArg( 'use-filebackend=' ) ) {
356 if ( self
::$backendToUse ) {
357 $backend = self
::$backendToUse;
359 $name = $this->getCliArg( 'use-filebackend=' );
360 $useConfig = array();
361 foreach ( $wgFileBackends as $conf ) {
362 if ( $conf['name'] == $name ) {
366 $useConfig['name'] = 'local-backend'; // swap name
367 unset( $useConfig['lockManager'] );
368 unset( $useConfig['fileJournal'] );
369 $class = $useConfig['class'];
370 self
::$backendToUse = new $class( $useConfig );
371 $backend = self
::$backendToUse;
374 # Replace with a mock. We do not care about generating real
375 # files on the filesystem, just need to expose the file
377 $backend = new MockFileBackend( array(
378 'name' => 'local-backend',
379 'wikiId' => wfWikiId()
384 'wgLocalFileRepo' => array(
385 'class' => 'LocalRepo',
387 'url' => 'http://example.com/images',
389 'transformVia404' => false,
390 'backend' => $backend
392 'wgEnableUploads' => self
::getOptionValue( 'wgEnableUploads', $opts, true ),
393 'wgLanguageCode' => $lang,
394 'wgDBprefix' => $this->db
->getType() != 'oracle' ?
'unittest_' : 'ut_',
395 'wgRawHtml' => self
::getOptionValue( 'wgRawHtml', $opts, false ),
396 'wgNamespacesWithSubpages' => array( NS_MAIN
=> isset( $opts['subpage'] ) ),
397 'wgAllowExternalImages' => self
::getOptionValue( 'wgAllowExternalImages', $opts, true ),
398 'wgThumbLimits' => array( self
::getOptionValue( 'thumbsize', $opts, 180 ) ),
399 'wgMaxTocLevel' => $maxtoclevel,
400 'wgUseTeX' => isset( $opts['math'] ) ||
isset( $opts['texvc'] ),
401 'wgMathDirectory' => $uploadDir . '/math',
402 'wgDefaultLanguageVariant' => $variant,
403 'wgLinkHolderBatchSize' => $linkHolderBatchSize,
407 $configLines = explode( "\n", $config );
409 foreach ( $configLines as $line ) {
410 list( $var, $value ) = explode( '=', $line, 2 );
412 $settings[$var] = eval( "return $value;" ); //???
416 $this->savedGlobals
= array();
419 wfRunHooks( 'ParserTestGlobals', array( &$settings ) );
421 $langObj = Language
::factory( $lang );
422 $settings['wgContLang'] = $langObj;
423 $settings['wgLang'] = $langObj;
425 $context = new RequestContext();
426 $settings['wgOut'] = $context->getOutput();
427 $settings['wgUser'] = $context->getUser();
428 $settings['wgRequest'] = $context->getRequest();
430 // We (re)set $wgThumbLimits to a single-element array above.
431 $context->getUser()->setOption( 'thumbsize', 0 );
433 foreach ( $settings as $var => $val ) {
434 if ( array_key_exists( $var, $GLOBALS ) ) {
435 $this->savedGlobals
[$var] = $GLOBALS[$var];
438 $GLOBALS[$var] = $val;
441 MagicWord
::clearCache();
443 # The entries saved into RepoGroup cache with previous globals will be wrong.
444 RepoGroup
::destroySingleton();
445 FileBackendGroup
::destroySingleton();
447 # Create dummy files in storage
448 $this->setupUploads();
450 # Publish the articles after we have the final language set
451 $this->publishTestArticles();
453 MessageCache
::destroyInstance();
459 * Get an FS upload directory (only applies to FSFileBackend)
461 * @return string The directory
463 protected function getUploadDir() {
464 if ( $this->keepUploads
) {
465 $dir = wfTempDir() . '/mwParser-images';
467 if ( is_dir( $dir ) ) {
471 $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
474 // wfDebug( "Creating upload directory $dir\n" );
475 if ( file_exists( $dir ) ) {
476 wfDebug( "Already exists!\n" );
485 * Create a dummy uploads directory which will contain a couple
486 * of files in order to pass existence tests.
488 * @return string The directory
490 protected function setupUploads() {
493 $base = $this->getBaseDir();
494 $backend = RepoGroup
::singleton()->getLocalRepo()->getBackend();
495 $backend->prepare( array( 'dir' => "$base/local-public/3/3a" ) );
496 $backend->store( array(
497 'src' => "$IP/tests/phpunit/data/parser/headbg.jpg", 'dst' => "$base/local-public/3/3a/Foobar.jpg"
499 $backend->prepare( array( 'dir' => "$base/local-public/e/ea" ) );
500 $backend->store( array(
501 'src' => "$IP/tests/phpunit/data/parser/wiki.png", 'dst' => "$base/local-public/e/ea/Thumb.png"
503 $backend->prepare( array( 'dir' => "$base/local-public/0/09" ) );
504 $backend->store( array(
505 'src' => "$IP/tests/phpunit/data/parser/headbg.jpg", 'dst' => "$base/local-public/0/09/Bad.jpg"
507 $backend->prepare( array( 'dir' => "$base/local-public/5/5f" ) );
508 $backend->store( array(
509 'src' => "$IP/tests/phpunit/data/parser/LoremIpsum.djvu", 'dst' => "$base/local-public/5/5f/LoremIpsum.djvu"
512 // No helpful SVG file to copy, so make one ourselves
513 $data = '<?xml version="1.0" encoding="utf-8"?>' .
514 '<svg xmlns="http://www.w3.org/2000/svg"' .
515 ' version="1.1" width="240" height="180"/>';
517 $backend->prepare( array( 'dir' => "$base/local-public/f/ff" ) );
518 $backend->quickCreate( array(
519 'content' => $data, 'dst' => "$base/local-public/f/ff/Foobar.svg"
524 * Restore default values and perform any necessary clean-up
525 * after each test runs.
527 protected function teardownGlobals() {
528 $this->teardownUploads();
530 foreach ( $this->savedGlobals
as $var => $val ) {
531 $GLOBALS[$var] = $val;
536 * Remove the dummy uploads directory
538 private function teardownUploads() {
539 if ( $this->keepUploads
) {
543 $backend = RepoGroup
::singleton()->getLocalRepo()->getBackend();
544 if ( $backend instanceof MockFileBackend
) {
545 # In memory backend, so dont bother cleaning them up.
549 $base = $this->getBaseDir();
550 // delete the files first, then the dirs.
553 "$base/local-public/3/3a/Foobar.jpg",
554 "$base/local-thumb/3/3a/Foobar.jpg/1000px-Foobar.jpg",
555 "$base/local-thumb/3/3a/Foobar.jpg/100px-Foobar.jpg",
556 "$base/local-thumb/3/3a/Foobar.jpg/120px-Foobar.jpg",
557 "$base/local-thumb/3/3a/Foobar.jpg/1280px-Foobar.jpg",
558 "$base/local-thumb/3/3a/Foobar.jpg/137px-Foobar.jpg",
559 "$base/local-thumb/3/3a/Foobar.jpg/1500px-Foobar.jpg",
560 "$base/local-thumb/3/3a/Foobar.jpg/177px-Foobar.jpg",
561 "$base/local-thumb/3/3a/Foobar.jpg/180px-Foobar.jpg",
562 "$base/local-thumb/3/3a/Foobar.jpg/200px-Foobar.jpg",
563 "$base/local-thumb/3/3a/Foobar.jpg/206px-Foobar.jpg",
564 "$base/local-thumb/3/3a/Foobar.jpg/20px-Foobar.jpg",
565 "$base/local-thumb/3/3a/Foobar.jpg/220px-Foobar.jpg",
566 "$base/local-thumb/3/3a/Foobar.jpg/265px-Foobar.jpg",
567 "$base/local-thumb/3/3a/Foobar.jpg/270px-Foobar.jpg",
568 "$base/local-thumb/3/3a/Foobar.jpg/274px-Foobar.jpg",
569 "$base/local-thumb/3/3a/Foobar.jpg/300px-Foobar.jpg",
570 "$base/local-thumb/3/3a/Foobar.jpg/30px-Foobar.jpg",
571 "$base/local-thumb/3/3a/Foobar.jpg/330px-Foobar.jpg",
572 "$base/local-thumb/3/3a/Foobar.jpg/353px-Foobar.jpg",
573 "$base/local-thumb/3/3a/Foobar.jpg/360px-Foobar.jpg",
574 "$base/local-thumb/3/3a/Foobar.jpg/400px-Foobar.jpg",
575 "$base/local-thumb/3/3a/Foobar.jpg/40px-Foobar.jpg",
576 "$base/local-thumb/3/3a/Foobar.jpg/440px-Foobar.jpg",
577 "$base/local-thumb/3/3a/Foobar.jpg/442px-Foobar.jpg",
578 "$base/local-thumb/3/3a/Foobar.jpg/450px-Foobar.jpg",
579 "$base/local-thumb/3/3a/Foobar.jpg/50px-Foobar.jpg",
580 "$base/local-thumb/3/3a/Foobar.jpg/600px-Foobar.jpg",
581 "$base/local-thumb/3/3a/Foobar.jpg/640px-Foobar.jpg",
582 "$base/local-thumb/3/3a/Foobar.jpg/70px-Foobar.jpg",
583 "$base/local-thumb/3/3a/Foobar.jpg/75px-Foobar.jpg",
584 "$base/local-thumb/3/3a/Foobar.jpg/960px-Foobar.jpg",
586 "$base/local-public/e/ea/Thumb.png",
588 "$base/local-public/0/09/Bad.jpg",
590 "$base/local-public/5/5f/LoremIpsum.djvu",
591 "$base/local-thumb/5/5f/LoremIpsum.djvu/page2-2480px-LoremIpsum.djvu.jpg",
592 "$base/local-thumb/5/5f/LoremIpsum.djvu/page2-3720px-LoremIpsum.djvu.jpg",
593 "$base/local-thumb/5/5f/LoremIpsum.djvu/page2-4960px-LoremIpsum.djvu.jpg",
595 "$base/local-public/f/ff/Foobar.svg",
596 "$base/local-thumb/f/ff/Foobar.svg/180px-Foobar.svg.png",
597 "$base/local-thumb/f/ff/Foobar.svg/2000px-Foobar.svg.png",
598 "$base/local-thumb/f/ff/Foobar.svg/270px-Foobar.svg.png",
599 "$base/local-thumb/f/ff/Foobar.svg/3000px-Foobar.svg.png",
600 "$base/local-thumb/f/ff/Foobar.svg/360px-Foobar.svg.png",
601 "$base/local-thumb/f/ff/Foobar.svg/4000px-Foobar.svg.png",
602 "$base/local-thumb/f/ff/Foobar.svg/langde-180px-Foobar.svg.png",
603 "$base/local-thumb/f/ff/Foobar.svg/langde-270px-Foobar.svg.png",
604 "$base/local-thumb/f/ff/Foobar.svg/langde-360px-Foobar.svg.png",
606 "$base/local-public/math/f/a/5/fa50b8b616463173474302ca3e63586b.png",
612 * Delete the specified files, if they exist.
613 * @param array $files Full paths to files to delete.
615 private static function deleteFiles( $files ) {
616 $backend = RepoGroup
::singleton()->getLocalRepo()->getBackend();
617 foreach ( $files as $file ) {
618 $backend->delete( array( 'src' => $file ), array( 'force' => 1 ) );
620 foreach ( $files as $file ) {
622 while ( $tmp = FileBackend
::parentStoragePath( $tmp ) ) {
623 if ( !$backend->clean( array( 'dir' => $tmp ) )->isOK() ) {
630 protected function getBaseDir() {
631 return 'mwstore://local-backend';
634 public function parserTestProvider() {
635 if ( $this->file
=== false ) {
636 global $wgParserTestFiles;
637 $this->file
= $wgParserTestFiles[0];
640 return new TestFileIterator( $this->file
, $this );
644 * Set the file from whose tests will be run by this instance
645 * @param string $filename
647 public function setParserTestFile( $filename ) {
648 $this->file
= $filename;
653 * @dataProvider parserTestProvider
654 * @param string $desc
655 * @param string $input
656 * @param string $result
658 * @param array $config
660 public function testParserTest( $desc, $input, $result, $opts, $config ) {
661 if ( $this->regex
!= '' && !preg_match( '/' . $this->regex
. '/', $desc ) ) {
662 $this->assertTrue( true ); // XXX: don't flood output with "test made no assertions"
663 //$this->markTestSkipped( 'Filtered out by the user' );
667 if ( !$this->isWikitextNS( NS_MAIN
) ) {
668 // parser tests frequently assume that the main namespace contains wikitext.
669 // @todo When setting up pages, force the content model. Only skip if
670 // $wgtContentModelUseDB is false.
671 $this->markTestSkipped( "Main namespace does not support wikitext,"
672 . "skipping parser test: $desc" );
675 wfDebug( "Running parser test: $desc\n" );
677 $opts = $this->parseOptions( $opts );
678 $context = $this->setupGlobals( $opts, $config );
680 $user = $context->getUser();
681 $options = ParserOptions
::newFromContext( $context );
683 if ( isset( $opts['title'] ) ) {
684 $titleText = $opts['title'];
686 $titleText = 'Parser test';
689 $local = isset( $opts['local'] );
690 $preprocessor = isset( $opts['preprocessor'] ) ?
$opts['preprocessor'] : null;
691 $parser = $this->getParser( $preprocessor );
693 $title = Title
::newFromText( $titleText );
695 # Parser test requiring math. Make sure texvc is executable
696 # or just skip such tests.
697 if ( isset( $opts['math'] ) ||
isset( $opts['texvc'] ) ) {
700 if ( !isset( $wgTexvc ) ) {
701 $this->markTestSkipped( "SKIPPED: \$wgTexvc is not set" );
702 } elseif ( !is_executable( $wgTexvc ) ) {
703 $this->markTestSkipped( "SKIPPED: texvc binary does not exist"
704 . " or is not executable.\n"
705 . "Current configuration is:\n\$wgTexvc = '$wgTexvc'" );
708 if ( isset( $opts['djvu'] ) ) {
709 if ( !$this->djVuSupport
->isEnabled() ) {
710 $this->markTestSkipped( "SKIPPED: djvu binaries do not exist or are not executable.\n" );
714 if ( isset( $opts['pst'] ) ) {
715 $out = $parser->preSaveTransform( $input, $title, $user, $options );
716 } elseif ( isset( $opts['msg'] ) ) {
717 $out = $parser->transformMsg( $input, $options, $title );
718 } elseif ( isset( $opts['section'] ) ) {
719 $section = $opts['section'];
720 $out = $parser->getSection( $input, $section );
721 } elseif ( isset( $opts['replace'] ) ) {
722 $section = $opts['replace'][0];
723 $replace = $opts['replace'][1];
724 $out = $parser->replaceSection( $input, $section, $replace );
725 } elseif ( isset( $opts['comment'] ) ) {
726 $out = Linker
::formatComment( $input, $title, $local );
727 } elseif ( isset( $opts['preload'] ) ) {
728 $out = $parser->getPreloadText( $input, $title, $options );
730 $output = $parser->parse( $input, $title, $options, true, true, 1337 );
731 $output->setTOCEnabled( !isset( $opts['notoc'] ) );
732 $out = $output->getText();
734 if ( isset( $opts['showtitle'] ) ) {
735 if ( $output->getTitleText() ) {
736 $title = $output->getTitleText();
739 $out = "$title\n$out";
742 if ( isset( $opts['ill'] ) ) {
743 $out = $this->tidy( implode( ' ', $output->getLanguageLinks() ) );
744 } elseif ( isset( $opts['cat'] ) ) {
745 $outputPage = $context->getOutput();
746 $outputPage->addCategoryLinks( $output->getCategories() );
747 $cats = $outputPage->getCategoryLinks();
749 if ( isset( $cats['normal'] ) ) {
750 $out = $this->tidy( implode( ' ', $cats['normal'] ) );
755 $parser->mPreprocessor
= null;
757 $result = $this->tidy( $result );
760 $this->teardownGlobals();
762 $this->assertEquals( $result, $out, $desc );
766 * Run a fuzz test series
767 * Draw input from a set of test files
769 * @todo fixme Needs some work to not eat memory until the world explodes
773 public function testFuzzTests() {
774 global $wgParserTestFiles;
776 $files = $wgParserTestFiles;
778 if ( $this->getCliArg( 'file=' ) ) {
779 $files = array( $this->getCliArg( 'file=' ) );
782 $dict = $this->getFuzzInput( $files );
783 $dictSize = strlen( $dict );
784 $logMaxLength = log( $this->maxFuzzTestLength
);
786 ini_set( 'memory_limit', $this->memoryLimit
* 1048576 );
789 $opts = ParserOptions
::newFromUser( $user );
790 $title = Title
::makeTitle( NS_MAIN
, 'Parser_test' );
796 // Generate test input
797 mt_srand( ++
$this->fuzzSeed
);
798 $totalLength = mt_rand( 1, $this->maxFuzzTestLength
);
801 while ( strlen( $input ) < $totalLength ) {
802 $logHairLength = mt_rand( 0, 1000000 ) / 1000000 * $logMaxLength;
803 $hairLength = min( intval( exp( $logHairLength ) ), $dictSize );
804 $offset = mt_rand( 0, $dictSize - $hairLength );
805 $input .= substr( $dict, $offset, $hairLength );
808 $this->setupGlobals();
809 $parser = $this->getParser();
813 $parser->parse( $input, $title, $opts );
814 $this->assertTrue( true, "Test $id, fuzz seed {$this->fuzzSeed}" );
815 } catch ( Exception
$exception ) {
816 $input_dump = sprintf( "string(%d) \"%s\"\n", strlen( $input ), $input );
818 $this->assertTrue( false, "Test $id, fuzz seed {$this->fuzzSeed}. \n\n" .
819 "Input: $input_dump\n\nError: {$exception->getMessage()}\n\n" .
820 "Backtrace: {$exception->getTraceAsString()}" );
823 $this->teardownGlobals();
824 $parser->__destruct();
826 if ( $id %
100 == 0 ) {
827 $usage = intval( memory_get_usage( true ) / $this->memoryLimit
/ 1048576 * 100 );
828 //echo "{$this->fuzzSeed}: $numSuccess/$numTotal (mem: $usage%)\n";
830 $ret = "Out of memory:\n";
831 $memStats = $this->getMemoryBreakdown();
833 foreach ( $memStats as $name => $usage ) {
834 $ret .= "$name: $usage\n";
837 throw new MWException( $ret );
845 //Various getter functions
848 * Get an input dictionary from a set of parser test files
849 * @param array $filenames
851 function getFuzzInput( $filenames ) {
854 foreach ( $filenames as $filename ) {
855 $contents = file_get_contents( $filename );
856 preg_match_all( '/!!\s*input\n(.*?)\n!!\s*result/s', $contents, $matches );
858 foreach ( $matches[1] as $match ) {
859 $dict .= $match . "\n";
867 * Get a memory usage breakdown
869 function getMemoryBreakdown() {
872 foreach ( $GLOBALS as $name => $value ) {
873 $memStats['$' . $name] = strlen( serialize( $value ) );
876 $classes = get_declared_classes();
878 foreach ( $classes as $class ) {
879 $rc = new ReflectionClass( $class );
880 $props = $rc->getStaticProperties();
881 $memStats[$class] = strlen( serialize( $props ) );
882 $methods = $rc->getMethods();
884 foreach ( $methods as $method ) {
885 $memStats[$class] +
= strlen( serialize( $method->getStaticVariables() ) );
889 $functions = get_defined_functions();
891 foreach ( $functions['user'] as $function ) {
892 $rf = new ReflectionFunction( $function );
893 $memStats["$function()"] = strlen( serialize( $rf->getStaticVariables() ) );
902 * Get a Parser object
903 * @param Preprocessor $preprocessor
905 function getParser( $preprocessor = null ) {
906 global $wgParserConf;
908 $class = $wgParserConf['class'];
909 $parser = new $class( array( 'preprocessorClass' => $preprocessor ) +
$wgParserConf );
911 wfRunHooks( 'ParserTestParser', array( &$parser ) );
916 //Various action functions
918 public function addArticle( $name, $text, $line ) {
919 self
::$articles[$name] = array( $text, $line );
922 public function publishTestArticles() {
923 if ( empty( self
::$articles ) ) {
927 foreach ( self
::$articles as $name => $info ) {
928 list( $text, $line ) = $info;
929 ParserTest
::addArticle( $name, $text, $line, 'ignoreduplicate' );
934 * Steal a callback function from the primary parser, save it for
935 * application to our scary parser. If the hook is not installed,
936 * abort processing of this file.
938 * @param string $name
939 * @return bool True if tag hook is present
941 public function requireHook( $name ) {
943 $wgParser->firstCallInit(); // make sure hooks are loaded.
944 return isset( $wgParser->mTagHooks
[$name] );
947 public function requireFunctionHook( $name ) {
949 $wgParser->firstCallInit(); // make sure hooks are loaded.
950 return isset( $wgParser->mFunctionHooks
[$name] );
953 public function requireTransparentHook( $name ) {
955 $wgParser->firstCallInit(); // make sure hooks are loaded.
956 return isset( $wgParser->mTransparentTagHooks
[$name] );
959 //Various "cleanup" functions
962 * Run the "tidy" command on text if the $wgUseTidy
965 * @param string $text The text to tidy
968 protected function tidy( $text ) {
972 $text = MWTidy
::tidy( $text );
979 * Remove last character if it is a newline
982 public function removeEndingNewline( $s ) {
983 if ( substr( $s, -1 ) === "\n" ) {
984 return substr( $s, 0, -1 );
990 //Test options parser functions
992 protected function parseOptions( $instring ) {
998 // foo=bar,"baz quux"
1020 "[^"]*" # Quoted val
1022 \[\[[^]]*\]\] # Link target
1030 if ( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER
) ) {
1031 foreach ( $matches as $bits ) {
1032 array_shift( $bits );
1033 $key = strtolower( array_shift( $bits ) );
1034 if ( count( $bits ) == 0 ) {
1036 } elseif ( count( $bits ) == 1 ) {
1037 $opts[$key] = $this->cleanupOption( array_shift( $bits ) );
1040 $opts[$key] = array_map( array( $this, 'cleanupOption' ), $bits );
1048 protected function cleanupOption( $opt ) {
1049 if ( substr( $opt, 0, 1 ) == '"' ) {
1050 return substr( $opt, 1, -1 );
1053 if ( substr( $opt, 0, 2 ) == '[[' ) {
1054 return substr( $opt, 2, -2 );
1061 * Use a regex to find out the value of an option
1062 * @param string $key Name of option val to retrieve
1063 * @param array $opts Options array to look in
1064 * @param mixed $default Default value returned if not found
1066 protected static function getOptionValue( $key, $opts, $default ) {
1067 $key = strtolower( $key );
1069 if ( isset( $opts[$key] ) ) {