Parser tests: Make Foobar.svg consistent.
[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' => 240,
267 'height' => 180,
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 = $useConfig['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 ) );
323 }
324
325 $settings = array(
326 'wgLocalFileRepo' => array(
327 'class' => 'LocalRepo',
328 'name' => 'local',
329 'url' => 'http://example.com/images',
330 'hashLevels' => 2,
331 'transformVia404' => false,
332 'backend' => $backend
333 ),
334 'wgEnableUploads' => self::getOptionValue( 'wgEnableUploads', $opts, true ),
335 'wgLanguageCode' => $lang,
336 'wgDBprefix' => $this->db->getType() != 'oracle' ? 'unittest_' : 'ut_',
337 'wgRawHtml' => self::getOptionValue( 'wgRawHtml', $opts, false ),
338 'wgNamespacesWithSubpages' => array( NS_MAIN => isset( $opts['subpage'] ) ),
339 'wgAllowExternalImages' => self::getOptionValue( 'wgAllowExternalImages', $opts, true ),
340 'wgMaxTocLevel' => $maxtoclevel,
341 'wgUseTeX' => isset( $opts['math'] ) || isset( $opts['texvc'] ),
342 'wgMathDirectory' => $uploadDir . '/math',
343 'wgDefaultLanguageVariant' => $variant,
344 'wgLinkHolderBatchSize' => $linkHolderBatchSize,
345 );
346
347 if ( $config ) {
348 $configLines = explode( "\n", $config );
349
350 foreach ( $configLines as $line ) {
351 list( $var, $value ) = explode( '=', $line, 2 );
352
353 $settings[$var] = eval( "return $value;" ); //???
354 }
355 }
356
357 $this->savedGlobals = array();
358
359 /** @since 1.20 */
360 wfRunHooks( 'ParserTestGlobals', array( &$settings ) );
361
362 $langObj = Language::factory( $lang );
363 $settings['wgContLang'] = $langObj;
364 $settings['wgLang'] = $langObj;
365
366 $context = new RequestContext();
367 $settings['wgOut'] = $context->getOutput();
368 $settings['wgUser'] = $context->getUser();
369 $settings['wgRequest'] = $context->getRequest();
370
371 foreach ( $settings as $var => $val ) {
372 if ( array_key_exists( $var, $GLOBALS ) ) {
373 $this->savedGlobals[$var] = $GLOBALS[$var];
374 }
375
376 $GLOBALS[$var] = $val;
377 }
378
379 MagicWord::clearCache();
380
381 # The entries saved into RepoGroup cache with previous globals will be wrong.
382 RepoGroup::destroySingleton();
383 FileBackendGroup::destroySingleton();
384
385 # Create dummy files in storage
386 $this->setupUploads();
387
388 # Publish the articles after we have the final language set
389 $this->publishTestArticles();
390
391 MessageCache::destroyInstance();
392
393 return $context;
394 }
395
396 /**
397 * Get an FS upload directory (only applies to FSFileBackend)
398 *
399 * @return String: the directory
400 */
401 protected function getUploadDir() {
402 if ( $this->keepUploads ) {
403 $dir = wfTempDir() . '/mwParser-images';
404
405 if ( is_dir( $dir ) ) {
406 return $dir;
407 }
408 } else {
409 $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
410 }
411
412 // wfDebug( "Creating upload directory $dir\n" );
413 if ( file_exists( $dir ) ) {
414 wfDebug( "Already exists!\n" );
415
416 return $dir;
417 }
418
419 return $dir;
420 }
421
422 /**
423 * Create a dummy uploads directory which will contain a couple
424 * of files in order to pass existence tests.
425 *
426 * @return String: the directory
427 */
428 protected function setupUploads() {
429 global $IP;
430
431 $base = $this->getBaseDir();
432 $backend = RepoGroup::singleton()->getLocalRepo()->getBackend();
433 $backend->prepare( array( 'dir' => "$base/local-public/3/3a" ) );
434 $backend->store( array(
435 'src' => "$IP/skins/monobook/headbg.jpg", 'dst' => "$base/local-public/3/3a/Foobar.jpg"
436 ) );
437 $backend->prepare( array( 'dir' => "$base/local-public/e/ea" ) );
438 $backend->store( array(
439 'src' => "$IP/skins/monobook/wiki.png", 'dst' => "$base/local-public/e/ea/Thumb.png"
440 ) );
441 $backend->prepare( array( 'dir' => "$base/local-public/0/09" ) );
442 $backend->store( array(
443 'src' => "$IP/skins/monobook/headbg.jpg", 'dst' => "$base/local-public/0/09/Bad.jpg"
444 ) );
445
446 // No helpful SVG file to copy, so make one ourselves
447 $data = '<?xml version="1.0" encoding="utf-8"?>' .
448 '<svg xmlns="http://www.w3.org/2000/svg"' .
449 ' version="1.1" width="240" height="180"/>';
450
451 $backend->prepare( array( 'dir' => "$base/local-public/f/ff" ) );
452 $backend->quickCreate( array(
453 'content' => $data, 'dst' => "$base/local-public/f/ff/Foobar.svg"
454 ) );
455 }
456
457 /**
458 * Restore default values and perform any necessary clean-up
459 * after each test runs.
460 */
461 protected function teardownGlobals() {
462 $this->teardownUploads();
463
464 foreach ( $this->savedGlobals as $var => $val ) {
465 $GLOBALS[$var] = $val;
466 }
467 }
468
469 /**
470 * Remove the dummy uploads directory
471 */
472 private function teardownUploads() {
473 if ( $this->keepUploads ) {
474 return;
475 }
476
477 $backend = RepoGroup::singleton()->getLocalRepo()->getBackend();
478 if ( $backend instanceof MockFileBackend ) {
479 # In memory backend, so dont bother cleaning them up.
480 return;
481 }
482
483 $base = $this->getBaseDir();
484 // delete the files first, then the dirs.
485 self::deleteFiles(
486 array(
487 "$base/local-public/3/3a/Foobar.jpg",
488 "$base/local-thumb/3/3a/Foobar.jpg/180px-Foobar.jpg",
489 "$base/local-thumb/3/3a/Foobar.jpg/200px-Foobar.jpg",
490 "$base/local-thumb/3/3a/Foobar.jpg/640px-Foobar.jpg",
491 "$base/local-thumb/3/3a/Foobar.jpg/120px-Foobar.jpg",
492 "$base/local-thumb/3/3a/Foobar.jpg/1280px-Foobar.jpg",
493 "$base/local-thumb/3/3a/Foobar.jpg/20px-Foobar.jpg",
494 "$base/local-thumb/3/3a/Foobar.jpg/270px-Foobar.jpg",
495 "$base/local-thumb/3/3a/Foobar.jpg/300px-Foobar.jpg",
496 "$base/local-thumb/3/3a/Foobar.jpg/30px-Foobar.jpg",
497 "$base/local-thumb/3/3a/Foobar.jpg/360px-Foobar.jpg",
498 "$base/local-thumb/3/3a/Foobar.jpg/400px-Foobar.jpg",
499 "$base/local-thumb/3/3a/Foobar.jpg/40px-Foobar.jpg",
500 "$base/local-thumb/3/3a/Foobar.jpg/70px-Foobar.jpg",
501 "$base/local-thumb/3/3a/Foobar.jpg/960px-Foobar.jpg",
502
503 "$base/local-public/e/ea/Thumb.png",
504
505 "$base/local-public/0/09/Bad.jpg",
506
507 "$base/local-public/f/ff/Foobar.svg",
508 "$base/local-thumb/f/ff/Foobar.svg/180px-Foobar.svg.jpg",
509 "$base/local-thumb/f/ff/Foobar.svg/270px-Foobar.svg.jpg",
510 "$base/local-thumb/f/ff/Foobar.svg/360px-Foobar.svg.jpg",
511 "$base/local-thumb/f/ff/Foobar.svg/langde-180px-Foobar.svg.jpg",
512 "$base/local-thumb/f/ff/Foobar.svg/langde-270px-Foobar.svg.jpg",
513 "$base/local-thumb/f/ff/Foobar.svg/langde-360px-Foobar.svg.jpg",
514
515 "$base/local-public/math/f/a/5/fa50b8b616463173474302ca3e63586b.png",
516 )
517 );
518 }
519
520 /**
521 * Delete the specified files, if they exist.
522 * @param $files Array: full paths to files to delete.
523 */
524 private static function deleteFiles( $files ) {
525 $backend = RepoGroup::singleton()->getLocalRepo()->getBackend();
526 foreach ( $files as $file ) {
527 $backend->delete( array( 'src' => $file ), array( 'force' => 1 ) );
528 }
529 foreach ( $files as $file ) {
530 $tmp = $file;
531 while ( $tmp = FileBackend::parentStoragePath( $tmp ) ) {
532 if ( !$backend->clean( array( 'dir' => $tmp ) )->isOK() ) {
533 break;
534 }
535 }
536 }
537 }
538
539 protected function getBaseDir() {
540 return 'mwstore://local-backend';
541 }
542
543 public function parserTestProvider() {
544 if ( $this->file === false ) {
545 global $wgParserTestFiles;
546 $this->file = $wgParserTestFiles[0];
547 }
548
549 return new TestFileIterator( $this->file, $this );
550 }
551
552 /**
553 * Set the file from whose tests will be run by this instance
554 */
555 public function setParserTestFile( $filename ) {
556 $this->file = $filename;
557 }
558
559 /**
560 * @group medium
561 * @dataProvider parserTestProvider
562 */
563 public function testParserTest( $desc, $input, $result, $opts, $config ) {
564 if ( $this->regex != '' && !preg_match( '/' . $this->regex . '/', $desc ) ) {
565 $this->assertTrue( true ); // XXX: don't flood output with "test made no assertions"
566 //$this->markTestSkipped( 'Filtered out by the user' );
567 return;
568 }
569
570 if ( !$this->isWikitextNS( NS_MAIN ) ) {
571 // parser tests frequently assume that the main namespace contains wikitext.
572 // @todo When setting up pages, force the content model. Only skip if
573 // $wgtContentModelUseDB is false.
574 $this->markTestSkipped( "Main namespace does not support wikitext,"
575 . "skipping parser test: $desc" );
576 }
577
578 wfDebug( "Running parser test: $desc\n" );
579
580 $opts = $this->parseOptions( $opts );
581 $context = $this->setupGlobals( $opts, $config );
582
583 $user = $context->getUser();
584 $options = ParserOptions::newFromContext( $context );
585
586 if ( isset( $opts['title'] ) ) {
587 $titleText = $opts['title'];
588 } else {
589 $titleText = 'Parser test';
590 }
591
592 $local = isset( $opts['local'] );
593 $preprocessor = isset( $opts['preprocessor'] ) ? $opts['preprocessor'] : null;
594 $parser = $this->getParser( $preprocessor );
595
596 $title = Title::newFromText( $titleText );
597
598 # Parser test requiring math. Make sure texvc is executable
599 # or just skip such tests.
600 if ( isset( $opts['math'] ) || isset( $opts['texvc'] ) ) {
601 global $wgTexvc;
602
603 if ( !isset( $wgTexvc ) ) {
604 $this->markTestSkipped( "SKIPPED: \$wgTexvc is not set" );
605 } elseif ( !is_executable( $wgTexvc ) ) {
606 $this->markTestSkipped( "SKIPPED: texvc binary does not exist"
607 . " or is not executable.\n"
608 . "Current configuration is:\n\$wgTexvc = '$wgTexvc'" );
609 }
610 }
611
612 if ( isset( $opts['pst'] ) ) {
613 $out = $parser->preSaveTransform( $input, $title, $user, $options );
614 } elseif ( isset( $opts['msg'] ) ) {
615 $out = $parser->transformMsg( $input, $options, $title );
616 } elseif ( isset( $opts['section'] ) ) {
617 $section = $opts['section'];
618 $out = $parser->getSection( $input, $section );
619 } elseif ( isset( $opts['replace'] ) ) {
620 $section = $opts['replace'][0];
621 $replace = $opts['replace'][1];
622 $out = $parser->replaceSection( $input, $section, $replace );
623 } elseif ( isset( $opts['comment'] ) ) {
624 $out = Linker::formatComment( $input, $title, $local );
625 } elseif ( isset( $opts['preload'] ) ) {
626 $out = $parser->getPreloadText( $input, $title, $options );
627 } else {
628 $output = $parser->parse( $input, $title, $options, true, true, 1337 );
629 $output->setTOCEnabled( !isset( $opts['notoc'] ) );
630 $out = $output->getText();
631
632 if ( isset( $opts['showtitle'] ) ) {
633 if ( $output->getTitleText() ) {
634 $title = $output->getTitleText();
635 }
636
637 $out = "$title\n$out";
638 }
639
640 if ( isset( $opts['ill'] ) ) {
641 $out = $this->tidy( implode( ' ', $output->getLanguageLinks() ) );
642 } elseif ( isset( $opts['cat'] ) ) {
643 $outputPage = $context->getOutput();
644 $outputPage->addCategoryLinks( $output->getCategories() );
645 $cats = $outputPage->getCategoryLinks();
646
647 if ( isset( $cats['normal'] ) ) {
648 $out = $this->tidy( implode( ' ', $cats['normal'] ) );
649 } else {
650 $out = '';
651 }
652 }
653 $parser->mPreprocessor = null;
654
655 $result = $this->tidy( $result );
656 }
657
658 $this->teardownGlobals();
659
660 $this->assertEquals( $result, $out, $desc );
661 }
662
663 /**
664 * Run a fuzz test series
665 * Draw input from a set of test files
666 *
667 * @todo fixme Needs some work to not eat memory until the world explodes
668 *
669 * @group ParserFuzz
670 */
671 public function testFuzzTests() {
672 global $wgParserTestFiles;
673
674 $files = $wgParserTestFiles;
675
676 if ( $this->getCliArg( 'file=' ) ) {
677 $files = array( $this->getCliArg( 'file=' ) );
678 }
679
680 $dict = $this->getFuzzInput( $files );
681 $dictSize = strlen( $dict );
682 $logMaxLength = log( $this->maxFuzzTestLength );
683
684 ini_set( 'memory_limit', $this->memoryLimit * 1048576 );
685
686 $user = new User;
687 $opts = ParserOptions::newFromUser( $user );
688 $title = Title::makeTitle( NS_MAIN, 'Parser_test' );
689
690 $id = 1;
691
692 while ( true ) {
693
694 // Generate test input
695 mt_srand( ++$this->fuzzSeed );
696 $totalLength = mt_rand( 1, $this->maxFuzzTestLength );
697 $input = '';
698
699 while ( strlen( $input ) < $totalLength ) {
700 $logHairLength = mt_rand( 0, 1000000 ) / 1000000 * $logMaxLength;
701 $hairLength = min( intval( exp( $logHairLength ) ), $dictSize );
702 $offset = mt_rand( 0, $dictSize - $hairLength );
703 $input .= substr( $dict, $offset, $hairLength );
704 }
705
706 $this->setupGlobals();
707 $parser = $this->getParser();
708
709 // Run the test
710 try {
711 $parser->parse( $input, $title, $opts );
712 $this->assertTrue( true, "Test $id, fuzz seed {$this->fuzzSeed}" );
713 } catch ( Exception $exception ) {
714 $input_dump = sprintf( "string(%d) \"%s\"\n", strlen( $input ), $input );
715
716 $this->assertTrue( false, "Test $id, fuzz seed {$this->fuzzSeed}. \n\n" .
717 "Input: $input_dump\n\nError: {$exception->getMessage()}\n\n" .
718 "Backtrace: {$exception->getTraceAsString()}" );
719 }
720
721 $this->teardownGlobals();
722 $parser->__destruct();
723
724 if ( $id % 100 == 0 ) {
725 $usage = intval( memory_get_usage( true ) / $this->memoryLimit / 1048576 * 100 );
726 //echo "{$this->fuzzSeed}: $numSuccess/$numTotal (mem: $usage%)\n";
727 if ( $usage > 90 ) {
728 $ret = "Out of memory:\n";
729 $memStats = $this->getMemoryBreakdown();
730
731 foreach ( $memStats as $name => $usage ) {
732 $ret .= "$name: $usage\n";
733 }
734
735 throw new MWException( $ret );
736 }
737 }
738
739 $id++;
740 }
741 }
742
743 //Various getter functions
744
745 /**
746 * Get an input dictionary from a set of parser test files
747 */
748 function getFuzzInput( $filenames ) {
749 $dict = '';
750
751 foreach ( $filenames as $filename ) {
752 $contents = file_get_contents( $filename );
753 preg_match_all( '/!!\s*input\n(.*?)\n!!\s*result/s', $contents, $matches );
754
755 foreach ( $matches[1] as $match ) {
756 $dict .= $match . "\n";
757 }
758 }
759
760 return $dict;
761 }
762
763 /**
764 * Get a memory usage breakdown
765 */
766 function getMemoryBreakdown() {
767 $memStats = array();
768
769 foreach ( $GLOBALS as $name => $value ) {
770 $memStats['$' . $name] = strlen( serialize( $value ) );
771 }
772
773 $classes = get_declared_classes();
774
775 foreach ( $classes as $class ) {
776 $rc = new ReflectionClass( $class );
777 $props = $rc->getStaticProperties();
778 $memStats[$class] = strlen( serialize( $props ) );
779 $methods = $rc->getMethods();
780
781 foreach ( $methods as $method ) {
782 $memStats[$class] += strlen( serialize( $method->getStaticVariables() ) );
783 }
784 }
785
786 $functions = get_defined_functions();
787
788 foreach ( $functions['user'] as $function ) {
789 $rf = new ReflectionFunction( $function );
790 $memStats["$function()"] = strlen( serialize( $rf->getStaticVariables() ) );
791 }
792
793 asort( $memStats );
794
795 return $memStats;
796 }
797
798 /**
799 * Get a Parser object
800 */
801 function getParser( $preprocessor = null ) {
802 global $wgParserConf;
803
804 $class = $wgParserConf['class'];
805 $parser = new $class( array( 'preprocessorClass' => $preprocessor ) + $wgParserConf );
806
807 wfRunHooks( 'ParserTestParser', array( &$parser ) );
808
809 return $parser;
810 }
811
812 //Various action functions
813
814 public function addArticle( $name, $text, $line ) {
815 self::$articles[$name] = array( $text, $line );
816 }
817
818 public function publishTestArticles() {
819 if ( empty( self::$articles ) ) {
820 return;
821 }
822
823 foreach ( self::$articles as $name => $info ) {
824 list( $text, $line ) = $info;
825 ParserTest::addArticle( $name, $text, $line, 'ignoreduplicate' );
826 }
827 }
828
829 /**
830 * Steal a callback function from the primary parser, save it for
831 * application to our scary parser. If the hook is not installed,
832 * abort processing of this file.
833 *
834 * @param $name String
835 * @return Bool true if tag hook is present
836 */
837 public function requireHook( $name ) {
838 global $wgParser;
839 $wgParser->firstCallInit(); // make sure hooks are loaded.
840 return isset( $wgParser->mTagHooks[$name] );
841 }
842
843 public function requireFunctionHook( $name ) {
844 global $wgParser;
845 $wgParser->firstCallInit(); // make sure hooks are loaded.
846 return isset( $wgParser->mFunctionHooks[$name] );
847 }
848
849 //Various "cleanup" functions
850
851 /**
852 * Run the "tidy" command on text if the $wgUseTidy
853 * global is true
854 *
855 * @param $text String: the text to tidy
856 * @return String
857 */
858 protected function tidy( $text ) {
859 global $wgUseTidy;
860
861 if ( $wgUseTidy ) {
862 $text = MWTidy::tidy( $text );
863 }
864
865 return $text;
866 }
867
868 /**
869 * Remove last character if it is a newline
870 */
871 public function removeEndingNewline( $s ) {
872 if ( substr( $s, -1 ) === "\n" ) {
873 return substr( $s, 0, -1 );
874 } else {
875 return $s;
876 }
877 }
878
879 //Test options parser functions
880
881 protected function parseOptions( $instring ) {
882 $opts = array();
883 // foo
884 // foo=bar
885 // foo="bar baz"
886 // foo=[[bar baz]]
887 // foo=bar,"baz quux"
888 $regex = '/\b
889 ([\w-]+) # Key
890 \b
891 (?:\s*
892 = # First sub-value
893 \s*
894 (
895 "
896 [^"]* # Quoted val
897 "
898 |
899 \[\[
900 [^]]* # Link target
901 \]\]
902 |
903 [\w-]+ # Plain word
904 )
905 (?:\s*
906 , # Sub-vals 1..N
907 \s*
908 (
909 "[^"]*" # Quoted val
910 |
911 \[\[[^]]*\]\] # Link target
912 |
913 [\w-]+ # Plain word
914 )
915 )*
916 )?
917 /x';
918
919 if ( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER ) ) {
920 foreach ( $matches as $bits ) {
921 array_shift( $bits );
922 $key = strtolower( array_shift( $bits ) );
923 if ( count( $bits ) == 0 ) {
924 $opts[$key] = true;
925 } elseif ( count( $bits ) == 1 ) {
926 $opts[$key] = $this->cleanupOption( array_shift( $bits ) );
927 } else {
928 // Array!
929 $opts[$key] = array_map( array( $this, 'cleanupOption' ), $bits );
930 }
931 }
932 }
933
934 return $opts;
935 }
936
937 protected function cleanupOption( $opt ) {
938 if ( substr( $opt, 0, 1 ) == '"' ) {
939 return substr( $opt, 1, -1 );
940 }
941
942 if ( substr( $opt, 0, 2 ) == '[[' ) {
943 return substr( $opt, 2, -2 );
944 }
945
946 return $opt;
947 }
948
949 /**
950 * Use a regex to find out the value of an option
951 * @param $key String: name of option val to retrieve
952 * @param $opts Options array to look in
953 * @param $default Mixed: default value returned if not found
954 */
955 protected static function getOptionValue( $key, $opts, $default ) {
956 $key = strtolower( $key );
957
958 if ( isset( $opts[$key] ) ) {
959 return $opts[$key];
960 } else {
961 return $default;
962 }
963 }
964 }