3 * Although marked as a stub, can work independently.
11 class NewParserTest
extends MediaWikiTestCase
{
12 static protected $articles = []; // Array of test articles defined by the tests
13 /* The data provider is run on a different instance than the test, so it must be static
14 * When running tests from several files, all tests will see all articles.
16 static protected $backendToUse;
18 public $keepUploads = false;
19 public $runDisabled = false;
20 public $runParsoid = false;
22 public $showProgress = true;
23 public $savedWeirdGlobals = [];
24 public $savedGlobals = [];
26 public $functionHooks = [];
27 public $transparentHooks = [];
30 public $maxFuzzTestLength = 300;
32 public $memoryLimit = 50;
43 protected $file = false;
45 public static function setUpBeforeClass() {
46 // Inject ParserTest well-known interwikis
47 ParserTest
::setupInterwikis();
50 protected function setUp() {
51 global $wgNamespaceAliases, $wgContLang;
56 // Setup CLI arguments
57 if ( $this->getCliArg( 'regex' ) ) {
58 $this->regex
= $this->getCliArg( 'regex' );
64 $this->keepUploads
= $this->getCliArg( 'keep-uploads' );
68 $tmpGlobals['wgLanguageCode'] = 'en';
69 $tmpGlobals['wgContLang'] = Language
::factory( 'en' );
70 $tmpGlobals['wgSitename'] = 'MediaWiki';
71 $tmpGlobals['wgServer'] = 'http://example.org';
72 $tmpGlobals['wgServerName'] = 'example.org';
73 $tmpGlobals['wgScriptPath'] = '';
74 $tmpGlobals['wgScript'] = '/index.php';
75 $tmpGlobals['wgResourceBasePath'] = '';
76 $tmpGlobals['wgStylePath'] = '/skins';
77 $tmpGlobals['wgExtensionAssetsPath'] = '/extensions';
78 $tmpGlobals['wgArticlePath'] = '/wiki/$1';
79 $tmpGlobals['wgActionPaths'] = [];
80 $tmpGlobals['wgVariantArticlePath'] = false;
81 $tmpGlobals['wgEnableUploads'] = true;
82 $tmpGlobals['wgUploadNavigationUrl'] = false;
83 $tmpGlobals['wgThumbnailScriptPath'] = false;
84 $tmpGlobals['wgLocalFileRepo'] = [
85 'class' => 'LocalRepo',
87 'url' => 'http://example.com/images',
89 'transformVia404' => false,
90 'backend' => 'local-backend'
92 $tmpGlobals['wgForeignFileRepos'] = [];
93 $tmpGlobals['wgDefaultExternalStore'] = [];
94 $tmpGlobals['wgParserCacheType'] = CACHE_NONE
;
95 $tmpGlobals['wgCapitalLinks'] = true;
96 $tmpGlobals['wgNoFollowLinks'] = true;
97 $tmpGlobals['wgNoFollowDomainExceptions'] = [ 'no-nofollow.org' ];
98 $tmpGlobals['wgExternalLinkTarget'] = false;
99 $tmpGlobals['wgThumbnailScriptPath'] = false;
100 $tmpGlobals['wgUseImageResize'] = true;
101 $tmpGlobals['wgAllowExternalImages'] = true;
102 $tmpGlobals['wgRawHtml'] = false;
103 $tmpGlobals['wgExperimentalHtmlIds'] = false;
104 $tmpGlobals['wgAdaptiveMessageCache'] = true;
105 $tmpGlobals['wgUseDatabaseMessages'] = true;
106 $tmpGlobals['wgLocaltimezone'] = 'UTC';
107 $tmpGlobals['wgGroupPermissions'] = [
109 'createaccount' => true,
112 'createpage' => true,
113 'createtalk' => true,
115 $tmpGlobals['wgNamespaceProtection'] = [ NS_MEDIAWIKI
=> 'editinterface' ];
117 $tmpGlobals['wgParser'] = new StubObject(
118 'wgParser', $GLOBALS['wgParserConf']['class'],
119 [ $GLOBALS['wgParserConf'] ] );
121 $tmpGlobals['wgFileExtensions'][] = 'svg';
122 $tmpGlobals['wgSVGConverter'] = 'rsvg';
123 $tmpGlobals['wgSVGConverters']['rsvg'] =
124 '$path/rsvg-convert -w $width -h $height -o $output $input';
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 // Ogg video/audio increasingly more differently
144 $tmpGlobals['wgMediaHandlers']['application/ogg'] = 'MockOggHandler';
146 $tmpHooks = $wgHooks;
147 $tmpHooks['ParserTestParser'][] = 'ParserTestParserHook::setup';
148 $tmpHooks['ParserGetVariableValueTs'][] = 'ParserTest::getFakeTimestamp';
149 $tmpGlobals['wgHooks'] = $tmpHooks;
150 # add a namespace shadowing a interwiki link, to test
151 # proper precedence when resolving links. (bug 51680)
152 $tmpGlobals['wgExtraNamespaces'] = [
153 100 => 'MemoryAlpha',
154 101 => 'MemoryAlpha_talk'
157 $tmpGlobals['wgLocalInterwikis'] = [ 'local', 'mi' ];
158 # "extra language links"
159 # see https://gerrit.wikimedia.org/r/111390
160 $tmpGlobals['wgExtraInterlanguageLinkPrefixes'] = [ 'mul' ];
163 $this->djVuSupport
= new DjVuSupport();
165 $this->tidySupport
= new TidySupport();
166 $tmpGlobals['wgTidyConfig'] = $this->tidySupport
->getConfig();
167 $tmpGlobals['wgUseTidy'] = false;
169 $this->setMwGlobals( $tmpGlobals );
171 $this->savedWeirdGlobals
['image_alias'] = $wgNamespaceAliases['Image'];
172 $this->savedWeirdGlobals
['image_talk_alias'] = $wgNamespaceAliases['Image_talk'];
174 $wgNamespaceAliases['Image'] = NS_FILE
;
175 $wgNamespaceAliases['Image_talk'] = NS_FILE_TALK
;
177 MWNamespace
::getCanonicalNamespaces( true ); # reset namespace cache
178 $wgContLang->resetNamespaces(); # reset namespace cache
179 ParserTest
::resetTitleServices();
182 protected function tearDown() {
183 global $wgNamespaceAliases, $wgContLang;
185 $wgNamespaceAliases['Image'] = $this->savedWeirdGlobals
['image_alias'];
186 $wgNamespaceAliases['Image_talk'] = $this->savedWeirdGlobals
['image_talk_alias'];
188 MWTidy
::destroySingleton();
191 RepoGroup
::destroySingleton();
192 FileBackendGroup
::destroySingleton();
194 // Remove temporary pages from the link cache
195 LinkCache
::singleton()->clear();
197 // Restore message cache (temporary pages and $wgUseDatabaseMessages)
198 MessageCache
::destroyInstance();
202 MWNamespace
::getCanonicalNamespaces( true ); # reset namespace cache
203 $wgContLang->resetNamespaces(); # reset namespace cache
206 public static function tearDownAfterClass() {
207 ParserTest
::tearDownInterwikis();
208 parent
::tearDownAfterClass();
211 function addDBDataOnce() {
212 # disabled for performance
213 # $this->tablesUsed[] = 'image';
215 # Update certain things in site_stats
216 $this->db
->insert( 'site_stats',
217 [ 'ss_row_id' => 1, 'ss_images' => 2, 'ss_good_articles' => 1 ],
222 $user = User
::newFromId( 0 );
223 LinkCache
::singleton()->clear(); # Avoids the odd failure at creating the nullRevision
225 # Upload DB table entries for files.
226 # We will upload the actual files later. Note that if anything causes LocalFile::load()
227 # to be triggered before then, it will break via maybeUpgrade() setting the fileExists
228 # member to false and storing it in cache.
229 # note that the size/width/height/bits/etc of the file
230 # are actually set by inspecting the file itself; the arguments
231 # to recordUpload2 have no effect. That said, we try to make things
232 # match up so it is less confusing to readers of the code & tests.
233 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Foobar.jpg' ) );
234 if ( !$this->db
->selectField( 'image', '1', [ 'img_name' => $image->getName() ] ) ) {
235 $image->recordUpload2(
237 'Upload of some lame file',
244 'media_type' => MEDIATYPE_BITMAP
,
245 'mime' => 'image/jpeg',
246 'metadata' => serialize( [] ),
247 'sha1' => Wikimedia\base_convert
( '1', 16, 36, 31 ),
248 'fileExists' => true ],
249 $this->db
->timestamp( '20010115123500' ), $user
253 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Thumb.png' ) );
254 if ( !$this->db
->selectField( 'image', '1', [ 'img_name' => $image->getName() ] ) ) {
255 $image->recordUpload2(
257 'Upload of some lame thumbnail',
258 'Some lame thumbnail',
264 'media_type' => MEDIATYPE_BITMAP
,
265 'mime' => 'image/png',
266 'metadata' => serialize( [] ),
267 'sha1' => Wikimedia\base_convert
( '2', 16, 36, 31 ),
268 'fileExists' => true ],
269 $this->db
->timestamp( '20130225203040' ), $user
273 # This image will be blacklisted in [[MediaWiki:Bad image list]]
274 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Bad.jpg' ) );
275 if ( !$this->db
->selectField( 'image', '1', [ 'img_name' => $image->getName() ] ) ) {
276 $image->recordUpload2(
285 'media_type' => MEDIATYPE_BITMAP
,
286 'mime' => 'image/jpeg',
287 'metadata' => serialize( [] ),
288 'sha1' => Wikimedia\base_convert
( '3', 16, 36, 31 ),
289 'fileExists' => true ],
290 $this->db
->timestamp( '20010115123500' ), $user
293 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Foobar.svg' ) );
294 if ( !$this->db
->selectField( 'image', '1', [ 'img_name' => $image->getName() ] ) ) {
295 $image->recordUpload2( '', 'Upload of some lame SVG', 'Some lame SVG', [
300 'media_type' => MEDIATYPE_DRAWING
,
301 'mime' => 'image/svg+xml',
302 'metadata' => serialize( [] ),
303 'sha1' => Wikimedia\base_convert
( '', 16, 36, 31 ),
305 ], $this->db
->timestamp( '20010115123500' ), $user );
308 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Video.ogv' ) );
309 if ( !$this->db
->selectField( 'image', '1', [ 'img_name' => $image->getName() ] ) ) {
310 $image->recordUpload2( '', 'A pretty movie', 'Will it play', [
315 'media_type' => MEDIATYPE_VIDEO
,
316 'mime' => 'application/ogg',
317 'metadata' => serialize( [] ),
318 'sha1' => Wikimedia\base_convert
( '', 16, 36, 32 ),
320 ], $this->db
->timestamp( '20010115123500' ), $user );
323 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Audio.oga' ) );
324 if ( !$this->db
->selectField( 'image', '1', [ 'img_name' => $image->getName() ] ) ) {
325 $image->recordUpload2( '', 'An awesome hitsong ', 'Will it play', [
330 'media_type' => MEDIATYPE_AUDIO
,
331 'mime' => 'application/ogg',
332 'metadata' => serialize( [] ),
333 'sha1' => Wikimedia\base_convert
( '', 16, 36, 32 ),
335 ], $this->db
->timestamp( '20010115123500' ), $user );
339 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'LoremIpsum.djvu' ) );
340 if ( !$this->db
->selectField( 'image', '1', [ 'img_name' => $image->getName() ] ) ) {
341 $image->recordUpload2( '', 'Upload a DjVu', 'A DjVu', [
346 'media_type' => MEDIATYPE_BITMAP
,
347 'mime' => 'image/vnd.djvu',
348 'metadata' => '<?xml version="1.0" ?>
349 <!DOCTYPE DjVuXML PUBLIC "-//W3C//DTD DjVuXML 1.1//EN" "pubtext/DjVuXML-s.dtd">
352 <BODY><OBJECT height="3508" width="2480">
353 <PARAM name="DPI" value="300" />
354 <PARAM name="GAMMA" value="2.2" />
356 <OBJECT height="3508" width="2480">
357 <PARAM name="DPI" value="300" />
358 <PARAM name="GAMMA" value="2.2" />
360 <OBJECT height="3508" width="2480">
361 <PARAM name="DPI" value="300" />
362 <PARAM name="GAMMA" value="2.2" />
364 <OBJECT height="3508" width="2480">
365 <PARAM name="DPI" value="300" />
366 <PARAM name="GAMMA" value="2.2" />
368 <OBJECT height="3508" width="2480">
369 <PARAM name="DPI" value="300" />
370 <PARAM name="GAMMA" value="2.2" />
374 'sha1' => Wikimedia\base_convert
( '', 16, 36, 31 ),
376 ], $this->db
->timestamp( '20140115123600' ), $user );
380 // ParserTest setup/teardown functions
383 * Set up the global variables for a consistent environment for each test.
384 * Ideally this should replace the global configuration entirely.
386 * @param string $config
387 * @return RequestContext
389 protected function setupGlobals( $opts = [], $config = '' ) {
390 global $wgFileBackends;
391 # Find out values for some special options.
393 self
::getOptionValue( 'language', $opts, 'en' );
395 self
::getOptionValue( 'variant', $opts, false );
397 self
::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
398 $linkHolderBatchSize =
399 self
::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
401 $uploadDir = $this->getUploadDir();
402 if ( $this->getCliArg( 'use-filebackend' ) ) {
403 if ( self
::$backendToUse ) {
404 $backend = self
::$backendToUse;
406 $name = $this->getCliArg( 'use-filebackend' );
408 foreach ( $wgFileBackends as $conf ) {
409 if ( $conf['name'] == $name ) {
413 $useConfig['name'] = 'local-backend'; // swap name
414 unset( $useConfig['lockManager'] );
415 unset( $useConfig['fileJournal'] );
416 $class = $useConfig['class'];
417 self
::$backendToUse = new $class( $useConfig );
418 $backend = self
::$backendToUse;
421 # Replace with a mock. We do not care about generating real
422 # files on the filesystem, just need to expose the file
424 $backend = new MockFileBackend( [
425 'name' => 'local-backend',
426 'wikiId' => wfWikiID()
431 'wgLocalFileRepo' => [
432 'class' => 'LocalRepo',
434 'url' => 'http://example.com/images',
436 'transformVia404' => false,
437 'backend' => $backend
439 'wgEnableUploads' => self
::getOptionValue( 'wgEnableUploads', $opts, true ),
440 'wgLanguageCode' => $lang,
441 'wgDBprefix' => $this->db
->getType() != 'oracle' ?
'unittest_' : 'ut_',
442 'wgRawHtml' => self
::getOptionValue( 'wgRawHtml', $opts, false ),
443 'wgNamespacesWithSubpages' => [ NS_MAIN
=> isset( $opts['subpage'] ) ],
444 'wgAllowExternalImages' => self
::getOptionValue( 'wgAllowExternalImages', $opts, true ),
445 'wgThumbLimits' => [ self
::getOptionValue( 'thumbsize', $opts, 180 ) ],
446 'wgMaxTocLevel' => $maxtoclevel,
447 'wgUseTeX' => isset( $opts['math'] ) ||
isset( $opts['texvc'] ),
448 'wgMathDirectory' => $uploadDir . '/math',
449 'wgDefaultLanguageVariant' => $variant,
450 'wgLinkHolderBatchSize' => $linkHolderBatchSize,
451 'wgUseTidy' => false,
452 'wgTidyConfig' => isset( $opts['tidy'] ) ?
$this->tidySupport
->getConfig() : null
456 $configLines = explode( "\n", $config );
458 foreach ( $configLines as $line ) {
459 list( $var, $value ) = explode( '=', $line, 2 );
461 $settings[$var] = eval( "return $value;" ); // ???
465 $this->savedGlobals
= [];
468 Hooks
::run( 'ParserTestGlobals', [ &$settings ] );
470 $langObj = Language
::factory( $lang );
471 $settings['wgContLang'] = $langObj;
472 $settings['wgLang'] = $langObj;
474 $context = new RequestContext();
475 $settings['wgOut'] = $context->getOutput();
476 $settings['wgUser'] = $context->getUser();
477 $settings['wgRequest'] = $context->getRequest();
479 // We (re)set $wgThumbLimits to a single-element array above.
480 $context->getUser()->setOption( 'thumbsize', 0 );
482 foreach ( $settings as $var => $val ) {
483 if ( array_key_exists( $var, $GLOBALS ) ) {
484 $this->savedGlobals
[$var] = $GLOBALS[$var];
487 $GLOBALS[$var] = $val;
490 MWTidy
::destroySingleton();
491 MagicWord
::clearCache();
493 # The entries saved into RepoGroup cache with previous globals will be wrong.
494 RepoGroup
::destroySingleton();
495 FileBackendGroup
::destroySingleton();
497 # Create dummy files in storage
498 $this->setupUploads();
500 # Publish the articles after we have the final language set
501 $this->publishTestArticles();
503 MessageCache
::destroyInstance();
509 * Get an FS upload directory (only applies to FSFileBackend)
511 * @return string The directory
513 protected function getUploadDir() {
514 if ( $this->keepUploads
) {
515 // Don't use getNewTempDirectory() as this is meant to persist
516 $dir = wfTempDir() . '/mwParser-images';
518 if ( is_dir( $dir ) ) {
522 $dir = $this->getNewTempDirectory();
525 if ( file_exists( $dir ) ) {
526 wfDebug( "Already exists!\n" );
535 * Create a dummy uploads directory which will contain a couple
536 * of files in order to pass existence tests.
538 * @return string The directory
540 protected function setupUploads() {
543 $base = $this->getBaseDir();
544 $backend = RepoGroup
::singleton()->getLocalRepo()->getBackend();
545 $backend->prepare( [ 'dir' => "$base/local-public/3/3a" ] );
547 'src' => "$IP/tests/phpunit/data/parser/headbg.jpg",
548 'dst' => "$base/local-public/3/3a/Foobar.jpg"
550 $backend->prepare( [ 'dir' => "$base/local-public/e/ea" ] );
552 'src' => "$IP/tests/phpunit/data/parser/wiki.png",
553 'dst' => "$base/local-public/e/ea/Thumb.png"
555 $backend->prepare( [ 'dir' => "$base/local-public/0/09" ] );
557 'src' => "$IP/tests/phpunit/data/parser/headbg.jpg",
558 'dst' => "$base/local-public/0/09/Bad.jpg"
560 $backend->prepare( [ 'dir' => "$base/local-public/5/5f" ] );
562 'src' => "$IP/tests/phpunit/data/parser/LoremIpsum.djvu",
563 'dst' => "$base/local-public/5/5f/LoremIpsum.djvu"
566 // No helpful SVG file to copy, so make one ourselves
567 $data = '<?xml version="1.0" encoding="utf-8"?>' .
568 '<svg xmlns="http://www.w3.org/2000/svg"' .
569 ' version="1.1" width="240" height="180"/>';
571 $backend->prepare( [ 'dir' => "$base/local-public/f/ff" ] );
572 $backend->quickCreate( [
573 'content' => $data, 'dst' => "$base/local-public/f/ff/Foobar.svg"
578 * Restore default values and perform any necessary clean-up
579 * after each test runs.
581 protected function teardownGlobals() {
582 $this->teardownUploads();
584 foreach ( $this->savedGlobals
as $var => $val ) {
585 $GLOBALS[$var] = $val;
590 * Remove the dummy uploads directory
592 private function teardownUploads() {
593 if ( $this->keepUploads
) {
597 $backend = RepoGroup
::singleton()->getLocalRepo()->getBackend();
598 if ( $backend instanceof MockFileBackend
) {
599 # In memory backend, so dont bother cleaning them up.
603 $base = $this->getBaseDir();
604 // delete the files first, then the dirs.
607 "$base/local-public/3/3a/Foobar.jpg",
608 "$base/local-thumb/3/3a/Foobar.jpg/1000px-Foobar.jpg",
609 "$base/local-thumb/3/3a/Foobar.jpg/100px-Foobar.jpg",
610 "$base/local-thumb/3/3a/Foobar.jpg/120px-Foobar.jpg",
611 "$base/local-thumb/3/3a/Foobar.jpg/1280px-Foobar.jpg",
612 "$base/local-thumb/3/3a/Foobar.jpg/137px-Foobar.jpg",
613 "$base/local-thumb/3/3a/Foobar.jpg/1500px-Foobar.jpg",
614 "$base/local-thumb/3/3a/Foobar.jpg/177px-Foobar.jpg",
615 "$base/local-thumb/3/3a/Foobar.jpg/180px-Foobar.jpg",
616 "$base/local-thumb/3/3a/Foobar.jpg/200px-Foobar.jpg",
617 "$base/local-thumb/3/3a/Foobar.jpg/206px-Foobar.jpg",
618 "$base/local-thumb/3/3a/Foobar.jpg/20px-Foobar.jpg",
619 "$base/local-thumb/3/3a/Foobar.jpg/220px-Foobar.jpg",
620 "$base/local-thumb/3/3a/Foobar.jpg/265px-Foobar.jpg",
621 "$base/local-thumb/3/3a/Foobar.jpg/270px-Foobar.jpg",
622 "$base/local-thumb/3/3a/Foobar.jpg/274px-Foobar.jpg",
623 "$base/local-thumb/3/3a/Foobar.jpg/300px-Foobar.jpg",
624 "$base/local-thumb/3/3a/Foobar.jpg/30px-Foobar.jpg",
625 "$base/local-thumb/3/3a/Foobar.jpg/330px-Foobar.jpg",
626 "$base/local-thumb/3/3a/Foobar.jpg/353px-Foobar.jpg",
627 "$base/local-thumb/3/3a/Foobar.jpg/360px-Foobar.jpg",
628 "$base/local-thumb/3/3a/Foobar.jpg/400px-Foobar.jpg",
629 "$base/local-thumb/3/3a/Foobar.jpg/40px-Foobar.jpg",
630 "$base/local-thumb/3/3a/Foobar.jpg/440px-Foobar.jpg",
631 "$base/local-thumb/3/3a/Foobar.jpg/442px-Foobar.jpg",
632 "$base/local-thumb/3/3a/Foobar.jpg/450px-Foobar.jpg",
633 "$base/local-thumb/3/3a/Foobar.jpg/50px-Foobar.jpg",
634 "$base/local-thumb/3/3a/Foobar.jpg/600px-Foobar.jpg",
635 "$base/local-thumb/3/3a/Foobar.jpg/640px-Foobar.jpg",
636 "$base/local-thumb/3/3a/Foobar.jpg/70px-Foobar.jpg",
637 "$base/local-thumb/3/3a/Foobar.jpg/75px-Foobar.jpg",
638 "$base/local-thumb/3/3a/Foobar.jpg/960px-Foobar.jpg",
640 "$base/local-public/e/ea/Thumb.png",
642 "$base/local-public/0/09/Bad.jpg",
644 "$base/local-public/5/5f/LoremIpsum.djvu",
645 "$base/local-thumb/5/5f/LoremIpsum.djvu/page2-2480px-LoremIpsum.djvu.jpg",
646 "$base/local-thumb/5/5f/LoremIpsum.djvu/page2-3720px-LoremIpsum.djvu.jpg",
647 "$base/local-thumb/5/5f/LoremIpsum.djvu/page2-4960px-LoremIpsum.djvu.jpg",
649 "$base/local-public/f/ff/Foobar.svg",
650 "$base/local-thumb/f/ff/Foobar.svg/180px-Foobar.svg.png",
651 "$base/local-thumb/f/ff/Foobar.svg/2000px-Foobar.svg.png",
652 "$base/local-thumb/f/ff/Foobar.svg/270px-Foobar.svg.png",
653 "$base/local-thumb/f/ff/Foobar.svg/3000px-Foobar.svg.png",
654 "$base/local-thumb/f/ff/Foobar.svg/360px-Foobar.svg.png",
655 "$base/local-thumb/f/ff/Foobar.svg/4000px-Foobar.svg.png",
656 "$base/local-thumb/f/ff/Foobar.svg/langde-180px-Foobar.svg.png",
657 "$base/local-thumb/f/ff/Foobar.svg/langde-270px-Foobar.svg.png",
658 "$base/local-thumb/f/ff/Foobar.svg/langde-360px-Foobar.svg.png",
660 "$base/local-public/math/f/a/5/fa50b8b616463173474302ca3e63586b.png",
666 * Delete the specified files, if they exist.
667 * @param array $files Full paths to files to delete.
669 private static function deleteFiles( $files ) {
670 $backend = RepoGroup
::singleton()->getLocalRepo()->getBackend();
671 foreach ( $files as $file ) {
672 $backend->delete( [ 'src' => $file ], [ 'force' => 1 ] );
674 foreach ( $files as $file ) {
675 $tmp = FileBackend
::parentStoragePath( $file );
677 if ( !$backend->clean( [ 'dir' => $tmp ] )->isOK() ) {
680 $tmp = FileBackend
::parentStoragePath( $tmp );
685 protected function getBaseDir() {
686 return 'mwstore://local-backend';
689 public function parserTestProvider() {
690 if ( $this->file
=== false ) {
691 global $wgParserTestFiles;
692 $this->file
= $wgParserTestFiles[0];
695 return new TestFileDataProvider( $this->file
, $this );
699 * Set the file from whose tests will be run by this instance
700 * @param string $filename
702 public function setParserTestFile( $filename ) {
703 $this->file
= $filename;
709 * @dataProvider parserTestProvider
710 * @param string $desc
711 * @param string $input
712 * @param string $result
714 * @param array $config
716 public function testParserTest( $desc, $input, $result, $opts, $config ) {
717 if ( $this->regex
!= '' && !preg_match( '/' . $this->regex
. '/', $desc ) ) {
718 $this->assertTrue( true ); // XXX: don't flood output with "test made no assertions"
719 // $this->markTestSkipped( 'Filtered out by the user' );
723 if ( !$this->isWikitextNS( NS_MAIN
) ) {
724 // parser tests frequently assume that the main namespace contains wikitext.
725 // @todo When setting up pages, force the content model. Only skip if
726 // $wgtContentModelUseDB is false.
727 $this->markTestSkipped( "Main namespace does not support wikitext,"
728 . "skipping parser test: $desc" );
731 wfDebug( "Running parser test: $desc\n" );
733 $opts = $this->parseOptions( $opts );
734 $context = $this->setupGlobals( $opts, $config );
736 $user = $context->getUser();
737 $options = ParserOptions
::newFromContext( $context );
739 if ( isset( $opts['title'] ) ) {
740 $titleText = $opts['title'];
742 $titleText = 'Parser test';
745 $local = isset( $opts['local'] );
746 $preprocessor = isset( $opts['preprocessor'] ) ?
$opts['preprocessor'] : null;
747 $parser = $this->getParser( $preprocessor );
749 $title = Title
::newFromText( $titleText );
751 # Parser test requiring math. Make sure texvc is executable
752 # or just skip such tests.
753 if ( isset( $opts['math'] ) ||
isset( $opts['texvc'] ) ) {
756 if ( !isset( $wgTexvc ) ) {
757 $this->markTestSkipped( "SKIPPED: \$wgTexvc is not set" );
758 } elseif ( !is_executable( $wgTexvc ) ) {
759 $this->markTestSkipped( "SKIPPED: texvc binary does not exist"
760 . " or is not executable.\n"
761 . "Current configuration is:\n\$wgTexvc = '$wgTexvc'" );
765 if ( isset( $opts['djvu'] ) ) {
766 if ( !$this->djVuSupport
->isEnabled() ) {
767 $this->markTestSkipped( "SKIPPED: djvu binaries do not exist or are not executable.\n" );
771 if ( isset( $opts['tidy'] ) ) {
772 if ( !$this->tidySupport
->isEnabled() ) {
773 $this->markTestSkipped( "SKIPPED: tidy extension is not installed.\n" );
775 $options->setTidy( true );
779 if ( isset( $opts['pst'] ) ) {
780 $out = $parser->preSaveTransform( $input, $title, $user, $options );
781 } elseif ( isset( $opts['msg'] ) ) {
782 $out = $parser->transformMsg( $input, $options, $title );
783 } elseif ( isset( $opts['section'] ) ) {
784 $section = $opts['section'];
785 $out = $parser->getSection( $input, $section );
786 } elseif ( isset( $opts['replace'] ) ) {
787 $section = $opts['replace'][0];
788 $replace = $opts['replace'][1];
789 $out = $parser->replaceSection( $input, $section, $replace );
790 } elseif ( isset( $opts['comment'] ) ) {
791 $out = Linker
::formatComment( $input, $title, $local );
792 } elseif ( isset( $opts['preload'] ) ) {
793 $out = $parser->getPreloadText( $input, $title, $options );
795 $output = $parser->parse( $input, $title, $options, true, true, 1337 );
796 $output->setTOCEnabled( !isset( $opts['notoc'] ) );
797 $out = $output->getText();
798 if ( isset( $opts['tidy'] ) ) {
799 $out = preg_replace( '/\s+$/', '', $out );
802 if ( isset( $opts['showtitle'] ) ) {
803 if ( $output->getTitleText() ) {
804 $title = $output->getTitleText();
807 $out = "$title\n$out";
810 if ( isset( $opts['showindicators'] ) ) {
812 foreach ( $output->getIndicators() as $id => $content ) {
813 $indicators .= "$id=$content\n";
815 $out = $indicators . $out;
818 if ( isset( $opts['ill'] ) ) {
819 $out = implode( ' ', $output->getLanguageLinks() );
820 } elseif ( isset( $opts['cat'] ) ) {
821 $outputPage = $context->getOutput();
822 $outputPage->addCategoryLinks( $output->getCategories() );
823 $cats = $outputPage->getCategoryLinks();
825 if ( isset( $cats['normal'] ) ) {
826 $out = implode( ' ', $cats['normal'] );
831 $parser->mPreprocessor
= null;
834 $this->teardownGlobals();
836 $this->assertEquals( $result, $out, $desc );
840 * Run a fuzz test series
841 * Draw input from a set of test files
843 * @todo fixme Needs some work to not eat memory until the world explodes
847 public function testFuzzTests() {
848 global $wgParserTestFiles;
850 $files = $wgParserTestFiles;
852 if ( $this->getCliArg( 'file' ) ) {
853 $files = [ $this->getCliArg( 'file' ) ];
856 $dict = $this->getFuzzInput( $files );
857 $dictSize = strlen( $dict );
858 $logMaxLength = log( $this->maxFuzzTestLength
);
860 ini_set( 'memory_limit', $this->memoryLimit
* 1048576 );
863 $opts = ParserOptions
::newFromUser( $user );
864 $title = Title
::makeTitle( NS_MAIN
, 'Parser_test' );
870 // Generate test input
871 mt_srand( ++
$this->fuzzSeed
);
872 $totalLength = mt_rand( 1, $this->maxFuzzTestLength
);
875 while ( strlen( $input ) < $totalLength ) {
876 $logHairLength = mt_rand( 0, 1000000 ) / 1000000 * $logMaxLength;
877 $hairLength = min( intval( exp( $logHairLength ) ), $dictSize );
878 $offset = mt_rand( 0, $dictSize - $hairLength );
879 $input .= substr( $dict, $offset, $hairLength );
882 $this->setupGlobals();
883 $parser = $this->getParser();
887 $parser->parse( $input, $title, $opts );
888 $this->assertTrue( true, "Test $id, fuzz seed {$this->fuzzSeed}" );
889 } catch ( Exception
$exception ) {
890 $input_dump = sprintf( "string(%d) \"%s\"\n", strlen( $input ), $input );
892 $this->assertTrue( false, "Test $id, fuzz seed {$this->fuzzSeed}. \n\n" .
893 "Input: $input_dump\n\nError: {$exception->getMessage()}\n\n" .
894 "Backtrace: {$exception->getTraceAsString()}" );
897 $this->teardownGlobals();
898 $parser->__destruct();
900 if ( $id %
100 == 0 ) {
901 $usage = intval( memory_get_usage( true ) / $this->memoryLimit
/ 1048576 * 100 );
902 // echo "{$this->fuzzSeed}: $numSuccess/$numTotal (mem: $usage%)\n";
904 $ret = "Out of memory:\n";
905 $memStats = $this->getMemoryBreakdown();
907 foreach ( $memStats as $name => $usage ) {
908 $ret .= "$name: $usage\n";
911 throw new MWException( $ret );
919 // Various getter functions
922 * Get an input dictionary from a set of parser test files
923 * @param array $filenames
926 function getFuzzInput( $filenames ) {
929 foreach ( $filenames as $filename ) {
930 $contents = file_get_contents( $filename );
931 preg_match_all( '/!!\s*input\n(.*?)\n!!\s*result/s', $contents, $matches );
933 foreach ( $matches[1] as $match ) {
934 $dict .= $match . "\n";
942 * Get a memory usage breakdown
945 function getMemoryBreakdown() {
948 foreach ( $GLOBALS as $name => $value ) {
949 $memStats['$' . $name] = strlen( serialize( $value ) );
952 $classes = get_declared_classes();
954 foreach ( $classes as $class ) {
955 $rc = new ReflectionClass( $class );
956 $props = $rc->getStaticProperties();
957 $memStats[$class] = strlen( serialize( $props ) );
958 $methods = $rc->getMethods();
960 foreach ( $methods as $method ) {
961 $memStats[$class] +
= strlen( serialize( $method->getStaticVariables() ) );
965 $functions = get_defined_functions();
967 foreach ( $functions['user'] as $function ) {
968 $rf = new ReflectionFunction( $function );
969 $memStats["$function()"] = strlen( serialize( $rf->getStaticVariables() ) );
978 * Get a Parser object
979 * @param Preprocessor $preprocessor
982 function getParser( $preprocessor = null ) {
983 global $wgParserConf;
985 $class = $wgParserConf['class'];
986 $parser = new $class( [ 'preprocessorClass' => $preprocessor ] +
$wgParserConf );
988 Hooks
::run( 'ParserTestParser', [ &$parser ] );
993 // Various action functions
995 public function addArticle( $name, $text, $line ) {
996 self
::$articles[$name] = [ $text, $line ];
999 public function publishTestArticles() {
1000 if ( empty( self
::$articles ) ) {
1004 foreach ( self
::$articles as $name => $info ) {
1005 list( $text, $line ) = $info;
1006 ParserTest
::addArticle( $name, $text, $line, 'ignoreduplicate' );
1011 * Steal a callback function from the primary parser, save it for
1012 * application to our scary parser. If the hook is not installed,
1013 * abort processing of this file.
1015 * @param string $name
1016 * @return bool True if tag hook is present
1018 public function requireHook( $name ) {
1020 $wgParser->firstCallInit(); // make sure hooks are loaded.
1021 return isset( $wgParser->mTagHooks
[$name] );
1024 public function requireFunctionHook( $name ) {
1026 $wgParser->firstCallInit(); // make sure hooks are loaded.
1027 return isset( $wgParser->mFunctionHooks
[$name] );
1030 public function requireTransparentHook( $name ) {
1032 $wgParser->firstCallInit(); // make sure hooks are loaded.
1033 return isset( $wgParser->mTransparentTagHooks
[$name] );
1036 // Various "cleanup" functions
1039 * Remove last character if it is a newline
1043 public function removeEndingNewline( $s ) {
1044 if ( substr( $s, -1 ) === "\n" ) {
1045 return substr( $s, 0, -1 );
1051 // Test options parser functions
1053 protected function parseOptions( $instring ) {
1059 // foo=bar,"baz quux"
1081 "[^"]*" # Quoted val
1083 \[\[[^]]*\]\] # Link target
1091 if ( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER
) ) {
1092 foreach ( $matches as $bits ) {
1093 array_shift( $bits );
1094 $key = strtolower( array_shift( $bits ) );
1095 if ( count( $bits ) == 0 ) {
1097 } elseif ( count( $bits ) == 1 ) {
1098 $opts[$key] = $this->cleanupOption( array_shift( $bits ) );
1101 $opts[$key] = array_map( [ $this, 'cleanupOption' ], $bits );
1109 protected function cleanupOption( $opt ) {
1110 if ( substr( $opt, 0, 1 ) == '"' ) {
1111 return substr( $opt, 1, -1 );
1114 if ( substr( $opt, 0, 2 ) == '[[' ) {
1115 return substr( $opt, 2, -2 );
1122 * Use a regex to find out the value of an option
1123 * @param string $key Name of option val to retrieve
1124 * @param array $opts Options array to look in
1125 * @param mixed $default Default value returned if not found
1128 protected static function getOptionValue( $key, $opts, $default ) {
1129 $key = strtolower( $key );
1131 if ( isset( $opts[$key] ) ) {