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