ad84c207b20037ae1d6447205cbca2084a0f007c
[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 $this->teardownGlobals();
716 return;
717 }
718
719 if ( !$this->isWikitextNS( NS_MAIN ) ) {
720 // parser tests frequently assume that the main namespace contains wikitext.
721 // @todo When setting up pages, force the content model. Only skip if
722 // $wgtContentModelUseDB is false.
723 $this->teardownGlobals();
724 $this->markTestSkipped( "Main namespace does not support wikitext,"
725 . "skipping parser test: $desc" );
726 }
727
728 wfDebug( "Running parser test: $desc\n" );
729
730 $opts = $this->parseOptions( $opts );
731 $context = $this->setupGlobals( $opts, $config );
732
733 $user = $context->getUser();
734 $options = ParserOptions::newFromContext( $context );
735
736 if ( isset( $opts['title'] ) ) {
737 $titleText = $opts['title'];
738 } else {
739 $titleText = 'Parser test';
740 }
741
742 $local = isset( $opts['local'] );
743 $preprocessor = isset( $opts['preprocessor'] ) ? $opts['preprocessor'] : null;
744 $parser = $this->getParser( $preprocessor );
745
746 $title = Title::newFromText( $titleText );
747
748 # Parser test requiring math. Make sure texvc is executable
749 # or just skip such tests.
750 if ( isset( $opts['math'] ) || isset( $opts['texvc'] ) ) {
751 global $wgTexvc;
752
753 if ( !isset( $wgTexvc ) ) {
754 $this->teardownGlobals();
755 $this->markTestSkipped( "SKIPPED: \$wgTexvc is not set" );
756 } elseif ( !is_executable( $wgTexvc ) ) {
757 $this->teardownGlobals();
758 $this->markTestSkipped( "SKIPPED: texvc binary does not exist"
759 . " or is not executable.\n"
760 . "Current configuration is:\n\$wgTexvc = '$wgTexvc'" );
761 }
762 }
763
764 if ( isset( $opts['djvu'] ) ) {
765 if ( !$this->djVuSupport->isEnabled() ) {
766 $this->teardownGlobals();
767 $this->markTestSkipped( "SKIPPED: djvu binaries do not exist or are not executable.\n" );
768 }
769 }
770
771 if ( isset( $opts['tidy'] ) ) {
772 if ( !$this->tidySupport->isEnabled() ) {
773 $this->teardownGlobals();
774 $this->markTestSkipped( "SKIPPED: tidy extension is not installed.\n" );
775 } else {
776 $options->setTidy( true );
777 }
778 }
779
780 if ( isset( $opts['pst'] ) ) {
781 $out = $parser->preSaveTransform( $input, $title, $user, $options );
782 } elseif ( isset( $opts['msg'] ) ) {
783 $out = $parser->transformMsg( $input, $options, $title );
784 } elseif ( isset( $opts['section'] ) ) {
785 $section = $opts['section'];
786 $out = $parser->getSection( $input, $section );
787 } elseif ( isset( $opts['replace'] ) ) {
788 $section = $opts['replace'][0];
789 $replace = $opts['replace'][1];
790 $out = $parser->replaceSection( $input, $section, $replace );
791 } elseif ( isset( $opts['comment'] ) ) {
792 $out = Linker::formatComment( $input, $title, $local );
793 } elseif ( isset( $opts['preload'] ) ) {
794 $out = $parser->getPreloadText( $input, $title, $options );
795 } else {
796 $output = $parser->parse( $input, $title, $options, true, true, 1337 );
797 $output->setTOCEnabled( !isset( $opts['notoc'] ) );
798 $out = $output->getText();
799 if ( isset( $opts['tidy'] ) ) {
800 $out = preg_replace( '/\s+$/', '', $out );
801 }
802
803 if ( isset( $opts['showtitle'] ) ) {
804 if ( $output->getTitleText() ) {
805 $title = $output->getTitleText();
806 }
807
808 $out = "$title\n$out";
809 }
810
811 if ( isset( $opts['showindicators'] ) ) {
812 $indicators = '';
813 foreach ( $output->getIndicators() as $id => $content ) {
814 $indicators .= "$id=$content\n";
815 }
816 $out = $indicators . $out;
817 }
818
819 if ( isset( $opts['ill'] ) ) {
820 $out = implode( ' ', $output->getLanguageLinks() );
821 } elseif ( isset( $opts['cat'] ) ) {
822 $outputPage = $context->getOutput();
823 $outputPage->addCategoryLinks( $output->getCategories() );
824 $cats = $outputPage->getCategoryLinks();
825
826 if ( isset( $cats['normal'] ) ) {
827 $out = implode( ' ', $cats['normal'] );
828 } else {
829 $out = '';
830 }
831 }
832 $parser->mPreprocessor = null;
833 }
834
835 $this->teardownGlobals();
836
837 $this->assertEquals( $result, $out, $desc );
838 }
839
840 /**
841 * Run a fuzz test series
842 * Draw input from a set of test files
843 *
844 * @todo fixme Needs some work to not eat memory until the world explodes
845 *
846 * @group ParserFuzz
847 */
848 public function testFuzzTests() {
849 global $wgParserTestFiles;
850
851 $files = $wgParserTestFiles;
852
853 if ( $this->getCliArg( 'file' ) ) {
854 $files = [ $this->getCliArg( 'file' ) ];
855 }
856
857 $dict = $this->getFuzzInput( $files );
858 $dictSize = strlen( $dict );
859 $logMaxLength = log( $this->maxFuzzTestLength );
860
861 ini_set( 'memory_limit', $this->memoryLimit * 1048576 );
862
863 $user = new User;
864 $opts = ParserOptions::newFromUser( $user );
865 $title = Title::makeTitle( NS_MAIN, 'Parser_test' );
866
867 $id = 1;
868
869 while ( true ) {
870
871 // Generate test input
872 mt_srand( ++$this->fuzzSeed );
873 $totalLength = mt_rand( 1, $this->maxFuzzTestLength );
874 $input = '';
875
876 while ( strlen( $input ) < $totalLength ) {
877 $logHairLength = mt_rand( 0, 1000000 ) / 1000000 * $logMaxLength;
878 $hairLength = min( intval( exp( $logHairLength ) ), $dictSize );
879 $offset = mt_rand( 0, $dictSize - $hairLength );
880 $input .= substr( $dict, $offset, $hairLength );
881 }
882
883 $this->setupGlobals();
884 $parser = $this->getParser();
885
886 // Run the test
887 try {
888 $parser->parse( $input, $title, $opts );
889 $this->assertTrue( true, "Test $id, fuzz seed {$this->fuzzSeed}" );
890 } catch ( Exception $exception ) {
891 $input_dump = sprintf( "string(%d) \"%s\"\n", strlen( $input ), $input );
892
893 $this->assertTrue( false, "Test $id, fuzz seed {$this->fuzzSeed}. \n\n" .
894 "Input: $input_dump\n\nError: {$exception->getMessage()}\n\n" .
895 "Backtrace: {$exception->getTraceAsString()}" );
896 }
897
898 $this->teardownGlobals();
899 $parser->__destruct();
900
901 if ( $id % 100 == 0 ) {
902 $usage = intval( memory_get_usage( true ) / $this->memoryLimit / 1048576 * 100 );
903 // echo "{$this->fuzzSeed}: $numSuccess/$numTotal (mem: $usage%)\n";
904 if ( $usage > 90 ) {
905 $ret = "Out of memory:\n";
906 $memStats = $this->getMemoryBreakdown();
907
908 foreach ( $memStats as $name => $usage ) {
909 $ret .= "$name: $usage\n";
910 }
911
912 throw new MWException( $ret );
913 }
914 }
915
916 $id++;
917 }
918 }
919
920 // Various getter functions
921
922 /**
923 * Get an input dictionary from a set of parser test files
924 * @param array $filenames
925 * @return string
926 */
927 function getFuzzInput( $filenames ) {
928 $dict = '';
929
930 foreach ( $filenames as $filename ) {
931 $contents = file_get_contents( $filename );
932 preg_match_all( '/!!\s*input\n(.*?)\n!!\s*result/s', $contents, $matches );
933
934 foreach ( $matches[1] as $match ) {
935 $dict .= $match . "\n";
936 }
937 }
938
939 return $dict;
940 }
941
942 /**
943 * Get a memory usage breakdown
944 * @return array
945 */
946 function getMemoryBreakdown() {
947 $memStats = [];
948
949 foreach ( $GLOBALS as $name => $value ) {
950 $memStats['$' . $name] = strlen( serialize( $value ) );
951 }
952
953 $classes = get_declared_classes();
954
955 foreach ( $classes as $class ) {
956 $rc = new ReflectionClass( $class );
957 $props = $rc->getStaticProperties();
958 $memStats[$class] = strlen( serialize( $props ) );
959 $methods = $rc->getMethods();
960
961 foreach ( $methods as $method ) {
962 $memStats[$class] += strlen( serialize( $method->getStaticVariables() ) );
963 }
964 }
965
966 $functions = get_defined_functions();
967
968 foreach ( $functions['user'] as $function ) {
969 $rf = new ReflectionFunction( $function );
970 $memStats["$function()"] = strlen( serialize( $rf->getStaticVariables() ) );
971 }
972
973 asort( $memStats );
974
975 return $memStats;
976 }
977
978 /**
979 * Get a Parser object
980 * @param Preprocessor $preprocessor
981 * @return Parser
982 */
983 function getParser( $preprocessor = null ) {
984 global $wgParserConf;
985
986 $class = $wgParserConf['class'];
987 $parser = new $class( [ 'preprocessorClass' => $preprocessor ] + $wgParserConf );
988
989 Hooks::run( 'ParserTestParser', [ &$parser ] );
990
991 return $parser;
992 }
993
994 // Various action functions
995
996 public function addArticle( $name, $text, $line ) {
997 self::$articles[$name] = [ $text, $line ];
998 }
999
1000 public function publishTestArticles() {
1001 if ( empty( self::$articles ) ) {
1002 return;
1003 }
1004
1005 foreach ( self::$articles as $name => $info ) {
1006 list( $text, $line ) = $info;
1007 ParserTest::addArticle( $name, $text, $line, 'ignoreduplicate' );
1008 }
1009 }
1010
1011 /**
1012 * Steal a callback function from the primary parser, save it for
1013 * application to our scary parser. If the hook is not installed,
1014 * abort processing of this file.
1015 *
1016 * @param string $name
1017 * @return bool True if tag hook is present
1018 */
1019 public function requireHook( $name ) {
1020 global $wgParser;
1021 $wgParser->firstCallInit(); // make sure hooks are loaded.
1022 return isset( $wgParser->mTagHooks[$name] );
1023 }
1024
1025 public function requireFunctionHook( $name ) {
1026 global $wgParser;
1027 $wgParser->firstCallInit(); // make sure hooks are loaded.
1028 return isset( $wgParser->mFunctionHooks[$name] );
1029 }
1030
1031 public function requireTransparentHook( $name ) {
1032 global $wgParser;
1033 $wgParser->firstCallInit(); // make sure hooks are loaded.
1034 return isset( $wgParser->mTransparentTagHooks[$name] );
1035 }
1036
1037 // Various "cleanup" functions
1038
1039 /**
1040 * Remove last character if it is a newline
1041 * @param string $s
1042 * @return string
1043 */
1044 public function removeEndingNewline( $s ) {
1045 if ( substr( $s, -1 ) === "\n" ) {
1046 return substr( $s, 0, -1 );
1047 } else {
1048 return $s;
1049 }
1050 }
1051
1052 // Test options parser functions
1053
1054 protected function parseOptions( $instring ) {
1055 $opts = [];
1056 // foo
1057 // foo=bar
1058 // foo="bar baz"
1059 // foo=[[bar baz]]
1060 // foo=bar,"baz quux"
1061 $regex = '/\b
1062 ([\w-]+) # Key
1063 \b
1064 (?:\s*
1065 = # First sub-value
1066 \s*
1067 (
1068 "
1069 [^"]* # Quoted val
1070 "
1071 |
1072 \[\[
1073 [^]]* # Link target
1074 \]\]
1075 |
1076 [\w-]+ # Plain word
1077 )
1078 (?:\s*
1079 , # Sub-vals 1..N
1080 \s*
1081 (
1082 "[^"]*" # Quoted val
1083 |
1084 \[\[[^]]*\]\] # Link target
1085 |
1086 [\w-]+ # Plain word
1087 )
1088 )*
1089 )?
1090 /x';
1091
1092 if ( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER ) ) {
1093 foreach ( $matches as $bits ) {
1094 array_shift( $bits );
1095 $key = strtolower( array_shift( $bits ) );
1096 if ( count( $bits ) == 0 ) {
1097 $opts[$key] = true;
1098 } elseif ( count( $bits ) == 1 ) {
1099 $opts[$key] = $this->cleanupOption( array_shift( $bits ) );
1100 } else {
1101 // Array!
1102 $opts[$key] = array_map( [ $this, 'cleanupOption' ], $bits );
1103 }
1104 }
1105 }
1106
1107 return $opts;
1108 }
1109
1110 protected function cleanupOption( $opt ) {
1111 if ( substr( $opt, 0, 1 ) == '"' ) {
1112 return substr( $opt, 1, -1 );
1113 }
1114
1115 if ( substr( $opt, 0, 2 ) == '[[' ) {
1116 return substr( $opt, 2, -2 );
1117 }
1118
1119 return $opt;
1120 }
1121
1122 /**
1123 * Use a regex to find out the value of an option
1124 * @param string $key Name of option val to retrieve
1125 * @param array $opts Options array to look in
1126 * @param mixed $default Default value returned if not found
1127 * @return mixed
1128 */
1129 protected static function getOptionValue( $key, $opts, $default ) {
1130 $key = strtolower( $key );
1131
1132 if ( isset( $opts[$key] ) ) {
1133 return $opts[$key];
1134 } else {
1135 return $default;
1136 }
1137 }
1138 }