mw.Upload.BookletLayout: Don't explode when the API call fails with 'exception'
[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 # 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' => Wikimedia\base_convert( '', 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 = FileBackend::parentStoragePath( $file );
644 while ( $tmp ) {
645 if ( !$backend->clean( array( 'dir' => $tmp ) )->isOK() ) {
646 break;
647 }
648 $tmp = FileBackend::parentStoragePath( $tmp );
649 }
650 }
651 }
652
653 protected function getBaseDir() {
654 return 'mwstore://local-backend';
655 }
656
657 public function parserTestProvider() {
658 if ( $this->file === false ) {
659 global $wgParserTestFiles;
660 $this->file = $wgParserTestFiles[0];
661 }
662
663 return new TestFileIterator( $this->file, $this );
664 }
665
666 /**
667 * Set the file from whose tests will be run by this instance
668 * @param string $filename
669 */
670 public function setParserTestFile( $filename ) {
671 $this->file = $filename;
672 }
673
674 /**
675 * @group medium
676 * @group ParserTests
677 * @dataProvider parserTestProvider
678 * @param string $desc
679 * @param string $input
680 * @param string $result
681 * @param array $opts
682 * @param array $config
683 */
684 public function testParserTest( $desc, $input, $result, $opts, $config ) {
685 if ( $this->regex != '' && !preg_match( '/' . $this->regex . '/', $desc ) ) {
686 $this->assertTrue( true ); // XXX: don't flood output with "test made no assertions"
687 // $this->markTestSkipped( 'Filtered out by the user' );
688 return;
689 }
690
691 if ( !$this->isWikitextNS( NS_MAIN ) ) {
692 // parser tests frequently assume that the main namespace contains wikitext.
693 // @todo When setting up pages, force the content model. Only skip if
694 // $wgtContentModelUseDB is false.
695 $this->markTestSkipped( "Main namespace does not support wikitext,"
696 . "skipping parser test: $desc" );
697 }
698
699 wfDebug( "Running parser test: $desc\n" );
700
701 $opts = $this->parseOptions( $opts );
702 $context = $this->setupGlobals( $opts, $config );
703
704 $user = $context->getUser();
705 $options = ParserOptions::newFromContext( $context );
706
707 if ( isset( $opts['title'] ) ) {
708 $titleText = $opts['title'];
709 } else {
710 $titleText = 'Parser test';
711 }
712
713 $local = isset( $opts['local'] );
714 $preprocessor = isset( $opts['preprocessor'] ) ? $opts['preprocessor'] : null;
715 $parser = $this->getParser( $preprocessor );
716
717 $title = Title::newFromText( $titleText );
718
719 # Parser test requiring math. Make sure texvc is executable
720 # or just skip such tests.
721 if ( isset( $opts['math'] ) || isset( $opts['texvc'] ) ) {
722 global $wgTexvc;
723
724 if ( !isset( $wgTexvc ) ) {
725 $this->markTestSkipped( "SKIPPED: \$wgTexvc is not set" );
726 } elseif ( !is_executable( $wgTexvc ) ) {
727 $this->markTestSkipped( "SKIPPED: texvc binary does not exist"
728 . " or is not executable.\n"
729 . "Current configuration is:\n\$wgTexvc = '$wgTexvc'" );
730 }
731 }
732
733 if ( isset( $opts['djvu'] ) ) {
734 if ( !$this->djVuSupport->isEnabled() ) {
735 $this->markTestSkipped( "SKIPPED: djvu binaries do not exist or are not executable.\n" );
736 }
737 }
738
739 if ( isset( $opts['tidy'] ) ) {
740 if ( !$this->tidySupport->isEnabled() ) {
741 $this->markTestSkipped( "SKIPPED: tidy extension is not installed.\n" );
742 } else {
743 $options->setTidy( true );
744 }
745 }
746
747 if ( isset( $opts['pst'] ) ) {
748 $out = $parser->preSaveTransform( $input, $title, $user, $options );
749 } elseif ( isset( $opts['msg'] ) ) {
750 $out = $parser->transformMsg( $input, $options, $title );
751 } elseif ( isset( $opts['section'] ) ) {
752 $section = $opts['section'];
753 $out = $parser->getSection( $input, $section );
754 } elseif ( isset( $opts['replace'] ) ) {
755 $section = $opts['replace'][0];
756 $replace = $opts['replace'][1];
757 $out = $parser->replaceSection( $input, $section, $replace );
758 } elseif ( isset( $opts['comment'] ) ) {
759 $out = Linker::formatComment( $input, $title, $local );
760 } elseif ( isset( $opts['preload'] ) ) {
761 $out = $parser->getPreloadText( $input, $title, $options );
762 } else {
763 $output = $parser->parse( $input, $title, $options, true, true, 1337 );
764 $output->setTOCEnabled( !isset( $opts['notoc'] ) );
765 $out = $output->getText();
766 if ( isset( $opts['tidy'] ) ) {
767 $out = preg_replace( '/\s+$/', '', $out );
768 }
769
770 if ( isset( $opts['showtitle'] ) ) {
771 if ( $output->getTitleText() ) {
772 $title = $output->getTitleText();
773 }
774
775 $out = "$title\n$out";
776 }
777
778 if ( isset( $opts['showindicators'] ) ) {
779 $indicators = '';
780 foreach ( $output->getIndicators() as $id => $content ) {
781 $indicators .= "$id=$content\n";
782 }
783 $out = $indicators . $out;
784 }
785
786 if ( isset( $opts['ill'] ) ) {
787 $out = implode( ' ', $output->getLanguageLinks() );
788 } elseif ( isset( $opts['cat'] ) ) {
789 $outputPage = $context->getOutput();
790 $outputPage->addCategoryLinks( $output->getCategories() );
791 $cats = $outputPage->getCategoryLinks();
792
793 if ( isset( $cats['normal'] ) ) {
794 $out = implode( ' ', $cats['normal'] );
795 } else {
796 $out = '';
797 }
798 }
799 $parser->mPreprocessor = null;
800 }
801
802 $this->teardownGlobals();
803
804 $this->assertEquals( $result, $out, $desc );
805 }
806
807 /**
808 * Run a fuzz test series
809 * Draw input from a set of test files
810 *
811 * @todo fixme Needs some work to not eat memory until the world explodes
812 *
813 * @group ParserFuzz
814 */
815 public function testFuzzTests() {
816 global $wgParserTestFiles;
817
818 $files = $wgParserTestFiles;
819
820 if ( $this->getCliArg( 'file' ) ) {
821 $files = array( $this->getCliArg( 'file' ) );
822 }
823
824 $dict = $this->getFuzzInput( $files );
825 $dictSize = strlen( $dict );
826 $logMaxLength = log( $this->maxFuzzTestLength );
827
828 ini_set( 'memory_limit', $this->memoryLimit * 1048576 );
829
830 $user = new User;
831 $opts = ParserOptions::newFromUser( $user );
832 $title = Title::makeTitle( NS_MAIN, 'Parser_test' );
833
834 $id = 1;
835
836 while ( true ) {
837
838 // Generate test input
839 mt_srand( ++$this->fuzzSeed );
840 $totalLength = mt_rand( 1, $this->maxFuzzTestLength );
841 $input = '';
842
843 while ( strlen( $input ) < $totalLength ) {
844 $logHairLength = mt_rand( 0, 1000000 ) / 1000000 * $logMaxLength;
845 $hairLength = min( intval( exp( $logHairLength ) ), $dictSize );
846 $offset = mt_rand( 0, $dictSize - $hairLength );
847 $input .= substr( $dict, $offset, $hairLength );
848 }
849
850 $this->setupGlobals();
851 $parser = $this->getParser();
852
853 // Run the test
854 try {
855 $parser->parse( $input, $title, $opts );
856 $this->assertTrue( true, "Test $id, fuzz seed {$this->fuzzSeed}" );
857 } catch ( Exception $exception ) {
858 $input_dump = sprintf( "string(%d) \"%s\"\n", strlen( $input ), $input );
859
860 $this->assertTrue( false, "Test $id, fuzz seed {$this->fuzzSeed}. \n\n" .
861 "Input: $input_dump\n\nError: {$exception->getMessage()}\n\n" .
862 "Backtrace: {$exception->getTraceAsString()}" );
863 }
864
865 $this->teardownGlobals();
866 $parser->__destruct();
867
868 if ( $id % 100 == 0 ) {
869 $usage = intval( memory_get_usage( true ) / $this->memoryLimit / 1048576 * 100 );
870 // echo "{$this->fuzzSeed}: $numSuccess/$numTotal (mem: $usage%)\n";
871 if ( $usage > 90 ) {
872 $ret = "Out of memory:\n";
873 $memStats = $this->getMemoryBreakdown();
874
875 foreach ( $memStats as $name => $usage ) {
876 $ret .= "$name: $usage\n";
877 }
878
879 throw new MWException( $ret );
880 }
881 }
882
883 $id++;
884 }
885 }
886
887 // Various getter functions
888
889 /**
890 * Get an input dictionary from a set of parser test files
891 * @param array $filenames
892 * @return string
893 */
894 function getFuzzInput( $filenames ) {
895 $dict = '';
896
897 foreach ( $filenames as $filename ) {
898 $contents = file_get_contents( $filename );
899 preg_match_all( '/!!\s*input\n(.*?)\n!!\s*result/s', $contents, $matches );
900
901 foreach ( $matches[1] as $match ) {
902 $dict .= $match . "\n";
903 }
904 }
905
906 return $dict;
907 }
908
909 /**
910 * Get a memory usage breakdown
911 * @return array
912 */
913 function getMemoryBreakdown() {
914 $memStats = array();
915
916 foreach ( $GLOBALS as $name => $value ) {
917 $memStats['$' . $name] = strlen( serialize( $value ) );
918 }
919
920 $classes = get_declared_classes();
921
922 foreach ( $classes as $class ) {
923 $rc = new ReflectionClass( $class );
924 $props = $rc->getStaticProperties();
925 $memStats[$class] = strlen( serialize( $props ) );
926 $methods = $rc->getMethods();
927
928 foreach ( $methods as $method ) {
929 $memStats[$class] += strlen( serialize( $method->getStaticVariables() ) );
930 }
931 }
932
933 $functions = get_defined_functions();
934
935 foreach ( $functions['user'] as $function ) {
936 $rf = new ReflectionFunction( $function );
937 $memStats["$function()"] = strlen( serialize( $rf->getStaticVariables() ) );
938 }
939
940 asort( $memStats );
941
942 return $memStats;
943 }
944
945 /**
946 * Get a Parser object
947 * @param Preprocessor $preprocessor
948 * @return Parser
949 */
950 function getParser( $preprocessor = null ) {
951 global $wgParserConf;
952
953 $class = $wgParserConf['class'];
954 $parser = new $class( array( 'preprocessorClass' => $preprocessor ) + $wgParserConf );
955
956 Hooks::run( 'ParserTestParser', array( &$parser ) );
957
958 return $parser;
959 }
960
961 // Various action functions
962
963 public function addArticle( $name, $text, $line ) {
964 self::$articles[$name] = array( $text, $line );
965 }
966
967 public function publishTestArticles() {
968 if ( empty( self::$articles ) ) {
969 return;
970 }
971
972 foreach ( self::$articles as $name => $info ) {
973 list( $text, $line ) = $info;
974 ParserTest::addArticle( $name, $text, $line, 'ignoreduplicate' );
975 }
976 }
977
978 /**
979 * Steal a callback function from the primary parser, save it for
980 * application to our scary parser. If the hook is not installed,
981 * abort processing of this file.
982 *
983 * @param string $name
984 * @return bool True if tag hook is present
985 */
986 public function requireHook( $name ) {
987 global $wgParser;
988 $wgParser->firstCallInit(); // make sure hooks are loaded.
989 return isset( $wgParser->mTagHooks[$name] );
990 }
991
992 public function requireFunctionHook( $name ) {
993 global $wgParser;
994 $wgParser->firstCallInit(); // make sure hooks are loaded.
995 return isset( $wgParser->mFunctionHooks[$name] );
996 }
997
998 public function requireTransparentHook( $name ) {
999 global $wgParser;
1000 $wgParser->firstCallInit(); // make sure hooks are loaded.
1001 return isset( $wgParser->mTransparentTagHooks[$name] );
1002 }
1003
1004 // Various "cleanup" functions
1005
1006 /**
1007 * Remove last character if it is a newline
1008 * @param string $s
1009 * @return string
1010 */
1011 public function removeEndingNewline( $s ) {
1012 if ( substr( $s, -1 ) === "\n" ) {
1013 return substr( $s, 0, -1 );
1014 } else {
1015 return $s;
1016 }
1017 }
1018
1019 // Test options parser functions
1020
1021 protected function parseOptions( $instring ) {
1022 $opts = array();
1023 // foo
1024 // foo=bar
1025 // foo="bar baz"
1026 // foo=[[bar baz]]
1027 // foo=bar,"baz quux"
1028 $regex = '/\b
1029 ([\w-]+) # Key
1030 \b
1031 (?:\s*
1032 = # First sub-value
1033 \s*
1034 (
1035 "
1036 [^"]* # Quoted val
1037 "
1038 |
1039 \[\[
1040 [^]]* # Link target
1041 \]\]
1042 |
1043 [\w-]+ # Plain word
1044 )
1045 (?:\s*
1046 , # Sub-vals 1..N
1047 \s*
1048 (
1049 "[^"]*" # Quoted val
1050 |
1051 \[\[[^]]*\]\] # Link target
1052 |
1053 [\w-]+ # Plain word
1054 )
1055 )*
1056 )?
1057 /x';
1058
1059 if ( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER ) ) {
1060 foreach ( $matches as $bits ) {
1061 array_shift( $bits );
1062 $key = strtolower( array_shift( $bits ) );
1063 if ( count( $bits ) == 0 ) {
1064 $opts[$key] = true;
1065 } elseif ( count( $bits ) == 1 ) {
1066 $opts[$key] = $this->cleanupOption( array_shift( $bits ) );
1067 } else {
1068 // Array!
1069 $opts[$key] = array_map( array( $this, 'cleanupOption' ), $bits );
1070 }
1071 }
1072 }
1073
1074 return $opts;
1075 }
1076
1077 protected function cleanupOption( $opt ) {
1078 if ( substr( $opt, 0, 1 ) == '"' ) {
1079 return substr( $opt, 1, -1 );
1080 }
1081
1082 if ( substr( $opt, 0, 2 ) == '[[' ) {
1083 return substr( $opt, 2, -2 );
1084 }
1085
1086 return $opt;
1087 }
1088
1089 /**
1090 * Use a regex to find out the value of an option
1091 * @param string $key Name of option val to retrieve
1092 * @param array $opts Options array to look in
1093 * @param mixed $default Default value returned if not found
1094 * @return mixed
1095 */
1096 protected static function getOptionValue( $key, $opts, $default ) {
1097 $key = strtolower( $key );
1098
1099 if ( isset( $opts[$key] ) ) {
1100 return $opts[$key];
1101 } else {
1102 return $default;
1103 }
1104 }
1105 }