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