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 -o $output $input';
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 $tmpGlobals['wgUseTidy'] = false;
164 $tmpGlobals['wgAlwaysUseTidy'] = false;
165 $tmpGlobals['wgDebugTidy'] = false;
166 $tmpGlobals['wgTidyConf'] = $IP . '/includes/tidy.conf';
167 $tmpGlobals['wgTidyOpts'] = '';
168 $tmpGlobals['wgTidyInternal'] = $this->tidySupport
->isInternal();
170 $this->setMwGlobals( $tmpGlobals );
172 $this->savedWeirdGlobals
['image_alias'] = $wgNamespaceAliases['Image'];
173 $this->savedWeirdGlobals
['image_talk_alias'] = $wgNamespaceAliases['Image_talk'];
175 $wgNamespaceAliases['Image'] = NS_FILE
;
176 $wgNamespaceAliases['Image_talk'] = NS_FILE_TALK
;
178 MWNamespace
::getCanonicalNamespaces( true ); # reset namespace cache
179 $wgContLang->resetNamespaces(); # reset namespace cache
182 protected function tearDown() {
183 global $wgNamespaceAliases, $wgContLang;
185 $wgNamespaceAliases['Image'] = $this->savedWeirdGlobals
['image_alias'];
186 $wgNamespaceAliases['Image_talk'] = $this->savedWeirdGlobals
['image_talk_alias'];
189 RepoGroup
::destroySingleton();
190 FileBackendGroup
::destroySingleton();
192 // Remove temporary pages from the link cache
193 LinkCache
::singleton()->clear();
195 // Restore message cache (temporary pages and $wgUseDatabaseMessages)
196 MessageCache
::destroyInstance();
200 MWNamespace
::getCanonicalNamespaces( true ); # reset namespace cache
201 $wgContLang->resetNamespaces(); # reset namespace cache
204 public static function tearDownAfterClass() {
205 ParserTest
::tearDownInterwikis();
206 parent
::tearDownAfterClass();
209 function addDBData() {
210 $this->tablesUsed
[] = 'site_stats';
211 # disabled for performance
212 #$this->tablesUsed[] = 'image';
214 # Update certain things in site_stats
215 $this->db
->insert( 'site_stats',
216 array( 'ss_row_id' => 1, 'ss_images' => 2, 'ss_good_articles' => 1 ),
220 $user = User
::newFromId( 0 );
221 LinkCache
::singleton()->clear(); # Avoids the odd failure at creating the nullRevision
223 # Upload DB table entries for files.
224 # We will upload the actual files later. Note that if anything causes LocalFile::load()
225 # to be triggered before then, it will break via maybeUpgrade() setting the fileExists
226 # member to false and storing it in cache.
227 # note that the size/width/height/bits/etc of the file
228 # are actually set by inspecting the file itself; the arguments
229 # to recordUpload2 have no effect. That said, we try to make things
230 # match up so it is less confusing to readers of the code & tests.
231 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Foobar.jpg' ) );
232 if ( !$this->db
->selectField( 'image', '1', array( 'img_name' => $image->getName() ) ) ) {
233 $image->recordUpload2(
235 'Upload of some lame file',
242 'media_type' => MEDIATYPE_BITMAP
,
243 'mime' => 'image/jpeg',
244 'metadata' => serialize( array() ),
245 'sha1' => wfBaseConvert( '1', 16, 36, 31 ),
246 'fileExists' => true ),
247 $this->db
->timestamp( '20010115123500' ), $user
251 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Thumb.png' ) );
252 if ( !$this->db
->selectField( 'image', '1', array( 'img_name' => $image->getName() ) ) ) {
253 $image->recordUpload2(
255 'Upload of some lame thumbnail',
256 'Some lame thumbnail',
262 'media_type' => MEDIATYPE_BITMAP
,
263 'mime' => 'image/png',
264 'metadata' => serialize( array() ),
265 'sha1' => wfBaseConvert( '2', 16, 36, 31 ),
266 'fileExists' => true ),
267 $this->db
->timestamp( '20130225203040' ), $user
271 # This image will be blacklisted in [[MediaWiki:Bad image list]]
272 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Bad.jpg' ) );
273 if ( !$this->db
->selectField( 'image', '1', array( 'img_name' => $image->getName() ) ) ) {
274 $image->recordUpload2(
283 'media_type' => MEDIATYPE_BITMAP
,
284 'mime' => 'image/jpeg',
285 'metadata' => serialize( array() ),
286 'sha1' => wfBaseConvert( '3', 16, 36, 31 ),
287 'fileExists' => true ),
288 $this->db
->timestamp( '20010115123500' ), $user
291 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Foobar.svg' ) );
292 if ( !$this->db
->selectField( 'image', '1', array( 'img_name' => $image->getName() ) ) ) {
293 $image->recordUpload2( '', 'Upload of some lame SVG', 'Some lame SVG', array(
298 'media_type' => MEDIATYPE_DRAWING
,
299 'mime' => 'image/svg+xml',
300 'metadata' => serialize( array() ),
301 'sha1' => wfBaseConvert( '', 16, 36, 31 ),
303 ), $this->db
->timestamp( '20010115123500' ), $user );
307 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'LoremIpsum.djvu' ) );
308 if ( !$this->db
->selectField( 'image', '1', array( 'img_name' => $image->getName() ) ) ) {
309 $image->recordUpload2( '', 'Upload a DjVu', 'A DjVu', array(
314 'media_type' => MEDIATYPE_BITMAP
,
315 'mime' => 'image/vnd.djvu',
316 'metadata' => '<?xml version="1.0" ?>
317 <!DOCTYPE DjVuXML PUBLIC "-//W3C//DTD DjVuXML 1.1//EN" "pubtext/DjVuXML-s.dtd">
320 <BODY><OBJECT height="3508" width="2480">
321 <PARAM name="DPI" value="300" />
322 <PARAM name="GAMMA" value="2.2" />
324 <OBJECT height="3508" width="2480">
325 <PARAM name="DPI" value="300" />
326 <PARAM name="GAMMA" value="2.2" />
328 <OBJECT height="3508" width="2480">
329 <PARAM name="DPI" value="300" />
330 <PARAM name="GAMMA" value="2.2" />
332 <OBJECT height="3508" width="2480">
333 <PARAM name="DPI" value="300" />
334 <PARAM name="GAMMA" value="2.2" />
336 <OBJECT height="3508" width="2480">
337 <PARAM name="DPI" value="300" />
338 <PARAM name="GAMMA" value="2.2" />
342 'sha1' => wfBaseConvert( '', 16, 36, 31 ),
344 ), $this->db
->timestamp( '20140115123600' ), $user );
348 //ParserTest setup/teardown functions
351 * Set up the global variables for a consistent environment for each test.
352 * Ideally this should replace the global configuration entirely.
354 * @param string $config
355 * @return RequestContext
357 protected function setupGlobals( $opts = array(), $config = '' ) {
358 global $wgFileBackends;
359 # Find out values for some special options.
361 self
::getOptionValue( 'language', $opts, 'en' );
363 self
::getOptionValue( 'variant', $opts, false );
365 self
::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
366 $linkHolderBatchSize =
367 self
::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
369 $uploadDir = $this->getUploadDir();
370 if ( $this->getCliArg( 'use-filebackend' ) ) {
371 if ( self
::$backendToUse ) {
372 $backend = self
::$backendToUse;
374 $name = $this->getCliArg( 'use-filebackend' );
375 $useConfig = array();
376 foreach ( $wgFileBackends as $conf ) {
377 if ( $conf['name'] == $name ) {
381 $useConfig['name'] = 'local-backend'; // swap name
382 unset( $useConfig['lockManager'] );
383 unset( $useConfig['fileJournal'] );
384 $class = $useConfig['class'];
385 self
::$backendToUse = new $class( $useConfig );
386 $backend = self
::$backendToUse;
389 # Replace with a mock. We do not care about generating real
390 # files on the filesystem, just need to expose the file
392 $backend = new MockFileBackend( array(
393 'name' => 'local-backend',
394 'wikiId' => wfWikiId()
399 'wgLocalFileRepo' => array(
400 'class' => 'LocalRepo',
402 'url' => 'http://example.com/images',
404 'transformVia404' => false,
405 'backend' => $backend
407 'wgEnableUploads' => self
::getOptionValue( 'wgEnableUploads', $opts, true ),
408 'wgLanguageCode' => $lang,
409 'wgDBprefix' => $this->db
->getType() != 'oracle' ?
'unittest_' : 'ut_',
410 'wgRawHtml' => self
::getOptionValue( 'wgRawHtml', $opts, false ),
411 'wgNamespacesWithSubpages' => array( NS_MAIN
=> isset( $opts['subpage'] ) ),
412 'wgAllowExternalImages' => self
::getOptionValue( 'wgAllowExternalImages', $opts, true ),
413 'wgThumbLimits' => array( self
::getOptionValue( 'thumbsize', $opts, 180 ) ),
414 'wgMaxTocLevel' => $maxtoclevel,
415 'wgUseTeX' => isset( $opts['math'] ) ||
isset( $opts['texvc'] ),
416 'wgMathDirectory' => $uploadDir . '/math',
417 'wgDefaultLanguageVariant' => $variant,
418 'wgLinkHolderBatchSize' => $linkHolderBatchSize,
419 'wgUseTidy' => isset( $opts['tidy'] ),
423 $configLines = explode( "\n", $config );
425 foreach ( $configLines as $line ) {
426 list( $var, $value ) = explode( '=', $line, 2 );
428 $settings[$var] = eval( "return $value;" ); //???
432 $this->savedGlobals
= array();
435 Hooks
::run( 'ParserTestGlobals', array( &$settings ) );
437 $langObj = Language
::factory( $lang );
438 $settings['wgContLang'] = $langObj;
439 $settings['wgLang'] = $langObj;
441 $context = new RequestContext();
442 $settings['wgOut'] = $context->getOutput();
443 $settings['wgUser'] = $context->getUser();
444 $settings['wgRequest'] = $context->getRequest();
446 // We (re)set $wgThumbLimits to a single-element array above.
447 $context->getUser()->setOption( 'thumbsize', 0 );
449 foreach ( $settings as $var => $val ) {
450 if ( array_key_exists( $var, $GLOBALS ) ) {
451 $this->savedGlobals
[$var] = $GLOBALS[$var];
454 $GLOBALS[$var] = $val;
457 MagicWord
::clearCache();
459 # The entries saved into RepoGroup cache with previous globals will be wrong.
460 RepoGroup
::destroySingleton();
461 FileBackendGroup
::destroySingleton();
463 # Create dummy files in storage
464 $this->setupUploads();
466 # Publish the articles after we have the final language set
467 $this->publishTestArticles();
469 MessageCache
::destroyInstance();
475 * Get an FS upload directory (only applies to FSFileBackend)
477 * @return string The directory
479 protected function getUploadDir() {
480 if ( $this->keepUploads
) {
481 // Don't use getNewTempDirectory() as this is meant to persist
482 $dir = wfTempDir() . '/mwParser-images';
484 if ( is_dir( $dir ) ) {
488 $dir = $this->getNewTempDirectory();
491 if ( file_exists( $dir ) ) {
492 wfDebug( "Already exists!\n" );
501 * Create a dummy uploads directory which will contain a couple
502 * of files in order to pass existence tests.
504 * @return string The directory
506 protected function setupUploads() {
509 $base = $this->getBaseDir();
510 $backend = RepoGroup
::singleton()->getLocalRepo()->getBackend();
511 $backend->prepare( array( 'dir' => "$base/local-public/3/3a" ) );
512 $backend->store( array(
513 'src' => "$IP/tests/phpunit/data/parser/headbg.jpg",
514 'dst' => "$base/local-public/3/3a/Foobar.jpg"
516 $backend->prepare( array( 'dir' => "$base/local-public/e/ea" ) );
517 $backend->store( array(
518 'src' => "$IP/tests/phpunit/data/parser/wiki.png",
519 'dst' => "$base/local-public/e/ea/Thumb.png"
521 $backend->prepare( array( 'dir' => "$base/local-public/0/09" ) );
522 $backend->store( array(
523 'src' => "$IP/tests/phpunit/data/parser/headbg.jpg",
524 'dst' => "$base/local-public/0/09/Bad.jpg"
526 $backend->prepare( array( 'dir' => "$base/local-public/5/5f" ) );
527 $backend->store( array(
528 'src' => "$IP/tests/phpunit/data/parser/LoremIpsum.djvu",
529 'dst' => "$base/local-public/5/5f/LoremIpsum.djvu"
532 // No helpful SVG file to copy, so make one ourselves
533 $data = '<?xml version="1.0" encoding="utf-8"?>' .
534 '<svg xmlns="http://www.w3.org/2000/svg"' .
535 ' version="1.1" width="240" height="180"/>';
537 $backend->prepare( array( 'dir' => "$base/local-public/f/ff" ) );
538 $backend->quickCreate( array(
539 'content' => $data, 'dst' => "$base/local-public/f/ff/Foobar.svg"
544 * Restore default values and perform any necessary clean-up
545 * after each test runs.
547 protected function teardownGlobals() {
548 $this->teardownUploads();
550 foreach ( $this->savedGlobals
as $var => $val ) {
551 $GLOBALS[$var] = $val;
556 * Remove the dummy uploads directory
558 private function teardownUploads() {
559 if ( $this->keepUploads
) {
563 $backend = RepoGroup
::singleton()->getLocalRepo()->getBackend();
564 if ( $backend instanceof MockFileBackend
) {
565 # In memory backend, so dont bother cleaning them up.
569 $base = $this->getBaseDir();
570 // delete the files first, then the dirs.
573 "$base/local-public/3/3a/Foobar.jpg",
574 "$base/local-thumb/3/3a/Foobar.jpg/1000px-Foobar.jpg",
575 "$base/local-thumb/3/3a/Foobar.jpg/100px-Foobar.jpg",
576 "$base/local-thumb/3/3a/Foobar.jpg/120px-Foobar.jpg",
577 "$base/local-thumb/3/3a/Foobar.jpg/1280px-Foobar.jpg",
578 "$base/local-thumb/3/3a/Foobar.jpg/137px-Foobar.jpg",
579 "$base/local-thumb/3/3a/Foobar.jpg/1500px-Foobar.jpg",
580 "$base/local-thumb/3/3a/Foobar.jpg/177px-Foobar.jpg",
581 "$base/local-thumb/3/3a/Foobar.jpg/180px-Foobar.jpg",
582 "$base/local-thumb/3/3a/Foobar.jpg/200px-Foobar.jpg",
583 "$base/local-thumb/3/3a/Foobar.jpg/206px-Foobar.jpg",
584 "$base/local-thumb/3/3a/Foobar.jpg/20px-Foobar.jpg",
585 "$base/local-thumb/3/3a/Foobar.jpg/220px-Foobar.jpg",
586 "$base/local-thumb/3/3a/Foobar.jpg/265px-Foobar.jpg",
587 "$base/local-thumb/3/3a/Foobar.jpg/270px-Foobar.jpg",
588 "$base/local-thumb/3/3a/Foobar.jpg/274px-Foobar.jpg",
589 "$base/local-thumb/3/3a/Foobar.jpg/300px-Foobar.jpg",
590 "$base/local-thumb/3/3a/Foobar.jpg/30px-Foobar.jpg",
591 "$base/local-thumb/3/3a/Foobar.jpg/330px-Foobar.jpg",
592 "$base/local-thumb/3/3a/Foobar.jpg/353px-Foobar.jpg",
593 "$base/local-thumb/3/3a/Foobar.jpg/360px-Foobar.jpg",
594 "$base/local-thumb/3/3a/Foobar.jpg/400px-Foobar.jpg",
595 "$base/local-thumb/3/3a/Foobar.jpg/40px-Foobar.jpg",
596 "$base/local-thumb/3/3a/Foobar.jpg/440px-Foobar.jpg",
597 "$base/local-thumb/3/3a/Foobar.jpg/442px-Foobar.jpg",
598 "$base/local-thumb/3/3a/Foobar.jpg/450px-Foobar.jpg",
599 "$base/local-thumb/3/3a/Foobar.jpg/50px-Foobar.jpg",
600 "$base/local-thumb/3/3a/Foobar.jpg/600px-Foobar.jpg",
601 "$base/local-thumb/3/3a/Foobar.jpg/640px-Foobar.jpg",
602 "$base/local-thumb/3/3a/Foobar.jpg/70px-Foobar.jpg",
603 "$base/local-thumb/3/3a/Foobar.jpg/75px-Foobar.jpg",
604 "$base/local-thumb/3/3a/Foobar.jpg/960px-Foobar.jpg",
606 "$base/local-public/e/ea/Thumb.png",
608 "$base/local-public/0/09/Bad.jpg",
610 "$base/local-public/5/5f/LoremIpsum.djvu",
611 "$base/local-thumb/5/5f/LoremIpsum.djvu/page2-2480px-LoremIpsum.djvu.jpg",
612 "$base/local-thumb/5/5f/LoremIpsum.djvu/page2-3720px-LoremIpsum.djvu.jpg",
613 "$base/local-thumb/5/5f/LoremIpsum.djvu/page2-4960px-LoremIpsum.djvu.jpg",
615 "$base/local-public/f/ff/Foobar.svg",
616 "$base/local-thumb/f/ff/Foobar.svg/180px-Foobar.svg.png",
617 "$base/local-thumb/f/ff/Foobar.svg/2000px-Foobar.svg.png",
618 "$base/local-thumb/f/ff/Foobar.svg/270px-Foobar.svg.png",
619 "$base/local-thumb/f/ff/Foobar.svg/3000px-Foobar.svg.png",
620 "$base/local-thumb/f/ff/Foobar.svg/360px-Foobar.svg.png",
621 "$base/local-thumb/f/ff/Foobar.svg/4000px-Foobar.svg.png",
622 "$base/local-thumb/f/ff/Foobar.svg/langde-180px-Foobar.svg.png",
623 "$base/local-thumb/f/ff/Foobar.svg/langde-270px-Foobar.svg.png",
624 "$base/local-thumb/f/ff/Foobar.svg/langde-360px-Foobar.svg.png",
626 "$base/local-public/math/f/a/5/fa50b8b616463173474302ca3e63586b.png",
632 * Delete the specified files, if they exist.
633 * @param array $files Full paths to files to delete.
635 private static function deleteFiles( $files ) {
636 $backend = RepoGroup
::singleton()->getLocalRepo()->getBackend();
637 foreach ( $files as $file ) {
638 $backend->delete( array( 'src' => $file ), array( 'force' => 1 ) );
640 foreach ( $files as $file ) {
642 while ( $tmp = FileBackend
::parentStoragePath( $tmp ) ) {
643 if ( !$backend->clean( array( 'dir' => $tmp ) )->isOK() ) {
650 protected function getBaseDir() {
651 return 'mwstore://local-backend';
654 public function parserTestProvider() {
655 if ( $this->file
=== false ) {
656 global $wgParserTestFiles;
657 $this->file
= $wgParserTestFiles[0];
660 return new TestFileIterator( $this->file
, $this );
664 * Set the file from whose tests will be run by this instance
665 * @param string $filename
667 public function setParserTestFile( $filename ) {
668 $this->file
= $filename;
673 * @dataProvider parserTestProvider
674 * @param string $desc
675 * @param string $input
676 * @param string $result
678 * @param array $config
680 public function testParserTest( $desc, $input, $result, $opts, $config ) {
681 if ( $this->regex
!= '' && !preg_match( '/' . $this->regex
. '/', $desc ) ) {
682 $this->assertTrue( true ); // XXX: don't flood output with "test made no assertions"
683 //$this->markTestSkipped( 'Filtered out by the user' );
687 if ( !$this->isWikitextNS( NS_MAIN
) ) {
688 // parser tests frequently assume that the main namespace contains wikitext.
689 // @todo When setting up pages, force the content model. Only skip if
690 // $wgtContentModelUseDB is false.
691 $this->markTestSkipped( "Main namespace does not support wikitext,"
692 . "skipping parser test: $desc" );
695 wfDebug( "Running parser test: $desc\n" );
697 $opts = $this->parseOptions( $opts );
698 $context = $this->setupGlobals( $opts, $config );
700 $user = $context->getUser();
701 $options = ParserOptions
::newFromContext( $context );
703 if ( isset( $opts['title'] ) ) {
704 $titleText = $opts['title'];
706 $titleText = 'Parser test';
709 $local = isset( $opts['local'] );
710 $preprocessor = isset( $opts['preprocessor'] ) ?
$opts['preprocessor'] : null;
711 $parser = $this->getParser( $preprocessor );
713 $title = Title
::newFromText( $titleText );
715 # Parser test requiring math. Make sure texvc is executable
716 # or just skip such tests.
717 if ( isset( $opts['math'] ) ||
isset( $opts['texvc'] ) ) {
720 if ( !isset( $wgTexvc ) ) {
721 $this->markTestSkipped( "SKIPPED: \$wgTexvc is not set" );
722 } elseif ( !is_executable( $wgTexvc ) ) {
723 $this->markTestSkipped( "SKIPPED: texvc binary does not exist"
724 . " or is not executable.\n"
725 . "Current configuration is:\n\$wgTexvc = '$wgTexvc'" );
729 if ( isset( $opts['djvu'] ) ) {
730 if ( !$this->djVuSupport
->isEnabled() ) {
731 $this->markTestSkipped( "SKIPPED: djvu binaries do not exist or are not executable.\n" );
735 if ( isset( $opts['tidy'] ) ) {
736 if ( !$this->tidySupport
->isEnabled() ) {
737 $this->markTestSkipped( "SKIPPED: tidy extension is not installed.\n" );
739 $options->setTidy( true );
743 if ( isset( $opts['pst'] ) ) {
744 $out = $parser->preSaveTransform( $input, $title, $user, $options );
745 } elseif ( isset( $opts['msg'] ) ) {
746 $out = $parser->transformMsg( $input, $options, $title );
747 } elseif ( isset( $opts['section'] ) ) {
748 $section = $opts['section'];
749 $out = $parser->getSection( $input, $section );
750 } elseif ( isset( $opts['replace'] ) ) {
751 $section = $opts['replace'][0];
752 $replace = $opts['replace'][1];
753 $out = $parser->replaceSection( $input, $section, $replace );
754 } elseif ( isset( $opts['comment'] ) ) {
755 $out = Linker
::formatComment( $input, $title, $local );
756 } elseif ( isset( $opts['preload'] ) ) {
757 $out = $parser->getPreloadText( $input, $title, $options );
759 $output = $parser->parse( $input, $title, $options, true, true, 1337 );
760 $output->setTOCEnabled( !isset( $opts['notoc'] ) );
761 $out = $output->getText();
762 if ( isset( $opts['tidy'] ) ) {
763 $out = preg_replace( '/\s+$/', '', $out );
766 if ( isset( $opts['showtitle'] ) ) {
767 if ( $output->getTitleText() ) {
768 $title = $output->getTitleText();
771 $out = "$title\n$out";
774 if ( isset( $opts['showindicators'] ) ) {
776 foreach ( $output->getIndicators() as $id => $content ) {
777 $indicators .= "$id=$content\n";
779 $out = $indicators . $out;
782 if ( isset( $opts['ill'] ) ) {
783 $out = implode( ' ', $output->getLanguageLinks() );
784 } elseif ( isset( $opts['cat'] ) ) {
785 $outputPage = $context->getOutput();
786 $outputPage->addCategoryLinks( $output->getCategories() );
787 $cats = $outputPage->getCategoryLinks();
789 if ( isset( $cats['normal'] ) ) {
790 $out = implode( ' ', $cats['normal'] );
795 $parser->mPreprocessor
= null;
798 $this->teardownGlobals();
800 $this->assertEquals( $result, $out, $desc );
804 * Run a fuzz test series
805 * Draw input from a set of test files
807 * @todo fixme Needs some work to not eat memory until the world explodes
811 public function testFuzzTests() {
812 global $wgParserTestFiles;
814 $files = $wgParserTestFiles;
816 if ( $this->getCliArg( 'file' ) ) {
817 $files = array( $this->getCliArg( 'file' ) );
820 $dict = $this->getFuzzInput( $files );
821 $dictSize = strlen( $dict );
822 $logMaxLength = log( $this->maxFuzzTestLength
);
824 ini_set( 'memory_limit', $this->memoryLimit
* 1048576 );
827 $opts = ParserOptions
::newFromUser( $user );
828 $title = Title
::makeTitle( NS_MAIN
, 'Parser_test' );
834 // Generate test input
835 mt_srand( ++
$this->fuzzSeed
);
836 $totalLength = mt_rand( 1, $this->maxFuzzTestLength
);
839 while ( strlen( $input ) < $totalLength ) {
840 $logHairLength = mt_rand( 0, 1000000 ) / 1000000 * $logMaxLength;
841 $hairLength = min( intval( exp( $logHairLength ) ), $dictSize );
842 $offset = mt_rand( 0, $dictSize - $hairLength );
843 $input .= substr( $dict, $offset, $hairLength );
846 $this->setupGlobals();
847 $parser = $this->getParser();
851 $parser->parse( $input, $title, $opts );
852 $this->assertTrue( true, "Test $id, fuzz seed {$this->fuzzSeed}" );
853 } catch ( Exception
$exception ) {
854 $input_dump = sprintf( "string(%d) \"%s\"\n", strlen( $input ), $input );
856 $this->assertTrue( false, "Test $id, fuzz seed {$this->fuzzSeed}. \n\n" .
857 "Input: $input_dump\n\nError: {$exception->getMessage()}\n\n" .
858 "Backtrace: {$exception->getTraceAsString()}" );
861 $this->teardownGlobals();
862 $parser->__destruct();
864 if ( $id %
100 == 0 ) {
865 $usage = intval( memory_get_usage( true ) / $this->memoryLimit
/ 1048576 * 100 );
866 //echo "{$this->fuzzSeed}: $numSuccess/$numTotal (mem: $usage%)\n";
868 $ret = "Out of memory:\n";
869 $memStats = $this->getMemoryBreakdown();
871 foreach ( $memStats as $name => $usage ) {
872 $ret .= "$name: $usage\n";
875 throw new MWException( $ret );
883 //Various getter functions
886 * Get an input dictionary from a set of parser test files
887 * @param array $filenames
890 function getFuzzInput( $filenames ) {
893 foreach ( $filenames as $filename ) {
894 $contents = file_get_contents( $filename );
895 preg_match_all( '/!!\s*input\n(.*?)\n!!\s*result/s', $contents, $matches );
897 foreach ( $matches[1] as $match ) {
898 $dict .= $match . "\n";
906 * Get a memory usage breakdown
909 function getMemoryBreakdown() {
912 foreach ( $GLOBALS as $name => $value ) {
913 $memStats['$' . $name] = strlen( serialize( $value ) );
916 $classes = get_declared_classes();
918 foreach ( $classes as $class ) {
919 $rc = new ReflectionClass( $class );
920 $props = $rc->getStaticProperties();
921 $memStats[$class] = strlen( serialize( $props ) );
922 $methods = $rc->getMethods();
924 foreach ( $methods as $method ) {
925 $memStats[$class] +
= strlen( serialize( $method->getStaticVariables() ) );
929 $functions = get_defined_functions();
931 foreach ( $functions['user'] as $function ) {
932 $rf = new ReflectionFunction( $function );
933 $memStats["$function()"] = strlen( serialize( $rf->getStaticVariables() ) );
942 * Get a Parser object
943 * @param Preprocessor $preprocessor
946 function getParser( $preprocessor = null ) {
947 global $wgParserConf;
949 $class = $wgParserConf['class'];
950 $parser = new $class( array( 'preprocessorClass' => $preprocessor ) +
$wgParserConf );
952 Hooks
::run( 'ParserTestParser', array( &$parser ) );
957 //Various action functions
959 public function addArticle( $name, $text, $line ) {
960 self
::$articles[$name] = array( $text, $line );
963 public function publishTestArticles() {
964 if ( empty( self
::$articles ) ) {
968 foreach ( self
::$articles as $name => $info ) {
969 list( $text, $line ) = $info;
970 ParserTest
::addArticle( $name, $text, $line, 'ignoreduplicate' );
975 * Steal a callback function from the primary parser, save it for
976 * application to our scary parser. If the hook is not installed,
977 * abort processing of this file.
979 * @param string $name
980 * @return bool True if tag hook is present
982 public function requireHook( $name ) {
984 $wgParser->firstCallInit(); // make sure hooks are loaded.
985 return isset( $wgParser->mTagHooks
[$name] );
988 public function requireFunctionHook( $name ) {
990 $wgParser->firstCallInit(); // make sure hooks are loaded.
991 return isset( $wgParser->mFunctionHooks
[$name] );
994 public function requireTransparentHook( $name ) {
996 $wgParser->firstCallInit(); // make sure hooks are loaded.
997 return isset( $wgParser->mTransparentTagHooks
[$name] );
1000 //Various "cleanup" functions
1003 * Remove last character if it is a newline
1007 public function removeEndingNewline( $s ) {
1008 if ( substr( $s, -1 ) === "\n" ) {
1009 return substr( $s, 0, -1 );
1015 //Test options parser functions
1017 protected function parseOptions( $instring ) {
1023 // foo=bar,"baz quux"
1045 "[^"]*" # Quoted val
1047 \[\[[^]]*\]\] # Link target
1055 if ( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER
) ) {
1056 foreach ( $matches as $bits ) {
1057 array_shift( $bits );
1058 $key = strtolower( array_shift( $bits ) );
1059 if ( count( $bits ) == 0 ) {
1061 } elseif ( count( $bits ) == 1 ) {
1062 $opts[$key] = $this->cleanupOption( array_shift( $bits ) );
1065 $opts[$key] = array_map( array( $this, 'cleanupOption' ), $bits );
1073 protected function cleanupOption( $opt ) {
1074 if ( substr( $opt, 0, 1 ) == '"' ) {
1075 return substr( $opt, 1, -1 );
1078 if ( substr( $opt, 0, 2 ) == '[[' ) {
1079 return substr( $opt, 2, -2 );
1086 * Use a regex to find out the value of an option
1087 * @param string $key Name of option val to retrieve
1088 * @param array $opts Options array to look in
1089 * @param mixed $default Default value returned if not found
1092 protected static function getOptionValue( $key, $opts, $default ) {
1093 $key = strtolower( $key );
1095 if ( isset( $opts[$key] ) ) {