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