Renames preparatory to parser tests refactor
[lhc/web/wiklou.git] / tests / phpunit / includes / parser / ParserIntegrationTest.php
1 <?php
2
3 use MediaWiki\MediaWikiServices;
4
5 /**
6 * Although marked as a stub, can work independently.
7 *
8 * @group Database
9 * @group Parser
10 * @group Stub
11 *
12 * @todo covers tags
13 */
14 class ParserIntegrationTest extends MediaWikiTestCase {
15 static protected $articles = []; // Array of test articles defined by the tests
16 /* The data provider is run on a different instance than the test, so it must be static
17 * When running tests from several files, all tests will see all articles.
18 */
19 static protected $backendToUse;
20
21 public $keepUploads = false;
22 public $runDisabled = false;
23 public $runParsoid = false;
24 public $regex = '';
25 public $showProgress = true;
26 public $savedWeirdGlobals = [];
27 public $savedGlobals = [];
28 public $hooks = [];
29 public $functionHooks = [];
30 public $transparentHooks = [];
31
32 /**
33 * @var DjVuSupport
34 */
35 private $djVuSupport;
36 /**
37 * @var TidySupport
38 */
39 private $tidySupport;
40
41 protected $file = false;
42
43 public static function setUpBeforeClass() {
44 // Inject ParserTestRunner well-known interwikis
45 ParserTestRunner::setupInterwikis();
46 }
47
48 protected function setUp() {
49 global $wgNamespaceAliases, $wgContLang;
50 global $wgHooks, $IP;
51
52 parent::setUp();
53
54 // Setup CLI arguments
55 if ( $this->getCliArg( 'regex' ) ) {
56 $this->regex = $this->getCliArg( 'regex' );
57 } else {
58 # Matches anything
59 $this->regex = '';
60 }
61
62 $this->keepUploads = $this->getCliArg( 'keep-uploads' );
63
64 $tmpGlobals = [];
65
66 $tmpGlobals['wgLanguageCode'] = 'en';
67 $tmpGlobals['wgContLang'] = Language::factory( 'en' );
68 $tmpGlobals['wgSitename'] = 'MediaWiki';
69 $tmpGlobals['wgServer'] = 'http://example.org';
70 $tmpGlobals['wgServerName'] = 'example.org';
71 $tmpGlobals['wgScriptPath'] = '';
72 $tmpGlobals['wgScript'] = '/index.php';
73 $tmpGlobals['wgResourceBasePath'] = '';
74 $tmpGlobals['wgStylePath'] = '/skins';
75 $tmpGlobals['wgExtensionAssetsPath'] = '/extensions';
76 $tmpGlobals['wgArticlePath'] = '/wiki/$1';
77 $tmpGlobals['wgActionPaths'] = [];
78 $tmpGlobals['wgVariantArticlePath'] = false;
79 $tmpGlobals['wgEnableUploads'] = true;
80 $tmpGlobals['wgUploadNavigationUrl'] = false;
81 $tmpGlobals['wgThumbnailScriptPath'] = false;
82 $tmpGlobals['wgLocalFileRepo'] = [
83 'class' => 'LocalRepo',
84 'name' => 'local',
85 'url' => 'http://example.com/images',
86 'hashLevels' => 2,
87 'transformVia404' => false,
88 'backend' => 'local-backend'
89 ];
90 $tmpGlobals['wgForeignFileRepos'] = [];
91 $tmpGlobals['wgDefaultExternalStore'] = [];
92 $tmpGlobals['wgParserCacheType'] = CACHE_NONE;
93 $tmpGlobals['wgCapitalLinks'] = true;
94 $tmpGlobals['wgNoFollowLinks'] = true;
95 $tmpGlobals['wgNoFollowDomainExceptions'] = [ 'no-nofollow.org' ];
96 $tmpGlobals['wgExternalLinkTarget'] = false;
97 $tmpGlobals['wgThumbnailScriptPath'] = false;
98 $tmpGlobals['wgUseImageResize'] = true;
99 $tmpGlobals['wgAllowExternalImages'] = true;
100 $tmpGlobals['wgRawHtml'] = false;
101 $tmpGlobals['wgExperimentalHtmlIds'] = false;
102 $tmpGlobals['wgAdaptiveMessageCache'] = true;
103 $tmpGlobals['wgUseDatabaseMessages'] = true;
104 $tmpGlobals['wgLocaltimezone'] = 'UTC';
105 $tmpGlobals['wgGroupPermissions'] = [
106 '*' => [
107 'createaccount' => true,
108 'read' => true,
109 'edit' => true,
110 'createpage' => true,
111 'createtalk' => true,
112 ] ];
113 $tmpGlobals['wgNamespaceProtection'] = [ NS_MEDIAWIKI => 'editinterface' ];
114
115 $tmpGlobals['wgParser'] = new StubObject(
116 'wgParser', $GLOBALS['wgParserConf']['class'],
117 [ $GLOBALS['wgParserConf'] ] );
118
119 $tmpGlobals['wgFileExtensions'][] = 'svg';
120 $tmpGlobals['wgSVGConverter'] = 'rsvg';
121 $tmpGlobals['wgSVGConverters']['rsvg'] =
122 '$path/rsvg-convert -w $width -h $height -o $output $input';
123
124 if ( $GLOBALS['wgStyleDirectory'] === false ) {
125 $tmpGlobals['wgStyleDirectory'] = "$IP/skins";
126 }
127
128 $tmpHooks = $wgHooks;
129 $tmpHooks['ParserTestParser'][] = 'ParserTestParserHook::setup';
130 $tmpHooks['ParserGetVariableValueTs'][] = 'ParserTestRunner::getFakeTimestamp';
131 $tmpGlobals['wgHooks'] = $tmpHooks;
132 # add a namespace shadowing a interwiki link, to test
133 # proper precedence when resolving links. (bug 51680)
134 $tmpGlobals['wgExtraNamespaces'] = [
135 100 => 'MemoryAlpha',
136 101 => 'MemoryAlpha_talk'
137 ];
138
139 $tmpGlobals['wgLocalInterwikis'] = [ 'local', 'mi' ];
140 # "extra language links"
141 # see https://gerrit.wikimedia.org/r/111390
142 $tmpGlobals['wgExtraInterlanguageLinkPrefixes'] = [ 'mul' ];
143
144 // DjVu support
145 $this->djVuSupport = new DjVuSupport();
146 // Tidy support
147 $this->tidySupport = new TidySupport();
148 $tmpGlobals['wgTidyConfig'] = $this->tidySupport->getConfig();
149 $tmpGlobals['wgUseTidy'] = false;
150
151 $this->setMwGlobals( $tmpGlobals );
152
153 $this->savedWeirdGlobals['image_alias'] = $wgNamespaceAliases['Image'];
154 $this->savedWeirdGlobals['image_talk_alias'] = $wgNamespaceAliases['Image_talk'];
155
156 $wgNamespaceAliases['Image'] = NS_FILE;
157 $wgNamespaceAliases['Image_talk'] = NS_FILE_TALK;
158
159 MWNamespace::getCanonicalNamespaces( true ); # reset namespace cache
160 $wgContLang->resetNamespaces(); # reset namespace cache
161 ParserTestRunner::resetTitleServices();
162 MediaWikiServices::getInstance()->disableService( 'MediaHandlerFactory' );
163 MediaWikiServices::getInstance()->redefineService(
164 'MediaHandlerFactory',
165 function() {
166 return new MockMediaHandlerFactory();
167 }
168 );
169 }
170
171 protected function tearDown() {
172 global $wgNamespaceAliases, $wgContLang;
173
174 $wgNamespaceAliases['Image'] = $this->savedWeirdGlobals['image_alias'];
175 $wgNamespaceAliases['Image_talk'] = $this->savedWeirdGlobals['image_talk_alias'];
176
177 MWTidy::destroySingleton();
178
179 // Restore backends
180 RepoGroup::destroySingleton();
181 FileBackendGroup::destroySingleton();
182
183 // Remove temporary pages from the link cache
184 LinkCache::singleton()->clear();
185
186 // Restore message cache (temporary pages and $wgUseDatabaseMessages)
187 MessageCache::destroyInstance();
188 MediaWikiServices::getInstance()->resetServiceForTesting( 'MediaHandlerFactory' );
189
190 parent::tearDown();
191
192 MWNamespace::getCanonicalNamespaces( true ); # reset namespace cache
193 $wgContLang->resetNamespaces(); # reset namespace cache
194 }
195
196 public static function tearDownAfterClass() {
197 ParserTestRunner::tearDownInterwikis();
198 parent::tearDownAfterClass();
199 }
200
201 function addDBDataOnce() {
202 # disabled for performance
203 # $this->tablesUsed[] = 'image';
204
205 # Update certain things in site_stats
206 $this->db->insert( 'site_stats',
207 [ 'ss_row_id' => 1, 'ss_images' => 2, 'ss_good_articles' => 1 ],
208 __METHOD__,
209 [ 'IGNORE' ]
210 );
211
212 $user = User::newFromId( 0 );
213 LinkCache::singleton()->clear(); # Avoids the odd failure at creating the nullRevision
214
215 # Upload DB table entries for files.
216 # We will upload the actual files later. Note that if anything causes LocalFile::load()
217 # to be triggered before then, it will break via maybeUpgrade() setting the fileExists
218 # member to false and storing it in cache.
219 # note that the size/width/height/bits/etc of the file
220 # are actually set by inspecting the file itself; the arguments
221 # to recordUpload2 have no effect. That said, we try to make things
222 # match up so it is less confusing to readers of the code & tests.
223 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Foobar.jpg' ) );
224 if ( !$this->db->selectField( 'image', '1', [ 'img_name' => $image->getName() ] ) ) {
225 $image->recordUpload2(
226 '', // archive name
227 'Upload of some lame file',
228 'Some lame file',
229 [
230 'size' => 7881,
231 'width' => 1941,
232 'height' => 220,
233 'bits' => 8,
234 'media_type' => MEDIATYPE_BITMAP,
235 'mime' => 'image/jpeg',
236 'metadata' => serialize( [] ),
237 'sha1' => Wikimedia\base_convert( '1', 16, 36, 31 ),
238 'fileExists' => true ],
239 $this->db->timestamp( '20010115123500' ), $user
240 );
241 }
242
243 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Thumb.png' ) );
244 if ( !$this->db->selectField( 'image', '1', [ 'img_name' => $image->getName() ] ) ) {
245 $image->recordUpload2(
246 '', // archive name
247 'Upload of some lame thumbnail',
248 'Some lame thumbnail',
249 [
250 'size' => 22589,
251 'width' => 135,
252 'height' => 135,
253 'bits' => 8,
254 'media_type' => MEDIATYPE_BITMAP,
255 'mime' => 'image/png',
256 'metadata' => serialize( [] ),
257 'sha1' => Wikimedia\base_convert( '2', 16, 36, 31 ),
258 'fileExists' => true ],
259 $this->db->timestamp( '20130225203040' ), $user
260 );
261 }
262
263 # This image will be blacklisted in [[MediaWiki:Bad image list]]
264 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Bad.jpg' ) );
265 if ( !$this->db->selectField( 'image', '1', [ 'img_name' => $image->getName() ] ) ) {
266 $image->recordUpload2(
267 '', // archive name
268 'zomgnotcensored',
269 'Borderline image',
270 [
271 'size' => 12345,
272 'width' => 320,
273 'height' => 240,
274 'bits' => 24,
275 'media_type' => MEDIATYPE_BITMAP,
276 'mime' => 'image/jpeg',
277 'metadata' => serialize( [] ),
278 'sha1' => Wikimedia\base_convert( '3', 16, 36, 31 ),
279 'fileExists' => true ],
280 $this->db->timestamp( '20010115123500' ), $user
281 );
282 }
283 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Foobar.svg' ) );
284 if ( !$this->db->selectField( 'image', '1', [ 'img_name' => $image->getName() ] ) ) {
285 $image->recordUpload2( '', 'Upload of some lame SVG', 'Some lame SVG', [
286 'size' => 12345,
287 'width' => 240,
288 'height' => 180,
289 'bits' => 0,
290 'media_type' => MEDIATYPE_DRAWING,
291 'mime' => 'image/svg+xml',
292 'metadata' => serialize( [] ),
293 'sha1' => Wikimedia\base_convert( '', 16, 36, 31 ),
294 'fileExists' => true
295 ], $this->db->timestamp( '20010115123500' ), $user );
296 }
297
298 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Video.ogv' ) );
299 if ( !$this->db->selectField( 'image', '1', [ 'img_name' => $image->getName() ] ) ) {
300 $image->recordUpload2( '', 'A pretty movie', 'Will it play', [
301 'size' => 12345,
302 'width' => 320,
303 'height' => 240,
304 'bits' => 0,
305 'media_type' => MEDIATYPE_VIDEO,
306 'mime' => 'application/ogg',
307 'metadata' => serialize( [] ),
308 'sha1' => Wikimedia\base_convert( '', 16, 36, 32 ),
309 'fileExists' => true
310 ], $this->db->timestamp( '20010115123500' ), $user );
311 }
312
313 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Audio.oga' ) );
314 if ( !$this->db->selectField( 'image', '1', [ 'img_name' => $image->getName() ] ) ) {
315 $image->recordUpload2( '', 'An awesome hitsong ', 'Will it play', [
316 'size' => 12345,
317 'width' => 0,
318 'height' => 0,
319 'bits' => 0,
320 'media_type' => MEDIATYPE_AUDIO,
321 'mime' => 'application/ogg',
322 'metadata' => serialize( [] ),
323 'sha1' => Wikimedia\base_convert( '', 16, 36, 32 ),
324 'fileExists' => true
325 ], $this->db->timestamp( '20010115123500' ), $user );
326 }
327
328 # A DjVu file
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', [
332 'size' => 3249,
333 'width' => 2480,
334 'height' => 3508,
335 'bits' => 0,
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">
340 <DjVuXML>
341 <HEAD></HEAD>
342 <BODY><OBJECT height="3508" width="2480">
343 <PARAM name="DPI" value="300" />
344 <PARAM name="GAMMA" value="2.2" />
345 </OBJECT>
346 <OBJECT height="3508" width="2480">
347 <PARAM name="DPI" value="300" />
348 <PARAM name="GAMMA" value="2.2" />
349 </OBJECT>
350 <OBJECT height="3508" width="2480">
351 <PARAM name="DPI" value="300" />
352 <PARAM name="GAMMA" value="2.2" />
353 </OBJECT>
354 <OBJECT height="3508" width="2480">
355 <PARAM name="DPI" value="300" />
356 <PARAM name="GAMMA" value="2.2" />
357 </OBJECT>
358 <OBJECT height="3508" width="2480">
359 <PARAM name="DPI" value="300" />
360 <PARAM name="GAMMA" value="2.2" />
361 </OBJECT>
362 </BODY>
363 </DjVuXML>',
364 'sha1' => Wikimedia\base_convert( '', 16, 36, 31 ),
365 'fileExists' => true
366 ], $this->db->timestamp( '20140115123600' ), $user );
367 }
368 }
369
370 // ParserTestRunner setup/teardown functions
371
372 /**
373 * Set up the global variables for a consistent environment for each test.
374 * Ideally this should replace the global configuration entirely.
375 * @param array $opts
376 * @param string $config
377 * @return RequestContext
378 */
379 protected function setupGlobals( $opts = [], $config = '' ) {
380 global $wgFileBackends;
381 # Find out values for some special options.
382 $lang =
383 self::getOptionValue( 'language', $opts, 'en' );
384 $variant =
385 self::getOptionValue( 'variant', $opts, false );
386 $maxtoclevel =
387 self::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
388 $linkHolderBatchSize =
389 self::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
390
391 $uploadDir = $this->getUploadDir();
392 if ( $this->getCliArg( 'use-filebackend' ) ) {
393 if ( self::$backendToUse ) {
394 $backend = self::$backendToUse;
395 } else {
396 $name = $this->getCliArg( 'use-filebackend' );
397 $useConfig = [];
398 foreach ( $wgFileBackends as $conf ) {
399 if ( $conf['name'] == $name ) {
400 $useConfig = $conf;
401 }
402 }
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;
409 }
410 } else {
411 # Replace with a mock. We do not care about generating real
412 # files on the filesystem, just need to expose the file
413 # informations.
414 $backend = new MockFileBackend( [
415 'name' => 'local-backend',
416 'wikiId' => wfWikiID()
417 ] );
418 }
419
420 $settings = [
421 'wgLocalFileRepo' => [
422 'class' => 'LocalRepo',
423 'name' => 'local',
424 'url' => 'http://example.com/images',
425 'hashLevels' => 2,
426 'transformVia404' => false,
427 'backend' => $backend
428 ],
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' => false,
442 'wgTidyConfig' => isset( $opts['tidy'] ) ? $this->tidySupport->getConfig() : null
443 ];
444
445 if ( $config ) {
446 $configLines = explode( "\n", $config );
447
448 foreach ( $configLines as $line ) {
449 list( $var, $value ) = explode( '=', $line, 2 );
450
451 $settings[$var] = eval( "return $value;" ); // ???
452 }
453 }
454
455 $this->savedGlobals = [];
456
457 /** @since 1.20 */
458 Hooks::run( 'ParserTestGlobals', [ &$settings ] );
459
460 $langObj = Language::factory( $lang );
461 $settings['wgContLang'] = $langObj;
462 $settings['wgLang'] = $langObj;
463
464 $context = new RequestContext();
465 $settings['wgOut'] = $context->getOutput();
466 $settings['wgUser'] = $context->getUser();
467 $settings['wgRequest'] = $context->getRequest();
468
469 // We (re)set $wgThumbLimits to a single-element array above.
470 $context->getUser()->setOption( 'thumbsize', 0 );
471
472 foreach ( $settings as $var => $val ) {
473 if ( array_key_exists( $var, $GLOBALS ) ) {
474 $this->savedGlobals[$var] = $GLOBALS[$var];
475 }
476
477 $GLOBALS[$var] = $val;
478 }
479
480 MWTidy::destroySingleton();
481 MagicWord::clearCache();
482
483 # The entries saved into RepoGroup cache with previous globals will be wrong.
484 RepoGroup::destroySingleton();
485 FileBackendGroup::destroySingleton();
486
487 # Create dummy files in storage
488 $this->setupUploads();
489
490 # Publish the articles after we have the final language set
491 $this->publishTestArticles();
492
493 MessageCache::destroyInstance();
494
495 return $context;
496 }
497
498 /**
499 * Get an FS upload directory (only applies to FSFileBackend)
500 *
501 * @return string The directory
502 */
503 protected function getUploadDir() {
504 if ( $this->keepUploads ) {
505 // Don't use getNewTempDirectory() as this is meant to persist
506 $dir = wfTempDir() . '/mwParser-images';
507
508 if ( is_dir( $dir ) ) {
509 return $dir;
510 }
511 } else {
512 $dir = $this->getNewTempDirectory();
513 }
514
515 if ( file_exists( $dir ) ) {
516 wfDebug( "Already exists!\n" );
517
518 return $dir;
519 }
520
521 return $dir;
522 }
523
524 /**
525 * Create a dummy uploads directory which will contain a couple
526 * of files in order to pass existence tests.
527 *
528 * @return string The directory
529 */
530 protected function setupUploads() {
531 global $IP;
532
533 $base = $this->getBaseDir();
534 $backend = RepoGroup::singleton()->getLocalRepo()->getBackend();
535 $backend->prepare( [ 'dir' => "$base/local-public/3/3a" ] );
536 $backend->store( [
537 'src' => "$IP/tests/phpunit/data/parser/headbg.jpg",
538 'dst' => "$base/local-public/3/3a/Foobar.jpg"
539 ] );
540 $backend->prepare( [ 'dir' => "$base/local-public/e/ea" ] );
541 $backend->store( [
542 'src' => "$IP/tests/phpunit/data/parser/wiki.png",
543 'dst' => "$base/local-public/e/ea/Thumb.png"
544 ] );
545 $backend->prepare( [ 'dir' => "$base/local-public/0/09" ] );
546 $backend->store( [
547 'src' => "$IP/tests/phpunit/data/parser/headbg.jpg",
548 'dst' => "$base/local-public/0/09/Bad.jpg"
549 ] );
550 $backend->prepare( [ 'dir' => "$base/local-public/5/5f" ] );
551 $backend->store( [
552 'src' => "$IP/tests/phpunit/data/parser/LoremIpsum.djvu",
553 'dst' => "$base/local-public/5/5f/LoremIpsum.djvu"
554 ] );
555
556 // No helpful SVG file to copy, so make one ourselves
557 $data = '<?xml version="1.0" encoding="utf-8"?>' .
558 '<svg xmlns="http://www.w3.org/2000/svg"' .
559 ' version="1.1" width="240" height="180"/>';
560
561 $backend->prepare( [ 'dir' => "$base/local-public/f/ff" ] );
562 $backend->quickCreate( [
563 'content' => $data, 'dst' => "$base/local-public/f/ff/Foobar.svg"
564 ] );
565 }
566
567 /**
568 * Restore default values and perform any necessary clean-up
569 * after each test runs.
570 */
571 protected function teardownGlobals() {
572 $this->teardownUploads();
573
574 foreach ( $this->savedGlobals as $var => $val ) {
575 $GLOBALS[$var] = $val;
576 }
577 }
578
579 /**
580 * Remove the dummy uploads directory
581 */
582 private function teardownUploads() {
583 if ( $this->keepUploads ) {
584 return;
585 }
586
587 $backend = RepoGroup::singleton()->getLocalRepo()->getBackend();
588 if ( $backend instanceof MockFileBackend ) {
589 # In memory backend, so dont bother cleaning them up.
590 return;
591 }
592
593 $base = $this->getBaseDir();
594 // delete the files first, then the dirs.
595 self::deleteFiles(
596 [
597 "$base/local-public/3/3a/Foobar.jpg",
598 "$base/local-thumb/3/3a/Foobar.jpg/1000px-Foobar.jpg",
599 "$base/local-thumb/3/3a/Foobar.jpg/100px-Foobar.jpg",
600 "$base/local-thumb/3/3a/Foobar.jpg/120px-Foobar.jpg",
601 "$base/local-thumb/3/3a/Foobar.jpg/1280px-Foobar.jpg",
602 "$base/local-thumb/3/3a/Foobar.jpg/137px-Foobar.jpg",
603 "$base/local-thumb/3/3a/Foobar.jpg/1500px-Foobar.jpg",
604 "$base/local-thumb/3/3a/Foobar.jpg/177px-Foobar.jpg",
605 "$base/local-thumb/3/3a/Foobar.jpg/180px-Foobar.jpg",
606 "$base/local-thumb/3/3a/Foobar.jpg/200px-Foobar.jpg",
607 "$base/local-thumb/3/3a/Foobar.jpg/206px-Foobar.jpg",
608 "$base/local-thumb/3/3a/Foobar.jpg/20px-Foobar.jpg",
609 "$base/local-thumb/3/3a/Foobar.jpg/220px-Foobar.jpg",
610 "$base/local-thumb/3/3a/Foobar.jpg/265px-Foobar.jpg",
611 "$base/local-thumb/3/3a/Foobar.jpg/270px-Foobar.jpg",
612 "$base/local-thumb/3/3a/Foobar.jpg/274px-Foobar.jpg",
613 "$base/local-thumb/3/3a/Foobar.jpg/300px-Foobar.jpg",
614 "$base/local-thumb/3/3a/Foobar.jpg/30px-Foobar.jpg",
615 "$base/local-thumb/3/3a/Foobar.jpg/330px-Foobar.jpg",
616 "$base/local-thumb/3/3a/Foobar.jpg/353px-Foobar.jpg",
617 "$base/local-thumb/3/3a/Foobar.jpg/360px-Foobar.jpg",
618 "$base/local-thumb/3/3a/Foobar.jpg/400px-Foobar.jpg",
619 "$base/local-thumb/3/3a/Foobar.jpg/40px-Foobar.jpg",
620 "$base/local-thumb/3/3a/Foobar.jpg/440px-Foobar.jpg",
621 "$base/local-thumb/3/3a/Foobar.jpg/442px-Foobar.jpg",
622 "$base/local-thumb/3/3a/Foobar.jpg/450px-Foobar.jpg",
623 "$base/local-thumb/3/3a/Foobar.jpg/50px-Foobar.jpg",
624 "$base/local-thumb/3/3a/Foobar.jpg/600px-Foobar.jpg",
625 "$base/local-thumb/3/3a/Foobar.jpg/640px-Foobar.jpg",
626 "$base/local-thumb/3/3a/Foobar.jpg/70px-Foobar.jpg",
627 "$base/local-thumb/3/3a/Foobar.jpg/75px-Foobar.jpg",
628 "$base/local-thumb/3/3a/Foobar.jpg/960px-Foobar.jpg",
629
630 "$base/local-public/e/ea/Thumb.png",
631
632 "$base/local-public/0/09/Bad.jpg",
633
634 "$base/local-public/5/5f/LoremIpsum.djvu",
635 "$base/local-thumb/5/5f/LoremIpsum.djvu/page2-2480px-LoremIpsum.djvu.jpg",
636 "$base/local-thumb/5/5f/LoremIpsum.djvu/page2-3720px-LoremIpsum.djvu.jpg",
637 "$base/local-thumb/5/5f/LoremIpsum.djvu/page2-4960px-LoremIpsum.djvu.jpg",
638
639 "$base/local-public/f/ff/Foobar.svg",
640 "$base/local-thumb/f/ff/Foobar.svg/180px-Foobar.svg.png",
641 "$base/local-thumb/f/ff/Foobar.svg/2000px-Foobar.svg.png",
642 "$base/local-thumb/f/ff/Foobar.svg/270px-Foobar.svg.png",
643 "$base/local-thumb/f/ff/Foobar.svg/3000px-Foobar.svg.png",
644 "$base/local-thumb/f/ff/Foobar.svg/360px-Foobar.svg.png",
645 "$base/local-thumb/f/ff/Foobar.svg/4000px-Foobar.svg.png",
646 "$base/local-thumb/f/ff/Foobar.svg/langde-180px-Foobar.svg.png",
647 "$base/local-thumb/f/ff/Foobar.svg/langde-270px-Foobar.svg.png",
648 "$base/local-thumb/f/ff/Foobar.svg/langde-360px-Foobar.svg.png",
649
650 "$base/local-public/math/f/a/5/fa50b8b616463173474302ca3e63586b.png",
651 ]
652 );
653 }
654
655 /**
656 * Delete the specified files, if they exist.
657 * @param array $files Full paths to files to delete.
658 */
659 private static function deleteFiles( $files ) {
660 $backend = RepoGroup::singleton()->getLocalRepo()->getBackend();
661 foreach ( $files as $file ) {
662 $backend->delete( [ 'src' => $file ], [ 'force' => 1 ] );
663 }
664 foreach ( $files as $file ) {
665 $tmp = FileBackend::parentStoragePath( $file );
666 while ( $tmp ) {
667 if ( !$backend->clean( [ 'dir' => $tmp ] )->isOK() ) {
668 break;
669 }
670 $tmp = FileBackend::parentStoragePath( $tmp );
671 }
672 }
673 }
674
675 protected function getBaseDir() {
676 return 'mwstore://local-backend';
677 }
678
679 public function parserTestProvider() {
680 if ( $this->file === false ) {
681 global $wgParserTestFiles;
682 $this->file = $wgParserTestFiles[0];
683 }
684
685 return new TestFileDataProvider( $this->file, $this );
686 }
687
688 /**
689 * Set the file from whose tests will be run by this instance
690 * @param string $filename
691 */
692 public function setParserTestFile( $filename ) {
693 $this->file = $filename;
694 }
695
696 /**
697 * @group medium
698 * @group ParserTests
699 * @dataProvider parserTestProvider
700 * @param string $desc
701 * @param string $input
702 * @param string $result
703 * @param array $opts
704 * @param array $config
705 */
706 public function testParserTest( $desc, $input, $result, $opts, $config ) {
707 if ( $this->regex != '' && !preg_match( '/' . $this->regex . '/', $desc ) ) {
708 $this->assertTrue( true ); // XXX: don't flood output with "test made no assertions"
709 // $this->markTestSkipped( 'Filtered out by the user' );
710 $this->teardownGlobals();
711 return;
712 }
713
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->teardownGlobals();
719 $this->markTestSkipped( "Main namespace does not support wikitext,"
720 . "skipping parser test: $desc" );
721 }
722
723 wfDebug( "Running parser test: $desc\n" );
724
725 $opts = $this->parseOptions( $opts );
726 $context = $this->setupGlobals( $opts, $config );
727
728 $user = $context->getUser();
729 $options = ParserOptions::newFromContext( $context );
730
731 if ( isset( $opts['title'] ) ) {
732 $titleText = $opts['title'];
733 } else {
734 $titleText = 'Parser test';
735 }
736
737 $local = isset( $opts['local'] );
738 $preprocessor = isset( $opts['preprocessor'] ) ? $opts['preprocessor'] : null;
739 $parser = $this->getParser( $preprocessor );
740
741 $title = Title::newFromText( $titleText );
742
743 # Parser test requiring math. Make sure texvc is executable
744 # or just skip such tests.
745 if ( isset( $opts['math'] ) || isset( $opts['texvc'] ) ) {
746 global $wgTexvc;
747
748 if ( !isset( $wgTexvc ) ) {
749 $this->teardownGlobals();
750 $this->markTestSkipped( "SKIPPED: \$wgTexvc is not set" );
751 } elseif ( !is_executable( $wgTexvc ) ) {
752 $this->teardownGlobals();
753 $this->markTestSkipped( "SKIPPED: texvc binary does not exist"
754 . " or is not executable.\n"
755 . "Current configuration is:\n\$wgTexvc = '$wgTexvc'" );
756 }
757 }
758
759 if ( isset( $opts['djvu'] ) ) {
760 if ( !$this->djVuSupport->isEnabled() ) {
761 $this->teardownGlobals();
762 $this->markTestSkipped( "SKIPPED: djvu binaries do not exist or are not executable.\n" );
763 }
764 }
765
766 if ( isset( $opts['tidy'] ) ) {
767 if ( !$this->tidySupport->isEnabled() ) {
768 $this->teardownGlobals();
769 $this->markTestSkipped( "SKIPPED: tidy extension is not installed.\n" );
770 } else {
771 $options->setTidy( true );
772 }
773 }
774
775 if ( isset( $opts['pst'] ) ) {
776 $out = $parser->preSaveTransform( $input, $title, $user, $options );
777 } elseif ( isset( $opts['msg'] ) ) {
778 $out = $parser->transformMsg( $input, $options, $title );
779 } elseif ( isset( $opts['section'] ) ) {
780 $section = $opts['section'];
781 $out = $parser->getSection( $input, $section );
782 } elseif ( isset( $opts['replace'] ) ) {
783 $section = $opts['replace'][0];
784 $replace = $opts['replace'][1];
785 $out = $parser->replaceSection( $input, $section, $replace );
786 } elseif ( isset( $opts['comment'] ) ) {
787 $out = Linker::formatComment( $input, $title, $local );
788 } elseif ( isset( $opts['preload'] ) ) {
789 $out = $parser->getPreloadText( $input, $title, $options );
790 } else {
791 $output = $parser->parse( $input, $title, $options, true, true, 1337 );
792 $output->setTOCEnabled( !isset( $opts['notoc'] ) );
793 $out = $output->getText();
794 if ( isset( $opts['tidy'] ) ) {
795 $out = preg_replace( '/\s+$/', '', $out );
796 }
797
798 if ( isset( $opts['showtitle'] ) ) {
799 if ( $output->getTitleText() ) {
800 $title = $output->getTitleText();
801 }
802
803 $out = "$title\n$out";
804 }
805
806 if ( isset( $opts['showindicators'] ) ) {
807 $indicators = '';
808 foreach ( $output->getIndicators() as $id => $content ) {
809 $indicators .= "$id=$content\n";
810 }
811 $out = $indicators . $out;
812 }
813
814 if ( isset( $opts['ill'] ) ) {
815 $out = implode( ' ', $output->getLanguageLinks() );
816 } elseif ( isset( $opts['cat'] ) ) {
817 $outputPage = $context->getOutput();
818 $outputPage->addCategoryLinks( $output->getCategories() );
819 $cats = $outputPage->getCategoryLinks();
820
821 if ( isset( $cats['normal'] ) ) {
822 $out = implode( ' ', $cats['normal'] );
823 } else {
824 $out = '';
825 }
826 }
827 $parser->mPreprocessor = null;
828 }
829
830 $this->teardownGlobals();
831
832 $this->assertEquals( $result, $out, $desc );
833 }
834
835 /**
836 * Get a Parser object
837 * @param Preprocessor $preprocessor
838 * @return Parser
839 */
840 function getParser( $preprocessor = null ) {
841 global $wgParserConf;
842
843 $class = $wgParserConf['class'];
844 $parser = new $class( [ 'preprocessorClass' => $preprocessor ] + $wgParserConf );
845
846 Hooks::run( 'ParserTestParser', [ &$parser ] );
847
848 return $parser;
849 }
850
851 // Various action functions
852
853 public function addArticle( $name, $text, $line ) {
854 self::$articles[$name] = [ $text, $line ];
855 }
856
857 public function publishTestArticles() {
858 if ( empty( self::$articles ) ) {
859 return;
860 }
861
862 foreach ( self::$articles as $name => $info ) {
863 list( $text, $line ) = $info;
864 ParserTestRunner::addArticle( $name, $text, $line, 'ignoreduplicate' );
865 }
866 }
867
868 /**
869 * Steal a callback function from the primary parser, save it for
870 * application to our scary parser. If the hook is not installed,
871 * abort processing of this file.
872 *
873 * @param string $name
874 * @return bool True if tag hook is present
875 */
876 public function requireHook( $name ) {
877 global $wgParser;
878 $wgParser->firstCallInit(); // make sure hooks are loaded.
879 return isset( $wgParser->mTagHooks[$name] );
880 }
881
882 public function requireFunctionHook( $name ) {
883 global $wgParser;
884 $wgParser->firstCallInit(); // make sure hooks are loaded.
885 return isset( $wgParser->mFunctionHooks[$name] );
886 }
887
888 public function requireTransparentHook( $name ) {
889 global $wgParser;
890 $wgParser->firstCallInit(); // make sure hooks are loaded.
891 return isset( $wgParser->mTransparentTagHooks[$name] );
892 }
893
894 // Various "cleanup" functions
895
896 /**
897 * Remove last character if it is a newline
898 * @param string $s
899 * @return string
900 */
901 public function removeEndingNewline( $s ) {
902 if ( substr( $s, -1 ) === "\n" ) {
903 return substr( $s, 0, -1 );
904 } else {
905 return $s;
906 }
907 }
908
909 // Test options parser functions
910
911 protected function parseOptions( $instring ) {
912 $opts = [];
913 // foo
914 // foo=bar
915 // foo="bar baz"
916 // foo=[[bar baz]]
917 // foo=bar,"baz quux"
918 $regex = '/\b
919 ([\w-]+) # Key
920 \b
921 (?:\s*
922 = # First sub-value
923 \s*
924 (
925 "
926 [^"]* # Quoted val
927 "
928 |
929 \[\[
930 [^]]* # Link target
931 \]\]
932 |
933 [\w-]+ # Plain word
934 )
935 (?:\s*
936 , # Sub-vals 1..N
937 \s*
938 (
939 "[^"]*" # Quoted val
940 |
941 \[\[[^]]*\]\] # Link target
942 |
943 [\w-]+ # Plain word
944 )
945 )*
946 )?
947 /x';
948
949 if ( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER ) ) {
950 foreach ( $matches as $bits ) {
951 array_shift( $bits );
952 $key = strtolower( array_shift( $bits ) );
953 if ( count( $bits ) == 0 ) {
954 $opts[$key] = true;
955 } elseif ( count( $bits ) == 1 ) {
956 $opts[$key] = $this->cleanupOption( array_shift( $bits ) );
957 } else {
958 // Array!
959 $opts[$key] = array_map( [ $this, 'cleanupOption' ], $bits );
960 }
961 }
962 }
963
964 return $opts;
965 }
966
967 protected function cleanupOption( $opt ) {
968 if ( substr( $opt, 0, 1 ) == '"' ) {
969 return substr( $opt, 1, -1 );
970 }
971
972 if ( substr( $opt, 0, 2 ) == '[[' ) {
973 return substr( $opt, 2, -2 );
974 }
975
976 return $opt;
977 }
978
979 /**
980 * Use a regex to find out the value of an option
981 * @param string $key Name of option val to retrieve
982 * @param array $opts Options array to look in
983 * @param mixed $default Default value returned if not found
984 * @return mixed
985 */
986 protected static function getOptionValue( $key, $opts, $default ) {
987 $key = strtolower( $key );
988
989 if ( isset( $opts[$key] ) ) {
990 return $opts[$key];
991 } else {
992 return $default;
993 }
994 }
995 }