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