3 * Generic backend for the MediaWiki parser test suite, used by both the
4 * standalone parserTests.php and the PHPUnit "parsertests" suite.
6 * Copyright © 2004, 2010 Brion Vibber <brion@pobox.com>
7 * https://www.mediawiki.org/
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU General Public License along
20 * with this program; if not, write to the Free Software Foundation, Inc.,
21 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
22 * http://www.gnu.org/copyleft/gpl.html
24 * @todo Make this more independent of the configuration (and if possible the database)
28 use Wikimedia\Rdbms\IDatabase
;
29 use MediaWiki\MediaWikiServices
;
30 use MediaWiki\Tidy\TidyDriverBase
;
31 use Wikimedia\ScopedCallback
;
32 use Wikimedia\TestingAccessWrapper
;
37 class ParserTestRunner
{
40 * MediaWiki core parser test files, paths
41 * will be prefixed with __DIR__ . '/'
45 private static $coreTestFiles = [
47 'extraParserTests.txt',
51 * @var bool $useTemporaryTables Use temporary tables for the temporary database
53 private $useTemporaryTables = true;
56 * @var array $setupDone The status of each setup function
58 private $setupDone = [
59 'staticSetup' => false,
60 'perTestSetup' => false,
61 'setupDatabase' => false,
62 'setDatabase' => false,
63 'setupUploads' => false,
67 * Our connection to the database
73 * Database clone helper
86 private $tidyDriver = null;
94 * The upload directory, or null to not set up an upload directory
98 private $uploadDir = null;
101 * The name of the file backend to use, or null to use MockFileBackend.
104 private $fileBackendName;
107 * A complete regex for filtering tests.
113 * A list of normalization functions to apply to the expected and actual
117 private $normalizationFunctions = [];
120 * Run disabled parser tests
123 private $runDisabled;
126 * Disable parse on article insertion
129 private $disableSaveParse;
132 * Reuse upload directory
135 private $keepUploads;
138 * @param TestRecorder $recorder
139 * @param array $options
141 public function __construct( TestRecorder
$recorder, $options = [] ) {
142 $this->recorder
= $recorder;
144 if ( isset( $options['norm'] ) ) {
145 foreach ( $options['norm'] as $func ) {
146 if ( in_array( $func, [ 'removeTbody', 'trimWhitespace' ] ) ) {
147 $this->normalizationFunctions
[] = $func;
149 $this->recorder
->warning(
150 "Warning: unknown normalization option \"$func\"\n" );
155 if ( isset( $options['regex'] ) && $options['regex'] !== false ) {
156 $this->regex
= $options['regex'];
162 $this->keepUploads
= !empty( $options['keep-uploads'] );
164 $this->fileBackendName
= $options['file-backend'] ??
false;
166 $this->runDisabled
= !empty( $options['run-disabled'] );
168 $this->disableSaveParse
= !empty( $options['disable-save-parse'] );
170 $this->tidySupport
= new TidySupport( !empty( $options['use-tidy-config'] ) );
171 if ( !$this->tidySupport
->isEnabled() ) {
172 $this->recorder
->warning(
173 "Warning: tidy is not installed, skipping some tests\n" );
176 if ( isset( $options['upload-dir'] ) ) {
177 $this->uploadDir
= $options['upload-dir'];
182 * Get list of filenames to extension and core parser tests
186 public static function getParserTestFiles() {
187 global $wgParserTestFiles;
189 // Add core test files
190 $files = array_map( function ( $item ) {
191 return __DIR__
. "/$item";
192 }, self
::$coreTestFiles );
194 // Plus legacy global files
195 $files = array_merge( $files, $wgParserTestFiles );
197 // Auto-discover extension parser tests
198 $registry = ExtensionRegistry
::getInstance();
199 foreach ( $registry->getAllThings() as $info ) {
200 $dir = dirname( $info['path'] ) . '/tests/parser';
201 if ( !file_exists( $dir ) ) {
205 $dirIterator = new RecursiveIteratorIterator(
206 new RecursiveDirectoryIterator( $dir )
208 foreach ( $dirIterator as $fileInfo ) {
209 /** @var SplFileInfo $fileInfo */
210 if ( substr( $fileInfo->getFilename(), -4 ) === '.txt' ) {
211 $name = $info['name'] . $counter;
212 while ( isset( $files[$name] ) ) {
213 $name = $info['name'] . '_' . $counter++
;
215 $files[$name] = $fileInfo->getPathname();
220 return array_unique( $files );
223 public function getRecorder() {
224 return $this->recorder
;
228 * Do any setup which can be done once for all tests, independent of test
229 * options, except for database setup.
231 * Public setup functions in this class return a ScopedCallback object. When
232 * this object is destroyed by going out of scope, teardown of the
233 * corresponding test setup is performed.
235 * Teardown objects may be chained by passing a ScopedCallback from a
236 * previous setup stage as the $nextTeardown parameter. This enforces the
237 * convention that teardown actions are taken in reverse order to the
238 * corresponding setup actions. When $nextTeardown is specified, a
239 * ScopedCallback will be returned which first tears down the current
240 * setup stage, and then tears down the previous setup stage which was
241 * specified by $nextTeardown.
243 * @param ScopedCallback|null $nextTeardown
244 * @return ScopedCallback
246 public function staticSetup( $nextTeardown = null ) {
247 // A note on coding style:
249 // The general idea here is to keep setup code together with
250 // corresponding teardown code, in a fine-grained manner. We have two
251 // arrays: $setup and $teardown. The code snippets in the $setup array
252 // are executed at the end of the method, before it returns, and the
253 // code snippets in the $teardown array are executed in reverse order
254 // when the Wikimedia\ScopedCallback object is consumed.
256 // Because it is a common operation to save, set and restore global
257 // variables, we have an additional convention: when the array key of
258 // $setup is a string, the string is taken to be the name of the global
259 // variable, and the element value is taken to be the desired new value.
261 // It's acceptable to just do the setup immediately, instead of adding
262 // a closure to $setup, except when the setup action depends on global
263 // variable initialisation being done first. In this case, you have to
264 // append a closure to $setup after the global variable is appended.
266 // When you add to setup functions in this class, please keep associated
267 // setup and teardown actions together in the source code, and please
268 // add comments explaining why the setup action is necessary.
273 $teardown[] = $this->markSetupDone( 'staticSetup' );
275 // Some settings which influence HTML output
276 $setup['wgSitename'] = 'MediaWiki';
277 $setup['wgServer'] = 'http://example.org';
278 $setup['wgServerName'] = 'example.org';
279 $setup['wgScriptPath'] = '';
280 $setup['wgScript'] = '/index.php';
281 $setup['wgResourceBasePath'] = '';
282 $setup['wgStylePath'] = '/skins';
283 $setup['wgExtensionAssetsPath'] = '/extensions';
284 $setup['wgArticlePath'] = '/wiki/$1';
285 $setup['wgActionPaths'] = [];
286 $setup['wgVariantArticlePath'] = false;
287 $setup['wgUploadNavigationUrl'] = false;
288 $setup['wgCapitalLinks'] = true;
289 $setup['wgNoFollowLinks'] = true;
290 $setup['wgNoFollowDomainExceptions'] = [ 'no-nofollow.org' ];
291 $setup['wgExternalLinkTarget'] = false;
292 $setup['wgLocaltimezone'] = 'UTC';
293 $setup['wgHtml5'] = true;
294 $setup['wgDisableLangConversion'] = false;
295 $setup['wgDisableTitleConversion'] = false;
296 $setup['wgMediaInTargetLanguage'] = false;
298 // "extra language links"
299 // see https://gerrit.wikimedia.org/r/111390
300 $setup['wgExtraInterlanguageLinkPrefixes'] = [ 'mul' ];
302 // All FileRepo changes should be done here by injecting services,
303 // there should be no need to change global variables.
304 RepoGroup
::setSingleton( $this->createRepoGroup() );
305 $teardown[] = function () {
306 RepoGroup
::destroySingleton();
309 // Set up null lock managers
310 $setup['wgLockManagers'] = [ [
311 'name' => 'fsLockManager',
312 'class' => NullLockManager
::class,
314 'name' => 'nullLockManager',
315 'class' => NullLockManager
::class,
317 $reset = function () {
318 LockManagerGroup
::destroySingletons();
321 $teardown[] = $reset;
323 // This allows article insertion into the prefixed DB
324 $setup['wgDefaultExternalStore'] = false;
326 // This might slightly reduce memory usage
327 $setup['wgAdaptiveMessageCache'] = true;
329 // This is essential and overrides disabling of database messages in TestSetup
330 $setup['wgUseDatabaseMessages'] = true;
331 $reset = function () {
332 MessageCache
::destroyInstance();
335 $teardown[] = $reset;
337 // It's not necessary to actually convert any files
338 $setup['wgSVGConverter'] = 'null';
339 $setup['wgSVGConverters'] = [ 'null' => 'echo "1">$output' ];
341 // Fake constant timestamp
342 Hooks
::register( 'ParserGetVariableValueTs', function ( &$parser, &$ts ) {
343 $ts = $this->getFakeTimestamp();
346 $teardown[] = function () {
347 Hooks
::clear( 'ParserGetVariableValueTs' );
350 $this->appendNamespaceSetup( $setup, $teardown );
352 // Set up interwikis and append teardown function
353 $teardown[] = $this->setupInterwikis();
355 // This affects title normalization in links. It invalidates
356 // MediaWikiTitleCodec objects.
357 $setup['wgLocalInterwikis'] = [ 'local', 'mi' ];
358 $reset = function () {
359 $this->resetTitleServices();
362 $teardown[] = $reset;
364 // Set up a mock MediaHandlerFactory
365 MediaWikiServices
::getInstance()->disableService( 'MediaHandlerFactory' );
366 MediaWikiServices
::getInstance()->redefineService(
367 'MediaHandlerFactory',
368 function ( MediaWikiServices
$services ) {
369 $handlers = $services->getMainConfig()->get( 'ParserTestMediaHandlers' );
370 return new MediaHandlerFactory( $handlers );
373 $teardown[] = function () {
374 MediaWikiServices
::getInstance()->resetServiceForTesting( 'MediaHandlerFactory' );
377 // SqlBagOStuff broke when using temporary tables on r40209 (T17892).
378 // It seems to have been fixed since (r55079?), but regressed at some point before r85701.
379 // This works around it for now...
380 global $wgObjectCaches;
381 $setup['wgObjectCaches'] = [ CACHE_DB
=> $wgObjectCaches['hash'] ] +
$wgObjectCaches;
382 if ( isset( ObjectCache
::$instances[CACHE_DB
] ) ) {
383 $savedCache = ObjectCache
::$instances[CACHE_DB
];
384 ObjectCache
::$instances[CACHE_DB
] = new HashBagOStuff
;
385 $teardown[] = function () use ( $savedCache ) {
386 ObjectCache
::$instances[CACHE_DB
] = $savedCache;
390 $teardown[] = $this->executeSetupSnippets( $setup );
392 // Schedule teardown snippets in reverse order
393 return $this->createTeardownObject( $teardown, $nextTeardown );
396 private function appendNamespaceSetup( &$setup, &$teardown ) {
397 // Add a namespace shadowing a interwiki link, to test
398 // proper precedence when resolving links. (T53680)
399 $setup['wgExtraNamespaces'] = [
400 100 => 'MemoryAlpha',
401 101 => 'MemoryAlpha_talk'
403 // Changing wgExtraNamespaces invalidates caches in MWNamespace and
404 // any live Language object, both on setup and teardown
405 $reset = function () {
406 MWNamespace
::clearCaches();
407 MediaWikiServices
::getInstance()->getContentLanguage()->resetNamespaces();
410 $teardown[] = $reset;
414 * Create a RepoGroup object appropriate for the current configuration
417 protected function createRepoGroup() {
418 if ( $this->uploadDir
) {
419 if ( $this->fileBackendName
) {
420 throw new MWException( 'You cannot specify both use-filebackend and upload-dir' );
422 $backend = new FSFileBackend( [
423 'name' => 'local-backend',
424 'wikiId' => wfWikiID(),
425 'basePath' => $this->uploadDir
,
426 'tmpDirectory' => wfTempDir()
428 } elseif ( $this->fileBackendName
) {
429 global $wgFileBackends;
430 $name = $this->fileBackendName
;
432 foreach ( $wgFileBackends as $conf ) {
433 if ( $conf['name'] === $name ) {
437 if ( $useConfig === false ) {
438 throw new MWException( "Unable to find file backend \"$name\"" );
440 $useConfig['name'] = 'local-backend'; // swap name
441 unset( $useConfig['lockManager'] );
442 unset( $useConfig['fileJournal'] );
443 $class = $useConfig['class'];
444 $backend = new $class( $useConfig );
446 # Replace with a mock. We do not care about generating real
447 # files on the filesystem, just need to expose the file
449 $backend = new MockFileBackend( [
450 'name' => 'local-backend',
451 'wikiId' => wfWikiID()
455 return new RepoGroup(
457 'class' => MockLocalRepo
::class,
459 'url' => 'http://example.com/images',
461 'transformVia404' => false,
462 'backend' => $backend
469 * Execute an array in which elements with integer keys are taken to be
470 * callable objects, and other elements are taken to be global variable
471 * set operations, with the key giving the variable name and the value
472 * giving the new global variable value. A closure is returned which, when
473 * executed, sets the global variables back to the values they had before
474 * this function was called.
478 * @param array $setup
481 protected function executeSetupSnippets( $setup ) {
483 foreach ( $setup as $name => $value ) {
484 if ( is_int( $name ) ) {
487 $saved[$name] = $GLOBALS[$name] ??
null;
488 $GLOBALS[$name] = $value;
491 return function () use ( $saved ) {
492 $this->executeSetupSnippets( $saved );
497 * Take a setup array in the same format as the one given to
498 * executeSetupSnippets(), and return a ScopedCallback which, when consumed,
499 * executes the snippets in the setup array in reverse order. This is used
500 * to create "teardown objects" for the public API.
504 * @param array $teardown The snippet array
505 * @param ScopedCallback|null $nextTeardown A ScopedCallback to consume
506 * @return ScopedCallback
508 protected function createTeardownObject( $teardown, $nextTeardown = null ) {
509 return new ScopedCallback( function () use ( $teardown, $nextTeardown ) {
510 // Schedule teardown snippets in reverse order
511 $teardown = array_reverse( $teardown );
513 $this->executeSetupSnippets( $teardown );
514 if ( $nextTeardown ) {
515 ScopedCallback
::consume( $nextTeardown );
521 * Set a setupDone flag to indicate that setup has been done, and return
522 * the teardown closure. If the flag was already set, throw an exception.
524 * @param string $funcName The setup function name
527 protected function markSetupDone( $funcName ) {
528 if ( $this->setupDone
[$funcName] ) {
529 throw new MWException( "$funcName is already done" );
531 $this->setupDone
[$funcName] = true;
532 return function () use ( $funcName ) {
533 $this->setupDone
[$funcName] = false;
538 * Ensure a given setup stage has been done, throw an exception if it has
540 * @param string $funcName
541 * @param string|null $funcName2
543 protected function checkSetupDone( $funcName, $funcName2 = null ) {
544 if ( !$this->setupDone
[$funcName]
545 && ( $funcName === null ||
!$this->setupDone
[$funcName2] )
547 throw new MWException( "$funcName must be called before calling " .
553 * Determine whether a particular setup function has been run
555 * @param string $funcName
558 public function isSetupDone( $funcName ) {
559 return $this->setupDone
[$funcName] ??
false;
563 * Insert hardcoded interwiki in the lookup table.
565 * This function insert a set of well known interwikis that are used in
566 * the parser tests. They can be considered has fixtures are injected in
567 * the interwiki cache by using the 'InterwikiLoadPrefix' hook.
568 * Since we are not interested in looking up interwikis in the database,
569 * the hook completely replace the existing mechanism (hook returns false).
571 * @return closure for teardown
573 private function setupInterwikis() {
574 # Hack: insert a few Wikipedia in-project interwiki prefixes,
575 # for testing inter-language links
576 Hooks
::register( 'InterwikiLoadPrefix', function ( $prefix, &$iwData ) {
577 static $testInterwikis = [
579 'iw_url' => 'http://doesnt.matter.org/$1',
584 'iw_url' => 'http://en.wikipedia.org/wiki/$1',
589 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
594 'iw_url' => 'http://www.memory-alpha.org/en/index.php/$1',
599 'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
604 'iw_url' => 'http://es.wikipedia.org/wiki/$1',
609 'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
614 'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
619 'iw_url' => 'http://mi.wikipedia.org/wiki/$1',
624 'iw_url' => 'http://wikisource.org/wiki/$1',
629 if ( array_key_exists( $prefix, $testInterwikis ) ) {
630 $iwData = $testInterwikis[$prefix];
633 // We only want to rely on the above fixtures
635 } );// hooks::register
637 // Reset the service in case any other tests already cached some prefixes.
638 MediaWikiServices
::getInstance()->resetServiceForTesting( 'InterwikiLookup' );
642 Hooks
::clear( 'InterwikiLoadPrefix' );
643 MediaWikiServices
::getInstance()->resetServiceForTesting( 'InterwikiLookup' );
648 * Reset the Title-related services that need resetting
651 private function resetTitleServices() {
652 $services = MediaWikiServices
::getInstance();
653 $services->resetServiceForTesting( 'TitleFormatter' );
654 $services->resetServiceForTesting( 'TitleParser' );
655 $services->resetServiceForTesting( '_MediaWikiTitleCodec' );
656 $services->resetServiceForTesting( 'LinkRenderer' );
657 $services->resetServiceForTesting( 'LinkRendererFactory' );
661 * Remove last character if it is a newline
665 public static function chomp( $s ) {
666 if ( substr( $s, -1 ) === "\n" ) {
667 return substr( $s, 0, -1 );
674 * Run a series of tests listed in the given text files.
675 * Each test consists of a brief description, wikitext input,
676 * and the expected HTML output.
678 * Prints status updates on stdout and counts up the total
679 * number and percentage of passed tests.
681 * Handles all setup and teardown.
683 * @param array $filenames Array of strings
684 * @return bool True if passed all tests, false if any tests failed.
686 public function runTestsFromFiles( $filenames ) {
689 $teardownGuard = $this->staticSetup();
690 $teardownGuard = $this->setupDatabase( $teardownGuard );
691 $teardownGuard = $this->setupUploads( $teardownGuard );
693 $this->recorder
->start();
697 foreach ( $filenames as $filename ) {
698 $testFileInfo = TestFileReader
::read( $filename, [
699 'runDisabled' => $this->runDisabled
,
700 'regex' => $this->regex
] );
702 // Don't start the suite if there are no enabled tests in the file
703 if ( !$testFileInfo['tests'] ) {
707 $this->recorder
->startSuite( $filename );
708 $ok = $this->runTests( $testFileInfo ) && $ok;
709 $this->recorder
->endSuite( $filename );
712 $this->recorder
->report();
713 } catch ( DBError
$e ) {
714 $this->recorder
->warning( $e->getMessage() );
716 $this->recorder
->end();
718 ScopedCallback
::consume( $teardownGuard );
724 * Determine whether the current parser has the hooks registered in it
725 * that are required by a file read by TestFileReader.
726 * @param array $requirements
729 public function meetsRequirements( $requirements ) {
730 foreach ( $requirements as $requirement ) {
731 switch ( $requirement['type'] ) {
733 $ok = $this->requireHook( $requirement['name'] );
736 $ok = $this->requireFunctionHook( $requirement['name'] );
738 case 'transparentHook':
739 $ok = $this->requireTransparentHook( $requirement['name'] );
750 * Run the tests from a single file. staticSetup() and setupDatabase()
751 * must have been called already.
753 * @param array $testFileInfo Parsed file info returned by TestFileReader
754 * @return bool True if passed all tests, false if any tests failed.
756 public function runTests( $testFileInfo ) {
759 $this->checkSetupDone( 'staticSetup' );
761 // Don't add articles from the file if there are no enabled tests from the file
762 if ( !$testFileInfo['tests'] ) {
766 // If any requirements are not met, mark all tests from the file as skipped
767 if ( !$this->meetsRequirements( $testFileInfo['requirements'] ) ) {
768 foreach ( $testFileInfo['tests'] as $test ) {
769 $this->recorder
->startTest( $test );
770 $this->recorder
->skipped( $test, 'required extension not enabled' );
776 $this->addArticles( $testFileInfo['articles'] );
779 foreach ( $testFileInfo['tests'] as $test ) {
780 $this->recorder
->startTest( $test );
782 $this->runTest( $test );
783 if ( $result !== false ) {
784 $ok = $ok && $result->isSuccess();
785 $this->recorder
->record( $test, $result );
793 * Get a Parser object
795 * @param string|null $preprocessor
798 function getParser( $preprocessor = null ) {
799 global $wgParserConf;
801 $class = $wgParserConf['class'];
802 $parser = new $class( [ 'preprocessorClass' => $preprocessor ] +
$wgParserConf );
803 ParserTestParserHook
::setup( $parser );
809 * Run a given wikitext input through a freshly-constructed wiki parser,
810 * and compare the output against the expected results.
811 * Prints status and explanatory messages to stdout.
813 * staticSetup() and setupWikiData() must be called before this function
816 * @param array $test The test parameters:
817 * - test: The test name
818 * - desc: The subtest description
819 * - input: Wikitext to try rendering
820 * - options: Array of test options
821 * - config: Overrides for global variables, one per line
823 * @return ParserTestResult|false false if skipped
825 public function runTest( $test ) {
826 wfDebug( __METHOD__
. ": running {$test['desc']}" );
827 $opts = $this->parseOptions( $test['options'] );
828 $teardownGuard = $this->perTestSetup( $test );
830 $context = RequestContext
::getMain();
831 $user = $context->getUser();
832 $options = ParserOptions
::newFromContext( $context );
833 $options->setTimestamp( $this->getFakeTimestamp() );
835 if ( isset( $opts['tidy'] ) ) {
836 if ( !$this->tidySupport
->isEnabled() ) {
837 $this->recorder
->skipped( $test, 'tidy extension is not installed' );
840 $options->setTidy( true );
844 if ( isset( $opts['title'] ) ) {
845 $titleText = $opts['title'];
847 $titleText = 'Parser test';
850 if ( isset( $opts['maxincludesize'] ) ) {
851 $options->setMaxIncludeSize( $opts['maxincludesize'] );
853 if ( isset( $opts['maxtemplatedepth'] ) ) {
854 $options->setMaxTemplateDepth( $opts['maxtemplatedepth'] );
857 $local = isset( $opts['local'] );
858 $preprocessor = $opts['preprocessor'] ??
null;
859 $parser = $this->getParser( $preprocessor );
860 $title = Title
::newFromText( $titleText );
862 if ( isset( $opts['styletag'] ) ) {
863 // For testing the behavior of <style> (including those deduplicated
864 // into <link> tags), add tag hooks to allow them to be generated.
865 $parser->setHook( 'style', function ( $content, $attributes, $parser ) {
866 $marker = Parser
::MARKER_PREFIX
. '-style-' . md5( $content ) . Parser
::MARKER_SUFFIX
;
867 $parser->mStripState
->addNoWiki( $marker, $content );
868 return Html
::inlineStyle( $marker, 'all', $attributes );
870 $parser->setHook( 'link', function ( $content, $attributes, $parser ) {
871 return Html
::element( 'link', $attributes );
875 if ( isset( $opts['pst'] ) ) {
876 $out = $parser->preSaveTransform( $test['input'], $title, $user, $options );
877 $output = $parser->getOutput();
878 } elseif ( isset( $opts['msg'] ) ) {
879 $out = $parser->transformMsg( $test['input'], $options, $title );
880 } elseif ( isset( $opts['section'] ) ) {
881 $section = $opts['section'];
882 $out = $parser->getSection( $test['input'], $section );
883 } elseif ( isset( $opts['replace'] ) ) {
884 $section = $opts['replace'][0];
885 $replace = $opts['replace'][1];
886 $out = $parser->replaceSection( $test['input'], $section, $replace );
887 } elseif ( isset( $opts['comment'] ) ) {
888 $out = Linker
::formatComment( $test['input'], $title, $local );
889 } elseif ( isset( $opts['preload'] ) ) {
890 $out = $parser->getPreloadText( $test['input'], $title, $options );
892 $output = $parser->parse( $test['input'], $title, $options, true, true, 1337 );
893 $out = $output->getText( [
894 'allowTOC' => !isset( $opts['notoc'] ),
895 'unwrap' => !isset( $opts['wrap'] ),
897 if ( isset( $opts['tidy'] ) ) {
898 $out = preg_replace( '/\s+$/', '', $out );
901 if ( isset( $opts['showtitle'] ) ) {
902 if ( $output->getTitleText() ) {
903 $title = $output->getTitleText();
906 $out = "$title\n$out";
909 if ( isset( $opts['showindicators'] ) ) {
911 foreach ( $output->getIndicators() as $id => $content ) {
912 $indicators .= "$id=$content\n";
914 $out = $indicators . $out;
917 if ( isset( $opts['ill'] ) ) {
918 $out = implode( ' ', $output->getLanguageLinks() );
919 } elseif ( isset( $opts['cat'] ) ) {
921 foreach ( $output->getCategories() as $name => $sortkey ) {
925 $out .= "cat=$name sort=$sortkey";
930 if ( isset( $output ) && isset( $opts['showflags'] ) ) {
931 $actualFlags = array_keys( TestingAccessWrapper
::newFromObject( $output )->mFlags
);
932 sort( $actualFlags );
933 $out .= "\nflags=" . implode( ', ', $actualFlags );
936 ScopedCallback
::consume( $teardownGuard );
938 $expected = $test['result'];
939 if ( count( $this->normalizationFunctions
) ) {
940 $expected = ParserTestResultNormalizer
::normalize(
941 $test['expected'], $this->normalizationFunctions
);
942 $out = ParserTestResultNormalizer
::normalize( $out, $this->normalizationFunctions
);
945 $testResult = new ParserTestResult( $test, $expected, $out );
950 * Use a regex to find out the value of an option
951 * @param string $key Name of option val to retrieve
952 * @param array $opts Options array to look in
953 * @param mixed $default Default value returned if not found
956 private static function getOptionValue( $key, $opts, $default ) {
957 $key = strtolower( $key );
959 if ( isset( $opts[$key] ) ) {
967 * Given the options string, return an associative array of options.
968 * @todo Move this to TestFileReader
970 * @param string $instring
973 private function parseOptions( $instring ) {
979 // foo=bar,"baz quux"
982 (?<qstr> # Quoted string
984 (?:[^\\\\"] | \\\\.)*
990 [^"{}] | # Not a quoted string or object, or
991 (?&qstr) | # A quoted string, or
992 (?&json) # A json object (recursively)
998 (?&qstr) # Quoted val
1006 (?&json) # JSON object
1010 $regex = '/' . $defs . '\b
1026 $valueregex = '/' . $defs . '(?&value)/x';
1028 if ( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER
) ) {
1029 foreach ( $matches as $bits ) {
1030 $key = strtolower( $bits['k'] );
1031 if ( !isset( $bits['v'] ) ) {
1034 preg_match_all( $valueregex, $bits['v'], $vmatches );
1035 $opts[$key] = array_map( [ $this, 'cleanupOption' ], $vmatches[0] );
1036 if ( count( $opts[$key] ) == 1 ) {
1037 $opts[$key] = $opts[$key][0];
1045 private function cleanupOption( $opt ) {
1046 if ( substr( $opt, 0, 1 ) == '"' ) {
1047 return stripcslashes( substr( $opt, 1, -1 ) );
1050 if ( substr( $opt, 0, 2 ) == '[[' ) {
1051 return substr( $opt, 2, -2 );
1054 if ( substr( $opt, 0, 1 ) == '{' ) {
1055 return FormatJson
::decode( $opt, true );
1061 * Do any required setup which is dependent on test options.
1063 * @see staticSetup() for more information about setup/teardown
1065 * @param array $test Test info supplied by TestFileReader
1066 * @param callable|null $nextTeardown
1067 * @return ScopedCallback
1069 public function perTestSetup( $test, $nextTeardown = null ) {
1072 $this->checkSetupDone( 'setupDatabase', 'setDatabase' );
1073 $teardown[] = $this->markSetupDone( 'perTestSetup' );
1075 $opts = $this->parseOptions( $test['options'] );
1076 $config = $test['config'];
1078 // Find out values for some special options.
1080 self
::getOptionValue( 'language', $opts, 'en' );
1082 self
::getOptionValue( 'variant', $opts, false );
1084 self
::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
1085 $linkHolderBatchSize =
1086 self
::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
1088 // Default to fallback skin, but allow it to be overridden
1089 $skin = self
::getOptionValue( 'skin', $opts, 'fallback' );
1092 'wgEnableUploads' => self
::getOptionValue( 'wgEnableUploads', $opts, true ),
1093 'wgLanguageCode' => $langCode,
1094 'wgRawHtml' => self
::getOptionValue( 'wgRawHtml', $opts, false ),
1095 'wgNamespacesWithSubpages' => array_fill_keys(
1096 MWNamespace
::getValidNamespaces(), isset( $opts['subpage'] )
1098 'wgMaxTocLevel' => $maxtoclevel,
1099 'wgAllowExternalImages' => self
::getOptionValue( 'wgAllowExternalImages', $opts, true ),
1100 'wgThumbLimits' => [ self
::getOptionValue( 'thumbsize', $opts, 180 ) ],
1101 'wgDefaultLanguageVariant' => $variant,
1102 'wgLinkHolderBatchSize' => $linkHolderBatchSize,
1103 // Set as a JSON object like:
1104 // wgEnableMagicLinks={"ISBN":false, "PMID":false, "RFC":false}
1105 'wgEnableMagicLinks' => self
::getOptionValue( 'wgEnableMagicLinks', $opts, [] )
1106 +
[ 'ISBN' => true, 'PMID' => true, 'RFC' => true ],
1107 // Test with legacy encoding by default until HTML5 is very stable and default
1108 'wgFragmentMode' => [ 'legacy' ],
1109 'wgMediaInTargetLanguage' => self
::getOptionValue( 'wgMediaInTargetLanguage', $opts, false ),
1112 $nonIncludable = self
::getOptionValue( 'wgNonincludableNamespaces', $opts, false );
1113 if ( $nonIncludable !== false ) {
1114 $setup['wgNonincludableNamespaces'] = [ $nonIncludable ];
1118 $configLines = explode( "\n", $config );
1120 foreach ( $configLines as $line ) {
1121 list( $var, $value ) = explode( '=', $line, 2 );
1122 $setup[$var] = eval( "return $value;" );
1127 Hooks
::run( 'ParserTestGlobals', [ &$setup ] );
1129 // Create tidy driver
1130 if ( isset( $opts['tidy'] ) ) {
1131 // Cache a driver instance
1132 if ( $this->tidyDriver
=== null ) {
1133 $this->tidyDriver
= MWTidy
::factory( $this->tidySupport
->getConfig() );
1135 $tidy = $this->tidyDriver
;
1140 # Suppress warnings about running tests without tidy
1141 Wikimedia\
suppressWarnings();
1142 wfDeprecated( 'disabling tidy' );
1143 Wikimedia\restoreWarnings
();
1145 MWTidy
::setInstance( $tidy );
1146 $teardown[] = function () {
1147 MWTidy
::destroySingleton();
1150 // Set content language. This invalidates the magic word cache and title services
1151 $lang = Language
::factory( $langCode );
1152 $lang->resetNamespaces();
1153 $setup['wgContLang'] = $lang;
1154 $setup[] = function () use ( $lang ) {
1155 MediaWikiServices
::getInstance()->disableService( 'ContentLanguage' );
1156 MediaWikiServices
::getInstance()->redefineService(
1158 function () use ( $lang ) {
1163 $teardown[] = function () {
1164 MediaWikiServices
::getInstance()->resetServiceForTesting( 'ContentLanguage' );
1166 $reset = function () {
1167 MediaWikiServices
::getInstance()->resetServiceForTesting( 'MagicWordFactory' );
1168 $this->resetTitleServices();
1171 $teardown[] = $reset;
1173 // Make a user object with the same language
1175 $user->setOption( 'language', $langCode );
1176 $setup['wgLang'] = $lang;
1178 // We (re)set $wgThumbLimits to a single-element array above.
1179 $user->setOption( 'thumbsize', 0 );
1181 $setup['wgUser'] = $user;
1183 // And put both user and language into the context
1184 $context = RequestContext
::getMain();
1185 $context->setUser( $user );
1186 $context->setLanguage( $lang );
1188 $oldSkin = $context->getSkin();
1189 $skinFactory = MediaWikiServices
::getInstance()->getSkinFactory();
1190 $context->setSkin( $skinFactory->makeSkin( $skin ) );
1191 $context->setOutput( new OutputPage( $context ) );
1192 $setup['wgOut'] = $context->getOutput();
1193 $teardown[] = function () use ( $context, $oldSkin ) {
1194 // Clear language conversion tables
1195 $wrapper = TestingAccessWrapper
::newFromObject(
1196 $context->getLanguage()->getConverter()
1198 $wrapper->reloadTables();
1199 // Reset context to the restored globals
1200 $context->setUser( $GLOBALS['wgUser'] );
1201 $context->setLanguage( $GLOBALS['wgContLang'] );
1202 $context->setSkin( $oldSkin );
1203 $context->setOutput( $GLOBALS['wgOut'] );
1206 $teardown[] = $this->executeSetupSnippets( $setup );
1208 return $this->createTeardownObject( $teardown, $nextTeardown );
1212 * List of temporary tables to create, without prefix.
1213 * Some of these probably aren't necessary.
1216 private function listTables() {
1217 global $wgCommentTableSchemaMigrationStage, $wgActorTableSchemaMigrationStage;
1219 $tables = [ 'user', 'user_properties', 'user_former_groups', 'page', 'page_restrictions',
1220 'protected_titles', 'revision', 'ip_changes', 'text', 'pagelinks', 'imagelinks',
1221 'categorylinks', 'templatelinks', 'externallinks', 'langlinks', 'iwlinks',
1222 'site_stats', 'ipblocks', 'image', 'oldimage',
1223 'recentchanges', 'watchlist', 'interwiki', 'logging', 'log_search',
1224 'querycache', 'objectcache', 'job', 'l10n_cache', 'redirect', 'querycachetwo',
1225 'archive', 'user_groups', 'page_props', 'category',
1226 'slots', 'content', 'slot_roles', 'content_models',
1229 if ( $wgCommentTableSchemaMigrationStage >= MIGRATION_WRITE_BOTH
) {
1230 // The new tables for comments are in use
1231 $tables[] = 'comment';
1232 $tables[] = 'revision_comment_temp';
1233 $tables[] = 'image_comment_temp';
1236 if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_NEW
) {
1237 // The new tables for actors are in use
1238 $tables[] = 'actor';
1239 $tables[] = 'revision_actor_temp';
1242 if ( in_array( $this->db
->getType(), [ 'mysql', 'sqlite', 'oracle' ] ) ) {
1243 array_push( $tables, 'searchindex' );
1246 // Allow extensions to add to the list of tables to duplicate;
1247 // may be necessary if they hook into page save or other code
1248 // which will require them while running tests.
1249 Hooks
::run( 'ParserTestTables', [ &$tables ] );
1254 public function setDatabase( IDatabase
$db ) {
1256 $this->setupDone
['setDatabase'] = true;
1260 * Set up temporary DB tables.
1262 * For best performance, call this once only for all tests. However, it can
1263 * be called at the start of each test if more isolation is desired.
1265 * @todo This is basically an unrefactored copy of
1266 * MediaWikiTestCase::setupAllTestDBs. They should be factored out somehow.
1268 * Do not call this function from a MediaWikiTestCase subclass, since
1269 * MediaWikiTestCase does its own DB setup. Instead use setDatabase().
1271 * @see staticSetup() for more information about setup/teardown
1273 * @param ScopedCallback|null $nextTeardown The next teardown object
1274 * @return ScopedCallback The teardown object
1276 public function setupDatabase( $nextTeardown = null ) {
1279 $this->db
= wfGetDB( DB_MASTER
);
1280 $dbType = $this->db
->getType();
1282 if ( $dbType == 'oracle' ) {
1283 $suspiciousPrefixes = [ 'pt_', MediaWikiTestCase
::ORA_DB_PREFIX
];
1285 $suspiciousPrefixes = [ 'parsertest_', MediaWikiTestCase
::DB_PREFIX
];
1287 if ( in_array( $wgDBprefix, $suspiciousPrefixes ) ) {
1288 throw new MWException( "\$wgDBprefix=$wgDBprefix suggests DB setup is already done" );
1293 $teardown[] = $this->markSetupDone( 'setupDatabase' );
1295 # CREATE TEMPORARY TABLE breaks if there is more than one server
1296 if ( MediaWikiServices
::getInstance()->getDBLoadBalancer()->getServerCount() != 1 ) {
1297 $this->useTemporaryTables
= false;
1300 $temporary = $this->useTemporaryTables ||
$dbType == 'postgres';
1301 $prefix = $dbType != 'oracle' ?
'parsertest_' : 'pt_';
1303 $this->dbClone
= new CloneDatabase( $this->db
, $this->listTables(), $prefix );
1304 $this->dbClone
->useTemporaryTables( $temporary );
1305 $this->dbClone
->cloneTableStructure();
1306 CloneDatabase
::changePrefix( $prefix );
1308 if ( $dbType == 'oracle' ) {
1309 $this->db
->query( 'BEGIN FILL_WIKI_INFO; END;' );
1310 # Insert 0 user to prevent FK violations
1313 $this->db
->insert( 'user', [
1315 'user_name' => 'Anonymous' ] );
1318 $teardown[] = function () {
1319 $this->teardownDatabase();
1322 // Wipe some DB query result caches on setup and teardown
1323 $reset = function () {
1324 MediaWikiServices
::getInstance()->getLinkCache()->clear();
1326 // Clear the message cache
1327 MessageCache
::singleton()->clear();
1330 $teardown[] = $reset;
1331 return $this->createTeardownObject( $teardown, $nextTeardown );
1335 * Add data about uploads to the new test DB, and set up the upload
1336 * directory. This should be called after either setDatabase() or
1339 * @param ScopedCallback|null $nextTeardown The next teardown object
1340 * @return ScopedCallback The teardown object
1342 public function setupUploads( $nextTeardown = null ) {
1345 $this->checkSetupDone( 'setupDatabase', 'setDatabase' );
1346 $teardown[] = $this->markSetupDone( 'setupUploads' );
1348 // Create the files in the upload directory (or pretend to create them
1349 // in a MockFileBackend). Append teardown callback.
1350 $teardown[] = $this->setupUploadBackend();
1353 $user = User
::createNew( 'WikiSysop' );
1355 // Register the uploads in the database
1357 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Foobar.jpg' ) );
1358 # note that the size/width/height/bits/etc of the file
1359 # are actually set by inspecting the file itself; the arguments
1360 # to recordUpload2 have no effect. That said, we try to make things
1361 # match up so it is less confusing to readers of the code & tests.
1362 $image->recordUpload2( '', 'Upload of some lame file', 'Some lame file', [
1367 'media_type' => MEDIATYPE_BITMAP
,
1368 'mime' => 'image/jpeg',
1369 'metadata' => serialize( [] ),
1370 'sha1' => Wikimedia\base_convert
( '1', 16, 36, 31 ),
1371 'fileExists' => true
1372 ], $this->db
->timestamp( '20010115123500' ), $user );
1374 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Thumb.png' ) );
1375 # again, note that size/width/height below are ignored; see above.
1376 $image->recordUpload2( '', 'Upload of some lame thumbnail', 'Some lame thumbnail', [
1381 'media_type' => MEDIATYPE_BITMAP
,
1382 'mime' => 'image/png',
1383 'metadata' => serialize( [] ),
1384 'sha1' => Wikimedia\base_convert
( '2', 16, 36, 31 ),
1385 'fileExists' => true
1386 ], $this->db
->timestamp( '20130225203040' ), $user );
1388 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Foobar.svg' ) );
1389 $image->recordUpload2( '', 'Upload of some lame SVG', 'Some lame SVG', [
1394 'media_type' => MEDIATYPE_DRAWING
,
1395 'mime' => 'image/svg+xml',
1396 'metadata' => serialize( [
1397 'version' => SvgHandler
::SVG_METADATA_VERSION
,
1400 'originalWidth' => '100%',
1401 'originalHeight' => '100%',
1403 'en' => SVGReader
::LANG_FULL_MATCH
,
1404 'ru' => SVGReader
::LANG_FULL_MATCH
,
1407 'sha1' => Wikimedia\base_convert
( '', 16, 36, 31 ),
1408 'fileExists' => true
1409 ], $this->db
->timestamp( '20010115123500' ), $user );
1411 # This image will be blacklisted in [[MediaWiki:Bad image list]]
1412 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Bad.jpg' ) );
1413 $image->recordUpload2( '', 'zomgnotcensored', 'Borderline image', [
1418 'media_type' => MEDIATYPE_BITMAP
,
1419 'mime' => 'image/jpeg',
1420 'metadata' => serialize( [] ),
1421 'sha1' => Wikimedia\base_convert
( '3', 16, 36, 31 ),
1422 'fileExists' => true
1423 ], $this->db
->timestamp( '20010115123500' ), $user );
1425 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Video.ogv' ) );
1426 $image->recordUpload2( '', 'A pretty movie', 'Will it play', [
1431 'media_type' => MEDIATYPE_VIDEO
,
1432 'mime' => 'application/ogg',
1433 'metadata' => serialize( [] ),
1434 'sha1' => Wikimedia\base_convert
( '', 16, 36, 31 ),
1435 'fileExists' => true
1436 ], $this->db
->timestamp( '20010115123500' ), $user );
1438 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Audio.oga' ) );
1439 $image->recordUpload2( '', 'An awesome hitsong', 'Will it play', [
1444 'media_type' => MEDIATYPE_AUDIO
,
1445 'mime' => 'application/ogg',
1446 'metadata' => serialize( [] ),
1447 'sha1' => Wikimedia\base_convert
( '', 16, 36, 31 ),
1448 'fileExists' => true
1449 ], $this->db
->timestamp( '20010115123500' ), $user );
1452 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'LoremIpsum.djvu' ) );
1453 $image->recordUpload2( '', 'Upload a DjVu', 'A DjVu', [
1458 'media_type' => MEDIATYPE_BITMAP
,
1459 'mime' => 'image/vnd.djvu',
1460 'metadata' => '<?xml version="1.0" ?>
1461 <!DOCTYPE DjVuXML PUBLIC "-//W3C//DTD DjVuXML 1.1//EN" "pubtext/DjVuXML-s.dtd">
1464 <BODY><OBJECT height="3508" width="2480">
1465 <PARAM name="DPI" value="300" />
1466 <PARAM name="GAMMA" value="2.2" />
1468 <OBJECT height="3508" width="2480">
1469 <PARAM name="DPI" value="300" />
1470 <PARAM name="GAMMA" value="2.2" />
1472 <OBJECT height="3508" width="2480">
1473 <PARAM name="DPI" value="300" />
1474 <PARAM name="GAMMA" value="2.2" />
1476 <OBJECT height="3508" width="2480">
1477 <PARAM name="DPI" value="300" />
1478 <PARAM name="GAMMA" value="2.2" />
1480 <OBJECT height="3508" width="2480">
1481 <PARAM name="DPI" value="300" />
1482 <PARAM name="GAMMA" value="2.2" />
1486 'sha1' => Wikimedia\base_convert
( '', 16, 36, 31 ),
1487 'fileExists' => true
1488 ], $this->db
->timestamp( '20010115123600' ), $user );
1490 return $this->createTeardownObject( $teardown, $nextTeardown );
1494 * Helper for database teardown, called from the teardown closure. Destroy
1495 * the database clone and fix up some things that CloneDatabase doesn't fix.
1497 * @todo Move most things here to CloneDatabase
1499 private function teardownDatabase() {
1500 $this->checkSetupDone( 'setupDatabase' );
1502 $this->dbClone
->destroy();
1504 if ( $this->useTemporaryTables
) {
1505 if ( $this->db
->getType() == 'sqlite' ) {
1506 # Under SQLite the searchindex table is virtual and need
1507 # to be explicitly destroyed. See T31912
1508 # See also MediaWikiTestCase::destroyDB()
1509 wfDebug( __METHOD__
. " explicitly destroying sqlite virtual table parsertest_searchindex\n" );
1510 $this->db
->query( "DROP TABLE `parsertest_searchindex`" );
1512 # Don't need to do anything
1516 $tables = $this->listTables();
1518 foreach ( $tables as $table ) {
1519 if ( $this->db
->getType() == 'oracle' ) {
1520 $this->db
->query( "DROP TABLE pt_$table DROP CONSTRAINTS" );
1522 $this->db
->query( "DROP TABLE `parsertest_$table`" );
1526 if ( $this->db
->getType() == 'oracle' ) {
1527 $this->db
->query( 'BEGIN FILL_WIKI_INFO; END;' );
1532 * Upload test files to the backend created by createRepoGroup().
1534 * @return callable The teardown callback
1536 private function setupUploadBackend() {
1539 $repo = RepoGroup
::singleton()->getLocalRepo();
1540 $base = $repo->getZonePath( 'public' );
1541 $backend = $repo->getBackend();
1542 $backend->prepare( [ 'dir' => "$base/3/3a" ] );
1544 'src' => "$IP/tests/phpunit/data/parser/headbg.jpg",
1545 'dst' => "$base/3/3a/Foobar.jpg"
1547 $backend->prepare( [ 'dir' => "$base/e/ea" ] );
1549 'src' => "$IP/tests/phpunit/data/parser/wiki.png",
1550 'dst' => "$base/e/ea/Thumb.png"
1552 $backend->prepare( [ 'dir' => "$base/0/09" ] );
1554 'src' => "$IP/tests/phpunit/data/parser/headbg.jpg",
1555 'dst' => "$base/0/09/Bad.jpg"
1557 $backend->prepare( [ 'dir' => "$base/5/5f" ] );
1559 'src' => "$IP/tests/phpunit/data/parser/LoremIpsum.djvu",
1560 'dst' => "$base/5/5f/LoremIpsum.djvu"
1563 // No helpful SVG file to copy, so make one ourselves
1564 $data = '<?xml version="1.0" encoding="utf-8"?>' .
1565 '<svg xmlns="http://www.w3.org/2000/svg"' .
1566 ' version="1.1" width="240" height="180"/>';
1568 $backend->prepare( [ 'dir' => "$base/f/ff" ] );
1569 $backend->quickCreate( [
1570 'content' => $data, 'dst' => "$base/f/ff/Foobar.svg"
1573 return function () use ( $backend ) {
1574 if ( $backend instanceof MockFileBackend
) {
1575 // In memory backend, so dont bother cleaning them up.
1578 $this->teardownUploadBackend();
1583 * Remove the dummy uploads directory
1585 private function teardownUploadBackend() {
1586 if ( $this->keepUploads
) {
1590 $repo = RepoGroup
::singleton()->getLocalRepo();
1591 $public = $repo->getZonePath( 'public' );
1595 "$public/3/3a/Foobar.jpg",
1596 "$public/e/ea/Thumb.png",
1597 "$public/0/09/Bad.jpg",
1598 "$public/5/5f/LoremIpsum.djvu",
1599 "$public/f/ff/Foobar.svg",
1600 "$public/0/00/Video.ogv",
1601 "$public/4/41/Audio.oga",
1607 * Delete the specified files and their parent directories
1608 * @param array $files File backend URIs mwstore://...
1610 private function deleteFiles( $files ) {
1612 $backend = RepoGroup
::singleton()->getLocalRepo()->getBackend();
1613 foreach ( $files as $file ) {
1614 $backend->delete( [ 'src' => $file ], [ 'force' => 1 ] );
1617 // Delete the parent directories
1618 foreach ( $files as $file ) {
1619 $tmp = FileBackend
::parentStoragePath( $file );
1621 if ( !$backend->clean( [ 'dir' => $tmp ] )->isOK() ) {
1624 $tmp = FileBackend
::parentStoragePath( $tmp );
1630 * Add articles to the test DB.
1632 * @param array $articles Article info array from TestFileReader
1634 public function addArticles( $articles ) {
1638 // Be sure ParserTestRunner::addArticle has correct language set,
1639 // so that system messages get into the right language cache
1640 if ( MediaWikiServices
::getInstance()->getContentLanguage()->getCode() !== 'en' ) {
1641 $setup['wgLanguageCode'] = 'en';
1642 $lang = Language
::factory( 'en' );
1643 $setup['wgContLang'] = $lang;
1644 $setup[] = function () use ( $lang ) {
1645 $services = MediaWikiServices
::getInstance();
1646 $services->disableService( 'ContentLanguage' );
1647 $services->redefineService( 'ContentLanguage', function () use ( $lang ) {
1651 $teardown[] = function () {
1652 MediaWikiServices
::getInstance()->resetServiceForTesting( 'ContentLanguage' );
1656 // Add special namespaces, in case that hasn't been done by staticSetup() yet
1657 $this->appendNamespaceSetup( $setup, $teardown );
1659 // wgCapitalLinks obviously needs initialisation
1660 $setup['wgCapitalLinks'] = true;
1662 $teardown[] = $this->executeSetupSnippets( $setup );
1664 foreach ( $articles as $info ) {
1665 $this->addArticle( $info['name'], $info['text'], $info['file'], $info['line'] );
1668 // Wipe WANObjectCache process cache, which is invalidated by article insertion
1670 ObjectCache
::getMainWANInstance()->clearProcessCache();
1672 $this->executeSetupSnippets( $teardown );
1676 * Insert a temporary test article
1677 * @param string $name The title, including any prefix
1678 * @param string $text The article text
1679 * @param string $file The input file name
1680 * @param int|string $line The input line number, for reporting errors
1682 * @throws MWException
1684 private function addArticle( $name, $text, $file, $line ) {
1685 $text = self
::chomp( $text );
1686 $name = self
::chomp( $name );
1688 $title = Title
::newFromText( $name );
1689 wfDebug( __METHOD__
. ": adding $name" );
1691 if ( is_null( $title ) ) {
1692 throw new MWException( "invalid title '$name' at $file:$line\n" );
1695 $newContent = ContentHandler
::makeContent( $text, $title );
1697 $page = WikiPage
::factory( $title );
1698 $page->loadPageData( 'fromdbmaster' );
1700 if ( $page->exists() ) {
1701 $content = $page->getContent( Revision
::RAW
);
1702 // Only reject the title, if the content/content model is different.
1703 // This makes it easier to create Template:(( or Template:)) in different extensions
1704 if ( $newContent->equals( $content ) ) {
1707 throw new MWException(
1708 "duplicate article '$name' with different content at $file:$line\n"
1712 // Optionally use mock parser, to make debugging of actual parser tests simpler.
1713 // But initialise the MessageCache clone first, don't let MessageCache
1714 // get a reference to the mock object.
1715 if ( $this->disableSaveParse
) {
1716 MessageCache
::singleton()->getParser();
1717 $restore = $this->executeSetupSnippets( [ 'wgParser' => new ParserTestMockParser
] );
1722 $status = $page->doEditContent(
1725 EDIT_NEW | EDIT_INTERNAL
1733 if ( !$status->isOK() ) {
1734 throw new MWException( $status->getWikiText( false, false, 'en' ) );
1737 // The RepoGroup cache is invalidated by the creation of file redirects
1738 if ( $title->inNamespace( NS_FILE
) ) {
1739 RepoGroup
::singleton()->clearCache( $title );
1744 * Check if a hook is installed
1746 * @param string $name
1747 * @return bool True if tag hook is present
1749 public function requireHook( $name ) {
1752 $wgParser->firstCallInit(); // make sure hooks are loaded.
1753 if ( isset( $wgParser->mTagHooks
[$name] ) ) {
1756 $this->recorder
->warning( " This test suite requires the '$name' hook " .
1757 "extension, skipping." );
1763 * Check if a function hook is installed
1765 * @param string $name
1766 * @return bool True if function hook is present
1768 public function requireFunctionHook( $name ) {
1771 $wgParser->firstCallInit(); // make sure hooks are loaded.
1773 if ( isset( $wgParser->mFunctionHooks
[$name] ) ) {
1776 $this->recorder
->warning( " This test suite requires the '$name' function " .
1777 "hook extension, skipping." );
1783 * Check if a transparent tag hook is installed
1785 * @param string $name
1786 * @return bool True if function hook is present
1788 public function requireTransparentHook( $name ) {
1791 $wgParser->firstCallInit(); // make sure hooks are loaded.
1793 if ( isset( $wgParser->mTransparentTagHooks
[$name] ) ) {
1796 $this->recorder
->warning( " This test suite requires the '$name' transparent " .
1797 "hook extension, skipping.\n" );
1803 * Fake constant timestamp to make sure time-related parser
1804 * functions give a persistent value.
1806 * - Parser::getVariableValue (via ParserGetVariableValueTs hook)
1807 * - Parser::preSaveTransform (via ParserOptions)
1809 private function getFakeTimestamp() {
1810 // parsed as '1970-01-01T00:02:03Z'