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