aboutsummaryrefslogtreecommitdiffstats
path: root/apps/user_ldap/tests
diff options
context:
space:
mode:
Diffstat (limited to 'apps/user_ldap/tests')
-rw-r--r--apps/user_ldap/tests/AccessTest.php203
-rw-r--r--apps/user_ldap/tests/ConfigurationTest.php26
-rw-r--r--apps/user_ldap/tests/ConnectionTest.php33
-rw-r--r--apps/user_ldap/tests/GroupLDAPPluginTest.php66
-rw-r--r--apps/user_ldap/tests/Group_LDAPTest.php198
-rw-r--r--apps/user_ldap/tests/HelperTest.php95
-rw-r--r--apps/user_ldap/tests/Integration/AbstractIntegrationTest.php47
-rw-r--r--apps/user_ldap/tests/Integration/Bootstrap.php3
-rw-r--r--apps/user_ldap/tests/Integration/ExceptionOnLostConnection.php53
-rw-r--r--apps/user_ldap/tests/Integration/Lib/IntegrationTestAttributeDetection.php23
-rw-r--r--apps/user_ldap/tests/Integration/Lib/IntegrationTestFetchUsersByLoginName.php8
-rw-r--r--apps/user_ldap/tests/Integration/Lib/IntegrationTestPaging.php5
-rw-r--r--apps/user_ldap/tests/Integration/Lib/User/IntegrationTestUserAvatar.php36
-rw-r--r--apps/user_ldap/tests/Integration/Lib/User/IntegrationTestUserCleanUp.php15
-rw-r--r--apps/user_ldap/tests/Integration/Lib/User/IntegrationTestUserDisplayName.php15
-rw-r--r--apps/user_ldap/tests/Jobs/CleanUpTest.php23
-rw-r--r--apps/user_ldap/tests/Jobs/SyncTest.php160
-rw-r--r--apps/user_ldap/tests/LDAPGroupPluginDummy.php2
-rw-r--r--apps/user_ldap/tests/LDAPProviderTest.php434
-rw-r--r--apps/user_ldap/tests/LDAPTest.php24
-rw-r--r--apps/user_ldap/tests/LDAPUserPluginDummy.php10
-rw-r--r--apps/user_ldap/tests/Mapping/AbstractMappingTestCase.php (renamed from apps/user_ldap/tests/Mapping/AbstractMappingTest.php)66
-rw-r--r--apps/user_ldap/tests/Mapping/GroupMappingTest.php6
-rw-r--r--apps/user_ldap/tests/Mapping/UserMappingTest.php6
-rw-r--r--apps/user_ldap/tests/Migration/AbstractUUIDFixTestCase.php (renamed from apps/user_ldap/tests/Migration/AbstractUUIDFixTest.php)49
-rw-r--r--apps/user_ldap/tests/Migration/UUIDFixGroupTest.php7
-rw-r--r--apps/user_ldap/tests/Migration/UUIDFixInsertTest.php60
-rw-r--r--apps/user_ldap/tests/Migration/UUIDFixUserTest.php4
-rw-r--r--apps/user_ldap/tests/Service/BirthdateParserServiceTest.php9
-rw-r--r--apps/user_ldap/tests/Service/UpdateGroupsServiceTest.php33
-rw-r--r--apps/user_ldap/tests/Settings/AdminTest.php35
-rw-r--r--apps/user_ldap/tests/Settings/SectionTest.php20
-rw-r--r--apps/user_ldap/tests/User/DeletedUsersIndexTest.php30
-rw-r--r--apps/user_ldap/tests/User/ManagerTest.php84
-rw-r--r--apps/user_ldap/tests/User/OfflineUserTest.php25
-rw-r--r--apps/user_ldap/tests/User/UserTest.php175
-rw-r--r--apps/user_ldap/tests/UserLDAPPluginTest.php98
-rw-r--r--apps/user_ldap/tests/User_LDAPTest.php738
-rw-r--r--apps/user_ldap/tests/User_ProxyTest.php44
-rw-r--r--apps/user_ldap/tests/WizardTest.php35
40 files changed, 1484 insertions, 1519 deletions
diff --git a/apps/user_ldap/tests/AccessTest.php b/apps/user_ldap/tests/AccessTest.php
index 941aa51fc31..54be29d0f86 100644
--- a/apps/user_ldap/tests/AccessTest.php
+++ b/apps/user_ldap/tests/AccessTest.php
@@ -1,4 +1,6 @@
<?php
+
+declare(strict_types=1);
/**
* SPDX-FileCopyrightText: 2016 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -6,10 +8,10 @@
*/
namespace OCA\User_LDAP\Tests;
+use OC\ServerNotAvailableException;
use OCA\User_LDAP\Access;
use OCA\User_LDAP\Connection;
use OCA\User_LDAP\Exceptions\ConstraintViolationException;
-use OCA\User_LDAP\FilesystemHelper;
use OCA\User_LDAP\Helper;
use OCA\User_LDAP\ILDAPWrapper;
use OCA\User_LDAP\LDAP;
@@ -18,12 +20,15 @@ use OCA\User_LDAP\Mapping\UserMapping;
use OCA\User_LDAP\User\Manager;
use OCA\User_LDAP\User\OfflineUser;
use OCA\User_LDAP\User\User;
+use OCP\EventDispatcher\IEventDispatcher;
+use OCP\HintException;
use OCP\IAppConfig;
use OCP\IAvatarManager;
use OCP\IConfig;
use OCP\Image;
use OCP\IUserManager;
use OCP\Notification\IManager as INotificationManager;
+use OCP\Server;
use OCP\Share\IManager;
use PHPUnit\Framework\MockObject\MockObject;
use Psr\Log\LoggerInterface;
@@ -37,34 +42,25 @@ use Test\TestCase;
* @package OCA\User_LDAP\Tests
*/
class AccessTest extends TestCase {
- /** @var UserMapping|\PHPUnit\Framework\MockObject\MockObject */
- protected $userMapper;
- /** @var IManager|\PHPUnit\Framework\MockObject\MockObject */
- protected $shareManager;
- /** @var GroupMapping|\PHPUnit\Framework\MockObject\MockObject */
- protected $groupMapper;
- /** @var Connection|\PHPUnit\Framework\MockObject\MockObject */
- private $connection;
- /** @var LDAP|\PHPUnit\Framework\MockObject\MockObject */
- private $ldap;
- /** @var Manager|\PHPUnit\Framework\MockObject\MockObject */
- private $userManager;
- /** @var Helper|\PHPUnit\Framework\MockObject\MockObject */
- private $helper;
- /** @var IConfig|\PHPUnit\Framework\MockObject\MockObject */
- private $config;
- /** @var IUserManager|\PHPUnit\Framework\MockObject\MockObject */
- private $ncUserManager;
-
+ protected UserMapping&MockObject $userMapper;
+ protected IManager&MockObject $shareManager;
+ protected GroupMapping&MockObject $groupMapper;
+ private Connection&MockObject $connection;
+ private LDAP&MockObject $ldap;
+ private Manager&MockObject $userManager;
+ private Helper&MockObject $helper;
+ private IConfig&MockObject $config;
+ private IUserManager&MockObject $ncUserManager;
private LoggerInterface&MockObject $logger;
-
private IAppConfig&MockObject $appConfig;
-
+ private IEventDispatcher&MockObject $dispatcher;
private Access $access;
protected function setUp(): void {
- $this->connection = $this->createMock(Connection::class);
$this->ldap = $this->createMock(LDAP::class);
+ $this->connection = $this->getMockBuilder(Connection::class)
+ ->setConstructorArgs([$this->ldap])
+ ->getMock();
$this->userManager = $this->createMock(Manager::class);
$this->helper = $this->createMock(Helper::class);
$this->config = $this->createMock(IConfig::class);
@@ -74,6 +70,7 @@ class AccessTest extends TestCase {
$this->shareManager = $this->createMock(IManager::class);
$this->logger = $this->createMock(LoggerInterface::class);
$this->appConfig = $this->createMock(IAppConfig::class);
+ $this->dispatcher = $this->createMock(IEventDispatcher::class);
$this->access = new Access(
$this->ldap,
@@ -84,7 +81,9 @@ class AccessTest extends TestCase {
$this->ncUserManager,
$this->logger,
$this->appConfig,
+ $this->dispatcher,
);
+ $this->dispatcher->expects($this->any())->method('dispatchTyped');
$this->access->setUserMapper($this->userMapper);
$this->access->setGroupMapper($this->groupMapper);
}
@@ -103,7 +102,6 @@ class AccessTest extends TestCase {
$um = $this->getMockBuilder(Manager::class)
->setConstructorArgs([
$this->createMock(IConfig::class),
- $this->createMock(FilesystemHelper::class),
$this->createMock(LoggerInterface::class),
$this->createMock(IAvatarManager::class),
$this->createMock(Image::class),
@@ -111,39 +109,39 @@ class AccessTest extends TestCase {
$this->createMock(INotificationManager::class),
$this->shareManager])
->getMock();
- $helper = new Helper(\OC::$server->getConfig(), \OC::$server->getDatabaseConnection());
+ $helper = Server::get(Helper::class);
return [$lw, $connector, $um, $helper];
}
- public function testEscapeFilterPartValidChars() {
+ public function testEscapeFilterPartValidChars(): void {
$input = 'okay';
- $this->assertTrue($input === $this->access->escapeFilterPart($input));
+ $this->assertSame($input, $this->access->escapeFilterPart($input));
}
- public function testEscapeFilterPartEscapeWildcard() {
+ public function testEscapeFilterPartEscapeWildcard(): void {
$input = '*';
$expected = '\\2a';
- $this->assertTrue($expected === $this->access->escapeFilterPart($input));
+ $this->assertSame($expected, $this->access->escapeFilterPart($input));
}
- public function testEscapeFilterPartEscapeWildcard2() {
+ public function testEscapeFilterPartEscapeWildcard2(): void {
$input = 'foo*bar';
$expected = 'foo\\2abar';
- $this->assertTrue($expected === $this->access->escapeFilterPart($input));
+ $this->assertSame($expected, $this->access->escapeFilterPart($input));
}
/**
- * @dataProvider convertSID2StrSuccessData
* @param array $sidArray
* @param $sidExpected
*/
- public function testConvertSID2StrSuccess(array $sidArray, $sidExpected) {
+ #[\PHPUnit\Framework\Attributes\DataProvider('convertSID2StrSuccessData')]
+ public function testConvertSID2StrSuccess(array $sidArray, $sidExpected): void {
$sidBinary = implode('', $sidArray);
$this->assertSame($sidExpected, $this->access->convertSID2Str($sidBinary));
}
- public function convertSID2StrSuccessData() {
+ public static function convertSID2StrSuccessData(): array {
return [
[
[
@@ -170,14 +168,14 @@ class AccessTest extends TestCase {
];
}
- public function testConvertSID2StrInputError() {
+ public function testConvertSID2StrInputError(): void {
$sidIllegal = 'foobar';
$sidExpected = '';
$this->assertSame($sidExpected, $this->access->convertSID2Str($sidIllegal));
}
- public function testGetDomainDNFromDNSuccess() {
+ public function testGetDomainDNFromDNSuccess(): void {
$inputDN = 'uid=zaphod,cn=foobar,dc=my,dc=server,dc=com';
$domainDN = 'dc=my,dc=server,dc=com';
@@ -189,7 +187,7 @@ class AccessTest extends TestCase {
$this->assertSame($domainDN, $this->access->getDomainDNFromDN($inputDN));
}
- public function testGetDomainDNFromDNError() {
+ public function testGetDomainDNFromDNError(): void {
$inputDN = 'foobar';
$expected = '';
@@ -201,74 +199,68 @@ class AccessTest extends TestCase {
$this->assertSame($expected, $this->access->getDomainDNFromDN($inputDN));
}
- public function dnInputDataProvider() {
- return [[
+ public static function dnInputDataProvider(): array {
+ return [
[
- 'input' => 'foo=bar,bar=foo,dc=foobar',
- 'interResult' => [
+ 'foo=bar,bar=foo,dc=foobar',
+ [
'count' => 3,
0 => 'foo=bar',
1 => 'bar=foo',
2 => 'dc=foobar'
],
- 'expectedResult' => true
+ true
],
[
- 'input' => 'foobarbarfoodcfoobar',
- 'interResult' => false,
- 'expectedResult' => false
+ 'foobarbarfoodcfoobar',
+ false,
+ false
]
- ]];
+ ];
}
- /**
- * @dataProvider dnInputDataProvider
- * @param array $case
- */
- public function testStringResemblesDN($case) {
+ #[\PHPUnit\Framework\Attributes\DataProvider('dnInputDataProvider')]
+ public function testStringResemblesDN(string $input, array|bool $interResult, bool $expectedResult): void {
[$lw, $con, $um, $helper] = $this->getConnectorAndLdapMock();
- /** @var IConfig|\PHPUnit\Framework\MockObject\MockObject $config */
+ /** @var IConfig&MockObject $config */
$config = $this->createMock(IConfig::class);
- $access = new Access($lw, $con, $um, $helper, $config, $this->ncUserManager, $this->logger, $this->appConfig);
+ $access = new Access($lw, $con, $um, $helper, $config, $this->ncUserManager, $this->logger, $this->appConfig, $this->dispatcher);
$lw->expects($this->exactly(1))
->method('explodeDN')
- ->willReturnCallback(function ($dn) use ($case) {
- if ($dn === $case['input']) {
- return $case['interResult'];
+ ->willReturnCallback(function ($dn) use ($input, $interResult) {
+ if ($dn === $input) {
+ return $interResult;
}
return null;
});
- $this->assertSame($case['expectedResult'], $access->stringResemblesDN($case['input']));
+ $this->assertSame($expectedResult, $access->stringResemblesDN($input));
}
- /**
- * @dataProvider dnInputDataProvider
- * @param $case
- */
- public function testStringResemblesDNLDAPmod($case) {
+ #[\PHPUnit\Framework\Attributes\DataProvider('dnInputDataProvider')]
+ public function testStringResemblesDNLDAPmod(string $input, array|bool $interResult, bool $expectedResult): void {
[, $con, $um, $helper] = $this->getConnectorAndLdapMock();
- /** @var IConfig|\PHPUnit\Framework\MockObject\MockObject $config */
+ /** @var IConfig&MockObject $config */
$config = $this->createMock(IConfig::class);
$lw = new LDAP();
- $access = new Access($lw, $con, $um, $helper, $config, $this->ncUserManager, $this->logger, $this->appConfig);
+ $access = new Access($lw, $con, $um, $helper, $config, $this->ncUserManager, $this->logger, $this->appConfig, $this->dispatcher);
if (!function_exists('ldap_explode_dn')) {
$this->markTestSkipped('LDAP Module not available');
}
- $this->assertSame($case['expectedResult'], $access->stringResemblesDN($case['input']));
+ $this->assertSame($expectedResult, $access->stringResemblesDN($input));
}
- public function testCacheUserHome() {
+ public function testCacheUserHome(): void {
$this->connection->expects($this->once())
->method('writeToCache');
$this->access->cacheUserHome('foobar', '/foobars/path');
}
- public function testBatchApplyUserAttributes() {
+ public function testBatchApplyUserAttributes(): void {
$this->ldap->expects($this->any())
->method('isResource')
->willReturn(true);
@@ -282,7 +274,7 @@ class AccessTest extends TestCase {
->method('getAttributes')
->willReturn(['displayname' => ['bar', 'count' => 1]]);
- /** @var UserMapping|\PHPUnit\Framework\MockObject\MockObject $mapperMock */
+ /** @var UserMapping&MockObject $mapperMock */
$mapperMock = $this->createMock(UserMapping::class);
$mapperMock->expects($this->any())
->method('getNameByDN')
@@ -326,8 +318,8 @@ class AccessTest extends TestCase {
$this->access->batchApplyUserAttributes($data);
}
- public function testBatchApplyUserAttributesSkipped() {
- /** @var UserMapping|\PHPUnit\Framework\MockObject\MockObject $mapperMock */
+ public function testBatchApplyUserAttributesSkipped(): void {
+ /** @var UserMapping&MockObject $mapperMock */
$mapperMock = $this->createMock(UserMapping::class);
$mapperMock->expects($this->any())
->method('getNameByDN')
@@ -367,8 +359,8 @@ class AccessTest extends TestCase {
$this->access->batchApplyUserAttributes($data);
}
- public function testBatchApplyUserAttributesDontSkip() {
- /** @var UserMapping|\PHPUnit\Framework\MockObject\MockObject $mapperMock */
+ public function testBatchApplyUserAttributesDontSkip(): void {
+ /** @var UserMapping&MockObject $mapperMock */
$mapperMock = $this->createMock(UserMapping::class);
$mapperMock->expects($this->any())
->method('getNameByDN')
@@ -408,7 +400,7 @@ class AccessTest extends TestCase {
$this->access->batchApplyUserAttributes($data);
}
- public function dNAttributeProvider() {
+ public static function dNAttributeProvider(): array {
// corresponds to Access::resemblesDN()
return [
'dn' => ['dn'],
@@ -418,13 +410,10 @@ class AccessTest extends TestCase {
];
}
- /**
- * @dataProvider dNAttributeProvider
- * @param $attribute
- */
- public function testSanitizeDN($attribute) {
+ #[\PHPUnit\Framework\Attributes\DataProvider('dNAttributeProvider')]
+ public function testSanitizeDN(string $attribute): void {
[$lw, $con, $um, $helper] = $this->getConnectorAndLdapMock();
- /** @var IConfig|\PHPUnit\Framework\MockObject\MockObject $config */
+ /** @var IConfig&MockObject $config */
$config = $this->createMock(IConfig::class);
$dnFromServer = 'cn=Mixed Cases,ou=Are Sufficient To,ou=Test,dc=example,dc=org';
@@ -438,13 +427,13 @@ class AccessTest extends TestCase {
$attribute => ['count' => 1, $dnFromServer]
]);
- $access = new Access($lw, $con, $um, $helper, $config, $this->ncUserManager, $this->logger, $this->appConfig);
+ $access = new Access($lw, $con, $um, $helper, $config, $this->ncUserManager, $this->logger, $this->appConfig, $this->dispatcher);
$values = $access->readAttribute('uid=whoever,dc=example,dc=org', $attribute);
$this->assertSame($values[0], strtolower($dnFromServer));
}
- public function testSetPasswordWithDisabledChanges() {
+ public function testSetPasswordWithDisabledChanges(): void {
$this->expectException(\Exception::class);
$this->expectExceptionMessage('LDAP password changes are disabled');
@@ -456,7 +445,7 @@ class AccessTest extends TestCase {
$this->access->setPassword('CN=foo', 'MyPassword');
}
- public function testSetPasswordWithLdapNotAvailable() {
+ public function testSetPasswordWithLdapNotAvailable(): void {
$this->connection
->method('__get')
->willReturn(true);
@@ -464,19 +453,19 @@ class AccessTest extends TestCase {
$this->connection
->expects($this->once())
->method('getConnectionResource')
- ->willThrowException(new \OC\ServerNotAvailableException('Connection to LDAP server could not be established'));
+ ->willThrowException(new ServerNotAvailableException('Connection to LDAP server could not be established'));
$this->ldap
->expects($this->never())
->method('isResource');
- $this->expectException(\OC\ServerNotAvailableException::class);
+ $this->expectException(ServerNotAvailableException::class);
$this->expectExceptionMessage('Connection to LDAP server could not be established');
$this->access->setPassword('CN=foo', 'MyPassword');
}
- public function testSetPasswordWithRejectedChange() {
- $this->expectException(\OCP\HintException::class);
+ public function testSetPasswordWithRejectedChange(): void {
+ $this->expectException(HintException::class);
$this->expectExceptionMessage('Password change rejected.');
$this->connection
@@ -497,7 +486,7 @@ class AccessTest extends TestCase {
$this->access->setPassword('CN=foo', 'MyPassword');
}
- public function testSetPassword() {
+ public function testSetPassword(): void {
$this->connection
->method('__get')
->willReturn(true);
@@ -520,7 +509,7 @@ class AccessTest extends TestCase {
$base,
$fakeConnection,
$fakeSearchResultResource,
- $fakeLdapEntries
+ $fakeLdapEntries,
) {
$this->connection
->expects($this->any())
@@ -559,7 +548,7 @@ class AccessTest extends TestCase {
->willReturnArgument(0);
}
- public function testSearchNoPagedSearch() {
+ public function testSearchNoPagedSearch(): void {
// scenario: no pages search, 1 search base
$filter = 'objectClass=nextcloudUser';
$base = 'ou=zombies,dc=foobar,dc=nextcloud,dc=com';
@@ -586,7 +575,7 @@ class AccessTest extends TestCase {
$this->assertSame($expected, $result);
}
- public function testFetchListOfUsers() {
+ public function testFetchListOfUsers(): void {
$filter = 'objectClass=nextcloudUser';
$base = 'ou=zombies,dc=foobar,dc=nextcloud,dc=com';
$attrs = ['dn', 'uid'];
@@ -606,20 +595,21 @@ class AccessTest extends TestCase {
];
$expected = $fakeLdapEntries;
unset($expected['count']);
- array_walk($expected, function (&$v) {
+ array_walk($expected, function (&$v): void {
$v['dn'] = [$v['dn']]; // dn is translated into an array internally for consistency
});
$this->prepareMocksForSearchTests($base, $fakeConnection, $fakeSearchResultResource, $fakeLdapEntries);
- $this->connection->expects($this->exactly($fakeLdapEntries['count']))
+ // Called twice per user, for userExists and userExistsOnLdap
+ $this->connection->expects($this->exactly(2 * $fakeLdapEntries['count']))
->method('writeToCache')
->with($this->stringStartsWith('userExists'), true);
$this->userMapper->expects($this->exactly($fakeLdapEntries['count']))
->method('getNameByDN')
->willReturnCallback(function ($fdn) {
- $parts = ldap_explode_dn($fdn, false);
+ $parts = ldap_explode_dn($fdn, 0);
return $parts[0];
});
@@ -628,7 +618,7 @@ class AccessTest extends TestCase {
$this->assertSame($expected, $list);
}
- public function testFetchListOfGroupsKnown() {
+ public function testFetchListOfGroupsKnown(): void {
$filter = 'objectClass=nextcloudGroup';
$attributes = ['cn', 'gidNumber', 'dn'];
$base = 'ou=SomeGroups,dc=my,dc=directory';
@@ -658,7 +648,7 @@ class AccessTest extends TestCase {
$this->groupMapper->expects($this->never())
->method('getNameByDN');
- $this->connection->expects($this->exactly(3))
+ $this->connection->expects($this->exactly(1))
->method('writeToCache');
$groups = $this->access->fetchListOfGroups($filter, $attributes);
@@ -667,7 +657,7 @@ class AccessTest extends TestCase {
$this->assertSame('Another Good Team', $groups[1]['cn'][0]);
}
- public function intUsernameProvider() {
+ public static function intUsernameProvider(): array {
return [
['alice', 'alice'],
['b/ob', 'bob'],
@@ -685,7 +675,7 @@ class AccessTest extends TestCase {
];
}
- public function groupIDCandidateProvider() {
+ public static function groupIDCandidateProvider(): array {
return [
['alice', 'alice'],
['b/ob', 'b/ob'],
@@ -702,13 +692,8 @@ class AccessTest extends TestCase {
];
}
- /**
- * @dataProvider intUsernameProvider
- *
- * @param $name
- * @param $expected
- */
- public function testSanitizeUsername($name, $expected) {
+ #[\PHPUnit\Framework\Attributes\DataProvider('intUsernameProvider')]
+ public function testSanitizeUsername(string $name, ?string $expected): void {
if ($expected === null) {
$this->expectException(\InvalidArgumentException::class);
}
@@ -716,15 +701,13 @@ class AccessTest extends TestCase {
$this->assertSame($expected, $sanitizedName);
}
- /**
- * @dataProvider groupIDCandidateProvider
- */
- public function testSanitizeGroupIDCandidate(string $name, string $expected) {
+ #[\PHPUnit\Framework\Attributes\DataProvider('groupIDCandidateProvider')]
+ public function testSanitizeGroupIDCandidate(string $name, string $expected): void {
$sanitizedName = $this->access->sanitizeGroupIDCandidate($name);
$this->assertSame($expected, $sanitizedName);
}
- public function testUserStateUpdate() {
+ public function testUserStateUpdate(): void {
$this->connection->expects($this->any())
->method('__get')
->willReturnMap([
@@ -743,7 +726,7 @@ class AccessTest extends TestCase {
->with('detta')
->willReturnOnConsecutiveCalls($offlineUserMock, $regularUserMock);
- /** @var UserMapping|\PHPUnit\Framework\MockObject\MockObject $mapperMock */
+ /** @var UserMapping&MockObject $mapperMock */
$mapperMock = $this->createMock(UserMapping::class);
$mapperMock->expects($this->any())
->method('getNameByDN')
diff --git a/apps/user_ldap/tests/ConfigurationTest.php b/apps/user_ldap/tests/ConfigurationTest.php
index 96b08c4cf8a..db92598fcfd 100644
--- a/apps/user_ldap/tests/ConfigurationTest.php
+++ b/apps/user_ldap/tests/ConfigurationTest.php
@@ -1,5 +1,6 @@
<?php
+declare(strict_types=1);
/**
* SPDX-FileCopyrightText: 2018-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -10,15 +11,14 @@ namespace OCA\User_LDAP\Tests;
use OCA\User_LDAP\Configuration;
class ConfigurationTest extends \Test\TestCase {
- /** @var Configuration */
- protected $configuration;
+ protected Configuration $configuration;
protected function setUp(): void {
parent::setUp();
$this->configuration = new Configuration('t01', false);
}
- public function configurationDataProvider() {
+ public static function configurationDataProvider(): array {
$inputWithDN = [
'cn=someUsers,dc=example,dc=org',
' ',
@@ -86,15 +86,13 @@ class ConfigurationTest extends \Test\TestCase {
];
}
- /**
- * @dataProvider configurationDataProvider
- */
- public function testSetValue($key, $input, $expected) {
+ #[\PHPUnit\Framework\Attributes\DataProvider('configurationDataProvider')]
+ public function testSetValue(string $key, string|array $input, string|array $expected): void {
$this->configuration->setConfiguration([$key => $input]);
$this->assertSame($this->configuration->$key, $expected);
}
- public function avatarRuleValueProvider() {
+ public static function avatarRuleValueProvider(): array {
return [
['none', []],
['data:selfie', ['selfie']],
@@ -105,18 +103,14 @@ class ConfigurationTest extends \Test\TestCase {
];
}
- /**
- * @dataProvider avatarRuleValueProvider
- */
- public function testGetAvatarAttributes($setting, $expected) {
+ #[\PHPUnit\Framework\Attributes\DataProvider('avatarRuleValueProvider')]
+ public function testGetAvatarAttributes(string $setting, array $expected): void {
$this->configuration->setConfiguration(['ldapUserAvatarRule' => $setting]);
$this->assertSame($expected, $this->configuration->getAvatarAttributes());
}
- /**
- * @dataProvider avatarRuleValueProvider
- */
- public function testResolveRule($setting, $expected) {
+ #[\PHPUnit\Framework\Attributes\DataProvider('avatarRuleValueProvider')]
+ public function testResolveRule(string $setting, array $expected): void {
$this->configuration->setConfiguration(['ldapUserAvatarRule' => $setting]);
// so far the only thing that can get resolved :)
$this->assertSame($expected, $this->configuration->resolveRule('avatar'));
diff --git a/apps/user_ldap/tests/ConnectionTest.php b/apps/user_ldap/tests/ConnectionTest.php
index 1054448198b..7116e15898f 100644
--- a/apps/user_ldap/tests/ConnectionTest.php
+++ b/apps/user_ldap/tests/ConnectionTest.php
@@ -1,5 +1,6 @@
<?php
+declare(strict_types=1);
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -7,8 +8,10 @@
*/
namespace OCA\User_LDAP\Tests;
+use OC\ServerNotAvailableException;
use OCA\User_LDAP\Connection;
use OCA\User_LDAP\ILDAPWrapper;
+use PHPUnit\Framework\MockObject\MockObject;
/**
* Class Test_Connection
@@ -18,19 +21,16 @@ use OCA\User_LDAP\ILDAPWrapper;
* @package OCA\User_LDAP\Tests
*/
class ConnectionTest extends \Test\TestCase {
- /** @var \OCA\User_LDAP\ILDAPWrapper|\PHPUnit\Framework\MockObject\MockObject */
- protected $ldap;
-
- /** @var Connection */
- protected $connection;
+ protected ILDAPWrapper&MockObject $ldap;
+ protected Connection $connection;
protected function setUp(): void {
parent::setUp();
$this->ldap = $this->createMock(ILDAPWrapper::class);
// we use a mock here to replace the cache mechanism, due to missing DI in LDAP backend.
- $this->connection = $this->getMockBuilder('OCA\User_LDAP\Connection')
- ->setMethods(['getFromCache', 'writeToCache'])
+ $this->connection = $this->getMockBuilder(Connection::class)
+ ->onlyMethods(['getFromCache', 'writeToCache'])
->setConstructorArgs([$this->ldap, '', null])
->getMock();
@@ -39,7 +39,7 @@ class ConnectionTest extends \Test\TestCase {
->willReturn(true);
}
- public function testOriginalAgentUnchangedOnClone() {
+ public function testOriginalAgentUnchangedOnClone(): void {
//background: upon login a bind is done with the user credentials
//which is valid for the whole LDAP resource. It needs to be reset
//to the agent's credentials
@@ -66,7 +66,7 @@ class ConnectionTest extends \Test\TestCase {
$this->assertSame($agentPawd, $agent['ldapAgentPassword']);
}
- public function testUseBackupServer() {
+ public function testUseBackupServer(): void {
$mainHost = 'ldap://nixda.ldap';
$backupHost = 'ldap://fallback.ldap';
$config = [
@@ -101,8 +101,7 @@ class ConnectionTest extends \Test\TestCase {
// Not called often enough? Then, the fallback to the backup server is broken.
$this->connection->expects($this->exactly(2))
->method('getFromCache')
- ->with('overrideMainServer')
- ->will($this->onConsecutiveCalls(false, false, true, true));
+ ->with('overrideMainServer')->willReturnOnConsecutiveCalls(false, false, true, true);
$this->connection->expects($this->once())
->method('writeToCache')
@@ -114,7 +113,7 @@ class ConnectionTest extends \Test\TestCase {
->willReturnCallback(function () use (&$isThrown) {
if (!$isThrown) {
$isThrown = true;
- throw new \OC\ServerNotAvailableException();
+ throw new ServerNotAvailableException();
}
return true;
});
@@ -125,7 +124,7 @@ class ConnectionTest extends \Test\TestCase {
$this->connection->init();
}
- public function testDontUseBackupServerOnFailedAuth() {
+ public function testDontUseBackupServerOnFailedAuth(): void {
$mainHost = 'ldap://nixda.ldap';
$backupHost = 'ldap://fallback.ldap';
$config = [
@@ -172,7 +171,7 @@ class ConnectionTest extends \Test\TestCase {
$this->connection->init();
}
- public function testBindWithInvalidCredentials() {
+ public function testBindWithInvalidCredentials(): void {
// background: Bind with invalid credentials should return false
// and not throw a ServerNotAvailableException.
@@ -212,12 +211,12 @@ class ConnectionTest extends \Test\TestCase {
try {
$this->assertFalse($this->connection->bind(), 'Connection::bind() should not return true with invalid credentials.');
- } catch (\OC\ServerNotAvailableException $e) {
+ } catch (ServerNotAvailableException $e) {
$this->fail('Failed asserting that exception of type "OC\ServerNotAvailableException" is not thrown.');
}
}
- public function testStartTlsNegotiationFailure() {
+ public function testStartTlsNegotiationFailure(): void {
// background: If Start TLS negotiation fails,
// a ServerNotAvailableException should be thrown.
@@ -260,7 +259,7 @@ class ConnectionTest extends \Test\TestCase {
->method('startTls')
->willReturn(false);
- $this->expectException(\OC\ServerNotAvailableException::class);
+ $this->expectException(ServerNotAvailableException::class);
$this->expectExceptionMessage('Start TLS failed, when connecting to LDAP host ' . $host . '.');
$this->connection->init();
diff --git a/apps/user_ldap/tests/GroupLDAPPluginTest.php b/apps/user_ldap/tests/GroupLDAPPluginTest.php
index 24cfb5d51e9..9f4cff64d6b 100644
--- a/apps/user_ldap/tests/GroupLDAPPluginTest.php
+++ b/apps/user_ldap/tests/GroupLDAPPluginTest.php
@@ -1,4 +1,6 @@
<?php
+
+declare(strict_types=1);
/**
* SPDX-FileCopyrightText: 2017 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
@@ -9,27 +11,23 @@ use OCA\User_LDAP\GroupPluginManager;
use OCP\GroupInterface;
class GroupLDAPPluginTest extends \Test\TestCase {
-
- /**
- * @return GroupPluginManager
- */
- private function getGroupPluginManager() {
+ private function getGroupPluginManager(): GroupPluginManager {
return new GroupPluginManager();
}
- public function testImplementsActions() {
+ public function testImplementsActions(): void {
$pluginManager = $this->getGroupPluginManager();
- $plugin = $this->getMockBuilder('OCA\User_LDAP\Tests\LDAPGroupPluginDummy')
- ->setMethods(['respondToActions'])
+ $plugin = $this->getMockBuilder(LDAPGroupPluginDummy::class)
+ ->onlyMethods(['respondToActions'])
->getMock();
$plugin->expects($this->any())
->method('respondToActions')
->willReturn(GroupInterface::CREATE_GROUP);
- $plugin2 = $this->getMockBuilder('OCA\User_LDAP\Tests\LDAPGroupPluginDummy')
- ->setMethods(['respondToActions'])
+ $plugin2 = $this->getMockBuilder(LDAPGroupPluginDummy::class)
+ ->onlyMethods(['respondToActions'])
->getMock();
$plugin2->expects($this->any())
@@ -44,11 +42,11 @@ class GroupLDAPPluginTest extends \Test\TestCase {
$this->assertTrue($pluginManager->implementsActions(GroupInterface::ADD_TO_GROUP));
}
- public function testCreateGroup() {
+ public function testCreateGroup(): void {
$pluginManager = $this->getGroupPluginManager();
- $plugin = $this->getMockBuilder('OCA\User_LDAP\Tests\LDAPGroupPluginDummy')
- ->setMethods(['respondToActions', 'createGroup'])
+ $plugin = $this->getMockBuilder(LDAPGroupPluginDummy::class)
+ ->onlyMethods(['respondToActions', 'createGroup'])
->getMock();
$plugin->expects($this->any())
@@ -66,7 +64,7 @@ class GroupLDAPPluginTest extends \Test\TestCase {
}
- public function testCreateGroupNotRegistered() {
+ public function testCreateGroupNotRegistered(): void {
$this->expectException(\Exception::class);
$this->expectExceptionMessage('No plugin implements createGroup in this LDAP Backend.');
@@ -74,11 +72,11 @@ class GroupLDAPPluginTest extends \Test\TestCase {
$pluginManager->createGroup('foo');
}
- public function testDeleteGroup() {
+ public function testDeleteGroup(): void {
$pluginManager = $this->getGroupPluginManager();
- $plugin = $this->getMockBuilder('OCA\User_LDAP\Tests\LDAPGroupPluginDummy')
- ->setMethods(['respondToActions', 'deleteGroup'])
+ $plugin = $this->getMockBuilder(LDAPGroupPluginDummy::class)
+ ->onlyMethods(['respondToActions', 'deleteGroup'])
->getMock();
$plugin->expects($this->any())
@@ -96,7 +94,7 @@ class GroupLDAPPluginTest extends \Test\TestCase {
}
- public function testDeleteGroupNotRegistered() {
+ public function testDeleteGroupNotRegistered(): void {
$this->expectException(\Exception::class);
$this->expectExceptionMessage('No plugin implements deleteGroup in this LDAP Backend.');
@@ -104,11 +102,11 @@ class GroupLDAPPluginTest extends \Test\TestCase {
$pluginManager->deleteGroup('foo');
}
- public function testAddToGroup() {
+ public function testAddToGroup(): void {
$pluginManager = $this->getGroupPluginManager();
- $plugin = $this->getMockBuilder('OCA\User_LDAP\Tests\LDAPGroupPluginDummy')
- ->setMethods(['respondToActions', 'addToGroup'])
+ $plugin = $this->getMockBuilder(LDAPGroupPluginDummy::class)
+ ->onlyMethods(['respondToActions', 'addToGroup'])
->getMock();
$plugin->expects($this->any())
@@ -127,7 +125,7 @@ class GroupLDAPPluginTest extends \Test\TestCase {
}
- public function testAddToGroupNotRegistered() {
+ public function testAddToGroupNotRegistered(): void {
$this->expectException(\Exception::class);
$this->expectExceptionMessage('No plugin implements addToGroup in this LDAP Backend.');
@@ -135,11 +133,11 @@ class GroupLDAPPluginTest extends \Test\TestCase {
$pluginManager->addToGroup('foo', 'bar');
}
- public function testRemoveFromGroup() {
+ public function testRemoveFromGroup(): void {
$pluginManager = $this->getGroupPluginManager();
- $plugin = $this->getMockBuilder('OCA\User_LDAP\Tests\LDAPGroupPluginDummy')
- ->setMethods(['respondToActions', 'removeFromGroup'])
+ $plugin = $this->getMockBuilder(LDAPGroupPluginDummy::class)
+ ->onlyMethods(['respondToActions', 'removeFromGroup'])
->getMock();
$plugin->expects($this->any())
@@ -158,7 +156,7 @@ class GroupLDAPPluginTest extends \Test\TestCase {
}
- public function testRemoveFromGroupNotRegistered() {
+ public function testRemoveFromGroupNotRegistered(): void {
$this->expectException(\Exception::class);
$this->expectExceptionMessage('No plugin implements removeFromGroup in this LDAP Backend.');
@@ -166,11 +164,11 @@ class GroupLDAPPluginTest extends \Test\TestCase {
$pluginManager->removeFromGroup('foo', 'bar');
}
- public function testCountUsersInGroup() {
+ public function testCountUsersInGroup(): void {
$pluginManager = $this->getGroupPluginManager();
- $plugin = $this->getMockBuilder('OCA\User_LDAP\Tests\LDAPGroupPluginDummy')
- ->setMethods(['respondToActions', 'countUsersInGroup'])
+ $plugin = $this->getMockBuilder(LDAPGroupPluginDummy::class)
+ ->onlyMethods(['respondToActions', 'countUsersInGroup'])
->getMock();
$plugin->expects($this->any())
@@ -189,7 +187,7 @@ class GroupLDAPPluginTest extends \Test\TestCase {
}
- public function testCountUsersInGroupNotRegistered() {
+ public function testCountUsersInGroupNotRegistered(): void {
$this->expectException(\Exception::class);
$this->expectExceptionMessage('No plugin implements countUsersInGroup in this LDAP Backend.');
@@ -197,11 +195,11 @@ class GroupLDAPPluginTest extends \Test\TestCase {
$pluginManager->countUsersInGroup('foo', 'bar');
}
- public function testgetGroupDetails() {
+ public function testgetGroupDetails(): void {
$pluginManager = $this->getGroupPluginManager();
- $plugin = $this->getMockBuilder('OCA\User_LDAP\Tests\LDAPGroupPluginDummy')
- ->setMethods(['respondToActions', 'getGroupDetails'])
+ $plugin = $this->getMockBuilder(LDAPGroupPluginDummy::class)
+ ->onlyMethods(['respondToActions', 'getGroupDetails'])
->getMock();
$plugin->expects($this->any())
@@ -219,7 +217,7 @@ class GroupLDAPPluginTest extends \Test\TestCase {
}
- public function testgetGroupDetailsNotRegistered() {
+ public function testgetGroupDetailsNotRegistered(): void {
$this->expectException(\Exception::class);
$this->expectExceptionMessage('No plugin implements getGroupDetails in this LDAP Backend.');
diff --git a/apps/user_ldap/tests/Group_LDAPTest.php b/apps/user_ldap/tests/Group_LDAPTest.php
index 06d64b99a4f..10182111768 100644
--- a/apps/user_ldap/tests/Group_LDAPTest.php
+++ b/apps/user_ldap/tests/Group_LDAPTest.php
@@ -1,5 +1,6 @@
<?php
+declare(strict_types=1);
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -21,6 +22,8 @@ use OCP\GroupInterface;
use OCP\IConfig;
use OCP\IUser;
use OCP\IUserManager;
+use OCP\Security\ISecureRandom;
+use OCP\Server;
use PHPUnit\Framework\MockObject\MockObject;
use Test\TestCase;
@@ -32,10 +35,10 @@ use Test\TestCase;
* @package OCA\User_LDAP\Tests
*/
class Group_LDAPTest extends TestCase {
- private MockObject|Access $access;
- private MockObject|GroupPluginManager $pluginManager;
- private MockObject|IConfig $config;
- private MockObject|IUserManager $ncUserManager;
+ private Access&MockObject $access;
+ private GroupPluginManager&MockObject $pluginManager;
+ private IConfig&MockObject $config;
+ private IUserManager&MockObject $ncUserManager;
private GroupLDAP $groupBackend;
public function setUp(): void {
@@ -51,7 +54,7 @@ class Group_LDAPTest extends TestCase {
$this->groupBackend = new GroupLDAP($this->access, $this->pluginManager, $this->config, $this->ncUserManager);
}
- public function testCountEmptySearchString() {
+ public function testCountEmptySearchString(): void {
$groupDN = 'cn=group,dc=foo,dc=bar';
$this->enableGroups();
@@ -94,30 +97,19 @@ class Group_LDAPTest extends TestCase {
* @return MockObject|Access
*/
private function getAccessMock() {
- static $conMethods;
- static $accMethods;
-
- if (is_null($conMethods) || is_null($accMethods)) {
- $conMethods = get_class_methods(Connection::class);
- $accMethods = get_class_methods(Access::class);
- }
$lw = $this->createMock(ILDAPWrapper::class);
-
$connector = $this->getMockBuilder(Connection::class)
- ->setMethods($conMethods)
->setConstructorArgs([$lw, '', null])
->getMock();
$this->access = $this->createMock(Access::class);
-
$this->access->connection = $connector;
-
$this->access->userManager = $this->createMock(Manager::class);
return $this->access;
}
- private function enableGroups() {
+ private function enableGroups(): void {
$this->access->connection->expects($this->any())
->method('__get')
->willReturnCallback(function ($name) {
@@ -130,7 +122,7 @@ class Group_LDAPTest extends TestCase {
});
}
- public function testCountWithSearchString() {
+ public function testCountWithSearchString(): void {
$this->enableGroups();
$this->access->expects($this->any())
@@ -155,7 +147,7 @@ class Group_LDAPTest extends TestCase {
$this->access->expects($this->any())
->method('dn2username')
->willReturnCallback(function () {
- return 'foobar' . \OC::$server->getSecureRandom()->generate(7);
+ return 'foobar' . Server::get(ISecureRandom::class)->generate(7);
});
$this->access->expects($this->any())
->method('isDNPartOfBase')
@@ -174,10 +166,10 @@ class Group_LDAPTest extends TestCase {
$this->assertSame(2, $users);
}
- public function testCountUsersWithPlugin() {
+ public function testCountUsersWithPlugin(): void {
/** @var GroupPluginManager|MockObject $pluginManager */
$this->pluginManager = $this->getMockBuilder(GroupPluginManager::class)
- ->setMethods(['implementsActions', 'countUsersInGroup'])
+ ->onlyMethods(['implementsActions', 'countUsersInGroup'])
->getMock();
$this->pluginManager->expects($this->once())
@@ -194,7 +186,7 @@ class Group_LDAPTest extends TestCase {
$this->assertEquals($this->groupBackend->countUsersInGroup('gid', 'search'), 42);
}
- public function testGidNumber2NameSuccess() {
+ public function testGidNumber2NameSuccess(): void {
$this->enableGroups();
$userDN = 'cn=alice,cn=foo,dc=barfoo,dc=bar';
@@ -214,7 +206,7 @@ class Group_LDAPTest extends TestCase {
$this->assertSame('MyGroup', $group);
}
- public function testGidNumberID2NameNoGroup() {
+ public function testGidNumberID2NameNoGroup(): void {
$this->enableGroups();
$userDN = 'cn=alice,cn=foo,dc=barfoo,dc=bar';
@@ -232,7 +224,7 @@ class Group_LDAPTest extends TestCase {
$this->assertSame(false, $group);
}
- public function testGidNumberID2NameNoName() {
+ public function testGidNumberID2NameNoName(): void {
$this->enableGroups();
$userDN = 'cn=alice,cn=foo,dc=barfoo,dc=bar';
@@ -251,7 +243,7 @@ class Group_LDAPTest extends TestCase {
$this->assertSame(false, $group);
}
- public function testGetEntryGidNumberValue() {
+ public function testGetEntryGidNumberValue(): void {
$this->enableGroups();
$dn = 'cn=foobar,cn=foo,dc=barfoo,dc=bar';
@@ -268,7 +260,7 @@ class Group_LDAPTest extends TestCase {
$this->assertSame('3117', $gid);
}
- public function testGetEntryGidNumberNoValue() {
+ public function testGetEntryGidNumberNoValue(): void {
$this->enableGroups();
$dn = 'cn=foobar,cn=foo,dc=barfoo,dc=bar';
@@ -285,7 +277,7 @@ class Group_LDAPTest extends TestCase {
$this->assertSame(false, $gid);
}
- public function testPrimaryGroupID2NameSuccessCache() {
+ public function testPrimaryGroupID2NameSuccessCache(): void {
$this->enableGroups();
$userDN = 'cn=alice,cn=foo,dc=barfoo,dc=bar';
@@ -313,7 +305,7 @@ class Group_LDAPTest extends TestCase {
$this->assertSame('MyGroup', $group);
}
- public function testPrimaryGroupID2NameSuccess() {
+ public function testPrimaryGroupID2NameSuccess(): void {
$this->enableGroups();
$userDN = 'cn=alice,cn=foo,dc=barfoo,dc=bar';
@@ -338,7 +330,7 @@ class Group_LDAPTest extends TestCase {
$this->assertSame('MyGroup', $group);
}
- public function testPrimaryGroupID2NameNoSID() {
+ public function testPrimaryGroupID2NameNoSID(): void {
$this->enableGroups();
$userDN = 'cn=alice,cn=foo,dc=barfoo,dc=bar';
@@ -360,7 +352,7 @@ class Group_LDAPTest extends TestCase {
$this->assertSame(false, $group);
}
- public function testPrimaryGroupID2NameNoGroup() {
+ public function testPrimaryGroupID2NameNoGroup(): void {
$this->enableGroups();
$userDN = 'cn=alice,cn=foo,dc=barfoo,dc=bar';
@@ -383,7 +375,7 @@ class Group_LDAPTest extends TestCase {
$this->assertSame(false, $group);
}
- public function testPrimaryGroupID2NameNoName() {
+ public function testPrimaryGroupID2NameNoName(): void {
$this->enableGroups();
$userDN = 'cn=alice,cn=foo,dc=barfoo,dc=bar';
@@ -407,7 +399,7 @@ class Group_LDAPTest extends TestCase {
$this->assertSame(false, $group);
}
- public function testGetEntryGroupIDValue() {
+ public function testGetEntryGroupIDValue(): void {
//tests getEntryGroupID via getGroupPrimaryGroupID
//which is basically identical to getUserPrimaryGroupIDs
$this->enableGroups();
@@ -426,7 +418,7 @@ class Group_LDAPTest extends TestCase {
$this->assertSame('3117', $gid);
}
- public function testGetEntryGroupIDNoValue() {
+ public function testGetEntryGroupIDNoValue(): void {
//tests getEntryGroupID via getGroupPrimaryGroupID
//which is basically identical to getUserPrimaryGroupIDs
$this->enableGroups();
@@ -449,7 +441,7 @@ class Group_LDAPTest extends TestCase {
* tests whether Group Backend behaves correctly when cache with uid and gid
* is hit
*/
- public function testInGroupHitsUidGidCache() {
+ public function testInGroupHitsUidGidCache(): void {
$this->enableGroups();
$uid = 'someUser';
@@ -468,7 +460,7 @@ class Group_LDAPTest extends TestCase {
$this->groupBackend->inGroup($uid, $gid);
}
- public function groupWithMembersProvider() {
+ public static function groupWithMembersProvider(): array {
return [
[
'someGroup',
@@ -483,10 +475,8 @@ class Group_LDAPTest extends TestCase {
];
}
- /**
- * @dataProvider groupWithMembersProvider
- */
- public function testInGroupMember(string $gid, string $groupDn, array $memberDNs) {
+ #[\PHPUnit\Framework\Attributes\DataProvider('groupWithMembersProvider')]
+ public function testInGroupMember(string $gid, string $groupDn, array $memberDNs): void {
$uid = 'someUser';
$userDn = $memberDNs[0];
@@ -524,10 +514,8 @@ class Group_LDAPTest extends TestCase {
$this->assertTrue($this->groupBackend->inGroup($uid, $gid));
}
- /**
- * @dataProvider groupWithMembersProvider
- */
- public function testInGroupMemberNot(string $gid, string $groupDn, array $memberDNs) {
+ #[\PHPUnit\Framework\Attributes\DataProvider('groupWithMembersProvider')]
+ public function testInGroupMemberNot(string $gid, string $groupDn, array $memberDNs): void {
$uid = 'unelatedUser';
$userDn = 'uid=unrelatedUser,ou=unrelatedTeam,ou=unrelatedDepartment,dc=someDomain,dc=someTld';
@@ -565,14 +553,12 @@ class Group_LDAPTest extends TestCase {
$this->assertFalse($this->groupBackend->inGroup($uid, $gid));
}
- /**
- * @dataProvider groupWithMembersProvider
- */
- public function testInGroupMemberUid(string $gid, string $groupDn, array $memberDNs) {
+ #[\PHPUnit\Framework\Attributes\DataProvider('groupWithMembersProvider')]
+ public function testInGroupMemberUid(string $gid, string $groupDn, array $memberDNs): void {
$memberUids = [];
$userRecords = [];
foreach ($memberDNs as $dn) {
- $memberUids[] = ldap_explode_dn($dn, false)[0];
+ $memberUids[] = ldap_explode_dn($dn, 0)[0];
$userRecords[] = ['dn' => [$dn]];
}
@@ -625,7 +611,7 @@ class Group_LDAPTest extends TestCase {
$this->assertTrue($this->groupBackend->inGroup($uid, $gid));
}
- public function testGetGroupsWithOffset() {
+ public function testGetGroupsWithOffset(): void {
$this->enableGroups();
$this->access->expects($this->once())
@@ -642,7 +628,7 @@ class Group_LDAPTest extends TestCase {
* tests that a user listing is complete, if all its members have the group
* as their primary.
*/
- public function testUsersInGroupPrimaryMembersOnly() {
+ public function testUsersInGroupPrimaryMembersOnly(): void {
$this->enableGroups();
$this->access->connection->expects($this->any())
@@ -685,7 +671,7 @@ class Group_LDAPTest extends TestCase {
* tests that a user listing is complete, if all its members have the group
* as their primary.
*/
- public function testUsersInGroupPrimaryAndUnixMembers() {
+ public function testUsersInGroupPrimaryAndUnixMembers(): void {
$this->enableGroups();
$this->access->connection->expects($this->any())
@@ -726,7 +712,7 @@ class Group_LDAPTest extends TestCase {
* tests that a user counting is complete, if all its members have the group
* as their primary.
*/
- public function testCountUsersInGroupPrimaryMembersOnly() {
+ public function testCountUsersInGroupPrimaryMembersOnly(): void {
$this->enableGroups();
$this->access->connection->expects($this->any())
@@ -761,7 +747,7 @@ class Group_LDAPTest extends TestCase {
$this->assertSame(4, $users);
}
- public function testGetUserGroupsMemberOf() {
+ public function testGetUserGroupsMemberOf(): void {
$this->enableGroups();
$dn = 'cn=userX,dc=foobar';
@@ -775,8 +761,7 @@ class Group_LDAPTest extends TestCase {
->method('username2dn')
->willReturn($dn);
$this->access->expects($this->exactly(5))
- ->method('readAttribute')
- ->will($this->onConsecutiveCalls($expectedGroups, [], [], [], []));
+ ->method('readAttribute')->willReturnOnConsecutiveCalls($expectedGroups, [], [], [], []);
$this->access->expects($this->any())
->method('dn2groupname')
->willReturnArgument(0);
@@ -797,7 +782,7 @@ class Group_LDAPTest extends TestCase {
$this->assertSame(2, count($groups));
}
- public function testGetUserGroupsMemberOfDisabled() {
+ public function testGetUserGroupsMemberOfDisabled(): void {
$this->access->connection->expects($this->any())
->method('__get')
->willReturnCallback(function ($name) {
@@ -856,7 +841,7 @@ class Group_LDAPTest extends TestCase {
$this->groupBackend->getUserGroups('userX');
}
- public function testGetUserGroupsOfflineUser() {
+ public function testGetUserGroupsOfflineUser(): void {
$this->enableGroups();
$offlineUser = $this->createMock(OfflineUser::class);
@@ -874,15 +859,15 @@ class Group_LDAPTest extends TestCase {
$this->initBackend();
$returnedGroups = $this->groupBackend->getUserGroups('userX');
$this->assertCount(2, $returnedGroups);
- $this->assertTrue(in_array('groupB', $returnedGroups));
- $this->assertTrue(in_array('groupF', $returnedGroups));
+ $this->assertContains('groupB', $returnedGroups);
+ $this->assertContains('groupF', $returnedGroups);
}
/**
* regression tests against a case where a json object was stored instead of expected list
* @see https://github.com/nextcloud/server/issues/42374
*/
- public function testGetUserGroupsOfflineUserUnexpectedJson() {
+ public function testGetUserGroupsOfflineUserUnexpectedJson(): void {
$this->enableGroups();
$offlineUser = $this->createMock(OfflineUser::class);
@@ -901,11 +886,11 @@ class Group_LDAPTest extends TestCase {
$this->initBackend();
$returnedGroups = $this->groupBackend->getUserGroups('userX');
$this->assertCount(2, $returnedGroups);
- $this->assertTrue(in_array('groupB', $returnedGroups));
- $this->assertTrue(in_array('groupF', $returnedGroups));
+ $this->assertContains('groupB', $returnedGroups);
+ $this->assertContains('groupF', $returnedGroups);
}
- public function testGetUserGroupsUnrecognizedOfflineUser() {
+ public function testGetUserGroupsUnrecognizedOfflineUser(): void {
$this->enableGroups();
$dn = 'cn=userX,dc=foobar';
@@ -944,21 +929,19 @@ class Group_LDAPTest extends TestCase {
$this->initBackend();
$returnedGroups = $this->groupBackend->getUserGroups('userX');
$this->assertCount(2, $returnedGroups);
- $this->assertTrue(in_array('groupB', $returnedGroups));
- $this->assertTrue(in_array('groupF', $returnedGroups));
+ $this->assertContains('groupB', $returnedGroups);
+ $this->assertContains('groupF', $returnedGroups);
}
- public function nestedGroupsProvider(): array {
+ public static function nestedGroupsProvider(): array {
return [
[true],
[false],
];
}
- /**
- * @dataProvider nestedGroupsProvider
- */
- public function testGetGroupsByMember(bool $nestedGroups) {
+ #[\PHPUnit\Framework\Attributes\DataProvider('nestedGroupsProvider')]
+ public function testGetGroupsByMember(bool $nestedGroups): void {
$groupFilter = '(&(objectclass=nextcloudGroup)(nextcloudEnabled=TRUE))';
$this->access->connection->expects($this->any())
->method('__get')
@@ -1033,10 +1016,10 @@ class Group_LDAPTest extends TestCase {
$this->assertTrue(str_contains($filter, $groupFilter));
}
[$memberFilter] = explode('&', $filter);
- if ($memberFilter === 'member='.$dn) {
+ if ($memberFilter === 'member=' . $dn) {
return [$group1, $group2];
return [];
- } elseif ($memberFilter === 'member='.$group2['dn'][0]) {
+ } elseif ($memberFilter === 'member=' . $group2['dn'][0]) {
return [$group3];
} else {
return [];
@@ -1072,9 +1055,9 @@ class Group_LDAPTest extends TestCase {
$this->assertEquals($expectedGroupsNames, $groupsAgain);
}
- public function testCreateGroupWithPlugin() {
+ public function testCreateGroupWithPlugin(): void {
$this->pluginManager = $this->getMockBuilder(GroupPluginManager::class)
- ->setMethods(['implementsActions', 'createGroup'])
+ ->onlyMethods(['implementsActions', 'createGroup'])
->getMock();
$this->pluginManager->expects($this->once())
@@ -1088,15 +1071,15 @@ class Group_LDAPTest extends TestCase {
->willReturn('result');
$this->initBackend();
- $this->assertEquals($this->groupBackend->createGroup('gid'), true);
+ $this->assertTrue($this->groupBackend->createGroup('gid'));
}
- public function testCreateGroupFailing() {
+ public function testCreateGroupFailing(): void {
$this->expectException(\Exception::class);
$this->pluginManager = $this->getMockBuilder(GroupPluginManager::class)
- ->setMethods(['implementsActions', 'createGroup'])
+ ->onlyMethods(['implementsActions', 'createGroup'])
->getMock();
$this->pluginManager->expects($this->once())
@@ -1108,9 +1091,9 @@ class Group_LDAPTest extends TestCase {
$this->groupBackend->createGroup('gid');
}
- public function testDeleteGroupWithPlugin() {
+ public function testDeleteGroupWithPlugin(): void {
$this->pluginManager = $this->getMockBuilder(GroupPluginManager::class)
- ->setMethods(['implementsActions', 'deleteGroup'])
+ ->onlyMethods(['implementsActions', 'deleteGroup'])
->getMock();
$this->pluginManager->expects($this->once())
@@ -1124,7 +1107,7 @@ class Group_LDAPTest extends TestCase {
->willReturn(true);
$mapper = $this->getMockBuilder(GroupMapping::class)
- ->setMethods(['unmap'])
+ ->onlyMethods(['unmap'])
->disableOriginalConstructor()
->getMock();
@@ -1137,11 +1120,11 @@ class Group_LDAPTest extends TestCase {
}
- public function testDeleteGroupFailing() {
+ public function testDeleteGroupFailing(): void {
$this->expectException(\Exception::class);
$this->pluginManager = $this->getMockBuilder(GroupPluginManager::class)
- ->setMethods(['implementsActions', 'deleteGroup'])
+ ->onlyMethods(['implementsActions', 'deleteGroup'])
->getMock();
$this->pluginManager->expects($this->once())
@@ -1153,9 +1136,9 @@ class Group_LDAPTest extends TestCase {
$this->groupBackend->deleteGroup('gid');
}
- public function testAddToGroupWithPlugin() {
+ public function testAddToGroupWithPlugin(): void {
$this->pluginManager = $this->getMockBuilder(GroupPluginManager::class)
- ->setMethods(['implementsActions', 'addToGroup'])
+ ->onlyMethods(['implementsActions', 'addToGroup'])
->getMock();
$this->pluginManager->expects($this->once())
@@ -1169,15 +1152,15 @@ class Group_LDAPTest extends TestCase {
->willReturn('result');
$this->initBackend();
- $this->assertEquals($this->groupBackend->addToGroup('uid', 'gid'), 'result');
+ $this->assertEquals('result', $this->groupBackend->addToGroup('uid', 'gid'));
}
- public function testAddToGroupFailing() {
+ public function testAddToGroupFailing(): void {
$this->expectException(\Exception::class);
$this->pluginManager = $this->getMockBuilder(GroupPluginManager::class)
- ->setMethods(['implementsActions', 'addToGroup'])
+ ->onlyMethods(['implementsActions', 'addToGroup'])
->getMock();
$this->pluginManager->expects($this->once())
@@ -1189,9 +1172,9 @@ class Group_LDAPTest extends TestCase {
$this->groupBackend->addToGroup('uid', 'gid');
}
- public function testRemoveFromGroupWithPlugin() {
+ public function testRemoveFromGroupWithPlugin(): void {
$this->pluginManager = $this->getMockBuilder(GroupPluginManager::class)
- ->setMethods(['implementsActions', 'removeFromGroup'])
+ ->onlyMethods(['implementsActions', 'removeFromGroup'])
->getMock();
$this->pluginManager->expects($this->once())
@@ -1205,15 +1188,15 @@ class Group_LDAPTest extends TestCase {
->willReturn('result');
$this->initBackend();
- $this->assertEquals($this->groupBackend->removeFromGroup('uid', 'gid'), 'result');
+ $this->assertEquals('result', $this->groupBackend->removeFromGroup('uid', 'gid'));
}
- public function testRemoveFromGroupFailing() {
+ public function testRemoveFromGroupFailing(): void {
$this->expectException(\Exception::class);
$this->pluginManager = $this->getMockBuilder(GroupPluginManager::class)
- ->setMethods(['implementsActions', 'removeFromGroup'])
+ ->onlyMethods(['implementsActions', 'removeFromGroup'])
->getMock();
$this->pluginManager->expects($this->once())
@@ -1225,10 +1208,10 @@ class Group_LDAPTest extends TestCase {
$this->groupBackend->removeFromGroup('uid', 'gid');
}
- public function testGetGroupDetailsWithPlugin() {
+ public function testGetGroupDetailsWithPlugin(): void {
/** @var GroupPluginManager|MockObject $pluginManager */
$this->pluginManager = $this->getMockBuilder(GroupPluginManager::class)
- ->setMethods(['implementsActions', 'getGroupDetails'])
+ ->onlyMethods(['implementsActions', 'getGroupDetails'])
->getMock();
$this->pluginManager->expects($this->once())
@@ -1242,14 +1225,14 @@ class Group_LDAPTest extends TestCase {
->willReturn('result');
$this->initBackend();
- $this->assertEquals($this->groupBackend->getGroupDetails('gid'), 'result');
+ $this->assertEquals('result', $this->groupBackend->getGroupDetails('gid'));
}
- public function testGetGroupDetailsFailing() {
+ public function testGetGroupDetailsFailing(): void {
$this->expectException(\Exception::class);
$this->pluginManager = $this->getMockBuilder(GroupPluginManager::class)
- ->setMethods(['implementsActions', 'getGroupDetails'])
+ ->onlyMethods(['implementsActions', 'getGroupDetails'])
->getMock();
$this->pluginManager->expects($this->once())
@@ -1261,7 +1244,7 @@ class Group_LDAPTest extends TestCase {
$this->groupBackend->getGroupDetails('gid');
}
- public function groupMemberProvider() {
+ public static function groupMemberProvider(): array {
$base = 'dc=species,dc=earth';
$birdsDn = [
@@ -1329,11 +1312,8 @@ class Group_LDAPTest extends TestCase {
];
}
- /**
- * @param string[] $expectedMembers
- * @dataProvider groupMemberProvider
- */
- public function testGroupMembers(array $expectedResult, ?array $groupsInfo = null) {
+ #[\PHPUnit\Framework\Attributes\DataProvider('groupMemberProvider')]
+ public function testGroupMembers(array $expectedResult, array $groupsInfo): void {
$this->access->expects($this->any())
->method('readAttribute')
->willReturnCallback(function ($group) use ($groupsInfo) {
@@ -1358,21 +1338,21 @@ class Group_LDAPTest extends TestCase {
foreach ($expectedResult as $groupDN => $expectedMembers) {
$resultingMembers = $this->invokePrivate($this->groupBackend, '_groupMembers', [$groupDN]);
- $this->assertEqualsCanonicalizing($expectedMembers, $resultingMembers);
+ sort($expectedMembers);
+ sort($resultingMembers);
+ $this->assertEquals($expectedMembers, $resultingMembers);
}
}
- public function displayNameProvider() {
+ public static function displayNameProvider(): array {
return [
['Graphic Novelists', ['Graphic Novelists']],
['', false],
];
}
- /**
- * @dataProvider displayNameProvider
- */
- public function testGetDisplayName(string $expected, $ldapResult) {
+ #[\PHPUnit\Framework\Attributes\DataProvider('displayNameProvider')]
+ public function testGetDisplayName(string $expected, bool|array $ldapResult): void {
$gid = 'graphic_novelists';
$this->access->expects($this->atLeastOnce())
diff --git a/apps/user_ldap/tests/HelperTest.php b/apps/user_ldap/tests/HelperTest.php
index bbb3956f918..adea600d900 100644
--- a/apps/user_ldap/tests/HelperTest.php
+++ b/apps/user_ldap/tests/HelperTest.php
@@ -1,4 +1,6 @@
<?php
+
+declare(strict_types=1);
/**
* SPDX-FileCopyrightText: 2016 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
@@ -6,54 +8,62 @@
namespace OCA\User_LDAP\Tests;
use OCA\User_LDAP\Helper;
-use OCP\IConfig;
+use OCP\IAppConfig;
+use OCP\IDBConnection;
+use OCP\Server;
+use PHPUnit\Framework\MockObject\MockObject;
/**
* @group DB
*/
class HelperTest extends \Test\TestCase {
+ private IAppConfig&MockObject $appConfig;
- /** @var IConfig|\PHPUnit\Framework\MockObject\MockObject */
- private $config;
-
- /** @var Helper */
- private $helper;
+ private Helper $helper;
protected function setUp(): void {
parent::setUp();
- $this->config = $this->createMock(IConfig::class);
- $this->helper = new Helper($this->config, \OC::$server->getDatabaseConnection());
+ $this->appConfig = $this->createMock(IAppConfig::class);
+ $this->helper = new Helper(
+ $this->appConfig,
+ Server::get(IDBConnection::class)
+ );
}
- public function testGetServerConfigurationPrefixes() {
- $this->config->method('getAppKeys')
- ->with($this->equalTo('user_ldap'))
+ public function testGetServerConfigurationPrefixes(): void {
+ $this->appConfig->method('getKeys')
+ ->with('user_ldap')
->willReturn([
'foo',
'ldap_configuration_active',
's1ldap_configuration_active',
]);
+ $this->appConfig->method('getValueArray')
+ ->with('user_ldap', 'configuration_prefixes')
+ -> willReturnArgument(2);
+
$result = $this->helper->getServerConfigurationPrefixes(false);
$this->assertEquals(['', 's1'], $result);
}
- public function testGetServerConfigurationPrefixesActive() {
- $this->config->method('getAppKeys')
- ->with($this->equalTo('user_ldap'))
+ public function testGetServerConfigurationPrefixesActive(): void {
+ $this->appConfig->method('getKeys')
+ ->with('user_ldap')
->willReturn([
'foo',
'ldap_configuration_active',
's1ldap_configuration_active',
]);
- $this->config->method('getAppValue')
+ $this->appConfig->method('getValueArray')
+ ->with('user_ldap', 'configuration_prefixes')
+ -> willReturnArgument(2);
+
+ $this->appConfig->method('getValueString')
->willReturnCallback(function ($app, $key, $default) {
- if ($app !== 'user_ldap') {
- $this->fail('wrong app');
- }
if ($key === 's1ldap_configuration_active') {
return '1';
}
@@ -65,21 +75,58 @@ class HelperTest extends \Test\TestCase {
$this->assertEquals(['s1'], $result);
}
- public function testGetServerConfigurationHost() {
- $this->config->method('getAppKeys')
- ->with($this->equalTo('user_ldap'))
+ public function testGetServerConfigurationHostFromAppKeys(): void {
+ $this->appConfig->method('getKeys')
+ ->with('user_ldap')
->willReturn([
'foo',
'ldap_host',
's1ldap_host',
's02ldap_host',
+ 'ldap_configuration_active',
+ 's1ldap_configuration_active',
+ 's02ldap_configuration_active',
]);
- $this->config->method('getAppValue')
+ $this->appConfig->method('getValueArray')
+ ->with('user_ldap', 'configuration_prefixes')
+ -> willReturnArgument(2);
+
+ $this->appConfig->method('getValueString')
->willReturnCallback(function ($app, $key, $default) {
- if ($app !== 'user_ldap') {
- $this->fail('wrong app');
+ if ($key === 'ldap_host') {
+ return 'example.com';
}
+ if ($key === 's1ldap_host') {
+ return 'foo.bar.com';
+ }
+ return $default;
+ });
+
+ $result = $this->helper->getServerConfigurationHosts();
+
+ $this->assertEquals([
+ '' => 'example.com',
+ 's1' => 'foo.bar.com',
+ 's02' => '',
+ ], $result);
+ }
+
+ public function testGetServerConfigurationHost(): void {
+ $this->appConfig
+ ->expects(self::never())
+ ->method('getKeys');
+
+ $this->appConfig->method('getValueArray')
+ ->with('user_ldap', 'configuration_prefixes')
+ -> willReturn([
+ '',
+ 's1',
+ 's02',
+ ]);
+
+ $this->appConfig->method('getValueString')
+ ->willReturnCallback(function ($app, $key, $default) {
if ($key === 'ldap_host') {
return 'example.com';
}
diff --git a/apps/user_ldap/tests/Integration/AbstractIntegrationTest.php b/apps/user_ldap/tests/Integration/AbstractIntegrationTest.php
index ef84beb8f56..00f8be18586 100644
--- a/apps/user_ldap/tests/Integration/AbstractIntegrationTest.php
+++ b/apps/user_ldap/tests/Integration/AbstractIntegrationTest.php
@@ -9,21 +9,24 @@ namespace OCA\User_LDAP\Tests\Integration;
use OCA\User_LDAP\Access;
use OCA\User_LDAP\Connection;
-use OCA\User_LDAP\FilesystemHelper;
use OCA\User_LDAP\GroupPluginManager;
use OCA\User_LDAP\Helper;
use OCA\User_LDAP\LDAP;
use OCA\User_LDAP\User\Manager;
use OCA\User_LDAP\UserPluginManager;
use OCP\IAvatarManager;
+use OCP\IConfig;
+use OCP\Image;
+use OCP\IUserManager;
+use OCP\Server;
use OCP\Share\IManager;
use Psr\Log\LoggerInterface;
abstract class AbstractIntegrationTest {
- /** @var LDAP */
+ /** @var LDAP */
protected $ldap;
- /** @var Connection */
+ /** @var Connection */
protected $connection;
/** @var Access */
@@ -35,14 +38,19 @@ abstract class AbstractIntegrationTest {
/** @var Helper */
protected $helper;
- /** @var string */
- protected $base;
-
/** @var string[] */
protected $server;
- public function __construct($host, $port, $bind, $pwd, $base) {
- $this->base = $base;
+ /**
+ * @param string $base
+ */
+ public function __construct(
+ $host,
+ $port,
+ $bind,
+ $pwd,
+ protected $base,
+ ) {
$this->server = [
'host' => $host,
'port' => $port,
@@ -57,10 +65,10 @@ abstract class AbstractIntegrationTest {
*/
public function init() {
\OC::$server->registerService(UserPluginManager::class, function () {
- return new \OCA\User_LDAP\UserPluginManager();
+ return new UserPluginManager();
});
\OC::$server->registerService(GroupPluginManager::class, function () {
- return new \OCA\User_LDAP\GroupPluginManager();
+ return new GroupPluginManager();
});
$this->initLDAPWrapper();
@@ -102,14 +110,13 @@ abstract class AbstractIntegrationTest {
*/
protected function initUserManager() {
$this->userManager = new Manager(
- \OC::$server->getConfig(),
- new FilesystemHelper(),
- \OC::$server->get(LoggerInterface::class),
- \OC::$server->get(IAvatarManager::class),
- new \OCP\Image(),
- \OC::$server->getUserManager(),
- \OC::$server->getNotificationManager(),
- \OC::$server->get(IManager::class)
+ Server::get(IConfig::class),
+ Server::get(LoggerInterface::class),
+ Server::get(IAvatarManager::class),
+ new Image(),
+ Server::get(IUserManager::class),
+ Server::get(\OCP\Notification\IManager::class),
+ Server::get(IManager::class)
);
}
@@ -117,14 +124,14 @@ abstract class AbstractIntegrationTest {
* initializes the test Helper
*/
protected function initHelper() {
- $this->helper = new Helper(\OC::$server->getConfig(), \OC::$server->getDatabaseConnection());
+ $this->helper = Server::get(Helper::class);
}
/**
* initializes the Access test instance
*/
protected function initAccess() {
- $this->access = new Access($this->connection, $this->ldap, $this->userManager, $this->helper, \OC::$server->getConfig(), \OCP\Server::get(LoggerInterface::class));
+ $this->access = new Access($this->connection, $this->ldap, $this->userManager, $this->helper, Server::get(IConfig::class), Server::get(LoggerInterface::class));
}
/**
diff --git a/apps/user_ldap/tests/Integration/Bootstrap.php b/apps/user_ldap/tests/Integration/Bootstrap.php
index 872e06139ff..ef0909d4bea 100644
--- a/apps/user_ldap/tests/Integration/Bootstrap.php
+++ b/apps/user_ldap/tests/Integration/Bootstrap.php
@@ -1,8 +1,9 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
define('CLI_TEST_RUN', true);
-require_once __DIR__ . '/../../../../lib/base.php';
+require_once __DIR__ . '/../../../../lib/base.php';
require_once __DIR__ . '/setup-scripts/config.php';
diff --git a/apps/user_ldap/tests/Integration/ExceptionOnLostConnection.php b/apps/user_ldap/tests/Integration/ExceptionOnLostConnection.php
index 7dc2aa00065..3eec3df675a 100644
--- a/apps/user_ldap/tests/Integration/ExceptionOnLostConnection.php
+++ b/apps/user_ldap/tests/Integration/ExceptionOnLostConnection.php
@@ -9,6 +9,8 @@ namespace OCA\User_LDAP\Tests\Integration;
use OC\ServerNotAvailableException;
use OCA\User_LDAP\LDAP;
+use OCP\App\IAppManager;
+use OCP\Server;
/**
* Class ExceptionOnLostConnection
@@ -21,44 +23,29 @@ use OCA\User_LDAP\LDAP;
*
*/
class ExceptionOnLostConnection {
- /** @var string */
- private $toxiProxyHost;
-
- /** @var string */
- private $toxiProxyName;
-
- /** @var string */
- private $ldapBase;
-
- /** @var string|null */
- private $ldapBindDN;
-
- /** @var string|null */
- private $ldapBindPwd;
-
- /** @var string */
+ /** @var string */
private $ldapHost;
- /** @var \OCA\User_LDAP\LDAP */
+ /** @var LDAP */
private $ldap;
- /** @var bool */
+ /** @var bool */
private $originalProxyState;
/**
- * @param string $proxyHost host of toxiproxy as url, like http://localhost:8474
- * @param string $proxyName name of the LDAP proxy service as configured in toxiProxy
+ * @param string $toxiProxyHost host of toxiproxy as url, like http://localhost:8474
+ * @param string $toxiProxyName name of the LDAP proxy service as configured in toxiProxy
* @param string $ldapBase any valid LDAP base DN
- * @param null $bindDN optional, bind DN if anonymous bind is not possible
- * @param null $bindPwd optional
+ * @param null $ldapBindDN optional, bind DN if anonymous bind is not possible
+ * @param null $ldapBindPwd optional
*/
- public function __construct($proxyHost, $proxyName, $ldapBase, $bindDN = null, $bindPwd = null) {
- $this->toxiProxyHost = $proxyHost;
- $this->toxiProxyName = $proxyName;
- $this->ldapBase = $ldapBase;
- $this->ldapBindDN = $bindDN;
- $this->ldapBindPwd = $bindPwd;
-
+ public function __construct(
+ private $toxiProxyHost,
+ private $toxiProxyName,
+ private $ldapBase,
+ private $ldapBindDN = null,
+ private $ldapBindPwd = null,
+ ) {
$this->setUp();
}
@@ -77,8 +64,8 @@ class ExceptionOnLostConnection {
* @throws \Exception
*/
public function setUp(): void {
- require_once __DIR__ . '/../../../../lib/base.php';
- \OC_App::loadApps(['user_ldap']);
+ require_once __DIR__ . '/../../../../lib/base.php';
+ Server::get(IAppManager::class)->loadApps(['user_ldap']);
$ch = $this->getCurl();
$proxyInfoJson = curl_exec($ch);
@@ -117,10 +104,10 @@ class ExceptionOnLostConnection {
try {
$this->ldap->search($cr, $this->ldapBase, 'objectClass=*', ['dn'], true, 5);
} catch (ServerNotAvailableException $e) {
- print("Test PASSED" . PHP_EOL);
+ print('Test PASSED' . PHP_EOL);
exit(0);
}
- print("Test FAILED" . PHP_EOL);
+ print('Test FAILED' . PHP_EOL);
exit(1);
}
diff --git a/apps/user_ldap/tests/Integration/Lib/IntegrationTestAttributeDetection.php b/apps/user_ldap/tests/Integration/Lib/IntegrationTestAttributeDetection.php
index dbfe568d383..e1529384239 100644
--- a/apps/user_ldap/tests/Integration/Lib/IntegrationTestAttributeDetection.php
+++ b/apps/user_ldap/tests/Integration/Lib/IntegrationTestAttributeDetection.php
@@ -1,9 +1,10 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2017 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
-namespace OCA\user_ldap\tests\Integration\Lib;
+namespace OCA\User_LDAP\Tests\Integration\Lib;
use OCA\User_LDAP\Group_LDAP;
use OCA\User_LDAP\GroupPluginManager;
@@ -14,6 +15,10 @@ use OCA\User_LDAP\User\DeletedUsersIndex;
use OCA\User_LDAP\User_LDAP;
use OCA\User_LDAP\UserPluginManager;
use OCP\IConfig;
+use OCP\IDBConnection;
+use OCP\IGroupManager;
+use OCP\IUserManager;
+use OCP\Server;
use Psr\Log\LoggerInterface;
require_once __DIR__ . '/../Bootstrap.php';
@@ -28,28 +33,28 @@ class IntegrationTestAttributeDetection extends AbstractIntegrationTest {
$this->connection->setConfiguration(['ldapGroupFilter' => 'objectClass=groupOfNames']);
$this->connection->setConfiguration(['ldapGroupMemberAssocAttr' => 'member']);
- $userMapper = new UserMapping(\OC::$server->getDatabaseConnection());
+ $userMapper = new UserMapping(Server::get(IDBConnection::class));
$userMapper->clear();
$this->access->setUserMapper($userMapper);
- $groupMapper = new GroupMapping(\OC::$server->getDatabaseConnection());
+ $groupMapper = new GroupMapping(Server::get(IDBConnection::class));
$groupMapper->clear();
$this->access->setGroupMapper($groupMapper);
- $userBackend = new User_LDAP($this->access, \OC::$server->getConfig(), \OC::$server->getNotificationManager(), \OC::$server->getUserSession(), \OC::$server->get(UserPluginManager::class), \OC::$server->get(LoggerInterface::class), \OC::$server->get(DeletedUsersIndex::class));
- $userManager = \OC::$server->getUserManager();
+ $userBackend = new User_LDAP($this->access, Server::get(\OCP\Notification\IManager::class), Server::get(UserPluginManager::class), Server::get(LoggerInterface::class), Server::get(DeletedUsersIndex::class));
+ $userManager = Server::get(IUserManager::class);
$userManager->clearBackends();
$userManager->registerBackend($userBackend);
- $groupBackend = new Group_LDAP($this->access, \OC::$server->query(GroupPluginManager::class), \OC::$server->get(IConfig::class));
- $groupManger = \OC::$server->getGroupManager();
+ $groupBackend = new Group_LDAP($this->access, Server::get(GroupPluginManager::class), Server::get(IConfig::class));
+ $groupManger = Server::get(IGroupManager::class);
$groupManger->clearBackends();
$groupManger->addBackend($groupBackend);
}
protected function caseNativeUUIDAttributeUsers() {
// trigger importing of users which also triggers UUID attribute detection
- \OC::$server->getUserManager()->search('', 5, 0);
+ Server::get(IUserManager::class)->search('', 5, 0);
return $this->connection->ldapUuidUserAttribute === 'entryuuid';
}
@@ -58,7 +63,7 @@ class IntegrationTestAttributeDetection extends AbstractIntegrationTest {
// are similar, but we take no chances.
// trigger importing of users which also triggers UUID attribute detection
- \OC::$server->getGroupManager()->search('', 5, 0);
+ Server::get(IGroupManager::class)->search('', 5, 0);
return $this->connection->ldapUuidGroupAttribute === 'entryuuid';
}
}
diff --git a/apps/user_ldap/tests/Integration/Lib/IntegrationTestFetchUsersByLoginName.php b/apps/user_ldap/tests/Integration/Lib/IntegrationTestFetchUsersByLoginName.php
index f45317fde2e..1c2d7145ddf 100644
--- a/apps/user_ldap/tests/Integration/Lib/IntegrationTestFetchUsersByLoginName.php
+++ b/apps/user_ldap/tests/Integration/Lib/IntegrationTestFetchUsersByLoginName.php
@@ -12,12 +12,14 @@ use OCA\User_LDAP\Tests\Integration\AbstractIntegrationTest;
use OCA\User_LDAP\User\DeletedUsersIndex;
use OCA\User_LDAP\User_LDAP;
use OCA\User_LDAP\UserPluginManager;
+use OCP\IDBConnection;
+use OCP\Server;
use Psr\Log\LoggerInterface;
require_once __DIR__ . '/../Bootstrap.php';
class IntegrationTestFetchUsersByLoginName extends AbstractIntegrationTest {
- /** @var UserMapping */
+ /** @var UserMapping */
protected $mapping;
/** @var User_LDAP */
@@ -31,10 +33,10 @@ class IntegrationTestFetchUsersByLoginName extends AbstractIntegrationTest {
require(__DIR__ . '/../setup-scripts/createExplicitUsers.php');
parent::init();
- $this->mapping = new UserMapping(\OC::$server->getDatabaseConnection());
+ $this->mapping = new UserMapping(Server::get(IDBConnection::class));
$this->mapping->clear();
$this->access->setUserMapper($this->mapping);
- $this->backend = new User_LDAP($this->access, \OC::$server->getConfig(), \OC::$server->getNotificationManager(), \OC::$server->getUserSession(), \OC::$server->get(UserPluginManager::class), \OC::$server->get(LoggerInterface::class), \OC::$server->get(DeletedUsersIndex::class));
+ $this->backend = new User_LDAP($this->access, Server::get(\OCP\Notification\IManager::class), Server::get(UserPluginManager::class), Server::get(LoggerInterface::class), Server::get(DeletedUsersIndex::class));
}
/**
diff --git a/apps/user_ldap/tests/Integration/Lib/IntegrationTestPaging.php b/apps/user_ldap/tests/Integration/Lib/IntegrationTestPaging.php
index 1a4923c8fc0..3e21d22fca3 100644
--- a/apps/user_ldap/tests/Integration/Lib/IntegrationTestPaging.php
+++ b/apps/user_ldap/tests/Integration/Lib/IntegrationTestPaging.php
@@ -12,12 +12,13 @@ use OCA\User_LDAP\Tests\Integration\AbstractIntegrationTest;
use OCA\User_LDAP\User\DeletedUsersIndex;
use OCA\User_LDAP\User_LDAP;
use OCA\User_LDAP\UserPluginManager;
+use OCP\Server;
use Psr\Log\LoggerInterface;
require_once __DIR__ . '/../Bootstrap.php';
class IntegrationTestPaging extends AbstractIntegrationTest {
- /** @var UserMapping */
+ /** @var UserMapping */
protected $mapping;
/** @var User_LDAP */
@@ -34,7 +35,7 @@ class IntegrationTestPaging extends AbstractIntegrationTest {
require(__DIR__ . '/../setup-scripts/createExplicitUsers.php');
parent::init();
- $this->backend = new User_LDAP($this->access, \OC::$server->getConfig(), \OC::$server->getNotificationManager(), \OC::$server->getUserSession(), \OC::$server->get(UserPluginManager::class), \OC::$server->get(LoggerInterface::class), \OC::$server->get(DeletedUsersIndex::class));
+ $this->backend = new User_LDAP($this->access, Server::get(\OCP\Notification\IManager::class), Server::get(UserPluginManager::class), Server::get(LoggerInterface::class), Server::get(DeletedUsersIndex::class));
}
public function initConnection() {
diff --git a/apps/user_ldap/tests/Integration/Lib/User/IntegrationTestUserAvatar.php b/apps/user_ldap/tests/Integration/Lib/User/IntegrationTestUserAvatar.php
index 708f00c6214..6726143a449 100644
--- a/apps/user_ldap/tests/Integration/Lib/User/IntegrationTestUserAvatar.php
+++ b/apps/user_ldap/tests/Integration/Lib/User/IntegrationTestUserAvatar.php
@@ -7,7 +7,6 @@
*/
namespace OCA\User_LDAP\Tests\Integration\Lib\User;
-use OCA\User_LDAP\FilesystemHelper;
use OCA\User_LDAP\Mapping\UserMapping;
use OCA\User_LDAP\Tests\Integration\AbstractIntegrationTest;
use OCA\User_LDAP\User\DeletedUsersIndex;
@@ -16,13 +15,17 @@ use OCA\User_LDAP\User\User;
use OCA\User_LDAP\User_LDAP;
use OCA\User_LDAP\UserPluginManager;
use OCP\IAvatarManager;
+use OCP\IConfig;
+use OCP\IDBConnection;
use OCP\Image;
+use OCP\IUserManager;
+use OCP\Server;
use Psr\Log\LoggerInterface;
require_once __DIR__ . '/../../Bootstrap.php';
class IntegrationTestUserAvatar extends AbstractIntegrationTest {
- /** @var UserMapping */
+ /** @var UserMapping */
protected $mapping;
/**
@@ -32,11 +35,11 @@ class IntegrationTestUserAvatar extends AbstractIntegrationTest {
public function init() {
require(__DIR__ . '/../../setup-scripts/createExplicitUsers.php');
parent::init();
- $this->mapping = new UserMapping(\OC::$server->getDatabaseConnection());
+ $this->mapping = new UserMapping(Server::get(IDBConnection::class));
$this->mapping->clear();
$this->access->setUserMapper($this->mapping);
- $userBackend = new User_LDAP($this->access, \OC::$server->getConfig(), \OC::$server->getNotificationManager(), \OC::$server->getUserSession(), \OC::$server->get(UserPluginManager::class), \OC::$server->get(LoggerInterface::class), \OC::$server->get(DeletedUsersIndex::class));
- \OC_User::useBackend($userBackend);
+ $userBackend = new User_LDAP($this->access, Server::get(\OCP\Notification\IManager::class), Server::get(UserPluginManager::class), Server::get(LoggerInterface::class), Server::get(DeletedUsersIndex::class));
+ Server::get(IUserManager::class)->registerBackend($userBackend);
}
/**
@@ -58,9 +61,9 @@ class IntegrationTestUserAvatar extends AbstractIntegrationTest {
\OC_Util::tearDownFS();
\OC_Util::setupFS($username);
\OC::$server->getUserFolder($username);
- \OC::$server->getConfig()->deleteUserValue($username, 'user_ldap', User::USER_PREFKEY_LASTREFRESH);
- if (\OC::$server->get(IAvatarManager::class)->getAvatar($username)->exists()) {
- \OC::$server->get(IAvatarManager::class)->getAvatar($username)->remove();
+ Server::get(IConfig::class)->deleteUserValue($username, 'user_ldap', User::USER_PREFKEY_LASTREFRESH);
+ if (Server::get(IAvatarManager::class)->getAvatar($username)->exists()) {
+ Server::get(IAvatarManager::class)->getAvatar($username)->remove();
}
// finally attempt to get the avatar set
@@ -80,7 +83,7 @@ class IntegrationTestUserAvatar extends AbstractIntegrationTest {
$this->execFetchTest($dn, $username, $image);
- return \OC::$server->get(IAvatarManager::class)->getAvatar($username)->exists();
+ return Server::get(IAvatarManager::class)->getAvatar($username)->exists();
}
/**
@@ -97,7 +100,7 @@ class IntegrationTestUserAvatar extends AbstractIntegrationTest {
$this->execFetchTest($dn, $username, $image);
- return !\OC::$server->get(IAvatarManager::class)->getAvatar($username)->exists();
+ return !Server::get(IAvatarManager::class)->getAvatar($username)->exists();
}
/**
@@ -114,14 +117,13 @@ class IntegrationTestUserAvatar extends AbstractIntegrationTest {
protected function initUserManager() {
$this->userManager = new Manager(
- \OC::$server->getConfig(),
- new FilesystemHelper(),
- \OC::$server->get(LoggerInterface::class),
- \OC::$server->get(IAvatarManager::class),
+ Server::get(IConfig::class),
+ Server::get(LoggerInterface::class),
+ Server::get(IAvatarManager::class),
new Image(),
- \OC::$server->getDatabaseConnection(),
- \OC::$server->getUserManager(),
- \OC::$server->getNotificationManager()
+ Server::get(IDBConnection::class),
+ Server::get(IUserManager::class),
+ Server::get(\OCP\Notification\IManager::class)
);
}
diff --git a/apps/user_ldap/tests/Integration/Lib/User/IntegrationTestUserCleanUp.php b/apps/user_ldap/tests/Integration/Lib/User/IntegrationTestUserCleanUp.php
index 16685c136e8..9b05298a151 100644
--- a/apps/user_ldap/tests/Integration/Lib/User/IntegrationTestUserCleanUp.php
+++ b/apps/user_ldap/tests/Integration/Lib/User/IntegrationTestUserCleanUp.php
@@ -13,12 +13,15 @@ use OCA\User_LDAP\Tests\Integration\AbstractIntegrationTest;
use OCA\User_LDAP\User\DeletedUsersIndex;
use OCA\User_LDAP\User_LDAP;
use OCA\User_LDAP\UserPluginManager;
+use OCP\IDBConnection;
+use OCP\IUserManager;
+use OCP\Server;
use Psr\Log\LoggerInterface;
require_once __DIR__ . '/../../Bootstrap.php';
class IntegrationTestUserCleanUp extends AbstractIntegrationTest {
- /** @var UserMapping */
+ /** @var UserMapping */
protected $mapping;
/**
@@ -28,12 +31,12 @@ class IntegrationTestUserCleanUp extends AbstractIntegrationTest {
public function init() {
require(__DIR__ . '/../../setup-scripts/createExplicitUsers.php');
parent::init();
- $this->mapping = new UserMapping(\OC::$server->getDatabaseConnection());
+ $this->mapping = new UserMapping(Server::get(IDBConnection::class));
$this->mapping->clear();
$this->access->setUserMapper($this->mapping);
- $userBackend = new User_LDAP($this->access, \OC::$server->getConfig(), \OC::$server->getNotificationManager(), \OC::$server->getUserSession(), \OC::$server->get(UserPluginManager::class), \OC::$server->get(LoggerInterface::class), \OC::$server->get(DeletedUsersIndex::class));
- \OC_User::useBackend($userBackend);
+ $userBackend = new User_LDAP($this->access, Server::get(\OCP\Notification\IManager::class), Server::get(UserPluginManager::class), Server::get(LoggerInterface::class), Server::get(DeletedUsersIndex::class));
+ Server::get(IUserManager::class)->registerBackend($userBackend);
}
/**
@@ -70,13 +73,13 @@ class IntegrationTestUserCleanUp extends AbstractIntegrationTest {
// user instance must not be requested from global user manager, before
// it is deleted from the LDAP server. The instance will be returned
// from cache and may false-positively confirm the correctness.
- $user = \OC::$server->getUserManager()->get($username);
+ $user = Server::get(IUserManager::class)->get($username);
if ($user === null) {
return false;
}
$user->delete();
- return \OC::$server->getUserManager()->get($username) === null;
+ return Server::get(IUserManager::class)->get($username) === null;
}
}
diff --git a/apps/user_ldap/tests/Integration/Lib/User/IntegrationTestUserDisplayName.php b/apps/user_ldap/tests/Integration/Lib/User/IntegrationTestUserDisplayName.php
index 08cccd4ac67..6fbfd9ba51b 100644
--- a/apps/user_ldap/tests/Integration/Lib/User/IntegrationTestUserDisplayName.php
+++ b/apps/user_ldap/tests/Integration/Lib/User/IntegrationTestUserDisplayName.php
@@ -12,12 +12,15 @@ use OCA\User_LDAP\Tests\Integration\AbstractIntegrationTest;
use OCA\User_LDAP\User\DeletedUsersIndex;
use OCA\User_LDAP\User_LDAP;
use OCA\User_LDAP\UserPluginManager;
+use OCP\IDBConnection;
+use OCP\IUserManager;
+use OCP\Server;
use Psr\Log\LoggerInterface;
require_once __DIR__ . '/../../Bootstrap.php';
class IntegrationTestUserDisplayName extends AbstractIntegrationTest {
- /** @var UserMapping */
+ /** @var UserMapping */
protected $mapping;
/**
@@ -27,11 +30,11 @@ class IntegrationTestUserDisplayName extends AbstractIntegrationTest {
public function init() {
require(__DIR__ . '/../../setup-scripts/createExplicitUsers.php');
parent::init();
- $this->mapping = new UserMapping(\OC::$server->getDatabaseConnection());
+ $this->mapping = new UserMapping(Server::get(IDBConnection::class));
$this->mapping->clear();
$this->access->setUserMapper($this->mapping);
- $userBackend = new User_LDAP($this->access, \OC::$server->getConfig(), \OC::$server->getNotificationManager(), \OC::$server->getUserSession(), \OC::$server->get(UserPluginManager::class), \OC::$server->get(LoggerInterface::class), \OC::$server->get(DeletedUsersIndex::class));
- \OC_User::useBackend($userBackend);
+ $userBackend = new User_LDAP($this->access, Server::get(\OCP\Notification\IManager::class), Server::get(UserPluginManager::class), Server::get(LoggerInterface::class), Server::get(DeletedUsersIndex::class));
+ Server::get(IUserManager::class)->registerBackend($userBackend);
}
/**
@@ -54,7 +57,7 @@ class IntegrationTestUserDisplayName extends AbstractIntegrationTest {
$username = 'alice1337';
$dn = 'uid=alice,ou=Users,' . $this->base;
$this->prepareUser($dn, $username);
- $displayName = \OC::$server->getUserManager()->get($username)->getDisplayName();
+ $displayName = Server::get(IUserManager::class)->get($username)->getDisplayName();
return str_contains($displayName, '(Alice@example.com)');
}
@@ -71,7 +74,7 @@ class IntegrationTestUserDisplayName extends AbstractIntegrationTest {
$username = 'boris23421';
$dn = 'uid=boris,ou=Users,' . $this->base;
$this->prepareUser($dn, $username);
- $displayName = \OC::$server->getUserManager()->get($username)->getDisplayName();
+ $displayName = Server::get(IUserManager::class)->get($username)->getDisplayName();
return !str_contains($displayName, '(Boris@example.com)');
}
diff --git a/apps/user_ldap/tests/Jobs/CleanUpTest.php b/apps/user_ldap/tests/Jobs/CleanUpTest.php
index 05d202f82df..5a1e563a1e8 100644
--- a/apps/user_ldap/tests/Jobs/CleanUpTest.php
+++ b/apps/user_ldap/tests/Jobs/CleanUpTest.php
@@ -1,5 +1,6 @@
<?php
+declare(strict_types=1);
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -18,13 +19,11 @@ use OCP\IDBConnection;
use Test\TestCase;
class CleanUpTest extends TestCase {
- /** @var CleanUp */
- protected $bgJob;
-
- /** @var array */
- protected $mocks;
+ protected CleanUp $bgJob;
+ protected array $mocks;
public function setUp(): void {
+ parent::setUp();
$this->createMocks();
$this->bgJob = new CleanUp($this->mocks['timeFactory'], $this->mocks['userBackend'], $this->mocks['deletedUsersIndex']);
$this->bgJob->setArguments($this->mocks);
@@ -43,7 +42,7 @@ class CleanUpTest extends TestCase {
/**
* clean up job must not run when there are disabled configurations
*/
- public function test_runNotAllowedByDisabledConfigurations() {
+ public function test_runNotAllowedByDisabledConfigurations(): void {
$this->mocks['helper']->expects($this->once())
->method('haveDisabledConfigurations')
->willReturn(true);
@@ -59,10 +58,10 @@ class CleanUpTest extends TestCase {
* clean up job must not run when LDAP Helper is broken i.e.
* returning unexpected results
*/
- public function test_runNotAllowedByBrokenHelper() {
+ public function test_runNotAllowedByBrokenHelper(): void {
$this->mocks['helper']->expects($this->once())
->method('haveDisabledConfigurations')
- ->will($this->throwException(new Exception()));
+ ->willThrowException(new Exception());
$this->mocks['ocConfig']->expects($this->never())
->method('getSystemValue');
@@ -74,7 +73,7 @@ class CleanUpTest extends TestCase {
/**
* clean up job must not run when it is not enabled
*/
- public function test_runNotAllowedBySysConfig() {
+ public function test_runNotAllowedBySysConfig(): void {
$this->mocks['helper']->expects($this->once())
->method('haveDisabledConfigurations')
->willReturn(false);
@@ -90,7 +89,7 @@ class CleanUpTest extends TestCase {
/**
* clean up job is allowed to run
*/
- public function test_runIsAllowed() {
+ public function test_runIsAllowed(): void {
$this->mocks['helper']->expects($this->once())
->method('haveDisabledConfigurations')
->willReturn(false);
@@ -106,7 +105,7 @@ class CleanUpTest extends TestCase {
/**
* check whether offset will be reset when it needs to
*/
- public function test_OffsetResetIsNecessary() {
+ public function test_OffsetResetIsNecessary(): void {
$result = $this->bgJob->isOffsetResetNecessary($this->bgJob->getChunkSize() - 1);
$this->assertSame(true, $result);
}
@@ -114,7 +113,7 @@ class CleanUpTest extends TestCase {
/**
* make sure offset is not reset when it is not due
*/
- public function test_OffsetResetIsNotNecessary() {
+ public function test_OffsetResetIsNotNecessary(): void {
$result = $this->bgJob->isOffsetResetNecessary($this->bgJob->getChunkSize());
$this->assertSame(false, $result);
}
diff --git a/apps/user_ldap/tests/Jobs/SyncTest.php b/apps/user_ldap/tests/Jobs/SyncTest.php
index 850e1ed42a4..f6ecf984ab0 100644
--- a/apps/user_ldap/tests/Jobs/SyncTest.php
+++ b/apps/user_ldap/tests/Jobs/SyncTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2017 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
@@ -15,40 +16,34 @@ use OCA\User_LDAP\LDAP;
use OCA\User_LDAP\Mapping\UserMapping;
use OCA\User_LDAP\User\Manager;
use OCP\AppFramework\Utility\ITimeFactory;
+use OCP\EventDispatcher\IEventDispatcher;
use OCP\IAvatarManager;
use OCP\IConfig;
use OCP\IDBConnection;
use OCP\IUserManager;
use OCP\Notification\IManager;
+use OCP\Server;
+use PHPUnit\Framework\MockObject\MockObject;
+use Psr\Log\LoggerInterface;
use Test\TestCase;
+/**
+ * @group DB
+ */
class SyncTest extends TestCase {
- /** @var array */
- protected $arguments;
- /** @var Helper|\PHPUnit\Framework\MockObject\MockObject */
- protected $helper;
- /** @var LDAP|\PHPUnit\Framework\MockObject\MockObject */
- protected $ldapWrapper;
- /** @var Manager|\PHPUnit\Framework\MockObject\MockObject */
- protected $userManager;
- /** @var UserMapping|\PHPUnit\Framework\MockObject\MockObject */
- protected $mapper;
- /** @var Sync */
- protected $sync;
- /** @var IConfig|\PHPUnit\Framework\MockObject\MockObject */
- protected $config;
- /** @var IAvatarManager|\PHPUnit\Framework\MockObject\MockObject */
- protected $avatarManager;
- /** @var IDBConnection|\PHPUnit\Framework\MockObject\MockObject */
- protected $dbc;
- /** @var IUserManager|\PHPUnit\Framework\MockObject\MockObject */
- protected $ncUserManager;
- /** @var IManager|\PHPUnit\Framework\MockObject\MockObject */
- protected $notificationManager;
- /** @var ConnectionFactory|\PHPUnit\Framework\MockObject\MockObject */
- protected $connectionFactory;
- /** @var AccessFactory|\PHPUnit\Framework\MockObject\MockObject */
- protected $accessFactory;
+ protected Helper&MockObject $helper;
+ protected LDAP&MockObject $ldapWrapper;
+ protected Manager&MockObject $userManager;
+ protected UserMapping&MockObject $mapper;
+ protected IConfig&MockObject $config;
+ protected IAvatarManager&MockObject $avatarManager;
+ protected IDBConnection&MockObject $dbc;
+ protected IUserManager&MockObject $ncUserManager;
+ protected IManager&MockObject $notificationManager;
+ protected ConnectionFactory&MockObject $connectionFactory;
+ protected AccessFactory&MockObject $accessFactory;
+ protected array $arguments = [];
+ protected Sync $sync;
protected function setUp(): void {
parent::setUp();
@@ -62,26 +57,32 @@ class SyncTest extends TestCase {
$this->dbc = $this->createMock(IDBConnection::class);
$this->ncUserManager = $this->createMock(IUserManager::class);
$this->notificationManager = $this->createMock(IManager::class);
- $this->connectionFactory = $this->createMock(ConnectionFactory::class);
+ $this->connectionFactory = $this->getMockBuilder(ConnectionFactory::class)
+ ->setConstructorArgs([
+ $this->ldapWrapper,
+ ])
+ ->getMock();
$this->accessFactory = $this->createMock(AccessFactory::class);
- $this->arguments = [
- 'helper' => $this->helper,
- 'ldapWrapper' => $this->ldapWrapper,
- 'mapper' => $this->mapper,
- 'config' => $this->config,
- 'avatarManager' => $this->avatarManager,
- 'dbc' => $this->dbc,
- 'ncUserManager' => $this->ncUserManager,
- 'notificationManager' => $this->notificationManager,
- 'connectionFactory' => $this->connectionFactory,
- 'accessFactory' => $this->accessFactory,
- ];
-
- $this->sync = new Sync($this->createMock(ITimeFactory::class));
+ $this->sync = new Sync(
+ Server::get(ITimeFactory::class),
+ Server::get(IEventDispatcher::class),
+ $this->config,
+ $this->dbc,
+ $this->avatarManager,
+ $this->ncUserManager,
+ Server::get(LoggerInterface::class),
+ $this->notificationManager,
+ $this->mapper,
+ $this->helper,
+ $this->connectionFactory,
+ $this->accessFactory,
+ );
+
+ $this->sync->overwritePropertiesForTest($this->ldapWrapper);
}
- public function intervalDataProvider() {
+ public static function intervalDataProvider(): array {
return [
[
0, 1000, 750
@@ -101,10 +102,8 @@ class SyncTest extends TestCase {
];
}
- /**
- * @dataProvider intervalDataProvider
- */
- public function testUpdateInterval($userCount, $pagingSize1, $pagingSize2) {
+ #[\PHPUnit\Framework\Attributes\DataProvider('intervalDataProvider')]
+ public function testUpdateInterval(int $userCount, int $pagingSize1, int $pagingSize2): void {
$this->config->expects($this->once())
->method('setAppValue')
->with('user_ldap', 'background_sync_interval', $this->anything())
@@ -134,7 +133,7 @@ class SyncTest extends TestCase {
$this->sync->updateInterval();
}
- public function moreResultsProvider() {
+ public static function moreResultsProvider(): array {
return [
[ 3, 3, true ],
[ 3, 5, true ],
@@ -144,11 +143,13 @@ class SyncTest extends TestCase {
];
}
- /**
- * @dataProvider moreResultsProvider
- */
- public function testMoreResults($pagingSize, $results, $expected) {
- $connection = $this->createMock(Connection::class);
+ #[\PHPUnit\Framework\Attributes\DataProvider('moreResultsProvider')]
+ public function testMoreResults($pagingSize, $results, $expected): void {
+ $connection = $this->getMockBuilder(Connection::class)
+ ->setConstructorArgs([
+ $this->ldapWrapper,
+ ])
+ ->getMock();
$this->connectionFactory->expects($this->any())
->method('get')
->willReturn($connection);
@@ -161,7 +162,7 @@ class SyncTest extends TestCase {
return null;
});
- /** @var Access|\PHPUnit\Framework\MockObject\MockObject $access */
+ /** @var Access&MockObject $access */
$access = $this->createMock(Access::class);
$this->accessFactory->expects($this->any())
->method('get')
@@ -186,7 +187,7 @@ class SyncTest extends TestCase {
$this->assertSame($expected, $hasMoreResults);
}
- public function cycleDataProvider() {
+ public static function cycleDataProvider(): array {
$lastCycle = ['prefix' => 's01', 'offset' => 1000];
$lastCycle2 = ['prefix' => '', 'offset' => 1000];
return [
@@ -199,22 +200,24 @@ class SyncTest extends TestCase {
];
}
- /**
- * @dataProvider cycleDataProvider
- */
- public function testDetermineNextCycle($cycleData, $prefixes, $expectedCycle) {
+ #[\PHPUnit\Framework\Attributes\DataProvider('cycleDataProvider')]
+ public function testDetermineNextCycle(?array $cycleData, array $prefixes, ?array $expectedCycle): void {
$this->helper->expects($this->any())
->method('getServerConfigurationPrefixes')
->with(true)
->willReturn($prefixes);
if (is_array($expectedCycle)) {
+ $calls = [
+ ['user_ldap', 'background_sync_prefix', $expectedCycle['prefix']],
+ ['user_ldap', 'background_sync_offset', $expectedCycle['offset']],
+ ];
$this->config->expects($this->exactly(2))
->method('setAppValue')
- ->withConsecutive(
- ['user_ldap', 'background_sync_prefix', $expectedCycle['prefix']],
- ['user_ldap', 'background_sync_offset', $expectedCycle['offset']]
- );
+ ->willReturnCallback(function () use (&$calls): void {
+ $expected = array_shift($calls);
+ $this->assertEquals($expected, func_get_args());
+ });
} else {
$this->config->expects($this->never())
->method('setAppValue');
@@ -231,7 +234,7 @@ class SyncTest extends TestCase {
}
}
- public function testQualifiesToRun() {
+ public function testQualifiesToRun(): void {
$cycleData = ['prefix' => 's01'];
$this->config->expects($this->exactly(2))
@@ -243,7 +246,7 @@ class SyncTest extends TestCase {
$this->assertFalse($this->sync->qualifiesToRun($cycleData));
}
- public function runDataProvider() {
+ public static function runDataProvider(): array {
return [
#0 - one LDAP server, reset
[[
@@ -275,10 +278,8 @@ class SyncTest extends TestCase {
];
}
- /**
- * @dataProvider runDataProvider
- */
- public function testRun($runData) {
+ #[\PHPUnit\Framework\Attributes\DataProvider('runDataProvider')]
+ public function testRun(array $runData): void {
$this->config->expects($this->any())
->method('getAppValue')
->willReturnCallback(function ($app, $key, $default) use ($runData) {
@@ -305,13 +306,18 @@ class SyncTest extends TestCase {
return $default;
});
+
+ $calls = [
+ ['user_ldap', 'background_sync_prefix', $runData['expectedNextCycle']['prefix']],
+ ['user_ldap', 'background_sync_offset', $runData['expectedNextCycle']['offset']],
+ ['user_ldap', 'background_sync_interval', '43200'],
+ ];
$this->config->expects($this->exactly(3))
->method('setAppValue')
- ->withConsecutive(
- ['user_ldap', 'background_sync_prefix', $runData['expectedNextCycle']['prefix']],
- ['user_ldap', 'background_sync_offset', $runData['expectedNextCycle']['offset']],
- ['user_ldap', 'background_sync_interval', $this->anything()]
- );
+ ->willReturnCallback(function () use (&$calls): void {
+ $expected = array_shift($calls);
+ $this->assertEquals($expected, func_get_args());
+ });
$this->config->expects($this->any())
->method('getAppKeys')
->with('user_ldap')
@@ -322,7 +328,11 @@ class SyncTest extends TestCase {
->with(true)
->willReturn($runData['prefixes']);
- $connection = $this->createMock(Connection::class);
+ $connection = $this->getMockBuilder(Connection::class)
+ ->setConstructorArgs([
+ $this->ldapWrapper,
+ ])
+ ->getMock();
$this->connectionFactory->expects($this->any())
->method('get')
->willReturn($connection);
@@ -335,7 +345,7 @@ class SyncTest extends TestCase {
return null;
});
- /** @var Access|\PHPUnit\Framework\MockObject\MockObject $access */
+ /** @var Access&MockObject $access */
$access = $this->createMock(Access::class);
$this->accessFactory->expects($this->any())
->method('get')
diff --git a/apps/user_ldap/tests/LDAPGroupPluginDummy.php b/apps/user_ldap/tests/LDAPGroupPluginDummy.php
index 0d47fbbd290..5ea1a491f14 100644
--- a/apps/user_ldap/tests/LDAPGroupPluginDummy.php
+++ b/apps/user_ldap/tests/LDAPGroupPluginDummy.php
@@ -1,4 +1,6 @@
<?php
+
+declare(strict_types=1);
/**
* SPDX-FileCopyrightText: 2017 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
diff --git a/apps/user_ldap/tests/LDAPProviderTest.php b/apps/user_ldap/tests/LDAPProviderTest.php
index 6e6c62157b3..57323e374aa 100644
--- a/apps/user_ldap/tests/LDAPProviderTest.php
+++ b/apps/user_ldap/tests/LDAPProviderTest.php
@@ -1,21 +1,29 @@
<?php
+
+declare(strict_types=1);
/**
* SPDX-FileCopyrightText: 2016 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
namespace OCA\User_LDAP\Tests;
+use OC\Config;
use OC\User\Manager;
use OCA\User_LDAP\Access;
use OCA\User_LDAP\Connection;
use OCA\User_LDAP\Group_LDAP;
+use OCA\User_LDAP\Helper;
use OCA\User_LDAP\IGroupLDAP;
+use OCA\User_LDAP\ILDAPWrapper;
use OCA\User_LDAP\IUserLDAP;
+use OCA\User_LDAP\LDAPProviderFactory;
use OCA\User_LDAP\User_LDAP;
use OCP\EventDispatcher\IEventDispatcher;
use OCP\ICacheFactory;
use OCP\IConfig;
use OCP\IServerContainer;
+use OCP\Server;
+use Psr\Log\LoggerInterface;
/**
* Class LDAPProviderTest
@@ -25,35 +33,29 @@ use OCP\IServerContainer;
* @package OCA\User_LDAP\Tests
*/
class LDAPProviderTest extends \Test\TestCase {
- protected function setUp(): void {
- parent::setUp();
- }
-
private function getServerMock(IUserLDAP $userBackend, IGroupLDAP $groupBackend) {
$server = $this->getMockBuilder('OC\Server')
- ->setMethods(['getUserManager', 'getBackends', 'getGroupManager'])
- ->setConstructorArgs(['', new \OC\Config(\OC::$configDir)])
- ->getMock();
+ ->onlyMethods(['getUserManager', 'getGroupManager'])
+ ->setConstructorArgs(['', new Config(\OC::$configDir)])
+ ->getMock();
$server->expects($this->any())
->method('getUserManager')
->willReturn($this->getUserManagerMock($userBackend));
$server->expects($this->any())
->method('getGroupManager')
->willReturn($this->getGroupManagerMock($groupBackend));
- $server->expects($this->any())
- ->method($this->anything())
- ->willReturnSelf();
return $server;
}
private function getUserManagerMock(IUserLDAP $userBackend) {
$userManager = $this->getMockBuilder(Manager::class)
- ->setMethods(['getBackends'])
+ ->onlyMethods(['getBackends'])
->setConstructorArgs([
$this->createMock(IConfig::class),
$this->createMock(ICacheFactory::class),
$this->createMock(IEventDispatcher::class),
+ $this->createMock(LoggerInterface::class),
])
->getMock();
$userManager->expects($this->any())
@@ -64,7 +66,7 @@ class LDAPProviderTest extends \Test\TestCase {
private function getGroupManagerMock(IGroupLDAP $groupBackend) {
$groupManager = $this->getMockBuilder('OC\Group\Manager')
- ->setMethods(['getBackends'])
+ ->onlyMethods(['getBackends'])
->disableOriginalConstructor()
->getMock();
$groupManager->expects($this->any())
@@ -82,19 +84,19 @@ class LDAPProviderTest extends \Test\TestCase {
}
private function getLDAPProvider(IServerContainer $serverContainer) {
- $factory = new \OCA\User_LDAP\LDAPProviderFactory($serverContainer);
+ $factory = new LDAPProviderFactory($serverContainer);
return $factory->getLDAPProvider();
}
- public function testGetUserDNUserIDNotFound() {
+ public function testGetUserDNUserIDNotFound(): void {
$this->expectException(\Exception::class);
$this->expectExceptionMessage('User id not found in LDAP');
- $userBackend = $this->getMockBuilder('OCA\User_LDAP\User_LDAP')
- ->setMethods(['userExists'])
- ->disableOriginalConstructor()
- ->getMock();
+ $userBackend = $this->getMockBuilder(User_LDAP::class)
+ ->onlyMethods(['userExists'])
+ ->disableOriginalConstructor()
+ ->getMock();
$userBackend->expects($this->any())->method('userExists')->willReturn(false);
$server = $this->getServerMock($userBackend, $this->getDefaultGroupBackendMock());
@@ -103,20 +105,25 @@ class LDAPProviderTest extends \Test\TestCase {
$ldapProvider->getUserDN('nonexisting_user');
}
- public function testGetUserDN() {
- $userBackend = $this->getMockBuilder('OCA\User_LDAP\User_LDAP')
- ->setMethods(['userExists', 'getLDAPAccess', 'username2dn'])
- ->disableOriginalConstructor()
- ->getMock();
+
+ public function testGetUserDN(): void {
+ $userAccess = $this->getMockBuilder(Access::class)
+ ->onlyMethods(['username2dn'])
+ ->disableOriginalConstructor()
+ ->getMock();
+ $userAccess->expects($this->once())
+ ->method('username2dn')
+ ->willReturn('cn=existing_user,ou=Are Sufficient To,ou=Test,dc=example,dc=org');
+ $userBackend = $this->getMockBuilder(User_LDAP::class)
+ ->onlyMethods(['userExists', 'getLDAPAccess'])
+ ->disableOriginalConstructor()
+ ->getMock();
$userBackend->expects($this->once())
->method('userExists')
->willReturn(true);
- $userBackend->expects($this->once())
- ->method('username2dn')
- ->willReturn('cn=existing_user,ou=Are Sufficient To,ou=Test,dc=example,dc=org');
$userBackend->expects($this->any())
- ->method($this->anything())
- ->willReturnSelf();
+ ->method('getLDAPAccess')
+ ->willReturn($userAccess);
$server = $this->getServerMock($userBackend, $this->getDefaultGroupBackendMock());
@@ -126,16 +133,13 @@ class LDAPProviderTest extends \Test\TestCase {
}
- public function testGetGroupDNGroupIDNotFound() {
+ public function testGetGroupDNGroupIDNotFound(): void {
$this->expectException(\Exception::class);
$this->expectExceptionMessage('Group id not found in LDAP');
- $userBackend = $this->getMockBuilder('OCA\User_LDAP\User_LDAP')
- ->disableOriginalConstructor()
- ->getMock();
-
- $groupBackend = $this->getMockBuilder('OCA\User_LDAP\Group_LDAP')
- ->setMethods(['groupExists'])
+ $userBackend = $this->createMock(User_LDAP::class);
+ $groupBackend = $this->getMockBuilder(Group_LDAP::class)
+ ->onlyMethods(['groupExists'])
->disableOriginalConstructor()
->getMock();
@@ -147,26 +151,24 @@ class LDAPProviderTest extends \Test\TestCase {
$ldapProvider->getGroupDN('nonexisting_group');
}
- public function testGetGroupDN() {
- $userBackend = $this->getMockBuilder('OCA\User_LDAP\User_LDAP')
- ->setMethods(['userExists', 'getLDAPAccess', 'username2dn'])
- ->disableOriginalConstructor()
- ->getMock();
+ public function testGetGroupDN(): void {
+ $userBackend = $this->createMock(User_LDAP::class);
- $groupBackend = $this->getMockBuilder('OCA\User_LDAP\Group_LDAP')
- ->setMethods(['groupExists', 'getLDAPAccess', 'groupname2dn'])
+ $groupBackend = $this->getMockBuilder(Group_LDAP::class)
+ ->onlyMethods(['groupExists', 'getLDAPAccess'])
->disableOriginalConstructor()
->getMock();
+ $groupAccess = $this->createMock(Access::class);
+ $groupAccess->expects($this->once())
+ ->method('groupname2dn')
+ ->willReturn('cn=existing_group,ou=Are Sufficient To,ou=Test,dc=example,dc=org');
$groupBackend->expects($this->once())
->method('groupExists')
->willReturn(true);
- $groupBackend->expects($this->once())
- ->method('groupname2dn')
- ->willReturn('cn=existing_group,ou=Are Sufficient To,ou=Test,dc=example,dc=org');
$groupBackend->expects($this->any())
- ->method($this->anything())
- ->willReturnSelf();
+ ->method('getLDAPAccess')
+ ->willReturn($groupAccess);
$server = $this->getServerMock($userBackend, $groupBackend);
@@ -175,11 +177,11 @@ class LDAPProviderTest extends \Test\TestCase {
$ldapProvider->getGroupDN('existing_group'));
}
- public function testGetUserName() {
- $userBackend = $this->getMockBuilder('OCA\User_LDAP\User_LDAP')
- ->setMethods(['dn2UserName'])
- ->disableOriginalConstructor()
- ->getMock();
+ public function testGetUserName(): void {
+ $userBackend = $this->getMockBuilder(User_LDAP::class)
+ ->onlyMethods(['dn2UserName'])
+ ->disableOriginalConstructor()
+ ->getMock();
$userBackend->expects($this->any())
->method('dn2UserName')
->willReturn('existing_user');
@@ -191,15 +193,12 @@ class LDAPProviderTest extends \Test\TestCase {
$ldapProvider->getUserName('cn=existing_user,ou=Are Sufficient To,ou=Test,dc=example,dc=org'));
}
- public function testDNasBaseParameter() {
- $userBackend = $this->getMockBuilder('OCA\User_LDAP\User_LDAP')
- ->setMethods([])
- ->disableOriginalConstructor()
- ->getMock();
+ public function testDNasBaseParameter(): void {
+ $userBackend = $this->createMock(User_LDAP::class);
$server = $this->getServerMock($userBackend, $this->getDefaultGroupBackendMock());
- $helper = new \OCA\User_LDAP\Helper(\OC::$server->getConfig(), \OC::$server->getDatabaseConnection());
+ $helper = Server::get(Helper::class);
$ldapProvider = $this->getLDAPProvider($server);
$this->assertEquals(
@@ -207,15 +206,12 @@ class LDAPProviderTest extends \Test\TestCase {
$ldapProvider->DNasBaseParameter('cn=existing_user,ou=Are Sufficient To,ou=Test,dc=example,dc=org'));
}
- public function testSanitizeDN() {
- $userBackend = $this->getMockBuilder('OCA\User_LDAP\User_LDAP')
- ->setMethods([])
- ->disableOriginalConstructor()
- ->getMock();
+ public function testSanitizeDN(): void {
+ $userBackend = $this->createMock(User_LDAP::class);
$server = $this->getServerMock($userBackend, $this->getDefaultGroupBackendMock());
- $helper = new \OCA\User_LDAP\Helper(\OC::$server->getConfig(), \OC::$server->getDatabaseConnection());
+ $helper = Server::get(Helper::class);
$ldapProvider = $this->getLDAPProvider($server);
$this->assertEquals(
@@ -224,14 +220,11 @@ class LDAPProviderTest extends \Test\TestCase {
}
- public function testGetLDAPConnectionUserIDNotFound() {
+ public function testGetLDAPConnectionUserIDNotFound(): void {
$this->expectException(\Exception::class);
$this->expectExceptionMessage('User id not found in LDAP');
- $userBackend = $this->getMockBuilder('OCA\User_LDAP\User_LDAP')
- ->setMethods(['userExists'])
- ->disableOriginalConstructor()
- ->getMock();
+ $userBackend = $this->createMock(User_LDAP::class);
$userBackend->expects($this->any())->method('userExists')->willReturn(false);
$server = $this->getServerMock($userBackend, $this->getDefaultGroupBackendMock());
@@ -240,11 +233,11 @@ class LDAPProviderTest extends \Test\TestCase {
$ldapProvider->getLDAPConnection('nonexisting_user');
}
- public function testGetLDAPConnection() {
- $userBackend = $this->getMockBuilder('OCA\User_LDAP\User_LDAP')
- ->setMethods(['userExists', 'getNewLDAPConnection'])
- ->disableOriginalConstructor()
- ->getMock();
+ public function testGetLDAPConnection(): void {
+ $userBackend = $this->getMockBuilder(User_LDAP::class)
+ ->onlyMethods(['userExists', 'getNewLDAPConnection'])
+ ->disableOriginalConstructor()
+ ->getMock();
$userBackend->expects($this->any())
->method('userExists')
->willReturn(true);
@@ -260,16 +253,13 @@ class LDAPProviderTest extends \Test\TestCase {
}
- public function testGetGroupLDAPConnectionGroupIDNotFound() {
+ public function testGetGroupLDAPConnectionGroupIDNotFound(): void {
$this->expectException(\Exception::class);
$this->expectExceptionMessage('Group id not found in LDAP');
- $userBackend = $this->getMockBuilder('OCA\User_LDAP\User_LDAP')
- ->disableOriginalConstructor()
- ->getMock();
-
- $groupBackend = $this->getMockBuilder('OCA\User_LDAP\Group_LDAP')
- ->setMethods(['groupExists'])
+ $userBackend = $this->createMock(User_LDAP::class);
+ $groupBackend = $this->getMockBuilder(Group_LDAP::class)
+ ->onlyMethods(['groupExists'])
->disableOriginalConstructor()
->getMock();
@@ -281,13 +271,10 @@ class LDAPProviderTest extends \Test\TestCase {
$ldapProvider->getGroupLDAPConnection('nonexisting_group');
}
- public function testGetGroupLDAPConnection() {
- $userBackend = $this->getMockBuilder('OCA\User_LDAP\User_LDAP')
- ->disableOriginalConstructor()
- ->getMock();
-
- $groupBackend = $this->getMockBuilder('OCA\User_LDAP\Group_LDAP')
- ->setMethods(['groupExists','getNewLDAPConnection'])
+ public function testGetGroupLDAPConnection(): void {
+ $userBackend = $this->createMock(User_LDAP::class);
+ $groupBackend = $this->getMockBuilder(Group_LDAP::class)
+ ->onlyMethods(['groupExists','getNewLDAPConnection'])
->disableOriginalConstructor()
->getMock();
@@ -307,14 +294,14 @@ class LDAPProviderTest extends \Test\TestCase {
}
- public function testGetLDAPBaseUsersUserIDNotFound() {
+ public function testGetLDAPBaseUsersUserIDNotFound(): void {
$this->expectException(\Exception::class);
$this->expectExceptionMessage('User id not found in LDAP');
- $userBackend = $this->getMockBuilder('OCA\User_LDAP\User_LDAP')
- ->setMethods(['userExists'])
- ->disableOriginalConstructor()
- ->getMock();
+ $userBackend = $this->getMockBuilder(User_LDAP::class)
+ ->onlyMethods(['userExists'])
+ ->disableOriginalConstructor()
+ ->getMock();
$userBackend->expects($this->any())->method('userExists')->willReturn(false);
$server = $this->getServerMock($userBackend, $this->getDefaultGroupBackendMock());
@@ -323,14 +310,16 @@ class LDAPProviderTest extends \Test\TestCase {
$ldapProvider->getLDAPBaseUsers('nonexisting_user');
}
- public function testGetLDAPBaseUsers() {
+ public function testGetLDAPBaseUsers(): void {
$bases = [
'ou=users,ou=foobar,dc=example,dc=org',
'ou=users,ou=barfoo,dc=example,dc=org',
];
$dn = 'uid=malik,' . $bases[1];
- $connection = $this->createMock(Connection::class);
+ $connection = $this->getMockBuilder(Connection::class)
+ ->setConstructorArgs([$this->createMock(ILDAPWrapper::class)])
+ ->getMock();
$connection->expects($this->any())
->method('__get')
->willReturnCallback(function ($key) use ($bases) {
@@ -352,10 +341,10 @@ class LDAPProviderTest extends \Test\TestCase {
->method('username2dn')
->willReturn($dn);
- $userBackend = $this->getMockBuilder('OCA\User_LDAP\User_LDAP')
- ->setMethods(['userExists', 'getLDAPAccess', 'getConnection', 'getConfiguration'])
- ->disableOriginalConstructor()
- ->getMock();
+ $userBackend = $this->getMockBuilder(User_LDAP::class)
+ ->onlyMethods(['userExists', 'getLDAPAccess'])
+ ->disableOriginalConstructor()
+ ->getMock();
$userBackend->expects($this->atLeastOnce())
->method('userExists')
->willReturn(true);
@@ -370,14 +359,14 @@ class LDAPProviderTest extends \Test\TestCase {
}
- public function testGetLDAPBaseGroupsUserIDNotFound() {
+ public function testGetLDAPBaseGroupsUserIDNotFound(): void {
$this->expectException(\Exception::class);
$this->expectExceptionMessage('User id not found in LDAP');
- $userBackend = $this->getMockBuilder('OCA\User_LDAP\User_LDAP')
- ->setMethods(['userExists'])
- ->disableOriginalConstructor()
- ->getMock();
+ $userBackend = $this->getMockBuilder(User_LDAP::class)
+ ->onlyMethods(['userExists'])
+ ->disableOriginalConstructor()
+ ->getMock();
$userBackend->expects($this->any())->method('userExists')->willReturn(false);
$server = $this->getServerMock($userBackend, $this->getDefaultGroupBackendMock());
@@ -386,13 +375,15 @@ class LDAPProviderTest extends \Test\TestCase {
$ldapProvider->getLDAPBaseGroups('nonexisting_user');
}
- public function testGetLDAPBaseGroups() {
+ public function testGetLDAPBaseGroups(): void {
$bases = [
'ou=groupd,ou=foobar,dc=example,dc=org',
'ou=groups,ou=barfoo,dc=example,dc=org',
];
- $connection = $this->createMock(Connection::class);
+ $connection = $this->getMockBuilder(Connection::class)
+ ->setConstructorArgs([$this->createMock(ILDAPWrapper::class)])
+ ->getMock();
$connection->expects($this->any())
->method('__get')
->willReturnCallback(function ($key) use ($bases) {
@@ -408,10 +399,10 @@ class LDAPProviderTest extends \Test\TestCase {
->method('getConnection')
->willReturn($connection);
- $userBackend = $this->getMockBuilder('OCA\User_LDAP\User_LDAP')
- ->setMethods(['userExists', 'getLDAPAccess', 'getConnection', 'getConfiguration'])
- ->disableOriginalConstructor()
- ->getMock();
+ $userBackend = $this->getMockBuilder(User_LDAP::class)
+ ->onlyMethods(['userExists', 'getLDAPAccess'])
+ ->disableOriginalConstructor()
+ ->getMock();
$userBackend->expects($this->any())
->method('userExists')
->willReturn(true);
@@ -426,14 +417,14 @@ class LDAPProviderTest extends \Test\TestCase {
}
- public function testClearCacheUserIDNotFound() {
+ public function testClearCacheUserIDNotFound(): void {
$this->expectException(\Exception::class);
$this->expectExceptionMessage('User id not found in LDAP');
- $userBackend = $this->getMockBuilder('OCA\User_LDAP\User_LDAP')
- ->setMethods(['userExists'])
- ->disableOriginalConstructor()
- ->getMock();
+ $userBackend = $this->getMockBuilder(User_LDAP::class)
+ ->onlyMethods(['userExists'])
+ ->disableOriginalConstructor()
+ ->getMock();
$userBackend->expects($this->any())->method('userExists')->willReturn(false);
$server = $this->getServerMock($userBackend, $this->getDefaultGroupBackendMock());
@@ -442,20 +433,26 @@ class LDAPProviderTest extends \Test\TestCase {
$ldapProvider->clearCache('nonexisting_user');
}
- public function testClearCache() {
- $userBackend = $this->getMockBuilder('OCA\User_LDAP\User_LDAP')
- ->setMethods(['userExists', 'getLDAPAccess', 'getConnection', 'clearCache'])
- ->disableOriginalConstructor()
- ->getMock();
- $userBackend->expects($this->once())
- ->method('userExists')
+ public function testClearCache(): void {
+ $connection = $this->getMockBuilder(Connection::class)
+ ->setConstructorArgs([$this->createMock(ILDAPWrapper::class)])
+ ->getMock();
+ $connection->expects($this->once())
+ ->method('clearCache')
->willReturn(true);
+ $access = $this->createMock(Access::class);
+ $access->method('getConnection')
+ ->willReturn($connection);
+ $userBackend = $this->getMockBuilder(User_LDAP::class)
+ ->onlyMethods(['userExists', 'getLDAPAccess'])
+ ->disableOriginalConstructor()
+ ->getMock();
$userBackend->expects($this->once())
- ->method('clearCache')
+ ->method('userExists')
->willReturn(true);
$userBackend->expects($this->any())
- ->method($this->anything())
- ->willReturnSelf();
+ ->method('getLDAPAccess')
+ ->willReturn($access);
$server = $this->getServerMock($userBackend, $this->getDefaultGroupBackendMock());
@@ -465,15 +462,15 @@ class LDAPProviderTest extends \Test\TestCase {
}
- public function testClearGroupCacheGroupIDNotFound() {
+ public function testClearGroupCacheGroupIDNotFound(): void {
$this->expectException(\Exception::class);
$this->expectExceptionMessage('Group id not found in LDAP');
- $userBackend = $this->getMockBuilder('OCA\User_LDAP\User_LDAP')
+ $userBackend = $this->getMockBuilder(User_LDAP::class)
->disableOriginalConstructor()
->getMock();
- $groupBackend = $this->getMockBuilder('OCA\User_LDAP\Group_LDAP')
- ->setMethods(['groupExists'])
+ $groupBackend = $this->getMockBuilder(Group_LDAP::class)
+ ->onlyMethods(['groupExists'])
->disableOriginalConstructor()
->getMock();
$groupBackend->expects($this->any())->method('groupExists')->willReturn(false);
@@ -484,23 +481,27 @@ class LDAPProviderTest extends \Test\TestCase {
$ldapProvider->clearGroupCache('nonexisting_group');
}
- public function testClearGroupCache() {
- $userBackend = $this->getMockBuilder('OCA\User_LDAP\User_LDAP')
- ->disableOriginalConstructor()
+ public function testClearGroupCache(): void {
+ $userBackend = $this->createMock(User_LDAP::class);
+ $connection = $this->getMockBuilder(Connection::class)
+ ->setConstructorArgs([$this->createMock(ILDAPWrapper::class)])
->getMock();
- $groupBackend = $this->getMockBuilder('OCA\User_LDAP\Group_LDAP')
- ->setMethods(['groupExists', 'getLDAPAccess', 'getConnection', 'clearCache'])
+ $connection->expects($this->once())
+ ->method('clearCache')
+ ->willReturn(true);
+ $access = $this->createMock(Access::class);
+ $access->method('getConnection')
+ ->willReturn($connection);
+ $groupBackend = $this->getMockBuilder(Group_LDAP::class)
+ ->onlyMethods(['groupExists', 'getLDAPAccess'])
->disableOriginalConstructor()
->getMock();
$groupBackend->expects($this->once())
->method('groupExists')
->willReturn(true);
- $groupBackend->expects($this->once())
- ->method('clearCache')
- ->willReturn(true);
$groupBackend->expects($this->any())
- ->method($this->anything())
- ->willReturnSelf();
+ ->method('getLDAPAccess')
+ ->willReturn($access);
$server = $this->getServerMock($userBackend, $groupBackend);
@@ -509,11 +510,11 @@ class LDAPProviderTest extends \Test\TestCase {
$this->addToAssertionCount(1);
}
- public function testDnExists() {
- $userBackend = $this->getMockBuilder('OCA\User_LDAP\User_LDAP')
- ->setMethods(['dn2UserName'])
- ->disableOriginalConstructor()
- ->getMock();
+ public function testDnExists(): void {
+ $userBackend = $this->getMockBuilder(User_LDAP::class)
+ ->onlyMethods(['dn2UserName'])
+ ->disableOriginalConstructor()
+ ->getMock();
$userBackend->expects($this->any())
->method('dn2UserName')
->willReturn('existing_user');
@@ -524,12 +525,8 @@ class LDAPProviderTest extends \Test\TestCase {
$this->assertTrue($ldapProvider->dnExists('cn=existing_user,ou=Are Sufficient To,ou=Test,dc=example,dc=org'));
}
- public function testFlagRecord() {
- $userBackend = $this->getMockBuilder('OCA\User_LDAP\User_LDAP')
- ->setMethods([])
- ->disableOriginalConstructor()
- ->getMock();
-
+ public function testFlagRecord(): void {
+ $userBackend = $this->createMock(User_LDAP::class);
$server = $this->getServerMock($userBackend, $this->getDefaultGroupBackendMock());
$ldapProvider = $this->getLDAPProvider($server);
@@ -537,12 +534,8 @@ class LDAPProviderTest extends \Test\TestCase {
$this->addToAssertionCount(1);
}
- public function testUnflagRecord() {
- $userBackend = $this->getMockBuilder('OCA\User_LDAP\User_LDAP')
- ->setMethods([])
- ->disableOriginalConstructor()
- ->getMock();
-
+ public function testUnflagRecord(): void {
+ $userBackend = $this->createMock(User_LDAP::class);
$server = $this->getServerMock($userBackend, $this->getDefaultGroupBackendMock());
$ldapProvider = $this->getLDAPProvider($server);
@@ -551,12 +544,12 @@ class LDAPProviderTest extends \Test\TestCase {
}
- public function testGetLDAPDisplayNameFieldUserIDNotFound() {
+ public function testGetLDAPDisplayNameFieldUserIDNotFound(): void {
$this->expectException(\Exception::class);
$this->expectExceptionMessage('User id not found in LDAP');
- $userBackend = $this->getMockBuilder('OCA\User_LDAP\User_LDAP')
- ->setMethods(['userExists'])
+ $userBackend = $this->getMockBuilder(User_LDAP::class)
+ ->onlyMethods(['userExists'])
->disableOriginalConstructor()
->getMock();
$userBackend->expects($this->any())->method('userExists')->willReturn(false);
@@ -567,20 +560,26 @@ class LDAPProviderTest extends \Test\TestCase {
$ldapProvider->getLDAPDisplayNameField('nonexisting_user');
}
- public function testGetLDAPDisplayNameField() {
- $userBackend = $this->getMockBuilder('OCA\User_LDAP\User_LDAP')
- ->setMethods(['userExists', 'getLDAPAccess', 'getConnection', 'getConfiguration'])
+ public function testGetLDAPDisplayNameField(): void {
+ $connection = $this->getMockBuilder(Connection::class)
+ ->setConstructorArgs([$this->createMock(ILDAPWrapper::class)])
+ ->getMock();
+ $connection->expects($this->once())
+ ->method('getConfiguration')
+ ->willReturn(['ldap_display_name' => 'displayName']);
+ $access = $this->createMock(Access::class);
+ $access->method('getConnection')
+ ->willReturn($connection);
+ $userBackend = $this->getMockBuilder(User_LDAP::class)
+ ->onlyMethods(['userExists', 'getLDAPAccess'])
->disableOriginalConstructor()
->getMock();
$userBackend->expects($this->once())
->method('userExists')
->willReturn(true);
- $userBackend->expects($this->once())
- ->method('getConfiguration')
- ->willReturn(['ldap_display_name' => 'displayName']);
$userBackend->expects($this->any())
- ->method($this->anything())
- ->willReturnSelf();
+ ->method('getLDAPAccess')
+ ->willReturn($access);
$server = $this->getServerMock($userBackend, $this->getDefaultGroupBackendMock());
@@ -589,12 +588,12 @@ class LDAPProviderTest extends \Test\TestCase {
}
- public function testGetLDAPEmailFieldUserIDNotFound() {
+ public function testGetLDAPEmailFieldUserIDNotFound(): void {
$this->expectException(\Exception::class);
$this->expectExceptionMessage('User id not found in LDAP');
- $userBackend = $this->getMockBuilder('OCA\User_LDAP\User_LDAP')
- ->setMethods(['userExists'])
+ $userBackend = $this->getMockBuilder(User_LDAP::class)
+ ->onlyMethods(['userExists'])
->disableOriginalConstructor()
->getMock();
$userBackend->expects($this->any())->method('userExists')->willReturn(false);
@@ -605,20 +604,26 @@ class LDAPProviderTest extends \Test\TestCase {
$ldapProvider->getLDAPEmailField('nonexisting_user');
}
- public function testGetLDAPEmailField() {
- $userBackend = $this->getMockBuilder('OCA\User_LDAP\User_LDAP')
- ->setMethods(['userExists', 'getLDAPAccess', 'getConnection', 'getConfiguration'])
+ public function testGetLDAPEmailField(): void {
+ $connection = $this->getMockBuilder(Connection::class)
+ ->setConstructorArgs([$this->createMock(ILDAPWrapper::class)])
+ ->getMock();
+ $connection->expects($this->once())
+ ->method('getConfiguration')
+ ->willReturn(['ldap_email_attr' => 'mail']);
+ $access = $this->createMock(Access::class);
+ $access->method('getConnection')
+ ->willReturn($connection);
+ $userBackend = $this->getMockBuilder(User_LDAP::class)
+ ->onlyMethods(['userExists', 'getLDAPAccess'])
->disableOriginalConstructor()
->getMock();
$userBackend->expects($this->once())
->method('userExists')
->willReturn(true);
- $userBackend->expects($this->once())
- ->method('getConfiguration')
- ->willReturn(['ldap_email_attr' => 'mail']);
$userBackend->expects($this->any())
- ->method($this->anything())
- ->willReturnSelf();
+ ->method('getLDAPAccess')
+ ->willReturn($access);
$server = $this->getServerMock($userBackend, $this->getDefaultGroupBackendMock());
@@ -627,20 +632,19 @@ class LDAPProviderTest extends \Test\TestCase {
}
- public function testGetLDAPGroupMemberAssocUserIDNotFound() {
+ public function testGetLDAPGroupMemberAssocUserIDNotFound(): void {
$this->expectException(\Exception::class);
$this->expectExceptionMessage('Group id not found in LDAP');
- $userBackend = $this->getMockBuilder('OCA\User_LDAP\User_LDAP')
- ->disableOriginalConstructor()
- ->getMock();
-
- $groupBackend = $this->getMockBuilder('OCA\User_LDAP\Group_LDAP')
- ->setMethods(['groupExists'])
+ $userBackend = $this->createMock(User_LDAP::class);
+ $groupBackend = $this->getMockBuilder(Group_LDAP::class)
+ ->onlyMethods(['groupExists'])
->disableOriginalConstructor()
->getMock();
- $groupBackend->expects($this->any())->method('groupExists')->willReturn(false);
+ $groupBackend->expects($this->any())
+ ->method('groupExists')
+ ->willReturn(false);
$server = $this->getServerMock($userBackend, $groupBackend);
@@ -648,13 +652,20 @@ class LDAPProviderTest extends \Test\TestCase {
$ldapProvider->getLDAPGroupMemberAssoc('nonexisting_group');
}
- public function testgetLDAPGroupMemberAssoc() {
- $userBackend = $this->getMockBuilder('OCA\User_LDAP\User_LDAP')
- ->disableOriginalConstructor()
- ->getMock();
+ public function testgetLDAPGroupMemberAssoc(): void {
+ $userBackend = $this->createMock(User_LDAP::class);
- $groupBackend = $this->getMockBuilder('OCA\User_LDAP\Group_LDAP')
- ->setMethods(['groupExists', 'getLDAPAccess', 'getConnection', 'getConfiguration'])
+ $connection = $this->getMockBuilder(Connection::class)
+ ->setConstructorArgs([$this->createMock(ILDAPWrapper::class)])
+ ->getMock();
+ $connection->expects($this->once())
+ ->method('getConfiguration')
+ ->willReturn(['ldap_group_member_assoc_attribute' => 'assoc_type']);
+ $access = $this->createMock(Access::class);
+ $access->method('getConnection')
+ ->willReturn($connection);
+ $groupBackend = $this->getMockBuilder(Group_LDAP::class)
+ ->onlyMethods(['groupExists', 'getLDAPAccess'])
->disableOriginalConstructor()
->getMock();
@@ -662,11 +673,8 @@ class LDAPProviderTest extends \Test\TestCase {
->method('groupExists')
->willReturn(true);
$groupBackend->expects($this->any())
- ->method('getConfiguration')
- ->willReturn(['ldap_group_member_assoc_attribute' => 'assoc_type']);
- $groupBackend->expects($this->any())
- ->method($this->anything())
- ->willReturnSelf();
+ ->method('getLDAPAccess')
+ ->willReturn($access);
$server = $this->getServerMock($userBackend, $groupBackend);
@@ -674,7 +682,7 @@ class LDAPProviderTest extends \Test\TestCase {
$this->assertEquals('assoc_type', $ldapProvider->getLDAPGroupMemberAssoc('existing_group'));
}
- public function testGetMultiValueUserAttributeUserNotFound() {
+ public function testGetMultiValueUserAttributeUserNotFound(): void {
$this->expectException(\Exception::class);
$this->expectExceptionMessage('User id not found in LDAP');
@@ -690,8 +698,10 @@ class LDAPProviderTest extends \Test\TestCase {
$ldapProvider->getMultiValueUserAttribute('admin', 'mailAlias');
}
- public function testGetMultiValueUserAttributeCacheHit() {
- $connection = $this->createMock(Connection::class);
+ public function testGetMultiValueUserAttributeCacheHit(): void {
+ $connection = $this->getMockBuilder(Connection::class)
+ ->setConstructorArgs([$this->createMock(ILDAPWrapper::class)])
+ ->getMock();
$connection->expects(self::once())
->method('getFromCache')
->with('admin-mailAlias')
@@ -715,8 +725,10 @@ class LDAPProviderTest extends \Test\TestCase {
$ldapProvider->getMultiValueUserAttribute('admin', 'mailAlias');
}
- public function testGetMultiValueUserAttributeLdapError() {
- $connection = $this->createMock(Connection::class);
+ public function testGetMultiValueUserAttributeLdapError(): void {
+ $connection = $this->getMockBuilder(Connection::class)
+ ->setConstructorArgs([$this->createMock(ILDAPWrapper::class)])
+ ->getMock();
$connection->expects(self::once())
->method('getFromCache')
->with('admin-mailAlias')
@@ -752,8 +764,10 @@ class LDAPProviderTest extends \Test\TestCase {
self::assertCount(0, $values);
}
- public function testGetMultiValueUserAttribute() {
- $connection = $this->createMock(Connection::class);
+ public function testGetMultiValueUserAttribute(): void {
+ $connection = $this->getMockBuilder(Connection::class)
+ ->setConstructorArgs([$this->createMock(ILDAPWrapper::class)])
+ ->getMock();
$connection->expects(self::once())
->method('getFromCache')
->with('admin-mailAlias')
@@ -789,8 +803,10 @@ class LDAPProviderTest extends \Test\TestCase {
self::assertCount(2, $values);
}
- public function testGetUserAttributeLdapError() {
- $connection = $this->createMock(Connection::class);
+ public function testGetUserAttributeLdapError(): void {
+ $connection = $this->getMockBuilder(Connection::class)
+ ->setConstructorArgs([$this->createMock(ILDAPWrapper::class)])
+ ->getMock();
$connection->expects(self::once())
->method('getFromCache')
->with('admin-mailAlias')
@@ -826,8 +842,10 @@ class LDAPProviderTest extends \Test\TestCase {
self::assertNull($value);
}
- public function testGetUserAttribute() {
- $connection = $this->createMock(Connection::class);
+ public function testGetUserAttribute(): void {
+ $connection = $this->getMockBuilder(Connection::class)
+ ->setConstructorArgs([$this->createMock(ILDAPWrapper::class)])
+ ->getMock();
$connection->expects(self::once())
->method('getFromCache')
->with('admin-mailAlias')
diff --git a/apps/user_ldap/tests/LDAPTest.php b/apps/user_ldap/tests/LDAPTest.php
index 51ed0c2b462..6da592ad6a1 100644
--- a/apps/user_ldap/tests/LDAPTest.php
+++ b/apps/user_ldap/tests/LDAPTest.php
@@ -1,4 +1,6 @@
<?php
+
+declare(strict_types=1);
/**
* SPDX-FileCopyrightText: 2016 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
@@ -6,20 +8,20 @@
namespace OCA\User_LDAP\Tests;
use OCA\User_LDAP\LDAP;
+use PHPUnit\Framework\MockObject\MockObject;
use Test\TestCase;
class LDAPTest extends TestCase {
- /** @var LDAP|\PHPUnit\Framework\MockObject\MockObject */
- private $ldap;
+ private LDAP&MockObject $ldap;
protected function setUp(): void {
parent::setUp();
$this->ldap = $this->getMockBuilder(LDAP::class)
- ->setMethods(['invokeLDAPMethod'])
+ ->onlyMethods(['invokeLDAPMethod'])
->getMock();
}
- public function errorProvider() {
+ public static function errorProvider(): array {
return [
[
'ldap_search(): Partial search results returned: Sizelimit exceeded at /srv/http/nextcloud/master/apps/user_ldap/lib/LDAP.php#292',
@@ -31,14 +33,10 @@ class LDAPTest extends TestCase {
];
}
- /**
- * @param string $errorMessage
- * @param bool $passThrough
- * @dataProvider errorProvider
- */
- public function testSearchWithErrorHandler(string $errorMessage, bool $passThrough) {
+ #[\PHPUnit\Framework\Attributes\DataProvider('errorProvider')]
+ public function testSearchWithErrorHandler(string $errorMessage, bool $passThrough): void {
$wasErrorHandlerCalled = false;
- $errorHandler = function ($number, $message, $file, $line) use (&$wasErrorHandlerCalled) {
+ $errorHandler = function ($number, $message, $file, $line) use (&$wasErrorHandlerCalled): void {
$wasErrorHandlerCalled = true;
};
@@ -48,7 +46,7 @@ class LDAPTest extends TestCase {
->expects($this->once())
->method('invokeLDAPMethod')
->with('search', $this->anything(), $this->anything(), $this->anything(), $this->anything(), $this->anything())
- ->willReturnCallback(function () use ($errorMessage) {
+ ->willReturnCallback(function () use ($errorMessage): void {
trigger_error($errorMessage);
});
@@ -59,7 +57,7 @@ class LDAPTest extends TestCase {
restore_error_handler();
}
- public function testModReplace() {
+ public function testModReplace(): void {
$link = $this->createMock(LDAP::class);
$userDN = 'CN=user';
$password = 'MyPassword';
diff --git a/apps/user_ldap/tests/LDAPUserPluginDummy.php b/apps/user_ldap/tests/LDAPUserPluginDummy.php
index f6edf3df63b..8d4870406ae 100644
--- a/apps/user_ldap/tests/LDAPUserPluginDummy.php
+++ b/apps/user_ldap/tests/LDAPUserPluginDummy.php
@@ -1,4 +1,6 @@
<?php
+
+declare(strict_types=1);
/**
* SPDX-FileCopyrightText: 2017 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
@@ -39,4 +41,12 @@ class LDAPUserPluginDummy implements ILDAPUserPlugin {
public function countUsers() {
return null;
}
+
+ public function canDeleteUser() {
+ return true;
+ }
+
+ public function deleteUser($uid) {
+ return null;
+ }
}
diff --git a/apps/user_ldap/tests/Mapping/AbstractMappingTest.php b/apps/user_ldap/tests/Mapping/AbstractMappingTestCase.php
index 7de3825a323..8efee4e2085 100644
--- a/apps/user_ldap/tests/Mapping/AbstractMappingTest.php
+++ b/apps/user_ldap/tests/Mapping/AbstractMappingTestCase.php
@@ -1,5 +1,6 @@
<?php
+declare(strict_types=1);
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -9,14 +10,15 @@ namespace OCA\User_LDAP\Tests\Mapping;
use OCA\User_LDAP\Mapping\AbstractMapping;
use OCP\IDBConnection;
+use OCP\Server;
-abstract class AbstractMappingTest extends \Test\TestCase {
- abstract public function getMapper(\OCP\IDBConnection $dbMock);
+abstract class AbstractMappingTestCase extends \Test\TestCase {
+ abstract public function getMapper(IDBConnection $dbMock);
/**
* kiss test on isColNameValid
*/
- public function testIsColNameValid() {
+ public function testIsColNameValid(): void {
$dbMock = $this->createMock(IDBConnection::class);
$mapper = $this->getMapper($dbMock);
@@ -28,8 +30,8 @@ abstract class AbstractMappingTest extends \Test\TestCase {
* returns an array of test entries with dn, name and uuid as keys
* @return array
*/
- protected function getTestData() {
- $data = [
+ protected static function getTestData(): array {
+ return [
[
'dn' => 'uid=foobar,dc=example,dc=org',
'name' => 'Foobar',
@@ -46,16 +48,14 @@ abstract class AbstractMappingTest extends \Test\TestCase {
'uuid' => '3333-CCCC-1234-CDEF',
]
];
-
- return $data;
}
/**
* calls map() on the given mapper and asserts result for true
- * @param \OCA\User_LDAP\Mapping\AbstractMapping $mapper
+ * @param AbstractMapping $mapper
* @param array $data
*/
- protected function mapEntries($mapper, $data) {
+ protected function mapEntries(AbstractMapping $mapper, array $data): void {
foreach ($data as $entry) {
$done = $mapper->map($entry['dn'], $entry['name'], $entry['uuid']);
$this->assertTrue($done);
@@ -67,10 +67,10 @@ abstract class AbstractMappingTest extends \Test\TestCase {
* test objects. Preparing environment means that all mappings are cleared
* first and then filled with test entries.
* @return array 0 = \OCA\User_LDAP\Mapping\AbstractMapping, 1 = array of
- * users or groups
+ * users or groups
*/
- private function initTest() {
- $dbc = \OC::$server->getDatabaseConnection();
+ private function initTest(): array {
+ $dbc = Server::get(IDBConnection::class);
$mapper = $this->getMapper($dbc);
$data = $this->getTestData();
// make sure DB is pristine, then fill it with test entries
@@ -84,7 +84,7 @@ abstract class AbstractMappingTest extends \Test\TestCase {
* tests map() method with input that should result in not-mapping.
* Hint: successful mapping is tested inherently with mapEntries().
*/
- public function testMap() {
+ public function testMap(): void {
[$mapper, $data] = $this->initTest();
// test that mapping will not happen when it shall not
@@ -104,7 +104,7 @@ abstract class AbstractMappingTest extends \Test\TestCase {
* tests unmap() for both successful and unsuccessful removing of
* mapping entries
*/
- public function testUnmap() {
+ public function testUnmap(): void {
[$mapper, $data] = $this->initTest();
foreach ($data as $entry) {
@@ -124,7 +124,7 @@ abstract class AbstractMappingTest extends \Test\TestCase {
* tests getDNByName(), getNameByDN() and getNameByUUID() for successful
* and unsuccessful requests.
*/
- public function testGetMethods() {
+ public function testGetMethods(): void {
[$mapper, $data] = $this->initTest();
foreach ($data as $entry) {
@@ -152,23 +152,23 @@ abstract class AbstractMappingTest extends \Test\TestCase {
/**
* tests getNamesBySearch() for successful and unsuccessful requests.
*/
- public function testSearch() {
+ public function testSearch(): void {
[$mapper,] = $this->initTest();
$names = $mapper->getNamesBySearch('oo', '%', '%');
- $this->assertTrue(is_array($names));
+ $this->assertIsArray($names);
$this->assertSame(2, count($names));
- $this->assertTrue(in_array('Foobar', $names));
- $this->assertTrue(in_array('Barfoo', $names));
+ $this->assertContains('Foobar', $names);
+ $this->assertContains('Barfoo', $names);
$names = $mapper->getNamesBySearch('nada');
- $this->assertTrue(is_array($names));
- $this->assertSame(0, count($names));
+ $this->assertIsArray($names);
+ $this->assertCount(0, $names);
}
/**
* tests setDNbyUUID() for successful and unsuccessful update.
*/
- public function testSetDNMethod() {
+ public function testSetDNMethod(): void {
[$mapper, $data] = $this->initTest();
$newDN = 'uid=modified,dc=example,dc=org';
@@ -187,7 +187,7 @@ abstract class AbstractMappingTest extends \Test\TestCase {
/**
* tests setUUIDbyDN() for successful and unsuccessful update.
*/
- public function testSetUUIDMethod() {
+ public function testSetUUIDMethod(): void {
/** @var AbstractMapping $mapper */
[$mapper, $data] = $this->initTest();
@@ -207,7 +207,7 @@ abstract class AbstractMappingTest extends \Test\TestCase {
/**
* tests clear() for successful update.
*/
- public function testClear() {
+ public function testClear(): void {
[$mapper, $data] = $this->initTest();
$done = $mapper->clear();
@@ -221,13 +221,13 @@ abstract class AbstractMappingTest extends \Test\TestCase {
/**
* tests clear() for successful update.
*/
- public function testClearCb() {
+ public function testClearCb(): void {
[$mapper, $data] = $this->initTest();
$callbackCalls = 0;
$test = $this;
- $callback = function (string $id) use ($test, &$callbackCalls) {
+ $callback = function (string $id) use ($test, &$callbackCalls): void {
$test->assertTrue(trim($id) !== '');
$callbackCalls++;
};
@@ -244,28 +244,28 @@ abstract class AbstractMappingTest extends \Test\TestCase {
/**
* tests getList() method
*/
- public function testList() {
+ public function testList(): void {
[$mapper, $data] = $this->initTest();
// get all entries without specifying offset or limit
$results = $mapper->getList();
- $this->assertSame(3, count($results));
+ $this->assertCount(3, $results);
// get all-1 entries by specifying offset, and an high limit
// specifying only offset without limit will not work by underlying lib
$results = $mapper->getList(1, 999);
- $this->assertSame(count($data) - 1, count($results));
+ $this->assertCount(count($data) - 1, $results);
// get first 2 entries by limit, but not offset
$results = $mapper->getList(0, 2);
- $this->assertSame(2, count($results));
+ $this->assertCount(2, $results);
// get 2nd entry by specifying both offset and limit
$results = $mapper->getList(1, 1);
- $this->assertSame(1, count($results));
+ $this->assertCount(1, $results);
}
- public function testGetListOfIdsByDn() {
+ public function testGetListOfIdsByDn(): void {
/** @var AbstractMapping $mapper */
[$mapper,] = $this->initTest();
@@ -281,6 +281,6 @@ abstract class AbstractMappingTest extends \Test\TestCase {
}
$result = $mapper->getListOfIdsByDn($listOfDNs);
- $this->assertSame(66640 / 20, count($result));
+ $this->assertCount(66640 / 20, $result);
}
}
diff --git a/apps/user_ldap/tests/Mapping/GroupMappingTest.php b/apps/user_ldap/tests/Mapping/GroupMappingTest.php
index 0d407577e1b..5729058d10e 100644
--- a/apps/user_ldap/tests/Mapping/GroupMappingTest.php
+++ b/apps/user_ldap/tests/Mapping/GroupMappingTest.php
@@ -1,5 +1,6 @@
<?php
+declare(strict_types=1);
/**
* SPDX-FileCopyrightText: 2019-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -8,6 +9,7 @@
namespace OCA\User_LDAP\Tests\Mapping;
use OCA\User_LDAP\Mapping\GroupMapping;
+use OCP\IDBConnection;
/**
* Class GroupMappingTest
@@ -16,8 +18,8 @@ use OCA\User_LDAP\Mapping\GroupMapping;
*
* @package OCA\User_LDAP\Tests\Mapping
*/
-class GroupMappingTest extends AbstractMappingTest {
- public function getMapper(\OCP\IDBConnection $dbMock) {
+class GroupMappingTest extends AbstractMappingTestCase {
+ public function getMapper(IDBConnection $dbMock) {
return new GroupMapping($dbMock);
}
}
diff --git a/apps/user_ldap/tests/Mapping/UserMappingTest.php b/apps/user_ldap/tests/Mapping/UserMappingTest.php
index 1792a4124be..4346fe1d23f 100644
--- a/apps/user_ldap/tests/Mapping/UserMappingTest.php
+++ b/apps/user_ldap/tests/Mapping/UserMappingTest.php
@@ -1,5 +1,6 @@
<?php
+declare(strict_types=1);
/**
* SPDX-FileCopyrightText: 2019-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -8,6 +9,7 @@
namespace OCA\User_LDAP\Tests\Mapping;
use OCA\User_LDAP\Mapping\UserMapping;
+use OCP\IDBConnection;
use OCP\Support\Subscription\IAssertion;
/**
@@ -17,8 +19,8 @@ use OCP\Support\Subscription\IAssertion;
*
* @package OCA\User_LDAP\Tests\Mapping
*/
-class UserMappingTest extends AbstractMappingTest {
- public function getMapper(\OCP\IDBConnection $dbMock) {
+class UserMappingTest extends AbstractMappingTestCase {
+ public function getMapper(IDBConnection $dbMock) {
return new UserMapping($dbMock, $this->createMock(IAssertion::class));
}
}
diff --git a/apps/user_ldap/tests/Migration/AbstractUUIDFixTest.php b/apps/user_ldap/tests/Migration/AbstractUUIDFixTestCase.php
index 9d433cf4937..7a85b885bc1 100644
--- a/apps/user_ldap/tests/Migration/AbstractUUIDFixTest.php
+++ b/apps/user_ldap/tests/Migration/AbstractUUIDFixTestCase.php
@@ -1,4 +1,6 @@
<?php
+
+declare(strict_types=1);
/**
* SPDX-FileCopyrightText: 2017 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
@@ -13,17 +15,18 @@ use OCA\User_LDAP\Migration\UUIDFix;
use OCA\User_LDAP\Proxy;
use OCP\AppFramework\Utility\ITimeFactory;
use OCP\IConfig;
+use PHPUnit\Framework\MockObject\MockObject;
use Test\TestCase;
-abstract class AbstractUUIDFixTest extends TestCase {
- protected Helper $helper;
- protected IConfig $config;
- protected LDAP $ldap;
+abstract class AbstractUUIDFixTestCase extends TestCase {
+ protected Helper&MockObject $helper;
+ protected IConfig&MockObject $config;
+ protected LDAP&MockObject $ldap;
protected AbstractMapping $mapper;
protected UUIDFix $job;
protected Proxy $proxy;
- protected Access $access;
- protected ITimeFactory $time;
+ protected Access&MockObject $access;
+ protected ITimeFactory&MockObject $time;
protected bool $isUser = true;
protected function setUp(): void {
@@ -48,7 +51,7 @@ abstract class AbstractUUIDFixTest extends TestCase {
->willReturn($this->access);
}
- public function testRunSingleRecord() {
+ public function testRunSingleRecord(): void {
$args = [
'records' => [
0 => [
@@ -72,7 +75,7 @@ abstract class AbstractUUIDFixTest extends TestCase {
$this->job->run($args);
}
- public function testRunValidRecord() {
+ public function testRunValidRecord(): void {
$correctUUID = '4355-AED3-9D73-03AD';
$args = [
'records' => [
@@ -95,7 +98,7 @@ abstract class AbstractUUIDFixTest extends TestCase {
$this->job->run($args);
}
- public function testRunRemovedRecord() {
+ public function testRunRemovedRecord(): void {
$args = [
'records' => [
0 => [
@@ -117,7 +120,7 @@ abstract class AbstractUUIDFixTest extends TestCase {
$this->job->run($args);
}
- public function testRunManyRecords() {
+ public function testRunManyRecords(): void {
$args = [
'records' => [
0 => [
@@ -141,19 +144,23 @@ abstract class AbstractUUIDFixTest extends TestCase {
$this->access->expects($this->exactly(3))
->method('getUUID')
- ->withConsecutive(
- [$args['records'][0]['dn'], $this->isUser],
- [$args['records'][1]['dn'], $this->isUser],
- [$args['records'][2]['dn'], $this->isUser]
- )
- ->willReturnOnConsecutiveCalls($correctUUIDs[0], $correctUUIDs[1], $correctUUIDs[2]);
-
+ ->willReturnMap([
+ [$args['records'][0]['dn'], $this->isUser, null, $correctUUIDs[0]],
+ [$args['records'][1]['dn'], $this->isUser, null, $correctUUIDs[1]],
+ [$args['records'][2]['dn'], $this->isUser, null, $correctUUIDs[2]],
+ ]);
+
+ $calls = [
+ [$correctUUIDs[0], $args['records'][0]['dn']],
+ [$correctUUIDs[2], $args['records'][2]['dn']],
+ ];
$this->mapper->expects($this->exactly(2))
->method('setUUIDbyDN')
- ->withConsecutive(
- [$correctUUIDs[0], $args['records'][0]['dn']],
- [$correctUUIDs[2], $args['records'][2]['dn']]
- );
+ ->willReturnCallback(function ($i, $j) use (&$calls) {
+ $expected = array_shift($calls);
+ $this->assertEquals($expected, func_get_args());
+ return true;
+ });
$this->job->run($args);
}
diff --git a/apps/user_ldap/tests/Migration/UUIDFixGroupTest.php b/apps/user_ldap/tests/Migration/UUIDFixGroupTest.php
index ab8fe03d6d2..89d880f4acb 100644
--- a/apps/user_ldap/tests/Migration/UUIDFixGroupTest.php
+++ b/apps/user_ldap/tests/Migration/UUIDFixGroupTest.php
@@ -1,14 +1,15 @@
<?php
+
+declare(strict_types=1);
/**
* SPDX-FileCopyrightText: 2017 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
-namespace OCA\Group_LDAP\Tests\Migration;
+namespace OCA\User_LDAP\Tests\Migration;
use OCA\User_LDAP\Group_Proxy;
use OCA\User_LDAP\Mapping\GroupMapping;
use OCA\User_LDAP\Migration\UUIDFixGroup;
-use OCA\User_LDAP\Tests\Migration\AbstractUUIDFixTest;
/**
* Class UUIDFixGroupTest
@@ -16,7 +17,7 @@ use OCA\User_LDAP\Tests\Migration\AbstractUUIDFixTest;
* @package OCA\Group_LDAP\Tests\Migration
* @group DB
*/
-class UUIDFixGroupTest extends AbstractUUIDFixTest {
+class UUIDFixGroupTest extends AbstractUUIDFixTestCase {
protected function setUp(): void {
$this->isUser = false;
parent::setUp();
diff --git a/apps/user_ldap/tests/Migration/UUIDFixInsertTest.php b/apps/user_ldap/tests/Migration/UUIDFixInsertTest.php
index e3ce332577d..6215ffcb6a1 100644
--- a/apps/user_ldap/tests/Migration/UUIDFixInsertTest.php
+++ b/apps/user_ldap/tests/Migration/UUIDFixInsertTest.php
@@ -1,4 +1,6 @@
<?php
+
+declare(strict_types=1);
/**
* SPDX-FileCopyrightText: 2017 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
@@ -11,23 +13,15 @@ use OCA\User_LDAP\Migration\UUIDFixInsert;
use OCP\BackgroundJob\IJobList;
use OCP\IConfig;
use OCP\Migration\IOutput;
+use PHPUnit\Framework\MockObject\MockObject;
use Test\TestCase;
class UUIDFixInsertTest extends TestCase {
- /** @var IConfig|\PHPUnit\Framework\MockObject\MockObject */
- protected $config;
-
- /** @var UserMapping|\PHPUnit\Framework\MockObject\MockObject */
- protected $userMapper;
-
- /** @var GroupMapping|\PHPUnit\Framework\MockObject\MockObject */
- protected $groupMapper;
-
- /** @var IJobList|\PHPUnit\Framework\MockObject\MockObject */
- protected $jobList;
-
- /** @var UUIDFixInsert */
- protected $job;
+ protected IConfig&MockObject $config;
+ protected UserMapping&MockObject $userMapper;
+ protected GroupMapping&MockObject $groupMapper;
+ protected IJobList&MockObject $jobList;
+ protected UUIDFixInsert $job;
protected function setUp(): void {
parent::setUp();
@@ -44,17 +38,16 @@ class UUIDFixInsertTest extends TestCase {
);
}
- public function testGetName() {
+ public function testGetName(): void {
$this->assertSame('Insert UUIDFix background job for user and group in batches', $this->job->getName());
}
- public function recordProvider() {
+ public static function recordProvider(): array {
$record = [
'dn' => 'cn=somerecord,dc=somewhere',
'name' => 'Something',
'uuid' => 'AB12-3456-CDEF7-8GH9'
];
- array_fill(0, 50, $record);
$userBatches = [
0 => array_fill(0, 50, $record),
@@ -71,13 +64,12 @@ class UUIDFixInsertTest extends TestCase {
];
}
- public function recordProviderTooLongAndNone() {
+ public static function recordProviderTooLongAndNone(): array {
$record = [
'dn' => 'cn=somerecord,dc=somewhere',
'name' => 'Something',
'uuid' => 'AB12-3456-CDEF7-8GH9'
];
- array_fill(0, 50, $record);
$userBatches = [
0 => array_fill(0, 50, $record),
@@ -94,10 +86,8 @@ class UUIDFixInsertTest extends TestCase {
];
}
- /**
- * @dataProvider recordProvider
- */
- public function testRun($userBatches, $groupBatches) {
+ #[\PHPUnit\Framework\Attributes\DataProvider('recordProvider')]
+ public function testRun(array $userBatches, array $groupBatches): void {
$this->config->expects($this->once())
->method('getAppValue')
->with('user_ldap', 'installed_version', '1.2.1')
@@ -105,8 +95,11 @@ class UUIDFixInsertTest extends TestCase {
$this->userMapper->expects($this->exactly(3))
->method('getList')
- ->withConsecutive([0, 50], [50, 50], [100, 50])
- ->willReturnOnConsecutiveCalls($userBatches[0], $userBatches[1], $userBatches[2]);
+ ->willReturnMap([
+ [0, 50, false, $userBatches[0]],
+ [50, 50, false, $userBatches[1]],
+ [100, 50, false, $userBatches[2]],
+ ]);
$this->groupMapper->expects($this->exactly(1))
->method('getList')
@@ -121,10 +114,8 @@ class UUIDFixInsertTest extends TestCase {
$this->job->run($out);
}
- /**
- * @dataProvider recordProviderTooLongAndNone
- */
- public function testRunWithManyAndNone($userBatches, $groupBatches) {
+ #[\PHPUnit\Framework\Attributes\DataProvider('recordProviderTooLongAndNone')]
+ public function testRunWithManyAndNone(array $userBatches, array $groupBatches): void {
$this->config->expects($this->once())
->method('getAppValue')
->with('user_ldap', 'installed_version', '1.2.1')
@@ -132,8 +123,13 @@ class UUIDFixInsertTest extends TestCase {
$this->userMapper->expects($this->exactly(5))
->method('getList')
- ->withConsecutive([0, 50], [0, 40], [0, 32], [32, 32], [64, 32])
- ->willReturnOnConsecutiveCalls($userBatches[0], $userBatches[1], $userBatches[2], $userBatches[3], $userBatches[4]);
+ ->willReturnMap([
+ [0, 50, false, $userBatches[0]],
+ [0, 40, false, $userBatches[1]],
+ [0, 32, false, $userBatches[2]],
+ [32, 32, false, $userBatches[3]],
+ [64, 32, false, $userBatches[4]],
+ ]);
$this->groupMapper->expects($this->once())
->method('getList')
@@ -155,7 +151,7 @@ class UUIDFixInsertTest extends TestCase {
$this->job->run($out);
}
- public function testDonNotRun() {
+ public function testDonNotRun(): void {
$this->config->expects($this->once())
->method('getAppValue')
->with('user_ldap', 'installed_version', '1.2.1')
diff --git a/apps/user_ldap/tests/Migration/UUIDFixUserTest.php b/apps/user_ldap/tests/Migration/UUIDFixUserTest.php
index dfa1898450f..a582fd677fa 100644
--- a/apps/user_ldap/tests/Migration/UUIDFixUserTest.php
+++ b/apps/user_ldap/tests/Migration/UUIDFixUserTest.php
@@ -1,4 +1,6 @@
<?php
+
+declare(strict_types=1);
/**
* SPDX-FileCopyrightText: 2017 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
@@ -15,7 +17,7 @@ use OCA\User_LDAP\User_Proxy;
* @package OCA\User_LDAP\Tests\Migration
* @group DB
*/
-class UUIDFixUserTest extends AbstractUUIDFixTest {
+class UUIDFixUserTest extends AbstractUUIDFixTestCase {
protected function setUp(): void {
$this->isUser = true;
parent::setUp();
diff --git a/apps/user_ldap/tests/Service/BirthdateParserServiceTest.php b/apps/user_ldap/tests/Service/BirthdateParserServiceTest.php
index 79450d6913e..061118f10c1 100644
--- a/apps/user_ldap/tests/Service/BirthdateParserServiceTest.php
+++ b/apps/user_ldap/tests/Service/BirthdateParserServiceTest.php
@@ -1,11 +1,12 @@
<?php
+declare(strict_types=1);
/**
* SPDX-FileCopyrightText: 2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
-namespace OCA\user_ldap\tests\Service;
+namespace OCA\User_LDAP\Tests\Service;
use DateTimeImmutable;
use OCA\User_LDAP\Service\BirthdateParserService;
@@ -20,7 +21,7 @@ class BirthdateParserServiceTest extends TestCase {
$this->service = new BirthdateParserService();
}
- public function parseBirthdateDataProvider(): array {
+ public static function parseBirthdateDataProvider(): array {
return [
['2024-01-01', new DateTimeImmutable('2024-01-01'), false],
['20240101', new DateTimeImmutable('2024-01-01'), false],
@@ -34,9 +35,7 @@ class BirthdateParserServiceTest extends TestCase {
];
}
- /**
- * @dataProvider parseBirthdateDataProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('parseBirthdateDataProvider')]
public function testParseBirthdate(
string $value,
?DateTimeImmutable $expected,
diff --git a/apps/user_ldap/tests/Service/UpdateGroupsServiceTest.php b/apps/user_ldap/tests/Service/UpdateGroupsServiceTest.php
index 38556ec312f..601aee86602 100644
--- a/apps/user_ldap/tests/Service/UpdateGroupsServiceTest.php
+++ b/apps/user_ldap/tests/Service/UpdateGroupsServiceTest.php
@@ -6,17 +6,15 @@ declare(strict_types=1);
* SPDX-FileCopyrightText: 2020 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
-namespace OCA\user_ldap\tests\Service;
+namespace OCA\User_LDAP\Tests\Service;
use OCA\User_LDAP\Db\GroupMembership;
use OCA\User_LDAP\Db\GroupMembershipMapper;
use OCA\User_LDAP\Group_Proxy;
use OCA\User_LDAP\Service\UpdateGroupsService;
-use OCP\AppFramework\Utility\ITimeFactory;
use OCP\EventDispatcher\IEventDispatcher;
use OCP\Group\Events\UserAddedEvent;
use OCP\Group\Events\UserRemovedEvent;
-use OCP\IConfig;
use OCP\IGroup;
use OCP\IGroupManager;
use OCP\IUser;
@@ -26,23 +24,12 @@ use Psr\Log\LoggerInterface;
use Test\TestCase;
class UpdateGroupsServiceTest extends TestCase {
- /** @var Group_Proxy|MockObject */
- protected $groupBackend;
- /** @var IEventDispatcher|MockObject */
- protected $dispatcher;
- /** @var IGroupManager|MockObject */
- protected $groupManager;
- /** @var IUserManager|MockObject */
- protected $userManager;
- /** @var LoggerInterface|MockObject */
- protected $logger;
- /** @var GroupMembershipMapper|MockObject */
- protected $groupMembershipMapper;
- /** @var IConfig|MockObject */
- protected $config;
- /** @var ITimeFactory|MockObject */
- protected $timeFactory;
-
+ protected Group_Proxy&MockObject $groupBackend;
+ protected IEventDispatcher&MockObject $dispatcher;
+ protected IGroupManager&MockObject $groupManager;
+ protected IUserManager&MockObject $userManager;
+ protected LoggerInterface&MockObject $logger;
+ protected GroupMembershipMapper&MockObject $groupMembershipMapper;
protected UpdateGroupsService $updateGroupsService;
public function setUp(): void {
@@ -52,8 +39,6 @@ class UpdateGroupsServiceTest extends TestCase {
$this->userManager = $this->createMock(IUserManager::class);
$this->logger = $this->createMock(LoggerInterface::class);
$this->groupMembershipMapper = $this->createMock(GroupMembershipMapper::class);
- $this->config = $this->createMock(IConfig::class);
- $this->timeFactory = $this->createMock(ITimeFactory::class);
$this->updateGroupsService = new UpdateGroupsService(
$this->groupBackend,
@@ -62,8 +47,6 @@ class UpdateGroupsServiceTest extends TestCase {
$this->userManager,
$this->logger,
$this->groupMembershipMapper,
- $this->config,
- $this->timeFactory
);
}
@@ -137,7 +120,7 @@ class UpdateGroupsServiceTest extends TestCase {
$removedEvents = 0;
$this->dispatcher->expects($this->exactly(4))
->method('dispatchTyped')
- ->willReturnCallback(function ($event) use (&$addedEvents, &$removedEvents) {
+ ->willReturnCallback(function ($event) use (&$addedEvents, &$removedEvents): void {
if ($event instanceof UserRemovedEvent) {
$removedEvents++;
} elseif ($event instanceof UserAddedEvent) {
diff --git a/apps/user_ldap/tests/Settings/AdminTest.php b/apps/user_ldap/tests/Settings/AdminTest.php
index 7906a07c3e9..b17e96c1a68 100644
--- a/apps/user_ldap/tests/Settings/AdminTest.php
+++ b/apps/user_ldap/tests/Settings/AdminTest.php
@@ -1,4 +1,6 @@
<?php
+
+declare(strict_types=1);
/**
* SPDX-FileCopyrightText: 2016 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
@@ -9,7 +11,9 @@ use OCA\User_LDAP\Configuration;
use OCA\User_LDAP\Settings\Admin;
use OCP\AppFramework\Http\TemplateResponse;
use OCP\IL10N;
-use OCP\Template;
+use OCP\Server;
+use OCP\Template\ITemplateManager;
+use PHPUnit\Framework\MockObject\MockObject;
use Test\TestCase;
/**
@@ -17,32 +21,31 @@ use Test\TestCase;
* @package OCA\User_LDAP\Tests\Settings
*/
class AdminTest extends TestCase {
- /** @var Admin */
- private $admin;
- /** @var IL10N */
- private $l10n;
+ private IL10N&MockObject $l10n;
+ private ITemplateManager $templateManager;
+ private Admin $admin;
protected function setUp(): void {
parent::setUp();
- $this->l10n = $this->getMockBuilder(IL10N::class)->getMock();
+ $this->l10n = $this->createMock(IL10N::class);
+ $this->templateManager = Server::get(ITemplateManager::class);
$this->admin = new Admin(
- $this->l10n
+ $this->l10n,
+ $this->templateManager,
);
}
- /**
- * @UseDB
- */
- public function testGetForm() {
+ public function testGetForm(): void {
$prefixes = ['s01'];
$hosts = ['s01' => ''];
- $wControls = new Template('user_ldap', 'part.wizardcontrols');
+ $wControls = $this->templateManager->getTemplate('user_ldap', 'part.wizardcontrols');
$wControls = $wControls->fetchPage();
- $sControls = new Template('user_ldap', 'part.settingcontrols');
+ $sControls = $this->templateManager->getTemplate('user_ldap', 'part.settingcontrols');
$sControls = $sControls->fetchPage();
+ $parameters = [];
$parameters['serverConfigurationPrefixes'] = $prefixes;
$parameters['serverConfigurationHosts'] = $hosts;
$parameters['settingControls'] = $sControls;
@@ -52,18 +55,18 @@ class AdminTest extends TestCase {
$config = new Configuration('', false);
$defaults = $config->getDefaults();
foreach ($defaults as $key => $default) {
- $parameters[$key.'_default'] = $default;
+ $parameters[$key . '_default'] = $default;
}
$expected = new TemplateResponse('user_ldap', 'settings', $parameters);
$this->assertEquals($expected, $this->admin->getForm());
}
- public function testGetSection() {
+ public function testGetSection(): void {
$this->assertSame('ldap', $this->admin->getSection());
}
- public function testGetPriority() {
+ public function testGetPriority(): void {
$this->assertSame(5, $this->admin->getPriority());
}
}
diff --git a/apps/user_ldap/tests/Settings/SectionTest.php b/apps/user_ldap/tests/Settings/SectionTest.php
index 5fe5476f1c3..3f9ae1e56d4 100644
--- a/apps/user_ldap/tests/Settings/SectionTest.php
+++ b/apps/user_ldap/tests/Settings/SectionTest.php
@@ -1,4 +1,6 @@
<?php
+
+declare(strict_types=1);
/**
* SPDX-FileCopyrightText: 2016 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
@@ -8,15 +10,13 @@ namespace OCA\User_LDAP\Tests\Settings;
use OCA\User_LDAP\Settings\Section;
use OCP\IL10N;
use OCP\IURLGenerator;
+use PHPUnit\Framework\MockObject\MockObject;
use Test\TestCase;
class SectionTest extends TestCase {
- /** @var IURLGenerator|\PHPUnit\Framework\MockObject\MockObject */
- private $url;
- /** @var IL10N|\PHPUnit\Framework\MockObject\MockObject */
- private $l;
- /** @var Section */
- private $section;
+ private IURLGenerator&MockObject $url;
+ private IL10N&MockObject $l;
+ private Section $section;
protected function setUp(): void {
parent::setUp();
@@ -29,11 +29,11 @@ class SectionTest extends TestCase {
);
}
- public function testGetID() {
+ public function testGetID(): void {
$this->assertSame('ldap', $this->section->getID());
}
- public function testGetName() {
+ public function testGetName(): void {
$this->l
->expects($this->once())
->method('t')
@@ -43,11 +43,11 @@ class SectionTest extends TestCase {
$this->assertSame('LDAP/AD integration', $this->section->getName());
}
- public function testGetPriority() {
+ public function testGetPriority(): void {
$this->assertSame(25, $this->section->getPriority());
}
- public function testGetIcon() {
+ public function testGetIcon(): void {
$this->url->expects($this->once())
->method('imagePath')
->with('user_ldap', 'app-dark.svg')
diff --git a/apps/user_ldap/tests/User/DeletedUsersIndexTest.php b/apps/user_ldap/tests/User/DeletedUsersIndexTest.php
index 32fa5bc38bf..b245e52fe6e 100644
--- a/apps/user_ldap/tests/User/DeletedUsersIndexTest.php
+++ b/apps/user_ldap/tests/User/DeletedUsersIndexTest.php
@@ -1,4 +1,6 @@
<?php
+
+declare(strict_types=1);
/**
* SPDX-FileCopyrightText: 2018 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
@@ -9,7 +11,9 @@ use OCA\User_LDAP\Mapping\UserMapping;
use OCA\User_LDAP\User\DeletedUsersIndex;
use OCP\IConfig;
use OCP\IDBConnection;
+use OCP\Server;
use OCP\Share\IManager;
+use PHPUnit\Framework\MockObject\MockObject;
/**
* Class DeletedUsersIndexTest
@@ -19,26 +23,18 @@ use OCP\Share\IManager;
* @package OCA\User_LDAP\Tests\User
*/
class DeletedUsersIndexTest extends \Test\TestCase {
- /** @var DeletedUsersIndex */
- protected $dui;
-
- /** @var IConfig */
- protected $config;
-
- /** @var IDBConnection */
- protected $db;
-
- /** @var UserMapping|\PHPUnit\Framework\MockObject\MockObject */
- protected $mapping;
- /** @var IManager|\PHPUnit\Framework\MockObject\MockObject */
- protected $shareManager;
+ protected DeletedUsersIndex $dui;
+ protected IConfig $config;
+ protected IDBConnection $db;
+ protected UserMapping&MockObject $mapping;
+ protected IManager&MockObject $shareManager;
protected function setUp(): void {
parent::setUp();
// no mocks for those as tests go against DB
- $this->config = \OC::$server->getConfig();
- $this->db = \OC::$server->getDatabaseConnection();
+ $this->config = Server::get(IConfig::class);
+ $this->db = Server::get(IDBConnection::class);
// ensure a clean database
$this->config->deleteAppFromAllUsers('user_ldap');
@@ -54,7 +50,7 @@ class DeletedUsersIndexTest extends \Test\TestCase {
parent::tearDown();
}
- public function testMarkAndFetchUser() {
+ public function testMarkAndFetchUser(): void {
$uids = [
'cef3775c-71d2-48eb-8984-39a4051b0b95',
'8c4bbb40-33ed-42d0-9b14-85b0ab76c1cc',
@@ -82,7 +78,7 @@ class DeletedUsersIndexTest extends \Test\TestCase {
$this->assertEmpty($uids);
}
- public function testUnmarkUser() {
+ public function testUnmarkUser(): void {
$uids = [
'22a162c7-a9ee-487c-9f33-0563795583fb',
'1fb4e0da-4a75-47f3-8fa7-becc7e35c9c5',
diff --git a/apps/user_ldap/tests/User/ManagerTest.php b/apps/user_ldap/tests/User/ManagerTest.php
index 597a2e69a0a..bf9d1f5746f 100644
--- a/apps/user_ldap/tests/User/ManagerTest.php
+++ b/apps/user_ldap/tests/User/ManagerTest.php
@@ -1,5 +1,6 @@
<?php
+declare(strict_types=1);
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -9,7 +10,6 @@ namespace OCA\User_LDAP\Tests\User;
use OCA\User_LDAP\Access;
use OCA\User_LDAP\Connection;
-use OCA\User_LDAP\FilesystemHelper;
use OCA\User_LDAP\ILDAPWrapper;
use OCA\User_LDAP\User\Manager;
use OCA\User_LDAP\User\User;
@@ -20,6 +20,7 @@ use OCP\Image;
use OCP\IUserManager;
use OCP\Notification\IManager as INotificationManager;
use OCP\Share\IManager;
+use PHPUnit\Framework\MockObject\MockObject;
use Psr\Log\LoggerInterface;
/**
@@ -30,50 +31,24 @@ use Psr\Log\LoggerInterface;
* @package OCA\User_LDAP\Tests\User
*/
class ManagerTest extends \Test\TestCase {
- /** @var Access|\PHPUnit\Framework\MockObject\MockObject */
- protected $access;
-
- /** @var IConfig|\PHPUnit\Framework\MockObject\MockObject */
- protected $config;
-
- /** @var FilesystemHelper|\PHPUnit\Framework\MockObject\MockObject */
- protected $fileSystemHelper;
-
- /** @var LoggerInterface|\PHPUnit\Framework\MockObject\MockObject */
- protected $logger;
-
- /** @var IAvatarManager|\PHPUnit\Framework\MockObject\MockObject */
- protected $avatarManager;
-
- /** @var Image|\PHPUnit\Framework\MockObject\MockObject */
- protected $image;
-
- /** @var IDBConnection|\PHPUnit\Framework\MockObject\MockObject */
- protected $dbc;
-
- /** @var IUserManager|\PHPUnit\Framework\MockObject\MockObject */
- protected $ncUserManager;
-
- /** @var INotificationManager|\PHPUnit\Framework\MockObject\MockObject */
- protected $notificationManager;
-
- /** @var ILDAPWrapper|\PHPUnit\Framework\MockObject\MockObject */
- protected $ldapWrapper;
-
- /** @var Connection */
- protected $connection;
-
- /** @var Manager */
- protected $manager;
- /** @var IManager|\PHPUnit\Framework\MockObject\MockObject */
- protected $shareManager;
+ protected Access&MockObject $access;
+ protected IConfig&MockObject $config;
+ protected LoggerInterface&MockObject $logger;
+ protected IAvatarManager&MockObject $avatarManager;
+ protected Image&MockObject $image;
+ protected IDBConnection&MockObject $dbc;
+ protected IUserManager&MockObject $ncUserManager;
+ protected INotificationManager&MockObject $notificationManager;
+ protected ILDAPWrapper&MockObject $ldapWrapper;
+ protected Connection $connection;
+ protected IManager&MockObject $shareManager;
+ protected Manager $manager;
protected function setUp(): void {
parent::setUp();
$this->access = $this->createMock(Access::class);
$this->config = $this->createMock(IConfig::class);
- $this->fileSystemHelper = $this->createMock(FilesystemHelper::class);
$this->logger = $this->createMock(LoggerInterface::class);
$this->avatarManager = $this->createMock(IAvatarManager::class);
$this->image = $this->createMock(Image::class);
@@ -91,7 +66,6 @@ class ManagerTest extends \Test\TestCase {
/** @noinspection PhpUnhandledExceptionInspection */
$this->manager = new Manager(
$this->config,
- $this->fileSystemHelper,
$this->logger,
$this->avatarManager,
$this->image,
@@ -103,7 +77,7 @@ class ManagerTest extends \Test\TestCase {
$this->manager->setLdapAccess($this->access);
}
- public function dnProvider() {
+ public static function dnProvider(): array {
return [
['cn=foo,dc=foobar,dc=bar'],
['uid=foo,o=foobar,c=bar'],
@@ -111,10 +85,8 @@ class ManagerTest extends \Test\TestCase {
];
}
- /**
- * @dataProvider dnProvider
- */
- public function testGetByDNExisting(string $inputDN) {
+ #[\PHPUnit\Framework\Attributes\DataProvider('dnProvider')]
+ public function testGetByDNExisting(string $inputDN): void {
$uid = '563418fc-423b-1033-8d1c-ad5f418ee02e';
$this->access->expects($this->once())
@@ -139,7 +111,7 @@ class ManagerTest extends \Test\TestCase {
$this->assertInstanceOf(User::class, $user);
}
- public function testGetByDNNotExisting() {
+ public function testGetByDNNotExisting(): void {
$inputDN = 'cn=gone,dc=foobar,dc=bar';
$this->access->expects($this->once())
@@ -161,7 +133,7 @@ class ManagerTest extends \Test\TestCase {
$this->assertNull($user);
}
- public function testGetByUidExisting() {
+ public function testGetByUidExisting(): void {
$dn = 'cn=foo,dc=foobar,dc=bar';
$uid = '563418fc-423b-1033-8d1c-ad5f418ee02e';
@@ -187,7 +159,7 @@ class ManagerTest extends \Test\TestCase {
$this->assertInstanceOf(User::class, $user);
}
- public function testGetByUidNotExisting() {
+ public function testGetByUidNotExisting(): void {
$uid = 'gone';
$this->access->expects($this->never())
@@ -203,17 +175,15 @@ class ManagerTest extends \Test\TestCase {
$this->assertNull($user);
}
- public function attributeRequestProvider() {
+ public static function attributeRequestProvider(): array {
return [
[false],
[true],
];
}
- /**
- * @dataProvider attributeRequestProvider
- */
- public function testGetAttributes($minimal) {
+ #[\PHPUnit\Framework\Attributes\DataProvider('attributeRequestProvider')]
+ public function testGetAttributes($minimal): void {
$this->connection->setConfiguration([
'ldapEmailAttribute' => 'MAIL',
'ldapUserAvatarRule' => 'default',
@@ -223,10 +193,10 @@ class ManagerTest extends \Test\TestCase {
$attributes = $this->manager->getAttributes($minimal);
- $this->assertTrue(in_array('dn', $attributes));
- $this->assertTrue(in_array(strtolower($this->access->getConnection()->ldapEmailAttribute), $attributes));
- $this->assertTrue(!in_array($this->access->getConnection()->ldapEmailAttribute, $attributes)); #cases check
- $this->assertFalse(in_array('', $attributes));
+ $this->assertContains('dn', $attributes);
+ $this->assertContains(strtolower($this->access->getConnection()->ldapEmailAttribute), $attributes);
+ $this->assertNotContains($this->access->getConnection()->ldapEmailAttribute, $attributes); #cases check
+ $this->assertNotContains('', $attributes);
$this->assertSame(!$minimal, in_array('jpegphoto', $attributes));
$this->assertSame(!$minimal, in_array('thumbnailphoto', $attributes));
$valueCounts = array_count_values($attributes);
diff --git a/apps/user_ldap/tests/User/OfflineUserTest.php b/apps/user_ldap/tests/User/OfflineUserTest.php
index 8ac0e617d80..223e63421ad 100644
--- a/apps/user_ldap/tests/User/OfflineUserTest.php
+++ b/apps/user_ldap/tests/User/OfflineUserTest.php
@@ -13,20 +13,15 @@ use OCA\User_LDAP\User\OfflineUser;
use OCP\IConfig;
use OCP\Share\IManager;
use OCP\Share\IShare;
+use PHPUnit\Framework\MockObject\MockObject;
use Test\TestCase;
class OfflineUserTest extends TestCase {
-
- /** @var OfflineUser */
- protected $offlineUser;
- /** @var UserMapping|\PHPUnit\Framework\MockObject\MockObject */
- protected $mapping;
- /** @var string */
- protected $uid;
- /** @var IConfig|\PHPUnit\Framework\MockObject\MockObject */
- protected $config;
- /** @var IManager|\PHPUnit\Framework\MockObject\MockObject */
- protected $shareManager;
+ protected UserMapping&MockObject $mapping;
+ protected string $uid;
+ protected IConfig&MockObject $config;
+ protected IManager&MockObject $shareManager;
+ protected OfflineUser $offlineUser;
public function setUp(): void {
$this->uid = 'deborah';
@@ -42,7 +37,7 @@ class OfflineUserTest extends TestCase {
);
}
- public function shareOwnerProvider(): array {
+ public static function shareOwnerProvider(): array {
return [
[[], false],
[[IShare::TYPE_USER], true],
@@ -52,10 +47,8 @@ class OfflineUserTest extends TestCase {
];
}
- /**
- * @dataProvider shareOwnerProvider
- */
- public function testHasActiveShares(array $existingShareTypes, bool $expected) {
+ #[\PHPUnit\Framework\Attributes\DataProvider('shareOwnerProvider')]
+ public function testHasActiveShares(array $existingShareTypes, bool $expected): void {
$shareMock = $this->createMock(IShare::class);
$this->shareManager->expects($this->atLeastOnce())
diff --git a/apps/user_ldap/tests/User/UserTest.php b/apps/user_ldap/tests/User/UserTest.php
index ec5cf03f402..00edd8b3f9b 100644
--- a/apps/user_ldap/tests/User/UserTest.php
+++ b/apps/user_ldap/tests/User/UserTest.php
@@ -1,5 +1,6 @@
<?php
+declare(strict_types=1);
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -9,7 +10,7 @@ namespace OCA\User_LDAP\Tests\User;
use OCA\User_LDAP\Access;
use OCA\User_LDAP\Connection;
-use OCA\User_LDAP\FilesystemHelper;
+use OCA\User_LDAP\ILDAPWrapper;
use OCA\User_LDAP\User\User;
use OCP\IAvatar;
use OCP\IAvatarManager;
@@ -19,6 +20,8 @@ use OCP\IUser;
use OCP\IUserManager;
use OCP\Notification\IManager as INotificationManager;
use OCP\Notification\INotification;
+use OCP\Util;
+use PHPUnit\Framework\MockObject\MockObject;
use Psr\Log\LoggerInterface;
/**
@@ -29,35 +32,24 @@ use Psr\Log\LoggerInterface;
* @package OCA\User_LDAP\Tests\User
*/
class UserTest extends \Test\TestCase {
- /** @var Access|\PHPUnit\Framework\MockObject\MockObject */
- protected $access;
- /** @var Connection|\PHPUnit\Framework\MockObject\MockObject */
- protected $connection;
- /** @var IConfig|\PHPUnit\Framework\MockObject\MockObject */
- protected $config;
- /** @var FilesystemHelper|\PHPUnit\Framework\MockObject\MockObject */
- protected $filesystemhelper;
- /** @var INotificationManager|\PHPUnit\Framework\MockObject\MockObject */
- protected $notificationManager;
- /** @var IUserManager|\PHPUnit\Framework\MockObject\MockObject */
- protected $userManager;
- /** @var Image|\PHPUnit\Framework\MockObject\MockObject */
- protected $image;
- /** @var IAvatarManager|\PHPUnit\Framework\MockObject\MockObject */
- protected $avatarManager;
- /** @var LoggerInterface|\PHPUnit\Framework\MockObject\MockObject */
- protected $logger;
- /** @var string */
- protected $uid = 'alice';
- /** @var string */
- protected $dn = 'uid=alice,dc=foo,dc=bar';
- /** @var User */
- protected $user;
+ protected Access&MockObject $access;
+ protected Connection&MockObject $connection;
+ protected IConfig&MockObject $config;
+ protected INotificationManager&MockObject $notificationManager;
+ protected IUserManager&MockObject $userManager;
+ protected Image&MockObject $image;
+ protected IAvatarManager&MockObject $avatarManager;
+ protected LoggerInterface&MockObject $logger;
+ protected string $uid = 'alice';
+ protected string $dn = 'uid=alice,dc=foo,dc=bar';
+ protected User $user;
protected function setUp(): void {
parent::setUp();
- $this->connection = $this->createMock(Connection::class);
+ $this->connection = $this->getMockBuilder(Connection::class)
+ ->setConstructorArgs([$this->createMock(ILDAPWrapper::class)])
+ ->getMock();
$this->access = $this->createMock(Access::class);
$this->access->connection = $this->connection;
@@ -66,7 +58,6 @@ class UserTest extends \Test\TestCase {
->willReturn($this->connection);
$this->config = $this->createMock(IConfig::class);
- $this->filesystemhelper = $this->createMock(FilesystemHelper::class);
$this->logger = $this->createMock(LoggerInterface::class);
$this->avatarManager = $this->createMock(IAvatarManager::class);
$this->image = $this->createMock(Image::class);
@@ -78,7 +69,6 @@ class UserTest extends \Test\TestCase {
$this->dn,
$this->access,
$this->config,
- $this->filesystemhelper,
$this->image,
$this->logger,
$this->avatarManager,
@@ -87,12 +77,12 @@ class UserTest extends \Test\TestCase {
);
}
- public function testGetDNandUsername() {
+ public function testGetDNandUsername(): void {
$this->assertSame($this->dn, $this->user->getDN());
$this->assertSame($this->uid, $this->user->getUsername());
}
- public function testUpdateEmailProvided() {
+ public function testUpdateEmailProvided(): void {
$this->connection->expects($this->once())
->method('__get')
->with($this->equalTo('ldapEmailAttribute'))
@@ -104,11 +94,9 @@ class UserTest extends \Test\TestCase {
$this->equalTo('email'))
->willReturn(['alice@foo.bar']);
- $coreUser = $this->getMockBuilder(IUser::class)
- ->disableOriginalConstructor()
- ->getMock();
+ $coreUser = $this->createMock(IUser::class);
$coreUser->expects($this->once())
- ->method('setEMailAddress')
+ ->method('setSystemEMailAddress')
->with('alice@foo.bar');
$this->userManager->expects($this->any())
@@ -118,7 +106,7 @@ class UserTest extends \Test\TestCase {
$this->user->updateEmail();
}
- public function testUpdateEmailNotProvided() {
+ public function testUpdateEmailNotProvided(): void {
$this->connection->expects($this->once())
->method('__get')
->with($this->equalTo('ldapEmailAttribute'))
@@ -136,7 +124,7 @@ class UserTest extends \Test\TestCase {
$this->user->updateEmail();
}
- public function testUpdateEmailNotConfigured() {
+ public function testUpdateEmailNotConfigured(): void {
$this->connection->expects($this->once())
->method('__get')
->with($this->equalTo('ldapEmailAttribute'))
@@ -151,7 +139,7 @@ class UserTest extends \Test\TestCase {
$this->user->updateEmail();
}
- public function testUpdateQuotaAllProvided() {
+ public function testUpdateQuotaAllProvided(): void {
$this->connection->expects($this->exactly(2))
->method('__get')
->willReturnMap([
@@ -178,7 +166,7 @@ class UserTest extends \Test\TestCase {
$this->user->updateQuota();
}
- public function testUpdateQuotaToDefaultAllProvided() {
+ public function testUpdateQuotaToDefaultAllProvided(): void {
$this->connection->expects($this->exactly(2))
->method('__get')
->willReturnMap([
@@ -205,7 +193,7 @@ class UserTest extends \Test\TestCase {
$this->user->updateQuota();
}
- public function testUpdateQuotaToNoneAllProvided() {
+ public function testUpdateQuotaToNoneAllProvided(): void {
$this->connection->expects($this->exactly(2))
->method('__get')
->willReturnMap([
@@ -232,7 +220,7 @@ class UserTest extends \Test\TestCase {
$this->user->updateQuota();
}
- public function testUpdateQuotaDefaultProvided() {
+ public function testUpdateQuotaDefaultProvided(): void {
$this->connection->expects($this->exactly(2))
->method('__get')
->willReturnMap([
@@ -259,7 +247,7 @@ class UserTest extends \Test\TestCase {
$this->user->updateQuota();
}
- public function testUpdateQuotaIndividualProvided() {
+ public function testUpdateQuotaIndividualProvided(): void {
$this->connection->expects($this->exactly(2))
->method('__get')
->willReturnMap([
@@ -286,7 +274,7 @@ class UserTest extends \Test\TestCase {
$this->user->updateQuota();
}
- public function testUpdateQuotaNoneProvided() {
+ public function testUpdateQuotaNoneProvided(): void {
$this->connection->expects($this->exactly(2))
->method('__get')
->willReturnMap([
@@ -314,7 +302,7 @@ class UserTest extends \Test\TestCase {
$this->user->updateQuota();
}
- public function testUpdateQuotaNoneConfigured() {
+ public function testUpdateQuotaNoneConfigured(): void {
$this->connection->expects($this->exactly(2))
->method('__get')
->willReturnMap([
@@ -338,7 +326,7 @@ class UserTest extends \Test\TestCase {
$this->user->updateQuota();
}
- public function testUpdateQuotaFromValue() {
+ public function testUpdateQuotaFromValue(): void {
$readQuota = '19 GB';
$this->connection->expects($this->exactly(2))
@@ -367,7 +355,7 @@ class UserTest extends \Test\TestCase {
/**
* Unparseable quota will fallback to use the LDAP default
*/
- public function testUpdateWrongQuotaAllProvided() {
+ public function testUpdateWrongQuotaAllProvided(): void {
$this->connection->expects($this->exactly(2))
->method('__get')
->willReturnMap([
@@ -397,7 +385,7 @@ class UserTest extends \Test\TestCase {
/**
* No user quota and wrong default will set 'default' as quota
*/
- public function testUpdateWrongDefaultQuotaProvided() {
+ public function testUpdateWrongDefaultQuotaProvided(): void {
$this->connection->expects($this->exactly(2))
->method('__get')
->willReturnMap([
@@ -424,7 +412,7 @@ class UserTest extends \Test\TestCase {
/**
* Wrong user quota and wrong default will set 'default' as quota
*/
- public function testUpdateWrongQuotaAndDefaultAllProvided() {
+ public function testUpdateWrongQuotaAndDefaultAllProvided(): void {
$this->connection->expects($this->exactly(2))
->method('__get')
->willReturnMap([
@@ -451,7 +439,7 @@ class UserTest extends \Test\TestCase {
/**
* No quota attribute set and wrong default will set 'default' as quota
*/
- public function testUpdateWrongDefaultQuotaNotProvided() {
+ public function testUpdateWrongDefaultQuotaNotProvided(): void {
$this->connection->expects($this->exactly(2))
->method('__get')
->willReturnMap([
@@ -507,14 +495,10 @@ class UserTest extends \Test\TestCase {
->method('setUserValue')
->with($this->uid, 'user_ldap', 'lastAvatarChecksum', md5('this is a photo'));
- $this->filesystemhelper->expects($this->once())
- ->method('isLoaded')
- ->willReturn(true);
-
$avatar = $this->createMock(IAvatar::class);
$avatar->expects($this->once())
->method('set')
- ->with($this->isInstanceOf($this->image));
+ ->with($this->image);
$this->avatarManager->expects($this->once())
->method('getAvatar')
@@ -529,7 +513,7 @@ class UserTest extends \Test\TestCase {
$this->user->updateAvatar();
}
- public function testUpdateAvatarKnownJpegPhotoProvided() {
+ public function testUpdateAvatarKnownJpegPhotoProvided(): void {
$this->access->expects($this->once())
->method('readAttribute')
->with($this->equalTo($this->dn),
@@ -558,9 +542,6 @@ class UserTest extends \Test\TestCase {
$this->config->expects($this->never())
->method('setUserValue');
- $this->filesystemhelper->expects($this->never())
- ->method('isLoaded');
-
$avatar = $this->createMock(IAvatar::class);
$avatar->expects($this->never())
->method('set');
@@ -625,14 +606,10 @@ class UserTest extends \Test\TestCase {
->method('setUserValue')
->with($this->uid, 'user_ldap', 'lastAvatarChecksum', md5('this is a photo'));
- $this->filesystemhelper->expects($this->once())
- ->method('isLoaded')
- ->willReturn(true);
-
$avatar = $this->createMock(IAvatar::class);
$avatar->expects($this->once())
->method('set')
- ->with($this->isInstanceOf($this->image));
+ ->with($this->image);
$this->avatarManager->expects($this->once())
->method('getAvatar')
@@ -647,7 +624,7 @@ class UserTest extends \Test\TestCase {
$this->user->updateAvatar();
}
- public function testUpdateAvatarCorruptPhotoProvided() {
+ public function testUpdateAvatarCorruptPhotoProvided(): void {
$this->access->expects($this->any())
->method('readAttribute')
->willReturnCallback(function ($dn, $attr) {
@@ -680,9 +657,6 @@ class UserTest extends \Test\TestCase {
$this->config->expects($this->never())
->method('setUserValue');
- $this->filesystemhelper->expects($this->never())
- ->method('isLoaded');
-
$avatar = $this->createMock(IAvatar::class);
$avatar->expects($this->never())
->method('set');
@@ -738,14 +712,10 @@ class UserTest extends \Test\TestCase {
$this->config->expects($this->never())
->method('setUserValue');
- $this->filesystemhelper->expects($this->once())
- ->method('isLoaded')
- ->willReturn(true);
-
$avatar = $this->createMock(IAvatar::class);
$avatar->expects($this->once())
->method('set')
- ->with($this->isInstanceOf($this->image))
+ ->with($this->image)
->willThrowException(new \Exception());
$this->avatarManager->expects($this->once())
@@ -761,7 +731,7 @@ class UserTest extends \Test\TestCase {
$this->assertFalse($this->user->updateAvatar());
}
- public function testUpdateAvatarNotProvided() {
+ public function testUpdateAvatarNotProvided(): void {
$this->access->expects($this->any())
->method('readAttribute')
->willReturnCallback(function ($dn, $attr) {
@@ -791,9 +761,6 @@ class UserTest extends \Test\TestCase {
$this->config->expects($this->never())
->method('setUserValue');
- $this->filesystemhelper->expects($this->never())
- ->method('isLoaded');
-
$this->avatarManager->expects($this->never())
->method('getAvatar');
@@ -805,7 +772,7 @@ class UserTest extends \Test\TestCase {
$this->user->updateAvatar();
}
- public function extStorageHomeDataProvider() {
+ public static function extStorageHomeDataProvider(): array {
return [
[ 'myFolder', null ],
[ '', null, false ],
@@ -813,10 +780,8 @@ class UserTest extends \Test\TestCase {
];
}
- /**
- * @dataProvider extStorageHomeDataProvider
- */
- public function testUpdateExtStorageHome(string $expected, ?string $valueFromLDAP = null, bool $isSet = true) {
+ #[\PHPUnit\Framework\Attributes\DataProvider('extStorageHomeDataProvider')]
+ public function testUpdateExtStorageHome(string $expected, ?string $valueFromLDAP = null, bool $isSet = true): void {
if ($valueFromLDAP === null) {
$this->connection->expects($this->once())
->method('__get')
@@ -848,7 +813,7 @@ class UserTest extends \Test\TestCase {
$this->assertSame($expected, $actual);
}
- public function testMarkLogin() {
+ public function testMarkLogin(): void {
$this->config->expects($this->once())
->method('setUserValue')
->with($this->equalTo($this->uid),
@@ -860,7 +825,7 @@ class UserTest extends \Test\TestCase {
$this->user->markLogin();
}
- public function testGetAvatarImageProvided() {
+ public function testGetAvatarImageProvided(): void {
$this->access->expects($this->once())
->method('readAttribute')
->with($this->equalTo($this->dn),
@@ -878,7 +843,7 @@ class UserTest extends \Test\TestCase {
$this->user->getAvatarImage();
}
- public function testGetAvatarImageDisabled() {
+ public function testGetAvatarImageDisabled(): void {
$this->access->expects($this->never())
->method('readAttribute')
->with($this->equalTo($this->dn), $this->anything());
@@ -890,7 +855,7 @@ class UserTest extends \Test\TestCase {
$this->assertFalse($this->user->getAvatarImage());
}
- public function imageDataProvider() {
+ public static function imageDataProvider(): array {
return [
[ false, false ],
[ 'corruptData', false ],
@@ -898,7 +863,7 @@ class UserTest extends \Test\TestCase {
];
}
- public function testProcessAttributes() {
+ public function testProcessAttributes(): void {
$requiredMethods = [
'updateQuota',
'updateEmail',
@@ -909,21 +874,20 @@ class UserTest extends \Test\TestCase {
'updateExtStorageHome',
];
- /** @var User|\PHPUnit\Framework\MockObject\MockObject $userMock */
+ /** @var User&MockObject $userMock */
$userMock = $this->getMockBuilder(User::class)
->setConstructorArgs([
$this->uid,
$this->dn,
$this->access,
$this->config,
- $this->filesystemhelper,
$this->image,
$this->logger,
$this->avatarManager,
$this->userManager,
$this->notificationManager
])
- ->setMethods($requiredMethods)
+ ->onlyMethods($requiredMethods)
->getMock();
$this->connection->setConfiguration([
@@ -963,17 +927,15 @@ class UserTest extends \Test\TestCase {
\OC_Hook::emit('OC_User', 'post_login', ['uid' => $this->uid]);
}
- public function emptyHomeFolderAttributeValueProvider() {
+ public static function emptyHomeFolderAttributeValueProvider(): array {
return [
'empty' => [''],
'prefixOnly' => ['attr:'],
];
}
- /**
- * @dataProvider emptyHomeFolderAttributeValueProvider
- */
- public function testGetHomePathNotConfigured($attributeValue) {
+ #[\PHPUnit\Framework\Attributes\DataProvider('emptyHomeFolderAttributeValueProvider')]
+ public function testGetHomePathNotConfigured(string $attributeValue): void {
$this->connection->expects($this->any())
->method('__get')
->with($this->equalTo('homeFolderNamingRule'))
@@ -989,7 +951,7 @@ class UserTest extends \Test\TestCase {
$this->assertFalse($this->user->getHomePath());
}
- public function testGetHomePathConfiguredNotAvailableAllowed() {
+ public function testGetHomePathConfiguredNotAvailableAllowed(): void {
$this->connection->expects($this->any())
->method('__get')
->with($this->equalTo('homeFolderNamingRule'))
@@ -1013,7 +975,7 @@ class UserTest extends \Test\TestCase {
}
- public function testGetHomePathConfiguredNotAvailableNotAllowed() {
+ public function testGetHomePathConfiguredNotAvailableNotAllowed(): void {
$this->expectException(\Exception::class);
$this->connection->expects($this->any())
@@ -1037,20 +999,17 @@ class UserTest extends \Test\TestCase {
$this->user->getHomePath();
}
- public function displayNameProvider() {
+ public static function displayNameProvider(): array {
return [
['Roland Deschain', '', 'Roland Deschain', false],
['Roland Deschain', '', 'Roland Deschain', true],
- ['Roland Deschain', null, 'Roland Deschain', false],
['Roland Deschain', 'gunslinger@darktower.com', 'Roland Deschain (gunslinger@darktower.com)', false],
['Roland Deschain', 'gunslinger@darktower.com', 'Roland Deschain (gunslinger@darktower.com)', true],
];
}
- /**
- * @dataProvider displayNameProvider
- */
- public function testComposeAndStoreDisplayName($part1, $part2, $expected, $expectTriggerChange) {
+ #[\PHPUnit\Framework\Attributes\DataProvider('displayNameProvider')]
+ public function testComposeAndStoreDisplayName(string $part1, string $part2, string $expected, bool $expectTriggerChange): void {
$this->config->expects($this->once())
->method('setUserValue');
$oldName = $expectTriggerChange ? 'xxGunslingerxx' : null;
@@ -1076,7 +1035,7 @@ class UserTest extends \Test\TestCase {
$this->assertSame($expected, $displayName);
}
- public function testComposeAndStoreDisplayNameNoOverwrite() {
+ public function testComposeAndStoreDisplayNameNoOverwrite(): void {
$displayName = 'Randall Flagg';
$this->config->expects($this->never())
->method('setUserValue');
@@ -1091,7 +1050,7 @@ class UserTest extends \Test\TestCase {
$this->assertSame($composedDisplayName, $displayName);
}
- public function testHandlePasswordExpiryWarningDefaultPolicy() {
+ public function testHandlePasswordExpiryWarningDefaultPolicy(): void {
$this->connection->expects($this->any())
->method('__get')
->willReturnCallback(function ($name) {
@@ -1110,7 +1069,7 @@ class UserTest extends \Test\TestCase {
if ($base === $this->dn) {
return [
[
- 'pwdchangedtime' => [(new \DateTime())->sub(new \DateInterval('P28D'))->format('Ymdhis').'Z'],
+ 'pwdchangedtime' => [(new \DateTime())->sub(new \DateInterval('P28D'))->format('Ymdhis') . 'Z'],
'pwdgraceusetime' => [],
],
];
@@ -1149,12 +1108,12 @@ class UserTest extends \Test\TestCase {
->method('notify');
\OC_Hook::clear();//disconnect irrelevant hooks
- \OCP\Util::connectHook('OC_User', 'post_login', $this->user, 'handlePasswordExpiry');
+ Util::connectHook('OC_User', 'post_login', $this->user, 'handlePasswordExpiry');
/** @noinspection PhpUnhandledExceptionInspection */
\OC_Hook::emit('OC_User', 'post_login', ['uid' => $this->uid]);
}
- public function testHandlePasswordExpiryWarningCustomPolicy() {
+ public function testHandlePasswordExpiryWarningCustomPolicy(): void {
$this->connection->expects($this->any())
->method('__get')
->willReturnCallback(function ($name) {
@@ -1174,7 +1133,7 @@ class UserTest extends \Test\TestCase {
return [
[
'pwdpolicysubentry' => ['cn=custom,ou=policies,dc=foo,dc=bar'],
- 'pwdchangedtime' => [(new \DateTime())->sub(new \DateInterval('P28D'))->format('Ymdhis').'Z'],
+ 'pwdchangedtime' => [(new \DateTime())->sub(new \DateInterval('P28D'))->format('Ymdhis') . 'Z'],
'pwdgraceusetime' => [],
]
];
@@ -1213,7 +1172,7 @@ class UserTest extends \Test\TestCase {
->method('notify');
\OC_Hook::clear();//disconnect irrelevant hooks
- \OCP\Util::connectHook('OC_User', 'post_login', $this->user, 'handlePasswordExpiry');
+ Util::connectHook('OC_User', 'post_login', $this->user, 'handlePasswordExpiry');
/** @noinspection PhpUnhandledExceptionInspection */
\OC_Hook::emit('OC_User', 'post_login', ['uid' => $this->uid]);
}
diff --git a/apps/user_ldap/tests/UserLDAPPluginTest.php b/apps/user_ldap/tests/UserLDAPPluginTest.php
index 1e3cd6afbf8..8a065374e61 100644
--- a/apps/user_ldap/tests/UserLDAPPluginTest.php
+++ b/apps/user_ldap/tests/UserLDAPPluginTest.php
@@ -1,4 +1,6 @@
<?php
+
+declare(strict_types=1);
/**
* SPDX-FileCopyrightText: 2017 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
@@ -9,27 +11,23 @@ use OC\User\Backend;
use OCA\User_LDAP\UserPluginManager;
class UserLDAPPluginTest extends \Test\TestCase {
-
- /**
- * @return UserPluginManager
- */
- private function getUserPluginManager() {
+ private function getUserPluginManager(): UserPluginManager {
return new UserPluginManager();
}
- public function testImplementsActions() {
+ public function testImplementsActions(): void {
$pluginManager = $this->getUserPluginManager();
- $plugin = $this->getMockBuilder('OCA\User_LDAP\Tests\LDAPUserPluginDummy')
- ->setMethods(['respondToActions'])
+ $plugin = $this->getMockBuilder(LDAPUserPluginDummy::class)
+ ->onlyMethods(['respondToActions'])
->getMock();
$plugin->expects($this->any())
->method('respondToActions')
->willReturn(Backend::CREATE_USER);
- $plugin2 = $this->getMockBuilder('OCA\User_LDAP\Tests\LDAPUserPluginDummy')
- ->setMethods(['respondToActions'])
+ $plugin2 = $this->getMockBuilder(LDAPUserPluginDummy::class)
+ ->onlyMethods(['respondToActions'])
->getMock();
$plugin2->expects($this->any())
@@ -44,11 +42,11 @@ class UserLDAPPluginTest extends \Test\TestCase {
$this->assertTrue($pluginManager->implementsActions(Backend::PROVIDE_AVATAR));
}
- public function testCreateUser() {
+ public function testCreateUser(): void {
$pluginManager = $this->getUserPluginManager();
- $plugin = $this->getMockBuilder('OCA\User_LDAP\Tests\LDAPUserPluginDummy')
- ->setMethods(['respondToActions', 'createUser'])
+ $plugin = $this->getMockBuilder(LDAPUserPluginDummy::class)
+ ->onlyMethods(['respondToActions', 'createUser'])
->getMock();
$plugin->expects($this->any())
@@ -66,8 +64,8 @@ class UserLDAPPluginTest extends \Test\TestCase {
$pluginManager->createUser('user', 'password');
}
-
- public function testCreateUserNotRegistered() {
+
+ public function testCreateUserNotRegistered(): void {
$this->expectException(\Exception::class);
$this->expectExceptionMessage('No plugin implements createUser in this LDAP Backend.');
@@ -75,11 +73,11 @@ class UserLDAPPluginTest extends \Test\TestCase {
$pluginManager->createUser('foo', 'bar');
}
- public function testSetPassword() {
+ public function testSetPassword(): void {
$pluginManager = $this->getUserPluginManager();
- $plugin = $this->getMockBuilder('OCA\User_LDAP\Tests\LDAPUserPluginDummy')
- ->setMethods(['respondToActions', 'setPassword'])
+ $plugin = $this->getMockBuilder(LDAPUserPluginDummy::class)
+ ->onlyMethods(['respondToActions', 'setPassword'])
->getMock();
$plugin->expects($this->any())
@@ -97,8 +95,8 @@ class UserLDAPPluginTest extends \Test\TestCase {
$pluginManager->setPassword('user', 'password');
}
-
- public function testSetPasswordNotRegistered() {
+
+ public function testSetPasswordNotRegistered(): void {
$this->expectException(\Exception::class);
$this->expectExceptionMessage('No plugin implements setPassword in this LDAP Backend.');
@@ -106,11 +104,11 @@ class UserLDAPPluginTest extends \Test\TestCase {
$pluginManager->setPassword('foo', 'bar');
}
- public function testGetHome() {
+ public function testGetHome(): void {
$pluginManager = $this->getUserPluginManager();
- $plugin = $this->getMockBuilder('OCA\User_LDAP\Tests\LDAPUserPluginDummy')
- ->setMethods(['respondToActions', 'getHome'])
+ $plugin = $this->getMockBuilder(LDAPUserPluginDummy::class)
+ ->onlyMethods(['respondToActions', 'getHome'])
->getMock();
$plugin->expects($this->any())
@@ -127,8 +125,8 @@ class UserLDAPPluginTest extends \Test\TestCase {
$pluginManager->getHome('uid');
}
-
- public function testGetHomeNotRegistered() {
+
+ public function testGetHomeNotRegistered(): void {
$this->expectException(\Exception::class);
$this->expectExceptionMessage('No plugin implements getHome in this LDAP Backend.');
@@ -136,11 +134,11 @@ class UserLDAPPluginTest extends \Test\TestCase {
$pluginManager->getHome('foo');
}
- public function testGetDisplayName() {
+ public function testGetDisplayName(): void {
$pluginManager = $this->getUserPluginManager();
- $plugin = $this->getMockBuilder('OCA\User_LDAP\Tests\LDAPUserPluginDummy')
- ->setMethods(['respondToActions', 'getDisplayName'])
+ $plugin = $this->getMockBuilder(LDAPUserPluginDummy::class)
+ ->onlyMethods(['respondToActions', 'getDisplayName'])
->getMock();
$plugin->expects($this->any())
@@ -157,8 +155,8 @@ class UserLDAPPluginTest extends \Test\TestCase {
$pluginManager->getDisplayName('uid');
}
-
- public function testGetDisplayNameNotRegistered() {
+
+ public function testGetDisplayNameNotRegistered(): void {
$this->expectException(\Exception::class);
$this->expectExceptionMessage('No plugin implements getDisplayName in this LDAP Backend.');
@@ -166,11 +164,11 @@ class UserLDAPPluginTest extends \Test\TestCase {
$pluginManager->getDisplayName('foo');
}
- public function testSetDisplayName() {
+ public function testSetDisplayName(): void {
$pluginManager = $this->getUserPluginManager();
- $plugin = $this->getMockBuilder('OCA\User_LDAP\Tests\LDAPUserPluginDummy')
- ->setMethods(['respondToActions', 'setDisplayName'])
+ $plugin = $this->getMockBuilder(LDAPUserPluginDummy::class)
+ ->onlyMethods(['respondToActions', 'setDisplayName'])
->getMock();
$plugin->expects($this->any())
@@ -188,8 +186,8 @@ class UserLDAPPluginTest extends \Test\TestCase {
$pluginManager->setDisplayName('user', 'password');
}
-
- public function testSetDisplayNameNotRegistered() {
+
+ public function testSetDisplayNameNotRegistered(): void {
$this->expectException(\Exception::class);
$this->expectExceptionMessage('No plugin implements setDisplayName in this LDAP Backend.');
@@ -197,11 +195,11 @@ class UserLDAPPluginTest extends \Test\TestCase {
$pluginManager->setDisplayName('foo', 'bar');
}
- public function testCanChangeAvatar() {
+ public function testCanChangeAvatar(): void {
$pluginManager = $this->getUserPluginManager();
- $plugin = $this->getMockBuilder('OCA\User_LDAP\Tests\LDAPUserPluginDummy')
- ->setMethods(['respondToActions', 'canChangeAvatar'])
+ $plugin = $this->getMockBuilder(LDAPUserPluginDummy::class)
+ ->onlyMethods(['respondToActions', 'canChangeAvatar'])
->getMock();
$plugin->expects($this->any())
@@ -218,8 +216,8 @@ class UserLDAPPluginTest extends \Test\TestCase {
$pluginManager->canChangeAvatar('uid');
}
-
- public function testCanChangeAvatarNotRegistered() {
+
+ public function testCanChangeAvatarNotRegistered(): void {
$this->expectException(\Exception::class);
$this->expectExceptionMessage('No plugin implements canChangeAvatar in this LDAP Backend.');
@@ -227,11 +225,11 @@ class UserLDAPPluginTest extends \Test\TestCase {
$pluginManager->canChangeAvatar('foo');
}
- public function testCountUsers() {
+ public function testCountUsers(): void {
$pluginManager = $this->getUserPluginManager();
- $plugin = $this->getMockBuilder('OCA\User_LDAP\Tests\LDAPUserPluginDummy')
- ->setMethods(['respondToActions', 'countUsers'])
+ $plugin = $this->getMockBuilder(LDAPUserPluginDummy::class)
+ ->onlyMethods(['respondToActions', 'countUsers'])
->getMock();
$plugin->expects($this->any())
@@ -245,8 +243,8 @@ class UserLDAPPluginTest extends \Test\TestCase {
$pluginManager->countUsers();
}
-
- public function testCountUsersNotRegistered() {
+
+ public function testCountUsersNotRegistered(): void {
$this->expectException(\Exception::class);
$this->expectExceptionMessage('No plugin implements countUsers in this LDAP Backend.');
@@ -254,11 +252,11 @@ class UserLDAPPluginTest extends \Test\TestCase {
$pluginManager->countUsers();
}
- public function testDeleteUser() {
+ public function testDeleteUser(): void {
$pluginManager = $this->getUserPluginManager();
- $plugin = $this->getMockBuilder('OCA\User_LDAP\Tests\LDAPUserPluginDummy')
- ->setMethods(['respondToActions', 'canDeleteUser','deleteUser'])
+ $plugin = $this->getMockBuilder(LDAPUserPluginDummy::class)
+ ->onlyMethods(['respondToActions', 'canDeleteUser','deleteUser'])
->getMock();
$plugin->expects($this->any())
@@ -281,8 +279,8 @@ class UserLDAPPluginTest extends \Test\TestCase {
$pluginManager->deleteUser('uid');
}
-
- public function testDeleteUserNotRegistered() {
+
+ public function testDeleteUserNotRegistered(): void {
$this->expectException(\Exception::class);
$this->expectExceptionMessage('No plugin implements deleteUser in this LDAP Backend.');
diff --git a/apps/user_ldap/tests/User_LDAPTest.php b/apps/user_ldap/tests/User_LDAPTest.php
index c09a16c75bb..f8900c3cca4 100644
--- a/apps/user_ldap/tests/User_LDAPTest.php
+++ b/apps/user_ldap/tests/User_LDAPTest.php
@@ -1,5 +1,6 @@
<?php
+declare(strict_types=1);
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -8,9 +9,9 @@
namespace OCA\User_LDAP\Tests;
use OC\User\Backend;
-use OC\User\Session;
use OCA\User_LDAP\Access;
use OCA\User_LDAP\Connection;
+use OCA\User_LDAP\ILDAPWrapper;
use OCA\User_LDAP\Mapping\AbstractMapping;
use OCA\User_LDAP\Mapping\UserMapping;
use OCA\User_LDAP\User\DeletedUsersIndex;
@@ -22,8 +23,11 @@ use OCA\User_LDAP\User_LDAP as UserLDAP;
use OCA\User_LDAP\UserPluginManager;
use OCP\HintException;
use OCP\IConfig;
+use OCP\IGroupManager;
use OCP\IUser;
+use OCP\IUserManager;
use OCP\Notification\IManager as INotificationManager;
+use OCP\Server;
use PHPUnit\Framework\MockObject\MockObject;
use Psr\Log\LoggerInterface;
use Test\TestCase;
@@ -36,46 +40,32 @@ use Test\TestCase;
* @package OCA\User_LDAP\Tests
*/
class User_LDAPTest extends TestCase {
- /** @var User_LDAP */
- protected $backend;
- /** @var Access|MockObject */
- protected $access;
- /** @var OfflineUser|MockObject */
- protected $offlineUser;
- /** @var IConfig|MockObject */
- protected $config;
- /** @var INotificationManager|MockObject */
- protected $notificationManager;
- /** @var Session|MockObject */
- protected $session;
- /** @var UserPluginManager|MockObject */
- protected $pluginManager;
- /** @var Connection|MockObject */
- protected $connection;
- /** @var Manager|MockObject */
- protected $userManager;
- /** @var LoggerInterface|MockObject */
- protected $logger;
- /** @var DeletedUsersIndex|MockObject */
- protected $deletedUsersIndex;
+ protected Access&MockObject $access;
+ protected OfflineUser&MockObject $offlineUser;
+ protected INotificationManager&MockObject $notificationManager;
+ protected UserPluginManager&MockObject $pluginManager;
+ protected Connection&MockObject $connection;
+ protected Manager&MockObject $userManager;
+ protected LoggerInterface&MockObject $logger;
+ protected DeletedUsersIndex&MockObject $deletedUsersIndex;
+ protected User_LDAP $backend;
protected function setUp(): void {
parent::setUp();
- \OC_User::clearBackends();
- \OC::$server->getGroupManager()->clearBackends();
+ Server::get(IUserManager::class)->clearBackends();
+ Server::get(IGroupManager::class)->clearBackends();
- $this->connection = $this->createMock(Connection::class);
+ $this->connection = $this->getMockBuilder(Connection::class)
+ ->setConstructorArgs([$this->createMock(ILDAPWrapper::class)])
+ ->getMock();
$this->userManager = $this->createMock(Manager::class);
$this->access = $this->createMock(Access::class);
$this->access->connection = $this->connection;
$this->access->userManager = $this->userManager;
- $this->config = $this->createMock(IConfig::class);
$this->notificationManager = $this->createMock(INotificationManager::class);
- // Cannot use IUserSession because of private listen() methods
- $this->session = $this->createMock(Session::class);
$this->pluginManager = $this->createMock(UserPluginManager::class);
$this->logger = $this->createMock(LoggerInterface::class);
@@ -84,36 +74,34 @@ class User_LDAPTest extends TestCase {
$this->backend = new User_LDAP(
$this->access,
- $this->config,
$this->notificationManager,
- $this->session,
$this->pluginManager,
$this->logger,
$this->deletedUsersIndex,
);
}
- private function prepareMockForUserExists() {
+ private function prepareMockForUserExists(): void {
$this->access->expects($this->any())
- ->method('username2dn')
- ->willReturnCallback(function ($uid) {
- switch ($uid) {
- case 'gunslinger':
- return 'dnOfRoland,dc=test';
- break;
- case 'formerUser':
- return 'dnOfFormerUser,dc=test';
- break;
- case 'newyorker':
- return 'dnOfNewYorker,dc=test';
- break;
- case 'ladyofshadows':
- return 'dnOfLadyOfShadows,dc=test';
- break;
- default:
- return false;
- }
- });
+ ->method('username2dn')
+ ->willReturnCallback(function ($uid) {
+ switch ($uid) {
+ case 'gunslinger':
+ return 'dnOfRoland,dc=test';
+ break;
+ case 'formerUser':
+ return 'dnOfFormerUser,dc=test';
+ break;
+ case 'newyorker':
+ return 'dnOfNewYorker,dc=test';
+ break;
+ case 'ladyofshadows':
+ return 'dnOfLadyOfShadows,dc=test';
+ break;
+ default:
+ return false;
+ }
+ });
$this->access->method('fetchUsersByLoginName')
->willReturn([]);
@@ -121,27 +109,25 @@ class User_LDAPTest extends TestCase {
/**
* Prepares the Access mock for checkPassword tests
- * @param bool $noDisplayName
- * @return void
*/
- private function prepareAccessForCheckPassword($noDisplayName = false) {
+ private function prepareAccessForCheckPassword(bool $noDisplayName = false): void {
$this->connection->expects($this->any())
- ->method('__get')
- ->willReturnCallback(function ($name) {
- if ($name === 'ldapLoginFilter') {
- return '%uid';
- }
- return null;
- });
+ ->method('__get')
+ ->willReturnCallback(function ($name) {
+ if ($name === 'ldapLoginFilter') {
+ return '%uid';
+ }
+ return null;
+ });
$this->access->expects($this->any())
- ->method('fetchListOfUsers')
- ->willReturnCallback(function ($filter) {
- if ($filter === 'roland') {
- return [['dn' => ['dnOfRoland,dc=test']]];
- }
- return [];
- });
+ ->method('fetchListOfUsers')
+ ->willReturnCallback(function ($filter) {
+ if ($filter === 'roland') {
+ return [['dn' => ['dnOfRoland,dc=test']]];
+ }
+ return [];
+ });
$this->access->expects($this->any())
->method('fetchUsersByLoginName')
->willReturnCallback(function ($uid) {
@@ -156,28 +142,32 @@ class User_LDAPTest extends TestCase {
$retVal = false;
}
$this->access->expects($this->any())
- ->method('dn2username')
- ->with($this->equalTo('dnOfRoland,dc=test'))
- ->willReturn($retVal);
+ ->method('dn2username')
+ ->with($this->equalTo('dnOfRoland,dc=test'))
+ ->willReturn($retVal);
$this->access->expects($this->any())
- ->method('stringResemblesDN')
- ->with($this->equalTo('dnOfRoland,dc=test'))
- ->willReturn(true);
+ ->method('username2dn')
+ ->with($this->equalTo('gunslinger'))
+ ->willReturn('dnOfRoland,dc=test');
+ $this->access->expects($this->any())
+ ->method('stringResemblesDN')
+ ->with($this->equalTo('dnOfRoland,dc=test'))
+ ->willReturn(true);
$this->access->expects($this->any())
- ->method('areCredentialsValid')
- ->willReturnCallback(function ($dn, $pwd) {
- if ($pwd === 'dt19') {
- return true;
- }
- return false;
- });
+ ->method('areCredentialsValid')
+ ->willReturnCallback(function ($dn, $pwd) {
+ if ($pwd === 'dt19') {
+ return true;
+ }
+ return false;
+ });
$this->userManager->expects($this->any())
->method('getAttributes')
->willReturn(['dn', 'uid', 'mail', 'displayname']);
}
- public function testCheckPasswordUidReturn() {
+ public function testCheckPasswordUidReturn(): void {
$user = $this->createMock(User::class);
$user->expects($this->any())
->method('getUsername')
@@ -188,33 +178,33 @@ class User_LDAPTest extends TestCase {
->method('get')
->willReturn($user);
- $backend = new UserLDAP($this->access, $this->config, $this->notificationManager, $this->session, $this->pluginManager, $this->logger, $this->deletedUsersIndex);
+ $backend = new UserLDAP($this->access, $this->notificationManager, $this->pluginManager, $this->logger, $this->deletedUsersIndex);
- \OC_User::useBackend($backend);
+ Server::get(IUserManager::class)->registerBackend($backend);
$result = $backend->checkPassword('roland', 'dt19');
$this->assertEquals('gunslinger', $result);
}
- public function testCheckPasswordWrongPassword() {
+ public function testCheckPasswordWrongPassword(): void {
$this->prepareAccessForCheckPassword();
- $backend = new UserLDAP($this->access, $this->config, $this->notificationManager, $this->session, $this->pluginManager, $this->logger, $this->deletedUsersIndex);
- \OC_User::useBackend($backend);
+ $backend = new UserLDAP($this->access, $this->notificationManager, $this->pluginManager, $this->logger, $this->deletedUsersIndex);
+ Server::get(IUserManager::class)->registerBackend($backend);
$result = $backend->checkPassword('roland', 'wrong');
$this->assertFalse($result);
}
- public function testCheckPasswordWrongUser() {
+ public function testCheckPasswordWrongUser(): void {
$this->prepareAccessForCheckPassword();
- $backend = new UserLDAP($this->access, $this->config, $this->notificationManager, $this->session, $this->pluginManager, $this->logger, $this->deletedUsersIndex);
- \OC_User::useBackend($backend);
+ $backend = new UserLDAP($this->access, $this->notificationManager, $this->pluginManager, $this->logger, $this->deletedUsersIndex);
+ Server::get(IUserManager::class)->registerBackend($backend);
$result = $backend->checkPassword('mallory', 'evil');
$this->assertFalse($result);
}
- public function testCheckPasswordNoDisplayName() {
+ public function testCheckPasswordNoDisplayName(): void {
$this->prepareAccessForCheckPassword(true);
$this->prepareAccessForCheckPassword();
@@ -222,14 +212,14 @@ class User_LDAPTest extends TestCase {
->method('get')
->willReturn(null);
- $backend = new UserLDAP($this->access, $this->config, $this->notificationManager, $this->session, $this->pluginManager, $this->logger, $this->deletedUsersIndex);
- \OC_User::useBackend($backend);
+ $backend = new UserLDAP($this->access, $this->notificationManager, $this->pluginManager, $this->logger, $this->deletedUsersIndex);
+ Server::get(IUserManager::class)->registerBackend($backend);
$result = $backend->checkPassword('roland', 'dt19');
$this->assertFalse($result);
}
- public function testCheckPasswordPublicAPI() {
+ public function testCheckPasswordPublicAPI(): void {
$user = $this->createMock(User::class);
$user->expects($this->any())
->method('getUsername')
@@ -240,10 +230,10 @@ class User_LDAPTest extends TestCase {
->method('get')
->willReturn($user);
- $backend = new UserLDAP($this->access, $this->config, $this->notificationManager, $this->session, $this->pluginManager, $this->logger, $this->deletedUsersIndex);
- \OC_User::useBackend($backend);
+ $backend = new UserLDAP($this->access, $this->notificationManager, $this->pluginManager, $this->logger, $this->deletedUsersIndex);
+ Server::get(IUserManager::class)->registerBackend($backend);
- $user = \OC::$server->getUserManager()->checkPassword('roland', 'dt19');
+ $user = Server::get(IUserManager::class)->checkPassword('roland', 'dt19');
$result = false;
if ($user !== false) {
$result = $user->getUID();
@@ -251,12 +241,12 @@ class User_LDAPTest extends TestCase {
$this->assertEquals('gunslinger', $result);
}
- public function testCheckPasswordPublicAPIWrongPassword() {
+ public function testCheckPasswordPublicAPIWrongPassword(): void {
$this->prepareAccessForCheckPassword();
- $backend = new UserLDAP($this->access, $this->config, $this->notificationManager, $this->session, $this->pluginManager, $this->logger, $this->deletedUsersIndex);
- \OC_User::useBackend($backend);
+ $backend = new UserLDAP($this->access, $this->notificationManager, $this->pluginManager, $this->logger, $this->deletedUsersIndex);
+ Server::get(IUserManager::class)->registerBackend($backend);
- $user = \OC::$server->getUserManager()->checkPassword('roland', 'wrong');
+ $user = Server::get(IUserManager::class)->checkPassword('roland', 'wrong');
$result = false;
if ($user !== false) {
$result = $user->getUID();
@@ -264,12 +254,12 @@ class User_LDAPTest extends TestCase {
$this->assertFalse($result);
}
- public function testCheckPasswordPublicAPIWrongUser() {
+ public function testCheckPasswordPublicAPIWrongUser(): void {
$this->prepareAccessForCheckPassword();
- $backend = new UserLDAP($this->access, $this->config, $this->notificationManager, $this->session, $this->pluginManager, $this->logger, $this->deletedUsersIndex);
- \OC_User::useBackend($backend);
+ $backend = new UserLDAP($this->access, $this->notificationManager, $this->pluginManager, $this->logger, $this->deletedUsersIndex);
+ Server::get(IUserManager::class)->registerBackend($backend);
- $user = \OC::$server->getUserManager()->checkPassword('mallory', 'evil');
+ $user = Server::get(IUserManager::class)->checkPassword('mallory', 'evil');
$result = false;
if ($user !== false) {
$result = $user->getUID();
@@ -277,13 +267,13 @@ class User_LDAPTest extends TestCase {
$this->assertFalse($result);
}
- public function testDeleteUserCancel() {
- $backend = new UserLDAP($this->access, $this->config, $this->notificationManager, $this->session, $this->pluginManager, $this->logger, $this->deletedUsersIndex);
+ public function testDeleteUserCancel(): void {
+ $backend = new UserLDAP($this->access, $this->notificationManager, $this->pluginManager, $this->logger, $this->deletedUsersIndex);
$result = $backend->deleteUser('notme');
$this->assertFalse($result);
}
- public function testDeleteUserSuccess() {
+ public function testDeleteUserSuccess(): void {
$uid = 'jeremy';
$home = '/var/vhome/jdings/';
@@ -299,9 +289,9 @@ class User_LDAPTest extends TestCase {
->willReturn(ldap_connect('ldap://example.com'));
$this->deletedUsersIndex->expects($this->once())
- ->method('isUserMarked')
- ->with($uid)
- ->willReturn(true);
+ ->method('isUserMarked')
+ ->with($uid)
+ ->willReturn(true);
$offlineUser = $this->createMock(OfflineUser::class);
$offlineUser->expects($this->once())
@@ -310,8 +300,12 @@ class User_LDAPTest extends TestCase {
$this->userManager->expects($this->atLeastOnce())
->method('get')
->willReturn($offlineUser);
+ $this->userManager->expects($this->once())
+ ->method('exists')
+ ->with($uid)
+ ->willReturn(true);
- $backend = new UserLDAP($this->access, $this->config, $this->notificationManager, $this->session, $this->pluginManager, $this->logger, $this->deletedUsersIndex);
+ $backend = new UserLDAP($this->access, $this->notificationManager, $this->pluginManager, $this->logger, $this->deletedUsersIndex);
$result = $backend->deleteUser($uid);
$this->assertTrue($result);
@@ -319,7 +313,7 @@ class User_LDAPTest extends TestCase {
$this->assertSame($backend->getHome($uid), $home);
}
- public function testDeleteUserWithPlugin() {
+ public function testDeleteUserWithPlugin(): void {
$this->pluginManager->expects($this->once())
->method('canDeleteUser')
->willReturn(true);
@@ -329,9 +323,9 @@ class User_LDAPTest extends TestCase {
->willReturn(true);
$this->deletedUsersIndex->expects($this->once())
- ->method('isUserMarked')
- ->with('uid')
- ->willReturn(true);
+ ->method('isUserMarked')
+ ->with('uid')
+ ->willReturn(true);
$mapper = $this->createMock(UserMapping::class);
$mapper->expects($this->once())
@@ -346,7 +340,7 @@ class User_LDAPTest extends TestCase {
->method('invalidate')
->with('uid');
- $this->assertEquals(true, $this->backend->deleteUser('uid'));
+ $this->assertTrue($this->backend->deleteUser('uid'));
}
/**
@@ -354,42 +348,42 @@ class User_LDAPTest extends TestCase {
*/
private function prepareAccessForGetUsers() {
$this->access->expects($this->once())
- ->method('escapeFilterPart')
- ->willReturnCallback(function ($search) {
- return $search;
- });
+ ->method('escapeFilterPart')
+ ->willReturnCallback(function ($search) {
+ return $search;
+ });
$this->access->expects($this->any())
- ->method('getFilterPartForUserSearch')
- ->willReturnCallback(function ($search) {
- return $search;
- });
+ ->method('getFilterPartForUserSearch')
+ ->willReturnCallback(function ($search) {
+ return $search;
+ });
$this->access->expects($this->any())
- ->method('combineFilterWithAnd')
- ->willReturnCallback(function ($param) {
- return $param[2];
- });
+ ->method('combineFilterWithAnd')
+ ->willReturnCallback(function ($param) {
+ return $param[2];
+ });
$this->access->expects($this->any())
- ->method('fetchListOfUsers')
- ->willReturnCallback(function ($search, $a, $l, $o) {
- $users = ['gunslinger', 'newyorker', 'ladyofshadows'];
- if (empty($search)) {
- $result = $users;
- } else {
- $result = [];
- foreach ($users as $user) {
- if (stripos($user, $search) !== false) {
- $result[] = $user;
- }
- }
- }
- if (!is_null($l) || !is_null($o)) {
- $result = array_slice($result, $o, $l);
- }
- return $result;
- });
+ ->method('fetchListOfUsers')
+ ->willReturnCallback(function ($search, $a, $l, $o) {
+ $users = ['gunslinger', 'newyorker', 'ladyofshadows'];
+ if (empty($search)) {
+ $result = $users;
+ } else {
+ $result = [];
+ foreach ($users as $user) {
+ if (stripos($user, $search) !== false) {
+ $result[] = $user;
+ }
+ }
+ }
+ if (!is_null($l) || !is_null($o)) {
+ $result = array_slice($result, $o, $l);
+ }
+ return $result;
+ });
$this->access->expects($this->any())
- ->method('nextcloudUserNames')
- ->willReturnArgument(0);
+ ->method('nextcloudUserNames')
+ ->willReturnArgument(0);
$this->access->method('fetchUsersByLoginName')
->willReturn([]);
@@ -398,108 +392,109 @@ class User_LDAPTest extends TestCase {
->willReturn(['dn', 'uid', 'mail', 'displayname']);
}
- public function testGetUsersNoParam() {
+ public function testGetUsersNoParam(): void {
$this->prepareAccessForGetUsers();
- $backend = new UserLDAP($this->access, $this->config, $this->notificationManager, $this->session, $this->pluginManager, $this->logger, $this->deletedUsersIndex);
+ $backend = new UserLDAP($this->access, $this->notificationManager, $this->pluginManager, $this->logger, $this->deletedUsersIndex);
$result = $backend->getUsers();
- $this->assertEquals(3, count($result));
+ $this->assertCount(3, $result);
}
- public function testGetUsersLimitOffset() {
+ public function testGetUsersLimitOffset(): void {
$this->prepareAccessForGetUsers();
- $backend = new UserLDAP($this->access, $this->config, $this->notificationManager, $this->session, $this->pluginManager, $this->logger, $this->deletedUsersIndex);
+ $backend = new UserLDAP($this->access, $this->notificationManager, $this->pluginManager, $this->logger, $this->deletedUsersIndex);
$result = $backend->getUsers('', 1, 2);
- $this->assertEquals(1, count($result));
+ $this->assertCount(1, $result);
}
- public function testGetUsersLimitOffset2() {
+ public function testGetUsersLimitOffset2(): void {
$this->prepareAccessForGetUsers();
- $backend = new UserLDAP($this->access, $this->config, $this->notificationManager, $this->session, $this->pluginManager, $this->logger, $this->deletedUsersIndex);
+ $backend = new UserLDAP($this->access, $this->notificationManager, $this->pluginManager, $this->logger, $this->deletedUsersIndex);
$result = $backend->getUsers('', 2, 1);
- $this->assertEquals(2, count($result));
+ $this->assertCount(2, $result);
}
- public function testGetUsersSearchWithResult() {
+ public function testGetUsersSearchWithResult(): void {
$this->prepareAccessForGetUsers();
- $backend = new UserLDAP($this->access, $this->config, $this->notificationManager, $this->session, $this->pluginManager, $this->logger, $this->deletedUsersIndex);
+ $backend = new UserLDAP($this->access, $this->notificationManager, $this->pluginManager, $this->logger, $this->deletedUsersIndex);
$result = $backend->getUsers('yo');
- $this->assertEquals(2, count($result));
+ $this->assertCount(2, $result);
}
- public function testGetUsersSearchEmptyResult() {
+ public function testGetUsersSearchEmptyResult(): void {
$this->prepareAccessForGetUsers();
- $backend = new UserLDAP($this->access, $this->config, $this->notificationManager, $this->session, $this->pluginManager, $this->logger, $this->deletedUsersIndex);
+ $backend = new UserLDAP($this->access, $this->notificationManager, $this->pluginManager, $this->logger, $this->deletedUsersIndex);
$result = $backend->getUsers('nix');
- $this->assertEquals(0, count($result));
+ $this->assertCount(0, $result);
}
private function getUsers($search = '', $limit = null, $offset = null) {
- $users = \OC::$server->getUserManager()->search($search, $limit, $offset);
+ $users = Server::get(IUserManager::class)->search($search, $limit, $offset);
$uids = array_map(function (IUser $user) {
return $user->getUID();
}, $users);
return $uids;
}
- public function testGetUsersViaAPINoParam() {
+ public function testGetUsersViaAPINoParam(): void {
$this->prepareAccessForGetUsers();
- $backend = new UserLDAP($this->access, $this->config, $this->notificationManager, $this->session, $this->pluginManager, $this->logger, $this->deletedUsersIndex);
- \OC_User::useBackend($backend);
+ $backend = new UserLDAP($this->access, $this->notificationManager, $this->pluginManager, $this->logger, $this->deletedUsersIndex);
+ Server::get(IUserManager::class)->registerBackend($backend);
$result = $this->getUsers();
- $this->assertEquals(3, count($result));
+ $this->assertCount(3, $result);
}
- public function testGetUsersViaAPILimitOffset() {
+ public function testGetUsersViaAPILimitOffset(): void {
$this->prepareAccessForGetUsers();
- $backend = new UserLDAP($this->access, $this->config, $this->notificationManager, $this->session, $this->pluginManager, $this->logger, $this->deletedUsersIndex);
- \OC_User::useBackend($backend);
+ $backend = new UserLDAP($this->access, $this->notificationManager, $this->pluginManager, $this->logger, $this->deletedUsersIndex);
+ Server::get(IUserManager::class)->registerBackend($backend);
$result = $this->getUsers('', 1, 2);
- $this->assertEquals(1, count($result));
+ $this->assertCount(1, $result);
}
- public function testGetUsersViaAPILimitOffset2() {
+ public function testGetUsersViaAPILimitOffset2(): void {
$this->prepareAccessForGetUsers();
- $backend = new UserLDAP($this->access, $this->config, $this->notificationManager, $this->session, $this->pluginManager, $this->logger, $this->deletedUsersIndex);
- \OC_User::useBackend($backend);
+ $backend = new UserLDAP($this->access, $this->notificationManager, $this->pluginManager, $this->logger, $this->deletedUsersIndex);
+ Server::get(IUserManager::class)->registerBackend($backend);
$result = $this->getUsers('', 2, 1);
- $this->assertEquals(2, count($result));
+ $this->assertCount(2, $result);
}
- public function testGetUsersViaAPISearchWithResult() {
+ public function testGetUsersViaAPISearchWithResult(): void {
$this->prepareAccessForGetUsers();
- $backend = new UserLDAP($this->access, $this->config, $this->notificationManager, $this->session, $this->pluginManager, $this->logger, $this->deletedUsersIndex);
- \OC_User::useBackend($backend);
+ $backend = new UserLDAP($this->access, $this->notificationManager, $this->pluginManager, $this->logger, $this->deletedUsersIndex);
+ Server::get(IUserManager::class)->registerBackend($backend);
$result = $this->getUsers('yo');
- $this->assertEquals(2, count($result));
+ $this->assertCount(2, $result);
}
- public function testGetUsersViaAPISearchEmptyResult() {
+ public function testGetUsersViaAPISearchEmptyResult(): void {
$this->prepareAccessForGetUsers();
- $backend = new UserLDAP($this->access, $this->config, $this->notificationManager, $this->session, $this->pluginManager, $this->logger, $this->deletedUsersIndex);
- \OC_User::useBackend($backend);
+ $backend = new UserLDAP($this->access, $this->notificationManager, $this->pluginManager, $this->logger, $this->deletedUsersIndex);
+ Server::get(IUserManager::class)->registerBackend($backend);
$result = $this->getUsers('nix');
- $this->assertEquals(0, count($result));
+ $this->assertCount(0, $result);
}
- public function testUserExists() {
- $backend = new UserLDAP($this->access, $this->config, $this->notificationManager, $this->session, $this->pluginManager, $this->logger, $this->deletedUsersIndex);
+ public function testUserExists(): void {
+ $backend = new UserLDAP($this->access, $this->notificationManager, $this->pluginManager, $this->logger, $this->deletedUsersIndex);
$this->prepareMockForUserExists();
- $user = $this->createMock(User::class);
-
- $this->userManager->expects($this->atLeastOnce())
- ->method('get')
- ->willReturn($user);
+ $this->userManager->expects($this->never())
+ ->method('get');
+ $this->userManager->expects($this->once())
+ ->method('exists')
+ ->with('gunslinger')
+ ->willReturn(true);
$this->access->expects($this->any())
->method('getUserMapper')
->willReturn($this->createMock(UserMapping::class));
@@ -510,8 +505,8 @@ class User_LDAPTest extends TestCase {
$this->assertTrue($result);
}
- public function testUserExistsForDeleted() {
- $backend = new UserLDAP($this->access, $this->config, $this->notificationManager, $this->session, $this->pluginManager, $this->logger, $this->deletedUsersIndex);
+ public function testUserExistsForDeleted(): void {
+ $backend = new UserLDAP($this->access, $this->notificationManager, $this->pluginManager, $this->logger, $this->deletedUsersIndex);
$this->prepareMockForUserExists();
$mapper = $this->createMock(UserMapping::class);
@@ -524,18 +519,19 @@ class User_LDAPTest extends TestCase {
->method('getUserMapper')
->willReturn($mapper);
- $user = $this->createMock(User::class);
-
- $this->userManager->expects($this->atLeastOnce())
- ->method('get')
- ->willReturn($user);
+ $this->userManager->expects($this->never())
+ ->method('get');
+ $this->userManager->expects($this->once())
+ ->method('exists')
+ ->with('formerUser')
+ ->willReturn(true);
//test for deleted user – always returns true as long as we have the user in DB
$this->assertTrue($backend->userExists('formerUser'));
}
- public function testUserExistsForNeverExisting() {
- $backend = new UserLDAP($this->access, $this->config, $this->notificationManager, $this->session, $this->pluginManager, $this->logger, $this->deletedUsersIndex);
+ public function testUserExistsForNeverExisting(): void {
+ $backend = new UserLDAP($this->access, $this->notificationManager, $this->pluginManager, $this->logger, $this->deletedUsersIndex);
$this->prepareMockForUserExists();
$this->access->expects($this->any())
@@ -553,10 +549,10 @@ class User_LDAPTest extends TestCase {
$this->assertFalse($result);
}
- public function testUserExistsPublicAPI() {
- $backend = new UserLDAP($this->access, $this->config, $this->notificationManager, $this->session, $this->pluginManager, $this->logger, $this->deletedUsersIndex);
+ public function testUserExistsPublicAPI(): void {
+ $backend = new UserLDAP($this->access, $this->notificationManager, $this->pluginManager, $this->logger, $this->deletedUsersIndex);
$this->prepareMockForUserExists();
- \OC_User::useBackend($backend);
+ Server::get(IUserManager::class)->registerBackend($backend);
$user = $this->createMock(User::class);
$user->expects($this->any())
@@ -571,28 +567,31 @@ class User_LDAPTest extends TestCase {
}
return false;
});
- $this->userManager->expects($this->atLeastOnce())
- ->method('get')
- ->willReturn($user);
+ $this->userManager->expects($this->never())
+ ->method('get');
+ $this->userManager->expects($this->once())
+ ->method('exists')
+ ->with('gunslinger')
+ ->willReturn(true);
$this->access->expects($this->any())
->method('getUserMapper')
->willReturn($this->createMock(UserMapping::class));
//test for existing user
- $result = \OC::$server->getUserManager()->userExists('gunslinger');
+ $result = Server::get(IUserManager::class)->userExists('gunslinger');
$this->assertTrue($result);
}
- public function testDeleteUserExisting() {
- $backend = new UserLDAP($this->access, $this->config, $this->notificationManager, $this->session, $this->pluginManager, $this->logger, $this->deletedUsersIndex);
+ public function testDeleteUserExisting(): void {
+ $backend = new UserLDAP($this->access, $this->notificationManager, $this->pluginManager, $this->logger, $this->deletedUsersIndex);
//we do not support deleting existing users at all
$result = $backend->deleteUser('gunslinger');
$this->assertFalse($result);
}
- public function testGetHomeAbsolutePath() {
- $backend = new UserLDAP($this->access, $this->config, $this->notificationManager, $this->session, $this->pluginManager, $this->logger, $this->deletedUsersIndex);
+ public function testGetHomeAbsolutePath(): void {
+ $backend = new UserLDAP($this->access, $this->notificationManager, $this->pluginManager, $this->logger, $this->deletedUsersIndex);
$this->prepareMockForUserExists();
$this->connection->expects($this->any())
@@ -632,7 +631,12 @@ class User_LDAPTest extends TestCase {
$this->userManager->expects($this->atLeastOnce())
->method('get')
+ ->with('gunslinger')
->willReturn($user);
+ $this->userManager->expects($this->once())
+ ->method('exists')
+ ->with('gunslinger')
+ ->willReturn(true);
//absolute path
/** @noinspection PhpUnhandledExceptionInspection */
@@ -640,12 +644,12 @@ class User_LDAPTest extends TestCase {
$this->assertEquals('/tmp/rolandshome/', $result);
}
- public function testGetHomeRelative() {
- $backend = new UserLDAP($this->access, $this->config, $this->notificationManager, $this->session, $this->pluginManager, $this->logger, $this->deletedUsersIndex);
+ public function testGetHomeRelative(): void {
+ $backend = new UserLDAP($this->access, $this->notificationManager, $this->pluginManager, $this->logger, $this->deletedUsersIndex);
$this->prepareMockForUserExists();
- $dataDir = \OC::$server->getConfig()->getSystemValue(
- 'datadirectory', \OC::$SERVERROOT.'/data');
+ $dataDir = Server::get(IConfig::class)->getSystemValue(
+ 'datadirectory', \OC::$SERVERROOT . '/data');
$this->connection->expects($this->any())
->method('__get')
@@ -680,22 +684,26 @@ class User_LDAPTest extends TestCase {
->willReturn('dnOfLadyOfShadows,dc=test');
$user->expects($this->any())
->method('getHomePath')
- ->willReturn($dataDir.'/susannah/');
+ ->willReturn($dataDir . '/susannah/');
$this->userManager->expects($this->atLeastOnce())
->method('get')
->willReturn($user);
+ $this->userManager->expects($this->once())
+ ->method('exists')
+ ->with('ladyofshadows')
+ ->willReturn(true);
/** @noinspection PhpUnhandledExceptionInspection */
$result = $backend->getHome('ladyofshadows');
- $this->assertEquals($dataDir.'/susannah/', $result);
+ $this->assertEquals($dataDir . '/susannah/', $result);
}
- public function testGetHomeNoPath() {
+ public function testGetHomeNoPath(): void {
$this->expectException(\Exception::class);
- $backend = new UserLDAP($this->access, $this->config, $this->notificationManager, $this->session, $this->pluginManager, $this->logger, $this->deletedUsersIndex);
+ $backend = new UserLDAP($this->access, $this->notificationManager, $this->pluginManager, $this->logger, $this->deletedUsersIndex);
$this->prepareMockForUserExists();
$this->connection->expects($this->any())
@@ -714,14 +722,6 @@ class User_LDAPTest extends TestCase {
return false;
}
});
- $this->access->connection->expects($this->any())
- ->method('getFromCache')
- ->willReturnCallback(function ($key) {
- if ($key === 'userExistsnewyorker') {
- return true;
- }
- return null;
- });
$user = $this->createMock(User::class);
$user->expects($this->any())
@@ -733,41 +733,42 @@ class User_LDAPTest extends TestCase {
$this->userManager->expects($this->atLeastOnce())
->method('get')
+ ->with('newyorker')
->willReturn($user);
+ $this->userManager->expects($this->once())
+ ->method('exists')
+ ->with('newyorker')
+ ->willReturn(true);
//no path at all – triggers OC default behaviour
$result = $backend->getHome('newyorker');
$this->assertFalse($result);
}
- public function testGetHomeDeletedUser() {
+ public function testGetHomeDeletedUser(): void {
$uid = 'newyorker';
- $backend = new UserLDAP($this->access, $this->config, $this->notificationManager, $this->session, $this->pluginManager, $this->logger, $this->deletedUsersIndex);
+ $backend = new UserLDAP($this->access, $this->notificationManager, $this->pluginManager, $this->logger, $this->deletedUsersIndex);
$this->prepareMockForUserExists();
$this->connection->expects($this->any())
- ->method('__get')
- ->willReturnCallback(function ($name) {
- if ($name === 'homeFolderNamingRule') {
- return 'attr:testAttribute';
- }
- return null;
- });
+ ->method('__get')
+ ->willReturnCallback(function ($name) {
+ if ($name === 'homeFolderNamingRule') {
+ return 'attr:testAttribute';
+ }
+ return null;
+ });
$this->access->expects($this->any())
- ->method('readAttribute')
- ->willReturn([]);
+ ->method('readAttribute')
+ ->willReturn([]);
$userMapper = $this->createMock(UserMapping::class);
$this->access->expects($this->any())
- ->method('getUserMapper')
- ->willReturn($userMapper);
-
- $this->config->expects($this->any())
- ->method('getUserValue')
- ->willReturn(true);
+ ->method('getUserMapper')
+ ->willReturn($userMapper);
$offlineUser = $this->createMock(OfflineUser::class);
$offlineUser->expects($this->atLeastOnce())
@@ -776,13 +777,18 @@ class User_LDAPTest extends TestCase {
$this->userManager->expects($this->atLeastOnce())
->method('get')
+ ->with($uid)
->willReturn($offlineUser);
+ $this->userManager->expects($this->once())
+ ->method('exists')
+ ->with($uid)
+ ->willReturn(true);
$result = $backend->getHome($uid);
$this->assertFalse($result);
}
- public function testGetHomeWithPlugin() {
+ public function testGetHomeWithPlugin(): void {
$this->pluginManager->expects($this->once())
->method('implementsActions')
->with(Backend::GET_HOME)
@@ -815,27 +821,27 @@ class User_LDAPTest extends TestCase {
});
$this->access->expects($this->any())
- ->method('readAttribute')
- ->willReturnCallback(function ($dn, $attr) {
- switch ($dn) {
- case 'dnOfRoland,dc=test':
- if ($attr === 'displayname') {
- return ['Roland Deschain'];
- }
- return [];
- break;
-
- default:
- return false;
- }
- });
+ ->method('readAttribute')
+ ->willReturnCallback(function ($dn, $attr) {
+ switch ($dn) {
+ case 'dnOfRoland,dc=test':
+ if ($attr === 'displayname') {
+ return ['Roland Deschain'];
+ }
+ return [];
+ break;
+
+ default:
+ return false;
+ }
+ });
$this->access->method('fetchUsersByLoginName')
->willReturn([]);
}
- public function testGetDisplayName() {
+ public function testGetDisplayName(): void {
$this->prepareAccessForGetDisplayName();
- $backend = new UserLDAP($this->access, $this->config, $this->notificationManager, $this->session, $this->pluginManager, $this->logger, $this->deletedUsersIndex);
+ $backend = new UserLDAP($this->access, $this->notificationManager, $this->pluginManager, $this->logger, $this->deletedUsersIndex);
$this->prepareMockForUserExists();
$this->connection->expects($this->any())
@@ -876,6 +882,16 @@ class User_LDAPTest extends TestCase {
}
return null;
});
+ $this->userManager->expects($this->any())
+ ->method('exists')
+ ->willReturnCallback(function ($uid) use ($user1, $user2) {
+ if ($uid === 'gunslinger') {
+ return true;
+ } elseif ($uid === 'newyorker') {
+ return true;
+ }
+ return false;
+ });
$this->access->expects($this->any())
->method('getUserMapper')
->willReturn($mapper);
@@ -894,7 +910,7 @@ class User_LDAPTest extends TestCase {
$this->assertEquals(null, $result);
}
- public function testGetDisplayNamePublicAPI() {
+ public function testGetDisplayNamePublicAPI(): void {
$this->access->expects($this->any())
->method('username2dn')
->willReturnCallback(function ($uid) {
@@ -916,7 +932,7 @@ class User_LDAPTest extends TestCase {
}
});
$this->prepareAccessForGetDisplayName();
- $backend = new UserLDAP($this->access, $this->config, $this->notificationManager, $this->session, $this->pluginManager, $this->logger, $this->deletedUsersIndex);
+ $backend = new UserLDAP($this->access, $this->notificationManager, $this->pluginManager, $this->logger, $this->deletedUsersIndex);
$this->prepareMockForUserExists();
$this->connection->expects($this->any())
@@ -925,7 +941,7 @@ class User_LDAPTest extends TestCase {
return true;
});
- \OC_User::useBackend($backend);
+ Server::get(IUserManager::class)->registerBackend($backend);
$user1 = $this->createMock(User::class);
$user1->expects($this->once())
@@ -959,6 +975,16 @@ class User_LDAPTest extends TestCase {
}
return null;
});
+ $this->userManager->expects($this->any())
+ ->method('exists')
+ ->willReturnCallback(function ($uid) use ($user1, $user2) {
+ if ($uid === 'gunslinger') {
+ return true;
+ } elseif ($uid === 'newyorker') {
+ return true;
+ }
+ return false;
+ });
$this->access->expects($this->any())
->method('getUserMapper')
->willReturn($mapper);
@@ -969,15 +995,15 @@ class User_LDAPTest extends TestCase {
});
//with displayName
- $result = \OC::$server->getUserManager()->get('gunslinger')->getDisplayName();
+ $result = Server::get(IUserManager::class)->get('gunslinger')?->getDisplayName();
$this->assertEquals('Roland Deschain', $result);
//empty displayname retrieved
- $result = \OC::$server->getUserManager()->get('newyorker') === null ? 'newyorker' : \OC::$server->getUserManager()->get('newyorker')->getDisplayName();
+ $result = Server::get(IUserManager::class)->get('newyorker') === null ? 'newyorker' : Server::get(IUserManager::class)->get('newyorker')->getDisplayName();
$this->assertEquals('newyorker', $result);
}
- public function testGetDisplayNameWithPlugin() {
+ public function testGetDisplayNameWithPlugin(): void {
$this->pluginManager->expects($this->once())
->method('implementsActions')
->with(Backend::GET_DISPLAYNAME)
@@ -993,29 +1019,29 @@ class User_LDAPTest extends TestCase {
//no test for getDisplayNames, because it just invokes getUsers and
//getDisplayName
- public function testCountUsers() {
+ public function testCountUsers(): void {
$this->access->expects($this->once())
- ->method('countUsers')
- ->willReturn(5);
+ ->method('countUsers')
+ ->willReturn(5);
- $backend = new UserLDAP($this->access, $this->config, $this->notificationManager, $this->session, $this->pluginManager, $this->logger, $this->deletedUsersIndex);
+ $backend = new UserLDAP($this->access, $this->notificationManager, $this->pluginManager, $this->logger, $this->deletedUsersIndex);
$result = $backend->countUsers();
$this->assertEquals(5, $result);
}
- public function testCountUsersFailing() {
+ public function testCountUsersFailing(): void {
$this->access->expects($this->once())
- ->method('countUsers')
- ->willReturn(false);
+ ->method('countUsers')
+ ->willReturn(false);
- $backend = new UserLDAP($this->access, $this->config, $this->notificationManager, $this->session, $this->pluginManager, $this->logger, $this->deletedUsersIndex);
+ $backend = new UserLDAP($this->access, $this->notificationManager, $this->pluginManager, $this->logger, $this->deletedUsersIndex);
$result = $backend->countUsers();
$this->assertFalse($result);
}
- public function testCountUsersWithPlugin() {
+ public function testCountUsersWithPlugin(): void {
$this->pluginManager->expects($this->once())
->method('implementsActions')
->with(Backend::COUNT_USERS)
@@ -1027,7 +1053,7 @@ class User_LDAPTest extends TestCase {
$this->assertEquals($this->backend->countUsers(), 42);
}
- public function testLoginName2UserNameSuccess() {
+ public function testLoginName2UserNameSuccess(): void {
$loginName = 'Alice';
$username = 'alice';
$dn = 'uid=alice,dc=what,dc=ever';
@@ -1047,13 +1073,13 @@ class User_LDAPTest extends TestCase {
$this->connection->expects($this->exactly(2))
->method('getFromCache')
- ->with($this->equalTo('loginName2UserName-'.$loginName))
+ ->with($this->equalTo('loginName2UserName-' . $loginName))
->willReturnOnConsecutiveCalls(null, $username);
$this->connection->expects($this->once())
->method('writeToCache')
- ->with($this->equalTo('loginName2UserName-'.$loginName), $this->equalTo($username));
+ ->with($this->equalTo('loginName2UserName-' . $loginName), $this->equalTo($username));
- $backend = new UserLDAP($this->access, $this->config, $this->notificationManager, $this->session, $this->pluginManager, $this->logger, $this->deletedUsersIndex);
+ $backend = new UserLDAP($this->access, $this->notificationManager, $this->pluginManager, $this->logger, $this->deletedUsersIndex);
$user = $this->createMock(User::class);
$user->expects($this->any())
->method('getUsername')
@@ -1063,6 +1089,8 @@ class User_LDAPTest extends TestCase {
->method('get')
->with($dn)
->willReturn($user);
+ $this->userManager->expects($this->never())
+ ->method('exists');
$this->userManager->expects($this->any())
->method('getAttributes')
->willReturn(['dn', 'uid', 'mail', 'displayname']);
@@ -1074,7 +1102,7 @@ class User_LDAPTest extends TestCase {
$backend->loginName2UserName($loginName);
}
- public function testLoginName2UserNameNoUsersOnLDAP() {
+ public function testLoginName2UserNameNoUsersOnLDAP(): void {
$loginName = 'Loki';
$this->access->expects($this->once())
@@ -1088,17 +1116,17 @@ class User_LDAPTest extends TestCase {
$this->connection->expects($this->exactly(2))
->method('getFromCache')
- ->with($this->equalTo('loginName2UserName-'.$loginName))
+ ->with($this->equalTo('loginName2UserName-' . $loginName))
->willReturnOnConsecutiveCalls(null, false);
$this->connection->expects($this->once())
->method('writeToCache')
- ->with($this->equalTo('loginName2UserName-'.$loginName), false);
+ ->with($this->equalTo('loginName2UserName-' . $loginName), false);
$this->userManager->expects($this->any())
->method('getAttributes')
->willReturn(['dn', 'uid', 'mail', 'displayname']);
- $backend = new UserLDAP($this->access, $this->config, $this->notificationManager, $this->session, $this->pluginManager, $this->logger, $this->deletedUsersIndex);
+ $backend = new UserLDAP($this->access, $this->notificationManager, $this->pluginManager, $this->logger, $this->deletedUsersIndex);
$name = $backend->loginName2UserName($loginName);
$this->assertSame(false, $name);
@@ -1106,7 +1134,7 @@ class User_LDAPTest extends TestCase {
$backend->loginName2UserName($loginName);
}
- public function testLoginName2UserNameOfflineUser() {
+ public function testLoginName2UserNameOfflineUser(): void {
$loginName = 'Alice';
$dn = 'uid=alice,dc=what,dc=ever';
@@ -1121,11 +1149,11 @@ class User_LDAPTest extends TestCase {
$this->connection->expects($this->exactly(2))
->method('getFromCache')
- ->with($this->equalTo('loginName2UserName-'.$loginName))
+ ->with($this->equalTo('loginName2UserName-' . $loginName))
->willReturnOnConsecutiveCalls(null, false);
$this->connection->expects($this->once())
->method('writeToCache')
- ->with($this->equalTo('loginName2UserName-'.$loginName), $this->equalTo(false));
+ ->with($this->equalTo('loginName2UserName-' . $loginName), $this->equalTo(false));
$this->userManager->expects($this->any())
->method('get')
@@ -1135,7 +1163,7 @@ class User_LDAPTest extends TestCase {
->method('getAttributes')
->willReturn(['dn', 'uid', 'mail', 'displayname']);
- $backend = new UserLDAP($this->access, $this->config, $this->notificationManager, $this->session, $this->pluginManager, $this->logger, $this->deletedUsersIndex);
+ $backend = new UserLDAP($this->access, $this->notificationManager, $this->pluginManager, $this->logger, $this->deletedUsersIndex);
$name = $backend->loginName2UserName($loginName);
$this->assertSame(false, $name);
@@ -1145,38 +1173,36 @@ class User_LDAPTest extends TestCase {
/**
* Prepares the Access mock for setPassword tests
- *
- * @param bool $enablePasswordChange
*/
private function prepareAccessForSetPassword($enablePasswordChange = true) {
$this->connection->expects($this->any())
- ->method('__get')
- ->willReturnCallback(function ($name) use (&$enablePasswordChange) {
- if ($name === 'ldapLoginFilter') {
- return '%uid';
- }
- if ($name === 'turnOnPasswordChange') {
- return $enablePasswordChange?1:0;
- }
- return null;
- });
+ ->method('__get')
+ ->willReturnCallback(function ($name) use (&$enablePasswordChange) {
+ if ($name === 'ldapLoginFilter') {
+ return '%uid';
+ }
+ if ($name === 'turnOnPasswordChange') {
+ return $enablePasswordChange?1:0;
+ }
+ return null;
+ });
$this->connection->expects($this->any())
- ->method('getFromCache')
- ->willReturnCallback(function ($uid) {
- if ($uid === 'userExists'.'roland') {
- return true;
- }
- return null;
- });
+ ->method('getFromCache')
+ ->willReturnCallback(function ($uid) {
+ if ($uid === 'userExists' . 'roland') {
+ return true;
+ }
+ return null;
+ });
$this->access->expects($this->any())
- ->method('fetchListOfUsers')
- ->willReturnCallback(function ($filter) {
- if ($filter === 'roland') {
- return [['dn' => ['dnOfRoland,dc=test']]];
- }
- return [];
- });
+ ->method('fetchListOfUsers')
+ ->willReturnCallback(function ($filter) {
+ if ($filter === 'roland') {
+ return [['dn' => ['dnOfRoland,dc=test']]];
+ }
+ return [];
+ });
$this->access->expects($this->any())
->method('fetchUsersByLoginName')
->willReturnCallback(function ($uid) {
@@ -1186,69 +1212,69 @@ class User_LDAPTest extends TestCase {
return [];
});
$this->access->expects($this->any())
- ->method('dn2username')
- ->with($this->equalTo('dnOfRoland,dc=test'))
- ->willReturn('roland');
+ ->method('dn2username')
+ ->with($this->equalTo('dnOfRoland,dc=test'))
+ ->willReturn('roland');
$this->access->expects($this->any())
- ->method('stringResemblesDN')
- ->with($this->equalTo('dnOfRoland,dc=test'))
- ->willReturn(true);
+ ->method('stringResemblesDN')
+ ->with($this->equalTo('dnOfRoland,dc=test'))
+ ->willReturn(true);
$this->access->expects($this->any())
- ->method('setPassword')
- ->willReturnCallback(function ($uid, $password) {
- if (strlen($password) <= 5) {
- throw new HintException('Password fails quality checking policy', '', 19);
- }
- return true;
- });
+ ->method('setPassword')
+ ->willReturnCallback(function ($uid, $password) {
+ if (strlen($password) <= 5) {
+ throw new HintException('Password fails quality checking policy', '', 19);
+ }
+ return true;
+ });
}
- public function testSetPasswordInvalid() {
- $this->expectException(\OCP\HintException::class);
+ public function testSetPasswordInvalid(): void {
+ $this->expectException(HintException::class);
$this->expectExceptionMessage('Password fails quality checking policy');
$this->prepareAccessForSetPassword($this->access);
$this->userManager->expects($this->atLeastOnce())
->method('get')
->willReturn($this->createMock(User::class));
- $backend = new UserLDAP($this->access, $this->config, $this->notificationManager, $this->session, $this->pluginManager, $this->logger, $this->deletedUsersIndex);
- \OC_User::useBackend($backend);
+ $backend = new UserLDAP($this->access, $this->notificationManager, $this->pluginManager, $this->logger, $this->deletedUsersIndex);
+ Server::get(IUserManager::class)->registerBackend($backend);
$this->assertTrue(\OC_User::setPassword('roland', 'dt'));
}
- public function testSetPasswordValid() {
+ public function testSetPasswordValid(): void {
$this->prepareAccessForSetPassword($this->access);
$this->userManager->expects($this->any())
->method('get')
->willReturn($this->createMock(User::class));
- $backend = new UserLDAP($this->access, $this->config, $this->notificationManager, $this->session, $this->pluginManager, $this->logger, $this->deletedUsersIndex);
+ $backend = new UserLDAP($this->access, $this->notificationManager, $this->pluginManager, $this->logger, $this->deletedUsersIndex);
$this->userManager->expects($this->any())
->method('get')
->willReturn($this->createMock(User::class));
- \OC_User::useBackend($backend);
+ Server::get(IUserManager::class)->registerBackend($backend);
$this->assertTrue(\OC_User::setPassword('roland', 'dt12234$'));
}
- public function testSetPasswordValidDisabled() {
+ public function testSetPasswordValidDisabled(): void {
$this->userManager->expects($this->any())
->method('get')
->willReturn($this->createMock(User::class));
$this->prepareAccessForSetPassword(false);
- $backend = new UserLDAP($this->access, $this->config, $this->notificationManager, $this->session, $this->pluginManager, $this->logger, $this->deletedUsersIndex);
- \OC_User::useBackend($backend);
+ $backend = new UserLDAP($this->access, $this->notificationManager, $this->pluginManager, $this->logger, $this->deletedUsersIndex);
+ Server::get(IUserManager::class)->registerBackend($backend);
$this->assertFalse(\OC_User::setPassword('roland', 'dt12234$'));
}
- public function testSetPasswordWithInvalidUser() {
+ public function testSetPasswordWithInvalidUser(): void {
$this->expectException(\Exception::class);
$this->expectExceptionMessage('LDAP setPassword: Could not get user object for uid NotExistingUser. Maybe the LDAP entry has no set display name attribute?');
@@ -1261,7 +1287,7 @@ class User_LDAPTest extends TestCase {
$this->backend->setPassword('NotExistingUser', 'Password');
}
- public function testSetPasswordWithUsernameFalse() {
+ public function testSetPasswordWithUsernameFalse(): void {
$user = $this->createMock(User::class);
$user
->expects($this->once())
@@ -1277,7 +1303,7 @@ class User_LDAPTest extends TestCase {
$this->assertFalse($this->backend->setPassword('NotExistingUser', 'Password'));
}
- public function testSetPasswordWithPlugin() {
+ public function testSetPasswordWithPlugin(): void {
$this->pluginManager->expects($this->once())
->method('implementsActions')
->with(Backend::SET_PASSWORD)
@@ -1291,7 +1317,7 @@ class User_LDAPTest extends TestCase {
$this->assertEquals($this->backend->setPassword('uid', 'password'), 'result');
}
- public function avatarDataProvider() {
+ public static function avatarDataProvider(): array {
return [
[ 'validImageData', false ],
[ 'corruptImageData', true ],
@@ -1299,8 +1325,8 @@ class User_LDAPTest extends TestCase {
];
}
- /** @dataProvider avatarDataProvider */
- public function testCanChangeAvatar($imageData, $expected) {
+ #[\PHPUnit\Framework\Attributes\DataProvider('avatarDataProvider')]
+ public function testCanChangeAvatar(string|bool $imageData, bool $expected): void {
$isValidImage = str_starts_with((string)$imageData, 'valid');
$user = $this->createMock(User::class);
@@ -1319,7 +1345,7 @@ class User_LDAPTest extends TestCase {
$this->assertSame($expected, $this->backend->canChangeAvatar('uid'));
}
- public function testCanChangeAvatarWithPlugin() {
+ public function testCanChangeAvatarWithPlugin(): void {
$this->pluginManager->expects($this->once())
->method('implementsActions')
->with(Backend::PROVIDE_AVATAR)
@@ -1332,7 +1358,7 @@ class User_LDAPTest extends TestCase {
$this->assertEquals($this->backend->canChangeAvatar('uid'), 'result');
}
- public function testSetDisplayNameWithPlugin() {
+ public function testSetDisplayNameWithPlugin(): void {
$newDisplayName = 'J. Baker';
$this->pluginManager->expects($this->once())
->method('implementsActions')
@@ -1349,8 +1375,8 @@ class User_LDAPTest extends TestCase {
}
- public function testSetDisplayNameErrorWithPlugin() {
- $this->expectException(\OCP\HintException::class);
+ public function testSetDisplayNameErrorWithPlugin(): void {
+ $this->expectException(HintException::class);
$newDisplayName = 'J. Baker';
$this->pluginManager->expects($this->once())
@@ -1367,7 +1393,7 @@ class User_LDAPTest extends TestCase {
$this->backend->setDisplayName('uid', $newDisplayName);
}
- public function testSetDisplayNameFailing() {
+ public function testSetDisplayNameFailing(): void {
$this->pluginManager->expects($this->once())
->method('implementsActions')
->with(Backend::SET_DISPLAYNAME)
@@ -1378,7 +1404,7 @@ class User_LDAPTest extends TestCase {
$this->assertFalse($this->backend->setDisplayName('uid', 'displayName'));
}
- public function testCreateUserWithPlugin() {
+ public function testCreateUserWithPlugin(): void {
$uid = 'alien6372';
$uuid = '123-2345-36756-123-2345234-4431';
$pwd = 'passwørd';
@@ -1405,7 +1431,7 @@ class User_LDAPTest extends TestCase {
$this->assertEquals($this->backend->createUser($uid, $pwd), true);
}
- public function testCreateUserFailing() {
+ public function testCreateUserFailing(): void {
$this->pluginManager->expects($this->once())
->method('implementsActions')
->with(Backend::CREATE_USER)
@@ -1414,9 +1440,9 @@ class User_LDAPTest extends TestCase {
$this->assertFalse($this->backend->createUser('uid', 'password'));
}
- public function actionProvider() {
+ public static function actionProvider(): array {
return [
- [ 'ldapUserAvatarRule', 'default', Backend::PROVIDE_AVATAR, true] ,
+ [ 'ldapUserAvatarRule', 'default', Backend::PROVIDE_AVATAR, true],
[ 'ldapUserAvatarRule', 'data:selfiePhoto', Backend::PROVIDE_AVATAR, true],
[ 'ldapUserAvatarRule', 'none', Backend::PROVIDE_AVATAR, false],
[ 'turnOnPasswordChange', 0, Backend::SET_PASSWORD, false],
@@ -1424,10 +1450,8 @@ class User_LDAPTest extends TestCase {
];
}
- /**
- * @dataProvider actionProvider
- */
- public function testImplementsAction($configurable, $value, $actionCode, $expected) {
+ #[\PHPUnit\Framework\Attributes\DataProvider('actionProvider')]
+ public function testImplementsAction(string $configurable, string|int $value, int $actionCode, bool $expected): void {
$this->pluginManager->expects($this->once())
->method('getImplementedActions')
->willReturn(0);
diff --git a/apps/user_ldap/tests/User_ProxyTest.php b/apps/user_ldap/tests/User_ProxyTest.php
index a74d1e13930..38f94af33a7 100644
--- a/apps/user_ldap/tests/User_ProxyTest.php
+++ b/apps/user_ldap/tests/User_ProxyTest.php
@@ -1,4 +1,6 @@
<?php
+
+declare(strict_types=1);
/**
* SPDX-FileCopyrightText: 2016 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
@@ -11,34 +13,20 @@ use OCA\User_LDAP\ILDAPWrapper;
use OCA\User_LDAP\User\DeletedUsersIndex;
use OCA\User_LDAP\User_Proxy;
use OCA\User_LDAP\UserPluginManager;
-use OCP\IConfig;
-use OCP\IUserSession;
use OCP\Notification\IManager as INotificationManager;
use PHPUnit\Framework\MockObject\MockObject;
use Psr\Log\LoggerInterface;
use Test\TestCase;
class User_ProxyTest extends TestCase {
- /** @var Helper|MockObject */
- protected $helper;
- /** @var ILDAPWrapper|MockObject */
- private $ldapWrapper;
- /** @var AccessFactory|MockObject */
- private $accessFactory;
- /** @var IConfig|MockObject */
- private $config;
- /** @var INotificationManager|MockObject */
- private $notificationManager;
- /** @var IUserSession|MockObject */
- private $userSession;
- /** @var User_Proxy|MockObject */
- private $proxy;
- /** @var UserPluginManager|MockObject */
- private $userPluginManager;
- /** @var LoggerInterface|MockObject */
- protected $logger;
- /** @var DeletedUsersIndex|MockObject */
- protected $deletedUsersIndex;
+ protected Helper&MockObject $helper;
+ private ILDAPWrapper&MockObject $ldapWrapper;
+ private AccessFactory&MockObject $accessFactory;
+ private INotificationManager&MockObject $notificationManager;
+ private User_Proxy&MockObject $proxy;
+ private UserPluginManager&MockObject $userPluginManager;
+ protected LoggerInterface&MockObject $logger;
+ protected DeletedUsersIndex&MockObject $deletedUsersIndex;
protected function setUp(): void {
parent::setUp();
@@ -46,9 +34,7 @@ class User_ProxyTest extends TestCase {
$this->helper = $this->createMock(Helper::class);
$this->ldapWrapper = $this->createMock(ILDAPWrapper::class);
$this->accessFactory = $this->createMock(AccessFactory::class);
- $this->config = $this->createMock(IConfig::class);
$this->notificationManager = $this->createMock(INotificationManager::class);
- $this->userSession = $this->createMock(IUserSession::class);
$this->userPluginManager = $this->createMock(UserPluginManager::class);
$this->logger = $this->createMock(LoggerInterface::class);
$this->deletedUsersIndex = $this->createMock(DeletedUsersIndex::class);
@@ -57,18 +43,16 @@ class User_ProxyTest extends TestCase {
$this->helper,
$this->ldapWrapper,
$this->accessFactory,
- $this->config,
$this->notificationManager,
- $this->userSession,
$this->userPluginManager,
$this->logger,
$this->deletedUsersIndex,
])
- ->setMethods(['handleRequest'])
+ ->onlyMethods(['handleRequest'])
->getMock();
}
- public function testSetPassword() {
+ public function testSetPassword(): void {
$this->proxy
->expects($this->once())
->method('handleRequest')
@@ -78,7 +62,7 @@ class User_ProxyTest extends TestCase {
$this->assertTrue($this->proxy->setPassword('MyUid', 'MyPassword'));
}
- public function testSetDisplayName() {
+ public function testSetDisplayName(): void {
$this->proxy
->expects($this->once())
->method('handleRequest')
@@ -88,7 +72,7 @@ class User_ProxyTest extends TestCase {
$this->assertTrue($this->proxy->setDisplayName('MyUid', 'MyPassword'));
}
- public function testCreateUser() {
+ public function testCreateUser(): void {
$this->proxy
->expects($this->once())
->method('handleRequest')
diff --git a/apps/user_ldap/tests/WizardTest.php b/apps/user_ldap/tests/WizardTest.php
index d3cf6ffb0ae..3ae9a409e88 100644
--- a/apps/user_ldap/tests/WizardTest.php
+++ b/apps/user_ldap/tests/WizardTest.php
@@ -1,5 +1,6 @@
<?php
+declare(strict_types=1);
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -35,32 +36,28 @@ class WizardTest extends TestCase {
}
}
- private function getWizardAndMocks() {
+ private function getWizardAndMocks(): array {
static $confMethods;
- static $connMethods;
- static $accMethods;
if (is_null($confMethods)) {
$confMethods = get_class_methods('\OCA\User_LDAP\Configuration');
- $connMethods = get_class_methods('\OCA\User_LDAP\Connection');
- $accMethods = get_class_methods('\OCA\User_LDAP\Access');
}
- /** @var ILDAPWrapper|\PHPUnit\Framework\MockObject\MockObject $lw */
+ /** @var ILDAPWrapper&MockObject $lw */
$lw = $this->createMock(ILDAPWrapper::class);
- /** @var Configuration|\PHPUnit\Framework\MockObject\MockObject $conf */
+ /** @var Configuration&MockObject $conf */
$conf = $this->getMockBuilder(Configuration::class)
- ->setMethods($confMethods)
+ ->onlyMethods($confMethods)
->setConstructorArgs(['', true])
->getMock();
- /** @var Access|\PHPUnit\Framework\MockObject\MockObject $access */
+ /** @var Access&MockObject $access */
$access = $this->createMock(Access::class);
return [new Wizard($conf, $lw, $access), $conf, $lw, $access];
}
- private function prepareLdapWrapperForConnections(MockObject &$ldap) {
+ private function prepareLdapWrapperForConnections(MockObject $ldap) {
$ldap->expects($this->once())
->method('connect')
//dummy value
@@ -75,7 +72,7 @@ class WizardTest extends TestCase {
->willReturn(true);
}
- public function testCumulativeSearchOnAttributeLimited() {
+ public function testCumulativeSearchOnAttributeLimited(): void {
[$wizard, $configuration, $ldap] = $this->getWizardAndMocks();
$configuration->expects($this->any())
@@ -135,7 +132,7 @@ class WizardTest extends TestCase {
unset($uidnumber);
}
- public function testCumulativeSearchOnAttributeUnlimited() {
+ public function testCumulativeSearchOnAttributeUnlimited(): void {
[$wizard, $configuration, $ldap] = $this->getWizardAndMocks();
$configuration->expects($this->any())
@@ -211,7 +208,7 @@ class WizardTest extends TestCase {
unset($uidnumber);
}
- public function testDetectEmailAttributeAlreadySet() {
+ public function testDetectEmailAttributeAlreadySet(): void {
[$wizard, $configuration, $ldap, $access]
= $this->getWizardAndMocks();
@@ -233,7 +230,7 @@ class WizardTest extends TestCase {
$wizard->detectEmailAttribute();
}
- public function testDetectEmailAttributeOverrideSet() {
+ public function testDetectEmailAttributeOverrideSet(): void {
[$wizard, $configuration, $ldap, $access]
= $this->getWizardAndMocks();
@@ -272,7 +269,7 @@ class WizardTest extends TestCase {
$result['changes']['ldap_email_attr']);
}
- public function testDetectEmailAttributeFind() {
+ public function testDetectEmailAttributeFind(): void {
[$wizard, $configuration, $ldap, $access]
= $this->getWizardAndMocks();
@@ -311,7 +308,7 @@ class WizardTest extends TestCase {
$result['changes']['ldap_email_attr']);
}
- public function testDetectEmailAttributeFindNothing() {
+ public function testDetectEmailAttributeFindNothing(): void {
[$wizard, $configuration, $ldap, $access]
= $this->getWizardAndMocks();
@@ -346,10 +343,10 @@ class WizardTest extends TestCase {
});
$result = $wizard->detectEmailAttribute();
- $this->assertSame(false, $result->hasChanges());
+ $this->assertFalse($result->hasChanges());
}
- public function testCumulativeSearchOnAttributeSkipReadDN() {
+ public function testCumulativeSearchOnAttributeSkipReadDN(): void {
// tests that there is no infinite loop, when skipping already processed
// DNs (they can be returned multiple times for multiple filters )
[$wizard, $configuration, $ldap] = $this->getWizardAndMocks();
@@ -423,7 +420,7 @@ class WizardTest extends TestCase {
// The following expectations are the real test
$filters = ['f1', 'f2', '*'];
$resultArray = $wizard->cumulativeSearchOnAttribute($filters, 'cn', 0);
- $this->assertSame(6, count($resultArray));
+ $this->assertCount(6, $resultArray);
unset($mark);
}
}