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