diff options
Diffstat (limited to 'apps/user_ldap/tests')
50 files changed, 2410 insertions, 3154 deletions
diff --git a/apps/user_ldap/tests/.htaccess b/apps/user_ldap/tests/.htaccess index 6fde30e763a..e62a37927bf 100755 --- a/apps/user_ldap/tests/.htaccess +++ b/apps/user_ldap/tests/.htaccess @@ -1,3 +1,7 @@ +# SPDX-FileCopyrightText: 2017 Nextcloud GmbH and Nextcloud contributors +# SPDX-FileCopyrightText: 2015 ownCloud, Inc. +# SPDX-License-Identifier: AGPL-3.0-only +# # Generated by ownCloud on 2015-06-18 14:16:40 # line below if for Apache 2.4 <ifModule mod_authz_core.c> diff --git a/apps/user_ldap/tests/AccessTest.php b/apps/user_ldap/tests/AccessTest.php index c2902a67766..54be29d0f86 100644 --- a/apps/user_ldap/tests/AccessTest.php +++ b/apps/user_ldap/tests/AccessTest.php @@ -1,41 +1,17 @@ <?php + +declare(strict_types=1); /** - * @copyright Copyright (c) 2016, ownCloud, Inc. - * @copyright Copyright (c) 2016, Lukas Reschke <lukas@statuscode.ch> - * - * @author Andreas Fischer <bantu@owncloud.com> - * @author Arthur Schiwon <blizzz@arthur-schiwon.de> - * @author Christoph Wurst <christoph@winzerhof-wurst.at> - * @author Joas Schilling <coding@schilljs.com> - * @author Jörn Friedrich Dreyer <jfd@butonic.de> - * @author Lukas Reschke <lukas@statuscode.ch> - * @author Morris Jobke <hey@morrisjobke.de> - * @author Roeland Jago Douma <roeland@famdouma.nl> - * @author Roger Szabo <roger.szabo@web.de> - * @author Thomas Müller <thomas.mueller@tmit.eu> - * @author Victor Dubiniuk <dubiniuk@owncloud.com> - * - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see <http://www.gnu.org/licenses/> - * + * SPDX-FileCopyrightText: 2016 Nextcloud GmbH and Nextcloud contributors + * SPDX-FileCopyrightText: 2016 ownCloud, Inc. + * SPDX-License-Identifier: AGPL-3.0-only */ 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; @@ -44,12 +20,17 @@ 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; use Test\TestCase; @@ -61,32 +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; - /** @var LoggerInterface|MockObject */ - private $logger; - /** @var Access */ - private $access; + 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); @@ -95,29 +69,39 @@ class AccessTest extends TestCase { $this->ncUserManager = $this->createMock(IUserManager::class); $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->connection, $this->ldap, + $this->connection, $this->userManager, $this->helper, $this->config, $this->ncUserManager, - $this->logger + $this->logger, + $this->appConfig, + $this->dispatcher, ); + $this->dispatcher->expects($this->any())->method('dispatchTyped'); $this->access->setUserMapper($this->userMapper); $this->access->setGroupMapper($this->groupMapper); } private function getConnectorAndLdapMock() { + /** @var ILDAPWrapper&MockObject */ $lw = $this->createMock(ILDAPWrapper::class); + /** @var Connection&MockObject */ $connector = $this->getMockBuilder(Connection::class) ->setConstructorArgs([$lw, '', null]) ->getMock(); + $connector->expects($this->any()) + ->method('getConnectionResource') + ->willReturn(ldap_connect('ldap://example.com')); + /** @var Manager&MockObject */ $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), @@ -125,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 = '\\\\*'; - $this->assertTrue($expected === $this->access->escapeFilterPart($input)); + $expected = '\\2a'; + $this->assertSame($expected, $this->access->escapeFilterPart($input)); } - public function testEscapeFilterPartEscapeWildcard2() { + public function testEscapeFilterPartEscapeWildcard2(): void { $input = 'foo*bar'; - $expected = 'foo\\\\*bar'; - $this->assertTrue($expected === $this->access->escapeFilterPart($input)); + $expected = 'foo\\2abar'; + $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 [ [ [ @@ -184,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'; @@ -203,7 +187,7 @@ class AccessTest extends TestCase { $this->assertSame($domainDN, $this->access->getDomainDNFromDN($inputDN)); } - public function testGetDomainDNFromDNError() { + public function testGetDomainDNFromDNError(): void { $inputDN = 'foobar'; $expected = ''; @@ -215,83 +199,82 @@ 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($con, $lw, $um, $helper, $config, $this->ncUserManager, $this->logger); + $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($con, $lw, $um, $helper, $config, $this->ncUserManager, $this->logger); + $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); + $this->connection + ->expects($this->any()) + ->method('getConnectionResource') + ->willReturn(ldap_connect('ldap://example.com')); + $this->ldap->expects($this->any()) ->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') @@ -335,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') @@ -376,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') @@ -417,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'], @@ -427,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'; @@ -447,13 +427,13 @@ class AccessTest extends TestCase { $attribute => ['count' => 1, $dnFromServer] ]); - $access = new Access($con, $lw, $um, $helper, $config, $this->ncUserManager, $this->logger); + $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'); @@ -465,45 +445,39 @@ class AccessTest extends TestCase { $this->access->setPassword('CN=foo', 'MyPassword'); } - public function testSetPasswordWithLdapNotAvailable() { + public function testSetPasswordWithLdapNotAvailable(): void { $this->connection ->method('__get') ->willReturn(true); - $connection = $this->createMock(LDAP::class); + $connection = ldap_connect('ldap://example.com'); $this->connection ->expects($this->once()) ->method('getConnectionResource') - ->willReturn($connection); + ->willThrowException(new ServerNotAvailableException('Connection to LDAP server could not be established')); $this->ldap - ->expects($this->once()) - ->method('isResource') - ->with($connection) - ->willReturn(false); + ->expects($this->never()) + ->method('isResource'); - /** @noinspection PhpUnhandledExceptionInspection */ - $this->assertFalse($this->access->setPassword('CN=foo', 'MyPassword')); + $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 ->method('__get') ->willReturn(true); - $connection = $this->createMock(LDAP::class); + $connection = ldap_connect('ldap://example.com'); $this->connection ->expects($this->any()) ->method('getConnectionResource') ->willReturn($connection); $this->ldap ->expects($this->once()) - ->method('isResource') - ->with($connection) - ->willReturn(true); - $this->ldap - ->expects($this->once()) ->method('modReplace') ->with($connection, 'CN=foo', 'MyPassword') ->willThrowException(new ConstraintViolationException()); @@ -512,22 +486,17 @@ class AccessTest extends TestCase { $this->access->setPassword('CN=foo', 'MyPassword'); } - public function testSetPassword() { + public function testSetPassword(): void { $this->connection ->method('__get') ->willReturn(true); - $connection = $this->createMock(LDAP::class); + $connection = ldap_connect('ldap://example.com'); $this->connection ->expects($this->any()) ->method('getConnectionResource') ->willReturn($connection); $this->ldap ->expects($this->once()) - ->method('isResource') - ->with($connection) - ->willReturn(true); - $this->ldap - ->expects($this->once()) ->method('modReplace') ->with($connection, 'CN=foo', 'MyPassword') ->willReturn(true); @@ -540,7 +509,7 @@ class AccessTest extends TestCase { $base, $fakeConnection, $fakeSearchResultResource, - $fakeLdapEntries + $fakeLdapEntries, ) { $this->connection ->expects($this->any()) @@ -559,7 +528,7 @@ class AccessTest extends TestCase { ->expects($this->any()) ->method('isResource') ->willReturnCallback(function ($resource) { - return is_resource($resource) || is_object($resource); + return is_object($resource); }); $this->ldap ->expects($this->any()) @@ -579,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'; @@ -606,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']; @@ -626,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]; }); @@ -648,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'; @@ -678,7 +648,7 @@ class AccessTest extends TestCase { $this->groupMapper->expects($this->never()) ->method('getNameByDN'); - $this->connection->expects($this->exactly(2)) + $this->connection->expects($this->exactly(1)) ->method('writeToCache'); $groups = $this->access->fetchListOfGroups($filter, $attributes); @@ -687,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'], @@ -705,7 +675,7 @@ class AccessTest extends TestCase { ]; } - public function groupIDCandidateProvider() { + public static function groupIDCandidateProvider(): array { return [ ['alice', 'alice'], ['b/ob', 'b/ob'], @@ -722,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); } @@ -736,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([ @@ -763,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 6be09c474a2..db92598fcfd 100644 --- a/apps/user_ldap/tests/ConfigurationTest.php +++ b/apps/user_ldap/tests/ConfigurationTest.php @@ -1,41 +1,24 @@ <?php + +declare(strict_types=1); /** - * @copyright Copyright (c) 2016, ownCloud, Inc. - * - * @author Arthur Schiwon <blizzz@arthur-schiwon.de> - * @author Christoph Wurst <christoph@winzerhof-wurst.at> - * @author Joas Schilling <coding@schilljs.com> - * @author Roeland Jago Douma <roeland@famdouma.nl> - * - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see <http://www.gnu.org/licenses/> - * + * SPDX-FileCopyrightText: 2018-2024 Nextcloud GmbH and Nextcloud contributors + * SPDX-FileCopyrightText: 2016 ownCloud, Inc. + * SPDX-License-Identifier: AGPL-3.0-only */ 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', ' ', @@ -103,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']], @@ -122,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 3b771c6d04f..7116e15898f 100644 --- a/apps/user_ldap/tests/ConnectionTest.php +++ b/apps/user_ldap/tests/ConnectionTest.php @@ -1,36 +1,17 @@ <?php + +declare(strict_types=1); /** - * @copyright Copyright (c) 2016, ownCloud, Inc. - * - * @author Arthur Schiwon <blizzz@arthur-schiwon.de> - * @author Christoph Wurst <christoph@winzerhof-wurst.at> - * @author Jarkko Lehtoranta <devel@jlranta.com> - * @author Joas Schilling <coding@schilljs.com> - * @author Julius Härtl <jus@bitgrid.net> - * @author Morris Jobke <hey@morrisjobke.de> - * @author Roeland Jago Douma <roeland@famdouma.nl> - * @author Thomas Müller <thomas.mueller@tmit.eu> - * @author Victor Dubiniuk <dubiniuk@owncloud.com> - * - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see <http://www.gnu.org/licenses/> - * + * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors + * SPDX-FileCopyrightText: 2016 ownCloud, Inc. + * SPDX-License-Identifier: AGPL-3.0-only */ 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 @@ -40,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(); @@ -61,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 @@ -88,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 = [ @@ -114,17 +92,16 @@ class ConnectionTest extends \Test\TestCase { $this->ldap->expects($this->exactly(3)) ->method('connect') - ->willReturn('ldapResource'); + ->willReturn(ldap_connect('ldap://example.com')); $this->ldap->expects($this->any()) ->method('errno') ->willReturn(0); // Not called often enough? Then, the fallback to the backup server is broken. - $this->connection->expects($this->exactly(4)) + $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') @@ -136,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; }); @@ -147,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 = [ @@ -173,7 +150,7 @@ class ConnectionTest extends \Test\TestCase { $this->ldap->expects($this->once()) ->method('connect') - ->willReturn('ldapResource'); + ->willReturn(ldap_connect('ldap://example.com')); $this->ldap->expects($this->any()) ->method('errno') @@ -194,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. @@ -221,7 +198,7 @@ class ConnectionTest extends \Test\TestCase { $this->ldap->expects($this->any()) ->method('connect') - ->willReturn('ldapResource'); + ->willReturn(ldap_connect('ldap://example.com')); $this->ldap->expects($this->once()) ->method('bind') @@ -234,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. @@ -264,7 +241,7 @@ class ConnectionTest extends \Test\TestCase { $this->ldap->expects($this->any()) ->method('connect') - ->willReturn('ldapResource'); + ->willReturn(ldap_connect('ldap://example.com')); $this->ldap->expects($this->any()) ->method('setOption') @@ -282,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 660608d6b1f..9f4cff64d6b 100644 --- a/apps/user_ldap/tests/GroupLDAPPluginTest.php +++ b/apps/user_ldap/tests/GroupLDAPPluginTest.php @@ -1,26 +1,9 @@ <?php + +declare(strict_types=1); /** - * @copyright Copyright (c) 2017 EITA Cooperative (eita.org.br) - * - * @author Christoph Wurst <christoph@winzerhof-wurst.at> - * @author Roeland Jago Douma <roeland@famdouma.nl> - * @author Vinicius Cubas Brand <vinicius@eita.org.br> - * - * @license GNU AGPL version 3 or any later version - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see <http://www.gnu.org/licenses/>. - * + * SPDX-FileCopyrightText: 2017 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: AGPL-3.0-or-later */ namespace OCA\User_LDAP\Tests; @@ -28,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()) @@ -63,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()) @@ -85,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.'); @@ -93,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()) @@ -115,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.'); @@ -123,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()) @@ -146,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.'); @@ -154,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()) @@ -177,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.'); @@ -185,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()) @@ -208,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.'); @@ -216,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()) @@ -238,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 6204c22cb9e..10182111768 100644 --- a/apps/user_ldap/tests/Group_LDAPTest.php +++ b/apps/user_ldap/tests/Group_LDAPTest.php @@ -1,32 +1,10 @@ <?php + +declare(strict_types=1); /** - * @copyright Copyright (c) 2016, ownCloud, Inc. - * - * @author Arthur Schiwon <blizzz@arthur-schiwon.de> - * @author Christoph Wurst <christoph@winzerhof-wurst.at> - * @author Joas Schilling <coding@schilljs.com> - * @author Morris Jobke <hey@morrisjobke.de> - * @author Roeland Jago Douma <roeland@famdouma.nl> - * @author Thomas Müller <thomas.mueller@tmit.eu> - * @author Victor Dubiniuk <dubiniuk@owncloud.com> - * @author Vincent Petry <vincent@nextcloud.com> - * @author Vinicius Cubas Brand <vinicius@eita.org.br> - * @author Xuanwo <xuanwo@yunify.com> - * - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see <http://www.gnu.org/licenses/> - * + * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors + * SPDX-FileCopyrightText: 2016 ownCloud, Inc. + * SPDX-License-Identifier: AGPL-3.0-only */ namespace OCA\User_LDAP\Tests; @@ -37,7 +15,15 @@ use OCA\User_LDAP\GroupPluginManager; use OCA\User_LDAP\ILDAPWrapper; use OCA\User_LDAP\Mapping\GroupMapping; use OCA\User_LDAP\User\Manager; +use OCA\User_LDAP\User\OfflineUser; +use OCA\User_LDAP\User\User; +use OCA\User_LDAP\User_Proxy; 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; @@ -49,17 +35,34 @@ use Test\TestCase; * @package OCA\User_LDAP\Tests */ class Group_LDAPTest extends TestCase { - public function testCountEmptySearchString() { - $access = $this->getAccessMock(); - $pluginManager = $this->getPluginManagerMock(); + private Access&MockObject $access; + private GroupPluginManager&MockObject $pluginManager; + private IConfig&MockObject $config; + private IUserManager&MockObject $ncUserManager; + private GroupLDAP $groupBackend; + + public function setUp(): void { + parent::setUp(); + + $this->access = $this->getAccessMock(); + $this->pluginManager = $this->createMock(GroupPluginManager::class); + $this->config = $this->createMock(IConfig::class); + $this->ncUserManager = $this->createMock(IUserManager::class); + } + + public function initBackend(): void { + $this->groupBackend = new GroupLDAP($this->access, $this->pluginManager, $this->config, $this->ncUserManager); + } + + public function testCountEmptySearchString(): void { $groupDN = 'cn=group,dc=foo,dc=bar'; - $this->enableGroups($access); + $this->enableGroups(); - $access->expects($this->any()) + $this->access->expects($this->any()) ->method('groupname2dn') ->willReturn($groupDN); - $access->expects($this->any()) + $this->access->expects($this->any()) ->method('readAttribute') ->willReturnCallback(function ($dn) use ($groupDN) { if ($dn === $groupDN) { @@ -72,20 +75,20 @@ class Group_LDAPTest extends TestCase { } return []; }); - $access->expects($this->any()) + $this->access->expects($this->any()) ->method('isDNPartOfBase') ->willReturn(true); // for primary groups - $access->expects($this->once()) + $this->access->expects($this->once()) ->method('countUsers') ->willReturn(2); - $access->userManager->expects($this->any()) + $this->access->userManager->expects($this->any()) ->method('getAttributes') ->willReturn(['displayName', 'mail']); - $groupBackend = new GroupLDAP($access, $pluginManager); - $users = $groupBackend->countUsersInGroup('group'); + $this->initBackend(); + $users = $this->groupBackend->countUsersInGroup('group'); $this->assertSame(6, $users); } @@ -94,39 +97,20 @@ 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(); - $access = $this->createMock(Access::class); - - $access->connection = $connector; - - $access->userManager = $this->createMock(Manager::class); + $this->access = $this->createMock(Access::class); + $this->access->connection = $connector; + $this->access->userManager = $this->createMock(Manager::class); - return $access; + return $this->access; } - /** - * @return MockObject|GroupPluginManager - */ - private function getPluginManagerMock() { - return $this->createMock(GroupPluginManager::class); - } - - private function enableGroups(Access $access) { - $access->connection = $this->createMock(Connection::class); - - $access->connection->expects($this->any()) + private function enableGroups(): void { + $this->access->connection->expects($this->any()) ->method('__get') ->willReturnCallback(function ($name) { if ($name === 'ldapDynamicGroupMemberURL') { @@ -138,372 +122,317 @@ class Group_LDAPTest extends TestCase { }); } - public function testCountWithSearchString() { - $access = $this->getAccessMock(); - $pluginManager = $this->getPluginManagerMock(); + public function testCountWithSearchString(): void { + $this->enableGroups(); - $this->enableGroups($access); - - $access->expects($this->any()) + $this->access->expects($this->any()) ->method('groupname2dn') ->willReturn('cn=group,dc=foo,dc=bar'); - $access->expects($this->any()) + $this->access->expects($this->any()) ->method('fetchListOfUsers') ->willReturn([]); - $access->expects($this->any()) + $this->access->expects($this->any()) ->method('readAttribute') ->willReturnCallback(function ($name) { //the search operation will call readAttribute, thus we need - //to anaylze the "dn". All other times we just need to return + //to analyze the "dn". All other times we just need to return //something that is neither null or false, but once an array //with the users in the group – so we do so all other times for - //simplicicity. - if (strpos($name, 'u') === 0) { + //simplicity. + if (str_starts_with($name, 'u')) { return strpos($name, '3'); } return ['u11', 'u22', 'u33', 'u34']; }); - $access->expects($this->any()) + $this->access->expects($this->any()) ->method('dn2username') ->willReturnCallback(function () { - return 'foobar' . \OC::$server->getSecureRandom()->generate(7); + return 'foobar' . Server::get(ISecureRandom::class)->generate(7); }); - $access->expects($this->any()) + $this->access->expects($this->any()) ->method('isDNPartOfBase') ->willReturn(true); - $access->expects($this->any()) + $this->access->expects($this->any()) ->method('escapeFilterPart') ->willReturnArgument(0); - $access->userManager->expects($this->any()) + $this->access->userManager->expects($this->any()) ->method('getAttributes') ->willReturn(['displayName', 'mail']); - $groupBackend = new GroupLDAP($access, $pluginManager); - $users = $groupBackend->countUsersInGroup('group', '3'); + $this->initBackend(); + $users = $this->groupBackend->countUsersInGroup('group', '3'); $this->assertSame(2, $users); } - public function testCountUsersWithPlugin() { + public function testCountUsersWithPlugin(): void { /** @var GroupPluginManager|MockObject $pluginManager */ - $pluginManager = $this->getMockBuilder(GroupPluginManager::class) - ->setMethods(['implementsActions', 'countUsersInGroup']) + $this->pluginManager = $this->getMockBuilder(GroupPluginManager::class) + ->onlyMethods(['implementsActions', 'countUsersInGroup']) ->getMock(); - $pluginManager->expects($this->once()) + $this->pluginManager->expects($this->once()) ->method('implementsActions') ->with(GroupInterface::COUNT_USERS) ->willReturn(true); - $pluginManager->expects($this->once()) + $this->pluginManager->expects($this->once()) ->method('countUsersInGroup') ->with('gid', 'search') ->willReturn(42); - $access = $this->getAccessMock(); - $access->connection = $this->createMock(Connection::class); - - $ldap = new GroupLDAP($access, $pluginManager); - - $this->assertEquals($ldap->countUsersInGroup('gid', 'search'), 42); + $this->initBackend(); + $this->assertEquals($this->groupBackend->countUsersInGroup('gid', 'search'), 42); } - public function testGidNumber2NameSuccess() { - $access = $this->getAccessMock(); - $pluginManager = $this->getPluginManagerMock(); - - $this->enableGroups($access); + public function testGidNumber2NameSuccess(): void { + $this->enableGroups(); $userDN = 'cn=alice,cn=foo,dc=barfoo,dc=bar'; - $access->expects($this->once()) + $this->access->expects($this->once()) ->method('searchGroups') ->willReturn([['dn' => ['cn=foo,dc=barfoo,dc=bar']]]); - $access->expects($this->once()) + $this->access->expects($this->once()) ->method('dn2groupname') ->with('cn=foo,dc=barfoo,dc=bar') ->willReturn('MyGroup'); - $groupBackend = new GroupLDAP($access, $pluginManager); - - $group = $groupBackend->gidNumber2Name('3117', $userDN); + $this->initBackend(); + $group = $this->groupBackend->gidNumber2Name('3117', $userDN); $this->assertSame('MyGroup', $group); } - public function testGidNumberID2NameNoGroup() { - $access = $this->getAccessMock(); - $pluginManager = $this->getPluginManagerMock(); - - $this->enableGroups($access); + public function testGidNumberID2NameNoGroup(): void { + $this->enableGroups(); $userDN = 'cn=alice,cn=foo,dc=barfoo,dc=bar'; - $access->expects($this->once()) + $this->access->expects($this->once()) ->method('searchGroups') ->willReturn([]); - $access->expects($this->never()) + $this->access->expects($this->never()) ->method('dn2groupname'); - $groupBackend = new GroupLDAP($access, $pluginManager); - - $group = $groupBackend->gidNumber2Name('3117', $userDN); + $this->initBackend(); + $group = $this->groupBackend->gidNumber2Name('3117', $userDN); $this->assertSame(false, $group); } - public function testGidNumberID2NameNoName() { - $access = $this->getAccessMock(); - $pluginManager = $this->getPluginManagerMock(); - - $this->enableGroups($access); + public function testGidNumberID2NameNoName(): void { + $this->enableGroups(); $userDN = 'cn=alice,cn=foo,dc=barfoo,dc=bar'; - $access->expects($this->once()) + $this->access->expects($this->once()) ->method('searchGroups') ->willReturn([['dn' => ['cn=foo,dc=barfoo,dc=bar']]]); - $access->expects($this->once()) + $this->access->expects($this->once()) ->method('dn2groupname') ->willReturn(false); - $groupBackend = new GroupLDAP($access, $pluginManager); - - $group = $groupBackend->gidNumber2Name('3117', $userDN); + $this->initBackend(); + $group = $this->groupBackend->gidNumber2Name('3117', $userDN); $this->assertSame(false, $group); } - public function testGetEntryGidNumberValue() { - $access = $this->getAccessMock(); - $pluginManager = $this->getPluginManagerMock(); - - $this->enableGroups($access); + public function testGetEntryGidNumberValue(): void { + $this->enableGroups(); $dn = 'cn=foobar,cn=foo,dc=barfoo,dc=bar'; $attr = 'gidNumber'; - $access->expects($this->once()) + $this->access->expects($this->once()) ->method('readAttribute') ->with($dn, $attr) ->willReturn(['3117']); - $groupBackend = new GroupLDAP($access, $pluginManager); - - $gid = $groupBackend->getGroupGidNumber($dn); + $this->initBackend(); + $gid = $this->groupBackend->getGroupGidNumber($dn); $this->assertSame('3117', $gid); } - public function testGetEntryGidNumberNoValue() { - $access = $this->getAccessMock(); - $pluginManager = $this->getPluginManagerMock(); - - $this->enableGroups($access); + public function testGetEntryGidNumberNoValue(): void { + $this->enableGroups(); $dn = 'cn=foobar,cn=foo,dc=barfoo,dc=bar'; $attr = 'gidNumber'; - $access->expects($this->once()) + $this->access->expects($this->once()) ->method('readAttribute') ->with($dn, $attr) ->willReturn(false); - $groupBackend = new GroupLDAP($access, $pluginManager); - - $gid = $groupBackend->getGroupGidNumber($dn); + $this->initBackend(); + $gid = $this->groupBackend->getGroupGidNumber($dn); $this->assertSame(false, $gid); } - public function testPrimaryGroupID2NameSuccessCache() { - $access = $this->getAccessMock(); - $pluginManager = $this->getPluginManagerMock(); - - $this->enableGroups($access); + public function testPrimaryGroupID2NameSuccessCache(): void { + $this->enableGroups(); $userDN = 'cn=alice,cn=foo,dc=barfoo,dc=bar'; $gid = '3117'; - $groupDN = 'cn=foo,dc=barfoo,dc=bar'; /** @var MockObject $connection */ - $connection = $access->connection; + $connection = $this->access->connection; $connection->expects($this->once()) ->method('getFromCache') ->with('primaryGroupIDtoName_' . $gid) ->willReturn('MyGroup'); - $access->expects($this->never()) + $this->access->expects($this->never()) ->method('getSID'); - $access->expects($this->never()) + $this->access->expects($this->never()) ->method('searchGroups'); - $access->expects($this->never()) + $this->access->expects($this->never()) ->method('dn2groupname'); - $groupBackend = new GroupLDAP($access, $pluginManager); - $group = $groupBackend->primaryGroupID2Name($gid, $userDN); + $this->initBackend(); + $group = $this->groupBackend->primaryGroupID2Name($gid, $userDN); $this->assertSame('MyGroup', $group); } - public function testPrimaryGroupID2NameSuccess() { - $access = $this->getAccessMock(); - $pluginManager = $this->getPluginManagerMock(); - - $this->enableGroups($access); + public function testPrimaryGroupID2NameSuccess(): void { + $this->enableGroups(); $userDN = 'cn=alice,cn=foo,dc=barfoo,dc=bar'; - $access->expects($this->once()) + $this->access->expects($this->once()) ->method('getSID') ->with($userDN) ->willReturn('S-1-5-21-249921958-728525901-1594176202'); - $access->expects($this->once()) + $this->access->expects($this->once()) ->method('searchGroups') ->willReturn([['dn' => ['cn=foo,dc=barfoo,dc=bar']]]); - $access->expects($this->once()) + $this->access->expects($this->once()) ->method('dn2groupname') ->with('cn=foo,dc=barfoo,dc=bar') ->willReturn('MyGroup'); - $groupBackend = new GroupLDAP($access, $pluginManager); - - $group = $groupBackend->primaryGroupID2Name('3117', $userDN); + $this->initBackend(); + $group = $this->groupBackend->primaryGroupID2Name('3117', $userDN); $this->assertSame('MyGroup', $group); } - public function testPrimaryGroupID2NameNoSID() { - $access = $this->getAccessMock(); - $pluginManager = $this->getPluginManagerMock(); - - $this->enableGroups($access); + public function testPrimaryGroupID2NameNoSID(): void { + $this->enableGroups(); $userDN = 'cn=alice,cn=foo,dc=barfoo,dc=bar'; - $access->expects($this->once()) + $this->access->expects($this->once()) ->method('getSID') ->with($userDN) ->willReturn(false); - $access->expects($this->never()) + $this->access->expects($this->never()) ->method('searchGroups'); - $access->expects($this->never()) + $this->access->expects($this->never()) ->method('dn2groupname'); - $groupBackend = new GroupLDAP($access, $pluginManager); - - $group = $groupBackend->primaryGroupID2Name('3117', $userDN); + $this->initBackend(); + $group = $this->groupBackend->primaryGroupID2Name('3117', $userDN); $this->assertSame(false, $group); } - public function testPrimaryGroupID2NameNoGroup() { - $access = $this->getAccessMock(); - $pluginManager = $this->getPluginManagerMock(); - - $this->enableGroups($access); + public function testPrimaryGroupID2NameNoGroup(): void { + $this->enableGroups(); $userDN = 'cn=alice,cn=foo,dc=barfoo,dc=bar'; - $access->expects($this->once()) + $this->access->expects($this->once()) ->method('getSID') ->with($userDN) ->willReturn('S-1-5-21-249921958-728525901-1594176202'); - $access->expects($this->once()) + $this->access->expects($this->once()) ->method('searchGroups') ->willReturn([]); - $access->expects($this->never()) + $this->access->expects($this->never()) ->method('dn2groupname'); - $groupBackend = new GroupLDAP($access, $pluginManager); - - $group = $groupBackend->primaryGroupID2Name('3117', $userDN); + $this->initBackend(); + $group = $this->groupBackend->primaryGroupID2Name('3117', $userDN); $this->assertSame(false, $group); } - public function testPrimaryGroupID2NameNoName() { - $access = $this->getAccessMock(); - $pluginManager = $this->getPluginManagerMock(); - - $this->enableGroups($access); + public function testPrimaryGroupID2NameNoName(): void { + $this->enableGroups(); $userDN = 'cn=alice,cn=foo,dc=barfoo,dc=bar'; - $access->expects($this->once()) + $this->access->expects($this->once()) ->method('getSID') ->with($userDN) ->willReturn('S-1-5-21-249921958-728525901-1594176202'); - $access->expects($this->once()) + $this->access->expects($this->once()) ->method('searchGroups') ->willReturn([['dn' => ['cn=foo,dc=barfoo,dc=bar']]]); - $access->expects($this->once()) + $this->access->expects($this->once()) ->method('dn2groupname') ->willReturn(false); - $groupBackend = new GroupLDAP($access, $pluginManager); - - $group = $groupBackend->primaryGroupID2Name('3117', $userDN); + $this->initBackend(); + $group = $this->groupBackend->primaryGroupID2Name('3117', $userDN); $this->assertSame(false, $group); } - public function testGetEntryGroupIDValue() { + public function testGetEntryGroupIDValue(): void { //tests getEntryGroupID via getGroupPrimaryGroupID //which is basically identical to getUserPrimaryGroupIDs - $access = $this->getAccessMock(); - $pluginManager = $this->getPluginManagerMock(); - - $this->enableGroups($access); + $this->enableGroups(); $dn = 'cn=foobar,cn=foo,dc=barfoo,dc=bar'; $attr = 'primaryGroupToken'; - $access->expects($this->once()) + $this->access->expects($this->once()) ->method('readAttribute') ->with($dn, $attr) ->willReturn(['3117']); - $groupBackend = new GroupLDAP($access, $pluginManager); - - $gid = $groupBackend->getGroupPrimaryGroupID($dn); + $this->initBackend(); + $gid = $this->groupBackend->getGroupPrimaryGroupID($dn); $this->assertSame('3117', $gid); } - public function testGetEntryGroupIDNoValue() { + public function testGetEntryGroupIDNoValue(): void { //tests getEntryGroupID via getGroupPrimaryGroupID //which is basically identical to getUserPrimaryGroupIDs - $access = $this->getAccessMock(); - $pluginManager = $this->getPluginManagerMock(); - - $this->enableGroups($access); + $this->enableGroups(); $dn = 'cn=foobar,cn=foo,dc=barfoo,dc=bar'; $attr = 'primaryGroupToken'; - $access->expects($this->once()) + $this->access->expects($this->once()) ->method('readAttribute') ->with($dn, $attr) ->willReturn(false); - $groupBackend = new GroupLDAP($access, $pluginManager); - - $gid = $groupBackend->getGroupPrimaryGroupID($dn); + $this->initBackend(); + $gid = $this->groupBackend->getGroupPrimaryGroupID($dn); $this->assertSame(false, $gid); } @@ -512,29 +441,26 @@ class Group_LDAPTest extends TestCase { * tests whether Group Backend behaves correctly when cache with uid and gid * is hit */ - public function testInGroupHitsUidGidCache() { - $access = $this->getAccessMock(); - $pluginManager = $this->getPluginManagerMock(); - - $this->enableGroups($access); + public function testInGroupHitsUidGidCache(): void { + $this->enableGroups(); $uid = 'someUser'; $gid = 'someGroup'; $cacheKey = 'inGroup' . $uid . ':' . $gid; - $access->connection->expects($this->once()) + $this->access->connection->expects($this->once()) ->method('getFromCache') ->with($cacheKey) ->willReturn(true); - $access->expects($this->never()) + $this->access->expects($this->never()) ->method('username2dn'); - $groupBackend = new GroupLDAP($access, $pluginManager); - $groupBackend->inGroup($uid, $gid); + $this->initBackend(); + $this->groupBackend->inGroup($uid, $gid); } - public function groupWithMembersProvider() { + public static function groupWithMembersProvider(): array { return [ [ 'someGroup', @@ -549,19 +475,12 @@ class Group_LDAPTest extends TestCase { ]; } - /** - * @dataProvider groupWithMembersProvider - */ - public function testInGroupMember(string $gid, string $groupDn, array $memberDNs) { - $access = $this->getAccessMock(); - $pluginManager = $this->getPluginManagerMock(); - - $access->connection = $this->createMock(Connection::class); - + #[\PHPUnit\Framework\Attributes\DataProvider('groupWithMembersProvider')] + public function testInGroupMember(string $gid, string $groupDn, array $memberDNs): void { $uid = 'someUser'; $userDn = $memberDNs[0]; - $access->connection->expects($this->any()) + $this->access->connection->expects($this->any()) ->method('__get') ->willReturnCallback(function ($name) { switch ($name) { @@ -576,38 +495,31 @@ class Group_LDAPTest extends TestCase { return 1; } }); - $access->connection->expects($this->any()) + $this->access->connection->expects($this->any()) ->method('getFromCache') ->willReturn(null); - $access->expects($this->once()) + $this->access->expects($this->once()) ->method('username2dn') ->with($uid) ->willReturn($userDn); - $access->expects($this->once()) + $this->access->expects($this->once()) ->method('groupname2dn') ->willReturn($groupDn); - $access->expects($this->any()) + $this->access->expects($this->any()) ->method('readAttribute') ->willReturn($memberDNs); - $groupBackend = new GroupLDAP($access, $pluginManager); - $this->assertTrue($groupBackend->inGroup($uid, $gid)); + $this->initBackend(); + $this->assertTrue($this->groupBackend->inGroup($uid, $gid)); } - /** - * @dataProvider groupWithMembersProvider - */ - public function testInGroupMemberNot(string $gid, string $groupDn, array $memberDNs) { - $access = $this->getAccessMock(); - $pluginManager = $this->getPluginManagerMock(); - - $access->connection = $this->createMock(Connection::class); - + #[\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'; - $access->connection->expects($this->any()) + $this->access->connection->expects($this->any()) ->method('__get') ->willReturnCallback(function ($name) { switch ($name) { @@ -622,46 +534,38 @@ class Group_LDAPTest extends TestCase { return 1; } }); - $access->connection->expects($this->any()) + $this->access->connection->expects($this->any()) ->method('getFromCache') ->willReturn(null); - $access->expects($this->once()) + $this->access->expects($this->once()) ->method('username2dn') ->with($uid) ->willReturn($userDn); - $access->expects($this->once()) + $this->access->expects($this->once()) ->method('groupname2dn') ->willReturn($groupDn); - $access->expects($this->any()) + $this->access->expects($this->any()) ->method('readAttribute') ->willReturn($memberDNs); - $groupBackend = new GroupLDAP($access, $pluginManager); - $this->assertFalse($groupBackend->inGroup($uid, $gid)); + $this->initBackend(); + $this->assertFalse($this->groupBackend->inGroup($uid, $gid)); } - /** - * @dataProvider groupWithMembersProvider - */ - public function testInGroupMemberUid(string $gid, string $groupDn, array $memberDNs) { - $access = $this->getAccessMock(); - $pluginManager = $this->getPluginManagerMock(); - + #[\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]]; } - - $access->connection = $this->createMock(Connection::class); - $uid = 'someUser'; $userDn = $memberDNs[0]; - $access->connection->expects($this->any()) + $this->access->connection->expects($this->any()) ->method('__get') ->willReturnCallback(function ($name) { switch ($name) { @@ -678,65 +582,59 @@ class Group_LDAPTest extends TestCase { return 1; } }); - $access->connection->expects($this->any()) + $this->access->connection->expects($this->any()) ->method('getFromCache') ->willReturn(null); - $access->userManager->expects($this->any()) + $this->access->userManager->expects($this->any()) ->method('getAttributes') ->willReturn(['uid', 'mail', 'displayname']); - $access->expects($this->once()) + $this->access->expects($this->once()) ->method('username2dn') ->with($uid) ->willReturn($userDn); - $access->expects($this->once()) + $this->access->expects($this->once()) ->method('groupname2dn') ->willReturn($groupDn); - $access->expects($this->any()) + $this->access->expects($this->any()) ->method('readAttribute') ->willReturn($memberUids); - $access->expects($this->any()) + $this->access->expects($this->any()) ->method('fetchListOfUsers') ->willReturn($userRecords); - $access->expects($this->any()) + $this->access->expects($this->any()) ->method('combineFilterWithOr') ->willReturn('(|(pseudo=filter)(filter=pseudo))'); - $groupBackend = new GroupLDAP($access, $pluginManager); - $this->assertTrue($groupBackend->inGroup($uid, $gid)); + $this->initBackend(); + $this->assertTrue($this->groupBackend->inGroup($uid, $gid)); } - public function testGetGroupsWithOffset() { - $access = $this->getAccessMock(); - $pluginManager = $this->getPluginManagerMock(); + public function testGetGroupsWithOffset(): void { + $this->enableGroups(); - $this->enableGroups($access); - - $access->expects($this->once()) + $this->access->expects($this->once()) ->method('nextcloudGroupNames') ->willReturn(['group1', 'group2']); - $groupBackend = new GroupLDAP($access, $pluginManager); - $groups = $groupBackend->getGroups('', 2, 2); + $this->initBackend(); + $groups = $this->groupBackend->getGroups('', 2, 2); $this->assertSame(2, count($groups)); } /** - * tests that a user listing is complete, if all it's members have the group + * tests that a user listing is complete, if all its members have the group * as their primary. */ - public function testUsersInGroupPrimaryMembersOnly() { - $access = $this->getAccessMock(); - $pluginManager = $this->getPluginManagerMock(); - - $this->enableGroups($access); + public function testUsersInGroupPrimaryMembersOnly(): void { + $this->enableGroups(); - $access->connection->expects($this->any()) + $this->access->connection->expects($this->any()) ->method('getFromCache') ->willReturn(null); - $access->expects($this->any()) + $this->access->expects($this->any()) ->method('readAttribute') ->willReturnCallback(function ($dn, $attr) { if ($attr === 'primaryGroupToken') { @@ -746,43 +644,40 @@ class Group_LDAPTest extends TestCase { } return []; }); - $access->expects($this->any()) + $this->access->expects($this->any()) ->method('groupname2dn') ->willReturn('cn=foobar,dc=foo,dc=bar'); - $access->expects($this->exactly(2)) + $this->access->expects($this->exactly(2)) ->method('nextcloudUserNames') ->willReturnOnConsecutiveCalls(['lisa', 'bart', 'kira', 'brad'], ['walle', 'dino', 'xenia']); - $access->expects($this->any()) + $this->access->expects($this->any()) ->method('isDNPartOfBase') ->willReturn(true); - $access->expects($this->any()) + $this->access->expects($this->any()) ->method('combineFilterWithAnd') ->willReturn('pseudo=filter'); - $access->userManager->expects($this->any()) + $this->access->userManager->expects($this->any()) ->method('getAttributes') ->willReturn(['displayName', 'mail']); - $groupBackend = new GroupLDAP($access, $pluginManager); - $users = $groupBackend->usersInGroup('foobar'); + $this->initBackend(); + $users = $this->groupBackend->usersInGroup('foobar'); $this->assertSame(7, count($users)); } /** - * tests that a user listing is complete, if all it's members have the group + * tests that a user listing is complete, if all its members have the group * as their primary. */ - public function testUsersInGroupPrimaryAndUnixMembers() { - $access = $this->getAccessMock(); - $pluginManager = $this->getPluginManagerMock(); - - $this->enableGroups($access); + public function testUsersInGroupPrimaryAndUnixMembers(): void { + $this->enableGroups(); - $access->connection->expects($this->any()) + $this->access->connection->expects($this->any()) ->method('getFromCache') ->willReturn(null); - $access->expects($this->any()) + $this->access->expects($this->any()) ->method('readAttribute') ->willReturnCallback(function ($dn, $attr) { if ($attr === 'primaryGroupToken') { @@ -790,44 +685,41 @@ class Group_LDAPTest extends TestCase { } return []; }); - $access->expects($this->any()) + $this->access->expects($this->any()) ->method('groupname2dn') ->willReturn('cn=foobar,dc=foo,dc=bar'); - $access->expects($this->once()) + $this->access->expects($this->once()) ->method('nextcloudUserNames') ->willReturn(['lisa', 'bart', 'kira', 'brad']); - $access->expects($this->any()) + $this->access->expects($this->any()) ->method('isDNPartOfBase') ->willReturn(true); - $access->expects($this->any()) + $this->access->expects($this->any()) ->method('combineFilterWithAnd') ->willReturn('pseudo=filter'); - $access->userManager->expects($this->any()) + $this->access->userManager->expects($this->any()) ->method('getAttributes') ->willReturn(['displayName', 'mail']); - $groupBackend = new GroupLDAP($access, $pluginManager); - $users = $groupBackend->usersInGroup('foobar'); + $this->initBackend(); + $users = $this->groupBackend->usersInGroup('foobar'); $this->assertSame(4, count($users)); } /** - * tests that a user counting is complete, if all it's members have the group + * tests that a user counting is complete, if all its members have the group * as their primary. */ - public function testCountUsersInGroupPrimaryMembersOnly() { - $access = $this->getAccessMock(); - $pluginManager = $this->getPluginManagerMock(); + public function testCountUsersInGroupPrimaryMembersOnly(): void { + $this->enableGroups(); - $this->enableGroups($access); - - $access->connection->expects($this->any()) + $this->access->connection->expects($this->any()) ->method('getFromCache') ->willReturn(null); - $access->expects($this->any()) + $this->access->expects($this->any()) ->method('readAttribute') ->willReturnCallback(function ($dn, $attr) { if ($attr === 'primaryGroupToken') { @@ -835,65 +727,63 @@ class Group_LDAPTest extends TestCase { } return []; }); - $access->expects($this->any()) + $this->access->expects($this->any()) ->method('groupname2dn') ->willReturn('cn=foobar,dc=foo,dc=bar'); - $access->expects($this->once()) + $this->access->expects($this->once()) ->method('countUsers') ->willReturn(4); - $access->expects($this->any()) + $this->access->expects($this->any()) ->method('isDNPartOfBase') ->willReturn(true); - $access->userManager->expects($this->any()) + $this->access->userManager->expects($this->any()) ->method('getAttributes') ->willReturn(['displayName', 'mail']); - $groupBackend = new GroupLDAP($access, $pluginManager); - $users = $groupBackend->countUsersInGroup('foobar'); + $this->initBackend(); + $users = $this->groupBackend->countUsersInGroup('foobar'); $this->assertSame(4, $users); } - public function testGetUserGroupsMemberOf() { - $access = $this->getAccessMock(); - $pluginManager = $this->getPluginManagerMock(); - - $this->enableGroups($access); + public function testGetUserGroupsMemberOf(): void { + $this->enableGroups(); $dn = 'cn=userX,dc=foobar'; - $access->connection->hasPrimaryGroups = false; - $access->connection->hasGidNumber = false; + $this->access->connection->hasPrimaryGroups = false; + $this->access->connection->hasGidNumber = false; - $access->expects($this->any()) + $expectedGroups = ['cn=groupA,dc=foobar', 'cn=groupB,dc=foobar']; + + $this->access->expects($this->any()) ->method('username2dn') ->willReturn($dn); - $access->expects($this->exactly(5)) - ->method('readAttribute') - ->will($this->onConsecutiveCalls(['cn=groupA,dc=foobar', 'cn=groupB,dc=foobar'], [], [], [], [])); - $access->expects($this->any()) + $this->access->expects($this->exactly(5)) + ->method('readAttribute')->willReturnOnConsecutiveCalls($expectedGroups, [], [], [], []); + $this->access->expects($this->any()) ->method('dn2groupname') ->willReturnArgument(0); - $access->expects($this->any()) + $this->access->expects($this->any()) ->method('groupname2dn') ->willReturnArgument(0); - $access->expects($this->any()) + $this->access->expects($this->any()) ->method('isDNPartOfBase') ->willReturn(true); - $groupBackend = new GroupLDAP($access, $pluginManager); - $groups = $groupBackend->getUserGroups('userX'); + $this->config->expects($this->once()) + ->method('setUserValue') + ->with('userX', 'user_ldap', 'cached-group-memberships-', \json_encode($expectedGroups)); + + $this->initBackend(); + $groups = $this->groupBackend->getUserGroups('userX'); $this->assertSame(2, count($groups)); } - public function testGetUserGroupsMemberOfDisabled() { - $access = $this->getAccessMock(); - $pluginManager = $this->getPluginManagerMock(); - - $access->connection = $this->createMock(Connection::class); - $access->connection->expects($this->any()) + public function testGetUserGroupsMemberOfDisabled(): void { + $this->access->connection->expects($this->any()) ->method('__get') ->willReturnCallback(function ($name) { if ($name === 'useMemberOfToDetectMembership') { @@ -906,71 +796,187 @@ class Group_LDAPTest extends TestCase { $dn = 'cn=userX,dc=foobar'; - $access->connection->hasPrimaryGroups = false; - $access->connection->hasGidNumber = false; + $this->access->connection->hasPrimaryGroups = false; + $this->access->connection->hasGidNumber = false; - $access->expects($this->once()) + $this->access->expects($this->once()) ->method('username2dn') ->willReturn($dn); - $access->expects($this->never()) + $this->access->expects($this->never()) ->method('readAttribute') ->with($dn, 'memberOf'); - $access->expects($this->once()) + $this->access->expects($this->once()) ->method('nextcloudGroupNames') ->willReturn([]); - $groupBackend = new GroupLDAP($access, $pluginManager); - $groupBackend->getUserGroups('userX'); + // empty group result should not be oer + $this->config->expects($this->once()) + ->method('setUserValue') + ->with('userX', 'user_ldap', 'cached-group-memberships-', '[]'); + + $ldapUser = $this->createMock(User::class); + + $this->access->userManager->expects($this->any()) + ->method('get') + ->with('userX') + ->willReturn($ldapUser); + + $userBackend = $this->createMock(User_Proxy::class); + $userBackend->expects($this->once()) + ->method('userExistsOnLDAP') + ->with('userX', true) + ->willReturn(true); + + $ncUser = $this->createMock(IUser::class); + $ncUser->expects($this->any()) + ->method('getBackend') + ->willReturn($userBackend); + + $this->ncUserManager->expects($this->once()) + ->method('get') + ->with('userX') + ->willReturn($ncUser); + + $this->initBackend(); + $this->groupBackend->getUserGroups('userX'); } - public function nestedGroupsProvider(): array { + public function testGetUserGroupsOfflineUser(): void { + $this->enableGroups(); + + $offlineUser = $this->createMock(OfflineUser::class); + + $this->config->expects($this->any()) + ->method('getUserValue') + ->with('userX', 'user_ldap', 'cached-group-memberships-', $this->anything()) + ->willReturn(\json_encode(['groupB', 'groupF'])); + + $this->access->userManager->expects($this->any()) + ->method('get') + ->with('userX') + ->willReturn($offlineUser); + + $this->initBackend(); + $returnedGroups = $this->groupBackend->getUserGroups('userX'); + $this->assertCount(2, $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(): void { + $this->enableGroups(); + + $offlineUser = $this->createMock(OfflineUser::class); + + $this->config->expects($this->any()) + ->method('getUserValue') + ->with('userX', 'user_ldap', 'cached-group-memberships-', $this->anything()) + // results in a json object: {"0":"groupB","2":"groupF"} + ->willReturn(\json_encode([0 => 'groupB', 2 => 'groupF'])); + + $this->access->userManager->expects($this->any()) + ->method('get') + ->with('userX') + ->willReturn($offlineUser); + + $this->initBackend(); + $returnedGroups = $this->groupBackend->getUserGroups('userX'); + $this->assertCount(2, $returnedGroups); + $this->assertContains('groupB', $returnedGroups); + $this->assertContains('groupF', $returnedGroups); + } + + public function testGetUserGroupsUnrecognizedOfflineUser(): void { + $this->enableGroups(); + $dn = 'cn=userX,dc=foobar'; + + $ldapUser = $this->createMock(User::class); + + $userBackend = $this->createMock(User_Proxy::class); + $userBackend->expects($this->once()) + ->method('userExistsOnLDAP') + ->with('userX', true) + ->willReturn(false); + + $ncUser = $this->createMock(IUser::class); + $ncUser->expects($this->any()) + ->method('getBackend') + ->willReturn($userBackend); + + $this->config->expects($this->atLeastOnce()) + ->method('getUserValue') + ->with('userX', 'user_ldap', 'cached-group-memberships-', $this->anything()) + ->willReturn(\json_encode(['groupB', 'groupF'])); + + $this->access->expects($this->any()) + ->method('username2dn') + ->willReturn($dn); + + $this->access->userManager->expects($this->any()) + ->method('get') + ->with('userX') + ->willReturn($ldapUser); + + $this->ncUserManager->expects($this->once()) + ->method('get') + ->with('userX') + ->willReturn($ncUser); + + $this->initBackend(); + $returnedGroups = $this->groupBackend->getUserGroups('userX'); + $this->assertCount(2, $returnedGroups); + $this->assertContains('groupB', $returnedGroups); + $this->assertContains('groupF', $returnedGroups); + } + + public static function nestedGroupsProvider(): array { return [ [true], [false], ]; } - /** - * @dataProvider nestedGroupsProvider - */ - public function testGetGroupsByMember(bool $nestedGroups) { - $access = $this->getAccessMock(); - $pluginManager = $this->getPluginManagerMock(); - + #[\PHPUnit\Framework\Attributes\DataProvider('nestedGroupsProvider')] + public function testGetGroupsByMember(bool $nestedGroups): void { $groupFilter = '(&(objectclass=nextcloudGroup)(nextcloudEnabled=TRUE))'; - $access->connection = $this->createMock(Connection::class); - $access->connection->expects($this->any()) + $this->access->connection->expects($this->any()) ->method('__get') - ->willReturnCallback(function ($name) use ($nestedGroups, $groupFilter) { + ->willReturnCallback(function (string $name) use ($nestedGroups, $groupFilter) { switch ($name) { case 'useMemberOfToDetectMembership': return 0; case 'ldapDynamicGroupMemberURL': return ''; case 'ldapNestedGroups': - return $nestedGroups; + return (int)$nestedGroups; case 'ldapGroupMemberAssocAttr': return 'member'; case 'ldapGroupFilter': return $groupFilter; case 'ldapBaseGroups': return []; + case 'ldapGroupDisplayName': + return 'cn'; } return 1; }); $dn = 'cn=userX,dc=foobar'; - $access->connection->hasPrimaryGroups = false; - $access->connection->hasGidNumber = false; + $this->access->connection->hasPrimaryGroups = false; + $this->access->connection->hasGidNumber = false; - $access->expects($this->exactly(2)) + $this->access->expects($this->exactly(2)) ->method('username2dn') ->willReturn($dn); - $access->expects($this->any()) + $this->access->expects($this->any()) ->method('readAttribute') ->willReturn([]); - $access->expects($this->any()) + $this->access->expects($this->any()) ->method('combineFilterWithAnd') ->willReturnCallback(function (array $filterParts) { // ⚠ returns a pseudo-filter only, not real LDAP Filter syntax @@ -980,352 +986,346 @@ class Group_LDAPTest extends TestCase { $group1 = [ 'cn' => 'group1', 'dn' => ['cn=group1,ou=groups,dc=domain,dc=com'], + 'member' => [$dn], ]; $group2 = [ 'cn' => 'group2', 'dn' => ['cn=group2,ou=groups,dc=domain,dc=com'], + 'member' => [$dn], + ]; + $group3 = [ + 'cn' => 'group3', + 'dn' => ['cn=group3,ou=groups,dc=domain,dc=com'], + 'member' => [$group2['dn'][0]], ]; - $access->expects($this->once()) + $expectedGroups = ($nestedGroups ? [$group1, $group2, $group3] : [$group1, $group2]); + $expectedGroupsNames = ($nestedGroups ? ['group1', 'group2', 'group3'] : ['group1', 'group2']); + + $this->access->expects($this->any()) ->method('nextcloudGroupNames') - ->with([$group1, $group2]) - ->willReturn(['group1', 'group2']); - $access->expects($nestedGroups ? $this->atLeastOnce() : $this->once()) + ->with($expectedGroups) + ->willReturn($expectedGroupsNames); + $this->access->expects($nestedGroups ? $this->atLeastOnce() : $this->once()) ->method('fetchListOfGroups') - ->willReturnCallback(function ($filter, $attr, $limit, $offset) use ($nestedGroups, $groupFilter, $group1, $group2) { + ->willReturnCallback(function ($filter, $attr, $limit, $offset) use ($nestedGroups, $groupFilter, $group1, $group2, $group3, $dn) { static $firstRun = true; if (!$nestedGroups) { // When nested groups are enabled, groups cannot be filtered early as it would // exclude intermediate groups. But we can, and should, when working with flat groups. - $this->assertTrue(strpos($filter, $groupFilter) !== false); + $this->assertTrue(str_contains($filter, $groupFilter)); } - if ($firstRun) { - $firstRun = false; + [$memberFilter] = explode('&', $filter); + if ($memberFilter === 'member=' . $dn) { return [$group1, $group2]; + return []; + } elseif ($memberFilter === 'member=' . $group2['dn'][0]) { + return [$group3]; + } else { + return []; } - return []; }); - $access->expects($this->any()) + $this->access->expects($this->any()) ->method('dn2groupname') ->willReturnCallback(function (string $dn) { return ldap_explode_dn($dn, 1)[0]; }); - $access->expects($this->any()) + $this->access->expects($this->any()) ->method('groupname2dn') - ->willReturnCallback(function (string $gid) use ($group1, $group2) { + ->willReturnCallback(function (string $gid) use ($group1, $group2, $group3) { if ($gid === $group1['cn']) { return $group1['dn'][0]; } if ($gid === $group2['cn']) { return $group2['dn'][0]; } + if ($gid === $group3['cn']) { + return $group3['dn'][0]; + } }); - $access->expects($this->any()) + $this->access->expects($this->any()) ->method('isDNPartOfBase') ->willReturn(true); - $groupBackend = new GroupLDAP($access, $pluginManager); - $groups = $groupBackend->getUserGroups('userX'); - $this->assertEquals(['group1', 'group2'], $groups); + $this->initBackend(); + $groups = $this->groupBackend->getUserGroups('userX'); + $this->assertEquals($expectedGroupsNames, $groups); - $groupsAgain = $groupBackend->getUserGroups('userX'); - $this->assertEquals(['group1', 'group2'], $groupsAgain); + $groupsAgain = $this->groupBackend->getUserGroups('userX'); + $this->assertEquals($expectedGroupsNames, $groupsAgain); } - public function testCreateGroupWithPlugin() { - /** @var GroupPluginManager|MockObject $pluginManager */ - $pluginManager = $this->getMockBuilder(GroupPluginManager::class) - ->setMethods(['implementsActions', 'createGroup']) + public function testCreateGroupWithPlugin(): void { + $this->pluginManager = $this->getMockBuilder(GroupPluginManager::class) + ->onlyMethods(['implementsActions', 'createGroup']) ->getMock(); - $pluginManager->expects($this->once()) + $this->pluginManager->expects($this->once()) ->method('implementsActions') ->with(GroupInterface::CREATE_GROUP) ->willReturn(true); - $pluginManager->expects($this->once()) + $this->pluginManager->expects($this->once()) ->method('createGroup') ->with('gid') ->willReturn('result'); - $access = $this->getAccessMock(); - $access->connection = $this->createMock(Connection::class); - - $ldap = new GroupLDAP($access, $pluginManager); - - $this->assertEquals($ldap->createGroup('gid'), true); + $this->initBackend(); + $this->assertTrue($this->groupBackend->createGroup('gid')); } - public function testCreateGroupFailing() { + public function testCreateGroupFailing(): void { $this->expectException(\Exception::class); - /** @var GroupPluginManager|MockObject $pluginManager */ - $pluginManager = $this->getMockBuilder(GroupPluginManager::class) - ->setMethods(['implementsActions', 'createGroup']) + $this->pluginManager = $this->getMockBuilder(GroupPluginManager::class) + ->onlyMethods(['implementsActions', 'createGroup']) ->getMock(); - $pluginManager->expects($this->once()) + $this->pluginManager->expects($this->once()) ->method('implementsActions') ->with(GroupInterface::CREATE_GROUP) ->willReturn(false); - $access = $this->getAccessMock(); - $access->connection = $this->createMock(Connection::class); - - $ldap = new GroupLDAP($access, $pluginManager); - - $ldap->createGroup('gid'); + $this->initBackend(); + $this->groupBackend->createGroup('gid'); } - public function testDeleteGroupWithPlugin() { - /** @var GroupPluginManager|MockObject $pluginManager */ - $pluginManager = $this->getMockBuilder(GroupPluginManager::class) - ->setMethods(['implementsActions', 'deleteGroup']) + public function testDeleteGroupWithPlugin(): void { + $this->pluginManager = $this->getMockBuilder(GroupPluginManager::class) + ->onlyMethods(['implementsActions', 'deleteGroup']) ->getMock(); - $pluginManager->expects($this->once()) + $this->pluginManager->expects($this->once()) ->method('implementsActions') ->with(GroupInterface::DELETE_GROUP) ->willReturn(true); - $pluginManager->expects($this->once()) + $this->pluginManager->expects($this->once()) ->method('deleteGroup') ->with('gid') ->willReturn(true); $mapper = $this->getMockBuilder(GroupMapping::class) - ->setMethods(['unmap']) + ->onlyMethods(['unmap']) ->disableOriginalConstructor() ->getMock(); - $access = $this->getAccessMock(); - $access->expects($this->any()) + $this->access->expects($this->any()) ->method('getGroupMapper') ->willReturn($mapper); - $access->connection = $this->createMock(Connection::class); - - $ldap = new GroupLDAP($access, $pluginManager); - - $this->assertTrue($ldap->deleteGroup('gid')); + $this->initBackend(); + $this->assertTrue($this->groupBackend->deleteGroup('gid')); } - public function testDeleteGroupFailing() { + public function testDeleteGroupFailing(): void { $this->expectException(\Exception::class); - /** @var GroupPluginManager|MockObject $pluginManager */ - $pluginManager = $this->getMockBuilder(GroupPluginManager::class) - ->setMethods(['implementsActions', 'deleteGroup']) + $this->pluginManager = $this->getMockBuilder(GroupPluginManager::class) + ->onlyMethods(['implementsActions', 'deleteGroup']) ->getMock(); - $pluginManager->expects($this->once()) + $this->pluginManager->expects($this->once()) ->method('implementsActions') ->with(GroupInterface::DELETE_GROUP) ->willReturn(false); - $access = $this->getAccessMock(); - $access->connection = $this->createMock(Connection::class); - - $ldap = new GroupLDAP($access, $pluginManager); - - $ldap->deleteGroup('gid'); + $this->initBackend(); + $this->groupBackend->deleteGroup('gid'); } - public function testAddToGroupWithPlugin() { - /** @var GroupPluginManager|MockObject $pluginManager */ - $pluginManager = $this->getMockBuilder(GroupPluginManager::class) - ->setMethods(['implementsActions', 'addToGroup']) + public function testAddToGroupWithPlugin(): void { + $this->pluginManager = $this->getMockBuilder(GroupPluginManager::class) + ->onlyMethods(['implementsActions', 'addToGroup']) ->getMock(); - $pluginManager->expects($this->once()) + $this->pluginManager->expects($this->once()) ->method('implementsActions') ->with(GroupInterface::ADD_TO_GROUP) ->willReturn(true); - $pluginManager->expects($this->once()) + $this->pluginManager->expects($this->once()) ->method('addToGroup') ->with('uid', 'gid') ->willReturn('result'); - $access = $this->getAccessMock(); - $access->connection = $this->createMock(Connection::class); - - $ldap = new GroupLDAP($access, $pluginManager); - - $this->assertEquals($ldap->addToGroup('uid', 'gid'), 'result'); + $this->initBackend(); + $this->assertEquals('result', $this->groupBackend->addToGroup('uid', 'gid')); } - public function testAddToGroupFailing() { + public function testAddToGroupFailing(): void { $this->expectException(\Exception::class); - /** @var GroupPluginManager|MockObject $pluginManager */ - $pluginManager = $this->getMockBuilder(GroupPluginManager::class) - ->setMethods(['implementsActions', 'addToGroup']) + $this->pluginManager = $this->getMockBuilder(GroupPluginManager::class) + ->onlyMethods(['implementsActions', 'addToGroup']) ->getMock(); - $pluginManager->expects($this->once()) + $this->pluginManager->expects($this->once()) ->method('implementsActions') ->with(GroupInterface::ADD_TO_GROUP) ->willReturn(false); - $access = $this->getAccessMock(); - $access->connection = $this->createMock(Connection::class); - - $ldap = new GroupLDAP($access, $pluginManager); - - $ldap->addToGroup('uid', 'gid'); + $this->initBackend(); + $this->groupBackend->addToGroup('uid', 'gid'); } - public function testRemoveFromGroupWithPlugin() { - /** @var GroupPluginManager|MockObject $pluginManager */ - $pluginManager = $this->getMockBuilder(GroupPluginManager::class) - ->setMethods(['implementsActions', 'removeFromGroup']) + public function testRemoveFromGroupWithPlugin(): void { + $this->pluginManager = $this->getMockBuilder(GroupPluginManager::class) + ->onlyMethods(['implementsActions', 'removeFromGroup']) ->getMock(); - $pluginManager->expects($this->once()) + $this->pluginManager->expects($this->once()) ->method('implementsActions') ->with(GroupInterface::REMOVE_FROM_GROUP) ->willReturn(true); - $pluginManager->expects($this->once()) + $this->pluginManager->expects($this->once()) ->method('removeFromGroup') ->with('uid', 'gid') ->willReturn('result'); - $access = $this->getAccessMock(); - $access->connection = $this->createMock(Connection::class); - - $ldap = new GroupLDAP($access, $pluginManager); - - $this->assertEquals($ldap->removeFromGroup('uid', 'gid'), 'result'); + $this->initBackend(); + $this->assertEquals('result', $this->groupBackend->removeFromGroup('uid', 'gid')); } - public function testRemoveFromGroupFailing() { + public function testRemoveFromGroupFailing(): void { $this->expectException(\Exception::class); - /** @var GroupPluginManager|MockObject $pluginManager */ - $pluginManager = $this->getMockBuilder(GroupPluginManager::class) - ->setMethods(['implementsActions', 'removeFromGroup']) + $this->pluginManager = $this->getMockBuilder(GroupPluginManager::class) + ->onlyMethods(['implementsActions', 'removeFromGroup']) ->getMock(); - $pluginManager->expects($this->once()) + $this->pluginManager->expects($this->once()) ->method('implementsActions') ->with(GroupInterface::REMOVE_FROM_GROUP) ->willReturn(false); - $access = $this->getAccessMock(); - $access->connection = $this->createMock(Connection::class); - - $ldap = new GroupLDAP($access, $pluginManager); - - $ldap->removeFromGroup('uid', 'gid'); + $this->initBackend(); + $this->groupBackend->removeFromGroup('uid', 'gid'); } - public function testGetGroupDetailsWithPlugin() { + public function testGetGroupDetailsWithPlugin(): void { /** @var GroupPluginManager|MockObject $pluginManager */ - $pluginManager = $this->getMockBuilder(GroupPluginManager::class) - ->setMethods(['implementsActions', 'getGroupDetails']) + $this->pluginManager = $this->getMockBuilder(GroupPluginManager::class) + ->onlyMethods(['implementsActions', 'getGroupDetails']) ->getMock(); - $pluginManager->expects($this->once()) + $this->pluginManager->expects($this->once()) ->method('implementsActions') ->with(GroupInterface::GROUP_DETAILS) ->willReturn(true); - $pluginManager->expects($this->once()) + $this->pluginManager->expects($this->once()) ->method('getGroupDetails') ->with('gid') ->willReturn('result'); - $access = $this->getAccessMock(); - $access->connection = $this->createMock(Connection::class); - - $ldap = new GroupLDAP($access, $pluginManager); - - $this->assertEquals($ldap->getGroupDetails('gid'), 'result'); + $this->initBackend(); + $this->assertEquals('result', $this->groupBackend->getGroupDetails('gid')); } - - public function testGetGroupDetailsFailing() { + public function testGetGroupDetailsFailing(): void { $this->expectException(\Exception::class); - /** @var GroupPluginManager|MockObject $pluginManager */ - $pluginManager = $this->getMockBuilder(GroupPluginManager::class) - ->setMethods(['implementsActions', 'getGroupDetails']) + $this->pluginManager = $this->getMockBuilder(GroupPluginManager::class) + ->onlyMethods(['implementsActions', 'getGroupDetails']) ->getMock(); - $pluginManager->expects($this->once()) + $this->pluginManager->expects($this->once()) ->method('implementsActions') ->with(GroupInterface::GROUP_DETAILS) ->willReturn(false); - $access = $this->getAccessMock(); - $access->connection = $this->createMock(Connection::class); - - $ldap = new GroupLDAP($access, $pluginManager); - - $ldap->getGroupDetails('gid'); + $this->initBackend(); + $this->groupBackend->getGroupDetails('gid'); } - public function groupMemberProvider() { + public static function groupMemberProvider(): array { $base = 'dc=species,dc=earth'; - $groups0 = [ + $birdsDn = [ 'uid=3723,' . $base, 'uid=8372,' . $base, 'uid=8427,' . $base, 'uid=2333,' . $base, 'uid=4754,' . $base, ]; - $groups1 = [ + $birdsUid = [ '3723', '8372', '8427', '2333', '4754', ]; - $groups2Nested = ['6642', '1424']; - $expGroups2 = array_merge($groups1, $groups2Nested); + $animalsDn = [ + 'uid=lion,' . $base, + 'uid=tiger,' . $base, + ]; + $plantsDn = [ + 'uid=flower,' . $base, + 'uid=tree,' . $base, + ]; + $thingsDn = [ + 'uid=thing1,' . $base, + 'uid=thing2,' . $base, + ]; return [ [ #0 – test DNs - 'cn=Birds,' . $base, - $groups0, - ['cn=Birds,' . $base => $groups0] + ['cn=Birds,' . $base => $birdsDn], + ['cn=Birds,' . $base => $birdsDn] ], [ #1 – test uids - 'cn=Birds,' . $base, - $groups1, - ['cn=Birds,' . $base => $groups1] + ['cn=Birds,' . $base => $birdsUid], + ['cn=Birds,' . $base => $birdsUid] + ], + [ #2 – test simple nested group + ['cn=Animals,' . $base => array_merge($birdsDn, $animalsDn)], + [ + 'cn=Animals,' . $base => array_merge(['cn=Birds,' . $base], $animalsDn), + 'cn=Birds,' . $base => $birdsDn, + ] + ], + [ #3 – test recursive nested group + [ + 'cn=Animals,' . $base => array_merge($birdsDn, $animalsDn), + 'cn=Birds,' . $base => array_merge($birdsDn, $animalsDn), + ], + [ + 'cn=Animals,' . $base => array_merge(['cn=Birds,' . $base,'cn=Birds,' . $base,'cn=Animals,' . $base], $animalsDn), + 'cn=Birds,' . $base => array_merge(['cn=Animals,' . $base,'cn=Birds,' . $base], $birdsDn), + ] + ], + [ #4 – Complicated nested group + ['cn=Things,' . $base => array_merge($birdsDn, $animalsDn, $thingsDn, $plantsDn)], + [ + 'cn=Animals,' . $base => array_merge(['cn=Birds,' . $base], $animalsDn), + 'cn=Birds,' . $base => $birdsDn, + 'cn=Plants,' . $base => $plantsDn, + 'cn=Things,' . $base => array_merge(['cn=Animals,' . $base,'cn=Plants,' . $base], $thingsDn), + ] ], ]; } - /** - * @param string $groupDN - * @param string[] $expectedMembers - * @param array $groupsInfo - * @dataProvider groupMemberProvider - */ - public function testGroupMembers($groupDN, $expectedMembers, $groupsInfo = null) { - $access = $this->getAccessMock(); - $access->expects($this->any()) + #[\PHPUnit\Framework\Attributes\DataProvider('groupMemberProvider')] + public function testGroupMembers(array $expectedResult, array $groupsInfo): void { + $this->access->expects($this->any()) ->method('readAttribute') - ->willReturnCallback(function ($group) use ($groupDN, $expectedMembers, $groupsInfo) { + ->willReturnCallback(function ($group) use ($groupsInfo) { if (isset($groupsInfo[$group])) { return $groupsInfo[$group]; } return []; }); - $access->connection = $this->createMock(Connection::class); - $access->connection->expects($this->any()) + $this->access->connection->expects($this->any()) ->method('__get') - ->willReturnCallback(function ($name) { + ->willReturnCallback(function (string $name) { if ($name === 'ldapNestedGroups') { return 1; } elseif ($name === 'ldapGroupMemberAssocAttr') { @@ -1334,35 +1334,32 @@ class Group_LDAPTest extends TestCase { return null; }); - /** @var GroupPluginManager $pluginManager */ - $pluginManager = $this->createMock(GroupPluginManager::class); - - $ldap = new GroupLDAP($access, $pluginManager); - $resultingMembers = $this->invokePrivate($ldap, '_groupMembers', [$groupDN]); + $this->initBackend(); + 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'; - $access = $this->getAccessMock(); - $access->expects($this->atLeastOnce()) + $this->access->expects($this->atLeastOnce()) ->method('readAttribute') ->willReturn($ldapResult); - $access->connection = $this->createMock(Connection::class); - $access->connection->expects($this->any()) + $this->access->connection->expects($this->any()) ->method('__get') ->willReturnCallback(function ($name) { if ($name === 'ldapGroupMemberAssocAttr') { @@ -1375,14 +1372,11 @@ class Group_LDAPTest extends TestCase { return null; }); - $access->expects($this->any()) + $this->access->expects($this->any()) ->method('groupname2dn') ->willReturn('fakedn'); - /** @var GroupPluginManager $pluginManager */ - $pluginManager = $this->createMock(GroupPluginManager::class); - - $ldap = new GroupLDAP($access, $pluginManager); - $this->assertSame($expected, $ldap->getDisplayName($gid)); + $this->initBackend(); + $this->assertSame($expected, $this->groupBackend->getDisplayName($gid)); } } diff --git a/apps/user_ldap/tests/HelperTest.php b/apps/user_ldap/tests/HelperTest.php index e8ccf0dfbcb..adea600d900 100644 --- a/apps/user_ldap/tests/HelperTest.php +++ b/apps/user_ldap/tests/HelperTest.php @@ -1,79 +1,69 @@ <?php + +declare(strict_types=1); /** - * @copyright Copyright (c) 2016 Roeland Jago Douma <roeland@famdouma.nl> - * - * @author Christoph Wurst <christoph@winzerhof-wurst.at> - * @author Joas Schilling <coding@schilljs.com> - * @author Morris Jobke <hey@morrisjobke.de> - * @author Roeland Jago Douma <roeland@famdouma.nl> - * - * @license GNU AGPL version 3 or any later version - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see <http://www.gnu.org/licenses/>. - * + * SPDX-FileCopyrightText: 2016 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: AGPL-3.0-or-later */ 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'; } @@ -85,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 e22678620c1..00f8be18586 100644 --- a/apps/user_ldap/tests/Integration/AbstractIntegrationTest.php +++ b/apps/user_ldap/tests/Integration/AbstractIntegrationTest.php @@ -1,48 +1,32 @@ <?php + /** - * @copyright Copyright (c) 2016, ownCloud, Inc. - * - * @author Arthur Schiwon <blizzz@arthur-schiwon.de> - * @author Christoph Wurst <christoph@winzerhof-wurst.at> - * @author Joas Schilling <coding@schilljs.com> - * @author Morris Jobke <hey@morrisjobke.de> - * @author Roeland Jago Douma <roeland@famdouma.nl> - * @author root <root@localhost.localdomain> - * @author Vinicius Cubas Brand <vinicius@eita.org.br> - * - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see <http://www.gnu.org/licenses/> - * + * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors + * SPDX-FileCopyrightText: 2016 ownCloud, Inc. + * SPDX-License-Identifier: AGPL-3.0-only */ 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 */ @@ -54,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, @@ -76,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(); @@ -121,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->getAvatarManager(), - 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) ); } @@ -136,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(), \OC::$server->getLogger()); + $this->access = new Access($this->connection, $this->ldap, $this->userManager, $this->helper, Server::get(IConfig::class), Server::get(LoggerInterface::class)); } /** @@ -155,7 +143,7 @@ abstract class AbstractIntegrationTest { $methods = get_class_methods($this); $atLeastOneCaseRan = false; foreach ($methods as $method) { - if (strpos($method, 'case') === 0) { + if (str_starts_with($method, 'case')) { print("running $method " . PHP_EOL); try { if (!$this->$method()) { diff --git a/apps/user_ldap/tests/Integration/Bootstrap.php b/apps/user_ldap/tests/Integration/Bootstrap.php index 62537989171..ef0909d4bea 100644 --- a/apps/user_ldap/tests/Integration/Bootstrap.php +++ b/apps/user_ldap/tests/Integration/Bootstrap.php @@ -1,25 +1,9 @@ <?php + /** - * @copyright Copyright (c) 2016 Arthur Schiwon <blizzz@arthur-schiwon.de> - * - * @author Arthur Schiwon <blizzz@arthur-schiwon.de> - * - * @license GNU AGPL version 3 or any later version - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see <http://www.gnu.org/licenses/>. - * + * 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 fa46f73054c..3eec3df675a 100644 --- a/apps/user_ldap/tests/Integration/ExceptionOnLostConnection.php +++ b/apps/user_ldap/tests/Integration/ExceptionOnLostConnection.php @@ -1,32 +1,16 @@ <?php + /** - * @copyright Copyright (c) 2016, ownCloud, Inc. - * - * @author Arthur Schiwon <blizzz@arthur-schiwon.de> - * @author Christoph Wurst <christoph@winzerhof-wurst.at> - * @author Joas Schilling <coding@schilljs.com> - * @author Morris Jobke <hey@morrisjobke.de> - * @author Roeland Jago Douma <roeland@famdouma.nl> - * - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see <http://www.gnu.org/licenses/> - * + * SPDX-FileCopyrightText: 2017-2024 Nextcloud GmbH and Nextcloud contributors + * SPDX-FileCopyrightText: 2016 ownCloud, Inc. + * SPDX-License-Identifier: AGPL-3.0-only */ namespace OCA\User_LDAP\Tests\Integration; use OC\ServerNotAvailableException; use OCA\User_LDAP\LDAP; +use OCP\App\IAppManager; +use OCP\Server; /** * Class ExceptionOnLostConnection @@ -39,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(); } @@ -95,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); @@ -135,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 eb70c774e25..e1529384239 100644 --- a/apps/user_ldap/tests/Integration/Lib/IntegrationTestAttributeDetection.php +++ b/apps/user_ldap/tests/Integration/Lib/IntegrationTestAttributeDetection.php @@ -1,35 +1,25 @@ <?php + /** - * @copyright Copyright (c) 2017 Arthur Schiwon <blizzz@arthur-schiwon.de> - * - * @author Arthur Schiwon <blizzz@arthur-schiwon.de> - * @author Morris Jobke <hey@morrisjobke.de> - * - * @license GNU AGPL version 3 or any later version - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see <http://www.gnu.org/licenses/>. - * + * 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; use OCA\User_LDAP\Mapping\GroupMapping; use OCA\User_LDAP\Mapping\UserMapping; 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\IConfig; +use OCP\IDBConnection; +use OCP\IGroupManager; +use OCP\IUserManager; +use OCP\Server; +use Psr\Log\LoggerInterface; require_once __DIR__ . '/../Bootstrap.php'; @@ -43,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->query(UserPluginManager::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)); - $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'; } @@ -73,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/IntegrationTestCountUsersByLoginName.php b/apps/user_ldap/tests/Integration/Lib/IntegrationTestCountUsersByLoginName.php index c02ac5ccdae..8a1093e4304 100644 --- a/apps/user_ldap/tests/Integration/Lib/IntegrationTestCountUsersByLoginName.php +++ b/apps/user_ldap/tests/Integration/Lib/IntegrationTestCountUsersByLoginName.php @@ -1,24 +1,9 @@ <?php + /** - * @copyright Copyright (c) 2016, ownCloud, Inc. - * - * @author Arthur Schiwon <blizzz@arthur-schiwon.de> - * @author Joas Schilling <coding@schilljs.com> - * - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see <http://www.gnu.org/licenses/> - * + * SPDX-FileCopyrightText: 2017-2024 Nextcloud GmbH and Nextcloud contributors + * SPDX-FileCopyrightText: 2016 ownCloud, Inc. + * SPDX-License-Identifier: AGPL-3.0-only */ namespace OCA\User_LDAP\Tests\Integration\Lib; diff --git a/apps/user_ldap/tests/Integration/Lib/IntegrationTestFetchUsersByLoginName.php b/apps/user_ldap/tests/Integration/Lib/IntegrationTestFetchUsersByLoginName.php index 36c8ab4c0d3..1c2d7145ddf 100644 --- a/apps/user_ldap/tests/Integration/Lib/IntegrationTestFetchUsersByLoginName.php +++ b/apps/user_ldap/tests/Integration/Lib/IntegrationTestFetchUsersByLoginName.php @@ -1,38 +1,25 @@ <?php + /** - * @copyright Copyright (c) 2016, ownCloud, Inc. - * - * @author Arthur Schiwon <blizzz@arthur-schiwon.de> - * @author Joas Schilling <coding@schilljs.com> - * @author Morris Jobke <hey@morrisjobke.de> - * @author Roeland Jago Douma <roeland@famdouma.nl> - * - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see <http://www.gnu.org/licenses/> - * + * SPDX-FileCopyrightText: 2017-2024 Nextcloud GmbH and Nextcloud contributors + * SPDX-FileCopyrightText: 2016 ownCloud, Inc. + * SPDX-License-Identifier: AGPL-3.0-only */ namespace OCA\User_LDAP\Tests\Integration\Lib; use OCA\User_LDAP\Mapping\UserMapping; 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 */ @@ -46,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->query(UserPluginManager::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 b941fa6fc66..3e21d22fca3 100644 --- a/apps/user_ldap/tests/Integration/Lib/IntegrationTestPaging.php +++ b/apps/user_ldap/tests/Integration/Lib/IntegrationTestPaging.php @@ -1,39 +1,24 @@ <?php + /** - * @copyright Copyright (c) 2016, ownCloud, Inc. - * - * @author Arthur Schiwon <blizzz@arthur-schiwon.de> - * @author Christoph Wurst <christoph@winzerhof-wurst.at> - * @author Joas Schilling <coding@schilljs.com> - * @author Morris Jobke <hey@morrisjobke.de> - * @author Roeland Jago Douma <roeland@famdouma.nl> - * - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see <http://www.gnu.org/licenses/> - * + * SPDX-FileCopyrightText: 2017-2024 Nextcloud GmbH and Nextcloud contributors + * SPDX-FileCopyrightText: 2016 ownCloud, Inc. + * SPDX-License-Identifier: AGPL-3.0-only */ namespace OCA\User_LDAP\Tests\Integration\Lib; use OCA\User_LDAP\Mapping\UserMapping; 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 */ @@ -50,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->query(UserPluginManager::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 ec1cebbe087..6726143a449 100644 --- a/apps/user_ldap/tests/Integration/Lib/User/IntegrationTestUserAvatar.php +++ b/apps/user_ldap/tests/Integration/Lib/User/IntegrationTestUserAvatar.php @@ -1,46 +1,31 @@ <?php + /** - * @copyright Copyright (c) 2016, ownCloud, Inc. - * - * @author Arthur Schiwon <blizzz@arthur-schiwon.de> - * @author Christoph Wurst <christoph@winzerhof-wurst.at> - * @author Joas Schilling <coding@schilljs.com> - * @author Morris Jobke <hey@morrisjobke.de> - * @author Roeland Jago Douma <roeland@famdouma.nl> - * @author Roger Szabo <roger.szabo@web.de> - * @author Thomas Müller <thomas.mueller@tmit.eu> - * - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see <http://www.gnu.org/licenses/> - * + * SPDX-FileCopyrightText: 2017-2024 Nextcloud GmbH and Nextcloud contributors + * SPDX-FileCopyrightText: 2016 ownCloud, Inc. + * SPDX-License-Identifier: AGPL-3.0-only */ 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; use OCA\User_LDAP\User\Manager; 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; /** @@ -50,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->query(UserPluginManager::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); } /** @@ -76,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->getAvatarManager()->getAvatar($username)->exists()) { - \OC::$server->getAvatarManager()->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 @@ -98,7 +83,7 @@ class IntegrationTestUserAvatar extends AbstractIntegrationTest { $this->execFetchTest($dn, $username, $image); - return \OC::$server->getAvatarManager()->getAvatar($username)->exists(); + return Server::get(IAvatarManager::class)->getAvatar($username)->exists(); } /** @@ -115,7 +100,7 @@ class IntegrationTestUserAvatar extends AbstractIntegrationTest { $this->execFetchTest($dn, $username, $image); - return !\OC::$server->getAvatarManager()->getAvatar($username)->exists(); + return !Server::get(IAvatarManager::class)->getAvatar($username)->exists(); } /** @@ -132,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->getAvatarManager(), + 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 5da672d8a55..9b05298a151 100644 --- a/apps/user_ldap/tests/Integration/Lib/User/IntegrationTestUserCleanUp.php +++ b/apps/user_ldap/tests/Integration/Lib/User/IntegrationTestUserCleanUp.php @@ -1,38 +1,27 @@ <?php + /** - * @copyright Copyright (c) 2016, ownCloud, Inc. - * - * @author Arthur Schiwon <blizzz@arthur-schiwon.de> - * @author Christoph Wurst <christoph@winzerhof-wurst.at> - * @author Morris Jobke <hey@morrisjobke.de> - * - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see <http://www.gnu.org/licenses/> - * + * SPDX-FileCopyrightText: 2017-2024 Nextcloud GmbH and Nextcloud contributors + * SPDX-FileCopyrightText: 2016 ownCloud, Inc. + * SPDX-License-Identifier: AGPL-3.0-only */ namespace OCA\User_LDAP\Tests\Integration\Lib\User; use OCA\User_LDAP\Jobs\CleanUp; use OCA\User_LDAP\Mapping\UserMapping; 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; /** @@ -42,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->query(UserPluginManager::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); } /** @@ -84,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 null === \OC::$server->getUserManager()->get($username); + 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 7353c5bef30..6fbfd9ba51b 100644 --- a/apps/user_ldap/tests/Integration/Lib/User/IntegrationTestUserDisplayName.php +++ b/apps/user_ldap/tests/Integration/Lib/User/IntegrationTestUserDisplayName.php @@ -1,38 +1,26 @@ <?php + /** - * @copyright Copyright (c) 2016, ownCloud, Inc. - * - * @author Arthur Schiwon <blizzz@arthur-schiwon.de> - * @author Christoph Wurst <christoph@winzerhof-wurst.at> - * @author Joas Schilling <coding@schilljs.com> - * @author Morris Jobke <hey@morrisjobke.de> - * - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see <http://www.gnu.org/licenses/> - * + * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors + * SPDX-FileCopyrightText: 2016 ownCloud, Inc. + * SPDX-License-Identifier: AGPL-3.0-only */ namespace OCA\User_LDAP\Tests\Integration\Lib\User; use OCA\User_LDAP\Mapping\UserMapping; 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; /** @@ -42,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->query(UserPluginManager::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); } /** @@ -69,9 +57,9 @@ 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 strpos($displayName, '(Alice@example.com)') !== false; + return str_contains($displayName, '(Alice@example.com)'); } /** @@ -86,9 +74,9 @@ 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 strpos($displayName, '(Boris@example.com)') === false; + return !str_contains($displayName, '(Boris@example.com)'); } /** diff --git a/apps/user_ldap/tests/Integration/readme.md b/apps/user_ldap/tests/Integration/readme.md index e20efef8fdc..d551387c903 100644 --- a/apps/user_ldap/tests/Integration/readme.md +++ b/apps/user_ldap/tests/Integration/readme.md @@ -1,3 +1,8 @@ +<!-- + - SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors + - SPDX-FileCopyrightText: 2015 ownCloud, Inc. + - SPDX-License-Identifier: AGPL-3.0-only + --> # Requirements # Have (as in do copy if not already done) the following files from https://github.com/owncloud/administration/tree/master/ldap-testing copied into the directory "setup-scripts": diff --git a/apps/user_ldap/tests/Integration/run-all.sh b/apps/user_ldap/tests/Integration/run-all.sh index 02bab97e45f..a0739a019eb 100755 --- a/apps/user_ldap/tests/Integration/run-all.sh +++ b/apps/user_ldap/tests/Integration/run-all.sh @@ -1,5 +1,8 @@ #!/bin/bash - +# +# SPDX-FileCopyrightText: 2017 Nextcloud GmbH and Nextcloud contributors +# SPDX-License-Identifier: AGPL-3.0-or-later +# trigger_notification() { which notify-send 1>/dev/null if [[ $? == 1 ]] ; then diff --git a/apps/user_ldap/tests/Integration/run-test.sh b/apps/user_ldap/tests/Integration/run-test.sh index 7a29db25670..1b674aa04f3 100755 --- a/apps/user_ldap/tests/Integration/run-test.sh +++ b/apps/user_ldap/tests/Integration/run-test.sh @@ -1,5 +1,8 @@ #!/bin/sh - +# +# SPDX-FileCopyrightText: 2016 Nextcloud GmbH and Nextcloud contributors +# SPDX-License-Identifier: AGPL-3.0-or-later +# if [ $1 ] ; then TESTSCRIPT=$1 else diff --git a/apps/user_ldap/tests/Integration/setup-scripts/createExplicitGroups.php b/apps/user_ldap/tests/Integration/setup-scripts/createExplicitGroups.php index 69bc90dedb2..819c4c6e860 100644 --- a/apps/user_ldap/tests/Integration/setup-scripts/createExplicitGroups.php +++ b/apps/user_ldap/tests/Integration/setup-scripts/createExplicitGroups.php @@ -1,25 +1,9 @@ <?php + /** - * @copyright Copyright (c) 2016, ownCloud, Inc. - * - * @author Arthur Schiwon <blizzz@arthur-schiwon.de> - * @author Christoph Wurst <christoph@winzerhof-wurst.at> - * @author Morris Jobke <hey@morrisjobke.de> - * - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see <http://www.gnu.org/licenses/> - * + * SPDX-FileCopyrightText: 2019-2024 Nextcloud GmbH and Nextcloud contributors + * SPDX-FileCopyrightText: 2016 ownCloud, Inc. + * SPDX-License-Identifier: AGPL-3.0-only */ if (php_sapi_name() !== 'cli') { print('Only via CLI, please.'); diff --git a/apps/user_ldap/tests/Integration/setup-scripts/createExplicitGroupsDifferentOU.php b/apps/user_ldap/tests/Integration/setup-scripts/createExplicitGroupsDifferentOU.php index e2607b0ccc3..b0a3cd46b4f 100644 --- a/apps/user_ldap/tests/Integration/setup-scripts/createExplicitGroupsDifferentOU.php +++ b/apps/user_ldap/tests/Integration/setup-scripts/createExplicitGroupsDifferentOU.php @@ -1,25 +1,9 @@ <?php + /** - * @copyright Copyright (c) 2016, ownCloud, Inc. - * - * @author Arthur Schiwon <blizzz@arthur-schiwon.de> - * @author Christoph Wurst <christoph@winzerhof-wurst.at> - * @author Morris Jobke <hey@morrisjobke.de> - * - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see <http://www.gnu.org/licenses/> - * + * SPDX-FileCopyrightText: 2019-2024 Nextcloud GmbH and Nextcloud contributors + * SPDX-FileCopyrightText: 2016 ownCloud, Inc. + * SPDX-License-Identifier: AGPL-3.0-only */ if (php_sapi_name() !== 'cli') { print('Only via CLI, please.'); diff --git a/apps/user_ldap/tests/Integration/setup-scripts/createExplicitUsers.php b/apps/user_ldap/tests/Integration/setup-scripts/createExplicitUsers.php index 6160179b9d4..7137bd18a58 100644 --- a/apps/user_ldap/tests/Integration/setup-scripts/createExplicitUsers.php +++ b/apps/user_ldap/tests/Integration/setup-scripts/createExplicitUsers.php @@ -1,25 +1,9 @@ <?php + /** - * @copyright Copyright (c) 2016, ownCloud, Inc. - * - * @author Arthur Schiwon <blizzz@arthur-schiwon.de> - * @author Christoph Wurst <christoph@winzerhof-wurst.at> - * @author Morris Jobke <hey@morrisjobke.de> - * - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see <http://www.gnu.org/licenses/> - * + * SPDX-FileCopyrightText: 2017-2024 Nextcloud GmbH and Nextcloud contributors + * SPDX-FileCopyrightText: 2016 ownCloud, Inc. + * SPDX-License-Identifier: AGPL-3.0-only */ if (php_sapi_name() !== 'cli') { print('Only via CLI, please.'); diff --git a/apps/user_ldap/tests/Integration/setup-scripts/createUsersWithoutDisplayName.php b/apps/user_ldap/tests/Integration/setup-scripts/createUsersWithoutDisplayName.php index 5a36ce24838..18584fbe748 100644 --- a/apps/user_ldap/tests/Integration/setup-scripts/createUsersWithoutDisplayName.php +++ b/apps/user_ldap/tests/Integration/setup-scripts/createUsersWithoutDisplayName.php @@ -1,24 +1,9 @@ <?php + /** - * @copyright Copyright (c) 2016, ownCloud, Inc. - * - * @author Arthur Schiwon <blizzz@arthur-schiwon.de> - * @author Christoph Wurst <christoph@winzerhof-wurst.at> - * - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see <http://www.gnu.org/licenses/> - * + * SPDX-FileCopyrightText: 2019-2024 Nextcloud GmbH and Nextcloud contributors + * SPDX-FileCopyrightText: 2016 ownCloud, Inc. + * SPDX-License-Identifier: AGPL-3.0-only */ if (php_sapi_name() !== 'cli') { print('Only via CLI, please.'); diff --git a/apps/user_ldap/tests/Jobs/CleanUpTest.php b/apps/user_ldap/tests/Jobs/CleanUpTest.php index f70d65a6ea2..5a1e563a1e8 100644 --- a/apps/user_ldap/tests/Jobs/CleanUpTest.php +++ b/apps/user_ldap/tests/Jobs/CleanUpTest.php @@ -1,26 +1,10 @@ <?php + +declare(strict_types=1); /** - * @copyright Copyright (c) 2016, ownCloud, Inc. - * - * @author Arthur Schiwon <blizzz@arthur-schiwon.de> - * @author Christoph Wurst <christoph@winzerhof-wurst.at> - * @author Joas Schilling <coding@schilljs.com> - * @author Roeland Jago Douma <roeland@famdouma.nl> - * - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see <http://www.gnu.org/licenses/> - * + * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors + * SPDX-FileCopyrightText: 2016 ownCloud, Inc. + * SPDX-License-Identifier: AGPL-3.0-only */ namespace OCA\User_LDAP\Tests\Jobs; @@ -29,20 +13,19 @@ use OCA\User_LDAP\Helper; use OCA\User_LDAP\Jobs\CleanUp; use OCA\User_LDAP\User\DeletedUsersIndex; use OCA\User_LDAP\User_Proxy; +use OCP\AppFramework\Utility\ITimeFactory; use OCP\IConfig; 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['userBackend'], $this->mocks['deletedUsersIndex']); + $this->bgJob = new CleanUp($this->mocks['timeFactory'], $this->mocks['userBackend'], $this->mocks['deletedUsersIndex']); $this->bgJob->setArguments($this->mocks); } @@ -53,12 +36,13 @@ class CleanUpTest extends TestCase { $this->mocks['ocConfig'] = $this->createMock(IConfig::class); $this->mocks['db'] = $this->createMock(IDBConnection::class); $this->mocks['helper'] = $this->createMock(Helper::class); + $this->mocks['timeFactory'] = $this->createMock(ITimeFactory::class); } /** * 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); @@ -74,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'); @@ -89,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); @@ -105,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); @@ -121,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); } @@ -129,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 5592a2531bc..f6ecf984ab0 100644 --- a/apps/user_ldap/tests/Jobs/SyncTest.php +++ b/apps/user_ldap/tests/Jobs/SyncTest.php @@ -1,27 +1,8 @@ <?php + /** - * @copyright Copyright (c) 2017 Arthur Schiwon <blizzz@arthur-schiwon.de> - * - * @author Arthur Schiwon <blizzz@arthur-schiwon.de> - * @author Christoph Wurst <christoph@winzerhof-wurst.at> - * @author Morris Jobke <hey@morrisjobke.de> - * @author Roeland Jago Douma <roeland@famdouma.nl> - * - * @license GNU AGPL version 3 or any later version - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see <http://www.gnu.org/licenses/>. - * + * SPDX-FileCopyrightText: 2017 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: AGPL-3.0-or-later */ namespace OCA\User_LDAP\Tests\Jobs; @@ -34,41 +15,35 @@ use OCA\User_LDAP\Jobs\Sync; 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(); @@ -82,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->userManager); + $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 @@ -121,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()) @@ -154,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 ], @@ -164,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); @@ -181,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') @@ -206,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 [ @@ -219,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'); @@ -251,7 +234,7 @@ class SyncTest extends TestCase { } } - public function testQualifiesToRun() { + public function testQualifiesToRun(): void { $cycleData = ['prefix' => 's01']; $this->config->expects($this->exactly(2)) @@ -263,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 [[ @@ -295,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) { @@ -325,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') @@ -342,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); @@ -355,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/Jobs/UpdateGroupsTest.php b/apps/user_ldap/tests/Jobs/UpdateGroupsTest.php deleted file mode 100644 index 9c9c62b0d0e..00000000000 --- a/apps/user_ldap/tests/Jobs/UpdateGroupsTest.php +++ /dev/null @@ -1,190 +0,0 @@ -<?php - -declare(strict_types=1); - -/** - * @copyright Copyright (c) 2020 Arthur Schiwon <blizzz@arthur-schiwon.de> - * - * @author Arthur Schiwon <blizzz@arthur-schiwon.de> - * @author Joas Schilling <coding@schilljs.com> - * - * @license GNU AGPL version 3 or any later version - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see <http://www.gnu.org/licenses/>. - * - */ -namespace OCA\user_ldap\tests\Jobs; - -use OCA\User_LDAP\Group_Proxy; -use OCA\User_LDAP\Jobs\UpdateGroups; -use OCP\DB\IResult; -use OCP\DB\QueryBuilder\IExpressionBuilder; -use OCP\DB\QueryBuilder\IQueryBuilder; -use OCP\EventDispatcher\IEventDispatcher; -use OCP\Group\Events\UserAddedEvent; -use OCP\Group\Events\UserRemovedEvent; -use OCP\IDBConnection; -use OCP\IGroup; -use OCP\IGroupManager; -use OCP\IUser; -use OCP\IUserManager; -use Psr\Log\LoggerInterface; -use Test\TestCase; - -class UpdateGroupsTest extends TestCase { - - /** @var Group_Proxy|\PHPUnit\Framework\MockObject\MockObject */ - protected $groupBackend; - /** @var IEventDispatcher|\PHPUnit\Framework\MockObject\MockObject */ - protected $dispatcher; - /** @var IGroupManager|\PHPUnit\Framework\MockObject\MockObject */ - protected $groupManager; - /** @var IUserManager|\PHPUnit\Framework\MockObject\MockObject */ - protected $userManager; - /** @var LoggerInterface|\PHPUnit\Framework\MockObject\MockObject */ - protected $logger; - /** @var IDBConnection|\PHPUnit\Framework\MockObject\MockObject */ - protected $dbc; - - /** @var UpdateGroups */ - protected $updateGroupsJob; - - public function setUp(): void { - $this->groupBackend = $this->createMock(Group_Proxy::class); - $this->dispatcher = $this->createMock(IEventDispatcher::class); - $this->groupManager = $this->createMock(IGroupManager::class); - $this->userManager = $this->createMock(IUserManager::class); - $this->logger = $this->createMock(LoggerInterface::class); - $this->dbc = $this->createMock(IDBConnection::class); - - $this->updateGroupsJob = new UpdateGroups( - $this->groupBackend, - $this->dispatcher, - $this->groupManager, - $this->userManager, - $this->logger, - $this->dbc - ); - } - - public function testHandleKnownGroups() { - $knownGroups = [ - 'emptyGroup' => \serialize([]), - 'stableGroup' => \serialize(['userA', 'userC', 'userE']), - 'groupWithAdditions' => \serialize(['userA', 'userC', 'userE']), - 'groupWithRemovals' => \serialize(['userA', 'userC', 'userDeleted', 'userE']), - 'groupWithAdditionsAndRemovals' => \serialize(['userA', 'userC', 'userE']), - 'vanishedGroup' => \serialize(['userB', 'userDeleted']) - ]; - $knownGroupsDB = []; - foreach ($knownGroups as $gid => $members) { - $knownGroupsDB[] = [ - 'owncloudname' => $gid, - 'owncloudusers' => $members - ]; - } - $actualGroups = [ - 'emptyGroup' => [], - 'stableGroup' => ['userA', 'userC', 'userE'], - 'groupWithAdditions' => ['userA', 'userC', 'userE', 'userF'], - 'groupWithRemovals' => ['userA', 'userE'], - 'groupWithAdditionsAndRemovals' => ['userC', 'userE', 'userF'], - 'newGroup' => ['userB', 'userF'], - ]; - $groups = array_intersect(array_keys($knownGroups), array_keys($actualGroups)); - - /** @var IQueryBuilder|\PHPUnit\Framework\MockObject\MockObject $updateQb */ - $updateQb = $this->createMock(IQueryBuilder::class); - $updateQb->expects($this->once()) - ->method('update') - ->willReturn($updateQb); - $updateQb->expects($this->once()) - ->method('set') - ->willReturn($updateQb); - $updateQb->expects($this->once()) - ->method('where') - ->willReturn($updateQb); - // three groups need to be updated - $updateQb->expects($this->exactly(3)) - ->method('setParameters'); - $updateQb->expects($this->exactly(3)) - ->method('execute'); - $updateQb->expects($this->any()) - ->method('expr') - ->willReturn($this->createMock(IExpressionBuilder::class)); - - $stmt = $this->createMock(IResult::class); - $stmt->expects($this->once()) - ->method('fetchAll') - ->willReturn($knownGroupsDB); - - $selectQb = $this->createMock(IQueryBuilder::class); - $selectQb->expects($this->once()) - ->method('select') - ->willReturn($selectQb); - $selectQb->expects($this->once()) - ->method('from') - ->willReturn($selectQb); - $selectQb->expects($this->once()) - ->method('execute') - ->willReturn($stmt); - - $this->dbc->expects($this->any()) - ->method('getQueryBuilder') - ->willReturnOnConsecutiveCalls($updateQb, $selectQb); - - $this->groupBackend->expects($this->any()) - ->method('usersInGroup') - ->willReturnCallback(function ($groupID) use ($actualGroups) { - return isset($actualGroups[$groupID]) ? $actualGroups[$groupID] : []; - }); - - $this->groupManager->expects($this->any()) - ->method('get') - ->willReturnCallback(function (string $groupId): ?IGroup { - if ($groupId === 'vanishedGroup') { - return null; - } - return $this->createMock(IGroup::class); - }); - - $this->userManager->expects($this->exactly(5)) - ->method('get') - ->willReturnCallback(function (string $userId) { - if ($userId === 'userDeleted') { - // user already deleted - return null; - } - return $this->createMock(IUser::class); - }); - - $addedEvents = 0; - $removedEvents = 0; - $this->dispatcher->expects($this->exactly(4)) - ->method('dispatchTyped') - ->willReturnCallback(function ($event) use (&$addedEvents, &$removedEvents) { - if ($event instanceof UserRemovedEvent) { - $removedEvents++; - } elseif ($event instanceof UserAddedEvent) { - $addedEvents++; - } - }); - - $this->invokePrivate($this->updateGroupsJob, 'handleKnownGroups', [$groups]); - - $this->assertSame(2, $removedEvents); - $this->assertSame(2, $addedEvents); - // and no event for the user that is already deleted, the DB is nevertheless updated, hence 5 - } -} diff --git a/apps/user_ldap/tests/LDAPGroupPluginDummy.php b/apps/user_ldap/tests/LDAPGroupPluginDummy.php index 25350bfc16a..5ea1a491f14 100644 --- a/apps/user_ldap/tests/LDAPGroupPluginDummy.php +++ b/apps/user_ldap/tests/LDAPGroupPluginDummy.php @@ -1,24 +1,9 @@ <?php + +declare(strict_types=1); /** - * @copyright Copyright (c) 2017 EITA Cooperative (eita.org.br) - * - * @author Vinicius Cubas Brand <vinicius@eita.org.br> - * - * @license GNU AGPL version 3 or any later version - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see <http://www.gnu.org/licenses/>. - * + * SPDX-FileCopyrightText: 2017 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: AGPL-3.0-or-later */ namespace OCA\User_LDAP\Tests; diff --git a/apps/user_ldap/tests/LDAPProviderTest.php b/apps/user_ldap/tests/LDAPProviderTest.php index 59f51f204bf..57323e374aa 100644 --- a/apps/user_ldap/tests/LDAPProviderTest.php +++ b/apps/user_ldap/tests/LDAPProviderTest.php @@ -1,45 +1,29 @@ <?php + +declare(strict_types=1); /** - * @copyright Copyright (c) 2016, Roger Szabo (roger.szabo@web.de) - * - * @author Arthur Schiwon <blizzz@arthur-schiwon.de> - * @author Christoph Wurst <christoph@winzerhof-wurst.at> - * @author Joas Schilling <coding@schilljs.com> - * @author Julius Härtl <jus@bitgrid.net> - * @author Roeland Jago Douma <roeland@famdouma.nl> - * @author root <root@localhost.localdomain> - * @author Vinicius Cubas Brand <vinicius@eita.org.br> - * - * @license GNU AGPL version 3 or any later version - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see <http://www.gnu.org/licenses/>. - * + * 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 Symfony\Component\EventDispatcher\EventDispatcherInterface; +use OCP\Server; +use Psr\Log\LoggerInterface; /** * Class LDAPProviderTest @@ -49,39 +33,29 @@ use Symfony\Component\EventDispatcher\EventDispatcherInterface; * @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(); - $server->expects($this->at(1)) - ->method('getBackends') - ->willReturn([$userBackend]); + ->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(EventDispatcherInterface::class), $this->createMock(ICacheFactory::class), $this->createMock(IEventDispatcher::class), + $this->createMock(LoggerInterface::class), ]) ->getMock(); $userManager->expects($this->any()) @@ -92,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()) @@ -110,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()); @@ -131,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(); - $userBackend->expects($this->at(0)) - ->method('userExists') - ->willReturn(true); - $userBackend->expects($this->at(2)) + + 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->any()) - ->method($this->anything()) - ->willReturnSelf(); + ->method('getLDAPAccess') + ->willReturn($userAccess); $server = $this->getServerMock($userBackend, $this->getDefaultGroupBackendMock()); @@ -154,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(); @@ -175,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(); - $groupBackend->expects($this->at(0)) - ->method('groupExists') - ->willReturn(true); - $groupBackend->expects($this->at(2)) + $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->any()) - ->method($this->anything()) - ->willReturnSelf(); + ->method('getLDAPAccess') + ->willReturn($groupAccess); $server = $this->getServerMock($userBackend, $groupBackend); @@ -203,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'); @@ -219,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( @@ -235,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( @@ -252,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()); @@ -268,35 +233,33 @@ 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); + $ldapConnection = ldap_connect('ldap://example.com'); $userBackend->expects($this->any()) ->method('getNewLDAPConnection') - ->willReturn(true); + ->willReturn($ldapConnection); $server = $this->getServerMock($userBackend, $this->getDefaultGroupBackendMock()); $ldapProvider = $this->getLDAPProvider($server); - $this->assertTrue($ldapProvider->getLDAPConnection('existing_user')); + $this->assertEquals($ldapConnection, $ldapProvider->getLDAPConnection('existing_user')); } - 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(); @@ -308,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(); @@ -322,25 +282,26 @@ class LDAPProviderTest extends \Test\TestCase { ->method('groupExists') ->willReturn(true); + $ldapConnection = ldap_connect('ldap://example.com'); $groupBackend->expects($this->any()) ->method('getNewLDAPConnection') - ->willReturn(true); + ->willReturn($ldapConnection); $server = $this->getServerMock($userBackend, $groupBackend); $ldapProvider = $this->getLDAPProvider($server); - $this->assertTrue($ldapProvider->getGroupLDAPConnection('existing_group')); + $this->assertEquals($ldapConnection, $ldapProvider->getGroupLDAPConnection('existing_group')); } - 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()); @@ -349,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) { @@ -378,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); @@ -396,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()); @@ -412,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) { @@ -434,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); @@ -452,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()); @@ -468,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->at(0)) - ->method('userExists') - ->willReturn(true); - $userBackend->expects($this->at(3)) + 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('userExists') + ->willReturn(true); $userBackend->expects($this->any()) - ->method($this->anything()) - ->willReturnSelf(); + ->method('getLDAPAccess') + ->willReturn($access); $server = $this->getServerMock($userBackend, $this->getDefaultGroupBackendMock()); @@ -491,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); @@ -510,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->at(0)) + $groupBackend->expects($this->once()) ->method('groupExists') ->willReturn(true); - $groupBackend->expects($this->at(3)) - ->method('clearCache') - ->willReturn(true); $groupBackend->expects($this->any()) - ->method($this->anything()) - ->willReturnSelf(); + ->method('getLDAPAccess') + ->willReturn($access); $server = $this->getServerMock($userBackend, $groupBackend); @@ -535,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'); @@ -550,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); @@ -563,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); @@ -577,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); @@ -593,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->at(0)) + $userBackend->expects($this->once()) ->method('userExists') ->willReturn(true); - $userBackend->expects($this->at(3)) - ->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()); @@ -615,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); @@ -631,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->at(0)) + $userBackend->expects($this->once()) ->method('userExists') ->willReturn(true); - $userBackend->expects($this->at(3)) - ->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()); @@ -653,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); @@ -674,25 +652,29 @@ 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(); - $groupBackend->expects($this->at(0)) + $groupBackend->expects($this->once()) ->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); @@ -700,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'); @@ -716,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') @@ -741,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') @@ -778,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') @@ -815,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') @@ -852,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 876ea9b1f68..6da592ad6a1 100644 --- a/apps/user_ldap/tests/LDAPTest.php +++ b/apps/user_ldap/tests/LDAPTest.php @@ -1,46 +1,27 @@ <?php + +declare(strict_types=1); /** - * @copyright Copyright (c) 2016 Lukas Reschke <lukas@statuscode.ch> - * - * @author Arthur Schiwon <blizzz@arthur-schiwon.de> - * @author Christoph Wurst <christoph@winzerhof-wurst.at> - * @author Lukas Reschke <lukas@statuscode.ch> - * @author Morris Jobke <hey@morrisjobke.de> - * @author Roeland Jago Douma <roeland@famdouma.nl> - * - * @license GNU AGPL version 3 or any later version - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see <http://www.gnu.org/licenses/>. - * + * SPDX-FileCopyrightText: 2016 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: AGPL-3.0-or-later */ 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', @@ -52,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; }; @@ -69,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); }); @@ -80,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 def10820784..8d4870406ae 100644 --- a/apps/user_ldap/tests/LDAPUserPluginDummy.php +++ b/apps/user_ldap/tests/LDAPUserPluginDummy.php @@ -1,24 +1,9 @@ <?php + +declare(strict_types=1); /** - * @copyright Copyright (c) 2017 EITA Cooperative (eita.org.br) - * - * @author Vinicius Cubas Brand <vinicius@eita.org.br> - * - * @license GNU AGPL version 3 or any later version - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see <http://www.gnu.org/licenses/>. - * + * SPDX-FileCopyrightText: 2017 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: AGPL-3.0-or-later */ namespace OCA\User_LDAP\Tests; @@ -56,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 0d21172445f..8efee4e2085 100644 --- a/apps/user_ldap/tests/Mapping/AbstractMappingTest.php +++ b/apps/user_ldap/tests/Mapping/AbstractMappingTestCase.php @@ -1,41 +1,24 @@ <?php + +declare(strict_types=1); /** - * @copyright Copyright (c) 2016, ownCloud, Inc. - * - * @author Aaron Wood <aaronjwood@gmail.com> - * @author Arthur Schiwon <blizzz@arthur-schiwon.de> - * @author Christoph Wurst <christoph@winzerhof-wurst.at> - * @author Joas Schilling <coding@schilljs.com> - * @author Roeland Jago Douma <roeland@famdouma.nl> - * @author Stefan Weil <sw@weilnetz.de> - * - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see <http://www.gnu.org/licenses/> - * + * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors + * SPDX-FileCopyrightText: 2016 ownCloud, Inc. + * SPDX-License-Identifier: AGPL-3.0-only */ 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); @@ -47,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', @@ -65,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); @@ -82,14 +63,14 @@ abstract class AbstractMappingTest extends \Test\TestCase { } /** - * initalizes environment for a test run and returns an array with + * initializes environment for a test run and returns an array with * 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 @@ -103,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 @@ -123,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) { @@ -143,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) { @@ -171,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'; @@ -206,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(); @@ -226,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(); @@ -240,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++; }; @@ -263,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(); @@ -300,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 2bb9445d1ee..5729058d10e 100644 --- a/apps/user_ldap/tests/Mapping/GroupMappingTest.php +++ b/apps/user_ldap/tests/Mapping/GroupMappingTest.php @@ -1,29 +1,15 @@ <?php + +declare(strict_types=1); /** - * @copyright Copyright (c) 2016, ownCloud, Inc. - * - * @author Arthur Schiwon <blizzz@arthur-schiwon.de> - * @author Joas Schilling <coding@schilljs.com> - * @author Thomas Müller <thomas.mueller@tmit.eu> - * - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see <http://www.gnu.org/licenses/> - * + * SPDX-FileCopyrightText: 2019-2024 Nextcloud GmbH and Nextcloud contributors + * SPDX-FileCopyrightText: 2016 ownCloud, Inc. + * SPDX-License-Identifier: AGPL-3.0-only */ namespace OCA\User_LDAP\Tests\Mapping; use OCA\User_LDAP\Mapping\GroupMapping; +use OCP\IDBConnection; /** * Class GroupMappingTest @@ -32,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 081266cf3f1..4346fe1d23f 100644 --- a/apps/user_ldap/tests/Mapping/UserMappingTest.php +++ b/apps/user_ldap/tests/Mapping/UserMappingTest.php @@ -1,29 +1,16 @@ <?php + +declare(strict_types=1); /** - * @copyright Copyright (c) 2016, ownCloud, Inc. - * - * @author Arthur Schiwon <blizzz@arthur-schiwon.de> - * @author Joas Schilling <coding@schilljs.com> - * @author Thomas Müller <thomas.mueller@tmit.eu> - * - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see <http://www.gnu.org/licenses/> - * + * SPDX-FileCopyrightText: 2019-2024 Nextcloud GmbH and Nextcloud contributors + * SPDX-FileCopyrightText: 2016 ownCloud, Inc. + * SPDX-License-Identifier: AGPL-3.0-only */ namespace OCA\User_LDAP\Tests\Mapping; use OCA\User_LDAP\Mapping\UserMapping; +use OCP\IDBConnection; +use OCP\Support\Subscription\IAssertion; /** * Class UserMappingTest @@ -32,8 +19,8 @@ use OCA\User_LDAP\Mapping\UserMapping; * * @package OCA\User_LDAP\Tests\Mapping */ -class UserMappingTest extends AbstractMappingTest { - public function getMapper(\OCP\IDBConnection $dbMock) { - return new UserMapping($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 7cb666b2514..7a85b885bc1 100644 --- a/apps/user_ldap/tests/Migration/AbstractUUIDFixTest.php +++ b/apps/user_ldap/tests/Migration/AbstractUUIDFixTestCase.php @@ -1,63 +1,33 @@ <?php + +declare(strict_types=1); /** - * @copyright Copyright (c) 2017 Arthur Schiwon <blizzz@arthur-schiwon.de> - * - * @author Arthur Schiwon <blizzz@arthur-schiwon.de> - * @author Morris Jobke <hey@morrisjobke.de> - * @author Roeland Jago Douma <roeland@famdouma.nl> - * - * @license GNU AGPL version 3 or any later version - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see <http://www.gnu.org/licenses/>. - * + * SPDX-FileCopyrightText: 2017 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: AGPL-3.0-or-later */ namespace OCA\User_LDAP\Tests\Migration; use OCA\User_LDAP\Access; use OCA\User_LDAP\Helper; use OCA\User_LDAP\LDAP; -use OCA\User_LDAP\Mapping\GroupMapping; -use OCA\User_LDAP\Mapping\UserMapping; -use OCA\User_LDAP\Migration\UUIDFixUser; -use OCA\User_LDAP\User_Proxy; +use OCA\User_LDAP\Mapping\AbstractMapping; +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 { - /** @var Helper|\PHPUnit\Framework\MockObject\MockObject */ - protected $helper; - - /** @var IConfig|\PHPUnit\Framework\MockObject\MockObject */ - protected $config; - - /** @var LDAP|\PHPUnit\Framework\MockObject\MockObject */ - protected $ldap; - - /** @var UserMapping|GroupMapping|\PHPUnit\Framework\MockObject\MockObject */ - protected $mapper; - - /** @var UUIDFixUser */ - protected $job; - - /** @var User_Proxy|\PHPUnit\Framework\MockObject\MockObject */ - protected $proxy; - - /** @var Access|\PHPUnit\Framework\MockObject\MockObject */ - protected $access; - - /** @var bool */ - protected $isUser = true; +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&MockObject $access; + protected ITimeFactory&MockObject $time; + protected bool $isUser = true; protected function setUp(): void { parent::setUp(); @@ -65,6 +35,7 @@ abstract class AbstractUUIDFixTest extends TestCase { $this->ldap = $this->createMock(LDAP::class); $this->config = $this->createMock(IConfig::class); $this->access = $this->createMock(Access::class); + $this->time = $this->createMock(ITimeFactory::class); $this->helper = $this->createMock(Helper::class); $this->helper->expects($this->any()) @@ -74,13 +45,13 @@ abstract class AbstractUUIDFixTest extends TestCase { } protected function instantiateJob($className) { - $this->job = new $className($this->mapper, $this->proxy); + $this->job = new $className($this->time, $this->mapper, $this->proxy); $this->proxy->expects($this->any()) ->method('getLDAPAccess') ->willReturn($this->access); } - public function testRunSingleRecord() { + public function testRunSingleRecord(): void { $args = [ 'records' => [ 0 => [ @@ -104,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' => [ @@ -127,7 +98,7 @@ abstract class AbstractUUIDFixTest extends TestCase { $this->job->run($args); } - public function testRunRemovedRecord() { + public function testRunRemovedRecord(): void { $args = [ 'records' => [ 0 => [ @@ -149,7 +120,7 @@ abstract class AbstractUUIDFixTest extends TestCase { $this->job->run($args); } - public function testRunManyRecords() { + public function testRunManyRecords(): void { $args = [ 'records' => [ 0 => [ @@ -173,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 0144a259318..89d880f4acb 100644 --- a/apps/user_ldap/tests/Migration/UUIDFixGroupTest.php +++ b/apps/user_ldap/tests/Migration/UUIDFixGroupTest.php @@ -1,32 +1,15 @@ <?php + +declare(strict_types=1); /** - * @copyright Copyright (c) 2017 Arthur Schiwon <blizzz@arthur-schiwon.de> - * - * @author Arthur Schiwon <blizzz@arthur-schiwon.de> - * @author Roeland Jago Douma <roeland@famdouma.nl> - * - * @license GNU AGPL version 3 or any later version - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see <http://www.gnu.org/licenses/>. - * + * 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 @@ -34,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 b13efa14e5c..6215ffcb6a1 100644 --- a/apps/user_ldap/tests/Migration/UUIDFixInsertTest.php +++ b/apps/user_ldap/tests/Migration/UUIDFixInsertTest.php @@ -1,26 +1,9 @@ <?php + +declare(strict_types=1); /** - * @copyright Copyright (c) 2017 Arthur Schiwon <blizzz@arthur-schiwon.de> - * - * @author Arthur Schiwon <blizzz@arthur-schiwon.de> - * @author Morris Jobke <hey@morrisjobke.de> - * @author Roeland Jago Douma <roeland@famdouma.nl> - * - * @license GNU AGPL version 3 or any later version - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see <http://www.gnu.org/licenses/>. - * + * SPDX-FileCopyrightText: 2017 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: AGPL-3.0-or-later */ namespace OCA\User_LDAP\Tests\Migration; @@ -30,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(); @@ -63,22 +38,21 @@ 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), 1 => array_fill(0, 50, $record), - 2 => array_fill(0, 13, $record), + 2 => array_fill(0, 13, $record), ]; $groupBatches = [ @@ -90,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), @@ -113,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') @@ -124,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') @@ -140,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') @@ -151,33 +123,35 @@ 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') ->with(0, 50) ->willReturn($groupBatches[0]); - $this->jobList->expects($this->at(0)) + $this->jobList->expects($this->exactly(5)) ->method('add') - ->willThrowException(new \InvalidArgumentException('Background job arguments can\'t exceed 4000 etc')); - $this->jobList->expects($this->at(1)) - ->method('add') - ->willThrowException(new \InvalidArgumentException('Background job arguments can\'t exceed 4000 etc')); - $this->jobList->expects($this->at(2)) - ->method('add'); - $this->jobList->expects($this->at(3)) - ->method('add'); - $this->jobList->expects($this->at(4)) - ->method('add'); + ->willReturnOnConsecutiveCalls( + $this->throwException(new \InvalidArgumentException('Background job arguments can\'t exceed 4000 etc')), + $this->throwException(new \InvalidArgumentException('Background job arguments can\'t exceed 4000 etc')), + null, + null, + null, + ); /** @var IOutput $out */ $out = $this->createMock(IOutput::class); $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 477bc66f1a9..a582fd677fa 100644 --- a/apps/user_ldap/tests/Migration/UUIDFixUserTest.php +++ b/apps/user_ldap/tests/Migration/UUIDFixUserTest.php @@ -1,25 +1,9 @@ <?php + +declare(strict_types=1); /** - * @copyright Copyright (c) 2017 Arthur Schiwon <blizzz@arthur-schiwon.de> - * - * @author Arthur Schiwon <blizzz@arthur-schiwon.de> - * @author Roeland Jago Douma <roeland@famdouma.nl> - * - * @license GNU AGPL version 3 or any later version - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see <http://www.gnu.org/licenses/>. - * + * SPDX-FileCopyrightText: 2017 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: AGPL-3.0-or-later */ namespace OCA\User_LDAP\Tests\Migration; @@ -33,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 new file mode 100644 index 00000000000..061118f10c1 --- /dev/null +++ b/apps/user_ldap/tests/Service/BirthdateParserServiceTest.php @@ -0,0 +1,51 @@ +<?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; + +use DateTimeImmutable; +use OCA\User_LDAP\Service\BirthdateParserService; +use PHPUnit\Framework\TestCase; + +class BirthdateParserServiceTest extends TestCase { + private BirthdateParserService $service; + + protected function setUp(): void { + parent::setUp(); + + $this->service = new BirthdateParserService(); + } + + public static function parseBirthdateDataProvider(): array { + return [ + ['2024-01-01', new DateTimeImmutable('2024-01-01'), false], + ['20240101', new DateTimeImmutable('2024-01-01'), false], + ['199412161032Z', new DateTimeImmutable('1994-12-16'), false], // LDAP generalized time + ['199412160532-0500', new DateTimeImmutable('1994-12-16'), false], // LDAP generalized time + ['2023-07-31T00:60:59.000Z', null, true], + ['01.01.2024', null, true], + ['01/01/2024', null, true], + ['01 01 2024', null, true], + ['foobar', null, true], + ]; + } + + #[\PHPUnit\Framework\Attributes\DataProvider('parseBirthdateDataProvider')] + public function testParseBirthdate( + string $value, + ?DateTimeImmutable $expected, + bool $shouldThrow, + ): void { + if ($shouldThrow) { + $this->expectException(\InvalidArgumentException::class); + } + + $actual = $this->service->parseBirthdate($value); + $this->assertEquals($expected, $actual); + } +} diff --git a/apps/user_ldap/tests/Service/UpdateGroupsServiceTest.php b/apps/user_ldap/tests/Service/UpdateGroupsServiceTest.php new file mode 100644 index 00000000000..601aee86602 --- /dev/null +++ b/apps/user_ldap/tests/Service/UpdateGroupsServiceTest.php @@ -0,0 +1,137 @@ +<?php + +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; + +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\EventDispatcher\IEventDispatcher; +use OCP\Group\Events\UserAddedEvent; +use OCP\Group\Events\UserRemovedEvent; +use OCP\IGroup; +use OCP\IGroupManager; +use OCP\IUser; +use OCP\IUserManager; +use PHPUnit\Framework\MockObject\MockObject; +use Psr\Log\LoggerInterface; +use Test\TestCase; + +class UpdateGroupsServiceTest extends TestCase { + 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 { + $this->groupBackend = $this->createMock(Group_Proxy::class); + $this->dispatcher = $this->createMock(IEventDispatcher::class); + $this->groupManager = $this->createMock(IGroupManager::class); + $this->userManager = $this->createMock(IUserManager::class); + $this->logger = $this->createMock(LoggerInterface::class); + $this->groupMembershipMapper = $this->createMock(GroupMembershipMapper::class); + + $this->updateGroupsService = new UpdateGroupsService( + $this->groupBackend, + $this->dispatcher, + $this->groupManager, + $this->userManager, + $this->logger, + $this->groupMembershipMapper, + ); + } + + public function testHandleKnownGroups(): void { + $knownGroups = [ + 'emptyGroup' => [], + 'stableGroup' => ['userA', 'userC', 'userE'], + 'groupWithAdditions' => ['userA', 'userC', 'userE'], + 'groupWithRemovals' => ['userA', 'userC', 'userDeleted', 'userE'], + 'groupWithAdditionsAndRemovals' => ['userA', 'userC', 'userE'], + 'vanishedGroup' => ['userB', 'userDeleted'], + ]; + $knownGroupsDB = []; + foreach ($knownGroups as $gid => $members) { + $knownGroupsDB[] = [ + 'owncloudname' => $gid, + 'owncloudusers' => $members + ]; + } + $actualGroups = [ + 'emptyGroup' => [], + 'stableGroup' => ['userA', 'userC', 'userE'], + 'groupWithAdditions' => ['userA', 'userC', 'userE', 'userF'], + 'groupWithRemovals' => ['userA', 'userE'], + 'groupWithAdditionsAndRemovals' => ['userC', 'userE', 'userF'], + 'newGroup' => ['userB', 'userF'], + ]; + $groups = array_intersect(array_keys($knownGroups), array_keys($actualGroups)); + + $this->groupMembershipMapper->expects($this->never()) + ->method('getKnownGroups'); + $this->groupMembershipMapper->expects($this->exactly(5)) + ->method('findGroupMemberships') + ->willReturnCallback( + fn ($group) => array_map( + fn ($userid) => GroupMembership::fromParams(['groupid' => $group,'userid' => $userid]), + $knownGroups[$group] + ) + ); + $this->groupMembershipMapper->expects($this->exactly(3)) + ->method('delete'); + $this->groupMembershipMapper->expects($this->exactly(2)) + ->method('insert'); + + $this->groupBackend->expects($this->any()) + ->method('usersInGroup') + ->willReturnCallback(function ($groupID) use ($actualGroups) { + return $actualGroups[$groupID] ?? []; + }); + + $this->groupManager->expects($this->any()) + ->method('get') + ->willReturnCallback(function (string $groupId): ?IGroup { + if ($groupId === 'vanishedGroup') { + return null; + } + return $this->createMock(IGroup::class); + }); + + $this->userManager->expects($this->exactly(5)) + ->method('get') + ->willReturnCallback(function (string $userId) { + if ($userId === 'userDeleted') { + // user already deleted + return null; + } + return $this->createMock(IUser::class); + }); + + $addedEvents = 0; + $removedEvents = 0; + $this->dispatcher->expects($this->exactly(4)) + ->method('dispatchTyped') + ->willReturnCallback(function ($event) use (&$addedEvents, &$removedEvents): void { + if ($event instanceof UserRemovedEvent) { + $removedEvents++; + } elseif ($event instanceof UserAddedEvent) { + $addedEvents++; + } + }); + + $this->updateGroupsService->handleKnownGroups($groups); + + $this->assertSame(2, $removedEvents); + $this->assertSame(2, $addedEvents); + // and no event for the user that is already deleted, the DB is nevertheless updated, hence 5 + } +} diff --git a/apps/user_ldap/tests/Settings/AdminTest.php b/apps/user_ldap/tests/Settings/AdminTest.php index 44f253ad598..b17e96c1a68 100644 --- a/apps/user_ldap/tests/Settings/AdminTest.php +++ b/apps/user_ldap/tests/Settings/AdminTest.php @@ -1,28 +1,9 @@ <?php + +declare(strict_types=1); /** - * @copyright Copyright (c) 2016 Lukas Reschke <lukas@statuscode.ch> - * - * @author Arthur Schiwon <blizzz@arthur-schiwon.de> - * @author Christoph Wurst <christoph@winzerhof-wurst.at> - * @author Lukas Reschke <lukas@statuscode.ch> - * @author Morris Jobke <hey@morrisjobke.de> - * @author Roeland Jago Douma <roeland@famdouma.nl> - * - * @license GNU AGPL version 3 or any later version - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see <http://www.gnu.org/licenses/>. - * + * SPDX-FileCopyrightText: 2016 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: AGPL-3.0-or-later */ namespace OCA\User_LDAP\Tests\Settings; @@ -30,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; /** @@ -38,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; @@ -73,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 21de15118c8..3f9ae1e56d4 100644 --- a/apps/user_ldap/tests/Settings/SectionTest.php +++ b/apps/user_ldap/tests/Settings/SectionTest.php @@ -1,43 +1,22 @@ <?php + +declare(strict_types=1); /** - * @copyright Copyright (c) 2016 Lukas Reschke <lukas@statuscode.ch> - * - * @author Joas Schilling <coding@schilljs.com> - * @author Lukas Reschke <lukas@statuscode.ch> - * @author Morris Jobke <hey@morrisjobke.de> - * @author Roeland Jago Douma <roeland@famdouma.nl> - * @author Valdnet <47037905+Valdnet@users.noreply.github.com> - * - * @license GNU AGPL version 3 or any later version - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see <http://www.gnu.org/licenses/>. - * + * SPDX-FileCopyrightText: 2016 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: AGPL-3.0-or-later */ 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(); @@ -50,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') @@ -64,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 7d0b49b21c8..b245e52fe6e 100644 --- a/apps/user_ldap/tests/User/DeletedUsersIndexTest.php +++ b/apps/user_ldap/tests/User/DeletedUsersIndexTest.php @@ -1,27 +1,9 @@ <?php + +declare(strict_types=1); /** - * @copyright Copyright (c) 2018 Arthur Schiwon <blizzz@arthur-schiwon.de> - * - * @author Arthur Schiwon <blizzz@arthur-schiwon.de> - * @author Christoph Wurst <christoph@winzerhof-wurst.at> - * @author Morris Jobke <hey@morrisjobke.de> - * @author Roeland Jago Douma <roeland@famdouma.nl> - * - * @license GNU AGPL version 3 or any later version - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see <http://www.gnu.org/licenses/>. - * + * SPDX-FileCopyrightText: 2018 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: AGPL-3.0-or-later */ namespace OCA\User_LDAP\Tests\User; @@ -29,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 @@ -39,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'); @@ -74,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', @@ -102,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 adeabea73e9..bf9d1f5746f 100644 --- a/apps/user_ldap/tests/User/ManagerTest.php +++ b/apps/user_ldap/tests/User/ManagerTest.php @@ -1,36 +1,15 @@ <?php + +declare(strict_types=1); /** - * @copyright Copyright (c) 2016, ownCloud, Inc. - * - * @author Arthur Schiwon <blizzz@arthur-schiwon.de> - * @author Christoph Wurst <christoph@winzerhof-wurst.at> - * @author Joas Schilling <coding@schilljs.com> - * @author Morris Jobke <hey@morrisjobke.de> - * @author Philippe Jung <phil.jung@free.fr> - * @author Roeland Jago Douma <roeland@famdouma.nl> - * @author Roger Szabo <roger.szabo@web.de> - * @author Thomas Müller <thomas.mueller@tmit.eu> - * - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see <http://www.gnu.org/licenses/> - * + * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors + * SPDX-FileCopyrightText: 2016 ownCloud, Inc. + * SPDX-License-Identifier: AGPL-3.0-only */ 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; @@ -41,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; /** @@ -51,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); @@ -112,7 +66,6 @@ class ManagerTest extends \Test\TestCase { /** @noinspection PhpUnhandledExceptionInspection */ $this->manager = new Manager( $this->config, - $this->fileSystemHelper, $this->logger, $this->avatarManager, $this->image, @@ -124,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'], @@ -132,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()) @@ -160,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()) @@ -182,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'; @@ -208,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()) @@ -224,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', @@ -244,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 e1fda3f16ca..223e63421ad 100644 --- a/apps/user_ldap/tests/User/OfflineUserTest.php +++ b/apps/user_ldap/tests/User/OfflineUserTest.php @@ -3,25 +3,8 @@ declare(strict_types=1); /** - * @copyright Copyright (c) 2020 Arthur Schiwon <blizzz@arthur-schiwon.de> - * - * @author Arthur Schiwon <blizzz@arthur-schiwon.de> - * - * @license GNU AGPL version 3 or any later version - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see <http://www.gnu.org/licenses/>. - * + * SPDX-FileCopyrightText: 2020 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: AGPL-3.0-or-later */ namespace OCA\User_LDAP\Tests\User; @@ -30,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'; @@ -59,7 +37,7 @@ class OfflineUserTest extends TestCase { ); } - public function shareOwnerProvider(): array { + public static function shareOwnerProvider(): array { return [ [[], false], [[IShare::TYPE_USER], true], @@ -69,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 e86eb5e9e2e..00edd8b3f9b 100644 --- a/apps/user_ldap/tests/User/UserTest.php +++ b/apps/user_ldap/tests/User/UserTest.php @@ -1,36 +1,16 @@ <?php + +declare(strict_types=1); /** - * @copyright Copyright (c) 2016, ownCloud, Inc. - * - * @author Arthur Schiwon <blizzz@arthur-schiwon.de> - * @author Christoph Wurst <christoph@winzerhof-wurst.at> - * @author Joas Schilling <coding@schilljs.com> - * @author Juan Pablo Villafáñez <jvillafanez@solidgear.es> - * @author Morris Jobke <hey@morrisjobke.de> - * @author Roeland Jago Douma <roeland@famdouma.nl> - * @author Roger Szabo <roger.szabo@web.de> - * @author Thomas Müller <thomas.mueller@tmit.eu> - * - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see <http://www.gnu.org/licenses/> - * + * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors + * SPDX-FileCopyrightText: 2016 ownCloud, Inc. + * SPDX-License-Identifier: AGPL-3.0-only */ 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; @@ -40,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; /** @@ -50,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; @@ -87,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); @@ -99,7 +69,6 @@ class UserTest extends \Test\TestCase { $this->dn, $this->access, $this->config, - $this->filesystemhelper, $this->image, $this->logger, $this->avatarManager, @@ -108,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')) @@ -125,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()) @@ -139,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')) @@ -157,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')) @@ -172,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([ @@ -199,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([ @@ -226,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([ @@ -253,17 +220,13 @@ class UserTest extends \Test\TestCase { $this->user->updateQuota(); } - public function testUpdateQuotaDefaultProvided() { - $this->connection->expects($this->at(0)) - ->method('__get') - ->with($this->equalTo('ldapQuotaAttribute')) - ->willReturn('myquota'); - $this->connection->expects($this->at(1)) - ->method('__get') - ->with($this->equalTo('ldapQuotaDefault')) - ->willReturn('25 GB'); + public function testUpdateQuotaDefaultProvided(): void { $this->connection->expects($this->exactly(2)) - ->method('__get'); + ->method('__get') + ->willReturnMap([ + ['ldapQuotaAttribute', 'myquota'], + ['ldapQuotaDefault', '25 GB'], + ]); $this->access->expects($this->once()) ->method('readAttribute') @@ -284,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([ @@ -311,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([ @@ -339,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([ @@ -363,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)) @@ -392,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([ @@ -422,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([ @@ -449,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([ @@ -476,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([ @@ -497,7 +460,7 @@ class UserTest extends \Test\TestCase { $this->user->updateQuota(); } - //the testUpdateAvatar series also implicitely tests getAvatarImage + //the testUpdateAvatar series also implicitly tests getAvatarImage public function XtestUpdateAvatarJpegPhotoProvided() { $this->access->expects($this->once()) ->method('readAttribute') @@ -532,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') @@ -554,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), @@ -583,15 +542,20 @@ 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'); + $avatar->expects($this->any()) + ->method('exists') + ->willReturn(true); + $avatar->expects($this->any()) + ->method('isCustomAvatar') + ->willReturn(true); - $this->avatarManager->expects($this->never()) - ->method('getAvatar'); + $this->avatarManager->expects($this->any()) + ->method('getAvatar') + ->with($this->uid) + ->willReturn($avatar); $this->connection->expects($this->any()) ->method('resolveRule') @@ -642,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') @@ -664,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) { @@ -697,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'); @@ -755,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()) @@ -778,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) { @@ -808,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'); @@ -822,7 +772,7 @@ class UserTest extends \Test\TestCase { $this->user->updateAvatar(); } - public function extStorageHomeDataProvider() { + public static function extStorageHomeDataProvider(): array { return [ [ 'myFolder', null ], [ '', null, false ], @@ -830,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') @@ -865,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), @@ -877,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), @@ -895,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()); @@ -907,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 ], @@ -915,7 +863,7 @@ class UserTest extends \Test\TestCase { ]; } - public function testProcessAttributes() { + public function testProcessAttributes(): void { $requiredMethods = [ 'updateQuota', 'updateEmail', @@ -926,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([ @@ -980,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')) @@ -1006,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')) @@ -1030,7 +975,7 @@ class UserTest extends \Test\TestCase { } - public function testGetHomePathConfiguredNotAvailableNotAllowed() { + public function testGetHomePathConfiguredNotAvailableNotAllowed(): void { $this->expectException(\Exception::class); $this->connection->expects($this->any()) @@ -1054,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; @@ -1093,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'); @@ -1108,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) { @@ -1127,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' => [], ], ]; @@ -1166,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) { @@ -1191,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' => [], ] ]; @@ -1230,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 98d9c409027..8a065374e61 100644 --- a/apps/user_ldap/tests/UserLDAPPluginTest.php +++ b/apps/user_ldap/tests/UserLDAPPluginTest.php @@ -1,26 +1,9 @@ <?php + +declare(strict_types=1); /** - * @copyright Copyright (c) 2017 EITA Cooperative (eita.org.br) - * - * @author Christoph Wurst <christoph@winzerhof-wurst.at> - * @author Roeland Jago Douma <roeland@famdouma.nl> - * @author Vinicius Cubas Brand <vinicius@eita.org.br> - * - * @license GNU AGPL version 3 or any later version - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see <http://www.gnu.org/licenses/>. - * + * SPDX-FileCopyrightText: 2017 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: AGPL-3.0-or-later */ namespace OCA\User_LDAP\Tests; @@ -28,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()) @@ -63,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()) @@ -85,20 +64,20 @@ 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.'); $pluginManager = $this->getUserPluginManager(); - $pluginManager->createUser('foo','bar'); + $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()) @@ -116,20 +95,20 @@ 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.'); $pluginManager = $this->getUserPluginManager(); - $pluginManager->setPassword('foo','bar'); + $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()) @@ -146,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.'); @@ -155,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()) @@ -176,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.'); @@ -185,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()) @@ -207,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.'); @@ -216,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()) @@ -237,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.'); @@ -246,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()) @@ -264,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.'); @@ -273,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()) @@ -300,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 b00c93e79f0..f8900c3cca4 100644 --- a/apps/user_ldap/tests/User_LDAPTest.php +++ b/apps/user_ldap/tests/User_LDAPTest.php @@ -1,42 +1,20 @@ <?php + +declare(strict_types=1); /** - * @copyright Copyright (c) 2016, ownCloud, Inc. - * - * @author Arthur Schiwon <blizzz@arthur-schiwon.de> - * @author Christoph Wurst <christoph@winzerhof-wurst.at> - * @author Joas Schilling <coding@schilljs.com> - * @author Jörn Friedrich Dreyer <jfd@butonic.de> - * @author Lukas Reschke <lukas@statuscode.ch> - * @author Morris Jobke <hey@morrisjobke.de> - * @author Robin McCorkell <robin@mccorkell.me.uk> - * @author Roeland Jago Douma <roeland@famdouma.nl> - * @author Roger Szabo <roger.szabo@web.de> - * @author Thomas Müller <thomas.mueller@tmit.eu> - * @author Vinicius Cubas Brand <vinicius@eita.org.br> - * - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see <http://www.gnu.org/licenses/> - * + * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors + * SPDX-FileCopyrightText: 2016 ownCloud, Inc. + * SPDX-License-Identifier: AGPL-3.0-only */ 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; use OCA\User_LDAP\User\Manager; use OCA\User_LDAP\User\OfflineUser; use OCA\User_LDAP\User\User; @@ -45,8 +23,13 @@ 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; /** @@ -57,74 +40,68 @@ use Test\TestCase; * @package OCA\User_LDAP\Tests */ class User_LDAPTest extends TestCase { - /** @var User_LDAP */ - protected $backend; - /** @var Access|\PHPUnit\Framework\MockObject\MockObject */ - protected $access; - /** @var OfflineUser|\PHPUnit\Framework\MockObject\MockObject */ - protected $offlineUser; - /** @var IConfig|\PHPUnit\Framework\MockObject\MockObject */ - protected $config; - /** @var INotificationManager|\PHPUnit\Framework\MockObject\MockObject */ - protected $notificationManager; - /** @var Session|\PHPUnit\Framework\MockObject\MockObject */ - protected $session; - /** @var UserPluginManager|\PHPUnit\Framework\MockObject\MockObject */ - protected $pluginManager; - /** @var Connection|\PHPUnit\Framework\MockObject\MockObject */ - protected $connection; - /** @var Manager|\PHPUnit\Framework\MockObject\MockObject */ - protected $userManager; + 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); + + $this->deletedUsersIndex = $this->createMock(DeletedUsersIndex::class); + $this->backend = new User_LDAP( $this->access, - $this->config, $this->notificationManager, - $this->session, - $this->pluginManager + $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([]); @@ -132,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) { @@ -167,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('username2dn') + ->with($this->equalTo('gunslinger')) + ->willReturn('dnOfRoland,dc=test'); $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('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') @@ -199,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); + $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); - \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); - \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(); @@ -233,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); - \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') @@ -251,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); - \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(); @@ -262,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); - \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(); @@ -275,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); - \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(); @@ -288,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); + 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/'; @@ -307,12 +286,12 @@ class User_LDAPTest extends TestCase { ->willReturn($mapping); $this->connection->expects($this->any()) ->method('getConnectionResource') - ->willReturn('this is an ldap link'); + ->willReturn(ldap_connect('ldap://example.com')); - $this->config->expects($this->any()) - ->method('getUserValue') - ->with($uid, 'user_ldap', 'isDeleted') - ->willReturn('1'); + $this->deletedUsersIndex->expects($this->once()) + ->method('isUserMarked') + ->with($uid) + ->willReturn(true); $offlineUser = $this->createMock(OfflineUser::class); $offlineUser->expects($this->once()) @@ -321,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); + $backend = new UserLDAP($this->access, $this->notificationManager, $this->pluginManager, $this->logger, $this->deletedUsersIndex); $result = $backend->deleteUser($uid); $this->assertTrue($result); @@ -330,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); @@ -339,10 +322,10 @@ class User_LDAPTest extends TestCase { ->with('uid') ->willReturn(true); - $this->config->expects($this->once()) - ->method('getUserValue') - ->with('uid', 'user_ldap', 'isDeleted', 0) - ->willReturn(1); + $this->deletedUsersIndex->expects($this->once()) + ->method('isUserMarked') + ->with('uid') + ->willReturn(true); $mapper = $this->createMock(UserMapping::class); $mapper->expects($this->once()) @@ -357,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')); } /** @@ -365,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([]); @@ -409,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); + $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); + $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); + $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); + $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); + $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); - \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); - \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); - \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); - \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); - \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); + 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)); @@ -521,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); + public function testUserExistsForDeleted(): void { + $backend = new UserLDAP($this->access, $this->notificationManager, $this->pluginManager, $this->logger, $this->deletedUsersIndex); $this->prepareMockForUserExists(); $mapper = $this->createMock(UserMapping::class); @@ -535,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); + public function testUserExistsForNeverExisting(): void { + $backend = new UserLDAP($this->access, $this->notificationManager, $this->pluginManager, $this->logger, $this->deletedUsersIndex); $this->prepareMockForUserExists(); $this->access->expects($this->any()) @@ -564,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); + 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()) @@ -582,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); + 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); + public function testGetHomeAbsolutePath(): void { + $backend = new UserLDAP($this->access, $this->notificationManager, $this->pluginManager, $this->logger, $this->deletedUsersIndex); $this->prepareMockForUserExists(); $this->connection->expects($this->any()) @@ -643,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 */ @@ -651,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); + 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') @@ -691,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); + $backend = new UserLDAP($this->access, $this->notificationManager, $this->pluginManager, $this->logger, $this->deletedUsersIndex); $this->prepareMockForUserExists(); $this->connection->expects($this->any()) @@ -725,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()) @@ -744,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); + $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()) @@ -787,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) @@ -810,7 +805,7 @@ class User_LDAPTest extends TestCase { }); /** @noinspection PhpUnhandledExceptionInspection */ - $this->assertEquals($this->backend->getHome('uid'),'result'); + $this->assertEquals($this->backend->getHome('uid'), 'result'); } private function prepareAccessForGetDisplayName() { @@ -826,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); + $backend = new UserLDAP($this->access, $this->notificationManager, $this->pluginManager, $this->logger, $this->deletedUsersIndex); $this->prepareMockForUserExists(); $this->connection->expects($this->any()) @@ -887,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); @@ -905,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) { @@ -927,7 +932,7 @@ class User_LDAPTest extends TestCase { } }); $this->prepareAccessForGetDisplayName(); - $backend = new UserLDAP($this->access, $this->config, $this->notificationManager, $this->session, $this->pluginManager); + $backend = new UserLDAP($this->access, $this->notificationManager, $this->pluginManager, $this->logger, $this->deletedUsersIndex); $this->prepareMockForUserExists(); $this->connection->expects($this->any()) @@ -936,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()) @@ -970,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); @@ -980,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) @@ -998,35 +1013,35 @@ class User_LDAPTest extends TestCase { ->with('uid') ->willReturn('result'); - $this->assertEquals($this->backend->getDisplayName('uid'),'result'); + $this->assertEquals($this->backend->getDisplayName('uid'), 'result'); } //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); + $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); + $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) @@ -1035,10 +1050,10 @@ class User_LDAPTest extends TestCase { ->method('countUsers') ->willReturn(42); - $this->assertEquals($this->backend->countUsers(),42); + $this->assertEquals($this->backend->countUsers(), 42); } - public function testLoginName2UserNameSuccess() { + public function testLoginName2UserNameSuccess(): void { $loginName = 'Alice'; $username = 'alice'; $dn = 'uid=alice,dc=what,dc=ever'; @@ -1058,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); + $backend = new UserLDAP($this->access, $this->notificationManager, $this->pluginManager, $this->logger, $this->deletedUsersIndex); $user = $this->createMock(User::class); $user->expects($this->any()) ->method('getUsername') @@ -1074,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']); @@ -1085,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()) @@ -1099,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); + $backend = new UserLDAP($this->access, $this->notificationManager, $this->pluginManager, $this->logger, $this->deletedUsersIndex); $name = $backend->loginName2UserName($loginName); $this->assertSame(false, $name); @@ -1117,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'; @@ -1132,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') @@ -1146,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); + $backend = new UserLDAP($this->access, $this->notificationManager, $this->pluginManager, $this->logger, $this->deletedUsersIndex); $name = $backend->loginName2UserName($loginName); $this->assertSame(false, $name); @@ -1156,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) { @@ -1197,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); - \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); + $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); - \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?'); @@ -1272,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()) @@ -1288,21 +1303,21 @@ 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) ->willReturn(true); $this->pluginManager->expects($this->once()) ->method('setPassword') - ->with('uid','password') + ->with('uid', 'password') ->willReturn('result'); /** @noinspection PhpUnhandledExceptionInspection */ - $this->assertEquals($this->backend->setPassword('uid', 'password'),'result'); + $this->assertEquals($this->backend->setPassword('uid', 'password'), 'result'); } - public function avatarDataProvider() { + public static function avatarDataProvider(): array { return [ [ 'validImageData', false ], [ 'corruptImageData', true ], @@ -1310,9 +1325,9 @@ class User_LDAPTest extends TestCase { ]; } - /** @dataProvider avatarDataProvider */ - public function testCanChangeAvatar($imageData, $expected) { - $isValidImage = strpos((string)$imageData, 'valid') === 0; + #[\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); $user->expects($this->once()) @@ -1330,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) @@ -1340,10 +1355,10 @@ class User_LDAPTest extends TestCase { ->with('uid') ->willReturn('result'); - $this->assertEquals($this->backend->canChangeAvatar('uid'),'result'); + $this->assertEquals($this->backend->canChangeAvatar('uid'), 'result'); } - public function testSetDisplayNameWithPlugin() { + public function testSetDisplayNameWithPlugin(): void { $newDisplayName = 'J. Baker'; $this->pluginManager->expects($this->once()) ->method('implementsActions') @@ -1360,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()) @@ -1378,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) @@ -1389,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'; @@ -1413,10 +1428,10 @@ class User_LDAPTest extends TestCase { ->method('getUserMapper') ->willReturn($this->createMock(UserMapping::class)); - $this->assertEquals($this->backend->createUser($uid, $pwd),true); + $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) @@ -1425,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], @@ -1435,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 ed95344f115..38f94af33a7 100644 --- a/apps/user_ldap/tests/User_ProxyTest.php +++ b/apps/user_ldap/tests/User_ProxyTest.php @@ -1,81 +1,58 @@ <?php + +declare(strict_types=1); /** - * @copyright Copyright (c) 2016 Lukas Reschke <lukas@statuscode.ch> - * - * @author Arthur Schiwon <blizzz@arthur-schiwon.de> - * @author Christoph Wurst <christoph@winzerhof-wurst.at> - * @author Lukas Reschke <lukas@statuscode.ch> - * @author Morris Jobke <hey@morrisjobke.de> - * @author Roeland Jago Douma <roeland@famdouma.nl> - * @author Roger Szabo <roger.szabo@web.de> - * @author Vinicius Cubas Brand <vinicius@eita.org.br> - * - * @license GNU AGPL version 3 or any later version - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see <http://www.gnu.org/licenses/>. - * + * SPDX-FileCopyrightText: 2016 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: AGPL-3.0-or-later */ namespace OCA\User_LDAP\Tests; +use OCA\User_LDAP\AccessFactory; use OCA\User_LDAP\Helper; 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|\PHPUnit\Framework\MockObject\MockObject */ - protected $helper; - /** @var ILDAPWrapper|\PHPUnit\Framework\MockObject\MockObject */ - private $ldapWrapper; - /** @var IConfig|\PHPUnit\Framework\MockObject\MockObject */ - private $config; - /** @var INotificationManager|\PHPUnit\Framework\MockObject\MockObject */ - private $notificationManager; - /** @var IUserSession|\PHPUnit\Framework\MockObject\MockObject */ - private $userSession; - /** @var User_Proxy|\PHPUnit\Framework\MockObject\MockObject */ - private $proxy; - /** @var UserPluginManager|\PHPUnit\Framework\MockObject\MockObject */ - private $userPluginManager; + 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(); $this->helper = $this->createMock(Helper::class); $this->ldapWrapper = $this->createMock(ILDAPWrapper::class); - $this->config = $this->createMock(IConfig::class); + $this->accessFactory = $this->createMock(AccessFactory::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); $this->proxy = $this->getMockBuilder(User_Proxy::class) ->setConstructorArgs([ $this->helper, $this->ldapWrapper, - $this->config, + $this->accessFactory, $this->notificationManager, - $this->userSession, - $this->userPluginManager + $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') @@ -85,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') @@ -95,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 5382a0c7f6f..3ae9a409e88 100644 --- a/apps/user_ldap/tests/WizardTest.php +++ b/apps/user_ldap/tests/WizardTest.php @@ -1,30 +1,10 @@ <?php + +declare(strict_types=1); /** - * @copyright Copyright (c) 2016, ownCloud, Inc. - * - * @author Arthur Schiwon <blizzz@arthur-schiwon.de> - * @author Christoph Wurst <christoph@winzerhof-wurst.at> - * @author Joas Schilling <coding@schilljs.com> - * @author Morris Jobke <hey@morrisjobke.de> - * @author Roeland Jago Douma <roeland@famdouma.nl> - * @author Thomas Müller <thomas.mueller@tmit.eu> - * @author Victor Dubiniuk <dubiniuk@owncloud.com> - * @author Viktor Szépe <viktor@szepe.net> - * - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see <http://www.gnu.org/licenses/> - * + * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors + * SPDX-FileCopyrightText: 2016 ownCloud, Inc. + * SPDX-License-Identifier: AGPL-3.0-only */ namespace OCA\User_LDAP\Tests; @@ -56,36 +36,32 @@ 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, usually invalid - ->willReturn(true); + //dummy value + ->willReturn(ldap_connect('ldap://example.com')); $ldap->expects($this->exactly(3)) ->method('setOption') @@ -96,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()) @@ -156,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()) @@ -173,7 +149,7 @@ class WizardTest extends TestCase { $ldap->expects($this->any()) ->method('isResource') ->willReturnCallback(function ($r) { - if ($r === true) { + if ($r instanceof \LDAP\Connection) { return true; } if ($r % 24 === 0) { @@ -232,7 +208,7 @@ class WizardTest extends TestCase { unset($uidnumber); } - public function testDetectEmailAttributeAlreadySet() { + public function testDetectEmailAttributeAlreadySet(): void { [$wizard, $configuration, $ldap, $access] = $this->getWizardAndMocks(); @@ -254,7 +230,7 @@ class WizardTest extends TestCase { $wizard->detectEmailAttribute(); } - public function testDetectEmailAttributeOverrideSet() { + public function testDetectEmailAttributeOverrideSet(): void { [$wizard, $configuration, $ldap, $access] = $this->getWizardAndMocks(); @@ -293,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(); @@ -332,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(); @@ -367,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(); @@ -444,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); } } |