wiki.techinc.nl/tests/phpunit/includes/preferences/DefaultPreferencesFactoryTest.php

344 lines
11 KiB
PHP
Raw Normal View History

<?php
use MediaWiki\Auth\AuthManager;
use MediaWiki\MediaWikiServices;
use MediaWiki\Permissions\PermissionManager;
use MediaWiki\Preferences\DefaultPreferencesFactory;
use Wikimedia\TestingAccessWrapper;
/**
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
* http://www.gnu.org/copyleft/gpl.html
*
* @file
*/
/**
* @group Preferences
* @coversDefaultClass MediaWiki\Preferences\DefaultPreferencesFactory
*/
class DefaultPreferencesFactoryTest extends \MediaWikiTestCase {
use TestAllServiceOptionsUsed;
/** @var IContextSource */
protected $context;
/** @var Config */
protected $config;
protected function setUp() : void {
parent::setUp();
$this->context = new RequestContext();
$this->context->setTitle( Title::newFromText( self::class ) );
$services = MediaWikiServices::getInstance();
$this->setMwGlobals( 'wgParser', $services->getParserFactory()->create() );
$this->setMwGlobals( 'wgDisableLangConversion', false );
$this->config = $services->getMainConfig();
}
/**
* Get a basic PreferencesFactory for testing with.
* @param PermissionManager $mockPM
* @param Language $language
* @return DefaultPreferencesFactory
*/
protected function getPreferencesFactory( PermissionManager $mockPM, Language $language ) {
$mockNsInfo = $this->createMock( NamespaceInfo::class );
$mockNsInfo->method( 'getValidNamespaces' )->willReturn( [
NS_MAIN, NS_TALK, NS_USER, NS_USER_TALK
] );
$mockNsInfo->expects( $this->never() )
->method( $this->anythingBut( 'getValidNamespaces', '__destruct' ) );
Hooks::run() call site migration Migrate all callers of Hooks::run() to use the new HookContainer/HookRunner system. General principles: * Use DI if it is already used. We're not changing the way state is managed in this patch. * HookContainer is always injected, not HookRunner. HookContainer is a service, it's a more generic interface, it is the only thing that provides isRegistered() which is needed in some cases, and a HookRunner can be efficiently constructed from it (confirmed by benchmark). Because HookContainer is needed for object construction, it is also needed by all factories. * "Ask your friendly local base class". Big hierarchies like SpecialPage and ApiBase have getHookContainer() and getHookRunner() methods in the base class, and classes that extend that base class are not expected to know or care where the base class gets its HookContainer from. * ProtectedHookAccessorTrait provides protected getHookContainer() and getHookRunner() methods, getting them from the global service container. The point of this is to ease migration to DI by ensuring that call sites ask their local friendly base class rather than getting a HookRunner from the service container directly. * Private $this->hookRunner. In some smaller classes where accessor methods did not seem warranted, there is a private HookRunner property which is accessed directly. Very rarely (two cases), there is a protected property, for consistency with code that conventionally assumes protected=private, but in cases where the class might actually be overridden, a protected accessor is preferred over a protected property. * The last resort: Hooks::runner(). Mostly for static, file-scope and global code. In a few cases it was used for objects with broken construction schemes, out of horror or laziness. Constructors with new required arguments: * AuthManager * BadFileLookup * BlockManager * ClassicInterwikiLookup * ContentHandlerFactory * ContentSecurityPolicy * DefaultOptionsManager * DerivedPageDataUpdater * FullSearchResultWidget * HtmlCacheUpdater * LanguageFactory * LanguageNameUtils * LinkRenderer * LinkRendererFactory * LocalisationCache * MagicWordFactory * MessageCache * NamespaceInfo * PageEditStash * PageHandlerFactory * PageUpdater * ParserFactory * PermissionManager * RevisionStore * RevisionStoreFactory * SearchEngineConfig * SearchEngineFactory * SearchFormWidget * SearchNearMatcher * SessionBackend * SpecialPageFactory * UserNameUtils * UserOptionsManager * WatchedItemQueryService * WatchedItemStore Constructors with new optional arguments: * DefaultPreferencesFactory * Language * LinkHolderArray * MovePage * Parser * ParserCache * PasswordReset * Router setHookContainer() now required after construction: * AuthenticationProvider * ResourceLoaderModule * SearchEngine Change-Id: Id442b0dbe43aba84bd5cf801d86dedc768b082c7
2020-03-19 02:42:09 +00:00
$services = MediaWikiServices::getInstance();
return new DefaultPreferencesFactory(
new LoggedServiceOptions( self::$serviceOptionsAccessLog,
DefaultPreferencesFactory::CONSTRUCTOR_OPTIONS, $this->config ),
$language,
AuthManager::singleton(),
Hooks::run() call site migration Migrate all callers of Hooks::run() to use the new HookContainer/HookRunner system. General principles: * Use DI if it is already used. We're not changing the way state is managed in this patch. * HookContainer is always injected, not HookRunner. HookContainer is a service, it's a more generic interface, it is the only thing that provides isRegistered() which is needed in some cases, and a HookRunner can be efficiently constructed from it (confirmed by benchmark). Because HookContainer is needed for object construction, it is also needed by all factories. * "Ask your friendly local base class". Big hierarchies like SpecialPage and ApiBase have getHookContainer() and getHookRunner() methods in the base class, and classes that extend that base class are not expected to know or care where the base class gets its HookContainer from. * ProtectedHookAccessorTrait provides protected getHookContainer() and getHookRunner() methods, getting them from the global service container. The point of this is to ease migration to DI by ensuring that call sites ask their local friendly base class rather than getting a HookRunner from the service container directly. * Private $this->hookRunner. In some smaller classes where accessor methods did not seem warranted, there is a private HookRunner property which is accessed directly. Very rarely (two cases), there is a protected property, for consistency with code that conventionally assumes protected=private, but in cases where the class might actually be overridden, a protected accessor is preferred over a protected property. * The last resort: Hooks::runner(). Mostly for static, file-scope and global code. In a few cases it was used for objects with broken construction schemes, out of horror or laziness. Constructors with new required arguments: * AuthManager * BadFileLookup * BlockManager * ClassicInterwikiLookup * ContentHandlerFactory * ContentSecurityPolicy * DefaultOptionsManager * DerivedPageDataUpdater * FullSearchResultWidget * HtmlCacheUpdater * LanguageFactory * LanguageNameUtils * LinkRenderer * LinkRendererFactory * LocalisationCache * MagicWordFactory * MessageCache * NamespaceInfo * PageEditStash * PageHandlerFactory * PageUpdater * ParserFactory * PermissionManager * RevisionStore * RevisionStoreFactory * SearchEngineConfig * SearchEngineFactory * SearchFormWidget * SearchNearMatcher * SessionBackend * SpecialPageFactory * UserNameUtils * UserOptionsManager * WatchedItemQueryService * WatchedItemStore Constructors with new optional arguments: * DefaultPreferencesFactory * Language * LinkHolderArray * MovePage * Parser * ParserCache * PasswordReset * Router setHookContainer() now required after construction: * AuthenticationProvider * ResourceLoaderModule * SearchEngine Change-Id: Id442b0dbe43aba84bd5cf801d86dedc768b082c7
2020-03-19 02:42:09 +00:00
$services->getLinkRenderer(),
$mockNsInfo,
$mockPM,
Hooks::run() call site migration Migrate all callers of Hooks::run() to use the new HookContainer/HookRunner system. General principles: * Use DI if it is already used. We're not changing the way state is managed in this patch. * HookContainer is always injected, not HookRunner. HookContainer is a service, it's a more generic interface, it is the only thing that provides isRegistered() which is needed in some cases, and a HookRunner can be efficiently constructed from it (confirmed by benchmark). Because HookContainer is needed for object construction, it is also needed by all factories. * "Ask your friendly local base class". Big hierarchies like SpecialPage and ApiBase have getHookContainer() and getHookRunner() methods in the base class, and classes that extend that base class are not expected to know or care where the base class gets its HookContainer from. * ProtectedHookAccessorTrait provides protected getHookContainer() and getHookRunner() methods, getting them from the global service container. The point of this is to ease migration to DI by ensuring that call sites ask their local friendly base class rather than getting a HookRunner from the service container directly. * Private $this->hookRunner. In some smaller classes where accessor methods did not seem warranted, there is a private HookRunner property which is accessed directly. Very rarely (two cases), there is a protected property, for consistency with code that conventionally assumes protected=private, but in cases where the class might actually be overridden, a protected accessor is preferred over a protected property. * The last resort: Hooks::runner(). Mostly for static, file-scope and global code. In a few cases it was used for objects with broken construction schemes, out of horror or laziness. Constructors with new required arguments: * AuthManager * BadFileLookup * BlockManager * ClassicInterwikiLookup * ContentHandlerFactory * ContentSecurityPolicy * DefaultOptionsManager * DerivedPageDataUpdater * FullSearchResultWidget * HtmlCacheUpdater * LanguageFactory * LanguageNameUtils * LinkRenderer * LinkRendererFactory * LocalisationCache * MagicWordFactory * MessageCache * NamespaceInfo * PageEditStash * PageHandlerFactory * PageUpdater * ParserFactory * PermissionManager * RevisionStore * RevisionStoreFactory * SearchEngineConfig * SearchEngineFactory * SearchFormWidget * SearchNearMatcher * SessionBackend * SpecialPageFactory * UserNameUtils * UserOptionsManager * WatchedItemQueryService * WatchedItemStore Constructors with new optional arguments: * DefaultPreferencesFactory * Language * LinkHolderArray * MovePage * Parser * ParserCache * PasswordReset * Router setHookContainer() now required after construction: * AuthenticationProvider * ResourceLoaderModule * SearchEngine Change-Id: Id442b0dbe43aba84bd5cf801d86dedc768b082c7
2020-03-19 02:42:09 +00:00
$services->getLanguageConverterFactory()->getLanguageConverter( $language ),
$services->getLanguageNameUtils(),
$services->getHookContainer()
);
}
/**
* @covers ::getForm
* @covers ::searchPreferences
*/
public function testGetForm() {
$this->setTemporaryHook( 'GetPreferences', null );
$testUser = $this->getTestUser();
$pm = $this->createMock( PermissionManager::class );
$pm->method( 'userHasRight' )->willReturn( true );
$prefFactory = $this->getPreferencesFactory( $pm, new Language() );
$form = $prefFactory->getForm( $testUser->getUser(), $this->context );
$this->assertInstanceOf( PreferencesFormOOUI::class, $form );
$this->assertCount( 5, $form->getPreferenceSections() );
}
/**
* CSS classes for emailauthentication preference field when there's no email.
* @see https://phabricator.wikimedia.org/T36302
*
* @covers ::profilePreferences
* @dataProvider emailAuthenticationProvider
*/
public function testEmailAuthentication( $user, $cssClass ) {
$pm = $this->createMock( PermissionManager::class );
$pm->method( 'userHasRight' )->willReturn( true );
$prefs = $this->getPreferencesFactory( $pm, new Language() )
->getFormDescriptor( $user, $this->context );
$this->assertArrayHasKey( 'cssclass', $prefs['emailauthentication'] );
$this->assertEquals( $cssClass, $prefs['emailauthentication']['cssclass'] );
}
/**
* @covers ::renderingPreferences
*/
public function testShowRollbackConfIsHiddenForUsersWithoutRollbackRights() {
$userMock = $this->getMockBuilder( User::class )
->disableOriginalConstructor()
->getMock();
$userMock->method( 'getEffectiveGroups' )
->willReturn( [] );
$userMock->method( 'getGroupMemberships' )
->willReturn( [] );
$userMock->method( 'getOptions' )
->willReturn( [ 'test' => 'yes' ] );
$pm = $this->createMock( PermissionManager::class );
$pm->method( 'userHasRight' )
->will( $this->returnValueMap( [
[ $userMock, 'editmyoptions', true ]
] ) );
$prefs = $this->getPreferencesFactory( $pm, new Language() )
->getFormDescriptor( $userMock, $this->context );
$this->assertArrayNotHasKey( 'showrollbackconfirmation', $prefs );
}
/**
* @covers ::renderingPreferences
*/
public function testShowRollbackConfIsShownForUsersWithRollbackRights() {
$userMock = $this->getMockBuilder( User::class )
->disableOriginalConstructor()
->getMock();
$userMock->method( 'getEffectiveGroups' )
->willReturn( [] );
$userMock->method( 'getGroupMemberships' )
->willReturn( [] );
$userMock->method( 'getOptions' )
->willReturn( [ 'test' => 'yes' ] );
$pm = $this->createMock( PermissionManager::class );
$pm->method( 'userHasRight' )
->will( $this->returnValueMap( [
[ $userMock, 'editmyoptions', true ],
[ $userMock, 'rollback', true ]
] ) );
$prefs = $this->getPreferencesFactory( $pm, new Language() )
->getFormDescriptor( $userMock, $this->context );
$this->assertArrayHasKey( 'showrollbackconfirmation', $prefs );
$this->assertEquals(
'rendering/advancedrendering',
$prefs['showrollbackconfirmation']['section']
);
}
public function emailAuthenticationProvider() {
$userNoEmail = new User;
$userEmailUnauthed = new User;
$userEmailUnauthed->setEmail( 'noauth@example.org' );
$userEmailAuthed = new User;
$userEmailAuthed->setEmail( 'noauth@example.org' );
$userEmailAuthed->setEmailAuthenticationTimestamp( wfTimestamp() );
return [
[ $userNoEmail, 'mw-email-none' ],
[ $userEmailUnauthed, 'mw-email-not-authenticated' ],
[ $userEmailAuthed, 'mw-email-authenticated' ],
];
}
/**
* Test that PreferencesFormPreSave hook has correct data:
* - user Object is passed
* - oldUserOptions contains previous user options (before save)
* - formData and User object have set up new properties
*
* @see https://phabricator.wikimedia.org/T169365
* @covers ::submitForm
*/
public function testPreferencesFormPreSaveHookHasCorrectData() {
$oldOptions = [
'test' => 'abc',
'option' => 'old'
];
$newOptions = [
'test' => 'abc',
'option' => 'new'
];
$configMock = new HashConfig( [
'HiddenPrefs' => []
] );
$form = $this->getMockBuilder( PreferencesFormOOUI::class )
->disableOriginalConstructor()
->getMock();
$userMock = $this->getMockBuilder( User::class )
->disableOriginalConstructor()
->getMock();
$userMock->method( 'getOptions' )
->willReturn( $oldOptions );
$userMock->expects( $this->exactly( 2 ) )
->method( 'setOption' )
->withConsecutive(
[ $this->equalTo( 'test' ), $this->equalTo( $newOptions[ 'test' ] ) ],
[ $this->equalTo( 'option' ), $this->equalTo( $newOptions[ 'option' ] ) ]
);
$form->method( 'getModifiedUser' )
->willReturn( $userMock );
$form->method( 'getContext' )
->willReturn( $this->context );
$form->method( 'getConfig' )
->willReturn( $configMock );
$pm = $this->createMock( PermissionManager::class );
$pm->method( 'userHasAnyRight' )
->will( $this->returnValueMap( [
[ $userMock, 'editmyprivateinfo', 'editmyoptions', true ]
] ) );
$pm->method( 'userHasRight' )
->will( $this->returnValueMap( [
[ $userMock, 'editmyoptions', true ]
] ) );
$this->setTemporaryHook( 'PreferencesFormPreSave',
function ( $formData, $form, $user, &$result, $oldUserOptions )
use ( $newOptions, $oldOptions, $userMock ) {
$this->assertSame( $userMock, $user );
foreach ( $newOptions as $option => $value ) {
$this->assertSame( $value, $formData[ $option ] );
}
foreach ( $oldOptions as $option => $value ) {
$this->assertSame( $value, $oldUserOptions[ $option ] );
}
$this->assertTrue( $result );
}
);
/** @var DefaultPreferencesFactory $factory */
$factory = TestingAccessWrapper::newFromObject(
$this->getPreferencesFactory( $pm, new Language() )
);
$factory->saveFormData( $newOptions, $form, [] );
}
/**
* The rclimit preference should accept non-integer input and filter it to become an integer.
*
* @covers ::saveFormData
*/
public function testIntvalFilter() {
// Test a string with leading zeros (i.e. not octal) and spaces.
$this->context->getRequest()->setVal( 'wprclimit', ' 0012 ' );
$user = new User;
$pm = $this->createMock( PermissionManager::class );
$pm->method( 'userHasAnyRight' )
->willReturn( true );
$pm->method( 'userHasRight' )
->will( $this->returnValueMap( [
[ $user, 'editmyoptions', true ]
] ) );
$prefFactory = $this->getPreferencesFactory( $pm, new Language() );
$form = $prefFactory->getForm( $user, $this->context );
$form->show();
$form->trySubmit();
$this->assertEquals( 12, $user->getOption( 'rclimit' ) );
}
/**
* @covers ::profilePreferences
*/
public function testVariantsSupport() {
$userMock = $this->getMockBuilder( User::class )
->disableOriginalConstructor()
->getMock();
$userMock->method( 'getEffectiveGroups' )
->willReturn( [] );
$userMock->method( 'getGroupMemberships' )
->willReturn( [] );
$userMock->method( 'getOptions' )
->willReturn( [ 'LanguageCode' => 'sr', 'variant' => 'sr' ] );
$pm = $this->createMock( PermissionManager::class );
$pm->method( 'userHasRight' )
->will( $this->returnValue( true ) );
$language = $this->createMock( Language::class );
$language->expects( $this->any() )->method( 'getCode' )
->willReturn( 'sr' );
$prefs = $this->getPreferencesFactory( $pm, $language )
->getFormDescriptor( $userMock, $this->context );
$this->assertArrayHasKey( 'default', $prefs['variant'] );
$this->assertEquals( 'sr', $prefs['variant']['default'] );
}
/**
* @covers ::profilePreferences
*/
public function testUserGroupMemberships() {
$userMock = $this->getMockBuilder( User::class )
->disableOriginalConstructor()
->getMock();
$userMock->method( 'getEffectiveGroups' )
->willReturn( [ 'users' ] );
$userMock->method( 'getGroupMemberships' )
->willReturn( [ 'users' ] );
$userMock->method( 'getOptions' )
->willReturn( [] );
$pm = $this->createMock( PermissionManager::class );
$pm->method( 'userHasRight' )
->will( $this->returnValue( true ) );
$language = $this->createMock( Language::class );
$language->expects( $this->any() )->method( 'getCode' )
->willReturn( 'en' );
$prefs = $this->getPreferencesFactory( $pm, $language )
->getFormDescriptor( $userMock, $this->context );
$this->assertArrayHasKey( 'default', $prefs['usergroups'] );
$this->assertEquals( 'users', $prefs['usergroups']['default'] );
}
/**
* @coversNothing
*/
public function testAllServiceOptionsUsed() {
$this->assertAllServiceOptionsUsed( [ 'EnotifMinorEdits', 'EnotifRevealEditorAddress' ] );
}
}