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