Merge "Enforce MW_NO_SESSION, add MW_NO_SESSION_HANDLER"
[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['wgScript'] = '/index.php';
75 $tmpGlobals['wgScriptPath'] = '/';
76 $tmpGlobals['wgArticlePath'] = '/wiki/$1';
77 $tmpGlobals['wgActionPaths'] = [];
78 $tmpGlobals['wgVariantArticlePath'] = false;
79 $tmpGlobals['wgExtensionAssetsPath'] = '/extensions';
80 $tmpGlobals['wgStylePath'] = '/skins';
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['wgWellFormedXml'] = true;
104 $tmpGlobals['wgAllowMicrodataAttributes'] = 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 addDBData() {
214 $this->tablesUsed[] = 'site_stats';
215 # disabled for performance
216 # $this->tablesUsed[] = 'image';
217
218 # Update certain things in site_stats
219 $this->db->insert( 'site_stats',
220 [ 'ss_row_id' => 1, 'ss_images' => 2, 'ss_good_articles' => 1 ],
221 __METHOD__
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 'wgMathDirectory' => $uploadDir . '/math',
437 'wgDefaultLanguageVariant' => $variant,
438 'wgLinkHolderBatchSize' => $linkHolderBatchSize,
439 'wgUseTidy' => isset( $opts['tidy'] ),
440 ];
441
442 if ( $config ) {
443 $configLines = explode( "\n", $config );
444
445 foreach ( $configLines as $line ) {
446 list( $var, $value ) = explode( '=', $line, 2 );
447
448 $settings[$var] = eval( "return $value;" ); // ???
449 }
450 }
451
452 $this->savedGlobals = [];
453
454 /** @since 1.20 */
455 Hooks::run( 'ParserTestGlobals', [ &$settings ] );
456
457 $langObj = Language::factory( $lang );
458 $settings['wgContLang'] = $langObj;
459 $settings['wgLang'] = $langObj;
460
461 $context = new RequestContext();
462 $settings['wgOut'] = $context->getOutput();
463 $settings['wgUser'] = $context->getUser();
464 $settings['wgRequest'] = $context->getRequest();
465
466 // We (re)set $wgThumbLimits to a single-element array above.
467 $context->getUser()->setOption( 'thumbsize', 0 );
468
469 foreach ( $settings as $var => $val ) {
470 if ( array_key_exists( $var, $GLOBALS ) ) {
471 $this->savedGlobals[$var] = $GLOBALS[$var];
472 }
473
474 $GLOBALS[$var] = $val;
475 }
476
477 MWTidy::destroySingleton();
478 MagicWord::clearCache();
479
480 # The entries saved into RepoGroup cache with previous globals will be wrong.
481 RepoGroup::destroySingleton();
482 FileBackendGroup::destroySingleton();
483
484 # Create dummy files in storage
485 $this->setupUploads();
486
487 # Publish the articles after we have the final language set
488 $this->publishTestArticles();
489
490 MessageCache::destroyInstance();
491
492 return $context;
493 }
494
495 /**
496 * Get an FS upload directory (only applies to FSFileBackend)
497 *
498 * @return string The directory
499 */
500 protected function getUploadDir() {
501 if ( $this->keepUploads ) {
502 // Don't use getNewTempDirectory() as this is meant to persist
503 $dir = wfTempDir() . '/mwParser-images';
504
505 if ( is_dir( $dir ) ) {
506 return $dir;
507 }
508 } else {
509 $dir = $this->getNewTempDirectory();
510 }
511
512 if ( file_exists( $dir ) ) {
513 wfDebug( "Already exists!\n" );
514
515 return $dir;
516 }
517
518 return $dir;
519 }
520
521 /**
522 * Create a dummy uploads directory which will contain a couple
523 * of files in order to pass existence tests.
524 *
525 * @return string The directory
526 */
527 protected function setupUploads() {
528 global $IP;
529
530 $base = $this->getBaseDir();
531 $backend = RepoGroup::singleton()->getLocalRepo()->getBackend();
532 $backend->prepare( [ 'dir' => "$base/local-public/3/3a" ] );
533 $backend->store( [
534 'src' => "$IP/tests/phpunit/data/parser/headbg.jpg",
535 'dst' => "$base/local-public/3/3a/Foobar.jpg"
536 ] );
537 $backend->prepare( [ 'dir' => "$base/local-public/e/ea" ] );
538 $backend->store( [
539 'src' => "$IP/tests/phpunit/data/parser/wiki.png",
540 'dst' => "$base/local-public/e/ea/Thumb.png"
541 ] );
542 $backend->prepare( [ 'dir' => "$base/local-public/0/09" ] );
543 $backend->store( [
544 'src' => "$IP/tests/phpunit/data/parser/headbg.jpg",
545 'dst' => "$base/local-public/0/09/Bad.jpg"
546 ] );
547 $backend->prepare( [ 'dir' => "$base/local-public/5/5f" ] );
548 $backend->store( [
549 'src' => "$IP/tests/phpunit/data/parser/LoremIpsum.djvu",
550 'dst' => "$base/local-public/5/5f/LoremIpsum.djvu"
551 ] );
552
553 // No helpful SVG file to copy, so make one ourselves
554 $data = '<?xml version="1.0" encoding="utf-8"?>' .
555 '<svg xmlns="http://www.w3.org/2000/svg"' .
556 ' version="1.1" width="240" height="180"/>';
557
558 $backend->prepare( [ 'dir' => "$base/local-public/f/ff" ] );
559 $backend->quickCreate( [
560 'content' => $data, 'dst' => "$base/local-public/f/ff/Foobar.svg"
561 ] );
562 }
563
564 /**
565 * Restore default values and perform any necessary clean-up
566 * after each test runs.
567 */
568 protected function teardownGlobals() {
569 $this->teardownUploads();
570
571 foreach ( $this->savedGlobals as $var => $val ) {
572 $GLOBALS[$var] = $val;
573 }
574 }
575
576 /**
577 * Remove the dummy uploads directory
578 */
579 private function teardownUploads() {
580 if ( $this->keepUploads ) {
581 return;
582 }
583
584 $backend = RepoGroup::singleton()->getLocalRepo()->getBackend();
585 if ( $backend instanceof MockFileBackend ) {
586 # In memory backend, so dont bother cleaning them up.
587 return;
588 }
589
590 $base = $this->getBaseDir();
591 // delete the files first, then the dirs.
592 self::deleteFiles(
593 [
594 "$base/local-public/3/3a/Foobar.jpg",
595 "$base/local-thumb/3/3a/Foobar.jpg/1000px-Foobar.jpg",
596 "$base/local-thumb/3/3a/Foobar.jpg/100px-Foobar.jpg",
597 "$base/local-thumb/3/3a/Foobar.jpg/120px-Foobar.jpg",
598 "$base/local-thumb/3/3a/Foobar.jpg/1280px-Foobar.jpg",
599 "$base/local-thumb/3/3a/Foobar.jpg/137px-Foobar.jpg",
600 "$base/local-thumb/3/3a/Foobar.jpg/1500px-Foobar.jpg",
601 "$base/local-thumb/3/3a/Foobar.jpg/177px-Foobar.jpg",
602 "$base/local-thumb/3/3a/Foobar.jpg/180px-Foobar.jpg",
603 "$base/local-thumb/3/3a/Foobar.jpg/200px-Foobar.jpg",
604 "$base/local-thumb/3/3a/Foobar.jpg/206px-Foobar.jpg",
605 "$base/local-thumb/3/3a/Foobar.jpg/20px-Foobar.jpg",
606 "$base/local-thumb/3/3a/Foobar.jpg/220px-Foobar.jpg",
607 "$base/local-thumb/3/3a/Foobar.jpg/265px-Foobar.jpg",
608 "$base/local-thumb/3/3a/Foobar.jpg/270px-Foobar.jpg",
609 "$base/local-thumb/3/3a/Foobar.jpg/274px-Foobar.jpg",
610 "$base/local-thumb/3/3a/Foobar.jpg/300px-Foobar.jpg",
611 "$base/local-thumb/3/3a/Foobar.jpg/30px-Foobar.jpg",
612 "$base/local-thumb/3/3a/Foobar.jpg/330px-Foobar.jpg",
613 "$base/local-thumb/3/3a/Foobar.jpg/353px-Foobar.jpg",
614 "$base/local-thumb/3/3a/Foobar.jpg/360px-Foobar.jpg",
615 "$base/local-thumb/3/3a/Foobar.jpg/400px-Foobar.jpg",
616 "$base/local-thumb/3/3a/Foobar.jpg/40px-Foobar.jpg",
617 "$base/local-thumb/3/3a/Foobar.jpg/440px-Foobar.jpg",
618 "$base/local-thumb/3/3a/Foobar.jpg/442px-Foobar.jpg",
619 "$base/local-thumb/3/3a/Foobar.jpg/450px-Foobar.jpg",
620 "$base/local-thumb/3/3a/Foobar.jpg/50px-Foobar.jpg",
621 "$base/local-thumb/3/3a/Foobar.jpg/600px-Foobar.jpg",
622 "$base/local-thumb/3/3a/Foobar.jpg/640px-Foobar.jpg",
623 "$base/local-thumb/3/3a/Foobar.jpg/70px-Foobar.jpg",
624 "$base/local-thumb/3/3a/Foobar.jpg/75px-Foobar.jpg",
625 "$base/local-thumb/3/3a/Foobar.jpg/960px-Foobar.jpg",
626
627 "$base/local-public/e/ea/Thumb.png",
628
629 "$base/local-public/0/09/Bad.jpg",
630
631 "$base/local-public/5/5f/LoremIpsum.djvu",
632 "$base/local-thumb/5/5f/LoremIpsum.djvu/page2-2480px-LoremIpsum.djvu.jpg",
633 "$base/local-thumb/5/5f/LoremIpsum.djvu/page2-3720px-LoremIpsum.djvu.jpg",
634 "$base/local-thumb/5/5f/LoremIpsum.djvu/page2-4960px-LoremIpsum.djvu.jpg",
635
636 "$base/local-public/f/ff/Foobar.svg",
637 "$base/local-thumb/f/ff/Foobar.svg/180px-Foobar.svg.png",
638 "$base/local-thumb/f/ff/Foobar.svg/2000px-Foobar.svg.png",
639 "$base/local-thumb/f/ff/Foobar.svg/270px-Foobar.svg.png",
640 "$base/local-thumb/f/ff/Foobar.svg/3000px-Foobar.svg.png",
641 "$base/local-thumb/f/ff/Foobar.svg/360px-Foobar.svg.png",
642 "$base/local-thumb/f/ff/Foobar.svg/4000px-Foobar.svg.png",
643 "$base/local-thumb/f/ff/Foobar.svg/langde-180px-Foobar.svg.png",
644 "$base/local-thumb/f/ff/Foobar.svg/langde-270px-Foobar.svg.png",
645 "$base/local-thumb/f/ff/Foobar.svg/langde-360px-Foobar.svg.png",
646
647 "$base/local-public/math/f/a/5/fa50b8b616463173474302ca3e63586b.png",
648 ]
649 );
650 }
651
652 /**
653 * Delete the specified files, if they exist.
654 * @param array $files Full paths to files to delete.
655 */
656 private static function deleteFiles( $files ) {
657 $backend = RepoGroup::singleton()->getLocalRepo()->getBackend();
658 foreach ( $files as $file ) {
659 $backend->delete( [ 'src' => $file ], [ 'force' => 1 ] );
660 }
661 foreach ( $files as $file ) {
662 $tmp = FileBackend::parentStoragePath( $file );
663 while ( $tmp ) {
664 if ( !$backend->clean( [ 'dir' => $tmp ] )->isOK() ) {
665 break;
666 }
667 $tmp = FileBackend::parentStoragePath( $tmp );
668 }
669 }
670 }
671
672 protected function getBaseDir() {
673 return 'mwstore://local-backend';
674 }
675
676 public function parserTestProvider() {
677 if ( $this->file === false ) {
678 global $wgParserTestFiles;
679 $this->file = $wgParserTestFiles[0];
680 }
681
682 return new TestFileIterator( $this->file, $this );
683 }
684
685 /**
686 * Set the file from whose tests will be run by this instance
687 * @param string $filename
688 */
689 public function setParserTestFile( $filename ) {
690 $this->file = $filename;
691 }
692
693 /**
694 * @group medium
695 * @group ParserTests
696 * @dataProvider parserTestProvider
697 * @param string $desc
698 * @param string $input
699 * @param string $result
700 * @param array $opts
701 * @param array $config
702 */
703 public function testParserTest( $desc, $input, $result, $opts, $config ) {
704 if ( $this->regex != '' && !preg_match( '/' . $this->regex . '/', $desc ) ) {
705 $this->assertTrue( true ); // XXX: don't flood output with "test made no assertions"
706 // $this->markTestSkipped( 'Filtered out by the user' );
707 return;
708 }
709
710 if ( !$this->isWikitextNS( NS_MAIN ) ) {
711 // parser tests frequently assume that the main namespace contains wikitext.
712 // @todo When setting up pages, force the content model. Only skip if
713 // $wgtContentModelUseDB is false.
714 $this->markTestSkipped( "Main namespace does not support wikitext,"
715 . "skipping parser test: $desc" );
716 }
717
718 wfDebug( "Running parser test: $desc\n" );
719
720 $opts = $this->parseOptions( $opts );
721 $context = $this->setupGlobals( $opts, $config );
722
723 $user = $context->getUser();
724 $options = ParserOptions::newFromContext( $context );
725
726 if ( isset( $opts['title'] ) ) {
727 $titleText = $opts['title'];
728 } else {
729 $titleText = 'Parser test';
730 }
731
732 $local = isset( $opts['local'] );
733 $preprocessor = isset( $opts['preprocessor'] ) ? $opts['preprocessor'] : null;
734 $parser = $this->getParser( $preprocessor );
735
736 $title = Title::newFromText( $titleText );
737
738 # Parser test requiring math. Make sure texvc is executable
739 # or just skip such tests.
740 if ( isset( $opts['math'] ) || isset( $opts['texvc'] ) ) {
741 global $wgTexvc;
742
743 if ( !isset( $wgTexvc ) ) {
744 $this->markTestSkipped( "SKIPPED: \$wgTexvc is not set" );
745 } elseif ( !is_executable( $wgTexvc ) ) {
746 $this->markTestSkipped( "SKIPPED: texvc binary does not exist"
747 . " or is not executable.\n"
748 . "Current configuration is:\n\$wgTexvc = '$wgTexvc'" );
749 }
750 }
751
752 if ( isset( $opts['djvu'] ) ) {
753 if ( !$this->djVuSupport->isEnabled() ) {
754 $this->markTestSkipped( "SKIPPED: djvu binaries do not exist or are not executable.\n" );
755 }
756 }
757
758 if ( isset( $opts['tidy'] ) ) {
759 if ( !$this->tidySupport->isEnabled() ) {
760 $this->markTestSkipped( "SKIPPED: tidy extension is not installed.\n" );
761 } else {
762 $options->setTidy( true );
763 }
764 }
765
766 if ( isset( $opts['pst'] ) ) {
767 $out = $parser->preSaveTransform( $input, $title, $user, $options );
768 } elseif ( isset( $opts['msg'] ) ) {
769 $out = $parser->transformMsg( $input, $options, $title );
770 } elseif ( isset( $opts['section'] ) ) {
771 $section = $opts['section'];
772 $out = $parser->getSection( $input, $section );
773 } elseif ( isset( $opts['replace'] ) ) {
774 $section = $opts['replace'][0];
775 $replace = $opts['replace'][1];
776 $out = $parser->replaceSection( $input, $section, $replace );
777 } elseif ( isset( $opts['comment'] ) ) {
778 $out = Linker::formatComment( $input, $title, $local );
779 } elseif ( isset( $opts['preload'] ) ) {
780 $out = $parser->getPreloadText( $input, $title, $options );
781 } else {
782 $output = $parser->parse( $input, $title, $options, true, true, 1337 );
783 $output->setTOCEnabled( !isset( $opts['notoc'] ) );
784 $out = $output->getText();
785 if ( isset( $opts['tidy'] ) ) {
786 $out = preg_replace( '/\s+$/', '', $out );
787 }
788
789 if ( isset( $opts['showtitle'] ) ) {
790 if ( $output->getTitleText() ) {
791 $title = $output->getTitleText();
792 }
793
794 $out = "$title\n$out";
795 }
796
797 if ( isset( $opts['showindicators'] ) ) {
798 $indicators = '';
799 foreach ( $output->getIndicators() as $id => $content ) {
800 $indicators .= "$id=$content\n";
801 }
802 $out = $indicators . $out;
803 }
804
805 if ( isset( $opts['ill'] ) ) {
806 $out = implode( ' ', $output->getLanguageLinks() );
807 } elseif ( isset( $opts['cat'] ) ) {
808 $outputPage = $context->getOutput();
809 $outputPage->addCategoryLinks( $output->getCategories() );
810 $cats = $outputPage->getCategoryLinks();
811
812 if ( isset( $cats['normal'] ) ) {
813 $out = implode( ' ', $cats['normal'] );
814 } else {
815 $out = '';
816 }
817 }
818 $parser->mPreprocessor = null;
819 }
820
821 $this->teardownGlobals();
822
823 $this->assertEquals( $result, $out, $desc );
824 }
825
826 /**
827 * Run a fuzz test series
828 * Draw input from a set of test files
829 *
830 * @todo fixme Needs some work to not eat memory until the world explodes
831 *
832 * @group ParserFuzz
833 */
834 public function testFuzzTests() {
835 global $wgParserTestFiles;
836
837 $files = $wgParserTestFiles;
838
839 if ( $this->getCliArg( 'file' ) ) {
840 $files = [ $this->getCliArg( 'file' ) ];
841 }
842
843 $dict = $this->getFuzzInput( $files );
844 $dictSize = strlen( $dict );
845 $logMaxLength = log( $this->maxFuzzTestLength );
846
847 ini_set( 'memory_limit', $this->memoryLimit * 1048576 );
848
849 $user = new User;
850 $opts = ParserOptions::newFromUser( $user );
851 $title = Title::makeTitle( NS_MAIN, 'Parser_test' );
852
853 $id = 1;
854
855 while ( true ) {
856
857 // Generate test input
858 mt_srand( ++$this->fuzzSeed );
859 $totalLength = mt_rand( 1, $this->maxFuzzTestLength );
860 $input = '';
861
862 while ( strlen( $input ) < $totalLength ) {
863 $logHairLength = mt_rand( 0, 1000000 ) / 1000000 * $logMaxLength;
864 $hairLength = min( intval( exp( $logHairLength ) ), $dictSize );
865 $offset = mt_rand( 0, $dictSize - $hairLength );
866 $input .= substr( $dict, $offset, $hairLength );
867 }
868
869 $this->setupGlobals();
870 $parser = $this->getParser();
871
872 // Run the test
873 try {
874 $parser->parse( $input, $title, $opts );
875 $this->assertTrue( true, "Test $id, fuzz seed {$this->fuzzSeed}" );
876 } catch ( Exception $exception ) {
877 $input_dump = sprintf( "string(%d) \"%s\"\n", strlen( $input ), $input );
878
879 $this->assertTrue( false, "Test $id, fuzz seed {$this->fuzzSeed}. \n\n" .
880 "Input: $input_dump\n\nError: {$exception->getMessage()}\n\n" .
881 "Backtrace: {$exception->getTraceAsString()}" );
882 }
883
884 $this->teardownGlobals();
885 $parser->__destruct();
886
887 if ( $id % 100 == 0 ) {
888 $usage = intval( memory_get_usage( true ) / $this->memoryLimit / 1048576 * 100 );
889 // echo "{$this->fuzzSeed}: $numSuccess/$numTotal (mem: $usage%)\n";
890 if ( $usage > 90 ) {
891 $ret = "Out of memory:\n";
892 $memStats = $this->getMemoryBreakdown();
893
894 foreach ( $memStats as $name => $usage ) {
895 $ret .= "$name: $usage\n";
896 }
897
898 throw new MWException( $ret );
899 }
900 }
901
902 $id++;
903 }
904 }
905
906 // Various getter functions
907
908 /**
909 * Get an input dictionary from a set of parser test files
910 * @param array $filenames
911 * @return string
912 */
913 function getFuzzInput( $filenames ) {
914 $dict = '';
915
916 foreach ( $filenames as $filename ) {
917 $contents = file_get_contents( $filename );
918 preg_match_all( '/!!\s*input\n(.*?)\n!!\s*result/s', $contents, $matches );
919
920 foreach ( $matches[1] as $match ) {
921 $dict .= $match . "\n";
922 }
923 }
924
925 return $dict;
926 }
927
928 /**
929 * Get a memory usage breakdown
930 * @return array
931 */
932 function getMemoryBreakdown() {
933 $memStats = [];
934
935 foreach ( $GLOBALS as $name => $value ) {
936 $memStats['$' . $name] = strlen( serialize( $value ) );
937 }
938
939 $classes = get_declared_classes();
940
941 foreach ( $classes as $class ) {
942 $rc = new ReflectionClass( $class );
943 $props = $rc->getStaticProperties();
944 $memStats[$class] = strlen( serialize( $props ) );
945 $methods = $rc->getMethods();
946
947 foreach ( $methods as $method ) {
948 $memStats[$class] += strlen( serialize( $method->getStaticVariables() ) );
949 }
950 }
951
952 $functions = get_defined_functions();
953
954 foreach ( $functions['user'] as $function ) {
955 $rf = new ReflectionFunction( $function );
956 $memStats["$function()"] = strlen( serialize( $rf->getStaticVariables() ) );
957 }
958
959 asort( $memStats );
960
961 return $memStats;
962 }
963
964 /**
965 * Get a Parser object
966 * @param Preprocessor $preprocessor
967 * @return Parser
968 */
969 function getParser( $preprocessor = null ) {
970 global $wgParserConf;
971
972 $class = $wgParserConf['class'];
973 $parser = new $class( [ 'preprocessorClass' => $preprocessor ] + $wgParserConf );
974
975 Hooks::run( 'ParserTestParser', [ &$parser ] );
976
977 return $parser;
978 }
979
980 // Various action functions
981
982 public function addArticle( $name, $text, $line ) {
983 self::$articles[$name] = [ $text, $line ];
984 }
985
986 public function publishTestArticles() {
987 if ( empty( self::$articles ) ) {
988 return;
989 }
990
991 foreach ( self::$articles as $name => $info ) {
992 list( $text, $line ) = $info;
993 ParserTest::addArticle( $name, $text, $line, 'ignoreduplicate' );
994 }
995 }
996
997 /**
998 * Steal a callback function from the primary parser, save it for
999 * application to our scary parser. If the hook is not installed,
1000 * abort processing of this file.
1001 *
1002 * @param string $name
1003 * @return bool True if tag hook is present
1004 */
1005 public function requireHook( $name ) {
1006 global $wgParser;
1007 $wgParser->firstCallInit(); // make sure hooks are loaded.
1008 return isset( $wgParser->mTagHooks[$name] );
1009 }
1010
1011 public function requireFunctionHook( $name ) {
1012 global $wgParser;
1013 $wgParser->firstCallInit(); // make sure hooks are loaded.
1014 return isset( $wgParser->mFunctionHooks[$name] );
1015 }
1016
1017 public function requireTransparentHook( $name ) {
1018 global $wgParser;
1019 $wgParser->firstCallInit(); // make sure hooks are loaded.
1020 return isset( $wgParser->mTransparentTagHooks[$name] );
1021 }
1022
1023 // Various "cleanup" functions
1024
1025 /**
1026 * Remove last character if it is a newline
1027 * @param string $s
1028 * @return string
1029 */
1030 public function removeEndingNewline( $s ) {
1031 if ( substr( $s, -1 ) === "\n" ) {
1032 return substr( $s, 0, -1 );
1033 } else {
1034 return $s;
1035 }
1036 }
1037
1038 // Test options parser functions
1039
1040 protected function parseOptions( $instring ) {
1041 $opts = [];
1042 // foo
1043 // foo=bar
1044 // foo="bar baz"
1045 // foo=[[bar baz]]
1046 // foo=bar,"baz quux"
1047 $regex = '/\b
1048 ([\w-]+) # Key
1049 \b
1050 (?:\s*
1051 = # First sub-value
1052 \s*
1053 (
1054 "
1055 [^"]* # Quoted val
1056 "
1057 |
1058 \[\[
1059 [^]]* # Link target
1060 \]\]
1061 |
1062 [\w-]+ # Plain word
1063 )
1064 (?:\s*
1065 , # Sub-vals 1..N
1066 \s*
1067 (
1068 "[^"]*" # Quoted val
1069 |
1070 \[\[[^]]*\]\] # Link target
1071 |
1072 [\w-]+ # Plain word
1073 )
1074 )*
1075 )?
1076 /x';
1077
1078 if ( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER ) ) {
1079 foreach ( $matches as $bits ) {
1080 array_shift( $bits );
1081 $key = strtolower( array_shift( $bits ) );
1082 if ( count( $bits ) == 0 ) {
1083 $opts[$key] = true;
1084 } elseif ( count( $bits ) == 1 ) {
1085 $opts[$key] = $this->cleanupOption( array_shift( $bits ) );
1086 } else {
1087 // Array!
1088 $opts[$key] = array_map( [ $this, 'cleanupOption' ], $bits );
1089 }
1090 }
1091 }
1092
1093 return $opts;
1094 }
1095
1096 protected function cleanupOption( $opt ) {
1097 if ( substr( $opt, 0, 1 ) == '"' ) {
1098 return substr( $opt, 1, -1 );
1099 }
1100
1101 if ( substr( $opt, 0, 2 ) == '[[' ) {
1102 return substr( $opt, 2, -2 );
1103 }
1104
1105 return $opt;
1106 }
1107
1108 /**
1109 * Use a regex to find out the value of an option
1110 * @param string $key Name of option val to retrieve
1111 * @param array $opts Options array to look in
1112 * @param mixed $default Default value returned if not found
1113 * @return mixed
1114 */
1115 protected static function getOptionValue( $key, $opts, $default ) {
1116 $key = strtolower( $key );
1117
1118 if ( isset( $opts[$key] ) ) {
1119 return $opts[$key];
1120 } else {
1121 return $default;
1122 }
1123 }
1124 }