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