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