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 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,
422 $configLines = explode( "\n", $config );
424 foreach ( $configLines as $line ) {
425 list( $var, $value ) = explode( '=', $line, 2 );
427 $settings[$var] = eval( "return $value;" ); //???
431 $this->savedGlobals
= array();
434 wfRunHooks( 'ParserTestGlobals', array( &$settings ) );
436 $langObj = Language
::factory( $lang );
437 $settings['wgContLang'] = $langObj;
438 $settings['wgLang'] = $langObj;
440 $context = new RequestContext();
441 $settings['wgOut'] = $context->getOutput();
442 $settings['wgUser'] = $context->getUser();
443 $settings['wgRequest'] = $context->getRequest();
445 // We (re)set $wgThumbLimits to a single-element array above.
446 $context->getUser()->setOption( 'thumbsize', 0 );
448 foreach ( $settings as $var => $val ) {
449 if ( array_key_exists( $var, $GLOBALS ) ) {
450 $this->savedGlobals
[$var] = $GLOBALS[$var];
453 $GLOBALS[$var] = $val;
456 MagicWord
::clearCache();
458 # The entries saved into RepoGroup cache with previous globals will be wrong.
459 RepoGroup
::destroySingleton();
460 FileBackendGroup
::destroySingleton();
462 # Create dummy files in storage
463 $this->setupUploads();
465 # Publish the articles after we have the final language set
466 $this->publishTestArticles();
468 MessageCache
::destroyInstance();
474 * Get an FS upload directory (only applies to FSFileBackend)
476 * @return string The directory
478 protected function getUploadDir() {
479 if ( $this->keepUploads
) {
480 $dir = wfTempDir() . '/mwParser-images';
482 if ( is_dir( $dir ) ) {
486 $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
489 // wfDebug( "Creating upload directory $dir\n" );
490 if ( file_exists( $dir ) ) {
491 wfDebug( "Already exists!\n" );
500 * Create a dummy uploads directory which will contain a couple
501 * of files in order to pass existence tests.
503 * @return string The directory
505 protected function setupUploads() {
508 $base = $this->getBaseDir();
509 $backend = RepoGroup
::singleton()->getLocalRepo()->getBackend();
510 $backend->prepare( array( 'dir' => "$base/local-public/3/3a" ) );
511 $backend->store( array(
512 'src' => "$IP/tests/phpunit/data/parser/headbg.jpg",
513 'dst' => "$base/local-public/3/3a/Foobar.jpg"
515 $backend->prepare( array( 'dir' => "$base/local-public/e/ea" ) );
516 $backend->store( array(
517 'src' => "$IP/tests/phpunit/data/parser/wiki.png",
518 'dst' => "$base/local-public/e/ea/Thumb.png"
520 $backend->prepare( array( 'dir' => "$base/local-public/0/09" ) );
521 $backend->store( array(
522 'src' => "$IP/tests/phpunit/data/parser/headbg.jpg",
523 'dst' => "$base/local-public/0/09/Bad.jpg"
525 $backend->prepare( array( 'dir' => "$base/local-public/5/5f" ) );
526 $backend->store( array(
527 'src' => "$IP/tests/phpunit/data/parser/LoremIpsum.djvu",
528 'dst' => "$base/local-public/5/5f/LoremIpsum.djvu"
531 // No helpful SVG file to copy, so make one ourselves
532 $data = '<?xml version="1.0" encoding="utf-8"?>' .
533 '<svg xmlns="http://www.w3.org/2000/svg"' .
534 ' version="1.1" width="240" height="180"/>';
536 $backend->prepare( array( 'dir' => "$base/local-public/f/ff" ) );
537 $backend->quickCreate( array(
538 'content' => $data, 'dst' => "$base/local-public/f/ff/Foobar.svg"
543 * Restore default values and perform any necessary clean-up
544 * after each test runs.
546 protected function teardownGlobals() {
547 $this->teardownUploads();
549 foreach ( $this->savedGlobals
as $var => $val ) {
550 $GLOBALS[$var] = $val;
555 * Remove the dummy uploads directory
557 private function teardownUploads() {
558 if ( $this->keepUploads
) {
562 $backend = RepoGroup
::singleton()->getLocalRepo()->getBackend();
563 if ( $backend instanceof MockFileBackend
) {
564 # In memory backend, so dont bother cleaning them up.
568 $base = $this->getBaseDir();
569 // delete the files first, then the dirs.
572 "$base/local-public/3/3a/Foobar.jpg",
573 "$base/local-thumb/3/3a/Foobar.jpg/1000px-Foobar.jpg",
574 "$base/local-thumb/3/3a/Foobar.jpg/100px-Foobar.jpg",
575 "$base/local-thumb/3/3a/Foobar.jpg/120px-Foobar.jpg",
576 "$base/local-thumb/3/3a/Foobar.jpg/1280px-Foobar.jpg",
577 "$base/local-thumb/3/3a/Foobar.jpg/137px-Foobar.jpg",
578 "$base/local-thumb/3/3a/Foobar.jpg/1500px-Foobar.jpg",
579 "$base/local-thumb/3/3a/Foobar.jpg/177px-Foobar.jpg",
580 "$base/local-thumb/3/3a/Foobar.jpg/180px-Foobar.jpg",
581 "$base/local-thumb/3/3a/Foobar.jpg/200px-Foobar.jpg",
582 "$base/local-thumb/3/3a/Foobar.jpg/206px-Foobar.jpg",
583 "$base/local-thumb/3/3a/Foobar.jpg/20px-Foobar.jpg",
584 "$base/local-thumb/3/3a/Foobar.jpg/220px-Foobar.jpg",
585 "$base/local-thumb/3/3a/Foobar.jpg/265px-Foobar.jpg",
586 "$base/local-thumb/3/3a/Foobar.jpg/270px-Foobar.jpg",
587 "$base/local-thumb/3/3a/Foobar.jpg/274px-Foobar.jpg",
588 "$base/local-thumb/3/3a/Foobar.jpg/300px-Foobar.jpg",
589 "$base/local-thumb/3/3a/Foobar.jpg/30px-Foobar.jpg",
590 "$base/local-thumb/3/3a/Foobar.jpg/330px-Foobar.jpg",
591 "$base/local-thumb/3/3a/Foobar.jpg/353px-Foobar.jpg",
592 "$base/local-thumb/3/3a/Foobar.jpg/360px-Foobar.jpg",
593 "$base/local-thumb/3/3a/Foobar.jpg/400px-Foobar.jpg",
594 "$base/local-thumb/3/3a/Foobar.jpg/40px-Foobar.jpg",
595 "$base/local-thumb/3/3a/Foobar.jpg/440px-Foobar.jpg",
596 "$base/local-thumb/3/3a/Foobar.jpg/442px-Foobar.jpg",
597 "$base/local-thumb/3/3a/Foobar.jpg/450px-Foobar.jpg",
598 "$base/local-thumb/3/3a/Foobar.jpg/50px-Foobar.jpg",
599 "$base/local-thumb/3/3a/Foobar.jpg/600px-Foobar.jpg",
600 "$base/local-thumb/3/3a/Foobar.jpg/640px-Foobar.jpg",
601 "$base/local-thumb/3/3a/Foobar.jpg/70px-Foobar.jpg",
602 "$base/local-thumb/3/3a/Foobar.jpg/75px-Foobar.jpg",
603 "$base/local-thumb/3/3a/Foobar.jpg/960px-Foobar.jpg",
605 "$base/local-public/e/ea/Thumb.png",
607 "$base/local-public/0/09/Bad.jpg",
609 "$base/local-public/5/5f/LoremIpsum.djvu",
610 "$base/local-thumb/5/5f/LoremIpsum.djvu/page2-2480px-LoremIpsum.djvu.jpg",
611 "$base/local-thumb/5/5f/LoremIpsum.djvu/page2-3720px-LoremIpsum.djvu.jpg",
612 "$base/local-thumb/5/5f/LoremIpsum.djvu/page2-4960px-LoremIpsum.djvu.jpg",
614 "$base/local-public/f/ff/Foobar.svg",
615 "$base/local-thumb/f/ff/Foobar.svg/180px-Foobar.svg.png",
616 "$base/local-thumb/f/ff/Foobar.svg/2000px-Foobar.svg.png",
617 "$base/local-thumb/f/ff/Foobar.svg/270px-Foobar.svg.png",
618 "$base/local-thumb/f/ff/Foobar.svg/3000px-Foobar.svg.png",
619 "$base/local-thumb/f/ff/Foobar.svg/360px-Foobar.svg.png",
620 "$base/local-thumb/f/ff/Foobar.svg/4000px-Foobar.svg.png",
621 "$base/local-thumb/f/ff/Foobar.svg/langde-180px-Foobar.svg.png",
622 "$base/local-thumb/f/ff/Foobar.svg/langde-270px-Foobar.svg.png",
623 "$base/local-thumb/f/ff/Foobar.svg/langde-360px-Foobar.svg.png",
625 "$base/local-public/math/f/a/5/fa50b8b616463173474302ca3e63586b.png",
631 * Delete the specified files, if they exist.
632 * @param array $files Full paths to files to delete.
634 private static function deleteFiles( $files ) {
635 $backend = RepoGroup
::singleton()->getLocalRepo()->getBackend();
636 foreach ( $files as $file ) {
637 $backend->delete( array( 'src' => $file ), array( 'force' => 1 ) );
639 foreach ( $files as $file ) {
641 while ( $tmp = FileBackend
::parentStoragePath( $tmp ) ) {
642 if ( !$backend->clean( array( 'dir' => $tmp ) )->isOK() ) {
649 protected function getBaseDir() {
650 return 'mwstore://local-backend';
653 public function parserTestProvider() {
654 if ( $this->file
=== false ) {
655 global $wgParserTestFiles;
656 $this->file
= $wgParserTestFiles[0];
659 return new TestFileIterator( $this->file
, $this );
663 * Set the file from whose tests will be run by this instance
664 * @param string $filename
666 public function setParserTestFile( $filename ) {
667 $this->file
= $filename;
672 * @dataProvider parserTestProvider
673 * @param string $desc
674 * @param string $input
675 * @param string $result
677 * @param array $config
679 public function testParserTest( $desc, $input, $result, $opts, $config ) {
680 if ( $this->regex
!= '' && !preg_match( '/' . $this->regex
. '/', $desc ) ) {
681 $this->assertTrue( true ); // XXX: don't flood output with "test made no assertions"
682 //$this->markTestSkipped( 'Filtered out by the user' );
686 if ( !$this->isWikitextNS( NS_MAIN
) ) {
687 // parser tests frequently assume that the main namespace contains wikitext.
688 // @todo When setting up pages, force the content model. Only skip if
689 // $wgtContentModelUseDB is false.
690 $this->markTestSkipped( "Main namespace does not support wikitext,"
691 . "skipping parser test: $desc" );
694 wfDebug( "Running parser test: $desc\n" );
696 $opts = $this->parseOptions( $opts );
697 $context = $this->setupGlobals( $opts, $config );
699 $user = $context->getUser();
700 $options = ParserOptions
::newFromContext( $context );
702 if ( isset( $opts['title'] ) ) {
703 $titleText = $opts['title'];
705 $titleText = 'Parser test';
708 $local = isset( $opts['local'] );
709 $preprocessor = isset( $opts['preprocessor'] ) ?
$opts['preprocessor'] : null;
710 $parser = $this->getParser( $preprocessor );
712 $title = Title
::newFromText( $titleText );
714 # Parser test requiring math. Make sure texvc is executable
715 # or just skip such tests.
716 if ( isset( $opts['math'] ) ||
isset( $opts['texvc'] ) ) {
719 if ( !isset( $wgTexvc ) ) {
720 $this->markTestSkipped( "SKIPPED: \$wgTexvc is not set" );
721 } elseif ( !is_executable( $wgTexvc ) ) {
722 $this->markTestSkipped( "SKIPPED: texvc binary does not exist"
723 . " or is not executable.\n"
724 . "Current configuration is:\n\$wgTexvc = '$wgTexvc'" );
727 if ( isset( $opts['djvu'] ) ) {
728 if ( !$this->djVuSupport
->isEnabled() ) {
729 $this->markTestSkipped( "SKIPPED: djvu binaries do not exist or are not executable.\n" );
733 if ( isset( $opts['pst'] ) ) {
734 $out = $parser->preSaveTransform( $input, $title, $user, $options );
735 } elseif ( isset( $opts['msg'] ) ) {
736 $out = $parser->transformMsg( $input, $options, $title );
737 } elseif ( isset( $opts['section'] ) ) {
738 $section = $opts['section'];
739 $out = $parser->getSection( $input, $section );
740 } elseif ( isset( $opts['replace'] ) ) {
741 $section = $opts['replace'][0];
742 $replace = $opts['replace'][1];
743 $out = $parser->replaceSection( $input, $section, $replace );
744 } elseif ( isset( $opts['comment'] ) ) {
745 $out = Linker
::formatComment( $input, $title, $local );
746 } elseif ( isset( $opts['preload'] ) ) {
747 $out = $parser->getPreloadText( $input, $title, $options );
749 $output = $parser->parse( $input, $title, $options, true, true, 1337 );
750 $output->setTOCEnabled( !isset( $opts['notoc'] ) );
751 $out = $output->getText();
752 if ( isset( $opts['tidy'] ) ) {
753 if ( !$this->tidySupport
->isEnabled() ) {
754 $this->markTestSkipped( "SKIPPED: tidy extension is not installed.\n" );
756 $out = MWTidy
::tidy( $out );
757 $out = preg_replace( '/\s+$/', '', $out);
761 if ( isset( $opts['showtitle'] ) ) {
762 if ( $output->getTitleText() ) {
763 $title = $output->getTitleText();
766 $out = "$title\n$out";
769 if ( isset( $opts['ill'] ) ) {
770 $out = implode( ' ', $output->getLanguageLinks() );
771 } elseif ( isset( $opts['cat'] ) ) {
772 $outputPage = $context->getOutput();
773 $outputPage->addCategoryLinks( $output->getCategories() );
774 $cats = $outputPage->getCategoryLinks();
776 if ( isset( $cats['normal'] ) ) {
777 $out = implode( ' ', $cats['normal'] );
782 $parser->mPreprocessor
= null;
785 $this->teardownGlobals();
787 $this->assertEquals( $result, $out, $desc );
791 * Run a fuzz test series
792 * Draw input from a set of test files
794 * @todo fixme Needs some work to not eat memory until the world explodes
798 public function testFuzzTests() {
799 global $wgParserTestFiles;
801 $files = $wgParserTestFiles;
803 if ( $this->getCliArg( 'file' ) ) {
804 $files = array( $this->getCliArg( 'file' ) );
807 $dict = $this->getFuzzInput( $files );
808 $dictSize = strlen( $dict );
809 $logMaxLength = log( $this->maxFuzzTestLength
);
811 ini_set( 'memory_limit', $this->memoryLimit
* 1048576 );
814 $opts = ParserOptions
::newFromUser( $user );
815 $title = Title
::makeTitle( NS_MAIN
, 'Parser_test' );
821 // Generate test input
822 mt_srand( ++
$this->fuzzSeed
);
823 $totalLength = mt_rand( 1, $this->maxFuzzTestLength
);
826 while ( strlen( $input ) < $totalLength ) {
827 $logHairLength = mt_rand( 0, 1000000 ) / 1000000 * $logMaxLength;
828 $hairLength = min( intval( exp( $logHairLength ) ), $dictSize );
829 $offset = mt_rand( 0, $dictSize - $hairLength );
830 $input .= substr( $dict, $offset, $hairLength );
833 $this->setupGlobals();
834 $parser = $this->getParser();
838 $parser->parse( $input, $title, $opts );
839 $this->assertTrue( true, "Test $id, fuzz seed {$this->fuzzSeed}" );
840 } catch ( Exception
$exception ) {
841 $input_dump = sprintf( "string(%d) \"%s\"\n", strlen( $input ), $input );
843 $this->assertTrue( false, "Test $id, fuzz seed {$this->fuzzSeed}. \n\n" .
844 "Input: $input_dump\n\nError: {$exception->getMessage()}\n\n" .
845 "Backtrace: {$exception->getTraceAsString()}" );
848 $this->teardownGlobals();
849 $parser->__destruct();
851 if ( $id %
100 == 0 ) {
852 $usage = intval( memory_get_usage( true ) / $this->memoryLimit
/ 1048576 * 100 );
853 //echo "{$this->fuzzSeed}: $numSuccess/$numTotal (mem: $usage%)\n";
855 $ret = "Out of memory:\n";
856 $memStats = $this->getMemoryBreakdown();
858 foreach ( $memStats as $name => $usage ) {
859 $ret .= "$name: $usage\n";
862 throw new MWException( $ret );
870 //Various getter functions
873 * Get an input dictionary from a set of parser test files
874 * @param array $filenames
876 function getFuzzInput( $filenames ) {
879 foreach ( $filenames as $filename ) {
880 $contents = file_get_contents( $filename );
881 preg_match_all( '/!!\s*input\n(.*?)\n!!\s*result/s', $contents, $matches );
883 foreach ( $matches[1] as $match ) {
884 $dict .= $match . "\n";
892 * Get a memory usage breakdown
894 function getMemoryBreakdown() {
897 foreach ( $GLOBALS as $name => $value ) {
898 $memStats['$' . $name] = strlen( serialize( $value ) );
901 $classes = get_declared_classes();
903 foreach ( $classes as $class ) {
904 $rc = new ReflectionClass( $class );
905 $props = $rc->getStaticProperties();
906 $memStats[$class] = strlen( serialize( $props ) );
907 $methods = $rc->getMethods();
909 foreach ( $methods as $method ) {
910 $memStats[$class] +
= strlen( serialize( $method->getStaticVariables() ) );
914 $functions = get_defined_functions();
916 foreach ( $functions['user'] as $function ) {
917 $rf = new ReflectionFunction( $function );
918 $memStats["$function()"] = strlen( serialize( $rf->getStaticVariables() ) );
927 * Get a Parser object
928 * @param Preprocessor $preprocessor
930 function getParser( $preprocessor = null ) {
931 global $wgParserConf;
933 $class = $wgParserConf['class'];
934 $parser = new $class( array( 'preprocessorClass' => $preprocessor ) +
$wgParserConf );
936 wfRunHooks( 'ParserTestParser', array( &$parser ) );
941 //Various action functions
943 public function addArticle( $name, $text, $line ) {
944 self
::$articles[$name] = array( $text, $line );
947 public function publishTestArticles() {
948 if ( empty( self
::$articles ) ) {
952 foreach ( self
::$articles as $name => $info ) {
953 list( $text, $line ) = $info;
954 ParserTest
::addArticle( $name, $text, $line, 'ignoreduplicate' );
959 * Steal a callback function from the primary parser, save it for
960 * application to our scary parser. If the hook is not installed,
961 * abort processing of this file.
963 * @param string $name
964 * @return bool True if tag hook is present
966 public function requireHook( $name ) {
968 $wgParser->firstCallInit(); // make sure hooks are loaded.
969 return isset( $wgParser->mTagHooks
[$name] );
972 public function requireFunctionHook( $name ) {
974 $wgParser->firstCallInit(); // make sure hooks are loaded.
975 return isset( $wgParser->mFunctionHooks
[$name] );
978 public function requireTransparentHook( $name ) {
980 $wgParser->firstCallInit(); // make sure hooks are loaded.
981 return isset( $wgParser->mTransparentTagHooks
[$name] );
984 //Various "cleanup" functions
987 * Remove last character if it is a newline
990 public function removeEndingNewline( $s ) {
991 if ( substr( $s, -1 ) === "\n" ) {
992 return substr( $s, 0, -1 );
998 //Test options parser functions
1000 protected function parseOptions( $instring ) {
1006 // foo=bar,"baz quux"
1028 "[^"]*" # Quoted val
1030 \[\[[^]]*\]\] # Link target
1038 if ( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER
) ) {
1039 foreach ( $matches as $bits ) {
1040 array_shift( $bits );
1041 $key = strtolower( array_shift( $bits ) );
1042 if ( count( $bits ) == 0 ) {
1044 } elseif ( count( $bits ) == 1 ) {
1045 $opts[$key] = $this->cleanupOption( array_shift( $bits ) );
1048 $opts[$key] = array_map( array( $this, 'cleanupOption' ), $bits );
1056 protected function cleanupOption( $opt ) {
1057 if ( substr( $opt, 0, 1 ) == '"' ) {
1058 return substr( $opt, 1, -1 );
1061 if ( substr( $opt, 0, 2 ) == '[[' ) {
1062 return substr( $opt, 2, -2 );
1069 * Use a regex to find out the value of an option
1070 * @param string $key Name of option val to retrieve
1071 * @param array $opts Options array to look in
1072 * @param mixed $default Default value returned if not found
1074 protected static function getOptionValue( $key, $opts, $default ) {
1075 $key = strtolower( $key );
1077 if ( isset( $opts[$key] ) ) {