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