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