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 * @param TestRecorder $recorder
121 * @param array $options
123 public function __construct( TestRecorder
$recorder, $options = [] ) {
124 $this->recorder
= $recorder;
126 if ( isset( $options['norm'] ) ) {
127 foreach ( $options['norm'] as $func ) {
128 if ( in_array( $func, [ 'removeTbody', 'trimWhitespace' ] ) ) {
129 $this->normalizationFunctions
[] = $func;
131 $this->recorder
->warning(
132 "Warning: unknown normalization option \"$func\"\n" );
137 if ( isset( $options['regex'] ) && $options['regex'] !== false ) {
138 $this->regex
= $options['regex'];
144 $this->keepUploads
= !empty( $options['keep-uploads'] );
146 $this->fileBackendName
= isset( $options['file-backend'] ) ?
147 $options['file-backend'] : false;
149 $this->runDisabled
= !empty( $options['run-disabled'] );
150 $this->runParsoid
= !empty( $options['run-parsoid'] );
152 $this->tidySupport
= new TidySupport( !empty( $options['use-tidy-config'] ) );
153 if ( !$this->tidySupport
->isEnabled() ) {
154 $this->recorder
->warning(
155 "Warning: tidy is not installed, skipping some tests\n" );
158 if ( isset( $options['upload-dir'] ) ) {
159 $this->uploadDir
= $options['upload-dir'];
164 * Get list of filenames to extension and core parser tests
168 public static function getParserTestFiles() {
169 global $wgParserTestFiles;
171 // Add core test files
172 $files = array_map( function ( $item ) {
173 return __DIR__
. "/$item";
174 }, self
::$coreTestFiles );
176 // Plus legacy global files
177 $files = array_merge( $files, $wgParserTestFiles );
179 // Auto-discover extension parser tests
180 $registry = ExtensionRegistry
::getInstance();
181 foreach ( $registry->getAllThings() as $info ) {
182 $dir = dirname( $info['path'] ) . '/tests/parser';
183 if ( !file_exists( $dir ) ) {
187 $dirIterator = new RecursiveIteratorIterator(
188 new RecursiveDirectoryIterator( $dir )
190 foreach ( $dirIterator as $fileInfo ) {
191 /** @var SplFileInfo $fileInfo */
192 if ( substr( $fileInfo->getFilename(), -4 ) === '.txt' ) {
193 $name = $info['name'] . $counter;
194 while ( isset( $files[$name] ) ) {
195 $name = $info['name'] . '_' . $counter++
;
197 $files[$name] = $fileInfo->getPathname();
202 return array_unique( $files );
205 public function getRecorder() {
206 return $this->recorder
;
210 * Do any setup which can be done once for all tests, independent of test
211 * options, except for database setup.
213 * Public setup functions in this class return a ScopedCallback object. When
214 * this object is destroyed by going out of scope, teardown of the
215 * corresponding test setup is performed.
217 * Teardown objects may be chained by passing a ScopedCallback from a
218 * previous setup stage as the $nextTeardown parameter. This enforces the
219 * convention that teardown actions are taken in reverse order to the
220 * corresponding setup actions. When $nextTeardown is specified, a
221 * ScopedCallback will be returned which first tears down the current
222 * setup stage, and then tears down the previous setup stage which was
223 * specified by $nextTeardown.
225 * @param ScopedCallback|null $nextTeardown
226 * @return ScopedCallback
228 public function staticSetup( $nextTeardown = null ) {
229 // A note on coding style:
231 // The general idea here is to keep setup code together with
232 // corresponding teardown code, in a fine-grained manner. We have two
233 // arrays: $setup and $teardown. The code snippets in the $setup array
234 // are executed at the end of the method, before it returns, and the
235 // code snippets in the $teardown array are executed in reverse order
236 // when the Wikimedia\ScopedCallback object is consumed.
238 // Because it is a common operation to save, set and restore global
239 // variables, we have an additional convention: when the array key of
240 // $setup is a string, the string is taken to be the name of the global
241 // variable, and the element value is taken to be the desired new value.
243 // It's acceptable to just do the setup immediately, instead of adding
244 // a closure to $setup, except when the setup action depends on global
245 // variable initialisation being done first. In this case, you have to
246 // append a closure to $setup after the global variable is appended.
248 // When you add to setup functions in this class, please keep associated
249 // setup and teardown actions together in the source code, and please
250 // add comments explaining why the setup action is necessary.
255 $teardown[] = $this->markSetupDone( 'staticSetup' );
257 // Some settings which influence HTML output
258 $setup['wgSitename'] = 'MediaWiki';
259 $setup['wgServer'] = 'http://example.org';
260 $setup['wgServerName'] = 'example.org';
261 $setup['wgScriptPath'] = '';
262 $setup['wgScript'] = '/index.php';
263 $setup['wgResourceBasePath'] = '';
264 $setup['wgStylePath'] = '/skins';
265 $setup['wgExtensionAssetsPath'] = '/extensions';
266 $setup['wgArticlePath'] = '/wiki/$1';
267 $setup['wgActionPaths'] = [];
268 $setup['wgVariantArticlePath'] = false;
269 $setup['wgUploadNavigationUrl'] = false;
270 $setup['wgCapitalLinks'] = true;
271 $setup['wgNoFollowLinks'] = true;
272 $setup['wgNoFollowDomainExceptions'] = [ 'no-nofollow.org' ];
273 $setup['wgExternalLinkTarget'] = false;
274 $setup['wgLocaltimezone'] = 'UTC';
275 $setup['wgHtml5'] = true;
276 $setup['wgDisableLangConversion'] = false;
277 $setup['wgDisableTitleConversion'] = false;
279 // "extra language links"
280 // see https://gerrit.wikimedia.org/r/111390
281 $setup['wgExtraInterlanguageLinkPrefixes'] = [ 'mul' ];
283 // All FileRepo changes should be done here by injecting services,
284 // there should be no need to change global variables.
285 RepoGroup
::setSingleton( $this->createRepoGroup() );
286 $teardown[] = function () {
287 RepoGroup
::destroySingleton();
290 // Set up null lock managers
291 $setup['wgLockManagers'] = [ [
292 'name' => 'fsLockManager',
293 'class' => NullLockManager
::class,
295 'name' => 'nullLockManager',
296 'class' => NullLockManager
::class,
298 $reset = function () {
299 LockManagerGroup
::destroySingletons();
302 $teardown[] = $reset;
304 // This allows article insertion into the prefixed DB
305 $setup['wgDefaultExternalStore'] = false;
307 // This might slightly reduce memory usage
308 $setup['wgAdaptiveMessageCache'] = true;
310 // This is essential and overrides disabling of database messages in TestSetup
311 $setup['wgUseDatabaseMessages'] = true;
312 $reset = function () {
313 MessageCache
::destroyInstance();
316 $teardown[] = $reset;
318 // It's not necessary to actually convert any files
319 $setup['wgSVGConverter'] = 'null';
320 $setup['wgSVGConverters'] = [ 'null' => 'echo "1">$output' ];
322 // Fake constant timestamp
323 Hooks
::register( 'ParserGetVariableValueTs', function ( &$parser, &$ts ) {
324 $ts = $this->getFakeTimestamp();
327 $teardown[] = function () {
328 Hooks
::clear( 'ParserGetVariableValueTs' );
331 $this->appendNamespaceSetup( $setup, $teardown );
333 // Set up interwikis and append teardown function
334 $teardown[] = $this->setupInterwikis();
336 // This affects title normalization in links. It invalidates
337 // MediaWikiTitleCodec objects.
338 $setup['wgLocalInterwikis'] = [ 'local', 'mi' ];
339 $reset = function () {
340 $this->resetTitleServices();
343 $teardown[] = $reset;
345 // Set up a mock MediaHandlerFactory
346 MediaWikiServices
::getInstance()->disableService( 'MediaHandlerFactory' );
347 MediaWikiServices
::getInstance()->redefineService(
348 'MediaHandlerFactory',
349 function ( MediaWikiServices
$services ) {
350 $handlers = $services->getMainConfig()->get( 'ParserTestMediaHandlers' );
351 return new MediaHandlerFactory( $handlers );
354 $teardown[] = function () {
355 MediaWikiServices
::getInstance()->resetServiceForTesting( 'MediaHandlerFactory' );
358 // SqlBagOStuff broke when using temporary tables on r40209 (T17892).
359 // It seems to have been fixed since (r55079?), but regressed at some point before r85701.
360 // This works around it for now...
361 global $wgObjectCaches;
362 $setup['wgObjectCaches'] = [ CACHE_DB
=> $wgObjectCaches['hash'] ] +
$wgObjectCaches;
363 if ( isset( ObjectCache
::$instances[CACHE_DB
] ) ) {
364 $savedCache = ObjectCache
::$instances[CACHE_DB
];
365 ObjectCache
::$instances[CACHE_DB
] = new HashBagOStuff
;
366 $teardown[] = function () use ( $savedCache ) {
367 ObjectCache
::$instances[CACHE_DB
] = $savedCache;
371 $teardown[] = $this->executeSetupSnippets( $setup );
373 // Schedule teardown snippets in reverse order
374 return $this->createTeardownObject( $teardown, $nextTeardown );
377 private function appendNamespaceSetup( &$setup, &$teardown ) {
378 // Add a namespace shadowing a interwiki link, to test
379 // proper precedence when resolving links. (T53680)
380 $setup['wgExtraNamespaces'] = [
381 100 => 'MemoryAlpha',
382 101 => 'MemoryAlpha_talk'
384 // Changing wgExtraNamespaces invalidates caches in MWNamespace and
385 // any live Language object, both on setup and teardown
386 $reset = function () {
387 MWNamespace
::clearCaches();
388 $GLOBALS['wgContLang']->resetNamespaces();
391 $teardown[] = $reset;
395 * Create a RepoGroup object appropriate for the current configuration
398 protected function createRepoGroup() {
399 if ( $this->uploadDir
) {
400 if ( $this->fileBackendName
) {
401 throw new MWException( 'You cannot specify both use-filebackend and upload-dir' );
403 $backend = new FSFileBackend( [
404 'name' => 'local-backend',
405 'wikiId' => wfWikiID(),
406 'basePath' => $this->uploadDir
,
407 'tmpDirectory' => wfTempDir()
409 } elseif ( $this->fileBackendName
) {
410 global $wgFileBackends;
411 $name = $this->fileBackendName
;
413 foreach ( $wgFileBackends as $conf ) {
414 if ( $conf['name'] === $name ) {
418 if ( $useConfig === false ) {
419 throw new MWException( "Unable to find file backend \"$name\"" );
421 $useConfig['name'] = 'local-backend'; // swap name
422 unset( $useConfig['lockManager'] );
423 unset( $useConfig['fileJournal'] );
424 $class = $useConfig['class'];
425 $backend = new $class( $useConfig );
427 # Replace with a mock. We do not care about generating real
428 # files on the filesystem, just need to expose the file
430 $backend = new MockFileBackend( [
431 'name' => 'local-backend',
432 'wikiId' => wfWikiID()
436 return new RepoGroup(
438 'class' => MockLocalRepo
::class,
440 'url' => 'http://example.com/images',
442 'transformVia404' => false,
443 'backend' => $backend
450 * Execute an array in which elements with integer keys are taken to be
451 * callable objects, and other elements are taken to be global variable
452 * set operations, with the key giving the variable name and the value
453 * giving the new global variable value. A closure is returned which, when
454 * executed, sets the global variables back to the values they had before
455 * this function was called.
459 * @param array $setup
462 protected function executeSetupSnippets( $setup ) {
464 foreach ( $setup as $name => $value ) {
465 if ( is_int( $name ) ) {
468 $saved[$name] = isset( $GLOBALS[$name] ) ?
$GLOBALS[$name] : null;
469 $GLOBALS[$name] = $value;
472 return function () use ( $saved ) {
473 $this->executeSetupSnippets( $saved );
478 * Take a setup array in the same format as the one given to
479 * executeSetupSnippets(), and return a ScopedCallback which, when consumed,
480 * executes the snippets in the setup array in reverse order. This is used
481 * to create "teardown objects" for the public API.
485 * @param array $teardown The snippet array
486 * @param ScopedCallback|null $nextTeardown A ScopedCallback to consume
487 * @return ScopedCallback
489 protected function createTeardownObject( $teardown, $nextTeardown = null ) {
490 return new ScopedCallback( function () use ( $teardown, $nextTeardown ) {
491 // Schedule teardown snippets in reverse order
492 $teardown = array_reverse( $teardown );
494 $this->executeSetupSnippets( $teardown );
495 if ( $nextTeardown ) {
496 ScopedCallback
::consume( $nextTeardown );
502 * Set a setupDone flag to indicate that setup has been done, and return
503 * the teardown closure. If the flag was already set, throw an exception.
505 * @param string $funcName The setup function name
508 protected function markSetupDone( $funcName ) {
509 if ( $this->setupDone
[$funcName] ) {
510 throw new MWException( "$funcName is already done" );
512 $this->setupDone
[$funcName] = true;
513 return function () use ( $funcName ) {
514 $this->setupDone
[$funcName] = false;
519 * Ensure a given setup stage has been done, throw an exception if it has
521 * @param string $funcName
522 * @param string|null $funcName2
524 protected function checkSetupDone( $funcName, $funcName2 = null ) {
525 if ( !$this->setupDone
[$funcName]
526 && ( $funcName === null ||
!$this->setupDone
[$funcName2] )
528 throw new MWException( "$funcName must be called before calling " .
534 * Determine whether a particular setup function has been run
536 * @param string $funcName
539 public function isSetupDone( $funcName ) {
540 return isset( $this->setupDone
[$funcName] ) ?
$this->setupDone
[$funcName] : false;
544 * Insert hardcoded interwiki in the lookup table.
546 * This function insert a set of well known interwikis that are used in
547 * the parser tests. They can be considered has fixtures are injected in
548 * the interwiki cache by using the 'InterwikiLoadPrefix' hook.
549 * Since we are not interested in looking up interwikis in the database,
550 * the hook completely replace the existing mechanism (hook returns false).
552 * @return closure for teardown
554 private function setupInterwikis() {
555 # Hack: insert a few Wikipedia in-project interwiki prefixes,
556 # for testing inter-language links
557 Hooks
::register( 'InterwikiLoadPrefix', function ( $prefix, &$iwData ) {
558 static $testInterwikis = [
560 'iw_url' => 'http://doesnt.matter.org/$1',
565 'iw_url' => 'http://en.wikipedia.org/wiki/$1',
570 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
575 'iw_url' => 'http://www.memory-alpha.org/en/index.php/$1',
580 'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
585 'iw_url' => 'http://es.wikipedia.org/wiki/$1',
590 'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
595 'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
600 'iw_url' => 'http://mi.wikipedia.org/wiki/$1',
605 'iw_url' => 'http://wikisource.org/wiki/$1',
610 if ( array_key_exists( $prefix, $testInterwikis ) ) {
611 $iwData = $testInterwikis[$prefix];
614 // We only want to rely on the above fixtures
616 } );// hooks::register
618 // Reset the service in case any other tests already cached some prefixes.
619 MediaWikiServices
::getInstance()->resetServiceForTesting( 'InterwikiLookup' );
623 Hooks
::clear( 'InterwikiLoadPrefix' );
624 MediaWikiServices
::getInstance()->resetServiceForTesting( 'InterwikiLookup' );
629 * Reset the Title-related services that need resetting
632 private function resetTitleServices() {
633 $services = MediaWikiServices
::getInstance();
634 $services->resetServiceForTesting( 'TitleFormatter' );
635 $services->resetServiceForTesting( 'TitleParser' );
636 $services->resetServiceForTesting( '_MediaWikiTitleCodec' );
637 $services->resetServiceForTesting( 'LinkRenderer' );
638 $services->resetServiceForTesting( 'LinkRendererFactory' );
642 * Remove last character if it is a newline
646 public static function chomp( $s ) {
647 if ( substr( $s, -1 ) === "\n" ) {
648 return substr( $s, 0, -1 );
655 * Run a series of tests listed in the given text files.
656 * Each test consists of a brief description, wikitext input,
657 * and the expected HTML output.
659 * Prints status updates on stdout and counts up the total
660 * number and percentage of passed tests.
662 * Handles all setup and teardown.
664 * @param array $filenames Array of strings
665 * @return bool True if passed all tests, false if any tests failed.
667 public function runTestsFromFiles( $filenames ) {
670 $teardownGuard = $this->staticSetup();
671 $teardownGuard = $this->setupDatabase( $teardownGuard );
672 $teardownGuard = $this->setupUploads( $teardownGuard );
674 $this->recorder
->start();
678 foreach ( $filenames as $filename ) {
679 $testFileInfo = TestFileReader
::read( $filename, [
680 'runDisabled' => $this->runDisabled
,
681 'runParsoid' => $this->runParsoid
,
682 'regex' => $this->regex
] );
684 // Don't start the suite if there are no enabled tests in the file
685 if ( !$testFileInfo['tests'] ) {
689 $this->recorder
->startSuite( $filename );
690 $ok = $this->runTests( $testFileInfo ) && $ok;
691 $this->recorder
->endSuite( $filename );
694 $this->recorder
->report();
695 } catch ( DBError
$e ) {
696 $this->recorder
->warning( $e->getMessage() );
698 $this->recorder
->end();
700 ScopedCallback
::consume( $teardownGuard );
706 * Determine whether the current parser has the hooks registered in it
707 * that are required by a file read by TestFileReader.
708 * @param array $requirements
711 public function meetsRequirements( $requirements ) {
712 foreach ( $requirements as $requirement ) {
713 switch ( $requirement['type'] ) {
715 $ok = $this->requireHook( $requirement['name'] );
718 $ok = $this->requireFunctionHook( $requirement['name'] );
720 case 'transparentHook':
721 $ok = $this->requireTransparentHook( $requirement['name'] );
732 * Run the tests from a single file. staticSetup() and setupDatabase()
733 * must have been called already.
735 * @param array $testFileInfo Parsed file info returned by TestFileReader
736 * @return bool True if passed all tests, false if any tests failed.
738 public function runTests( $testFileInfo ) {
741 $this->checkSetupDone( 'staticSetup' );
743 // Don't add articles from the file if there are no enabled tests from the file
744 if ( !$testFileInfo['tests'] ) {
748 // If any requirements are not met, mark all tests from the file as skipped
749 if ( !$this->meetsRequirements( $testFileInfo['requirements'] ) ) {
750 foreach ( $testFileInfo['tests'] as $test ) {
751 $this->recorder
->startTest( $test );
752 $this->recorder
->skipped( $test, 'required extension not enabled' );
758 $this->addArticles( $testFileInfo['articles'] );
761 foreach ( $testFileInfo['tests'] as $test ) {
762 $this->recorder
->startTest( $test );
764 $this->runTest( $test );
765 if ( $result !== false ) {
766 $ok = $ok && $result->isSuccess();
767 $this->recorder
->record( $test, $result );
775 * Get a Parser object
777 * @param string $preprocessor
780 function getParser( $preprocessor = null ) {
781 global $wgParserConf;
783 $class = $wgParserConf['class'];
784 $parser = new $class( [ 'preprocessorClass' => $preprocessor ] +
$wgParserConf );
785 ParserTestParserHook
::setup( $parser );
791 * Run a given wikitext input through a freshly-constructed wiki parser,
792 * and compare the output against the expected results.
793 * Prints status and explanatory messages to stdout.
795 * staticSetup() and setupWikiData() must be called before this function
798 * @param array $test The test parameters:
799 * - test: The test name
800 * - desc: The subtest description
801 * - input: Wikitext to try rendering
802 * - options: Array of test options
803 * - config: Overrides for global variables, one per line
805 * @return ParserTestResult|false false if skipped
807 public function runTest( $test ) {
808 wfDebug( __METHOD__
.": running {$test['desc']}" );
809 $opts = $this->parseOptions( $test['options'] );
810 $teardownGuard = $this->perTestSetup( $test );
812 $context = RequestContext
::getMain();
813 $user = $context->getUser();
814 $options = ParserOptions
::newFromContext( $context );
815 $options->setTimestamp( $this->getFakeTimestamp() );
817 if ( isset( $opts['tidy'] ) ) {
818 if ( !$this->tidySupport
->isEnabled() ) {
819 $this->recorder
->skipped( $test, 'tidy extension is not installed' );
822 $options->setTidy( true );
826 if ( isset( $opts['title'] ) ) {
827 $titleText = $opts['title'];
829 $titleText = 'Parser test';
832 $local = isset( $opts['local'] );
833 $preprocessor = isset( $opts['preprocessor'] ) ?
$opts['preprocessor'] : null;
834 $parser = $this->getParser( $preprocessor );
835 $title = Title
::newFromText( $titleText );
837 if ( isset( $opts['styletag'] ) ) {
838 // For testing the behavior of <style> (including those deduplicated
839 // into <link> tags), add tag hooks to allow them to be generated.
840 $parser->setHook( 'style', function ( $content, $attributes, $parser ) {
841 $marker = Parser
::MARKER_PREFIX
. '-style-' . md5( $content ) . Parser
::MARKER_SUFFIX
;
842 $parser->mStripState
->addNoWiki( $marker, $content );
843 return Html
::inlineStyle( $marker, 'all', $attributes );
845 $parser->setHook( 'link', function ( $content, $attributes, $parser ) {
846 return Html
::element( 'link', $attributes );
850 if ( isset( $opts['pst'] ) ) {
851 $out = $parser->preSaveTransform( $test['input'], $title, $user, $options );
852 $output = $parser->getOutput();
853 } elseif ( isset( $opts['msg'] ) ) {
854 $out = $parser->transformMsg( $test['input'], $options, $title );
855 } elseif ( isset( $opts['section'] ) ) {
856 $section = $opts['section'];
857 $out = $parser->getSection( $test['input'], $section );
858 } elseif ( isset( $opts['replace'] ) ) {
859 $section = $opts['replace'][0];
860 $replace = $opts['replace'][1];
861 $out = $parser->replaceSection( $test['input'], $section, $replace );
862 } elseif ( isset( $opts['comment'] ) ) {
863 $out = Linker
::formatComment( $test['input'], $title, $local );
864 } elseif ( isset( $opts['preload'] ) ) {
865 $out = $parser->getPreloadText( $test['input'], $title, $options );
867 $output = $parser->parse( $test['input'], $title, $options, true, true, 1337 );
868 $out = $output->getText( [
869 'allowTOC' => !isset( $opts['notoc'] ),
870 'unwrap' => !isset( $opts['wrap'] ),
872 if ( isset( $opts['tidy'] ) ) {
873 $out = preg_replace( '/\s+$/', '', $out );
876 if ( isset( $opts['showtitle'] ) ) {
877 if ( $output->getTitleText() ) {
878 $title = $output->getTitleText();
881 $out = "$title\n$out";
884 if ( isset( $opts['showindicators'] ) ) {
886 foreach ( $output->getIndicators() as $id => $content ) {
887 $indicators .= "$id=$content\n";
889 $out = $indicators . $out;
892 if ( isset( $opts['ill'] ) ) {
893 $out = implode( ' ', $output->getLanguageLinks() );
894 } elseif ( isset( $opts['cat'] ) ) {
896 foreach ( $output->getCategories() as $name => $sortkey ) {
900 $out .= "cat=$name sort=$sortkey";
905 if ( isset( $output ) && isset( $opts['showflags'] ) ) {
906 $actualFlags = array_keys( TestingAccessWrapper
::newFromObject( $output )->mFlags
);
907 sort( $actualFlags );
908 $out .= "\nflags=" . implode( ', ', $actualFlags );
911 ScopedCallback
::consume( $teardownGuard );
913 $expected = $test['result'];
914 if ( count( $this->normalizationFunctions
) ) {
915 $expected = ParserTestResultNormalizer
::normalize(
916 $test['expected'], $this->normalizationFunctions
);
917 $out = ParserTestResultNormalizer
::normalize( $out, $this->normalizationFunctions
);
920 $testResult = new ParserTestResult( $test, $expected, $out );
925 * Use a regex to find out the value of an option
926 * @param string $key Name of option val to retrieve
927 * @param array $opts Options array to look in
928 * @param mixed $default Default value returned if not found
931 private static function getOptionValue( $key, $opts, $default ) {
932 $key = strtolower( $key );
934 if ( isset( $opts[$key] ) ) {
942 * Given the options string, return an associative array of options.
943 * @todo Move this to TestFileReader
945 * @param string $instring
948 private function parseOptions( $instring ) {
954 // foo=bar,"baz quux"
957 (?<qstr> # Quoted string
959 (?:[^\\\\"] | \\\\.)*
965 [^"{}] | # Not a quoted string or object, or
966 (?&qstr) | # A quoted string, or
967 (?&json) # A json object (recursively)
973 (?&qstr) # Quoted val
981 (?&json) # JSON object
985 $regex = '/' . $defs . '\b
1001 $valueregex = '/' . $defs . '(?&value)/x';
1003 if ( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER
) ) {
1004 foreach ( $matches as $bits ) {
1005 $key = strtolower( $bits['k'] );
1006 if ( !isset( $bits['v'] ) ) {
1009 preg_match_all( $valueregex, $bits['v'], $vmatches );
1010 $opts[$key] = array_map( [ $this, 'cleanupOption' ], $vmatches[0] );
1011 if ( count( $opts[$key] ) == 1 ) {
1012 $opts[$key] = $opts[$key][0];
1020 private function cleanupOption( $opt ) {
1021 if ( substr( $opt, 0, 1 ) == '"' ) {
1022 return stripcslashes( substr( $opt, 1, -1 ) );
1025 if ( substr( $opt, 0, 2 ) == '[[' ) {
1026 return substr( $opt, 2, -2 );
1029 if ( substr( $opt, 0, 1 ) == '{' ) {
1030 return FormatJson
::decode( $opt, true );
1036 * Do any required setup which is dependent on test options.
1038 * @see staticSetup() for more information about setup/teardown
1040 * @param array $test Test info supplied by TestFileReader
1041 * @param callable|null $nextTeardown
1042 * @return ScopedCallback
1044 public function perTestSetup( $test, $nextTeardown = null ) {
1047 $this->checkSetupDone( 'setupDatabase', 'setDatabase' );
1048 $teardown[] = $this->markSetupDone( 'perTestSetup' );
1050 $opts = $this->parseOptions( $test['options'] );
1051 $config = $test['config'];
1053 // Find out values for some special options.
1055 self
::getOptionValue( 'language', $opts, 'en' );
1057 self
::getOptionValue( 'variant', $opts, false );
1059 self
::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
1060 $linkHolderBatchSize =
1061 self
::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
1063 // Default to fallback skin, but allow it to be overridden
1064 $skin = self
::getOptionValue( 'skin', $opts, 'fallback' );
1067 'wgEnableUploads' => self
::getOptionValue( 'wgEnableUploads', $opts, true ),
1068 'wgLanguageCode' => $langCode,
1069 'wgRawHtml' => self
::getOptionValue( 'wgRawHtml', $opts, false ),
1070 'wgNamespacesWithSubpages' => array_fill_keys(
1071 MWNamespace
::getValidNamespaces(), isset( $opts['subpage'] )
1073 'wgMaxTocLevel' => $maxtoclevel,
1074 'wgAllowExternalImages' => self
::getOptionValue( 'wgAllowExternalImages', $opts, true ),
1075 'wgThumbLimits' => [ self
::getOptionValue( 'thumbsize', $opts, 180 ) ],
1076 'wgDefaultLanguageVariant' => $variant,
1077 'wgLinkHolderBatchSize' => $linkHolderBatchSize,
1078 // Set as a JSON object like:
1079 // wgEnableMagicLinks={"ISBN":false, "PMID":false, "RFC":false}
1080 'wgEnableMagicLinks' => self
::getOptionValue( 'wgEnableMagicLinks', $opts, [] )
1081 +
[ 'ISBN' => true, 'PMID' => true, 'RFC' => true ],
1082 // Test with legacy encoding by default until HTML5 is very stable and default
1083 'wgFragmentMode' => [ 'legacy' ],
1087 $configLines = explode( "\n", $config );
1089 foreach ( $configLines as $line ) {
1090 list( $var, $value ) = explode( '=', $line, 2 );
1091 $setup[$var] = eval( "return $value;" );
1096 Hooks
::run( 'ParserTestGlobals', [ &$setup ] );
1098 // Create tidy driver
1099 if ( isset( $opts['tidy'] ) ) {
1100 // Cache a driver instance
1101 if ( $this->tidyDriver
=== null ) {
1102 $this->tidyDriver
= MWTidy
::factory( $this->tidySupport
->getConfig() );
1104 $tidy = $this->tidyDriver
;
1108 MWTidy
::setInstance( $tidy );
1109 $teardown[] = function () {
1110 MWTidy
::destroySingleton();
1113 // Set content language. This invalidates the magic word cache and title services
1114 $lang = Language
::factory( $langCode );
1115 $lang->resetNamespaces();
1116 $setup['wgContLang'] = $lang;
1117 $reset = function () {
1118 MagicWord
::clearCache();
1119 $this->resetTitleServices();
1122 $teardown[] = $reset;
1124 // Make a user object with the same language
1126 $user->setOption( 'language', $langCode );
1127 $setup['wgLang'] = $lang;
1129 // We (re)set $wgThumbLimits to a single-element array above.
1130 $user->setOption( 'thumbsize', 0 );
1132 $setup['wgUser'] = $user;
1134 // And put both user and language into the context
1135 $context = RequestContext
::getMain();
1136 $context->setUser( $user );
1137 $context->setLanguage( $lang );
1139 $oldSkin = $context->getSkin();
1140 $skinFactory = MediaWikiServices
::getInstance()->getSkinFactory();
1141 $context->setSkin( $skinFactory->makeSkin( $skin ) );
1142 $context->setOutput( new OutputPage( $context ) );
1143 $setup['wgOut'] = $context->getOutput();
1144 $teardown[] = function () use ( $context, $oldSkin ) {
1145 // Clear language conversion tables
1146 $wrapper = TestingAccessWrapper
::newFromObject(
1147 $context->getLanguage()->getConverter()
1149 $wrapper->reloadTables();
1150 // Reset context to the restored globals
1151 $context->setUser( $GLOBALS['wgUser'] );
1152 $context->setLanguage( $GLOBALS['wgContLang'] );
1153 $context->setSkin( $oldSkin );
1154 $context->setOutput( $GLOBALS['wgOut'] );
1157 $teardown[] = $this->executeSetupSnippets( $setup );
1159 return $this->createTeardownObject( $teardown, $nextTeardown );
1163 * List of temporary tables to create, without prefix.
1164 * Some of these probably aren't necessary.
1167 private function listTables() {
1168 global $wgCommentTableSchemaMigrationStage, $wgActorTableSchemaMigrationStage;
1170 $tables = [ 'user', 'user_properties', 'user_former_groups', 'page', 'page_restrictions',
1171 'protected_titles', 'revision', 'ip_changes', 'text', 'pagelinks', 'imagelinks',
1172 'categorylinks', 'templatelinks', 'externallinks', 'langlinks', 'iwlinks',
1173 'site_stats', 'ipblocks', 'image', 'oldimage',
1174 'recentchanges', 'watchlist', 'interwiki', 'logging', 'log_search',
1175 'querycache', 'objectcache', 'job', 'l10n_cache', 'redirect', 'querycachetwo',
1176 'archive', 'user_groups', 'page_props', 'category'
1179 if ( $wgCommentTableSchemaMigrationStage >= MIGRATION_WRITE_BOTH
) {
1180 // The new tables for comments are in use
1181 $tables[] = 'comment';
1182 $tables[] = 'revision_comment_temp';
1183 $tables[] = 'image_comment_temp';
1186 if ( $wgActorTableSchemaMigrationStage >= MIGRATION_WRITE_BOTH
) {
1187 // The new tables for actors are in use
1188 $tables[] = 'actor';
1189 $tables[] = 'revision_actor_temp';
1192 if ( in_array( $this->db
->getType(), [ 'mysql', 'sqlite', 'oracle' ] ) ) {
1193 array_push( $tables, 'searchindex' );
1196 // Allow extensions to add to the list of tables to duplicate;
1197 // may be necessary if they hook into page save or other code
1198 // which will require them while running tests.
1199 Hooks
::run( 'ParserTestTables', [ &$tables ] );
1204 public function setDatabase( IDatabase
$db ) {
1206 $this->setupDone
['setDatabase'] = true;
1210 * Set up temporary DB tables.
1212 * For best performance, call this once only for all tests. However, it can
1213 * be called at the start of each test if more isolation is desired.
1215 * @todo: This is basically an unrefactored copy of
1216 * MediaWikiTestCase::setupAllTestDBs. They should be factored out somehow.
1218 * Do not call this function from a MediaWikiTestCase subclass, since
1219 * MediaWikiTestCase does its own DB setup. Instead use setDatabase().
1221 * @see staticSetup() for more information about setup/teardown
1223 * @param ScopedCallback|null $nextTeardown The next teardown object
1224 * @return ScopedCallback The teardown object
1226 public function setupDatabase( $nextTeardown = null ) {
1229 $this->db
= wfGetDB( DB_MASTER
);
1230 $dbType = $this->db
->getType();
1232 if ( $dbType == 'oracle' ) {
1233 $suspiciousPrefixes = [ 'pt_', MediaWikiTestCase
::ORA_DB_PREFIX
];
1235 $suspiciousPrefixes = [ 'parsertest_', MediaWikiTestCase
::DB_PREFIX
];
1237 if ( in_array( $wgDBprefix, $suspiciousPrefixes ) ) {
1238 throw new MWException( "\$wgDBprefix=$wgDBprefix suggests DB setup is already done" );
1243 $teardown[] = $this->markSetupDone( 'setupDatabase' );
1245 # CREATE TEMPORARY TABLE breaks if there is more than one server
1246 if ( MediaWikiServices
::getInstance()->getDBLoadBalancer()->getServerCount() != 1 ) {
1247 $this->useTemporaryTables
= false;
1250 $temporary = $this->useTemporaryTables ||
$dbType == 'postgres';
1251 $prefix = $dbType != 'oracle' ?
'parsertest_' : 'pt_';
1253 $this->dbClone
= new CloneDatabase( $this->db
, $this->listTables(), $prefix );
1254 $this->dbClone
->useTemporaryTables( $temporary );
1255 $this->dbClone
->cloneTableStructure();
1257 if ( $dbType == 'oracle' ) {
1258 $this->db
->query( 'BEGIN FILL_WIKI_INFO; END;' );
1259 # Insert 0 user to prevent FK violations
1262 $this->db
->insert( 'user', [
1264 'user_name' => 'Anonymous' ] );
1267 $teardown[] = function () {
1268 $this->teardownDatabase();
1271 // Wipe some DB query result caches on setup and teardown
1272 $reset = function () {
1273 LinkCache
::singleton()->clear();
1275 // Clear the message cache
1276 MessageCache
::singleton()->clear();
1279 $teardown[] = $reset;
1280 return $this->createTeardownObject( $teardown, $nextTeardown );
1284 * Add data about uploads to the new test DB, and set up the upload
1285 * directory. This should be called after either setDatabase() or
1288 * @param ScopedCallback|null $nextTeardown The next teardown object
1289 * @return ScopedCallback The teardown object
1291 public function setupUploads( $nextTeardown = null ) {
1294 $this->checkSetupDone( 'setupDatabase', 'setDatabase' );
1295 $teardown[] = $this->markSetupDone( 'setupUploads' );
1297 // Create the files in the upload directory (or pretend to create them
1298 // in a MockFileBackend). Append teardown callback.
1299 $teardown[] = $this->setupUploadBackend();
1302 $user = User
::createNew( 'WikiSysop' );
1304 // Register the uploads in the database
1306 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Foobar.jpg' ) );
1307 # note that the size/width/height/bits/etc of the file
1308 # are actually set by inspecting the file itself; the arguments
1309 # to recordUpload2 have no effect. That said, we try to make things
1310 # match up so it is less confusing to readers of the code & tests.
1311 $image->recordUpload2( '', 'Upload of some lame file', 'Some lame file', [
1316 'media_type' => MEDIATYPE_BITMAP
,
1317 'mime' => 'image/jpeg',
1318 'metadata' => serialize( [] ),
1319 'sha1' => Wikimedia\base_convert
( '1', 16, 36, 31 ),
1320 'fileExists' => true
1321 ], $this->db
->timestamp( '20010115123500' ), $user );
1323 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Thumb.png' ) );
1324 # again, note that size/width/height below are ignored; see above.
1325 $image->recordUpload2( '', 'Upload of some lame thumbnail', 'Some lame thumbnail', [
1330 'media_type' => MEDIATYPE_BITMAP
,
1331 'mime' => 'image/png',
1332 'metadata' => serialize( [] ),
1333 'sha1' => Wikimedia\base_convert
( '2', 16, 36, 31 ),
1334 'fileExists' => true
1335 ], $this->db
->timestamp( '20130225203040' ), $user );
1337 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Foobar.svg' ) );
1338 $image->recordUpload2( '', 'Upload of some lame SVG', 'Some lame SVG', [
1343 'media_type' => MEDIATYPE_DRAWING
,
1344 'mime' => 'image/svg+xml',
1345 'metadata' => serialize( [] ),
1346 'sha1' => Wikimedia\base_convert
( '', 16, 36, 31 ),
1347 'fileExists' => true
1348 ], $this->db
->timestamp( '20010115123500' ), $user );
1350 # This image will be blacklisted in [[MediaWiki:Bad image list]]
1351 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Bad.jpg' ) );
1352 $image->recordUpload2( '', 'zomgnotcensored', 'Borderline image', [
1357 'media_type' => MEDIATYPE_BITMAP
,
1358 'mime' => 'image/jpeg',
1359 'metadata' => serialize( [] ),
1360 'sha1' => Wikimedia\base_convert
( '3', 16, 36, 31 ),
1361 'fileExists' => true
1362 ], $this->db
->timestamp( '20010115123500' ), $user );
1364 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Video.ogv' ) );
1365 $image->recordUpload2( '', 'A pretty movie', 'Will it play', [
1370 'media_type' => MEDIATYPE_VIDEO
,
1371 'mime' => 'application/ogg',
1372 'metadata' => serialize( [] ),
1373 'sha1' => Wikimedia\base_convert
( '', 16, 36, 31 ),
1374 'fileExists' => true
1375 ], $this->db
->timestamp( '20010115123500' ), $user );
1377 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Audio.oga' ) );
1378 $image->recordUpload2( '', 'An awesome hitsong', 'Will it play', [
1383 'media_type' => MEDIATYPE_AUDIO
,
1384 'mime' => 'application/ogg',
1385 'metadata' => serialize( [] ),
1386 'sha1' => Wikimedia\base_convert
( '', 16, 36, 31 ),
1387 'fileExists' => true
1388 ], $this->db
->timestamp( '20010115123500' ), $user );
1391 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'LoremIpsum.djvu' ) );
1392 $image->recordUpload2( '', 'Upload a DjVu', 'A DjVu', [
1397 'media_type' => MEDIATYPE_BITMAP
,
1398 'mime' => 'image/vnd.djvu',
1399 'metadata' => '<?xml version="1.0" ?>
1400 <!DOCTYPE DjVuXML PUBLIC "-//W3C//DTD DjVuXML 1.1//EN" "pubtext/DjVuXML-s.dtd">
1403 <BODY><OBJECT height="3508" width="2480">
1404 <PARAM name="DPI" value="300" />
1405 <PARAM name="GAMMA" value="2.2" />
1407 <OBJECT height="3508" width="2480">
1408 <PARAM name="DPI" value="300" />
1409 <PARAM name="GAMMA" value="2.2" />
1411 <OBJECT height="3508" width="2480">
1412 <PARAM name="DPI" value="300" />
1413 <PARAM name="GAMMA" value="2.2" />
1415 <OBJECT height="3508" width="2480">
1416 <PARAM name="DPI" value="300" />
1417 <PARAM name="GAMMA" value="2.2" />
1419 <OBJECT height="3508" width="2480">
1420 <PARAM name="DPI" value="300" />
1421 <PARAM name="GAMMA" value="2.2" />
1425 'sha1' => Wikimedia\base_convert
( '', 16, 36, 31 ),
1426 'fileExists' => true
1427 ], $this->db
->timestamp( '20010115123600' ), $user );
1429 return $this->createTeardownObject( $teardown, $nextTeardown );
1433 * Helper for database teardown, called from the teardown closure. Destroy
1434 * the database clone and fix up some things that CloneDatabase doesn't fix.
1436 * @todo Move most things here to CloneDatabase
1438 private function teardownDatabase() {
1439 $this->checkSetupDone( 'setupDatabase' );
1441 $this->dbClone
->destroy();
1442 $this->databaseSetupDone
= false;
1444 if ( $this->useTemporaryTables
) {
1445 if ( $this->db
->getType() == 'sqlite' ) {
1446 # Under SQLite the searchindex table is virtual and need
1447 # to be explicitly destroyed. See T31912
1448 # See also MediaWikiTestCase::destroyDB()
1449 wfDebug( __METHOD__
. " explicitly destroying sqlite virtual table parsertest_searchindex\n" );
1450 $this->db
->query( "DROP TABLE `parsertest_searchindex`" );
1452 # Don't need to do anything
1456 $tables = $this->listTables();
1458 foreach ( $tables as $table ) {
1459 if ( $this->db
->getType() == 'oracle' ) {
1460 $this->db
->query( "DROP TABLE pt_$table DROP CONSTRAINTS" );
1462 $this->db
->query( "DROP TABLE `parsertest_$table`" );
1466 if ( $this->db
->getType() == 'oracle' ) {
1467 $this->db
->query( 'BEGIN FILL_WIKI_INFO; END;' );
1472 * Upload test files to the backend created by createRepoGroup().
1474 * @return callable The teardown callback
1476 private function setupUploadBackend() {
1479 $repo = RepoGroup
::singleton()->getLocalRepo();
1480 $base = $repo->getZonePath( 'public' );
1481 $backend = $repo->getBackend();
1482 $backend->prepare( [ 'dir' => "$base/3/3a" ] );
1484 'src' => "$IP/tests/phpunit/data/parser/headbg.jpg",
1485 'dst' => "$base/3/3a/Foobar.jpg"
1487 $backend->prepare( [ 'dir' => "$base/e/ea" ] );
1489 'src' => "$IP/tests/phpunit/data/parser/wiki.png",
1490 'dst' => "$base/e/ea/Thumb.png"
1492 $backend->prepare( [ 'dir' => "$base/0/09" ] );
1494 'src' => "$IP/tests/phpunit/data/parser/headbg.jpg",
1495 'dst' => "$base/0/09/Bad.jpg"
1497 $backend->prepare( [ 'dir' => "$base/5/5f" ] );
1499 'src' => "$IP/tests/phpunit/data/parser/LoremIpsum.djvu",
1500 'dst' => "$base/5/5f/LoremIpsum.djvu"
1503 // No helpful SVG file to copy, so make one ourselves
1504 $data = '<?xml version="1.0" encoding="utf-8"?>' .
1505 '<svg xmlns="http://www.w3.org/2000/svg"' .
1506 ' version="1.1" width="240" height="180"/>';
1508 $backend->prepare( [ 'dir' => "$base/f/ff" ] );
1509 $backend->quickCreate( [
1510 'content' => $data, 'dst' => "$base/f/ff/Foobar.svg"
1513 return function () use ( $backend ) {
1514 if ( $backend instanceof MockFileBackend
) {
1515 // In memory backend, so dont bother cleaning them up.
1518 $this->teardownUploadBackend();
1523 * Remove the dummy uploads directory
1525 private function teardownUploadBackend() {
1526 if ( $this->keepUploads
) {
1530 $repo = RepoGroup
::singleton()->getLocalRepo();
1531 $public = $repo->getZonePath( 'public' );
1535 "$public/3/3a/Foobar.jpg",
1536 "$public/e/ea/Thumb.png",
1537 "$public/0/09/Bad.jpg",
1538 "$public/5/5f/LoremIpsum.djvu",
1539 "$public/f/ff/Foobar.svg",
1540 "$public/0/00/Video.ogv",
1541 "$public/4/41/Audio.oga",
1547 * Delete the specified files and their parent directories
1548 * @param array $files File backend URIs mwstore://...
1550 private function deleteFiles( $files ) {
1552 $backend = RepoGroup
::singleton()->getLocalRepo()->getBackend();
1553 foreach ( $files as $file ) {
1554 $backend->delete( [ 'src' => $file ], [ 'force' => 1 ] );
1557 // Delete the parent directories
1558 foreach ( $files as $file ) {
1559 $tmp = FileBackend
::parentStoragePath( $file );
1561 if ( !$backend->clean( [ 'dir' => $tmp ] )->isOK() ) {
1564 $tmp = FileBackend
::parentStoragePath( $tmp );
1570 * Add articles to the test DB.
1572 * @param array $articles Article info array from TestFileReader
1574 public function addArticles( $articles ) {
1579 // Be sure ParserTestRunner::addArticle has correct language set,
1580 // so that system messages get into the right language cache
1581 if ( $wgContLang->getCode() !== 'en' ) {
1582 $setup['wgLanguageCode'] = 'en';
1583 $setup['wgContLang'] = Language
::factory( 'en' );
1586 // Add special namespaces, in case that hasn't been done by staticSetup() yet
1587 $this->appendNamespaceSetup( $setup, $teardown );
1589 // wgCapitalLinks obviously needs initialisation
1590 $setup['wgCapitalLinks'] = true;
1592 $teardown[] = $this->executeSetupSnippets( $setup );
1594 foreach ( $articles as $info ) {
1595 $this->addArticle( $info['name'], $info['text'], $info['file'], $info['line'] );
1598 // Wipe WANObjectCache process cache, which is invalidated by article insertion
1600 ObjectCache
::getMainWANInstance()->clearProcessCache();
1602 $this->executeSetupSnippets( $teardown );
1606 * Insert a temporary test article
1607 * @param string $name The title, including any prefix
1608 * @param string $text The article text
1609 * @param string $file The input file name
1610 * @param int|string $line The input line number, for reporting errors
1612 * @throws MWException
1614 private function addArticle( $name, $text, $file, $line ) {
1615 $text = self
::chomp( $text );
1616 $name = self
::chomp( $name );
1618 $title = Title
::newFromText( $name );
1619 wfDebug( __METHOD__
. ": adding $name" );
1621 if ( is_null( $title ) ) {
1622 throw new MWException( "invalid title '$name' at $file:$line\n" );
1625 $newContent = ContentHandler
::makeContent( $text, $title );
1627 $page = WikiPage
::factory( $title );
1628 $page->loadPageData( 'fromdbmaster' );
1630 if ( $page->exists() ) {
1631 $content = $page->getContent( Revision
::RAW
);
1632 // Only reject the title, if the content/content model is different.
1633 // This makes it easier to create Template:(( or Template:)) in different extensions
1634 if ( $newContent->equals( $content ) ) {
1637 throw new MWException(
1638 "duplicate article '$name' with different content at $file:$line\n"
1642 // Use mock parser, to make debugging of actual parser tests simpler.
1643 // But initialise the MessageCache clone first, don't let MessageCache
1644 // get a reference to the mock object.
1645 MessageCache
::singleton()->getParser();
1646 $restore = $this->executeSetupSnippets( [ 'wgParser' => new ParserTestMockParser
] );
1648 $status = $page->doEditContent(
1651 EDIT_NEW | EDIT_INTERNAL
1657 if ( !$status->isOK() ) {
1658 throw new MWException( $status->getWikiText( false, false, 'en' ) );
1661 // The RepoGroup cache is invalidated by the creation of file redirects
1662 if ( $title->inNamespace( NS_FILE
) ) {
1663 RepoGroup
::singleton()->clearCache( $title );
1668 * Check if a hook is installed
1670 * @param string $name
1671 * @return bool True if tag hook is present
1673 public function requireHook( $name ) {
1676 $wgParser->firstCallInit(); // make sure hooks are loaded.
1677 if ( isset( $wgParser->mTagHooks
[$name] ) ) {
1680 $this->recorder
->warning( " This test suite requires the '$name' hook " .
1681 "extension, skipping." );
1687 * Check if a function hook is installed
1689 * @param string $name
1690 * @return bool True if function hook is present
1692 public function requireFunctionHook( $name ) {
1695 $wgParser->firstCallInit(); // make sure hooks are loaded.
1697 if ( isset( $wgParser->mFunctionHooks
[$name] ) ) {
1700 $this->recorder
->warning( " This test suite requires the '$name' function " .
1701 "hook extension, skipping." );
1707 * Check if a transparent tag hook is installed
1709 * @param string $name
1710 * @return bool True if function hook is present
1712 public function requireTransparentHook( $name ) {
1715 $wgParser->firstCallInit(); // make sure hooks are loaded.
1717 if ( isset( $wgParser->mTransparentTagHooks
[$name] ) ) {
1720 $this->recorder
->warning( " This test suite requires the '$name' transparent " .
1721 "hook extension, skipping.\n" );
1727 * Fake constant timestamp to make sure time-related parser
1728 * functions give a persistent value.
1730 * - Parser::getVariableValue (via ParserGetVariableValueTs hook)
1731 * - Parser::preSaveTransform (via ParserOptions)
1733 private function getFakeTimestamp() {
1734 // parsed as '1970-01-01T00:02:03Z'