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