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 Wikimedia\ScopedCallback
;
31 use Wikimedia\TestingAccessWrapper
;
36 class ParserTestRunner
{
39 * MediaWiki core parser test files, paths
40 * will be prefixed with __DIR__ . '/'
44 private static $coreTestFiles = [
46 'extraParserTests.txt',
50 * @var bool $useTemporaryTables Use temporary tables for the temporary database
52 private $useTemporaryTables = true;
55 * @var array $setupDone The status of each setup function
57 private $setupDone = [
58 'staticSetup' => false,
59 'perTestSetup' => false,
60 'setupDatabase' => false,
61 'setDatabase' => false,
62 'setupUploads' => false,
66 * Our connection to the database
72 * Database clone helper
85 private $tidyDriver = null;
93 * The upload directory, or null to not set up an upload directory
97 private $uploadDir = null;
100 * The name of the file backend to use, or null to use MockFileBackend.
103 private $fileBackendName;
106 * A complete regex for filtering tests.
112 * A list of normalization functions to apply to the expected and actual
116 private $normalizationFunctions = [];
119 * @param TestRecorder $recorder
120 * @param array $options
122 public function __construct( TestRecorder
$recorder, $options = [] ) {
123 $this->recorder
= $recorder;
125 if ( isset( $options['norm'] ) ) {
126 foreach ( $options['norm'] as $func ) {
127 if ( in_array( $func, [ 'removeTbody', 'trimWhitespace' ] ) ) {
128 $this->normalizationFunctions
[] = $func;
130 $this->recorder
->warning(
131 "Warning: unknown normalization option \"$func\"\n" );
136 if ( isset( $options['regex'] ) && $options['regex'] !== false ) {
137 $this->regex
= $options['regex'];
143 $this->keepUploads
= !empty( $options['keep-uploads'] );
145 $this->fileBackendName
= isset( $options['file-backend'] ) ?
146 $options['file-backend'] : false;
148 $this->runDisabled
= !empty( $options['run-disabled'] );
149 $this->runParsoid
= !empty( $options['run-parsoid'] );
151 $this->tidySupport
= new TidySupport( !empty( $options['use-tidy-config'] ) );
152 if ( !$this->tidySupport
->isEnabled() ) {
153 $this->recorder
->warning(
154 "Warning: tidy is not installed, skipping some tests\n" );
157 if ( isset( $options['upload-dir'] ) ) {
158 $this->uploadDir
= $options['upload-dir'];
163 * Get list of filenames to extension and core parser tests
167 public static function getParserTestFiles() {
168 global $wgParserTestFiles;
170 // Add core test files
171 $files = array_map( function ( $item ) {
172 return __DIR__
. "/$item";
173 }, self
::$coreTestFiles );
175 // Plus legacy global files
176 $files = array_merge( $files, $wgParserTestFiles );
178 // Auto-discover extension parser tests
179 $registry = ExtensionRegistry
::getInstance();
180 foreach ( $registry->getAllThings() as $info ) {
181 $dir = dirname( $info['path'] ) . '/tests/parser';
182 if ( !file_exists( $dir ) ) {
186 $dirIterator = new RecursiveIteratorIterator(
187 new RecursiveDirectoryIterator( $dir )
189 foreach ( $dirIterator as $fileInfo ) {
190 /** @var SplFileInfo $fileInfo */
191 if ( substr( $fileInfo->getFilename(), -4 ) === '.txt' ) {
192 $name = $info['name'] . $counter;
193 while ( isset( $files[$name] ) ) {
194 $name = $info['name'] . '_' . $counter++
;
196 $files[$name] = $fileInfo->getPathname();
201 return array_unique( $files );
204 public function getRecorder() {
205 return $this->recorder
;
209 * Do any setup which can be done once for all tests, independent of test
210 * options, except for database setup.
212 * Public setup functions in this class return a ScopedCallback object. When
213 * this object is destroyed by going out of scope, teardown of the
214 * corresponding test setup is performed.
216 * Teardown objects may be chained by passing a ScopedCallback from a
217 * previous setup stage as the $nextTeardown parameter. This enforces the
218 * convention that teardown actions are taken in reverse order to the
219 * corresponding setup actions. When $nextTeardown is specified, a
220 * ScopedCallback will be returned which first tears down the current
221 * setup stage, and then tears down the previous setup stage which was
222 * specified by $nextTeardown.
224 * @param ScopedCallback|null $nextTeardown
225 * @return ScopedCallback
227 public function staticSetup( $nextTeardown = null ) {
228 // A note on coding style:
230 // The general idea here is to keep setup code together with
231 // corresponding teardown code, in a fine-grained manner. We have two
232 // arrays: $setup and $teardown. The code snippets in the $setup array
233 // are executed at the end of the method, before it returns, and the
234 // code snippets in the $teardown array are executed in reverse order
235 // when the Wikimedia\ScopedCallback object is consumed.
237 // Because it is a common operation to save, set and restore global
238 // variables, we have an additional convention: when the array key of
239 // $setup is a string, the string is taken to be the name of the global
240 // variable, and the element value is taken to be the desired new value.
242 // It's acceptable to just do the setup immediately, instead of adding
243 // a closure to $setup, except when the setup action depends on global
244 // variable initialisation being done first. In this case, you have to
245 // append a closure to $setup after the global variable is appended.
247 // When you add to setup functions in this class, please keep associated
248 // setup and teardown actions together in the source code, and please
249 // add comments explaining why the setup action is necessary.
254 $teardown[] = $this->markSetupDone( 'staticSetup' );
256 // Some settings which influence HTML output
257 $setup['wgSitename'] = 'MediaWiki';
258 $setup['wgServer'] = 'http://example.org';
259 $setup['wgServerName'] = 'example.org';
260 $setup['wgScriptPath'] = '';
261 $setup['wgScript'] = '/index.php';
262 $setup['wgResourceBasePath'] = '';
263 $setup['wgStylePath'] = '/skins';
264 $setup['wgExtensionAssetsPath'] = '/extensions';
265 $setup['wgArticlePath'] = '/wiki/$1';
266 $setup['wgActionPaths'] = [];
267 $setup['wgVariantArticlePath'] = false;
268 $setup['wgUploadNavigationUrl'] = false;
269 $setup['wgCapitalLinks'] = true;
270 $setup['wgNoFollowLinks'] = true;
271 $setup['wgNoFollowDomainExceptions'] = [ 'no-nofollow.org' ];
272 $setup['wgExternalLinkTarget'] = false;
273 $setup['wgExperimentalHtmlIds'] = 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
620 Hooks
::clear( 'InterwikiLoadPrefix' );
625 * Reset the Title-related services that need resetting
628 private function resetTitleServices() {
629 $services = MediaWikiServices
::getInstance();
630 $services->resetServiceForTesting( 'TitleFormatter' );
631 $services->resetServiceForTesting( 'TitleParser' );
632 $services->resetServiceForTesting( '_MediaWikiTitleCodec' );
633 $services->resetServiceForTesting( 'LinkRenderer' );
634 $services->resetServiceForTesting( 'LinkRendererFactory' );
638 * Remove last character if it is a newline
643 public static function chomp( $s ) {
644 if ( substr( $s, -1 ) === "\n" ) {
645 return substr( $s, 0, -1 );
652 * Run a series of tests listed in the given text files.
653 * Each test consists of a brief description, wikitext input,
654 * and the expected HTML output.
656 * Prints status updates on stdout and counts up the total
657 * number and percentage of passed tests.
659 * Handles all setup and teardown.
661 * @param array $filenames Array of strings
662 * @return bool True if passed all tests, false if any tests failed.
664 public function runTestsFromFiles( $filenames ) {
667 $teardownGuard = $this->staticSetup();
668 $teardownGuard = $this->setupDatabase( $teardownGuard );
669 $teardownGuard = $this->setupUploads( $teardownGuard );
671 $this->recorder
->start();
675 foreach ( $filenames as $filename ) {
676 $testFileInfo = TestFileReader
::read( $filename, [
677 'runDisabled' => $this->runDisabled
,
678 'runParsoid' => $this->runParsoid
,
679 'regex' => $this->regex
] );
681 // Don't start the suite if there are no enabled tests in the file
682 if ( !$testFileInfo['tests'] ) {
686 $this->recorder
->startSuite( $filename );
687 $ok = $this->runTests( $testFileInfo ) && $ok;
688 $this->recorder
->endSuite( $filename );
691 $this->recorder
->report();
692 } catch ( DBError
$e ) {
693 $this->recorder
->warning( $e->getMessage() );
695 $this->recorder
->end();
697 ScopedCallback
::consume( $teardownGuard );
703 * Determine whether the current parser has the hooks registered in it
704 * that are required by a file read by TestFileReader.
705 * @param array $requirements
708 public function meetsRequirements( $requirements ) {
709 foreach ( $requirements as $requirement ) {
710 switch ( $requirement['type'] ) {
712 $ok = $this->requireHook( $requirement['name'] );
715 $ok = $this->requireFunctionHook( $requirement['name'] );
717 case 'transparentHook':
718 $ok = $this->requireTransparentHook( $requirement['name'] );
729 * Run the tests from a single file. staticSetup() and setupDatabase()
730 * must have been called already.
732 * @param array $testFileInfo Parsed file info returned by TestFileReader
733 * @return bool True if passed all tests, false if any tests failed.
735 public function runTests( $testFileInfo ) {
738 $this->checkSetupDone( 'staticSetup' );
740 // Don't add articles from the file if there are no enabled tests from the file
741 if ( !$testFileInfo['tests'] ) {
745 // If any requirements are not met, mark all tests from the file as skipped
746 if ( !$this->meetsRequirements( $testFileInfo['requirements'] ) ) {
747 foreach ( $testFileInfo['tests'] as $test ) {
748 $this->recorder
->startTest( $test );
749 $this->recorder
->skipped( $test, 'required extension not enabled' );
755 $this->addArticles( $testFileInfo['articles'] );
758 foreach ( $testFileInfo['tests'] as $test ) {
759 $this->recorder
->startTest( $test );
761 $this->runTest( $test );
762 if ( $result !== false ) {
763 $ok = $ok && $result->isSuccess();
764 $this->recorder
->record( $test, $result );
772 * Get a Parser object
774 * @param string $preprocessor
777 function getParser( $preprocessor = null ) {
778 global $wgParserConf;
780 $class = $wgParserConf['class'];
781 $parser = new $class( [ 'preprocessorClass' => $preprocessor ] +
$wgParserConf );
782 ParserTestParserHook
::setup( $parser );
788 * Run a given wikitext input through a freshly-constructed wiki parser,
789 * and compare the output against the expected results.
790 * Prints status and explanatory messages to stdout.
792 * staticSetup() and setupWikiData() must be called before this function
795 * @param array $test The test parameters:
796 * - test: The test name
797 * - desc: The subtest description
798 * - input: Wikitext to try rendering
799 * - options: Array of test options
800 * - config: Overrides for global variables, one per line
802 * @return ParserTestResult or false if skipped
804 public function runTest( $test ) {
805 wfDebug( __METHOD__
.": running {$test['desc']}" );
806 $opts = $this->parseOptions( $test['options'] );
807 $teardownGuard = $this->perTestSetup( $test );
809 $context = RequestContext
::getMain();
810 $user = $context->getUser();
811 $options = ParserOptions
::newFromContext( $context );
812 $options->setTimestamp( $this->getFakeTimestamp() );
814 if ( isset( $opts['tidy'] ) ) {
815 if ( !$this->tidySupport
->isEnabled() ) {
816 $this->recorder
->skipped( $test, 'tidy extension is not installed' );
819 $options->setTidy( true );
823 if ( isset( $opts['title'] ) ) {
824 $titleText = $opts['title'];
826 $titleText = 'Parser test';
829 $local = isset( $opts['local'] );
830 $preprocessor = isset( $opts['preprocessor'] ) ?
$opts['preprocessor'] : null;
831 $parser = $this->getParser( $preprocessor );
832 $title = Title
::newFromText( $titleText );
834 if ( isset( $opts['pst'] ) ) {
835 $out = $parser->preSaveTransform( $test['input'], $title, $user, $options );
836 $output = $parser->getOutput();
837 } elseif ( isset( $opts['msg'] ) ) {
838 $out = $parser->transformMsg( $test['input'], $options, $title );
839 } elseif ( isset( $opts['section'] ) ) {
840 $section = $opts['section'];
841 $out = $parser->getSection( $test['input'], $section );
842 } elseif ( isset( $opts['replace'] ) ) {
843 $section = $opts['replace'][0];
844 $replace = $opts['replace'][1];
845 $out = $parser->replaceSection( $test['input'], $section, $replace );
846 } elseif ( isset( $opts['comment'] ) ) {
847 $out = Linker
::formatComment( $test['input'], $title, $local );
848 } elseif ( isset( $opts['preload'] ) ) {
849 $out = $parser->getPreloadText( $test['input'], $title, $options );
851 $output = $parser->parse( $test['input'], $title, $options, true, true, 1337 );
852 $out = $output->getText( [
853 'allowTOC' => !isset( $opts['notoc'] ),
854 'unwrap' => !isset( $opts['wrap'] ),
856 if ( isset( $opts['tidy'] ) ) {
857 $out = preg_replace( '/\s+$/', '', $out );
860 if ( isset( $opts['showtitle'] ) ) {
861 if ( $output->getTitleText() ) {
862 $title = $output->getTitleText();
865 $out = "$title\n$out";
868 if ( isset( $opts['showindicators'] ) ) {
870 foreach ( $output->getIndicators() as $id => $content ) {
871 $indicators .= "$id=$content\n";
873 $out = $indicators . $out;
876 if ( isset( $opts['ill'] ) ) {
877 $out = implode( ' ', $output->getLanguageLinks() );
878 } elseif ( isset( $opts['cat'] ) ) {
880 foreach ( $output->getCategories() as $name => $sortkey ) {
884 $out .= "cat=$name sort=$sortkey";
889 if ( isset( $output ) && isset( $opts['showflags'] ) ) {
890 $actualFlags = array_keys( TestingAccessWrapper
::newFromObject( $output )->mFlags
);
891 sort( $actualFlags );
892 $out .= "\nflags=" . join( ', ', $actualFlags );
895 ScopedCallback
::consume( $teardownGuard );
897 $expected = $test['result'];
898 if ( count( $this->normalizationFunctions
) ) {
899 $expected = ParserTestResultNormalizer
::normalize(
900 $test['expected'], $this->normalizationFunctions
);
901 $out = ParserTestResultNormalizer
::normalize( $out, $this->normalizationFunctions
);
904 $testResult = new ParserTestResult( $test, $expected, $out );
909 * Use a regex to find out the value of an option
910 * @param string $key Name of option val to retrieve
911 * @param array $opts Options array to look in
912 * @param mixed $default Default value returned if not found
915 private static function getOptionValue( $key, $opts, $default ) {
916 $key = strtolower( $key );
918 if ( isset( $opts[$key] ) ) {
926 * Given the options string, return an associative array of options.
927 * @todo Move this to TestFileReader
929 * @param string $instring
932 private function parseOptions( $instring ) {
938 // foo=bar,"baz quux"
941 (?<qstr> # Quoted string
943 (?:[^\\\\"] | \\\\.)*
949 [^"{}] | # Not a quoted string or object, or
950 (?&qstr) | # A quoted string, or
951 (?&json) # A json object (recursively)
957 (?&qstr) # Quoted val
965 (?&json) # JSON object
969 $regex = '/' . $defs . '\b
985 $valueregex = '/' . $defs . '(?&value)/x';
987 if ( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER
) ) {
988 foreach ( $matches as $bits ) {
989 $key = strtolower( $bits['k'] );
990 if ( !isset( $bits['v'] ) ) {
993 preg_match_all( $valueregex, $bits['v'], $vmatches );
994 $opts[$key] = array_map( [ $this, 'cleanupOption' ], $vmatches[0] );
995 if ( count( $opts[$key] ) == 1 ) {
996 $opts[$key] = $opts[$key][0];
1004 private function cleanupOption( $opt ) {
1005 if ( substr( $opt, 0, 1 ) == '"' ) {
1006 return stripcslashes( substr( $opt, 1, -1 ) );
1009 if ( substr( $opt, 0, 2 ) == '[[' ) {
1010 return substr( $opt, 2, -2 );
1013 if ( substr( $opt, 0, 1 ) == '{' ) {
1014 return FormatJson
::decode( $opt, true );
1020 * Do any required setup which is dependent on test options.
1022 * @see staticSetup() for more information about setup/teardown
1024 * @param array $test Test info supplied by TestFileReader
1025 * @param callable|null $nextTeardown
1026 * @return ScopedCallback
1028 public function perTestSetup( $test, $nextTeardown = null ) {
1031 $this->checkSetupDone( 'setupDatabase', 'setDatabase' );
1032 $teardown[] = $this->markSetupDone( 'perTestSetup' );
1034 $opts = $this->parseOptions( $test['options'] );
1035 $config = $test['config'];
1037 // Find out values for some special options.
1039 self
::getOptionValue( 'language', $opts, 'en' );
1041 self
::getOptionValue( 'variant', $opts, false );
1043 self
::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
1044 $linkHolderBatchSize =
1045 self
::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
1047 // Default to fallback skin, but allow it to be overridden
1048 $skin = self
::getOptionValue( 'skin', $opts, 'fallback' );
1051 'wgEnableUploads' => self
::getOptionValue( 'wgEnableUploads', $opts, true ),
1052 'wgLanguageCode' => $langCode,
1053 'wgRawHtml' => self
::getOptionValue( 'wgRawHtml', $opts, false ),
1054 'wgNamespacesWithSubpages' => array_fill_keys(
1055 MWNamespace
::getValidNamespaces(), isset( $opts['subpage'] )
1057 'wgMaxTocLevel' => $maxtoclevel,
1058 'wgAllowExternalImages' => self
::getOptionValue( 'wgAllowExternalImages', $opts, true ),
1059 'wgThumbLimits' => [ self
::getOptionValue( 'thumbsize', $opts, 180 ) ],
1060 'wgDefaultLanguageVariant' => $variant,
1061 'wgLinkHolderBatchSize' => $linkHolderBatchSize,
1062 // Set as a JSON object like:
1063 // wgEnableMagicLinks={"ISBN":false, "PMID":false, "RFC":false}
1064 'wgEnableMagicLinks' => self
::getOptionValue( 'wgEnableMagicLinks', $opts, [] )
1065 +
[ 'ISBN' => true, 'PMID' => true, 'RFC' => true ],
1066 // Test with legacy encoding by default until HTML5 is very stable and default
1067 'wgFragmentMode' => [ 'legacy' ],
1071 $configLines = explode( "\n", $config );
1073 foreach ( $configLines as $line ) {
1074 list( $var, $value ) = explode( '=', $line, 2 );
1075 $setup[$var] = eval( "return $value;" );
1080 Hooks
::run( 'ParserTestGlobals', [ &$setup ] );
1082 // Create tidy driver
1083 if ( isset( $opts['tidy'] ) ) {
1084 // Cache a driver instance
1085 if ( $this->tidyDriver
=== null ) {
1086 $this->tidyDriver
= MWTidy
::factory( $this->tidySupport
->getConfig() );
1088 $tidy = $this->tidyDriver
;
1092 MWTidy
::setInstance( $tidy );
1093 $teardown[] = function () {
1094 MWTidy
::destroySingleton();
1097 // Set content language. This invalidates the magic word cache and title services
1098 $lang = Language
::factory( $langCode );
1099 $setup['wgContLang'] = $lang;
1100 $reset = function () {
1101 MagicWord
::clearCache();
1102 $this->resetTitleServices();
1105 $teardown[] = $reset;
1107 // Make a user object with the same language
1109 $user->setOption( 'language', $langCode );
1110 $setup['wgLang'] = $lang;
1112 // We (re)set $wgThumbLimits to a single-element array above.
1113 $user->setOption( 'thumbsize', 0 );
1115 $setup['wgUser'] = $user;
1117 // And put both user and language into the context
1118 $context = RequestContext
::getMain();
1119 $context->setUser( $user );
1120 $context->setLanguage( $lang );
1122 $oldSkin = $context->getSkin();
1123 $skinFactory = MediaWikiServices
::getInstance()->getSkinFactory();
1124 $context->setSkin( $skinFactory->makeSkin( $skin ) );
1125 $context->setOutput( new OutputPage( $context ) );
1126 $setup['wgOut'] = $context->getOutput();
1127 $teardown[] = function () use ( $context, $oldSkin ) {
1128 // Clear language conversion tables
1129 $wrapper = TestingAccessWrapper
::newFromObject(
1130 $context->getLanguage()->getConverter()
1132 $wrapper->reloadTables();
1133 // Reset context to the restored globals
1134 $context->setUser( $GLOBALS['wgUser'] );
1135 $context->setLanguage( $GLOBALS['wgContLang'] );
1136 $context->setSkin( $oldSkin );
1137 $context->setOutput( $GLOBALS['wgOut'] );
1140 $teardown[] = $this->executeSetupSnippets( $setup );
1142 return $this->createTeardownObject( $teardown, $nextTeardown );
1146 * List of temporary tables to create, without prefix.
1147 * Some of these probably aren't necessary.
1150 private function listTables() {
1151 global $wgCommentTableSchemaMigrationStage;
1153 $tables = [ 'user', 'user_properties', 'user_former_groups', 'page', 'page_restrictions',
1154 'protected_titles', 'revision', 'ip_changes', 'text', 'pagelinks', 'imagelinks',
1155 'categorylinks', 'templatelinks', 'externallinks', 'langlinks', 'iwlinks',
1156 'site_stats', 'ipblocks', 'image', 'oldimage',
1157 'recentchanges', 'watchlist', 'interwiki', 'logging', 'log_search',
1158 'querycache', 'objectcache', 'job', 'l10n_cache', 'redirect', 'querycachetwo',
1159 'archive', 'user_groups', 'page_props', 'category'
1162 if ( $wgCommentTableSchemaMigrationStage >= MIGRATION_WRITE_BOTH
) {
1163 // The new tables for comments are in use
1164 $tables[] = 'comment';
1165 $tables[] = 'revision_comment_temp';
1166 $tables[] = 'image_comment_temp';
1169 if ( in_array( $this->db
->getType(), [ 'mysql', 'sqlite', 'oracle' ] ) ) {
1170 array_push( $tables, 'searchindex' );
1173 // Allow extensions to add to the list of tables to duplicate;
1174 // may be necessary if they hook into page save or other code
1175 // which will require them while running tests.
1176 Hooks
::run( 'ParserTestTables', [ &$tables ] );
1181 public function setDatabase( IDatabase
$db ) {
1183 $this->setupDone
['setDatabase'] = true;
1187 * Set up temporary DB tables.
1189 * For best performance, call this once only for all tests. However, it can
1190 * be called at the start of each test if more isolation is desired.
1192 * @todo: This is basically an unrefactored copy of
1193 * MediaWikiTestCase::setupAllTestDBs. They should be factored out somehow.
1195 * Do not call this function from a MediaWikiTestCase subclass, since
1196 * MediaWikiTestCase does its own DB setup. Instead use setDatabase().
1198 * @see staticSetup() for more information about setup/teardown
1200 * @param ScopedCallback|null $nextTeardown The next teardown object
1201 * @return ScopedCallback The teardown object
1203 public function setupDatabase( $nextTeardown = null ) {
1206 $this->db
= wfGetDB( DB_MASTER
);
1207 $dbType = $this->db
->getType();
1209 if ( $dbType == 'oracle' ) {
1210 $suspiciousPrefixes = [ 'pt_', MediaWikiTestCase
::ORA_DB_PREFIX
];
1212 $suspiciousPrefixes = [ 'parsertest_', MediaWikiTestCase
::DB_PREFIX
];
1214 if ( in_array( $wgDBprefix, $suspiciousPrefixes ) ) {
1215 throw new MWException( "\$wgDBprefix=$wgDBprefix suggests DB setup is already done" );
1220 $teardown[] = $this->markSetupDone( 'setupDatabase' );
1222 # CREATE TEMPORARY TABLE breaks if there is more than one server
1223 if ( wfGetLB()->getServerCount() != 1 ) {
1224 $this->useTemporaryTables
= false;
1227 $temporary = $this->useTemporaryTables ||
$dbType == 'postgres';
1228 $prefix = $dbType != 'oracle' ?
'parsertest_' : 'pt_';
1230 $this->dbClone
= new CloneDatabase( $this->db
, $this->listTables(), $prefix );
1231 $this->dbClone
->useTemporaryTables( $temporary );
1232 $this->dbClone
->cloneTableStructure();
1234 if ( $dbType == 'oracle' ) {
1235 $this->db
->query( 'BEGIN FILL_WIKI_INFO; END;' );
1236 # Insert 0 user to prevent FK violations
1239 $this->db
->insert( 'user', [
1241 'user_name' => 'Anonymous' ] );
1244 $teardown[] = function () {
1245 $this->teardownDatabase();
1248 // Wipe some DB query result caches on setup and teardown
1249 $reset = function () {
1250 LinkCache
::singleton()->clear();
1252 // Clear the message cache
1253 MessageCache
::singleton()->clear();
1256 $teardown[] = $reset;
1257 return $this->createTeardownObject( $teardown, $nextTeardown );
1261 * Add data about uploads to the new test DB, and set up the upload
1262 * directory. This should be called after either setDatabase() or
1265 * @param ScopedCallback|null $nextTeardown The next teardown object
1266 * @return ScopedCallback The teardown object
1268 public function setupUploads( $nextTeardown = null ) {
1271 $this->checkSetupDone( 'setupDatabase', 'setDatabase' );
1272 $teardown[] = $this->markSetupDone( 'setupUploads' );
1274 // Create the files in the upload directory (or pretend to create them
1275 // in a MockFileBackend). Append teardown callback.
1276 $teardown[] = $this->setupUploadBackend();
1279 $user = User
::createNew( 'WikiSysop' );
1281 // Register the uploads in the database
1283 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Foobar.jpg' ) );
1284 # note that the size/width/height/bits/etc of the file
1285 # are actually set by inspecting the file itself; the arguments
1286 # to recordUpload2 have no effect. That said, we try to make things
1287 # match up so it is less confusing to readers of the code & tests.
1288 $image->recordUpload2( '', 'Upload of some lame file', 'Some lame file', [
1293 'media_type' => MEDIATYPE_BITMAP
,
1294 'mime' => 'image/jpeg',
1295 'metadata' => serialize( [] ),
1296 'sha1' => Wikimedia\base_convert
( '1', 16, 36, 31 ),
1297 'fileExists' => true
1298 ], $this->db
->timestamp( '20010115123500' ), $user );
1300 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Thumb.png' ) );
1301 # again, note that size/width/height below are ignored; see above.
1302 $image->recordUpload2( '', 'Upload of some lame thumbnail', 'Some lame thumbnail', [
1307 'media_type' => MEDIATYPE_BITMAP
,
1308 'mime' => 'image/png',
1309 'metadata' => serialize( [] ),
1310 'sha1' => Wikimedia\base_convert
( '2', 16, 36, 31 ),
1311 'fileExists' => true
1312 ], $this->db
->timestamp( '20130225203040' ), $user );
1314 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Foobar.svg' ) );
1315 $image->recordUpload2( '', 'Upload of some lame SVG', 'Some lame SVG', [
1320 'media_type' => MEDIATYPE_DRAWING
,
1321 'mime' => 'image/svg+xml',
1322 'metadata' => serialize( [] ),
1323 'sha1' => Wikimedia\base_convert
( '', 16, 36, 31 ),
1324 'fileExists' => true
1325 ], $this->db
->timestamp( '20010115123500' ), $user );
1327 # This image will be blacklisted in [[MediaWiki:Bad image list]]
1328 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Bad.jpg' ) );
1329 $image->recordUpload2( '', 'zomgnotcensored', 'Borderline image', [
1334 'media_type' => MEDIATYPE_BITMAP
,
1335 'mime' => 'image/jpeg',
1336 'metadata' => serialize( [] ),
1337 'sha1' => Wikimedia\base_convert
( '3', 16, 36, 31 ),
1338 'fileExists' => true
1339 ], $this->db
->timestamp( '20010115123500' ), $user );
1341 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Video.ogv' ) );
1342 $image->recordUpload2( '', 'A pretty movie', 'Will it play', [
1347 'media_type' => MEDIATYPE_VIDEO
,
1348 'mime' => 'application/ogg',
1349 'metadata' => serialize( [] ),
1350 'sha1' => Wikimedia\base_convert
( '', 16, 36, 31 ),
1351 'fileExists' => true
1352 ], $this->db
->timestamp( '20010115123500' ), $user );
1354 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'Audio.oga' ) );
1355 $image->recordUpload2( '', 'An awesome hitsong', 'Will it play', [
1360 'media_type' => MEDIATYPE_AUDIO
,
1361 'mime' => 'application/ogg',
1362 'metadata' => serialize( [] ),
1363 'sha1' => Wikimedia\base_convert
( '', 16, 36, 31 ),
1364 'fileExists' => true
1365 ], $this->db
->timestamp( '20010115123500' ), $user );
1368 $image = wfLocalFile( Title
::makeTitle( NS_FILE
, 'LoremIpsum.djvu' ) );
1369 $image->recordUpload2( '', 'Upload a DjVu', 'A DjVu', [
1374 'media_type' => MEDIATYPE_BITMAP
,
1375 'mime' => 'image/vnd.djvu',
1376 'metadata' => '<?xml version="1.0" ?>
1377 <!DOCTYPE DjVuXML PUBLIC "-//W3C//DTD DjVuXML 1.1//EN" "pubtext/DjVuXML-s.dtd">
1380 <BODY><OBJECT height="3508" width="2480">
1381 <PARAM name="DPI" value="300" />
1382 <PARAM name="GAMMA" value="2.2" />
1384 <OBJECT height="3508" width="2480">
1385 <PARAM name="DPI" value="300" />
1386 <PARAM name="GAMMA" value="2.2" />
1388 <OBJECT height="3508" width="2480">
1389 <PARAM name="DPI" value="300" />
1390 <PARAM name="GAMMA" value="2.2" />
1392 <OBJECT height="3508" width="2480">
1393 <PARAM name="DPI" value="300" />
1394 <PARAM name="GAMMA" value="2.2" />
1396 <OBJECT height="3508" width="2480">
1397 <PARAM name="DPI" value="300" />
1398 <PARAM name="GAMMA" value="2.2" />
1402 'sha1' => Wikimedia\base_convert
( '', 16, 36, 31 ),
1403 'fileExists' => true
1404 ], $this->db
->timestamp( '20010115123600' ), $user );
1406 return $this->createTeardownObject( $teardown, $nextTeardown );
1410 * Helper for database teardown, called from the teardown closure. Destroy
1411 * the database clone and fix up some things that CloneDatabase doesn't fix.
1413 * @todo Move most things here to CloneDatabase
1415 private function teardownDatabase() {
1416 $this->checkSetupDone( 'setupDatabase' );
1418 $this->dbClone
->destroy();
1419 $this->databaseSetupDone
= false;
1421 if ( $this->useTemporaryTables
) {
1422 if ( $this->db
->getType() == 'sqlite' ) {
1423 # Under SQLite the searchindex table is virtual and need
1424 # to be explicitly destroyed. See T31912
1425 # See also MediaWikiTestCase::destroyDB()
1426 wfDebug( __METHOD__
. " explicitly destroying sqlite virtual table parsertest_searchindex\n" );
1427 $this->db
->query( "DROP TABLE `parsertest_searchindex`" );
1429 # Don't need to do anything
1433 $tables = $this->listTables();
1435 foreach ( $tables as $table ) {
1436 if ( $this->db
->getType() == 'oracle' ) {
1437 $this->db
->query( "DROP TABLE pt_$table DROP CONSTRAINTS" );
1439 $this->db
->query( "DROP TABLE `parsertest_$table`" );
1443 if ( $this->db
->getType() == 'oracle' ) {
1444 $this->db
->query( 'BEGIN FILL_WIKI_INFO; END;' );
1449 * Upload test files to the backend created by createRepoGroup().
1451 * @return callable The teardown callback
1453 private function setupUploadBackend() {
1456 $repo = RepoGroup
::singleton()->getLocalRepo();
1457 $base = $repo->getZonePath( 'public' );
1458 $backend = $repo->getBackend();
1459 $backend->prepare( [ 'dir' => "$base/3/3a" ] );
1461 'src' => "$IP/tests/phpunit/data/parser/headbg.jpg",
1462 'dst' => "$base/3/3a/Foobar.jpg"
1464 $backend->prepare( [ 'dir' => "$base/e/ea" ] );
1466 'src' => "$IP/tests/phpunit/data/parser/wiki.png",
1467 'dst' => "$base/e/ea/Thumb.png"
1469 $backend->prepare( [ 'dir' => "$base/0/09" ] );
1471 'src' => "$IP/tests/phpunit/data/parser/headbg.jpg",
1472 'dst' => "$base/0/09/Bad.jpg"
1474 $backend->prepare( [ 'dir' => "$base/5/5f" ] );
1476 'src' => "$IP/tests/phpunit/data/parser/LoremIpsum.djvu",
1477 'dst' => "$base/5/5f/LoremIpsum.djvu"
1480 // No helpful SVG file to copy, so make one ourselves
1481 $data = '<?xml version="1.0" encoding="utf-8"?>' .
1482 '<svg xmlns="http://www.w3.org/2000/svg"' .
1483 ' version="1.1" width="240" height="180"/>';
1485 $backend->prepare( [ 'dir' => "$base/f/ff" ] );
1486 $backend->quickCreate( [
1487 'content' => $data, 'dst' => "$base/f/ff/Foobar.svg"
1490 return function () use ( $backend ) {
1491 if ( $backend instanceof MockFileBackend
) {
1492 // In memory backend, so dont bother cleaning them up.
1495 $this->teardownUploadBackend();
1500 * Remove the dummy uploads directory
1502 private function teardownUploadBackend() {
1503 if ( $this->keepUploads
) {
1507 $repo = RepoGroup
::singleton()->getLocalRepo();
1508 $public = $repo->getZonePath( 'public' );
1512 "$public/3/3a/Foobar.jpg",
1513 "$public/e/ea/Thumb.png",
1514 "$public/0/09/Bad.jpg",
1515 "$public/5/5f/LoremIpsum.djvu",
1516 "$public/f/ff/Foobar.svg",
1517 "$public/0/00/Video.ogv",
1518 "$public/4/41/Audio.oga",
1524 * Delete the specified files and their parent directories
1525 * @param array $files File backend URIs mwstore://...
1527 private function deleteFiles( $files ) {
1529 $backend = RepoGroup
::singleton()->getLocalRepo()->getBackend();
1530 foreach ( $files as $file ) {
1531 $backend->delete( [ 'src' => $file ], [ 'force' => 1 ] );
1534 // Delete the parent directories
1535 foreach ( $files as $file ) {
1536 $tmp = FileBackend
::parentStoragePath( $file );
1538 if ( !$backend->clean( [ 'dir' => $tmp ] )->isOK() ) {
1541 $tmp = FileBackend
::parentStoragePath( $tmp );
1547 * Add articles to the test DB.
1549 * @param array $articles Article info array from TestFileReader
1551 public function addArticles( $articles ) {
1556 // Be sure ParserTestRunner::addArticle has correct language set,
1557 // so that system messages get into the right language cache
1558 if ( $wgContLang->getCode() !== 'en' ) {
1559 $setup['wgLanguageCode'] = 'en';
1560 $setup['wgContLang'] = Language
::factory( 'en' );
1563 // Add special namespaces, in case that hasn't been done by staticSetup() yet
1564 $this->appendNamespaceSetup( $setup, $teardown );
1566 // wgCapitalLinks obviously needs initialisation
1567 $setup['wgCapitalLinks'] = true;
1569 $teardown[] = $this->executeSetupSnippets( $setup );
1571 foreach ( $articles as $info ) {
1572 $this->addArticle( $info['name'], $info['text'], $info['file'], $info['line'] );
1575 // Wipe WANObjectCache process cache, which is invalidated by article insertion
1577 ObjectCache
::getMainWANInstance()->clearProcessCache();
1579 $this->executeSetupSnippets( $teardown );
1583 * Insert a temporary test article
1584 * @param string $name The title, including any prefix
1585 * @param string $text The article text
1586 * @param string $file The input file name
1587 * @param int|string $line The input line number, for reporting errors
1589 * @throws MWException
1591 private function addArticle( $name, $text, $file, $line ) {
1592 $text = self
::chomp( $text );
1593 $name = self
::chomp( $name );
1595 $title = Title
::newFromText( $name );
1596 wfDebug( __METHOD__
. ": adding $name" );
1598 if ( is_null( $title ) ) {
1599 throw new MWException( "invalid title '$name' at $file:$line\n" );
1602 $newContent = ContentHandler
::makeContent( $text, $title );
1604 $page = WikiPage
::factory( $title );
1605 $page->loadPageData( 'fromdbmaster' );
1607 if ( $page->exists() ) {
1608 $content = $page->getContent( Revision
::RAW
);
1609 // Only reject the title, if the content/content model is different.
1610 // This makes it easier to create Template:(( or Template:)) in different extensions
1611 if ( $newContent->equals( $content ) ) {
1614 throw new MWException(
1615 "duplicate article '$name' with different content at $file:$line\n"
1619 // Use mock parser, to make debugging of actual parser tests simpler.
1620 // But initialise the MessageCache clone first, don't let MessageCache
1621 // get a reference to the mock object.
1622 MessageCache
::singleton()->getParser();
1623 $restore = $this->executeSetupSnippets( [ 'wgParser' => new ParserTestMockParser
] );
1625 $status = $page->doEditContent(
1628 EDIT_NEW | EDIT_INTERNAL
1634 if ( !$status->isOK() ) {
1635 throw new MWException( $status->getWikiText( false, false, 'en' ) );
1638 // The RepoGroup cache is invalidated by the creation of file redirects
1639 if ( $title->inNamespace( NS_FILE
) ) {
1640 RepoGroup
::singleton()->clearCache( $title );
1645 * Check if a hook is installed
1647 * @param string $name
1648 * @return bool True if tag hook is present
1650 public function requireHook( $name ) {
1653 $wgParser->firstCallInit(); // make sure hooks are loaded.
1654 if ( isset( $wgParser->mTagHooks
[$name] ) ) {
1657 $this->recorder
->warning( " This test suite requires the '$name' hook " .
1658 "extension, skipping." );
1664 * Check if a function hook is installed
1666 * @param string $name
1667 * @return bool True if function hook is present
1669 public function requireFunctionHook( $name ) {
1672 $wgParser->firstCallInit(); // make sure hooks are loaded.
1674 if ( isset( $wgParser->mFunctionHooks
[$name] ) ) {
1677 $this->recorder
->warning( " This test suite requires the '$name' function " .
1678 "hook extension, skipping." );
1684 * Check if a transparent tag hook is installed
1686 * @param string $name
1687 * @return bool True if function hook is present
1689 public function requireTransparentHook( $name ) {
1692 $wgParser->firstCallInit(); // make sure hooks are loaded.
1694 if ( isset( $wgParser->mTransparentTagHooks
[$name] ) ) {
1697 $this->recorder
->warning( " This test suite requires the '$name' transparent " .
1698 "hook extension, skipping.\n" );
1704 * Fake constant timestamp to make sure time-related parser
1705 * functions give a persistent value.
1707 * - Parser::getVariableValue (via ParserGetVariableValueTs hook)
1708 * - Parser::preSaveTransform (via ParserOptions)
1710 private function getFakeTimestamp() {
1711 // parsed as '1970-01-01T00:02:03Z'