30use Wikimedia\ScopedCallback;
31use Wikimedia\TestingAccessWrapper;
46 'extraParserTests.txt',
58 'staticSetup' =>
false,
59 'perTestSetup' =>
false,
60 'setupDatabase' =>
false,
61 'setDatabase' =>
false,
62 'setupUploads' =>
false,
126 foreach (
$options[
'norm'] as $func ) {
127 if ( in_array( $func, [
'removeTbody',
'trimWhitespace' ] ) ) {
128 $this->normalizationFunctions[] = $func;
131 "Warning: unknown normalization option \"$func\"\n" );
143 $this->keepUploads = !empty(
$options[
'keep-uploads'] );
145 $this->fileBackendName = isset(
$options[
'file-backend'] ) ?
148 $this->runDisabled = !empty(
$options[
'run-disabled'] );
149 $this->runParsoid = !empty(
$options[
'run-parsoid'] );
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'];
171 $files = array_map(
function ( $item ) {
172 return __DIR__ .
"/$item";
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 ) {
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 );
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;
281 $setup[
'wgExtraInterlanguageLinkPrefixes'] = [
'mul' ];
286 $teardown[] =
function () {
291 $setup[
'wgLockManagers'] = [ [
292 'name' =>
'fsLockManager',
293 'class' => NullLockManager::class,
295 'name' =>
'nullLockManager',
296 'class' => NullLockManager::class,
298 $reset =
function () {
302 $teardown[] = $reset;
305 $setup[
'wgDefaultExternalStore'] =
false;
308 $setup[
'wgAdaptiveMessageCache'] =
true;
311 $setup[
'wgUseDatabaseMessages'] =
true;
312 $reset =
function () {
316 $teardown[] = $reset;
319 $setup[
'wgSVGConverter'] =
'null';
320 $setup[
'wgSVGConverters'] = [
'null' =>
'echo "1">$output' ];
323 Hooks::register(
'ParserGetVariableValueTs',
function ( &
$parser, &$ts ) {
327 $teardown[] =
function () {
328 Hooks::clear(
'ParserGetVariableValueTs' );
338 $setup[
'wgLocalInterwikis'] = [
'local',
'mi' ];
339 $reset =
function () {
343 $teardown[] = $reset;
346 MediaWikiServices::getInstance()->disableService(
'MediaHandlerFactory' );
347 MediaWikiServices::getInstance()->redefineService(
348 'MediaHandlerFactory',
350 $handlers =
$services->getMainConfig()->
get(
'ParserTestMediaHandlers' );
354 $teardown[] =
function () {
355 MediaWikiServices::getInstance()->resetServiceForTesting(
'MediaHandlerFactory' );
363 if ( isset( ObjectCache::$instances[
CACHE_DB] ) ) {
364 $savedCache = ObjectCache::$instances[
CACHE_DB];
366 $teardown[] =
function () use ( $savedCache ) {
367 ObjectCache::$instances[
CACHE_DB] = $savedCache;
380 $setup[
'wgExtraNamespaces'] = [
381 100 =>
'MemoryAlpha',
382 101 =>
'MemoryAlpha_talk'
386 $reset =
function () {
387 MWNamespace::clearCaches();
388 $GLOBALS[
'wgContLang']->resetNamespaces();
391 $teardown[] = $reset;
399 if ( $this->uploadDir ) {
400 if ( $this->fileBackendName ) {
401 throw new MWException(
'You cannot specify both use-filebackend and upload-dir' );
404 'name' =>
'local-backend',
406 'basePath' => $this->uploadDir,
409 } elseif ( $this->fileBackendName ) {
414 if ( $conf[
'name'] === $name ) {
418 if ( $useConfig ===
false ) {
419 throw new MWException(
"Unable to find file backend \"$name\"" );
421 $useConfig[
'name'] =
'local-backend';
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
431 'name' =>
'local-backend',
438 'class' => MockLocalRepo::class,
440 'url' =>
'http://example.com/images',
442 'transformVia404' =>
false,
443 'backend' => $backend
464 foreach ( $setup as $name =>
$value ) {
465 if ( is_int( $name ) ) {
472 return function () use ( $saved ) {
490 return new ScopedCallback(
function () use ( $teardown, $nextTeardown ) {
492 $teardown = array_reverse( $teardown );
495 if ( $nextTeardown ) {
496 ScopedCallback::consume( $nextTeardown );
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;
525 if ( !$this->setupDone[$funcName]
526 && ( $funcName ===
null || !$this->setupDone[$funcName2] )
528 throw new MWException(
"$funcName must be called before calling " .
540 return isset( $this->setupDone[$funcName] ) ? $this->setupDone[$funcName] :
false;
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];
619 MediaWikiServices::getInstance()->resetServiceForTesting(
'InterwikiLookup' );
623 Hooks::clear(
'InterwikiLoadPrefix' );
624 MediaWikiServices::getInstance()->resetServiceForTesting(
'InterwikiLookup' );
633 $services = MediaWikiServices::getInstance();
634 $services->resetServiceForTesting(
'TitleFormatter' );
635 $services->resetServiceForTesting(
'TitleParser' );
636 $services->resetServiceForTesting(
'_MediaWikiTitleCodec' );
637 $services->resetServiceForTesting(
'LinkRenderer' );
638 $services->resetServiceForTesting(
'LinkRendererFactory' );
647 if ( substr(
$s, -1 ) ===
"\n" ) {
648 return substr(
$s, 0, -1 );
674 $this->recorder->start();
678 foreach ( $filenames as $filename ) {
680 'runDisabled' => $this->runDisabled,
681 'runParsoid' => $this->runParsoid,
682 'regex' => $this->regex ] );
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 );
712 foreach ( $requirements as $requirement ) {
713 switch ( $requirement[
'type'] ) {
720 case 'transparentHook':
744 if ( !$testFileInfo[
'tests'] ) {
750 foreach ( $testFileInfo[
'tests'] as $test ) {
751 $this->recorder->startTest( $test );
752 $this->recorder->skipped( $test,
'required extension not enabled' );
761 foreach ( $testFileInfo[
'tests'] as $test ) {
762 $this->recorder->startTest( $test );
765 if ( $result !==
false ) {
766 $ok = $ok && $result->isSuccess();
767 $this->recorder->record( $test, $result );
808 wfDebug( __METHOD__.
": running {$test['desc']}" );
817 if ( isset( $opts[
'tidy'] ) ) {
818 if ( !$this->tidySupport->isEnabled() ) {
819 $this->recorder->skipped( $test,
'tidy extension is not installed' );
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;
835 $title = Title::newFromText( $titleText );
837 if ( isset( $opts[
'styletag'] ) ) {
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'] ) ) {
853 } elseif ( isset( $opts[
'msg'] ) ) {
855 } elseif ( isset( $opts[
'section'] ) ) {
858 } elseif ( isset( $opts[
'replace'] ) ) {
860 $replace = $opts[
'replace'][1];
862 } elseif ( isset( $opts[
'comment'] ) ) {
864 } elseif ( isset( $opts[
'preload'] ) ) {
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";
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 ) ) {
916 $test[
'expected'], $this->normalizationFunctions );
932 $key = strtolower( $key );
934 if ( isset( $opts[$key] ) ) {
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 ) ) {
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];
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 );
1051 $config = $test[
'config'];
1060 $linkHolderBatchSize =
1068 'wgLanguageCode' => $langCode,
1070 'wgNamespacesWithSubpages' => array_fill_keys(
1071 MWNamespace::getValidNamespaces(), isset( $opts[
'subpage'] )
1073 'wgMaxTocLevel' => $maxtoclevel,
1076 'wgDefaultLanguageVariant' => $variant,
1077 'wgLinkHolderBatchSize' => $linkHolderBatchSize,
1081 + [
'ISBN' =>
true,
'PMID' =>
true,
'RFC' =>
true ],
1083 'wgFragmentMode' => [
'legacy' ],
1087 $configLines = explode(
"\n", $config );
1089 foreach ( $configLines as
$line ) {
1091 $setup[$var] = eval(
"return $value;" );
1096 Hooks::run(
'ParserTestGlobals', [ &$setup ] );
1099 if ( isset( $opts[
'tidy'] ) ) {
1101 if ( $this->tidyDriver ===
null ) {
1102 $this->tidyDriver =
MWTidy::factory( $this->tidySupport->getConfig() );
1109 $teardown[] =
function () {
1114 $lang = Language::factory( $langCode );
1115 $lang->resetNamespaces();
1116 $setup[
'wgContLang'] =
$lang;
1117 $reset =
function () {
1122 $teardown[] = $reset;
1126 $user->
setOption(
'language', $langCode );
1127 $setup[
'wgLang'] =
$lang;
1130 $user->setOption(
'thumbsize', 0 );
1132 $setup[
'wgUser'] =
$user;
1140 $skinFactory = MediaWikiServices::getInstance()->getSkinFactory();
1141 $context->setSkin( $skinFactory->makeSkin( $skin ) );
1143 $setup[
'wgOut'] =
$context->getOutput();
1144 $teardown[] =
function () use (
$context, $oldSkin ) {
1146 $wrapper = TestingAccessWrapper::newFromObject(
1147 $context->getLanguage()->getConverter()
1149 $wrapper->reloadTables();
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'
1182 $tables[] =
'revision_comment_temp';
1183 $tables[] =
'image_comment_temp';
1189 $tables[] =
'revision_actor_temp';
1192 if ( in_array( $this->db->getType(), [
'mysql',
'sqlite',
'oracle' ] ) ) {
1193 array_push(
$tables,
'searchindex' );
1199 Hooks::run(
'ParserTestTables', [ &
$tables ] );
1206 $this->setupDone[
'setDatabase'] =
true;
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" );
1245 # CREATE TEMPORARY TABLE breaks if there is more than one server
1246 if (
wfGetLB()->getServerCount() != 1 ) {
1247 $this->useTemporaryTables =
false;
1250 $temporary = $this->useTemporaryTables || $dbType ==
'postgres';
1251 $prefix = $dbType !=
'oracle' ?
'parsertest_' :
'pt_';
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 () {
1272 $reset =
function () {
1273 LinkCache::singleton()->clear();
1279 $teardown[] = $reset;
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', [
1317 'mime' =>
'image/jpeg',
1319 'sha1' => Wikimedia\base_convert(
'1', 16, 36, 31 ),
1320 'fileExists' =>
true
1321 ], $this->db->timestamp(
'20010115123500' ), $user );
1324 # again, note that size/width/height below are ignored; see above.
1325 $image->recordUpload2(
'',
'Upload of some lame thumbnail',
'Some lame thumbnail', [
1331 'mime' =>
'image/png',
1333 'sha1' => Wikimedia\base_convert(
'2', 16, 36, 31 ),
1334 'fileExists' =>
true
1335 ], $this->db->timestamp(
'20130225203040' ), $user );
1338 $image->recordUpload2(
'',
'Upload of some lame SVG',
'Some lame SVG', [
1344 'mime' =>
'image/svg+xml',
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]]
1352 $image->recordUpload2(
'',
'zomgnotcensored',
'Borderline image', [
1358 'mime' =>
'image/jpeg',
1360 'sha1' => Wikimedia\base_convert(
'3', 16, 36, 31 ),
1361 'fileExists' =>
true
1362 ], $this->db->timestamp(
'20010115123500' ), $user );
1365 $image->recordUpload2(
'',
'A pretty movie',
'Will it play', [
1371 'mime' =>
'application/ogg',
1373 'sha1' => Wikimedia\base_convert(
'', 16, 36, 31 ),
1374 'fileExists' =>
true
1375 ], $this->db->timestamp(
'20010115123500' ), $user );
1378 $image->recordUpload2(
'',
'An awesome hitsong',
'Will it play', [
1384 'mime' =>
'application/ogg',
1386 'sha1' => Wikimedia\base_convert(
'', 16, 36, 31 ),
1387 'fileExists' =>
true
1388 ], $this->db->timestamp(
'20010115123500' ), $user );
1392 $image->recordUpload2(
'',
'Upload a DjVu',
'A DjVu', [
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 );
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
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;' );
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"
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 ) {
1526 if ( $this->keepUploads ) {
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",
1553 foreach ( $files as $file ) {
1554 $backend->delete( [
'src' => $file ], [
'force' => 1 ] );
1558 foreach ( $files as $file ) {
1561 if ( !$backend->clean( [
'dir' => $tmp ] )->isOK() ) {
1582 $setup[
'wgLanguageCode'] =
'en';
1583 $setup[
'wgContLang'] = Language::factory(
'en' );
1590 $setup[
'wgCapitalLinks'] =
true;
1594 foreach ( $articles as $info ) {
1595 $this->
addArticle( $info[
'name'], $info[
'text'], $info[
'file'], $info[
'line'] );
1600 ObjectCache::getMainWANInstance()->clearProcessCache();
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 );
1634 if ( $newContent->equals( $content ) ) {
1638 "duplicate article '$name' with different content at $file:$line\n"
1648 $status = $page->doEditContent(
1662 if ( $title->inNamespace(
NS_FILE ) ) {
1677 if ( isset(
$wgParser->mTagHooks[$name] ) ) {
1680 $this->recorder->warning(
" This test suite requires the '$name' hook " .
1681 "extension, skipping." );
1697 if ( isset(
$wgParser->mFunctionHooks[$name] ) ) {
1700 $this->recorder->warning(
" This test suite requires the '$name' function " .
1701 "hook extension, skipping." );
1717 if ( isset(
$wgParser->mTransparentTagHooks[$name] ) ) {
1720 $this->recorder->warning(
" This test suite requires the '$name' transparent " .
1721 "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.
wfGetLB( $wiki=false)
Get a load balancer object.
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.
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.
static clearCache()
Clear the self::$mObjects variable For use in parser tests.
static destroyInstance()
Destroy the singleton instance.
static singleton()
Get the signleton instance of this class.
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.
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.
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.
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 getMain()
Get the RequestContext object associated with the main request.
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
this class mediates it Skin Encapsulates a look and feel for the wiki All of the functions that render HTML and make choices about how to render it are here and are called from various other places when and is meant to be subclassed with other skins that may override some of its functions The User object contains a reference to a and so rather than having a global skin object we just rely on the global User and get the skin with $wgUser and also has some character encoding functions and other locale stuff The current user interface language is instantiated as and the local content language as $wgContLang
do that in ParserLimitReportFormat instead $parser
static configuration should be added through ResourceLoaderGetConfigVars instead can be used to get the real title after the basic globals have been set but before ordinary actions take place $output
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. '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
this hook is for auditing only RecentChangesLinked and Watchlist 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
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
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 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
usually copyright or history_copyright This message must be in HTML not wikitext if the section is included from a template $section
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 MIGRATION_WRITE_BOTH
if(!isset( $args[0])) $lang