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