31use Wikimedia\ScopedCallback;
32use Wikimedia\TestingAccessWrapper;
47 'extraParserTests.txt',
59 'staticSetup' =>
false,
60 'perTestSetup' =>
false,
61 'setupDatabase' =>
false,
62 'setDatabase' =>
false,
63 'setupUploads' =>
false,
151 foreach (
$options[
'norm'] as $func ) {
152 if ( in_array( $func, [
'removeTbody',
'trimWhitespace' ] ) ) {
153 $this->normalizationFunctions[] = $func;
156 "Warning: unknown normalization option \"$func\"\n" );
168 $this->keepUploads = !empty(
$options[
'keep-uploads'] );
170 $this->fileBackendName =
$options[
'file-backend'] ??
false;
172 $this->runDisabled = !empty(
$options[
'run-disabled'] );
173 $this->runParsoid = !empty(
$options[
'run-parsoid'] );
175 $this->disableSaveParse = !empty(
$options[
'disable-save-parse'] );
178 if ( !$this->tidySupport->isEnabled() ) {
179 $this->recorder->warning(
180 "Warning: tidy is not installed, skipping some tests\n" );
183 if ( isset(
$options[
'upload-dir'] ) ) {
184 $this->uploadDir =
$options[
'upload-dir'];
197 $files = array_map(
function ( $item ) {
198 return __DIR__ .
"/$item";
206 foreach ( $registry->getAllThings() as $info ) {
207 $dir = dirname( $info[
'path'] ) .
'/tests/parser';
208 if ( !file_exists( $dir ) ) {
212 $dirIterator =
new RecursiveIteratorIterator(
213 new RecursiveDirectoryIterator( $dir )
215 foreach ( $dirIterator as $fileInfo ) {
217 if ( substr( $fileInfo->getFilename(), -4 ) ===
'.txt' ) {
218 $name = $info[
'name'] . $counter;
219 while ( isset( $files[$name] ) ) {
220 $name = $info[
'name'] .
'_' . $counter++;
222 $files[
$name] = $fileInfo->getPathname();
227 return array_unique( $files );
283 $setup[
'wgSitename'] =
'MediaWiki';
284 $setup[
'wgServer'] =
'http://example.org';
285 $setup[
'wgServerName'] =
'example.org';
286 $setup[
'wgScriptPath'] =
'';
287 $setup[
'wgScript'] =
'/index.php';
288 $setup[
'wgResourceBasePath'] =
'';
289 $setup[
'wgStylePath'] =
'/skins';
290 $setup[
'wgExtensionAssetsPath'] =
'/extensions';
291 $setup[
'wgArticlePath'] =
'/wiki/$1';
292 $setup[
'wgActionPaths'] = [];
293 $setup[
'wgVariantArticlePath'] =
false;
294 $setup[
'wgUploadNavigationUrl'] =
false;
295 $setup[
'wgCapitalLinks'] =
true;
296 $setup[
'wgNoFollowLinks'] =
true;
297 $setup[
'wgNoFollowDomainExceptions'] = [
'no-nofollow.org' ];
298 $setup[
'wgExternalLinkTarget'] =
false;
299 $setup[
'wgLocaltimezone'] =
'UTC';
300 $setup[
'wgHtml5'] =
true;
301 $setup[
'wgDisableLangConversion'] =
false;
302 $setup[
'wgDisableTitleConversion'] =
false;
306 $setup[
'wgExtraInterlanguageLinkPrefixes'] = [
'mul' ];
311 $teardown[] =
function () {
316 $setup[
'wgLockManagers'] = [ [
317 'name' =>
'fsLockManager',
318 'class' => NullLockManager::class,
320 'name' =>
'nullLockManager',
321 'class' => NullLockManager::class,
323 $reset =
function () {
327 $teardown[] = $reset;
330 $setup[
'wgDefaultExternalStore'] =
false;
333 $setup[
'wgAdaptiveMessageCache'] =
true;
336 $setup[
'wgUseDatabaseMessages'] =
true;
337 $reset =
function () {
338 MessageCache::destroyInstance();
341 $teardown[] = $reset;
344 $setup[
'wgSVGConverter'] =
'null';
345 $setup[
'wgSVGConverters'] = [
'null' =>
'echo "1">$output' ];
348 Hooks::register(
'ParserGetVariableValueTs',
function ( &
$parser, &$ts ) {
352 $teardown[] =
function () {
353 Hooks::clear(
'ParserGetVariableValueTs' );
363 $setup[
'wgLocalInterwikis'] = [
'local',
'mi' ];
364 $reset =
function () {
368 $teardown[] = $reset;
371 MediaWikiServices::getInstance()->disableService(
'MediaHandlerFactory' );
372 MediaWikiServices::getInstance()->redefineService(
373 'MediaHandlerFactory',
375 $handlers =
$services->getMainConfig()->
get(
'ParserTestMediaHandlers' );
379 $teardown[] =
function () {
380 MediaWikiServices::getInstance()->resetServiceForTesting(
'MediaHandlerFactory' );
388 if ( isset( ObjectCache::$instances[
CACHE_DB] ) ) {
389 $savedCache = ObjectCache::$instances[
CACHE_DB];
391 $teardown[] =
function () use ( $savedCache ) {
392 ObjectCache::$instances[
CACHE_DB] = $savedCache;
405 $setup[
'wgExtraNamespaces'] = [
406 100 =>
'MemoryAlpha',
407 101 =>
'MemoryAlpha_talk'
411 $reset =
function () {
412 MWNamespace::clearCaches();
413 MediaWikiServices::getInstance()->getContentLanguage()->resetNamespaces();
416 $teardown[] = $reset;
424 if ( $this->uploadDir ) {
425 if ( $this->fileBackendName ) {
426 throw new MWException(
'You cannot specify both use-filebackend and upload-dir' );
429 'name' =>
'local-backend',
431 'basePath' => $this->uploadDir,
434 } elseif ( $this->fileBackendName ) {
439 if ( $conf[
'name'] === $name ) {
443 if ( $useConfig ===
false ) {
444 throw new MWException(
"Unable to find file backend \"$name\"" );
446 $useConfig[
'name'] =
'local-backend';
447 unset( $useConfig[
'lockManager'] );
448 unset( $useConfig[
'fileJournal'] );
449 $class = $useConfig[
'class'];
450 $backend =
new $class( $useConfig );
452 # Replace with a mock. We do not care about generating real
453 # files on the filesystem, just need to expose the file
456 'name' =>
'local-backend',
463 'class' => MockLocalRepo::class,
465 'url' =>
'http://example.com/images',
467 'transformVia404' =>
false,
468 'backend' => $backend
489 foreach ( $setup as $name =>
$value ) {
490 if ( is_int( $name ) ) {
497 return function () use ( $saved ) {
515 return new ScopedCallback(
function () use ( $teardown, $nextTeardown ) {
517 $teardown = array_reverse( $teardown );
520 if ( $nextTeardown ) {
521 ScopedCallback::consume( $nextTeardown );
534 if ( $this->setupDone[$funcName] ) {
535 throw new MWException(
"$funcName is already done" );
537 $this->setupDone[$funcName] =
true;
538 return function () use ( $funcName ) {
539 $this->setupDone[$funcName] =
false;
550 if ( !$this->setupDone[$funcName]
551 && ( $funcName ===
null || !$this->setupDone[$funcName2] )
553 throw new MWException(
"$funcName must be called before calling " .
565 return $this->setupDone[$funcName] ??
false;
580 # Hack: insert a few Wikipedia in-project interwiki prefixes,
581 # for testing inter-language links
582 Hooks::register(
'InterwikiLoadPrefix',
function ( $prefix, &$iwData ) {
583 static $testInterwikis = [
585 'iw_url' =>
'http://doesnt.matter.org/$1',
590 'iw_url' =>
'http://en.wikipedia.org/wiki/$1',
595 'iw_url' =>
'http://www.usemod.com/cgi-bin/mb.pl?$1',
600 'iw_url' =>
'http://www.memory-alpha.org/en/index.php/$1',
605 'iw_url' =>
'http://zh.wikipedia.org/wiki/$1',
610 'iw_url' =>
'http://es.wikipedia.org/wiki/$1',
615 'iw_url' =>
'http://fr.wikipedia.org/wiki/$1',
620 'iw_url' =>
'http://ru.wikipedia.org/wiki/$1',
625 'iw_url' =>
'http://mi.wikipedia.org/wiki/$1',
630 'iw_url' =>
'http://wikisource.org/wiki/$1',
635 if ( array_key_exists( $prefix, $testInterwikis ) ) {
636 $iwData = $testInterwikis[$prefix];
644 MediaWikiServices::getInstance()->resetServiceForTesting(
'InterwikiLookup' );
648 Hooks::clear(
'InterwikiLoadPrefix' );
649 MediaWikiServices::getInstance()->resetServiceForTesting(
'InterwikiLookup' );
658 $services = MediaWikiServices::getInstance();
659 $services->resetServiceForTesting(
'TitleFormatter' );
660 $services->resetServiceForTesting(
'TitleParser' );
661 $services->resetServiceForTesting(
'_MediaWikiTitleCodec' );
662 $services->resetServiceForTesting(
'LinkRenderer' );
663 $services->resetServiceForTesting(
'LinkRendererFactory' );
672 if ( substr(
$s, -1 ) ===
"\n" ) {
673 return substr(
$s, 0, -1 );
699 $this->recorder->start();
703 foreach ( $filenames as $filename ) {
705 'runDisabled' => $this->runDisabled,
706 'runParsoid' => $this->runParsoid,
707 'regex' => $this->regex ] );
710 if ( !$testFileInfo[
'tests'] ) {
714 $this->recorder->startSuite( $filename );
715 $ok = $this->
runTests( $testFileInfo ) && $ok;
716 $this->recorder->endSuite( $filename );
719 $this->recorder->report();
720 }
catch ( DBError
$e ) {
721 $this->recorder->warning(
$e->getMessage() );
723 $this->recorder->end();
725 ScopedCallback::consume( $teardownGuard );
737 foreach ( $requirements as $requirement ) {
738 switch ( $requirement[
'type'] ) {
745 case 'transparentHook':
769 if ( !$testFileInfo[
'tests'] ) {
775 foreach ( $testFileInfo[
'tests'] as $test ) {
776 $this->recorder->startTest( $test );
777 $this->recorder->skipped( $test,
'required extension not enabled' );
786 foreach ( $testFileInfo[
'tests'] as $test ) {
787 $this->recorder->startTest( $test );
790 if ( $result !==
false ) {
791 $ok = $ok && $result->isSuccess();
792 $this->recorder->record( $test, $result );
833 wfDebug( __METHOD__ .
": running {$test['desc']}" );
837 $context = RequestContext::getMain();
842 if ( isset( $opts[
'tidy'] ) ) {
843 if ( !$this->tidySupport->isEnabled() ) {
844 $this->recorder->skipped( $test,
'tidy extension is not installed' );
851 if ( isset( $opts[
'title'] ) ) {
852 $titleText = $opts[
'title'];
854 $titleText =
'Parser test';
857 if ( isset( $opts[
'maxincludesize'] ) ) {
858 $options->setMaxIncludeSize( $opts[
'maxincludesize'] );
860 if ( isset( $opts[
'maxtemplatedepth'] ) ) {
861 $options->setMaxTemplateDepth( $opts[
'maxtemplatedepth'] );
864 $local = isset( $opts[
'local'] );
865 $preprocessor = $opts[
'preprocessor'] ??
null;
867 $title = Title::newFromText( $titleText );
869 if ( isset( $opts[
'styletag'] ) ) {
873 $marker = Parser::MARKER_PREFIX .
'-style-' . md5(
$content ) . Parser::MARKER_SUFFIX;
875 return Html::inlineStyle( $marker,
'all', $attributes );
878 return Html::element(
'link', $attributes );
882 if ( isset( $opts[
'pst'] ) ) {
885 } elseif ( isset( $opts[
'msg'] ) ) {
887 } elseif ( isset( $opts[
'section'] ) ) {
890 } elseif ( isset( $opts[
'replace'] ) ) {
892 $replace = $opts[
'replace'][1];
894 } elseif ( isset( $opts[
'comment'] ) ) {
896 } elseif ( isset( $opts[
'preload'] ) ) {
901 'allowTOC' => !isset( $opts[
'notoc'] ),
902 'unwrap' => !isset( $opts[
'wrap'] ),
904 if ( isset( $opts[
'tidy'] ) ) {
905 $out = preg_replace(
'/\s+$/',
'',
$out );
908 if ( isset( $opts[
'showtitle'] ) ) {
909 if (
$output->getTitleText() ) {
910 $title =
$output->getTitleText();
913 $out =
"$title\n$out";
916 if ( isset( $opts[
'showindicators'] ) ) {
919 $indicators .=
"$id=$content\n";
924 if ( isset( $opts[
'ill'] ) ) {
925 $out = implode(
' ',
$output->getLanguageLinks() );
926 } elseif ( isset( $opts[
'cat'] ) ) {
928 foreach (
$output->getCategories() as $name => $sortkey ) {
932 $out .=
"cat=$name sort=$sortkey";
937 if ( isset(
$output ) && isset( $opts[
'showflags'] ) ) {
938 $actualFlags = array_keys( TestingAccessWrapper::newFromObject(
$output )->mFlags );
939 sort( $actualFlags );
940 $out .=
"\nflags=" . implode(
', ', $actualFlags );
943 ScopedCallback::consume( $teardownGuard );
945 $expected = $test[
'result'];
946 if ( count( $this->normalizationFunctions ) ) {
948 $test[
'expected'], $this->normalizationFunctions );
964 $key = strtolower( $key );
966 if ( isset( $opts[$key] ) ) {
989 (?<qstr> # Quoted string
991 (?:[^\\\\"] | \\\\.)*
997 [^"{}] | # Not a quoted string or object, or
998 (?&qstr) | # A quoted string, or
999 (?&json) # A json object (recursively)
1005 (?&qstr) # Quoted val
1013 (?&json) # JSON object
1017 $regex =
'/' . $defs .
'\b
1033 $valueregex =
'/' . $defs .
'(?&value)/x';
1035 if ( preg_match_all(
$regex, $instring,
$matches, PREG_SET_ORDER ) ) {
1037 $key = strtolower( $bits[
'k'] );
1038 if ( !isset( $bits[
'v'] ) ) {
1041 preg_match_all( $valueregex, $bits[
'v'], $vmatches );
1042 $opts[$key] = array_map( [ $this,
'cleanupOption' ], $vmatches[0] );
1043 if ( count( $opts[$key] ) == 1 ) {
1044 $opts[$key] = $opts[$key][0];
1053 if ( substr(
$opt, 0, 1 ) ==
'"' ) {
1054 return stripcslashes( substr(
$opt, 1, -1 ) );
1057 if ( substr(
$opt, 0, 2 ) ==
'[[' ) {
1058 return substr(
$opt, 2, -2 );
1061 if ( substr(
$opt, 0, 1 ) ==
'{' ) {
1062 return FormatJson::decode(
$opt,
true );
1083 $config = $test[
'config'];
1092 $linkHolderBatchSize =
1100 'wgLanguageCode' => $langCode,
1102 'wgNamespacesWithSubpages' => array_fill_keys(
1103 MWNamespace::getValidNamespaces(), isset( $opts[
'subpage'] )
1105 'wgMaxTocLevel' => $maxtoclevel,
1108 'wgDefaultLanguageVariant' => $variant,
1109 'wgLinkHolderBatchSize' => $linkHolderBatchSize,
1113 + [
'ISBN' =>
true,
'PMID' =>
true,
'RFC' =>
true ],
1115 'wgFragmentMode' => [
'legacy' ],
1119 if ( $nonIncludable !==
false ) {
1120 $setup[
'wgNonincludableNamespaces'] = [ $nonIncludable ];
1124 $configLines = explode(
"\n", $config );
1126 foreach ( $configLines as
$line ) {
1128 $setup[$var] = eval(
"return $value;" );
1133 Hooks::run(
'ParserTestGlobals', [ &$setup ] );
1136 if ( isset( $opts[
'tidy'] ) ) {
1138 if ( $this->tidyDriver ===
null ) {
1139 $this->tidyDriver =
MWTidy::factory( $this->tidySupport->getConfig() );
1146 $teardown[] =
function () {
1151 $lang = Language::factory( $langCode );
1152 $lang->resetNamespaces();
1153 $setup[
'wgContLang'] =
$lang;
1154 $setup[] =
function () use (
$lang ) {
1155 MediaWikiServices::getInstance()->disableService(
'ContentLanguage' );
1156 MediaWikiServices::getInstance()->redefineService(
1158 function () use (
$lang ) {
1163 $teardown[] =
function () {
1164 MediaWikiServices::getInstance()->resetServiceForTesting(
'ContentLanguage' );
1166 $reset =
function () {
1167 MediaWikiServices::getInstance()->resetServiceForTesting(
'MagicWordFactory' );
1171 $teardown[] = $reset;
1175 $user->
setOption(
'language', $langCode );
1176 $setup[
'wgLang'] =
$lang;
1179 $user->setOption(
'thumbsize', 0 );
1181 $setup[
'wgUser'] =
$user;
1184 $context = RequestContext::getMain();
1189 $skinFactory = MediaWikiServices::getInstance()->getSkinFactory();
1190 $context->setSkin( $skinFactory->makeSkin( $skin ) );
1192 $setup[
'wgOut'] =
$context->getOutput();
1193 $teardown[] =
function () use (
$context, $oldSkin ) {
1195 $wrapper = TestingAccessWrapper::newFromObject(
1196 $context->getLanguage()->getConverter()
1198 $wrapper->reloadTables();
1219 $tables = [
'user',
'user_properties',
'user_former_groups',
'page',
'page_restrictions',
1220 'protected_titles',
'revision',
'ip_changes',
'text',
'pagelinks',
'imagelinks',
1221 'categorylinks',
'templatelinks',
'externallinks',
'langlinks',
'iwlinks',
1222 'site_stats',
'ipblocks',
'image',
'oldimage',
1223 'recentchanges',
'watchlist',
'interwiki',
'logging',
'log_search',
1224 'querycache',
'objectcache',
'job',
'l10n_cache',
'redirect',
'querycachetwo',
1225 'archive',
'user_groups',
'page_props',
'category',
1226 'slots',
'content',
'slot_roles',
'content_models',
1232 $tables[] =
'revision_comment_temp';
1238 $tables[] =
'revision_actor_temp';
1241 if ( in_array( $this->db->getType(), [
'mysql',
'sqlite',
'oracle' ] ) ) {
1242 array_push(
$tables,
'searchindex' );
1248 Hooks::run(
'ParserTestTables', [ &
$tables ] );
1255 $this->setupDone[
'setDatabase'] =
true;
1279 $dbType = $this->db->getType();
1281 if ( $dbType ==
'oracle' ) {
1282 $suspiciousPrefixes = [
'pt_', MediaWikiTestCase::ORA_DB_PREFIX ];
1284 $suspiciousPrefixes = [
'parsertest_', MediaWikiTestCase::DB_PREFIX ];
1286 if ( in_array(
$wgDBprefix, $suspiciousPrefixes ) ) {
1287 throw new MWException(
"\$wgDBprefix=$wgDBprefix suggests DB setup is already done" );
1294 # CREATE TEMPORARY TABLE breaks if there is more than one server
1295 if ( MediaWikiServices::getInstance()->getDBLoadBalancer()->getServerCount() != 1 ) {
1296 $this->useTemporaryTables =
false;
1299 $temporary = $this->useTemporaryTables || $dbType ==
'postgres';
1300 $prefix = $dbType !=
'oracle' ?
'parsertest_' :
'pt_';
1303 $this->dbClone->useTemporaryTables( $temporary );
1304 $this->dbClone->cloneTableStructure();
1307 if ( $dbType ==
'oracle' ) {
1308 $this->db->query(
'BEGIN FILL_WIKI_INFO; END;' );
1309 # Insert 0 user to prevent FK violations
1312 $this->db->insert(
'user', [
1314 'user_name' =>
'Anonymous' ] );
1317 $teardown[] =
function () {
1322 $reset =
function () {
1323 MediaWikiServices::getInstance()->getLinkCache()->clear();
1326 MessageCache::singleton()->clear();
1329 $teardown[] = $reset;
1357 # note that the size/width/height/bits/etc of the file
1358 # are actually set by inspecting the file itself; the arguments
1359 # to recordUpload2 have no effect. That said, we try to make things
1360 # match up so it is less confusing to readers of the code & tests.
1361 $image->recordUpload2(
'',
'Upload of some lame file',
'Some lame file', [
1367 'mime' =>
'image/jpeg',
1369 'sha1' =>
Wikimedia\base_convert(
'1', 16, 36, 31 ),
1370 'fileExists' =>
true
1371 ], $this->db->timestamp(
'20010115123500' ), $user );
1374 # again, note that size/width/height below are ignored; see above.
1375 $image->recordUpload2(
'',
'Upload of some lame thumbnail',
'Some lame thumbnail', [
1381 'mime' =>
'image/png',
1383 'sha1' =>
Wikimedia\base_convert(
'2', 16, 36, 31 ),
1384 'fileExists' =>
true
1385 ], $this->db->timestamp(
'20130225203040' ), $user );
1388 $image->recordUpload2(
'',
'Upload of some lame SVG',
'Some lame SVG', [
1394 'mime' =>
'image/svg+xml',
1396 'sha1' =>
Wikimedia\base_convert(
'', 16, 36, 31 ),
1397 'fileExists' =>
true
1398 ], $this->db->timestamp(
'20010115123500' ), $user );
1400 # This image will be blacklisted in [[MediaWiki:Bad image list]]
1402 $image->recordUpload2(
'',
'zomgnotcensored',
'Borderline image', [
1408 'mime' =>
'image/jpeg',
1410 'sha1' =>
Wikimedia\base_convert(
'3', 16, 36, 31 ),
1411 'fileExists' =>
true
1412 ], $this->db->timestamp(
'20010115123500' ), $user );
1415 $image->recordUpload2(
'',
'A pretty movie',
'Will it play', [
1421 'mime' =>
'application/ogg',
1423 'sha1' =>
Wikimedia\base_convert(
'', 16, 36, 31 ),
1424 'fileExists' =>
true
1425 ], $this->db->timestamp(
'20010115123500' ), $user );
1428 $image->recordUpload2(
'',
'An awesome hitsong',
'Will it play', [
1434 'mime' =>
'application/ogg',
1436 'sha1' =>
Wikimedia\base_convert(
'', 16, 36, 31 ),
1437 'fileExists' =>
true
1438 ], $this->db->timestamp(
'20010115123500' ), $user );
1442 $image->recordUpload2(
'',
'Upload a DjVu',
'A DjVu', [
1448 'mime' =>
'image/vnd.djvu',
1449 'metadata' =>
'<?xml version="1.0" ?>
1450<!DOCTYPE DjVuXML PUBLIC "-//W3C//DTD DjVuXML 1.1//EN" "pubtext/DjVuXML-s.dtd">
1453<BODY><OBJECT height="3508" width="2480">
1454<PARAM name="DPI" value="300" />
1455<PARAM name="GAMMA" value="2.2" />
1457<OBJECT height="3508" width="2480">
1458<PARAM name="DPI" value="300" />
1459<PARAM name="GAMMA" value="2.2" />
1461<OBJECT height="3508" width="2480">
1462<PARAM name="DPI" value="300" />
1463<PARAM name="GAMMA" value="2.2" />
1465<OBJECT height="3508" width="2480">
1466<PARAM name="DPI" value="300" />
1467<PARAM name="GAMMA" value="2.2" />
1469<OBJECT height="3508" width="2480">
1470<PARAM name="DPI" value="300" />
1471<PARAM name="GAMMA" value="2.2" />
1475 'sha1' =>
Wikimedia\base_convert(
'', 16, 36, 31 ),
1476 'fileExists' =>
true
1477 ], $this->db->timestamp(
'20010115123600' ), $user );
1491 $this->dbClone->destroy();
1493 if ( $this->useTemporaryTables ) {
1494 if ( $this->db->getType() ==
'sqlite' ) {
1495 # Under SQLite the searchindex table is virtual and need
1496 # to be explicitly destroyed. See T31912
1497 # See also MediaWikiTestCase::destroyDB()
1498 wfDebug( __METHOD__ .
" explicitly destroying sqlite virtual table parsertest_searchindex\n" );
1499 $this->db->query(
"DROP TABLE `parsertest_searchindex`" );
1501 # Don't need to do anything
1507 foreach (
$tables as $table ) {
1508 if ( $this->db->getType() ==
'oracle' ) {
1509 $this->db->query(
"DROP TABLE pt_$table DROP CONSTRAINTS" );
1511 $this->db->query(
"DROP TABLE `parsertest_$table`" );
1515 if ( $this->db->getType() ==
'oracle' ) {
1516 $this->db->query(
'BEGIN FILL_WIKI_INFO; END;' );
1529 $base = $repo->getZonePath(
'public' );
1530 $backend = $repo->getBackend();
1531 $backend->prepare( [
'dir' =>
"$base/3/3a" ] );
1533 'src' =>
"$IP/tests/phpunit/data/parser/headbg.jpg",
1534 'dst' =>
"$base/3/3a/Foobar.jpg"
1536 $backend->prepare( [
'dir' =>
"$base/e/ea" ] );
1538 'src' =>
"$IP/tests/phpunit/data/parser/wiki.png",
1539 'dst' =>
"$base/e/ea/Thumb.png"
1541 $backend->prepare( [
'dir' =>
"$base/0/09" ] );
1543 'src' =>
"$IP/tests/phpunit/data/parser/headbg.jpg",
1544 'dst' =>
"$base/0/09/Bad.jpg"
1546 $backend->prepare( [
'dir' =>
"$base/5/5f" ] );
1548 'src' =>
"$IP/tests/phpunit/data/parser/LoremIpsum.djvu",
1549 'dst' =>
"$base/5/5f/LoremIpsum.djvu"
1553 $data =
'<?xml version="1.0" encoding="utf-8"?>' .
1554 '<svg xmlns="http://www.w3.org/2000/svg"' .
1555 ' version="1.1" width="240" height="180"/>';
1557 $backend->prepare( [
'dir' =>
"$base/f/ff" ] );
1558 $backend->quickCreate( [
1559 'content' => $data,
'dst' =>
"$base/f/ff/Foobar.svg"
1562 return function () use ( $backend ) {
1575 if ( $this->keepUploads ) {
1580 $public = $repo->getZonePath(
'public' );
1584 "$public/3/3a/Foobar.jpg",
1585 "$public/e/ea/Thumb.png",
1586 "$public/0/09/Bad.jpg",
1587 "$public/5/5f/LoremIpsum.djvu",
1588 "$public/f/ff/Foobar.svg",
1589 "$public/0/00/Video.ogv",
1590 "$public/4/41/Audio.oga",
1602 foreach ( $files as $file ) {
1603 $backend->delete( [
'src' => $file ], [
'force' => 1 ] );
1607 foreach ( $files as $file ) {
1610 if ( !$backend->clean( [
'dir' => $tmp ] )->isOK() ) {
1629 if ( MediaWikiServices::getInstance()->getContentLanguage()->getCode() !==
'en' ) {
1630 $setup[
'wgLanguageCode'] =
'en';
1631 $lang = Language::factory(
'en' );
1632 $setup[
'wgContLang'] =
$lang;
1633 $setup[] =
function () use (
$lang ) {
1634 $services = MediaWikiServices::getInstance();
1635 $services->disableService(
'ContentLanguage' );
1636 $services->redefineService(
'ContentLanguage',
function () use (
$lang ) {
1640 $teardown[] =
function () {
1641 MediaWikiServices::getInstance()->resetServiceForTesting(
'ContentLanguage' );
1649 $setup[
'wgCapitalLinks'] =
true;
1653 foreach ( $articles as $info ) {
1654 $this->
addArticle( $info[
'name'], $info[
'text'], $info[
'file'], $info[
'line'] );
1659 ObjectCache::getMainWANInstance()->clearProcessCache();
1677 $title = Title::newFromText( $name );
1678 wfDebug( __METHOD__ .
": adding $name" );
1680 if ( is_null( $title ) ) {
1681 throw new MWException(
"invalid title '$name' at $file:$line\n" );
1684 $newContent = ContentHandler::makeContent( $text, $title );
1686 $page = WikiPage::factory( $title );
1687 $page->loadPageData(
'fromdbmaster' );
1689 if ( $page->exists() ) {
1693 if ( $newContent->equals(
$content ) ) {
1697 "duplicate article '$name' with different content at $file:$line\n"
1704 if ( $this->disableSaveParse ) {
1705 MessageCache::singleton()->getParser();
1711 $status = $page->doEditContent(
1727 if ( $title->inNamespace(
NS_FILE ) ) {
1742 if ( isset(
$wgParser->mTagHooks[$name] ) ) {
1745 $this->recorder->warning(
" This test suite requires the '$name' hook " .
1746 "extension, skipping." );
1762 if ( isset(
$wgParser->mFunctionHooks[$name] ) ) {
1765 $this->recorder->warning(
" This test suite requires the '$name' function " .
1766 "hook extension, skipping." );
1782 if ( isset(
$wgParser->mTransparentTagHooks[$name] ) ) {
1785 $this->recorder->warning(
" This test suite requires the '$name' transparent " .
1786 "hook extension, skipping.\n" );
$wgObjectCaches
Advanced object cache configuration.
$wgFileBackends
File backend structure configuration.
$wgDBprefix
Table name prefix.
$wgParserTestFiles
Parser test suite files to be run by parserTests.php when no specific filename is passed to it.
$wgParserConf
Parser configuration.
int $wgCommentTableSchemaMigrationStage
Comment table schema migration stage.
int $wgActorTableSchemaMigrationStage
Actor table schema migration stage.
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
wfTempDir()
Tries to get the system directory for temporary files.
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
wfGetCaller( $level=2)
Get the name of the function which called this function wfGetCaller( 1 ) is the function with the wfG...
wfLocalFile( $title)
Get an object referring to a locally registered file.
wfWikiID()
Get an ASCII string identifying this wiki This is used as a prefix in memcached keys.
static changePrefix( $prefix)
Change the table prefix on all open DB connections/.
Class for a file system (FS) based file backend.
static parentStoragePath( $storagePath)
Get the parent storage directory of a storage path.
Simple store for keeping values in an associative array for the current process.
static formatComment( $comment, $title=null, $local=false, $wikiId=null)
This function is called by all recent changes variants, by the page history, and by the user contribu...
static destroySingletons()
Destroy the singleton instances.
static factory(array $config)
Create a new Tidy driver object from configuration.
static setInstance( $instance)
Set the driver to be used.
static destroySingleton()
Destroy the current singleton instance.
Class simulating a backend store.
This class should be covered by a general architecture document which does not exist as of January 20...
A parser used during article insertion which does nothing, to avoid unnecessary log noise and other i...
static normalize( $text, $funcs)
Represent the result of a parser test.
listTables()
List of temporary tables to create, without prefix.
runTestsFromFiles( $filenames)
Run a series of tests listed in the given text files.
bool $keepUploads
Reuse upload directory.
bool $runParsoid
Run tests intended only for parsoid.
staticSetup( $nextTeardown=null)
Do any setup which can be done once for all tests, independent of test options, except for database s...
markSetupDone( $funcName)
Set a setupDone flag to indicate that setup has been done, and return the teardown closure.
string $regex
A complete regex for filtering tests.
runTest( $test)
Run a given wikitext input through a freshly-constructed wiki parser, and compare the output against ...
setupUploads( $nextTeardown=null)
Add data about uploads to the new test DB, and set up the upload directory.
bool $disableSaveParse
Disable parse on article insertion.
createRepoGroup()
Create a RepoGroup object appropriate for the current configuration.
createTeardownObject( $teardown, $nextTeardown=null)
Take a setup array in the same format as the one given to executeSetupSnippets(), and return a Scoped...
teardownUploadBackend()
Remove the dummy uploads directory.
static array $coreTestFiles
MediaWiki core parser test files, paths will be prefixed with DIR .
string null $uploadDir
The upload directory, or null to not set up an upload directory.
setupDatabase( $nextTeardown=null)
Set up temporary DB tables.
checkSetupDone( $funcName, $funcName2=null)
Ensure a given setup stage has been done, throw an exception if it has not.
static getParserTestFiles()
Get list of filenames to extension and core parser tests.
requireHook( $name)
Check if a hook is installed.
setDatabase(IDatabase $db)
array $normalizationFunctions
A list of normalization functions to apply to the expected and actual output.
isSetupDone( $funcName)
Determine whether a particular setup function has been run.
resetTitleServices()
Reset the Title-related services that need resetting for each test.
string null $fileBackendName
The name of the file backend to use, or null to use MockFileBackend.
bool $runDisabled
Run disabled parser tests.
deleteFiles( $files)
Delete the specified files and their parent directories.
static getOptionValue( $key, $opts, $default)
Use a regex to find out the value of an option.
perTestSetup( $test, $nextTeardown=null)
Do any required setup which is dependent on test options.
Database $db
Our connection to the database.
setupInterwikis()
Insert hardcoded interwiki in the lookup table.
__construct(TestRecorder $recorder, $options=[])
requireTransparentHook( $name)
Check if a transparent tag hook is installed.
CloneDatabase $dbClone
Database clone helper.
runTests( $testFileInfo)
Run the tests from a single file.
teardownDatabase()
Helper for database teardown, called from the teardown closure.
requireFunctionHook( $name)
Check if a function hook is installed.
meetsRequirements( $requirements)
Determine whether the current parser has the hooks registered in it that are required by a file read ...
setupUploadBackend()
Upload test files to the backend created by createRepoGroup().
executeSetupSnippets( $setup)
Execute an array in which elements with integer keys are taken to be callable objects,...
addArticles( $articles)
Add articles to the test DB.
getFakeTimestamp()
Fake constant timestamp to make sure time-related parser functions give a persistent value.
static chomp( $s)
Remove last character if it is a newline.
TidyDriverBase $tidyDriver
parseOptions( $instring)
Given the options string, return an associative array of options.
addArticle( $name, $text, $file, $line)
Insert a temporary test article.
getParser( $preprocessor=null)
Get a Parser object.
appendNamespaceSetup(&$setup, &$teardown)
Prioritized list of file repositories.
static singleton()
Get a RepoGroup instance.
static setSingleton( $instance)
Set the singleton instance to a given object Used by extensions which hook into the Repo chain.
static destroySingleton()
Destroy the singleton instance, so that a new one will be created next time singleton() is called.
static read( $file, array $options=[])
Interface to record parser test results.
warning( $message)
Show a warning to the user.
Initialize and detect the tidy support.
The User object encapsulates all of the user-specific settings (user_id, name, rights,...
setOption( $oname, $val)
Set the given option for a user.
static createNew( $name, $params=[])
Add a user to the database, return the user object.
deferred txt A few of the database updates required by various functions here can be deferred until after the result page is displayed to the user For updating the view updating the linked to tables after a etc PHP does not yet have any way to tell the server to actually return and disconnect while still running these but it might have such a feature in the future We handle these by creating a deferred update object and putting those objects on a global list
see documentation in includes Linker php for Linker::makeImageLink or false for current used if you return false $parser
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that probably a stub it is not rendered in wiki pages or galleries in category pages allow injecting custom HTML after the section Any uses of the hook need to handle escaping see BaseTemplate::getToolbox and BaseTemplate::makeListItem for details on the format of individual items inside of this array or by returning and letting standard HTTP rendering take place modifiable or by returning false and taking over the output modifiable modifiable after all normalizations have been except for the $wgMaxImageArea check $image
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped & $options
do that in ParserLimitReportFormat instead use this to modify the parameters of the image all existing parser cache entries will be invalid To avoid you ll need to handle that somehow(e.g. with the RejectParserCacheValue hook) because MediaWiki won 't do it for you. & $defaults also a ContextSource after deleting those rows but within the same transaction you ll probably need to make sure the header is varied on and they can depend only on the ResourceLoaderContext $context
this hook is for auditing only RecentChangesLinked and Watchlist Do not use this to implement individual filters if they are compatible with the ChangesListFilter and ChangesListFilterGroup structure use sub classes of those in conjunction with the ChangesListSpecialPageStructuredFilters hook This hook can be used to implement filters that do not implement that or custom behavior that is not an individual filter e g Watchlist & $tables
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses just before the function returns a value If you return true
static configuration should be added through ResourceLoaderGetConfigVars instead can be used to get the real title e g db for database replication lag or jobqueue for job queue size converted to pseudo seconds It is possible to add more fields and they will be returned to the user in the API response after the basic globals have been set but before ordinary actions take place or wrap services the preferred way to define a new service is the $wgServiceWiringFiles array $services
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that probably a stub it is not rendered in wiki pages or galleries in category pages allow injecting custom HTML after the section Any uses of the hook need to handle escaping see BaseTemplate::getToolbox and BaseTemplate::makeListItem for details on the format of individual items inside of this array or by returning and letting standard HTTP rendering take place modifiable or by returning false and taking over the output $out
Allows to change the fields on the form that will be generated $name
Status::newGood()` to allow deletion, and then `return false` from the hook function. Ensure you consume the 'ChangeTagAfterDelete' hook to carry out custom deletion actions. $tag:name of the tag $user:user initiating the action & $status:Status object. See above. 'ChangeTagsListActive':Allows you to nominate which of the tags your extension uses are in active use. & $tags:list of all active tags. Append to this array. 'ChangeTagsAfterUpdateTags':Called after tags have been updated with the ChangeTags::updateTags function. Params:$addedTags:tags effectively added in the update $removedTags:tags effectively removed in the update $prevTags:tags that were present prior to the update $rc_id:recentchanges table id $rev_id:revision table id $log_id:logging table id $params:tag params $rc:RecentChange being tagged when the tagging accompanies the action, or null $user:User who performed the tagging when the tagging is subsequent to the action, or null 'ChangeTagsAllowedAdd':Called when checking if a user can add tags to a change. & $allowedTags:List of all the tags the user is allowed to add. Any tags the user wants to add( $addTags) that are not in this array will cause it to fail. You may add or remove tags to this array as required. $addTags:List of tags user intends to add. $user:User who is adding the tags. 'ChangeUserGroups':Called before user groups are changed. $performer:The User who will perform the change $user:The User whose groups will be changed & $add:The groups that will be added & $remove:The groups that will be removed 'Collation::factory':Called if $wgCategoryCollation is an unknown collation. $collationName:Name of the collation in question & $collationObject:Null. Replace with a subclass of the Collation class that implements the collation given in $collationName. 'ConfirmEmailComplete':Called after a user 's email has been confirmed successfully. $user:user(object) whose email is being confirmed 'ContentAlterParserOutput':Modify parser output for a given content object. Called by Content::getParserOutput after parsing has finished. Can be used for changes that depend on the result of the parsing but have to be done before LinksUpdate is called(such as adding tracking categories based on the rendered HTML). $content:The Content to render $title:Title of the page, as context $parserOutput:ParserOutput to manipulate 'ContentGetParserOutput':Customize parser output for a given content object, called by AbstractContent::getParserOutput. May be used to override the normal model-specific rendering of page content. $content:The Content to render $title:Title of the page, as context $revId:The revision ID, as context $options:ParserOptions for rendering. To avoid confusing the parser cache, the output can only depend on parameters provided to this hook function, not on global state. $generateHtml:boolean, indicating whether full HTML should be generated. If false, generation of HTML may be skipped, but other information should still be present in the ParserOutput object. & $output:ParserOutput, to manipulate or replace 'ContentHandlerDefaultModelFor':Called when the default content model is determined for a given title. May be used to assign a different model for that title. $title:the Title in question & $model:the model name. Use with CONTENT_MODEL_XXX constants. 'ContentHandlerForModelID':Called when a ContentHandler is requested for a given content model name, but no entry for that model exists in $wgContentHandlers. Note:if your extension implements additional models via this hook, please use GetContentModels hook to make them known to core. $modeName:the requested content model name & $handler:set this to a ContentHandler object, if desired. 'ContentModelCanBeUsedOn':Called to determine whether that content model can be used on a given page. This is especially useful to prevent some content models to be used in some special location. $contentModel:ID of the content model in question $title:the Title in question. & $ok:Output parameter, whether it is OK to use $contentModel on $title. Handler functions that modify $ok should generally return false to prevent further hooks from further modifying $ok. 'ContribsPager::getQueryInfo':Before the contributions query is about to run & $pager:Pager object for contributions & $queryInfo:The query for the contribs Pager 'ContribsPager::reallyDoQuery':Called before really executing the query for My Contributions & $data:an array of results of all contribs queries $pager:The ContribsPager object hooked into $offset:Index offset, inclusive $limit:Exact query limit $descending:Query direction, false for ascending, true for descending 'ContributionsLineEnding':Called before a contributions HTML line is finished $page:SpecialPage object for contributions & $ret:the HTML line $row:the DB row for this line & $classes:the classes to add to the surrounding< li > & $attribs:associative array of other HTML attributes for the< li > element. Currently only data attributes reserved to MediaWiki are allowed(see Sanitizer::isReservedDataAttribute). 'ContributionsToolLinks':Change tool links above Special:Contributions $id:User identifier $title:User page title & $tools:Array of tool links $specialPage:SpecialPage instance for context and services. Can be either SpecialContributions or DeletedContributionsPage. Extensions should type hint against a generic SpecialPage though. 'ConvertContent':Called by AbstractContent::convert when a conversion to another content model is requested. Handler functions that modify $result should generally return false to disable further attempts at conversion. $content:The Content object to be converted. $toModel:The ID of the content model to convert to. $lossy: boolean indicating whether lossy conversion is allowed. & $result:Output parameter, in case the handler function wants to provide a converted Content object. Note that $result->getContentModel() must return $toModel. 'ContentSecurityPolicyDefaultSource':Modify the allowed CSP load sources. This affects all directives except for the script directive. If you want to add a script source, see ContentSecurityPolicyScriptSource hook. & $defaultSrc:Array of Content-Security-Policy allowed sources $policyConfig:Current configuration for the Content-Security-Policy header $mode:ContentSecurityPolicy::REPORT_ONLY_MODE or ContentSecurityPolicy::FULL_MODE depending on type of header 'ContentSecurityPolicyDirectives':Modify the content security policy directives. Use this only if ContentSecurityPolicyDefaultSource and ContentSecurityPolicyScriptSource do not meet your needs. & $directives:Array of CSP directives $policyConfig:Current configuration for the CSP header $mode:ContentSecurityPolicy::REPORT_ONLY_MODE or ContentSecurityPolicy::FULL_MODE depending on type of header 'ContentSecurityPolicyScriptSource':Modify the allowed CSP script sources. Note that you also have to use ContentSecurityPolicyDefaultSource if you want non-script sources to be loaded from whatever you add. & $scriptSrc:Array of CSP directives $policyConfig:Current configuration for the CSP header $mode:ContentSecurityPolicy::REPORT_ONLY_MODE or ContentSecurityPolicy::FULL_MODE depending on type of header 'CustomEditor':When invoking the page editor Return true to allow the normal editor to be used, or false if implementing a custom editor, e.g. for a special namespace, etc. $article:Article being edited $user:User performing the edit 'DatabaseOraclePostInit':Called after initialising an Oracle database $db:the DatabaseOracle object 'DeletedContribsPager::reallyDoQuery':Called before really executing the query for Special:DeletedContributions Similar to ContribsPager::reallyDoQuery & $data:an array of results of all contribs queries $pager:The DeletedContribsPager object hooked into $offset:Index offset, inclusive $limit:Exact query limit $descending:Query direction, false for ascending, true for descending 'DeletedContributionsLineEnding':Called before a DeletedContributions HTML line is finished. Similar to ContributionsLineEnding $page:SpecialPage object for DeletedContributions & $ret:the HTML line $row:the DB row for this line & $classes:the classes to add to the surrounding< li > & $attribs:associative array of other HTML attributes for the< li > element. Currently only data attributes reserved to MediaWiki are allowed(see Sanitizer::isReservedDataAttribute). 'DeleteUnknownPreferences':Called by the cleanupPreferences.php maintenance script to build a WHERE clause with which to delete preferences that are not known about. This hook is used by extensions that have dynamically-named preferences that should not be deleted in the usual cleanup process. For example, the Gadgets extension creates preferences prefixed with 'gadget-', and so anything with that prefix is excluded from the deletion. &where:An array that will be passed as the $cond parameter to IDatabase::select() to determine what will be deleted from the user_properties table. $db:The IDatabase object, useful for accessing $db->buildLike() etc. 'DifferenceEngineAfterLoadNewText':called in DifferenceEngine::loadNewText() after the new revision 's content has been loaded into the class member variable $differenceEngine->mNewContent but before returning true from this function. $differenceEngine:DifferenceEngine object 'DifferenceEngineLoadTextAfterNewContentIsLoaded':called in DifferenceEngine::loadText() after the new revision 's content has been loaded into the class member variable $differenceEngine->mNewContent but before checking if the variable 's value is null. This hook can be used to inject content into said class member variable. $differenceEngine:DifferenceEngine object 'DifferenceEngineMarkPatrolledLink':Allows extensions to change the "mark as
patrolled" link which is shown both on the diff header as well as on the bottom of a page, usually wrapped in a span element which has class="patrollink". $differenceEngine:DifferenceEngine object & $markAsPatrolledLink:The "mark as patrolled" link HTML(string) $rcid:Recent change ID(rc_id) for this change(int) 'DifferenceEngineMarkPatrolledRCID':Allows extensions to possibly change the rcid parameter. For example the rcid might be set to zero due to the user being the same as the performer of the change but an extension might still want to show it under certain conditions. & $rcid:rc_id(int) of the change or 0 $differenceEngine:DifferenceEngine object $change:RecentChange object $user:User object representing the current user 'DifferenceEngineNewHeader':Allows extensions to change the $newHeader variable, which contains information about the new revision, such as the revision 's author, whether the revision was marked as a minor edit or not, etc. $differenceEngine:DifferenceEngine object & $newHeader:The string containing the various #mw-diff-otitle[1-5] divs, which include things like revision author info, revision comment, RevisionDelete link and more $formattedRevisionTools:Array containing revision tools, some of which may have been injected with the DiffRevisionTools hook $nextlink:String containing the link to the next revision(if any) $status
usually copyright or history_copyright This message must be in HTML not wikitext if the section is included from a template $section
static configuration should be added through ResourceLoaderGetConfigVars instead can be used to get the real title e g db for database replication lag or jobqueue for job queue size converted to pseudo seconds It is possible to add more fields and they will be returned to the user in the API response after the basic globals have been set but before ordinary actions take place $output
please add to it if you re going to add events to the MediaWiki code where normally authentication against an external auth plugin would be creating a local account $user
returning false will NOT prevent logging $e
const SCHEMA_COMPAT_WRITE_NEW
const MIGRATION_WRITE_BOTH
The wiki should then use memcached to cache various data To use multiple just add more items to the array To increase the weight of a make its entry a array("192.168.0.1:11211", 2))
if(!isset( $args[0])) $lang