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