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