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'] = [];
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'] = null;
167 $tmpGlobals['wgUseTidy'] = false;
168 $tmpGlobals['wgDebugTidy'] = false;
169 $tmpGlobals['wgTidyConf'] = $IP . '/includes/tidy/tidy.conf';
170 $tmpGlobals['wgTidyOpts'] = '';
171 $tmpGlobals['wgTidyInternal'] = $this->tidySupport
->isInternal();
173 $this->setMwGlobals( $tmpGlobals );
175 $this->savedWeirdGlobals
['image_alias'] = $wgNamespaceAliases['Image'];
176 $this->savedWeirdGlobals
['image_talk_alias'] = $wgNamespaceAliases['Image_talk'];
178 $wgNamespaceAliases['Image'] = NS_FILE
;
179 $wgNamespaceAliases['Image_talk'] = NS_FILE_TALK
;
181 MWNamespace
::getCanonicalNamespaces( true ); # reset namespace cache
182 $wgContLang->resetNamespaces(); # reset namespace cache
183 ParserTest
::resetTitleServices();
186 protected function tearDown() {
187 global $wgNamespaceAliases, $wgContLang;
189 $wgNamespaceAliases['Image'] = $this->savedWeirdGlobals
['image_alias'];
190 $wgNamespaceAliases['Image_talk'] = $this->savedWeirdGlobals
['image_talk_alias'];
192 MWTidy
::destroySingleton();
195 RepoGroup
::destroySingleton();
196 FileBackendGroup
::destroySingleton();
198 // Remove temporary pages from the link cache
199 LinkCache
::singleton()->clear();
201 // Restore message cache (temporary pages and $wgUseDatabaseMessages)
202 MessageCache
::destroyInstance();
206 MWNamespace
::getCanonicalNamespaces( true ); # reset namespace cache
207 $wgContLang->resetNamespaces(); # reset namespace cache
210 public static function tearDownAfterClass() {
211 ParserTest
::tearDownInterwikis();
212 parent
::tearDownAfterClass();
215 function addDBDataOnce() {
216 # disabled for performance
217 # $this->tablesUsed[] = 'image';
219 # Update certain things in site_stats
220 $this->db
->insert( 'site_stats',
221 [ 'ss_row_id' => 1, 'ss_images' => 2, 'ss_good_articles' => 1 ],
226 $user = User
::newFromId( 0 );
227 LinkCache
::singleton()->clear(); # Avoids the odd failure at creating the nullRevision
229 # Upload DB table entries for files.
230 # We will upload the actual files later. Note that if anything causes LocalFile::load()
231 # to be triggered before then, it will break via maybeUpgrade() setting the fileExists
232 # member to false and storing it in cache.
233 # note that the size/width/height/bits/etc of the file
234 # are actually set by inspecting the file itself; the arguments
235 # to recordUpload2 have no effect. That said, we try to make things
236 # match up so it is less confusing to readers of the code & tests.
237 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Foobar.jpg' ) );
238 if ( !$this->db
->selectField( 'image', '1', [ 'img_name' => $image->getName() ] ) ) {
239 $image->recordUpload2(
241 'Upload of some lame file',
248 'media_type' => MEDIATYPE_BITMAP
,
249 'mime' => 'image/jpeg',
250 'metadata' => serialize( [] ),
251 'sha1' => Wikimedia\base_convert
( '1', 16, 36, 31 ),
252 'fileExists' => true ],
253 $this->db
->timestamp( '20010115123500' ), $user
257 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Thumb.png' ) );
258 if ( !$this->db
->selectField( 'image', '1', [ 'img_name' => $image->getName() ] ) ) {
259 $image->recordUpload2(
261 'Upload of some lame thumbnail',
262 'Some lame thumbnail',
268 'media_type' => MEDIATYPE_BITMAP
,
269 'mime' => 'image/png',
270 'metadata' => serialize( [] ),
271 'sha1' => Wikimedia\base_convert
( '2', 16, 36, 31 ),
272 'fileExists' => true ],
273 $this->db
->timestamp( '20130225203040' ), $user
277 # This image will be blacklisted in [[MediaWiki:Bad image list]]
278 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Bad.jpg' ) );
279 if ( !$this->db
->selectField( 'image', '1', [ 'img_name' => $image->getName() ] ) ) {
280 $image->recordUpload2(
289 'media_type' => MEDIATYPE_BITMAP
,
290 'mime' => 'image/jpeg',
291 'metadata' => serialize( [] ),
292 'sha1' => Wikimedia\base_convert
( '3', 16, 36, 31 ),
293 'fileExists' => true ],
294 $this->db
->timestamp( '20010115123500' ), $user
297 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Foobar.svg' ) );
298 if ( !$this->db
->selectField( 'image', '1', [ 'img_name' => $image->getName() ] ) ) {
299 $image->recordUpload2( '', 'Upload of some lame SVG', 'Some lame SVG', [
304 'media_type' => MEDIATYPE_DRAWING
,
305 'mime' => 'image/svg+xml',
306 'metadata' => serialize( [] ),
307 'sha1' => Wikimedia\base_convert
( '', 16, 36, 31 ),
309 ], $this->db
->timestamp( '20010115123500' ), $user );
312 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Video.ogv' ) );
313 if ( !$this->db
->selectField( 'image', '1', [ 'img_name' => $image->getName() ] ) ) {
314 $image->recordUpload2( '', 'A pretty movie', 'Will it play', [
319 'media_type' => MEDIATYPE_VIDEO
,
320 'mime' => 'application/ogg',
321 'metadata' => serialize( [] ),
322 'sha1' => Wikimedia\base_convert
( '', 16, 36, 32 ),
324 ], $this->db
->timestamp( '20010115123500' ), $user );
329 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'LoremIpsum.djvu' ) );
330 if ( !$this->db
->selectField( 'image', '1', [ 'img_name' => $image->getName() ] ) ) {
331 $image->recordUpload2( '', 'Upload a DjVu', 'A DjVu', [
336 'media_type' => MEDIATYPE_BITMAP
,
337 'mime' => 'image/vnd.djvu',
338 'metadata' => '<?xml version="1.0" ?>
339 <!DOCTYPE DjVuXML PUBLIC "-//W3C//DTD DjVuXML 1.1//EN" "pubtext/DjVuXML-s.dtd">
342 <BODY><OBJECT height="3508" width="2480">
343 <PARAM name="DPI" value="300" />
344 <PARAM name="GAMMA" value="2.2" />
346 <OBJECT height="3508" width="2480">
347 <PARAM name="DPI" value="300" />
348 <PARAM name="GAMMA" value="2.2" />
350 <OBJECT height="3508" width="2480">
351 <PARAM name="DPI" value="300" />
352 <PARAM name="GAMMA" value="2.2" />
354 <OBJECT height="3508" width="2480">
355 <PARAM name="DPI" value="300" />
356 <PARAM name="GAMMA" value="2.2" />
358 <OBJECT height="3508" width="2480">
359 <PARAM name="DPI" value="300" />
360 <PARAM name="GAMMA" value="2.2" />
364 'sha1' => Wikimedia\base_convert
( '', 16, 36, 31 ),
366 ], $this->db
->timestamp( '20140115123600' ), $user );
370 // ParserTest setup/teardown functions
373 * Set up the global variables for a consistent environment for each test.
374 * Ideally this should replace the global configuration entirely.
376 * @param string $config
377 * @return RequestContext
379 protected function setupGlobals( $opts = [], $config = '' ) {
380 global $wgFileBackends;
381 # Find out values for some special options.
383 self
::getOptionValue( 'language', $opts, 'en' );
385 self
::getOptionValue( 'variant', $opts, false );
387 self
::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
388 $linkHolderBatchSize =
389 self
::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
391 $uploadDir = $this->getUploadDir();
392 if ( $this->getCliArg( 'use-filebackend' ) ) {
393 if ( self
::$backendToUse ) {
394 $backend = self
::$backendToUse;
396 $name = $this->getCliArg( 'use-filebackend' );
398 foreach ( $wgFileBackends as $conf ) {
399 if ( $conf['name'] == $name ) {
403 $useConfig['name'] = 'local-backend'; // swap name
404 unset( $useConfig['lockManager'] );
405 unset( $useConfig['fileJournal'] );
406 $class = $useConfig['class'];
407 self
::$backendToUse = new $class( $useConfig );
408 $backend = self
::$backendToUse;
411 # Replace with a mock. We do not care about generating real
412 # files on the filesystem, just need to expose the file
414 $backend = new MockFileBackend( [
415 'name' => 'local-backend',
416 'wikiId' => wfWikiID()
421 'wgLocalFileRepo' => [
422 'class' => 'LocalRepo',
424 'url' => 'http://example.com/images',
426 'transformVia404' => false,
427 'backend' => $backend
429 'wgEnableUploads' => self
::getOptionValue( 'wgEnableUploads', $opts, true ),
430 'wgLanguageCode' => $lang,
431 'wgDBprefix' => $this->db
->getType() != 'oracle' ?
'unittest_' : 'ut_',
432 'wgRawHtml' => self
::getOptionValue( 'wgRawHtml', $opts, false ),
433 'wgNamespacesWithSubpages' => [ NS_MAIN
=> isset( $opts['subpage'] ) ],
434 'wgAllowExternalImages' => self
::getOptionValue( 'wgAllowExternalImages', $opts, true ),
435 'wgThumbLimits' => [ self
::getOptionValue( 'thumbsize', $opts, 180 ) ],
436 'wgMaxTocLevel' => $maxtoclevel,
437 'wgUseTeX' => isset( $opts['math'] ) ||
isset( $opts['texvc'] ),
438 'wgMathDirectory' => $uploadDir . '/math',
439 'wgDefaultLanguageVariant' => $variant,
440 'wgLinkHolderBatchSize' => $linkHolderBatchSize,
441 'wgUseTidy' => isset( $opts['tidy'] ),
445 $configLines = explode( "\n", $config );
447 foreach ( $configLines as $line ) {
448 list( $var, $value ) = explode( '=', $line, 2 );
450 $settings[$var] = eval( "return $value;" ); // ???
454 $this->savedGlobals
= [];
457 Hooks
::run( 'ParserTestGlobals', [ &$settings ] );
459 $langObj = Language
::factory( $lang );
460 $settings['wgContLang'] = $langObj;
461 $settings['wgLang'] = $langObj;
463 $context = new RequestContext();
464 $settings['wgOut'] = $context->getOutput();
465 $settings['wgUser'] = $context->getUser();
466 $settings['wgRequest'] = $context->getRequest();
468 // We (re)set $wgThumbLimits to a single-element array above.
469 $context->getUser()->setOption( 'thumbsize', 0 );
471 foreach ( $settings as $var => $val ) {
472 if ( array_key_exists( $var, $GLOBALS ) ) {
473 $this->savedGlobals
[$var] = $GLOBALS[$var];
476 $GLOBALS[$var] = $val;
479 MWTidy
::destroySingleton();
480 MagicWord
::clearCache();
482 # The entries saved into RepoGroup cache with previous globals will be wrong.
483 RepoGroup
::destroySingleton();
484 FileBackendGroup
::destroySingleton();
486 # Create dummy files in storage
487 $this->setupUploads();
489 # Publish the articles after we have the final language set
490 $this->publishTestArticles();
492 MessageCache
::destroyInstance();
498 * Get an FS upload directory (only applies to FSFileBackend)
500 * @return string The directory
502 protected function getUploadDir() {
503 if ( $this->keepUploads
) {
504 // Don't use getNewTempDirectory() as this is meant to persist
505 $dir = wfTempDir() . '/mwParser-images';
507 if ( is_dir( $dir ) ) {
511 $dir = $this->getNewTempDirectory();
514 if ( file_exists( $dir ) ) {
515 wfDebug( "Already exists!\n" );
524 * Create a dummy uploads directory which will contain a couple
525 * of files in order to pass existence tests.
527 * @return string The directory
529 protected function setupUploads() {
532 $base = $this->getBaseDir();
533 $backend = RepoGroup
::singleton()->getLocalRepo()->getBackend();
534 $backend->prepare( [ 'dir' => "$base/local-public/3/3a" ] );
536 'src' => "$IP/tests/phpunit/data/parser/headbg.jpg",
537 'dst' => "$base/local-public/3/3a/Foobar.jpg"
539 $backend->prepare( [ 'dir' => "$base/local-public/e/ea" ] );
541 'src' => "$IP/tests/phpunit/data/parser/wiki.png",
542 'dst' => "$base/local-public/e/ea/Thumb.png"
544 $backend->prepare( [ 'dir' => "$base/local-public/0/09" ] );
546 'src' => "$IP/tests/phpunit/data/parser/headbg.jpg",
547 'dst' => "$base/local-public/0/09/Bad.jpg"
549 $backend->prepare( [ 'dir' => "$base/local-public/5/5f" ] );
551 'src' => "$IP/tests/phpunit/data/parser/LoremIpsum.djvu",
552 'dst' => "$base/local-public/5/5f/LoremIpsum.djvu"
555 // No helpful SVG file to copy, so make one ourselves
556 $data = '<?xml version="1.0" encoding="utf-8"?>' .
557 '<svg xmlns="http://www.w3.org/2000/svg"' .
558 ' version="1.1" width="240" height="180"/>';
560 $backend->prepare( [ 'dir' => "$base/local-public/f/ff" ] );
561 $backend->quickCreate( [
562 'content' => $data, 'dst' => "$base/local-public/f/ff/Foobar.svg"
567 * Restore default values and perform any necessary clean-up
568 * after each test runs.
570 protected function teardownGlobals() {
571 $this->teardownUploads();
573 foreach ( $this->savedGlobals
as $var => $val ) {
574 $GLOBALS[$var] = $val;
579 * Remove the dummy uploads directory
581 private function teardownUploads() {
582 if ( $this->keepUploads
) {
586 $backend = RepoGroup
::singleton()->getLocalRepo()->getBackend();
587 if ( $backend instanceof MockFileBackend
) {
588 # In memory backend, so dont bother cleaning them up.
592 $base = $this->getBaseDir();
593 // delete the files first, then the dirs.
596 "$base/local-public/3/3a/Foobar.jpg",
597 "$base/local-thumb/3/3a/Foobar.jpg/1000px-Foobar.jpg",
598 "$base/local-thumb/3/3a/Foobar.jpg/100px-Foobar.jpg",
599 "$base/local-thumb/3/3a/Foobar.jpg/120px-Foobar.jpg",
600 "$base/local-thumb/3/3a/Foobar.jpg/1280px-Foobar.jpg",
601 "$base/local-thumb/3/3a/Foobar.jpg/137px-Foobar.jpg",
602 "$base/local-thumb/3/3a/Foobar.jpg/1500px-Foobar.jpg",
603 "$base/local-thumb/3/3a/Foobar.jpg/177px-Foobar.jpg",
604 "$base/local-thumb/3/3a/Foobar.jpg/180px-Foobar.jpg",
605 "$base/local-thumb/3/3a/Foobar.jpg/200px-Foobar.jpg",
606 "$base/local-thumb/3/3a/Foobar.jpg/206px-Foobar.jpg",
607 "$base/local-thumb/3/3a/Foobar.jpg/20px-Foobar.jpg",
608 "$base/local-thumb/3/3a/Foobar.jpg/220px-Foobar.jpg",
609 "$base/local-thumb/3/3a/Foobar.jpg/265px-Foobar.jpg",
610 "$base/local-thumb/3/3a/Foobar.jpg/270px-Foobar.jpg",
611 "$base/local-thumb/3/3a/Foobar.jpg/274px-Foobar.jpg",
612 "$base/local-thumb/3/3a/Foobar.jpg/300px-Foobar.jpg",
613 "$base/local-thumb/3/3a/Foobar.jpg/30px-Foobar.jpg",
614 "$base/local-thumb/3/3a/Foobar.jpg/330px-Foobar.jpg",
615 "$base/local-thumb/3/3a/Foobar.jpg/353px-Foobar.jpg",
616 "$base/local-thumb/3/3a/Foobar.jpg/360px-Foobar.jpg",
617 "$base/local-thumb/3/3a/Foobar.jpg/400px-Foobar.jpg",
618 "$base/local-thumb/3/3a/Foobar.jpg/40px-Foobar.jpg",
619 "$base/local-thumb/3/3a/Foobar.jpg/440px-Foobar.jpg",
620 "$base/local-thumb/3/3a/Foobar.jpg/442px-Foobar.jpg",
621 "$base/local-thumb/3/3a/Foobar.jpg/450px-Foobar.jpg",
622 "$base/local-thumb/3/3a/Foobar.jpg/50px-Foobar.jpg",
623 "$base/local-thumb/3/3a/Foobar.jpg/600px-Foobar.jpg",
624 "$base/local-thumb/3/3a/Foobar.jpg/640px-Foobar.jpg",
625 "$base/local-thumb/3/3a/Foobar.jpg/70px-Foobar.jpg",
626 "$base/local-thumb/3/3a/Foobar.jpg/75px-Foobar.jpg",
627 "$base/local-thumb/3/3a/Foobar.jpg/960px-Foobar.jpg",
629 "$base/local-public/e/ea/Thumb.png",
631 "$base/local-public/0/09/Bad.jpg",
633 "$base/local-public/5/5f/LoremIpsum.djvu",
634 "$base/local-thumb/5/5f/LoremIpsum.djvu/page2-2480px-LoremIpsum.djvu.jpg",
635 "$base/local-thumb/5/5f/LoremIpsum.djvu/page2-3720px-LoremIpsum.djvu.jpg",
636 "$base/local-thumb/5/5f/LoremIpsum.djvu/page2-4960px-LoremIpsum.djvu.jpg",
638 "$base/local-public/f/ff/Foobar.svg",
639 "$base/local-thumb/f/ff/Foobar.svg/180px-Foobar.svg.png",
640 "$base/local-thumb/f/ff/Foobar.svg/2000px-Foobar.svg.png",
641 "$base/local-thumb/f/ff/Foobar.svg/270px-Foobar.svg.png",
642 "$base/local-thumb/f/ff/Foobar.svg/3000px-Foobar.svg.png",
643 "$base/local-thumb/f/ff/Foobar.svg/360px-Foobar.svg.png",
644 "$base/local-thumb/f/ff/Foobar.svg/4000px-Foobar.svg.png",
645 "$base/local-thumb/f/ff/Foobar.svg/langde-180px-Foobar.svg.png",
646 "$base/local-thumb/f/ff/Foobar.svg/langde-270px-Foobar.svg.png",
647 "$base/local-thumb/f/ff/Foobar.svg/langde-360px-Foobar.svg.png",
649 "$base/local-public/math/f/a/5/fa50b8b616463173474302ca3e63586b.png",
655 * Delete the specified files, if they exist.
656 * @param array $files Full paths to files to delete.
658 private static function deleteFiles( $files ) {
659 $backend = RepoGroup
::singleton()->getLocalRepo()->getBackend();
660 foreach ( $files as $file ) {
661 $backend->delete( [ 'src' => $file ], [ 'force' => 1 ] );
663 foreach ( $files as $file ) {
664 $tmp = FileBackend
::parentStoragePath( $file );
666 if ( !$backend->clean( [ 'dir' => $tmp ] )->isOK() ) {
669 $tmp = FileBackend
::parentStoragePath( $tmp );
674 protected function getBaseDir() {
675 return 'mwstore://local-backend';
678 public function parserTestProvider() {
679 if ( $this->file
=== false ) {
680 global $wgParserTestFiles;
681 $this->file
= $wgParserTestFiles[0];
684 return new TestFileDataProvider( $this->file
, $this );
688 * Set the file from whose tests will be run by this instance
689 * @param string $filename
691 public function setParserTestFile( $filename ) {
692 $this->file
= $filename;
698 * @dataProvider parserTestProvider
699 * @param string $desc
700 * @param string $input
701 * @param string $result
703 * @param array $config
705 public function testParserTest( $desc, $input, $result, $opts, $config ) {
706 if ( $this->regex
!= '' && !preg_match( '/' . $this->regex
. '/', $desc ) ) {
707 $this->assertTrue( true ); // XXX: don't flood output with "test made no assertions"
708 // $this->markTestSkipped( 'Filtered out by the user' );
712 if ( !$this->isWikitextNS( NS_MAIN
) ) {
713 // parser tests frequently assume that the main namespace contains wikitext.
714 // @todo When setting up pages, force the content model. Only skip if
715 // $wgtContentModelUseDB is false.
716 $this->markTestSkipped( "Main namespace does not support wikitext,"
717 . "skipping parser test: $desc" );
720 wfDebug( "Running parser test: $desc\n" );
722 $opts = $this->parseOptions( $opts );
723 $context = $this->setupGlobals( $opts, $config );
725 $user = $context->getUser();
726 $options = ParserOptions
::newFromContext( $context );
728 if ( isset( $opts['title'] ) ) {
729 $titleText = $opts['title'];
731 $titleText = 'Parser test';
734 $local = isset( $opts['local'] );
735 $preprocessor = isset( $opts['preprocessor'] ) ?
$opts['preprocessor'] : null;
736 $parser = $this->getParser( $preprocessor );
738 $title = Title
::newFromText( $titleText );
740 # Parser test requiring math. Make sure texvc is executable
741 # or just skip such tests.
742 if ( isset( $opts['math'] ) ||
isset( $opts['texvc'] ) ) {
745 if ( !isset( $wgTexvc ) ) {
746 $this->markTestSkipped( "SKIPPED: \$wgTexvc is not set" );
747 } elseif ( !is_executable( $wgTexvc ) ) {
748 $this->markTestSkipped( "SKIPPED: texvc binary does not exist"
749 . " or is not executable.\n"
750 . "Current configuration is:\n\$wgTexvc = '$wgTexvc'" );
754 if ( isset( $opts['djvu'] ) ) {
755 if ( !$this->djVuSupport
->isEnabled() ) {
756 $this->markTestSkipped( "SKIPPED: djvu binaries do not exist or are not executable.\n" );
760 if ( isset( $opts['tidy'] ) ) {
761 if ( !$this->tidySupport
->isEnabled() ) {
762 $this->markTestSkipped( "SKIPPED: tidy extension is not installed.\n" );
764 $options->setTidy( true );
768 if ( isset( $opts['pst'] ) ) {
769 $out = $parser->preSaveTransform( $input, $title, $user, $options );
770 } elseif ( isset( $opts['msg'] ) ) {
771 $out = $parser->transformMsg( $input, $options, $title );
772 } elseif ( isset( $opts['section'] ) ) {
773 $section = $opts['section'];
774 $out = $parser->getSection( $input, $section );
775 } elseif ( isset( $opts['replace'] ) ) {
776 $section = $opts['replace'][0];
777 $replace = $opts['replace'][1];
778 $out = $parser->replaceSection( $input, $section, $replace );
779 } elseif ( isset( $opts['comment'] ) ) {
780 $out = Linker
::formatComment( $input, $title, $local );
781 } elseif ( isset( $opts['preload'] ) ) {
782 $out = $parser->getPreloadText( $input, $title, $options );
784 $output = $parser->parse( $input, $title, $options, true, true, 1337 );
785 $output->setTOCEnabled( !isset( $opts['notoc'] ) );
786 $out = $output->getText();
787 if ( isset( $opts['tidy'] ) ) {
788 $out = preg_replace( '/\s+$/', '', $out );
791 if ( isset( $opts['showtitle'] ) ) {
792 if ( $output->getTitleText() ) {
793 $title = $output->getTitleText();
796 $out = "$title\n$out";
799 if ( isset( $opts['showindicators'] ) ) {
801 foreach ( $output->getIndicators() as $id => $content ) {
802 $indicators .= "$id=$content\n";
804 $out = $indicators . $out;
807 if ( isset( $opts['ill'] ) ) {
808 $out = implode( ' ', $output->getLanguageLinks() );
809 } elseif ( isset( $opts['cat'] ) ) {
810 $outputPage = $context->getOutput();
811 $outputPage->addCategoryLinks( $output->getCategories() );
812 $cats = $outputPage->getCategoryLinks();
814 if ( isset( $cats['normal'] ) ) {
815 $out = implode( ' ', $cats['normal'] );
820 $parser->mPreprocessor
= null;
823 $this->teardownGlobals();
825 $this->assertEquals( $result, $out, $desc );
829 * Run a fuzz test series
830 * Draw input from a set of test files
832 * @todo fixme Needs some work to not eat memory until the world explodes
836 public function testFuzzTests() {
837 global $wgParserTestFiles;
839 $files = $wgParserTestFiles;
841 if ( $this->getCliArg( 'file' ) ) {
842 $files = [ $this->getCliArg( 'file' ) ];
845 $dict = $this->getFuzzInput( $files );
846 $dictSize = strlen( $dict );
847 $logMaxLength = log( $this->maxFuzzTestLength
);
849 ini_set( 'memory_limit', $this->memoryLimit
* 1048576 );
852 $opts = ParserOptions
::newFromUser( $user );
853 $title = Title
::makeTitle( NS_MAIN
, 'Parser_test' );
859 // Generate test input
860 mt_srand( ++
$this->fuzzSeed
);
861 $totalLength = mt_rand( 1, $this->maxFuzzTestLength
);
864 while ( strlen( $input ) < $totalLength ) {
865 $logHairLength = mt_rand( 0, 1000000 ) / 1000000 * $logMaxLength;
866 $hairLength = min( intval( exp( $logHairLength ) ), $dictSize );
867 $offset = mt_rand( 0, $dictSize - $hairLength );
868 $input .= substr( $dict, $offset, $hairLength );
871 $this->setupGlobals();
872 $parser = $this->getParser();
876 $parser->parse( $input, $title, $opts );
877 $this->assertTrue( true, "Test $id, fuzz seed {$this->fuzzSeed}" );
878 } catch ( Exception
$exception ) {
879 $input_dump = sprintf( "string(%d) \"%s\"\n", strlen( $input ), $input );
881 $this->assertTrue( false, "Test $id, fuzz seed {$this->fuzzSeed}. \n\n" .
882 "Input: $input_dump\n\nError: {$exception->getMessage()}\n\n" .
883 "Backtrace: {$exception->getTraceAsString()}" );
886 $this->teardownGlobals();
887 $parser->__destruct();
889 if ( $id %
100 == 0 ) {
890 $usage = intval( memory_get_usage( true ) / $this->memoryLimit
/ 1048576 * 100 );
891 // echo "{$this->fuzzSeed}: $numSuccess/$numTotal (mem: $usage%)\n";
893 $ret = "Out of memory:\n";
894 $memStats = $this->getMemoryBreakdown();
896 foreach ( $memStats as $name => $usage ) {
897 $ret .= "$name: $usage\n";
900 throw new MWException( $ret );
908 // Various getter functions
911 * Get an input dictionary from a set of parser test files
912 * @param array $filenames
915 function getFuzzInput( $filenames ) {
918 foreach ( $filenames as $filename ) {
919 $contents = file_get_contents( $filename );
920 preg_match_all( '/!!\s*input\n(.*?)\n!!\s*result/s', $contents, $matches );
922 foreach ( $matches[1] as $match ) {
923 $dict .= $match . "\n";
931 * Get a memory usage breakdown
934 function getMemoryBreakdown() {
937 foreach ( $GLOBALS as $name => $value ) {
938 $memStats['$' . $name] = strlen( serialize( $value ) );
941 $classes = get_declared_classes();
943 foreach ( $classes as $class ) {
944 $rc = new ReflectionClass( $class );
945 $props = $rc->getStaticProperties();
946 $memStats[$class] = strlen( serialize( $props ) );
947 $methods = $rc->getMethods();
949 foreach ( $methods as $method ) {
950 $memStats[$class] +
= strlen( serialize( $method->getStaticVariables() ) );
954 $functions = get_defined_functions();
956 foreach ( $functions['user'] as $function ) {
957 $rf = new ReflectionFunction( $function );
958 $memStats["$function()"] = strlen( serialize( $rf->getStaticVariables() ) );
967 * Get a Parser object
968 * @param Preprocessor $preprocessor
971 function getParser( $preprocessor = null ) {
972 global $wgParserConf;
974 $class = $wgParserConf['class'];
975 $parser = new $class( [ 'preprocessorClass' => $preprocessor ] +
$wgParserConf );
977 Hooks
::run( 'ParserTestParser', [ &$parser ] );
982 // Various action functions
984 public function addArticle( $name, $text, $line ) {
985 self
::$articles[$name] = [ $text, $line ];
988 public function publishTestArticles() {
989 if ( empty( self
::$articles ) ) {
993 foreach ( self
::$articles as $name => $info ) {
994 list( $text, $line ) = $info;
995 ParserTest
::addArticle( $name, $text, $line, 'ignoreduplicate' );
1000 * Steal a callback function from the primary parser, save it for
1001 * application to our scary parser. If the hook is not installed,
1002 * abort processing of this file.
1004 * @param string $name
1005 * @return bool True if tag hook is present
1007 public function requireHook( $name ) {
1009 $wgParser->firstCallInit(); // make sure hooks are loaded.
1010 return isset( $wgParser->mTagHooks
[$name] );
1013 public function requireFunctionHook( $name ) {
1015 $wgParser->firstCallInit(); // make sure hooks are loaded.
1016 return isset( $wgParser->mFunctionHooks
[$name] );
1019 public function requireTransparentHook( $name ) {
1021 $wgParser->firstCallInit(); // make sure hooks are loaded.
1022 return isset( $wgParser->mTransparentTagHooks
[$name] );
1025 // Various "cleanup" functions
1028 * Remove last character if it is a newline
1032 public function removeEndingNewline( $s ) {
1033 if ( substr( $s, -1 ) === "\n" ) {
1034 return substr( $s, 0, -1 );
1040 // Test options parser functions
1042 protected function parseOptions( $instring ) {
1048 // foo=bar,"baz quux"
1070 "[^"]*" # Quoted val
1072 \[\[[^]]*\]\] # Link target
1080 if ( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER
) ) {
1081 foreach ( $matches as $bits ) {
1082 array_shift( $bits );
1083 $key = strtolower( array_shift( $bits ) );
1084 if ( count( $bits ) == 0 ) {
1086 } elseif ( count( $bits ) == 1 ) {
1087 $opts[$key] = $this->cleanupOption( array_shift( $bits ) );
1090 $opts[$key] = array_map( [ $this, 'cleanupOption' ], $bits );
1098 protected function cleanupOption( $opt ) {
1099 if ( substr( $opt, 0, 1 ) == '"' ) {
1100 return substr( $opt, 1, -1 );
1103 if ( substr( $opt, 0, 2 ) == '[[' ) {
1104 return substr( $opt, 2, -2 );
1111 * Use a regex to find out the value of an option
1112 * @param string $key Name of option val to retrieve
1113 * @param array $opts Options array to look in
1114 * @param mixed $default Default value returned if not found
1117 protected static function getOptionValue( $key, $opts, $default ) {
1118 $key = strtolower( $key );
1120 if ( isset( $opts[$key] ) ) {