' . "\nMy message\n
"
], 'List at start' => [
[ '* List' ],
"{{PAGENAME}}", 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['addWikiTextTidy'] as $key => $val ) {
$args = [ $val[0][0], null, $val[0][1] ?? true, true, false ];
$tests['addWikiTextTitle']["$key (addWikiTextTitle)"] =
array_merge( [ $args ], array_slice( $val, 1 ) );
}
foreach ( $tests['addWikiTextTitleTidy'] as $key => $val ) {
$args = [ $val[0][0], $val[0][1], $val[0][2] ?? true, true, false ];
$tests['addWikiTextTitle']["$key (addWikiTextTitle)"] =
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::addParserOutputMetadata
*/
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->addParserOutputMetadata( $stubPO2 );
$this->assertFalse( $op->mNoGallery );
}
// @todo Make sure to test the following in addParserOutputMetadata() as well when we add tests
// for them:
// * enableClientCache()
// * addModules()
// * addModuleScripts()
// * addModuleStyles()
// * addJsConfigVars()
// * preventClickJacking()
// Otherwise those lines of addParserOutputMetadata() will be reported as covered, but we won't
// be testing they actually work.
/**
* @covers OutputPage::haveCacheVaryCookies
*/
public function testHaveCacheVaryCookies() {
$request = new FauxRequest();
$context = new RequestContext();
$context->setRequest( $request );
$op = new OutputPage( $context );
// 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
*/
public function testVaryHeaders( $calls, $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( [] ) );
TestingAccessWrapper::newFromObject( $op )->mVaryHeader = [];
foreach ( $calls as $call ) {
call_user_func_array( [ $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 [
[ // 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',
],
];
}
/**
* @dataProvider provideLinkHeaders
*
* @covers OutputPage::addLinkHeader
* @covers OutputPage::getLinkHeader
*/
public function testLinkHeaders( $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',
],
];
}
/**
* 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'
] );
}
/**
* @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() {
}
}