diff options
Diffstat (limited to 'apps/federation/tests')
18 files changed, 1443 insertions, 1548 deletions
diff --git a/apps/federation/tests/BackgroundJob/GetSharedSecretTest.php b/apps/federation/tests/BackgroundJob/GetSharedSecretTest.php new file mode 100644 index 00000000000..943bdf352de --- /dev/null +++ b/apps/federation/tests/BackgroundJob/GetSharedSecretTest.php @@ -0,0 +1,262 @@ +<?php + +declare(strict_types=1); +/** + * 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; +use OCA\Federation\BackgroundJob\GetSharedSecret; +use OCA\Federation\TrustedServers; +use OCA\Files_Sharing\Tests\TestCase; +use OCP\AppFramework\Http; +use OCP\AppFramework\Utility\ITimeFactory; +use OCP\BackgroundJob\IJobList; +use OCP\Http\Client\IClient; +use OCP\Http\Client\IClientService; +use OCP\Http\Client\IResponse; +use OCP\IConfig; +use OCP\IURLGenerator; +use OCP\OCS\IDiscoveryService; +use PHPUnit\Framework\MockObject\MockObject; +use Psr\Log\LoggerInterface; + +/** + * Class GetSharedSecretTest + * + * @group DB + * + * @package OCA\Federation\Tests\BackgroundJob + */ +class GetSharedSecretTest extends TestCase { + + 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; + + private GetSharedSecret $getSharedSecret; + + 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->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); + + $this->getSharedSecret = new GetSharedSecret( + $this->httpClientService, + $this->urlGenerator, + $this->jobList, + $this->trustedServers, + $this->logger, + $this->discoverService, + $this->timeFactory, + $this->config, + ); + } + + #[\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, + $this->urlGenerator, + $this->jobList, + $this->trustedServers, + $this->logger, + $this->discoverService, + $this->timeFactory, + $this->config, + ] + ) + ->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('parentStart'); + } else { + $getSharedSecret->expects($this->never())->method('parentStart'); + } + self::invokePrivate($getSharedSecret, 'retainJob', [$retainBackgroundJob]); + $this->jobList->expects($this->once())->method('remove'); + + $this->timeFactory->method('getTime')->willReturn(42); + + if ($retainBackgroundJob) { + $this->jobList->expects($this->once()) + ->method('add') + ->with( + GetSharedSecret::class, + [ + 'url' => 'url', + 'token' => 'token', + 'created' => 42, + ] + ); + } else { + $this->jobList->expects($this->never())->method('add'); + } + + $getSharedSecret->start($this->jobList); + } + + public static function dataTestExecute(): array { + return [ + [true, true], + [true, false], + [false, false], + ]; + } + + #[\PHPUnit\Framework\Attributes\DataProvider('dataTestRun')] + public function testRun(int $statusCode): void { + $target = 'targetURL'; + $source = 'sourceURL'; + $token = 'token'; + + $argument = ['url' => $target, 'token' => $token]; + + $this->timeFactory->method('getTime') + ->willReturn(42); + + $this->urlGenerator->expects($this->once())->method('getAbsoluteURL')->with('/') + ->willReturn($source); + $this->httpClient->expects($this->once())->method('get') + ->with( + $target . '/ocs/v2.php/apps/federation/api/v1/shared-secret', + [ + 'query' => [ + '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); + + if ($statusCode === Http::STATUS_OK) { + $this->response->expects($this->once())->method('getBody') + ->willReturn('{"ocs":{"data":{"sharedSecret":"secret"}}}'); + $this->trustedServers->expects($this->once())->method('addSharedSecret') + ->with($target, 'secret'); + } else { + $this->trustedServers->expects($this->never())->method('addSharedSecret'); + } + + self::invokePrivate($this->getSharedSecret, 'run', [$argument]); + if ( + $statusCode !== Http::STATUS_OK + && $statusCode !== Http::STATUS_FORBIDDEN + ) { + $this->assertTrue(self::invokePrivate($this->getSharedSecret, 'retainJob')); + } else { + $this->assertFalse(self::invokePrivate($this->getSharedSecret, 'retainJob')); + } + } + + public static function dataTestRun(): array { + return [ + [Http::STATUS_OK], + [Http::STATUS_FORBIDDEN], + [Http::STATUS_CONFLICT], + ]; + } + + public function testRunExpired(): void { + $target = 'targetURL'; + $source = 'sourceURL'; + $token = 'token'; + $created = 42; + + $argument = [ + 'url' => $target, + 'token' => $token, + 'created' => $created, + ]; + + $this->urlGenerator->expects($this->once()) + ->method('getAbsoluteURL') + ->with('/') + ->willReturn($source); + + $this->timeFactory->method('getTime') + ->willReturn($created + 2592000 + 1); + + $this->trustedServers->expects($this->once()) + ->method('setServerStatus') + ->with( + $target, + TrustedServers::STATUS_FAILURE + ); + + self::invokePrivate($this->getSharedSecret, 'run', [$argument]); + } + + public function testRunConnectionError(): void { + $target = 'targetURL'; + $source = 'sourceURL'; + $token = 'token'; + + $argument = ['url' => $target, 'token' => $token]; + + $this->timeFactory->method('getTime') + ->willReturn(42); + + $this->urlGenerator + ->expects($this->once()) + ->method('getAbsoluteURL') + ->with('/') + ->willReturn($source); + $this->httpClient->expects($this->once())->method('get') + ->with( + $target . '/ocs/v2.php/apps/federation/api/v1/shared-secret', + [ + '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'); + + self::invokePrivate($this->getSharedSecret, 'run', [$argument]); + + $this->assertTrue(self::invokePrivate($this->getSharedSecret, 'retainJob')); + } +} diff --git a/apps/federation/tests/BackgroundJob/RequestSharedSecretTest.php b/apps/federation/tests/BackgroundJob/RequestSharedSecretTest.php new file mode 100644 index 00000000000..6ef579c7483 --- /dev/null +++ b/apps/federation/tests/BackgroundJob/RequestSharedSecretTest.php @@ -0,0 +1,243 @@ +<?php + +declare(strict_types=1); +/** + * 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; +use OCA\Federation\BackgroundJob\RequestSharedSecret; +use OCA\Federation\TrustedServers; +use OCP\AppFramework\Http; +use OCP\AppFramework\Utility\ITimeFactory; +use OCP\BackgroundJob\IJobList; +use OCP\Http\Client\IClient; +use OCP\Http\Client\IClientService; +use OCP\Http\Client\IResponse; +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 { + 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->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); + + $this->requestSharedSecret = new RequestSharedSecret( + $this->httpClientService, + $this->urlGenerator, + $this->jobList, + $this->trustedServers, + $this->discoveryService, + $this->logger, + $this->timeFactory, + $this->config, + ); + } + + #[\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, + $this->urlGenerator, + $this->jobList, + $this->trustedServers, + $this->discoveryService, + $this->logger, + $this->timeFactory, + $this->config, + ] + ) + ->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('parentStart'); + } else { + $requestSharedSecret->expects($this->never())->method('parentStart'); + } + self::invokePrivate($requestSharedSecret, 'retainJob', [$retainBackgroundJob]); + $this->jobList->expects($this->once())->method('remove'); + + $this->timeFactory->method('getTime')->willReturn(42); + + if ($retainBackgroundJob) { + $this->jobList->expects($this->once()) + ->method('add') + ->with( + RequestSharedSecret::class, + [ + 'url' => 'url', + 'token' => 'token', + 'created' => 42, + 'attempt' => 1, + ] + ); + } else { + $this->jobList->expects($this->never())->method('add'); + } + + $requestSharedSecret->start($this->jobList); + } + + public static function dataTestStart(): array { + return [ + [true, true], + [true, false], + [false, false], + ]; + } + + #[\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, 'attempt' => $attempt]; + + $this->timeFactory->method('getTime')->willReturn(42); + + $this->urlGenerator->expects($this->once())->method('getAbsoluteURL')->with('/') + ->willReturn($source); + $this->httpClient->expects($this->once())->method('post') + ->with( + $target . '/ocs/v2.php/apps/federation/api/v1/request-shared-secret', + [ + '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); + + self::invokePrivate($this->requestSharedSecret, 'run', [$argument]); + if ( + $statusCode !== Http::STATUS_OK + && ($statusCode !== Http::STATUS_FORBIDDEN || $attempt < 5) + ) { + $this->assertTrue(self::invokePrivate($this->requestSharedSecret, 'retainJob')); + } else { + $this->assertFalse(self::invokePrivate($this->requestSharedSecret, 'retainJob')); + } + } + + public static function dataTestRun(): array { + return [ + [Http::STATUS_OK], + [Http::STATUS_FORBIDDEN, 5], + [Http::STATUS_FORBIDDEN], + [Http::STATUS_CONFLICT], + ]; + } + + public function testRunExpired(): void { + $target = 'targetURL'; + $source = 'sourceURL'; + $token = 'token'; + $created = 42; + + $argument = [ + 'url' => $target, + 'token' => $token, + 'created' => $created, + ]; + + $this->urlGenerator->expects($this->once()) + ->method('getAbsoluteURL') + ->with('/') + ->willReturn($source); + + $this->timeFactory->method('getTime') + ->willReturn($created + 2592000 + 1); + + $this->trustedServers->expects($this->once()) + ->method('setServerStatus') + ->with( + $target, + TrustedServers::STATUS_FAILURE + ); + + self::invokePrivate($this->requestSharedSecret, 'run', [$argument]); + } + + public function testRunConnectionError(): void { + $target = 'targetURL'; + $source = 'sourceURL'; + $token = 'token'; + + $argument = ['url' => $target, 'token' => $token]; + + $this->timeFactory->method('getTime')->willReturn(42); + + $this->urlGenerator + ->expects($this->once()) + ->method('getAbsoluteURL') + ->with('/') + ->willReturn($source); + + $this->httpClient + ->expects($this->once()) + ->method('post') + ->with( + $target . '/ocs/v2.php/apps/federation/api/v1/request-shared-secret', + [ + 'body' => [ + 'url' => $source, + 'token' => $token, + 'format' => 'json', + ], + 'timeout' => 3, + 'connect_timeout' => 3, + 'verify' => true, + ] + )->willThrowException($this->createMock(ConnectException::class)); + + 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 new file mode 100644 index 00000000000..a054277c5cd --- /dev/null +++ b/apps/federation/tests/Controller/OCSAuthAPIControllerTest.php @@ -0,0 +1,167 @@ +<?php + +declare(strict_types=1); +/** + * 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\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 { + 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 int $currentTime = 1234567; + + protected function setUp(): void { + parent::setUp(); + + $this->request = $this->createMock(IRequest::class); + $this->secureRandom = $this->createMock(ISecureRandom::class); + $this->trustedServers = $this->createMock(TrustedServers::class); + $this->dbHandler = $this->createMock(DbHandler::class); + $this->jobList = $this->createMock(JobList::class); + $this->logger = $this->createMock(LoggerInterface::class); + $this->timeFactory = $this->createMock(ITimeFactory::class); + $this->throttler = $this->createMock(IThrottler::class); + + $this->ocsAuthApi = new OCSAuthAPIController( + 'federation', + $this->request, + $this->secureRandom, + $this->jobList, + $this->trustedServers, + $this->dbHandler, + $this->logger, + $this->timeFactory, + $this->throttler + ); + + $this->timeFactory->method('getTime') + ->willReturn($this->currentTime); + } + + #[\PHPUnit\Framework\Attributes\DataProvider('dataTestRequestSharedSecret')] + public function testRequestSharedSecret(string $token, string $localToken, bool $isTrustedServer, bool $ok): void { + $url = 'url'; + + $this->trustedServers + ->expects($this->once()) + ->method('isTrustedServer')->with($url)->willReturn($isTrustedServer); + $this->dbHandler->expects($this->any()) + ->method('getToken')->with($url)->willReturn($localToken); + + if ($ok) { + $this->jobList->expects($this->once())->method('add') + ->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); + } catch (OCSForbiddenException $e) { + $this->assertFalse($ok); + } + } + + public static function dataTestRequestSharedSecret(): array { + return [ + ['token2', 'token1', true, true], + ['token1', 'token2', false, false], + ['token1', 'token2', true, false], + ]; + } + + #[\PHPUnit\Framework\Attributes\DataProvider('dataTestGetSharedSecret')] + public function testGetSharedSecret(bool $isTrustedServer, bool $isValidToken, bool $ok): void { + $url = 'url'; + $token = 'token'; + + /** @var OCSAuthAPIController&MockObject $ocsAuthApi */ + $ocsAuthApi = $this->getMockBuilder(OCSAuthAPIController::class) + ->setConstructorArgs( + [ + 'federation', + $this->request, + $this->secureRandom, + $this->jobList, + $this->trustedServers, + $this->dbHandler, + $this->logger, + $this->timeFactory, + $this->throttler + ] + ) + ->onlyMethods(['isValidToken']) + ->getMock(); + + $this->trustedServers + ->expects($this->any()) + ->method('isTrustedServer')->with($url)->willReturn($isTrustedServer); + $ocsAuthApi->expects($this->any()) + ->method('isValidToken')->with($url, $token)->willReturn($isValidToken); + + if ($ok) { + $this->secureRandom->expects($this->once())->method('generate')->with(32) + ->willReturn('secret'); + $this->trustedServers->expects($this->once()) + ->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 { + $result = $ocsAuthApi->getSharedSecret($url, $token); + $this->assertTrue($ok); + $data = $result->getData(); + $this->assertSame('secret', $data['sharedSecret']); + } catch (OCSForbiddenException $e) { + $this->assertFalse($ok); + } + } + + public static function dataTestGetSharedSecret(): array { + return [ + [true, true, true], + [false, true, false], + [true, false, false], + [false, false, false], + ]; + } +} diff --git a/apps/federation/tests/Controller/SettingsControllerTest.php b/apps/federation/tests/Controller/SettingsControllerTest.php new file mode 100644 index 00000000000..b0a7a5e30c9 --- /dev/null +++ b/apps/federation/tests/Controller/SettingsControllerTest.php @@ -0,0 +1,146 @@ +<?php + +declare(strict_types=1); +/** + * 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; + + 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->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->logger, + ); + } + + public function testAddServer(): void { + $this->trustedServers + ->expects($this->once()) + ->method('isTrustedServer') + ->with('url') + ->willReturn(false); + $this->trustedServers + ->expects($this->once()) + ->method('isNextcloudServer') + ->with('url') + ->willReturn(true); + + $result = $this->controller->addServer('url'); + $this->assertInstanceOf(DataResponse::class, $result); + + $data = $result->getData(); + $this->assertSame(200, $result->getStatus()); + $this->assertSame('url', $data['url']); + $this->assertArrayHasKey('id', $data); + } + + #[\PHPUnit\Framework\Attributes\DataProvider('checkServerFails')] + public function testAddServerFail(bool $isTrustedServer, bool $isNextcloud): void { + $this->trustedServers + ->expects($this->any()) + ->method('isTrustedServer') + ->with('url') + ->willReturn($isTrustedServer); + $this->trustedServers + ->expects($this->any()) + ->method('isNextcloudServer') + ->with('url') + ->willReturn($isNextcloud); + + if ($isTrustedServer) { + $this->expectException(OCSException::class); + } else { + $this->expectException(OCSNotFoundException::class); + } + + $this->controller->addServer('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(): void { + $this->trustedServers + ->expects($this->once()) + ->method('isTrustedServer') + ->with('url') + ->willReturn(false); + $this->trustedServers + ->expects($this->once()) + ->method('isNextcloudServer') + ->with('url') + ->willReturn(true); + + $this->assertNull( + self::invokePrivate($this->controller, 'checkServer', ['url']) + ); + } + + #[\PHPUnit\Framework\Attributes\DataProvider('checkServerFails')] + public function testCheckServerFail(bool $isTrustedServer, bool $isNextcloud): void { + $this->trustedServers + ->expects($this->any()) + ->method('isTrustedServer') + ->with('url') + ->willReturn($isTrustedServer); + $this->trustedServers + ->expects($this->any()) + ->method('isNextcloudServer') + ->with('url') + ->willReturn($isNextcloud); + + if ($isTrustedServer) { + $this->expectException(OCSException::class); + } else { + $this->expectException(OCSNotFoundException::class); + } + + $this->assertTrue( + self::invokePrivate($this->controller, 'checkServer', ['url']) + ); + } + + 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 new file mode 100644 index 00000000000..c95d3852b48 --- /dev/null +++ b/apps/federation/tests/DAV/FedAuthTest.php @@ -0,0 +1,33 @@ +<?php + +declare(strict_types=1); +/** + * 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 { + + #[\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 = self::invokePrivate($auth, 'validateUserPass', [$user, $password]); + $this->assertEquals($expected, $result); + } + + public static function providesUser(): array { + return [ + [true, 'system', '123456'] + ]; + } +} diff --git a/apps/federation/tests/lib/dbhandlertest.php b/apps/federation/tests/DbHandlerTest.php index 3ded486d36a..5452a48fc4a 100644 --- a/apps/federation/tests/lib/dbhandlertest.php +++ b/apps/federation/tests/DbHandlerTest.php @@ -1,57 +1,35 @@ <?php + +declare(strict_types=1); /** - * @author Björn Schießle <schiessle@owncloud.com> - * @author Thomas Müller <thomas.mueller@tmit.eu> - * - * @copyright Copyright (c) 2016, ownCloud, Inc. - * @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\lib; - +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 { + private DbHandler $dbHandler; + private IL10N&MockObject $il10n; + private IDBConnection $connection; + private string $dbTable = 'trusted_servers'; - /** @var DbHandler */ - private $dbHandler; - - /** @var IL10N | \PHPUnit_Framework_MockObject_MockObject */ - private $il10n; - - /** @var IDBConnection */ - private $connection; - - /** @var string */ - private $dbTable = 'trusted_servers'; - - public function setUp() { + protected function setUp(): void { parent::setUp(); - $this->connection = \OC::$server->getDatabaseConnection(); - $this->il10n = $this->getMock('OCP\IL10N'); + $this->connection = Server::get(IDBConnection::class); + $this->il10n = $this->createMock(IL10N::class); $this->dbHandler = new DbHandler( $this->connection, @@ -59,50 +37,60 @@ class DbHandlerTest extends TestCase { ); $query = $this->connection->getQueryBuilder()->select('*')->from($this->dbTable); - $result = $query->execute()->fetchAll(); + + $qResult = $query->executeQuery(); + $result = $qResult->fetchAll(); + $qResult->closeCursor(); $this->assertEmpty($result, 'we need to start with a empty trusted_servers table'); } - public function tearDown() { - parent::tearDown(); + protected function tearDown(): void { $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); - $result = $query->execute()->fetchAll(); - $this->assertSame(1, count($result)); + + $qResult = $query->execute(); + $result = $qResult->fetchAll(); + $qResult->closeCursor(); + $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')], - ['http://owncloud.org/', 'http://owncloud.org', sha1('owncloud.org')], + ['http://owncloud.org', 'http://owncloud.org', sha1('owncloud.org')], + ['https://owncloud.org', 'https://owncloud.org', sha1('owncloud.org')], + ['http://owncloud.org/', 'http://owncloud.org', sha1('owncloud.org')], ]; } - public function testRemove() { + public function testRemove(): void { $id1 = $this->dbHandler->addServer('server1'); $id2 = $this->dbHandler->addServer('server2'); $query = $this->connection->getQueryBuilder()->select('*')->from($this->dbTable); - $result = $query->execute()->fetchAll(); - $this->assertSame(2, count($result)); + + $qResult = $query->execute(); + $result = $qResult->fetchAll(); + $qResult->closeCursor(); + $this->assertCount(2, $result); $this->assertSame('server1', $result[0]['url']); $this->assertSame('server2', $result[1]['url']); $this->assertSame($id1, (int)$result[0]['id']); @@ -110,14 +98,17 @@ class DbHandlerTest extends TestCase { $this->dbHandler->removeServer($id2); $query = $this->connection->getQueryBuilder()->select('*')->from($this->dbTable); - $result = $query->execute()->fetchAll(); - $this->assertSame(1, count($result)); + + $qResult = $query->execute(); + $result = $qResult->fetchAll(); + $qResult->closeCursor(); + $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'); @@ -125,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'); @@ -137,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], @@ -159,20 +144,26 @@ class DbHandlerTest extends TestCase { ]; } - public function testAddToken() { + public function XtestAddToken() { $this->dbHandler->addServer('server1'); $query = $this->connection->getQueryBuilder()->select('*')->from($this->dbTable); - $result = $query->execute()->fetchAll(); - $this->assertSame(1, count($result)); + + $qResult = $query->executeQuery(); + $result = $qResult->fetchAll(); + $qResult->closeCursor(); + $this->assertCount(1, $result); $this->assertSame(null, $result[0]['token']); $this->dbHandler->addToken('http://server1', 'token'); $query = $this->connection->getQueryBuilder()->select('*')->from($this->dbTable); - $result = $query->execute()->fetchAll(); - $this->assertSame(1, count($result)); + + $qResult = $query->executeQuery(); + $result = $qResult->fetchAll(); + $qResult->closeCursor(); + $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', @@ -180,20 +171,26 @@ class DbHandlerTest extends TestCase { ); } - public function testAddSharedSecret() { + public function XtestAddSharedSecret() { $this->dbHandler->addServer('server1'); $query = $this->connection->getQueryBuilder()->select('*')->from($this->dbTable); - $result = $query->execute()->fetchAll(); - $this->assertSame(1, count($result)); + + $qResult = $query->execute(); + $result = $qResult->fetchAll(); + $qResult->closeCursor(); + $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); - $result = $query->execute()->fetchAll(); - $this->assertSame(1, count($result)); + + $qResult = $query->execute(); + $result = $qResult->fetchAll(); + $qResult->closeCursor(); + $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', @@ -201,20 +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); - $result = $query->execute()->fetchAll(); - $this->assertSame(1, count($result)); + + $qResult = $query->executeQuery(); + $result = $qResult->fetchAll(); + $qResult->closeCursor(); + $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); - $result = $query->execute()->fetchAll(); - $this->assertSame(1, count($result)); + + $qResult = $query->executeQuery(); + $result = $qResult->fetchAll(); + $qResult->closeCursor(); + $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, @@ -229,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')], @@ -250,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'], @@ -272,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); @@ -284,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/Settings/AdminTest.php b/apps/federation/tests/Settings/AdminTest.php new file mode 100644 index 00000000000..b879547a8cd --- /dev/null +++ b/apps/federation/tests/Settings/AdminTest.php @@ -0,0 +1,50 @@ +<?php + +declare(strict_types=1); +/** + * 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 { + private TrustedServers&MockObject $trustedServers; + private Admin $admin; + + protected function setUp(): void { + parent::setUp(); + $this->trustedServers = $this->createMock(TrustedServers::class); + $this->admin = new Admin( + $this->trustedServers, + $this->createMock(IL10N::class) + ); + } + + public function testGetForm(): void { + $this->trustedServers + ->expects($this->once()) + ->method('getServers') + ->willReturn(['myserver', 'secondserver']); + + $params = [ + 'trustedServers' => ['myserver', 'secondserver'], + ]; + $expected = new TemplateResponse('federation', 'settings-admin', $params, ''); + $this->assertEquals($expected, $this->admin->getForm()); + } + + public function testGetSection(): void { + $this->assertSame('sharing', $this->admin->getSection()); + } + + public function testGetPriority(): void { + $this->assertSame(30, $this->admin->getPriority()); + } +} diff --git a/apps/federation/tests/SyncFederationAddressbooksTest.php b/apps/federation/tests/SyncFederationAddressbooksTest.php new file mode 100644 index 00000000000..ff03f5cf442 --- /dev/null +++ b/apps/federation/tests/SyncFederationAddressbooksTest.php @@ -0,0 +1,108 @@ +<?php + +declare(strict_types=1); +/** + * 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 { + private array $callBacks = []; + private DiscoveryService&MockObject $discoveryService; + private LoggerInterface&MockObject $logger; + + protected function setUp(): void { + parent::setUp(); + + $this->discoveryService = $this->createMock(DiscoveryService::class); + $this->discoveryService->expects($this->any())->method('discover')->willReturn([]); + $this->logger = $this->createMock(LoggerInterface::class); + } + + public function testSync(): 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->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', false]); + + /** @var SyncService $syncService */ + $s = new SyncFederationAddressBooks($dbHandler, $syncService, $this->discoveryService, $this->logger); + $s->syncThemAll(function ($url, $ex): void { + $this->callBacks[] = [$url, $ex]; + }); + $this->assertCount(1, $this->callBacks); + } + + 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 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->assertCount(1, $this->callBacks); + } +} diff --git a/apps/federation/tests/TrustedServersTest.php b/apps/federation/tests/TrustedServersTest.php new file mode 100644 index 00000000000..0c900f6edf7 --- /dev/null +++ b/apps/federation/tests/TrustedServersTest.php @@ -0,0 +1,339 @@ +<?php + +declare(strict_types=1); +/** + * 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\Security\ISecureRandom; +use PHPUnit\Framework\MockObject\MockObject; +use Psr\Log\LoggerInterface; +use Test\TestCase; + +class TrustedServersTest extends TestCase { + 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->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( + $this->dbHandler, + $this->httpClientService, + $this->logger, + $this->jobList, + $this->secureRandom, + $this->config, + $this->dispatcher, + $this->timeFactory + ); + } + + public function testAddServer(): void { + /** @var TrustedServers&MockObject $trustedServers */ + $trustedServers = $this->getMockBuilder(TrustedServers::class) + ->setConstructorArgs( + [ + $this->dbHandler, + $this->httpClientService, + $this->logger, + $this->jobList, + $this->secureRandom, + $this->config, + $this->dispatcher, + $this->timeFactory + ] + ) + ->onlyMethods(['updateProtocol']) + ->getMock(); + $trustedServers->expects($this->once())->method('updateProtocol') + ->with('url')->willReturn('https://url'); + $this->timeFactory->method('getTime') + ->willReturn(1234567); + $this->dbHandler->expects($this->once())->method('addServer')->with('https://url') + ->willReturn(1); + + $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( + 1, + $trustedServers->addServer('url') + ); + } + + public function testAddSharedSecret(): void { + $this->dbHandler->expects($this->once())->method('addSharedSecret') + ->with('url', 'secret'); + $this->trustedServers->addSharedSecret('url', 'secret'); + } + + 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(): 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('dispatchTyped') + ->willReturnCallback( + 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(): void { + $this->dbHandler->expects($this->once())->method('getAllServer')->willReturn(['servers']); + + $this->assertEquals( + ['servers'], + $this->trustedServers->getServers() + ); + } + + 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); + + 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( + $this->trustedServers->isTrustedServer('url') + ); + } + + public function testSetServerStatus(): void { + $this->dbHandler->expects($this->once())->method('setServerStatus') + ->with('url', 1); + $this->trustedServers->setServerStatus('url', 1); + } + + public function testGetServerStatus(): void { + $this->dbHandler->expects($this->once())->method('getServerStatus') + ->with('url')->willReturn(1); + $this->assertSame( + $this->trustedServers->getServerStatus('url'), + 1 + ); + } + + #[\PHPUnit\Framework\Attributes\DataProvider('dataTestIsNextcloudServer')] + public function testIsNextcloudServer(int $statusCode, bool $isValidNextcloudVersion, bool $expected): void { + $server = 'server1'; + + /** @var TrustedServers&MockObject $trustedServers */ + $trustedServers = $this->getMockBuilder(TrustedServers::class) + ->setConstructorArgs( + [ + $this->dbHandler, + $this->httpClientService, + $this->logger, + $this->jobList, + $this->secureRandom, + $this->config, + $this->dispatcher, + $this->timeFactory + ] + ) + ->onlyMethods(['checkNextcloudVersion']) + ->getMock(); + + $this->httpClientService->expects($this->once())->method('newClient') + ->willReturn($this->httpClient); + + $this->httpClient->expects($this->once())->method('get')->with($server . '/status.php') + ->willReturn($this->response); + + $this->response->expects($this->once())->method('getStatusCode') + ->willReturn($statusCode); + + if ($statusCode === 200) { + $this->response->expects($this->once())->method('getBody') + ->willReturn(''); + $trustedServers->expects($this->once())->method('checkNextcloudVersion') + ->willReturn($isValidNextcloudVersion); + } else { + $trustedServers->expects($this->never())->method('checkNextcloudVersion'); + } + + $this->assertSame($expected, + $trustedServers->isNextcloudServer($server) + ); + } + + public static function dataTestIsNextcloudServer(): array { + return [ + [200, true, true], + [200, false, false], + [404, true, false], + ]; + } + + public function testIsNextcloudServerFail(): void { + $server = 'server1'; + + $this->httpClientService->expects($this->once()) + ->method('newClient') + ->willReturn($this->httpClient); + + $this->httpClient->expects($this->once()) + ->method('get') + ->with($server . '/status.php') + ->willThrowException(new \Exception('simulated exception')); + + $this->assertFalse($this->trustedServers->isNextcloudServer($server)); + } + + #[\PHPUnit\Framework\Attributes\DataProvider('dataTestCheckNextcloudVersion')] + public function testCheckNextcloudVersion(string $status): void { + $this->assertTrue(self::invokePrivate($this->trustedServers, 'checkNextcloudVersion', [$status])); + } + + public static function dataTestCheckNextcloudVersion(): array { + return [ + ['{"version":"9.0.0"}'], + ['{"version":"9.1.0"}'] + ]; + } + + #[\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.'); + + self::invokePrivate($this->trustedServers, 'checkNextcloudVersion', [$status]); + } + + public static function dataTestCheckNextcloudVersionTooLow(): array { + return [ + ['{"version":"8.2.3"}'], + ]; + } + + #[\PHPUnit\Framework\Attributes\DataProvider('dataTestUpdateProtocol')] + public function testUpdateProtocol(string $url, string $expected): void { + $this->assertSame($expected, + self::invokePrivate($this->trustedServers, 'updateProtocol', [$url]) + ); + } + + public static function dataTestUpdateProtocol(): array { + return [ + ['http://owncloud.org', 'http://owncloud.org'], + ['https://owncloud.org', 'https://owncloud.org'], + ['owncloud.org', 'https://owncloud.org'], + ['httpserver', 'https://httpserver'], + ]; + } +} diff --git a/apps/federation/tests/api/ocsauthapitest.php b/apps/federation/tests/api/ocsauthapitest.php deleted file mode 100644 index d3e61c0641a..00000000000 --- a/apps/federation/tests/api/ocsauthapitest.php +++ /dev/null @@ -1,194 +0,0 @@ -<?php -/** - * @author Björn Schießle <schiessle@owncloud.com> - * @author Robin Appelman <icewind@owncloud.com> - * - * @copyright Copyright (c) 2016, ownCloud, Inc. - * @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\API; - - -use OC\BackgroundJob\JobList; -use OCA\Federation\API\OCSAuthAPI; -use OCA\Federation\DbHandler; -use OCA\Federation\TrustedServers; -use OCP\AppFramework\Http; -use OCP\ILogger; -use OCP\IRequest; -use OCP\Security\ISecureRandom; -use Test\TestCase; - -class OCSAuthAPITest 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 OCSAuthApi */ - private $ocsAuthApi; - - public function setUp() { - parent::setUp(); - - $this->request = $this->getMock('OCP\IRequest'); - $this->secureRandom = $this->getMock('OCP\Security\ISecureRandom'); - $this->trustedServers = $this->getMockBuilder('OCA\Federation\TrustedServers') - ->disableOriginalConstructor()->getMock(); - $this->dbHandler = $this->getMockBuilder('OCA\Federation\DbHandler') - ->disableOriginalConstructor()->getMock(); - $this->jobList = $this->getMockBuilder('OC\BackgroundJob\JobList') - ->disableOriginalConstructor()->getMock(); - $this->logger = $this->getMockBuilder('OCP\ILogger') - ->disableOriginalConstructor()->getMock(); - - $this->ocsAuthApi = new OCSAuthAPI( - $this->request, - $this->secureRandom, - $this->jobList, - $this->trustedServers, - $this->dbHandler, - $this->logger - ); - - } - - /** - * @dataProvider dataTestRequestSharedSecret - * - * @param string $token - * @param string $localToken - * @param bool $isTrustedServer - * @param int $expected - */ - public function testRequestSharedSecret($token, $localToken, $isTrustedServer, $expected) { - - $url = 'url'; - - $this->request->expects($this->at(0))->method('getParam')->with('url')->willReturn($url); - $this->request->expects($this->at(1))->method('getParam')->with('token')->willReturn($token); - $this->trustedServers - ->expects($this->once()) - ->method('isTrustedServer')->with($url)->willReturn($isTrustedServer); - $this->dbHandler->expects($this->any()) - ->method('getToken')->with($url)->willReturn($localToken); - - if ($expected === Http::STATUS_OK) { - $this->jobList->expects($this->once())->method('add') - ->with('OCA\Federation\BackgroundJob\GetSharedSecret', ['url' => $url, 'token' => $token]); - $this->jobList->expects($this->once())->method('remove') - ->with('OCA\Federation\BackgroundJob\RequestSharedSecret', ['url' => $url, 'token' => $localToken]); - } else { - $this->jobList->expects($this->never())->method('add'); - $this->jobList->expects($this->never())->method('remove'); - } - - $result = $this->ocsAuthApi->requestSharedSecret(); - $this->assertSame($expected, $result->getStatusCode()); - } - - public function dataTestRequestSharedSecret() { - return [ - ['token2', 'token1', true, Http::STATUS_OK], - ['token1', 'token2', false, Http::STATUS_FORBIDDEN], - ['token1', 'token2', true, Http::STATUS_FORBIDDEN], - ]; - } - - /** - * @dataProvider dataTestGetSharedSecret - * - * @param bool $isTrustedServer - * @param bool $isValidToken - * @param int $expected - */ - public function testGetSharedSecret($isTrustedServer, $isValidToken, $expected) { - - $url = 'url'; - $token = 'token'; - - $this->request->expects($this->at(0))->method('getParam')->with('url')->willReturn($url); - $this->request->expects($this->at(1))->method('getParam')->with('token')->willReturn($token); - - /** @var OCSAuthAPI | \PHPUnit_Framework_MockObject_MockObject $ocsAuthApi */ - $ocsAuthApi = $this->getMockBuilder('OCA\Federation\API\OCSAuthAPI') - ->setConstructorArgs( - [ - $this->request, - $this->secureRandom, - $this->jobList, - $this->trustedServers, - $this->dbHandler, - $this->logger - ] - )->setMethods(['isValidToken'])->getMock(); - - $this->trustedServers - ->expects($this->any()) - ->method('isTrustedServer')->with($url)->willReturn($isTrustedServer); - $ocsAuthApi->expects($this->any()) - ->method('isValidToken')->with($url, $token)->willReturn($isValidToken); - - if($expected === Http::STATUS_OK) { - $this->secureRandom->expects($this->once())->method('generate')->with(32) - ->willReturn('secret'); - $this->trustedServers->expects($this->once()) - ->method('addSharedSecret')->willReturn($url, 'secret'); - $this->dbHandler->expects($this->once()) - ->method('addToken')->with($url, ''); - } else { - $this->secureRandom->expects($this->never())->method('getMediumStrengthGenerator'); - $this->secureRandom->expects($this->never())->method('generate'); - $this->trustedServers->expects($this->never())->method('addSharedSecret'); - $this->dbHandler->expects($this->never())->method('addToken'); - } - - $result = $ocsAuthApi->getSharedSecret(); - - $this->assertSame($expected, $result->getStatusCode()); - - if ($expected === Http::STATUS_OK) { - $data = $result->getData(); - $this->assertSame('secret', $data['sharedSecret']); - } - } - - public function dataTestGetSharedSecret() { - return [ - [true, true, Http::STATUS_OK], - [false, true, Http::STATUS_FORBIDDEN], - [true, false, Http::STATUS_FORBIDDEN], - [false, false, Http::STATUS_FORBIDDEN], - ]; - } - -} diff --git a/apps/federation/tests/backgroundjob/getsharedsecrettest.php b/apps/federation/tests/backgroundjob/getsharedsecrettest.php deleted file mode 100644 index 25f7502741d..00000000000 --- a/apps/federation/tests/backgroundjob/getsharedsecrettest.php +++ /dev/null @@ -1,211 +0,0 @@ -<?php -/** - * @author Björn Schießle <schiessle@owncloud.com> - * @author Thomas Müller <thomas.mueller@tmit.eu> - * - * @copyright Copyright (c) 2016, ownCloud, Inc. - * @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\BackgroundJob; - - -use OCA\Federation\BackgroundJob\GetSharedSecret; -use OCA\Files_Sharing\Tests\TestCase; -use OCA\Federation\DbHandler; -use OCA\Federation\TrustedServers; -use OCP\AppFramework\Http; -use OCP\BackgroundJob\IJobList; -use OCP\Http\Client\IClient; -use OCP\Http\Client\IResponse; -use OCP\ILogger; -use OCP\IURLGenerator; - -/** - * Class GetSharedSecretTest - * - * @group DB - * - * @package OCA\Federation\Tests\BackgroundJob - */ -class GetSharedSecretTest extends TestCase { - - /** @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 | DbHandler */ - private $dbHandler; - - /** @var \PHPUnit_Framework_MockObject_MockObject | ILogger */ - private $logger; - - /** @var \PHPUnit_Framework_MockObject_MockObject | IResponse */ - private $response; - - /** @var GetSharedSecret */ - private $getSharedSecret; - - public function setUp() { - parent::setUp(); - - $this->httpClient = $this->getMock('OCP\Http\Client\IClient'); - $this->jobList = $this->getMock('OCP\BackgroundJob\IJobList'); - $this->urlGenerator = $this->getMock('OCP\IURLGenerator'); - $this->trustedServers = $this->getMockBuilder('OCA\Federation\TrustedServers') - ->disableOriginalConstructor()->getMock(); - $this->dbHandler = $this->getMockBuilder('OCA\Federation\DbHandler') - ->disableOriginalConstructor()->getMock(); - $this->logger = $this->getMock('OCP\ILogger'); - $this->response = $this->getMock('OCP\Http\Client\IResponse'); - - $this->getSharedSecret = new GetSharedSecret( - $this->httpClient, - $this->urlGenerator, - $this->jobList, - $this->trustedServers, - $this->logger, - $this->dbHandler - ); - } - - /** - * @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') - ->setConstructorArgs( - [ - $this->httpClient, - $this->urlGenerator, - $this->jobList, - $this->trustedServers, - $this->logger, - $this->dbHandler - ] - )->setMethods(['parentExecute'])->getMock(); - $this->invokePrivate($getSharedSecret, 'argument', [['url' => 'url']]); - - $this->trustedServers->expects($this->once())->method('isTrustedServer') - ->with('url')->willReturn($isTrustedServer); - if ($isTrustedServer) { - $getSharedSecret->expects($this->once())->method('parentExecute'); - } else { - $getSharedSecret->expects($this->never())->method('parentExecute'); - } - $this->invokePrivate($getSharedSecret, 'retainJob', [$retainBackgroundJob]); - if ($retainBackgroundJob) { - $this->jobList->expects($this->never())->method('remove'); - } else { - $this->jobList->expects($this->once())->method('remove'); - } - - $getSharedSecret->execute($this->jobList); - - } - - public function dataTestExecute() { - return [ - [true, true], - [true, false], - [false, false], - ]; - } - - /** - * @dataProvider dataTestRun - * - * @param int $statusCode - */ - public function testRun($statusCode) { - - $target = 'targetURL'; - $source = 'sourceURL'; - $token = 'token'; - - $argument = ['url' => $target, 'token' => $token]; - - $this->urlGenerator->expects($this->once())->method('getAbsoluteURL')->with('/') - ->willReturn($source); - $this->httpClient->expects($this->once())->method('get') - ->with( - $target . '/ocs/v2.php/apps/federation/api/v1/shared-secret?format=json', - [ - 'query' => - [ - 'url' => $source, - 'token' => $token - ], - 'timeout' => 3, - 'connect_timeout' => 3, - ] - )->willReturn($this->response); - - $this->response->expects($this->once())->method('getStatusCode') - ->willReturn($statusCode); - - if ( - $statusCode !== Http::STATUS_OK - && $statusCode !== Http::STATUS_FORBIDDEN - ) { - $this->dbHandler->expects($this->never())->method('addToken'); - } else { - $this->dbHandler->expects($this->once())->method('addToken')->with($target, ''); - } - - if ($statusCode === Http::STATUS_OK) { - $this->response->expects($this->once())->method('getBody') - ->willReturn('{"ocs":{"data":{"sharedSecret":"secret"}}}'); - $this->trustedServers->expects($this->once())->method('addSharedSecret') - ->with($target, 'secret'); - } else { - $this->trustedServers->expects($this->never())->method('addSharedSecret'); - } - - $this->invokePrivate($this->getSharedSecret, 'run', [$argument]); - if ( - $statusCode !== Http::STATUS_OK - && $statusCode !== Http::STATUS_FORBIDDEN - ) { - $this->assertTrue($this->invokePrivate($this->getSharedSecret, 'retainJob')); - } else { - $this->assertFalse($this->invokePrivate($this->getSharedSecret, 'retainJob')); - } - - } - - public function dataTestRun() { - return [ - [Http::STATUS_OK], - [Http::STATUS_FORBIDDEN], - [Http::STATUS_CONFLICT], - ]; - } - -} diff --git a/apps/federation/tests/backgroundjob/requestsharedsecrettest.php b/apps/federation/tests/backgroundjob/requestsharedsecrettest.php deleted file mode 100644 index 5b4a1f87a5f..00000000000 --- a/apps/federation/tests/backgroundjob/requestsharedsecrettest.php +++ /dev/null @@ -1,181 +0,0 @@ -<?php -/** - * @author Björn Schießle <schiessle@owncloud.com> - * - * @copyright Copyright (c) 2016, ownCloud, Inc. - * @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\BackgroundJob; - - -use OCA\Federation\BackgroundJob\RequestSharedSecret; -use OCP\AppFramework\Http; -use Test\TestCase; - -class RequestSharedSecretTest extends TestCase { - - /** @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 | DbHandler */ - private $dbHandler; - - /** @var \PHPUnit_Framework_MockObject_MockObject | TrustedServers */ - private $trustedServers; - - /** @var \PHPUnit_Framework_MockObject_MockObject | IResponse */ - private $response; - - /** @var RequestSharedSecret */ - private $requestSharedSecret; - - public function setUp() { - parent::setUp(); - - $this->httpClient = $this->getMock('OCP\Http\Client\IClient'); - $this->jobList = $this->getMock('OCP\BackgroundJob\IJobList'); - $this->urlGenerator = $this->getMock('OCP\IURLGenerator'); - $this->trustedServers = $this->getMockBuilder('OCA\Federation\TrustedServers') - ->disableOriginalConstructor()->getMock(); - $this->dbHandler = $this->getMockBuilder('OCA\Federation\DbHandler') - ->disableOriginalConstructor()->getMock(); - $this->response = $this->getMock('OCP\Http\Client\IResponse'); - - $this->requestSharedSecret = new RequestSharedSecret( - $this->httpClient, - $this->urlGenerator, - $this->jobList, - $this->trustedServers, - $this->dbHandler - ); - } - - /** - * @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') - ->setConstructorArgs( - [ - $this->httpClient, - $this->urlGenerator, - $this->jobList, - $this->trustedServers, - $this->dbHandler - ] - )->setMethods(['parentExecute'])->getMock(); - $this->invokePrivate($requestSharedSecret, 'argument', [['url' => 'url']]); - - $this->trustedServers->expects($this->once())->method('isTrustedServer') - ->with('url')->willReturn($isTrustedServer); - if ($isTrustedServer) { - $requestSharedSecret->expects($this->once())->method('parentExecute'); - } else { - $requestSharedSecret->expects($this->never())->method('parentExecute'); - } - $this->invokePrivate($requestSharedSecret, 'retainJob', [$retainBackgroundJob]); - if ($retainBackgroundJob) { - $this->jobList->expects($this->never())->method('remove'); - } else { - $this->jobList->expects($this->once())->method('remove'); - } - - $requestSharedSecret->execute($this->jobList); - - } - - public function dataTestExecute() { - return [ - [true, true], - [true, false], - [false, false], - ]; - } - - /** - * @dataProvider dataTestRun - * - * @param int $statusCode - */ - public function testRun($statusCode) { - - $target = 'targetURL'; - $source = 'sourceURL'; - $token = 'token'; - - $argument = ['url' => $target, 'token' => $token]; - - $this->urlGenerator->expects($this->once())->method('getAbsoluteURL')->with('/') - ->willReturn($source); - $this->httpClient->expects($this->once())->method('post') - ->with( - $target . '/ocs/v2.php/apps/federation/api/v1/request-shared-secret?format=json', - [ - 'body' => - [ - 'url' => $source, - 'token' => $token - ], - 'timeout' => 3, - 'connect_timeout' => 3, - ] - )->willReturn($this->response); - - $this->response->expects($this->once())->method('getStatusCode') - ->willReturn($statusCode); - - if ( - $statusCode !== Http::STATUS_OK - && $statusCode !== Http::STATUS_FORBIDDEN - ) { - $this->dbHandler->expects($this->never())->method('addToken'); - } - - if ($statusCode === Http::STATUS_FORBIDDEN) { - $this->dbHandler->expects($this->once())->method('addToken')->with($target, ''); - } - - $this->invokePrivate($this->requestSharedSecret, 'run', [$argument]); - if ( - $statusCode !== Http::STATUS_OK - && $statusCode !== Http::STATUS_FORBIDDEN - ) { - $this->assertTrue($this->invokePrivate($this->requestSharedSecret, 'retainJob')); - } else { - $this->assertFalse($this->invokePrivate($this->requestSharedSecret, 'retainJob')); - } - } - - public function dataTestRun() { - return [ - [Http::STATUS_OK], - [Http::STATUS_FORBIDDEN], - [Http::STATUS_CONFLICT], - ]; - } -} diff --git a/apps/federation/tests/controller/settingscontrollertest.php b/apps/federation/tests/controller/settingscontrollertest.php deleted file mode 100644 index 65f7d5f91d3..00000000000 --- a/apps/federation/tests/controller/settingscontrollertest.php +++ /dev/null @@ -1,166 +0,0 @@ -<?php -/** - * @author Björn Schießle <schiessle@owncloud.com> - * - * @copyright Copyright (c) 2016, ownCloud, Inc. - * @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\Controller; - - -use OCA\Federation\Controller\SettingsController; -use OCP\AppFramework\Http\DataResponse; -use Test\TestCase; - -class SettingsControllerTest extends TestCase { - - /** @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; - - public function setUp() { - parent::setUp(); - - $this->request = $this->getMock('OCP\IRequest'); - $this->l10n = $this->getMock('OCP\IL10N'); - $this->trustedServers = $this->getMockBuilder('OCA\Federation\TrustedServers') - ->disableOriginalConstructor()->getMock(); - - $this->controller = new SettingsController( - 'SettingsControllerTest', - $this->request, - $this->l10n, - $this->trustedServers - ); - } - - public function testAddServer() { - $this->trustedServers - ->expects($this->once()) - ->method('isTrustedServer') - ->with('url') - ->willReturn(false); - $this->trustedServers - ->expects($this->once()) - ->method('isOwnCloudServer') - ->with('url') - ->willReturn(true); - - $result = $this->controller->addServer('url'); - $this->assertTrue($result instanceof DataResponse); - - $data = $result->getData(); - $this->assertSame(200, $result->getStatus()); - $this->assertSame('url', $data['url']); - $this->assertArrayHasKey('id', $data); - } - - /** - * @dataProvider checkServerFails - * @expectedException \OC\HintException - * - * @param bool $isTrustedServer - * @param bool $isOwnCloud - */ - public function testAddServerFail($isTrustedServer, $isOwnCloud) { - $this->trustedServers - ->expects($this->any()) - ->method('isTrustedServer') - ->with('url') - ->willReturn($isTrustedServer); - $this->trustedServers - ->expects($this->any()) - ->method('isOwnCloudServer') - ->with('url') - ->willReturn($isOwnCloud); - - $this->controller->addServer('url'); - } - - public function testRemoveServer() { - $this->trustedServers->expects($this->once())->method('removeServer') - ->with('url'); - $result = $this->controller->removeServer('url'); - $this->assertTrue($result instanceof DataResponse); - $this->assertSame(200, $result->getStatus()); - } - - public function testCheckServer() { - $this->trustedServers - ->expects($this->once()) - ->method('isTrustedServer') - ->with('url') - ->willReturn(false); - $this->trustedServers - ->expects($this->once()) - ->method('isOwnCloudServer') - ->with('url') - ->willReturn(true); - - $this->assertTrue( - $this->invokePrivate($this->controller, 'checkServer', ['url']) - ); - - } - - /** - * @dataProvider checkServerFails - * @expectedException \OC\HintException - * - * @param bool $isTrustedServer - * @param bool $isOwnCloud - */ - public function testCheckServerFail($isTrustedServer, $isOwnCloud) { - $this->trustedServers - ->expects($this->any()) - ->method('isTrustedServer') - ->with('url') - ->willReturn($isTrustedServer); - $this->trustedServers - ->expects($this->any()) - ->method('isOwnCloudServer') - ->with('url') - ->willReturn($isOwnCloud); - - $this->assertTrue( - $this->invokePrivate($this->controller, 'checkServer', ['url']) - ); - - } - - /** - * data to simulate checkServer fails - * - * @return array - */ - public function checkServerFails() { - return [ - [true, true], - [false, false] - ]; - } - -} diff --git a/apps/federation/tests/dav/fedauthtest.php b/apps/federation/tests/dav/fedauthtest.php deleted file mode 100644 index b716084a45d..00000000000 --- a/apps/federation/tests/dav/fedauthtest.php +++ /dev/null @@ -1,52 +0,0 @@ -<?php -/** - * @author Thomas Müller <thomas.mueller@tmit.eu> - * - * @copyright Copyright (c) 2016, ownCloud, Inc. - * @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\DAV; - -use OCA\Federation\DAV\FedAuth; -use OCA\Federation\DbHandler; -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(); - $db->method('auth')->willReturn(true); - $auth = new FedAuth($db); - $result = $this->invokePrivate($auth, 'validateUserPass', [$user, $password]); - $this->assertEquals($expected, $result); - } - - public function providesUser() { - return [ - [true, 'system', '123456'] - ]; - } -} diff --git a/apps/federation/tests/lib/hookstest.php b/apps/federation/tests/lib/hookstest.php deleted file mode 100644 index 71569226dd2..00000000000 --- a/apps/federation/tests/lib/hookstest.php +++ /dev/null @@ -1,79 +0,0 @@ -<?php -/** - * @author Björn Schießle <schiessle@owncloud.com> - * - * @copyright Copyright (c) 2016, ownCloud, Inc. - * @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\lib; - - -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; - - public function setUp() { - 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/lib/syncfederationaddressbookstest.php b/apps/federation/tests/lib/syncfederationaddressbookstest.php deleted file mode 100644 index aa2bd9ac2cb..00000000000 --- a/apps/federation/tests/lib/syncfederationaddressbookstest.php +++ /dev/null @@ -1,88 +0,0 @@ -<?php -/** - * @author Björn Schießle <schiessle@owncloud.com> - * @author Lukas Reschke <lukas@owncloud.com> - * @author Thomas Müller <thomas.mueller@tmit.eu> - * - * @copyright Copyright (c) 2016, ownCloud, Inc. - * @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\lib; - -use OCA\Federation\DbHandler; -use OCA\Federation\SyncFederationAddressBooks; - -class SyncFederationAddressbooksTest extends \Test\TestCase { - - /** @var array */ - private $callBacks = []; - - function testSync() { - /** @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' - ] - ]); - $dbHandler->expects($this->once())->method('setServerStatus')-> - with('https://cloud.drop.box', 1, '1'); - $syncService = $this->getMockBuilder('OCA\DAV\CardDAV\SyncService') - ->disableOriginalConstructor() - ->getMock(); - $syncService->expects($this->once())->method('syncRemoteAddressBook') - ->willReturn(1); - - $s = new SyncFederationAddressBooks($dbHandler, $syncService); - $s->syncThemAll(function($url, $ex) { - $this->callBacks[] = [$url, $ex]; - }); - $this->assertEquals(1, count($this->callBacks)); - } - - 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(); - $syncService->expects($this->once())->method('syncRemoteAddressBook') - ->willThrowException(new \Exception('something did not work out')); - - $s = new SyncFederationAddressBooks($dbHandler, $syncService); - $s->syncThemAll(function($url, $ex) { - $this->callBacks[] = [$url, $ex]; - }); - $this->assertEquals(2, count($this->callBacks)); - } -} diff --git a/apps/federation/tests/lib/trustedserverstest.php b/apps/federation/tests/lib/trustedserverstest.php deleted file mode 100644 index a8c7c7afb1f..00000000000 --- a/apps/federation/tests/lib/trustedserverstest.php +++ /dev/null @@ -1,372 +0,0 @@ -<?php -/** - * @author Björn Schießle <schiessle@owncloud.com> - * @author Thomas Müller <thomas.mueller@tmit.eu> - * - * @copyright Copyright (c) 2016, ownCloud, Inc. - * @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\lib; - - -use OCA\Federation\DbHandler; -use OCA\Federation\TrustedServers; -use OCP\BackgroundJob\IJobList; -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 Test\TestCase; - -class TrustedServersTest extends TestCase { - - /** @var 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; - - public function setUp() { - parent::setUp(); - - $this->dbHandler = $this->getMockBuilder('\OCA\Federation\DbHandler') - ->disableOriginalConstructor()->getMock(); - $this->dispatcher = $this->getMockBuilder('Symfony\Component\EventDispatcher\EventDispatcherInterface') - ->disableOriginalConstructor()->getMock(); - $this->httpClientService = $this->getMock('OCP\Http\Client\IClientService'); - $this->httpClient = $this->getMock('OCP\Http\Client\IClient'); - $this->response = $this->getMock('OCP\Http\Client\IResponse'); - $this->logger = $this->getMock('OCP\ILogger'); - $this->jobList = $this->getMock('OCP\BackgroundJob\IJobList'); - $this->secureRandom = $this->getMock('OCP\Security\ISecureRandom'); - $this->config = $this->getMock('OCP\IConfig'); - - $this->trustedServers = new TrustedServers( - $this->dbHandler, - $this->httpClientService, - $this->logger, - $this->jobList, - $this->secureRandom, - $this->config, - $this->dispatcher - ); - - } - - /** - * @dataProvider dataTrueFalse - * - * @param bool $success - */ - public function testAddServer($success) { - /** @var \PHPUnit_Framework_MockObject_MockObject | TrustedServers $trustedServer */ - $trustedServers = $this->getMockBuilder('OCA\Federation\TrustedServers') - ->setConstructorArgs( - [ - $this->dbHandler, - $this->httpClientService, - $this->logger, - $this->jobList, - $this->secureRandom, - $this->config, - $this->dispatcher - ] - ) - ->setMethods(['normalizeUrl', 'updateProtocol']) - ->getMock(); - $trustedServers->expects($this->once())->method('updateProtocol') - ->with('url')->willReturn('https://url'); - $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']); - } 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); - } - - /** - * @dataProvider dataTestGetAutoAddServers - * - * @param string $status - * @param bool $expected - */ - public function testGetAutoAddServers($status, $expected) { - $this->config->expects($this->once())->method('getAppValue') - ->with('federation', 'autoAddServers', '1')->willReturn($status); - - $this->assertSame($expected, - $this->trustedServers->getAutoAddServers($status) - ); - } - - public function dataTestGetAutoAddServers() { - return [ - ['1', true], - ['0', false] - ]; - } - - public function testAddSharedSecret() { - $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 testRemoveServer() { - $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') - ->willReturnCallback( - function($eventId, $event) { - $this->assertSame($eventId, 'OCP\Federation\TrustedServerEvent::remove'); - $this->assertInstanceOf('Symfony\Component\EventDispatcher\GenericEvent', $event); - $this->assertSame('url_hash', $event->getSubject()); - } - ); - $this->trustedServers->removeServer($id); - } - - public function testGetServers() { - $this->dbHandler->expects($this->once())->method('getAllServer')->willReturn(true); - - $this->assertTrue( - $this->trustedServers->getServers() - ); - } - - - public function testIsTrustedServer() { - $this->dbHandler->expects($this->once())->method('serverExists')->with('url') - ->willReturn(true); - - $this->assertTrue( - $this->trustedServers->isTrustedServer('url') - ); - } - - public function testSetServerStatus() { - $this->dbHandler->expects($this->once())->method('setServerStatus') - ->with('url', 'status'); - $this->trustedServers->setServerStatus('url', 'status'); - } - - public function testGetServerStatus() { - $this->dbHandler->expects($this->once())->method('getServerStatus') - ->with('url')->willReturn(true); - $this->assertTrue( - $this->trustedServers->getServerStatus('url') - ); - } - - /** - * @dataProvider dataTestIsOwnCloudServer - * - * @param int $statusCode - * @param bool $isValidOwnCloudVersion - * @param bool $expected - */ - public function testIsOwnCloudServer($statusCode, $isValidOwnCloudVersion, $expected) { - - $server = 'server1'; - - /** @var \PHPUnit_Framework_MockObject_MockObject | TrustedServers $trustedServer */ - $trustedServers = $this->getMockBuilder('OCA\Federation\TrustedServers') - ->setConstructorArgs( - [ - $this->dbHandler, - $this->httpClientService, - $this->logger, - $this->jobList, - $this->secureRandom, - $this->config, - $this->dispatcher - ] - ) - ->setMethods(['checkOwnCloudVersion']) - ->getMock(); - - $this->httpClientService->expects($this->once())->method('newClient') - ->willReturn($this->httpClient); - - $this->httpClient->expects($this->once())->method('get')->with($server . '/status.php') - ->willReturn($this->response); - - $this->response->expects($this->once())->method('getStatusCode') - ->willReturn($statusCode); - - if ($statusCode === 200) { - $trustedServers->expects($this->once())->method('checkOwnCloudVersion') - ->willReturn($isValidOwnCloudVersion); - } else { - $trustedServers->expects($this->never())->method('checkOwnCloudVersion'); - } - - $this->assertSame($expected, - $trustedServers->isOwnCloudServer($server) - ); - - } - - public function dataTestIsOwnCloudServer() { - return [ - [200, true, true], - [200, false, false], - [404, true, false], - ]; - } - - /** - * @expectedException \Exception - * @expectedExceptionMessage simulated exception - */ - public function testIsOwnCloudServerFail() { - $server = 'server1'; - - $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->trustedServers->isOwnCloudServer($server); - } - - /** - * @dataProvider dataTestCheckOwnCloudVersion - */ - public function testCheckOwnCloudVersion($status) { - $this->assertTrue($this->invokePrivate($this->trustedServers, 'checkOwnCloudVersion', [$status])); - } - - public function dataTestCheckOwnCloudVersion() { - return [ - ['{"version":"9.0.0"}'], - ['{"version":"9.1.0"}'] - ]; - } - - /** - * @dataProvider dataTestCheckOwnCloudVersionTooLow - * @expectedException \OC\HintException - * @expectedExceptionMessage Remote server version is too low. ownCloud 9.0 is required. - */ - public function testCheckOwnCloudVersionTooLow($status) { - $this->invokePrivate($this->trustedServers, 'checkOwnCloudVersion', [$status]); - } - - public function dataTestCheckOwnCloudVersionTooLow() { - return [ - ['{"version":"8.2.3"}'], - ]; - } - - /** - * @dataProvider dataTestUpdateProtocol - * @param string $url - * @param string $expected - */ - public function testUpdateProtocol($url, $expected) { - $this->assertSame($expected, - $this->invokePrivate($this->trustedServers, 'updateProtocol', [$url]) - ); - } - - public function dataTestUpdateProtocol() { - return [ - ['http://owncloud.org', 'http://owncloud.org'], - ['https://owncloud.org', 'https://owncloud.org'], - ['owncloud.org', 'https://owncloud.org'], - ['httpserver', 'https://httpserver'], - ]; - } -} diff --git a/apps/federation/tests/middleware/addservermiddlewaretest.php b/apps/federation/tests/middleware/addservermiddlewaretest.php deleted file mode 100644 index be1d97c4035..00000000000 --- a/apps/federation/tests/middleware/addservermiddlewaretest.php +++ /dev/null @@ -1,102 +0,0 @@ -<?php -/** - * @author Björn Schießle <schiessle@owncloud.com> - * @author Thomas Müller <thomas.mueller@tmit.eu> - * - * @copyright Copyright (c) 2016, ownCloud, Inc. - * @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\Middleware\AddServerMiddleware; -use OCP\AppFramework\Controller; -use OCP\AppFramework\Http; -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 | Controller */ - private $controller; - - public function setUp() { - parent::setUp(); - - $this->logger = $this->getMock('OCP\ILogger'); - $this->l10n = $this->getMock('OCP\IL10N'); - $this->controller = $this->getMockBuilder('OCP\AppFramework\Controller') - ->disableOriginalConstructor()->getMock(); - - $this->middleware = new AddServerMiddleware( - 'AddServerMiddlewareTest', - $this->l10n, - $this->logger - ); - } - - /** - * @dataProvider dataTestAfterException - * - * @param \Exception $exception - * @param string $message - * @param string $hint - */ - public function testAfterException($exception, $message, $hint) { - - $this->logger->expects($this->once())->method('error') - ->with($message, ['app' => 'AddServerMiddlewareTest']); - - $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'), 'message', 'hint'], - [new \Exception('message'), 'message', 'message'], - ]; - } - -} |