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