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