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