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