diff options
Diffstat (limited to 'apps/files_external/tests')
67 files changed, 1784 insertions, 2521 deletions
diff --git a/apps/files_external/tests/Auth/AuthMechanismTest.php b/apps/files_external/tests/Auth/AuthMechanismTest.php index ed3b52c1dbb..e999cecf181 100644 --- a/apps/files_external/tests/Auth/AuthMechanismTest.php +++ b/apps/files_external/tests/Auth/AuthMechanismTest.php @@ -1,26 +1,11 @@ <?php + +declare(strict_types=1); /** - * @copyright Copyright (c) 2016, ownCloud, Inc. - * - * @author Morris Jobke <hey@morrisjobke.de> - * @author Robin McCorkell <robin@mccorkell.me.uk> - * - * @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: 2020-2024 Nextcloud GmbH and Nextcloud contributors + * SPDX-FileCopyrightText: 2016 ownCloud, Inc. + * SPDX-License-Identifier: AGPL-3.0-only */ - namespace OCA\Files_External\Tests\Auth; use OCA\Files_External\Lib\Auth\AuthMechanism; @@ -28,10 +13,9 @@ use OCA\Files_External\Lib\Backend\Backend; use OCA\Files_External\Lib\StorageConfig; class AuthMechanismTest extends \Test\TestCase { - - public function testJsonSerialization() { + public function testJsonSerialization(): void { $mechanism = $this->getMockBuilder(AuthMechanism::class) - ->setMethods(['jsonSerializeDefinition']) + ->onlyMethods(['jsonSerializeDefinition']) ->getMock(); $mechanism->expects($this->once()) ->method('jsonSerializeDefinition') @@ -44,7 +28,7 @@ class AuthMechanismTest extends \Test\TestCase { $this->assertEquals('scheme', $json['scheme']); } - public function validateStorageProvider() { + public static function validateStorageProvider(): array { return [ [true, 'scheme', true], [false, 'scheme', false], @@ -53,12 +37,10 @@ class AuthMechanismTest extends \Test\TestCase { ]; } - /** - * @dataProvider validateStorageProvider - */ - public function testValidateStorage($expectedSuccess, $scheme, $definitionSuccess) { + #[\PHPUnit\Framework\Attributes\DataProvider('validateStorageProvider')] + public function testValidateStorage(bool $expectedSuccess, string $scheme, bool $definitionSuccess): void { $mechanism = $this->getMockBuilder(AuthMechanism::class) - ->setMethods(['validateStorageDefinition']) + ->onlyMethods(['validateStorageDefinition']) ->getMock(); $mechanism->expects($this->atMost(1)) ->method('validateStorageDefinition') @@ -66,21 +48,16 @@ class AuthMechanismTest extends \Test\TestCase { $mechanism->setScheme($scheme); - $backend = $this->getMockBuilder(Backend::class) - ->disableOriginalConstructor() - ->getMock(); + $backend = $this->createMock(Backend::class); $backend->expects($this->once()) ->method('getAuthSchemes') ->willReturn(['scheme' => true, 'foobar' => true]); - $storageConfig = $this->getMockBuilder(StorageConfig::class) - ->disableOriginalConstructor() - ->getMock(); + $storageConfig = $this->createMock(StorageConfig::class); $storageConfig->expects($this->once()) ->method('getBackend') ->willReturn($backend); $this->assertEquals($expectedSuccess, $mechanism->validateStorage($storageConfig)); } - } diff --git a/apps/files_external/tests/Auth/Password/GlobalAuth.php b/apps/files_external/tests/Auth/Password/GlobalAuthTest.php index c447be7a669..6d83655403e 100644 --- a/apps/files_external/tests/Auth/Password/GlobalAuth.php +++ b/apps/files_external/tests/Auth/Password/GlobalAuthTest.php @@ -1,51 +1,27 @@ <?php + +declare(strict_types=1); /** - * @copyright Copyright (c) 2016, ownCloud, Inc. - * - * @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\Files_External\Tests\Auth\Password; use OCA\Files_External\Lib\Auth\Password\GlobalAuth; -use OCA\Files_external\Lib\StorageConfig; +use OCA\Files_External\Lib\InsufficientDataForMeaningfulAnswerException; +use OCA\Files_External\Lib\StorageConfig; use OCP\IL10N; use OCP\Security\ICredentialsManager; +use PHPUnit\Framework\MockObject\MockObject; use Test\TestCase; class GlobalAuthTest extends TestCase { - /** - * @var \OCP\IL10N|\PHPUnit_Framework_MockObject_MockObject - */ - private $l10n; - - /** - * @var \OCP\Security\ICredentialsManager|\PHPUnit_Framework_MockObject_MockObject - */ - private $credentialsManager; - - /** - * @var GlobalAuth - */ - private $instance; - - protected function setUp() { + private IL10N&MockObject $l10n; + private ICredentialsManager&MockObject $credentialsManager; + private GlobalAuth $instance; + + protected function setUp(): void { parent::setUp(); $this->l10n = $this->createMock(IL10N::class); $this->credentialsManager = $this->createMock(ICredentialsManager::class); @@ -53,34 +29,34 @@ class GlobalAuthTest extends TestCase { } private function getStorageConfig($type, $config = []) { - /** @var \OCA\Files_External\Lib\StorageConfig|\PHPUnit_Framework_MockObject_MockObject $storageConfig */ + /** @var StorageConfig&MockObject $storageConfig */ $storageConfig = $this->createMock(StorageConfig::class); $storageConfig->expects($this->any()) ->method('getType') - ->will($this->returnValue($type)); + ->willReturn($type); $storageConfig->expects($this->any()) ->method('getBackendOptions') - ->will($this->returnCallback(function () use (&$config) { + ->willReturnCallback(function () use (&$config) { return $config; - })); + }); $storageConfig->expects($this->any()) ->method('getBackendOption') - ->will($this->returnCallback(function ($key) use (&$config) { + ->willReturnCallback(function ($key) use (&$config) { return $config[$key]; - })); + }); $storageConfig->expects($this->any()) ->method('setBackendOption') - ->will($this->returnCallback(function ($key, $value) use (&$config) { + ->willReturnCallback(function ($key, $value) use (&$config): void { $config[$key] = $value; - })); + }); return $storageConfig; } - public function testNoCredentials() { + public function testNoCredentials(): void { $this->credentialsManager->expects($this->once()) ->method('retrieve') - ->will($this->returnValue(null)); + ->willReturn(null); $storage = $this->getStorageConfig(StorageConfig::MOUNT_TYPE_ADMIN); @@ -88,13 +64,13 @@ class GlobalAuthTest extends TestCase { $this->assertEquals([], $storage->getBackendOptions()); } - public function testSavedCredentials() { + public function testSavedCredentials(): void { $this->credentialsManager->expects($this->once()) ->method('retrieve') - ->will($this->returnValue([ + ->willReturn([ 'user' => 'a', 'password' => 'b' - ])); + ]); $storage = $this->getStorageConfig(StorageConfig::MOUNT_TYPE_ADMIN); @@ -105,17 +81,16 @@ class GlobalAuthTest extends TestCase { ], $storage->getBackendOptions()); } - /** - * @expectedException \OCA\Files_External\Lib\InsufficientDataForMeaningfulAnswerException - */ - public function testNoCredentialsPersonal() { + + public function testNoCredentialsPersonal(): void { + $this->expectException(InsufficientDataForMeaningfulAnswerException::class); + $this->credentialsManager->expects($this->never()) ->method('retrieve'); - $storage = $this->getStorageConfig(StorageConfig::MOUNT_TYPE_PERSONAl); + $storage = $this->getStorageConfig(StorageConfig::MOUNT_TYPE_PERSONAL); $this->instance->manipulateStorageConfig($storage); $this->assertEquals([], $storage->getBackendOptions()); } - } diff --git a/apps/files_external/tests/Backend/BackendTest.php b/apps/files_external/tests/Backend/BackendTest.php index bc8aa6a0aee..1653c354e16 100644 --- a/apps/files_external/tests/Backend/BackendTest.php +++ b/apps/files_external/tests/Backend/BackendTest.php @@ -1,36 +1,20 @@ <?php + +declare(strict_types=1); /** - * @copyright Copyright (c) 2016, ownCloud, Inc. - * - * @author Morris Jobke <hey@morrisjobke.de> - * @author Robin McCorkell <robin@mccorkell.me.uk> - * - * @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\Files_External\Tests\Backend; -use \OCA\Files_External\Lib\Backend\Backend; +use OCA\Files_External\Lib\Backend\Backend; use OCA\Files_External\Lib\StorageConfig; class BackendTest extends \Test\TestCase { - - public function testJsonSerialization() { + public function testJsonSerialization(): void { $backend = $this->getMockBuilder(Backend::class) - ->setMethods(['jsonSerializeDefinition']) + ->onlyMethods(['jsonSerializeDefinition']) ->getMock(); $backend->expects($this->once()) ->method('jsonSerializeDefinition') @@ -46,23 +30,21 @@ class BackendTest extends \Test\TestCase { $this->assertEquals($json['name'], $json['backend']); $this->assertEquals(57, $json['priority']); - $this->assertContains('foopass', $json['authSchemes']); - $this->assertContains('barauth', $json['authSchemes']); + $this->assertContains('foopass', array_keys($json['authSchemes'])); + $this->assertContains('barauth', array_keys($json['authSchemes'])); } - public function validateStorageProvider() { + public static function validateStorageProvider(): array { return [ [true, true], [false, false], ]; } - /** - * @dataProvider validateStorageProvider - */ - public function testValidateStorage($expectedSuccess, $definitionSuccess) { + #[\PHPUnit\Framework\Attributes\DataProvider('validateStorageProvider')] + public function testValidateStorage(bool $expectedSuccess, bool $definitionSuccess): void { $backend = $this->getMockBuilder(Backend::class) - ->setMethods(['validateStorageDefinition']) + ->onlyMethods(['validateStorageDefinition']) ->getMock(); $backend->expects($this->atMost(1)) ->method('validateStorageDefinition') @@ -75,9 +57,9 @@ class BackendTest extends \Test\TestCase { $this->assertEquals($expectedSuccess, $backend->validateStorage($storageConfig)); } - public function testLegacyAuthMechanismCallback() { + public function testLegacyAuthMechanismCallback(): void { $backend = new Backend(); - $backend->setLegacyAuthMechanismCallback(function(array $params) { + $backend->setLegacyAuthMechanismCallback(function (array $params) { if (isset($params['ping'])) { return 'pong'; } @@ -88,5 +70,4 @@ class BackendTest extends \Test\TestCase { $this->assertEquals('foobar', $backend->getLegacyAuthMechanism(['other' => true])); $this->assertEquals('foobar', $backend->getLegacyAuthMechanism()); } - } diff --git a/apps/files_external/tests/Backend/LegacyBackendTest.php b/apps/files_external/tests/Backend/LegacyBackendTest.php index c1d54d1ca34..c4ddfedf6e2 100644 --- a/apps/files_external/tests/Backend/LegacyBackendTest.php +++ b/apps/files_external/tests/Backend/LegacyBackendTest.php @@ -1,54 +1,37 @@ <?php + /** - * @copyright Copyright (c) 2016, ownCloud, Inc. - * - * @author Robin McCorkell <robin@mccorkell.me.uk> - * - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see <http://www.gnu.org/licenses/> - * + * SPDX-FileCopyrightText: 2019-2024 Nextcloud GmbH and Nextcloud contributors + * SPDX-FileCopyrightText: 2016 ownCloud, Inc. + * SPDX-License-Identifier: AGPL-3.0-only */ - namespace OCA\Files_External\Tests\Backend; -use \OCA\Files_External\Lib\Backend\LegacyBackend; -use \OCA\Files_External\Lib\DefinitionParameter; -use \OCA\Files_External\Lib\MissingDependency; +use OCA\Files_External\Lib\Auth\Builtin; +use OCA\Files_External\Lib\Backend\LegacyBackend; +use OCA\Files_External\Lib\DefinitionParameter; +use OCA\Files_External\Lib\MissingDependency; class LegacyBackendTest extends \Test\TestCase { /** * @return MissingDependency[] */ - public static function checkDependencies() { + public static function checkDependencies(): array { return [ (new MissingDependency('abc'))->setMessage('foobar') ]; } - public function testConstructor() { - $auth = $this->getMockBuilder('\OCA\Files_External\Lib\Auth\Builtin') - ->disableOriginalConstructor() - ->getMock(); + public function testConstructor(): void { + $auth = $this->createMock(Builtin::class); - $class = '\OCA\Files_External\Tests\Backend\LegacyBackendTest'; + $class = self::class; $definition = [ 'configuration' => [ 'textfield' => 'Text field', 'passwordfield' => '*Password field', 'checkbox' => '!Checkbox', - 'hiddenfield' => '#Hidden field', 'optionaltext' => '&Optional text field', 'optionalpassword' => '&*Optional password field', ], @@ -60,7 +43,7 @@ class LegacyBackendTest extends \Test\TestCase { $backend = new LegacyBackend($class, $definition, $auth); - $this->assertEquals('\OCA\Files_External\Tests\Backend\LegacyBackendTest', $backend->getStorageClass()); + $this->assertEquals(self::class, $backend->getStorageClass()); $this->assertEquals('Backend text', $backend->getText()); $this->assertEquals(123, $backend->getPriority()); $this->assertContains('foo/bar.js', $backend->getCustomJs()); @@ -82,9 +65,6 @@ class LegacyBackendTest extends \Test\TestCase { $this->assertEquals('Checkbox', $parameters['checkbox']->getText()); $this->assertEquals(DefinitionParameter::VALUE_BOOLEAN, $parameters['checkbox']->getType()); $this->assertEquals(DefinitionParameter::FLAG_NONE, $parameters['checkbox']->getFlags()); - $this->assertEquals('Hidden field', $parameters['hiddenfield']->getText()); - $this->assertEquals(DefinitionParameter::VALUE_HIDDEN, $parameters['hiddenfield']->getType()); - $this->assertEquals(DefinitionParameter::FLAG_NONE, $parameters['hiddenfield']->getFlags()); $this->assertEquals('Optional text field', $parameters['optionaltext']->getText()); $this->assertEquals(DefinitionParameter::VALUE_TEXT, $parameters['optionaltext']->getType()); $this->assertEquals(DefinitionParameter::FLAG_OPTIONAL, $parameters['optionaltext']->getFlags()); @@ -93,12 +73,10 @@ class LegacyBackendTest extends \Test\TestCase { $this->assertEquals(DefinitionParameter::FLAG_OPTIONAL, $parameters['optionalpassword']->getFlags()); } - public function testNoDependencies() { - $auth = $this->getMockBuilder('\OCA\Files_External\Lib\Auth\Builtin') - ->disableOriginalConstructor() - ->getMock(); + public function testNoDependencies(): void { + $auth = $this->createMock(Builtin::class); - $class = '\OCA\Files_External\Tests\Backend\LegacyBackendTest'; + $class = self::class; $definition = [ 'configuration' => [ ], @@ -110,5 +88,4 @@ class LegacyBackendTest extends \Test\TestCase { $dependencies = $backend->checkDependencies(); $this->assertCount(0, $dependencies); } - } diff --git a/apps/files_external/tests/Command/ApplicableTest.php b/apps/files_external/tests/Command/ApplicableTest.php index 90cfeace361..59db18a42de 100644 --- a/apps/files_external/tests/Command/ApplicableTest.php +++ b/apps/files_external/tests/Command/ApplicableTest.php @@ -1,51 +1,37 @@ <?php + +declare(strict_types=1); /** - * @copyright Copyright (c) 2016, ownCloud, Inc. - * - * @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: 2017-2024 Nextcloud GmbH and Nextcloud contributors + * SPDX-FileCopyrightText: 2016 ownCloud, Inc. + * SPDX-License-Identifier: AGPL-3.0-only */ - namespace OCA\Files_External\Tests\Command; use OCA\Files_External\Command\Applicable; use OCP\IGroupManager; use OCP\IUserManager; +use PHPUnit\Framework\MockObject\MockObject; -class ApplicableTest extends CommandTest { - private function getInstance($storageService) { - /** @var \OCP\IUserManager|\PHPUnit_Framework_MockObject_MockObject $userManager */ +class ApplicableTest extends CommandTestCase { + private function getInstance($storageService): Applicable { + /** @var IUserManager&MockObject $userManager */ $userManager = $this->createMock(IUserManager::class); - /** @var \OCP\IGroupManager|\PHPUnit_Framework_MockObject_MockObject $groupManager */ + /** @var IGroupManager&MockObject $groupManager */ $groupManager = $this->createMock(IGroupManager::class); $userManager->expects($this->any()) ->method('userExists') - ->will($this->returnValue(true)); + ->willReturn(true); $groupManager->expects($this->any()) ->method('groupExists') - ->will($this->returnValue(true)); + ->willReturn(true); return new Applicable($storageService, $userManager, $groupManager); } - public function testListEmpty() { + public function testListEmpty(): void { $mount = $this->getMount(1, '', ''); $storageService = $this->getGlobalStorageService([$mount]); @@ -62,7 +48,7 @@ class ApplicableTest extends CommandTest { $this->assertEquals(['users' => [], 'groups' => []], $result); } - public function testList() { + public function testList(): void { $mount = $this->getMount(1, '', '', '', [], [], ['test', 'asd']); $storageService = $this->getGlobalStorageService([$mount]); @@ -79,7 +65,7 @@ class ApplicableTest extends CommandTest { $this->assertEquals(['users' => ['test', 'asd'], 'groups' => []], $result); } - public function testAddSingle() { + public function testAddSingle(): void { $mount = $this->getMount(1, '', '', '', [], [], []); $storageService = $this->getGlobalStorageService([$mount]); @@ -97,7 +83,7 @@ class ApplicableTest extends CommandTest { $this->assertEquals(['foo'], $mount->getApplicableUsers()); } - public function testAddDuplicate() { + public function testAddDuplicate(): void { $mount = $this->getMount(1, '', '', '', [], [], ['foo']); $storageService = $this->getGlobalStorageService([$mount]); @@ -115,7 +101,7 @@ class ApplicableTest extends CommandTest { $this->assertEquals(['foo', 'bar'], $mount->getApplicableUsers()); } - public function testRemoveSingle() { + public function testRemoveSingle(): void { $mount = $this->getMount(1, '', '', '', [], [], ['foo', 'bar']); $storageService = $this->getGlobalStorageService([$mount]); @@ -133,7 +119,7 @@ class ApplicableTest extends CommandTest { $this->assertEquals(['foo'], $mount->getApplicableUsers()); } - public function testRemoveNonExisting() { + public function testRemoveNonExisting(): void { $mount = $this->getMount(1, '', '', '', [], [], ['foo', 'bar']); $storageService = $this->getGlobalStorageService([$mount]); @@ -151,7 +137,7 @@ class ApplicableTest extends CommandTest { $this->assertEquals(['foo'], $mount->getApplicableUsers()); } - public function testRemoveAddRemove() { + public function testRemoveAddRemove(): void { $mount = $this->getMount(1, '', '', '', [], [], ['foo', 'bar']); $storageService = $this->getGlobalStorageService([$mount]); diff --git a/apps/files_external/tests/Command/CommandTest.php b/apps/files_external/tests/Command/CommandTestCase.php index 568fdd7a52f..e42ad9cd68a 100644 --- a/apps/files_external/tests/Command/CommandTest.php +++ b/apps/files_external/tests/Command/CommandTestCase.php @@ -1,45 +1,29 @@ <?php + /** - * @copyright Copyright (c) 2016, ownCloud, Inc. - * - * @author Joas Schilling <coding@schilljs.com> - * @author Robin Appelman <robin@icewind.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: 2019-2024 Nextcloud GmbH and Nextcloud contributors + * SPDX-FileCopyrightText: 2016 ownCloud, Inc. + * SPDX-License-Identifier: AGPL-3.0-only */ - namespace OCA\Files_External\Tests\Command; use OCA\Files_External\Lib\StorageConfig; use OCA\Files_External\NotFoundException; +use OCA\Files_External\Service\GlobalStoragesService; +use PHPUnit\Framework\MockObject\MockObject; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\ArrayInput; use Symfony\Component\Console\Input\Input; use Symfony\Component\Console\Output\BufferedOutput; use Test\TestCase; -abstract class CommandTest extends TestCase { +abstract class CommandTestCase extends TestCase { /** * @param StorageConfig[] $mounts - * @return \OCA\Files_External\Service\GlobalStoragesService|\PHPUnit_Framework_MockObject_MockObject + * @return GlobalStoragesService&MockObject */ protected function getGlobalStorageService(array $mounts = []) { - $mock = $this->getMockBuilder('OCA\Files_External\Service\GlobalStoragesService') - ->disableOriginalConstructor() - ->getMock(); + $mock = $this->createMock(GlobalStoragesService::class); $this->bindMounts($mock, $mounts); @@ -47,20 +31,20 @@ abstract class CommandTest extends TestCase { } /** - * @param \PHPUnit_Framework_MockObject_MockObject $mock + * @param MockObject $mock * @param StorageConfig[] $mounts */ - protected function bindMounts(\PHPUnit_Framework_MockObject_MockObject $mock, array $mounts) { + protected function bindMounts(MockObject $mock, array $mounts) { $mock->expects($this->any()) ->method('getStorage') - ->will($this->returnCallback(function ($id) use ($mounts) { + ->willReturnCallback(function ($id) use ($mounts) { foreach ($mounts as $mount) { if ($mount->getId() === $id) { return $mount; } } throw new NotFoundException(); - })); + }); } /** @@ -86,7 +70,7 @@ abstract class CommandTest extends TestCase { return $mount; } - protected function getInput(Command $command, array $arguments = [], array $options = []) { + protected function getInput(Command $command, array $arguments = [], array $options = []): ArrayInput { $input = new ArrayInput([]); $input->bind($command->getDefinition()); foreach ($arguments as $key => $value) { @@ -98,7 +82,7 @@ abstract class CommandTest extends TestCase { return $input; } - protected function executeCommand(Command $command, Input $input) { + protected function executeCommand(Command $command, Input $input): string { $output = new BufferedOutput(); $this->invokePrivate($command, 'execute', [$input, $output]); return $output->fetch(); diff --git a/apps/files_external/tests/Command/ListCommandTest.php b/apps/files_external/tests/Command/ListCommandTest.php index 046b4de3282..5b84e500e3f 100644 --- a/apps/files_external/tests/Command/ListCommandTest.php +++ b/apps/files_external/tests/Command/ListCommandTest.php @@ -1,29 +1,11 @@ <?php + +declare(strict_types=1); /** - * @copyright Copyright (c) 2016, ownCloud, Inc. - * - * @author Christoph Wurst <christoph@owncloud.com> - * @author Joas Schilling <coding@schilljs.com> - * @author Lukas Reschke <lukas@statuscode.ch> - * @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\Files_External\Tests\Command; use OCA\Files_External\Command\ListCommand; @@ -36,34 +18,27 @@ use OCA\Files_External\Service\GlobalStoragesService; use OCA\Files_External\Service\UserStoragesService; use OCP\Authentication\LoginCredentials\IStore; use OCP\IL10N; -use OCP\ISession; use OCP\IUserManager; use OCP\IUserSession; -use OCP\Security\ICrypto; -use PHPUnit_Framework_MockObject_MockObject; +use PHPUnit\Framework\MockObject\MockObject; use Symfony\Component\Console\Output\BufferedOutput; -class ListCommandTest extends CommandTest { - /** - * @return ListCommand|PHPUnit_Framework_MockObject_MockObject - */ - private function getInstance() { - /** @var GlobalStoragesService|PHPUnit_Framework_MockObject_MockObject $globalService */ +class ListCommandTest extends CommandTestCase { + private function getInstance(): ListCommand { + /** @var GlobalStoragesService&MockObject $globalService */ $globalService = $this->createMock(GlobalStoragesService::class); - /** @var UserStoragesService|PHPUnit_Framework_MockObject_MockObject $userService */ + /** @var UserStoragesService&MockObject $userService */ $userService = $this->createMock(UserStoragesService::class); - /** @var IUserManager|PHPUnit_Framework_MockObject_MockObject $userManager */ + /** @var IUserManager&MockObject $userManager */ $userManager = $this->createMock(IUserManager::class); - /** @var IUserSession|PHPUnit_Framework_MockObject_MockObject $userSession */ + /** @var IUserSession&MockObject $userSession */ $userSession = $this->createMock(IUserSession::class); return new ListCommand($globalService, $userService, $userSession, $userManager); } - public function testListAuthIdentifier() { + public function testListAuthIdentifier(): void { $l10n = $this->createMock(IL10N::class); - $session = $this->createMock(ISession::class); - $crypto = $this->createMock(ICrypto::class); $instance = $this->getInstance(); $mount1 = new StorageConfig(); $mount1->setAuthMechanism(new Password($l10n)); diff --git a/apps/files_external/tests/Config/UserPlaceholderHandlerTest.php b/apps/files_external/tests/Config/UserPlaceholderHandlerTest.php new file mode 100644 index 00000000000..13d25ce5075 --- /dev/null +++ b/apps/files_external/tests/Config/UserPlaceholderHandlerTest.php @@ -0,0 +1,69 @@ +<?php + +declare(strict_types=1); +/** + * SPDX-FileCopyrightText: 2019 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: AGPL-3.0-or-later + */ +namespace OCA\Files_External\Tests\Config; + +use OCA\Files_External\Config\UserPlaceholderHandler; +use OCP\IRequest; +use OCP\IUser; +use OCP\IUserManager; +use OCP\IUserSession; +use OCP\Share\Exceptions\ShareNotFound; +use OCP\Share\IManager; +use PHPUnit\Framework\MockObject\MockObject; + +class UserPlaceholderHandlerTest extends \Test\TestCase { + protected IUser&MockObject $user; + protected IUserSession&MockObject $session; + protected IManager&MockObject $shareManager; + protected IRequest&MockObject $request; + protected IUserManager&MockObject $userManager; + protected UserPlaceholderHandler $handler; + + protected function setUp(): void { + parent::setUp(); + + $this->user = $this->createMock(IUser::class); + $this->user->expects($this->any()) + ->method('getUid') + ->willReturn('alice'); + $this->session = $this->createMock(IUserSession::class); + $this->shareManager = $this->createMock(IManager::class); + $this->request = $this->createMock(IRequest::class); + $this->userManager = $this->createMock(IUserManager::class); + + $this->handler = new UserPlaceholderHandler($this->session, $this->shareManager, $this->request, $this->userManager); + } + + protected function setUser(): void { + $this->session->expects($this->any()) + ->method('getUser') + ->willReturn($this->user); + } + + public static function optionProvider(): array { + return [ + ['/foo/bar/$user/foobar', '/foo/bar/alice/foobar'], + [['/foo/bar/$user/foobar'], ['/foo/bar/alice/foobar']], + [['/FOO/BAR/$USER/FOOBAR'], ['/FOO/BAR/alice/FOOBAR']], + ]; + } + + #[\PHPUnit\Framework\Attributes\DataProvider('optionProvider')] + public function testHandle(string|array $option, string|array $expected): void { + $this->setUser(); + $this->assertSame($expected, $this->handler->handle($option)); + } + + #[\PHPUnit\Framework\Attributes\DataProvider('optionProvider')] + public function testHandleNoUser(string|array $option): void { + $this->shareManager->expects($this->once()) + ->method('getShareByToken') + ->willThrowException(new ShareNotFound()); + $this->assertSame($option, $this->handler->handle($option)); + } +} diff --git a/apps/files_external/tests/Controller/AjaxControllerTest.php b/apps/files_external/tests/Controller/AjaxControllerTest.php index 1153036c414..b1ea7a2b1b1 100644 --- a/apps/files_external/tests/Controller/AjaxControllerTest.php +++ b/apps/files_external/tests/Controller/AjaxControllerTest.php @@ -1,25 +1,9 @@ <?php + +declare(strict_types=1); /** - * @copyright Copyright (c) 2016 Lukas Reschke <lukas@statuscode.ch> - * - * @author Lukas Reschke <lukas@statuscode.ch> - * @author Roeland Jago Douma <roeland@famdouma.nl> - * - * @license GNU AGPL version 3 or any later version - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see <http://www.gnu.org/licenses/>. - * + * SPDX-FileCopyrightText: 2016 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: AGPL-3.0-or-later */ namespace OCA\Files_External\Tests\Controller; @@ -28,35 +12,29 @@ use OCA\Files_External\Lib\Auth\Password\GlobalAuth; use OCA\Files_External\Lib\Auth\PublicKey\RSA; use OCP\AppFramework\Http\JSONResponse; use OCP\IGroupManager; +use OCP\IL10N; use OCP\IRequest; use OCP\IUser; use OCP\IUserSession; +use PHPUnit\Framework\MockObject\MockObject; use Test\TestCase; class AjaxControllerTest extends TestCase { - /** @var IRequest */ - private $request; - /** @var RSA */ - private $rsa; - /** @var GlobalAuth */ - private $globalAuth; - /** @var IUserSession */ - private $userSession; - /** @var IGroupManager */ - private $groupManager; - /** @var AjaxController */ - private $ajaxController; - - public function setUp() { + private IRequest&MockObject $request; + private RSA&MockObject $rsa; + private GlobalAuth&MockObject $globalAuth; + private IUserSession&MockObject $userSession; + private IGroupManager&MockObject $groupManager; + private IL10N&MockObject $l10n; + private AjaxController $ajaxController; + + protected function setUp(): void { $this->request = $this->createMock(IRequest::class); - $this->rsa = $this->getMockBuilder('\\OCA\\Files_External\\Lib\\Auth\\PublicKey\\RSA') - ->disableOriginalConstructor() - ->getMock(); - $this->globalAuth = $this->getMockBuilder('\\OCA\\Files_External\\Lib\\Auth\\Password\GlobalAuth') - ->disableOriginalConstructor() - ->getMock(); + $this->rsa = $this->createMock(RSA::class); + $this->globalAuth = $this->createMock(GlobalAuth::class); $this->userSession = $this->createMock(IUserSession::class); $this->groupManager = $this->createMock(IGroupManager::class); + $this->l10n = $this->createMock(IL10N::class); $this->ajaxController = new AjaxController( 'files_external', @@ -64,13 +42,23 @@ class AjaxControllerTest extends TestCase { $this->rsa, $this->globalAuth, $this->userSession, - $this->groupManager + $this->groupManager, + $this->l10n, ); + $this->l10n->expects($this->any()) + ->method('t') + ->willReturnCallback(function ($string, $args) { + if (!is_array($args)) { + $args = [$args]; + } + return vsprintf($string, $args); + }); + parent::setUp(); } - public function testGetSshKeys() { + public function testGetSshKeys(): void { $this->rsa ->expects($this->once()) ->method('createKey') @@ -79,7 +67,7 @@ class AjaxControllerTest extends TestCase { 'publickey' => 'MyPublicKey', ]); - $expected = new JSONResponse( + $expected = new JSONResponse( [ 'data' => [ 'private_key' => 'MyPrivateKey', @@ -91,7 +79,7 @@ class AjaxControllerTest extends TestCase { $this->assertEquals($expected, $this->ajaxController->getSshKeys()); } - public function testSaveGlobalCredentialsAsAdminForAnotherUser() { + public function testSaveGlobalCredentialsAsAdminForAnotherUser(): void { $user = $this->createMock(IUser::class); $user ->expects($this->once()) @@ -101,20 +89,16 @@ class AjaxControllerTest extends TestCase { ->expects($this->once()) ->method('getUser') ->willReturn($user); - $this->groupManager - ->expects($this->once()) - ->method('isAdmin') - ->with('MyAdminUid') - ->willReturn(true); $this->globalAuth - ->expects($this->once()) - ->method('saveAuth') - ->with('UidOfTestUser', 'test', 'password'); + ->expects($this->never()) + ->method('saveAuth'); - $this->assertSame(true, $this->ajaxController->saveGlobalCredentials('UidOfTestUser', 'test', 'password')); + $response = $this->ajaxController->saveGlobalCredentials('UidOfTestUser', 'test', 'password'); + $this->assertSame($response->getStatus(), 403); + $this->assertSame('Permission denied', $response->getData()['message']); } - public function testSaveGlobalCredentialsAsAdminForSelf() { + public function testSaveGlobalCredentialsAsAdminForSelf(): void { $user = $this->createMock(IUser::class); $user ->expects($this->once()) @@ -124,58 +108,45 @@ class AjaxControllerTest extends TestCase { ->expects($this->once()) ->method('getUser') ->willReturn($user); - $this->groupManager - ->expects($this->once()) - ->method('isAdmin') - ->with('MyAdminUid') - ->willReturn(true); $this->globalAuth ->expects($this->once()) ->method('saveAuth') ->with('MyAdminUid', 'test', 'password'); - $this->assertSame(true, $this->ajaxController->saveGlobalCredentials('MyAdminUid', 'test', 'password')); + $response = $this->ajaxController->saveGlobalCredentials('MyAdminUid', 'test', 'password'); + $this->assertSame($response->getStatus(), 200); } - public function testSaveGlobalCredentialsAsNormalUserForSelf() { + public function testSaveGlobalCredentialsAsNormalUserForSelf(): void { $user = $this->createMock(IUser::class); $user - ->expects($this->exactly(2)) ->method('getUID') ->willReturn('MyUserUid'); $this->userSession - ->expects($this->once()) ->method('getUser') ->willReturn($user); - $this->groupManager - ->expects($this->once()) - ->method('isAdmin') - ->with('MyUserUid') - ->willReturn(false); $this->globalAuth - ->expects($this->once()) ->method('saveAuth') ->with('MyUserUid', 'test', 'password'); - $this->assertSame(true, $this->ajaxController->saveGlobalCredentials('MyUserUid', 'test', 'password')); + $response = $this->ajaxController->saveGlobalCredentials('MyUserUid', 'test', 'password'); + $this->assertSame($response->getStatus(), 200); } - public function testSaveGlobalCredentialsAsNormalUserForAnotherUser() { + public function testSaveGlobalCredentialsAsNormalUserForAnotherUser(): void { $user = $this->createMock(IUser::class); $user - ->expects($this->exactly(2)) ->method('getUID') ->willReturn('MyUserUid'); $this->userSession - ->expects($this->once()) ->method('getUser') ->willReturn($user); - $this->groupManager - ->expects($this->once()) - ->method('isAdmin') - ->with('MyUserUid') - ->willReturn(false); + $this->globalAuth + ->expects($this->never()) + ->method('saveAuth'); - $this->assertSame(false, $this->ajaxController->saveGlobalCredentials('AnotherUserUid', 'test', 'password')); + $response = $this->ajaxController->saveGlobalCredentials('AnotherUserUid', 'test', 'password'); + $this->assertSame($response->getStatus(), 403); + $this->assertSame('Permission denied', $response->getData()['message']); } } diff --git a/apps/files_external/tests/Controller/GlobalStoragesControllerTest.php b/apps/files_external/tests/Controller/GlobalStoragesControllerTest.php index 2e0245e76fa..74a27eb15e4 100644 --- a/apps/files_external/tests/Controller/GlobalStoragesControllerTest.php +++ b/apps/files_external/tests/Controller/GlobalStoragesControllerTest.php @@ -1,53 +1,60 @@ <?php + /** - * @copyright Copyright (c) 2016, ownCloud, Inc. - * - * @author Joas Schilling <coding@schilljs.com> - * @author Robin Appelman <robin@icewind.nl> - * @author Robin McCorkell <robin@mccorkell.me.uk> - * @author Roeland Jago Douma <roeland@famdouma.nl> - * @author Vincent Petry <pvince81@owncloud.com> - * - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see <http://www.gnu.org/licenses/> - * + * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors + * SPDX-FileCopyrightText: 2016 ownCloud, Inc. + * SPDX-License-Identifier: AGPL-3.0-only */ namespace OCA\Files_External\Tests\Controller; +use OC\User\User; use OCA\Files_External\Controller\GlobalStoragesController; -use \OCP\AppFramework\Http; -use \OCA\Files_External\Service\BackendService; +use OCA\Files_External\Service\BackendService; +use OCA\Files_External\Service\GlobalStoragesService; +use OCP\EventDispatcher\IEventDispatcher; +use OCP\IConfig; +use OCP\IGroupManager; use OCP\IL10N; -use OCP\ILogger; use OCP\IRequest; +use OCP\IUserSession; +use Psr\Log\LoggerInterface; -class GlobalStoragesControllerTest extends StoragesControllerTest { - public function setUp() { +class GlobalStoragesControllerTest extends StoragesControllerTestCase { + protected function setUp(): void { parent::setUp(); - $this->service = $this->getMockBuilder('\OCA\Files_External\Service\GlobalStoragesService') - ->disableOriginalConstructor() - ->getMock(); + + $this->service = $this->createMock(GlobalStoragesService::class); $this->service->method('getVisibilityType') ->willReturn(BackendService::VISIBILITY_ADMIN); - $this->controller = new GlobalStoragesController( + $this->controller = $this->createController(true); + } + + private function createController(bool $allowCreateLocal = true): GlobalStoragesController { + $session = $this->createMock(IUserSession::class); + $session->method('getUser') + ->willReturn(new User('test', null, $this->createMock(IEventDispatcher::class))); + + $config = $this->createMock(IConfig::class); + $config->method('getSystemValue') + ->with('files_external_allow_create_new_local', true) + ->willReturn($allowCreateLocal); + + return new GlobalStoragesController( 'files_external', $this->createMock(IRequest::class), $this->createMock(IL10N::class), $this->service, - $this->createMock(ILogger::class) + $this->createMock(LoggerInterface::class), + $session, + $this->createMock(IGroupManager::class), + $config ); } + + public function testAddLocalStorageWhenDisabled(): void { + $this->controller = $this->createController(false); + parent::testAddLocalStorageWhenDisabled(); + } } diff --git a/apps/files_external/tests/Controller/StoragesControllerTest.php b/apps/files_external/tests/Controller/StoragesControllerTestCase.php index ad0a3401412..1eb52f9b459 100644 --- a/apps/files_external/tests/Controller/StoragesControllerTest.php +++ b/apps/files_external/tests/Controller/StoragesControllerTestCase.php @@ -1,88 +1,71 @@ <?php + +declare(strict_types=1); /** - * @copyright Copyright (c) 2016, ownCloud, Inc. - * - * @author Joas Schilling <coding@schilljs.com> - * @author Morris Jobke <hey@morrisjobke.de> - * @author Robin McCorkell <robin@mccorkell.me.uk> - * @author Vincent Petry <pvince81@owncloud.com> - * - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see <http://www.gnu.org/licenses/> - * + * SPDX-FileCopyrightText: 2017-2024 Nextcloud GmbH and Nextcloud contributors + * SPDX-FileCopyrightText: 2016 ownCloud, Inc. + * SPDX-License-Identifier: AGPL-3.0-only */ namespace OCA\Files_External\Tests\Controller; +use OCA\Files_External\Controller\GlobalStoragesController; +use OCA\Files_External\Controller\UserStoragesController; use OCA\Files_External\Lib\Auth\AuthMechanism; +use OCA\Files_External\Lib\Auth\NullMechanism; use OCA\Files_External\Lib\Backend\Backend; -use \OCP\AppFramework\Http; - -use \OCA\Files_External\Controller\GlobalStoragesController; -use \OCA\Files_External\Service\GlobalStoragesService; +use OCA\Files_External\Lib\Backend\SMB; use OCA\Files_External\Lib\StorageConfig; +use OCA\Files_External\MountConfig; use OCA\Files_External\NotFoundException; - -abstract class StoragesControllerTest extends \Test\TestCase { - - /** - * @var GlobalStoragesController - */ - protected $controller; - - /** - * @var GlobalStoragesService - */ - protected $service; - - public function setUp() { - \OC_Mount_Config::$skipTest = true; +use OCA\Files_External\Service\GlobalStoragesService; +use OCA\Files_External\Service\UserStoragesService; +use OCP\AppFramework\Http; +use PHPUnit\Framework\MockObject\MockObject; + +abstract class StoragesControllerTestCase extends \Test\TestCase { + protected GlobalStoragesController|UserStoragesController $controller; + protected GlobalStoragesService|UserStoragesService|MockObject $service; + + protected function setUp(): void { + parent::setUp(); + MountConfig::$skipTest = true; } - public function tearDown() { - \OC_Mount_Config::$skipTest = false; + protected function tearDown(): void { + MountConfig::$skipTest = false; + parent::tearDown(); } /** - * @return \OCA\Files_External\Lib\Backend\Backend + * @return \OCA\Files_External\Lib\Backend\Backend&MockObject */ - protected function getBackendMock($class = '\OCA\Files_External\Lib\Backend\SMB', $storageClass = '\OCA\Files_External\Lib\Storage\SMB') { - $backend = $this->getMockBuilder(Backend::class) - ->disableOriginalConstructor() - ->getMock(); + protected function getBackendMock($class = SMB::class, $storageClass = \OCA\Files_External\Lib\Storage\SMB::class) { + $backend = $this->createMock(Backend::class); $backend->method('getStorageClass') ->willReturn($storageClass); $backend->method('getIdentifier') - ->willReturn('identifier:'.$class); + ->willReturn('identifier:' . $class); + $backend->method('getParameters') + ->willReturn([]); return $backend; } /** - * @return \OCA\Files_External\Lib\Auth\AuthMechanism + * @return AuthMechanism|MockObject */ - protected function getAuthMechMock($scheme = 'null', $class = '\OCA\Files_External\Lib\Auth\NullMechanism') { - $authMech = $this->getMockBuilder(AuthMechanism::class) - ->disableOriginalConstructor() - ->getMock(); + protected function getAuthMechMock($scheme = 'null', $class = NullMechanism::class) { + $authMech = $this->createMock(AuthMechanism::class); $authMech->method('getScheme') ->willReturn($scheme); $authMech->method('getIdentifier') - ->willReturn('identifier:'.$class); + ->willReturn('identifier:' . $class); + $authMech->method('getParameters') + ->willReturn([]); return $authMech; } - public function testAddStorage() { + public function testAddStorage(): void { $authMech = $this->getAuthMechMock(); $authMech->method('validateStorage') ->willReturn(true); @@ -102,16 +85,16 @@ abstract class StoragesControllerTest extends \Test\TestCase { $this->service->expects($this->once()) ->method('createStorage') - ->will($this->returnValue($storageConfig)); + ->willReturn($storageConfig); $this->service->expects($this->once()) ->method('addStorage') - ->will($this->returnValue($storageConfig)); + ->willReturn($storageConfig); $response = $this->controller->create( 'mount', - '\OCA\Files_External\Lib\Storage\SMB', - '\OCA\Files_External\Lib\Auth\NullMechanism', - array(), + \OCA\Files_External\Lib\Storage\SMB::class, + NullMechanism::class, + [], [], [], [], @@ -120,10 +103,40 @@ abstract class StoragesControllerTest extends \Test\TestCase { $data = $response->getData(); $this->assertEquals(Http::STATUS_CREATED, $response->getStatus()); - $this->assertEquals($storageConfig, $data); + $this->assertEquals($storageConfig->jsonSerialize(), $data); } - public function testUpdateStorage() { + public function testAddLocalStorageWhenDisabled(): void { + $authMech = $this->getAuthMechMock(); + $backend = $this->getBackendMock(); + + $storageConfig = new StorageConfig(1); + $storageConfig->setMountPoint('mount'); + $storageConfig->setBackend($backend); + $storageConfig->setAuthMechanism($authMech); + $storageConfig->setBackendOptions([]); + + $this->service->expects($this->never()) + ->method('createStorage'); + $this->service->expects($this->never()) + ->method('addStorage'); + + $response = $this->controller->create( + 'mount', + 'local', + NullMechanism::class, + [], + [], + [], + [], + null + ); + + $data = $response->getData(); + $this->assertEquals(Http::STATUS_FORBIDDEN, $response->getStatus()); + } + + public function testUpdateStorage(): void { $authMech = $this->getAuthMechMock(); $authMech->method('validateStorage') ->willReturn(true); @@ -143,17 +156,17 @@ abstract class StoragesControllerTest extends \Test\TestCase { $this->service->expects($this->once()) ->method('createStorage') - ->will($this->returnValue($storageConfig)); + ->willReturn($storageConfig); $this->service->expects($this->once()) ->method('updateStorage') - ->will($this->returnValue($storageConfig)); + ->willReturn($storageConfig); $response = $this->controller->update( 1, 'mount', - '\OCA\Files_External\Lib\Storage\SMB', - '\OCA\Files_External\Lib\Auth\NullMechanism', - array(), + \OCA\Files_External\Lib\Storage\SMB::class, + NullMechanism::class, + [], [], [], [], @@ -162,21 +175,19 @@ abstract class StoragesControllerTest extends \Test\TestCase { $data = $response->getData(); $this->assertEquals(Http::STATUS_OK, $response->getStatus()); - $this->assertEquals($storageConfig, $data); + $this->assertEquals($storageConfig->jsonSerialize(), $data); } - function mountPointNamesProvider() { - return array( - array(''), - array('/'), - array('//'), - ); + public static function mountPointNamesProvider(): array { + return [ + [''], + ['/'], + ['//'], + ]; } - /** - * @dataProvider mountPointNamesProvider - */ - public function testAddOrUpdateStorageInvalidMountPoint($mountPoint) { + #[\PHPUnit\Framework\Attributes\DataProvider('mountPointNamesProvider')] + public function testAddOrUpdateStorageInvalidMountPoint($mountPoint): void { $storageConfig = new StorageConfig(1); $storageConfig->setMountPoint($mountPoint); $storageConfig->setBackend($this->getBackendMock()); @@ -185,7 +196,7 @@ abstract class StoragesControllerTest extends \Test\TestCase { $this->service->expects($this->exactly(2)) ->method('createStorage') - ->will($this->returnValue($storageConfig)); + ->willReturn($storageConfig); $this->service->expects($this->never()) ->method('addStorage'); $this->service->expects($this->never()) @@ -193,9 +204,9 @@ abstract class StoragesControllerTest extends \Test\TestCase { $response = $this->controller->create( $mountPoint, - '\OCA\Files_External\Lib\Storage\SMB', - '\OCA\Files_External\Lib\Auth\NullMechanism', - array(), + \OCA\Files_External\Lib\Storage\SMB::class, + NullMechanism::class, + [], [], [], [], @@ -207,9 +218,9 @@ abstract class StoragesControllerTest extends \Test\TestCase { $response = $this->controller->update( 1, $mountPoint, - '\OCA\Files_External\Lib\Storage\SMB', - '\OCA\Files_External\Lib\Auth\NullMechanism', - array(), + \OCA\Files_External\Lib\Storage\SMB::class, + NullMechanism::class, + [], [], [], [], @@ -219,10 +230,10 @@ abstract class StoragesControllerTest extends \Test\TestCase { $this->assertEquals(Http::STATUS_UNPROCESSABLE_ENTITY, $response->getStatus()); } - public function testAddOrUpdateStorageInvalidBackend() { + public function testAddOrUpdateStorageInvalidBackend(): void { $this->service->expects($this->exactly(2)) ->method('createStorage') - ->will($this->throwException(new \InvalidArgumentException())); + ->willThrowException(new \InvalidArgumentException()); $this->service->expects($this->never()) ->method('addStorage'); $this->service->expects($this->never()) @@ -231,8 +242,8 @@ abstract class StoragesControllerTest extends \Test\TestCase { $response = $this->controller->create( 'mount', '\OC\Files\Storage\InvalidStorage', - '\OCA\Files_External\Lib\Auth\NullMechanism', - array(), + NullMechanism::class, + [], [], [], [], @@ -245,8 +256,8 @@ abstract class StoragesControllerTest extends \Test\TestCase { 1, 'mount', '\OC\Files\Storage\InvalidStorage', - '\OCA\Files_External\Lib\Auth\NullMechanism', - array(), + NullMechanism::class, + [], [], [], [], @@ -256,7 +267,7 @@ abstract class StoragesControllerTest extends \Test\TestCase { $this->assertEquals(Http::STATUS_UNPROCESSABLE_ENTITY, $response->getStatus()); } - public function testUpdateStorageNonExisting() { + public function testUpdateStorageNonExisting(): void { $authMech = $this->getAuthMechMock(); $authMech->method('validateStorage') ->willReturn(true); @@ -276,17 +287,17 @@ abstract class StoragesControllerTest extends \Test\TestCase { $this->service->expects($this->once()) ->method('createStorage') - ->will($this->returnValue($storageConfig)); + ->willReturn($storageConfig); $this->service->expects($this->once()) ->method('updateStorage') - ->will($this->throwException(new NotFoundException())); + ->willThrowException(new NotFoundException()); $response = $this->controller->update( 255, 'mount', - '\OCA\Files_External\Lib\Storage\SMB', - '\OCA\Files_External\Lib\Auth\NullMechanism', - array(), + \OCA\Files_External\Lib\Storage\SMB::class, + NullMechanism::class, + [], [], [], [], @@ -296,7 +307,7 @@ abstract class StoragesControllerTest extends \Test\TestCase { $this->assertEquals(Http::STATUS_NOT_FOUND, $response->getStatus()); } - public function testDeleteStorage() { + public function testDeleteStorage(): void { $this->service->expects($this->once()) ->method('removeStorage'); @@ -304,16 +315,16 @@ abstract class StoragesControllerTest extends \Test\TestCase { $this->assertEquals(Http::STATUS_NO_CONTENT, $response->getStatus()); } - public function testDeleteStorageNonExisting() { + public function testDeleteStorageNonExisting(): void { $this->service->expects($this->once()) ->method('removeStorage') - ->will($this->throwException(new NotFoundException())); + ->willThrowException(new NotFoundException()); $response = $this->controller->destroy(255); $this->assertEquals(Http::STATUS_NOT_FOUND, $response->getStatus()); } - public function testGetStorage() { + public function testGetStorage(): void { $backend = $this->getBackendMock(); $authMech = $this->getAuthMechMock(); $storageConfig = new StorageConfig(1); @@ -326,14 +337,16 @@ abstract class StoragesControllerTest extends \Test\TestCase { $this->service->expects($this->once()) ->method('getStorage') ->with(1) - ->will($this->returnValue($storageConfig)); + ->willReturn($storageConfig); $response = $this->controller->show(1); $this->assertEquals(Http::STATUS_OK, $response->getStatus()); - $this->assertEquals($storageConfig, $response->getData()); + $expected = $storageConfig->jsonSerialize(); + $expected['can_edit'] = false; + $this->assertEquals($expected, $response->getData()); } - public function validateStorageProvider() { + public static function validateStorageProvider(): array { return [ [true, true, true], [false, true, false], @@ -342,10 +355,8 @@ abstract class StoragesControllerTest extends \Test\TestCase { ]; } - /** - * @dataProvider validateStorageProvider - */ - public function testValidateStorage($backendValidate, $authMechValidate, $expectSuccess) { + #[\PHPUnit\Framework\Attributes\DataProvider('validateStorageProvider')] + public function testValidateStorage(bool $backendValidate, bool $authMechValidate, bool $expectSuccess): void { $backend = $this->getBackendMock(); $backend->method('validateStorage') ->willReturn($backendValidate); @@ -354,7 +365,7 @@ abstract class StoragesControllerTest extends \Test\TestCase { $authMech = $this->getAuthMechMock(); $authMech->method('validateStorage') - ->will($this->returnValue($authMechValidate)); + ->willReturn($authMechValidate); $authMech->method('isVisibleFor') ->willReturn(true); @@ -366,13 +377,13 @@ abstract class StoragesControllerTest extends \Test\TestCase { $this->service->expects($this->once()) ->method('createStorage') - ->will($this->returnValue($storageConfig)); + ->willReturn($storageConfig); if ($expectSuccess) { $this->service->expects($this->once()) ->method('addStorage') ->with($storageConfig) - ->will($this->returnValue($storageConfig)); + ->willReturn($storageConfig); } else { $this->service->expects($this->never()) ->method('addStorage'); @@ -380,9 +391,9 @@ abstract class StoragesControllerTest extends \Test\TestCase { $response = $this->controller->create( 'mount', - '\OCA\Files_External\Lib\Storage\SMB', - '\OCA\Files_External\Lib\Auth\NullMechanism', - array(), + \OCA\Files_External\Lib\Storage\SMB::class, + NullMechanism::class, + [], [], [], [], @@ -395,5 +406,4 @@ abstract class StoragesControllerTest extends \Test\TestCase { $this->assertEquals(Http::STATUS_UNPROCESSABLE_ENTITY, $response->getStatus()); } } - } diff --git a/apps/files_external/tests/Controller/UserStoragesControllerTest.php b/apps/files_external/tests/Controller/UserStoragesControllerTest.php index 817c5b4e5c3..3e8d89ec060 100644 --- a/apps/files_external/tests/Controller/UserStoragesControllerTest.php +++ b/apps/files_external/tests/Controller/UserStoragesControllerTest.php @@ -1,66 +1,73 @@ <?php + +declare(strict_types=1); /** - * @copyright Copyright (c) 2016, ownCloud, Inc. - * - * @author Joas Schilling <coding@schilljs.com> - * @author Robin Appelman <robin@icewind.nl> - * @author Robin McCorkell <robin@mccorkell.me.uk> - * @author Roeland Jago Douma <roeland@famdouma.nl> - * @author Vincent Petry <pvince81@owncloud.com> - * - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see <http://www.gnu.org/licenses/> - * + * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors + * SPDX-FileCopyrightText: 2016 ownCloud, Inc. + * SPDX-License-Identifier: AGPL-3.0-only */ namespace OCA\Files_External\Tests\Controller; -use \OCA\Files_External\Controller\UserStoragesController; +use OC\User\User; +use OCA\Files_External\Controller\UserStoragesController; +use OCA\Files_External\Lib\Storage\SMB; use OCA\Files_External\Lib\StorageConfig; -use \OCP\AppFramework\Http; -use \OCA\Files_External\Service\BackendService; +use OCA\Files_External\Service\BackendService; +use OCA\Files_External\Service\UserStoragesService; +use OCP\AppFramework\Http; +use OCP\EventDispatcher\IEventDispatcher; +use OCP\IConfig; +use OCP\IGroupManager; use OCP\IL10N; -use OCP\ILogger; use OCP\IRequest; use OCP\IUserSession; +use Psr\Log\LoggerInterface; -class UserStoragesControllerTest extends StoragesControllerTest { +class UserStoragesControllerTest extends StoragesControllerTestCase { /** * @var array */ - private $oldAllowedBackends; + private array $oldAllowedBackends; - public function setUp() { + protected function setUp(): void { parent::setUp(); - $this->service = $this->getMockBuilder('\OCA\Files_External\Service\UserStoragesService') - ->disableOriginalConstructor() - ->getMock(); + $this->service = $this->createMock(UserStoragesService::class); $this->service->method('getVisibilityType') ->willReturn(BackendService::VISIBILITY_PERSONAL); - $this->controller = new UserStoragesController( + $this->controller = $this->createController(true); + } + + private function createController(bool $allowCreateLocal = true) { + $session = $this->createMock(IUserSession::class); + $session->method('getUser') + ->willReturn(new User('test', null, $this->createMock(IEventDispatcher::class))); + + $config = $this->createMock(IConfig::class); + $config->method('getSystemValue') + ->with('files_external_allow_create_new_local', true) + ->willReturn($allowCreateLocal); + + return new UserStoragesController( 'files_external', $this->createMock(IRequest::class), $this->createMock(IL10N::class), $this->service, - $this->createMock(IUserSession::class), - $this->createMock(ILogger::class) + $this->createMock(LoggerInterface::class), + $session, + $this->createMock(IGroupManager::class), + $config ); } - public function testAddOrUpdateStorageDisallowedBackend() { + public function testAddLocalStorageWhenDisabled(): void { + $this->controller = $this->createController(false); + parent::testAddLocalStorageWhenDisabled(); + } + + public function testAddOrUpdateStorageDisallowedBackend(): void { $backend = $this->getBackendMock(); $backend->method('isVisibleFor') ->with(BackendService::VISIBILITY_PERSONAL) @@ -75,7 +82,7 @@ class UserStoragesControllerTest extends StoragesControllerTest { $this->service->expects($this->exactly(2)) ->method('createStorage') - ->will($this->returnValue($storageConfig)); + ->willReturn($storageConfig); $this->service->expects($this->never()) ->method('addStorage'); $this->service->expects($this->never()) @@ -83,9 +90,9 @@ class UserStoragesControllerTest extends StoragesControllerTest { $response = $this->controller->create( 'mount', - '\OCA\Files_External\Lib\Storage\SMB', + SMB::class, '\Auth\Mechanism', - array(), + [], [], [], [], @@ -97,9 +104,9 @@ class UserStoragesControllerTest extends StoragesControllerTest { $response = $this->controller->update( 1, 'mount', - '\OCA\Files_External\Lib\Storage\SMB', + SMB::class, '\Auth\Mechanism', - array(), + [], [], [], [], @@ -108,5 +115,4 @@ class UserStoragesControllerTest extends StoragesControllerTest { $this->assertEquals(Http::STATUS_UNPROCESSABLE_ENTITY, $response->getStatus()); } - } diff --git a/apps/files_external/tests/DefinitionParameterTest.php b/apps/files_external/tests/DefinitionParameterTest.php index d60d9677dbe..c535481bf66 100644 --- a/apps/files_external/tests/DefinitionParameterTest.php +++ b/apps/files_external/tests/DefinitionParameterTest.php @@ -1,69 +1,61 @@ <?php + +declare(strict_types=1); /** - * @copyright Copyright (c) 2016, ownCloud, Inc. - * - * @author Robin Appelman <robin@icewind.nl> - * @author Robin McCorkell <robin@mccorkell.me.uk> - * - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see <http://www.gnu.org/licenses/> - * + * SPDX-FileCopyrightText: 2019-2024 Nextcloud GmbH and Nextcloud contributors + * SPDX-FileCopyrightText: 2016 ownCloud, Inc. + * SPDX-License-Identifier: AGPL-3.0-only */ - namespace OCA\Files_External\Tests; -use \OCA\Files_External\Lib\DefinitionParameter as Param; +use OCA\Files_External\Lib\DefinitionParameter as Param; class DefinitionParameterTest extends \Test\TestCase { - - public function testJsonSerialization() { + public function testJsonSerialization(): void { $param = new Param('foo', 'bar'); $this->assertEquals([ 'value' => 'bar', 'flags' => 0, - 'type' => 0 + 'type' => 0, + 'tooltip' => '', ], $param->jsonSerialize()); $param->setType(Param::VALUE_BOOLEAN); + $param->setDefaultValue(true); $this->assertEquals([ 'value' => 'bar', 'flags' => 0, - 'type' => Param::VALUE_BOOLEAN + 'type' => Param::VALUE_BOOLEAN, + 'tooltip' => '', + 'defaultValue' => true, ], $param->jsonSerialize()); $param->setType(Param::VALUE_PASSWORD); $param->setFlag(Param::FLAG_OPTIONAL); + $param->setDefaultValue(null); $this->assertEquals([ 'value' => 'bar', 'flags' => Param::FLAG_OPTIONAL, - 'type' => Param::VALUE_PASSWORD + 'type' => Param::VALUE_PASSWORD, + 'tooltip' => '', ], $param->jsonSerialize()); - $param->setType(Param::VALUE_HIDDEN); - $param->setFlags(Param::FLAG_NONE); + $param->setType(Param::VALUE_TEXT); + $param->setFlags(Param::FLAG_HIDDEN); $this->assertEquals([ 'value' => 'bar', - 'flags' => Param::FLAG_NONE, - 'type' => Param::VALUE_HIDDEN + 'flags' => Param::FLAG_HIDDEN, + 'type' => Param::VALUE_TEXT, + 'tooltip' => '', ], $param->jsonSerialize()); } - public function validateValueProvider() { + public static function validateValueProvider(): array { return [ [Param::VALUE_TEXT, Param::FLAG_NONE, 'abc', true], [Param::VALUE_TEXT, Param::FLAG_NONE, '', false], [Param::VALUE_TEXT, Param::FLAG_OPTIONAL, '', true], + [Param::VALUE_TEXT, Param::FLAG_HIDDEN, '', false], [Param::VALUE_BOOLEAN, Param::FLAG_NONE, false, true], [Param::VALUE_BOOLEAN, Param::FLAG_NONE, 123, false], @@ -73,15 +65,11 @@ class DefinitionParameterTest extends \Test\TestCase { [Param::VALUE_PASSWORD, Param::FLAG_NONE, 'foobar', true], [Param::VALUE_PASSWORD, Param::FLAG_NONE, '', false], - - [Param::VALUE_HIDDEN, Param::FLAG_NONE, '', false] ]; } - /** - * @dataProvider validateValueProvider - */ - public function testValidateValue($type, $flags, $value, $success, $expectedValue = null) { + #[\PHPUnit\Framework\Attributes\DataProvider('validateValueProvider')] + public function testValidateValue($type, $flags, $value, $success, $expectedValue = null): void { $param = new Param('foo', 'bar'); $param->setType($type); $param->setFlags($flags); diff --git a/apps/files_external/tests/FrontendDefinitionTraitTest.php b/apps/files_external/tests/FrontendDefinitionTraitTest.php index cdb1cb2b879..e0bf066e70a 100644 --- a/apps/files_external/tests/FrontendDefinitionTraitTest.php +++ b/apps/files_external/tests/FrontendDefinitionTraitTest.php @@ -1,41 +1,24 @@ <?php + /** - * @copyright Copyright (c) 2016, ownCloud, Inc. - * - * @author Morris Jobke <hey@morrisjobke.de> - * @author Robin Appelman <robin@icewind.nl> - * @author Robin McCorkell <robin@mccorkell.me.uk> - * - * @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\Files_External\Tests; use OCA\Files_External\Lib\DefinitionParameter; +use OCA\Files_External\Lib\FrontendDefinitionTrait; use OCA\Files_External\Lib\StorageConfig; class FrontendDefinitionTraitTest extends \Test\TestCase { - - public function testJsonSerialization() { + public function testJsonSerialization(): void { $param = $this->getMockBuilder(DefinitionParameter::class) ->disableOriginalConstructor() ->getMock(); $param->method('getName')->willReturn('foo'); - $trait = $this->getMockForTrait('\OCA\Files_External\Lib\FrontendDefinitionTrait'); + $trait = $this->getMockForTrait(FrontendDefinitionTrait::class); $trait->setText('test'); $trait->addParameters([$param]); $trait->addCustomJs('foo/bar.js'); @@ -51,17 +34,15 @@ class FrontendDefinitionTraitTest extends \Test\TestCase { $this->assertArrayHasKey('foo', $configuration); } - public function validateStorageProvider() { + public static function validateStorageProvider(): array { return [ [true, ['foo' => true, 'bar' => true, 'baz' => true]], [false, ['foo' => true, 'bar' => false]] ]; } - /** - * @dataProvider validateStorageProvider - */ - public function testValidateStorage($expectedSuccess, $params) { + #[\PHPUnit\Framework\Attributes\DataProvider('validateStorageProvider')] + public function testValidateStorage(bool $expectedSuccess, array $params): void { $backendParams = []; foreach ($params as $name => $valid) { $param = $this->getMockBuilder(DefinitionParameter::class) @@ -86,14 +67,14 @@ class FrontendDefinitionTraitTest extends \Test\TestCase { $storageConfig->expects($this->any()) ->method('setBackendOption'); - $trait = $this->getMockForTrait('\OCA\Files_External\Lib\FrontendDefinitionTrait'); + $trait = $this->getMockForTrait(FrontendDefinitionTrait::class); $trait->setText('test'); $trait->addParameters($backendParams); $this->assertEquals($expectedSuccess, $trait->validateStorageDefinition($storageConfig)); } - public function testValidateStorageSet() { + public function testValidateStorageSet(): void { $param = $this->getMockBuilder(DefinitionParameter::class) ->disableOriginalConstructor() ->getMock(); @@ -101,10 +82,10 @@ class FrontendDefinitionTraitTest extends \Test\TestCase { ->willReturn('param'); $param->expects($this->once()) ->method('validateValue') - ->will($this->returnCallback(function(&$value) { + ->willReturnCallback(function (&$value) { $value = 'foobar'; return true; - })); + }); $storageConfig = $this->getMockBuilder(StorageConfig::class) ->disableOriginalConstructor() @@ -117,7 +98,7 @@ class FrontendDefinitionTraitTest extends \Test\TestCase { ->method('setBackendOption') ->with('param', 'foobar'); - $trait = $this->getMockForTrait('\OCA\Files_External\Lib\FrontendDefinitionTrait'); + $trait = $this->getMockForTrait(FrontendDefinitionTrait::class); $trait->setText('test'); $trait->addParameter($param); diff --git a/apps/files_external/tests/LegacyDependencyCheckPolyfillTest.php b/apps/files_external/tests/LegacyDependencyCheckPolyfillTest.php index 89c9fc76fae..d26aa752ea1 100644 --- a/apps/files_external/tests/LegacyDependencyCheckPolyfillTest.php +++ b/apps/files_external/tests/LegacyDependencyCheckPolyfillTest.php @@ -1,46 +1,33 @@ <?php + +declare(strict_types=1); /** - * @copyright Copyright (c) 2016, ownCloud, Inc. - * - * @author Robin McCorkell <robin@mccorkell.me.uk> - * - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see <http://www.gnu.org/licenses/> - * + * SPDX-FileCopyrightText: 2019-2024 Nextcloud GmbH and Nextcloud contributors + * SPDX-FileCopyrightText: 2016 ownCloud, Inc. + * SPDX-License-Identifier: AGPL-3.0-only */ - namespace OCA\Files_External\Tests; -use \OCA\Files_External\Lib\MissingDependency; +use OCA\Files_External\Lib\LegacyDependencyCheckPolyfill; +use OCA\Files_External\Lib\MissingDependency; class LegacyDependencyCheckPolyfillTest extends \Test\TestCase { /** * @return MissingDependency[] */ - public static function checkDependencies() { + public static function checkDependencies(): array { return [ (new MissingDependency('dependency'))->setMessage('missing dependency'), (new MissingDependency('program'))->setMessage('cannot find program'), ]; } - public function testCheckDependencies() { - $trait = $this->getMockForTrait('\OCA\Files_External\Lib\LegacyDependencyCheckPolyfill'); + public function testCheckDependencies(): void { + $trait = $this->getMockForTrait(LegacyDependencyCheckPolyfill::class); $trait->expects($this->once()) ->method('getStorageClass') - ->willReturn('\OCA\Files_External\Tests\LegacyDependencyCheckPolyfillTest'); + ->willReturn(self::class); $dependencies = $trait->checkDependencies(); $this->assertCount(2, $dependencies); @@ -49,5 +36,4 @@ class LegacyDependencyCheckPolyfillTest extends \Test\TestCase { $this->assertEquals('program', $dependencies[1]->getDependency()); $this->assertEquals('cannot find program', $dependencies[1]->getMessage()); } - } diff --git a/apps/files_external/tests/Listener/StorePasswordListenerTest.php b/apps/files_external/tests/Listener/StorePasswordListenerTest.php new file mode 100644 index 00000000000..04635b7dafd --- /dev/null +++ b/apps/files_external/tests/Listener/StorePasswordListenerTest.php @@ -0,0 +1,155 @@ +<?php + +declare(strict_types=1); + +/** + * SPDX-FileCopyrightText: 2023 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: AGPL-3.0-or-later + */ + +namespace OCA\Files_External\Tests\Listener; + +use OCA\Files_External\Lib\Auth\Password\LoginCredentials; +use OCA\Files_External\Listener\StorePasswordListener; +use OCP\IUser; +use OCP\Security\ICredentialsManager; +use OCP\User\Events\PasswordUpdatedEvent; +use OCP\User\Events\UserLoggedInEvent; +use PHPUnit\Framework\MockObject\MockObject; +use Test\TestCase; + +/** + * @group DB + */ +class StorePasswordListenerTest extends TestCase { + protected IUser&MockObject $mockedUser; + + protected function setUp(): void { + parent::setUp(); + $this->mockedUser = $this->createMock(IUser::class); + $this->mockedUser->method('getUID') + ->willReturn('test'); + } + + /** + * @param array|false|null $initialCredentials + * @param UserLoggedInEvent|PasswordUpdatedEvent $event + * @param array|null $expectedCredentials + */ + public function getMockedCredentialManager($initialCredentials, $event, $expectedCredentials) { + $mockedCredentialsManager = $this->createMock(ICredentialsManager::class); + + if ($initialCredentials !== null) { + $mockedCredentialsManager + ->expects($this->once()) + ->method('retrieve') + ->with( + $this->equalTo('test'), + $this->equalTo(LoginCredentials::CREDENTIALS_IDENTIFIER), + ) + ->willReturn($initialCredentials); + } else { + $mockedCredentialsManager + ->expects($this->never()) + ->method('retrieve'); + } + + if ($expectedCredentials !== null) { + $mockedCredentialsManager + ->expects($this->once()) + ->method('store') + ->with( + $this->equalTo('test'), + $this->equalTo(LoginCredentials::CREDENTIALS_IDENTIFIER), + $this->equalTo($expectedCredentials), + ); + } else { + $mockedCredentialsManager + ->expects($this->never()) + ->method('store'); + } + + $storePasswordListener = new StorePasswordListener($mockedCredentialsManager); + $storePasswordListener->handle($event); + } + + public function testClassicLoginSameCredentials(): void { + $this->getMockedCredentialManager( + [ + 'user' => 'test', + 'password' => 'password', + ], + new UserLoggedInEvent($this->mockedUser, 'test', 'password', false), + null, + ); + } + + public function testClassicLoginNewPassword(): void { + $this->getMockedCredentialManager( + [ + 'user' => 'test', + 'password' => 'password', + ], + new UserLoggedInEvent($this->mockedUser, 'test', 'password2', false), + [ + 'user' => 'test', + 'password' => 'password2', + ], + ); + } + + public function testClassicLoginNewUser(): void { + $this->getMockedCredentialManager( + [ + 'user' => 'test', + 'password' => 'password', + ], + new UserLoggedInEvent($this->mockedUser, 'test2', 'password', false), + [ + 'user' => 'test2', + 'password' => 'password', + ], + ); + } + + public function testSSOLogin(): void { + $this->getMockedCredentialManager( + [ + 'user' => 'test', + 'password' => 'password', + ], + new UserLoggedInEvent($this->mockedUser, 'test', null, false), + null, + ); + } + + public function testPasswordUpdated(): void { + $this->getMockedCredentialManager( + [ + 'user' => 'test', + 'password' => 'password', + ], + new PasswordUpdatedEvent($this->mockedUser, 'password2'), + [ + 'user' => 'test', + 'password' => 'password2', + ], + ); + } + + public function testUserLoginWithToken(): void { + $this->getMockedCredentialManager( + null, + new UserLoggedInEvent($this->mockedUser, 'test', 'password', true), + null, + ); + } + + public function testNoInitialCredentials(): void { + $this->getMockedCredentialManager( + false, + new PasswordUpdatedEvent($this->mockedUser, 'test', 'password'), + null, + ); + } +} diff --git a/apps/files_external/tests/OwnCloudFunctionsTest.php b/apps/files_external/tests/OwnCloudFunctionsTest.php index 95222f66972..2e052cb86b0 100644 --- a/apps/files_external/tests/OwnCloudFunctionsTest.php +++ b/apps/files_external/tests/OwnCloudFunctionsTest.php @@ -1,31 +1,15 @@ <?php + +declare(strict_types=1); /** - * @copyright Copyright (c) 2016, ownCloud, Inc. - * - * @author Joas Schilling <coding@schilljs.com> - * @author Morris Jobke <hey@morrisjobke.de> - * @author Robin McCorkell <robin@mccorkell.me.uk> - * @author Thomas Müller <thomas.mueller@tmit.eu> - * @author Vincent Petry <pvince81@owncloud.com> - * - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see <http://www.gnu.org/licenses/> - * + * SPDX-FileCopyrightText: 2019-2024 Nextcloud GmbH and Nextcloud contributors + * SPDX-FileCopyrightText: 2016 ownCloud, Inc. + * SPDX-License-Identifier: AGPL-3.0-only */ - namespace OCA\Files_External\Tests; +use OCA\Files_External\Lib\Storage\OwnCloud; + /** * Class OwnCloudFunctions * @@ -34,83 +18,80 @@ namespace OCA\Files_External\Tests; * @package OCA\Files_External\Tests */ class OwnCloudFunctionsTest extends \Test\TestCase { - - function configUrlProvider() { - return array( - array( - array( + public static function configUrlProvider(): array { + return [ + [ + [ 'host' => 'testhost', 'root' => 'testroot', 'secure' => false - ), + ], 'http://testhost/remote.php/webdav/testroot/', - ), - array( - array( + ], + [ + [ 'host' => 'testhost', 'root' => 'testroot', 'secure' => true - ), + ], 'https://testhost/remote.php/webdav/testroot/', - ), - array( - array( + ], + [ + [ 'host' => 'http://testhost', 'root' => 'testroot', 'secure' => false - ), + ], 'http://testhost/remote.php/webdav/testroot/', - ), - array( - array( + ], + [ + [ 'host' => 'https://testhost', 'root' => 'testroot', 'secure' => false - ), + ], 'https://testhost/remote.php/webdav/testroot/', - ), - array( - array( + ], + [ + [ 'host' => 'https://testhost/testroot', 'root' => '', 'secure' => false - ), + ], 'https://testhost/testroot/remote.php/webdav/', - ), - array( - array( + ], + [ + [ 'host' => 'https://testhost/testroot', 'root' => 'subdir', 'secure' => false - ), + ], 'https://testhost/testroot/remote.php/webdav/subdir/', - ), - array( - array( + ], + [ + [ 'host' => 'http://testhost/testroot', 'root' => 'subdir', 'secure' => true - ), + ], 'http://testhost/testroot/remote.php/webdav/subdir/', - ), - array( - array( + ], + [ + [ 'host' => 'http://testhost/testroot/', 'root' => '/subdir', 'secure' => false - ), + ], 'http://testhost/testroot/remote.php/webdav/subdir/', - ), - ); + ], + ]; } - /** - * @dataProvider configUrlProvider - */ - public function testConfig($config, $expectedUri) { + #[\PHPUnit\Framework\Attributes\DataProvider('configUrlProvider')] + public function testConfig(array $config, string $expectedUri): void { $config['user'] = 'someuser'; $config['password'] = 'somepassword'; - $instance = new \OCA\Files_External\Lib\Storage\OwnCloud($config); + $instance = new OwnCloud($config); $this->assertEquals($expectedUri, $instance->createBaseUri()); } } diff --git a/apps/files_external/tests/PersonalMountTest.php b/apps/files_external/tests/PersonalMountTest.php index 28c3bab7455..618048c3335 100644 --- a/apps/files_external/tests/PersonalMountTest.php +++ b/apps/files_external/tests/PersonalMountTest.php @@ -1,50 +1,36 @@ <?php + +declare(strict_types=1); /** - * @copyright Copyright (c) 2016, ownCloud, Inc. - * - * @author Joas Schilling <coding@schilljs.com> - * @author Robin Appelman <robin@icewind.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: 2019-2024 Nextcloud GmbH and Nextcloud contributors + * SPDX-FileCopyrightText: 2016 ownCloud, Inc. + * SPDX-License-Identifier: AGPL-3.0-only */ - namespace OCA\Files_External\Tests; use OC\Files\Mount\Manager; +use OC\Files\SetupManagerFactory; +use OC\Files\Storage\Storage; use OCA\Files_External\Lib\PersonalMount; +use OCA\Files_External\Lib\StorageConfig; +use OCA\Files_External\Service\UserStoragesService; use Test\TestCase; class PersonalMountTest extends TestCase { - public function testFindByStorageId() { - /** @var \OCA\Files_External\Service\UserStoragesService $storageService */ - $storageService = $this->getMockBuilder('\OCA\Files_External\Service\UserStoragesService') - ->disableOriginalConstructor() - ->getMock(); + public function testFindByStorageId(): void { + $storageConfig = $this->createMock(StorageConfig::class); + /** @var UserStoragesService $storageService */ + $storageService = $this->createMock(UserStoragesService::class); - $storage = $this->getMockBuilder('\OC\Files\Storage\Storage') - ->disableOriginalConstructor() - ->getMock(); + $storage = $this->createMock(Storage::class); $storage->expects($this->any()) ->method('getId') - ->will($this->returnValue('dummy')); + ->willReturn('dummy'); - $mount = new PersonalMount($storageService, 10, $storage, '/foo'); + $mount = new PersonalMount($storageService, $storageConfig, 10, $storage, '/foo'); - $mountManager = new Manager(); + $mountManager = new Manager($this->createMock(SetupManagerFactory::class)); $mountManager->addMount($mount); $this->assertEquals([$mount], $mountManager->findByStorageId('dummy')); diff --git a/apps/files_external/tests/README.md b/apps/files_external/tests/README.md index 202ae8eee9a..4af03516860 100644 --- a/apps/files_external/tests/README.md +++ b/apps/files_external/tests/README.md @@ -1,3 +1,8 @@ +<!-- + - SPDX-FileCopyrightText: 2017 Nextcloud GmbH and Nextcloud contributors + - SPDX-FileCopyrightText: 2015 ownCloud, Inc. + - SPDX-License-Identifier: AGPL-3.0-only +--> # How to run the files external unit tests ## Components diff --git a/apps/files_external/tests/Service/BackendServiceTest.php b/apps/files_external/tests/Service/BackendServiceTest.php index e8a3181658c..ef545688040 100644 --- a/apps/files_external/tests/Service/BackendServiceTest.php +++ b/apps/files_external/tests/Service/BackendServiceTest.php @@ -1,85 +1,57 @@ <?php + /** - * @copyright Copyright (c) 2016, ownCloud, Inc. - * - * @author Morris Jobke <hey@morrisjobke.de> - * @author Robin McCorkell <robin@mccorkell.me.uk> - * @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\Files_External\Tests\Service; +use OCA\Files_External\Config\IConfigHandler; use OCA\Files_External\Lib\Auth\AuthMechanism; use OCA\Files_External\Lib\Backend\Backend; use OCA\Files_External\Lib\Config\IAuthMechanismProvider; use OCA\Files_External\Lib\Config\IBackendProvider; -use \OCA\Files_External\Service\BackendService; -use OCP\IConfig; -use OCP\IL10N; +use OCA\Files_External\Service\BackendService; +use OCP\IAppConfig; +use PHPUnit\Framework\MockObject\MockObject; class BackendServiceTest extends \Test\TestCase { + protected IAppConfig&MockObject $appConfig; - /** @var \OCP\IConfig */ - protected $config; - - /** @var \OCP\IL10N */ - protected $l10n; - - protected function setUp() { - $this->config = $this->createMock(IConfig::class); - $this->l10n = $this->createMock(IL10N::class); + protected function setUp(): void { + $this->appConfig = $this->createMock(IAppConfig::class); } /** - * @param string $class - * - * @return \OCA\Files_External\Lib\Backend\Backend + * @return \OCA\Files_External\Lib\Backend\Backend&MockObject */ - protected function getBackendMock($class) { - $backend = $this->getMockBuilder(Backend::class) - ->disableOriginalConstructor() - ->getMock(); - $backend->method('getIdentifier')->will($this->returnValue('identifier:'.$class)); - $backend->method('getIdentifierAliases')->will($this->returnValue(['identifier:'.$class])); + protected function getBackendMock(string $class) { + $backend = $this->createMock(Backend::class); + $backend->method('getIdentifier')->willReturn('identifier:' . $class); + $backend->method('getIdentifierAliases')->willReturn(['identifier:' . $class]); return $backend; } /** * @param string $class * - * @return \OCA\Files_External\Lib\Auth\AuthMechanism + * @return AuthMechanism&MockObject */ protected function getAuthMechanismMock($class) { - $backend = $this->getMockBuilder(AuthMechanism::class) - ->disableOriginalConstructor() - ->getMock(); - $backend->method('getIdentifier')->will($this->returnValue('identifier:'.$class)); - $backend->method('getIdentifierAliases')->will($this->returnValue(['identifier:'.$class])); + $backend = $this->createMock(AuthMechanism::class); + $backend->method('getIdentifier')->willReturn('identifier:' . $class); + $backend->method('getIdentifierAliases')->willReturn(['identifier:' . $class]); return $backend; } - public function testRegisterBackend() { - $service = new BackendService($this->config, $this->l10n); + public function testRegisterBackend(): void { + $service = new BackendService($this->appConfig); $backend = $this->getBackendMock('\Foo\Bar'); - $backendAlias = $this->getMockBuilder(Backend::class) - ->disableOriginalConstructor() - ->getMock(); + /** @var \OCA\Files_External\Lib\Backend\Backend&MockObject $backendAlias */ + $backendAlias = $this->createMock(Backend::class); $backendAlias->method('getIdentifierAliases') ->willReturn(['identifier_real', 'identifier_alias']); $backendAlias->method('getIdentifier') @@ -99,12 +71,13 @@ class BackendServiceTest extends \Test\TestCase { $this->assertArrayNotHasKey('identifier_alias', $backends); } - public function testBackendProvider() { - $service = new BackendService($this->config, $this->l10n); + public function testBackendProvider(): void { + $service = new BackendService($this->appConfig); $backend1 = $this->getBackendMock('\Foo\Bar'); $backend2 = $this->getBackendMock('\Bar\Foo'); + /** @var IBackendProvider&MockObject $providerMock */ $providerMock = $this->createMock(IBackendProvider::class); $providerMock->expects($this->once()) ->method('getBackends') @@ -117,12 +90,13 @@ class BackendServiceTest extends \Test\TestCase { $this->assertCount(2, $service->getBackends()); } - public function testAuthMechanismProvider() { - $service = new BackendService($this->config, $this->l10n); + public function testAuthMechanismProvider(): void { + $service = new BackendService($this->appConfig); $backend1 = $this->getAuthMechanismMock('\Foo\Bar'); $backend2 = $this->getAuthMechanismMock('\Bar\Foo'); + /** @var IAuthMechanismProvider&MockObject $providerMock */ $providerMock = $this->createMock(IAuthMechanismProvider::class); $providerMock->expects($this->once()) ->method('getAuthMechanisms') @@ -135,19 +109,21 @@ class BackendServiceTest extends \Test\TestCase { $this->assertCount(2, $service->getAuthMechanisms()); } - public function testMultipleBackendProviders() { - $service = new BackendService($this->config, $this->l10n); + public function testMultipleBackendProviders(): void { + $service = new BackendService($this->appConfig); $backend1a = $this->getBackendMock('\Foo\Bar'); $backend1b = $this->getBackendMock('\Bar\Foo'); $backend2 = $this->getBackendMock('\Dead\Beef'); + /** @var IBackendProvider&MockObject $provider1Mock */ $provider1Mock = $this->createMock(IBackendProvider::class); $provider1Mock->expects($this->once()) ->method('getBackends') ->willReturn([$backend1a, $backend1b]); $service->registerBackendProvider($provider1Mock); + /** @var IBackendProvider&MockObject $provider2Mock */ $provider2Mock = $this->createMock(IBackendProvider::class); $provider2Mock->expects($this->once()) ->method('getBackends') @@ -161,15 +137,17 @@ class BackendServiceTest extends \Test\TestCase { $this->assertCount(3, $service->getBackends()); } - public function testUserMountingBackends() { - $this->config->expects($this->exactly(2)) - ->method('getAppValue') - ->will($this->returnValueMap([ - ['files_external', 'allow_user_mounting', 'yes', 'yes'], - ['files_external', 'user_mounting_backends', '', 'identifier:\User\Mount\Allowed,identifier_alias'] - ])); + public function testUserMountingBackends(): void { + $this->appConfig->expects($this->once()) + ->method('getValueString') + ->with('files_external', 'user_mounting_backends') + ->willReturn('identifier:\User\Mount\Allowed,identifier_alias'); + $this->appConfig->expects($this->once()) + ->method('getValueBool') + ->with('files_external', 'allow_user_mounting') + ->willReturn(true); - $service = new BackendService($this->config, $this->l10n); + $service = new BackendService($this->appConfig); $backendAllowed = $this->getBackendMock('\User\Mount\Allowed'); $backendAllowed->expects($this->never()) @@ -192,21 +170,21 @@ class BackendServiceTest extends \Test\TestCase { $service->registerBackend($backendAlias); } - public function testGetAvailableBackends() { - $service = new BackendService($this->config, $this->l10n); + public function testGetAvailableBackends(): void { + $service = new BackendService($this->appConfig); $backendAvailable = $this->getBackendMock('\Backend\Available'); $backendAvailable->expects($this->once()) ->method('checkDependencies') - ->will($this->returnValue([])); + ->willReturn([]); $backendNotAvailable = $this->getBackendMock('\Backend\NotAvailable'); $backendNotAvailable->expects($this->once()) ->method('checkDependencies') - ->will($this->returnValue([ + ->willReturn([ $this->getMockBuilder('\OCA\Files_External\Lib\MissingDependency') ->disableOriginalConstructor() ->getMock() - ])); + ]); $service->registerBackend($backendAvailable); $service->registerBackend($backendNotAvailable); @@ -216,5 +194,51 @@ class BackendServiceTest extends \Test\TestCase { $this->assertArrayNotHasKey('identifier:\Backend\NotAvailable', $availableBackends); } -} + public static function invalidConfigPlaceholderProvider(): array { + return [ + [['@user']], + [['$user']], + [['hællo']], + [['spa ce']], + [['yo\o']], + [['<script>…</script>']], + [['xxyoloxx', 'invÆlid']], + [['tautology', 'tautology']], + [['tautology2', 'TAUTOLOGY2']], + ]; + } + #[\PHPUnit\Framework\Attributes\DataProvider('invalidConfigPlaceholderProvider')] + public function testRegisterConfigHandlerInvalid(array $placeholders): void { + $this->expectException(\RuntimeException::class); + + $service = new BackendService($this->appConfig); + $mock = $this->createMock(IConfigHandler::class); + $cb = function () use ($mock) { + return $mock; + }; + foreach ($placeholders as $placeholder) { + $service->registerConfigHandler($placeholder, $cb); + } + } + + public function testConfigHandlers(): void { + $service = new BackendService($this->appConfig); + $mock = $this->createMock(IConfigHandler::class); + $mock->expects($this->exactly(3)) + ->method('handle'); + $cb = function () use ($mock) { + return $mock; + }; + $service->registerConfigHandler('one', $cb); + $service->registerConfigHandler('2', $cb); + $service->registerConfigHandler('Three', $cb); + + /** @var IConfigHandler[] $handlers */ + $handlers = $service->getConfigHandlers(); + + foreach ($handlers as $handler) { + $handler->handle('Something'); + } + } +} diff --git a/apps/files_external/tests/Service/DBConfigServiceTest.php b/apps/files_external/tests/Service/DBConfigServiceTest.php index e6115ddec20..85d8b70fda7 100644 --- a/apps/files_external/tests/Service/DBConfigServiceTest.php +++ b/apps/files_external/tests/Service/DBConfigServiceTest.php @@ -1,69 +1,49 @@ <?php + +declare(strict_types=1); /** - * @copyright Copyright (c) 2016, ownCloud, Inc. - * - * @author Robin Appelman <robin@icewind.nl> - * @author Robin McCorkell <robin@mccorkell.me.uk> - * - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see <http://www.gnu.org/licenses/> - * + * SPDX-FileCopyrightText: 2019-2024 Nextcloud GmbH and Nextcloud contributors + * SPDX-FileCopyrightText: 2016 ownCloud, Inc. + * SPDX-License-Identifier: AGPL-3.0-only */ - namespace OCA\Files_External\Tests\Service; - use OCA\Files_External\Service\DBConfigService; use OCP\IDBConnection; +use OCP\Security\ICrypto; +use OCP\Server; use Test\TestCase; /** * @group DB */ class DBConfigServiceTest extends TestCase { - /** - * @var DBConfigService - */ - private $dbConfig; + private IDBConnection $connection; + private DBConfigService $dbConfig; - /** - * @var IDBConnection - */ - private $connection; + private array $mounts = []; - private $mounts = []; - - public function setUp() { + protected function setUp(): void { parent::setUp(); - $this->connection = \OC::$server->getDatabaseConnection(); - $this->dbConfig = new DBConfigService($this->connection, \OC::$server->getCrypto()); + $this->connection = Server::get(IDBConnection::class); + $this->dbConfig = new DBConfigService($this->connection, Server::get(ICrypto::class)); } - public function tearDown() { + protected function tearDown(): void { foreach ($this->mounts as $mount) { $this->dbConfig->removeMount($mount); } $this->mounts = []; + parent::tearDown(); } - private function addMount($mountPoint, $storageBackend, $authBackend, $priority, $type) { + private function addMount(string $mountPoint, string $storageBackend, string $authBackend, int $priority, int $type) { $id = $this->dbConfig->addMount($mountPoint, $storageBackend, $authBackend, $priority, $type); $this->mounts[] = $id; return $id; } - public function testAddSimpleMount() { + public function testAddSimpleMount(): void { $id = $this->addMount('/test', 'foo', 'bar', 100, DBConfigService::MOUNT_TYPE_ADMIN); $mount = $this->dbConfig->getMountById($id); @@ -77,7 +57,7 @@ class DBConfigServiceTest extends TestCase { $this->assertEquals([], $mount['options']); } - public function testAddApplicable() { + public function testAddApplicable(): void { $id = $this->addMount('/test', 'foo', 'bar', 100, DBConfigService::MOUNT_TYPE_ADMIN); $this->dbConfig->addApplicable($id, DBConfigService::APPLICABLE_TYPE_USER, 'test'); @@ -90,14 +70,14 @@ class DBConfigServiceTest extends TestCase { $this->dbConfig->addApplicable($id, DBConfigService::APPLICABLE_TYPE_GLOBAL, null); $mount = $this->dbConfig->getMountById($id); - $this->assertEquals([ + $this->assertEqualsCanonicalizing([ ['type' => DBConfigService::APPLICABLE_TYPE_USER, 'value' => 'test', 'mount_id' => $id], ['type' => DBConfigService::APPLICABLE_TYPE_GROUP, 'value' => 'bar', 'mount_id' => $id], ['type' => DBConfigService::APPLICABLE_TYPE_GLOBAL, 'value' => null, 'mount_id' => $id] ], $mount['applicable']); } - public function testAddApplicableDouble() { + public function testAddApplicableDouble(): void { $id = $this->addMount('/test', 'foo', 'bar', 100, DBConfigService::MOUNT_TYPE_ADMIN); $this->dbConfig->addApplicable($id, DBConfigService::APPLICABLE_TYPE_USER, 'test'); $this->dbConfig->addApplicable($id, DBConfigService::APPLICABLE_TYPE_USER, 'test'); @@ -108,7 +88,7 @@ class DBConfigServiceTest extends TestCase { ], $mount['applicable']); } - public function testDeleteMount() { + public function testDeleteMount(): void { $id = $this->addMount('/test', 'foo', 'bar', 100, DBConfigService::MOUNT_TYPE_ADMIN); $this->dbConfig->removeMount($id); @@ -117,7 +97,7 @@ class DBConfigServiceTest extends TestCase { $this->assertEquals(null, $mount); } - public function testRemoveApplicable() { + public function testRemoveApplicable(): void { $id = $this->addMount('/test', 'foo', 'bar', 100, DBConfigService::MOUNT_TYPE_ADMIN); $this->dbConfig->addApplicable($id, DBConfigService::APPLICABLE_TYPE_USER, 'test'); $this->dbConfig->removeApplicable($id, DBConfigService::APPLICABLE_TYPE_USER, 'test'); @@ -126,7 +106,7 @@ class DBConfigServiceTest extends TestCase { $this->assertEquals([], $mount['applicable']); } - public function testRemoveApplicableGlobal() { + public function testRemoveApplicableGlobal(): void { $id = $this->addMount('/test', 'foo', 'bar', 100, DBConfigService::MOUNT_TYPE_ADMIN); $this->dbConfig->addApplicable($id, DBConfigService::APPLICABLE_TYPE_GLOBAL, null); $this->dbConfig->removeApplicable($id, DBConfigService::APPLICABLE_TYPE_GLOBAL, null); @@ -138,7 +118,7 @@ class DBConfigServiceTest extends TestCase { ], $mount['applicable']); } - public function testSetConfig() { + public function testSetConfig(): void { $id = $this->addMount('/test', 'foo', 'bar', 100, DBConfigService::MOUNT_TYPE_ADMIN); $this->dbConfig->setConfig($id, 'foo', 'bar'); @@ -151,7 +131,7 @@ class DBConfigServiceTest extends TestCase { $this->assertEquals(['foo' => 'bar', 'foo2' => 'bar2'], $mount['config']); } - public function testSetConfigOverwrite() { + public function testSetConfigOverwrite(): void { $id = $this->addMount('/test', 'foo', 'bar', 100, DBConfigService::MOUNT_TYPE_ADMIN); $this->dbConfig->setConfig($id, 'foo', 'bar'); $this->dbConfig->setConfig($id, 'asd', '1'); @@ -161,7 +141,7 @@ class DBConfigServiceTest extends TestCase { $this->assertEquals(['foo' => 'qwerty', 'asd' => '1'], $mount['config']); } - public function testSetOption() { + public function testSetOption(): void { $id = $this->addMount('/test', 'foo', 'bar', 100, DBConfigService::MOUNT_TYPE_ADMIN); $this->dbConfig->setOption($id, 'foo', 'bar'); @@ -174,7 +154,7 @@ class DBConfigServiceTest extends TestCase { $this->assertEquals(['foo' => 'bar', 'foo2' => 'bar2'], $mount['options']); } - public function testSetOptionOverwrite() { + public function testSetOptionOverwrite(): void { $id = $this->addMount('/test', 'foo', 'bar', 100, DBConfigService::MOUNT_TYPE_ADMIN); $this->dbConfig->setOption($id, 'foo', 'bar'); $this->dbConfig->setOption($id, 'asd', '1'); @@ -184,7 +164,7 @@ class DBConfigServiceTest extends TestCase { $this->assertEquals(['foo' => 'qwerty', 'asd' => '1'], $mount['options']); } - public function testGetMountsFor() { + public function testGetMountsFor(): void { $mounts = $this->dbConfig->getMountsFor(DBConfigService::APPLICABLE_TYPE_USER, 'test'); $this->assertEquals([], $mounts); @@ -197,19 +177,19 @@ class DBConfigServiceTest extends TestCase { $this->assertEquals([['type' => DBConfigService::APPLICABLE_TYPE_USER, 'value' => 'test', 'mount_id' => $id]], $mounts[0]['applicable']); } - public function testGetAdminMounts() { + public function testGetAdminMounts(): void { $id1 = $this->addMount('/test', 'foo', 'bar', 100, DBConfigService::MOUNT_TYPE_ADMIN); - $this->addMount('/test2', 'foo2', 'bar2', 100, DBConfigService::MOUNT_TYPE_PERSONAl); + $this->addMount('/test2', 'foo2', 'bar2', 100, DBConfigService::MOUNT_TYPE_PERSONAL); $mounts = $this->dbConfig->getAdminMounts(); $this->assertCount(1, $mounts); $this->assertEquals($id1, $mounts[0]['mount_id']); } - public function testGetAdminMountsFor() { + public function testGetAdminMountsFor(): void { $id1 = $this->addMount('/test', 'foo', 'bar', 100, DBConfigService::MOUNT_TYPE_ADMIN); $this->addMount('/test2', 'foo2', 'bar2', 100, DBConfigService::MOUNT_TYPE_ADMIN); - $id3 = $this->addMount('/test3', 'foo3', 'bar3', 100, DBConfigService::MOUNT_TYPE_PERSONAl); + $id3 = $this->addMount('/test3', 'foo3', 'bar3', 100, DBConfigService::MOUNT_TYPE_PERSONAL); $this->dbConfig->addApplicable($id1, DBConfigService::APPLICABLE_TYPE_USER, 'test'); $this->dbConfig->addApplicable($id3, DBConfigService::APPLICABLE_TYPE_USER, 'test'); @@ -220,10 +200,10 @@ class DBConfigServiceTest extends TestCase { $this->assertEquals([['type' => DBConfigService::APPLICABLE_TYPE_USER, 'value' => 'test', 'mount_id' => $id1]], $mounts[0]['applicable']); } - public function testGetUserMountsFor() { + public function testGetUserMountsFor(): void { $id1 = $this->addMount('/test', 'foo', 'bar', 100, DBConfigService::MOUNT_TYPE_ADMIN); - $this->addMount('/test2', 'foo2', 'bar2', 100, DBConfigService::MOUNT_TYPE_PERSONAl); - $id3 = $this->addMount('/test3', 'foo3', 'bar3', 100, DBConfigService::MOUNT_TYPE_PERSONAl); + $this->addMount('/test2', 'foo2', 'bar2', 100, DBConfigService::MOUNT_TYPE_PERSONAL); + $id3 = $this->addMount('/test3', 'foo3', 'bar3', 100, DBConfigService::MOUNT_TYPE_PERSONAL); $this->dbConfig->addApplicable($id1, DBConfigService::APPLICABLE_TYPE_USER, 'test'); $this->dbConfig->addApplicable($id3, DBConfigService::APPLICABLE_TYPE_USER, 'test'); @@ -234,7 +214,7 @@ class DBConfigServiceTest extends TestCase { $this->assertEquals([['type' => DBConfigService::APPLICABLE_TYPE_USER, 'value' => 'test', 'mount_id' => $id3]], $mounts[0]['applicable']); } - public function testGetAdminMountsForGlobal() { + public function testGetAdminMountsForGlobal(): void { $id1 = $this->addMount('/test', 'foo', 'bar', 100, DBConfigService::MOUNT_TYPE_ADMIN); $this->dbConfig->addApplicable($id1, DBConfigService::APPLICABLE_TYPE_GLOBAL, null); @@ -245,7 +225,7 @@ class DBConfigServiceTest extends TestCase { $this->assertEquals([['type' => DBConfigService::APPLICABLE_TYPE_GLOBAL, 'value' => null, 'mount_id' => $id1]], $mounts[0]['applicable']); } - public function testSetMountPoint() { + public function testSetMountPoint(): void { $id1 = $this->addMount('/test', 'foo', 'bar', 100, DBConfigService::MOUNT_TYPE_ADMIN); $id2 = $this->addMount('/foo', 'foo', 'bar', 100, DBConfigService::MOUNT_TYPE_ADMIN); @@ -259,7 +239,7 @@ class DBConfigServiceTest extends TestCase { $this->assertEquals('/foo', $mount['mount_point']); } - public function testSetAuthBackend() { + public function testSetAuthBackend(): void { $id1 = $this->addMount('/test', 'foo', 'bar', 100, DBConfigService::MOUNT_TYPE_ADMIN); $id2 = $this->addMount('/foo', 'foo', 'bar', 100, DBConfigService::MOUNT_TYPE_ADMIN); @@ -273,7 +253,7 @@ class DBConfigServiceTest extends TestCase { $this->assertEquals('bar', $mount['auth_backend']); } - public function testGetMountsForDuplicateByGroup() { + public function testGetMountsForDuplicateByGroup(): void { $id1 = $this->addMount('/test', 'foo', 'bar', 100, DBConfigService::MOUNT_TYPE_ADMIN); $this->dbConfig->addApplicable($id1, DBConfigService::APPLICABLE_TYPE_GROUP, 'group1'); @@ -284,9 +264,9 @@ class DBConfigServiceTest extends TestCase { $this->assertEquals($id1, $mounts[0]['mount_id']); } - public function testGetAllMounts() { + public function testGetAllMounts(): void { $id1 = $this->addMount('/test', 'foo', 'bar', 100, DBConfigService::MOUNT_TYPE_ADMIN); - $id2 = $this->addMount('/test2', 'foo2', 'bar2', 100, DBConfigService::MOUNT_TYPE_PERSONAl); + $id2 = $this->addMount('/test2', 'foo2', 'bar2', 100, DBConfigService::MOUNT_TYPE_PERSONAL); $mounts = $this->dbConfig->getAllMounts(); $this->assertCount(2, $mounts); diff --git a/apps/files_external/tests/Service/GlobalStoragesServiceTest.php b/apps/files_external/tests/Service/GlobalStoragesServiceTest.php index ba62feb7f96..0a3749981c8 100644 --- a/apps/files_external/tests/Service/GlobalStoragesServiceTest.php +++ b/apps/files_external/tests/Service/GlobalStoragesServiceTest.php @@ -1,43 +1,28 @@ <?php + +declare(strict_types=1); /** - * @copyright Copyright (c) 2016, ownCloud, Inc. - * - * @author Joas Schilling <coding@schilljs.com> - * @author Robin Appelman <robin@icewind.nl> - * @author Robin McCorkell <robin@mccorkell.me.uk> - * @author Vincent Petry <pvince81@owncloud.com> - * - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see <http://www.gnu.org/licenses/> - * + * SPDX-FileCopyrightText: 2019-2024 Nextcloud GmbH and Nextcloud contributors + * SPDX-FileCopyrightText: 2016 ownCloud, Inc. + * SPDX-License-Identifier: AGPL-3.0-only */ namespace OCA\Files_External\Tests\Service; -use \OC\Files\Filesystem; +use OC\Files\Filesystem; +use OCA\Files_External\MountConfig; -use \OCA\Files_External\Service\GlobalStoragesService; +use OCA\Files_External\Service\GlobalStoragesService; /** * @group DB */ -class GlobalStoragesServiceTest extends StoragesServiceTest { - public function setUp() { +class GlobalStoragesServiceTest extends StoragesServiceTestCase { + protected function setUp(): void { parent::setUp(); - $this->service = new GlobalStoragesService($this->backendService, $this->dbConfig, $this->mountCache); + $this->service = new GlobalStoragesService($this->backendService, $this->dbConfig, $this->mountCache, $this->eventDispatcher); } - public function tearDown() { + protected function tearDown(): void { @unlink($this->dataDir . '/mount.json'); parent::tearDown(); } @@ -61,7 +46,7 @@ class GlobalStoragesServiceTest extends StoragesServiceTest { ]); } - function storageDataProvider() { + public static function storageDataProvider(): array { return [ // all users [ @@ -130,10 +115,8 @@ class GlobalStoragesServiceTest extends StoragesServiceTest { ]; } - /** - * @dataProvider storageDataProvider - */ - public function testAddStorage($storageParams) { + #[\PHPUnit\Framework\Attributes\DataProvider('storageDataProvider')] + public function testAddStorage($storageParams): void { $storage = $this->makeStorageConfig($storageParams); $newStorage = $this->service->addStorage($storage); @@ -154,10 +137,8 @@ class GlobalStoragesServiceTest extends StoragesServiceTest { $this->assertEquals($baseId + 1, $nextStorage->getId()); } - /** - * @dataProvider storageDataProvider - */ - public function testUpdateStorage($updatedStorageParams) { + #[\PHPUnit\Framework\Attributes\DataProvider('storageDataProvider')] + public function testUpdateStorage($updatedStorageParams): void { $updatedStorage = $this->makeStorageConfig($updatedStorageParams); $storage = $this->makeStorageConfig([ 'mountPoint' => 'mountpoint', @@ -183,13 +164,13 @@ class GlobalStoragesServiceTest extends StoragesServiceTest { $this->assertEquals($updatedStorage->getMountPoint(), $newStorage->getMountPoint()); $this->assertEquals($updatedStorage->getBackendOptions()['password'], $newStorage->getBackendOptions()['password']); - $this->assertEquals($updatedStorage->getApplicableUsers(), $newStorage->getApplicableUsers()); + $this->assertEqualsCanonicalizing($updatedStorage->getApplicableUsers(), $newStorage->getApplicableUsers()); $this->assertEquals($updatedStorage->getApplicableGroups(), $newStorage->getApplicableGroups()); $this->assertEquals($updatedStorage->getPriority(), $newStorage->getPriority()); $this->assertEquals(0, $newStorage->getStatus()); } - function hooksAddStorageDataProvider() { + public static function hooksAddStorageDataProvider(): array { return [ // applicable all [ @@ -199,7 +180,7 @@ class GlobalStoragesServiceTest extends StoragesServiceTest { [ [ Filesystem::signal_create_mount, - \OC_Mount_Config::MOUNT_TYPE_USER, + MountConfig::MOUNT_TYPE_USER, 'all' ], ], @@ -212,7 +193,7 @@ class GlobalStoragesServiceTest extends StoragesServiceTest { [ [ Filesystem::signal_create_mount, - \OC_Mount_Config::MOUNT_TYPE_USER, + MountConfig::MOUNT_TYPE_USER, 'user1', ], ], @@ -225,7 +206,7 @@ class GlobalStoragesServiceTest extends StoragesServiceTest { [ [ Filesystem::signal_create_mount, - \OC_Mount_Config::MOUNT_TYPE_GROUP, + MountConfig::MOUNT_TYPE_GROUP, 'group1', ], ], @@ -237,12 +218,12 @@ class GlobalStoragesServiceTest extends StoragesServiceTest { [ [ Filesystem::signal_create_mount, - \OC_Mount_Config::MOUNT_TYPE_USER, + MountConfig::MOUNT_TYPE_USER, 'user1', ], [ Filesystem::signal_create_mount, - \OC_Mount_Config::MOUNT_TYPE_USER, + MountConfig::MOUNT_TYPE_USER, 'user2', ], ], @@ -255,17 +236,17 @@ class GlobalStoragesServiceTest extends StoragesServiceTest { [ [ Filesystem::signal_create_mount, - \OC_Mount_Config::MOUNT_TYPE_GROUP, + MountConfig::MOUNT_TYPE_GROUP, 'group1' ], [ Filesystem::signal_create_mount, - \OC_Mount_Config::MOUNT_TYPE_GROUP, + MountConfig::MOUNT_TYPE_GROUP, 'group2' ], ], ], - // mixed groups and users + // mixed groups and users [ ['user1', 'user2'], ['group1', 'group2'], @@ -273,22 +254,22 @@ class GlobalStoragesServiceTest extends StoragesServiceTest { [ [ Filesystem::signal_create_mount, - \OC_Mount_Config::MOUNT_TYPE_USER, + MountConfig::MOUNT_TYPE_USER, 'user1', ], [ Filesystem::signal_create_mount, - \OC_Mount_Config::MOUNT_TYPE_USER, + MountConfig::MOUNT_TYPE_USER, 'user2', ], [ Filesystem::signal_create_mount, - \OC_Mount_Config::MOUNT_TYPE_GROUP, + MountConfig::MOUNT_TYPE_GROUP, 'group1' ], [ Filesystem::signal_create_mount, - \OC_Mount_Config::MOUNT_TYPE_GROUP, + MountConfig::MOUNT_TYPE_GROUP, 'group2' ], ], @@ -296,10 +277,8 @@ class GlobalStoragesServiceTest extends StoragesServiceTest { ]; } - /** - * @dataProvider hooksAddStorageDataProvider - */ - public function testHooksAddStorage($applicableUsers, $applicableGroups, $expectedCalls) { + #[\PHPUnit\Framework\Attributes\DataProvider('hooksAddStorageDataProvider')] + public function testHooksAddStorage($applicableUsers, $applicableGroups, $expectedCalls): void { $storage = $this->makeTestStorageData(); $storage->setApplicableUsers($applicableUsers); $storage->setApplicableGroups($applicableGroups); @@ -318,7 +297,7 @@ class GlobalStoragesServiceTest extends StoragesServiceTest { } } - function hooksUpdateStorageDataProvider() { + public static function hooksUpdateStorageDataProvider(): array { return [ [ // nothing to multiple users and groups @@ -331,27 +310,27 @@ class GlobalStoragesServiceTest extends StoragesServiceTest { // delete the "all entry" [ Filesystem::signal_delete_mount, - \OC_Mount_Config::MOUNT_TYPE_USER, + MountConfig::MOUNT_TYPE_USER, 'all', ], [ Filesystem::signal_create_mount, - \OC_Mount_Config::MOUNT_TYPE_USER, + MountConfig::MOUNT_TYPE_USER, 'user1', ], [ Filesystem::signal_create_mount, - \OC_Mount_Config::MOUNT_TYPE_USER, + MountConfig::MOUNT_TYPE_USER, 'user2', ], [ Filesystem::signal_create_mount, - \OC_Mount_Config::MOUNT_TYPE_GROUP, + MountConfig::MOUNT_TYPE_GROUP, 'group1' ], [ Filesystem::signal_create_mount, - \OC_Mount_Config::MOUNT_TYPE_GROUP, + MountConfig::MOUNT_TYPE_GROUP, 'group2' ], ], @@ -366,12 +345,12 @@ class GlobalStoragesServiceTest extends StoragesServiceTest { [ [ Filesystem::signal_create_mount, - \OC_Mount_Config::MOUNT_TYPE_USER, + MountConfig::MOUNT_TYPE_USER, 'user2', ], [ Filesystem::signal_create_mount, - \OC_Mount_Config::MOUNT_TYPE_GROUP, + MountConfig::MOUNT_TYPE_GROUP, 'group2' ], ], @@ -386,12 +365,12 @@ class GlobalStoragesServiceTest extends StoragesServiceTest { [ [ Filesystem::signal_delete_mount, - \OC_Mount_Config::MOUNT_TYPE_USER, + MountConfig::MOUNT_TYPE_USER, 'user2', ], [ Filesystem::signal_delete_mount, - \OC_Mount_Config::MOUNT_TYPE_GROUP, + MountConfig::MOUNT_TYPE_GROUP, 'group2' ], ], @@ -406,18 +385,18 @@ class GlobalStoragesServiceTest extends StoragesServiceTest { [ [ Filesystem::signal_delete_mount, - \OC_Mount_Config::MOUNT_TYPE_USER, + MountConfig::MOUNT_TYPE_USER, 'user1', ], [ Filesystem::signal_delete_mount, - \OC_Mount_Config::MOUNT_TYPE_GROUP, + MountConfig::MOUNT_TYPE_GROUP, 'group1' ], // create the "all" entry [ Filesystem::signal_create_mount, - \OC_Mount_Config::MOUNT_TYPE_USER, + MountConfig::MOUNT_TYPE_USER, 'all' ], ], @@ -434,16 +413,14 @@ class GlobalStoragesServiceTest extends StoragesServiceTest { ]; } - /** - * @dataProvider hooksUpdateStorageDataProvider - */ + #[\PHPUnit\Framework\Attributes\DataProvider('hooksUpdateStorageDataProvider')] public function testHooksUpdateStorage( - $sourceApplicableUsers, - $sourceApplicableGroups, - $updatedApplicableUsers, - $updatedApplicableGroups, - $expectedCalls) { - + array $sourceApplicableUsers, + array $sourceApplicableGroups, + array $updatedApplicableUsers, + array $updatedApplicableGroups, + array $expectedCalls, + ): void { $storage = $this->makeTestStorageData(); $storage->setApplicableUsers($sourceApplicableUsers); $storage->setApplicableGroups($sourceApplicableGroups); @@ -470,9 +447,8 @@ class GlobalStoragesServiceTest extends StoragesServiceTest { } } - /** - */ - public function testHooksRenameMountPoint() { + + public function testHooksRenameMountPoint(): void { $storage = $this->makeTestStorageData(); $storage->setApplicableUsers(['user1', 'user2']); $storage->setApplicableGroups(['group1', 'group2']); @@ -490,50 +466,50 @@ class GlobalStoragesServiceTest extends StoragesServiceTest { [ Filesystem::signal_delete_mount, '/mountpoint', - \OC_Mount_Config::MOUNT_TYPE_USER, + MountConfig::MOUNT_TYPE_USER, 'user1', ], [ Filesystem::signal_delete_mount, '/mountpoint', - \OC_Mount_Config::MOUNT_TYPE_USER, + MountConfig::MOUNT_TYPE_USER, 'user2', ], [ Filesystem::signal_delete_mount, '/mountpoint', - \OC_Mount_Config::MOUNT_TYPE_GROUP, + MountConfig::MOUNT_TYPE_GROUP, 'group1', ], [ Filesystem::signal_delete_mount, '/mountpoint', - \OC_Mount_Config::MOUNT_TYPE_GROUP, + MountConfig::MOUNT_TYPE_GROUP, 'group2', ], // creates new one [ Filesystem::signal_create_mount, '/renamedMountpoint', - \OC_Mount_Config::MOUNT_TYPE_USER, + MountConfig::MOUNT_TYPE_USER, 'user1', ], [ Filesystem::signal_create_mount, '/renamedMountpoint', - \OC_Mount_Config::MOUNT_TYPE_USER, + MountConfig::MOUNT_TYPE_USER, 'user2', ], [ Filesystem::signal_create_mount, '/renamedMountpoint', - \OC_Mount_Config::MOUNT_TYPE_GROUP, + MountConfig::MOUNT_TYPE_GROUP, 'group1', ], [ Filesystem::signal_create_mount, '/renamedMountpoint', - \OC_Mount_Config::MOUNT_TYPE_GROUP, + MountConfig::MOUNT_TYPE_GROUP, 'group2', ], ]; @@ -551,7 +527,7 @@ class GlobalStoragesServiceTest extends StoragesServiceTest { } } - function hooksDeleteStorageDataProvider() { + public static function hooksDeleteStorageDataProvider(): array { return [ [ ['user1', 'user2'], @@ -560,22 +536,22 @@ class GlobalStoragesServiceTest extends StoragesServiceTest { [ [ Filesystem::signal_delete_mount, - \OC_Mount_Config::MOUNT_TYPE_USER, + MountConfig::MOUNT_TYPE_USER, 'user1', ], [ Filesystem::signal_delete_mount, - \OC_Mount_Config::MOUNT_TYPE_USER, + MountConfig::MOUNT_TYPE_USER, 'user2', ], [ Filesystem::signal_delete_mount, - \OC_Mount_Config::MOUNT_TYPE_GROUP, + MountConfig::MOUNT_TYPE_GROUP, 'group1' ], [ Filesystem::signal_delete_mount, - \OC_Mount_Config::MOUNT_TYPE_GROUP, + MountConfig::MOUNT_TYPE_GROUP, 'group2' ], ], @@ -587,7 +563,7 @@ class GlobalStoragesServiceTest extends StoragesServiceTest { [ [ Filesystem::signal_delete_mount, - \OC_Mount_Config::MOUNT_TYPE_USER, + MountConfig::MOUNT_TYPE_USER, 'all', ], ], @@ -595,14 +571,12 @@ class GlobalStoragesServiceTest extends StoragesServiceTest { ]; } - /** - * @dataProvider hooksDeleteStorageDataProvider - */ + #[\PHPUnit\Framework\Attributes\DataProvider('hooksDeleteStorageDataProvider')] public function testHooksDeleteStorage( - $sourceApplicableUsers, - $sourceApplicableGroups, - $expectedCalls) { - + array $sourceApplicableUsers, + array $sourceApplicableGroups, + array $expectedCalls, + ): void { $storage = $this->makeTestStorageData(); $storage->setApplicableUsers($sourceApplicableUsers); $storage->setApplicableGroups($sourceApplicableGroups); @@ -625,5 +599,4 @@ class GlobalStoragesServiceTest extends StoragesServiceTest { ); } } - } diff --git a/apps/files_external/tests/Service/StoragesServiceTest.php b/apps/files_external/tests/Service/StoragesServiceTestCase.php index 01e5c4122f2..b41eb409468 100644 --- a/apps/files_external/tests/Service/StoragesServiceTest.php +++ b/apps/files_external/tests/Service/StoragesServiceTestCase.php @@ -1,48 +1,43 @@ <?php + +declare(strict_types=1); /** - * @copyright Copyright (c) 2016, ownCloud, Inc. - * - * @author Joas Schilling <coding@schilljs.com> - * @author Morris Jobke <hey@morrisjobke.de> - * @author Robin Appelman <robin@icewind.nl> - * @author Robin McCorkell <robin@mccorkell.me.uk> - * @author Roeland Jago Douma <roeland@famdouma.nl> - * @author Vincent Petry <pvince81@owncloud.com> - * - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see <http://www.gnu.org/licenses/> - * + * SPDX-FileCopyrightText: 2019-2024 Nextcloud GmbH and Nextcloud contributors + * SPDX-FileCopyrightText: 2016 ownCloud, Inc. + * SPDX-License-Identifier: AGPL-3.0-only */ - namespace OCA\Files_External\Tests\Service; -use \OC\Files\Filesystem; - +use OC\Files\Cache\Storage; +use OC\Files\Filesystem; use OCA\Files_External\Lib\Auth\AuthMechanism; use OCA\Files_External\Lib\Auth\InvalidAuth; +use OCA\Files_External\Lib\Auth\NullMechanism; use OCA\Files_External\Lib\Backend\Backend; use OCA\Files_External\Lib\Backend\InvalidBackend; -use OCA\Files_External\NotFoundException; +use OCA\Files_External\Lib\Backend\SMB; use OCA\Files_External\Lib\StorageConfig; +use OCA\Files_External\MountConfig; +use OCA\Files_External\NotFoundException; use OCA\Files_External\Service\BackendService; use OCA\Files_External\Service\DBConfigService; use OCA\Files_External\Service\StoragesService; use OCP\AppFramework\IAppContainer; +use OCP\EventDispatcher\IEventDispatcher; +use OCP\Files\Cache\ICache; use OCP\Files\Config\IUserMountCache; +use OCP\Files\Mount\IMountPoint; +use OCP\Files\Storage\IStorage; +use OCP\IConfig; +use OCP\IDBConnection; +use OCP\IUser; +use OCP\Security\ICrypto; +use OCP\Server; +use OCP\Util; +use PHPUnit\Framework\MockObject\MockObject; class CleaningDBConfig extends DBConfigService { - private $mountIds = []; + private array $mountIds = []; public function addMount($mountPoint, $storageBackend, $authBackend, $priority, $type) { $id = parent::addMount($mountPoint, $storageBackend, $authBackend, $priority, $type); // TODO: Change the autogenerated stub @@ -60,56 +55,31 @@ class CleaningDBConfig extends DBConfigService { /** * @group DB */ -abstract class StoragesServiceTest extends \Test\TestCase { - - /** - * @var StoragesService - */ - protected $service; - - /** @var BackendService */ - protected $backendService; - - /** - * Data directory - * - * @var string - */ - protected $dataDir; - - /** @var CleaningDBConfig */ - protected $dbConfig; - - /** - * Hook calls - * - * @var array - */ - protected static $hookCalls; - - /** - * @var \PHPUnit_Framework_MockObject_MockObject|\OCP\Files\Config\IUserMountCache - */ - protected $mountCache; - - public function setUp() { +abstract class StoragesServiceTestCase extends \Test\TestCase { + protected StoragesService $service; + protected BackendService $backendService; + protected string $dataDir; + protected CleaningDBConfig $dbConfig; + protected static array $hookCalls; + protected IUserMountCache&MockObject $mountCache; + protected IEventDispatcher&MockObject $eventDispatcher; + + protected function setUp(): void { parent::setUp(); - $this->dbConfig = new CleaningDBConfig(\OC::$server->getDatabaseConnection(), \OC::$server->getCrypto()); - self::$hookCalls = array(); - $config = \OC::$server->getConfig(); + $this->dbConfig = new CleaningDBConfig(Server::get(IDBConnection::class), Server::get(ICrypto::class)); + self::$hookCalls = []; + $config = Server::get(IConfig::class); $this->dataDir = $config->getSystemValue( 'datadirectory', \OC::$SERVERROOT . '/data/' ); - \OC_Mount_Config::$skipTest = true; + MountConfig::$skipTest = true; $this->mountCache = $this->createMock(IUserMountCache::class); + $this->eventDispatcher = $this->createMock(IEventDispatcher::class); // prepare BackendService mock - $this->backendService = - $this->getMockBuilder('\OCA\Files_External\Service\BackendService') - ->disableOriginalConstructor() - ->getMock(); + $this->backendService = $this->createMock(BackendService::class); $authMechanisms = [ 'identifier:\Auth\Mechanism' => $this->getAuthMechMock('null', '\Auth\Mechanism'), @@ -117,23 +87,24 @@ abstract class StoragesServiceTest extends \Test\TestCase { 'identifier:\OCA\Files_External\Lib\Auth\NullMechanism' => $this->getAuthMechMock(), ]; $this->backendService->method('getAuthMechanism') - ->will($this->returnCallback(function ($class) use ($authMechanisms) { + ->willReturnCallback(function ($class) use ($authMechanisms) { if (isset($authMechanisms[$class])) { return $authMechanisms[$class]; } return null; - })); + }); $this->backendService->method('getAuthMechanismsByScheme') - ->will($this->returnCallback(function ($schemes) use ($authMechanisms) { + ->willReturnCallback(function ($schemes) use ($authMechanisms) { return array_filter($authMechanisms, function ($authMech) use ($schemes) { return in_array($authMech->getScheme(), $schemes, true); }); - })); + }); $this->backendService->method('getAuthMechanisms') - ->will($this->returnValue($authMechanisms)); + ->willReturn($authMechanisms); $sftpBackend = $this->getBackendMock('\OCA\Files_External\Lib\Backend\SFTP', '\OCA\Files_External\Lib\Storage\SFTP'); $backends = [ + 'identifier:\OCA\Files_External\Lib\Backend\DAV' => $this->getBackendMock('\OCA\Files_External\Lib\Backend\DAV', '\OC\Files\Storage\DAV'), 'identifier:\OCA\Files_External\Lib\Backend\SMB' => $this->getBackendMock('\OCA\Files_External\Lib\Backend\SMB', '\OCA\Files_External\Lib\Storage\SMB'), 'identifier:\OCA\Files_External\Lib\Backend\SFTP' => $sftpBackend, 'identifier:sftp_alias' => $sftpBackend, @@ -141,51 +112,45 @@ abstract class StoragesServiceTest extends \Test\TestCase { $backends['identifier:\OCA\Files_External\Lib\Backend\SFTP']->method('getLegacyAuthMechanism') ->willReturn($authMechanisms['identifier:\Other\Auth\Mechanism']); $this->backendService->method('getBackend') - ->will($this->returnCallback(function ($backendClass) use ($backends) { + ->willReturnCallback(function ($backendClass) use ($backends) { if (isset($backends[$backendClass])) { return $backends[$backendClass]; } return null; - })); + }); $this->backendService->method('getBackends') - ->will($this->returnValue($backends)); + ->willReturn($backends); + $this->overwriteService(BackendService::class, $this->backendService); - \OCP\Util::connectHook( + Util::connectHook( Filesystem::CLASSNAME, Filesystem::signal_create_mount, get_class($this), 'createHookCallback'); - \OCP\Util::connectHook( + Util::connectHook( Filesystem::CLASSNAME, Filesystem::signal_delete_mount, get_class($this), 'deleteHookCallback'); $containerMock = $this->createMock(IAppContainer::class); $containerMock->method('query') - ->will($this->returnCallback(function ($name) { + ->willReturnCallback(function ($name) { if ($name === 'OCA\Files_External\Service\BackendService') { return $this->backendService; } - })); - - \OC_Mount_Config::$app = $this->getMockBuilder('\OCA\Files_External\Appinfo\Application') - ->disableOriginalConstructor() - ->getMock(); - \OC_Mount_Config::$app->method('getContainer') - ->willReturn($containerMock); + }); } - public function tearDown() { - \OC_Mount_Config::$skipTest = false; - self::$hookCalls = array(); + protected function tearDown(): void { + MountConfig::$skipTest = false; + self::$hookCalls = []; if ($this->dbConfig) { $this->dbConfig->clean(); } + parent::tearDown(); } - protected function getBackendMock($class = '\OCA\Files_External\Lib\Backend\SMB', $storageClass = '\OCA\Files_External\Lib\Storage\SMB') { - $backend = $this->getMockBuilder(Backend::class) - ->disableOriginalConstructor() - ->getMock(); + protected function getBackendMock($class = SMB::class, $storageClass = \OCA\Files_External\Lib\Storage\SMB::class) { + $backend = $this->createMock(Backend::class); $backend->method('getStorageClass') ->willReturn($storageClass); $backend->method('getIdentifier') @@ -193,10 +158,8 @@ abstract class StoragesServiceTest extends \Test\TestCase { return $backend; } - protected function getAuthMechMock($scheme = 'null', $class = '\OCA\Files_External\Lib\Auth\NullMechanism') { - $authMech = $this->getMockBuilder(AuthMechanism::class) - ->disableOriginalConstructor() - ->getMock(); + protected function getAuthMechMock($scheme = 'null', $class = NullMechanism::class) { + $authMech = $this->createMock(AuthMechanism::class); $authMech->method('getScheme') ->willReturn($scheme); $authMech->method('getIdentifier') @@ -207,12 +170,8 @@ abstract class StoragesServiceTest extends \Test\TestCase { /** * Creates a StorageConfig instance based on array data - * - * @param array $data - * - * @return StorageConfig storage config instance */ - protected function makeStorageConfig($data) { + protected function makeStorageConfig(array $data): StorageConfig { $storage = new StorageConfig(); if (isset($data['id'])) { $storage->setId($data['id']); @@ -251,10 +210,7 @@ abstract class StoragesServiceTest extends \Test\TestCase { } - /** - * @expectedException \OCA\Files_External\NotFoundException - */ - public function testNonExistingStorage() { + protected function ActualNonExistingStorageTest() { $backend = $this->backendService->getBackend('identifier:\OCA\Files_External\Lib\Backend\SMB'); $authMechanism = $this->backendService->getAuthMechanism('identifier:\Auth\Mechanism'); $storage = new StorageConfig(255); @@ -264,40 +220,39 @@ abstract class StoragesServiceTest extends \Test\TestCase { $this->service->updateStorage($storage); } - public function deleteStorageDataProvider() { + public function testNonExistingStorage(): void { + $this->expectException(NotFoundException::class); + + $this->ActualNonExistingStorageTest(); + } + + public static function deleteStorageDataProvider(): array { return [ // regular case, can properly delete the oc_storages entry [ [ - 'share' => 'share', 'host' => 'example.com', 'user' => 'test', 'password' => 'testPassword', 'root' => 'someroot', ], - 'smb::test@example.com//share//someroot/', - 0 + 'webdav::test@example.com//someroot/' ], - // special case with $user vars, cannot auto-remove the oc_storages entry [ [ - 'share' => 'share', 'host' => 'example.com', 'user' => '$user', 'password' => 'testPassword', 'root' => 'someroot', ], - 'smb::someone@example.com//share//someroot/', - 1 + 'webdav::someone@example.com//someroot/' ], ]; } - /** - * @dataProvider deleteStorageDataProvider - */ - public function testDeleteStorage($backendOptions, $rustyStorageId, $expectedCountAfterDeletion) { - $backend = $this->backendService->getBackend('identifier:\OCA\Files_External\Lib\Backend\SMB'); + #[\PHPUnit\Framework\Attributes\DataProvider('deleteStorageDataProvider')] + public function testDeleteStorage(array $backendOptions, string $rustyStorageId): void { + $backend = $this->backendService->getBackend('identifier:\OCA\Files_External\Lib\Backend\DAV'); $authMechanism = $this->backendService->getAuthMechanism('identifier:\Auth\Mechanism'); $storage = new StorageConfig(255); $storage->setMountPoint('mountpoint'); @@ -310,7 +265,32 @@ abstract class StoragesServiceTest extends \Test\TestCase { // manually trigger storage entry because normally it happens on first // access, which isn't possible within this test - $storageCache = new \OC\Files\Cache\Storage($rustyStorageId); + $storageCache = new Storage($rustyStorageId, true, Server::get(IDBConnection::class)); + + /** @var IUserMountCache $mountCache */ + $mountCache = Server::get(IUserMountCache::class); + $mountCache->clear(); + $user = $this->createMock(IUser::class); + $user->method('getUID')->willReturn('test'); + $cache = $this->createMock(ICache::class); + $storage = $this->createMock(IStorage::class); + $storage->method('getCache')->willReturn($cache); + $mount = $this->createMock(IMountPoint::class); + $mount->method('getStorage') + ->willReturn($storage); + $mount->method('getStorageId') + ->willReturn($rustyStorageId); + $mount->method('getNumericStorageId') + ->willReturn($storageCache->getNumericId()); + $mount->method('getStorageRootId') + ->willReturn(1); + $mount->method('getMountPoint') + ->willReturn('dummy'); + $mount->method('getMountId') + ->willReturn($id); + $mountCache->registerMounts($user, [ + $mount + ]); // get numeric id for later check $numericId = $storageCache->getNumericId(); @@ -327,21 +307,28 @@ abstract class StoragesServiceTest extends \Test\TestCase { $this->assertTrue($caught); // storage id was removed from oc_storages - $qb = \OC::$server->getDatabaseConnection()->getQueryBuilder(); + $qb = Server::get(IDBConnection::class)->getQueryBuilder(); $storageCheckQuery = $qb->select('*') ->from('storages') ->where($qb->expr()->eq('numeric_id', $qb->expr()->literal($numericId))); - $this->assertCount($expectedCountAfterDeletion, $storageCheckQuery->execute()->fetchAll()); + + $result = $storageCheckQuery->execute(); + $storages = $result->fetchAll(); + $result->closeCursor(); + $this->assertCount(0, $storages, 'expected 0 storages, got ' . json_encode($storages)); } - /** - * @expectedException \OCA\Files_External\NotFoundException - */ - public function testDeleteUnexistingStorage() { + protected function actualDeletedUnexistingStorageTest() { $this->service->removeStorage(255); } - public function testCreateStorage() { + public function testDeleteUnexistingStorage(): void { + $this->expectException(NotFoundException::class); + + $this->actualDeletedUnexistingStorageTest(); + } + + public function testCreateStorage(): void { $mountPoint = 'mount'; $backendIdentifier = 'identifier:\OCA\Files_External\Lib\Backend\SMB'; $authMechanismIdentifier = 'identifier:\Auth\Mechanism'; @@ -375,7 +362,7 @@ abstract class StoragesServiceTest extends \Test\TestCase { $this->assertEquals($priority, $storage->getPriority()); } - public function testCreateStorageInvalidClass() { + public function testCreateStorageInvalidClass(): void { $storage = $this->service->createStorage( 'mount', 'identifier:\OC\Not\A\Backend', @@ -385,7 +372,7 @@ abstract class StoragesServiceTest extends \Test\TestCase { $this->assertInstanceOf(InvalidBackend::class, $storage->getBackend()); } - public function testCreateStorageInvalidAuthMechanismClass() { + public function testCreateStorageInvalidAuthMechanismClass(): void { $storage = $this->service->createStorage( 'mount', 'identifier:\OCA\Files_External\Lib\Backend\SMB', @@ -395,7 +382,7 @@ abstract class StoragesServiceTest extends \Test\TestCase { $this->assertInstanceOf(InvalidAuth::class, $storage->getAuthMechanism()); } - public function testGetStoragesBackendNotVisible() { + public function testGetStoragesBackendNotVisible(): void { $backend = $this->backendService->getBackend('identifier:\OCA\Files_External\Lib\Backend\SMB'); $backend->expects($this->once()) ->method('isVisibleFor') @@ -418,7 +405,7 @@ abstract class StoragesServiceTest extends \Test\TestCase { $this->assertEmpty($this->service->getStorages()); } - public function testGetStoragesAuthMechanismNotVisible() { + public function testGetStoragesAuthMechanismNotVisible(): void { $backend = $this->backendService->getBackend('identifier:\OCA\Files_External\Lib\Backend\SMB'); $backend->method('isVisibleFor') ->with($this->service->getVisibilityType()) @@ -441,18 +428,18 @@ abstract class StoragesServiceTest extends \Test\TestCase { $this->assertEmpty($this->service->getStorages()); } - public static function createHookCallback($params) { - self::$hookCalls[] = array( + public static function createHookCallback($params): void { + self::$hookCalls[] = [ 'signal' => Filesystem::signal_create_mount, 'params' => $params - ); + ]; } - public static function deleteHookCallback($params) { - self::$hookCalls[] = array( + public static function deleteHookCallback($params): void { + self::$hookCalls[] = [ 'signal' => Filesystem::signal_delete_mount, 'params' => $params - ); + ]; } /** @@ -481,7 +468,7 @@ abstract class StoragesServiceTest extends \Test\TestCase { ); } - public function testUpdateStorageMountPoint() { + public function testUpdateStorageMountPoint(): void { $backend = $this->backendService->getBackend('identifier:\OCA\Files_External\Lib\Backend\SMB'); $authMechanism = $this->backendService->getAuthMechanism('identifier:\Auth\Mechanism'); diff --git a/apps/files_external/tests/Service/UserGlobalStoragesServiceTest.php b/apps/files_external/tests/Service/UserGlobalStoragesServiceTest.php index 013af9b0426..2a2f4596fda 100644 --- a/apps/files_external/tests/Service/UserGlobalStoragesServiceTest.php +++ b/apps/files_external/tests/Service/UserGlobalStoragesServiceTest.php @@ -1,37 +1,23 @@ <?php + /** - * @copyright Copyright (c) 2016, ownCloud, Inc. - * - * @author Joas Schilling <coding@schilljs.com> - * @author Robin Appelman <robin@icewind.nl> - * @author Robin McCorkell <robin@mccorkell.me.uk> - * @author Roeland Jago Douma <roeland@famdouma.nl> - * @author Vincent Petry <pvince81@owncloud.com> - * - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see <http://www.gnu.org/licenses/> - * + * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors + * SPDX-FileCopyrightText: 2016 ownCloud, Inc. + * SPDX-License-Identifier: AGPL-3.0-only */ namespace OCA\Files_External\Tests\Service; +use OC\User\User; use OCA\Files_External\Lib\StorageConfig; use OCA\Files_External\NotFoundException; use OCA\Files_External\Service\StoragesService; use OCA\Files_External\Service\UserGlobalStoragesService; +use OCP\EventDispatcher\IEventDispatcher; use OCP\IGroupManager; use OCP\IUser; use OCP\IUserSession; +use OCP\Server; +use PHPUnit\Framework\MockObject\MockObject; use Test\Traits\UserTrait; /** @@ -40,41 +26,30 @@ use Test\Traits\UserTrait; class UserGlobalStoragesServiceTest extends GlobalStoragesServiceTest { use UserTrait; - /** @var \OCP\IGroupManager|\PHPUnit_Framework_MockObject_MockObject groupManager */ - protected $groupManager; - - /** - * @var StoragesService - */ - protected $globalStoragesService; - - /** - * @var UserGlobalStoragesService - */ - protected $service; - - protected $user; + protected IGroupManager&MockObject $groupManager; + protected StoragesService $globalStoragesService; + protected User $user; - const USER_ID = 'test_user'; - const GROUP_ID = 'test_group'; - const GROUP_ID2 = 'test_group2'; + public const USER_ID = 'test_user'; + public const GROUP_ID = 'test_group'; + public const GROUP_ID2 = 'test_group2'; - public function setUp() { + protected function setUp(): void { parent::setUp(); $this->globalStoragesService = $this->service; - $this->user = new \OC\User\User(self::USER_ID, null); - /** @var \OCP\IUserSession|\PHPUnit_Framework_MockObject_MockObject $userSession */ + $this->user = new User(self::USER_ID, null, Server::get(IEventDispatcher::class)); + /** @var IUserSession&MockObject $userSession */ $userSession = $this->createMock(IUserSession::class); $userSession ->expects($this->any()) ->method('getUser') - ->will($this->returnValue($this->user)); + ->willReturn($this->user); $this->groupManager = $this->createMock(IGroupManager::class); $this->groupManager->method('isInGroup') - ->will($this->returnCallback(function ($userId, $groupId) { + ->willReturnCallback(function ($userId, $groupId) { if ($userId === self::USER_ID) { switch ($groupId) { case self::GROUP_ID: @@ -83,26 +58,27 @@ class UserGlobalStoragesServiceTest extends GlobalStoragesServiceTest { } } return false; - })); + }); $this->groupManager->method('getUserGroupIds') - ->will($this->returnCallback(function (IUser $user) { + ->willReturnCallback(function (IUser $user) { if ($user->getUID() === self::USER_ID) { return [self::GROUP_ID, self::GROUP_ID2]; } else { return []; } - })); + }); $this->service = new UserGlobalStoragesService( $this->backendService, $this->dbConfig, $userSession, $this->groupManager, - $this->mountCache + $this->mountCache, + $this->eventDispatcher, ); } - public function applicableStorageProvider() { + public static function applicableStorageProvider(): array { return [ [[], [], true], @@ -122,10 +98,8 @@ class UserGlobalStoragesServiceTest extends GlobalStoragesServiceTest { ]; } - /** - * @dataProvider applicableStorageProvider - */ - public function testGetStorageWithApplicable($applicableUsers, $applicableGroups, $isVisible) { + #[\PHPUnit\Framework\Attributes\DataProvider('applicableStorageProvider')] + public function testGetStorageWithApplicable($applicableUsers, $applicableGroups, $isVisible): void { $backend = $this->backendService->getBackend('identifier:\OCA\Files_External\Lib\Backend\SMB'); $authMechanism = $this->backendService->getAuthMechanism('identifier:\Auth\Mechanism'); @@ -151,16 +125,14 @@ class UserGlobalStoragesServiceTest extends GlobalStoragesServiceTest { $this->service->getStorage($newStorage->getId()); $this->fail('Failed asserting that storage can\'t be accessed by id'); } catch (NotFoundException $e) { - } } - } - /** - * @expectedException \DomainException - */ - public function testAddStorage($storageParams = null) { + + public function testAddStorage($storageParams = null): void { + $this->expectException(\DomainException::class); + $backend = $this->backendService->getBackend('identifier:\OCA\Files_External\Lib\Backend\SMB'); $authMechanism = $this->backendService->getAuthMechanism('identifier:\Auth\Mechanism'); @@ -173,10 +145,10 @@ class UserGlobalStoragesServiceTest extends GlobalStoragesServiceTest { $this->service->addStorage($storage); } - /** - * @expectedException \DomainException - */ - public function testUpdateStorage($storageParams = null) { + + public function testUpdateStorage($storageParams = null): void { + $this->expectException(\DomainException::class); + $backend = $this->backendService->getBackend('identifier:\OCA\Files_External\Lib\Backend\SMB'); $authMechanism = $this->backendService->getAuthMechanism('identifier:\Auth\Mechanism'); @@ -193,18 +165,17 @@ class UserGlobalStoragesServiceTest extends GlobalStoragesServiceTest { $this->service->updateStorage($retrievedStorage); } - /** - * @expectedException \DomainException - */ - public function testNonExistingStorage() { - parent::testNonExistingStorage(); + + public function testNonExistingStorage(): void { + $this->expectException(\DomainException::class); + + $this->ActualNonExistingStorageTest(); } - /** - * @expectedException \DomainException - * @dataProvider deleteStorageDataProvider - */ - public function testDeleteStorage($backendOptions, $rustyStorageId, $expectedCountAfterDeletion) { + #[\PHPUnit\Framework\Attributes\DataProvider('deleteStorageDataProvider')] + public function testDeleteStorage($backendOptions, $rustyStorageId): void { + $this->expectException(\DomainException::class); + $backend = $this->backendService->getBackend('identifier:\OCA\Files_External\Lib\Backend\SMB'); $authMechanism = $this->backendService->getAuthMechanism('identifier:\Auth\Mechanism'); @@ -220,14 +191,14 @@ class UserGlobalStoragesServiceTest extends GlobalStoragesServiceTest { $this->service->removeStorage($id); } - /** - * @expectedException \DomainException - */ - public function testDeleteUnexistingStorage() { - parent::testDeleteUnexistingStorage(); + + public function testDeleteUnexistingStorage(): void { + $this->expectException(\DomainException::class); + + $this->actualDeletedUnexistingStorageTest(); } - public function getUniqueStoragesProvider() { + public static function getUniqueStoragesProvider(): array { return [ // 'all' vs group [100, [], [], 100, [], [self::GROUP_ID], 2], @@ -255,14 +226,12 @@ class UserGlobalStoragesServiceTest extends GlobalStoragesServiceTest { ]; } - /** - * @dataProvider getUniqueStoragesProvider - */ + #[\PHPUnit\Framework\Attributes\DataProvider('getUniqueStoragesProvider')] public function testGetUniqueStorages( $priority1, $applicableUsers1, $applicableGroups1, $priority2, $applicableUsers2, $applicableGroups2, - $expectedPrecedence - ) { + $expectedPrecedence, + ): void { $backend = $this->backendService->getBackend('identifier:\OCA\Files_External\Lib\Backend\SMB'); $backend->method('isVisibleFor') ->willReturn(true); @@ -302,68 +271,68 @@ class UserGlobalStoragesServiceTest extends GlobalStoragesServiceTest { } } - public function testGetStoragesBackendNotVisible() { + public function testGetStoragesBackendNotVisible(): void { // we don't test this here - $this->assertTrue(true); + $this->addToAssertionCount(1); } - public function testGetStoragesAuthMechanismNotVisible() { + public function testGetStoragesAuthMechanismNotVisible(): void { // we don't test this here - $this->assertTrue(true); + $this->addToAssertionCount(1); } - public function testHooksAddStorage($a = null, $b = null, $c = null) { + public function testHooksAddStorage($a = null, $b = null, $c = null): void { // we don't test this here - $this->assertTrue(true); + $this->addToAssertionCount(1); } - public function testHooksUpdateStorage($a = null, $b = null, $c = null, $d = null, $e = null) { + public function testHooksUpdateStorage($a = null, $b = null, $c = null, $d = null, $e = null): void { // we don't test this here - $this->assertTrue(true); + $this->addToAssertionCount(1); } - public function testHooksRenameMountPoint() { + public function testHooksRenameMountPoint(): void { // we don't test this here - $this->assertTrue(true); + $this->addToAssertionCount(1); } - public function testHooksDeleteStorage($a = null, $b = null, $c = null) { + public function testHooksDeleteStorage($a = null, $b = null, $c = null): void { // we don't test this here - $this->assertTrue(true); + $this->addToAssertionCount(1); } - public function testLegacyConfigConversionApplicableAll() { + public function testLegacyConfigConversionApplicableAll(): void { // we don't test this here - $this->assertTrue(true); + $this->addToAssertionCount(1); } - public function testLegacyConfigConversionApplicableUserAndGroup() { + public function testLegacyConfigConversionApplicableUserAndGroup(): void { // we don't test this here - $this->assertTrue(true); + $this->addToAssertionCount(1); } - public function testReadLegacyConfigAndGenerateConfigId() { + public function testReadLegacyConfigAndGenerateConfigId(): void { // we don't test this here - $this->assertTrue(true); + $this->addToAssertionCount(1); } - public function testReadLegacyConfigNoAuthMechanism() { + public function testReadLegacyConfigNoAuthMechanism(): void { // we don't test this here - $this->assertTrue(true); + $this->addToAssertionCount(1); } - public function testReadLegacyConfigClass() { + public function testReadLegacyConfigClass(): void { // we don't test this here - $this->assertTrue(true); + $this->addToAssertionCount(1); } - public function testReadEmptyMountPoint() { + public function testReadEmptyMountPoint(): void { // we don't test this here - $this->assertTrue(true); + $this->addToAssertionCount(1); } - public function testUpdateStorageMountPoint() { + public function testUpdateStorageMountPoint(): void { // we don't test this here - $this->assertTrue(true); + $this->addToAssertionCount(1); } } diff --git a/apps/files_external/tests/Service/UserStoragesServiceTest.php b/apps/files_external/tests/Service/UserStoragesServiceTest.php index 2d90ec3a488..0a2f291f6e4 100644 --- a/apps/files_external/tests/Service/UserStoragesServiceTest.php +++ b/apps/files_external/tests/Service/UserStoragesServiceTest.php @@ -1,71 +1,55 @@ <?php + /** - * @copyright Copyright (c) 2016, ownCloud, Inc. - * - * @author Joas Schilling <coding@schilljs.com> - * @author Robin Appelman <robin@icewind.nl> - * @author Robin McCorkell <robin@mccorkell.me.uk> - * @author Roeland Jago Douma <roeland@famdouma.nl> - * @author Vincent Petry <pvince81@owncloud.com> - * - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see <http://www.gnu.org/licenses/> - * + * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors + * SPDX-FileCopyrightText: 2016 ownCloud, Inc. + * SPDX-License-Identifier: AGPL-3.0-only */ namespace OCA\Files_External\Tests\Service; -use \OC\Files\Filesystem; - +use OC\Files\Filesystem; +use OC\User\User; +use OCA\Files_External\Lib\StorageConfig; +use OCA\Files_External\MountConfig; +use OCA\Files_External\NotFoundException; use OCA\Files_External\Service\GlobalStoragesService; + use OCA\Files_External\Service\StoragesService; use OCA\Files_External\Service\UserStoragesService; -use OCA\Files_External\Lib\StorageConfig; +use OCP\IUserManager; use OCP\IUserSession; +use OCP\Server; +use PHPUnit\Framework\MockObject\MockObject; use Test\Traits\UserTrait; /** * @group DB */ -class UserStoragesServiceTest extends StoragesServiceTest { +class UserStoragesServiceTest extends StoragesServiceTestCase { use UserTrait; - private $user; - - private $userId; + protected User $user; - /** - * @var StoragesService - */ - protected $globalStoragesService; + protected string $userId; + protected StoragesService $globalStoragesService; - public function setUp() { + protected function setUp(): void { parent::setUp(); - $this->globalStoragesService = new GlobalStoragesService($this->backendService, $this->dbConfig, $this->mountCache); + $this->globalStoragesService = new GlobalStoragesService($this->backendService, $this->dbConfig, $this->mountCache, $this->eventDispatcher); $this->userId = $this->getUniqueID('user_'); $this->createUser($this->userId, $this->userId); - $this->user = \OC::$server->getUserManager()->get($this->userId); + $this->user = Server::get(IUserManager::class)->get($this->userId); - /** @var \OCP\IUserSession|\PHPUnit_Framework_MockObject_MockObject $userSession */ + /** @var IUserSession&MockObject $userSession */ $userSession = $this->createMock(IUserSession::class); $userSession ->expects($this->any()) ->method('getUser') - ->will($this->returnValue($this->user)); + ->willReturn($this->user); - $this->service = new UserStoragesService($this->backendService, $this->dbConfig, $userSession, $this->mountCache); + $this->service = new UserStoragesService($this->backendService, $this->dbConfig, $userSession, $this->mountCache, $this->eventDispatcher); } private function makeTestStorageData() { @@ -84,7 +68,7 @@ class UserStoragesServiceTest extends StoragesServiceTest { ]); } - public function testAddStorage() { + public function testAddStorage(): void { $storage = $this->makeTestStorageData(); $newStorage = $this->service->addStorage($storage); @@ -104,7 +88,7 @@ class UserStoragesServiceTest extends StoragesServiceTest { current(self::$hookCalls), Filesystem::signal_create_mount, $storage->getMountPoint(), - \OC_Mount_Config::MOUNT_TYPE_USER, + MountConfig::MOUNT_TYPE_USER, $this->userId ); @@ -112,7 +96,7 @@ class UserStoragesServiceTest extends StoragesServiceTest { $this->assertEquals($id + 1, $nextStorage->getId()); } - public function testUpdateStorage() { + public function testUpdateStorage(): void { $storage = $this->makeStorageConfig([ 'mountPoint' => 'mountpoint', 'backendIdentifier' => 'identifier:\OCA\Files_External\Lib\Backend\SMB', @@ -144,23 +128,21 @@ class UserStoragesServiceTest extends StoragesServiceTest { $this->assertEmpty(self::$hookCalls); } - /** - * @dataProvider deleteStorageDataProvider - */ - public function testDeleteStorage($backendOptions, $rustyStorageId, $expectedCountAfterDeletion) { - parent::testDeleteStorage($backendOptions, $rustyStorageId, $expectedCountAfterDeletion); + #[\PHPUnit\Framework\Attributes\DataProvider('deleteStorageDataProvider')] + public function testDeleteStorage($backendOptions, $rustyStorageId): void { + parent::testDeleteStorage($backendOptions, $rustyStorageId); // hook called once for user (first one was during test creation) $this->assertHookCall( self::$hookCalls[1], Filesystem::signal_delete_mount, '/mountpoint', - \OC_Mount_Config::MOUNT_TYPE_USER, + MountConfig::MOUNT_TYPE_USER, $this->userId ); } - public function testHooksRenameMountPoint() { + public function testHooksRenameMountPoint(): void { $storage = $this->makeTestStorageData(); $storage = $this->service->addStorage($storage); @@ -176,22 +158,22 @@ class UserStoragesServiceTest extends StoragesServiceTest { self::$hookCalls[0], Filesystem::signal_delete_mount, '/mountpoint', - \OC_Mount_Config::MOUNT_TYPE_USER, + MountConfig::MOUNT_TYPE_USER, $this->userId ); $this->assertHookCall( self::$hookCalls[1], Filesystem::signal_create_mount, '/renamedMountpoint', - \OC_Mount_Config::MOUNT_TYPE_USER, + MountConfig::MOUNT_TYPE_USER, $this->userId ); } - /** - * @expectedException \OCA\Files_External\NotFoundException - */ - public function testGetAdminStorage() { + + public function testGetAdminStorage(): void { + $this->expectException(NotFoundException::class); + $backend = $this->backendService->getBackend('identifier:\OCA\Files_External\Lib\Backend\SMB'); $authMechanism = $this->backendService->getAuthMechanism('identifier:\Auth\Mechanism'); diff --git a/apps/files_external/tests/Settings/AdminTest.php b/apps/files_external/tests/Settings/AdminTest.php index 6236f2d416a..fd4a1949760 100644 --- a/apps/files_external/tests/Settings/AdminTest.php +++ b/apps/files_external/tests/Settings/AdminTest.php @@ -1,49 +1,30 @@ <?php + +declare(strict_types=1); /** - * @copyright Copyright (c) 2016 Lukas Reschke <lukas@statuscode.ch> - * - * @author Lukas Reschke <lukas@statuscode.ch> - * - * @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\Files_External\Tests\Settings; use OCA\Files_External\Lib\Auth\Password\GlobalAuth; +use OCA\Files_External\MountConfig; use OCA\Files_External\Service\BackendService; use OCA\Files_External\Service\GlobalStoragesService; use OCA\Files_External\Settings\Admin; use OCP\AppFramework\Http\TemplateResponse; use OCP\Encryption\IManager; +use PHPUnit\Framework\MockObject\MockObject; use Test\TestCase; class AdminTest extends TestCase { - /** @var Admin */ - private $admin; - /** @var IManager|\PHPUnit_Framework_MockObject_MockObject */ - private $encryptionManager; - /** @var GlobalStoragesService|\PHPUnit_Framework_MockObject_MockObject */ - private $globalStoragesService; - /** @var BackendService|\PHPUnit_Framework_MockObject_MockObject */ - private $backendService; - /** @var GlobalAuth|\PHPUnit_Framework_MockObject_MockObject */ - private $globalAuth; + private IManager&MockObject $encryptionManager; + private GlobalStoragesService&MockObject $globalStoragesService; + private BackendService&MockObject $backendService; + private GlobalAuth&MockObject $globalAuth; + private Admin $admin; - public function setUp() { + protected function setUp(): void { parent::setUp(); $this->encryptionManager = $this->createMock(IManager::class); $this->globalStoragesService = $this->createMock(GlobalStoragesService::class); @@ -58,7 +39,7 @@ class AdminTest extends TestCase { ); } - public function testGetForm() { + public function testGetForm(): void { $this->encryptionManager ->expects($this->once()) ->method('isEnabled') @@ -89,25 +70,25 @@ class AdminTest extends TestCase { ->with('') ->willReturn('asdf:asdf'); $params = [ - 'encryptionEnabled' => false, - 'visibilityType' => BackendService::VISIBILITY_ADMIN, - 'storages' => ['a', 'b', 'c'], - 'backends' => ['d', 'e', 'f'], - 'authMechanisms' => ['g', 'h', 'i'], - 'dependencies' => \OC_Mount_Config::dependencyMessage($this->backendService->getBackends()), - 'allowUserMounting' => true, - 'globalCredentials' => 'asdf:asdf', + 'encryptionEnabled' => false, + 'visibilityType' => BackendService::VISIBILITY_ADMIN, + 'storages' => ['a', 'b', 'c'], + 'backends' => ['d', 'e', 'f'], + 'authMechanisms' => ['g', 'h', 'i'], + 'dependencies' => MountConfig::dependencyMessage($this->backendService->getBackends()), + 'allowUserMounting' => true, + 'globalCredentials' => 'asdf:asdf', 'globalCredentialsUid' => '', ]; $expected = new TemplateResponse('files_external', 'settings', $params, ''); $this->assertEquals($expected, $this->admin->getForm()); } - public function testGetSection() { + public function testGetSection(): void { $this->assertSame('externalstorages', $this->admin->getSection()); } - public function testGetPriority() { + public function testGetPriority(): void { $this->assertSame(40, $this->admin->getPriority()); } } diff --git a/apps/files_external/tests/Settings/SectionTest.php b/apps/files_external/tests/Settings/SectionTest.php index b83f8f0feef..c64849ff7ba 100644 --- a/apps/files_external/tests/Settings/SectionTest.php +++ b/apps/files_external/tests/Settings/SectionTest.php @@ -1,46 +1,27 @@ <?php + +declare(strict_types=1); /** - * @copyright Copyright (c) 2016 Lukas Reschke <lukas@statuscode.ch> - * - * @author Lukas Reschke <lukas@statuscode.ch> - * @author Morris Jobke <hey@morrisjobke.de> - * - * @license GNU AGPL version 3 or any later version - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see <http://www.gnu.org/licenses/>. - * + * SPDX-FileCopyrightText: 2016 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: AGPL-3.0-or-later */ - namespace OCA\Files_External\Tests\Settings; use OCA\Files_External\Settings\Section; use OCP\IL10N; use OCP\IURLGenerator; +use PHPUnit\Framework\MockObject\MockObject; use Test\TestCase; class SectionTest extends TestCase { - /** @var IL10N */ - private $l; - /** @var IURLGenerator */ - private $urlGenerator; - /** @var Section */ - private $section; + private IL10N&MockObject $l; + private IURLGenerator&MockObject $urlGenerator; + private Section $section; - public function setUp() { + protected function setUp(): void { parent::setUp(); - $this->urlGenerator = $this->getMockBuilder(IURLGenerator::class)->disableOriginalConstructor()->getMock(); - $this->l = $this->getMockBuilder(IL10N::class)->disableOriginalConstructor()->getMock(); + $this->urlGenerator = $this->createMock(IURLGenerator::class); + $this->l = $this->createMock(IL10N::class); $this->section = new Section( $this->urlGenerator, @@ -48,21 +29,21 @@ class SectionTest extends TestCase { ); } - public function testGetID() { + public function testGetID(): void { $this->assertSame('externalstorages', $this->section->getID()); } - public function testGetName() { + public function testGetName(): void { $this->l ->expects($this->once()) ->method('t') - ->with('External storages') - ->willReturn('External storages'); + ->with('External storage') + ->willReturn('External storage'); - $this->assertSame('External storages', $this->section->getName()); + $this->assertSame('External storage', $this->section->getName()); } - public function testGetPriority() { + public function testGetPriority(): void { $this->assertSame(10, $this->section->getPriority()); } } diff --git a/apps/files_external/tests/Storage/Amazons3MultiPartTest.php b/apps/files_external/tests/Storage/Amazons3MultiPartTest.php new file mode 100644 index 00000000000..aa3925899f3 --- /dev/null +++ b/apps/files_external/tests/Storage/Amazons3MultiPartTest.php @@ -0,0 +1,49 @@ +<?php + +declare(strict_types=1); +/** + * SPDX-FileCopyrightText: 2023 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: AGPL-3.0-or-later + */ +namespace OCA\Files_External\Tests\Storage; + +use OCA\Files_External\Lib\Storage\AmazonS3; + +/** + * Class Amazons3Test + * + * @group DB + * @group S3 + * + * @package OCA\Files_External\Tests\Storage + */ +class Amazons3MultiPartTest extends \Test\Files\Storage\Storage { + private $config; + /** @var AmazonS3 */ + protected $instance; + + protected function setUp(): void { + parent::setUp(); + + $this->config = include('files_external/tests/config.amazons3.php'); + if (!is_array($this->config) || !$this->config['run']) { + $this->markTestSkipped('AmazonS3 backend not configured'); + } + $this->instance = new AmazonS3($this->config + [ + 'putSizeLimit' => 1, + 'copySizeLimit' => 1, + ]); + } + + protected function tearDown(): void { + if ($this->instance) { + $this->instance->rmdir(''); + } + + parent::tearDown(); + } + + public function testStat(): void { + $this->markTestSkipped('S3 doesn\'t update the parents folder mtime'); + } +} diff --git a/apps/files_external/tests/Storage/Amazons3Test.php b/apps/files_external/tests/Storage/Amazons3Test.php index ce616ca175f..d02dec0230c 100644 --- a/apps/files_external/tests/Storage/Amazons3Test.php +++ b/apps/files_external/tests/Storage/Amazons3Test.php @@ -1,56 +1,39 @@ <?php + +declare(strict_types=1); /** - * @copyright Copyright (c) 2016, ownCloud, Inc. - * - * @author Joas Schilling <coding@schilljs.com> - * @author Michael Gapczynski <GapczynskiM@gmail.com> - * @author Morris Jobke <hey@morrisjobke.de> - * @author Robin Appelman <robin@icewind.nl> - * @author Robin McCorkell <robin@mccorkell.me.uk> - * @author Thomas Müller <thomas.mueller@tmit.eu> - * - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see <http://www.gnu.org/licenses/> - * + * SPDX-FileCopyrightText: 2019-2024 Nextcloud GmbH and Nextcloud contributors + * SPDX-FileCopyrightText: 2016 ownCloud, Inc. + * SPDX-License-Identifier: AGPL-3.0-only */ - namespace OCA\Files_External\Tests\Storage; -use \OCA\Files_External\Lib\Storage\AmazonS3; +use OCA\Files_External\Lib\Storage\AmazonS3; /** * Class Amazons3Test * * @group DB + * @group S3 * * @package OCA\Files_External\Tests\Storage */ class Amazons3Test extends \Test\Files\Storage\Storage { + protected $config; + /** @var AmazonS3 */ + protected $instance; - private $config; - - protected function setUp() { + protected function setUp(): void { parent::setUp(); $this->config = include('files_external/tests/config.amazons3.php'); - if ( ! is_array($this->config) or ! $this->config['run']) { + if (!is_array($this->config) || !$this->config['run']) { $this->markTestSkipped('AmazonS3 backend not configured'); } $this->instance = new AmazonS3($this->config); } - protected function tearDown() { + protected function tearDown(): void { if ($this->instance) { $this->instance->rmdir(''); } @@ -58,7 +41,7 @@ class Amazons3Test extends \Test\Files\Storage\Storage { parent::tearDown(); } - public function testStat() { + public function testStat(): void { $this->markTestSkipped('S3 doesn\'t update the parents folder mtime'); } } diff --git a/apps/files_external/tests/Storage/FtpTest.php b/apps/files_external/tests/Storage/FtpTest.php index 5b56becb4ad..095a5236049 100644 --- a/apps/files_external/tests/Storage/FtpTest.php +++ b/apps/files_external/tests/Storage/FtpTest.php @@ -1,34 +1,14 @@ <?php + +declare(strict_types=1); /** - * @copyright Copyright (c) 2016, ownCloud, Inc. - * - * @author Joas Schilling <coding@schilljs.com> - * @author Jörn Friedrich Dreyer <jfd@butonic.de> - * @author Morris Jobke <hey@morrisjobke.de> - * @author Robin Appelman <robin@icewind.nl> - * @author Robin McCorkell <robin@mccorkell.me.uk> - * @author Thomas Müller <thomas.mueller@tmit.eu> - * @author Vincent Petry <pvince81@owncloud.com> - * - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see <http://www.gnu.org/licenses/> - * + * SPDX-FileCopyrightText: 2019-2024 Nextcloud GmbH and Nextcloud contributors + * SPDX-FileCopyrightText: 2016 ownCloud, Inc. + * SPDX-License-Identifier: AGPL-3.0-only */ - namespace OCA\Files_External\Tests\Storage; -use \OCA\Files_External\Lib\Storage\FTP; +use OCA\Files_External\Lib\Storage\FTP; /** * Class FtpTest @@ -40,58 +20,71 @@ use \OCA\Files_External\Lib\Storage\FTP; class FtpTest extends \Test\Files\Storage\Storage { private $config; - protected function setUp() { + protected function setUp(): void { parent::setUp(); $id = $this->getUniqueID(); $this->config = include('files_external/tests/config.ftp.php'); - if ( ! is_array($this->config) or ! $this->config['run']) { + if (! is_array($this->config) or ! $this->config['run']) { $this->markTestSkipped('FTP backend not configured'); } + $rootInstance = new FTP($this->config); + $rootInstance->mkdir($id); + $this->config['root'] .= '/' . $id; //make sure we have an new empty folder to work in $this->instance = new FTP($this->config); - $this->instance->mkdir('/'); } - protected function tearDown() { + protected function tearDown(): void { if ($this->instance) { - \OCP\Files::rmdirr($this->instance->constructUrl('')); + $this->instance->rmdir(''); } + $this->instance = null; parent::tearDown(); } - public function testConstructUrl(){ - $config = array ( 'host' => 'localhost', - 'user' => 'ftp', - 'password' => 'ftp', - 'root' => '/', - 'secure' => false ); - $instance = new FTP($config); - $this->assertEquals('ftp://ftp:ftp@localhost/', $instance->constructUrl('')); - - $config['secure'] = true; - $instance = new FTP($config); - $this->assertEquals('ftps://ftp:ftp@localhost/', $instance->constructUrl('')); - - $config['secure'] = 'false'; - $instance = new FTP($config); - $this->assertEquals('ftp://ftp:ftp@localhost/', $instance->constructUrl('')); - - $config['secure'] = 'true'; - $instance = new FTP($config); - $this->assertEquals('ftps://ftp:ftp@localhost/', $instance->constructUrl('')); - - $config['root'] = ''; - $instance = new FTP($config); - $this->assertEquals('ftps://ftp:ftp@localhost/somefile.txt', $instance->constructUrl('somefile.txt')); - - $config['root'] = '/abc'; - $instance = new FTP($config); - $this->assertEquals('ftps://ftp:ftp@localhost/abc/somefile.txt', $instance->constructUrl('somefile.txt')); - - $config['root'] = '/abc/'; - $instance = new FTP($config); - $this->assertEquals('ftps://ftp:ftp@localhost/abc/somefile.txt', $instance->constructUrl('somefile.txt')); + /** + * ftp has no proper way to handle spaces at the end of file names + */ + public static function directoryProvider(): array { + return array_filter(parent::directoryProvider(), function ($item) { + return substr($item[0], -1) !== ' '; + }); + } + + + /** + * mtime for folders is only with a minute resolution + */ + public function testStat(): void { + $textFile = \OC::$SERVERROOT . '/tests/data/lorem.txt'; + $ctimeStart = time(); + $this->instance->file_put_contents('/lorem.txt', file_get_contents($textFile)); + $this->assertTrue($this->instance->isReadable('/lorem.txt')); + $ctimeEnd = time(); + $mTime = $this->instance->filemtime('/lorem.txt'); + $this->assertTrue($this->instance->hasUpdated('/lorem.txt', $ctimeStart - 5)); + $this->assertTrue($this->instance->hasUpdated('/', $ctimeStart - 61)); + + // check that ($ctimeStart - 5) <= $mTime <= ($ctimeEnd + 1) + $this->assertGreaterThanOrEqual(($ctimeStart - 5), $mTime); + $this->assertLessThanOrEqual(($ctimeEnd + 1), $mTime); + $this->assertEquals(filesize($textFile), $this->instance->filesize('/lorem.txt')); + + $stat = $this->instance->stat('/lorem.txt'); + //only size and mtime are required in the result + $this->assertEquals($stat['size'], $this->instance->filesize('/lorem.txt')); + $this->assertEquals($stat['mtime'], $mTime); + + if ($this->instance->touch('/lorem.txt', 100) !== false) { + $mTime = $this->instance->filemtime('/lorem.txt'); + $this->assertEquals($mTime, 100); + } + + $mtimeStart = time(); + + $this->instance->unlink('/lorem.txt'); + $this->assertTrue($this->instance->hasUpdated('/', $mtimeStart - 61)); } } diff --git a/apps/files_external/tests/Storage/OwncloudTest.php b/apps/files_external/tests/Storage/OwncloudTest.php index f1564304e2f..ab6cd443dba 100644 --- a/apps/files_external/tests/Storage/OwncloudTest.php +++ b/apps/files_external/tests/Storage/OwncloudTest.php @@ -1,32 +1,14 @@ <?php + +declare(strict_types=1); /** - * @copyright Copyright (c) 2016, ownCloud, Inc. - * - * @author Joas Schilling <coding@schilljs.com> - * @author Morris Jobke <hey@morrisjobke.de> - * @author Robin McCorkell <robin@mccorkell.me.uk> - * @author Thomas Müller <thomas.mueller@tmit.eu> - * @author Vincent Petry <pvince81@owncloud.com> - * - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see <http://www.gnu.org/licenses/> - * + * SPDX-FileCopyrightText: 2017-2024 Nextcloud GmbH and Nextcloud contributors + * SPDX-FileCopyrightText: 2016 ownCloud, Inc. + * SPDX-License-Identifier: AGPL-3.0-only */ - namespace OCA\Files_External\Tests\Storage; -use \OCA\Files_External\Lib\Storage\OwnCloud; +use OCA\Files_External\Lib\Storage\OwnCloud; /** * Class OwnCloudTest @@ -36,15 +18,14 @@ use \OCA\Files_External\Lib\Storage\OwnCloud; * @package OCA\Files_External\Tests\Storage */ class OwncloudTest extends \Test\Files\Storage\Storage { - private $config; - protected function setUp() { + protected function setUp(): void { parent::setUp(); $id = $this->getUniqueID(); $this->config = include('files_external/tests/config.php'); - if ( ! is_array($this->config) or ! isset($this->config['owncloud']) or ! $this->config['owncloud']['run']) { + if (! is_array($this->config) or ! isset($this->config['owncloud']) or ! $this->config['owncloud']['run']) { $this->markTestSkipped('Nextcloud backend not configured'); } $this->config['owncloud']['root'] .= '/' . $id; //make sure we have an new empty folder to work in @@ -52,7 +33,7 @@ class OwncloudTest extends \Test\Files\Storage\Storage { $this->instance->mkdir('/'); } - protected function tearDown() { + protected function tearDown(): void { if ($this->instance) { $this->instance->rmdir('/'); } diff --git a/apps/files_external/tests/Storage/SFTP_KeyTest.php b/apps/files_external/tests/Storage/SFTP_KeyTest.php index 6cd62309e68..17e2087f91b 100644 --- a/apps/files_external/tests/Storage/SFTP_KeyTest.php +++ b/apps/files_external/tests/Storage/SFTP_KeyTest.php @@ -1,32 +1,14 @@ <?php + +declare(strict_types=1); /** - * @copyright Copyright (c) 2016, ownCloud, Inc. - * - * @author Morris Jobke <hey@morrisjobke.de> - * @author Robin McCorkell <robin@mccorkell.me.uk> - * @author Ross Nicoll <jrn@jrn.me.uk> - * @author Thomas Müller <thomas.mueller@tmit.eu> - * @author Viktor Szépe <viktor@szepe.net> - * - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see <http://www.gnu.org/licenses/> - * + * SPDX-FileCopyrightText: 2019-2024 Nextcloud GmbH and Nextcloud contributors + * SPDX-FileCopyrightText: 2016 ownCloud, Inc. + * SPDX-License-Identifier: AGPL-3.0-only */ - namespace OCA\Files_External\Tests\Storage; -use \OCA\Files_External\Lib\Storage\SFTP_Key; +use OCA\Files_External\Lib\Storage\SFTP_Key; /** * Class SFTP_KeyTest @@ -38,12 +20,12 @@ use \OCA\Files_External\Lib\Storage\SFTP_Key; class SFTP_KeyTest extends \Test\Files\Storage\Storage { private $config; - protected function setUp() { + protected function setUp(): void { parent::setUp(); $id = $this->getUniqueID(); $this->config = include('files_external/tests/config.php'); - if ( ! is_array($this->config) or ! isset($this->config['sftp_key']) or ! $this->config['sftp_key']['run']) { + if (! is_array($this->config) or ! isset($this->config['sftp_key']) or ! $this->config['sftp_key']['run']) { $this->markTestSkipped('SFTP with key backend not configured'); } // Make sure we have an new empty folder to work in @@ -52,7 +34,7 @@ class SFTP_KeyTest extends \Test\Files\Storage\Storage { $this->instance->mkdir('/'); } - protected function tearDown() { + protected function tearDown(): void { if ($this->instance) { $this->instance->rmdir('/'); } @@ -60,40 +42,40 @@ class SFTP_KeyTest extends \Test\Files\Storage\Storage { parent::tearDown(); } - /** - * @expectedException InvalidArgumentException - */ - public function testInvalidAddressShouldThrowException() { + + public function testInvalidAddressShouldThrowException(): void { + $this->expectException(\InvalidArgumentException::class); + // I'd use example.com for this, but someone decided to break the spec and make it resolve $this->instance->assertHostAddressValid('notarealaddress...'); } - public function testValidAddressShouldPass() { + public function testValidAddressShouldPass(): void { $this->assertTrue($this->instance->assertHostAddressValid('localhost')); } - /** - * @expectedException InvalidArgumentException - */ - public function testNegativePortNumberShouldThrowException() { + + public function testNegativePortNumberShouldThrowException(): void { + $this->expectException(\InvalidArgumentException::class); + $this->instance->assertPortNumberValid('-1'); } - /** - * @expectedException InvalidArgumentException - */ - public function testNonNumericalPortNumberShouldThrowException() { + + public function testNonNumericalPortNumberShouldThrowException(): void { + $this->expectException(\InvalidArgumentException::class); + $this->instance->assertPortNumberValid('a'); } - /** - * @expectedException InvalidArgumentException - */ - public function testHighPortNumberShouldThrowException() { + + public function testHighPortNumberShouldThrowException(): void { + $this->expectException(\InvalidArgumentException::class); + $this->instance->assertPortNumberValid('65536'); } - public function testValidPortNumberShouldPass() { + public function testValidPortNumberShouldPass(): void { $this->assertTrue($this->instance->assertPortNumberValid('22222')); } } diff --git a/apps/files_external/tests/Storage/SftpTest.php b/apps/files_external/tests/Storage/SftpTest.php index 85b2eec057f..ebfc8ab3c1f 100644 --- a/apps/files_external/tests/Storage/SftpTest.php +++ b/apps/files_external/tests/Storage/SftpTest.php @@ -1,34 +1,14 @@ <?php + +declare(strict_types=1); /** - * @copyright Copyright (c) 2016, ownCloud, Inc. - * - * @author hkjolhede <hkjolhede@gmail.com> - * @author Joas Schilling <coding@schilljs.com> - * @author Morris Jobke <hey@morrisjobke.de> - * @author Robin Appelman <robin@icewind.nl> - * @author Robin McCorkell <robin@mccorkell.me.uk> - * @author Thomas Müller <thomas.mueller@tmit.eu> - * @author Vincent Petry <pvince81@owncloud.com> - * - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see <http://www.gnu.org/licenses/> - * + * SPDX-FileCopyrightText: 2019-2024 Nextcloud GmbH and Nextcloud contributors + * SPDX-FileCopyrightText: 2016 ownCloud, Inc. + * SPDX-License-Identifier: AGPL-3.0-only */ - namespace OCA\Files_External\Tests\Storage; -use \OCA\Files_External\Lib\Storage\SFTP; +use OCA\Files_External\Lib\Storage\SFTP; /** * Class SftpTest @@ -45,7 +25,7 @@ class SftpTest extends \Test\Files\Storage\Storage { private $config; - protected function setUp() { + protected function setUp(): void { parent::setUp(); $id = $this->getUniqueID(); @@ -58,7 +38,7 @@ class SftpTest extends \Test\Files\Storage\Storage { $this->instance->mkdir('/'); } - protected function tearDown() { + protected function tearDown(): void { if ($this->instance) { $this->instance->rmdir('/'); } @@ -66,15 +46,13 @@ class SftpTest extends \Test\Files\Storage\Storage { parent::tearDown(); } - /** - * @dataProvider configProvider - */ - public function testStorageId($config, $expectedStorageId) { + #[\PHPUnit\Framework\Attributes\DataProvider('configProvider')] + public function testStorageId($config, $expectedStorageId): void { $instance = new SFTP($config); $this->assertEquals($expectedStorageId, $instance->getId()); } - public function configProvider() { + public static function configProvider(): array { return [ [ // no root path diff --git a/apps/files_external/tests/Storage/SmbTest.php b/apps/files_external/tests/Storage/SmbTest.php index edacb498d5e..afcb5c1034f 100644 --- a/apps/files_external/tests/Storage/SmbTest.php +++ b/apps/files_external/tests/Storage/SmbTest.php @@ -1,37 +1,18 @@ <?php + +declare(strict_types=1); /** - * @copyright Copyright (c) 2016, ownCloud, Inc. - * - * @author Joas Schilling <coding@schilljs.com> - * @author Juan Pablo Villafáñez <jvillafanez@solidgear.es> - * @author Morris Jobke <hey@morrisjobke.de> - * @author Robin Appelman <robin@icewind.nl> - * @author Robin McCorkell <robin@mccorkell.me.uk> - * @author Thomas Müller <thomas.mueller@tmit.eu> - * @author Vincent Petry <pvince81@owncloud.com> - * - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see <http://www.gnu.org/licenses/> - * + * SPDX-FileCopyrightText: 2017-2024 Nextcloud GmbH and Nextcloud contributors + * SPDX-FileCopyrightText: 2016 ownCloud, Inc. + * SPDX-License-Identifier: AGPL-3.0-only */ - namespace OCA\Files_External\Tests\Storage; use OC\Files\Notify\Change; use OC\Files\Notify\RenameChange; -use \OCA\Files_External\Lib\Storage\SMB; +use OCA\Files_External\Lib\Storage\SMB; use OCP\Files\Notify\IChange; +use PHPUnit\Framework\ExpectationFailedException; /** * Class SmbTest @@ -46,7 +27,7 @@ class SmbTest extends \Test\Files\Storage\Storage { */ protected $instance; - protected function setUp() { + protected function setUp(): void { parent::setUp(); $id = $this->getUniqueID(); @@ -62,7 +43,7 @@ class SmbTest extends \Test\Files\Storage\Storage { $this->instance->mkdir('/'); } - protected function tearDown() { + protected function tearDown(): void { if ($this->instance) { $this->instance->rmdir(''); } @@ -70,19 +51,19 @@ class SmbTest extends \Test\Files\Storage\Storage { parent::tearDown(); } - public function directoryProvider() { + public static function directoryProvider(): array { // doesn't support leading/trailing spaces - return array(array('folder')); + return [['folder']]; } - public function testRenameWithSpaces() { + public function testRenameWithSpaces(): void { $this->instance->mkdir('with spaces'); $result = $this->instance->rename('with spaces', 'foo bar'); $this->assertTrue($result); $this->assertTrue($this->instance->is_dir('foo bar')); } - public function testStorageId() { + public function testStorageId(): void { $this->instance = new SMB([ 'host' => 'testhost', 'user' => 'testuser', @@ -94,29 +75,64 @@ class SmbTest extends \Test\Files\Storage\Storage { $this->instance = null; } - public function testNotifyGetChanges() { + public function testNotifyGetChanges(): void { + $lastError = null; + for ($i = 0; $i < 5; $i++) { + try { + $this->tryTestNotifyGetChanges(); + return; + } catch (ExpectationFailedException $e) { + $lastError = $e; + $this->tearDown(); + $this->setUp(); + sleep(1); + } + } + throw $lastError; + } + + private function tryTestNotifyGetChanges(): void { $notifyHandler = $this->instance->notify(''); - usleep(100 * 1000); //give time for the notify to start + sleep(1); //give time for the notify to start $this->instance->file_put_contents('/newfile.txt', 'test content'); + sleep(1); $this->instance->rename('/newfile.txt', 'renamed.txt'); + sleep(1); $this->instance->unlink('/renamed.txt'); - usleep(100 * 1000); //time for all changes to be processed - - $changes = $notifyHandler->getChanges(); + sleep(1); //time for all changes to be processed + + /** @var IChange[] $changes */ + $changes = []; + $count = 0; + // wait up to 10 seconds for incoming changes + while (count($changes) < 3 && $count < 10) { + $changes = array_merge($changes, $notifyHandler->getChanges()); + $count++; + sleep(1); + } $notifyHandler->stop(); - $expected = [ - new Change(IChange::ADDED, 'newfile.txt'), - new RenameChange(IChange::RENAMED, 'newfile.txt', 'renamed.txt'), - new Change(IChange::REMOVED, 'renamed.txt') - ]; + // depending on the server environment, the initial create might be detected as a change instead + if ($changes[0]->getType() === IChange::MODIFIED) { + $expected = [ + new Change(IChange::MODIFIED, 'newfile.txt'), + new RenameChange(IChange::RENAMED, 'newfile.txt', 'renamed.txt'), + new Change(IChange::REMOVED, 'renamed.txt') + ]; + } else { + $expected = [ + new Change(IChange::ADDED, 'newfile.txt'), + new RenameChange(IChange::RENAMED, 'newfile.txt', 'renamed.txt'), + new Change(IChange::REMOVED, 'renamed.txt') + ]; + } foreach ($expected as $expectedChange) { - $this->assertContains($expectedChange, $changes, '', false, false); // dont check object identity + $this->assertTrue(in_array($expectedChange, $changes), "Expected changes are:\n" . print_r($expected, true) . PHP_EOL . 'Expected to find: ' . PHP_EOL . print_r($expectedChange, true) . "\nGot:\n" . print_r($changes, true)); } } - public function testNotifyListen() { + public function testNotifyListen(): void { $notifyHandler = $this->instance->notify(''); usleep(100 * 1000); //give time for the notify to start $this->instance->file_put_contents('/newfile.txt', 'test content'); @@ -125,16 +141,21 @@ class SmbTest extends \Test\Files\Storage\Storage { $result = null; - // since the notify handler buffers untill we start listening we will get the above changes + // since the notify handler buffers until we start listening we will get the above changes $notifyHandler->listen(function (IChange $change) use (&$result) { $result = $change; return false;//stop listening }); - $this->assertEquals(new Change(IChange::ADDED, 'newfile.txt'), $result); + // depending on the server environment, the initial create might be detected as a change instead + if ($result->getType() === IChange::ADDED) { + $this->assertEquals(new Change(IChange::ADDED, 'newfile.txt'), $result); + } else { + $this->assertEquals(new Change(IChange::MODIFIED, 'newfile.txt'), $result); + } } - public function testRenameRoot() { + public function testRenameRoot(): void { // root can't be renamed $this->assertFalse($this->instance->rename('', 'foo1')); @@ -143,12 +164,12 @@ class SmbTest extends \Test\Files\Storage\Storage { $this->instance->rmdir('foo2'); } - public function testUnlinkRoot() { + public function testUnlinkRoot(): void { // root can't be deleted $this->assertFalse($this->instance->unlink('')); } - public function testRmdirRoot() { + public function testRmdirRoot(): void { // root can't be deleted $this->assertFalse($this->instance->rmdir('')); } diff --git a/apps/files_external/tests/Storage/SwiftTest.php b/apps/files_external/tests/Storage/SwiftTest.php index 19f185ed033..17037e76ee3 100644 --- a/apps/files_external/tests/Storage/SwiftTest.php +++ b/apps/files_external/tests/Storage/SwiftTest.php @@ -1,33 +1,15 @@ <?php + +declare(strict_types=1); /** - * @copyright Copyright (c) 2016, ownCloud, Inc. - * - * @author Christian Berendt <berendt@b1-systems.de> - * @author Joas Schilling <coding@schilljs.com> - * @author Morris Jobke <hey@morrisjobke.de> - * @author Robin Appelman <robin@icewind.nl> - * @author Robin McCorkell <robin@mccorkell.me.uk> - * @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: 2018-2024 Nextcloud GmbH and Nextcloud contributors + * SPDX-FileCopyrightText: 2016 ownCloud, Inc. + * SPDX-License-Identifier: AGPL-3.0-only */ - namespace OCA\Files_External\Tests\Storage; -use \OCA\Files_External\Lib\Storage\Swift; +use GuzzleHttp\Exception\ClientException; +use OCA\Files_External\Lib\Storage\Swift; /** * Class SwiftTest @@ -37,10 +19,14 @@ use \OCA\Files_External\Lib\Storage\Swift; * @package OCA\Files_External\Tests\Storage */ class SwiftTest extends \Test\Files\Storage\Storage { - private $config; - protected function setUp() { + /** + * @var Swift instance + */ + protected $instance; + + protected function setUp(): void { parent::setUp(); $this->config = include('files_external/tests/config.swift.php'); @@ -50,20 +36,18 @@ class SwiftTest extends \Test\Files\Storage\Storage { $this->instance = new Swift($this->config); } - protected function tearDown() { + protected function tearDown(): void { if ($this->instance) { try { - $connection = $this->instance->getConnection(); - $container = $connection->getContainer($this->config['bucket']); + $container = $this->instance->getContainer(); - $objects = $container->objectList(); - while($object = $objects->next()) { - $object->setName(str_replace('#','%23',$object->getName())); + $objects = $container->listObjects(); + foreach ($objects as $object) { $object->delete(); } $container->delete(); - } catch (\Guzzle\Http\Exception\ClientErrorResponseException $e) { + } catch (ClientException $e) { // container didn't exist, so we don't need to delete it } } @@ -71,7 +55,7 @@ class SwiftTest extends \Test\Files\Storage\Storage { parent::tearDown(); } - public function testStat() { + public function testStat(): void { $this->markTestSkipped('Swift doesn\'t update the parents folder mtime'); } } diff --git a/apps/files_external/tests/Storage/VersionedAmazonS3Test.php b/apps/files_external/tests/Storage/VersionedAmazonS3Test.php new file mode 100644 index 00000000000..9d413620292 --- /dev/null +++ b/apps/files_external/tests/Storage/VersionedAmazonS3Test.php @@ -0,0 +1,37 @@ +<?php + +declare(strict_types=1); +/** + * SPDX-FileCopyrightText: 2021 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: AGPL-3.0-or-later + */ + +namespace OCA\Files_External\Tests\Storage; + +/** + * @group DB + * @group S3 + */ +class VersionedAmazonS3Test extends Amazons3Test { + protected function setUp(): void { + parent::setUp(); + try { + $this->instance->getConnection()->putBucketVersioning([ + 'Bucket' => $this->instance->getBucket(), + 'VersioningConfiguration' => [ + 'Status' => 'Enabled', + ], + ]); + } catch (\Exception $e) { + $this->markTestSkipped("s3 backend doesn't seem to support versioning"); + } + } + + public function testCopyOverWriteDirectory(): void { + if (isset($this->config['minio'])) { + $this->markTestSkipped('MinIO has a bug with batch deletion on versioned storages, see https://github.com/minio/minio/issues/21366'); + } + + parent::testCopyOverWriteDirectory(); + } +} diff --git a/apps/files_external/tests/Storage/WebdavTest.php b/apps/files_external/tests/Storage/WebdavTest.php index b007ded2662..a8de178effd 100644 --- a/apps/files_external/tests/Storage/WebdavTest.php +++ b/apps/files_external/tests/Storage/WebdavTest.php @@ -1,34 +1,17 @@ <?php + +declare(strict_types=1); /** - * @copyright Copyright (c) 2016, ownCloud, Inc. - * - * @author Joas Schilling <coding@schilljs.com> - * @author Morris Jobke <hey@morrisjobke.de> - * @author Robin Appelman <robin@icewind.nl> - * @author Robin McCorkell <robin@mccorkell.me.uk> - * @author Thomas Müller <thomas.mueller@tmit.eu> - * @author Vincent Petry <pvince81@owncloud.com> - * - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see <http://www.gnu.org/licenses/> - * + * SPDX-FileCopyrightText: 2017-2024 Nextcloud GmbH and Nextcloud contributors + * SPDX-FileCopyrightText: 2016 ownCloud, Inc. + * SPDX-License-Identifier: AGPL-3.0-only */ - namespace OCA\Files_External\Tests\Storage; -use \OC\Files\Storage\DAV; +use OC\Files\Storage\DAV; use OC\Files\Type\Detection; +use OCP\Files\IMimeTypeDetector; +use OCP\Server; /** * Class WebdavTest @@ -38,8 +21,7 @@ use OC\Files\Type\Detection; * @package OCA\Files_External\Tests\Storage */ class WebdavTest extends \Test\Files\Storage\Storage { - - protected function setUp() { + protected function setUp(): void { parent::setUp(); $id = $this->getUniqueID(); @@ -55,7 +37,7 @@ class WebdavTest extends \Test\Files\Storage\Storage { $this->instance->mkdir('/'); } - protected function tearDown() { + protected function tearDown(): void { if ($this->instance) { $this->instance->rmdir('/'); } @@ -63,11 +45,11 @@ class WebdavTest extends \Test\Files\Storage\Storage { parent::tearDown(); } - public function testMimetypeFallback() { + public function testMimetypeFallback(): void { $this->instance->file_put_contents('foo.bar', 'asd'); /** @var Detection $mimeDetector */ - $mimeDetector = \OC::$server->getMimeTypeDetector(); + $mimeDetector = Server::get(IMimeTypeDetector::class); $mimeDetector->registerType('bar', 'application/x-bar'); $this->assertEquals('application/x-bar', $this->instance->getMimeType('foo.bar')); diff --git a/apps/files_external/tests/StorageConfigTest.php b/apps/files_external/tests/StorageConfigTest.php index 37bb27bf510..b3024cb228c 100644 --- a/apps/files_external/tests/StorageConfigTest.php +++ b/apps/files_external/tests/StorageConfigTest.php @@ -1,29 +1,11 @@ <?php + +declare(strict_types=1); /** - * @copyright Copyright (c) 2016, ownCloud, Inc. - * - * @author Joas Schilling <coding@schilljs.com> - * @author Lukas Reschke <lukas@statuscode.ch> - * @author Morris Jobke <hey@morrisjobke.de> - * @author Robin McCorkell <robin@mccorkell.me.uk> - * @author Vincent Petry <pvince81@owncloud.com> - * - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see <http://www.gnu.org/licenses/> - * + * SPDX-FileCopyrightText: 2017-2024 Nextcloud GmbH and Nextcloud contributors + * SPDX-FileCopyrightText: 2016 ownCloud, Inc. + * SPDX-License-Identifier: AGPL-3.0-only */ - namespace OCA\Files_External\Tests; use OCA\Files_External\Lib\Auth\AuthMechanism; @@ -32,14 +14,9 @@ use OCA\Files_External\Lib\DefinitionParameter; use OCA\Files_External\Lib\StorageConfig; class StorageConfigTest extends \Test\TestCase { - - public function testJsonSerialization() { - $backend = $this->getMockBuilder(Backend::class) - ->disableOriginalConstructor() - ->getMock(); - $parameter = $this->getMockBuilder(DefinitionParameter::class) - ->disableOriginalConstructor() - ->getMock(); + public function testJsonSerialization(): void { + $backend = $this->createMock(Backend::class); + $parameter = $this->createMock(DefinitionParameter::class); $parameter ->expects($this->once()) ->method('getType') @@ -51,9 +28,7 @@ class StorageConfigTest extends \Test\TestCase { $backend->method('getIdentifier') ->willReturn('storage::identifier'); - $authMech = $this->getMockBuilder(AuthMechanism::class) - ->disableOriginalConstructor() - ->getMock(); + $authMech = $this->createMock(AuthMechanism::class); $authMech->method('getIdentifier') ->willReturn('auth::identifier'); @@ -81,5 +56,4 @@ class StorageConfigTest extends \Test\TestCase { $this->assertSame(['group1', 'group2'], $json['applicableGroups']); $this->assertSame(['preview' => false], $json['mountOptions']); } - } diff --git a/apps/files_external/tests/appSpec.js b/apps/files_external/tests/appSpec.js deleted file mode 100644 index 43902d1c1d0..00000000000 --- a/apps/files_external/tests/appSpec.js +++ /dev/null @@ -1,99 +0,0 @@ -/** -* ownCloud -* -* @author Vincent Petry -* @copyright 2014 Vincent Petry <pvince81@owncloud.com> -* -* This library is free software; you can redistribute it and/or -* modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE -* License as published by the Free Software Foundation; either -* version 3 of the License, or any later version. -* -* This library 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 library. If not, see <http://www.gnu.org/licenses/>. -* -*/ - -describe('OCA.External.App tests', function() { - var App = OCA.External.App; - var fileList; - - beforeEach(function() { - $('#testArea').append( - '<div id="app-navigation">' + - '<ul><li data-id="files"><a>Files</a></li>' + - '<li data-id="sharingin"><a></a></li>' + - '<li data-id="sharingout"><a></a></li>' + - '</ul></div>' + - '<div id="app-content">' + - '<div id="app-content-files" class="hidden">' + - '</div>' + - '<div id="app-content-extstoragemounts" class="hidden">' + - '</div>' + - '</div>' + - '</div>' - ); - fileList = App.initList($('#app-content-extstoragemounts')); - }); - afterEach(function() { - App.fileList = null; - fileList.destroy(); - fileList = null; - }); - - describe('initialization', function() { - it('inits external mounts list on show', function() { - expect(App.fileList).toBeDefined(); - }); - }); - describe('file actions', function() { - it('provides default file actions', function() { - var fileActions = fileList.fileActions; - - expect(fileActions.actions.all).toBeDefined(); - expect(fileActions.actions.all.Delete).toBeDefined(); - expect(fileActions.actions.all.Rename).toBeDefined(); - expect(fileActions.actions.all.Download).toBeDefined(); - - expect(fileActions.defaults.dir).toEqual('Open'); - }); - it('redirects to files app when opening a directory', function() { - var oldList = OCA.Files.App.fileList; - // dummy new list to make sure it exists - OCA.Files.App.fileList = new OCA.Files.FileList($('<table><thead></thead><tbody></tbody></table>')); - - var setActiveViewStub = sinon.stub(OCA.Files.App, 'setActiveView'); - // create dummy table so we can click the dom - var $table = '<table><thead></thead><tbody id="fileList"></tbody></table>'; - $('#app-content-extstoragemounts').append($table); - - App._inFileList = null; - fileList = App.initList($('#app-content-extstoragemounts')); - - fileList.setFiles([{ - name: 'testdir', - type: 'dir', - path: '/somewhere/inside/subdir', - counterParts: ['user2'], - shareOwner: 'user2' - }]); - - fileList.findFileEl('testdir').find('td a.name').click(); - - expect(OCA.Files.App.fileList.getCurrentDirectory()).toEqual('/somewhere/inside/subdir/testdir'); - - expect(setActiveViewStub.calledOnce).toEqual(true); - expect(setActiveViewStub.calledWith('files')).toEqual(true); - - setActiveViewStub.restore(); - - // restore old list - OCA.Files.App.fileList = oldList; - }); - }); -}); diff --git a/apps/files_external/tests/config.php b/apps/files_external/tests/config.php index 6cdd7691dda..ec860cf05a4 100644 --- a/apps/files_external/tests/config.php +++ b/apps/files_external/tests/config.php @@ -1,29 +1,9 @@ <?php + /** - * @copyright Copyright (c) 2016, ownCloud, Inc. - * - * @author Christian Berendt <berendt@b1-systems.de> - * @author hkjolhede <hkjolhede@gmail.com> - * @author Michael Gapczynski <GapczynskiM@gmail.com> - * @author Robin Appelman <robin@icewind.nl> - * @author Ross Nicoll <jrn@jrn.me.uk> - * @author Thomas Müller <thomas.mueller@tmit.eu> - * @author Vincent Petry <pvince81@owncloud.com> - * - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see <http://www.gnu.org/licenses/> - * + * SPDX-FileCopyrightText: 2017-2024 Nextcloud GmbH and Nextcloud contributors + * SPDX-FileCopyrightText: 2012-2016 ownCloud, Inc. + * SPDX-License-Identifier: AGPL-3.0-only */ // in case there are private configurations in the users home -> use them $privateConfigFile = $_SERVER['HOME'] . '/owncloud-extfs-test-config.php'; @@ -33,33 +13,33 @@ if (file_exists($privateConfigFile)) { } // this is now more a template now for your private configurations -return array( - 'ftp'=>array( - 'run'=>false, - 'host'=>'localhost', - 'user'=>'test', - 'password'=>'test', - 'root'=>'/test', - ), - 'webdav'=>array( - 'run'=>false, - 'host'=>'localhost', - 'user'=>'test', - 'password'=>'test', - 'root'=>'', +return [ + 'ftp' => [ + 'run' => false, + 'host' => 'localhost', + 'user' => 'test', + 'password' => 'test', + 'root' => '/test', + ], + 'webdav' => [ + 'run' => false, + 'host' => 'localhost', + 'user' => 'test', + 'password' => 'test', + 'root' => '', // wait delay in seconds after write operations // (only in tests) // set to higher value for lighttpd webdav - 'wait'=> 0 - ), - 'owncloud'=>array( - 'run'=>false, - 'host'=>'localhost/owncloud', - 'user'=>'test', - 'password'=>'test', - 'root'=>'', - ), - 'swift' => array( + 'wait' => 0 + ], + 'owncloud' => [ + 'run' => false, + 'host' => 'localhost/owncloud', + 'user' => 'test', + 'password' => 'test', + 'root' => '', + ], + 'swift' => [ 'run' => false, 'user' => 'test', 'bucket' => 'test', @@ -70,40 +50,40 @@ return array( //'service_name' => 'swift', //should be 'swift' for OpenStack Object Storage and 'cloudFiles' for Rackspace Cloud Files (default value) //'url' => 'https://identity.api.rackspacecloud.com/v2.0/', //to be used with Rackspace Cloud Files and OpenStack Object Storage //'timeout' => 5 // timeout of HTTP requests in seconds - ), - 'smb'=>array( - 'run'=>false, - 'user'=>'test', - 'password'=>'test', - 'host'=>'localhost', - 'share'=>'/test', - 'root'=>'/test/', - ), - 'amazons3'=>array( - 'run'=>false, - 'key'=>'test', - 'secret'=>'test', - 'bucket'=>'bucket' + ], + 'smb' => [ + 'run' => false, + 'user' => 'test', + 'password' => 'test', + 'host' => 'localhost', + 'share' => '/test', + 'root' => '/test/', + ], + 'amazons3' => [ + 'run' => false, + 'key' => 'test', + 'secret' => 'test', + 'bucket' => 'bucket' //'hostname' => 'your.host.name', //'port' => '443', //'use_ssl' => 'true', //'region' => 'eu-west-1', //'test'=>'true', //'timeout'=>20 - ), - 'sftp' => array ( - 'run'=>false, - 'host'=>'localhost', - 'user'=>'test', - 'password'=>'test', - 'root'=>'/test' - ), - 'sftp_key' => array ( - 'run'=>false, - 'host'=>'localhost', - 'user'=>'test', - 'public_key'=>'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAAAgQDJPTvz3OLonF2KSGEKP/nd4CPmRYvemG2T4rIiNYjDj0U5y+2sKEWbjiUlQl2bsqYuVoJ+/UNJlGQbbZ08kQirFeo1GoWBzqioaTjUJfbLN6TzVVKXxR9YIVmH7Ajg2iEeGCndGgbmnPfj+kF9TR9IH8vMVvtubQwf7uEwB0ALhw== phpseclib-generated-key', - 'private_key'=>'test', - 'root'=>'/test' - ), -); + ], + 'sftp' => [ + 'run' => false, + 'host' => 'localhost', + 'user' => 'test', + 'password' => 'test', + 'root' => '/test' + ], + 'sftp_key' => [ + 'run' => false, + 'host' => 'localhost', + 'user' => 'test', + 'public_key' => 'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAAAgQDJPTvz3OLonF2KSGEKP/nd4CPmRYvemG2T4rIiNYjDj0U5y+2sKEWbjiUlQl2bsqYuVoJ+/UNJlGQbbZ08kQirFeo1GoWBzqioaTjUJfbLN6TzVVKXxR9YIVmH7Ajg2iEeGCndGgbmnPfj+kF9TR9IH8vMVvtubQwf7uEwB0ALhw== phpseclib-generated-key', + 'private_key' => 'test', + 'root' => '/test' + ], +]; diff --git a/apps/files_external/tests/env/start-amazons3-ceph.sh b/apps/files_external/tests/env/start-amazons3-ceph.sh index 1aa14ac990d..ecaa6e0ff46 100755 --- a/apps/files_external/tests/env/start-amazons3-ceph.sh +++ b/apps/files_external/tests/env/start-amazons3-ceph.sh @@ -1,6 +1,7 @@ #!/usr/bin/env bash # -# ownCloud +# SPDX-FileCopyrightText: 2015-2016 ownCloud, Inc. +# SPDX-License-Identifier: AGPL-3.0-only # # This script start a docker container to test the files_external tests # against. It will also change the files_external config to use the docker @@ -8,9 +9,6 @@ # # Set environment variable DEBUG to print config file # -# @author Morris Jobke -# @author Robin McCorkell -# @copyright 2015 ownCloud if ! command -v docker >/dev/null 2>&1; then echo "No docker executable found - skipped docker setup" diff --git a/apps/files_external/tests/env/start-ftp-morrisjobke.sh b/apps/files_external/tests/env/start-ftp-morrisjobke.sh index 3a5f6ffcb67..3074bedce74 100755 --- a/apps/files_external/tests/env/start-ftp-morrisjobke.sh +++ b/apps/files_external/tests/env/start-ftp-morrisjobke.sh @@ -1,6 +1,7 @@ #!/usr/bin/env bash # -# ownCloud +# SPDX-FileCopyrightText: 2015-2016 ownCloud, Inc. +# SPDX-License-Identifier: AGPL-3.0-only # # This script start a docker container to test the files_external tests # against. It will also change the files_external config to use the docker @@ -8,9 +9,6 @@ # # Set environment variable DEBUG to print config file # -# @author Morris Jobke -# @copyright 2015 Morris Jobke <hey@morrisjobke.de> -# if ! command -v docker >/dev/null 2>&1; then echo "No docker executable found - skipped docker setup" diff --git a/apps/files_external/tests/env/start-sftp-atmoz.sh b/apps/files_external/tests/env/start-sftp-atmoz.sh index 0fc0c5c427f..9d444515a8a 100755 --- a/apps/files_external/tests/env/start-sftp-atmoz.sh +++ b/apps/files_external/tests/env/start-sftp-atmoz.sh @@ -1,6 +1,7 @@ #!/usr/bin/env bash # -# ownCloud +# SPDX-FileCopyrightText: 2015 ownCloud, Inc. +# SPDX-License-Identifier: AGPL-3.0-only # # This script start a docker container to test the files_external tests # against. It will also change the files_external config to use the docker @@ -8,9 +9,6 @@ # # Set environment variable DEBUG to print config file # -# @author Morris Jobke -# @copyright 2015 Morris Jobke <hey@morrisjobke.de> -# if ! command -v docker >/dev/null 2>&1; then echo "No docker executable found - skipped docker setup" diff --git a/apps/files_external/tests/env/start-smb-linux.sh b/apps/files_external/tests/env/start-smb-linux.sh index 173dd25ebb9..ca303b521f4 100755 --- a/apps/files_external/tests/env/start-smb-linux.sh +++ b/apps/files_external/tests/env/start-smb-linux.sh @@ -1,6 +1,7 @@ #!/usr/bin/env bash # -# ownCloud +# SPDX-FileCopyrightText: 2016 Nextcloud GmbH and Nextcloud contributors +# SPDX-License-Identifier: AGPL-3.0-or-later # # This script start a docker container to test the files_external tests # against. It will also change the files_external config to use the docker @@ -8,9 +9,6 @@ # # Set environment variable DEBUG to print config file # -# @author Morris Jobke -# @copyright 2015 Morris Jobke <hey@morrisjobke.de> -# # retrieve current folder to place the config in the parent folder thisFolder=`echo $0 | sed 's#env/start-smb-linux\.sh##'` diff --git a/apps/files_external/tests/env/start-smb-windows.sh b/apps/files_external/tests/env/start-smb-windows.sh index a23c879dd96..3c5570a2f80 100755 --- a/apps/files_external/tests/env/start-smb-windows.sh +++ b/apps/files_external/tests/env/start-smb-windows.sh @@ -1,12 +1,10 @@ #!/usr/bin/env bash # -# ownCloud +# SPDX-FileCopyrightText: 2015 ownCloud, Inc. +# SPDX-License-Identifier: AGPL-3.0-only # # Set environment variable DEBUG to print config file # -# @author Thomas Müller -# @copyright 2015 Thomas Müller <deepdiver@owncloud.com> -# # retrieve current folder to place the config in the parent folder thisFolder=`echo $0 | sed 's#env/start-smb-windows\.sh##'` diff --git a/apps/files_external/tests/env/start-swift-ceph.sh b/apps/files_external/tests/env/start-swift-ceph.sh index 3a299a6fa85..c646b9eef28 100755 --- a/apps/files_external/tests/env/start-swift-ceph.sh +++ b/apps/files_external/tests/env/start-swift-ceph.sh @@ -1,6 +1,7 @@ #!/bin/bash # -# ownCloud +# SPDX-FileCopyrightText: 2015-2016 ownCloud, Inc. +# SPDX-License-Identifier: AGPL-3.0-only # # This script start a docker container to test the files_external tests # against. It will also change the files_external config to use the docker @@ -8,9 +9,6 @@ # # Set environment variable DEBUG to print config file # -# @author Morris Jobke -# @author Robin McCorkell -# @copyright 2015 ownCloud if ! command -v docker >/dev/null 2>&1; then echo "No docker executable found - skipped docker setup" diff --git a/apps/files_external/tests/env/start-webdav-apache.sh b/apps/files_external/tests/env/start-webdav-apache.sh index a5464c9cfab..517f278a366 100755 --- a/apps/files_external/tests/env/start-webdav-apache.sh +++ b/apps/files_external/tests/env/start-webdav-apache.sh @@ -1,6 +1,8 @@ #!/bin/bash # -# ownCloud +# SPDX-FileCopyrightText: 2017-2024 Nextcloud GmbH and Nextcloud contributors +# SPDX-FileCopyrightText: 2015 ownCloud, Inc. +# SPDX-License-Identifier: AGPL-3.0-only # # This script start a docker container to test the files_external tests # against. It will also change the files_external config to use the docker @@ -11,10 +13,6 @@ # # Set environment variable DEBUG to print config file # -# @author Morris Jobke -# @copyright 2014 Morris Jobke <hey@morrisjobke.de> -# @copyright 2016 Vincent Petry <pvince81@owncloud.com> -# if ! command -v docker >/dev/null 2>&1; then echo "No docker executable found - skipped docker setup" @@ -23,8 +21,8 @@ fi echo "Docker executable found - setup docker" -echo "Fetch recent morrisjobke/webdav docker image" -docker pull morrisjobke/webdav +echo "Fetch recent webdav docker image" +docker pull ghcr.io/nextcloud/continuous-integration-webdav-apache:latest # retrieve current folder to place the config in the parent folder thisFolder=`echo $0 | sed 's#env/start-webdav-apache\.sh##'` @@ -45,7 +43,7 @@ if [ -n "$RUN_DOCKER_MYSQL" ]; then parameter="--link $containerName:db" fi -container=`docker run -P $parameter -d -e USERNAME=test -e PASSWORD=test morrisjobke/webdav` +container=`docker run -P $parameter -d --rm ghcr.io/nextcloud/continuous-integration-webdav-apache:latest` host=`docker inspect --format="{{.NetworkSettings.IPAddress}}" $container` echo -n "Waiting for Apache initialization on ${host}:${port}" @@ -64,7 +62,7 @@ return array( 'run'=>true, 'host'=>'${host}:80/webdav/', 'user'=>'test', - 'password'=>'test', + 'password'=>'pass', 'root'=>'', // wait delay in seconds after write operations // (only in tests) diff --git a/apps/files_external/tests/env/start-webdav-apachedrone.sh b/apps/files_external/tests/env/start-webdav-apachedrone.sh deleted file mode 100755 index 9887cea5eee..00000000000 --- a/apps/files_external/tests/env/start-webdav-apachedrone.sh +++ /dev/null @@ -1,26 +0,0 @@ -#!/usr/bin/env bash -# -# Nextcloud -# - -# retrieve current folder to place the config in the parent folder -thisFolder=`echo $0 | sed 's#env/start-webdav-apachedrone\.sh##'` - -if [ -z "$thisFolder" ]; then - thisFolder="." -fi; - -cat > $thisFolder/config.webdav.php <<DELIM -<?php - -return array( - 'run'=>true, - 'host'=>'127.0.0.1:80/webdav/', - 'user'=>'test', - 'password'=>'pass', - 'root'=>'', - 'wait'=> 0 -); - -DELIM - diff --git a/apps/files_external/tests/env/start-webdav-ownCloud.sh b/apps/files_external/tests/env/start-webdav-ownCloud.sh index 870bd5bcdf8..9d833330205 100755 --- a/apps/files_external/tests/env/start-webdav-ownCloud.sh +++ b/apps/files_external/tests/env/start-webdav-ownCloud.sh @@ -1,6 +1,10 @@ #!/usr/bin/env bash # -# ownCloud +#!/bin/bash +# +# SPDX-FileCopyrightText: 2017 Nextcloud GmbH and Nextcloud contributors +# SPDX-FileCopyrightText: 2014-2015 ownCloud, Inc. +# SPDX-License-Identifier: AGPL-3.0-only # # This script start a docker container to test the files_external tests # against. It will also change the files_external config to use the docker @@ -11,9 +15,6 @@ # # Set environment variable DEBUG to print config file # -# @author Morris Jobke -# @copyright 2014 Morris Jobke <hey@morrisjobke.de> -# if ! command -v docker >/dev/null 2>&1; then echo "No docker executable found - skipped docker setup" diff --git a/apps/files_external/tests/env/stop-amazons3-ceph.sh b/apps/files_external/tests/env/stop-amazons3-ceph.sh index f559f8f9058..5e7aac5d5e7 100755 --- a/apps/files_external/tests/env/stop-amazons3-ceph.sh +++ b/apps/files_external/tests/env/stop-amazons3-ceph.sh @@ -1,13 +1,11 @@ #!/usr/bin/env bash # -# ownCloud +# SPDX-FileCopyrightText: 2015-2016 ownCloud, Inc. +# SPDX-License-Identifier: AGPL-3.0-only # # This script stops the docker container the files_external tests were run # against. It will also revert the config changes done in start step. # -# @author Morris Jobke -# @author Robin McCorkell -# @copyright 2015 ownCloud if ! command -v docker >/dev/null 2>&1; then echo "No docker executable found - skipped docker stop" diff --git a/apps/files_external/tests/env/stop-ftp-morrisjobke.sh b/apps/files_external/tests/env/stop-ftp-morrisjobke.sh index eedf8f82a50..cb6c8ee9d94 100755 --- a/apps/files_external/tests/env/stop-ftp-morrisjobke.sh +++ b/apps/files_external/tests/env/stop-ftp-morrisjobke.sh @@ -1,13 +1,11 @@ #!/usr/bin/env bash # -# ownCloud +# SPDX-FileCopyrightText: 2015-2016 ownCloud, Inc. +# SPDX-License-Identifier: AGPL-3.0-only # # This script stops the docker container the files_external tests were run # against. It will also revert the config changes done in start step. # -# @author Morris Jobke -# @copyright 2015 Morris Jobke <hey@morrisjobke.de> -# if ! command -v docker >/dev/null 2>&1; then echo "No docker executable found - skipped docker stop" diff --git a/apps/files_external/tests/env/stop-sftp-atmoz.sh b/apps/files_external/tests/env/stop-sftp-atmoz.sh index 44380152340..0dcdcebf96d 100755 --- a/apps/files_external/tests/env/stop-sftp-atmoz.sh +++ b/apps/files_external/tests/env/stop-sftp-atmoz.sh @@ -1,13 +1,11 @@ #!/usr/bin/env bash # -# ownCloud +# SPDX-FileCopyrightText: 2015-2016 ownCloud, Inc. +# SPDX-License-Identifier: AGPL-3.0-only # # This script stops the docker container the files_external tests were run # against. It will also revert the config changes done in start step. # -# @author Morris Jobke -# @copyright 2015 Morris Jobke <hey@morrisjobke.de> -# if ! command -v docker >/dev/null 2>&1; then echo "No docker executable found - skipped docker stop" diff --git a/apps/files_external/tests/env/stop-smb-linux.sh b/apps/files_external/tests/env/stop-smb-linux.sh index 434d3e166b1..dd9e78d2811 100755 --- a/apps/files_external/tests/env/stop-smb-linux.sh +++ b/apps/files_external/tests/env/stop-smb-linux.sh @@ -1,13 +1,11 @@ #!/usr/bin/env bash # -# ownCloud +# SPDX-FileCopyrightText: 2016 Nextcloud GmbH and Nextcloud contributors +# SPDX-License-Identifier: AGPL-3.0-or-later # # This script stops the docker container the files_external tests were run # against. It will also revert the config changes done in start step. # -# @author Morris Jobke -# @copyright 2015 Morris Jobke <hey@morrisjobke.de> -# # retrieve current folder to remove the config from the parent folder thisFolder=`echo $0 | sed 's#env/stop-smb-linux\.sh##'` diff --git a/apps/files_external/tests/env/stop-smb-windows.sh b/apps/files_external/tests/env/stop-smb-windows.sh index 39c49e2c505..268b531e145 100755 --- a/apps/files_external/tests/env/stop-smb-windows.sh +++ b/apps/files_external/tests/env/stop-smb-windows.sh @@ -1,9 +1,7 @@ #!/usr/bin/env bash # -# ownCloud -# -# @author Thomas Müller -# @copyright 2015 Thomas Müller <deepdiver@owncloud.com> +# SPDX-FileCopyrightText: 2015 ownCloud, Inc. +# SPDX-License-Identifier: AGPL-3.0-only # # retrieve current folder to remove the config from the parent folder diff --git a/apps/files_external/tests/env/stop-swift-ceph.sh b/apps/files_external/tests/env/stop-swift-ceph.sh index 418f96e63f6..d23ca2f13dc 100755 --- a/apps/files_external/tests/env/stop-swift-ceph.sh +++ b/apps/files_external/tests/env/stop-swift-ceph.sh @@ -1,13 +1,11 @@ #!/bin/bash # -# ownCloud +# SPDX-FileCopyrightText: 2015-2016 ownCloud, Inc. +# SPDX-License-Identifier: AGPL-3.0-only # # This script stops the docker container the files_external tests were run # against. It will also revert the config changes done in start step. # -# @author Morris Jobke -# @author Robin McCorkell -# @copyright 2015 ownCloud if ! command -v docker >/dev/null 2>&1; then echo "No docker executable found - skipped docker stop" diff --git a/apps/files_external/tests/env/stop-webdav-apache.sh b/apps/files_external/tests/env/stop-webdav-apache.sh index e898a65cc36..825f39470b1 100755 --- a/apps/files_external/tests/env/stop-webdav-apache.sh +++ b/apps/files_external/tests/env/stop-webdav-apache.sh @@ -1,13 +1,7 @@ #!/bin/bash # -# ownCloud -# -# This script stops the docker container the files_external tests were run -# against. It will also revert the config changes done in start step. -# -# @author Morris Jobke -# @copyright 2014 Morris Jobke <hey@morrisjobke.de> -# @copyright 2016 Vincent Petry <pvince81@owncloud.com> +# SPDX-FileCopyrightText: 2015-2016 ownCloud, Inc. +# SPDX-License-Identifier: AGPL-3.0-only # if ! command -v docker >/dev/null 2>&1; then diff --git a/apps/files_external/tests/env/stop-webdav-apachedrone.sh b/apps/files_external/tests/env/stop-webdav-apachedrone.sh deleted file mode 100755 index 3c4b0492dd0..00000000000 --- a/apps/files_external/tests/env/stop-webdav-apachedrone.sh +++ /dev/null @@ -1,14 +0,0 @@ -#!/usr/bin/env bash -# -# Nextcloud - -# retrieve current folder to remove the config from the parent folder -thisFolder=`echo $0 | sed 's#env/stop-webdav-apachedrone\.sh##'` - -if [ -z "$thisFolder" ]; then - thisFolder="." -fi; - -# cleanup -rm $thisFolder/config.webdav.php - diff --git a/apps/files_external/tests/env/stop-webdav-ownCloud.sh b/apps/files_external/tests/env/stop-webdav-ownCloud.sh index 613a22efb8c..140e7cce23b 100755 --- a/apps/files_external/tests/env/stop-webdav-ownCloud.sh +++ b/apps/files_external/tests/env/stop-webdav-ownCloud.sh @@ -1,12 +1,7 @@ #!/usr/bin/env bash # -# ownCloud -# -# This script stops the docker container the files_external tests were run -# against. It will also revert the config changes done in start step. -# -# @author Morris Jobke -# @copyright 2014 Morris Jobke <hey@morrisjobke.de> +# SPDX-FileCopyrightText: 2014-2016 ownCloud, Inc. +# SPDX-License-Identifier: AGPL-3.0-only # if ! command -v docker >/dev/null 2>&1; then diff --git a/apps/files_external/tests/env/wait-for-connection b/apps/files_external/tests/env/wait-for-connection index 2c480fb733e..a3ff5591122 100755 --- a/apps/files_external/tests/env/wait-for-connection +++ b/apps/files_external/tests/env/wait-for-connection @@ -1,6 +1,11 @@ #!/usr/bin/php <?php +/** + * SPDX-FileCopyrightText: 2015 ownCloud, Inc. + * SPDX-License-Identifier: AGPL-3.0-only + */ + $timeout = 60; switch ($argc) { diff --git a/apps/files_external/tests/js/mountsfilelistSpec.js b/apps/files_external/tests/js/mountsfilelistSpec.js deleted file mode 100644 index c7ea819d2fe..00000000000 --- a/apps/files_external/tests/js/mountsfilelistSpec.js +++ /dev/null @@ -1,152 +0,0 @@ -/* - * Copyright (c) 2014 Vincent Petry <pvince81@owncloud.com> - * - * This file is licensed under the Affero General Public License version 3 - * or later. - * - * See the COPYING-README file. - * - */ - -describe('OCA.External.FileList tests', function() { - var testFiles, alertStub, notificationStub, fileList; - - beforeEach(function() { - alertStub = sinon.stub(OC.dialogs, 'alert'); - notificationStub = sinon.stub(OC.Notification, 'show'); - - // init parameters and test table elements - $('#testArea').append( - '<div id="app-content-container">' + - // init horrible parameters - '<input type="hidden" id="dir" value="/"></input>' + - '<input type="hidden" id="permissions" value="31"></input>' + - // dummy controls - '<div id="controls">' + - ' <div class="actions creatable"></div>' + - ' <div class="notCreatable"></div>' + - '</div>' + - // dummy table - // TODO: at some point this will be rendered by the fileList class itself! - '<table id="filestable">' + - '<thead><tr>' + - '<th id="headerName" class="hidden column-name">' + - ' <div id="headerName-container">' + - ' <a class="name sort columntitle" data-sort="name"><span>Name</span><span class="sort-indicator"></span></a>' + - ' </div>' + - '</th>' + - '<th id="headerBackend" class="hidden column-backend">' + - ' <a class="backend sort columntitle" data-sort="backend"><span>Storage type</span><span class="sort-indicator"></span></a>' + - '</th>' + - '<th id="headerScope" class="hidden column-scope column-last">' + - ' <a class="scope sort columntitle" data-sort="scope"><span>Scope</span><span class="sort-indicator"></span></a>' + - '</th>' + - '</tr></thead>' + - '<tbody id="fileList"></tbody>' + - '<tfoot></tfoot>' + - '</table>' + - '<div id="emptycontent">Empty content message</div>' + - '</div>' - ); - }); - afterEach(function() { - testFiles = undefined; - fileList.destroy(); - fileList = undefined; - - notificationStub.restore(); - alertStub.restore(); - }); - - describe('loading file list for external storages', function() { - var ocsResponse; - - beforeEach(function() { - fileList = new OCA.External.FileList( - $('#app-content-container') - ); - - fileList.reload(); - - /* jshint camelcase: false */ - ocsResponse = { - ocs: { - meta: { - status: 'ok', - statuscode: 100, - message: null - }, - data: [{ - name: 'smb mount', - path: '/mount points', - type: 'dir', - backend: 'SMB', - scope: 'personal', - permissions: OC.PERMISSION_READ | OC.PERMISSION_DELETE - }, { - name: 'sftp mount', - path: '/another mount points', - type: 'dir', - backend: 'SFTP', - scope: 'system', - permissions: OC.PERMISSION_READ - }] - } - }; - }); - it('render storage list', function() { - var request; - var $rows; - var $tr; - - expect(fakeServer.requests.length).toEqual(1); - request = fakeServer.requests[0]; - expect(request.url).toEqual( - OC.linkToOCS('apps/files_external/api/v1') + - 'mounts?format=json' - ); - - fakeServer.requests[0].respond( - 200, - { 'Content-Type': 'application/json' }, - JSON.stringify(ocsResponse) - ); - - $rows = fileList.$el.find('tbody tr'); - expect($rows.length).toEqual(2); - - $tr = $rows.eq(0); - expect($tr.attr('data-id')).not.toBeDefined(); - expect($tr.attr('data-type')).toEqual('dir'); - expect($tr.attr('data-file')).toEqual('sftp mount'); - expect($tr.attr('data-path')).toEqual('/another mount points'); - expect($tr.attr('data-size')).not.toBeDefined(); - expect($tr.attr('data-permissions')).toEqual('1'); // read only - expect($tr.find('a.name').attr('href')).toEqual( - OC.webroot + - '/index.php/apps/files' + - '?dir=/another%20mount%20points/sftp%20mount' - ); - expect($tr.find('.nametext').text().trim()).toEqual('sftp mount'); - expect($tr.find('.column-scope > span').text().trim()).toEqual('System'); - expect($tr.find('.column-backend').text().trim()).toEqual('SFTP'); - - $tr = $rows.eq(1); - expect($tr.attr('data-id')).not.toBeDefined(); - expect($tr.attr('data-type')).toEqual('dir'); - expect($tr.attr('data-file')).toEqual('smb mount'); - expect($tr.attr('data-path')).toEqual('/mount points'); - expect($tr.attr('data-size')).not.toBeDefined(); - expect($tr.attr('data-permissions')).toEqual('9'); // read and delete - expect($tr.find('a.name').attr('href')).toEqual( - OC.webroot + - '/index.php/apps/files' + - '?dir=/mount%20points/smb%20mount' - ); - expect($tr.find('.nametext').text().trim()).toEqual('smb mount'); - expect($tr.find('.column-scope > span').text().trim()).toEqual('Personal'); - expect($tr.find('.column-backend').text().trim()).toEqual('SMB'); - - }); - }); -}); diff --git a/apps/files_external/tests/js/settingsSpec.js b/apps/files_external/tests/js/settingsSpec.js deleted file mode 100644 index d6b96a47189..00000000000 --- a/apps/files_external/tests/js/settingsSpec.js +++ /dev/null @@ -1,383 +0,0 @@ -/* - * Copyright (c) 2015 Vincent Petry <pvince81@owncloud.com> - * - * This file is licensed under the Affero General Public License version 3 - * or later. - * - * See the COPYING-README file. - * - */ - -describe('OCA.External.Settings tests', function() { - var clock; - var select2Stub; - var select2ApplicableUsers; - - beforeEach(function() { - clock = sinon.useFakeTimers(); - select2Stub = sinon.stub($.fn, 'select2').callsFake(function(args) { - if (args === 'val') { - return select2ApplicableUsers; - } - return { - on: function() {} - }; - }); - - // view still requires an existing DOM table - $('#testArea').append( - '<table id="externalStorage" data-admin="true">' + - '<thead></thead>' + - '<tbody>' + - '<tr id="addMountPoint" data-id="">' + - '<td class="status"></td>' + - '<td class="mountPoint"><input type="text" name="mountPoint"/></td>' + - '<td class="backend">' + - '<select class="selectBackend">' + - '<option disable selected>Add storage</option>' + - '<option value="\\OC\\TestBackend">Test Backend</option>' + - '<option value="\\OC\\AnotherTestBackend">Another Test Backend</option>' + - '<option value="\\OC\\InputsTestBackend">Inputs test backend</option>' + - '</select>' + - '</td>' + - '<td class="authentication"></td>' + - '<td class="configuration"></td>' + - '<td class="applicable">' + - '<input type="hidden" class="applicableUsers">' + - '</td>' + - '<td class="mountOptionsToggle"><input type="hidden" class="mountOptions"/><img class="svg action"/></td>' + - '<td class="remove"><img alt="Delete" title="Delete" class="svg action"/></td>' + - '<td class="save"><img alt="Save" title="Save" class="svg action"/></td>' + - '</tr>' + - '</tbody>' + - '</table>' - ); - // these are usually appended into the data attribute - // within the DOM by the server template - $('#externalStorage .selectBackend:first').data('configurations', { - '\\OC\\TestBackend': { - 'identifier': '\\OC\\TestBackend', - 'name': 'Test Backend', - 'configuration': { - 'field1': { - 'value': 'Display Name 1' - }, - 'field2': { - 'value': 'Display Name 2', - 'flags': 1 - } - }, - 'authSchemes': { - 'builtin': true, - }, - 'priority': 11 - }, - '\\OC\\AnotherTestBackend': { - 'identifier': '\\OC\\AnotherTestBackend', - 'name': 'Another Test Backend', - 'configuration': { - 'field1': { - 'value': 'Display Name 1' - }, - 'field2': { - 'value': 'Display Name 2', - 'flags': 1 - } - }, - 'authSchemes': { - 'builtin': true, - }, - 'priority': 12 - }, - '\\OC\\InputsTestBackend': { - 'identifier': '\\OC\\InputsTestBackend', - 'name': 'Inputs test backend', - 'configuration': { - 'field_text': { - 'value': 'Text field' - }, - 'field_password': { - 'value': ',Password field', - 'type': 2 - }, - 'field_bool': { - 'value': 'Boolean field', - 'type': 1 - }, - 'field_hidden': { - 'value': 'Hidden field', - 'type': 3 - }, - 'field_text_optional': { - 'value': 'Text field optional', - 'flags': 1 - }, - 'field_password_optional': { - 'value': 'Password field optional', - 'flags': 1, - 'type': 2 - } - }, - 'authSchemes': { - 'builtin': true, - }, - 'priority': 13 - } - } - ); - - $('#externalStorage #addMountPoint .authentication:first').data('mechanisms', { - 'mechanism1': { - 'identifier': 'mechanism1', - 'name': 'Mechanism 1', - 'configuration': { - }, - 'scheme': 'builtin', - 'visibility': 3 - }, - }); - - }); - afterEach(function() { - select2Stub.restore(); - clock.restore(); - }); - - describe('storage configuration', function() { - var view; - - function selectBackend(backendName) { - view.$el.find('.selectBackend:first').val(backendName).trigger('change'); - } - - beforeEach(function() { - var $el = $('#externalStorage'); - view = new OCA.External.Settings.MountConfigListView($el, {encryptionEnabled: false}); - }); - afterEach(function() { - view = null; - }); - describe('selecting backend', function() { - it('populates the row and creates a new empty one', function() { - var $firstRow = view.$el.find('tr:first'); - selectBackend('\\OC\\TestBackend'); - expect($firstRow.find('.backend').text()).toEqual('Test Backend'); - expect($firstRow.find('.selectBackend').length).toEqual(0); - - // TODO: check "remove" button visibility - - // the suggested mount point name - expect($firstRow.find('[name=mountPoint]').val()).toEqual('TestBackend'); - - // TODO: check that the options have been created - - // TODO: check select2 call on the ".applicableUsers" element - - var $emptyRow = $firstRow.next('tr'); - expect($emptyRow.length).toEqual(1); - expect($emptyRow.find('.selectBackend').length).toEqual(1); - expect($emptyRow.find('.applicable select').length).toEqual(0); - - // TODO: check "remove" button visibility - }); - it('shows row even if selection row is hidden', function() { - view.$el.find('tr#addMountPoint').hide(); - selectBackend('\\OC\\TestBackend'); - expect(view.$el.find('tr:first').is(':visible')).toBe(true); - expect(view.$el.find('tr#addMountPoint').is(':visible')).toBe(false); - }); - // TODO: test with personal mounts (no applicable fields) - // TODO: test suggested mount point logic - }); - describe('saving storages', function() { - var $tr; - - beforeEach(function() { - $tr = view.$el.find('tr:first'); - selectBackend('\\OC\\TestBackend'); - }); - it('saves storage after clicking the save button', function() { - var $field1 = $tr.find('input[data-parameter=field1]'); - expect($field1.length).toEqual(1); - $field1.val('test'); - $field1.trigger(new $.Event('keyup', {keyCode: 97})); - - var $mountOptionsField = $tr.find('input.mountOptions'); - expect($mountOptionsField.length).toEqual(1); - $mountOptionsField.val(JSON.stringify({previews:true})); - - var $saveButton = $tr.find('td.save img'); - $saveButton.click(); - - expect(fakeServer.requests.length).toEqual(1); - var request = fakeServer.requests[0]; - expect(request.url).toEqual(OC.webroot + '/index.php/apps/files_external/globalstorages'); - expect(JSON.parse(request.requestBody)).toEqual({ - backend: '\\OC\\TestBackend', - authMechanism: 'mechanism1', - backendOptions: { - 'field1': 'test', - 'field2': '' - }, - mountPoint: 'TestBackend', - priority: 11, - applicableUsers: [], - applicableGroups: [], - mountOptions: { - 'previews': true - }, - testOnly: true - }); - - // TODO: respond and check data-id - }); - it('saves storage after closing mount options dropdown', function() { - $tr.find('.mountOptionsToggle img').click(); - $tr.find('[name=previews]').trigger(new $.Event('keyup', {keyCode: 97})); - $tr.find('input[data-parameter=field1]').val('test'); - - // does not save inside the dropdown - expect(fakeServer.requests.length).toEqual(0); - - $('body').mouseup(); - - // but after closing the dropdown - expect(fakeServer.requests.length).toEqual(1); - }); - // TODO: status indicator - }); - describe('validate storage configuration', function() { - var $tr; - - beforeEach(function() { - $tr = view.$el.find('tr:first'); - selectBackend('\\OC\\InputsTestBackend'); - }); - - it('lists missing fields in storage errors', function() { - var storage = view.getStorageConfig($tr); - - expect(storage.errors).toEqual({ - backendOptions: ['field_text', 'field_password'] - }); - }); - - it('highlights missing non-optional fields', function() { - _.each([ - 'field_text', - 'field_password' - ], function(param) { - expect($tr.find('input[data-parameter='+param+']').hasClass('warning-input')).toBe(true); - }); - _.each([ - 'field_bool', - 'field_hidden', - 'field_text_optional', - 'field_password_optional' - ], function(param) { - expect($tr.find('input[data-parameter='+param+']').hasClass('warning-input')).toBe(false); - }); - }); - - it('validates correct storage', function() { - $tr.find('[name=mountPoint]').val('mountpoint'); - - $tr.find('input[data-parameter=field_text]').val('foo'); - $tr.find('input[data-parameter=field_password]').val('bar'); - $tr.find('input[data-parameter=field_text_optional]').val('foobar'); - // don't set field_password_optional - $tr.find('input[data-parameter=field_hidden]').val('baz'); - - var storage = view.getStorageConfig($tr); - - expect(storage.validate()).toBe(true); - }); - - it('checks missing mount point', function() { - $tr.find('[name=mountPoint]').val(''); - - $tr.find('input[data-parameter=field_text]').val('foo'); - $tr.find('input[data-parameter=field_password]').val('bar'); - - var storage = view.getStorageConfig($tr); - - expect(storage.validate()).toBe(false); - }); - }); - describe('update storage', function() { - // TODO - }); - describe('delete storage', function() { - // TODO - }); - describe('recheck storages', function() { - // TODO - }); - describe('mount options dropdown', function() { - var $tr; - var $td; - - beforeEach(function() { - $tr = view.$el.find('tr:first'); - $td = $tr.find('.mountOptionsToggle'); - selectBackend('\\OC\\TestBackend'); - }); - - it('shows dropdown when clicking on toggle button, hides when clicking outside', function() { - $td.find('img').click(); - - expect($td.find('.dropdown').length).toEqual(1); - - $('body').mouseup(); - - expect($td.find('.dropdown').length).toEqual(0); - }); - - it('doesnt show the encryption option when encryption is disabled', function () { - view._encryptionEnabled = false; - $td.find('img').click(); - - expect($td.find('.dropdown [name=encrypt]:visible').length).toEqual(0); - - $('body').mouseup(); - - expect($td.find('.dropdown').length).toEqual(0); - }); - - it('reads config from mountOptions field', function() { - $tr.find('input.mountOptions').val(JSON.stringify({previews:false})); - - $td.find('img').click(); - expect($td.find('.dropdown [name=previews]').prop('checked')).toEqual(false); - $('body').mouseup(); - - $tr.find('input.mountOptions').val(JSON.stringify({previews:true})); - $td.find('img').click(); - expect($td.find('.dropdown [name=previews]').prop('checked')).toEqual(true); - }); - - it('writes config into mountOptions field', function() { - $td.find('img').click(); - // defaults to true - var $field = $td.find('.dropdown [name=previews]'); - expect($field.prop('checked')).toEqual(true); - $td.find('.dropdown [name=filesystem_check_changes]').val(0); - $('body').mouseup(); - - expect(JSON.parse($tr.find('input.mountOptions').val())).toEqual({ - encrypt: true, - previews: true, - enable_sharing: false, - filesystem_check_changes: 0, - encoding_compatibility: false - }); - }); - }); - }); - describe('applicable user list', function() { - // TODO: test select2 retrieval logic - }); - describe('allow user mounts section', function() { - // TODO: test allowUserMounting section - }); -}); diff --git a/apps/files_external/tests/sso-setup/apps.config.php b/apps/files_external/tests/sso-setup/apps.config.php new file mode 100644 index 00000000000..b3889956a53 --- /dev/null +++ b/apps/files_external/tests/sso-setup/apps.config.php @@ -0,0 +1,20 @@ +<?php + +/** + * SPDX-FileCopyrightText: 2023 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: AGPL-3.0-or-later + */ +$CONFIG = [ + 'apps_paths' => [ + [ + 'path' => '/var/www/html/apps', + 'url' => '/apps', + 'writable' => false, + ], + [ + 'path' => '/var/www/html/extra-apps', + 'url' => '/extra-apps', + 'writable' => true, + ], + ], +]; diff --git a/apps/files_external/tests/sso-setup/client-cmd.sh b/apps/files_external/tests/sso-setup/client-cmd.sh new file mode 100755 index 00000000000..38b50bada67 --- /dev/null +++ b/apps/files_external/tests/sso-setup/client-cmd.sh @@ -0,0 +1,10 @@ +#!/usr/bin/env bash +# +# SPDX-FileCopyrightText: 2023 Nextcloud GmbH and Nextcloud contributors +# SPDX-License-Identifier: AGPL-3.0-or-later +# + +DC_IP=$1 +shift + +docker run --rm --name client -v /tmp/shared:/shared --dns $DC_IP --hostname client.domain.test icewind1991/samba-krb-test-client $@ diff --git a/apps/files_external/tests/sso-setup/setup-sso-nc.sh b/apps/files_external/tests/sso-setup/setup-sso-nc.sh new file mode 100755 index 00000000000..d0029ea684e --- /dev/null +++ b/apps/files_external/tests/sso-setup/setup-sso-nc.sh @@ -0,0 +1,26 @@ +#!/usr/bin/env bash +# +# SPDX-FileCopyrightText: 2023 Nextcloud GmbH and Nextcloud contributors +# SPDX-License-Identifier: AGPL-3.0-or-later +# + +set -e + +docker exec --user 33 apache ./occ maintenance:install --verbose --database=sqlite --database-name=nextcloud --database-host=127.0.0.1 --database-user=root --database-pass=rootpassword --admin-user admin --admin-pass password +docker exec --user 33 apache ./occ config:system:set trusted_domains 1 --value 'httpd.domain.test' + +# setup user_saml +docker exec --user 33 apache ./occ app:enable user_saml --force +docker exec --user 33 apache ./occ config:app:set user_saml type --value 'environment-variable' +docker exec --user 33 apache ./occ saml:config:create +docker exec --user 33 apache ./occ saml:config:set 1 --general-uid_mapping=REMOTE_USER + +# create user +docker exec -e OC_PASS=test --user 33 apache ./occ user:add 'testuser@DOMAIN.TEST' --password-from-env + +# setup external storage +docker exec --user 33 apache ./occ app:enable files_external --force +docker exec --user 33 apache ./occ files_external:create smb smb smb::kerberosapache +docker exec --user 33 apache ./occ files_external:config 1 host krb.domain.test +docker exec --user 33 apache ./occ files_external:config 1 share netlogon +docker exec --user 33 apache ./occ files_external:list diff --git a/apps/files_external/tests/sso-setup/start-apache.sh b/apps/files_external/tests/sso-setup/start-apache.sh new file mode 100755 index 00000000000..58ad71e3a3a --- /dev/null +++ b/apps/files_external/tests/sso-setup/start-apache.sh @@ -0,0 +1,24 @@ +#!/usr/bin/env bash +# +# SPDX-FileCopyrightText: 2023 Nextcloud GmbH and Nextcloud contributors +# SPDX-License-Identifier: AGPL-3.0-or-later +# + +set -e + +SCRIPT_DIR="${0%/*}" + +docker rm -f apache 2>/dev/null > /dev/null + +docker run -d --name apache -v $2:/var/www/html -v /var/www/html/data -v /var/www/html/config -v /var/www/html/extra-apps -v /tmp/shared:/shared --dns $1 --hostname httpd.domain.test icewind1991/samba-krb-test-apache 1>&2 +APACHE_IP=$(docker inspect apache --format '{{.NetworkSettings.IPAddress}}') +docker exec apache chown 33 /var/www/html/config /var/www/html/data /var/www/html/extra-apps +docker cp "$SCRIPT_DIR/apps.config.php" apache:/var/www/html/config/apps.config.php + +# ensure that samba is started (see https://github.com/icewind1991/samba-krb-test/pull/8) +docker exec dc service samba-ad-dc status || docker exec dc service samba-ad-dc start + +# add the dns record for apache +docker exec dc samba-tool dns add krb.domain.test domain.test httpd A $APACHE_IP -U administrator --password=passwOrd1 1>&2 + +echo $APACHE_IP diff --git a/apps/files_external/tests/sso-setup/start-dc.sh b/apps/files_external/tests/sso-setup/start-dc.sh new file mode 100755 index 00000000000..c08b49477b3 --- /dev/null +++ b/apps/files_external/tests/sso-setup/start-dc.sh @@ -0,0 +1,35 @@ +#!/usr/bin/env bash +# +# SPDX-FileCopyrightText: 2023 Nextcloud GmbH and Nextcloud contributors +# SPDX-License-Identifier: AGPL-3.0-or-later +# + +set -e + +function getContainerHealth { + docker inspect --format "{{.State.Health.Status}}" $1 +} + +function waitContainer { + while STATUS=$(getContainerHealth $1); [ $STATUS != "healthy" ]; do + if [ $STATUS == "unhealthy" ]; then + echo "Failed!" 1>&2 + exit -1 + fi + printf . 1>&2 + lf=$'\n' + sleep 1 + done + printf "$lf" 1>&2 +} + +docker rm -f dc 2>/dev/null > /dev/null + +mkdir -p /tmp/shared + +# start the dc +docker run -dit --name dc -v /tmp/shared:/shared --hostname krb.domain.test --cap-add SYS_ADMIN icewind1991/samba-krb-test-dc 1>&2 + +waitContainer dc + +docker inspect dc --format '{{.NetworkSettings.IPAddress}}' diff --git a/apps/files_external/tests/sso-setup/test-sso-smb.sh b/apps/files_external/tests/sso-setup/test-sso-smb.sh new file mode 100755 index 00000000000..46955ae0d3c --- /dev/null +++ b/apps/files_external/tests/sso-setup/test-sso-smb.sh @@ -0,0 +1,32 @@ +#!/usr/bin/env bash +# +# SPDX-FileCopyrightText: 2023 Nextcloud GmbH and Nextcloud contributors +# SPDX-License-Identifier: AGPL-3.0-or-later +# + +set -e + +DC_IP="$1" +SCRIPT_DIR="${0%/*}" + +echo -n "Checking that we can authenticate using kerberos: " +LOGIN_CONTENT=$("$SCRIPT_DIR/client-cmd.sh" $DC_IP curl -i -s --negotiate -u testuser@DOMAIN.TEST: --delegation always http://httpd.domain.test/index.php/apps/user_saml/saml/login?originalUrl=http://localhost/success) + +if [[ "$LOGIN_CONTENT" =~ "Location: http://localhost/success" ]]; then + echo "✔️" +else + echo "❌" + echo "$CONTENT" + exit 1 +fi +echo -n "Getting test file: " +CONTENT=$("$SCRIPT_DIR/client-cmd.sh" $DC_IP curl -s --negotiate -u testuser@DOMAIN.TEST: --delegation always http://httpd.domain.test/remote.php/webdav/smb/test.txt) +CONTENT=$(echo $CONTENT | head -n 1 | tr -d '[:space:]') + +if [[ $CONTENT == "testfile" ]]; then + echo "✔️" +else + echo "❌" + echo "$CONTENT" + exit 1 +fi |