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