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