4 * Although marked as a stub, can work independently.
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;
23 public $showProgress = true;
24 public $savedWeirdGlobals = array();
25 public $savedGlobals = array();
26 public $hooks = array();
27 public $functionHooks = array();
28 public $transparentHooks = array();
31 public $maxFuzzTestLength = 300;
33 public $memoryLimit = 50;
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;
58 if ( $this->getCliArg( 'regex' ) ) {
59 $this->regex
= $this->getCliArg( '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',
87 'url' => 'http://example.com/images',
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(
112 'createaccount' => true,
115 'createpage' => true,
116 'createtalk' => true,
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' );
160 $this->djVuSupport
= new DjVuSupport();
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'];
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();
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 ),
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(
238 'Upload of some lame file',
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(
258 'Upload of some lame thumbnail',
259 'Some lame thumbnail',
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(
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(
301 'media_type' => MEDIATYPE_DRAWING
,
302 'mime' => 'image/svg+xml',
303 'metadata' => serialize( array() ),
304 'sha1' => wfBaseConvert( '', 16, 36, 31 ),
306 ), $this->db
->timestamp( '20010115123500' ), $user );
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(
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">
323 <BODY><OBJECT height="3508" width="2480">
324 <PARAM name="DPI" value="300" />
325 <PARAM name="GAMMA" value="2.2" />
327 <OBJECT height="3508" width="2480">
328 <PARAM name="DPI" value="300" />
329 <PARAM name="GAMMA" value="2.2" />
331 <OBJECT height="3508" width="2480">
332 <PARAM name="DPI" value="300" />
333 <PARAM name="GAMMA" value="2.2" />
335 <OBJECT height="3508" width="2480">
336 <PARAM name="DPI" value="300" />
337 <PARAM name="GAMMA" value="2.2" />
339 <OBJECT height="3508" width="2480">
340 <PARAM name="DPI" value="300" />
341 <PARAM name="GAMMA" value="2.2" />
345 'sha1' => wfBaseConvert( '', 16, 36, 31 ),
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.
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.
364 self
::getOptionValue( 'language', $opts, 'en' );
366 self
::getOptionValue( 'variant', $opts, false );
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;
377 $name = $this->getCliArg( 'use-filebackend' );
378 $useConfig = array();
379 foreach ( $wgFileBackends as $conf ) {
380 if ( $conf['name'] == $name ) {
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;
392 # Replace with a mock. We do not care about generating real
393 # files on the filesystem, just need to expose the file
395 $backend = new MockFileBackend( array(
396 'name' => 'local-backend',
397 'wikiId' => wfWikiId()
402 'wgLocalFileRepo' => array(
403 'class' => 'LocalRepo',
405 'url' => 'http://example.com/images',
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,
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();
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();
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 ) ) {
489 $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
492 // wfDebug( "Creating upload directory $dir\n" );
493 if ( file_exists( $dir ) ) {
494 wfDebug( "Already exists!\n" );
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() {
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"
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"
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"
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"
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"
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
) {
565 $backend = RepoGroup
::singleton()->getLocalRepo()->getBackend();
566 if ( $backend instanceof MockFileBackend
) {
567 # In memory backend, so dont bother cleaning them up.
571 $base = $this->getBaseDir();
572 // delete the files first, then the dirs.
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 ) {
644 while ( $tmp = FileBackend
::parentStoragePath( $tmp ) ) {
645 if ( !$backend->clean( array( 'dir' => $tmp ) )->isOK() ) {
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;
675 * @dataProvider parserTestProvider
676 * @param string $desc
677 * @param string $input
678 * @param string $result
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' );
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'];
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'] ) ) {
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 );
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" );
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'] );
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
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 );
817 $opts = ParserOptions
::newFromUser( $user );
818 $title = Title
::makeTitle( NS_MAIN
, 'Parser_test' );
824 // Generate test input
825 mt_srand( ++
$this->fuzzSeed
);
826 $totalLength = mt_rand( 1, $this->maxFuzzTestLength
);
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();
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";
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 );
873 //Various getter functions
876 * Get an input dictionary from a set of parser test files
877 * @param array $filenames
880 function getFuzzInput( $filenames ) {
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";
896 * Get a memory usage breakdown
899 function getMemoryBreakdown() {
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() ) );
932 * Get a Parser object
933 * @param Preprocessor $preprocessor
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 ) );
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 ) ) {
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 ) {
974 $wgParser->firstCallInit(); // make sure hooks are loaded.
975 return isset( $wgParser->mTagHooks
[$name] );
978 public function requireFunctionHook( $name ) {
980 $wgParser->firstCallInit(); // make sure hooks are loaded.
981 return isset( $wgParser->mFunctionHooks
[$name] );
984 public function requireTransparentHook( $name ) {
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
997 public function removeEndingNewline( $s ) {
998 if ( substr( $s, -1 ) === "\n" ) {
999 return substr( $s, 0, -1 );
1005 //Test options parser functions
1007 protected function parseOptions( $instring ) {
1013 // foo=bar,"baz quux"
1035 "[^"]*" # Quoted val
1037 \[\[[^]]*\]\] # Link target
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 ) {
1051 } elseif ( count( $bits ) == 1 ) {
1052 $opts[$key] = $this->cleanupOption( array_shift( $bits ) );
1055 $opts[$key] = array_map( array( $this, 'cleanupOption' ), $bits );
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 );
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
1082 protected static function getOptionValue( $key, $opts, $default ) {
1083 $key = strtolower( $key );
1085 if ( isset( $opts[$key] ) ) {