' . "\nMy message\n
"
], 'List at start' => [
[ '* List' ],
"{{PAGENAME}}", true, Title::newFromText( 'Talk:Some page' ) ],
'
' . "Some page\n
"
],
],
];
// Test all the others on addWikiTextTitle as well
foreach ( $tests['addWikiText'] as $key => $val ) {
$args = [ $val[0][0], null, $val[0][1] ?? true, false, $val[0][2] ?? true ];
$tests['addWikiTextTitle']["$key (addWikiTextTitle)"] =
array_merge( [ $args ], array_slice( $val, 1 ) );
}
foreach ( $tests['addWikiTextWithTitle'] as $key => $val ) {
$args = [ $val[0][0], $val[0][1], $val[0][2] ?? true ];
$tests['addWikiTextTitle']["$key (addWikiTextTitle)"] =
array_merge( [ $args ], array_slice( $val, 1 ) );
}
foreach ( $tests['addWikiTextAsInterface'] as $key => $val ) {
$args = [ $val[0][0], $val[0][2] ?? null, $val[0][1] ?? true, true, true ];
$tests['addWikiTextTitle']["$key (addWikiTextTitle)"] =
array_merge( [ $args ], array_slice( $val, 1 ) );
}
foreach ( $tests['addWikiTextAsContent'] as $key => $val ) {
$args = [ $val[0][0], $val[0][2] ?? null, $val[0][1] ?? true, true, false ];
$tests['addWikiTextTitle']["$key (addWikiTextTitle)"] =
array_merge( [ $args ], array_slice( $val, 1 ) );
}
// addWikiTextTidy / addWikiTextTitleTidy were old aliases of
// addWikiTextAsContent
foreach ( $tests['addWikiTextAsContent'] as $key => $val ) {
if ( count( $val[0] ) > 2 ) {
$args = [ $val[0][0], $val[0][2], $val[0][1] ?? true ];
$tests['addWikiTextTitleTidy']["$key (addWikiTextTitleTidy)"] =
array_merge( [ $args ], array_slice( $val, 1 ) );
} else {
$args = [ $val[0][0], $val[0][1] ?? true ];
$tests['addWikiTextTidy']["$key (addWikiTextTidy)"] =
array_merge( [ $args ], array_slice( $val, 1 ) );
}
}
// 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;
}
/**
* @covers OutputPage::addWikiText
*/
public function testAddWikiTextNoTitle() {
$this->setExpectedException( MWException::class, 'Title is null' );
$op = $this->newInstance( [], null, 'notitle' );
$op->addWikiText( 'a' );
}
/**
* @covers OutputPage::addWikiTextAsInterface
*/
public function testAddWikiTextAsInterfaceNoTitle() {
$this->setExpectedException( MWException::class, 'Title is null' );
$op = $this->newInstance( [], null, 'notitle' );
$op->addWikiTextAsInterface( 'a' );
}
/**
* @covers OutputPage::addWikiTextAsContent
*/
public function testAddWikiTextAsContentNoTitle() {
$this->setExpectedException( MWException::class, 'Title is null' );
$op = $this->newInstance( [], null, 'notitle' );
$op->addWikiTextAsContent( 'a' );
}
/**
* @covers OutputPage::addWikiMsg
*/
public function testAddWikiMsg() {
$msg = wfMessage( 'parentheses' );
$this->assertSame( '(a)', $msg->rawParams( 'a' )->plain() );
$op = $this->newInstance();
$this->assertSame( '', $op->getHTML() );
$op->addWikiMsg( 'parentheses', "
a" );
// This is known to be bad unbalanced HTML; this will be fixed
// by I743f4185a03403f8d9b9db010ff1ee4e9342e062 (T198214)
$this->assertSame( " (a)\n
", $op->getHTML() );
}
/**
* @covers OutputPage::wrapWikiMsg
*/
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" ] );
// This is known to be bad unbalanced HTML; this will be fixed
// by I743f4185a03403f8d9b9db010ff1ee4e9342e062 (T198214)
$this->assertSame( " [(a)]\n
", $op->getHTML() );
}
/**
* @covers OutputPage::addParserOutputMetadata
* @covers OutputPage::addParserOutput
*/
public function testNoGallery() {
$op = $this->newInstance();
$this->assertFalse( $op->mNoGallery );
$stubPO1 = $this->createParserOutputStub( 'getNoGallery', true );
$op->addParserOutputMetadata( $stubPO1 );
$this->assertTrue( $op->mNoGallery );
$stubPO2 = $this->createParserOutputStub( 'getNoGallery', false );
$op->addParserOutput( $stubPO2 );
$this->assertFalse( $op->mNoGallery );
}
private static $parserOutputHookCalled;
/**
* @covers OutputPage::addParserOutputMetadata
*/
public function testParserOutputHooks() {
$op = $this->newInstance();
$pOut = $this->createParserOutputStub( 'getOutputHooks', [
[ 'myhook', 'banana' ],
[ 'yourhook', 'kumquat' ],
[ 'theirhook', 'hippopotamus' ],
] );
self::$parserOutputHookCalled = [];
$this->setMwGlobals( 'wgParserOutputHooks', [
'myhook' => function ( OutputPage $innerOp, ParserOutput $innerPOut, $data )
use ( $op, $pOut ) {
$this->assertSame( $op, $innerOp );
$this->assertSame( $pOut, $innerPOut );
$this->assertSame( 'banana', $data );
self::$parserOutputHookCalled[] = 'closure';
},
'yourhook' => [ $this, 'parserOutputHookCallback' ],
'theirhook' => [ __CLASS__, 'parserOutputHookCallbackStatic' ],
'uncalled' => function () {
$this->assertTrue( false );
},
] );
$op->addParserOutputMetadata( $pOut );
$this->assertSame( [ 'closure', 'callback', 'static' ], self::$parserOutputHookCalled );
}
public function parserOutputHookCallback(
OutputPage $op, ParserOutput $pOut, $data
) {
$this->assertSame( 'kumquat', $data );
self::$parserOutputHookCalled[] = 'callback';
}
public static function parserOutputHookCallbackStatic(
OutputPage $op, ParserOutput $pOut, $data
) {
// All the assert methods are actually static, who knew!
self::assertSame( 'hippopotamus', $data );
self::$parserOutputHookCalled[] = 'static';
}
// @todo Make sure to test the following in addParserOutputMetadata() as well when we add tests
// for them:
// * addModules()
// * addModuleScripts()
// * addModuleStyles()
// * addJsConfigVars()
// * enableOOUI()
// Otherwise those lines of addParserOutputMetadata() will be reported as covered, but we won't
// be testing they actually work.
/**
* @covers OutputPage::addParserOutputText
*/
public function testAddParserOutputText() {
$op = $this->newInstance();
$this->assertSame( '', $op->getHTML() );
$pOut = $this->createParserOutputStub( 'getText', '
' );
$op->addParserOutputMetadata( $pOut );
$this->assertSame( '', $op->getHTML() );
$op->addParserOutputText( $pOut );
$this->assertSame( '', $op->getHTML() );
}
/**
* @covers OutputPage::addParserOutput
*/
public function testAddParserOutput() {
$op = $this->newInstance();
$this->assertSame( '', $op->getHTML() );
$this->assertFalse( $op->showNewSectionLink() );
$pOut = $this->createParserOutputStub( [
'getText' => '',
'getNewSection' => true,
] );
$op->addParserOutput( $pOut );
$this->assertSame( '', $op->getHTML() );
$this->assertTrue( $op->showNewSectionLink() );
}
/**
* @covers OutputPage::addTemplate
*/
public function testAddTemplate() {
$template = $this->getMock( QuickTemplate::class );
$template->method( 'getHTML' )->willReturn( '&def;' );
$op = $this->newInstance();
$op->addTemplate( $template );
$this->assertSame( '&def;', $op->getHTML() );
}
/**
* @dataProvider provideParse
* @covers OutputPage::parse
* @param array $args To pass to parse()
* @param string $expectedHTML Expected return value for parse()
* @param string $expectedHTML Expected return value for parseInline(), if different
*/
public function testParse( array $args, $expectedHTML ) {
$op = $this->newInstance();
$this->assertSame( $expectedHTML, $op->parse( ...$args ) );
}
/**
* @dataProvider provideParse
* @covers OutputPage::parseInline
*/
public function testParseInline( array $args, $expectedHTML, $expectedHTMLInline = null ) {
if ( count( $args ) > 3 ) {
// $language param not supported
$this->assertTrue( true );
return;
}
$op = $this->newInstance();
$this->assertSame( $expectedHTMLInline ?? $expectedHTML, $op->parseInline( ...$args ) );
}
public function provideParse() {
return [
'List at start of line' => [
[ '* List' ],
"",
],
'List not at start' => [
[ "* ''Not'' list", false ],
'* Not list
',
],
'Interface' => [
[ "''Italic''", true, true ],
"Italic \n
",
'Italic ',
],
'formatnum' => [
[ '{{formatnum:123456.789}}' ],
"",
],
'Language' => [
[ '{{formatnum:123456.789}}', true, false, Language::factory( 'is' ) ],
"",
],
'Language with interface' => [
[ '{{formatnum:123456.789}}', true, true, Language::factory( 'is' ) ],
"123.456,789\n
",
'123.456,789',
],
'No section edit links' => [
[ '== Header ==' ],
'
\n",
]
];
}
/**
* @covers OutputPage::parse
*/
public function testParseNullTitle() {
$this->setExpectedException( MWException::class, 'Empty $mTitle in OutputPage::parse' );
$op = $this->newInstance( [], null, 'notitle' );
$op->parse( '' );
}
/**
* @covers OutputPage::parse
*/
public function testParseInlineNullTitle() {
$this->setExpectedException( MWException::class, 'Empty $mTitle in OutputPage::parse' );
$op = $this->newInstance( [], null, 'notitle' );
$op->parseInline( '' );
}
/**
* @covers OutputPage::setCdnMaxage
* @covers OutputPage::lowerCdnMaxage
*/
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
* @covers OutputPage::adaptCdnTTL
* @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 = [] ) {
try {
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 );
} finally {
MWTimestamp::setFakeTime( false );
}
$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 function provideAdaptCdnTTL() {
global $wgSquidMaxage;
$now = time();
self::$fakeTime = $now;
return [
'Five minutes ago' => [ [ $now - 300 ], 270 ],
'Now' => [ [ +0 ], IExpiringStore::TTL_MINUTE ],
'Five minutes from now' => [ [ $now + 300 ], IExpiringStore::TTL_MINUTE ],
'Five minutes ago, initial maxage four minutes' =>
[ [ $now - 300 ], 270, [ 'initialMaxage' => 240 ] ],
'A very long time ago' => [ [ $now - 1000000000 ], $wgSquidMaxage ],
'Initial maxage zero' => [ [ $now - 300 ], 270, [ 'initialMaxage' => 0 ] ],
'false' => [ [ false ], IExpiringStore::TTL_MINUTE ],
'null' => [ [ null ], IExpiringStore::TTL_MINUTE ],
"'0'" => [ [ '0' ], IExpiringStore::TTL_MINUTE ],
'Empty string' => [ [ '' ], IExpiringStore::TTL_MINUTE ],
// @todo These give incorrect results due to timezones, how to test?
//"'now'" => [ [ 'now' ], IExpiringStore::TTL_MINUTE ],
//"'parse error'" => [ [ 'parse error' ], IExpiringStore::TTL_MINUTE ],
'Now, minTTL 0' => [ [ $now, 0 ], IExpiringStore::TTL_MINUTE ],
'Now, minTTL 0.000001' => [ [ $now, 0.000001 ], 0 ],
'A very long time ago, maxTTL even longer' =>
[ [ $now - 1000000000, 0, 1000000001 ], 900000000 ],
];
}
/**
* @covers OutputPage::enableClientCache
* @covers OutputPage::addParserOutputMetadata
* @covers OutputPage::addParserOutput
*/
public function testClientCache() {
$op = $this->newInstance();
// Test initial value
$this->assertSame( true, $op->enableClientCache( null ) );
// Test that calling with null doesn't change the value
$this->assertSame( true, $op->enableClientCache( null ) );
// Test setting to false
$this->assertSame( true, $op->enableClientCache( false ) );
$this->assertSame( false, $op->enableClientCache( null ) );
// Test that calling with null doesn't change the value
$this->assertSame( false, $op->enableClientCache( null ) );
// Test that a cacheable ParserOutput doesn't set to true
$pOutCacheable = $this->createParserOutputStub( 'isCacheable', true );
$op->addParserOutputMetadata( $pOutCacheable );
$this->assertSame( false, $op->enableClientCache( null ) );
// Test setting back to true
$this->assertSame( false, $op->enableClientCache( true ) );
$this->assertSame( true, $op->enableClientCache( null ) );
// Test that an uncacheable ParserOutput does set to false
$pOutUncacheable = $this->createParserOutputStub( 'isCacheable', false );
$op->addParserOutput( $pOutUncacheable );
$this->assertSame( false, $op->enableClientCache( null ) );
}
/**
* @covers OutputPage::getCacheVaryCookies
*/
public function testGetCacheVaryCookies() {
global $wgCookiePrefix, $wgDBname;
$op = $this->newInstance();
$prefix = $wgCookiePrefix !== false ? $wgCookiePrefix : $wgDBname;
$expectedCookies = [
"{$prefix}Token",
"{$prefix}LoggedOut",
"{$prefix}_session",
'forceHTTPS',
'cookie1',
'cookie2',
];
// We have to reset the cookies because getCacheVaryCookies may have already been called
TestingAccessWrapper::newFromClass( OutputPage::class )->cacheVaryCookies = null;
$this->setMwGlobals( 'wgCacheVaryCookies', [ 'cookie1' ] );
$this->setTemporaryHook( 'GetCacheVaryCookies',
function ( $innerOP, &$cookies ) use ( $op, $expectedCookies ) {
$this->assertSame( $op, $innerOP );
$cookies[] = 'cookie2';
$this->assertSame( $expectedCookies, $cookies );
}
);
$this->assertSame( $expectedCookies, $op->getCacheVaryCookies() );
}
/**
* @covers OutputPage::haveCacheVaryCookies
*/
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
*
* @covers OutputPage::addVaryHeader
* @covers OutputPage::getVaryHeader
* @covers OutputPage::getKeyHeader
*
* @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: ')
* @param string $key Text of expected Key header (including the 'Key: ')
*/
public function testVaryHeaders( array $calls, array $cookies, $vary, $key ) {
// Get rid of default Vary fields
$op = $this->getMockBuilder( OutputPage::class )
->setConstructorArgs( [ new RequestContext() ] )
->setMethods( [ 'getCacheVaryCookies' ] )
->getMock();
$op->expects( $this->any() )
->method( 'getCacheVaryCookies' )
->will( $this->returnValue( $cookies ) );
TestingAccessWrapper::newFromObject( $op )->mVaryHeader = [];
$this->hideDeprecated( '$wgUseKeyHeader' );
foreach ( $calls as $call ) {
$op->addVaryHeader( ...$call );
}
$this->assertEquals( $vary, $op->getVaryHeader(), 'Vary:' );
$this->assertEquals( $key, $op->getKeyHeader(), 'Key:' );
}
public function provideVaryHeaders() {
// note: getKeyHeader() automatically adds Vary: Cookie
return [
'No header' => [
[],
[],
'Vary: ',
'Key: Cookie',
],
'Single header' => [
[
[ 'Cookie' ],
],
[],
'Vary: Cookie',
'Key: Cookie',
],
'Non-unique headers' => [
[
[ 'Cookie' ],
[ 'Accept-Language' ],
[ 'Cookie' ],
],
[],
'Vary: Cookie, Accept-Language',
'Key: Cookie,Accept-Language',
],
'Two headers with single options' => [
[
[ 'Cookie', [ 'param=phpsessid' ] ],
[ 'Accept-Language', [ 'substr=en' ] ],
],
[],
'Vary: Cookie, Accept-Language',
'Key: Cookie;param=phpsessid,Accept-Language;substr=en',
],
'One header with multiple options' => [
[
[ 'Cookie', [ 'param=phpsessid', 'param=userId' ] ],
],
[],
'Vary: Cookie',
'Key: Cookie;param=phpsessid;param=userId',
],
'Duplicate option' => [
[
[ 'Cookie', [ 'param=phpsessid' ] ],
[ 'Cookie', [ 'param=phpsessid' ] ],
[ 'Accept-Language', [ 'substr=en', 'substr=en' ] ],
],
[],
'Vary: Cookie, Accept-Language',
'Key: Cookie;param=phpsessid,Accept-Language;substr=en',
],
'Same header, different options' => [
[
[ 'Cookie', [ 'param=phpsessid' ] ],
[ 'Cookie', [ 'param=userId' ] ],
],
[],
'Vary: Cookie',
'Key: Cookie;param=phpsessid;param=userId',
],
'No header, vary cookies' => [
[],
[ 'cookie1', 'cookie2' ],
'Vary: Cookie',
'Key: Cookie;param=cookie1;param=cookie2',
],
'Cookie header with option plus vary cookies' => [
[
[ 'Cookie', [ 'param=cookie1' ] ],
],
[ 'cookie2', 'cookie3' ],
'Vary: Cookie',
'Key: Cookie;param=cookie1;param=cookie2;param=cookie3',
],
'Non-cookie header plus vary cookies' => [
[
[ 'Accept-Language' ],
],
[ 'cookie' ],
'Vary: Accept-Language, Cookie',
'Key: Accept-Language,Cookie;param=cookie',
],
'Cookie and non-cookie headers plus vary cookies' => [
[
[ 'Cookie', [ 'param=cookie1' ] ],
[ 'Accept-Language' ],
],
[ 'cookie2' ],
'Vary: Cookie, Accept-Language',
'Key: Cookie;param=cookie1;param=cookie2,Accept-Language',
],
];
}
/**
* @covers OutputPage::getVaryHeader
*/
public function testVaryHeaderDefault() {
$op = $this->newInstance();
$this->assertSame( 'Vary: Accept-Encoding, Cookie', $op->getVaryHeader() );
}
/**
* @dataProvider provideLinkHeaders
*
* @covers OutputPage::addLinkHeader
* @covers OutputPage::getLinkHeader
*/
public function testLinkHeaders( array $headers, $result ) {
$op = $this->newInstance();
foreach ( $headers as $header ) {
$op->addLinkHeader( $header );
}
$this->assertEquals( $result, $op->getLinkHeader() );
}
public 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
* @covers OutputPage::addAcceptLanguage
* @covers OutputPage::getKeyHeader
*/
public function testAddAcceptLanguage(
$code, array $variants, array $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->getMock( Language::class );
if ( in_array( 'varianturl', $options ) ) {
$mockLang->expects( $this->never() )->method( $this->anything() );
} else {
$mockLang->method( 'hasVariants' )->willReturn( count( $variants ) > 1 );
$mockLang->method( 'getVariants' )->willReturn( $variants );
$mockLang->method( 'getCode' )->willReturn( $code );
}
$mockTitle = $this->getMock( Title::class );
$mockTitle->method( 'getPageLanguage' )->willReturn( $mockLang );
$op->setTitle( $mockTitle );
}
// This will run addAcceptLanguage()
$op->sendCacheControl();
$this->hideDeprecated( '$wgUseKeyHeader' );
$keyHeader = $op->getKeyHeader();
if ( !$expected ) {
$this->assertFalse( strpos( 'Accept-Language', $keyHeader ) );
return;
}
$keyHeader = explode( ' ', $keyHeader, 2 )[1];
$keyHeader = explode( ',', $keyHeader );
$acceptLanguage = null;
foreach ( $keyHeader as $item ) {
if ( strpos( $item, 'Accept-Language;' ) === 0 ) {
$acceptLanguage = $item;
break;
}
}
$expectedString = 'Accept-Language;substr=' . implode( ';substr=', $expected );
$this->assertSame( $expectedString, $acceptLanguage );
}
public function provideAddAcceptLanguage() {
return [
'No variants' => [ 'en', [ 'en' ], [] ],
'One simple variant' => [ 'en', [ 'en', 'en-x-piglatin' ], [ 'en-x-piglatin' ] ],
'Multiple variants with BCP47 alternatives' => [
'zh',
[ 'zh', 'zh-hans', 'zh-cn', 'zh-tw' ],
[ 'zh-hans', 'zh-Hans', 'zh-cn', 'zh-Hans-CN', 'zh-tw', 'zh-Hant-TW' ],
],
'No title' => [ 'en', [ 'en', 'en-x-piglatin' ], [], [ 'notitle' ] ],
'Variant in URL' => [ 'en', [ 'en', 'en-x-piglatin' ], [], [ 'varianturl' ] ],
];
}
/**
* @covers OutputPage::preventClickjacking
* @covers OutputPage::allowClickjacking
* @covers OutputPage::getPreventClickjacking
* @covers OutputPage::addParserOutputMetadata
* @covers OutputPage::addParserOutput
*/
public function testClickjacking() {
$op = $this->newInstance();
$this->assertTrue( $op->getPreventClickjacking() );
$op->allowClickjacking();
$this->assertFalse( $op->getPreventClickjacking() );
$op->preventClickjacking();
$this->assertTrue( $op->getPreventClickjacking() );
$op->preventClickjacking( false );
$this->assertFalse( $op->getPreventClickjacking() );
$pOut1 = $this->createParserOutputStub( 'preventClickjacking', true );
$op->addParserOutputMetadata( $pOut1 );
$this->assertTrue( $op->getPreventClickjacking() );
// The ParserOutput can't allow, only prevent
$pOut2 = $this->createParserOutputStub( 'preventClickjacking', false );
$op->addParserOutputMetadata( $pOut2 );
$this->assertTrue( $op->getPreventClickjacking() );
// Reset to test with addParserOutput()
$op->allowClickjacking();
$this->assertFalse( $op->getPreventClickjacking() );
$op->addParserOutput( $pOut1 );
$this->assertTrue( $op->getPreventClickjacking() );
$op->addParserOutput( $pOut2 );
$this->assertTrue( $op->getPreventClickjacking() );
}
/**
* @dataProvider provideGetFrameOptions
* @covers OutputPage::getFrameOptions
* @covers OutputPage::preventClickjacking
*/
public function testGetFrameOptions(
$breakFrames, $preventClickjacking, $editPageFrameOptions, $expected
) {
$op = $this->newInstance( [
'BreakFrames' => $breakFrames,
'EditPageFrameOptions' => $editPageFrameOptions,
] );
$op->preventClickjacking( $preventClickjacking );
$this->assertSame( $expected, $op->getFrameOptions() );
}
public 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 ResourceLoaderClientHtmlTest for full coverage.
*
* @dataProvider provideMakeResourceLoaderLink
*
* @covers OutputPage::makeResourceLoaderLink
*/
public function testMakeResourceLoaderLink( $args, $expectedHtml ) {
$this->setMwGlobals( [
'wgResourceLoaderDebug' => false,
'wgLoadScript' => 'http://127.0.0.1:8080/w/load.php',
'wgCSPReportOnlyHeader' => true,
] );
$class = new ReflectionClass( OutputPage::class );
$method = $class->getMethod( 'makeResourceLoaderLink' );
$method->setAccessible( true );
$ctx = new RequestContext();
$ctx->setSkin( SkinFactory::getDefaultInstance()->makeSkin( 'fallback' ) );
$ctx->setLanguage( 'en' );
$out = new OutputPage( $ctx );
$nonce = $class->getProperty( 'CSPNonce' );
$nonce->setAccessible( true );
$nonce->setValue( $out, 'secret' );
$rl = $out->getResourceLoader();
$rl->setMessageBlobStore( new NullMessageBlobStore() );
$rl->register( [
'test.foo' => new ResourceLoaderTestModule( [
'script' => 'mw.test.foo( { a: true } );',
'styles' => '.mw-test-foo { content: "style"; }',
] ),
'test.bar' => new ResourceLoaderTestModule( [
'script' => 'mw.test.bar( { a: true } );',
'styles' => '.mw-test-bar { content: "style"; }',
] ),
'test.baz' => new ResourceLoaderTestModule( [
'script' => 'mw.test.baz( { a: true } );',
'styles' => '.mw-test-baz { content: "style"; }',
] ),
'test.quux' => new ResourceLoaderTestModule( [
'script' => 'mw.test.baz( { token: 123 } );',
'styles' => '/* pref-animate=off */ .mw-icon { transition: none; }',
'group' => 'private',
] ),
'test.noscript' => new ResourceLoaderTestModule( [
'styles' => '.stuff { color: red; }',
'group' => 'noscript',
] ),
'test.group.foo' => new ResourceLoaderTestModule( [
'script' => 'mw.doStuff( "foo" );',
'group' => 'foo',
] ),
'test.group.bar' => new ResourceLoaderTestModule( [
'script' => 'mw.doStuff( "bar" );',
'group' => 'bar',
] ),
] );
$links = $method->invokeArgs( $out, $args );
$actualHtml = strval( $links );
$this->assertEquals( $expectedHtml, $actualHtml );
}
public static function provideMakeResourceLoaderLink() {
// phpcs:disable Generic.Files.LineLength
return [
// Single only=scripts load
[
[ 'test.foo', ResourceLoaderModule::TYPE_SCRIPTS ],
""
],
// Multiple only=styles load
[
[ [ 'test.baz', 'test.foo', 'test.bar' ], ResourceLoaderModule::TYPE_STYLES ],
' '
],
// Private embed (only=scripts)
[
[ 'test.quux', ResourceLoaderModule::TYPE_SCRIPTS ],
""
],
// Load private module (combined)
[
[ 'test.quux', ResourceLoaderModule::TYPE_COMBINED ],
""
],
// Load no modules
[
[ [], ResourceLoaderModule::TYPE_COMBINED ],
'',
],
// noscript group
[
[ 'test.noscript', ResourceLoaderModule::TYPE_STYLES ],
' '
],
// Load two modules in separate groups
[
[ [ 'test.group.foo', 'test.group.bar' ], ResourceLoaderModule::TYPE_COMBINED ],
""
],
];
// phpcs:enable
}
/**
* @dataProvider provideBuildExemptModules
*
* @covers OutputPage::buildExemptModules
*/
public function testBuildExemptModules( array $exemptStyleModules, $expect ) {
$this->setMwGlobals( [
'wgResourceLoaderDebug' => false,
'wgLoadScript' => '/w/load.php',
// Stub wgCacheEpoch as it influences getVersionHash used for the
// urls in the expected HTML
'wgCacheEpoch' => '20140101000000',
] );
// Set up stubs
$ctx = new RequestContext();
$ctx->setSkin( SkinFactory::getDefaultInstance()->makeSkin( 'fallback' ) );
$ctx->setLanguage( 'en' );
$op = $this->getMockBuilder( OutputPage::class )
->setConstructorArgs( [ $ctx ] )
->setMethods( [ 'buildCssLinksArray' ] )
->getMock();
$op->expects( $this->any() )
->method( 'buildCssLinksArray' )
->willReturn( [] );
$rl = $op->getResourceLoader();
$rl->setMessageBlobStore( new NullMessageBlobStore() );
// Register custom modules
$rl->register( [
'example.site.a' => new ResourceLoaderTestModule( [ 'group' => 'site' ] ),
'example.site.b' => new ResourceLoaderTestModule( [ 'group' => 'site' ] ),
'example.user' => new ResourceLoaderTestModule( [ 'group' => 'user' ] ),
] );
$op = TestingAccessWrapper::newFromObject( $op );
$op->rlExemptStyleModules = $exemptStyleModules;
$this->assertEquals(
$expect,
strval( $op->buildExemptModules() )
);
}
public static function provideBuildExemptModules() {
// phpcs:disable Generic.Files.LineLength
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
* @covers OutputPage::transformFilePath
* @covers OutputPage::transformResourcePath
*/
public function testTransformResourcePath( $baseDir, $basePath, $uploadDir = null,
$uploadPath = null, $path = null, $expected = null
) {
if ( $path === null ) {
// Skip optional $uploadDir and $uploadPath
$path = $uploadDir;
$expected = $uploadPath;
$uploadDir = "$baseDir/images";
$uploadPath = "$basePath/images";
}
$this->setMwGlobals( 'IP', $baseDir );
$conf = new HashConfig( [
'ResourceBasePath' => $basePath,
'UploadDirectory' => $uploadDir,
'UploadPath' => $uploadPath,
] );
// Some of these paths don't exist and will cause warnings
Wikimedia\suppressWarnings();
$actual = OutputPage::transformResourcePath( $conf, $path );
Wikimedia\restoreWarnings();
$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.
[
'baseDir' => $baseDir, 'basePath' => '/w',
'/w/test.jpg',
'/w/test.jpg?edcf2'
],
// File that matches basePath, but not found on disk. Empty query.
[
'baseDir' => $baseDir, 'basePath' => '/w',
'/w/unknown.png',
'/w/unknown.png?'
],
// File not matching basePath. Ignored.
[
'baseDir' => $baseDir, 'basePath' => '/w',
'/files/test.jpg'
],
// Empty string. Ignored.
[
'baseDir' => $baseDir, 'basePath' => '/w',
'',
''
],
// Similar path, but with domain component. Ignored.
[
'baseDir' => $baseDir, 'basePath' => '/w',
'//example.org/w/test.jpg'
],
[
'baseDir' => $baseDir, 'basePath' => '/w',
'https://example.org/w/test.jpg'
],
// Unrelated path with domain component. Ignored.
[
'baseDir' => $baseDir, 'basePath' => '/w',
'https://example.org/files/test.jpg'
],
[
'baseDir' => $baseDir, 'basePath' => '/w',
'//example.org/files/test.jpg'
],
// Unrelated path with domain, and empty base path (root mw install). Ignored.
[
'baseDir' => $baseDir, 'basePath' => '',
'https://example.org/files/test.jpg'
],
[
'baseDir' => $baseDir, 'basePath' => '',
// T155310
'//example.org/files/test.jpg'
],
// Check UploadPath before ResourceBasePath (T155146)
[
'baseDir' => dirname( $baseDir ), 'basePath' => '',
'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['printableQuery'] - value of query string for printable, or omitted for none
* options['handheldQuery'] - value of query string for handheld, or omitted for none
* 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 = [];
if ( isset( $args['printableQuery'] ) ) {
$queryData['printable'] = $args['printableQuery'];
}
if ( isset( $args['handheldQuery'] ) ) {
$queryData['handheld'] = $args['handheldQuery'];
}
$fauxRequest = new FauxRequest( $queryData, false );
$this->setMwGlobals( [
'wgRequest' => $fauxRequest,
] );
$actualReturn = OutputPage::transformCssMedia( $args['media'] );
$this->assertSame( $args['expectedReturn'], $actualReturn, $args['message'] );
}
/**
* Tests print requests
*
* @covers OutputPage::transformCssMedia
*/
public function testPrintRequests() {
$this->assertTransformCssMediaCase( [
'printableQuery' => '1',
'media' => 'screen',
'expectedReturn' => null,
'message' => 'On printable request, screen returns null'
] );
$this->assertTransformCssMediaCase( [
'printableQuery' => '1',
'media' => self::SCREEN_MEDIA_QUERY,
'expectedReturn' => null,
'message' => 'On printable request, screen media query returns null'
] );
$this->assertTransformCssMediaCase( [
'printableQuery' => '1',
'media' => self::SCREEN_ONLY_MEDIA_QUERY,
'expectedReturn' => null,
'message' => 'On printable request, screen media query with only returns null'
] );
$this->assertTransformCssMediaCase( [
'printableQuery' => '1',
'media' => 'print',
'expectedReturn' => '',
'message' => 'On printable request, media print returns empty string'
] );
}
/**
* Tests screen requests, without either query parameter set
*
* @covers OutputPage::transformCssMedia
*/
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'
] );
}
/**
* Tests handheld behavior
*
* @covers OutputPage::transformCssMedia
*/
public function testHandheld() {
$this->assertTransformCssMediaCase( [
'handheldQuery' => '1',
'media' => 'handheld',
'expectedReturn' => '',
'message' => 'On request with handheld querystring and media is handheld, returns empty string'
] );
$this->assertTransformCssMediaCase( [
'handheldQuery' => '1',
'media' => 'screen',
'expectedReturn' => null,
'message' => 'On request with handheld querystring and media is screen, returns null'
] );
}
/**
* @covers OutputPage::isTOCEnabled
* @covers OutputPage::addParserOutputMetadata
* @covers OutputPage::addParserOutput
*/
public function testIsTOCEnabled() {
$op = $this->newInstance();
$this->assertFalse( $op->isTOCEnabled() );
$pOut1 = $this->createParserOutputStub( 'getTOCHTML', false );
$op->addParserOutputMetadata( $pOut1 );
$this->assertFalse( $op->isTOCEnabled() );
$pOut2 = $this->createParserOutputStub( 'getTOCHTML', true );
$op->addParserOutput( $pOut2 );
$this->assertTrue( $op->isTOCEnabled() );
// The parser output doesn't disable the TOC after it was enabled
$op->addParserOutputMetadata( $pOut1 );
$this->assertTrue( $op->isTOCEnabled() );
}
/**
* @dataProvider providePreloadLinkHeaders
* @covers ResourceLoaderSkinModule::getPreloadLinks
* @covers ResourceLoaderSkinModule::getLogoPreloadlinks
*/
public function testPreloadLinkHeaders( $config, $result ) {
$this->setMwGlobals( $config );
$ctx = $this->getMockBuilder( ResourceLoaderContext::class )
->disableOriginalConstructor()->getMock();
$module = new ResourceLoaderSkinModule();
$this->assertEquals( [ $result ], $module->getHeaders( $ctx ) );
}
public function providePreloadLinkHeaders() {
return [
[
[
'wgResourceBasePath' => '/w',
'wgLogo' => '/img/default.png',
'wgLogoHD' => [
'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)'
],
[
[
'wgResourceBasePath' => '/w',
'wgLogo' => '/img/default.png',
'wgLogoHD' => false,
],
'Link: ;rel=preload;as=image'
],
[
[
'wgResourceBasePath' => '/w',
'wgLogo' => '/img/default.png',
'wgLogoHD' => [
'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)'
],
[
[
'wgResourceBasePath' => '/w',
'wgLogo' => '/img/default.png',
'wgLogoHD' => [
'svg' => '/img/vector.svg',
],
],
'Link: ;rel=preload;as=image'
],
[
[
'wgResourceBasePath' => '/w',
'wgLogo' => '/w/test.jpg',
'wgLogoHD' => false,
'wgUploadPath' => '/w/images',
'IP' => dirname( __DIR__ ) . '/data/media',
],
'Link: ;rel=preload;as=image',
],
];
}
/**
* @return OutputPage
*/
private function newInstance( $config = [], WebRequest $request = null, $options = [] ) {
$context = new RequestContext();
$context->setConfig( new MultiConfig( [
new HashConfig( $config + [
'AppleTouchIcon' => false,
'DisableLangConversion' => true,
'EnableCanonicalServerLink' => false,
'Favicon' => false,
'Feed' => false,
'LanguageCode' => false,
'ReferrerPolicy' => false,
'RightsPage' => false,
'RightsUrl' => false,
'UniversalEditButton' => false,
] ),
$context->getConfig()
] ) );
if ( !in_array( 'notitle', (array)$options ) ) {
$context->setTitle( Title::newFromText( 'My test page' ) );
}
if ( $request ) {
$context->setRequest( $request );
}
return new OutputPage( $context );
}
}
/**
* MessageBlobStore that doesn't do anything
*/
class NullMessageBlobStore extends MessageBlobStore {
public function get( ResourceLoader $resourceLoader, $modules, $lang ) {
return [];
}
public function updateModule( $name, ResourceLoaderModule $module, $lang ) {
}
public function updateMessage( $key ) {
}
public function clear() {
}
}