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