Merge "Drop zh-tw message "saveprefs""
[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['wgDeferredUpdateList'] = array();
110 $tmpGlobals['wgGroupPermissions'] = array(
111 '*' => array(
112 'createaccount' => true,
113 'read' => true,
114 'edit' => true,
115 'createpage' => true,
116 'createtalk' => true,
117 ) );
118 $tmpGlobals['wgNamespaceProtection'] = array( NS_MEDIAWIKI => 'editinterface' );
119
120 $tmpGlobals['wgParser'] = new StubObject(
121 'wgParser', $GLOBALS['wgParserConf']['class'],
122 array( $GLOBALS['wgParserConf'] ) );
123
124 $tmpGlobals['wgFileExtensions'][] = 'svg';
125 $tmpGlobals['wgSVGConverter'] = 'rsvg';
126 $tmpGlobals['wgSVGConverters']['rsvg'] =
127 '$path/rsvg-convert -w $width -h $height -o $output $input';
128
129 if ( $GLOBALS['wgStyleDirectory'] === false ) {
130 $tmpGlobals['wgStyleDirectory'] = "$IP/skins";
131 }
132
133 # Replace all media handlers with a mock. We do not need to generate
134 # actual thumbnails to do parser testing, we only care about receiving
135 # a ThumbnailImage properly initialized.
136 global $wgMediaHandlers;
137 foreach ( $wgMediaHandlers as $type => $handler ) {
138 $tmpGlobals['wgMediaHandlers'][$type] = 'MockBitmapHandler';
139 }
140 // Vector images have to be handled slightly differently
141 $tmpGlobals['wgMediaHandlers']['image/svg+xml'] = 'MockSvgHandler';
142
143 // DjVu images have to be handled slightly differently
144 $tmpGlobals['wgMediaHandlers']['image/vnd.djvu'] = 'MockDjVuHandler';
145
146 $tmpHooks = $wgHooks;
147 $tmpHooks['ParserTestParser'][] = 'ParserTestParserHook::setup';
148 $tmpHooks['ParserGetVariableValueTs'][] = 'ParserTest::getFakeTimestamp';
149 $tmpGlobals['wgHooks'] = $tmpHooks;
150 # add a namespace shadowing a interwiki link, to test
151 # proper precedence when resolving links. (bug 51680)
152 $tmpGlobals['wgExtraNamespaces'] = array( 100 => 'MemoryAlpha' );
153
154 $tmpGlobals['wgLocalInterwikis'] = array( 'local', 'mi' );
155 # "extra language links"
156 # see https://gerrit.wikimedia.org/r/111390
157 $tmpGlobals['wgExtraInterlanguageLinkPrefixes'] = array( 'mul' );
158
159 // DjVu support
160 $this->djVuSupport = new DjVuSupport();
161 // Tidy support
162 $this->tidySupport = new TidySupport();
163 $tmpGlobals['wgTidyConfig'] = null;
164 $tmpGlobals['wgUseTidy'] = false;
165 $tmpGlobals['wgDebugTidy'] = false;
166 $tmpGlobals['wgTidyConf'] = $IP . '/includes/tidy/tidy.conf';
167 $tmpGlobals['wgTidyOpts'] = '';
168 $tmpGlobals['wgTidyInternal'] = $this->tidySupport->isInternal();
169
170 $this->setMwGlobals( $tmpGlobals );
171
172 $this->savedWeirdGlobals['image_alias'] = $wgNamespaceAliases['Image'];
173 $this->savedWeirdGlobals['image_talk_alias'] = $wgNamespaceAliases['Image_talk'];
174
175 $wgNamespaceAliases['Image'] = NS_FILE;
176 $wgNamespaceAliases['Image_talk'] = NS_FILE_TALK;
177
178 MWNamespace::getCanonicalNamespaces( true ); # reset namespace cache
179 $wgContLang->resetNamespaces(); # reset namespace cache
180 }
181
182 protected function tearDown() {
183 global $wgNamespaceAliases, $wgContLang;
184
185 $wgNamespaceAliases['Image'] = $this->savedWeirdGlobals['image_alias'];
186 $wgNamespaceAliases['Image_talk'] = $this->savedWeirdGlobals['image_talk_alias'];
187
188 MWTidy::destroySingleton();
189
190 // Restore backends
191 RepoGroup::destroySingleton();
192 FileBackendGroup::destroySingleton();
193
194 // Remove temporary pages from the link cache
195 LinkCache::singleton()->clear();
196
197 // Restore message cache (temporary pages and $wgUseDatabaseMessages)
198 MessageCache::destroyInstance();
199
200 parent::tearDown();
201
202 MWNamespace::getCanonicalNamespaces( true ); # reset namespace cache
203 $wgContLang->resetNamespaces(); # reset namespace cache
204 }
205
206 public static function tearDownAfterClass() {
207 ParserTest::tearDownInterwikis();
208 parent::tearDownAfterClass();
209 }
210
211 function addDBData() {
212 $this->tablesUsed[] = 'site_stats';
213 # disabled for performance
214 #$this->tablesUsed[] = 'image';
215
216 # Update certain things in site_stats
217 $this->db->insert( 'site_stats',
218 array( 'ss_row_id' => 1, 'ss_images' => 2, 'ss_good_articles' => 1 ),
219 __METHOD__
220 );
221
222 $user = User::newFromId( 0 );
223 LinkCache::singleton()->clear(); # Avoids the odd failure at creating the nullRevision
224
225 # Upload DB table entries for files.
226 # We will upload the actual files later. Note that if anything causes LocalFile::load()
227 # to be triggered before then, it will break via maybeUpgrade() setting the fileExists
228 # member to false and storing it in cache.
229 # note that the size/width/height/bits/etc of the file
230 # are actually set by inspecting the file itself; the arguments
231 # to recordUpload2 have no effect. That said, we try to make things
232 # match up so it is less confusing to readers of the code & tests.
233 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Foobar.jpg' ) );
234 if ( !$this->db->selectField( 'image', '1', array( 'img_name' => $image->getName() ) ) ) {
235 $image->recordUpload2(
236 '', // archive name
237 'Upload of some lame file',
238 'Some lame file',
239 array(
240 'size' => 7881,
241 'width' => 1941,
242 'height' => 220,
243 'bits' => 8,
244 'media_type' => MEDIATYPE_BITMAP,
245 'mime' => 'image/jpeg',
246 'metadata' => serialize( array() ),
247 'sha1' => wfBaseConvert( '1', 16, 36, 31 ),
248 'fileExists' => true ),
249 $this->db->timestamp( '20010115123500' ), $user
250 );
251 }
252
253 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Thumb.png' ) );
254 if ( !$this->db->selectField( 'image', '1', array( 'img_name' => $image->getName() ) ) ) {
255 $image->recordUpload2(
256 '', // archive name
257 'Upload of some lame thumbnail',
258 'Some lame thumbnail',
259 array(
260 'size' => 22589,
261 'width' => 135,
262 'height' => 135,
263 'bits' => 8,
264 'media_type' => MEDIATYPE_BITMAP,
265 'mime' => 'image/png',
266 'metadata' => serialize( array() ),
267 'sha1' => wfBaseConvert( '2', 16, 36, 31 ),
268 'fileExists' => true ),
269 $this->db->timestamp( '20130225203040' ), $user
270 );
271 }
272
273 # This image will be blacklisted in [[MediaWiki:Bad image list]]
274 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Bad.jpg' ) );
275 if ( !$this->db->selectField( 'image', '1', array( 'img_name' => $image->getName() ) ) ) {
276 $image->recordUpload2(
277 '', // archive name
278 'zomgnotcensored',
279 'Borderline image',
280 array(
281 'size' => 12345,
282 'width' => 320,
283 'height' => 240,
284 'bits' => 24,
285 'media_type' => MEDIATYPE_BITMAP,
286 'mime' => 'image/jpeg',
287 'metadata' => serialize( array() ),
288 'sha1' => wfBaseConvert( '3', 16, 36, 31 ),
289 'fileExists' => true ),
290 $this->db->timestamp( '20010115123500' ), $user
291 );
292 }
293 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Foobar.svg' ) );
294 if ( !$this->db->selectField( 'image', '1', array( 'img_name' => $image->getName() ) ) ) {
295 $image->recordUpload2( '', 'Upload of some lame SVG', 'Some lame SVG', array(
296 'size' => 12345,
297 'width' => 240,
298 'height' => 180,
299 'bits' => 0,
300 'media_type' => MEDIATYPE_DRAWING,
301 'mime' => 'image/svg+xml',
302 'metadata' => serialize( array() ),
303 'sha1' => wfBaseConvert( '', 16, 36, 31 ),
304 'fileExists' => true
305 ), $this->db->timestamp( '20010115123500' ), $user );
306 }
307
308 # A DjVu file
309 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'LoremIpsum.djvu' ) );
310 if ( !$this->db->selectField( 'image', '1', array( 'img_name' => $image->getName() ) ) ) {
311 $image->recordUpload2( '', 'Upload a DjVu', 'A DjVu', array(
312 'size' => 3249,
313 'width' => 2480,
314 'height' => 3508,
315 'bits' => 0,
316 'media_type' => MEDIATYPE_BITMAP,
317 'mime' => 'image/vnd.djvu',
318 'metadata' => '<?xml version="1.0" ?>
319 <!DOCTYPE DjVuXML PUBLIC "-//W3C//DTD DjVuXML 1.1//EN" "pubtext/DjVuXML-s.dtd">
320 <DjVuXML>
321 <HEAD></HEAD>
322 <BODY><OBJECT height="3508" width="2480">
323 <PARAM name="DPI" value="300" />
324 <PARAM name="GAMMA" value="2.2" />
325 </OBJECT>
326 <OBJECT height="3508" width="2480">
327 <PARAM name="DPI" value="300" />
328 <PARAM name="GAMMA" value="2.2" />
329 </OBJECT>
330 <OBJECT height="3508" width="2480">
331 <PARAM name="DPI" value="300" />
332 <PARAM name="GAMMA" value="2.2" />
333 </OBJECT>
334 <OBJECT height="3508" width="2480">
335 <PARAM name="DPI" value="300" />
336 <PARAM name="GAMMA" value="2.2" />
337 </OBJECT>
338 <OBJECT height="3508" width="2480">
339 <PARAM name="DPI" value="300" />
340 <PARAM name="GAMMA" value="2.2" />
341 </OBJECT>
342 </BODY>
343 </DjVuXML>',
344 'sha1' => wfBaseConvert( '', 16, 36, 31 ),
345 'fileExists' => true
346 ), $this->db->timestamp( '20140115123600' ), $user );
347 }
348 }
349
350 //ParserTest setup/teardown functions
351
352 /**
353 * Set up the global variables for a consistent environment for each test.
354 * Ideally this should replace the global configuration entirely.
355 * @param array $opts
356 * @param string $config
357 * @return RequestContext
358 */
359 protected function setupGlobals( $opts = array(), $config = '' ) {
360 global $wgFileBackends;
361 # Find out values for some special options.
362 $lang =
363 self::getOptionValue( 'language', $opts, 'en' );
364 $variant =
365 self::getOptionValue( 'variant', $opts, false );
366 $maxtoclevel =
367 self::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
368 $linkHolderBatchSize =
369 self::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
370
371 $uploadDir = $this->getUploadDir();
372 if ( $this->getCliArg( 'use-filebackend' ) ) {
373 if ( self::$backendToUse ) {
374 $backend = self::$backendToUse;
375 } else {
376 $name = $this->getCliArg( 'use-filebackend' );
377 $useConfig = array();
378 foreach ( $wgFileBackends as $conf ) {
379 if ( $conf['name'] == $name ) {
380 $useConfig = $conf;
381 }
382 }
383 $useConfig['name'] = 'local-backend'; // swap name
384 unset( $useConfig['lockManager'] );
385 unset( $useConfig['fileJournal'] );
386 $class = $useConfig['class'];
387 self::$backendToUse = new $class( $useConfig );
388 $backend = self::$backendToUse;
389 }
390 } else {
391 # Replace with a mock. We do not care about generating real
392 # files on the filesystem, just need to expose the file
393 # informations.
394 $backend = new MockFileBackend( array(
395 'name' => 'local-backend',
396 'wikiId' => wfWikiId()
397 ) );
398 }
399
400 $settings = array(
401 'wgLocalFileRepo' => array(
402 'class' => 'LocalRepo',
403 'name' => 'local',
404 'url' => 'http://example.com/images',
405 'hashLevels' => 2,
406 'transformVia404' => false,
407 'backend' => $backend
408 ),
409 'wgEnableUploads' => self::getOptionValue( 'wgEnableUploads', $opts, true ),
410 'wgLanguageCode' => $lang,
411 'wgDBprefix' => $this->db->getType() != 'oracle' ? 'unittest_' : 'ut_',
412 'wgRawHtml' => self::getOptionValue( 'wgRawHtml', $opts, false ),
413 'wgNamespacesWithSubpages' => array( NS_MAIN => isset( $opts['subpage'] ) ),
414 'wgAllowExternalImages' => self::getOptionValue( 'wgAllowExternalImages', $opts, true ),
415 'wgThumbLimits' => array( self::getOptionValue( 'thumbsize', $opts, 180 ) ),
416 'wgMaxTocLevel' => $maxtoclevel,
417 'wgUseTeX' => isset( $opts['math'] ) || isset( $opts['texvc'] ),
418 'wgMathDirectory' => $uploadDir . '/math',
419 'wgDefaultLanguageVariant' => $variant,
420 'wgLinkHolderBatchSize' => $linkHolderBatchSize,
421 'wgUseTidy' => isset( $opts['tidy'] ),
422 );
423
424 if ( $config ) {
425 $configLines = explode( "\n", $config );
426
427 foreach ( $configLines as $line ) {
428 list( $var, $value ) = explode( '=', $line, 2 );
429
430 $settings[$var] = eval( "return $value;" ); //???
431 }
432 }
433
434 $this->savedGlobals = array();
435
436 /** @since 1.20 */
437 Hooks::run( 'ParserTestGlobals', array( &$settings ) );
438
439 $langObj = Language::factory( $lang );
440 $settings['wgContLang'] = $langObj;
441 $settings['wgLang'] = $langObj;
442
443 $context = new RequestContext();
444 $settings['wgOut'] = $context->getOutput();
445 $settings['wgUser'] = $context->getUser();
446 $settings['wgRequest'] = $context->getRequest();
447
448 // We (re)set $wgThumbLimits to a single-element array above.
449 $context->getUser()->setOption( 'thumbsize', 0 );
450
451 foreach ( $settings as $var => $val ) {
452 if ( array_key_exists( $var, $GLOBALS ) ) {
453 $this->savedGlobals[$var] = $GLOBALS[$var];
454 }
455
456 $GLOBALS[$var] = $val;
457 }
458
459 MWTidy::destroySingleton();
460 MagicWord::clearCache();
461
462 # The entries saved into RepoGroup cache with previous globals will be wrong.
463 RepoGroup::destroySingleton();
464 FileBackendGroup::destroySingleton();
465
466 # Create dummy files in storage
467 $this->setupUploads();
468
469 # Publish the articles after we have the final language set
470 $this->publishTestArticles();
471
472 MessageCache::destroyInstance();
473
474 return $context;
475 }
476
477 /**
478 * Get an FS upload directory (only applies to FSFileBackend)
479 *
480 * @return string The directory
481 */
482 protected function getUploadDir() {
483 if ( $this->keepUploads ) {
484 // Don't use getNewTempDirectory() as this is meant to persist
485 $dir = wfTempDir() . '/mwParser-images';
486
487 if ( is_dir( $dir ) ) {
488 return $dir;
489 }
490 } else {
491 $dir = $this->getNewTempDirectory();
492 }
493
494 if ( file_exists( $dir ) ) {
495 wfDebug( "Already exists!\n" );
496
497 return $dir;
498 }
499
500 return $dir;
501 }
502
503 /**
504 * Create a dummy uploads directory which will contain a couple
505 * of files in order to pass existence tests.
506 *
507 * @return string The directory
508 */
509 protected function setupUploads() {
510 global $IP;
511
512 $base = $this->getBaseDir();
513 $backend = RepoGroup::singleton()->getLocalRepo()->getBackend();
514 $backend->prepare( array( 'dir' => "$base/local-public/3/3a" ) );
515 $backend->store( array(
516 'src' => "$IP/tests/phpunit/data/parser/headbg.jpg",
517 'dst' => "$base/local-public/3/3a/Foobar.jpg"
518 ) );
519 $backend->prepare( array( 'dir' => "$base/local-public/e/ea" ) );
520 $backend->store( array(
521 'src' => "$IP/tests/phpunit/data/parser/wiki.png",
522 'dst' => "$base/local-public/e/ea/Thumb.png"
523 ) );
524 $backend->prepare( array( 'dir' => "$base/local-public/0/09" ) );
525 $backend->store( array(
526 'src' => "$IP/tests/phpunit/data/parser/headbg.jpg",
527 'dst' => "$base/local-public/0/09/Bad.jpg"
528 ) );
529 $backend->prepare( array( 'dir' => "$base/local-public/5/5f" ) );
530 $backend->store( array(
531 'src' => "$IP/tests/phpunit/data/parser/LoremIpsum.djvu",
532 'dst' => "$base/local-public/5/5f/LoremIpsum.djvu"
533 ) );
534
535 // No helpful SVG file to copy, so make one ourselves
536 $data = '<?xml version="1.0" encoding="utf-8"?>' .
537 '<svg xmlns="http://www.w3.org/2000/svg"' .
538 ' version="1.1" width="240" height="180"/>';
539
540 $backend->prepare( array( 'dir' => "$base/local-public/f/ff" ) );
541 $backend->quickCreate( array(
542 'content' => $data, 'dst' => "$base/local-public/f/ff/Foobar.svg"
543 ) );
544 }
545
546 /**
547 * Restore default values and perform any necessary clean-up
548 * after each test runs.
549 */
550 protected function teardownGlobals() {
551 $this->teardownUploads();
552
553 foreach ( $this->savedGlobals as $var => $val ) {
554 $GLOBALS[$var] = $val;
555 }
556 }
557
558 /**
559 * Remove the dummy uploads directory
560 */
561 private function teardownUploads() {
562 if ( $this->keepUploads ) {
563 return;
564 }
565
566 $backend = RepoGroup::singleton()->getLocalRepo()->getBackend();
567 if ( $backend instanceof MockFileBackend ) {
568 # In memory backend, so dont bother cleaning them up.
569 return;
570 }
571
572 $base = $this->getBaseDir();
573 // delete the files first, then the dirs.
574 self::deleteFiles(
575 array(
576 "$base/local-public/3/3a/Foobar.jpg",
577 "$base/local-thumb/3/3a/Foobar.jpg/1000px-Foobar.jpg",
578 "$base/local-thumb/3/3a/Foobar.jpg/100px-Foobar.jpg",
579 "$base/local-thumb/3/3a/Foobar.jpg/120px-Foobar.jpg",
580 "$base/local-thumb/3/3a/Foobar.jpg/1280px-Foobar.jpg",
581 "$base/local-thumb/3/3a/Foobar.jpg/137px-Foobar.jpg",
582 "$base/local-thumb/3/3a/Foobar.jpg/1500px-Foobar.jpg",
583 "$base/local-thumb/3/3a/Foobar.jpg/177px-Foobar.jpg",
584 "$base/local-thumb/3/3a/Foobar.jpg/180px-Foobar.jpg",
585 "$base/local-thumb/3/3a/Foobar.jpg/200px-Foobar.jpg",
586 "$base/local-thumb/3/3a/Foobar.jpg/206px-Foobar.jpg",
587 "$base/local-thumb/3/3a/Foobar.jpg/20px-Foobar.jpg",
588 "$base/local-thumb/3/3a/Foobar.jpg/220px-Foobar.jpg",
589 "$base/local-thumb/3/3a/Foobar.jpg/265px-Foobar.jpg",
590 "$base/local-thumb/3/3a/Foobar.jpg/270px-Foobar.jpg",
591 "$base/local-thumb/3/3a/Foobar.jpg/274px-Foobar.jpg",
592 "$base/local-thumb/3/3a/Foobar.jpg/300px-Foobar.jpg",
593 "$base/local-thumb/3/3a/Foobar.jpg/30px-Foobar.jpg",
594 "$base/local-thumb/3/3a/Foobar.jpg/330px-Foobar.jpg",
595 "$base/local-thumb/3/3a/Foobar.jpg/353px-Foobar.jpg",
596 "$base/local-thumb/3/3a/Foobar.jpg/360px-Foobar.jpg",
597 "$base/local-thumb/3/3a/Foobar.jpg/400px-Foobar.jpg",
598 "$base/local-thumb/3/3a/Foobar.jpg/40px-Foobar.jpg",
599 "$base/local-thumb/3/3a/Foobar.jpg/440px-Foobar.jpg",
600 "$base/local-thumb/3/3a/Foobar.jpg/442px-Foobar.jpg",
601 "$base/local-thumb/3/3a/Foobar.jpg/450px-Foobar.jpg",
602 "$base/local-thumb/3/3a/Foobar.jpg/50px-Foobar.jpg",
603 "$base/local-thumb/3/3a/Foobar.jpg/600px-Foobar.jpg",
604 "$base/local-thumb/3/3a/Foobar.jpg/640px-Foobar.jpg",
605 "$base/local-thumb/3/3a/Foobar.jpg/70px-Foobar.jpg",
606 "$base/local-thumb/3/3a/Foobar.jpg/75px-Foobar.jpg",
607 "$base/local-thumb/3/3a/Foobar.jpg/960px-Foobar.jpg",
608
609 "$base/local-public/e/ea/Thumb.png",
610
611 "$base/local-public/0/09/Bad.jpg",
612
613 "$base/local-public/5/5f/LoremIpsum.djvu",
614 "$base/local-thumb/5/5f/LoremIpsum.djvu/page2-2480px-LoremIpsum.djvu.jpg",
615 "$base/local-thumb/5/5f/LoremIpsum.djvu/page2-3720px-LoremIpsum.djvu.jpg",
616 "$base/local-thumb/5/5f/LoremIpsum.djvu/page2-4960px-LoremIpsum.djvu.jpg",
617
618 "$base/local-public/f/ff/Foobar.svg",
619 "$base/local-thumb/f/ff/Foobar.svg/180px-Foobar.svg.png",
620 "$base/local-thumb/f/ff/Foobar.svg/2000px-Foobar.svg.png",
621 "$base/local-thumb/f/ff/Foobar.svg/270px-Foobar.svg.png",
622 "$base/local-thumb/f/ff/Foobar.svg/3000px-Foobar.svg.png",
623 "$base/local-thumb/f/ff/Foobar.svg/360px-Foobar.svg.png",
624 "$base/local-thumb/f/ff/Foobar.svg/4000px-Foobar.svg.png",
625 "$base/local-thumb/f/ff/Foobar.svg/langde-180px-Foobar.svg.png",
626 "$base/local-thumb/f/ff/Foobar.svg/langde-270px-Foobar.svg.png",
627 "$base/local-thumb/f/ff/Foobar.svg/langde-360px-Foobar.svg.png",
628
629 "$base/local-public/math/f/a/5/fa50b8b616463173474302ca3e63586b.png",
630 )
631 );
632 }
633
634 /**
635 * Delete the specified files, if they exist.
636 * @param array $files Full paths to files to delete.
637 */
638 private static function deleteFiles( $files ) {
639 $backend = RepoGroup::singleton()->getLocalRepo()->getBackend();
640 foreach ( $files as $file ) {
641 $backend->delete( array( 'src' => $file ), array( 'force' => 1 ) );
642 }
643 foreach ( $files as $file ) {
644 $tmp = $file;
645 while ( $tmp = FileBackend::parentStoragePath( $tmp ) ) {
646 if ( !$backend->clean( array( 'dir' => $tmp ) )->isOK() ) {
647 break;
648 }
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 }