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