3 * Helper code for the MediaWiki parser test suite. Some code is duplicated
4 * in PHPUnit's NewParserTests.php, so you'll probably want to update both
7 * Copyright © 2004, 2010 Brion Vibber <brion@pobox.com>
8 * https://www.mediawiki.org/
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation; either version 2 of the License, or
13 * (at your option) any later version.
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
20 * You should have received a copy of the GNU General Public License along
21 * with this program; if not, write to the Free Software Foundation, Inc.,
22 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
23 * http://www.gnu.org/copyleft/gpl.html
25 * @todo Make this more independent of the configuration (and if possible the database)
30 use MediaWiki\MediaWikiServices
;
37 * @var bool $color whereas output should be colorized
42 * @var bool $showOutput Show test output
47 * @var bool $useTemporaryTables Use temporary tables for the temporary database
49 private $useTemporaryTables = true;
52 * @var bool $databaseSetupDone True if the database has been set up
54 private $databaseSetupDone = false;
57 * Our connection to the database
63 * Database clone helper
83 private $uploadDir = null;
86 private $savedGlobals = [];
87 private $useDwdiff = false;
88 private $markWhitespace = false;
89 private $normalizationFunctions = [];
92 * Sets terminal colorization and diff/quick modes depending on OS and
93 * command-line options (--color and --quick).
94 * @param array $options
96 public function __construct( $options = [] ) {
97 # Only colorize output if stdout is a terminal.
98 $this->color
= !wfIsWindows() && Maintenance
::posix_isatty( 1 );
100 if ( isset( $options['color'] ) ) {
101 switch ( $options['color'] ) {
103 $this->color
= false;
112 $this->term
= $this->color
113 ?
new AnsiTermColorer()
114 : new DummyTermColorer();
116 $this->showDiffs
= !isset( $options['quick'] );
117 $this->showProgress
= !isset( $options['quiet'] );
118 $this->showFailure
= !(
119 isset( $options['quiet'] )
120 && ( isset( $options['record'] )
121 ||
isset( $options['compare'] ) ) ); // redundant output
123 $this->showOutput
= isset( $options['show-output'] );
124 $this->useDwdiff
= isset( $options['dwdiff'] );
125 $this->markWhitespace
= isset( $options['mark-ws'] );
127 if ( isset( $options['norm'] ) ) {
128 foreach ( explode( ',', $options['norm'] ) as $func ) {
129 if ( in_array( $func, [ 'removeTbody', 'trimWhitespace' ] ) ) {
130 $this->normalizationFunctions
[] = $func;
132 echo "Warning: unknown normalization option \"$func\"\n";
137 if ( isset( $options['filter'] ) ) {
138 $options['regex'] = $options['filter'];
141 if ( isset( $options['regex'] ) ) {
142 if ( isset( $options['record'] ) ) {
143 echo "Warning: --record cannot be used with --regex, disabling --record\n";
144 unset( $options['record'] );
146 $this->regex
= $options['regex'];
152 $this->setupRecorder( $options );
153 $this->keepUploads
= isset( $options['keep-uploads'] );
155 if ( $this->keepUploads
) {
156 $this->uploadDir
= wfTempDir() . '/mwParser-images';
158 $this->uploadDir
= wfTempDir() . "/mwParser-" . mt_rand() . "-images";
161 $this->runDisabled
= isset( $options['run-disabled'] );
162 $this->runParsoid
= isset( $options['run-parsoid'] );
164 $this->djVuSupport
= new DjVuSupport();
165 $this->tidySupport
= new TidySupport( isset( $options['use-tidy-config'] ) );
166 if ( !$this->tidySupport
->isEnabled() ) {
167 echo "Warning: tidy is not installed, skipping some tests\n";
171 $this->functionHooks
= [];
172 $this->transparentHooks
= [];
177 global $wgParser, $wgParserConf, $IP, $messageMemc, $wgMemc,
178 $wgUser, $wgLang, $wgOut, $wgRequest, $wgStyleDirectory,
179 $wgExtraNamespaces, $wgNamespaceAliases, $wgNamespaceProtection, $wgLocalFileRepo,
180 $wgExtraInterlanguageLinkPrefixes, $wgLocalInterwikis,
181 $parserMemc, $wgThumbnailScriptPath, $wgScriptPath, $wgResourceBasePath,
182 $wgArticlePath, $wgScript, $wgStylePath, $wgExtensionAssetsPath,
183 $wgMainCacheType, $wgMessageCacheType, $wgParserCacheType, $wgLockManagers;
186 $wgScript = '/index.php';
187 $wgStylePath = '/skins';
188 $wgResourceBasePath = '';
189 $wgExtensionAssetsPath = '/extensions';
190 $wgArticlePath = '/wiki/$1';
191 $wgThumbnailScriptPath = false;
192 $wgLockManagers = [ [
193 'name' => 'fsLockManager',
194 'class' => 'FSLockManager',
195 'lockDirectory' => $this->uploadDir
. '/lockdir',
197 'name' => 'nullLockManager',
198 'class' => 'NullLockManager',
201 'class' => 'LocalRepo',
203 'url' => 'http://example.com/images',
205 'transformVia404' => false,
206 'backend' => new FSFileBackend( [
207 'name' => 'local-backend',
208 'wikiId' => wfWikiID(),
209 'containerPaths' => [
210 'local-public' => $this->uploadDir
. '/public',
211 'local-thumb' => $this->uploadDir
. '/thumb',
212 'local-temp' => $this->uploadDir
. '/temp',
213 'local-deleted' => $this->uploadDir
. '/deleted',
217 $wgNamespaceProtection[NS_MEDIAWIKI
] = 'editinterface';
218 $wgNamespaceAliases['Image'] = NS_FILE
;
219 $wgNamespaceAliases['Image_talk'] = NS_FILE_TALK
;
220 # add a namespace shadowing a interwiki link, to test
221 # proper precedence when resolving links. (bug 51680)
222 $wgExtraNamespaces[100] = 'MemoryAlpha';
223 $wgExtraNamespaces[101] = 'MemoryAlpha talk';
225 // XXX: tests won't run without this (for CACHE_DB)
226 if ( $wgMainCacheType === CACHE_DB
) {
227 $wgMainCacheType = CACHE_NONE
;
229 if ( $wgMessageCacheType === CACHE_DB
) {
230 $wgMessageCacheType = CACHE_NONE
;
232 if ( $wgParserCacheType === CACHE_DB
) {
233 $wgParserCacheType = CACHE_NONE
;
236 DeferredUpdates
::clearPendingUpdates();
237 $wgMemc = wfGetMainCache(); // checks $wgMainCacheType
238 $messageMemc = wfGetMessageCacheStorage();
239 $parserMemc = wfGetParserCacheStorage();
241 RequestContext
::resetMain();
242 $context = new RequestContext
;
244 $wgLang = $context->getLanguage();
245 $wgOut = $context->getOutput();
246 $wgRequest = $context->getRequest();
247 $wgParser = new StubObject( 'wgParser', $wgParserConf['class'], [ $wgParserConf ] );
249 if ( $wgStyleDirectory === false ) {
250 $wgStyleDirectory = "$IP/skins";
253 self
::setupInterwikis();
254 $wgLocalInterwikis = [ 'local', 'mi' ];
255 // "extra language links"
256 // see https://gerrit.wikimedia.org/r/111390
257 array_push( $wgExtraInterlanguageLinkPrefixes, 'mul' );
259 // Reset namespace cache
260 MWNamespace
::getCanonicalNamespaces( true );
261 Language
::factory( 'en' )->resetNamespaces();
265 * Insert hardcoded interwiki in the lookup table.
267 * This function insert a set of well known interwikis that are used in
268 * the parser tests. They can be considered has fixtures are injected in
269 * the interwiki cache by using the 'InterwikiLoadPrefix' hook.
270 * Since we are not interested in looking up interwikis in the database,
271 * the hook completely replace the existing mechanism (hook returns false).
273 public static function setupInterwikis() {
274 # Hack: insert a few Wikipedia in-project interwiki prefixes,
275 # for testing inter-language links
276 Hooks
::register( 'InterwikiLoadPrefix', function ( $prefix, &$iwData ) {
277 static $testInterwikis = [
279 'iw_url' => 'http://doesnt.matter.org/$1',
284 'iw_url' => 'http://en.wikipedia.org/wiki/$1',
289 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
294 'iw_url' => 'http://www.memory-alpha.org/en/index.php/$1',
299 'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
304 'iw_url' => 'http://es.wikipedia.org/wiki/$1',
309 'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
314 'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
319 'iw_url' => 'http://mi.wikipedia.org/wiki/$1',
324 'iw_url' => 'http://wikisource.org/wiki/$1',
329 if ( array_key_exists( $prefix, $testInterwikis ) ) {
330 $iwData = $testInterwikis[$prefix];
333 // We only want to rely on the above fixtures
335 } );// hooks::register
339 * Remove the hardcoded interwiki lookup table.
341 public static function tearDownInterwikis() {
342 Hooks
::clear( 'InterwikiLoadPrefix' );
346 * Reset the Title-related services that need resetting
349 public static function resetTitleServices() {
350 $services = MediaWikiServices
::getInstance();
351 $services->resetServiceForTesting( 'TitleFormatter' );
352 $services->resetServiceForTesting( 'TitleParser' );
353 $services->resetServiceForTesting( '_MediaWikiTitleCodec' );
354 $services->resetServiceForTesting( 'LinkRenderer' );
355 $services->resetServiceForTesting( 'LinkRendererFactory' );
358 public function setupRecorder( $options ) {
359 if ( isset( $options['record'] ) ) {
360 $this->recorder
= new DbTestRecorder( $this );
361 $this->recorder
->version
= isset( $options['setversion'] ) ?
362 $options['setversion'] : SpecialVersion
::getVersion();
363 } elseif ( isset( $options['compare'] ) ) {
364 $this->recorder
= new DbTestPreviewer( $this );
366 $this->recorder
= new TestRecorder( $this );
371 * Remove last character if it is a newline
376 public static function chomp( $s ) {
377 if ( substr( $s, -1 ) === "\n" ) {
378 return substr( $s, 0, -1 );
385 * Run a series of tests listed in the given text files.
386 * Each test consists of a brief description, wikitext input,
387 * and the expected HTML output.
389 * Prints status updates on stdout and counts up the total
390 * number and percentage of passed tests.
392 * @param array $filenames Array of strings
393 * @return bool True if passed all tests, false if any tests failed.
395 public function runTestsFromFiles( $filenames ) {
398 // be sure, ParserTest::addArticle has correct language set,
399 // so that system messages gets into the right language cache
400 $GLOBALS['wgLanguageCode'] = 'en';
401 $GLOBALS['wgContLang'] = Language
::factory( 'en' );
403 $this->recorder
->start();
405 $this->setupDatabase();
408 foreach ( $filenames as $filename ) {
409 echo "Running parser tests from: $filename\n";
410 $tests = new TestFileIterator( $filename, $this );
411 $ok = $this->runTests( $tests ) && $ok;
414 $this->teardownDatabase();
415 $this->recorder
->report();
416 } catch ( DBError
$e ) {
417 echo $e->getMessage();
419 $this->recorder
->end();
424 function runTests( $tests ) {
427 foreach ( $tests as $t ) {
429 $this->runTest( $t['test'], $t['input'], $t['result'], $t['options'], $t['config'] );
430 $ok = $ok && $result;
431 $this->recorder
->record( $t['test'], $t['subtest'], $result );
434 if ( $this->showProgress
) {
442 * Get a Parser object
444 * @param string $preprocessor
447 function getParser( $preprocessor = null ) {
448 global $wgParserConf;
450 $class = $wgParserConf['class'];
451 $parser = new $class( [ 'preprocessorClass' => $preprocessor ] +
$wgParserConf );
453 foreach ( $this->hooks
as $tag => $callback ) {
454 $parser->setHook( $tag, $callback );
457 foreach ( $this->functionHooks
as $tag => $bits ) {
458 list( $callback, $flags ) = $bits;
459 $parser->setFunctionHook( $tag, $callback, $flags );
462 foreach ( $this->transparentHooks
as $tag => $callback ) {
463 $parser->setTransparentTagHook( $tag, $callback );
466 Hooks
::run( 'ParserTestParser', [ &$parser ] );
472 * Run a given wikitext input through a freshly-constructed wiki parser,
473 * and compare the output against the expected results.
474 * Prints status and explanatory messages to stdout.
476 * @param string $desc Test's description
477 * @param string $input Wikitext to try rendering
478 * @param string $result Result to output
479 * @param array $opts Test's options
480 * @param string $config Overrides for global variables, one per line
483 public function runTest( $desc, $input, $result, $opts, $config ) {
484 if ( $this->showProgress
) {
485 $this->showTesting( $desc );
488 $opts = $this->parseOptions( $opts );
489 $context = $this->setupGlobals( $opts, $config );
491 $user = $context->getUser();
492 $options = ParserOptions
::newFromContext( $context );
494 if ( isset( $opts['djvu'] ) ) {
495 if ( !$this->djVuSupport
->isEnabled() ) {
496 return $this->showSkipped();
500 if ( isset( $opts['tidy'] ) ) {
501 if ( !$this->tidySupport
->isEnabled() ) {
502 return $this->showSkipped();
504 $options->setTidy( true );
508 if ( isset( $opts['title'] ) ) {
509 $titleText = $opts['title'];
511 $titleText = 'Parser test';
514 ObjectCache
::getMainWANInstance()->clearProcessCache();
515 $local = isset( $opts['local'] );
516 $preprocessor = isset( $opts['preprocessor'] ) ?
$opts['preprocessor'] : null;
517 $parser = $this->getParser( $preprocessor );
518 $title = Title
::newFromText( $titleText );
520 if ( isset( $opts['pst'] ) ) {
521 $out = $parser->preSaveTransform( $input, $title, $user, $options );
522 } elseif ( isset( $opts['msg'] ) ) {
523 $out = $parser->transformMsg( $input, $options, $title );
524 } elseif ( isset( $opts['section'] ) ) {
525 $section = $opts['section'];
526 $out = $parser->getSection( $input, $section );
527 } elseif ( isset( $opts['replace'] ) ) {
528 $section = $opts['replace'][0];
529 $replace = $opts['replace'][1];
530 $out = $parser->replaceSection( $input, $section, $replace );
531 } elseif ( isset( $opts['comment'] ) ) {
532 $out = Linker
::formatComment( $input, $title, $local );
533 } elseif ( isset( $opts['preload'] ) ) {
534 $out = $parser->getPreloadText( $input, $title, $options );
536 $output = $parser->parse( $input, $title, $options, true, true, 1337 );
537 $output->setTOCEnabled( !isset( $opts['notoc'] ) );
538 $out = $output->getText();
539 if ( isset( $opts['tidy'] ) ) {
540 $out = preg_replace( '/\s+$/', '', $out );
543 if ( isset( $opts['showtitle'] ) ) {
544 if ( $output->getTitleText() ) {
545 $title = $output->getTitleText();
548 $out = "$title\n$out";
551 if ( isset( $opts['showindicators'] ) ) {
553 foreach ( $output->getIndicators() as $id => $content ) {
554 $indicators .= "$id=$content\n";
556 $out = $indicators . $out;
559 if ( isset( $opts['ill'] ) ) {
560 $out = implode( ' ', $output->getLanguageLinks() );
561 } elseif ( isset( $opts['cat'] ) ) {
562 $outputPage = $context->getOutput();
563 $outputPage->addCategoryLinks( $output->getCategories() );
564 $cats = $outputPage->getCategoryLinks();
566 if ( isset( $cats['normal'] ) ) {
567 $out = implode( ' ', $cats['normal'] );
574 $this->teardownGlobals();
576 if ( count( $this->normalizationFunctions
) ) {
577 $result = ParserTestResultNormalizer
::normalize( $result, $this->normalizationFunctions
);
578 $out = ParserTestResultNormalizer
::normalize( $out, $this->normalizationFunctions
);
581 $testResult = new ParserTestResult( $desc );
582 $testResult->expected
= $result;
583 $testResult->actual
= $out;
585 return $this->showTestResult( $testResult );
589 * Refactored in 1.22 to use ParserTestResult
590 * @param ParserTestResult $testResult
593 function showTestResult( ParserTestResult
$testResult ) {
594 if ( $testResult->isSuccess() ) {
595 $this->showSuccess( $testResult );
598 $this->showFailure( $testResult );
604 * Use a regex to find out the value of an option
605 * @param string $key Name of option val to retrieve
606 * @param array $opts Options array to look in
607 * @param mixed $default Default value returned if not found
610 private static function getOptionValue( $key, $opts, $default ) {
611 $key = strtolower( $key );
613 if ( isset( $opts[$key] ) ) {
620 private function parseOptions( $instring ) {
626 // foo=bar,"baz quux"
629 (?<qstr> # Quoted string
631 (?:[^\\\\"] | \\\\.)*
637 [^"{}] | # Not a quoted string or object, or
638 (?&qstr) | # A quoted string, or
639 (?&json) # A json object (recursively)
645 (?&qstr) # Quoted val
653 (?&json) # JSON object
657 $regex = '/' . $defs . '\b
673 $valueregex = '/' . $defs . '(?&value)/x';
675 if ( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER
) ) {
676 foreach ( $matches as $bits ) {
677 $key = strtolower( $bits['k'] );
678 if ( !isset( $bits['v'] ) ) {
681 preg_match_all( $valueregex, $bits['v'], $vmatches );
682 $opts[$key] = array_map( [ $this, 'cleanupOption' ], $vmatches[0] );
683 if ( count( $opts[$key] ) == 1 ) {
684 $opts[$key] = $opts[$key][0];
692 private function cleanupOption( $opt ) {
693 if ( substr( $opt, 0, 1 ) == '"' ) {
694 return stripcslashes( substr( $opt, 1, -1 ) );
697 if ( substr( $opt, 0, 2 ) == '[[' ) {
698 return substr( $opt, 2, -2 );
701 if ( substr( $opt, 0, 1 ) == '{' ) {
702 return FormatJson
::decode( $opt, true );
708 * Set up the global variables for a consistent environment for each test.
709 * Ideally this should replace the global configuration entirely.
710 * @param string $opts
711 * @param string $config
712 * @return RequestContext
714 public function setupGlobals( $opts = '', $config = '' ) {
715 # Find out values for some special options.
717 self
::getOptionValue( 'language', $opts, 'en' );
719 self
::getOptionValue( 'variant', $opts, false );
721 self
::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
722 $linkHolderBatchSize =
723 self
::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
726 'wgServer' => 'http://example.org',
727 'wgServerName' => 'example.org',
728 'wgScript' => '/index.php',
729 'wgScriptPath' => '',
730 'wgArticlePath' => '/wiki/$1',
731 'wgActionPaths' => [],
732 'wgLockManagers' => [ [
733 'name' => 'fsLockManager',
734 'class' => 'FSLockManager',
735 'lockDirectory' => $this->uploadDir
. '/lockdir',
737 'name' => 'nullLockManager',
738 'class' => 'NullLockManager',
740 'wgLocalFileRepo' => [
741 'class' => 'LocalRepo',
743 'url' => 'http://example.com/images',
745 'transformVia404' => false,
746 'backend' => new FSFileBackend( [
747 'name' => 'local-backend',
748 'wikiId' => wfWikiID(),
749 'containerPaths' => [
750 'local-public' => $this->uploadDir
,
751 'local-thumb' => $this->uploadDir
. '/thumb',
752 'local-temp' => $this->uploadDir
. '/temp',
753 'local-deleted' => $this->uploadDir
. '/delete',
757 'wgEnableUploads' => self
::getOptionValue( 'wgEnableUploads', $opts, true ),
758 'wgUploadNavigationUrl' => false,
759 'wgStylePath' => '/skins',
760 'wgSitename' => 'MediaWiki',
761 'wgLanguageCode' => $lang,
762 'wgDBprefix' => $this->db
->getType() != 'oracle' ?
'parsertest_' : 'pt_',
763 'wgRawHtml' => self
::getOptionValue( 'wgRawHtml', $opts, false ),
765 'wgContLang' => null,
766 'wgNamespacesWithSubpages' => [ 0 => isset( $opts['subpage'] ) ],
767 'wgMaxTocLevel' => $maxtoclevel,
768 'wgCapitalLinks' => true,
769 'wgNoFollowLinks' => true,
770 'wgNoFollowDomainExceptions' => [ 'no-nofollow.org' ],
771 'wgThumbnailScriptPath' => false,
772 'wgUseImageResize' => true,
773 'wgSVGConverter' => 'null',
774 'wgSVGConverters' => [ 'null' => 'echo "1">$output' ],
775 'wgLocaltimezone' => 'UTC',
776 'wgAllowExternalImages' => self
::getOptionValue( 'wgAllowExternalImages', $opts, true ),
777 'wgThumbLimits' => [ self
::getOptionValue( 'thumbsize', $opts, 180 ) ],
778 'wgDefaultLanguageVariant' => $variant,
779 'wgVariantArticlePath' => false,
780 'wgGroupPermissions' => [ '*' => [
781 'createaccount' => true,
784 'createpage' => true,
785 'createtalk' => true,
787 'wgNamespaceProtection' => [ NS_MEDIAWIKI
=> 'editinterface' ],
788 'wgDefaultExternalStore' => [],
789 'wgForeignFileRepos' => [],
790 'wgLinkHolderBatchSize' => $linkHolderBatchSize,
791 'wgExperimentalHtmlIds' => false,
792 'wgExternalLinkTarget' => false,
794 'wgAdaptiveMessageCache' => true,
795 'wgDisableLangConversion' => false,
796 'wgDisableTitleConversion' => false,
798 'wgUseTidy' => false,
799 'wgTidyConfig' => isset( $opts['tidy'] ) ?
$this->tidySupport
->getConfig() : null
803 $configLines = explode( "\n", $config );
805 foreach ( $configLines as $line ) {
806 list( $var, $value ) = explode( '=', $line, 2 );
808 $settings[$var] = eval( "return $value;" );
812 $this->savedGlobals
= [];
815 Hooks
::run( 'ParserTestGlobals', [ &$settings ] );
817 foreach ( $settings as $var => $val ) {
818 if ( array_key_exists( $var, $GLOBALS ) ) {
819 $this->savedGlobals
[$var] = $GLOBALS[$var];
822 $GLOBALS[$var] = $val;
825 // Must be set before $context as user language defaults to $wgContLang
826 $GLOBALS['wgContLang'] = Language
::factory( $lang );
827 $GLOBALS['wgMemc'] = new EmptyBagOStuff
;
829 RequestContext
::resetMain();
830 $context = RequestContext
::getMain();
831 $GLOBALS['wgLang'] = $context->getLanguage();
832 $GLOBALS['wgOut'] = $context->getOutput();
833 $GLOBALS['wgUser'] = $context->getUser();
835 // We (re)set $wgThumbLimits to a single-element array above.
836 $context->getUser()->setOption( 'thumbsize', 0 );
840 $wgHooks['ParserTestParser'][] = 'ParserTestParserHook::setup';
841 $wgHooks['ParserGetVariableValueTs'][] = 'ParserTest::getFakeTimestamp';
843 MagicWord
::clearCache();
844 MWTidy
::destroySingleton();
845 RepoGroup
::destroySingleton();
847 self
::resetTitleServices();
853 * List of temporary tables to create, without prefix.
854 * Some of these probably aren't necessary.
857 private function listTables() {
858 $tables = [ 'user', 'user_properties', 'user_former_groups', 'page', 'page_restrictions',
859 'protected_titles', 'revision', 'text', 'pagelinks', 'imagelinks',
860 'categorylinks', 'templatelinks', 'externallinks', 'langlinks', 'iwlinks',
861 'site_stats', 'ipblocks', 'image', 'oldimage',
862 'recentchanges', 'watchlist', 'interwiki', 'logging', 'log_search',
863 'querycache', 'objectcache', 'job', 'l10n_cache', 'redirect', 'querycachetwo',
864 'archive', 'user_groups', 'page_props', 'category'
867 if ( in_array( $this->db
->getType(), [ 'mysql', 'sqlite', 'oracle' ] ) ) {
868 array_push( $tables, 'searchindex' );
871 // Allow extensions to add to the list of tables to duplicate;
872 // may be necessary if they hook into page save or other code
873 // which will require them while running tests.
874 Hooks
::run( 'ParserTestTables', [ &$tables ] );
880 * Set up a temporary set of wiki tables to work with for the tests.
881 * Currently this will only be done once per run, and any changes to
882 * the db will be visible to later tests in the run.
884 public function setupDatabase() {
887 if ( $this->databaseSetupDone
) {
891 $this->db
= wfGetDB( DB_MASTER
);
892 $dbType = $this->db
->getType();
894 if ( $wgDBprefix === 'parsertest_' ||
( $dbType == 'oracle' && $wgDBprefix === 'pt_' ) ) {
895 throw new MWException( 'setupDatabase should be called before setupGlobals' );
898 $this->databaseSetupDone
= true;
900 # SqlBagOStuff broke when using temporary tables on r40209 (bug 15892).
901 # It seems to have been fixed since (r55079?), but regressed at some point before r85701.
902 # This works around it for now...
903 ObjectCache
::$instances[CACHE_DB
] = new HashBagOStuff
;
905 # CREATE TEMPORARY TABLE breaks if there is more than one server
906 if ( wfGetLB()->getServerCount() != 1 ) {
907 $this->useTemporaryTables
= false;
910 $temporary = $this->useTemporaryTables ||
$dbType == 'postgres';
911 $prefix = $dbType != 'oracle' ?
'parsertest_' : 'pt_';
913 $this->dbClone
= new CloneDatabase( $this->db
, $this->listTables(), $prefix );
914 $this->dbClone
->useTemporaryTables( $temporary );
915 $this->dbClone
->cloneTableStructure();
917 if ( $dbType == 'oracle' ) {
918 $this->db
->query( 'BEGIN FILL_WIKI_INFO; END;' );
919 # Insert 0 user to prevent FK violations
922 $this->db
->insert( 'user', [
924 'user_name' => 'Anonymous' ] );
927 # Update certain things in site_stats
928 $this->db
->insert( 'site_stats',
929 [ 'ss_row_id' => 1, 'ss_images' => 2, 'ss_good_articles' => 1 ] );
931 # Reinitialise the LocalisationCache to match the database state
932 Language
::getLocalisationCache()->unloadAll();
934 # Clear the message cache
935 MessageCache
::singleton()->clear();
937 // Remember to update newParserTests.php after changing the below
938 // (and it uses a slightly different syntax just for teh lulz)
939 $this->setupUploadDir();
940 $user = User
::createNew( 'WikiSysop' );
941 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Foobar.jpg' ) );
942 # note that the size/width/height/bits/etc of the file
943 # are actually set by inspecting the file itself; the arguments
944 # to recordUpload2 have no effect. That said, we try to make things
945 # match up so it is less confusing to readers of the code & tests.
946 $image->recordUpload2( '', 'Upload of some lame file', 'Some lame file', [
951 'media_type' => MEDIATYPE_BITMAP
,
952 'mime' => 'image/jpeg',
953 'metadata' => serialize( [] ),
954 'sha1' => Wikimedia\base_convert
( '1', 16, 36, 31 ),
956 ], $this->db
->timestamp( '20010115123500' ), $user );
958 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Thumb.png' ) );
959 # again, note that size/width/height below are ignored; see above.
960 $image->recordUpload2( '', 'Upload of some lame thumbnail', 'Some lame thumbnail', [
965 'media_type' => MEDIATYPE_BITMAP
,
966 'mime' => 'image/png',
967 'metadata' => serialize( [] ),
968 'sha1' => Wikimedia\base_convert
( '2', 16, 36, 31 ),
970 ], $this->db
->timestamp( '20130225203040' ), $user );
972 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Foobar.svg' ) );
973 $image->recordUpload2( '', 'Upload of some lame SVG', 'Some lame SVG', [
978 'media_type' => MEDIATYPE_DRAWING
,
979 'mime' => 'image/svg+xml',
980 'metadata' => serialize( [] ),
981 'sha1' => Wikimedia\base_convert
( '', 16, 36, 31 ),
983 ], $this->db
->timestamp( '20010115123500' ), $user );
985 # This image will be blacklisted in [[MediaWiki:Bad image list]]
986 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Bad.jpg' ) );
987 $image->recordUpload2( '', 'zomgnotcensored', 'Borderline image', [
992 'media_type' => MEDIATYPE_BITMAP
,
993 'mime' => 'image/jpeg',
994 'metadata' => serialize( [] ),
995 'sha1' => Wikimedia\base_convert
( '3', 16, 36, 31 ),
997 ], $this->db
->timestamp( '20010115123500' ), $user );
999 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Video.ogv' ) );
1000 $image->recordUpload2( '', 'A pretty movie', 'Will it play', [
1005 'media_type' => MEDIATYPE_VIDEO
,
1006 'mime' => 'application/ogg',
1007 'metadata' => serialize( [] ),
1008 'sha1' => Wikimedia\base_convert
( '', 16, 36, 31 ),
1009 'fileExists' => true
1010 ], $this->db
->timestamp( '20010115123500' ), $user );
1012 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Audio.oga' ) );
1013 $image->recordUpload2( '', 'An awesome hitsong', 'Will it play', [
1018 'media_type' => MEDIATYPE_AUDIO
,
1019 'mime' => 'application/ogg',
1020 'metadata' => serialize( [] ),
1021 'sha1' => Wikimedia\base_convert
( '', 16, 36, 31 ),
1022 'fileExists' => true
1023 ], $this->db
->timestamp( '20010115123500' ), $user );
1026 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'LoremIpsum.djvu' ) );
1027 $image->recordUpload2( '', 'Upload a DjVu', 'A DjVu', [
1032 'media_type' => MEDIATYPE_BITMAP
,
1033 'mime' => 'image/vnd.djvu',
1034 'metadata' => '<?xml version="1.0" ?>
1035 <!DOCTYPE DjVuXML PUBLIC "-//W3C//DTD DjVuXML 1.1//EN" "pubtext/DjVuXML-s.dtd">
1038 <BODY><OBJECT height="3508" width="2480">
1039 <PARAM name="DPI" value="300" />
1040 <PARAM name="GAMMA" value="2.2" />
1042 <OBJECT height="3508" width="2480">
1043 <PARAM name="DPI" value="300" />
1044 <PARAM name="GAMMA" value="2.2" />
1046 <OBJECT height="3508" width="2480">
1047 <PARAM name="DPI" value="300" />
1048 <PARAM name="GAMMA" value="2.2" />
1050 <OBJECT height="3508" width="2480">
1051 <PARAM name="DPI" value="300" />
1052 <PARAM name="GAMMA" value="2.2" />
1054 <OBJECT height="3508" width="2480">
1055 <PARAM name="DPI" value="300" />
1056 <PARAM name="GAMMA" value="2.2" />
1060 'sha1' => Wikimedia\base_convert
( '', 16, 36, 31 ),
1061 'fileExists' => true
1062 ], $this->db
->timestamp( '20010115123600' ), $user );
1065 public function teardownDatabase() {
1066 if ( !$this->databaseSetupDone
) {
1067 $this->teardownGlobals();
1070 $this->teardownUploadDir( $this->uploadDir
);
1072 $this->dbClone
->destroy();
1073 $this->databaseSetupDone
= false;
1075 if ( $this->useTemporaryTables
) {
1076 if ( $this->db
->getType() == 'sqlite' ) {
1077 # Under SQLite the searchindex table is virtual and need
1078 # to be explicitly destroyed. See bug 29912
1079 # See also MediaWikiTestCase::destroyDB()
1080 wfDebug( __METHOD__
. " explicitly destroying sqlite virtual table parsertest_searchindex\n" );
1081 $this->db
->query( "DROP TABLE `parsertest_searchindex`" );
1083 # Don't need to do anything
1084 $this->teardownGlobals();
1088 $tables = $this->listTables();
1090 foreach ( $tables as $table ) {
1091 if ( $this->db
->getType() == 'oracle' ) {
1092 $this->db
->query( "DROP TABLE pt_$table DROP CONSTRAINTS" );
1094 $this->db
->query( "DROP TABLE `parsertest_$table`" );
1098 if ( $this->db
->getType() == 'oracle' ) {
1099 $this->db
->query( 'BEGIN FILL_WIKI_INFO; END;' );
1102 $this->teardownGlobals();
1106 * Create a dummy uploads directory which will contain a couple
1107 * of files in order to pass existence tests.
1109 * @return string The directory
1111 private function setupUploadDir() {
1114 $dir = $this->uploadDir
;
1115 if ( $this->keepUploads
&& is_dir( $dir ) ) {
1119 // wfDebug( "Creating upload directory $dir\n" );
1120 if ( file_exists( $dir ) ) {
1121 wfDebug( "Already exists!\n" );
1125 wfMkdirParents( $dir . '/3/3a', null, __METHOD__
);
1126 copy( "$IP/tests/phpunit/data/parser/headbg.jpg", "$dir/3/3a/Foobar.jpg" );
1127 wfMkdirParents( $dir . '/e/ea', null, __METHOD__
);
1128 copy( "$IP/tests/phpunit/data/parser/wiki.png", "$dir/e/ea/Thumb.png" );
1129 wfMkdirParents( $dir . '/0/09', null, __METHOD__
);
1130 copy( "$IP/tests/phpunit/data/parser/headbg.jpg", "$dir/0/09/Bad.jpg" );
1131 wfMkdirParents( $dir . '/f/ff', null, __METHOD__
);
1132 file_put_contents( "$dir/f/ff/Foobar.svg",
1133 '<?xml version="1.0" encoding="utf-8"?>' .
1134 '<svg xmlns="http://www.w3.org/2000/svg"' .
1135 ' version="1.1" width="240" height="180"/>' );
1136 wfMkdirParents( $dir . '/5/5f', null, __METHOD__
);
1137 copy( "$IP/tests/phpunit/data/parser/LoremIpsum.djvu", "$dir/5/5f/LoremIpsum.djvu" );
1138 wfMkdirParents( $dir . '/0/00', null, __METHOD__
);
1139 copy( "$IP/tests/phpunit/data/parser/320x240.ogv", "$dir/0/00/Video.ogv" );
1140 wfMkdirParents( $dir . '/4/41', null, __METHOD__
);
1141 copy( "$IP/tests/phpunit/data/media/say-test.ogg", "$dir/4/41/Audio.oga" );
1147 * Restore default values and perform any necessary clean-up
1148 * after each test runs.
1150 public function teardownGlobals() {
1151 RepoGroup
::destroySingleton();
1152 FileBackendGroup
::destroySingleton();
1153 LockManagerGroup
::destroySingletons();
1154 LinkCache
::singleton()->clear();
1155 MWTidy
::destroySingleton();
1157 foreach ( $this->savedGlobals
as $var => $val ) {
1158 $GLOBALS[$var] = $val;
1163 * Remove the dummy uploads directory
1164 * @param string $dir
1166 private function teardownUploadDir( $dir ) {
1167 if ( $this->keepUploads
) {
1171 // delete the files first, then the dirs.
1174 "$dir/3/3a/Foobar.jpg",
1175 "$dir/thumb/3/3a/Foobar.jpg/*.jpg",
1176 "$dir/e/ea/Thumb.png",
1177 "$dir/0/09/Bad.jpg",
1178 "$dir/5/5f/LoremIpsum.djvu",
1179 "$dir/thumb/5/5f/LoremIpsum.djvu/*-LoremIpsum.djvu.jpg",
1180 "$dir/f/ff/Foobar.svg",
1181 "$dir/thumb/f/ff/Foobar.svg/*-Foobar.svg.png",
1182 "$dir/math/f/a/5/fa50b8b616463173474302ca3e63586b.png",
1183 "$dir/0/00/Video.ogv",
1184 "$dir/thumb/0/00/Video.ogv/120px--Video.ogv.jpg",
1185 "$dir/thumb/0/00/Video.ogv/180px--Video.ogv.jpg",
1186 "$dir/thumb/0/00/Video.ogv/240px--Video.ogv.jpg",
1187 "$dir/thumb/0/00/Video.ogv/320px--Video.ogv.jpg",
1188 "$dir/thumb/0/00/Video.ogv/270px--Video.ogv.jpg",
1189 "$dir/thumb/0/00/Video.ogv/320px-seek=2-Video.ogv.jpg",
1190 "$dir/thumb/0/00/Video.ogv/320px-seek=3.3666666666667-Video.ogv.jpg",
1191 "$dir/4/41/Audio.oga",
1199 "$dir/thumb/3/3a/Foobar.jpg",
1206 "$dir/thumb/f/ff/Foobar.svg",
1214 "$dir/thumb/0/00/Video.ogv",
1217 "$dir/thumb/5/5f/LoremIpsum.djvu",
1234 * Delete the specified files, if they exist.
1235 * @param array $files Full paths to files to delete.
1237 private static function deleteFiles( $files ) {
1238 foreach ( $files as $pattern ) {
1239 foreach ( glob( $pattern ) as $file ) {
1240 if ( file_exists( $file ) ) {
1248 * Delete the specified directories, if they exist. Must be empty.
1249 * @param array $dirs Full paths to directories to delete.
1251 private static function deleteDirs( $dirs ) {
1252 foreach ( $dirs as $dir ) {
1253 if ( is_dir( $dir ) ) {
1260 * "Running test $desc..."
1261 * @param string $desc
1263 protected function showTesting( $desc ) {
1264 print "Running test $desc... ";
1268 * Print a happy success message.
1270 * Refactored in 1.22 to use ParserTestResult
1272 * @param ParserTestResult $testResult
1275 protected function showSuccess( ParserTestResult
$testResult ) {
1276 if ( $this->showProgress
) {
1277 print $this->term
->color( '1;32' ) . 'PASSED' . $this->term
->reset() . "\n";
1284 * Print a failure message and provide some explanatory output
1285 * about what went wrong if so configured.
1287 * Refactored in 1.22 to use ParserTestResult
1289 * @param ParserTestResult $testResult
1292 protected function showFailure( ParserTestResult
$testResult ) {
1293 if ( $this->showFailure
) {
1294 if ( !$this->showProgress
) {
1295 # In quiet mode we didn't show the 'Testing' message before the
1296 # test, in case it succeeded. Show it now:
1297 $this->showTesting( $testResult->description
);
1300 print $this->term
->color( '31' ) . 'FAILED!' . $this->term
->reset() . "\n";
1302 if ( $this->showOutput
) {
1303 print "--- Expected ---\n{$testResult->expected}\n";
1304 print "--- Actual ---\n{$testResult->actual}\n";
1307 if ( $this->showDiffs
) {
1308 print $this->quickDiff( $testResult->expected
, $testResult->actual
);
1309 if ( !$this->wellFormed( $testResult->actual
) ) {
1310 print "XML error: $this->mXmlError\n";
1319 * Print a skipped message.
1323 protected function showSkipped() {
1324 if ( $this->showProgress
) {
1325 print $this->term
->color( '1;33' ) . 'SKIPPED' . $this->term
->reset() . "\n";
1332 * Run given strings through a diff and return the (colorized) output.
1333 * Requires writable /tmp directory and a 'diff' command in the PATH.
1335 * @param string $input
1336 * @param string $output
1337 * @param string $inFileTail Tailing for the input file name
1338 * @param string $outFileTail Tailing for the output file name
1341 protected function quickDiff( $input, $output,
1342 $inFileTail = 'expected', $outFileTail = 'actual'
1344 if ( $this->markWhitespace
) {
1350 $input = strtr( $input, $pairs );
1351 $output = strtr( $output, $pairs );
1354 # Windows, or at least the fc utility, is retarded
1355 $slash = wfIsWindows() ?
'\\' : '/';
1356 $prefix = wfTempDir() . "{$slash}mwParser-" . mt_rand();
1358 $infile = "$prefix-$inFileTail";
1359 $this->dumpToFile( $input, $infile );
1361 $outfile = "$prefix-$outFileTail";
1362 $this->dumpToFile( $output, $outfile );
1364 $shellInfile = wfEscapeShellArg( $infile );
1365 $shellOutfile = wfEscapeShellArg( $outfile );
1368 // we assume that people with diff3 also have usual diff
1369 if ( $this->useDwdiff
) {
1370 $shellCommand = 'dwdiff -Pc';
1372 $shellCommand = ( wfIsWindows() && !$wgDiff3 ) ?
'fc' : 'diff -au';
1375 $diff = wfShellExec( "$shellCommand $shellInfile $shellOutfile" );
1380 if ( $this->useDwdiff
) {
1383 return $this->colorDiff( $diff );
1388 * Write the given string to a file, adding a final newline.
1390 * @param string $data
1391 * @param string $filename
1393 private function dumpToFile( $data, $filename ) {
1394 $file = fopen( $filename, "wt" );
1395 fwrite( $file, $data . "\n" );
1400 * Colorize unified diff output if set for ANSI color output.
1401 * Subtractions are colored blue, additions red.
1403 * @param string $text
1406 protected function colorDiff( $text ) {
1407 return preg_replace(
1408 [ '/^(-.*)$/m', '/^(\+.*)$/m' ],
1409 [ $this->term
->color( 34 ) . '$1' . $this->term
->reset(),
1410 $this->term
->color( 31 ) . '$1' . $this->term
->reset() ],
1415 * Show "Reading tests from ..."
1417 * @param string $path
1419 public function showRunFile( $path ) {
1420 print $this->term
->color( 1 ) .
1421 "Reading tests from \"$path\"..." .
1422 $this->term
->reset() .
1427 * Insert a temporary test article
1428 * @param string $name The title, including any prefix
1429 * @param string $text The article text
1430 * @param int|string $line The input line number, for reporting errors
1431 * @param bool|string $ignoreDuplicate Whether to silently ignore duplicate pages
1433 * @throws MWException
1435 public static function addArticle( $name, $text, $line = 'unknown', $ignoreDuplicate = '' ) {
1436 global $wgCapitalLinks;
1438 $oldCapitalLinks = $wgCapitalLinks;
1439 $wgCapitalLinks = true; // We only need this from SetupGlobals() See r70917#c8637
1441 $text = self
::chomp( $text );
1442 $name = self
::chomp( $name );
1444 $title = Title
::newFromText( $name );
1446 if ( is_null( $title ) ) {
1447 throw new MWException( "invalid title '$name' at line $line\n" );
1450 $page = WikiPage
::factory( $title );
1451 $page->loadPageData( 'fromdbmaster' );
1453 if ( $page->exists() ) {
1454 if ( $ignoreDuplicate == 'ignoreduplicate' ) {
1457 throw new MWException( "duplicate article '$name' at line $line\n" );
1461 $page->doEditContent( ContentHandler
::makeContent( $text, $title ), '', EDIT_NEW
);
1463 $wgCapitalLinks = $oldCapitalLinks;
1467 * Steal a callback function from the primary parser, save it for
1468 * application to our scary parser. If the hook is not installed,
1469 * abort processing of this file.
1471 * @param string $name
1472 * @return bool True if tag hook is present
1474 public function requireHook( $name ) {
1477 $wgParser->firstCallInit(); // make sure hooks are loaded.
1479 if ( isset( $wgParser->mTagHooks
[$name] ) ) {
1480 $this->hooks
[$name] = $wgParser->mTagHooks
[$name];
1482 echo " This test suite requires the '$name' hook extension, skipping.\n";
1490 * Steal a callback function from the primary parser, save it for
1491 * application to our scary parser. If the hook is not installed,
1492 * abort processing of this file.
1494 * @param string $name
1495 * @return bool True if function hook is present
1497 public function requireFunctionHook( $name ) {
1500 $wgParser->firstCallInit(); // make sure hooks are loaded.
1502 if ( isset( $wgParser->mFunctionHooks
[$name] ) ) {
1503 $this->functionHooks
[$name] = $wgParser->mFunctionHooks
[$name];
1505 echo " This test suite requires the '$name' function hook extension, skipping.\n";
1513 * Steal a callback function from the primary parser, save it for
1514 * application to our scary parser. If the hook is not installed,
1515 * abort processing of this file.
1517 * @param string $name
1518 * @return bool True if function hook is present
1520 public function requireTransparentHook( $name ) {
1523 $wgParser->firstCallInit(); // make sure hooks are loaded.
1525 if ( isset( $wgParser->mTransparentTagHooks
[$name] ) ) {
1526 $this->transparentHooks
[$name] = $wgParser->mTransparentTagHooks
[$name];
1528 echo " This test suite requires the '$name' transparent hook extension, skipping.\n";
1535 private function wellFormed( $text ) {
1537 Sanitizer
::hackDocType() .
1542 $parser = xml_parser_create( "UTF-8" );
1544 # case folding violates XML standard, turn it off
1545 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING
, false );
1547 if ( !xml_parse( $parser, $html, true ) ) {
1548 $err = xml_error_string( xml_get_error_code( $parser ) );
1549 $position = xml_get_current_byte_index( $parser );
1550 $fragment = $this->extractFragment( $html, $position );
1551 $this->mXmlError
= "$err at byte $position:\n$fragment";
1552 xml_parser_free( $parser );
1557 xml_parser_free( $parser );
1562 private function extractFragment( $text, $position ) {
1563 $start = max( 0, $position - 10 );
1564 $before = $position - $start;
1566 $this->term
->color( 34 ) .
1567 substr( $text, $start, $before ) .
1568 $this->term
->color( 0 ) .
1569 $this->term
->color( 31 ) .
1570 $this->term
->color( 1 ) .
1571 substr( $text, $position, 1 ) .
1572 $this->term
->color( 0 ) .
1573 $this->term
->color( 34 ) .
1574 substr( $text, $position +
1, 9 ) .
1575 $this->term
->color( 0 ) .
1577 $display = str_replace( "\n", ' ', $fragment );
1579 str_repeat( ' ', $before ) .
1580 $this->term
->color( 31 ) .
1582 $this->term
->color( 0 );
1584 return "$display\n$caret";
1587 static function getFakeTimestamp( &$parser, &$ts ) {
1588 $ts = 123; // parsed as '1970-01-01T00:02:03Z'