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['wgServerName'] = 'example.org';
69 $tmpGlobals['wgScript'] = '/index.php';
70 $tmpGlobals['wgScriptPath'] = '/';
71 $tmpGlobals['wgArticlePath'] = '/wiki/$1';
72 $tmpGlobals['wgActionPaths'] = array();
73 $tmpGlobals['wgVariantArticlePath'] = false;
74 $tmpGlobals['wgExtensionAssetsPath'] = '/extensions';
75 $tmpGlobals['wgStylePath'] = '/skins';
76 $tmpGlobals['wgEnableUploads'] = true;
77 $tmpGlobals['wgThumbnailScriptPath'] = false;
78 $tmpGlobals['wgLocalFileRepo'] = array(
79 'class' => 'LocalRepo',
81 'url' => 'http://example.com/images',
83 'transformVia404' => false,
84 'backend' => 'local-backend'
86 $tmpGlobals['wgForeignFileRepos'] = array();
87 $tmpGlobals['wgDefaultExternalStore'] = array();
88 $tmpGlobals['wgEnableParserCache'] = false;
89 $tmpGlobals['wgCapitalLinks'] = true;
90 $tmpGlobals['wgNoFollowLinks'] = true;
91 $tmpGlobals['wgNoFollowDomainExceptions'] = array();
92 $tmpGlobals['wgExternalLinkTarget'] = false;
93 $tmpGlobals['wgThumbnailScriptPath'] = false;
94 $tmpGlobals['wgUseImageResize'] = true;
95 $tmpGlobals['wgAllowExternalImages'] = true;
96 $tmpGlobals['wgRawHtml'] = false;
97 $tmpGlobals['wgUseTidy'] = false;
98 $tmpGlobals['wgAlwaysUseTidy'] = false;
99 $tmpGlobals['wgWellFormedXml'] = true;
100 $tmpGlobals['wgAllowMicrodataAttributes'] = true;
101 $tmpGlobals['wgExperimentalHtmlIds'] = false;
102 $tmpGlobals['wgAdaptiveMessageCache'] = true;
103 $tmpGlobals['wgUseDatabaseMessages'] = true;
104 $tmpGlobals['wgLocaltimezone'] = 'UTC';
105 $tmpGlobals['wgDeferredUpdateList'] = array();
106 $tmpGlobals['wgGroupPermissions'] = array(
108 'createaccount' => true,
111 'createpage' => true,
112 'createtalk' => true,
114 $tmpGlobals['wgNamespaceProtection'] = array( NS_MEDIAWIKI
=> 'editinterface' );
116 $tmpGlobals['wgParser'] = new StubObject(
117 'wgParser', $GLOBALS['wgParserConf']['class'],
118 array( $GLOBALS['wgParserConf'] ) );
120 $tmpGlobals['wgFileExtensions'][] = 'svg';
121 $tmpGlobals['wgSVGConverter'] = 'rsvg';
122 $tmpGlobals['wgSVGConverters']['rsvg'] =
123 '$path/rsvg-convert -w $width -h $height $input -o $output';
125 if ( $GLOBALS['wgStyleDirectory'] === false ) {
126 $tmpGlobals['wgStyleDirectory'] = "$IP/skins";
129 # Replace all media handlers with a mock. We do not need to generate
130 # actual thumbnails to do parser testing, we only care about receiving
131 # a ThumbnailImage properly initialized.
132 global $wgMediaHandlers;
133 foreach ( $wgMediaHandlers as $type => $handler ) {
134 $tmpGlobals['wgMediaHandlers'][$type] = 'MockBitmapHandler';
136 // Vector images have to be handled slightly differently
137 $tmpGlobals['wgMediaHandlers']['image/svg+xml'] = 'MockSvgHandler';
139 // DjVu images have to be handled slightly differently
140 $tmpGlobals['wgMediaHandlers']['image/vnd.djvu'] = 'MockDjVuHandler';
142 $tmpHooks = $wgHooks;
143 $tmpHooks['ParserTestParser'][] = 'ParserTestParserHook::setup';
144 $tmpHooks['ParserGetVariableValueTs'][] = 'ParserTest::getFakeTimestamp';
145 $tmpGlobals['wgHooks'] = $tmpHooks;
146 # add a namespace shadowing a interwiki link, to test
147 # proper precedence when resolving links. (bug 51680)
148 $tmpGlobals['wgExtraNamespaces'] = array( 100 => 'MemoryAlpha' );
151 $this->djVuSupport
= new DjVuSupport();
153 $this->setMwGlobals( $tmpGlobals );
155 $this->savedWeirdGlobals
['image_alias'] = $wgNamespaceAliases['Image'];
156 $this->savedWeirdGlobals
['image_talk_alias'] = $wgNamespaceAliases['Image_talk'];
158 $wgNamespaceAliases['Image'] = NS_FILE
;
159 $wgNamespaceAliases['Image_talk'] = NS_FILE_TALK
;
161 MWNamespace
::getCanonicalNamespaces( true ); # reset namespace cache
162 $wgContLang->resetNamespaces(); # reset namespace cache
165 protected function tearDown() {
166 global $wgNamespaceAliases, $wgContLang;
168 $wgNamespaceAliases['Image'] = $this->savedWeirdGlobals
['image_alias'];
169 $wgNamespaceAliases['Image_talk'] = $this->savedWeirdGlobals
['image_talk_alias'];
172 RepoGroup
::destroySingleton();
173 FileBackendGroup
::destroySingleton();
175 // Remove temporary pages from the link cache
176 LinkCache
::singleton()->clear();
178 // Restore message cache (temporary pages and $wgUseDatabaseMessages)
179 MessageCache
::destroyInstance();
183 MWNamespace
::getCanonicalNamespaces( true ); # reset namespace cache
184 $wgContLang->resetNamespaces(); # reset namespace cache
187 public static function tearDownAfterClass() {
188 ParserTest
::tearDownInterwikis();
189 parent
::tearDownAfterClass();
192 function addDBData() {
193 $this->tablesUsed
[] = 'site_stats';
194 # disabled for performance
195 #$this->tablesUsed[] = 'image';
197 # Update certain things in site_stats
198 $this->db
->insert( 'site_stats',
199 array( 'ss_row_id' => 1, 'ss_images' => 2, 'ss_good_articles' => 1 ),
203 $user = User
::newFromId( 0 );
204 LinkCache
::singleton()->clear(); # Avoids the odd failure at creating the nullRevision
206 # Upload DB table entries for files.
207 # We will upload the actual files later. Note that if anything causes LocalFile::load()
208 # to be triggered before then, it will break via maybeUpgrade() setting the fileExists
209 # member to false and storing it in cache.
210 # note that the size/width/height/bits/etc of the file
211 # are actually set by inspecting the file itself; the arguments
212 # to recordUpload2 have no effect. That said, we try to make things
213 # match up so it is less confusing to readers of the code & tests.
214 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Foobar.jpg' ) );
215 if ( !$this->db
->selectField( 'image', '1', array( 'img_name' => $image->getName() ) ) ) {
216 $image->recordUpload2(
218 'Upload of some lame file',
225 'media_type' => MEDIATYPE_BITMAP
,
226 'mime' => 'image/jpeg',
227 'metadata' => serialize( array() ),
228 'sha1' => wfBaseConvert( '1', 16, 36, 31 ),
229 'fileExists' => true ),
230 $this->db
->timestamp( '20010115123500' ), $user
234 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Thumb.png' ) );
235 if ( !$this->db
->selectField( 'image', '1', array( 'img_name' => $image->getName() ) ) ) {
236 $image->recordUpload2(
238 'Upload of some lame thumbnail',
239 'Some lame thumbnail',
245 'media_type' => MEDIATYPE_BITMAP
,
246 'mime' => 'image/png',
247 'metadata' => serialize( array() ),
248 'sha1' => wfBaseConvert( '2', 16, 36, 31 ),
249 'fileExists' => true ),
250 $this->db
->timestamp( '20130225203040' ), $user
254 # This image will be blacklisted in [[MediaWiki:Bad image list]]
255 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Bad.jpg' ) );
256 if ( !$this->db
->selectField( 'image', '1', array( 'img_name' => $image->getName() ) ) ) {
257 $image->recordUpload2(
266 'media_type' => MEDIATYPE_BITMAP
,
267 'mime' => 'image/jpeg',
268 'metadata' => serialize( array() ),
269 'sha1' => wfBaseConvert( '3', 16, 36, 31 ),
270 'fileExists' => true ),
271 $this->db
->timestamp( '20010115123500' ), $user
274 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Foobar.svg' ) );
275 if ( !$this->db
->selectField( 'image', '1', array( 'img_name' => $image->getName() ) ) ) {
276 $image->recordUpload2( '', 'Upload of some lame SVG', 'Some lame SVG', array(
281 'media_type' => MEDIATYPE_DRAWING
,
282 'mime' => 'image/svg+xml',
283 'metadata' => serialize( array() ),
284 'sha1' => wfBaseConvert( '', 16, 36, 31 ),
286 ), $this->db
->timestamp( '20010115123500' ), $user );
288 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Portrait.png' ) );
289 if ( !$this->db
->selectField( 'image', '1', array( 'img_name' => $image->getName() ) ) ) {
290 $image->recordUpload2( '', 'Upload of tall bitmap', 'Some tall bitmap', array(
295 'media_type' => MEDIATYPE_BITMAP
,
296 'mime' => 'image/png',
297 'metadata' => serialize( array() ),
298 'sha1' => wfBaseConvert( '', 16, 36, 31 ),
300 ), $this->db
->timestamp( '20140515134200' ), $user );
302 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Portrait.svg' ) );
303 if ( !$this->db
->selectField( 'image', '1', array( 'img_name' => $image->getName() ) ) ) {
304 $image->recordUpload2( '', 'Upload of tall SVG', 'Some tall SVG', array(
309 'media_type' => MEDIATYPE_DRAWING
,
310 'mime' => 'image/svg+xml',
311 'metadata' => serialize( array() ),
312 'sha1' => wfBaseConvert( '', 16, 36, 31 ),
314 ), $this->db
->timestamp( '20140325124200' ), $user );
318 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'LoremIpsum.djvu' ) );
319 if ( !$this->db
->selectField( 'image', '1', array( 'img_name' => $image->getName() ) ) ) {
320 $image->recordUpload2( '', 'Upload a DjVu', 'A DjVu', array(
325 'media_type' => MEDIATYPE_BITMAP
,
326 'mime' => 'image/vnd.djvu',
327 'metadata' => '<?xml version="1.0" ?>
328 <!DOCTYPE DjVuXML PUBLIC "-//W3C//DTD DjVuXML 1.1//EN" "pubtext/DjVuXML-s.dtd">
331 <BODY><OBJECT height="3508" width="2480">
332 <PARAM name="DPI" value="300" />
333 <PARAM name="GAMMA" value="2.2" />
335 <OBJECT height="3508" width="2480">
336 <PARAM name="DPI" value="300" />
337 <PARAM name="GAMMA" value="2.2" />
339 <OBJECT height="3508" width="2480">
340 <PARAM name="DPI" value="300" />
341 <PARAM name="GAMMA" value="2.2" />
343 <OBJECT height="3508" width="2480">
344 <PARAM name="DPI" value="300" />
345 <PARAM name="GAMMA" value="2.2" />
347 <OBJECT height="3508" width="2480">
348 <PARAM name="DPI" value="300" />
349 <PARAM name="GAMMA" value="2.2" />
353 'sha1' => wfBaseConvert( '', 16, 36, 31 ),
355 ), $this->db
->timestamp( '20140115123600' ), $user );
359 //ParserTest setup/teardown functions
362 * Set up the global variables for a consistent environment for each test.
363 * Ideally this should replace the global configuration entirely.
365 protected function setupGlobals( $opts = array(), $config = '' ) {
366 global $wgFileBackends;
367 # Find out values for some special options.
369 self
::getOptionValue( 'language', $opts, 'en' );
371 self
::getOptionValue( 'variant', $opts, false );
373 self
::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
374 $linkHolderBatchSize =
375 self
::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
377 $uploadDir = $this->getUploadDir();
378 if ( $this->getCliArg( 'use-filebackend=' ) ) {
379 if ( self
::$backendToUse ) {
380 $backend = self
::$backendToUse;
382 $name = $this->getCliArg( 'use-filebackend=' );
383 $useConfig = array();
384 foreach ( $wgFileBackends as $conf ) {
385 if ( $conf['name'] == $name ) {
389 $useConfig['name'] = 'local-backend'; // swap name
390 unset( $useConfig['lockManager'] );
391 unset( $useConfig['fileJournal'] );
392 $class = $useConfig['class'];
393 self
::$backendToUse = new $class( $useConfig );
394 $backend = self
::$backendToUse;
397 # Replace with a mock. We do not care about generating real
398 # files on the filesystem, just need to expose the file
400 $backend = new MockFileBackend( array(
401 'name' => 'local-backend',
402 'wikiId' => wfWikiId()
407 'wgLocalFileRepo' => array(
408 'class' => 'LocalRepo',
410 'url' => 'http://example.com/images',
412 'transformVia404' => false,
413 'backend' => $backend
415 'wgEnableUploads' => self
::getOptionValue( 'wgEnableUploads', $opts, true ),
416 'wgLanguageCode' => $lang,
417 'wgDBprefix' => $this->db
->getType() != 'oracle' ?
'unittest_' : 'ut_',
418 'wgRawHtml' => self
::getOptionValue( 'wgRawHtml', $opts, false ),
419 'wgNamespacesWithSubpages' => array( NS_MAIN
=> isset( $opts['subpage'] ) ),
420 'wgAllowExternalImages' => self
::getOptionValue( 'wgAllowExternalImages', $opts, true ),
421 'wgThumbLimits' => array( self
::getOptionValue( 'thumbsize', $opts, 180 ) ),
422 'wgMaxTocLevel' => $maxtoclevel,
423 'wgUseTeX' => isset( $opts['math'] ) ||
isset( $opts['texvc'] ),
424 'wgMathDirectory' => $uploadDir . '/math',
425 'wgDefaultLanguageVariant' => $variant,
426 'wgLinkHolderBatchSize' => $linkHolderBatchSize,
430 $configLines = explode( "\n", $config );
432 foreach ( $configLines as $line ) {
433 list( $var, $value ) = explode( '=', $line, 2 );
435 $settings[$var] = eval( "return $value;" ); //???
439 $this->savedGlobals
= array();
442 wfRunHooks( 'ParserTestGlobals', array( &$settings ) );
444 $langObj = Language
::factory( $lang );
445 $settings['wgContLang'] = $langObj;
446 $settings['wgLang'] = $langObj;
448 $context = new RequestContext();
449 $settings['wgOut'] = $context->getOutput();
450 $settings['wgUser'] = $context->getUser();
451 $settings['wgRequest'] = $context->getRequest();
453 // We (re)set $wgThumbLimits to a single-element array above.
454 $context->getUser()->setOption( 'thumbsize', 0 );
456 foreach ( $settings as $var => $val ) {
457 if ( array_key_exists( $var, $GLOBALS ) ) {
458 $this->savedGlobals
[$var] = $GLOBALS[$var];
461 $GLOBALS[$var] = $val;
464 MagicWord
::clearCache();
466 # The entries saved into RepoGroup cache with previous globals will be wrong.
467 RepoGroup
::destroySingleton();
468 FileBackendGroup
::destroySingleton();
470 # Create dummy files in storage
471 $this->setupUploads();
473 # Publish the articles after we have the final language set
474 $this->publishTestArticles();
476 MessageCache
::destroyInstance();
482 * Get an FS upload directory (only applies to FSFileBackend)
484 * @return string The directory
486 protected function getUploadDir() {
487 if ( $this->keepUploads
) {
488 $dir = wfTempDir() . '/mwParser-images';
490 if ( is_dir( $dir ) ) {
494 $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
497 // wfDebug( "Creating upload directory $dir\n" );
498 if ( file_exists( $dir ) ) {
499 wfDebug( "Already exists!\n" );
508 * Create a dummy uploads directory which will contain a couple
509 * of files in order to pass existence tests.
511 * @return string The directory
513 protected function setupUploads() {
516 $base = $this->getBaseDir();
517 $backend = RepoGroup
::singleton()->getLocalRepo()->getBackend();
518 $backend->prepare( array( 'dir' => "$base/local-public/3/3a" ) );
519 $backend->store( array(
520 'src' => "$IP/skins/monobook/headbg.jpg", 'dst' => "$base/local-public/3/3a/Foobar.jpg"
522 $backend->prepare( array( 'dir' => "$base/local-public/e/ea" ) );
523 $backend->store( array(
524 'src' => "$IP/skins/monobook/wiki.png", 'dst' => "$base/local-public/e/ea/Thumb.png"
526 $backend->prepare( array( 'dir' => "$base/local-public/0/09" ) );
527 $backend->store( array(
528 'src' => "$IP/skins/monobook/headbg.jpg", 'dst' => "$base/local-public/0/09/Bad.jpg"
530 $backend->prepare( array( 'dir' => "$base/local-public/9/93" ) );
531 $backend->store( array(
532 'src' => "$IP/tests/phpunit/data/media/Portrait.png", 'dst' => "$base/local-public/9/93/Portrait.png"
534 $backend->prepare( array( 'dir' => "$base/local-public/5/5f" ) );
535 $backend->store( array(
536 'src' => "$IP/tests/phpunit/data/media/LoremIpsum.djvu", 'dst' => "$base/local-public/5/5f/LoremIpsum.djvu"
539 // No helpful SVG file to copy, so make one ourselves
540 $data = '<?xml version="1.0" encoding="utf-8"?>' .
541 '<svg xmlns="http://www.w3.org/2000/svg"' .
542 ' version="1.1" width="240" height="180"/>';
544 $backend->prepare( array( 'dir' => "$base/local-public/f/ff" ) );
545 $backend->quickCreate( array(
546 'content' => $data, 'dst' => "$base/local-public/f/ff/Foobar.svg"
549 $data = '<?xml version="1.0" encoding="utf-8"?>' .
550 '<svg xmlns="http://www.w3.org/2000/svg"' .
551 ' version="1.1" width="180" height="240"/>';
553 $backend->prepare( array( 'dir' => "$base/local-public/f/fc" ) );
554 $backend->quickCreate( array(
555 'content' => $data, 'dst' => "$base/local-public/f/fc/Portrait.svg"
560 * Restore default values and perform any necessary clean-up
561 * after each test runs.
563 protected function teardownGlobals() {
564 $this->teardownUploads();
566 foreach ( $this->savedGlobals
as $var => $val ) {
567 $GLOBALS[$var] = $val;
572 * Remove the dummy uploads directory
574 private function teardownUploads() {
575 if ( $this->keepUploads
) {
579 $backend = RepoGroup
::singleton()->getLocalRepo()->getBackend();
580 if ( $backend instanceof MockFileBackend
) {
581 # In memory backend, so dont bother cleaning them up.
585 $base = $this->getBaseDir();
586 // delete the files first, then the dirs.
589 "$base/local-public/3/3a/Foobar.jpg",
590 "$base/local-thumb/3/3a/Foobar.jpg/1000px-Foobar.jpg",
591 "$base/local-thumb/3/3a/Foobar.jpg/100px-Foobar.jpg",
592 "$base/local-thumb/3/3a/Foobar.jpg/120px-Foobar.jpg",
593 "$base/local-thumb/3/3a/Foobar.jpg/1280px-Foobar.jpg",
594 "$base/local-thumb/3/3a/Foobar.jpg/137px-Foobar.jpg",
595 "$base/local-thumb/3/3a/Foobar.jpg/1500px-Foobar.jpg",
596 "$base/local-thumb/3/3a/Foobar.jpg/177px-Foobar.jpg",
597 "$base/local-thumb/3/3a/Foobar.jpg/180px-Foobar.jpg",
598 "$base/local-thumb/3/3a/Foobar.jpg/200px-Foobar.jpg",
599 "$base/local-thumb/3/3a/Foobar.jpg/206px-Foobar.jpg",
600 "$base/local-thumb/3/3a/Foobar.jpg/20px-Foobar.jpg",
601 "$base/local-thumb/3/3a/Foobar.jpg/220px-Foobar.jpg",
602 "$base/local-thumb/3/3a/Foobar.jpg/265px-Foobar.jpg",
603 "$base/local-thumb/3/3a/Foobar.jpg/270px-Foobar.jpg",
604 "$base/local-thumb/3/3a/Foobar.jpg/274px-Foobar.jpg",
605 "$base/local-thumb/3/3a/Foobar.jpg/300px-Foobar.jpg",
606 "$base/local-thumb/3/3a/Foobar.jpg/30px-Foobar.jpg",
607 "$base/local-thumb/3/3a/Foobar.jpg/330px-Foobar.jpg",
608 "$base/local-thumb/3/3a/Foobar.jpg/353px-Foobar.jpg",
609 "$base/local-thumb/3/3a/Foobar.jpg/360px-Foobar.jpg",
610 "$base/local-thumb/3/3a/Foobar.jpg/400px-Foobar.jpg",
611 "$base/local-thumb/3/3a/Foobar.jpg/40px-Foobar.jpg",
612 "$base/local-thumb/3/3a/Foobar.jpg/440px-Foobar.jpg",
613 "$base/local-thumb/3/3a/Foobar.jpg/442px-Foobar.jpg",
614 "$base/local-thumb/3/3a/Foobar.jpg/450px-Foobar.jpg",
615 "$base/local-thumb/3/3a/Foobar.jpg/50px-Foobar.jpg",
616 "$base/local-thumb/3/3a/Foobar.jpg/600px-Foobar.jpg",
617 "$base/local-thumb/3/3a/Foobar.jpg/640px-Foobar.jpg",
618 "$base/local-thumb/3/3a/Foobar.jpg/70px-Foobar.jpg",
619 "$base/local-thumb/3/3a/Foobar.jpg/75px-Foobar.jpg",
620 "$base/local-thumb/3/3a/Foobar.jpg/960px-Foobar.jpg",
622 "$base/local-public/e/ea/Thumb.png",
624 "$base/local-public/0/09/Bad.jpg",
626 "$base/local-public/5/5f/LoremIpsum.djvu",
627 "$base/local-thumb/5/5f/LoremIpsum.djvu/page2-2480px-LoremIpsum.djvu.jpg",
628 "$base/local-thumb/5/5f/LoremIpsum.djvu/page2-3720px-LoremIpsum.djvu.jpg",
629 "$base/local-thumb/5/5f/LoremIpsum.djvu/page2-4960px-LoremIpsum.djvu.jpg",
631 "$base/local-public/9/93/Portrait.png",
632 "$base/local-thumb/9/93/Portrait.png/165px-Portrait.png",
634 "$base/local-public/f/ff/Foobar.svg",
635 "$base/local-thumb/f/ff/Foobar.svg/180px-Foobar.svg.png",
636 "$base/local-thumb/f/ff/Foobar.svg/2000px-Foobar.svg.png",
637 "$base/local-thumb/f/ff/Foobar.svg/270px-Foobar.svg.png",
638 "$base/local-thumb/f/ff/Foobar.svg/3000px-Foobar.svg.png",
639 "$base/local-thumb/f/ff/Foobar.svg/360px-Foobar.svg.png",
640 "$base/local-thumb/f/ff/Foobar.svg/4000px-Foobar.svg.png",
641 "$base/local-thumb/f/ff/Foobar.svg/langde-180px-Foobar.svg.png",
642 "$base/local-thumb/f/ff/Foobar.svg/langde-270px-Foobar.svg.png",
643 "$base/local-thumb/f/ff/Foobar.svg/langde-360px-Foobar.svg.png",
645 "$base/local-public/f/fc/Portrait.svg",
646 "$base/local-thumb/f/fc/Portrait.svg/165px-Portrait.svg.png",
647 "$base/local-thumb/f/fc/Portrait.svg/225px-Portrait.svg.png",
648 "$base/local-thumb/f/fc/Portrait.svg/247px-Portrait.svg.png",
649 "$base/local-thumb/f/fc/Portrait.svg/330px-Portrait.svg.png",
650 "$base/local-thumb/f/fc/Portrait.svg/337px-Portrait.svg.png",
651 "$base/local-thumb/f/fc/Portrait.svg/450px-Portrait.svg.png",
653 "$base/local-public/math/f/a/5/fa50b8b616463173474302ca3e63586b.png",
659 * Delete the specified files, if they exist.
660 * @param array $files Full paths to files to delete.
662 private static function deleteFiles( $files ) {
663 $backend = RepoGroup
::singleton()->getLocalRepo()->getBackend();
664 foreach ( $files as $file ) {
665 $backend->delete( array( 'src' => $file ), array( 'force' => 1 ) );
667 foreach ( $files as $file ) {
669 while ( $tmp = FileBackend
::parentStoragePath( $tmp ) ) {
670 if ( !$backend->clean( array( 'dir' => $tmp ) )->isOK() ) {
677 protected function getBaseDir() {
678 return 'mwstore://local-backend';
681 public function parserTestProvider() {
682 if ( $this->file
=== false ) {
683 global $wgParserTestFiles;
684 $this->file
= $wgParserTestFiles[0];
687 return new TestFileIterator( $this->file
, $this );
691 * Set the file from whose tests will be run by this instance
692 * @param string $filename
694 public function setParserTestFile( $filename ) {
695 $this->file
= $filename;
700 * @dataProvider parserTestProvider
701 * @param string $desc
702 * @param string $input
703 * @param string $result
705 * @param array $config
707 public function testParserTest( $desc, $input, $result, $opts, $config ) {
708 if ( $this->regex
!= '' && !preg_match( '/' . $this->regex
. '/', $desc ) ) {
709 $this->assertTrue( true ); // XXX: don't flood output with "test made no assertions"
710 //$this->markTestSkipped( 'Filtered out by the user' );
714 if ( !$this->isWikitextNS( NS_MAIN
) ) {
715 // parser tests frequently assume that the main namespace contains wikitext.
716 // @todo When setting up pages, force the content model. Only skip if
717 // $wgtContentModelUseDB is false.
718 $this->markTestSkipped( "Main namespace does not support wikitext,"
719 . "skipping parser test: $desc" );
722 wfDebug( "Running parser test: $desc\n" );
724 $opts = $this->parseOptions( $opts );
725 $context = $this->setupGlobals( $opts, $config );
727 $user = $context->getUser();
728 $options = ParserOptions
::newFromContext( $context );
730 if ( isset( $opts['title'] ) ) {
731 $titleText = $opts['title'];
733 $titleText = 'Parser test';
736 $local = isset( $opts['local'] );
737 $preprocessor = isset( $opts['preprocessor'] ) ?
$opts['preprocessor'] : null;
738 $parser = $this->getParser( $preprocessor );
740 $title = Title
::newFromText( $titleText );
742 # Parser test requiring math. Make sure texvc is executable
743 # or just skip such tests.
744 if ( isset( $opts['math'] ) ||
isset( $opts['texvc'] ) ) {
747 if ( !isset( $wgTexvc ) ) {
748 $this->markTestSkipped( "SKIPPED: \$wgTexvc is not set" );
749 } elseif ( !is_executable( $wgTexvc ) ) {
750 $this->markTestSkipped( "SKIPPED: texvc binary does not exist"
751 . " or is not executable.\n"
752 . "Current configuration is:\n\$wgTexvc = '$wgTexvc'" );
755 if ( isset( $opts['djvu'] ) ) {
756 if ( !$this->djVuSupport
->isEnabled() ) {
757 $this->markTestSkipped( "SKIPPED: djvu binaries do not exist or are not executable.\n" );
761 if ( isset( $opts['pst'] ) ) {
762 $out = $parser->preSaveTransform( $input, $title, $user, $options );
763 } elseif ( isset( $opts['msg'] ) ) {
764 $out = $parser->transformMsg( $input, $options, $title );
765 } elseif ( isset( $opts['section'] ) ) {
766 $section = $opts['section'];
767 $out = $parser->getSection( $input, $section );
768 } elseif ( isset( $opts['replace'] ) ) {
769 $section = $opts['replace'][0];
770 $replace = $opts['replace'][1];
771 $out = $parser->replaceSection( $input, $section, $replace );
772 } elseif ( isset( $opts['comment'] ) ) {
773 $out = Linker
::formatComment( $input, $title, $local );
774 } elseif ( isset( $opts['preload'] ) ) {
775 $out = $parser->getPreloadText( $input, $title, $options );
777 $output = $parser->parse( $input, $title, $options, true, true, 1337 );
778 $output->setTOCEnabled( !isset( $opts['notoc'] ) );
779 $out = $output->getText();
781 if ( isset( $opts['showtitle'] ) ) {
782 if ( $output->getTitleText() ) {
783 $title = $output->getTitleText();
786 $out = "$title\n$out";
789 if ( isset( $opts['ill'] ) ) {
790 $out = $this->tidy( implode( ' ', $output->getLanguageLinks() ) );
791 } elseif ( isset( $opts['cat'] ) ) {
792 $outputPage = $context->getOutput();
793 $outputPage->addCategoryLinks( $output->getCategories() );
794 $cats = $outputPage->getCategoryLinks();
796 if ( isset( $cats['normal'] ) ) {
797 $out = $this->tidy( implode( ' ', $cats['normal'] ) );
802 $parser->mPreprocessor
= null;
804 $result = $this->tidy( $result );
807 $this->teardownGlobals();
809 $this->assertEquals( $result, $out, $desc );
813 * Run a fuzz test series
814 * Draw input from a set of test files
816 * @todo fixme Needs some work to not eat memory until the world explodes
820 public function testFuzzTests() {
821 global $wgParserTestFiles;
823 $files = $wgParserTestFiles;
825 if ( $this->getCliArg( 'file=' ) ) {
826 $files = array( $this->getCliArg( 'file=' ) );
829 $dict = $this->getFuzzInput( $files );
830 $dictSize = strlen( $dict );
831 $logMaxLength = log( $this->maxFuzzTestLength
);
833 ini_set( 'memory_limit', $this->memoryLimit
* 1048576 );
836 $opts = ParserOptions
::newFromUser( $user );
837 $title = Title
::makeTitle( NS_MAIN
, 'Parser_test' );
843 // Generate test input
844 mt_srand( ++
$this->fuzzSeed
);
845 $totalLength = mt_rand( 1, $this->maxFuzzTestLength
);
848 while ( strlen( $input ) < $totalLength ) {
849 $logHairLength = mt_rand( 0, 1000000 ) / 1000000 * $logMaxLength;
850 $hairLength = min( intval( exp( $logHairLength ) ), $dictSize );
851 $offset = mt_rand( 0, $dictSize - $hairLength );
852 $input .= substr( $dict, $offset, $hairLength );
855 $this->setupGlobals();
856 $parser = $this->getParser();
860 $parser->parse( $input, $title, $opts );
861 $this->assertTrue( true, "Test $id, fuzz seed {$this->fuzzSeed}" );
862 } catch ( Exception
$exception ) {
863 $input_dump = sprintf( "string(%d) \"%s\"\n", strlen( $input ), $input );
865 $this->assertTrue( false, "Test $id, fuzz seed {$this->fuzzSeed}. \n\n" .
866 "Input: $input_dump\n\nError: {$exception->getMessage()}\n\n" .
867 "Backtrace: {$exception->getTraceAsString()}" );
870 $this->teardownGlobals();
871 $parser->__destruct();
873 if ( $id %
100 == 0 ) {
874 $usage = intval( memory_get_usage( true ) / $this->memoryLimit
/ 1048576 * 100 );
875 //echo "{$this->fuzzSeed}: $numSuccess/$numTotal (mem: $usage%)\n";
877 $ret = "Out of memory:\n";
878 $memStats = $this->getMemoryBreakdown();
880 foreach ( $memStats as $name => $usage ) {
881 $ret .= "$name: $usage\n";
884 throw new MWException( $ret );
892 //Various getter functions
895 * Get an input dictionary from a set of parser test files
896 * @param array $filenames
898 function getFuzzInput( $filenames ) {
901 foreach ( $filenames as $filename ) {
902 $contents = file_get_contents( $filename );
903 preg_match_all( '/!!\s*input\n(.*?)\n!!\s*result/s', $contents, $matches );
905 foreach ( $matches[1] as $match ) {
906 $dict .= $match . "\n";
914 * Get a memory usage breakdown
916 function getMemoryBreakdown() {
919 foreach ( $GLOBALS as $name => $value ) {
920 $memStats['$' . $name] = strlen( serialize( $value ) );
923 $classes = get_declared_classes();
925 foreach ( $classes as $class ) {
926 $rc = new ReflectionClass( $class );
927 $props = $rc->getStaticProperties();
928 $memStats[$class] = strlen( serialize( $props ) );
929 $methods = $rc->getMethods();
931 foreach ( $methods as $method ) {
932 $memStats[$class] +
= strlen( serialize( $method->getStaticVariables() ) );
936 $functions = get_defined_functions();
938 foreach ( $functions['user'] as $function ) {
939 $rf = new ReflectionFunction( $function );
940 $memStats["$function()"] = strlen( serialize( $rf->getStaticVariables() ) );
949 * Get a Parser object
950 * @param Preprocessor $preprocessor
952 function getParser( $preprocessor = null ) {
953 global $wgParserConf;
955 $class = $wgParserConf['class'];
956 $parser = new $class( array( 'preprocessorClass' => $preprocessor ) +
$wgParserConf );
958 wfRunHooks( 'ParserTestParser', array( &$parser ) );
963 //Various action functions
965 public function addArticle( $name, $text, $line ) {
966 self
::$articles[$name] = array( $text, $line );
969 public function publishTestArticles() {
970 if ( empty( self
::$articles ) ) {
974 foreach ( self
::$articles as $name => $info ) {
975 list( $text, $line ) = $info;
976 ParserTest
::addArticle( $name, $text, $line, 'ignoreduplicate' );
981 * Steal a callback function from the primary parser, save it for
982 * application to our scary parser. If the hook is not installed,
983 * abort processing of this file.
985 * @param string $name
986 * @return bool True if tag hook is present
988 public function requireHook( $name ) {
990 $wgParser->firstCallInit(); // make sure hooks are loaded.
991 return isset( $wgParser->mTagHooks
[$name] );
994 public function requireFunctionHook( $name ) {
996 $wgParser->firstCallInit(); // make sure hooks are loaded.
997 return isset( $wgParser->mFunctionHooks
[$name] );
1000 //Various "cleanup" functions
1003 * Run the "tidy" command on text if the $wgUseTidy
1006 * @param string $text The text to tidy
1009 protected function tidy( $text ) {
1013 $text = MWTidy
::tidy( $text );
1020 * Remove last character if it is a newline
1023 public function removeEndingNewline( $s ) {
1024 if ( substr( $s, -1 ) === "\n" ) {
1025 return substr( $s, 0, -1 );
1031 //Test options parser functions
1033 protected function parseOptions( $instring ) {
1039 // foo=bar,"baz quux"
1061 "[^"]*" # Quoted val
1063 \[\[[^]]*\]\] # Link target
1071 if ( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER
) ) {
1072 foreach ( $matches as $bits ) {
1073 array_shift( $bits );
1074 $key = strtolower( array_shift( $bits ) );
1075 if ( count( $bits ) == 0 ) {
1077 } elseif ( count( $bits ) == 1 ) {
1078 $opts[$key] = $this->cleanupOption( array_shift( $bits ) );
1081 $opts[$key] = array_map( array( $this, 'cleanupOption' ), $bits );
1089 protected function cleanupOption( $opt ) {
1090 if ( substr( $opt, 0, 1 ) == '"' ) {
1091 return substr( $opt, 1, -1 );
1094 if ( substr( $opt, 0, 2 ) == '[[' ) {
1095 return substr( $opt, 2, -2 );
1102 * Use a regex to find out the value of an option
1103 * @param string $key Name of option val to retrieve
1104 * @param array $opts Options array to look in
1105 * @param mixed $default Default value returned if not found
1107 protected static function getOptionValue( $key, $opts, $default ) {
1108 $key = strtolower( $key );
1110 if ( isset( $opts[$key] ) ) {