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