diff options
Diffstat (limited to 'apps/federation/tests')
-rw-r--r-- | apps/federation/tests/BackgroundJob/GetSharedSecretTest.php | 160 | ||||
-rw-r--r-- | apps/federation/tests/BackgroundJob/RequestSharedSecretTest.php | 180 | ||||
-rw-r--r-- | apps/federation/tests/Controller/OCSAuthAPIControllerTest.php | 126 | ||||
-rw-r--r-- | apps/federation/tests/Controller/SettingsControllerTest.php | 131 | ||||
-rw-r--r-- | apps/federation/tests/DAV/FedAuthTest.php | 44 | ||||
-rw-r--r-- | apps/federation/tests/DbHandlerTest.php | 145 | ||||
-rw-r--r-- | apps/federation/tests/HooksTest.php | 80 | ||||
-rw-r--r-- | apps/federation/tests/Middleware/AddServerMiddlewareTest.php | 102 | ||||
-rw-r--r-- | apps/federation/tests/Settings/AdminTest.php | 49 | ||||
-rw-r--r-- | apps/federation/tests/SyncFederationAddressbooksTest.php | 147 | ||||
-rw-r--r-- | apps/federation/tests/TrustedServersTest.php | 374 |
11 files changed, 548 insertions, 990 deletions
diff --git a/apps/federation/tests/BackgroundJob/GetSharedSecretTest.php b/apps/federation/tests/BackgroundJob/GetSharedSecretTest.php index 6da3ba68940..943bdf352de 100644 --- a/apps/federation/tests/BackgroundJob/GetSharedSecretTest.php +++ b/apps/federation/tests/BackgroundJob/GetSharedSecretTest.php @@ -1,30 +1,11 @@ <?php + +declare(strict_types=1); /** - * @copyright Copyright (c) 2016, ownCloud, Inc. - * - * @author Bjoern Schiessle <bjoern@schiessle.org> - * @author Björn Schießle <bjoern@schiessle.org> - * @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> - * - * @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\Federation\Tests\BackgroundJob; use GuzzleHttp\Exception\ConnectException; @@ -37,9 +18,11 @@ use OCP\BackgroundJob\IJobList; use OCP\Http\Client\IClient; use OCP\Http\Client\IClientService; use OCP\Http\Client\IResponse; -use OCP\ILogger; +use OCP\IConfig; use OCP\IURLGenerator; use OCP\OCS\IDiscoveryService; +use PHPUnit\Framework\MockObject\MockObject; +use Psr\Log\LoggerInterface; /** * Class GetSharedSecretTest @@ -50,35 +33,18 @@ use OCP\OCS\IDiscoveryService; */ class GetSharedSecretTest extends TestCase { - /** @var \PHPUnit\Framework\MockObject\MockObject|IClient */ - private $httpClient; - - /** @var \PHPUnit\Framework\MockObject\MockObject|IClientService */ - private $httpClientService; - - /** @var \PHPUnit\Framework\MockObject\MockObject|IJobList */ - private $jobList; - - /** @var \PHPUnit\Framework\MockObject\MockObject|IURLGenerator */ - private $urlGenerator; - - /** @var \PHPUnit\Framework\MockObject\MockObject|TrustedServers */ - private $trustedServers; - - /** @var \PHPUnit\Framework\MockObject\MockObject|ILogger */ - private $logger; - - /** @var \PHPUnit\Framework\MockObject\MockObject|IResponse */ - private $response; - - /** @var \PHPUnit\Framework\MockObject\MockObject|IDiscoveryService */ - private $discoverService; - - /** @var \PHPUnit\Framework\MockObject\MockObject|ITimeFactory */ - private $timeFactory; + private MockObject&IClient $httpClient; + private MockObject&IClientService $httpClientService; + private MockObject&IJobList $jobList; + private MockObject&IURLGenerator $urlGenerator; + private MockObject&TrustedServers $trustedServers; + private MockObject&LoggerInterface $logger; + private MockObject&IResponse $response; + private MockObject&IDiscoveryService $discoverService; + private MockObject&ITimeFactory $timeFactory; + private MockObject&IConfig $config; - /** @var GetSharedSecret */ - private $getSharedSecret; + private GetSharedSecret $getSharedSecret; protected function setUp(): void { parent::setUp(); @@ -89,10 +55,11 @@ class GetSharedSecretTest extends TestCase { $this->urlGenerator = $this->getMockBuilder(IURLGenerator::class)->getMock(); $this->trustedServers = $this->getMockBuilder(TrustedServers::class) ->disableOriginalConstructor()->getMock(); - $this->logger = $this->getMockBuilder(ILogger::class)->getMock(); + $this->logger = $this->getMockBuilder(LoggerInterface::class)->getMock(); $this->response = $this->getMockBuilder(IResponse::class)->getMock(); $this->discoverService = $this->getMockBuilder(IDiscoveryService::class)->getMock(); $this->timeFactory = $this->createMock(ITimeFactory::class); + $this->config = $this->createMock(IConfig::class); $this->discoverService->expects($this->any())->method('discover')->willReturn([]); $this->httpClientService->expects($this->any())->method('newClient')->willReturn($this->httpClient); @@ -104,19 +71,15 @@ class GetSharedSecretTest extends TestCase { $this->trustedServers, $this->logger, $this->discoverService, - $this->timeFactory + $this->timeFactory, + $this->config, ); } - /** - * @dataProvider dataTestExecute - * - * @param bool $isTrustedServer - * @param bool $retainBackgroundJob - */ - public function testExecute($isTrustedServer, $retainBackgroundJob) { - /** @var GetSharedSecret |\PHPUnit\Framework\MockObject\MockObject $getSharedSecret */ - $getSharedSecret = $this->getMockBuilder('OCA\Federation\BackgroundJob\GetSharedSecret') + #[\PHPUnit\Framework\Attributes\DataProvider('dataTestExecute')] + public function testExecute(bool $isTrustedServer, bool $retainBackgroundJob): void { + /** @var GetSharedSecret&MockObject $getSharedSecret */ + $getSharedSecret = $this->getMockBuilder(GetSharedSecret::class) ->setConstructorArgs( [ $this->httpClientService, @@ -125,19 +88,22 @@ class GetSharedSecretTest extends TestCase { $this->trustedServers, $this->logger, $this->discoverService, - $this->timeFactory + $this->timeFactory, + $this->config, ] - )->setMethods(['parentExecute'])->getMock(); - $this->invokePrivate($getSharedSecret, 'argument', [['url' => 'url', 'token' => 'token']]); + ) + ->onlyMethods(['parentStart']) + ->getMock(); + self::invokePrivate($getSharedSecret, 'argument', [['url' => 'url', 'token' => 'token']]); $this->trustedServers->expects($this->once())->method('isTrustedServer') ->with('url')->willReturn($isTrustedServer); if ($isTrustedServer) { - $getSharedSecret->expects($this->once())->method('parentExecute'); + $getSharedSecret->expects($this->once())->method('parentStart'); } else { - $getSharedSecret->expects($this->never())->method('parentExecute'); + $getSharedSecret->expects($this->never())->method('parentStart'); } - $this->invokePrivate($getSharedSecret, 'retainJob', [$retainBackgroundJob]); + self::invokePrivate($getSharedSecret, 'retainJob', [$retainBackgroundJob]); $this->jobList->expects($this->once())->method('remove'); $this->timeFactory->method('getTime')->willReturn(42); @@ -157,10 +123,10 @@ class GetSharedSecretTest extends TestCase { $this->jobList->expects($this->never())->method('add'); } - $getSharedSecret->execute($this->jobList); + $getSharedSecret->start($this->jobList); } - public function dataTestExecute() { + public static function dataTestExecute(): array { return [ [true, true], [true, false], @@ -168,12 +134,8 @@ class GetSharedSecretTest extends TestCase { ]; } - /** - * @dataProvider dataTestRun - * - * @param int $statusCode - */ - public function testRun($statusCode) { + #[\PHPUnit\Framework\Attributes\DataProvider('dataTestRun')] + public function testRun(int $statusCode): void { $target = 'targetURL'; $source = 'sourceURL'; $token = 'token'; @@ -189,14 +151,14 @@ class GetSharedSecretTest extends TestCase { ->with( $target . '/ocs/v2.php/apps/federation/api/v1/shared-secret', [ - 'query' => - [ - 'url' => $source, - 'token' => $token, - 'format' => 'json', - ], + 'query' => [ + 'url' => $source, + 'token' => $token, + 'format' => 'json', + ], 'timeout' => 3, 'connect_timeout' => 3, + 'verify' => true, ] )->willReturn($this->response); @@ -212,18 +174,18 @@ class GetSharedSecretTest extends TestCase { $this->trustedServers->expects($this->never())->method('addSharedSecret'); } - $this->invokePrivate($this->getSharedSecret, 'run', [$argument]); + self::invokePrivate($this->getSharedSecret, 'run', [$argument]); if ( $statusCode !== Http::STATUS_OK && $statusCode !== Http::STATUS_FORBIDDEN ) { - $this->assertTrue($this->invokePrivate($this->getSharedSecret, 'retainJob')); + $this->assertTrue(self::invokePrivate($this->getSharedSecret, 'retainJob')); } else { - $this->assertFalse($this->invokePrivate($this->getSharedSecret, 'retainJob')); + $this->assertFalse(self::invokePrivate($this->getSharedSecret, 'retainJob')); } } - public function dataTestRun() { + public static function dataTestRun(): array { return [ [Http::STATUS_OK], [Http::STATUS_FORBIDDEN], @@ -231,7 +193,7 @@ class GetSharedSecretTest extends TestCase { ]; } - public function testRunExpired() { + public function testRunExpired(): void { $target = 'targetURL'; $source = 'sourceURL'; $token = 'token'; @@ -258,10 +220,10 @@ class GetSharedSecretTest extends TestCase { TrustedServers::STATUS_FAILURE ); - $this->invokePrivate($this->getSharedSecret, 'run', [$argument]); + self::invokePrivate($this->getSharedSecret, 'run', [$argument]); } - public function testRunConnectionError() { + public function testRunConnectionError(): void { $target = 'targetURL'; $source = 'sourceURL'; $token = 'token'; @@ -280,21 +242,21 @@ class GetSharedSecretTest extends TestCase { ->with( $target . '/ocs/v2.php/apps/federation/api/v1/shared-secret', [ - 'query' => - [ - 'url' => $source, - 'token' => $token, - 'format' => 'json', - ], + 'query' => [ + 'url' => $source, + 'token' => $token, + 'format' => 'json', + ], 'timeout' => 3, 'connect_timeout' => 3, + 'verify' => true, ] )->willThrowException($this->createMock(ConnectException::class)); $this->trustedServers->expects($this->never())->method('addSharedSecret'); - $this->invokePrivate($this->getSharedSecret, 'run', [$argument]); + self::invokePrivate($this->getSharedSecret, 'run', [$argument]); - $this->assertTrue($this->invokePrivate($this->getSharedSecret, 'retainJob')); + $this->assertTrue(self::invokePrivate($this->getSharedSecret, 'retainJob')); } } diff --git a/apps/federation/tests/BackgroundJob/RequestSharedSecretTest.php b/apps/federation/tests/BackgroundJob/RequestSharedSecretTest.php index f03c5aa2a2b..6ef579c7483 100644 --- a/apps/federation/tests/BackgroundJob/RequestSharedSecretTest.php +++ b/apps/federation/tests/BackgroundJob/RequestSharedSecretTest.php @@ -1,29 +1,11 @@ <?php + +declare(strict_types=1); /** - * @copyright Copyright (c) 2016, ownCloud, Inc. - * - * @author Bjoern Schiessle <bjoern@schiessle.org> - * @author Björn Schießle <bjoern@schiessle.org> - * @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: 2016-2024 Nextcloud GmbH and Nextcloud contributors + * SPDX-FileCopyrightText: 2016 ownCloud, Inc. + * SPDX-License-Identifier: AGPL-3.0-only */ - namespace OCA\Federation\Tests\BackgroundJob; use GuzzleHttp\Exception\ConnectException; @@ -35,56 +17,39 @@ use OCP\BackgroundJob\IJobList; use OCP\Http\Client\IClient; use OCP\Http\Client\IClientService; use OCP\Http\Client\IResponse; -use OCP\ILogger; +use OCP\IConfig; use OCP\IURLGenerator; use OCP\OCS\IDiscoveryService; +use PHPUnit\Framework\MockObject\MockObject; +use Psr\Log\LoggerInterface; use Test\TestCase; class RequestSharedSecretTest extends TestCase { - - /** @var \PHPUnit\Framework\MockObject\MockObject|IClientService */ - private $httpClientService; - - /** @var \PHPUnit\Framework\MockObject\MockObject|IClient */ - private $httpClient; - - /** @var \PHPUnit\Framework\MockObject\MockObject|IJobList */ - private $jobList; - - /** @var \PHPUnit\Framework\MockObject\MockObject|IURLGenerator */ - private $urlGenerator; - - /** @var \PHPUnit\Framework\MockObject\MockObject|TrustedServers */ - private $trustedServers; - - /** @var \PHPUnit\Framework\MockObject\MockObject|IResponse */ - private $response; - - /** @var \PHPUnit\Framework\MockObject\MockObject|IDiscoveryService */ - private $discoveryService; - - /** @var \PHPUnit\Framework\MockObject\MockObject|ILogger */ - private $logger; - - /** @var \PHPUnit\Framework\MockObject\MockObject|ITimeFactory */ - private $timeFactory; - - /** @var RequestSharedSecret */ - private $requestSharedSecret; + private IClientService&MockObject $httpClientService; + private IClient&MockObject $httpClient; + private IJobList&MockObject $jobList; + private IURLGenerator&MockObject $urlGenerator; + private TrustedServers&MockObject $trustedServers; + private IResponse&MockObject $response; + private IDiscoveryService&MockObject $discoveryService; + private LoggerInterface&MockObject $logger; + private ITimeFactory&MockObject $timeFactory; + private IConfig&MockObject $config; + private RequestSharedSecret $requestSharedSecret; protected function setUp(): void { parent::setUp(); $this->httpClientService = $this->createMock(IClientService::class); - $this->httpClient = $this->getMockBuilder(IClient::class)->getMock(); - $this->jobList = $this->getMockBuilder(IJobList::class)->getMock(); - $this->urlGenerator = $this->getMockBuilder(IURLGenerator::class)->getMock(); - $this->trustedServers = $this->getMockBuilder(TrustedServers::class) - ->disableOriginalConstructor()->getMock(); - $this->response = $this->getMockBuilder(IResponse::class)->getMock(); - $this->discoveryService = $this->getMockBuilder(IDiscoveryService::class)->getMock(); - $this->logger = $this->createMock(ILogger::class); + $this->httpClient = $this->createMock(IClient::class); + $this->jobList = $this->createMock(IJobList::class); + $this->urlGenerator = $this->createMock(IURLGenerator::class); + $this->trustedServers = $this->createMock(TrustedServers::class); + $this->response = $this->createMock(IResponse::class); + $this->discoveryService = $this->createMock(IDiscoveryService::class); + $this->logger = $this->createMock(LoggerInterface::class); $this->timeFactory = $this->createMock(ITimeFactory::class); + $this->config = $this->createMock(IConfig::class); $this->discoveryService->expects($this->any())->method('discover')->willReturn([]); $this->httpClientService->expects($this->any())->method('newClient')->willReturn($this->httpClient); @@ -96,19 +61,15 @@ class RequestSharedSecretTest extends TestCase { $this->trustedServers, $this->discoveryService, $this->logger, - $this->timeFactory + $this->timeFactory, + $this->config, ); } - /** - * @dataProvider dataTestExecute - * - * @param bool $isTrustedServer - * @param bool $retainBackgroundJob - */ - public function testExecute($isTrustedServer, $retainBackgroundJob) { - /** @var RequestSharedSecret |\PHPUnit\Framework\MockObject\MockObject $requestSharedSecret */ - $requestSharedSecret = $this->getMockBuilder('OCA\Federation\BackgroundJob\RequestSharedSecret') + #[\PHPUnit\Framework\Attributes\DataProvider('dataTestStart')] + public function testStart(bool $isTrustedServer, bool $retainBackgroundJob): void { + /** @var RequestSharedSecret&MockObject $requestSharedSecret */ + $requestSharedSecret = $this->getMockBuilder(RequestSharedSecret::class) ->setConstructorArgs( [ $this->httpClientService, @@ -117,19 +78,22 @@ class RequestSharedSecretTest extends TestCase { $this->trustedServers, $this->discoveryService, $this->logger, - $this->timeFactory + $this->timeFactory, + $this->config, ] - )->setMethods(['parentExecute'])->getMock(); - $this->invokePrivate($requestSharedSecret, 'argument', [['url' => 'url', 'token' => 'token']]); + ) + ->onlyMethods(['parentStart']) + ->getMock(); + self::invokePrivate($requestSharedSecret, 'argument', [['url' => 'url', 'token' => 'token']]); $this->trustedServers->expects($this->once())->method('isTrustedServer') ->with('url')->willReturn($isTrustedServer); if ($isTrustedServer) { - $requestSharedSecret->expects($this->once())->method('parentExecute'); + $requestSharedSecret->expects($this->once())->method('parentStart'); } else { - $requestSharedSecret->expects($this->never())->method('parentExecute'); + $requestSharedSecret->expects($this->never())->method('parentStart'); } - $this->invokePrivate($requestSharedSecret, 'retainJob', [$retainBackgroundJob]); + self::invokePrivate($requestSharedSecret, 'retainJob', [$retainBackgroundJob]); $this->jobList->expects($this->once())->method('remove'); $this->timeFactory->method('getTime')->willReturn(42); @@ -143,16 +107,17 @@ class RequestSharedSecretTest extends TestCase { 'url' => 'url', 'token' => 'token', 'created' => 42, + 'attempt' => 1, ] ); } else { $this->jobList->expects($this->never())->method('add'); } - $requestSharedSecret->execute($this->jobList); + $requestSharedSecret->start($this->jobList); } - public function dataTestExecute() { + public static function dataTestStart(): array { return [ [true, true], [true, false], @@ -160,17 +125,13 @@ class RequestSharedSecretTest extends TestCase { ]; } - /** - * @dataProvider dataTestRun - * - * @param int $statusCode - */ - public function testRun($statusCode) { + #[\PHPUnit\Framework\Attributes\DataProvider('dataTestRun')] + public function testRun(int $statusCode, int $attempt = 0): void { $target = 'targetURL'; $source = 'sourceURL'; $token = 'token'; - $argument = ['url' => $target, 'token' => $token]; + $argument = ['url' => $target, 'token' => $token, 'attempt' => $attempt]; $this->timeFactory->method('getTime')->willReturn(42); @@ -180,40 +141,41 @@ class RequestSharedSecretTest extends TestCase { ->with( $target . '/ocs/v2.php/apps/federation/api/v1/request-shared-secret', [ - 'body' => - [ - 'url' => $source, - 'token' => $token, - 'format' => 'json', - ], + 'body' => [ + 'url' => $source, + 'token' => $token, + 'format' => 'json', + ], 'timeout' => 3, 'connect_timeout' => 3, + 'verify' => true, ] )->willReturn($this->response); $this->response->expects($this->once())->method('getStatusCode') ->willReturn($statusCode); - $this->invokePrivate($this->requestSharedSecret, 'run', [$argument]); + self::invokePrivate($this->requestSharedSecret, 'run', [$argument]); if ( $statusCode !== Http::STATUS_OK - && $statusCode !== Http::STATUS_FORBIDDEN + && ($statusCode !== Http::STATUS_FORBIDDEN || $attempt < 5) ) { - $this->assertTrue($this->invokePrivate($this->requestSharedSecret, 'retainJob')); + $this->assertTrue(self::invokePrivate($this->requestSharedSecret, 'retainJob')); } else { - $this->assertFalse($this->invokePrivate($this->requestSharedSecret, 'retainJob')); + $this->assertFalse(self::invokePrivate($this->requestSharedSecret, 'retainJob')); } } - public function dataTestRun() { + public static function dataTestRun(): array { return [ [Http::STATUS_OK], + [Http::STATUS_FORBIDDEN, 5], [Http::STATUS_FORBIDDEN], [Http::STATUS_CONFLICT], ]; } - public function testRunExpired() { + public function testRunExpired(): void { $target = 'targetURL'; $source = 'sourceURL'; $token = 'token'; @@ -240,10 +202,10 @@ class RequestSharedSecretTest extends TestCase { TrustedServers::STATUS_FAILURE ); - $this->invokePrivate($this->requestSharedSecret, 'run', [$argument]); + self::invokePrivate($this->requestSharedSecret, 'run', [$argument]); } - public function testRunConnectionError() { + public function testRunConnectionError(): void { $target = 'targetURL'; $source = 'sourceURL'; $token = 'token'; @@ -264,18 +226,18 @@ class RequestSharedSecretTest extends TestCase { ->with( $target . '/ocs/v2.php/apps/federation/api/v1/request-shared-secret', [ - 'body' => - [ - 'url' => $source, - 'token' => $token, - 'format' => 'json', - ], + 'body' => [ + 'url' => $source, + 'token' => $token, + 'format' => 'json', + ], 'timeout' => 3, 'connect_timeout' => 3, + 'verify' => true, ] )->willThrowException($this->createMock(ConnectException::class)); - $this->invokePrivate($this->requestSharedSecret, 'run', [$argument]); - $this->assertTrue($this->invokePrivate($this->requestSharedSecret, 'retainJob')); + self::invokePrivate($this->requestSharedSecret, 'run', [$argument]); + $this->assertTrue(self::invokePrivate($this->requestSharedSecret, 'retainJob')); } } diff --git a/apps/federation/tests/Controller/OCSAuthAPIControllerTest.php b/apps/federation/tests/Controller/OCSAuthAPIControllerTest.php index b7bad3aaf35..a054277c5cd 100644 --- a/apps/federation/tests/Controller/OCSAuthAPIControllerTest.php +++ b/apps/federation/tests/Controller/OCSAuthAPIControllerTest.php @@ -1,72 +1,40 @@ <?php + +declare(strict_types=1); /** - * @copyright Copyright (c) 2016, ownCloud, Inc. - * - * @author Bjoern Schiessle <bjoern@schiessle.org> - * @author Björn Schießle <bjoern@schiessle.org> - * @author Christoph Wurst <christoph@winzerhof-wurst.at> - * @author Morris Jobke <hey@morrisjobke.de> - * @author Robin Appelman <robin@icewind.nl> - * @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\Federation\Tests\Controller; use OC\BackgroundJob\JobList; +use OCA\Federation\BackgroundJob\GetSharedSecret; use OCA\Federation\Controller\OCSAuthAPIController; use OCA\Federation\DbHandler; use OCA\Federation\TrustedServers; use OCP\AppFramework\OCS\OCSForbiddenException; use OCP\AppFramework\Utility\ITimeFactory; -use OCP\ILogger; use OCP\IRequest; +use OCP\Security\Bruteforce\IThrottler; use OCP\Security\ISecureRandom; +use PHPUnit\Framework\MockObject\MockObject; +use Psr\Log\LoggerInterface; use Test\TestCase; class OCSAuthAPIControllerTest extends TestCase { - - /** @var \PHPUnit\Framework\MockObject\MockObject|IRequest */ - private $request; - - /** @var \PHPUnit\Framework\MockObject\MockObject|ISecureRandom */ - private $secureRandom; - - /** @var \PHPUnit\Framework\MockObject\MockObject|JobList */ - private $jobList; - - /** @var \PHPUnit\Framework\MockObject\MockObject|TrustedServers */ - private $trustedServers; - - /** @var \PHPUnit\Framework\MockObject\MockObject|DbHandler */ - private $dbHandler; - - /** @var \PHPUnit\Framework\MockObject\MockObject|ILogger */ - private $logger; - - /** @var \PHPUnit\Framework\MockObject\MockObject|ITimeFactory */ - private $timeFactory; - - - /** @var OCSAuthAPIController */ - private $ocsAuthApi; + private IRequest&MockObject $request; + private ISecureRandom&MockObject $secureRandom; + private JobList&MockObject $jobList; + private TrustedServers&MockObject $trustedServers; + private DbHandler&MockObject $dbHandler; + private LoggerInterface&MockObject $logger; + private ITimeFactory&MockObject $timeFactory; + private IThrottler&MockObject $throttler; + private OCSAuthAPIController $ocsAuthApi; /** @var int simulated timestamp */ - private $currentTime = 1234567; + private int $currentTime = 1234567; protected function setUp(): void { parent::setUp(); @@ -76,9 +44,9 @@ class OCSAuthAPIControllerTest extends TestCase { $this->trustedServers = $this->createMock(TrustedServers::class); $this->dbHandler = $this->createMock(DbHandler::class); $this->jobList = $this->createMock(JobList::class); - $this->logger = $this->createMock(ILogger::class); + $this->logger = $this->createMock(LoggerInterface::class); $this->timeFactory = $this->createMock(ITimeFactory::class); - + $this->throttler = $this->createMock(IThrottler::class); $this->ocsAuthApi = new OCSAuthAPIController( 'federation', @@ -88,22 +56,16 @@ class OCSAuthAPIControllerTest extends TestCase { $this->trustedServers, $this->dbHandler, $this->logger, - $this->timeFactory + $this->timeFactory, + $this->throttler ); $this->timeFactory->method('getTime') ->willReturn($this->currentTime); } - /** - * @dataProvider dataTestRequestSharedSecret - * - * @param string $token - * @param string $localToken - * @param bool $isTrustedServer - * @param bool $ok - */ - public function testRequestSharedSecret($token, $localToken, $isTrustedServer, $ok) { + #[\PHPUnit\Framework\Attributes\DataProvider('dataTestRequestSharedSecret')] + public function testRequestSharedSecret(string $token, string $localToken, bool $isTrustedServer, bool $ok): void { $url = 'url'; $this->trustedServers @@ -114,12 +76,18 @@ class OCSAuthAPIControllerTest extends TestCase { if ($ok) { $this->jobList->expects($this->once())->method('add') - ->with('OCA\Federation\BackgroundJob\GetSharedSecret', ['url' => $url, 'token' => $token, 'created' => $this->currentTime]); + ->with(GetSharedSecret::class, ['url' => $url, 'token' => $token, 'created' => $this->currentTime]); } else { $this->jobList->expects($this->never())->method('add'); $this->jobList->expects($this->never())->method('remove'); + if (!$isTrustedServer) { + $this->throttler->expects($this->once()) + ->method('registerAttempt') + ->with('federationSharedSecret'); + } } + try { $this->ocsAuthApi->requestSharedSecret($url, $token); $this->assertTrue($ok); @@ -128,7 +96,7 @@ class OCSAuthAPIControllerTest extends TestCase { } } - public function dataTestRequestSharedSecret() { + public static function dataTestRequestSharedSecret(): array { return [ ['token2', 'token1', true, true], ['token1', 'token2', false, false], @@ -136,19 +104,13 @@ class OCSAuthAPIControllerTest extends TestCase { ]; } - /** - * @dataProvider dataTestGetSharedSecret - * - * @param bool $isTrustedServer - * @param bool $isValidToken - * @param bool $ok - */ - public function testGetSharedSecret($isTrustedServer, $isValidToken, $ok) { + #[\PHPUnit\Framework\Attributes\DataProvider('dataTestGetSharedSecret')] + public function testGetSharedSecret(bool $isTrustedServer, bool $isValidToken, bool $ok): void { $url = 'url'; $token = 'token'; - /** @var OCSAuthAPIController | \PHPUnit\Framework\MockObject\MockObject $ocsAuthApi */ - $ocsAuthApi = $this->getMockBuilder('OCA\Federation\Controller\OCSAuthAPIController') + /** @var OCSAuthAPIController&MockObject $ocsAuthApi */ + $ocsAuthApi = $this->getMockBuilder(OCSAuthAPIController::class) ->setConstructorArgs( [ 'federation', @@ -158,9 +120,12 @@ class OCSAuthAPIControllerTest extends TestCase { $this->trustedServers, $this->dbHandler, $this->logger, - $this->timeFactory + $this->timeFactory, + $this->throttler ] - )->setMethods(['isValidToken'])->getMock(); + ) + ->onlyMethods(['isValidToken']) + ->getMock(); $this->trustedServers ->expects($this->any()) @@ -172,10 +137,13 @@ class OCSAuthAPIControllerTest extends TestCase { $this->secureRandom->expects($this->once())->method('generate')->with(32) ->willReturn('secret'); $this->trustedServers->expects($this->once()) - ->method('addSharedSecret')->willReturn($url, 'secret'); + ->method('addSharedSecret')->with($url, 'secret'); } else { $this->secureRandom->expects($this->never())->method('generate'); $this->trustedServers->expects($this->never())->method('addSharedSecret'); + $this->throttler->expects($this->once()) + ->method('registerAttempt') + ->with('federationSharedSecret'); } try { @@ -188,7 +156,7 @@ class OCSAuthAPIControllerTest extends TestCase { } } - public function dataTestGetSharedSecret() { + public static function dataTestGetSharedSecret(): array { return [ [true, true, true], [false, true, false], diff --git a/apps/federation/tests/Controller/SettingsControllerTest.php b/apps/federation/tests/Controller/SettingsControllerTest.php index fd072d841b5..b0a7a5e30c9 100644 --- a/apps/federation/tests/Controller/SettingsControllerTest.php +++ b/apps/federation/tests/Controller/SettingsControllerTest.php @@ -1,67 +1,50 @@ <?php + +declare(strict_types=1); /** - * @copyright Copyright (c) 2016, ownCloud, Inc. - * - * @author Björn Schießle <bjoern@schiessle.org> - * @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: 2016-2024 Nextcloud GmbH and Nextcloud contributors + * SPDX-FileCopyrightText: 2016 ownCloud, Inc. + * SPDX-License-Identifier: AGPL-3.0-only */ - namespace OCA\Federation\Tests\Controller; use OCA\Federation\Controller\SettingsController; use OCA\Federation\TrustedServers; use OCP\AppFramework\Http\DataResponse; +use OCP\AppFramework\OCS\OCSException; +use OCP\AppFramework\OCS\OCSNotFoundException; use OCP\IL10N; use OCP\IRequest; +use PHPUnit\Framework\MockObject\MockObject; +use Psr\Log\LoggerInterface; use Test\TestCase; class SettingsControllerTest extends TestCase { + private SettingsController $controller; - /** @var SettingsController */ - private $controller; - - /** @var \PHPUnit\Framework\MockObject\MockObject | \OCP\IRequest */ - private $request; - - /** @var \PHPUnit\Framework\MockObject\MockObject | \OCP\IL10N */ - private $l10n; - - /** @var \PHPUnit\Framework\MockObject\MockObject | \OCA\Federation\TrustedServers */ - private $trustedServers; + private IRequest&MockObject $request; + private IL10N&MockObject $l10n; + private TrustedServers&MockObject $trustedServers; + private LoggerInterface&MockObject $logger; protected function setUp(): void { parent::setUp(); - $this->request = $this->getMockBuilder(IRequest::class)->getMock(); - $this->l10n = $this->getMockBuilder(IL10N::class)->getMock(); - $this->trustedServers = $this->getMockBuilder(TrustedServers::class) - ->disableOriginalConstructor()->getMock(); + $this->request = $this->createMock(IRequest::class); + $this->l10n = $this->createMock(IL10N::class); + $this->trustedServers = $this->createMock(TrustedServers::class); + $this->logger = $this->createMock(LoggerInterface::class); $this->controller = new SettingsController( 'SettingsControllerTest', $this->request, $this->l10n, - $this->trustedServers + $this->trustedServers, + $this->logger, ); } - public function testAddServer() { + public function testAddServer(): void { $this->trustedServers ->expects($this->once()) ->method('isTrustedServer') @@ -69,12 +52,12 @@ class SettingsControllerTest extends TestCase { ->willReturn(false); $this->trustedServers ->expects($this->once()) - ->method('isOwnCloudServer') + ->method('isNextcloudServer') ->with('url') ->willReturn(true); $result = $this->controller->addServer('url'); - $this->assertTrue($result instanceof DataResponse); + $this->assertInstanceOf(DataResponse::class, $result); $data = $result->getData(); $this->assertSame(200, $result->getStatus()); @@ -82,15 +65,8 @@ class SettingsControllerTest extends TestCase { $this->assertArrayHasKey('id', $data); } - /** - * @dataProvider checkServerFails - * - * @param bool $isTrustedServer - * @param bool $isOwnCloud - */ - public function testAddServerFail($isTrustedServer, $isOwnCloud) { - $this->expectException(\OC\HintException::class); - + #[\PHPUnit\Framework\Attributes\DataProvider('checkServerFails')] + public function testAddServerFail(bool $isTrustedServer, bool $isNextcloud): void { $this->trustedServers ->expects($this->any()) ->method('isTrustedServer') @@ -98,22 +74,29 @@ class SettingsControllerTest extends TestCase { ->willReturn($isTrustedServer); $this->trustedServers ->expects($this->any()) - ->method('isOwnCloudServer') + ->method('isNextcloudServer') ->with('url') - ->willReturn($isOwnCloud); + ->willReturn($isNextcloud); + + if ($isTrustedServer) { + $this->expectException(OCSException::class); + } else { + $this->expectException(OCSNotFoundException::class); + } $this->controller->addServer('url'); } - public function testRemoveServer() { - $this->trustedServers->expects($this->once())->method('removeServer') - ->with('url'); - $result = $this->controller->removeServer('url'); + public function testRemoveServer(): void { + $this->trustedServers->expects($this->once()) + ->method('removeServer') + ->with(1); + $result = $this->controller->removeServer(1); $this->assertTrue($result instanceof DataResponse); $this->assertSame(200, $result->getStatus()); } - public function testCheckServer() { + public function testCheckServer(): void { $this->trustedServers ->expects($this->once()) ->method('isTrustedServer') @@ -121,24 +104,17 @@ class SettingsControllerTest extends TestCase { ->willReturn(false); $this->trustedServers ->expects($this->once()) - ->method('isOwnCloudServer') + ->method('isNextcloudServer') ->with('url') ->willReturn(true); - $this->assertTrue( - $this->invokePrivate($this->controller, 'checkServer', ['url']) + $this->assertNull( + self::invokePrivate($this->controller, 'checkServer', ['url']) ); } - /** - * @dataProvider checkServerFails - * - * @param bool $isTrustedServer - * @param bool $isOwnCloud - */ - public function testCheckServerFail($isTrustedServer, $isOwnCloud) { - $this->expectException(\OC\HintException::class); - + #[\PHPUnit\Framework\Attributes\DataProvider('checkServerFails')] + public function testCheckServerFail(bool $isTrustedServer, bool $isNextcloud): void { $this->trustedServers ->expects($this->any()) ->method('isTrustedServer') @@ -146,21 +122,22 @@ class SettingsControllerTest extends TestCase { ->willReturn($isTrustedServer); $this->trustedServers ->expects($this->any()) - ->method('isOwnCloudServer') + ->method('isNextcloudServer') ->with('url') - ->willReturn($isOwnCloud); + ->willReturn($isNextcloud); + + if ($isTrustedServer) { + $this->expectException(OCSException::class); + } else { + $this->expectException(OCSNotFoundException::class); + } $this->assertTrue( - $this->invokePrivate($this->controller, 'checkServer', ['url']) + self::invokePrivate($this->controller, 'checkServer', ['url']) ); } - /** - * data to simulate checkServer fails - * - * @return array - */ - public function checkServerFails() { + public static function checkServerFails(): array { return [ [true, true], [false, false] diff --git a/apps/federation/tests/DAV/FedAuthTest.php b/apps/federation/tests/DAV/FedAuthTest.php index 426bfc5d6d5..c95d3852b48 100644 --- a/apps/federation/tests/DAV/FedAuthTest.php +++ b/apps/federation/tests/DAV/FedAuthTest.php @@ -1,51 +1,31 @@ <?php + +declare(strict_types=1); /** - * @copyright Copyright (c) 2016, ownCloud, Inc. - * - * @author Morris Jobke <hey@morrisjobke.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: 2019-2024 Nextcloud GmbH and Nextcloud contributors + * SPDX-FileCopyrightText: 2016 ownCloud, Inc. + * SPDX-License-Identifier: AGPL-3.0-only */ - namespace OCA\Federation\Tests\DAV; use OCA\Federation\DAV\FedAuth; use OCA\Federation\DbHandler; +use PHPUnit\Framework\MockObject\MockObject; use Test\TestCase; class FedAuthTest extends TestCase { - /** - * @dataProvider providesUser - * - * @param array $expected - * @param string $user - * @param string $password - */ - public function testFedAuth($expected, $user, $password) { - /** @var DbHandler | \PHPUnit\Framework\MockObject\MockObject $db */ - $db = $this->getMockBuilder('OCA\Federation\DbHandler')->disableOriginalConstructor()->getMock(); + #[\PHPUnit\Framework\Attributes\DataProvider('providesUser')] + public function testFedAuth(bool $expected, string $user, string $password): void { + /** @var DbHandler&MockObject $db */ + $db = $this->createMock(DbHandler::class); $db->method('auth')->willReturn(true); $auth = new FedAuth($db); - $result = $this->invokePrivate($auth, 'validateUserPass', [$user, $password]); + $result = self::invokePrivate($auth, 'validateUserPass', [$user, $password]); $this->assertEquals($expected, $result); } - public function providesUser() { + public static function providesUser(): array { return [ [true, 'system', '123456'] ]; diff --git a/apps/federation/tests/DbHandlerTest.php b/apps/federation/tests/DbHandlerTest.php index ee972458747..5452a48fc4a 100644 --- a/apps/federation/tests/DbHandlerTest.php +++ b/apps/federation/tests/DbHandlerTest.php @@ -1,60 +1,35 @@ <?php + +declare(strict_types=1); /** - * @copyright Copyright (c) 2016, ownCloud, Inc. - * - * @author Björn Schießle <bjoern@schiessle.org> - * @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> - * - * @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\Federation\Tests; use OCA\Federation\DbHandler; use OCA\Federation\TrustedServers; use OCP\IDBConnection; use OCP\IL10N; +use OCP\Server; +use PHPUnit\Framework\MockObject\MockObject; use Test\TestCase; /** * @group DB */ class DbHandlerTest extends TestCase { - - /** @var DbHandler */ - private $dbHandler; - - /** @var IL10N | \PHPUnit\Framework\MockObject\MockObject */ - private $il10n; - - /** @var IDBConnection */ - private $connection; - - /** @var string */ - private $dbTable = 'trusted_servers'; + private DbHandler $dbHandler; + private IL10N&MockObject $il10n; + private IDBConnection $connection; + private string $dbTable = 'trusted_servers'; protected function setUp(): void { parent::setUp(); - $this->connection = \OC::$server->getDatabaseConnection(); - $this->il10n = $this->getMockBuilder(IL10N::class)->getMock(); + $this->connection = Server::get(IDBConnection::class); + $this->il10n = $this->createMock(IL10N::class); $this->dbHandler = new DbHandler( $this->connection, @@ -63,26 +38,27 @@ class DbHandlerTest extends TestCase { $query = $this->connection->getQueryBuilder()->select('*')->from($this->dbTable); - $qResult = $query->execute(); + $qResult = $query->executeQuery(); $result = $qResult->fetchAll(); $qResult->closeCursor(); $this->assertEmpty($result, 'we need to start with a empty trusted_servers table'); } protected function tearDown(): void { - parent::tearDown(); $query = $this->connection->getQueryBuilder()->delete($this->dbTable); - $query->execute(); + $query->executeStatement() + ; + parent::tearDown(); } /** - * @dataProvider dataTestAddServer * * @param string $url passed to the method * @param string $expectedUrl the url we expect to be written to the db * @param string $expectedHash the hash value we expect to be written to the db */ - public function testAddServer($url, $expectedUrl, $expectedHash) { + #[\PHPUnit\Framework\Attributes\DataProvider('dataTestAddServer')] + public function testAddServer(string $url, string $expectedUrl, string $expectedHash): void { $id = $this->dbHandler->addServer($url); $query = $this->connection->getQueryBuilder()->select('*')->from($this->dbTable); @@ -90,14 +66,14 @@ class DbHandlerTest extends TestCase { $qResult = $query->execute(); $result = $qResult->fetchAll(); $qResult->closeCursor(); - $this->assertSame(1, count($result)); + $this->assertCount(1, $result); $this->assertSame($expectedUrl, $result[0]['url']); $this->assertSame($id, (int)$result[0]['id']); $this->assertSame($expectedHash, $result[0]['url_hash']); $this->assertSame(TrustedServers::STATUS_PENDING, (int)$result[0]['status']); } - public function dataTestAddServer() { + public static function dataTestAddServer(): array { return [ ['http://owncloud.org', 'http://owncloud.org', sha1('owncloud.org')], ['https://owncloud.org', 'https://owncloud.org', sha1('owncloud.org')], @@ -105,7 +81,7 @@ class DbHandlerTest extends TestCase { ]; } - public function testRemove() { + public function testRemove(): void { $id1 = $this->dbHandler->addServer('server1'); $id2 = $this->dbHandler->addServer('server2'); @@ -114,7 +90,7 @@ class DbHandlerTest extends TestCase { $qResult = $query->execute(); $result = $qResult->fetchAll(); $qResult->closeCursor(); - $this->assertSame(2, count($result)); + $this->assertCount(2, $result); $this->assertSame('server1', $result[0]['url']); $this->assertSame('server2', $result[1]['url']); $this->assertSame($id1, (int)$result[0]['id']); @@ -126,13 +102,13 @@ class DbHandlerTest extends TestCase { $qResult = $query->execute(); $result = $qResult->fetchAll(); $qResult->closeCursor(); - $this->assertSame(1, count($result)); + $this->assertCount(1, $result); $this->assertSame('server1', $result[0]['url']); $this->assertSame($id1, (int)$result[0]['id']); } - public function testGetServerById() { + public function testGetServerById(): void { $this->dbHandler->addServer('server1'); $id = $this->dbHandler->addServer('server2'); @@ -140,7 +116,7 @@ class DbHandlerTest extends TestCase { $this->assertSame('server2', $result['url']); } - public function testGetAll() { + public function testGetAll(): void { $id1 = $this->dbHandler->addServer('server1'); $id2 = $this->dbHandler->addServer('server2'); @@ -152,21 +128,15 @@ class DbHandlerTest extends TestCase { $this->assertSame($id2, (int)$result[1]['id']); } - /** - * @dataProvider dataTestServerExists - * - * @param string $serverInTable - * @param string $checkForServer - * @param bool $expected - */ - public function testServerExists($serverInTable, $checkForServer, $expected) { + #[\PHPUnit\Framework\Attributes\DataProvider('dataTestServerExists')] + public function testServerExists(string $serverInTable, string $checkForServer, bool $expected): void { $this->dbHandler->addServer($serverInTable); $this->assertSame($expected, $this->dbHandler->serverExists($checkForServer) ); } - public function dataTestServerExists() { + public static function dataTestServerExists(): array { return [ ['server1', 'server1', true], ['server1', 'http://server1', true], @@ -178,22 +148,22 @@ class DbHandlerTest extends TestCase { $this->dbHandler->addServer('server1'); $query = $this->connection->getQueryBuilder()->select('*')->from($this->dbTable); - $qResult = $query->execute(); + $qResult = $query->executeQuery(); $result = $qResult->fetchAll(); $qResult->closeCursor(); - $this->assertSame(1, count($result)); + $this->assertCount(1, $result); $this->assertSame(null, $result[0]['token']); $this->dbHandler->addToken('http://server1', 'token'); $query = $this->connection->getQueryBuilder()->select('*')->from($this->dbTable); - $qResult = $query->execute(); + $qResult = $query->executeQuery(); $result = $qResult->fetchAll(); $qResult->closeCursor(); - $this->assertSame(1, count($result)); + $this->assertCount(1, $result); $this->assertSame('token', $result[0]['token']); } - public function testGetToken() { + public function testGetToken(): void { $this->dbHandler->addServer('server1'); $this->dbHandler->addToken('http://server1', 'token'); $this->assertSame('token', @@ -208,7 +178,7 @@ class DbHandlerTest extends TestCase { $qResult = $query->execute(); $result = $qResult->fetchAll(); $qResult->closeCursor(); - $this->assertSame(1, count($result)); + $this->assertCount(1, $result); $this->assertSame(null, $result[0]['shared_secret']); $this->dbHandler->addSharedSecret('http://server1', 'secret'); $query = $this->connection->getQueryBuilder()->select('*')->from($this->dbTable); @@ -216,11 +186,11 @@ class DbHandlerTest extends TestCase { $qResult = $query->execute(); $result = $qResult->fetchAll(); $qResult->closeCursor(); - $this->assertSame(1, count($result)); + $this->assertCount(1, $result); $this->assertSame('secret', $result[0]['shared_secret']); } - public function testGetSharedSecret() { + public function testGetSharedSecret(): void { $this->dbHandler->addServer('server1'); $this->dbHandler->addSharedSecret('http://server1', 'secret'); $this->assertSame('secret', @@ -228,26 +198,26 @@ class DbHandlerTest extends TestCase { ); } - public function testSetServerStatus() { + public function testSetServerStatus(): void { $this->dbHandler->addServer('server1'); $query = $this->connection->getQueryBuilder()->select('*')->from($this->dbTable); - $qResult = $query->execute(); + $qResult = $query->executeQuery(); $result = $qResult->fetchAll(); $qResult->closeCursor(); - $this->assertSame(1, count($result)); + $this->assertCount(1, $result); $this->assertSame(TrustedServers::STATUS_PENDING, (int)$result[0]['status']); $this->dbHandler->setServerStatus('http://server1', TrustedServers::STATUS_OK); $query = $this->connection->getQueryBuilder()->select('*')->from($this->dbTable); - $qResult = $query->execute(); + $qResult = $query->executeQuery(); $result = $qResult->fetchAll(); $qResult->closeCursor(); - $this->assertSame(1, count($result)); + $this->assertCount(1, $result); $this->assertSame(TrustedServers::STATUS_OK, (int)$result[0]['status']); } - public function testGetServerStatus() { + public function testGetServerStatus(): void { $this->dbHandler->addServer('server1'); $this->dbHandler->setServerStatus('http://server1', TrustedServers::STATUS_OK); $this->assertSame(TrustedServers::STATUS_OK, @@ -262,19 +232,15 @@ class DbHandlerTest extends TestCase { /** * hash should always be computed with the normalized URL - * - * @dataProvider dataTestHash - * - * @param string $url - * @param string $expected */ - public function testHash($url, $expected) { + #[\PHPUnit\Framework\Attributes\DataProvider('dataTestHash')] + public function testHash(string $url, string $expected): void { $this->assertSame($expected, $this->invokePrivate($this->dbHandler, 'hash', [$url]) ); } - public function dataTestHash() { + public static function dataTestHash(): array { return [ ['server1', sha1('server1')], ['http://server1', sha1('server1')], @@ -283,19 +249,14 @@ class DbHandlerTest extends TestCase { ]; } - /** - * @dataProvider dataTestNormalizeUrl - * - * @param string $url - * @param string $expected - */ - public function testNormalizeUrl($url, $expected) { + #[\PHPUnit\Framework\Attributes\DataProvider('dataTestNormalizeUrl')] + public function testNormalizeUrl(string $url, string $expected): void { $this->assertSame($expected, $this->invokePrivate($this->dbHandler, 'normalizeUrl', [$url]) ); } - public function dataTestNormalizeUrl() { + public static function dataTestNormalizeUrl(): array { return [ ['owncloud.org', 'owncloud.org'], ['http://owncloud.org', 'owncloud.org'], @@ -305,10 +266,8 @@ class DbHandlerTest extends TestCase { ]; } - /** - * @dataProvider providesAuth - */ - public function testAuth($expectedResult, $user, $password) { + #[\PHPUnit\Framework\Attributes\DataProvider('providesAuth')] + public function testAuth(bool $expectedResult, string $user, string $password): void { if ($expectedResult) { $this->dbHandler->addServer('url1'); $this->dbHandler->addSharedSecret('url1', $password); @@ -317,7 +276,7 @@ class DbHandlerTest extends TestCase { $this->assertEquals($expectedResult, $result); } - public function providesAuth() { + public static function providesAuth(): array { return [ [false, 'foo', ''], [true, 'system', '123456789'], diff --git a/apps/federation/tests/HooksTest.php b/apps/federation/tests/HooksTest.php deleted file mode 100644 index 8741ddb9fd6..00000000000 --- a/apps/federation/tests/HooksTest.php +++ /dev/null @@ -1,80 +0,0 @@ -<?php -/** - * @copyright Copyright (c) 2016, ownCloud, Inc. - * - * @author Björn Schießle <bjoern@schiessle.org> - * @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/> - * - */ - -namespace OCA\Federation\Tests; - -use OCA\Federation\Hooks; -use OCA\Federation\TrustedServers; -use Test\TestCase; - -class HooksTest extends TestCase { - - /** @var \PHPUnit\Framework\MockObject\MockObject | TrustedServers */ - private $trustedServers; - - /** @var Hooks */ - private $hooks; - - protected function setUp(): void { - parent::setUp(); - - $this->trustedServers = $this->getMockBuilder('OCA\Federation\TrustedServers') - ->disableOriginalConstructor()->getMock(); - - $this->hooks = new Hooks($this->trustedServers); - } - - /** - * @dataProvider dataTestAddServerHook - * - * @param bool $autoAddEnabled is auto-add enabled - * @param bool $isTrustedServer is the server already in the list of trusted servers - * @param bool $addServer should the server be added - */ - public function testAddServerHook($autoAddEnabled, $isTrustedServer, $addServer) { - $this->trustedServers->expects($this->any())->method('getAutoAddServers') - ->willReturn($autoAddEnabled); - $this->trustedServers->expects($this->any())->method('isTrustedServer') - ->with('url')->willReturn($isTrustedServer); - - if ($addServer) { - $this->trustedServers->expects($this->once())->method('addServer') - ->with('url'); - } else { - $this->trustedServers->expects($this->never())->method('addServer'); - } - - $this->hooks->addServerHook(['server' => 'url']); - } - - public function dataTestAddServerHook() { - return [ - [true, true, false], - [false, true, false], - [true, false, true], - [false, false, false], - ]; - } -} diff --git a/apps/federation/tests/Middleware/AddServerMiddlewareTest.php b/apps/federation/tests/Middleware/AddServerMiddlewareTest.php deleted file mode 100644 index 35fecf2f0e4..00000000000 --- a/apps/federation/tests/Middleware/AddServerMiddlewareTest.php +++ /dev/null @@ -1,102 +0,0 @@ -<?php -/** - * @copyright Copyright (c) 2016, ownCloud, Inc. - * - * @author Bjoern Schiessle <bjoern@schiessle.org> - * @author Björn Schießle <bjoern@schiessle.org> - * @author Christoph Wurst <christoph@winzerhof-wurst.at> - * @author Morris Jobke <hey@morrisjobke.de> - * @author Roeland Jago Douma <roeland@famdouma.nl> - * @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/> - * - */ - -namespace OCA\Federation\Tests\Middleware; - -use OC\HintException; -use OCA\Federation\Controller\SettingsController; -use OCA\Federation\Middleware\AddServerMiddleware; -use OCP\AppFramework\Http; -use OCP\IL10N; -use OCP\ILogger; -use Test\TestCase; - -class AddServerMiddlewareTest extends TestCase { - - /** @var \PHPUnit\Framework\MockObject\MockObject | ILogger */ - private $logger; - - /** @var \PHPUnit\Framework\MockObject\MockObject | \OCP\IL10N */ - private $l10n; - - /** @var AddServerMiddleware */ - private $middleware; - - /** @var \PHPUnit\Framework\MockObject\MockObject | SettingsController */ - private $controller; - - protected function setUp(): void { - parent::setUp(); - - $this->logger = $this->getMockBuilder(ILogger::class)->getMock(); - $this->l10n = $this->getMockBuilder(IL10N::class)->getMock(); - $this->controller = $this->getMockBuilder(SettingsController::class) - ->disableOriginalConstructor()->getMock(); - - $this->middleware = new AddServerMiddleware( - 'AddServerMiddlewareTest', - $this->l10n, - $this->logger - ); - } - - /** - * @dataProvider dataTestAfterException - * - * @param \Exception $exception - * @param string $hint - */ - public function testAfterException($exception, $hint) { - $this->logger->expects($this->once())->method('logException'); - - $this->l10n->expects($this->any())->method('t') - ->willReturnCallback( - function ($message) { - return $message; - } - ); - - $result = $this->middleware->afterException($this->controller, 'method', $exception); - - $this->assertSame(Http::STATUS_BAD_REQUEST, - $result->getStatus() - ); - - $data = $result->getData(); - - $this->assertSame($hint, - $data['message'] - ); - } - - public function dataTestAfterException() { - return [ - [new HintException('message', 'hint'), 'hint'], - [new \Exception('message'), 'message'], - ]; - } -} diff --git a/apps/federation/tests/Settings/AdminTest.php b/apps/federation/tests/Settings/AdminTest.php index 75ccabb968f..b879547a8cd 100644 --- a/apps/federation/tests/Settings/AdminTest.php +++ b/apps/federation/tests/Settings/AdminTest.php @@ -1,71 +1,50 @@ <?php + +declare(strict_types=1); /** - * @copyright Copyright (c) 2016 Lukas Reschke <lukas@statuscode.ch> - * - * @author Lukas Reschke <lukas@statuscode.ch> - * @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\Federation\Tests\Settings; use OCA\Federation\Settings\Admin; use OCA\Federation\TrustedServers; use OCP\AppFramework\Http\TemplateResponse; +use OCP\IL10N; +use PHPUnit\Framework\MockObject\MockObject; use Test\TestCase; class AdminTest extends TestCase { - /** @var Admin */ - private $admin; - /** @var TrustedServers */ - private $trustedServers; + private TrustedServers&MockObject $trustedServers; + private Admin $admin; protected function setUp(): void { parent::setUp(); - $this->trustedServers = $this->getMockBuilder('\OCA\Federation\TrustedServers')->disableOriginalConstructor()->getMock(); + $this->trustedServers = $this->createMock(TrustedServers::class); $this->admin = new Admin( - $this->trustedServers + $this->trustedServers, + $this->createMock(IL10N::class) ); } - public function testGetForm() { + public function testGetForm(): void { $this->trustedServers ->expects($this->once()) ->method('getServers') ->willReturn(['myserver', 'secondserver']); - $this->trustedServers - ->expects($this->once()) - ->method('getAutoAddServers') - ->willReturn(['autoserver1', 'autoserver2']); $params = [ 'trustedServers' => ['myserver', 'secondserver'], - 'autoAddServers' => ['autoserver1', 'autoserver2'], ]; $expected = new TemplateResponse('federation', 'settings-admin', $params, ''); $this->assertEquals($expected, $this->admin->getForm()); } - public function testGetSection() { + public function testGetSection(): void { $this->assertSame('sharing', $this->admin->getSection()); } - public function testGetPriority() { + public function testGetPriority(): void { $this->assertSame(30, $this->admin->getPriority()); } } diff --git a/apps/federation/tests/SyncFederationAddressbooksTest.php b/apps/federation/tests/SyncFederationAddressbooksTest.php index cda30c3ceb4..ff03f5cf442 100644 --- a/apps/federation/tests/SyncFederationAddressbooksTest.php +++ b/apps/federation/tests/SyncFederationAddressbooksTest.php @@ -1,109 +1,108 @@ <?php + +declare(strict_types=1); /** - * @copyright Copyright (c) 2016, ownCloud, Inc. - * - * @author Bjoern Schiessle <bjoern@schiessle.org> - * @author Björn Schießle <bjoern@schiessle.org> - * @author Christoph Wurst <christoph@winzerhof-wurst.at> - * @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 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\Federation\Tests; use OC\OCS\DiscoveryService; +use OCA\DAV\CardDAV\SyncService; use OCA\Federation\DbHandler; use OCA\Federation\SyncFederationAddressBooks; +use OCA\Federation\TrustedServers; +use PHPUnit\Framework\MockObject\MockObject; +use Psr\Log\LoggerInterface; class SyncFederationAddressbooksTest extends \Test\TestCase { - - /** @var array */ - private $callBacks = []; - - /** @var \PHPUnit\Framework\MockObject\MockObject | DiscoveryService */ - private $discoveryService; + private array $callBacks = []; + private DiscoveryService&MockObject $discoveryService; + private LoggerInterface&MockObject $logger; protected function setUp(): void { parent::setUp(); - $this->discoveryService = $this->getMockBuilder(DiscoveryService::class) - ->disableOriginalConstructor()->getMock(); + $this->discoveryService = $this->createMock(DiscoveryService::class); $this->discoveryService->expects($this->any())->method('discover')->willReturn([]); + $this->logger = $this->createMock(LoggerInterface::class); } - public function testSync() { - /** @var DbHandler | \PHPUnit\Framework\MockObject\MockObject $dbHandler */ - $dbHandler = $this->getMockBuilder('OCA\Federation\DbHandler')-> - disableOriginalConstructor()-> - getMock(); - $dbHandler->method('getAllServer')-> - willReturn([ + public function testSync(): void { + /** @var DbHandler&MockObject $dbHandler */ + $dbHandler = $this->createMock(DbHandler::class); + $dbHandler->method('getAllServer') + ->willReturn([ [ - 'url' => 'https://cloud.drop.box', + 'url' => 'https://cloud.example.org', 'url_hash' => 'sha1', - 'shared_secret' => 'iloveowncloud', + 'shared_secret' => 'ilovenextcloud', 'sync_token' => '0' ] ]); - $dbHandler->expects($this->once())->method('setServerStatus')-> - with('https://cloud.drop.box', 1, '1'); - $syncService = $this->getMockBuilder('OCA\DAV\CardDAV\SyncService') - ->disableOriginalConstructor() - ->getMock(); + $dbHandler->expects($this->once())->method('setServerStatus') + ->with('https://cloud.example.org', 1, '1'); + $syncService = $this->createMock(SyncService::class); $syncService->expects($this->once())->method('syncRemoteAddressBook') - ->willReturn(1); + ->willReturn(['1', false]); - /** @var \OCA\DAV\CardDAV\SyncService $syncService */ - $s = new SyncFederationAddressBooks($dbHandler, $syncService, $this->discoveryService); - $s->syncThemAll(function ($url, $ex) { + /** @var SyncService $syncService */ + $s = new SyncFederationAddressBooks($dbHandler, $syncService, $this->discoveryService, $this->logger); + $s->syncThemAll(function ($url, $ex): void { $this->callBacks[] = [$url, $ex]; }); - $this->assertEquals(1, count($this->callBacks)); + $this->assertCount(1, $this->callBacks); } - public function testException() { - /** @var DbHandler | \PHPUnit\Framework\MockObject\MockObject $dbHandler */ - $dbHandler = $this->getMockBuilder('OCA\Federation\DbHandler')-> - disableOriginalConstructor()-> - getMock(); - $dbHandler->method('getAllServer')-> - willReturn([ - [ - 'url' => 'https://cloud.drop.box', - 'url_hash' => 'sha1', - 'shared_secret' => 'iloveowncloud', - 'sync_token' => '0' - ] - ]); - $syncService = $this->getMockBuilder('OCA\DAV\CardDAV\SyncService') - ->disableOriginalConstructor() - ->getMock(); + public function testException(): void { + /** @var DbHandler&MockObject $dbHandler */ + $dbHandler = $this->createMock(DbHandler::class); + $dbHandler->method('getAllServer') + ->willReturn([ + [ + 'url' => 'https://cloud.example.org', + 'url_hash' => 'sha1', + 'shared_secret' => 'ilovenextcloud', + 'sync_token' => '0' + ] + ]); + $syncService = $this->createMock(SyncService::class); $syncService->expects($this->once())->method('syncRemoteAddressBook') ->willThrowException(new \Exception('something did not work out')); - /** @var \OCA\DAV\CardDAV\SyncService $syncService */ - $s = new SyncFederationAddressBooks($dbHandler, $syncService, $this->discoveryService); - $s->syncThemAll(function ($url, $ex) { + /** @var SyncService $syncService */ + $s = new SyncFederationAddressBooks($dbHandler, $syncService, $this->discoveryService, $this->logger); + $s->syncThemAll(function ($url, $ex): void { + $this->callBacks[] = [$url, $ex]; + }); + $this->assertCount(2, $this->callBacks); + } + + public function testSuccessfulSyncWithoutChangesAfterFailure(): void { + /** @var DbHandler&MockObject $dbHandler */ + $dbHandler = $this->createMock(DbHandler::class); + $dbHandler->method('getAllServer') + ->willReturn([ + [ + 'url' => 'https://cloud.example.org', + 'url_hash' => 'sha1', + 'shared_secret' => 'ilovenextcloud', + 'sync_token' => '0' + ] + ]); + $dbHandler->method('getServerStatus')->willReturn(TrustedServers::STATUS_FAILURE); + $dbHandler->expects($this->once())->method('setServerStatus') + ->with('https://cloud.example.org', 1); + $syncService = $this->createMock(SyncService::class); + $syncService->expects($this->once())->method('syncRemoteAddressBook') + ->willReturn(['0', false]); + + /** @var SyncService $syncService */ + $s = new SyncFederationAddressBooks($dbHandler, $syncService, $this->discoveryService, $this->logger); + $s->syncThemAll(function ($url, $ex): void { $this->callBacks[] = [$url, $ex]; }); - $this->assertEquals(2, count($this->callBacks)); + $this->assertCount(1, $this->callBacks); } } diff --git a/apps/federation/tests/TrustedServersTest.php b/apps/federation/tests/TrustedServersTest.php index 5cb494643b8..0c900f6edf7 100644 --- a/apps/federation/tests/TrustedServersTest.php +++ b/apps/federation/tests/TrustedServersTest.php @@ -1,95 +1,55 @@ <?php + +declare(strict_types=1); /** - * @copyright Copyright (c) 2016, ownCloud, Inc. - * - * @author Bjoern Schiessle <bjoern@schiessle.org> - * @author Björn Schießle <bjoern@schiessle.org> - * @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> - * - * @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\Federation\Tests; +use OCA\Federation\BackgroundJob\RequestSharedSecret; use OCA\Federation\DbHandler; use OCA\Federation\TrustedServers; use OCP\AppFramework\Utility\ITimeFactory; use OCP\BackgroundJob\IJobList; +use OCP\EventDispatcher\IEventDispatcher; +use OCP\Federation\Events\TrustedServerRemovedEvent; +use OCP\HintException; use OCP\Http\Client\IClient; use OCP\Http\Client\IClientService; use OCP\Http\Client\IResponse; use OCP\IConfig; -use OCP\ILogger; use OCP\Security\ISecureRandom; -use Symfony\Component\EventDispatcher\EventDispatcherInterface; +use PHPUnit\Framework\MockObject\MockObject; +use Psr\Log\LoggerInterface; use Test\TestCase; class TrustedServersTest extends TestCase { - - /** @var \PHPUnit\Framework\MockObject\MockObject | TrustedServers */ - private $trustedServers; - - /** @var \PHPUnit\Framework\MockObject\MockObject | DbHandler */ - private $dbHandler; - - /** @var \PHPUnit\Framework\MockObject\MockObject | IClientService */ - private $httpClientService; - - /** @var \PHPUnit\Framework\MockObject\MockObject | IClient */ - private $httpClient; - - /** @var \PHPUnit\Framework\MockObject\MockObject | IResponse */ - private $response; - - /** @var \PHPUnit\Framework\MockObject\MockObject | ILogger */ - private $logger; - - /** @var \PHPUnit\Framework\MockObject\MockObject | IJobList */ - private $jobList; - - /** @var \PHPUnit\Framework\MockObject\MockObject | ISecureRandom */ - private $secureRandom; - - /** @var \PHPUnit\Framework\MockObject\MockObject | IConfig */ - private $config; - - /** @var \PHPUnit\Framework\MockObject\MockObject | EventDispatcherInterface */ - private $dispatcher; - - /** @var \PHPUnit\Framework\MockObject\MockObject|ITimeFactory */ - private $timeFactory; + private TrustedServers $trustedServers; + private DbHandler&MockObject $dbHandler; + private IClientService&MockObject $httpClientService; + private IClient&MockObject $httpClient; + private IResponse&MockObject $response; + private LoggerInterface&MockObject $logger; + private IJobList&MockObject $jobList; + private ISecureRandom&MockObject $secureRandom; + private IConfig&MockObject $config; + private IEventDispatcher&MockObject $dispatcher; + private ITimeFactory&MockObject $timeFactory; protected function setUp(): void { parent::setUp(); - $this->dbHandler = $this->getMockBuilder(DbHandler::class) - ->disableOriginalConstructor()->getMock(); - $this->dispatcher = $this->getMockBuilder(EventDispatcherInterface::class) - ->disableOriginalConstructor()->getMock(); - $this->httpClientService = $this->getMockBuilder(IClientService::class)->getMock(); - $this->httpClient = $this->getMockBuilder(IClient::class)->getMock(); - $this->response = $this->getMockBuilder(IResponse::class)->getMock(); - $this->logger = $this->getMockBuilder(ILogger::class)->getMock(); - $this->jobList = $this->getMockBuilder(IJobList::class)->getMock(); - $this->secureRandom = $this->getMockBuilder(ISecureRandom::class)->getMock(); - $this->config = $this->getMockBuilder(IConfig::class)->getMock(); + $this->dbHandler = $this->createMock(DbHandler::class); + $this->dispatcher = $this->createMock(IEventDispatcher::class); + $this->httpClientService = $this->createMock(IClientService::class); + $this->httpClient = $this->createMock(IClient::class); + $this->response = $this->createMock(IResponse::class); + $this->logger = $this->createMock(LoggerInterface::class); + $this->jobList = $this->createMock(IJobList::class); + $this->secureRandom = $this->createMock(ISecureRandom::class); + $this->config = $this->createMock(IConfig::class); $this->timeFactory = $this->createMock(ITimeFactory::class); $this->trustedServers = new TrustedServers( @@ -104,14 +64,9 @@ class TrustedServersTest extends TestCase { ); } - /** - * @dataProvider dataTrueFalse - * - * @param bool $success - */ - public function testAddServer($success) { - /** @var \PHPUnit\Framework\MockObject\MockObject|TrustedServers $trustedServers */ - $trustedServers = $this->getMockBuilder('OCA\Federation\TrustedServers') + public function testAddServer(): void { + /** @var TrustedServers&MockObject $trustedServers */ + $trustedServers = $this->getMockBuilder(TrustedServers::class) ->setConstructorArgs( [ $this->dbHandler, @@ -124,110 +79,63 @@ class TrustedServersTest extends TestCase { $this->timeFactory ] ) - ->setMethods(['normalizeUrl', 'updateProtocol']) + ->onlyMethods(['updateProtocol']) ->getMock(); $trustedServers->expects($this->once())->method('updateProtocol') - ->with('url')->willReturn('https://url'); + ->with('url')->willReturn('https://url'); $this->timeFactory->method('getTime') ->willReturn(1234567); $this->dbHandler->expects($this->once())->method('addServer')->with('https://url') - ->willReturn($success); - - if ($success) { - $this->secureRandom->expects($this->once())->method('generate') - ->willReturn('token'); - $this->dbHandler->expects($this->once())->method('addToken')->with('https://url', 'token'); - $this->jobList->expects($this->once())->method('add') - ->with('OCA\Federation\BackgroundJob\RequestSharedSecret', - ['url' => 'https://url', 'token' => 'token', 'created' => 1234567]); - } else { - $this->jobList->expects($this->never())->method('add'); - } - - $this->assertSame($success, - $trustedServers->addServer('url') - ); - } - - public function dataTrueFalse() { - return [ - [true], - [false] - ]; - } - - /** - * @dataProvider dataTrueFalse - * - * @param bool $status - */ - public function testSetAutoAddServers($status) { - if ($status) { - $this->config->expects($this->once())->method('setAppValue') - ->with('federation', 'autoAddServers', '1'); - } else { - $this->config->expects($this->once())->method('setAppValue') - ->with('federation', 'autoAddServers', '0'); - } - - $this->trustedServers->setAutoAddServers($status); - } + ->willReturn(1); - /** - * @dataProvider dataTestGetAutoAddServers - * - * @param string $status - * @param bool $expected - */ - public function testGetAutoAddServers($status, $expected) { - $this->config->expects($this->once())->method('getAppValue') - ->with('federation', 'autoAddServers', '0')->willReturn($status); + $this->secureRandom->expects($this->once())->method('generate') + ->willReturn('token'); + $this->dbHandler->expects($this->once())->method('addToken')->with('https://url', 'token'); + $this->jobList->expects($this->once())->method('add') + ->with(RequestSharedSecret::class, + ['url' => 'https://url', 'token' => 'token', 'created' => 1234567]); - $this->assertSame($expected, - $this->trustedServers->getAutoAddServers() + $this->assertSame( + 1, + $trustedServers->addServer('url') ); } - public function dataTestGetAutoAddServers() { - return [ - ['1', true], - ['0', false] - ]; - } - - public function testAddSharedSecret() { + public function testAddSharedSecret(): void { $this->dbHandler->expects($this->once())->method('addSharedSecret') ->with('url', 'secret'); $this->trustedServers->addSharedSecret('url', 'secret'); } - public function testGetSharedSecret() { - $this->dbHandler->expects($this->once())->method('getSharedSecret') - ->with('url')->willReturn(true); - $this->assertTrue( - $this->trustedServers->getSharedSecret('url') + public function testGetSharedSecret(): void { + $this->dbHandler->expects($this->once()) + ->method('getSharedSecret') + ->with('url') + ->willReturn('secret'); + $this->assertSame( + $this->trustedServers->getSharedSecret('url'), + 'secret' ); } - public function testRemoveServer() { + public function testRemoveServer(): void { $id = 42; $server = ['url_hash' => 'url_hash']; $this->dbHandler->expects($this->once())->method('removeServer')->with($id); $this->dbHandler->expects($this->once())->method('getServerById')->with($id) ->willReturn($server); - $this->dispatcher->expects($this->once())->method('dispatch') + $this->dispatcher->expects($this->once())->method('dispatchTyped') ->willReturnCallback( - function ($eventId, $event) { - $this->assertSame($eventId, 'OCP\Federation\TrustedServerEvent::remove'); - $this->assertInstanceOf('Symfony\Component\EventDispatcher\GenericEvent', $event); - /** @var \Symfony\Component\EventDispatcher\GenericEvent $event */ - $this->assertSame('url_hash', $event->getSubject()); + function ($event): void { + $this->assertSame(get_class($event), TrustedServerRemovedEvent::class); + /** @var \OCP\Federated\Events\TrustedServerRemovedEvent $event */ + $this->assertSame('url_hash', $event->getUrlHash()); } ); $this->trustedServers->removeServer($id); } - public function testGetServers() { + public function testGetServers(): void { $this->dbHandler->expects($this->once())->method('getAllServer')->willReturn(['servers']); $this->assertEquals( @@ -236,9 +144,68 @@ class TrustedServersTest extends TestCase { ); } + public static function dataTestGetServer() { + return [ + [ + 15, + [ + 'id' => 15, + 'otherData' => 'first server', + ] + ], + [ + 16, + [ + 'id' => 16, + 'otherData' => 'second server', + ] + ], + [ + 42, + [ + 'id' => 42, + 'otherData' => 'last server', + ] + ], + [ + 108, + null + ], + ]; + } + + #[\PHPUnit\Framework\Attributes\DataProvider('dataTestGetServer')] + public function testGetServer(int $id, ?array $expectedServer): void { + $servers = [ + [ + 'id' => 15, + 'otherData' => 'first server', + ], + [ + 'id' => 16, + 'otherData' => 'second server', + ], + [ + 'id' => 42, + 'otherData' => 'last server', + ], + ]; + $this->dbHandler->expects($this->once())->method('getAllServer')->willReturn($servers); - public function testIsTrustedServer() { - $this->dbHandler->expects($this->once())->method('serverExists')->with('url') + if ($expectedServer === null) { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('No server found with ID: ' . $id); + } + + $this->assertEquals( + $expectedServer, + $this->trustedServers->getServer($id) + ); + } + + public function testIsTrustedServer(): void { + $this->dbHandler->expects($this->once()) + ->method('serverExists')->with('url') ->willReturn(true); $this->assertTrue( @@ -246,32 +213,27 @@ class TrustedServersTest extends TestCase { ); } - public function testSetServerStatus() { + public function testSetServerStatus(): void { $this->dbHandler->expects($this->once())->method('setServerStatus') - ->with('url', 'status'); - $this->trustedServers->setServerStatus('url', 'status'); + ->with('url', 1); + $this->trustedServers->setServerStatus('url', 1); } - public function testGetServerStatus() { + public function testGetServerStatus(): void { $this->dbHandler->expects($this->once())->method('getServerStatus') - ->with('url')->willReturn(true); - $this->assertTrue( - $this->trustedServers->getServerStatus('url') + ->with('url')->willReturn(1); + $this->assertSame( + $this->trustedServers->getServerStatus('url'), + 1 ); } - /** - * @dataProvider dataTestIsOwnCloudServer - * - * @param int $statusCode - * @param bool $isValidOwnCloudVersion - * @param bool $expected - */ - public function testIsOwnCloudServer($statusCode, $isValidOwnCloudVersion, $expected) { + #[\PHPUnit\Framework\Attributes\DataProvider('dataTestIsNextcloudServer')] + public function testIsNextcloudServer(int $statusCode, bool $isValidNextcloudVersion, bool $expected): void { $server = 'server1'; - /** @var \PHPUnit\Framework\MockObject\MockObject | TrustedServers $trustedServers */ - $trustedServers = $this->getMockBuilder('OCA\Federation\TrustedServers') + /** @var TrustedServers&MockObject $trustedServers */ + $trustedServers = $this->getMockBuilder(TrustedServers::class) ->setConstructorArgs( [ $this->dbHandler, @@ -284,7 +246,7 @@ class TrustedServersTest extends TestCase { $this->timeFactory ] ) - ->setMethods(['checkOwnCloudVersion']) + ->onlyMethods(['checkNextcloudVersion']) ->getMock(); $this->httpClientService->expects($this->once())->method('newClient') @@ -297,18 +259,20 @@ class TrustedServersTest extends TestCase { ->willReturn($statusCode); if ($statusCode === 200) { - $trustedServers->expects($this->once())->method('checkOwnCloudVersion') - ->willReturn($isValidOwnCloudVersion); + $this->response->expects($this->once())->method('getBody') + ->willReturn(''); + $trustedServers->expects($this->once())->method('checkNextcloudVersion') + ->willReturn($isValidNextcloudVersion); } else { - $trustedServers->expects($this->never())->method('checkOwnCloudVersion'); + $trustedServers->expects($this->never())->method('checkNextcloudVersion'); } $this->assertSame($expected, - $trustedServers->isOwnCloudServer($server) + $trustedServers->isNextcloudServer($server) ); } - public function dataTestIsOwnCloudServer() { + public static function dataTestIsNextcloudServer(): array { return [ [200, true, true], [200, false, false], @@ -316,65 +280,55 @@ class TrustedServersTest extends TestCase { ]; } - /** - * @expectedExceptionMessage simulated exception - */ - public function testIsOwnCloudServerFail() { + public function testIsNextcloudServerFail(): void { $server = 'server1'; - $this->httpClientService->expects($this->once())->method('newClient') + $this->httpClientService->expects($this->once()) + ->method('newClient') ->willReturn($this->httpClient); - $this->httpClient->expects($this->once())->method('get')->with($server . '/status.php') - ->willReturnCallback(function () { - throw new \Exception('simulated exception'); - }); + $this->httpClient->expects($this->once()) + ->method('get') + ->with($server . '/status.php') + ->willThrowException(new \Exception('simulated exception')); - $this->assertFalse($this->trustedServers->isOwnCloudServer($server)); + $this->assertFalse($this->trustedServers->isNextcloudServer($server)); } - /** - * @dataProvider dataTestCheckOwnCloudVersion - */ - public function testCheckOwnCloudVersion($status) { - $this->assertTrue($this->invokePrivate($this->trustedServers, 'checkOwnCloudVersion', [$status])); + #[\PHPUnit\Framework\Attributes\DataProvider('dataTestCheckNextcloudVersion')] + public function testCheckNextcloudVersion(string $status): void { + $this->assertTrue(self::invokePrivate($this->trustedServers, 'checkNextcloudVersion', [$status])); } - public function dataTestCheckOwnCloudVersion() { + public static function dataTestCheckNextcloudVersion(): array { return [ ['{"version":"9.0.0"}'], ['{"version":"9.1.0"}'] ]; } - /** - * @dataProvider dataTestCheckOwnCloudVersionTooLow - */ - public function testCheckOwnCloudVersionTooLow($status) { - $this->expectException(\OC\HintException::class); + #[\PHPUnit\Framework\Attributes\DataProvider('dataTestCheckNextcloudVersionTooLow')] + public function testCheckNextcloudVersionTooLow(string $status): void { + $this->expectException(HintException::class); $this->expectExceptionMessage('Remote server version is too low. 9.0 is required.'); - $this->invokePrivate($this->trustedServers, 'checkOwnCloudVersion', [$status]); + self::invokePrivate($this->trustedServers, 'checkNextcloudVersion', [$status]); } - public function dataTestCheckOwnCloudVersionTooLow() { + public static function dataTestCheckNextcloudVersionTooLow(): array { return [ ['{"version":"8.2.3"}'], ]; } - /** - * @dataProvider dataTestUpdateProtocol - * @param string $url - * @param string $expected - */ - public function testUpdateProtocol($url, $expected) { + #[\PHPUnit\Framework\Attributes\DataProvider('dataTestUpdateProtocol')] + public function testUpdateProtocol(string $url, string $expected): void { $this->assertSame($expected, - $this->invokePrivate($this->trustedServers, 'updateProtocol', [$url]) + self::invokePrivate($this->trustedServers, 'updateProtocol', [$url]) ); } - public function dataTestUpdateProtocol() { + public static function dataTestUpdateProtocol(): array { return [ ['http://owncloud.org', 'http://owncloud.org'], ['https://owncloud.org', 'https://owncloud.org'], |