' . "\nMy message
"
], 'List at start' => [
[ '* List' ],
"{{PAGENAME}}", true, $somePageRef ],
'
' . "Some page
"
],
],
'wrapWikiTextAsInterface' => [
'Simple' => [
[ 'wrapperClass', 'text' ],
"
"
], 'Spurious
' => [
[ 'wrapperClass', 'textmore' ],
"
"
], 'Extra newlines would break
wrappers' => [
[ 'two classes', "1\n\n2\n\n3" ],
"
"
], 'Other unclosed tags' => [
[ 'error', 'a
cd' ],
""
],
],
];
// We have to reformat our array to match what PHPUnit wants
$ret = [];
foreach ( $tests as $key => $subarray ) {
foreach ( $subarray as $subkey => $val ) {
$val = array_merge( [ $key ], $val );
$ret[$subkey] = $val;
}
}
return $ret;
}
public function testAddWikiTextAsInterfaceNoTitle() {
$this->expectException( RuntimeException::class );
$this->expectExceptionMessage( 'No title' );
$op = $this->newInstance( [], null, 'notitle' );
$op->addWikiTextAsInterface( 'a' );
}
public function testAddWikiTextAsContentNoTitle() {
$this->expectException( RuntimeException::class );
$this->expectExceptionMessage( 'No title' );
$op = $this->newInstance( [], null, 'notitle' );
$op->addWikiTextAsContent( 'a' );
}
public function testAddWikiMsg() {
$msg = wfMessage( 'parentheses' );
$this->assertSame( '(a)', $msg->rawParams( 'a' )->plain() );
$op = $this->newInstance();
$this->assertSame( '', $op->getHTML() );
$op->addWikiMsg( 'parentheses', "a" );
// The input is bad unbalanced HTML, but the output is tidied
$this->assertSame( "(a)\n
", $op->getHTML() );
}
public function testWrapWikiMsg() {
$msg = wfMessage( 'parentheses' );
$this->assertSame( '(a)', $msg->rawParams( 'a' )->plain() );
$op = $this->newInstance();
$this->assertSame( '', $op->getHTML() );
$op->wrapWikiMsg( '[$1]', [ 'parentheses', "
a" ] );
// The input is bad unbalanced HTML, but the output is tidied
$this->assertSame( "[(a)]\n
", $op->getHTML() );
}
public function testNoGallery() {
$this->filterDeprecated( '/OutputPage::getNoGallery was deprecated/' );
$op = $this->newInstance();
$this->assertFalse( $op->getNoGallery() );
$this->assertFalse( $op->getOutputFlag( ParserOutputFlags::NO_GALLERY ) );
$stubPO1 = $this->createParserOutputStubWithFlags(
[ 'getNoGallery' => true ], [ ParserOutputFlags::NO_GALLERY ]
);
$op->addParserOutputMetadata( $stubPO1 );
$this->assertTrue( $op->getNoGallery() );
$this->assertTrue( $op->getOutputFlag( ParserOutputFlags::NO_GALLERY ) );
$stubPO2 = $this->createParserOutputStub( 'getNoGallery', false );
$op->addParserOutput( $stubPO2, ParserOptions::newFromAnon() );
$this->assertFalse( $op->getNoGallery() );
// Note that flags are OR'ed together, and not reset.
$this->assertTrue( $op->getOutputFlag( ParserOutputFlags::NO_GALLERY ) );
}
// @todo Make sure to test the following in addParserOutputMetadata() as well when we add tests
// for them:
// * addModules()
// * addModuleStyles()
// * addJsConfigVars()
// * enableOOUI()
// Otherwise those lines of addParserOutputMetadata() will be reported as covered, but we won't
// be testing they actually work.
public function testAddParserOutputText() {
$op = $this->newInstance();
$this->assertSame( '', $op->getHTML() );
$text = '
';
$pOut = $this->createParserOutputStub( 'runOutputPipeline', new ParserOutput( $text ) );
$op->addParserOutputMetadata( $pOut );
$this->assertSame( '', $op->getHTML() );
$op->addParserOutputText( $text );
$this->assertSame( '', $op->getHTML() );
}
public function testAddParserOutput() {
$op = $this->newInstance();
$this->assertSame( '', $op->getHTML() );
$this->filterDeprecated( '/OutputPage::showNewSectionLink was deprecated/' );
$this->assertFalse( $op->showNewSectionLink() );
$this->assertFalse( $op->getOutputFlag( ParserOutputFlags::NEW_SECTION ) );
$pOut = $this->createParserOutputStubWithFlags( [
'getContentHolderText' => '',
'getNewSection' => true,
], [
ParserOutputFlags::NEW_SECTION,
] );
$op->addParserOutput( $pOut, ParserOptions::newFromAnon() );
$this->assertSame( '', $op->getHTML() );
$this->assertTrue( $op->showNewSectionLink() );
$this->assertTrue( $op->getOutputFlag( ParserOutputFlags::NEW_SECTION ) );
}
public function testAddTemplate() {
$template = $this->createMock( QuickTemplate::class );
$template->method( 'getHTML' )->willReturn( '&def;' );
$op = $this->newInstance();
$op->addTemplate( $template );
$this->assertSame( '&def;', $op->getHTML() );
}
/**
* @dataProvider provideParseAs
*/
public function testParseAsContent(
array $args, $expectedHTML, $expectedHTMLInline = null
) {
$op = $this->newInstance();
$this->assertSame( $expectedHTML, $op->parseAsContent( ...$args ) );
}
/**
* @dataProvider provideParseAs
*/
public function testParseAsInterface(
array $args, $expectedHTML, $expectedHTMLInline = null
) {
$op = $this->newInstance();
$this->assertSame( $expectedHTML, $op->parseAsInterface( ...$args ) );
}
/**
* @dataProvider provideParseAs
*/
public function testParseInlineAsInterface(
array $args, $expectedHTML, $expectedHTMLInline = null
) {
$op = $this->newInstance();
$this->assertSame(
$expectedHTMLInline ?? $expectedHTML,
$op->parseInlineAsInterface( ...$args )
);
}
public static function provideParseAs() {
return [
'List at start of line' => [
[ '* List', true ],
"",
],
'List not at start' => [
[ "* ''Not'' list", false ],
'* Not list
',
'* Not list',
],
'Italics' => [
[ "''Italic''", true ],
"Italic\n
",
'Italic',
],
'formatnum' => [
[ '{{formatnum:123456.789}}', true ],
"123,456.789\n
",
"123,456.789",
],
'No section edit links' => [
[ '== Header ==' ],
'',
]
];
}
public function testParseAsContentNullTitle() {
$this->expectException( RuntimeException::class );
$this->expectExceptionMessage( 'No title' );
$op = $this->newInstance( [], null, 'notitle' );
$op->parseAsContent( '' );
}
public function testParseAsInterfaceNullTitle() {
$this->expectException( RuntimeException::class );
$this->expectExceptionMessage( 'No title' );
$op = $this->newInstance( [], null, 'notitle' );
$op->parseAsInterface( '' );
}
public function testParseInlineAsInterfaceNullTitle() {
$this->expectException( RuntimeException::class );
$this->expectExceptionMessage( 'No title' );
$op = $this->newInstance( [], null, 'notitle' );
$op->parseInlineAsInterface( '' );
}
public function testCdnMaxage() {
$op = $this->newInstance();
$wrapper = TestingAccessWrapper::newFromObject( $op );
$this->assertSame( 0, $wrapper->mCdnMaxage );
$op->setCdnMaxage( -1 );
$this->assertSame( -1, $wrapper->mCdnMaxage );
$op->setCdnMaxage( 120 );
$this->assertSame( 120, $wrapper->mCdnMaxage );
$op->setCdnMaxage( 60 );
$this->assertSame( 60, $wrapper->mCdnMaxage );
$op->setCdnMaxage( 180 );
$this->assertSame( 180, $wrapper->mCdnMaxage );
$op->lowerCdnMaxage( 240 );
$this->assertSame( 180, $wrapper->mCdnMaxage );
$op->setCdnMaxage( 300 );
$this->assertSame( 240, $wrapper->mCdnMaxage );
$op->lowerCdnMaxage( 120 );
$this->assertSame( 120, $wrapper->mCdnMaxage );
$op->setCdnMaxage( 180 );
$this->assertSame( 120, $wrapper->mCdnMaxage );
$op->setCdnMaxage( 60 );
$this->assertSame( 60, $wrapper->mCdnMaxage );
$op->setCdnMaxage( 240 );
$this->assertSame( 120, $wrapper->mCdnMaxage );
}
/** @var int Faked time to set for tests that need it */
private static $fakeTime;
/**
* @dataProvider provideAdaptCdnTTL
* @param array $args To pass to adaptCdnTTL()
* @param int $expected Expected new value of mCdnMaxageLimit
* @param array $options Associative array:
* initialMaxage => Maxage to set before calling adaptCdnTTL() (default 86400)
*/
public function testAdaptCdnTTL( array $args, $expected, array $options = [] ) {
MWTimestamp::setFakeTime( self::$fakeTime );
$op = $this->newInstance();
// Set a high maxage so that it will get reduced by adaptCdnTTL(). The default maxage
// is 0, so adaptCdnTTL() won't mutate the object at all.
$initial = $options['initialMaxage'] ?? 86400;
$op->setCdnMaxage( $initial );
$op->adaptCdnTTL( ...$args );
$wrapper = TestingAccessWrapper::newFromObject( $op );
// Special rules for false/null
if ( $args[0] === null || $args[0] === false ) {
$this->assertSame( $initial, $wrapper->mCdnMaxage, 'member value' );
$op->setCdnMaxage( $expected + 1 );
$this->assertSame( $expected + 1, $wrapper->mCdnMaxage, 'member value after new set' );
return;
}
$this->assertSame( $expected, $wrapper->mCdnMaxageLimit, 'limit value' );
if ( $initial >= $expected ) {
$this->assertSame( $expected, $wrapper->mCdnMaxage, 'member value' );
} else {
$this->assertSame( $initial, $wrapper->mCdnMaxage, 'member value' );
}
$op->setCdnMaxage( $expected + 1 );
$this->assertSame( $expected, $wrapper->mCdnMaxage, 'member value after new set' );
}
public static function provideAdaptCdnTTL() {
global $wgCdnMaxAge;
$now = time();
self::$fakeTime = $now;
$oneMinute = 60;
return [
'Five minutes ago' => [ [ $now - 300 ], 270 ],
'Now' => [ [ +0 ], $oneMinute ],
'Five minutes from now' => [ [ $now + 300 ], $oneMinute ],
'Five minutes ago, initial maxage four minutes' =>
[ [ $now - 300 ], 270, [ 'initialMaxage' => 240 ] ],
'A very long time ago' => [ [ $now - 1000000000 ], $wgCdnMaxAge ],
'Initial maxage zero' => [ [ $now - 300 ], 270, [ 'initialMaxage' => 0 ] ],
'false' => [ [ false ], $oneMinute ],
'null' => [ [ null ], $oneMinute ],
"'0'" => [ [ '0' ], $oneMinute ],
'Empty string' => [ [ '' ], $oneMinute ],
// @todo These give incorrect results due to timezones, how to test?
//"'now'" => [ [ 'now' ], $oneMinute ],
//"'parse error'" => [ [ 'parse error' ], $oneMinute ],
'Now, minTTL 0' => [ [ $now, 0 ], $oneMinute ],
'Now, minTTL 0.000001' => [ [ $now, 0.000001 ], 0 ],
'A very long time ago, maxTTL even longer' =>
[ [ $now - 1000000000, 0, 1000000001 ], 900000000 ],
];
}
public function testClientCache() {
$op = $this->newInstance();
$op->considerCacheSettingsFinal();
// Test initial value
$this->assertSame( true, $op->couldBePublicCached() );
// Test setting to false
$op->disableClientCache();
$this->assertSame( false, $op->couldBePublicCached() );
// Test setting to true
$op->enableClientCache();
$this->assertSame( true, $op->couldBePublicCached() );
// set back to false
$op->disableClientCache();
// Test that a cacheable ParserOutput doesn't set to true
$pOutCacheable = $this->createParserOutputStub( 'isCacheable', true );
$op->addParserOutputMetadata( $pOutCacheable );
$this->assertSame( false, $op->couldBePublicCached() );
// Reset to true
$op = $this->newInstance();
$op->considerCacheSettingsFinal();
$this->assertSame( true, $op->couldBePublicCached() );
// Test that an uncacheable ParserOutput does set to false
$pOutUncacheable = $this->createParserOutputStub( 'isCacheable', false );
$op->addParserOutput( $pOutUncacheable, ParserOptions::newFromAnon() );
$this->assertSame( false, $op->couldBePublicCached() );
}
public function testGetCacheVaryCookies() {
$op = $this->newInstance();
$expectedCookies = array_merge(
SessionManager::singleton()->getVaryCookies(),
[
'forceHTTPS',
'cookie1',
'cookie2',
]
);
$expectedCookies = array_values( array_unique( $expectedCookies ) );
// We have to reset the cookies because getCacheVaryCookies may have already been called
TestingAccessWrapper::newFromClass( OutputPage::class )->cacheVaryCookies = null;
$this->overrideConfigValue( MainConfigNames::CacheVaryCookies, [ 'cookie1' ] );
// Clear out any extension hooks that may interfere with cookies.
$this->clearHook( 'GetCacheVaryCookies' );
$this->setTemporaryHook( 'GetCacheVaryCookies',
function ( $innerOP, &$cookies ) use ( $op, $expectedCookies ) {
$this->assertSame( $op, $innerOP );
$cookies[] = 'cookie2';
$this->assertSame( $expectedCookies, $cookies );
}
);
$this->assertSame( $expectedCookies, $op->getCacheVaryCookies() );
}
public function testHaveCacheVaryCookies() {
$request = new FauxRequest();
$op = $this->newInstance( [], $request );
// No cookies are set.
$this->assertFalse( $op->haveCacheVaryCookies() );
// 'Token' is present but empty, so it shouldn't count.
$request->setCookie( 'Token', '' );
$this->assertFalse( $op->haveCacheVaryCookies() );
// 'Token' present and nonempty.
$request->setCookie( 'Token', '123' );
$this->assertTrue( $op->haveCacheVaryCookies() );
}
/**
* @dataProvider provideVaryHeaders
*
*
* @param array[] $calls For each array, call addVaryHeader() with those arguments
* @param string[] $cookies Array of cookie names to vary on
* @param string $vary Text of expected Vary header (including the 'Vary: ')
*/
public function testVaryHeaders( array $calls, array $cookies, $vary ) {
// Get rid of default Vary fields
$op = $this->getMockBuilder( OutputPage::class )
->setConstructorArgs( [ new RequestContext() ] )
->onlyMethods( [ 'getCacheVaryCookies' ] )
->getMock();
$op->method( 'getCacheVaryCookies' )
->willReturn( $cookies );
TestingAccessWrapper::newFromObject( $op )->mVaryHeader = [];
foreach ( $calls as $call ) {
$op->addVaryHeader( ...$call );
}
$this->assertEquals( $vary, $op->getVaryHeader(), 'Vary:' );
}
public static function provideVaryHeaders() {
return [
'No header' => [
[],
[],
'Vary: ',
],
'Single header' => [
[
[ 'Cookie' ],
],
[],
'Vary: Cookie',
],
'Non-unique headers' => [
[
[ 'Cookie' ],
[ 'Accept-Language' ],
[ 'Cookie' ],
],
[],
'Vary: Cookie, Accept-Language',
],
'Two headers with single options' => [
// Options are deprecated since 1.34
[
[ 'Cookie', [ 'param=phpsessid' ] ],
[ 'Accept-Language', [ 'substr=en' ] ],
],
[],
'Vary: Cookie, Accept-Language',
],
'One header with multiple options' => [
// Options are deprecated since 1.34
[
[ 'Cookie', [ 'param=phpsessid', 'param=userId' ] ],
],
[],
'Vary: Cookie',
],
'Duplicate option' => [
// Options are deprecated since 1.34
[
[ 'Cookie', [ 'param=phpsessid' ] ],
[ 'Cookie', [ 'param=phpsessid' ] ],
[ 'Accept-Language', [ 'substr=en', 'substr=en' ] ],
],
[],
'Vary: Cookie, Accept-Language',
],
'Same header, different options' => [
// Options are deprecated since 1.34
[
[ 'Cookie', [ 'param=phpsessid' ] ],
[ 'Cookie', [ 'param=userId' ] ],
],
[],
'Vary: Cookie',
],
'No header, vary cookies' => [
[],
[ 'cookie1', 'cookie2' ],
'Vary: Cookie',
],
'Cookie header with option plus vary cookies' => [
// Options are deprecated since 1.34
[
[ 'Cookie', [ 'param=cookie1' ] ],
],
[ 'cookie2', 'cookie3' ],
'Vary: Cookie',
],
'Non-cookie header plus vary cookies' => [
[
[ 'Accept-Language' ],
],
[ 'cookie' ],
'Vary: Accept-Language, Cookie',
],
'Cookie and non-cookie headers plus vary cookies' => [
// Options are deprecated since 1.34
[
[ 'Cookie', [ 'param=cookie1' ] ],
[ 'Accept-Language' ],
],
[ 'cookie2' ],
'Vary: Cookie, Accept-Language',
],
];
}
public function testVaryHeaderDefault() {
$op = $this->newInstance();
$this->assertSame( 'Vary: Accept-Encoding, Cookie', $op->getVaryHeader() );
}
/**
* @dataProvider provideLinkHeaders
*/
public function testLinkHeaders( array $headers, $result ) {
$op = $this->newInstance();
foreach ( $headers as $header ) {
$op->addLinkHeader( $header );
}
$this->assertEquals( $result, $op->getLinkHeader() );
}
public static function provideLinkHeaders() {
return [
[
[],
false
],
[
[ ';rel=preload;as=image' ],
'Link: ;rel=preload;as=image',
],
[
[
';rel=preload;as=image',
';rel=preload;as=image'
],
'Link: ;rel=preload;as=image,;' .
'rel=preload;as=image',
],
];
}
/**
* @dataProvider provideAddAcceptLanguage
*/
public function testAddAcceptLanguage(
$code, array $variants, $expected, array $options = []
) {
$req = new FauxRequest( in_array( 'varianturl', $options ) ? [ 'variant' => 'x' ] : [] );
$op = $this->newInstance( [], $req, in_array( 'notitle', $options ) ? 'notitle' : null );
if ( !in_array( 'notitle', $options ) ) {
$mockLang = $this->createMock( Language::class );
$mockLang->method( 'getCode' )->willReturn( $code );
$mockLanguageConverter = $this
->createMock( ILanguageConverter::class );
if ( in_array( 'varianturl', $options ) ) {
$mockLanguageConverter->expects( $this->never() )->method( $this->anything() );
} else {
$mockLanguageConverter->method( 'hasVariants' )->willReturn( count( $variants ) > 1 );
$mockLanguageConverter->method( 'getVariants' )->willReturn( $variants );
}
$languageConverterFactory = $this
->createMock( LanguageConverterFactory::class );
$languageConverterFactory
->method( 'getLanguageConverter' )
->willReturn( $mockLanguageConverter );
$this->setService(
'LanguageConverterFactory',
$languageConverterFactory
);
$mockTitle = $this->createMock( Title::class );
$mockTitle->method( 'getPageLanguage' )->willReturn( $mockLang );
$op->setTitle( $mockTitle );
}
// This will run addAcceptLanguage()
$op->sendCacheControl();
$this->assertSame( "Vary: $expected", $op->getVaryHeader() );
}
public static function provideAddAcceptLanguage() {
return [
'No variants' => [
'en',
[ 'en' ],
'Accept-Encoding, Cookie',
],
'One simple variant' => [
'en',
[ 'en', 'en-x-piglatin' ],
'Accept-Encoding, Cookie, Accept-Language',
],
'Multiple variants with BCP47 alternatives' => [
'zh',
[ 'zh', 'zh-hans', 'zh-cn', 'zh-tw' ],
'Accept-Encoding, Cookie, Accept-Language',
],
'No title' => [
'en',
[ 'en', 'en-x-piglatin' ],
'Accept-Encoding, Cookie',
[ 'notitle' ]
],
'Variant in URL' => [
'en',
[ 'en', 'en-x-piglatin' ],
'Accept-Encoding, Cookie',
[ 'varianturl' ]
],
];
}
public function testClickjacking() {
$op = $this->newInstance();
$this->assertTrue( $op->getPreventClickjacking() );
$op->setPreventClickjacking( false );
$this->assertFalse( $op->getPreventClickjacking() );
$op->setPreventClickjacking( true );
$this->assertTrue( $op->getPreventClickjacking() );
$op->setPreventClickjacking( false );
$this->assertFalse( $op->getPreventClickjacking() );
$pOut1 = $this->createParserOutputStub( 'getPreventClickjacking', true );
$op->addParserOutputMetadata( $pOut1 );
$this->assertTrue( $op->getPreventClickjacking() );
// The ParserOutput can't allow, only prevent
$pOut2 = $this->createParserOutputStub( 'getPreventClickjacking', false );
$op->addParserOutputMetadata( $pOut2 );
$this->assertTrue( $op->getPreventClickjacking() );
// Reset to test with addParserOutput()
$op->setPreventClickjacking( false );
$this->assertFalse( $op->getPreventClickjacking() );
$op->addParserOutput( $pOut1, ParserOptions::newFromAnon() );
$this->assertTrue( $op->getPreventClickjacking() );
$op->addParserOutput( $pOut2, ParserOptions::newFromAnon() );
$this->assertTrue( $op->getPreventClickjacking() );
}
/**
* @dataProvider provideGetFrameOptions
*/
public function testGetFrameOptions(
$breakFrames, $preventClickjacking, $editPageFrameOptions, $expected
) {
$op = $this->newInstance( [
MainConfigNames::BreakFrames => $breakFrames,
MainConfigNames::EditPageFrameOptions => $editPageFrameOptions,
] );
$op->setPreventClickjacking( $preventClickjacking );
$this->assertSame( $expected, $op->getFrameOptions() );
}
public static function provideGetFrameOptions() {
return [
'BreakFrames true' => [ true, false, false, 'DENY' ],
'Allow clickjacking locally' => [ false, false, 'DENY', false ],
'Allow clickjacking globally' => [ false, true, false, false ],
'DENY globally' => [ false, true, 'DENY', 'DENY' ],
'SAMEORIGIN' => [ false, true, 'SAMEORIGIN', 'SAMEORIGIN' ],
'BreakFrames with SAMEORIGIN' => [ true, true, 'SAMEORIGIN', 'DENY' ],
];
}
/**
* See ClientHtmlTest for full coverage.
*
* @dataProvider provideMakeResourceLoaderLink
*/
public function testMakeResourceLoaderLink( $args, $expectedHtml ) {
$this->overrideConfigValues( [
MainConfigNames::ResourceLoaderDebug => false,
MainConfigNames::LoadScript => 'http://127.0.0.1:8080/w/load.php',
MainConfigNames::CSPReportOnlyHeader => true,
] );
$class = new ReflectionClass( OutputPage::class );
$method = $class->getMethod( 'makeResourceLoaderLink' );
$method->setAccessible( true );
$ctx = new RequestContext();
$skinFactory = $this->getServiceContainer()->getSkinFactory();
$ctx->setSkin( $skinFactory->makeSkin( 'fallback' ) );
$ctx->setLanguage( 'en' );
$out = new OutputPage( $ctx );
$reflectCSP = new ReflectionClass( ContentSecurityPolicy::class );
$rl = $out->getResourceLoader();
$rl->setMessageBlobStore( $this->createMock( RL\MessageBlobStore::class ) );
$rl->setDependencyStore( $this->createMock( DependencyStore::class ) );
$rl->register( [
'test.foo' => [
'class' => ResourceLoaderTestModule::class,
'script' => 'mw.test.foo( { a: true } );',
'styles' => '.mw-test-foo { content: "style"; }',
],
'test.bar' => [
'class' => ResourceLoaderTestModule::class,
'script' => 'mw.test.bar( { a: true } );',
'styles' => '.mw-test-bar { content: "style"; }',
],
'test.baz' => [
'class' => ResourceLoaderTestModule::class,
'script' => 'mw.test.baz( { a: true } );',
'styles' => '.mw-test-baz { content: "style"; }',
],
'test.quux' => [
'class' => ResourceLoaderTestModule::class,
'script' => 'mw.test.baz( { token: 123 } );',
'styles' => '/* pref-animate=off */ .mw-icon { transition: none; }',
'group' => 'private',
],
'test.noscript' => [
'class' => ResourceLoaderTestModule::class,
'styles' => '.stuff { color: red; }',
'group' => 'noscript',
],
'test.group.foo' => [
'class' => ResourceLoaderTestModule::class,
'script' => 'mw.doStuff( "foo" );',
'group' => 'foo',
],
'test.group.bar' => [
'class' => ResourceLoaderTestModule::class,
'script' => 'mw.doStuff( "bar" );',
'group' => 'bar',
],
] );
$links = $method->invokeArgs( $out, $args );
$actualHtml = strval( $links );
$this->assertEquals( $expectedHtml, $actualHtml );
}
public static function provideMakeResourceLoaderLink() {
return [
// Single only=scripts load
[
[ 'test.foo', RL\Module::TYPE_SCRIPTS ],
""
],
// Multiple only=styles load
[
[ [ 'test.baz', 'test.foo', 'test.bar' ], RL\Module::TYPE_STYLES ],
''
],
// Private embed (only=scripts)
[
[ 'test.quux', RL\Module::TYPE_SCRIPTS ],
""
],
// Load private module (combined)
[
[ 'test.quux', RL\Module::TYPE_COMBINED ],
""
],
// Load no modules
[
[ [], RL\Module::TYPE_COMBINED ],
'',
],
// noscript group
[
[ 'test.noscript', RL\Module::TYPE_STYLES ],
''
],
// Load two modules in separate groups
[
[ [ 'test.group.foo', 'test.group.bar' ], RL\Module::TYPE_COMBINED ],
""
],
];
// phpcs:enable
}
/**
* @dataProvider provideBuildExemptModules
*/
public function testBuildExemptModules( array $exemptStyleModules, $expect ) {
$this->overrideConfigValues( [
MainConfigNames::ResourceLoaderDebug => false,
MainConfigNames::LoadScript => '/w/load.php',
// Stub wgCacheEpoch as it influences getVersionHash used for the
// urls in the expected HTML
MainConfigNames::CacheEpoch => '20140101000000',
] );
// Set up stubs
$ctx = new RequestContext();
$skinFactory = $this->getServiceContainer()->getSkinFactory();
$ctx->setSkin( $skinFactory->makeSkin( 'fallback' ) );
$ctx->setLanguage( 'en' );
$op = $this->getMockBuilder( OutputPage::class )
->setConstructorArgs( [ $ctx ] )
->onlyMethods( [ 'buildCssLinksArray' ] )
->getMock();
$op->method( 'buildCssLinksArray' )
->willReturn( [] );
/** @var OutputPage $op */
$rl = $op->getResourceLoader();
$rl->setMessageBlobStore( $this->createMock( RL\MessageBlobStore::class ) );
// Register custom modules
$rl->register( [
'example.site.a' => [ 'class' => ResourceLoaderTestModule::class, 'group' => 'site' ],
'example.site.b' => [ 'class' => ResourceLoaderTestModule::class, 'group' => 'site' ],
'example.user' => [ 'class' => ResourceLoaderTestModule::class, 'group' => 'user' ],
] );
$op = TestingAccessWrapper::newFromObject( $op );
$op->rlExemptStyleModules = $exemptStyleModules;
$expect = strtr( $expect, [
'{blankCombi}' => ResourceLoaderTestCase::BLANK_COMBI,
] );
$this->assertEquals(
$expect,
strval( $op->buildExemptModules() )
);
}
public static function provideBuildExemptModules() {
return [
'empty' => [
'exemptStyleModules' => [],
'',
],
'empty sets' => [
'exemptStyleModules' => [ 'site' => [], 'noscript' => [], 'private' => [], 'user' => [] ],
'',
],
'default logged-out' => [
'exemptStyleModules' => [ 'site' => [ 'site.styles' ] ],
'' . "\n" .
'',
],
'default logged-in' => [
'exemptStyleModules' => [ 'site' => [ 'site.styles' ], 'user' => [ 'user.styles' ] ],
'' . "\n" .
'' . "\n" .
'',
],
'custom modules' => [
'exemptStyleModules' => [
'site' => [ 'site.styles', 'example.site.a', 'example.site.b' ],
'user' => [ 'user.styles', 'example.user' ],
],
'' . "\n" .
'' . "\n" .
'' . "\n" .
'' . "\n" .
'',
],
];
// phpcs:enable
}
/**
* @dataProvider provideTransformFilePath
*/
public function testTransformResourcePath( $basePath, $uploadDir = null,
$uploadPath = null, $path = null, $expected = null
) {
if ( $path === null ) {
// Skip optional $uploadDir and $uploadPath
$path = $uploadDir;
$expected = $uploadPath;
$uploadDir = MW_INSTALL_PATH . '/images';
$uploadPath = "$basePath/images";
}
$conf = new HashConfig( [
MainConfigNames::ResourceBasePath => $basePath,
MainConfigNames::UploadDirectory => $uploadDir,
MainConfigNames::UploadPath => $uploadPath,
] );
// Some of these paths don't exist and will cause warnings
$actual = @OutputPage::transformResourcePath( $conf, $path );
$this->assertEquals( $expected ?: $path, $actual );
}
public static function provideTransformFilePath() {
$baseDir = dirname( __DIR__ ) . '/../data/media';
return [
// File that matches basePath, and exists. Hash found and appended.
[
'/w',
'/w/tests/phpunit/data/media/test.jpg',
'/w/tests/phpunit/data/media/test.jpg?edcf2'
],
// File that matches basePath, but not found on disk. Empty query.
[
'/w',
'/w/unknown.png',
'/w/unknown.png'
],
// File not matching basePath. Ignored.
[
'/w',
'/files/test.jpg'
],
// Empty string. Ignored.
[
'/w',
'',
''
],
// Similar path, but with domain component. Ignored.
[
'/w',
'//example.org/w/test.jpg'
],
[
'/w',
'https://www.example.org/w/test.jpg'
],
// Unrelated path with domain component. Ignored.
[
'/w',
'https://www.example.org/files/test.jpg'
],
[
'/w',
'//example.org/files/test.jpg'
],
// Unrelated path with domain, and empty base path (root mw install). Ignored.
[
'',
'https://www.example.org/files/test.jpg'
],
// T155310
[
'',
'//example.org/files/test.jpg'
],
// Check UploadPath before ResourceBasePath (T155146)
[
'',
'uploadDir' => $baseDir, 'uploadPath' => '/images',
'/images/test.jpg',
'/images/test.jpg?edcf2'
],
];
}
/**
* Tests a particular case of transformCssMedia, using the given input, globals,
* expected return, and message
*
* Asserts that $expectedReturn is returned.
*
* options['queryData'] - value of query string
* options['media'] - passed into the method under the same name
* options['expectedReturn'] - expected return value
* options['message'] - PHPUnit message for assertion
*
* @param array $args Key-value array of arguments as shown above
*/
protected function assertTransformCssMediaCase( $args ) {
$queryData = $args['queryData'] ?? [];
$fauxRequest = new FauxRequest( $queryData, false );
$this->setRequest( $fauxRequest );
$actualReturn = OutputPage::transformCssMedia( $args['media'] );
$this->assertSame( $args['expectedReturn'], $actualReturn, $args['message'] );
}
public function testPrintRequests() {
$this->assertTransformCssMediaCase( [
'queryData' => [ 'printable' => '1' ],
'media' => 'screen',
'expectedReturn' => null,
'message' => 'On printable request, screen returns null'
] );
$this->assertTransformCssMediaCase( [
'queryData' => [ 'printable' => '1' ],
'media' => self::SCREEN_MEDIA_QUERY,
'expectedReturn' => null,
'message' => 'On printable request, screen media query returns null'
] );
$this->assertTransformCssMediaCase( [
'queryData' => [ 'printable' => '1' ],
'media' => self::SCREEN_ONLY_MEDIA_QUERY,
'expectedReturn' => null,
'message' => 'On printable request, screen media query with only returns null'
] );
$this->assertTransformCssMediaCase( [
'queryData' => [ 'printable' => '1' ],
'media' => 'print',
'expectedReturn' => '',
'message' => 'On printable request, media print returns empty string'
] );
}
/**
* Test screen requests, without either query parameter set
*/
public function testScreenRequests() {
$this->assertTransformCssMediaCase( [
'media' => 'screen',
'expectedReturn' => 'screen',
'message' => 'On screen request, screen media type is preserved'
] );
$this->assertTransformCssMediaCase( [
'media' => 'handheld',
'expectedReturn' => 'handheld',
'message' => 'On screen request, handheld media type is preserved'
] );
$this->assertTransformCssMediaCase( [
'media' => self::SCREEN_MEDIA_QUERY,
'expectedReturn' => self::SCREEN_MEDIA_QUERY,
'message' => 'On screen request, screen media query is preserved.'
] );
$this->assertTransformCssMediaCase( [
'media' => self::SCREEN_ONLY_MEDIA_QUERY,
'expectedReturn' => self::SCREEN_ONLY_MEDIA_QUERY,
'message' => 'On screen request, screen media query with only is preserved.'
] );
$this->assertTransformCssMediaCase( [
'media' => 'print',
'expectedReturn' => 'print',
'message' => 'On screen request, print media type is preserved'
] );
}
public function testIsTOCEnabled() {
$op = $this->newInstance();
$this->assertFalse( $op->isTOCEnabled() );
$this->assertFalse( $op->getOutputFlag( ParserOutputFlags::SHOW_TOC ) );
$pOut1 = $this->createParserOutputStub();
$op->addParserOutputMetadata( $pOut1 );
$this->assertFalse( $op->isTOCEnabled() );
$this->assertFalse( $op->getOutputFlag( ParserOutputFlags::SHOW_TOC ) );
$pOut2 = $this->createParserOutputStubWithFlags(
[], [ ParserOutputFlags::SHOW_TOC ]
);
$op->addParserOutput( $pOut2, ParserOptions::newFromAnon() );
$this->assertTrue( $op->isTOCEnabled() );
$this->assertTrue( $op->getOutputFlag( ParserOutputFlags::SHOW_TOC ) );
// The parser output doesn't disable the TOC after it was enabled
$op->addParserOutputMetadata( $pOut1 );
$this->assertTrue( $op->isTOCEnabled() );
$this->assertTrue( $op->getOutputFlag( ParserOutputFlags::SHOW_TOC ) );
}
public function testNoTOC() {
$op = $this->newInstance();
$this->assertFalse( $op->getOutputFlag( ParserOutputFlags::NO_TOC ) );
$stubPO1 = $this->createParserOutputStubWithFlags(
[], [ ParserOutputFlags::NO_TOC ]
);
$op->addParserOutputMetadata( $stubPO1 );
$this->assertTrue( $op->getOutputFlag( ParserOutputFlags::NO_TOC ) );
$stubPO2 = $this->createParserOutputStub();
$this->assertFalse( $stubPO2->getOutputFlag( ParserOutputFlags::NO_TOC ) );
$op->addParserOutput( $stubPO2, ParserOptions::newFromAnon() );
// Note that flags are OR'ed together, and not reset.
$this->assertTrue( $op->getOutputFlag( ParserOutputFlags::NO_TOC ) );
}
/**
* @dataProvider providePreloadLinkHeaders
* @covers \MediaWiki\ResourceLoader\SkinModule
*/
public function testPreloadLinkHeaders( $config, $result ) {
$ctx = $this->createMock( RL\Context::class );
$module = new RL\SkinModule();
$module->setConfig( new HashConfig( $config + ResourceLoaderTestCase::getSettings() ) );
$this->assertEquals( [ $result ], $module->getHeaders( $ctx ) );
}
public static function providePreloadLinkHeaders() {
return [
[
[
MainConfigNames::ResourceBasePath => '/w',
MainConfigNames::Logo => '/img/default.png',
MainConfigNames::Logos => [
'1.5x' => '/img/one-point-five.png',
'2x' => '/img/two-x.png',
],
],
'Link: ;rel=preload;as=image;media=' .
'not all and (min-resolution: 1.5dppx),' .
';rel=preload;as=image;media=' .
'(min-resolution: 1.5dppx) and (max-resolution: 1.999999dppx),' .
';rel=preload;as=image;media=(min-resolution: 2dppx)'
],
[
[
MainConfigNames::ResourceBasePath => '/w',
MainConfigNames::Logos => [
'1x' => '/img/default.png',
],
],
'Link: ;rel=preload;as=image'
],
[
[
MainConfigNames::ResourceBasePath => '/w',
MainConfigNames::Logos => [
'1x' => '/img/default.png',
'2x' => '/img/two-x.png',
],
],
'Link: ;rel=preload;as=image;media=' .
'not all and (min-resolution: 2dppx),' .
';rel=preload;as=image;media=(min-resolution: 2dppx)'
],
[
[
MainConfigNames::ResourceBasePath => '/w',
MainConfigNames::Logos => [
'1x' => '/img/default.png',
'svg' => '/img/vector.svg',
],
],
'Link: ;rel=preload;as=image'
],
[
[
MainConfigNames::ResourceBasePath => '/w',
MainConfigNames::Logos => [
'1x' => '/w/tests/phpunit/data/media/test.jpg',
],
MainConfigNames::UploadPath => '/w/images',
],
'Link: ;rel=preload;as=image',
],
];
}
/**
* @param int $titleLastRevision Last Title revision to set
* @param int $outputRevision Revision stored in OutputPage
* @param bool $expectedResult Expected result of $output->isRevisionCurrent call
* @dataProvider provideIsRevisionCurrent
*/
public function testIsRevisionCurrent( $titleLastRevision, $outputRevision, $expectedResult ) {
$titleMock = $this->createMock( Title::class );
$titleMock->method( 'getLatestRevID' )
->willReturn( $titleLastRevision );
$output = $this->newInstance( [], null );
$output->setTitle( $titleMock );
$output->setRevisionId( $outputRevision );
$this->assertEquals( $expectedResult, $output->isRevisionCurrent() );
}
public static function provideIsRevisionCurrent() {
return [
[ 10, null, true ],
[ 42, 42, true ],
[ null, 0, true ],
[ 42, 47, false ],
[ 47, 42, false ]
];
}
/**
* @dataProvider provideSendCacheControl
*/
public function testSendCacheControl( array $options = [], array $expectations = [] ) {
$this->overrideConfigValue( MainConfigNames::UsePigLatinVariant, $options['variant'] ?? false );
$output = $this->newInstance( [
MainConfigNames::UseCdn => $options['useCdn'] ?? false,
] );
$output->considerCacheSettingsFinal();
$cacheable = $options['enableClientCache'] ?? true;
if ( !$cacheable ) {
$output->disableClientCache();
}
$this->assertEquals( $cacheable, $output->couldBePublicCached() );
$output->setCdnMaxage( $options['cdnMaxAge'] ?? 0 );
if ( isset( $options['lastModified'] ) ) {
$output->setLastModified( $options['lastModified'] );
}
$response = $output->getRequest()->response();
if ( isset( $options['cookie'] ) ) {
$response->setCookie( 'test', 1234 );
}
$output->sendCacheControl();
$headers = [
'Vary' => 'Accept-Encoding, Cookie',
'Cache-Control' => 'private, must-revalidate, max-age=0',
'Expires' => true,
'Last-Modified' => false,
];
foreach ( $headers as $header => $default ) {
$value = $expectations[$header] ?? $default;
if ( $value === true ) {
$this->assertNotEmpty( $response->getHeader( $header ), "$header header" );
} elseif ( $value === false ) {
$this->assertNull( $response->getHeader( $header ), "$header header" );
} else {
$this->assertEquals( $value, $response->getHeader( $header ), "$header header" );
}
}
}
public static function provideSendCacheControl() {
return [
'Vary on variant' => [
[
'variant' => true,
],
[
'Vary' => 'Accept-Encoding, Cookie, Accept-Language',
]
],
'Private by default' => [
[],
[
'Cache-Control' => 'private, must-revalidate, max-age=0',
],
],
'Cookies force private' => [
[
'cookie' => true,
'useCdn' => true,
'cdnMaxAge' => 300,
],
[
'Cache-Control' => 'private, must-revalidate, max-age=0',
]
],
'Disable client cache' => [
[
'enableClientCache' => false,
'useCdn' => true,
'cdnMaxAge' => 300,
],
[
'Cache-Control' => 'no-cache, no-store, max-age=0, must-revalidate',
],
],
'Set last modified' => [
[
// 0 is the current time, so we'll use 1 instead.
'lastModified' => 1,
],
[
'Last-Modified' => 'Thu, 01 Jan 1970 00:00:01 GMT',
]
],
'Public' => [
[
'useCdn' => true,
'cdnMaxAge' => 300,
],
[
'Cache-Control' => 's-maxage=300, must-revalidate, max-age=0',
'Expires' => false,
],
],
];
}
public function provideGetJsVarsEditable() {
yield 'can edit and create' => [
'performer' => $this->mockAnonAuthorityWithPermissions( [ 'edit', 'create' ] ),
'expectedEditableConfig' => [
'wgIsProbablyEditable' => true,
'wgRelevantPageIsProbablyEditable' => true,
]
];
yield 'cannot edit or create' => [
'performer' => $this->mockAnonAuthorityWithoutPermissions( [ 'edit', 'create' ] ),
'expectedEditableConfig' => [
'wgIsProbablyEditable' => false,
'wgRelevantPageIsProbablyEditable' => false,
]
];
yield 'only can edit relevant title' => [
'performer' => $this->mockAnonAuthority( static function (
string $permission,
PageIdentity $page
) {
return ( $permission === 'edit' || $permission === 'create' ) && $page->getDBkey() === 'RelevantTitle';
} ),
'expectedEditableConfig' => [
'wgIsProbablyEditable' => false,
'wgRelevantPageIsProbablyEditable' => true,
]
];
}
/**
* @dataProvider provideGetJsVarsEditable
*/
public function testGetJsVarsEditable( Authority $performer, array $expectedEditableConfig ) {
$op = $this->newInstance( [], null, null, $performer );
$op->getContext()->getSkin()->setRelevantTitle( Title::makeTitle( NS_MAIN, 'RelevantTitle' ) );
$this->assertArraySubmapSame( $expectedEditableConfig, $op->getJSVars() );
}
public function provideJsVarsAboutPageLang() {
// Format:
// - expected
// - title
// - site content language
// - user language
// - wgDefaultLanguageVariant
return [
[ 'fr', [ NS_HELP, 'I_need_somebody' ], 'fr', 'fr', false ],
[ 'es', [ NS_HELP, 'I_need_somebody' ], 'es', 'zh-tw', false ],
[ 'zh', [ NS_HELP, 'I_need_somebody' ], 'zh', 'zh-tw', false ],
[ 'es', [ NS_HELP, 'I_need_somebody' ], 'es', 'zh-tw', 'zh-cn' ],
[ 'es', [ NS_MEDIAWIKI, 'About' ], 'es', 'zh-tw', 'zh-cn' ],
[ 'es', [ NS_MEDIAWIKI, 'About/' ], 'es', 'zh-tw', 'zh-cn' ],
[ 'de', [ NS_MEDIAWIKI, 'About/de' ], 'es', 'zh-tw', 'zh-cn' ],
[ 'en', [ NS_MEDIAWIKI, 'Common.js' ], 'es', 'zh-tw', 'zh-cn' ],
[ 'en', [ NS_MEDIAWIKI, 'Common.css' ], 'es', 'zh-tw', 'zh-cn' ],
[ 'en', [ NS_USER, 'JohnDoe/Common.js' ], 'es', 'zh-tw', 'zh-cn' ],
[ 'en', [ NS_USER, 'JohnDoe/Monobook.css' ], 'es', 'zh-tw', 'zh-cn' ],
[ 'zh-cn', [ NS_HELP, 'I_need_somebody' ], 'zh', 'zh-tw', 'zh-cn' ],
[ 'zh', [ NS_MEDIAWIKI, 'About' ], 'zh', 'zh-tw', 'zh-cn' ],
[ 'zh', [ NS_MEDIAWIKI, 'About/' ], 'zh', 'zh-tw', 'zh-cn' ],
[ 'de', [ NS_MEDIAWIKI, 'About/de' ], 'zh', 'zh-tw', 'zh-cn' ],
[ 'zh-cn', [ NS_MEDIAWIKI, 'About/zh-cn' ], 'zh', 'zh-tw', 'zh-cn' ],
[ 'zh-tw', [ NS_MEDIAWIKI, 'About/zh-tw' ], 'zh', 'zh-tw', 'zh-cn' ],
[ 'en', [ NS_MEDIAWIKI, 'Common.js' ], 'zh', 'zh-tw', 'zh-cn' ],
[ 'en', [ NS_MEDIAWIKI, 'Common.css' ], 'zh', 'zh-tw', 'zh-cn' ],
[ 'en', [ NS_USER, 'JohnDoe/Common.js' ], 'zh', 'zh-tw', 'zh-cn' ],
[ 'en', [ NS_USER, 'JohnDoe/Monobook.css' ], 'zh', 'zh-tw', 'zh-cn' ],
[ 'nl', [ NS_SPECIAL, 'BlankPage' ], 'en', 'nl', false ],
[ 'zh-tw', [ NS_SPECIAL, 'NewPages' ], 'es', 'zh-tw', 'zh-cn' ],
[ 'zh-tw', [ NS_SPECIAL, 'NewPages' ], 'zh', 'zh-tw', 'zh-cn' ],
[ 'sr-ec', [ NS_FILE, 'Example' ], 'sr', 'sr', 'sr-ec' ],
[ 'sr', [ NS_FILE, 'Example' ], 'sr', 'sr', 'sr' ],
[ 'sr-ec', [ NS_MEDIAWIKI, 'Example' ], 'sr-ec', 'sr-ec', 'sr' ],
[ 'sr', [ NS_MEDIAWIKI, 'Example' ], 'sr', 'sr', 'sr-ec' ],
];
}
/**
* @dataProvider provideJsVarsAboutPageLang
*/
public function testGetJsVarsAboutPageLang( $expected, $title, $contLang, $userLang, $variant ) {
$this->overrideConfigValues( [
MainConfigNames::DefaultLanguageVariant => $variant,
] );
$this->setContentLang( $contLang );
$output = $this->newInstance(
[ MainConfigNames::LanguageCode => $contLang ],
new FauxRequest( [ 'uselang' => $userLang ] ),
'notitle'
);
$output->setTitle( Title::makeTitle( $title[0], $title[1] ) );
$this->assertArraySubmapSame( [
'wgPageViewLanguage' => $expected,
'wgPageContentLanguage' => $expected,
], $output->getJSVars() );
}
/**
* @param bool $registered
* @param bool $matchToken
* @return MockObject|User
*/
private function mockUser( bool $registered, bool $matchToken ) {
$user = $this->createNoOpMock( User::class, [ 'isRegistered', 'matchEditToken' ] );
$user->method( 'isRegistered' )->willReturn( $registered );
$user->method( 'matchEditToken' )->willReturn( $matchToken );
return $user;
}
public function provideUserCanPreview() {
yield 'all good' => [
'performer' => $this->mockUserAuthorityWithPermissions(
$this->mockUser( true, true ),
[ 'edit' ]
),
'request' => new FauxRequest( [ 'action' => 'submit' ], true ),
true
];
yield 'get request' => [
'performer' => $this->mockUserAuthorityWithPermissions(
$this->mockUser( true, true ),
[ 'edit' ]
),
'request' => new FauxRequest( [ 'action' => 'submit' ], false ),
false
];
yield 'not a submit action' => [
'performer' => $this->mockUserAuthorityWithPermissions(
$this->mockUser( true, true ),
[ 'edit' ]
),
'request' => new FauxRequest( [ 'action' => 'something' ], true ),
false
];
yield 'anon can not' => [
'performer' => $this->mockUserAuthorityWithPermissions(
$this->mockUser( false, true ),
[ 'edit' ]
),
'request' => new FauxRequest( [ 'action' => 'submit' ], true ),
false
];
yield 'token not match' => [
'performer' => $this->mockUserAuthorityWithPermissions(
$this->mockUser( true, false ),
[ 'edit' ]
),
'request' => new FauxRequest( [ 'action' => 'submit' ], true ),
false
];
yield 'no permission' => [
'performer' => $this->mockUserAuthorityWithoutPermissions(
$this->mockUser( true, true ),
[ 'edit' ]
),
'request' => new FauxRequest( [ 'action' => 'submit' ], true ),
false
];
}
/**
* @dataProvider provideUserCanPreview
*/
public function testUserCanPreview( Authority $performer, WebRequest $request, bool $expected ) {
$op = $this->newInstance( [], $request, null, $performer );
$this->assertSame( $expected, $op->userCanPreview() );
}
public function providePermissionStatus() {
yield 'no errors' => [
PermissionStatus::newEmpty(),
'',
];
yield 'one message' => [
PermissionStatus::newEmpty()->fatal( 'badaccess-group0' ),
'(permissionserrorstext: 1)
',
];
yield 'two messages' => [
PermissionStatus::newEmpty()->fatal( 'badaccess-group0' )->fatal( 'foobar' ),
'(permissionserrorstext: 2)
- (badaccess-group0)
- (foobar)
',
];
}
public function provideFormatPermissionStatus() {
yield 'RawMessage' => [
PermissionStatus::newEmpty()->fatal( new RawMessage( 'Foo Bar' ) ),
'(permissionserrorstext: 1)
',
];
}
public function provideFormatPermissionsErrorMessage() {
yield 'RawMessage' => [
PermissionStatus::newEmpty()->fatal( new RawMessage( 'Foo Bar' ) ),
'(permissionserrorstext: 1)
',
];
}
/**
* @dataProvider providePermissionStatus
* @dataProvider provideFormatPermissionStatus
*/
public function testFormatPermissionStatus( PermissionStatus $status, string $expected ) {
$this->overrideConfigValue( MainConfigNames::LanguageCode, 'qqx' );
$actual = self::newInstance()->formatPermissionStatus( $status );
$this->assertEquals( $expected, $actual );
}
/**
* @dataProvider providePermissionStatus
* @dataProvider provideFormatPermissionsErrorMessage
*/
public function testFormatPermissionsErrorMessage( PermissionStatus $status, string $expected ) {
$this->overrideConfigValue( MainConfigNames::LanguageCode, 'qqx' );
$this->filterDeprecated( '/OutputPage::formatPermissionsErrorMessage was deprecated/' );
$this->filterDeprecated( '/toLegacyErrorArray/' );
// Unlike formatPermissionStatus, this method doesn't accept good statuses
$actual = $status->isGood() ? '' :
self::newInstance()->formatPermissionsErrorMessage( $status->toLegacyErrorArray() );
$this->assertEquals( $expected, $actual );
}
private function newInstance(
array $config = [],
?WebRequest $request = null,
$option = null,
?Authority $performer = null
): OutputPage {
$this->overrideConfigValues( [
// Avoid configured skin affecting the headings
MainConfigNames::ParserEnableLegacyHeadingDOM => false,
MainConfigNames::DefaultSkin => 'fallback',
MainConfigNames::HiddenPrefs => [ 'skin' ],
] );
$context = new RequestContext();
$context->setConfig( new MultiConfig( [
new HashConfig( $config + [
MainConfigNames::AppleTouchIcon => false,
MainConfigNames::EnableCanonicalServerLink => false,
MainConfigNames::Favicon => false,
MainConfigNames::Feed => false,
MainConfigNames::LanguageCode => false,
MainConfigNames::ReferrerPolicy => false,
MainConfigNames::RightsPage => false,
MainConfigNames::RightsUrl => false,
MainConfigNames::UniversalEditButton => false,
] ),
$this->getServiceContainer()->getMainConfig(),
] ) );
if ( $option !== 'notitle' ) {
$context->setTitle( Title::makeTitle( NS_MAIN, 'My test page' ) );
}
if ( $request ) {
$context->setRequest( $request );
}
if ( $performer ) {
$context->setAuthority( $performer );
}
return new OutputPage( $context );
}
}