diff options
Diffstat (limited to 'apps/federatedfilesharing/tests')
9 files changed, 424 insertions, 982 deletions
diff --git a/apps/federatedfilesharing/tests/AddressHandlerTest.php b/apps/federatedfilesharing/tests/AddressHandlerTest.php index 13030e73cb0..279bf485145 100644 --- a/apps/federatedfilesharing/tests/AddressHandlerTest.php +++ b/apps/federatedfilesharing/tests/AddressHandlerTest.php @@ -1,71 +1,50 @@ <?php + +declare(strict_types=1); /** - * @copyright Copyright (c) 2016, ownCloud, Inc. - * - * @author Arthur Schiwon <blizzz@arthur-schiwon.de> - * @author Bjoern Schiessle <bjoern@schiessle.org> - * @author Björn Schießle <bjoern@schiessle.org> - * @author Christoph Wurst <christoph@winzerhof-wurst.at> - * @author Morris Jobke <hey@morrisjobke.de> - * @author Robin Appelman <robin@icewind.nl> - * @author Roeland Jago Douma <roeland@famdouma.nl> - * - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see <http://www.gnu.org/licenses/> - * + * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors + * SPDX-FileCopyrightText: 2016 ownCloud, Inc. + * SPDX-License-Identifier: AGPL-3.0-only */ namespace OCA\FederatedFileSharing\Tests; use OC\Federation\CloudIdManager; use OCA\FederatedFileSharing\AddressHandler; use OCP\Contacts\IManager; +use OCP\EventDispatcher\IEventDispatcher; +use OCP\HintException; +use OCP\ICacheFactory; use OCP\IL10N; use OCP\IURLGenerator; use OCP\IUserManager; +use PHPUnit\Framework\MockObject\MockObject; class AddressHandlerTest extends \Test\TestCase { - /** @var IManager|\PHPUnit\Framework\MockObject\MockObject */ - protected $contactsManager; - - /** @var AddressHandler */ - private $addressHandler; - - /** @var IURLGenerator | \PHPUnit\Framework\MockObject\MockObject */ - private $urlGenerator; - - /** @var IL10N | \PHPUnit\Framework\MockObject\MockObject */ - private $il10n; - - /** @var CloudIdManager */ - private $cloudIdManager; + protected IManager&MockObject $contactsManager; + private IURLGenerator&MockObject $urlGenerator; + private IL10N&MockObject $il10n; + private CloudIdManager $cloudIdManager; + private AddressHandler $addressHandler; protected function setUp(): void { parent::setUp(); - $this->urlGenerator = $this->getMockBuilder(IURLGenerator::class) - ->getMock(); - $this->il10n = $this->getMockBuilder(IL10N::class) - ->getMock(); - + $this->urlGenerator = $this->createMock(IURLGenerator::class); + $this->il10n = $this->createMock(IL10N::class); $this->contactsManager = $this->createMock(IManager::class); - $this->cloudIdManager = new CloudIdManager($this->contactsManager, $this->urlGenerator, $this->createMock(IUserManager::class)); + $this->cloudIdManager = new CloudIdManager( + $this->createMock(ICacheFactory::class), + $this->createMock(IEventDispatcher::class), + $this->contactsManager, + $this->urlGenerator, + $this->createMock(IUserManager::class), + ); $this->addressHandler = new AddressHandler($this->urlGenerator, $this->il10n, $this->cloudIdManager); } - public function dataTestSplitUserRemote() { + public static function dataTestSplitUserRemote(): array { $userPrefix = ['user@name', 'username']; $protocols = ['', 'http://', 'https://']; $remotes = [ @@ -86,6 +65,11 @@ class AddressHandlerTest extends \Test\TestCase { foreach ($protocols as $protocol) { $baseUrl = $user . '@' . $protocol . $remote; + if ($protocol === '') { + // https:// protocol is expected in the final result + $protocol = 'https://'; + } + $testCases[] = [$baseUrl, $user, $protocol . $remote]; $testCases[] = [$baseUrl . '/', $user, $protocol . $remote]; $testCases[] = [$baseUrl . '/index.php', $user, $protocol . $remote]; @@ -96,14 +80,8 @@ class AddressHandlerTest extends \Test\TestCase { return $testCases; } - /** - * @dataProvider dataTestSplitUserRemote - * - * @param string $remote - * @param string $expectedUser - * @param string $expectedUrl - */ - public function testSplitUserRemote($remote, $expectedUser, $expectedUrl) { + #[\PHPUnit\Framework\Attributes\DataProvider('dataTestSplitUserRemote')] + public function testSplitUserRemote(string $remote, string $expectedUser, string $expectedUrl): void { $this->contactsManager->expects($this->any()) ->method('search') ->willReturn([]); @@ -113,7 +91,7 @@ class AddressHandlerTest extends \Test\TestCase { $this->assertSame($expectedUrl, $remoteUrl); } - public function dataTestSplitUserRemoteError() { + public static function dataTestSplitUserRemoteError(): array { return [ // Invalid path ['user@'], @@ -131,33 +109,21 @@ class AddressHandlerTest extends \Test\TestCase { ]; } - /** - * @dataProvider dataTestSplitUserRemoteError - * - * @param string $id - */ - public function testSplitUserRemoteError($id) { - $this->expectException(\OCP\HintException::class); + #[\PHPUnit\Framework\Attributes\DataProvider('dataTestSplitUserRemoteError')] + public function testSplitUserRemoteError(string $id): void { + $this->expectException(HintException::class); $this->addressHandler->splitUserRemote($id); } - /** - * @dataProvider dataTestCompareAddresses - * - * @param string $user1 - * @param string $server1 - * @param string $user2 - * @param string $server2 - * @param bool $expected - */ - public function testCompareAddresses($user1, $server1, $user2, $server2, $expected) { + #[\PHPUnit\Framework\Attributes\DataProvider('dataTestCompareAddresses')] + public function testCompareAddresses(string $user1, string $server1, string $user2, string $server2, bool $expected): void { $this->assertSame($expected, $this->addressHandler->compareAddresses($user1, $server1, $user2, $server2) ); } - public function dataTestCompareAddresses() { + public static function dataTestCompareAddresses(): array { return [ ['user1', 'http://server1', 'user1', 'http://server1', true], ['user1', 'https://server1', 'user1', 'http://server1', true], @@ -177,37 +143,27 @@ class AddressHandlerTest extends \Test\TestCase { ]; } - /** - * @dataProvider dataTestRemoveProtocolFromUrl - * - * @param string $url - * @param string $expectedResult - */ - public function testRemoveProtocolFromUrl($url, $expectedResult) { + #[\PHPUnit\Framework\Attributes\DataProvider('dataTestRemoveProtocolFromUrl')] + public function testRemoveProtocolFromUrl(string $url, string $expectedResult): void { $result = $this->addressHandler->removeProtocolFromUrl($url); $this->assertSame($expectedResult, $result); } - public function dataTestRemoveProtocolFromUrl() { + public static function dataTestRemoveProtocolFromUrl(): array { return [ - ['http://owncloud.org', 'owncloud.org'], - ['https://owncloud.org', 'owncloud.org'], - ['owncloud.org', 'owncloud.org'], + ['http://example.tld', 'example.tld'], + ['https://example.tld', 'example.tld'], + ['example.tld', 'example.tld'], ]; } - /** - * @dataProvider dataTestUrlContainProtocol - * - * @param string $url - * @param bool $expectedResult - */ - public function testUrlContainProtocol($url, $expectedResult) { + #[\PHPUnit\Framework\Attributes\DataProvider('dataTestUrlContainProtocol')] + public function testUrlContainProtocol(string $url, bool $expectedResult): void { $result = $this->addressHandler->urlContainProtocol($url); $this->assertSame($expectedResult, $result); } - public function dataTestUrlContainProtocol() { + public static function dataTestUrlContainProtocol(): array { return [ ['http://nextcloud.com', true], ['https://nextcloud.com', true], diff --git a/apps/federatedfilesharing/tests/Controller/MountPublicLinkControllerTest.php b/apps/federatedfilesharing/tests/Controller/MountPublicLinkControllerTest.php index ff979c23d2a..e99b59e82b8 100644 --- a/apps/federatedfilesharing/tests/Controller/MountPublicLinkControllerTest.php +++ b/apps/federatedfilesharing/tests/Controller/MountPublicLinkControllerTest.php @@ -1,43 +1,26 @@ <?php + +declare(strict_types=1); /** - * @copyright Copyright (c) 2016, ownCloud, Inc. - * @copyright Copyright (c) 2016, Björn Schießle <bjoern@schiessle.org> - * - * @author Arthur Schiwon <blizzz@arthur-schiwon.de> - * @author Bjoern Schiessle <bjoern@schiessle.org> - * @author Björn Schießle <bjoern@schiessle.org> - * @author Christoph Wurst <christoph@winzerhof-wurst.at> - * @author Morris Jobke <hey@morrisjobke.de> - * @author Robin Appelman <robin@icewind.nl> - * @author Roeland Jago Douma <roeland@famdouma.nl> - * - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see <http://www.gnu.org/licenses/> - * + * SPDX-FileCopyrightText: 2016 Nextcloud GmbH and Nextcloud contributors + * SPDX-FileCopyrightText: 2016 ownCloud, Inc. + * SPDX-License-Identifier: AGPL-3.0-only */ namespace OCA\FederatedFileSharing\Tests\Controller; use OC\Federation\CloudIdManager; +use OC\Share20\Share; use OCA\FederatedFileSharing\AddressHandler; use OCA\FederatedFileSharing\Controller\MountPublicLinkController; use OCA\FederatedFileSharing\FederatedShareProvider; use OCP\AppFramework\Http; use OCP\Contacts\IManager as IContactsManager; +use OCP\EventDispatcher\IEventDispatcher; use OCP\Federation\ICloudIdManager; use OCP\Files\IRootFolder; use OCP\HintException; use OCP\Http\Client\IClientService; +use OCP\ICacheFactory; use OCP\IL10N; use OCP\IRequest; use OCP\ISession; @@ -46,68 +29,47 @@ use OCP\IUserManager; use OCP\IUserSession; use OCP\Share\IManager; use OCP\Share\IShare; +use PHPUnit\Framework\MockObject\MockObject; +use Psr\Log\LoggerInterface; class MountPublicLinkControllerTest extends \Test\TestCase { - /** @var IContactsManager|\PHPUnit\Framework\MockObject\MockObject */ - protected $contactsManager; - - /** @var MountPublicLinkController */ - private $controller; - - /** @var \OCP\IRequest | \PHPUnit\Framework\MockObject\MockObject */ - private $request; - - /** @var FederatedShareProvider | \PHPUnit\Framework\MockObject\MockObject */ - private $federatedShareProvider; - - /** @var IManager | \PHPUnit\Framework\MockObject\MockObject */ - private $shareManager; - - /** @var AddressHandler | \PHPUnit\Framework\MockObject\MockObject */ - private $addressHandler; - - /** @var IRootFolder | \PHPUnit\Framework\MockObject\MockObject */ - private $rootFolder; - - /** @var IUserManager | \PHPUnit\Framework\MockObject\MockObject */ - private $userManager; - - /** @var ISession | \PHPUnit\Framework\MockObject\MockObject */ - private $session; - - /** @var IL10N | \PHPUnit\Framework\MockObject\MockObject */ - private $l10n; - - /** @var IUserSession | \PHPUnit\Framework\MockObject\MockObject */ - private $userSession; - - /** @var IClientService | \PHPUnit\Framework\MockObject\MockObject */ - private $clientService; - - /** @var IShare */ - private $share; - - /** @var ICloudIdManager */ - private $cloudIdManager; + protected IContactsManager&MockObject $contactsManager; + private IRequest&MockObject $request; + private FederatedShareProvider&MockObject $federatedShareProvider; + private IManager&MockObject $shareManager; + private AddressHandler&MockObject $addressHandler; + private IRootFolder&MockObject $rootFolder; + private IUserManager&MockObject $userManager; + private ISession&MockObject $session; + private IL10N&MockObject $l10n; + private IUserSession&MockObject $userSession; + private IClientService&MockObject $clientService; + private IShare $share; + private ICloudIdManager $cloudIdManager; + private MountPublicLinkController $controller; protected function setUp(): void { parent::setUp(); - $this->request = $this->getMockBuilder(IRequest::class)->disableOriginalConstructor()->getMock(); - $this->federatedShareProvider = $this->getMockBuilder('OCA\FederatedFileSharing\FederatedShareProvider') - ->disableOriginalConstructor()->getMock(); - $this->shareManager = $this->getMockBuilder(IManager::class)->disableOriginalConstructor()->getMock(); - $this->addressHandler = $this->getMockBuilder('OCA\FederatedFileSharing\AddressHandler') - ->disableOriginalConstructor()->getMock(); - $this->rootFolder = $this->getMockBuilder('OCP\Files\IRootFolder')->disableOriginalConstructor()->getMock(); - $this->userManager = $this->getMockBuilder(IUserManager::class)->disableOriginalConstructor()->getMock(); - $this->share = new \OC\Share20\Share($this->rootFolder, $this->userManager); - $this->session = $this->getMockBuilder(ISession::class)->disableOriginalConstructor()->getMock(); - $this->l10n = $this->getMockBuilder(IL10N::class)->disableOriginalConstructor()->getMock(); - $this->userSession = $this->getMockBuilder(IUserSession::class)->disableOriginalConstructor()->getMock(); - $this->clientService = $this->getMockBuilder('OCP\Http\Client\IClientService')->disableOriginalConstructor()->getMock(); + $this->request = $this->createMock(IRequest::class); + $this->federatedShareProvider = $this->createMock(FederatedShareProvider::class); + $this->shareManager = $this->createMock(IManager::class); + $this->addressHandler = $this->createMock(AddressHandler::class); + $this->rootFolder = $this->createMock(IRootFolder::class); + $this->userManager = $this->createMock(IUserManager::class); + $this->share = new Share($this->rootFolder, $this->userManager); + $this->session = $this->createMock(ISession::class); + $this->l10n = $this->createMock(IL10N::class); + $this->userSession = $this->createMock(IUserSession::class); + $this->clientService = $this->createMock(IClientService::class); $this->contactsManager = $this->createMock(IContactsManager::class); - $this->cloudIdManager = new CloudIdManager($this->contactsManager, $this->createMock(IURLGenerator::class), $this->userManager); + $this->cloudIdManager = new CloudIdManager( + $this->createMock(ICacheFactory::class), + $this->createMock(IEventDispatcher::class), + $this->contactsManager, + $this->createMock(IURLGenerator::class), + $this->userManager, + ); $this->controller = new MountPublicLinkController( 'federatedfilesharing', $this->request, @@ -118,30 +80,22 @@ class MountPublicLinkControllerTest extends \Test\TestCase { $this->l10n, $this->userSession, $this->clientService, - $this->cloudIdManager + $this->cloudIdManager, + $this->createMock(LoggerInterface::class), ); } - /** - * @dataProvider dataTestCreateFederatedShare - * - * @param string $shareWith - * @param bool $outgoingSharesAllowed - * @param bool $validShareWith - * @param string $token - * @param bool $validToken - * @param bool $createSuccessful - * @param string $expectedReturnData - */ - public function testCreateFederatedShare($shareWith, - $outgoingSharesAllowed, - $validShareWith, - $token, - $validToken, - $createSuccessful, - $expectedReturnData, - $permissions - ) { + #[\PHPUnit\Framework\Attributes\DataProvider('dataTestCreateFederatedShare')] + public function testCreateFederatedShare( + string $shareWith, + bool $outgoingSharesAllowed, + bool $validShareWith, + string $token, + bool $validToken, + bool $createSuccessful, + string $expectedReturnData, + int $permissions, + ): void { $this->federatedShareProvider->expects($this->any()) ->method('isOutgoingServer2serverShareEnabled') ->willReturn($outgoingSharesAllowed); @@ -198,7 +152,7 @@ class MountPublicLinkControllerTest extends \Test\TestCase { } } - public function dataTestCreateFederatedShare() { + public static function dataTestCreateFederatedShare(): array { return [ //shareWith, outgoingSharesAllowed, validShareWith, token, validToken, createSuccessful, expectedReturnData ['user@server', true, true, 'token', true, true, 'server', 31], diff --git a/apps/federatedfilesharing/tests/Controller/RequestHandlerControllerTest.php b/apps/federatedfilesharing/tests/Controller/RequestHandlerControllerTest.php index 77f7fde70fa..81c67a29254 100644 --- a/apps/federatedfilesharing/tests/Controller/RequestHandlerControllerTest.php +++ b/apps/federatedfilesharing/tests/Controller/RequestHandlerControllerTest.php @@ -1,45 +1,30 @@ <?php + +declare(strict_types=1); /** - * @copyright Copyright (c) 2016, ownCloud, Inc. - * - * @author Bjoern Schiessle <bjoern@schiessle.org> - * @author Björn Schießle <bjoern@schiessle.org> - * @author Christoph Wurst <christoph@winzerhof-wurst.at> - * @author Morris Jobke <hey@morrisjobke.de> - * @author Robin Appelman <robin@icewind.nl> - * @author Roeland Jago Douma <roeland@famdouma.nl> - * @author Thomas Müller <thomas.mueller@tmit.eu> - * - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see <http://www.gnu.org/licenses/> - * + * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors + * SPDX-FileCopyrightText: 2016 ownCloud, Inc. + * SPDX-License-Identifier: AGPL-3.0-only */ namespace OCA\FederatedFileSharing\Tests; +use OCA\FederatedFileSharing\AddressHandler; use OCA\FederatedFileSharing\Controller\RequestHandlerController; +use OCA\FederatedFileSharing\FederatedShareProvider; +use OCA\FederatedFileSharing\Notifications; use OCP\AppFramework\Http\DataResponse; +use OCP\EventDispatcher\IEventDispatcher; use OCP\Federation\ICloudFederationFactory; use OCP\Federation\ICloudFederationProvider; use OCP\Federation\ICloudFederationProviderManager; use OCP\Federation\ICloudFederationShare; use OCP\Federation\ICloudIdManager; -use OCP\EventDispatcher\IEventDispatcher; use OCP\IDBConnection; use OCP\IRequest; use OCP\IUserManager; use OCP\Share; use OCP\Share\IShare; +use PHPUnit\Framework\MockObject\MockObject; use Psr\Log\LoggerInterface; /** @@ -49,65 +34,32 @@ use Psr\Log\LoggerInterface; * @group DB */ class RequestHandlerControllerTest extends \Test\TestCase { - private $owner = 'owner'; - private $user1 = 'user1'; - private $user2 = 'user2'; - private $ownerCloudId = 'owner@server0.org'; - private $user1CloudId = 'user1@server1.org'; - private $user2CloudId = 'user2@server2.org'; - - /** @var RequestHandlerController */ - private $requestHandler; - - /** @var \OCA\FederatedFileSharing\FederatedShareProvider|\PHPUnit\Framework\MockObject\MockObject */ - private $federatedShareProvider; - - /** @var \OCA\FederatedFileSharing\Notifications|\PHPUnit\Framework\MockObject\MockObject */ - private $notifications; - - /** @var \OCA\FederatedFileSharing\AddressHandler|\PHPUnit\Framework\MockObject\MockObject */ - private $addressHandler; - - /** @var IUserManager|\PHPUnit\Framework\MockObject\MockObject */ - private $userManager; - - /** @var IShare|\PHPUnit\Framework\MockObject\MockObject */ - private $share; - - /** @var ICloudIdManager|\PHPUnit\Framework\MockObject\MockObject */ - private $cloudIdManager; - - /** @var LoggerInterface|\PHPUnit\Framework\MockObject\MockObject */ - private $logger; - - /** @var IRequest|\PHPUnit\Framework\MockObject\MockObject */ - private $request; - - /** @var IDBConnection|\PHPUnit\Framework\MockObject\MockObject */ - private $connection; - - /** @var Share\IManager|\PHPUnit\Framework\MockObject\MockObject */ - private $shareManager; - - /** @var ICloudFederationFactory|\PHPUnit\Framework\MockObject\MockObject */ - private $cloudFederationFactory; - - /** @var ICloudFederationProviderManager|\PHPUnit\Framework\MockObject\MockObject */ - private $cloudFederationProviderManager; - - /** @var ICloudFederationProvider|\PHPUnit\Framework\MockObject\MockObject */ - private $cloudFederationProvider; - - /** @var ICloudFederationShare|\PHPUnit\Framework\MockObject\MockObject */ - private $cloudFederationShare; - - /** @var IEventDispatcher|\PHPUnit\Framework\MockObject\MockObject */ - private $eventDispatcher; + private string $owner = 'owner'; + private string $user1 = 'user1'; + private string $user2 = 'user2'; + private string $ownerCloudId = 'owner@server0.org'; + private string $user1CloudId = 'user1@server1.org'; + + private RequestHandlerController $requestHandler; + private FederatedShareProvider&MockObject $federatedShareProvider; + private Notifications&MockObject $notifications; + private AddressHandler&MockObject $addressHandler; + private IUserManager&MockObject $userManager; + private IShare&MockObject $share; + private ICloudIdManager&MockObject $cloudIdManager; + private LoggerInterface&MockObject $logger; + private IRequest&MockObject $request; + private IDBConnection&MockObject $connection; + private Share\IManager&MockObject $shareManager; + private ICloudFederationFactory&MockObject $cloudFederationFactory; + private ICloudFederationProviderManager&MockObject $cloudFederationProviderManager; + private ICloudFederationProvider&MockObject $cloudFederationProvider; + private ICloudFederationShare&MockObject $cloudFederationShare; + private IEventDispatcher&MockObject $eventDispatcher; protected function setUp(): void { - $this->share = $this->getMockBuilder(IShare::class)->getMock(); - $this->federatedShareProvider = $this->getMockBuilder('OCA\FederatedFileSharing\FederatedShareProvider') - ->disableOriginalConstructor()->getMock(); + $this->share = $this->createMock(IShare::class); + $this->federatedShareProvider = $this->createMock(FederatedShareProvider::class); $this->federatedShareProvider->expects($this->any()) ->method('isOutgoingServer2serverShareEnabled')->willReturn(true); $this->federatedShareProvider->expects($this->any()) @@ -115,11 +67,9 @@ class RequestHandlerControllerTest extends \Test\TestCase { $this->federatedShareProvider->expects($this->any())->method('getShareById') ->willReturn($this->share); - $this->notifications = $this->getMockBuilder('OCA\FederatedFileSharing\Notifications') - ->disableOriginalConstructor()->getMock(); - $this->addressHandler = $this->getMockBuilder('OCA\FederatedFileSharing\AddressHandler') - ->disableOriginalConstructor()->getMock(); - $this->userManager = $this->getMockBuilder(IUserManager::class)->getMock(); + $this->notifications = $this->createMock(Notifications::class); + $this->addressHandler = $this->createMock(AddressHandler::class); + $this->userManager = $this->createMock(IUserManager::class); $this->cloudIdManager = $this->createMock(ICloudIdManager::class); $this->request = $this->createMock(IRequest::class); $this->connection = $this->createMock(IDBConnection::class); @@ -150,34 +100,23 @@ class RequestHandlerControllerTest extends \Test\TestCase { ); } - public function testCreateShare() { - // simulate a post request - $_POST['remote'] = 'localhost'; - $_POST['token'] = 'token'; - $_POST['name'] = 'name'; - $_POST['owner'] = $this->owner; - $_POST['sharedBy'] = $this->user1; - $_POST['shareWith'] = $this->user2; - $_POST['remoteId'] = 1; - $_POST['sharedByFederatedId'] = $this->user1CloudId; - $_POST['ownerFederatedId'] = $this->ownerCloudId; - + public function testCreateShare(): void { $this->cloudFederationFactory->expects($this->once())->method('getCloudFederationShare') ->with( - $this->user2, - 'name', - '', - 1, - $this->ownerCloudId, - $this->owner, - $this->user1CloudId, - $this->user1, - 'token', - 'user', - 'file' + $this->user2, + 'name', + '', + 1, + $this->ownerCloudId, + $this->owner, + $this->user1CloudId, + $this->user1, + 'token', + 'user', + 'file' )->willReturn($this->cloudFederationShare); - /** @var ICloudFederationProvider|\PHPUnit\Framework\MockObject\MockObject $provider */ + /** @var ICloudFederationProvider&MockObject $provider */ $this->cloudFederationProviderManager->expects($this->once()) ->method('getCloudFederationProvider') ->with('file') @@ -186,14 +125,13 @@ class RequestHandlerControllerTest extends \Test\TestCase { $this->cloudFederationProvider->expects($this->once())->method('shareReceived') ->with($this->cloudFederationShare); - $result = $this->requestHandler->createShare(); + $result = $this->requestHandler->createShare('localhost', 'token', 'name', $this->owner, $this->user1, $this->user2, 1, $this->user1CloudId, $this->ownerCloudId); $this->assertInstanceOf(DataResponse::class, $result); } - public function testDeclineShare() { + public function testDeclineShare(): void { $id = 42; - $_POST['token'] = 'token'; $notification = [ 'sharedSecret' => 'token', @@ -209,15 +147,14 @@ class RequestHandlerControllerTest extends \Test\TestCase { ->method('notificationReceived') ->with('SHARE_DECLINED', $id, $notification); - $result = $this->requestHandler->declineShare($id); + $result = $this->requestHandler->declineShare($id, 'token'); $this->assertInstanceOf(DataResponse::class, $result); } - public function testAcceptShare() { + public function testAcceptShare(): void { $id = 42; - $_POST['token'] = 'token'; $notification = [ 'sharedSecret' => 'token', @@ -233,7 +170,7 @@ class RequestHandlerControllerTest extends \Test\TestCase { ->method('notificationReceived') ->with('SHARE_ACCEPTED', $id, $notification); - $result = $this->requestHandler->acceptShare($id); + $result = $this->requestHandler->acceptShare($id, 'token'); $this->assertInstanceOf(DataResponse::class, $result); } diff --git a/apps/federatedfilesharing/tests/FederatedShareProviderTest.php b/apps/federatedfilesharing/tests/FederatedShareProviderTest.php index 831b9b59b54..7e97510af22 100644 --- a/apps/federatedfilesharing/tests/FederatedShareProviderTest.php +++ b/apps/federatedfilesharing/tests/FederatedShareProviderTest.php @@ -1,34 +1,10 @@ <?php + +declare(strict_types=1); /** - * @copyright Copyright (c) 2016, ownCloud, Inc. - * - * @author Arthur Schiwon <blizzz@arthur-schiwon.de> - * @author Bjoern Schiessle <bjoern@schiessle.org> - * @author Björn Schießle <bjoern@schiessle.org> - * @author Christoph Wurst <christoph@winzerhof-wurst.at> - * @author Georg Ehrke <oc.list@georgehrke.com> - * @author Joas Schilling <coding@schilljs.com> - * @author Lukas Reschke <lukas@statuscode.ch> - * @author Morris Jobke <hey@morrisjobke.de> - * @author Robin Appelman <robin@icewind.nl> - * @author Roeland Jago Douma <roeland@famdouma.nl> - * @author Valdnet <47037905+Valdnet@users.noreply.github.com> - * @author Vincent Petry <vincent@nextcloud.com> - * - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see <http://www.gnu.org/licenses/> - * + * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors + * SPDX-FileCopyrightText: 2016 ownCloud, Inc. + * SPDX-License-Identifier: AGPL-3.0-only */ namespace OCA\FederatedFileSharing\Tests; @@ -37,20 +13,24 @@ use OCA\FederatedFileSharing\AddressHandler; use OCA\FederatedFileSharing\FederatedShareProvider; use OCA\FederatedFileSharing\Notifications; use OCA\FederatedFileSharing\TokenHandler; +use OCP\Constants; use OCP\Contacts\IManager as IContactsManager; +use OCP\EventDispatcher\IEventDispatcher; use OCP\Federation\ICloudFederationProviderManager; use OCP\Federation\ICloudIdManager; use OCP\Files\File; use OCP\Files\IRootFolder; +use OCP\ICacheFactory; use OCP\IConfig; use OCP\IDBConnection; use OCP\IL10N; -use OCP\ILogger; use OCP\IURLGenerator; use OCP\IUserManager; +use OCP\Server; use OCP\Share\IManager; use OCP\Share\IShare; use PHPUnit\Framework\MockObject\MockObject; +use Psr\Log\LoggerInterface; /** * Class FederatedShareProviderTest @@ -59,64 +39,47 @@ use PHPUnit\Framework\MockObject\MockObject; * @group DB */ class FederatedShareProviderTest extends \Test\TestCase { - - /** @var IDBConnection */ - protected $connection; - /** @var AddressHandler | \PHPUnit\Framework\MockObject\MockObject */ - protected $addressHandler; - /** @var Notifications | \PHPUnit\Framework\MockObject\MockObject */ - protected $notifications; - /** @var TokenHandler|\PHPUnit\Framework\MockObject\MockObject */ - protected $tokenHandler; - /** @var IL10N */ - protected $l; - /** @var ILogger */ - protected $logger; - /** @var IRootFolder | \PHPUnit\Framework\MockObject\MockObject */ - protected $rootFolder; - /** @var IConfig | \PHPUnit\Framework\MockObject\MockObject */ - protected $config; - /** @var IUserManager | \PHPUnit\Framework\MockObject\MockObject */ - protected $userManager; - /** @var \OCP\GlobalScale\IConfig|\PHPUnit\Framework\MockObject\MockObject */ - protected $gsConfig; - - /** @var IManager */ - protected $shareManager; - /** @var FederatedShareProvider */ - protected $provider; - /** @var IContactsManager|\PHPUnit\Framework\MockObject\MockObject */ - protected $contactsManager; - - /** @var ICloudIdManager */ - private $cloudIdManager; - - /** @var \PHPUnit\Framework\MockObject\MockObject|ICloudFederationProviderManager */ - private $cloudFederationProviderManager; + protected IDBConnection $connection; + protected AddressHandler&MockObject $addressHandler; + protected Notifications&MockObject $notifications; + protected TokenHandler&MockObject $tokenHandler; + protected IL10N $l; + protected LoggerInterface $logger; + protected IRootFolder&MockObject $rootFolder; + protected IConfig&MockObject $config; + protected IUserManager&MockObject $userManager; + protected \OCP\GlobalScale\IConfig&MockObject $gsConfig; + protected IManager $shareManager; + protected FederatedShareProvider $provider; + protected IContactsManager&MockObject $contactsManager; + private ICloudIdManager $cloudIdManager; + private ICloudFederationProviderManager&MockObject $cloudFederationProviderManager; protected function setUp(): void { parent::setUp(); - $this->connection = \OC::$server->getDatabaseConnection(); - $this->notifications = $this->getMockBuilder('OCA\FederatedFileSharing\Notifications') - ->disableOriginalConstructor() - ->getMock(); - $this->tokenHandler = $this->getMockBuilder('OCA\FederatedFileSharing\TokenHandler') - ->disableOriginalConstructor() - ->getMock(); - $this->l = $this->getMockBuilder(IL10N::class)->getMock(); + $this->connection = Server::get(IDBConnection::class); + $this->notifications = $this->createMock(Notifications::class); + $this->tokenHandler = $this->createMock(TokenHandler::class); + $this->l = $this->createMock(IL10N::class); $this->l->method('t') ->willReturnCallback(function ($text, $parameters = []) { return vsprintf($text, $parameters); }); - $this->logger = $this->getMockBuilder(ILogger::class)->getMock(); - $this->rootFolder = $this->getMockBuilder('OCP\Files\IRootFolder')->getMock(); - $this->config = $this->getMockBuilder(IConfig::class)->getMock(); - $this->userManager = $this->getMockBuilder(IUserManager::class)->getMock(); + $this->logger = $this->createMock(LoggerInterface::class); + $this->rootFolder = $this->createMock(IRootFolder::class); + $this->config = $this->createMock(IConfig::class); + $this->userManager = $this->createMock(IUserManager::class); //$this->addressHandler = new AddressHandler(\OC::$server->getURLGenerator(), $this->l); - $this->addressHandler = $this->getMockBuilder('OCA\FederatedFileSharing\AddressHandler')->disableOriginalConstructor()->getMock(); + $this->addressHandler = $this->createMock(AddressHandler::class); $this->contactsManager = $this->createMock(IContactsManager::class); - $this->cloudIdManager = new CloudIdManager($this->contactsManager, $this->createMock(IURLGenerator::class), $this->userManager); + $this->cloudIdManager = new CloudIdManager( + $this->createMock(ICacheFactory::class), + $this->createMock(IEventDispatcher::class), + $this->contactsManager, + $this->createMock(IURLGenerator::class), + $this->userManager, + ); $this->gsConfig = $this->createMock(\OCP\GlobalScale\IConfig::class); $this->userManager->expects($this->any())->method('userExists')->willReturn(true); @@ -129,39 +92,37 @@ class FederatedShareProviderTest extends \Test\TestCase { $this->notifications, $this->tokenHandler, $this->l, - $this->logger, $this->rootFolder, $this->config, $this->userManager, $this->cloudIdManager, $this->gsConfig, - $this->cloudFederationProviderManager + $this->cloudFederationProviderManager, + $this->logger, ); - $this->shareManager = \OC::$server->getShareManager(); + $this->shareManager = Server::get(IManager::class); } protected function tearDown(): void { - $this->connection->getQueryBuilder()->delete('share')->execute(); + $this->connection->getQueryBuilder()->delete('share')->executeStatement(); parent::tearDown(); } - public function dataTestCreate() { + public static function dataTestCreate(): array { return [ [null, null], [new \DateTime('2020-03-01T01:02:03'), '2020-03-01 01:02:03'], ]; } - /** - * @dataProvider dataTestCreate - */ - public function testCreate($expirationDate, $expectedDataDate) { + #[\PHPUnit\Framework\Attributes\DataProvider('dataTestCreate')] + public function testCreate(?\DateTime $expirationDate, ?string $expectedDataDate): void { $share = $this->shareManager->newShare(); - /** @var File|MockObject $node */ - $node = $this->getMockBuilder(File::class)->getMock(); + /** @var File&MockObject $node */ + $node = $this->createMock(File::class); $node->method('getId')->willReturn(42); $node->method('getName')->willReturn('myFile'); @@ -188,9 +149,9 @@ class FederatedShareProviderTest extends \Test\TestCase { $this->equalTo('myFile'), $this->anything(), 'shareOwner', - 'shareOwner@http://localhost/', + 'shareOwner@http://localhost', 'sharedBy', - 'sharedBy@http://localhost/' + 'sharedBy@http://localhost' ) ->willReturn(true); @@ -206,7 +167,7 @@ class FederatedShareProviderTest extends \Test\TestCase { $stmt = $qb->select('*') ->from('share') ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId()))) - ->execute(); + ->executeQuery(); $data = $stmt->fetch(); $stmt->closeCursor(); @@ -240,10 +201,10 @@ class FederatedShareProviderTest extends \Test\TestCase { $this->assertEquals($expirationDate, $share->getExpirationDate()); } - public function testCreateCouldNotFindServer() { + public function testCreateCouldNotFindServer(): void { $share = $this->shareManager->newShare(); - $node = $this->getMockBuilder(File::class)->getMock(); + $node = $this->createMock(File::class); $node->method('getId')->willReturn(42); $node->method('getName')->willReturn('myFile'); @@ -269,9 +230,9 @@ class FederatedShareProviderTest extends \Test\TestCase { $this->equalTo('myFile'), $this->anything(), 'shareOwner', - 'shareOwner@http://localhost/', + 'shareOwner@http://localhost', 'sharedBy', - 'sharedBy@http://localhost/' + 'sharedBy@http://localhost' )->willReturn(false); $this->rootFolder->method('getById') @@ -293,7 +254,7 @@ class FederatedShareProviderTest extends \Test\TestCase { $stmt = $qb->select('*') ->from('share') ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId()))) - ->execute(); + ->executeQuery(); $data = $stmt->fetch(); $stmt->closeCursor(); @@ -301,10 +262,10 @@ class FederatedShareProviderTest extends \Test\TestCase { $this->assertFalse($data); } - public function testCreateException() { + public function testCreateException(): void { $share = $this->shareManager->newShare(); - $node = $this->getMockBuilder(File::class)->getMock(); + $node = $this->createMock(File::class); $node->method('getId')->willReturn(42); $node->method('getName')->willReturn('myFile'); @@ -330,9 +291,9 @@ class FederatedShareProviderTest extends \Test\TestCase { $this->equalTo('myFile'), $this->anything(), 'shareOwner', - 'shareOwner@http://localhost/', + 'shareOwner@http://localhost', 'sharedBy', - 'sharedBy@http://localhost/' + 'sharedBy@http://localhost' )->willThrowException(new \Exception('dummy')); $this->rootFolder->method('getById') @@ -354,7 +315,7 @@ class FederatedShareProviderTest extends \Test\TestCase { $stmt = $qb->select('*') ->from('share') ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId()))) - ->execute(); + ->executeQuery(); $data = $stmt->fetch(); $stmt->closeCursor(); @@ -362,10 +323,10 @@ class FederatedShareProviderTest extends \Test\TestCase { $this->assertFalse($data); } - public function testCreateShareWithSelf() { + public function testCreateShareWithSelf(): void { $share = $this->shareManager->newShare(); - $node = $this->getMockBuilder(File::class)->getMock(); + $node = $this->createMock(File::class); $node->method('getId')->willReturn(42); $node->method('getName')->willReturn('myFile'); @@ -390,14 +351,14 @@ class FederatedShareProviderTest extends \Test\TestCase { $share = $this->provider->create($share); $this->fail(); } catch (\Exception $e) { - $this->assertEquals('Not allowed to create a federated share with the same user', $e->getMessage()); + $this->assertEquals('Not allowed to create a federated share to the same account', $e->getMessage()); } $qb = $this->connection->getQueryBuilder(); $stmt = $qb->select('*') ->from('share') ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId()))) - ->execute(); + ->executeQuery(); $data = $stmt->fetch(); $stmt->closeCursor(); @@ -405,10 +366,10 @@ class FederatedShareProviderTest extends \Test\TestCase { $this->assertFalse($data); } - public function testCreateAlreadyShared() { + public function testCreateAlreadyShared(): void { $share = $this->shareManager->newShare(); - $node = $this->getMockBuilder(File::class)->getMock(); + $node = $this->createMock(File::class); $node->method('getId')->willReturn(42); $node->method('getName')->willReturn('myFile'); @@ -436,9 +397,9 @@ class FederatedShareProviderTest extends \Test\TestCase { $this->equalTo('myFile'), $this->anything(), 'shareOwner', - 'shareOwner@http://localhost/', + 'shareOwner@http://localhost', 'sharedBy', - 'sharedBy@http://localhost/' + 'sharedBy@http://localhost' )->willReturn(true); $this->rootFolder->expects($this->never())->method($this->anything()); @@ -452,15 +413,13 @@ class FederatedShareProviderTest extends \Test\TestCase { try { $this->provider->create($share); } catch (\Exception $e) { - $this->assertEquals('Sharing myFile failed, because this item is already shared with user user@server.com', $e->getMessage()); + $this->assertEquals('Sharing myFile failed, because this item is already shared with the account user@server.com', $e->getMessage()); } } - /** - * @dataProvider dataTestUpdate - */ - public function testUpdate($owner, $sharedBy, $expirationDate) { - $this->provider = $this->getMockBuilder('OCA\FederatedFileSharing\FederatedShareProvider') + #[\PHPUnit\Framework\Attributes\DataProvider('dataTestUpdate')] + public function testUpdate(string $owner, string $sharedBy, ?\DateTime $expirationDate): void { + $this->provider = $this->getMockBuilder(FederatedShareProvider::class) ->setConstructorArgs( [ $this->connection, @@ -468,19 +427,21 @@ class FederatedShareProviderTest extends \Test\TestCase { $this->notifications, $this->tokenHandler, $this->l, - $this->logger, $this->rootFolder, $this->config, $this->userManager, $this->cloudIdManager, $this->gsConfig, - $this->cloudFederationProviderManager + $this->cloudFederationProviderManager, + $this->logger, ] - )->setMethods(['sendPermissionUpdate'])->getMock(); + ) + ->onlyMethods(['sendPermissionUpdate']) + ->getMock(); $share = $this->shareManager->newShare(); - $node = $this->getMockBuilder(File::class)->getMock(); + $node = $this->createMock(File::class); $node->method('getId')->willReturn(42); $node->method('getName')->willReturn('myFile'); @@ -507,9 +468,9 @@ class FederatedShareProviderTest extends \Test\TestCase { $this->equalTo('myFile'), $this->anything(), $owner, - $owner . '@http://localhost/', + $owner . '@http://localhost', $sharedBy, - $sharedBy . '@http://localhost/' + $sharedBy . '@http://localhost' )->willReturn(true); if ($owner === $sharedBy) { @@ -536,23 +497,19 @@ class FederatedShareProviderTest extends \Test\TestCase { $this->assertEquals($expirationDate, $share->getExpirationDate()); } - public function dataTestUpdate() { + public static function dataTestUpdate(): array { return [ ['sharedBy', 'shareOwner', new \DateTime('2020-03-01T01:02:03')], ['shareOwner', 'shareOwner', null], ]; } - public function testGetSharedBy() { - $node = $this->getMockBuilder(File::class)->getMock(); + public function testGetSharedBy(): void { + $node = $this->createMock(File::class); $node->method('getId')->willReturn(42); $node->method('getName')->willReturn('myFile'); - $this->addressHandler->expects($this->at(0))->method('splitUserRemote') - ->willReturn(['user', 'server.com']); - - $this->addressHandler->expects($this->at(1))->method('splitUserRemote') - ->willReturn(['user2', 'server.com']); + $this->addressHandler->expects($this->never())->method('splitUserRemote'); $this->addressHandler->method('generateRemoteURL') ->willReturn('remoteurl.com'); @@ -593,8 +550,8 @@ class FederatedShareProviderTest extends \Test\TestCase { $this->assertEquals('sharedBy', $shares[0]->getSharedBy()); } - public function testGetSharedByWithNode() { - $node = $this->getMockBuilder(File::class)->getMock(); + public function testGetSharedByWithNode(): void { + $node = $this->createMock(File::class); $node->method('getId')->willReturn(42); $node->method('getName')->willReturn('myFile'); @@ -640,8 +597,8 @@ class FederatedShareProviderTest extends \Test\TestCase { $this->assertEquals(43, $shares[0]->getNodeId()); } - public function testGetSharedByWithReshares() { - $node = $this->getMockBuilder(File::class)->getMock(); + public function testGetSharedByWithReshares(): void { + $node = $this->createMock(File::class); $node->method('getId')->willReturn(42); $node->method('getName')->willReturn('myFile'); @@ -682,8 +639,8 @@ class FederatedShareProviderTest extends \Test\TestCase { $this->assertCount(2, $shares); } - public function testGetSharedByWithLimit() { - $node = $this->getMockBuilder(File::class)->getMock(); + public function testGetSharedByWithLimit(): void { + $node = $this->createMock(File::class); $node->method('getId')->willReturn(42); $node->method('getName')->willReturn('myFile'); @@ -733,7 +690,7 @@ class FederatedShareProviderTest extends \Test\TestCase { $this->assertEquals('user2@server.com', $shares[0]->getSharedWith()); } - public function dataDeleteUser() { + public static function dataDeleteUser(): array { return [ ['a', 'b', 'c', 'a', true], ['a', 'b', 'c', 'b', false], @@ -744,7 +701,6 @@ class FederatedShareProviderTest extends \Test\TestCase { } /** - * @dataProvider dataDeleteUser * * @param string $owner The owner of the share (uid) * @param string $initiator The initiator of the share (uid) @@ -752,7 +708,8 @@ class FederatedShareProviderTest extends \Test\TestCase { * @param string $deletedUser The user that is deleted * @param bool $rowDeleted Is the row deleted in this setup */ - public function testDeleteUser($owner, $initiator, $recipient, $deletedUser, $rowDeleted) { + #[\PHPUnit\Framework\Attributes\DataProvider('dataDeleteUser')] + public function testDeleteUser(string $owner, string $initiator, string $recipient, string $deletedUser, bool $rowDeleted): void { $qb = $this->connection->getQueryBuilder(); $qb->insert('share') ->setValue('share_type', $qb->createNamedParameter(IShare::TYPE_REMOTE)) @@ -762,7 +719,7 @@ class FederatedShareProviderTest extends \Test\TestCase { ->setValue('item_type', $qb->createNamedParameter('file')) ->setValue('item_source', $qb->createNamedParameter(42)) ->setValue('file_source', $qb->createNamedParameter(42)) - ->execute(); + ->executeStatement(); $id = $qb->getLastInsertId(); @@ -774,20 +731,15 @@ class FederatedShareProviderTest extends \Test\TestCase { ->where( $qb->expr()->eq('id', $qb->createNamedParameter($id)) ); - $cursor = $qb->execute(); + $cursor = $qb->executeQuery(); $data = $cursor->fetchAll(); $cursor->closeCursor(); $this->assertCount($rowDeleted ? 0 : 1, $data); } - /** - * @dataProvider dataTestIsOutgoingServer2serverShareEnabled - * - * @param string $isEnabled - * @param bool $expected - */ - public function testIsOutgoingServer2serverShareEnabled($internalOnly, $isEnabled, $expected) { + #[\PHPUnit\Framework\Attributes\DataProvider('dataTestIsOutgoingServer2serverShareEnabled')] + public function testIsOutgoingServer2serverShareEnabled(bool $internalOnly, string $isEnabled, bool $expected): void { $this->gsConfig->expects($this->once())->method('onlyInternalFederation') ->willReturn($internalOnly); $this->config->expects($this->any())->method('getAppValue') @@ -799,7 +751,7 @@ class FederatedShareProviderTest extends \Test\TestCase { ); } - public function dataTestIsOutgoingServer2serverShareEnabled() { + public static function dataTestIsOutgoingServer2serverShareEnabled(): array { return [ [false, 'yes', true], [false, 'no', false], @@ -808,13 +760,8 @@ class FederatedShareProviderTest extends \Test\TestCase { ]; } - /** - * @dataProvider dataTestIsIncomingServer2serverShareEnabled - * - * @param string $isEnabled - * @param bool $expected - */ - public function testIsIncomingServer2serverShareEnabled($onlyInternal, $isEnabled, $expected) { + #[\PHPUnit\Framework\Attributes\DataProvider('dataTestIsIncomingServer2serverShareEnabled')] + public function testIsIncomingServer2serverShareEnabled(bool $onlyInternal, string $isEnabled, bool $expected): void { $this->gsConfig->expects($this->once())->method('onlyInternalFederation') ->willReturn($onlyInternal); $this->config->expects($this->any())->method('getAppValue') @@ -826,7 +773,7 @@ class FederatedShareProviderTest extends \Test\TestCase { ); } - public function dataTestIsIncomingServer2serverShareEnabled() { + public static function dataTestIsIncomingServer2serverShareEnabled(): array { return [ [false, 'yes', true], [false, 'no', false], @@ -835,17 +782,12 @@ class FederatedShareProviderTest extends \Test\TestCase { ]; } - /** - * @dataProvider dataTestIsLookupServerQueriesEnabled - * - * @param string $isEnabled - * @param bool $expected - */ - public function testIsLookupServerQueriesEnabled($gsEnabled, $isEnabled, $expected) { + #[\PHPUnit\Framework\Attributes\DataProvider('dataTestIsLookupServerQueriesEnabled')] + public function testIsLookupServerQueriesEnabled(bool $gsEnabled, string $isEnabled, bool $expected): void { $this->gsConfig->expects($this->once())->method('isGlobalScaleEnabled') ->willReturn($gsEnabled); $this->config->expects($this->any())->method('getAppValue') - ->with('files_sharing', 'lookupServerEnabled', 'yes') + ->with('files_sharing', 'lookupServerEnabled', 'no') ->willReturn($isEnabled); $this->assertSame($expected, @@ -854,26 +796,24 @@ class FederatedShareProviderTest extends \Test\TestCase { } - public function dataTestIsLookupServerQueriesEnabled() { + public static function dataTestIsLookupServerQueriesEnabled(): array { return [ - [false, 'yes', true], - [false, 'no', false], [true, 'yes', true], [true, 'no', true], + // TODO: reenable if we use the lookup server for non-global scale + // [false, 'yes', true], + // [false, 'no', false], + [false, 'no', false], + [false, 'yes', false], ]; } - /** - * @dataProvider dataTestIsLookupServerUploadEnabled - * - * @param string $isEnabled - * @param bool $expected - */ - public function testIsLookupServerUploadEnabled($gsEnabled, $isEnabled, $expected) { + #[\PHPUnit\Framework\Attributes\DataProvider('dataTestIsLookupServerUploadEnabled')] + public function testIsLookupServerUploadEnabled(bool $gsEnabled, string $isEnabled, bool $expected): void { $this->gsConfig->expects($this->once())->method('isGlobalScaleEnabled') ->willReturn($gsEnabled); $this->config->expects($this->any())->method('getAppValue') - ->with('files_sharing', 'lookupServerUploadEnabled', 'yes') + ->with('files_sharing', 'lookupServerUploadEnabled', 'no') ->willReturn($isEnabled); $this->assertSame($expected, @@ -881,21 +821,24 @@ class FederatedShareProviderTest extends \Test\TestCase { ); } - public function dataTestIsLookupServerUploadEnabled() { + public static function dataTestIsLookupServerUploadEnabled(): array { return [ - [false, 'yes', true], - [false, 'no', false], [true, 'yes', false], [true, 'no', false], + // TODO: reenable if we use the lookup server again + // [false, 'yes', true], + // [false, 'no', false], + [false, 'yes', false], + [false, 'no', false], ]; } - public function testGetSharesInFolder() { - $userManager = \OC::$server->getUserManager(); - $rootFolder = \OC::$server->getRootFolder(); + public function testGetSharesInFolder(): void { + $userManager = Server::get(IUserManager::class); + $rootFolder = Server::get(IRootFolder::class); - $u1 = $userManager->createUser('testFed', md5(time())); - $u2 = $userManager->createUser('testFed2', md5(time())); + $u1 = $userManager->createUser('testFed', md5((string)time())); + $u2 = $userManager->createUser('testFed2', md5((string)time())); $folder1 = $rootFolder->getUserFolder($u1->getUID())->newFolder('foo'); $file1 = $folder1->newFile('bar1'); @@ -917,7 +860,7 @@ class FederatedShareProviderTest extends \Test\TestCase { $share1->setSharedWith('user@server.com') ->setSharedBy($u1->getUID()) ->setShareOwner($u1->getUID()) - ->setPermissions(\OCP\Constants::PERMISSION_READ) + ->setPermissions(Constants::PERMISSION_READ) ->setShareType(IShare::TYPE_REMOTE) ->setNode($file1); $this->provider->create($share1); @@ -926,7 +869,7 @@ class FederatedShareProviderTest extends \Test\TestCase { $share2->setSharedWith('user@server.com') ->setSharedBy($u2->getUID()) ->setShareOwner($u1->getUID()) - ->setPermissions(\OCP\Constants::PERMISSION_READ) + ->setPermissions(Constants::PERMISSION_READ) ->setShareType(IShare::TYPE_REMOTE) ->setNode($file2); $this->provider->create($share2); @@ -944,11 +887,11 @@ class FederatedShareProviderTest extends \Test\TestCase { $u2->delete(); } - public function testGetAccessList() { - $userManager = \OC::$server->getUserManager(); - $rootFolder = \OC::$server->getRootFolder(); + public function testGetAccessList(): void { + $userManager = Server::get(IUserManager::class); + $rootFolder = Server::get(IRootFolder::class); - $u1 = $userManager->createUser('testFed', md5(time())); + $u1 = $userManager->createUser('testFed', md5((string)time())); $folder1 = $rootFolder->getUserFolder($u1->getUID())->newFolder('foo'); $file1 = $folder1->newFile('bar1'); @@ -977,7 +920,7 @@ class FederatedShareProviderTest extends \Test\TestCase { $share1->setSharedWith('user@server.com') ->setSharedBy($u1->getUID()) ->setShareOwner($u1->getUID()) - ->setPermissions(\OCP\Constants::PERMISSION_READ) + ->setPermissions(Constants::PERMISSION_READ) ->setShareType(IShare::TYPE_REMOTE) ->setNode($file1); $this->provider->create($share1); @@ -986,7 +929,7 @@ class FederatedShareProviderTest extends \Test\TestCase { $share2->setSharedWith('foobar@localhost') ->setSharedBy($u1->getUID()) ->setShareOwner($u1->getUID()) - ->setPermissions(\OCP\Constants::PERMISSION_READ) + ->setPermissions(Constants::PERMISSION_READ) ->setShareType(IShare::TYPE_REMOTE) ->setNode($file1); $this->provider->create($share2); diff --git a/apps/federatedfilesharing/tests/NotificationsTest.php b/apps/federatedfilesharing/tests/NotificationsTest.php index c77d9affb17..da5defd8e55 100644 --- a/apps/federatedfilesharing/tests/NotificationsTest.php +++ b/apps/federatedfilesharing/tests/NotificationsTest.php @@ -1,126 +1,85 @@ <?php + +declare(strict_types=1); /** - * @copyright Copyright (c) 2016, ownCloud, Inc. - * - * @author Bjoern Schiessle <bjoern@schiessle.org> - * @author Björn Schießle <bjoern@schiessle.org> - * @author Morris Jobke <hey@morrisjobke.de> - * @author Roeland Jago Douma <roeland@famdouma.nl> - * @author Samuel <faust64@gmail.com> - * - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see <http://www.gnu.org/licenses/> - * + * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors + * SPDX-FileCopyrightText: 2016 ownCloud, Inc. + * SPDX-License-Identifier: AGPL-3.0-only */ namespace OCA\FederatedFileSharing\Tests; use OCA\FederatedFileSharing\AddressHandler; +use OCA\FederatedFileSharing\BackgroundJob\RetryJob; use OCA\FederatedFileSharing\Notifications; use OCP\BackgroundJob\IJobList; use OCP\EventDispatcher\IEventDispatcher; use OCP\Federation\ICloudFederationFactory; use OCP\Federation\ICloudFederationProviderManager; use OCP\Http\Client\IClientService; -use OCP\ILogger; use OCP\OCS\IDiscoveryService; +use PHPUnit\Framework\MockObject\MockObject; +use Psr\Log\LoggerInterface; class NotificationsTest extends \Test\TestCase { - - /** @var AddressHandler | \PHPUnit\Framework\MockObject\MockObject */ - private $addressHandler; - - /** @var IClientService | \PHPUnit\Framework\MockObject\MockObject*/ - private $httpClientService; - - /** @var IDiscoveryService | \PHPUnit\Framework\MockObject\MockObject */ - private $discoveryService; - - /** @var IJobList | \PHPUnit\Framework\MockObject\MockObject */ - private $jobList; - - /** @var ICloudFederationProviderManager|\PHPUnit\Framework\MockObject\MockObject */ - private $cloudFederationProviderManager; - - /** @var ICloudFederationFactory|\PHPUnit\Framework\MockObject\MockObject */ - private $cloudFederationFactory; - - /** @var IEventDispatcher|\PHPUnit\Framework\MockObject\MockObject */ - private $eventDispatcher; - - /** @var ILogger|\PHPUnit\Framework\MockObject\MockObject */ - private $logger; + private AddressHandler&MockObject $addressHandler; + private IClientService&MockObject $httpClientService; + private IDiscoveryService&MockObject $discoveryService; + private IJobList&MockObject $jobList; + private ICloudFederationProviderManager&MockObject $cloudFederationProviderManager; + private ICloudFederationFactory&MockObject $cloudFederationFactory; + private IEventDispatcher&MockObject $eventDispatcher; + private LoggerInterface&MockObject $logger; protected function setUp(): void { parent::setUp(); - $this->jobList = $this->getMockBuilder('OCP\BackgroundJob\IJobList')->getMock(); - $this->discoveryService = $this->getMockBuilder(IDiscoveryService::class)->getMock(); - $this->httpClientService = $this->getMockBuilder('OCP\Http\Client\IClientService')->getMock(); - $this->addressHandler = $this->getMockBuilder('OCA\FederatedFileSharing\AddressHandler') - ->disableOriginalConstructor()->getMock(); - $this->logger = $this->createMock(ILogger::class); + $this->jobList = $this->createMock(IJobList::class); + $this->discoveryService = $this->createMock(IDiscoveryService::class); + $this->httpClientService = $this->createMock(IClientService::class); + $this->addressHandler = $this->createMock(AddressHandler::class); + $this->logger = $this->createMock(LoggerInterface::class); $this->cloudFederationProviderManager = $this->createMock(ICloudFederationProviderManager::class); $this->cloudFederationFactory = $this->createMock(ICloudFederationFactory::class); $this->eventDispatcher = $this->createMock(IEventDispatcher::class); } /** - * get instance of Notifications class - * - * @param array $mockedMethods methods which should be mocked - * @return Notifications | \PHPUnit\Framework\MockObject\MockObject + * @return Notifications|MockObject */ private function getInstance(array $mockedMethods = []) { if (empty($mockedMethods)) { - $instance = new Notifications( + return new Notifications( $this->addressHandler, $this->httpClientService, $this->discoveryService, - $this->logger, $this->jobList, $this->cloudFederationProviderManager, $this->cloudFederationFactory, - $this->eventDispatcher + $this->eventDispatcher, + $this->logger, ); - } else { - $instance = $this->getMockBuilder('OCA\FederatedFileSharing\Notifications') - ->setConstructorArgs( - [ - $this->addressHandler, - $this->httpClientService, - $this->discoveryService, - $this->logger, - $this->jobList, - $this->cloudFederationProviderManager, - $this->cloudFederationFactory, - $this->eventDispatcher - ] - )->setMethods($mockedMethods)->getMock(); } - return $instance; + return $this->getMockBuilder(Notifications::class) + ->setConstructorArgs( + [ + $this->addressHandler, + $this->httpClientService, + $this->discoveryService, + $this->jobList, + $this->cloudFederationProviderManager, + $this->cloudFederationFactory, + $this->eventDispatcher, + $this->logger, + ] + ) + ->onlyMethods($mockedMethods) + ->getMock(); } - /** - * @dataProvider dataTestSendUpdateToRemote - * - * @param int $try - * @param array $httpRequestResult - * @param bool $expected - */ - public function testSendUpdateToRemote($try, $httpRequestResult, $expected) { + #[\PHPUnit\Framework\Attributes\DataProvider('dataTestSendUpdateToRemote')] + public function testSendUpdateToRemote(int $try, array $httpRequestResult, bool $expected): void { $remote = 'http://remote'; $id = 42; $timestamp = 63576; @@ -131,14 +90,14 @@ class NotificationsTest extends \Test\TestCase { $instance->expects($this->any())->method('getTimestamp')->willReturn($timestamp); $instance->expects($this->once())->method('tryHttpPostToShareEndpoint') - ->with($remote, '/'.$id.'/unshare', ['token' => $token, 'data1Key' => 'data1Value', 'remoteId' => $id], $action) + ->with($remote, '/' . $id . '/unshare', ['token' => $token, 'data1Key' => 'data1Value', 'remoteId' => $id], $action) ->willReturn($httpRequestResult); // only add background job on first try if ($try === 0 && $expected === false) { $this->jobList->expects($this->once())->method('add') ->with( - 'OCA\FederatedFileSharing\BackgroundJob\RetryJob', + RetryJob::class, [ 'remote' => $remote, 'remoteId' => $id, @@ -159,7 +118,7 @@ class NotificationsTest extends \Test\TestCase { } - public function dataTestSendUpdateToRemote() { + public static function dataTestSendUpdateToRemote(): array { return [ // test if background job is added correctly [0, ['success' => true, 'result' => json_encode(['ocs' => ['meta' => ['statuscode' => 200]]])], true], diff --git a/apps/federatedfilesharing/tests/Settings/AdminTest.php b/apps/federatedfilesharing/tests/Settings/AdminTest.php index 0b3a721d7da..1eee362c11f 100644 --- a/apps/federatedfilesharing/tests/Settings/AdminTest.php +++ b/apps/federatedfilesharing/tests/Settings/AdminTest.php @@ -1,57 +1,48 @@ <?php + +declare(strict_types=1); /** - * @copyright Copyright (c) 2016 Lukas Reschke <lukas@statuscode.ch> - * - * @author Bjoern Schiessle <bjoern@schiessle.org> - * @author Lukas Reschke <lukas@statuscode.ch> - * @author Morris Jobke <hey@morrisjobke.de> - * @author Roeland Jago Douma <roeland@famdouma.nl> - * - * @license GNU AGPL version 3 or any later version - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see <http://www.gnu.org/licenses/>. - * + * SPDX-FileCopyrightText: 2016 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: AGPL-3.0-or-later */ namespace OCA\FederatedFileSharing\Tests\Settings; use OCA\FederatedFileSharing\FederatedShareProvider; use OCA\FederatedFileSharing\Settings\Admin; use OCP\AppFramework\Http\TemplateResponse; +use OCP\AppFramework\Services\IInitialState; use OCP\GlobalScale\IConfig; use OCP\IL10N; +use OCP\IURLGenerator; +use PHPUnit\Framework\MockObject\MockObject; use Test\TestCase; class AdminTest extends TestCase { - /** @var Admin */ - private $admin; - /** @var \OCA\FederatedFileSharing\FederatedShareProvider */ - private $federatedShareProvider; - /** @var IConfig|\PHPUnit\Framework\MockObject\MockObject */ - private $gsConfig; + private FederatedShareProvider&MockObject $federatedShareProvider; + private IConfig $gsConfig; + private IInitialState&MockObject $initialState; + private Admin $admin; protected function setUp(): void { parent::setUp(); $this->federatedShareProvider = $this->createMock(FederatedShareProvider::class); $this->gsConfig = $this->createMock(IConfig::class); + $this->initialState = $this->createMock(IInitialState::class); + $urlGenerator = $this->createMock(IURLGenerator::class); + $urlGenerator->expects($this->any()) + ->method('linkToDocs') + ->willReturn('doc-link'); + $this->admin = new Admin( $this->federatedShareProvider, $this->gsConfig, - $this->createMock(IL10N::class) + $this->createMock(IL10N::class), + $urlGenerator, + $this->initialState ); } - public function sharingStateProvider() { + public static function sharingStateProvider(): array { return [ [ true, @@ -62,11 +53,8 @@ class AdminTest extends TestCase { ]; } - /** - * @dataProvider sharingStateProvider - * @param bool $state - */ - public function testGetForm($state) { + #[\PHPUnit\Framework\Attributes\DataProvider('sharingStateProvider')] + public function testGetForm(bool $state): void { $this->federatedShareProvider ->expects($this->once()) ->method('isOutgoingServer2serverShareEnabled') @@ -99,28 +87,41 @@ class AdminTest extends TestCase { ->expects($this->once()) ->method('isIncomingServer2serverGroupShareEnabled') ->willReturn($state); + $this->federatedShareProvider + ->expects($this->once()) + ->method('isFederatedTrustedShareAutoAccept') + ->willReturn($state); $this->gsConfig->expects($this->once())->method('onlyInternalFederation') ->willReturn($state); - $params = [ - 'internalOnly' => $state, - 'outgoingServer2serverShareEnabled' => $state, - 'incomingServer2serverShareEnabled' => $state, - 'lookupServerEnabled' => $state, - 'lookupServerUploadEnabled' => $state, - 'federatedGroupSharingSupported' => $state, - 'outgoingServer2serverGroupShareEnabled' => $state, - 'incomingServer2serverGroupShareEnabled' => $state, + $calls = [ + ['internalOnly', $state], + ['sharingFederatedDocUrl', 'doc-link'], + ['outgoingServer2serverShareEnabled', $state], + ['incomingServer2serverShareEnabled', $state], + ['federatedGroupSharingSupported', $state], + ['outgoingServer2serverGroupShareEnabled', $state], + ['incomingServer2serverGroupShareEnabled', $state], + ['lookupServerEnabled', $state], + ['lookupServerUploadEnabled', $state], + ['federatedTrustedShareAutoAccept', $state], ]; - $expected = new TemplateResponse('federatedfilesharing', 'settings-admin', $params, ''); + $this->initialState->expects($this->exactly(10)) + ->method('provideInitialState') + ->willReturnCallback(function () use (&$calls): void { + $expected = array_shift($calls); + $this->assertSame($expected, func_get_args()); + }); + + $expected = new TemplateResponse('federatedfilesharing', 'settings-admin', [], ''); $this->assertEquals($expected, $this->admin->getForm()); } - public function testGetSection() { + public function testGetSection(): void { $this->assertSame('sharing', $this->admin->getSection()); } - public function testGetPriority() { + public function testGetPriority(): void { $this->assertSame(20, $this->admin->getPriority()); } } diff --git a/apps/federatedfilesharing/tests/TestCase.php b/apps/federatedfilesharing/tests/TestCase.php index dbd1df38c74..50f01eb5e62 100644 --- a/apps/federatedfilesharing/tests/TestCase.php +++ b/apps/federatedfilesharing/tests/TestCase.php @@ -1,32 +1,20 @@ <?php + +declare(strict_types=1); /** - * @copyright Copyright (c) 2016, ownCloud, Inc. - * - * @author Björn Schießle <bjoern@schiessle.org> - * @author Christoph Wurst <christoph@winzerhof-wurst.at> - * @author Joas Schilling <coding@schilljs.com> - * @author Morris Jobke <hey@morrisjobke.de> - * @author Roeland Jago Douma <roeland@famdouma.nl> - * - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see <http://www.gnu.org/licenses/> - * + * SPDX-FileCopyrightText: 2017-2024 Nextcloud GmbH and Nextcloud contributors + * SPDX-FileCopyrightText: 2016 ownCloud, Inc. + * SPDX-License-Identifier: AGPL-3.0-only */ namespace OCA\FederatedFileSharing\Tests; use OC\Files\Filesystem; use OC\Group\Database; +use OCP\Files\IRootFolder; +use OCP\IGroupManager; +use OCP\IUserManager; +use OCP\IUserSession; +use OCP\Server; /** * Class Test_Files_Sharing_Base @@ -36,19 +24,19 @@ use OC\Group\Database; * Base class for sharing tests. */ abstract class TestCase extends \Test\TestCase { - public const TEST_FILES_SHARING_API_USER1 = "test-share-user1"; - public const TEST_FILES_SHARING_API_USER2 = "test-share-user2"; + public const TEST_FILES_SHARING_API_USER1 = 'test-share-user1'; + public const TEST_FILES_SHARING_API_USER2 = 'test-share-user2'; public static function setUpBeforeClass(): void { parent::setUpBeforeClass(); // reset backend - \OC_User::clearBackends(); - \OC::$server->getGroupManager()->clearBackends(); + Server::get(IUserManager::class)->clearBackends(); + Server::get(IGroupManager::class)->clearBackends(); // create users $backend = new \Test\Util\User\Dummy(); - \OC_User::useBackend($backend); + Server::get(IUserManager::class)->registerBackend($backend); $backend->createUser(self::TEST_FILES_SHARING_API_USER1, self::TEST_FILES_SHARING_API_USER1); $backend->createUser(self::TEST_FILES_SHARING_API_USER2, self::TEST_FILES_SHARING_API_USER2); } @@ -62,11 +50,11 @@ abstract class TestCase extends \Test\TestCase { public static function tearDownAfterClass(): void { // cleanup users - $user = \OC::$server->getUserManager()->get(self::TEST_FILES_SHARING_API_USER1); + $user = Server::get(IUserManager::class)->get(self::TEST_FILES_SHARING_API_USER1); if ($user !== null) { $user->delete(); } - $user = \OC::$server->getUserManager()->get(self::TEST_FILES_SHARING_API_USER2); + $user = Server::get(IUserManager::class)->get(self::TEST_FILES_SHARING_API_USER2); if ($user !== null) { $user->delete(); } @@ -76,27 +64,22 @@ abstract class TestCase extends \Test\TestCase { Filesystem::tearDown(); // reset backend - \OC_User::clearBackends(); - \OC_User::useBackend('database'); - \OC::$server->getGroupManager()->clearBackends(); - \OC::$server->getGroupManager()->addBackend(new Database()); + Server::get(IUserManager::class)->clearBackends(); + Server::get(IUserManager::class)->registerBackend(new \OC\User\Database()); + Server::get(IGroupManager::class)->clearBackends(); + Server::get(IGroupManager::class)->addBackend(new Database()); parent::tearDownAfterClass(); } - /** - * @param string $user - * @param bool $create - * @param bool $password - */ - protected static function loginHelper($user, $create = false, $password = false) { + protected static function loginHelper(string $user, bool $create = false, bool $password = false) { if ($password === false) { $password = $user; } if ($create) { - $userManager = \OC::$server->getUserManager(); - $groupManager = \OC::$server->getGroupManager(); + $userManager = Server::get(IUserManager::class); + $groupManager = Server::get(IGroupManager::class); $userObject = $userManager->createUser($user, $password); $group = $groupManager->createGroup('group'); @@ -106,25 +89,12 @@ abstract class TestCase extends \Test\TestCase { } } - self::resetStorage(); - \OC_Util::tearDownFS(); - \OC::$server->getUserSession()->setUser(null); - \OC\Files\Filesystem::tearDown(); - \OC::$server->getUserSession()->login($user, $password); - \OC::$server->getUserFolder($user); + Server::get(IUserSession::class)->setUser(null); + Filesystem::tearDown(); + Server::get(IUserSession::class)->login($user, $password); + Server::get(IRootFolder::class)->getUserFolder($user); \OC_Util::setupFS($user); } - - /** - * reset init status for the share storage - */ - protected static function resetStorage() { - $storage = new \ReflectionClass('\OCA\Files_Sharing\SharedStorage'); - $isInitialized = $storage->getProperty('initialized'); - $isInitialized->setAccessible(true); - $isInitialized->setValue($storage, false); - $isInitialized->setAccessible(false); - } } diff --git a/apps/federatedfilesharing/tests/TokenHandlerTest.php b/apps/federatedfilesharing/tests/TokenHandlerTest.php index ab28fc0858b..7a210274013 100644 --- a/apps/federatedfilesharing/tests/TokenHandlerTest.php +++ b/apps/federatedfilesharing/tests/TokenHandlerTest.php @@ -1,41 +1,21 @@ <?php + +declare(strict_types=1); /** - * @copyright Copyright (c) 2016, ownCloud, Inc. - * - * @author Björn Schießle <bjoern@schiessle.org> - * @author Morris Jobke <hey@morrisjobke.de> - * @author Roeland Jago Douma <roeland@famdouma.nl> - * - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see <http://www.gnu.org/licenses/> - * + * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors + * SPDX-FileCopyrightText: 2016 ownCloud, Inc. + * SPDX-License-Identifier: AGPL-3.0-only */ namespace OCA\FederatedFileSharing\Tests; use OCA\FederatedFileSharing\TokenHandler; use OCP\Security\ISecureRandom; +use PHPUnit\Framework\MockObject\MockObject; class TokenHandlerTest extends \Test\TestCase { - - /** @var TokenHandler */ - private $tokenHandler; - - /** @var ISecureRandom | \PHPUnit\Framework\MockObject\MockObject */ - private $secureRandom; - - /** @var int */ - private $expectedTokenLength = 15; + private TokenHandler $tokenHandler; + private ISecureRandom&MockObject $secureRandom; + private int $expectedTokenLength = 15; protected function setUp(): void { parent::setUp(); @@ -45,7 +25,7 @@ class TokenHandlerTest extends \Test\TestCase { $this->tokenHandler = new TokenHandler($this->secureRandom); } - public function testGenerateToken() { + public function testGenerateToken(): void { $this->secureRandom->expects($this->once())->method('generate') ->with( $this->expectedTokenLength, diff --git a/apps/federatedfilesharing/tests/js/externalSpec.js b/apps/federatedfilesharing/tests/js/externalSpec.js deleted file mode 100644 index 5a44686c1b3..00000000000 --- a/apps/federatedfilesharing/tests/js/externalSpec.js +++ /dev/null @@ -1,258 +0,0 @@ -/** - * Copyright (c) 2015 Vincent Petry <pvince81@owncloud.com> - * - * @author Christoph Wurst <christoph@winzerhof-wurst.at> - * @author Vincent Petry <vincent@nextcloud.com> - * - * @license AGPL-3.0-or-later - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see <http://www.gnu.org/licenses/>. - * - */ - -describe('OCA.Sharing external tests', function() { - var plugin; - var urlQueryStub; - var promptDialogStub; - var confirmDialogStub; - - function dummyShowDialog() { - var deferred = $.Deferred(); - deferred.resolve(); - return deferred.promise(); - } - - beforeEach(function() { - plugin = OCA.Sharing.ExternalShareDialogPlugin; - urlQueryStub = sinon.stub(OC.Util.History, 'parseUrlQuery'); - - confirmDialogStub = sinon.stub(OC.dialogs, 'confirm').callsFake(dummyShowDialog); - promptDialogStub = sinon.stub(OC.dialogs, 'prompt').callsFake(dummyShowDialog); - - plugin.filesApp = { - fileList: { - reload: sinon.stub() - } - }; - }); - afterEach(function() { - urlQueryStub.restore(); - confirmDialogStub.restore(); - promptDialogStub.restore(); - plugin = null; - }); - describe('confirmation dialog from URL', function() { - var testShare; - - /** - * Checks that the server call's query matches what is - * expected. - * - * @param {Object} expectedQuery expected query params - */ - function checkRequest(expectedQuery) { - var request = fakeServer.requests[0]; - var query = OC.parseQueryString(request.requestBody); - expect(request.method).toEqual('POST'); - expect(query).toEqual(expectedQuery); - - request.respond( - 200, - {'Content-Type': 'application/json'}, - JSON.stringify({status: 'success'}) - ); - expect(plugin.filesApp.fileList.reload.calledOnce).toEqual(true); - } - - beforeEach(function() { - testShare = { - remote: 'http://example.com/owncloud', - token: 'abcdefg', - owner: 'theowner', - ownerDisplayName: 'The Generous Owner', - name: 'the share name' - }; - }); - it('does nothing when no share was passed in URL', function() { - urlQueryStub.returns({}); - plugin.processIncomingShareFromUrl(); - expect(promptDialogStub.notCalled).toEqual(true); - expect(confirmDialogStub.notCalled).toEqual(true); - expect(fakeServer.requests.length).toEqual(0); - }); - it('sends share info to server on confirm', function() { - urlQueryStub.returns(testShare); - plugin.processIncomingShareFromUrl(); - expect(promptDialogStub.notCalled).toEqual(true); - expect(confirmDialogStub.calledOnce).toEqual(true); - confirmDialogStub.getCall(0).args[2](true); - expect(fakeServer.requests.length).toEqual(1); - checkRequest({ - remote: 'http://example.com/owncloud', - token: 'abcdefg', - owner: 'theowner', - ownerDisplayName: 'The Generous Owner', - name: 'the share name', - password: '' - }); - }); - it('sends share info with password to server on confirm', function() { - testShare = _.extend(testShare, {protected: 1}); - urlQueryStub.returns(testShare); - plugin.processIncomingShareFromUrl(); - expect(promptDialogStub.calledOnce).toEqual(true); - expect(confirmDialogStub.notCalled).toEqual(true); - promptDialogStub.getCall(0).args[2](true, 'thepassword'); - expect(fakeServer.requests.length).toEqual(1); - checkRequest({ - remote: 'http://example.com/owncloud', - token: 'abcdefg', - owner: 'theowner', - ownerDisplayName: 'The Generous Owner', - name: 'the share name', - password: 'thepassword' - }); - }); - it('does not send share info on cancel', function() { - urlQueryStub.returns(testShare); - plugin.processIncomingShareFromUrl(); - expect(promptDialogStub.notCalled).toEqual(true); - expect(confirmDialogStub.calledOnce).toEqual(true); - confirmDialogStub.getCall(0).args[2](false); - expect(fakeServer.requests.length).toEqual(0); - }); - }); - describe('show dialog for each share to confirm', function() { - var testShare; - - /** - * Call processSharesToConfirm() and make the fake server - * return the passed response. - * - * @param {Array} response list of shares to process - */ - function processShares(response) { - plugin.processSharesToConfirm(); - - expect(fakeServer.requests.length).toEqual(1); - - var req = fakeServer.requests[0]; - expect(req.method).toEqual('GET'); - expect(req.url).toEqual(OC.getRootPath() + '/index.php/apps/files_sharing/api/externalShares'); - - req.respond( - 200, - {'Content-Type': 'application/json'}, - JSON.stringify(response) - ); - } - - beforeEach(function() { - testShare = { - id: 123, - remote: 'http://example.com/owncloud', - token: 'abcdefg', - owner: 'theowner', - ownerDisplayName: 'The Generous Owner', - name: 'the share name' - }; - }); - - it('does not show any dialog if no shares to confirm', function() { - processShares([]); - expect(confirmDialogStub.notCalled).toEqual(true); - expect(promptDialogStub.notCalled).toEqual(true); - }); - it('sends accept info to server on confirm', function() { - processShares([testShare]); - - expect(promptDialogStub.notCalled).toEqual(true); - expect(confirmDialogStub.calledOnce).toEqual(true); - - confirmDialogStub.getCall(0).args[2](true); - - expect(fakeServer.requests.length).toEqual(2); - - var request = fakeServer.requests[1]; - var query = OC.parseQueryString(request.requestBody); - expect(request.method).toEqual('POST'); - expect(query).toEqual({id: '123'}); - expect(request.url).toEqual( - OC.getRootPath() + '/index.php/apps/files_sharing/api/externalShares' - ); - - expect(plugin.filesApp.fileList.reload.notCalled).toEqual(true); - request.respond( - 200, - {'Content-Type': 'application/json'}, - JSON.stringify({status: 'success'}) - ); - expect(plugin.filesApp.fileList.reload.calledOnce).toEqual(true); - }); - it('sends delete info to server on cancel', function() { - processShares([testShare]); - - expect(promptDialogStub.notCalled).toEqual(true); - expect(confirmDialogStub.calledOnce).toEqual(true); - - confirmDialogStub.getCall(0).args[2](false); - - expect(fakeServer.requests.length).toEqual(2); - - var request = fakeServer.requests[1]; - expect(request.method).toEqual('DELETE'); - expect(request.url).toEqual( - OC.getRootPath() + '/index.php/apps/files_sharing/api/externalShares/123' - ); - - expect(plugin.filesApp.fileList.reload.notCalled).toEqual(true); - request.respond( - 200, - {'Content-Type': 'application/json'}, - JSON.stringify({status: 'success'}) - ); - expect(plugin.filesApp.fileList.reload.notCalled).toEqual(true); - }); - xit('shows another dialog when multiple shares need to be accepted', function() { - // TODO: enable this test when fixing multiple dialogs issue / confirm loop - var testShare2 = _.extend({}, testShare); - testShare2.id = 256; - processShares([testShare, testShare2]); - - // confirm first one - expect(confirmDialogStub.calledOnce).toEqual(true); - confirmDialogStub.getCall(0).args[2](true); - - // next dialog not shown yet - expect(confirmDialogStub.calledOnce); - - // respond to the first accept request - fakeServer.requests[1].respond( - 200, - {'Content-Type': 'application/json'}, - JSON.stringify({status: 'success'}) - ); - - // don't reload yet, there are other shares to confirm - expect(plugin.filesApp.fileList.reload.notCalled).toEqual(true); - - // cancel second share - expect(confirmDialogStub.calledTwice).toEqual(true); - confirmDialogStub.getCall(1).args[2](true); - - // reload only called at the very end - expect(plugin.filesApp.fileList.reload.calledOnce).toEqual(true); - }); - }); -}); |