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