diff options
Diffstat (limited to 'tests/lib/Files/Storage')
-rw-r--r-- | tests/lib/Files/Storage/CommonTest.php | 74 | ||||
-rw-r--r-- | tests/lib/Files/Storage/CopyDirectoryTest.php | 30 | ||||
-rw-r--r-- | tests/lib/Files/Storage/HomeTest.php | 51 | ||||
-rw-r--r-- | tests/lib/Files/Storage/LocalTest.php | 98 | ||||
-rw-r--r-- | tests/lib/Files/Storage/Storage.php | 162 | ||||
-rw-r--r-- | tests/lib/Files/Storage/StorageFactoryTest.php | 31 | ||||
-rw-r--r-- | tests/lib/Files/Storage/StoragesTestCase.php | 128 | ||||
-rw-r--r-- | tests/lib/Files/Storage/Wrapper/AvailabilityTest.php | 55 | ||||
-rw-r--r-- | tests/lib/Files/Storage/Wrapper/EncodingTest.php | 99 | ||||
-rw-r--r-- | tests/lib/Files/Storage/Wrapper/EncryptionTest.php | 427 | ||||
-rw-r--r-- | tests/lib/Files/Storage/Wrapper/JailTest.php | 26 | ||||
-rw-r--r-- | tests/lib/Files/Storage/Wrapper/KnownMtimeTest.php | 69 | ||||
-rw-r--r-- | tests/lib/Files/Storage/Wrapper/PermissionsMaskTest.php | 54 | ||||
-rw-r--r-- | tests/lib/Files/Storage/Wrapper/QuotaTest.php | 72 | ||||
-rw-r--r-- | tests/lib/Files/Storage/Wrapper/WrapperTest.php | 24 |
15 files changed, 773 insertions, 627 deletions
diff --git a/tests/lib/Files/Storage/CommonTest.php b/tests/lib/Files/Storage/CommonTest.php index 0900765c510..c5ff6bb0b5f 100644 --- a/tests/lib/Files/Storage/CommonTest.php +++ b/tests/lib/Files/Storage/CommonTest.php @@ -1,29 +1,21 @@ <?php + /** - * ownCloud - * - * @author Robin Appelman - * @copyright 2012 Robin Appelman icewind@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/>. - * + * SPDX-FileCopyrightText: 2019-2024 Nextcloud GmbH and Nextcloud contributors + * SPDX-FileCopyrightText: 2016 ownCloud, Inc. + * SPDX-License-Identifier: AGPL-3.0-or-later */ namespace Test\Files\Storage; use OC\Files\Storage\Wrapper\Jail; use OC\Files\Storage\Wrapper\Wrapper; +use OCP\Files; +use OCP\Files\IFilenameValidator; +use OCP\Files\InvalidCharacterInPathException; +use OCP\Files\InvalidPathException; +use OCP\ITempManager; +use OCP\Server; use PHPUnit\Framework\MockObject\MockObject; /** @@ -34,27 +26,49 @@ use PHPUnit\Framework\MockObject\MockObject; * @package Test\Files\Storage */ class CommonTest extends Storage { - /** - * @var string tmpDir - */ - private $tmpDir; + + private string $tmpDir; + private IFilenameValidator&MockObject $filenameValidator; protected function setUp(): void { parent::setUp(); - $this->tmpDir = \OC::$server->getTempManager()->getTemporaryFolder(); + $this->filenameValidator = $this->createMock(IFilenameValidator::class); + $this->overwriteService(IFilenameValidator::class, $this->filenameValidator); + $this->tmpDir = Server::get(ITempManager::class)->getTemporaryFolder(); $this->instance = new \OC\Files\Storage\CommonTest(['datadir' => $this->tmpDir]); } protected function tearDown(): void { - \OC_Helper::rmdirr($this->tmpDir); + Files::rmdirr($this->tmpDir); + $this->restoreService(IFilenameValidator::class); parent::tearDown(); } - public function testMoveFromStorageWrapped() { + public function testVerifyPath(): void { + $this->filenameValidator + ->expects($this->once()) + ->method('validateFilename') + ->with('invalid:char.txt') + ->willThrowException(new InvalidCharacterInPathException()); + $this->expectException(InvalidPathException::class); + + $this->instance->verifyPath('/', 'invalid:char.txt'); + } + + public function testVerifyPathSucceed(): void { + $this->filenameValidator + ->expects($this->once()) + ->method('validateFilename') + ->with('valid-char.txt'); + + $this->instance->verifyPath('/', 'valid-char.txt'); + } + + public function testMoveFromStorageWrapped(): void { /** @var \OC\Files\Storage\CommonTest|MockObject $instance */ $instance = $this->getMockBuilder(\OC\Files\Storage\CommonTest::class) - ->setMethods(['copyFromStorage', 'rmdir', 'unlink']) + ->onlyMethods(['copyFromStorage', 'rmdir', 'unlink']) ->setConstructorArgs([['datadir' => $this->tmpDir]]) ->getMock(); $instance->method('copyFromStorage') @@ -69,10 +83,10 @@ class CommonTest extends Storage { $this->assertTrue($instance->file_exists('bar.txt')); } - public function testMoveFromStorageJailed() { + public function testMoveFromStorageJailed(): void { /** @var \OC\Files\Storage\CommonTest|MockObject $instance */ $instance = $this->getMockBuilder(\OC\Files\Storage\CommonTest::class) - ->setMethods(['copyFromStorage', 'rmdir', 'unlink']) + ->onlyMethods(['copyFromStorage', 'rmdir', 'unlink']) ->setConstructorArgs([['datadir' => $this->tmpDir]]) ->getMock(); $instance->method('copyFromStorage') @@ -92,10 +106,10 @@ class CommonTest extends Storage { $this->assertTrue($instance->file_exists('bar.txt')); } - public function testMoveFromStorageNestedJail() { + public function testMoveFromStorageNestedJail(): void { /** @var \OC\Files\Storage\CommonTest|MockObject $instance */ $instance = $this->getMockBuilder(\OC\Files\Storage\CommonTest::class) - ->setMethods(['copyFromStorage', 'rmdir', 'unlink']) + ->onlyMethods(['copyFromStorage', 'rmdir', 'unlink']) ->setConstructorArgs([['datadir' => $this->tmpDir]]) ->getMock(); $instance->method('copyFromStorage') diff --git a/tests/lib/Files/Storage/CopyDirectoryTest.php b/tests/lib/Files/Storage/CopyDirectoryTest.php index 25bdb016ead..b593b7c984f 100644 --- a/tests/lib/Files/Storage/CopyDirectoryTest.php +++ b/tests/lib/Files/Storage/CopyDirectoryTest.php @@ -1,39 +1,27 @@ <?php + /** - * @author Robin Appelman <icewind@owncloud.com> - * - * @copyright Copyright (c) 2015, ownCloud, Inc. - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see <http://www.gnu.org/licenses/> - * + * SPDX-FileCopyrightText: 2019-2024 Nextcloud GmbH and Nextcloud contributors + * SPDX-FileCopyrightText: 2016 ownCloud, Inc. + * SPDX-License-Identifier: AGPL-3.0-only */ namespace Test\Files\Storage; +use OC\Files\Storage\PolyFill\CopyDirectory; use OC\Files\Storage\Temporary; class StorageNoRecursiveCopy extends Temporary { - public function copy($path1, $path2) { - if ($this->is_dir($path1)) { + public function copy(string $source, string $target): bool { + if ($this->is_dir($source)) { return false; } - return copy($this->getSourcePath($path1), $this->getSourcePath($path2)); + return copy($this->getSourcePath($source), $this->getSourcePath($target)); } } class CopyDirectoryStorage extends StorageNoRecursiveCopy { - use \OC\Files\Storage\PolyFill\CopyDirectory; + use CopyDirectory; } /** diff --git a/tests/lib/Files/Storage/HomeTest.php b/tests/lib/Files/Storage/HomeTest.php index d5feb40840f..84a9816cb0c 100644 --- a/tests/lib/Files/Storage/HomeTest.php +++ b/tests/lib/Files/Storage/HomeTest.php @@ -1,41 +1,28 @@ <?php + /** - * ownCloud - * - * @author Robin Appelman - * @copyright 2012 Robin Appelman icewind@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/>. - * + * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors + * SPDX-FileCopyrightText: 2016 ownCloud, Inc. + * SPDX-License-Identifier: AGPL-3.0-or-later */ namespace Test\Files\Storage; +use OC\Files\Storage\Home; use OC\User\User; +use OCP\Files; +use OCP\ITempManager; +use OCP\Server; class DummyUser extends User { - private $home; - - private $uid; - /** * @param string $uid * @param string $home */ - public function __construct($uid, $home) { - $this->uid = $uid; - $this->home = $home; + public function __construct( + private $uid, + private $home, + ) { } public function getHome() { @@ -63,39 +50,39 @@ class HomeTest extends Storage { private $userId; /** - * @var \OC\User\User $user + * @var User $user */ private $user; protected function setUp(): void { parent::setUp(); - $this->tmpDir = \OC::$server->getTempManager()->getTemporaryFolder(); + $this->tmpDir = Server::get(ITempManager::class)->getTemporaryFolder(); $this->userId = $this->getUniqueID('user_'); $this->user = new DummyUser($this->userId, $this->tmpDir); - $this->instance = new \OC\Files\Storage\Home(['user' => $this->user]); + $this->instance = new Home(['user' => $this->user]); } protected function tearDown(): void { - \OC_Helper::rmdirr($this->tmpDir); + Files::rmdirr($this->tmpDir); parent::tearDown(); } /** * Tests that the home id is in the format home::user1 */ - public function testId() { + public function testId(): void { $this->assertEquals('home::' . $this->userId, $this->instance->getId()); } /** * Tests that getCache() returns an instance of HomeCache */ - public function testGetCacheReturnsHomeCache() { + public function testGetCacheReturnsHomeCache(): void { $this->assertInstanceOf('\OC\Files\Cache\HomeCache', $this->instance->getCache()); } - public function testGetOwner() { + public function testGetOwner(): void { $this->assertEquals($this->userId, $this->instance->getOwner('')); } } diff --git a/tests/lib/Files/Storage/LocalTest.php b/tests/lib/Files/Storage/LocalTest.php index e324d2b28db..89449a51351 100644 --- a/tests/lib/Files/Storage/LocalTest.php +++ b/tests/lib/Files/Storage/LocalTest.php @@ -1,27 +1,21 @@ <?php + /** - * ownCloud - * - * @author Robin Appelman - * @copyright 2012 Robin Appelman icewind@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/>. - * + * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors + * SPDX-FileCopyrightText: 2016 ownCloud, Inc. + * SPDX-License-Identifier: AGPL-3.0-or-later */ namespace Test\Files\Storage; +use OC\Files\Storage\Local; +use OC\Files\Storage\Wrapper\Jail; +use OCP\Files; +use OCP\Files\ForbiddenException; +use OCP\Files\StorageNotAvailableException; +use OCP\ITempManager; +use OCP\Server; + /** * Class LocalTest * @@ -38,23 +32,23 @@ class LocalTest extends Storage { protected function setUp(): void { parent::setUp(); - $this->tmpDir = \OC::$server->getTempManager()->getTemporaryFolder(); - $this->instance = new \OC\Files\Storage\Local(['datadir' => $this->tmpDir]); + $this->tmpDir = Server::get(ITempManager::class)->getTemporaryFolder(); + $this->instance = new Local(['datadir' => $this->tmpDir]); } protected function tearDown(): void { - \OC_Helper::rmdirr($this->tmpDir); + Files::rmdirr($this->tmpDir); parent::tearDown(); } - public function testStableEtag() { + public function testStableEtag(): void { $this->instance->file_put_contents('test.txt', 'foobar'); $etag1 = $this->instance->getETag('test.txt'); $etag2 = $this->instance->getETag('test.txt'); $this->assertEquals($etag1, $etag2); } - public function testEtagChange() { + public function testEtagChange(): void { $this->instance->file_put_contents('test.txt', 'foo'); $this->instance->touch('test.txt', time() - 2); $etag1 = $this->instance->getETag('test.txt'); @@ -64,22 +58,22 @@ class LocalTest extends Storage { } - public function testInvalidArgumentsEmptyArray() { + public function testInvalidArgumentsEmptyArray(): void { $this->expectException(\InvalidArgumentException::class); - new \OC\Files\Storage\Local([]); + new Local([]); } - public function testInvalidArgumentsNoArray() { + public function testInvalidArgumentsNoArray(): void { $this->expectException(\InvalidArgumentException::class); - new \OC\Files\Storage\Local(null); + new Local([]); } - public function testDisallowSymlinksOutsideDatadir() { - $this->expectException(\OCP\Files\ForbiddenException::class); + public function testDisallowSymlinksOutsideDatadir(): void { + $this->expectException(ForbiddenException::class); $subDir1 = $this->tmpDir . 'sub1'; $subDir2 = $this->tmpDir . 'sub2'; @@ -89,12 +83,12 @@ class LocalTest extends Storage { symlink($subDir2, $sym); - $storage = new \OC\Files\Storage\Local(['datadir' => $subDir1]); + $storage = new Local(['datadir' => $subDir1]); $storage->file_put_contents('sym/foo', 'bar'); } - public function testDisallowSymlinksInsideDatadir() { + public function testDisallowSymlinksInsideDatadir(): void { $subDir1 = $this->tmpDir . 'sub1'; $subDir2 = $this->tmpDir . 'sub1/sub2'; $sym = $this->tmpDir . 'sub1/sym'; @@ -103,27 +97,27 @@ class LocalTest extends Storage { symlink($subDir2, $sym); - $storage = new \OC\Files\Storage\Local(['datadir' => $subDir1]); + $storage = new Local(['datadir' => $subDir1]); $storage->file_put_contents('sym/foo', 'bar'); $this->addToAssertionCount(1); } - public function testWriteUmaskFilePutContents() { + public function testWriteUmaskFilePutContents(): void { $oldMask = umask(0333); $this->instance->file_put_contents('test.txt', 'sad'); umask($oldMask); $this->assertTrue($this->instance->isUpdatable('test.txt')); } - public function testWriteUmaskMkdir() { + public function testWriteUmaskMkdir(): void { $oldMask = umask(0333); $this->instance->mkdir('test.txt'); umask($oldMask); $this->assertTrue($this->instance->isUpdatable('test.txt')); } - public function testWriteUmaskFopen() { + public function testWriteUmaskFopen(): void { $oldMask = umask(0333); $handle = $this->instance->fopen('test.txt', 'w'); fwrite($handle, 'foo'); @@ -132,11 +126,43 @@ class LocalTest extends Storage { $this->assertTrue($this->instance->isUpdatable('test.txt')); } - public function testWriteUmaskCopy() { + public function testWriteUmaskCopy(): void { $this->instance->file_put_contents('source.txt', 'sad'); $oldMask = umask(0333); $this->instance->copy('source.txt', 'test.txt'); umask($oldMask); $this->assertTrue($this->instance->isUpdatable('test.txt')); } + + public function testUnavailableExternal(): void { + $this->expectException(StorageNotAvailableException::class); + $this->instance = new Local(['datadir' => $this->tmpDir . '/unexist', 'isExternal' => true]); + } + + public function testUnavailableNonExternal(): void { + $this->instance = new Local(['datadir' => $this->tmpDir . '/unexist']); + // no exception thrown + $this->assertNotNull($this->instance); + } + + public function testMoveNestedJail(): void { + $this->instance->mkdir('foo'); + $this->instance->mkdir('foo/bar'); + $this->instance->mkdir('target'); + $this->instance->file_put_contents('foo/bar/file.txt', 'foo'); + $jail1 = new Jail([ + 'storage' => $this->instance, + 'root' => 'foo' + ]); + $jail2 = new Jail([ + 'storage' => $jail1, + 'root' => 'bar' + ]); + $jail3 = new Jail([ + 'storage' => $this->instance, + 'root' => 'target' + ]); + $jail3->moveFromStorage($jail2, 'file.txt', 'file.txt'); + $this->assertTrue($this->instance->file_exists('target/file.txt')); + } } diff --git a/tests/lib/Files/Storage/Storage.php b/tests/lib/Files/Storage/Storage.php index a646fd5fd0b..51bb5b7c8ad 100644 --- a/tests/lib/Files/Storage/Storage.php +++ b/tests/lib/Files/Storage/Storage.php @@ -1,28 +1,16 @@ <?php + /** - * ownCloud - * - * @author Robin Appelman - * @copyright 2012 Robin Appelman icewind@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/>. - * + * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors + * SPDX-FileCopyrightText: 2016 ownCloud, Inc. + * SPDX-License-Identifier: AGPL-3.0-or-later */ namespace Test\Files\Storage; use OC\Files\Cache\Watcher; +use OC\Files\Storage\Wrapper\Wrapper; +use OCP\Files\Storage\IStorage; use OCP\Files\Storage\IWriteStreamStorage; abstract class Storage extends \Test\TestCase { @@ -45,7 +33,7 @@ abstract class Storage extends \Test\TestCase { /** * the root folder of the storage should always exist, be readable and be recognized as a directory */ - public function testRoot() { + public function testRoot(): void { $this->assertTrue($this->instance->file_exists('/'), 'Root folder does not exist'); $this->assertTrue($this->instance->isReadable('/'), 'Root folder is not readable'); $this->assertTrue($this->instance->is_dir('/'), 'Root folder is not a directory'); @@ -59,14 +47,12 @@ abstract class Storage extends \Test\TestCase { /** * Check that the test() function works */ - public function testTestFunction() { + public function testTestFunction(): void { $this->assertTrue($this->instance->test()); } - /** - * @dataProvider directoryProvider - */ - public function testDirectories($directory) { + #[\PHPUnit\Framework\Attributes\DataProvider('directoryProvider')] + public function testDirectories($directory): void { $this->assertFalse($this->instance->file_exists('/' . $directory)); $this->assertTrue($this->instance->mkdir('/' . $directory)); @@ -81,7 +67,7 @@ abstract class Storage extends \Test\TestCase { $dh = $this->instance->opendir('/'); $content = []; - while ($file = readdir($dh)) { + while (($file = readdir($dh)) !== false) { if ($file != '.' and $file != '..') { $content[] = $file; } @@ -94,12 +80,13 @@ abstract class Storage extends \Test\TestCase { $dirEntry = $content[0]; unset($dirEntry['scan_permissions']); unset($dirEntry['etag']); + $this->assertLessThanOrEqual(1, abs($dirEntry['mtime'] - $this->instance->filemtime($directory))); + unset($dirEntry['mtime']); + unset($dirEntry['storage_mtime']); $this->assertEquals([ 'name' => $directory, 'mimetype' => $this->instance->getMimeType($directory), - 'mtime' => $this->instance->filemtime($directory), 'size' => -1, - 'storage_mtime' => $this->instance->filemtime($directory), 'permissions' => $this->instance->getPermissions($directory), ], $dirEntry); @@ -113,7 +100,7 @@ abstract class Storage extends \Test\TestCase { $dh = $this->instance->opendir('/'); $content = []; - while ($file = readdir($dh)) { + while (($file = readdir($dh)) !== false) { if ($file != '.' and $file != '..') { $content[] = $file; } @@ -121,7 +108,7 @@ abstract class Storage extends \Test\TestCase { $this->assertEquals([], $content); } - public function fileNameProvider() { + public static function fileNameProvider(): array { return [ ['file.txt'], [' file.txt'], @@ -132,7 +119,7 @@ abstract class Storage extends \Test\TestCase { ]; } - public function directoryProvider() { + public static function directoryProvider(): array { return [ ['folder'], [' folder'], @@ -143,7 +130,7 @@ abstract class Storage extends \Test\TestCase { ]; } - public function loremFileProvider() { + public static function loremFileProvider(): array { $root = \OC::$SERVERROOT . '/tests/data/'; return [ // small file @@ -155,10 +142,9 @@ abstract class Storage extends \Test\TestCase { /** * test the various uses of file_get_contents and file_put_contents - * - * @dataProvider loremFileProvider */ - public function testGetPutContents($sourceFile) { + #[\PHPUnit\Framework\Attributes\DataProvider('loremFileProvider')] + public function testGetPutContents($sourceFile): void { $sourceText = file_get_contents($sourceFile); //fill a file with string data @@ -174,7 +160,7 @@ abstract class Storage extends \Test\TestCase { /** * test various known mimetypes */ - public function testMimeType() { + public function testMimeType(): void { $this->assertEquals('httpd/unix-directory', $this->instance->getMimeType('/')); $this->assertEquals(false, $this->instance->getMimeType('/non/existing/file')); @@ -192,7 +178,7 @@ abstract class Storage extends \Test\TestCase { } - public function copyAndMoveProvider() { + public static function copyAndMoveProvider(): array { return [ ['/source.txt', '/target.txt'], ['/source.txt', '/target with space.txt'], @@ -223,10 +209,8 @@ abstract class Storage extends \Test\TestCase { ); } - /** - * @dataProvider copyAndMoveProvider - */ - public function testCopy($source, $target) { + #[\PHPUnit\Framework\Attributes\DataProvider('copyAndMoveProvider')] + public function testCopy($source, $target): void { $this->initSourceAndTarget($source); $this->instance->copy($source, $target); @@ -236,10 +220,8 @@ abstract class Storage extends \Test\TestCase { $this->assertTrue($this->instance->file_exists($source), $source . ' was deleted'); } - /** - * @dataProvider copyAndMoveProvider - */ - public function testMove($source, $target) { + #[\PHPUnit\Framework\Attributes\DataProvider('copyAndMoveProvider')] + public function testMove($source, $target): void { $this->initSourceAndTarget($source); $this->instance->rename($source, $target); @@ -250,10 +232,8 @@ abstract class Storage extends \Test\TestCase { $this->assertSameAsLorem($target); } - /** - * @dataProvider copyAndMoveProvider - */ - public function testCopyOverwrite($source, $target) { + #[\PHPUnit\Framework\Attributes\DataProvider('copyAndMoveProvider')] + public function testCopyOverwrite($source, $target): void { $this->initSourceAndTarget($source, $target); $this->instance->copy($source, $target); @@ -264,10 +244,8 @@ abstract class Storage extends \Test\TestCase { $this->assertSameAsLorem($source); } - /** - * @dataProvider copyAndMoveProvider - */ - public function testMoveOverwrite($source, $target) { + #[\PHPUnit\Framework\Attributes\DataProvider('copyAndMoveProvider')] + public function testMoveOverwrite($source, $target): void { $this->initSourceAndTarget($source, $target); $this->instance->rename($source, $target); @@ -277,7 +255,7 @@ abstract class Storage extends \Test\TestCase { $this->assertSameAsLorem($target); } - public function testLocal() { + public function testLocal(): void { $textFile = \OC::$SERVERROOT . '/tests/data/lorem.txt'; $this->instance->file_put_contents('/lorem.txt', file_get_contents($textFile)); $localFile = $this->instance->getLocalFile('/lorem.txt'); @@ -304,7 +282,7 @@ abstract class Storage extends \Test\TestCase { $this->assertEquals(file_get_contents($localFile), 'foo'); } - public function testStat() { + public function testStat(): void { $textFile = \OC::$SERVERROOT . '/tests/data/lorem.txt'; $ctimeStart = time(); $this->instance->file_put_contents('/lorem.txt', file_get_contents($textFile)); @@ -339,8 +317,8 @@ abstract class Storage extends \Test\TestCase { * Test whether checkUpdate properly returns false when there was * no change. */ - public function testCheckUpdate() { - if ($this->instance instanceof \OC\Files\Storage\Wrapper\Wrapper) { + public function testCheckUpdate(): void { + if ($this->instance instanceof Wrapper) { $this->markTestSkipped('Cannot test update check on wrappers'); } $textFile = \OC::$SERVERROOT . '/tests/data/lorem.txt'; @@ -351,7 +329,7 @@ abstract class Storage extends \Test\TestCase { $this->assertFalse($watcher->checkUpdate('/lorem.txt'), 'No update'); } - public function testUnlink() { + public function testUnlink(): void { $textFile = \OC::$SERVERROOT . '/tests/data/lorem.txt'; $this->instance->file_put_contents('/lorem.txt', file_get_contents($textFile)); @@ -363,10 +341,8 @@ abstract class Storage extends \Test\TestCase { $this->assertFalse($this->instance->file_exists('/lorem.txt')); } - /** - * @dataProvider fileNameProvider - */ - public function testFOpen($fileName) { + #[\PHPUnit\Framework\Attributes\DataProvider('fileNameProvider')] + public function testFOpen($fileName): void { $textFile = \OC::$SERVERROOT . '/tests/data/lorem.txt'; $fh = @$this->instance->fopen($fileName, 'r'); @@ -386,14 +362,14 @@ abstract class Storage extends \Test\TestCase { $this->assertEquals(file_get_contents($textFile), $content); } - public function testTouchCreateFile() { + public function testTouchCreateFile(): void { $this->assertFalse($this->instance->file_exists('touch')); // returns true on success $this->assertTrue($this->instance->touch('touch')); $this->assertTrue($this->instance->file_exists('touch')); } - public function testRecursiveRmdir() { + public function testRecursiveRmdir(): void { $this->instance->mkdir('folder'); $this->instance->mkdir('folder/bar'); $this->wait(); @@ -407,14 +383,14 @@ abstract class Storage extends \Test\TestCase { $this->assertFalse($this->instance->file_exists('folder')); } - public function testRmdirEmptyFolder() { + public function testRmdirEmptyFolder(): void { $this->assertTrue($this->instance->mkdir('empty')); $this->wait(); $this->assertTrue($this->instance->rmdir('empty')); $this->assertFalse($this->instance->file_exists('empty')); } - public function testRecursiveUnlink() { + public function testRecursiveUnlink(): void { $this->instance->mkdir('folder'); $this->instance->mkdir('folder/bar'); $this->instance->file_put_contents('folder/asd.txt', 'foobar'); @@ -427,7 +403,7 @@ abstract class Storage extends \Test\TestCase { $this->assertFalse($this->instance->file_exists('folder')); } - public function hashProvider() { + public static function hashProvider(): array { return [ ['Foobar', 'md5'], ['Foobar', 'sha1'], @@ -435,16 +411,14 @@ abstract class Storage extends \Test\TestCase { ]; } - /** - * @dataProvider hashProvider - */ - public function testHash($data, $type) { + #[\PHPUnit\Framework\Attributes\DataProvider('hashProvider')] + public function testHash($data, $type): void { $this->instance->file_put_contents('hash.txt', $data); $this->assertEquals(hash($type, $data), $this->instance->hash($type, 'hash.txt')); $this->assertEquals(hash($type, $data, true), $this->instance->hash($type, 'hash.txt', true)); } - public function testHashInFileName() { + public function testHashInFileName(): void { $this->instance->file_put_contents('#test.txt', 'data'); $this->assertEquals('data', $this->instance->file_get_contents('#test.txt')); @@ -463,14 +437,14 @@ abstract class Storage extends \Test\TestCase { $this->assertEquals(['test.txt'], $content); } - public function testCopyOverWriteFile() { + public function testCopyOverWriteFile(): void { $this->instance->file_put_contents('target.txt', 'foo'); $this->instance->file_put_contents('source.txt', 'bar'); $this->instance->copy('source.txt', 'target.txt'); $this->assertEquals('bar', $this->instance->file_get_contents('target.txt')); } - public function testRenameOverWriteFile() { + public function testRenameOverWriteFile(): void { $this->instance->file_put_contents('target.txt', 'foo'); $this->instance->file_put_contents('source.txt', 'bar'); $this->instance->rename('source.txt', 'target.txt'); @@ -478,7 +452,7 @@ abstract class Storage extends \Test\TestCase { $this->assertFalse($this->instance->file_exists('source.txt')); } - public function testRenameDirectory() { + public function testRenameDirectory(): void { $this->instance->mkdir('source'); $this->instance->file_put_contents('source/test1.txt', 'foo'); $this->instance->file_put_contents('source/test2.txt', 'qwerty'); @@ -506,7 +480,7 @@ abstract class Storage extends \Test\TestCase { $this->assertEquals('bar', $this->instance->file_get_contents('target/subfolder/test.txt')); } - public function testRenameOverWriteDirectory() { + public function testRenameOverWriteDirectory(): void { $this->instance->mkdir('source'); $this->instance->file_put_contents('source/test1.txt', 'foo'); @@ -522,7 +496,7 @@ abstract class Storage extends \Test\TestCase { $this->assertEquals('foo', $this->instance->file_get_contents('target/test1.txt'), 'target/test1.txt has not been overwritten'); } - public function testRenameOverWriteDirectoryOverFile() { + public function testRenameOverWriteDirectoryOverFile(): void { $this->instance->mkdir('source'); $this->instance->file_put_contents('source/test1.txt', 'foo'); @@ -535,7 +509,7 @@ abstract class Storage extends \Test\TestCase { $this->assertEquals('foo', $this->instance->file_get_contents('target/test1.txt')); } - public function testCopyDirectory() { + public function testCopyDirectory(): void { $this->instance->mkdir('source'); $this->instance->file_put_contents('source/test1.txt', 'foo'); $this->instance->file_put_contents('source/test2.txt', 'qwerty'); @@ -560,7 +534,7 @@ abstract class Storage extends \Test\TestCase { $this->assertEquals('bar', $this->instance->file_get_contents('target/subfolder/test.txt')); } - public function testCopyOverWriteDirectory() { + public function testCopyOverWriteDirectory(): void { $this->instance->mkdir('source'); $this->instance->file_put_contents('source/test1.txt', 'foo'); @@ -570,11 +544,11 @@ abstract class Storage extends \Test\TestCase { $this->instance->copy('source', 'target'); - $this->assertFalse($this->instance->file_exists('target/test2.txt')); + $this->assertFalse($this->instance->file_exists('target/test2.txt'), 'File target/test2.txt should no longer exist, but does'); $this->assertEquals('foo', $this->instance->file_get_contents('target/test1.txt')); } - public function testCopyOverWriteDirectoryOverFile() { + public function testCopyOverWriteDirectoryOverFile(): void { $this->instance->mkdir('source'); $this->instance->file_put_contents('source/test1.txt', 'foo'); @@ -585,16 +559,14 @@ abstract class Storage extends \Test\TestCase { $this->assertEquals('foo', $this->instance->file_get_contents('target/test1.txt')); } - public function testInstanceOfStorage() { - $this->assertTrue($this->instance->instanceOfStorage('\OCP\Files\Storage')); + public function testInstanceOfStorage(): void { + $this->assertTrue($this->instance->instanceOfStorage(IStorage::class)); $this->assertTrue($this->instance->instanceOfStorage(get_class($this->instance))); $this->assertFalse($this->instance->instanceOfStorage('\OC')); } - /** - * @dataProvider copyAndMoveProvider - */ - public function testCopyFromSameStorage($source, $target) { + #[\PHPUnit\Framework\Attributes\DataProvider('copyAndMoveProvider')] + public function testCopyFromSameStorage($source, $target): void { $this->initSourceAndTarget($source); $this->instance->copyFromStorage($this->instance, $source, $target); @@ -604,32 +576,32 @@ abstract class Storage extends \Test\TestCase { $this->assertTrue($this->instance->file_exists($source), $source . ' was deleted'); } - public function testIsCreatable() { + public function testIsCreatable(): void { $this->instance->mkdir('source'); $this->assertTrue($this->instance->isCreatable('source')); } - public function testIsReadable() { + public function testIsReadable(): void { $this->instance->mkdir('source'); $this->assertTrue($this->instance->isReadable('source')); } - public function testIsUpdatable() { + public function testIsUpdatable(): void { $this->instance->mkdir('source'); $this->assertTrue($this->instance->isUpdatable('source')); } - public function testIsDeletable() { + public function testIsDeletable(): void { $this->instance->mkdir('source'); $this->assertTrue($this->instance->isDeletable('source')); } - public function testIsShareable() { + public function testIsShareable(): void { $this->instance->mkdir('source'); $this->assertTrue($this->instance->isSharable('source')); } - public function testStatAfterWrite() { + public function testStatAfterWrite(): void { $this->instance->file_put_contents('foo.txt', 'bar'); $stat = $this->instance->stat('foo.txt'); $this->assertEquals(3, $stat['size']); @@ -642,13 +614,13 @@ abstract class Storage extends \Test\TestCase { $this->assertEquals(6, $stat['size']); } - public function testPartFile() { + public function testPartFile(): void { $this->instance->file_put_contents('bar.txt.part', 'bar'); $this->instance->rename('bar.txt.part', 'bar.txt'); $this->assertEquals('bar', $this->instance->file_get_contents('bar.txt')); } - public function testWriteStream() { + public function testWriteStream(): void { $textFile = \OC::$SERVERROOT . '/tests/data/lorem.txt'; if (!$this->instance->instanceOfStorage(IWriteStreamStorage::class)) { @@ -665,7 +637,7 @@ abstract class Storage extends \Test\TestCase { $this->assertEquals('resource (closed)', gettype($source)); } - public function testFseekSize() { + public function testFseekSize(): void { $textFile = \OC::$SERVERROOT . '/tests/data/lorem.txt'; $this->instance->file_put_contents('bar.txt', file_get_contents($textFile)); diff --git a/tests/lib/Files/Storage/StorageFactoryTest.php b/tests/lib/Files/Storage/StorageFactoryTest.php index 20b51cdda22..0bb9cbf5824 100644 --- a/tests/lib/Files/Storage/StorageFactoryTest.php +++ b/tests/lib/Files/Storage/StorageFactoryTest.php @@ -1,33 +1,34 @@ <?php + /** - * Copyright (c) 2015 Robin Appelman <icewind@owncloud.com> - * This file is licensed under the Affero General Public License version 3 or - * later. - * See the COPYING-README file. + * SPDX-FileCopyrightText: 2019-2024 Nextcloud GmbH and Nextcloud contributors + * SPDX-FileCopyrightText: 2016 ownCloud, Inc. + * SPDX-License-Identifier: AGPL-3.0-or-later */ namespace Test\Files\Storage; use OC\Files\Mount\MountPoint; +use OC\Files\Storage\StorageFactory; use OC\Files\Storage\Wrapper\Wrapper; use OCP\Files\Mount\IMountPoint; -use OCP\Files\Storage as IStorage; +use OCP\Files\Storage\IStorage; use Test\TestCase; class DummyWrapper extends Wrapper { public $data; - public function __construct($arguments) { - parent::__construct($arguments); - if (isset($arguments['data'])) { - $this->data = $arguments['data']; + public function __construct(array $parameters) { + parent::__construct($parameters); + if (isset($parameters['data'])) { + $this->data = $parameters['data']; } } } class StorageFactoryTest extends TestCase { - public function testSimpleWrapper() { - $instance = new \OC\Files\Storage\StorageFactory(); + public function testSimpleWrapper(): void { + $instance = new StorageFactory(); $mount = new MountPoint('\OC\Files\Storage\Temporary', '/foo', [[]], $instance); $instance->addStorageWrapper('dummy', function ($mountPoint, IStorage $storage, IMountPoint $mount) { $this->assertInstanceOf('\OC\Files\Storage\Temporary', $storage); @@ -39,8 +40,8 @@ class StorageFactoryTest extends TestCase { $this->assertInstanceOf('\Test\Files\Storage\DummyWrapper', $wrapped); } - public function testRemoveWrapper() { - $instance = new \OC\Files\Storage\StorageFactory(); + public function testRemoveWrapper(): void { + $instance = new StorageFactory(); $mount = new MountPoint('\OC\Files\Storage\Temporary', '/foo', [[]], $instance); $instance->addStorageWrapper('dummy', function ($mountPoint, IStorage $storage) { return new DummyWrapper(['storage' => $storage]); @@ -50,8 +51,8 @@ class StorageFactoryTest extends TestCase { $this->assertInstanceOf('\OC\Files\Storage\Temporary', $wrapped); } - public function testWrapperPriority() { - $instance = new \OC\Files\Storage\StorageFactory(); + public function testWrapperPriority(): void { + $instance = new StorageFactory(); $mount = new MountPoint('\OC\Files\Storage\Temporary', '/foo', [[]], $instance); $instance->addStorageWrapper('dummy1', function ($mountPoint, IStorage $storage) { return new DummyWrapper(['storage' => $storage, 'data' => 1]); diff --git a/tests/lib/Files/Storage/StoragesTestCase.php b/tests/lib/Files/Storage/StoragesTestCase.php new file mode 100644 index 00000000000..565ff1ddfda --- /dev/null +++ b/tests/lib/Files/Storage/StoragesTestCase.php @@ -0,0 +1,128 @@ +<?php + +/** + * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors + * SPDX-FileCopyrightText: 2016 ownCloud, Inc. + * SPDX-License-Identifier: AGPL-3.0-or-later + */ + +namespace Test\Files\Storage; + +use OC\Files\Storage\Storage; +use Test\TestCase; + +abstract class StoragesTestCase extends TestCase { + /** + * @var Storage + */ + protected $storage1; + + /** + * @var Storage + */ + protected $storage2; + + protected function tearDown(): void { + if (is_null($this->storage1) && is_null($this->storage2)) { + return; + } + $this->storage1->getCache()->clear(); + $this->storage2->getCache()->clear(); + + parent::tearDown(); + } + + public function testMoveFileFromStorage() { + $source = 'source.txt'; + $target = 'target.txt'; + $this->storage2->file_put_contents($source, 'foo'); + + $this->storage1->moveFromStorage($this->storage2, $source, $target); + + $this->assertTrue($this->storage1->file_exists($target), $target . ' was not created'); + $this->assertFalse($this->storage2->file_exists($source), $source . ' still exists'); + $this->assertEquals('foo', $this->storage1->file_get_contents($target)); + } + + public function testMoveFileFromStorageWithExistingTarget() { + $source = 'source.txt'; + $target = 'target.txt'; + $this->storage1->file_put_contents($target, 'bar'); + $this->storage2->file_put_contents($source, 'foo'); + + $targetURN = $this->storage1->getURN($this->storage1->getCache()->get($target)->getID()); + $sourceURN = $this->storage2->getURN($this->storage2->getCache()->get($source)->getID()); + + $this->storage1->moveFromStorage($this->storage2, $source, $target); + + $this->assertTrue($this->storage1->file_exists($target), $target . ' was not created in DB'); + $this->assertFalse($this->storage2->file_exists($source), $source . ' still exists in DB'); + $this->assertTrue($this->storage1->getObjectStore()->objectExists($sourceURN), $sourceURN . ' was not created in bucket'); + $this->assertFalse($this->storage1->getObjectStore()->objectExists($targetURN), $targetURN . ' still exists in bucket'); + $this->assertEquals('foo', $this->storage1->file_get_contents($target)); + } + + public function testMoveDirectoryFromStorage() { + $this->storage2->mkdir('source'); + $this->storage2->file_put_contents('source/test1.txt', 'foo'); + $this->storage2->file_put_contents('source/test2.txt', 'qwerty'); + $this->storage2->mkdir('source/subfolder'); + $this->storage2->file_put_contents('source/subfolder/test.txt', 'bar'); + + $this->storage1->moveFromStorage($this->storage2, 'source', 'target'); + + $this->assertTrue($this->storage1->file_exists('target')); + $this->assertTrue($this->storage1->file_exists('target/test1.txt')); + $this->assertTrue($this->storage1->file_exists('target/test2.txt')); + $this->assertTrue($this->storage1->file_exists('target/subfolder')); + $this->assertTrue($this->storage1->file_exists('target/subfolder/test.txt')); + + $this->assertFalse($this->storage2->file_exists('source')); + $this->assertFalse($this->storage2->file_exists('source/test1.txt')); + $this->assertFalse($this->storage2->file_exists('source/test2.txt')); + $this->assertFalse($this->storage2->file_exists('source/subfolder')); + $this->assertFalse($this->storage2->file_exists('source/subfolder/test.txt')); + + $this->assertEquals('foo', $this->storage1->file_get_contents('target/test1.txt')); + $this->assertEquals('qwerty', $this->storage1->file_get_contents('target/test2.txt')); + $this->assertEquals('bar', $this->storage1->file_get_contents('target/subfolder/test.txt')); + } + + public function testCopyFileFromStorage() { + $source = 'source.txt'; + $target = 'target.txt'; + $this->storage2->file_put_contents($source, 'foo'); + + $this->storage1->copyFromStorage($this->storage2, $source, $target); + + $this->assertTrue($this->storage1->file_exists($target), $target . ' was not created'); + $this->assertTrue($this->storage2->file_exists($source), $source . ' was deleted'); + $this->assertEquals('foo', $this->storage1->file_get_contents($target)); + } + + public function testCopyDirectoryFromStorage() { + $this->storage2->mkdir('source'); + $this->storage2->file_put_contents('source/test1.txt', 'foo'); + $this->storage2->file_put_contents('source/test2.txt', 'qwerty'); + $this->storage2->mkdir('source/subfolder'); + $this->storage2->file_put_contents('source/subfolder/test.txt', 'bar'); + + $this->storage1->copyFromStorage($this->storage2, 'source', 'target'); + + $this->assertTrue($this->storage1->file_exists('target')); + $this->assertTrue($this->storage1->file_exists('target/test1.txt')); + $this->assertTrue($this->storage1->file_exists('target/test2.txt')); + $this->assertTrue($this->storage1->file_exists('target/subfolder')); + $this->assertTrue($this->storage1->file_exists('target/subfolder/test.txt')); + + $this->assertTrue($this->storage2->file_exists('source')); + $this->assertTrue($this->storage2->file_exists('source/test1.txt')); + $this->assertTrue($this->storage2->file_exists('source/test2.txt')); + $this->assertTrue($this->storage2->file_exists('source/subfolder')); + $this->assertTrue($this->storage2->file_exists('source/subfolder/test.txt')); + + $this->assertEquals('foo', $this->storage1->file_get_contents('target/test1.txt')); + $this->assertEquals('qwerty', $this->storage1->file_get_contents('target/test2.txt')); + $this->assertEquals('bar', $this->storage1->file_get_contents('target/subfolder/test.txt')); + } +} diff --git a/tests/lib/Files/Storage/Wrapper/AvailabilityTest.php b/tests/lib/Files/Storage/Wrapper/AvailabilityTest.php index 7d5d7d31808..d890081cbb6 100644 --- a/tests/lib/Files/Storage/Wrapper/AvailabilityTest.php +++ b/tests/lib/Files/Storage/Wrapper/AvailabilityTest.php @@ -1,22 +1,9 @@ <?php + /** - * @author Robin McCorkell <rmccorkell@karoshi.org.uk> - * - * @copyright Copyright (c) 2015, ownCloud, Inc. - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see <http://www.gnu.org/licenses/> - * + * SPDX-FileCopyrightText: 2019-2024 Nextcloud GmbH and Nextcloud contributors + * SPDX-FileCopyrightText: 2016 ownCloud, Inc. + * SPDX-License-Identifier: AGPL-3.0-only */ namespace Test\Files\Storage\Wrapper; @@ -31,7 +18,7 @@ class AvailabilityTest extends \Test\TestCase { protected $storageCache; /** @var \PHPUnit\Framework\MockObject\MockObject|Temporary */ protected $storage; - /** @var Availability */ + /** @var Availability */ protected $wrapper; protected function setUp(): void { @@ -50,7 +37,7 @@ class AvailabilityTest extends \Test\TestCase { /** * Storage is available */ - public function testAvailable() { + public function testAvailable(): void { $this->storage->expects($this->once()) ->method('getAvailability') ->willReturn(['available' => true, 'last_checked' => 0]); @@ -66,8 +53,8 @@ class AvailabilityTest extends \Test\TestCase { * Storage marked unavailable, TTL not expired * */ - public function testUnavailable() { - $this->expectException(\OCP\Files\StorageNotAvailableException::class); + public function testUnavailable(): void { + $this->expectException(StorageNotAvailableException::class); $this->storage->expects($this->once()) ->method('getAvailability') @@ -83,19 +70,23 @@ class AvailabilityTest extends \Test\TestCase { /** * Storage marked unavailable, TTL expired */ - public function testUnavailableRecheck() { + public function testUnavailableRecheck(): void { $this->storage->expects($this->once()) ->method('getAvailability') ->willReturn(['available' => false, 'last_checked' => 0]); $this->storage->expects($this->once()) ->method('test') ->willReturn(true); + $calls = [ + false, // prevents concurrent rechecks + true, // sets correct availability + ]; $this->storage->expects($this->exactly(2)) ->method('setAvailability') - ->withConsecutive( - [$this->equalTo(false)], // prevents concurrent rechecks - [$this->equalTo(true)] // sets correct availability - ); + ->willReturnCallback(function ($value) use (&$calls): void { + $expected = array_shift($calls); + $this->assertEquals($expected, $value); + }); $this->storage->expects($this->once()) ->method('mkdir'); @@ -106,8 +97,8 @@ class AvailabilityTest extends \Test\TestCase { * Storage marked available, but throws StorageNotAvailableException * */ - public function testAvailableThrowStorageNotAvailable() { - $this->expectException(\OCP\Files\StorageNotAvailableException::class); + public function testAvailableThrowStorageNotAvailable(): void { + $this->expectException(StorageNotAvailableException::class); $this->storage->expects($this->once()) ->method('getAvailability') @@ -116,7 +107,7 @@ class AvailabilityTest extends \Test\TestCase { ->method('test'); $this->storage->expects($this->once()) ->method('mkdir') - ->will($this->throwException(new StorageNotAvailableException())); + ->willThrowException(new StorageNotAvailableException()); $this->storageCache->expects($this->once()) ->method('setAvailability') ->with($this->equalTo(false)); @@ -128,7 +119,7 @@ class AvailabilityTest extends \Test\TestCase { * Storage available, but call fails * Method failure does not indicate storage unavailability */ - public function testAvailableFailure() { + public function testAvailableFailure(): void { $this->storage->expects($this->once()) ->method('getAvailability') ->willReturn(['available' => true, 'last_checked' => 0]); @@ -148,7 +139,7 @@ class AvailabilityTest extends \Test\TestCase { * Standard exception does not indicate storage unavailability * */ - public function testAvailableThrow() { + public function testAvailableThrow(): void { $this->expectException(\Exception::class); $this->storage->expects($this->once()) @@ -158,7 +149,7 @@ class AvailabilityTest extends \Test\TestCase { ->method('test'); $this->storage->expects($this->once()) ->method('mkdir') - ->will($this->throwException(new \Exception())); + ->willThrowException(new \Exception()); $this->storage->expects($this->never()) ->method('setAvailability'); diff --git a/tests/lib/Files/Storage/Wrapper/EncodingTest.php b/tests/lib/Files/Storage/Wrapper/EncodingTest.php index 0901edf83fa..cb6b6de0fb7 100644 --- a/tests/lib/Files/Storage/Wrapper/EncodingTest.php +++ b/tests/lib/Files/Storage/Wrapper/EncodingTest.php @@ -1,26 +1,29 @@ <?php + /** - * Copyright (c) 2016 Vincent Petry <pvince81@owncloud.com> - * This file is licensed under the Affero General Public License version 3 or - * later. - * See the COPYING-README file. + * SPDX-FileCopyrightText: 2019-2024 Nextcloud GmbH and Nextcloud contributors + * SPDX-FileCopyrightText: 2016 ownCloud, Inc. + * SPDX-License-Identifier: AGPL-3.0-or-later */ namespace Test\Files\Storage\Wrapper; +use OC\Files\Storage\Temporary; +use OC\Files\Storage\Wrapper\Encoding; + class EncodingTest extends \Test\Files\Storage\Storage { public const NFD_NAME = 'ümlaut'; public const NFC_NAME = 'ümlaut'; /** - * @var \OC\Files\Storage\Temporary + * @var Temporary */ private $sourceStorage; protected function setUp(): void { parent::setUp(); - $this->sourceStorage = new \OC\Files\Storage\Temporary([]); - $this->instance = new \OC\Files\Storage\Wrapper\Encoding([ + $this->sourceStorage = new Temporary([]); + $this->instance = new Encoding([ 'storage' => $this->sourceStorage ]); } @@ -30,43 +33,39 @@ class EncodingTest extends \Test\Files\Storage\Storage { parent::tearDown(); } - public function directoryProvider() { + public static function directoryProvider(): array { $a = parent::directoryProvider(); $a[] = [self::NFC_NAME]; return $a; } - public function fileNameProvider() { + public static function fileNameProvider(): array { $a = parent::fileNameProvider(); $a[] = [self::NFD_NAME . '.txt']; return $a; } - public function copyAndMoveProvider() { + public static function copyAndMoveProvider(): array { $a = parent::copyAndMoveProvider(); $a[] = [self::NFD_NAME . '.txt', self::NFC_NAME . '-renamed.txt']; return $a; } - public function accessNameProvider() { + public static function accessNameProvider(): array { return [ [self::NFD_NAME], [self::NFC_NAME], ]; } - /** - * @dataProvider accessNameProvider - */ - public function testFputEncoding($accessName) { + #[\PHPUnit\Framework\Attributes\DataProvider('accessNameProvider')] + public function testFputEncoding($accessName): void { $this->sourceStorage->file_put_contents(self::NFD_NAME, 'bar'); $this->assertEquals('bar', $this->instance->file_get_contents($accessName)); } - /** - * @dataProvider accessNameProvider - */ - public function testFopenReadEncoding($accessName) { + #[\PHPUnit\Framework\Attributes\DataProvider('accessNameProvider')] + public function testFopenReadEncoding($accessName): void { $this->sourceStorage->file_put_contents(self::NFD_NAME, 'bar'); $fh = $this->instance->fopen($accessName, 'r'); $data = fgets($fh); @@ -74,10 +73,8 @@ class EncodingTest extends \Test\Files\Storage\Storage { $this->assertEquals('bar', $data); } - /** - * @dataProvider accessNameProvider - */ - public function testFopenOverwriteEncoding($accessName) { + #[\PHPUnit\Framework\Attributes\DataProvider('accessNameProvider')] + public function testFopenOverwriteEncoding($accessName): void { $this->sourceStorage->file_put_contents(self::NFD_NAME, 'bar'); $fh = $this->instance->fopen($accessName, 'w'); $data = fputs($fh, 'test'); @@ -87,42 +84,36 @@ class EncodingTest extends \Test\Files\Storage\Storage { $this->assertFalse($this->sourceStorage->file_exists(self::NFC_NAME)); } - /** - * @dataProvider accessNameProvider - */ - public function testFileExistsEncoding($accessName) { + #[\PHPUnit\Framework\Attributes\DataProvider('accessNameProvider')] + public function testFileExistsEncoding($accessName): void { $this->sourceStorage->file_put_contents(self::NFD_NAME, 'bar'); $this->assertTrue($this->instance->file_exists($accessName)); } - /** - * @dataProvider accessNameProvider - */ - public function testUnlinkEncoding($accessName) { + #[\PHPUnit\Framework\Attributes\DataProvider('accessNameProvider')] + public function testUnlinkEncoding($accessName): void { $this->sourceStorage->file_put_contents(self::NFD_NAME, 'bar'); $this->assertTrue($this->instance->unlink($accessName)); $this->assertFalse($this->sourceStorage->file_exists(self::NFC_NAME)); $this->assertFalse($this->sourceStorage->file_exists(self::NFD_NAME)); } - public function testNfcHigherPriority() { + public function testNfcHigherPriority(): void { $this->sourceStorage->file_put_contents(self::NFC_NAME, 'nfc'); $this->sourceStorage->file_put_contents(self::NFD_NAME, 'nfd'); $this->assertEquals('nfc', $this->instance->file_get_contents(self::NFC_NAME)); } - public function encodedDirectoriesProvider() { + public static function encodedDirectoriesProvider(): array { return [ [self::NFD_NAME, self::NFC_NAME], [self::NFD_NAME . '/' . self::NFD_NAME, self::NFC_NAME . '/' . self::NFC_NAME], - [self::NFD_NAME . '/' . self::NFC_NAME . '/' .self::NFD_NAME, self::NFC_NAME . '/' . self::NFC_NAME . '/' . self::NFC_NAME], + [self::NFD_NAME . '/' . self::NFC_NAME . '/' . self::NFD_NAME, self::NFC_NAME . '/' . self::NFC_NAME . '/' . self::NFC_NAME], ]; } - /** - * @dataProvider encodedDirectoriesProvider - */ - public function testOperationInsideDirectory($sourceDir, $accessDir) { + #[\PHPUnit\Framework\Attributes\DataProvider('encodedDirectoriesProvider')] + public function testOperationInsideDirectory($sourceDir, $accessDir): void { $this->sourceStorage->mkdir($sourceDir); $this->instance->file_put_contents($accessDir . '/test.txt', 'bar'); $this->assertTrue($this->instance->file_exists($accessDir . '/test.txt')); @@ -139,7 +130,7 @@ class EncodingTest extends \Test\Files\Storage\Storage { $this->assertTrue($this->instance->file_exists($accessDir . '/' . self::NFC_NAME)); } - public function testCacheExtraSlash() { + public function testCacheExtraSlash(): void { $this->sourceStorage->file_put_contents(self::NFD_NAME, 'foo'); $this->assertEquals(3, $this->instance->file_put_contents(self::NFC_NAME, 'bar')); $this->assertEquals('bar', $this->instance->file_get_contents(self::NFC_NAME)); @@ -151,7 +142,7 @@ class EncodingTest extends \Test\Files\Storage\Storage { $this->assertEquals('barbaric', $this->instance->file_get_contents('//' . self::NFC_NAME)); } - public function sourceAndTargetDirectoryProvider() { + public static function sourceAndTargetDirectoryProvider(): array { return [ [self::NFC_NAME . '1', self::NFC_NAME . '2'], [self::NFD_NAME . '1', self::NFC_NAME . '2'], @@ -160,10 +151,8 @@ class EncodingTest extends \Test\Files\Storage\Storage { ]; } - /** - * @dataProvider sourceAndTargetDirectoryProvider - */ - public function testCopyAndMoveEncodedFolder($sourceDir, $targetDir) { + #[\PHPUnit\Framework\Attributes\DataProvider('sourceAndTargetDirectoryProvider')] + public function testCopyAndMoveEncodedFolder($sourceDir, $targetDir): void { $this->sourceStorage->mkdir($sourceDir); $this->sourceStorage->mkdir($targetDir); $this->sourceStorage->file_put_contents($sourceDir . '/test.txt', 'bar'); @@ -180,10 +169,8 @@ class EncodingTest extends \Test\Files\Storage\Storage { $this->assertEquals('bar', $this->instance->file_get_contents(self::NFC_NAME . '2/test2.txt')); } - /** - * @dataProvider sourceAndTargetDirectoryProvider - */ - public function testCopyAndMoveFromStorageEncodedFolder($sourceDir, $targetDir) { + #[\PHPUnit\Framework\Attributes\DataProvider('sourceAndTargetDirectoryProvider')] + public function testCopyAndMoveFromStorageEncodedFolder($sourceDir, $targetDir): void { $this->sourceStorage->mkdir($sourceDir); $this->sourceStorage->mkdir($targetDir); $this->sourceStorage->file_put_contents($sourceDir . '/test.txt', 'bar'); @@ -200,7 +187,7 @@ class EncodingTest extends \Test\Files\Storage\Storage { $this->assertEquals('bar', $this->instance->file_get_contents(self::NFC_NAME . '2/test2.txt')); } - public function testNormalizedDirectoryEntriesOpenDir() { + public function testNormalizedDirectoryEntriesOpenDir(): void { $this->sourceStorage->mkdir('/test'); $this->sourceStorage->mkdir('/test/' . self::NFD_NAME); @@ -209,7 +196,7 @@ class EncodingTest extends \Test\Files\Storage\Storage { $dh = $this->instance->opendir('/test'); $content = []; - while ($file = readdir($dh)) { + while (($file = readdir($dh)) !== false) { if ($file != '.' and $file != '..') { $content[] = $file; } @@ -219,7 +206,7 @@ class EncodingTest extends \Test\Files\Storage\Storage { $this->assertEquals(self::NFC_NAME, $content[0]); } - public function testNormalizedDirectoryEntriesGetDirectoryContent() { + public function testNormalizedDirectoryEntriesGetDirectoryContent(): void { $this->sourceStorage->mkdir('/test'); $this->sourceStorage->mkdir('/test/' . self::NFD_NAME); @@ -231,7 +218,7 @@ class EncodingTest extends \Test\Files\Storage\Storage { $this->assertEquals(self::NFC_NAME, $content[0]['name']); } - public function testNormalizedGetMetaData() { + public function testNormalizedGetMetaData(): void { $this->sourceStorage->mkdir('/test'); $this->sourceStorage->mkdir('/test/' . self::NFD_NAME); @@ -241,4 +228,12 @@ class EncodingTest extends \Test\Files\Storage\Storage { $entry = $this->instance->getMetaData('/test/' . self::NFD_NAME); $this->assertEquals(self::NFC_NAME, $entry['name']); } + + /** + * Regression test of https://github.com/nextcloud/server/issues/50431 + */ + public function testNoMetadata() { + $this->assertNull($this->instance->getMetaData('/test/null')); + } + } diff --git a/tests/lib/Files/Storage/Wrapper/EncryptionTest.php b/tests/lib/Files/Storage/Wrapper/EncryptionTest.php index ae776e40666..3e643714300 100644 --- a/tests/lib/Files/Storage/Wrapper/EncryptionTest.php +++ b/tests/lib/Files/Storage/Wrapper/EncryptionTest.php @@ -1,11 +1,20 @@ <?php +/** + * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors + * SPDX-FileCopyrightText: 2016 ownCloud, Inc. + * SPDX-License-Identifier: AGPL-3.0-only + */ + namespace Test\Files\Storage\Wrapper; +use Exception; use OC\Encryption\Exceptions\ModuleDoesNotExistsException; -use OC\Encryption\Update; +use OC\Encryption\File; use OC\Encryption\Util; +use OC\Files\Cache\Cache; use OC\Files\Cache\CacheEntry; +use OC\Files\Mount\MountPoint; use OC\Files\Storage\Temporary; use OC\Files\Storage\Wrapper\Encryption; use OC\Files\View; @@ -19,103 +28,43 @@ use OCP\Files\Cache\ICache; use OCP\Files\Mount\IMountPoint; use OCP\ICacheFactory; use OCP\IConfig; +use OCP\ITempManager; +use OCP\Server; +use PHPUnit\Framework\MockObject\MockObject; use Psr\Log\LoggerInterface; -use Symfony\Component\EventDispatcher\EventDispatcherInterface; use Test\Files\Storage\Storage; class EncryptionTest extends Storage { /** * block size will always be 8192 for a PHP stream * @see https://bugs.php.net/bug.php?id=21641 - * @var integer - */ - protected $headerSize = 8192; - - /** - * @var Temporary - */ - private $sourceStorage; - - /** - * @var \OC\Files\Storage\Wrapper\Encryption | \PHPUnit\Framework\MockObject\MockObject */ + protected int $headerSize = 8192; + private Temporary $sourceStorage; + /** @var Encryption&MockObject */ protected $instance; - - /** - * @var \OC\Encryption\Keys\Storage | \PHPUnit\Framework\MockObject\MockObject - */ - private $keyStore; - - /** - * @var \OC\Encryption\Util | \PHPUnit\Framework\MockObject\MockObject - */ - private $util; - - /** - * @var \OC\Encryption\Manager | \PHPUnit\Framework\MockObject\MockObject - */ - private $encryptionManager; - - /** - * @var \OCP\Encryption\IEncryptionModule | \PHPUnit\Framework\MockObject\MockObject - */ - private $encryptionModule; - - /** - * @var \OC\Encryption\Update | \PHPUnit\Framework\MockObject\MockObject - */ - private $update; - - /** - * @var \OC\Files\Cache\Cache | \PHPUnit\Framework\MockObject\MockObject - */ - private $cache; - - /** - * @var \OC\Log | \PHPUnit\Framework\MockObject\MockObject - */ - private $logger; - - /** - * @var \OC\Encryption\File | \PHPUnit\Framework\MockObject\MockObject - */ - private $file; - - - /** - * @var \OC\Files\Mount\MountPoint | \PHPUnit\Framework\MockObject\MockObject - */ - private $mount; - - /** - * @var \OC\Files\Mount\Manager | \PHPUnit\Framework\MockObject\MockObject - */ - private $mountManager; - - /** - * @var \OC\Group\Manager | \PHPUnit\Framework\MockObject\MockObject - */ - private $groupManager; - - /** - * @var \OCP\IConfig | \PHPUnit\Framework\MockObject\MockObject - */ - private $config; - - /** @var \OC\Memcache\ArrayCache | \PHPUnit\Framework\MockObject\MockObject */ - private $arrayCache; - - - /** @var integer dummy unencrypted size */ - private $dummySize = -1; + private \OC\Encryption\Keys\Storage&MockObject $keyStore; + private Util&MockObject $util; + private \OC\Encryption\Manager&MockObject $encryptionManager; + private IEncryptionModule&MockObject $encryptionModule; + private Cache&MockObject $cache; + private LoggerInterface&MockObject $logger; + private File&MockObject $file; + private MountPoint&MockObject $mount; + private \OC\Files\Mount\Manager&MockObject $mountManager; + private \OC\Group\Manager&MockObject $groupManager; + private IConfig&MockObject $config; + private ArrayCache&MockObject $arrayCache; + /** dummy unencrypted size */ + private int $dummySize = -1; protected function setUp(): void { parent::setUp(); $mockModule = $this->buildMockModule(); - $this->encryptionManager = $this->getMockBuilder('\OC\Encryption\Manager') + $this->encryptionManager = $this->getMockBuilder(\OC\Encryption\Manager::class) ->disableOriginalConstructor() - ->setMethods(['getEncryptionModule', 'isEnabled']) + ->onlyMethods(['getEncryptionModule', 'isEnabled']) ->getMock(); $this->encryptionManager->expects($this->any()) ->method('getEncryptionModule') @@ -129,13 +78,13 @@ class EncryptionTest extends Storage { ->disableOriginalConstructor() ->getMock(); - $this->util = $this->getMockBuilder('\OC\Encryption\Util') - ->setMethods(['getUidAndFilename', 'isFile', 'isExcluded']) + $this->util = $this->getMockBuilder(Util::class) + ->onlyMethods(['getUidAndFilename', 'isFile', 'isExcluded', 'stripPartialFileExtension']) ->setConstructorArgs([new View(), new Manager( $this->config, - $this->createMock(EventDispatcherInterface::class), $this->createMock(ICacheFactory::class), - $this->createMock(IEventDispatcher::class) + $this->createMock(IEventDispatcher::class), + $this->createMock(LoggerInterface::class), ), $this->groupManager, $this->config, $this->arrayCache]) ->getMock(); $this->util->expects($this->any()) @@ -143,10 +92,15 @@ class EncryptionTest extends Storage { ->willReturnCallback(function ($path) { return ['user1', $path]; }); + $this->util->expects($this->any()) + ->method('stripPartialFileExtension') + ->willReturnCallback(function ($path) { + return $path; + }); - $this->file = $this->getMockBuilder('\OC\Encryption\File') + $this->file = $this->getMockBuilder(File::class) ->disableOriginalConstructor() - ->setMethods(['getAccessList']) + ->onlyMethods(['getAccessList']) ->getMock(); $this->file->expects($this->any())->method('getAccessList')->willReturn([]); @@ -154,15 +108,11 @@ class EncryptionTest extends Storage { $this->sourceStorage = new Temporary([]); - $this->keyStore = $this->getMockBuilder('\OC\Encryption\Keys\Storage') - ->disableOriginalConstructor()->getMock(); - - $this->update = $this->getMockBuilder('\OC\Encryption\Update') - ->disableOriginalConstructor()->getMock(); + $this->keyStore = $this->createMock(\OC\Encryption\Keys\Storage::class); - $this->mount = $this->getMockBuilder('\OC\Files\Mount\MountPoint') + $this->mount = $this->getMockBuilder(MountPoint::class) ->disableOriginalConstructor() - ->setMethods(['getOption']) + ->onlyMethods(['getOption']) ->getMock(); $this->mount->expects($this->any())->method('getOption')->willReturnCallback(function ($option, $default) { if ($option === 'encrypt' && $default === true) { @@ -186,7 +136,7 @@ class EncryptionTest extends Storage { $this->mountManager->method('findByStorageId') ->willReturn([]); - $this->instance = $this->getMockBuilder('\OC\Files\Storage\Wrapper\Encryption') + $this->instance = $this->getMockBuilder(Encryption::class) ->setConstructorArgs( [ [ @@ -195,10 +145,17 @@ class EncryptionTest extends Storage { 'mountPoint' => '/', 'mount' => $this->mount ], - $this->encryptionManager, $this->util, $this->logger, $this->file, null, $this->keyStore, $this->update, $this->mountManager, $this->arrayCache + $this->encryptionManager, + $this->util, + $this->logger, + $this->file, + null, + $this->keyStore, + $this->mountManager, + $this->arrayCache ] ) - ->setMethods(['getMetaData', 'getCache', 'getEncryptionModule']) + ->onlyMethods(['getMetaData', 'getCache', 'getEncryptionModule']) ->getMock(); $this->instance->expects($this->any()) @@ -216,13 +173,10 @@ class EncryptionTest extends Storage { ->willReturn($mockModule); } - /** - * @return \PHPUnit\Framework\MockObject\MockObject - */ - protected function buildMockModule() { + protected function buildMockModule(): IEncryptionModule&MockObject { $this->encryptionModule = $this->getMockBuilder('\OCP\Encryption\IEncryptionModule') ->disableOriginalConstructor() - ->setMethods(['getId', 'getDisplayName', 'begin', 'end', 'encrypt', 'decrypt', 'update', 'shouldEncrypt', 'getUnencryptedBlockSize', 'isReadable', 'encryptAll', 'prepareDecryptAll', 'isReadyForUser', 'needDetailedAccessList']) + ->onlyMethods(['getId', 'getDisplayName', 'begin', 'end', 'encrypt', 'decrypt', 'update', 'shouldEncrypt', 'getUnencryptedBlockSize', 'isReadable', 'encryptAll', 'prepareDecryptAll', 'isReadyForUser', 'needDetailedAccessList']) ->getMock(); $this->encryptionModule->expects($this->any())->method('getId')->willReturn('UNIT_TEST_MODULE'); @@ -240,7 +194,6 @@ class EncryptionTest extends Storage { } /** - * @dataProvider dataTestGetMetaData * * @param string $path * @param array $metaData @@ -249,7 +202,8 @@ class EncryptionTest extends Storage { * @param int $storedUnencryptedSize * @param array $expected */ - public function testGetMetaData($path, $metaData, $encrypted, $unencryptedSizeSet, $storedUnencryptedSize, $expected) { + #[\PHPUnit\Framework\Attributes\DataProvider('dataTestGetMetaData')] + public function testGetMetaData($path, $metaData, $encrypted, $unencryptedSizeSet, $storedUnencryptedSize, $expected): void { $sourceStorage = $this->getMockBuilder('\OC\Files\Storage\Storage') ->disableOriginalConstructor()->getMock(); @@ -263,7 +217,7 @@ class EncryptionTest extends Storage { } ); - $this->instance = $this->getMockBuilder('\OC\Files\Storage\Wrapper\Encryption') + $this->instance = $this->getMockBuilder(Encryption::class) ->setConstructorArgs( [ [ @@ -272,10 +226,17 @@ class EncryptionTest extends Storage { 'mountPoint' => '/', 'mount' => $this->mount ], - $this->encryptionManager, $this->util, $this->logger, $this->file, null, $this->keyStore, $this->update, $this->mountManager, $this->arrayCache + $this->encryptionManager, + $this->util, + $this->logger, + $this->file, + null, + $this->keyStore, + $this->mountManager, + $this->arrayCache, ] ) - ->setMethods(['getCache', 'verifyUnencryptedSize']) + ->onlyMethods(['getCache', 'verifyUnencryptedSize']) ->getMock(); if ($unencryptedSizeSet) { @@ -318,7 +279,7 @@ class EncryptionTest extends Storage { } } - public function dataTestGetMetaData() { + public static function dataTestGetMetaData(): array { return [ ['/test.txt', ['size' => 42, 'encrypted' => 2, 'encryptedVersion' => 2, 'fileid' => 1], true, true, 12, ['size' => 12, 'encrypted' => true, 'encryptedVersion' => 2]], ['/test.txt', null, true, true, 12, null], @@ -327,14 +288,14 @@ class EncryptionTest extends Storage { ]; } - public function testFilesize() { + public function testFilesize(): void { $cache = $this->getMockBuilder('\OC\Files\Cache\Cache') ->disableOriginalConstructor()->getMock(); $cache->expects($this->any()) ->method('get') ->willReturn(new CacheEntry(['encrypted' => true, 'path' => '/test.txt', 'size' => 0, 'fileid' => 1])); - $this->instance = $this->getMockBuilder('\OC\Files\Storage\Wrapper\Encryption') + $this->instance = $this->getMockBuilder(Encryption::class) ->setConstructorArgs( [ [ @@ -343,10 +304,17 @@ class EncryptionTest extends Storage { 'mountPoint' => '/', 'mount' => $this->mount ], - $this->encryptionManager, $this->util, $this->logger, $this->file, null, $this->keyStore, $this->update, $this->mountManager, $this->arrayCache + $this->encryptionManager, + $this->util, + $this->logger, + $this->file, + null, + $this->keyStore, + $this->mountManager, + $this->arrayCache, ] ) - ->setMethods(['getCache', 'verifyUnencryptedSize']) + ->onlyMethods(['getCache', 'verifyUnencryptedSize']) ->getMock(); $this->instance->expects($this->any())->method('getCache')->willReturn($cache); @@ -360,18 +328,18 @@ class EncryptionTest extends Storage { } /** - * @dataProvider dataTestVerifyUnencryptedSize * * @param int $encryptedSize * @param int $unencryptedSize * @param bool $failure * @param int $expected */ - public function testVerifyUnencryptedSize($encryptedSize, $unencryptedSize, $failure, $expected) { + #[\PHPUnit\Framework\Attributes\DataProvider('dataTestVerifyUnencryptedSize')] + public function testVerifyUnencryptedSize($encryptedSize, $unencryptedSize, $failure, $expected): void { $sourceStorage = $this->getMockBuilder('\OC\Files\Storage\Storage') ->disableOriginalConstructor()->getMock(); - $this->instance = $this->getMockBuilder('\OC\Files\Storage\Wrapper\Encryption') + $this->instance = $this->getMockBuilder(Encryption::class) ->setConstructorArgs( [ [ @@ -380,10 +348,17 @@ class EncryptionTest extends Storage { 'mountPoint' => '/', 'mount' => $this->mount ], - $this->encryptionManager, $this->util, $this->logger, $this->file, null, $this->keyStore, $this->update, $this->mountManager, $this->arrayCache + $this->encryptionManager, + $this->util, + $this->logger, + $this->file, + null, + $this->keyStore, + $this->mountManager, + $this->arrayCache, ] ) - ->setMethods(['fixUnencryptedSize']) + ->onlyMethods(['fixUnencryptedSize']) ->getMock(); $sourceStorage->expects($this->once())->method('filesize')->willReturn($encryptedSize); @@ -393,7 +368,7 @@ class EncryptionTest extends Storage { ->willReturnCallback( function () use ($failure, $expected) { if ($failure) { - throw new \Exception(); + throw new Exception(); } else { return $expected; } @@ -406,7 +381,7 @@ class EncryptionTest extends Storage { ); } - public function dataTestVerifyUnencryptedSize() { + public static function dataTestVerifyUnencryptedSize(): array { return [ [120, 80, false, 80], [120, 120, false, 80], @@ -416,17 +391,17 @@ class EncryptionTest extends Storage { } /** - * @dataProvider dataTestCopyAndRename * * @param string $source * @param string $target * @param $encryptionEnabled * @param boolean $renameKeysReturn */ + #[\PHPUnit\Framework\Attributes\DataProvider('dataTestCopyAndRename')] public function testRename($source, - $target, - $encryptionEnabled, - $renameKeysReturn) { + $target, + $encryptionEnabled, + $renameKeysReturn): void { if ($encryptionEnabled) { $this->keyStore ->expects($this->once()) @@ -446,7 +421,7 @@ class EncryptionTest extends Storage { $this->instance->rename($source, $target); } - public function testCopyEncryption() { + public function testCopyEncryption(): void { $this->instance->file_put_contents('source.txt', 'bar'); $this->instance->copy('source.txt', 'target.txt'); $this->assertSame('bar', $this->instance->file_get_contents('target.txt')); @@ -461,7 +436,7 @@ class EncryptionTest extends Storage { * * @return array */ - public function dataTestCopyAndRename() { + public static function dataTestCopyAndRename(): array { return [ ['source', 'target', true, false, false], ['source', 'target', true, true, false], @@ -471,38 +446,45 @@ class EncryptionTest extends Storage { ]; } - public function testIsLocal() { + public function testIsLocal(): void { $this->encryptionManager->expects($this->once()) ->method('isEnabled')->willReturn(true); $this->assertFalse($this->instance->isLocal()); } /** - * @dataProvider dataTestRmdir * * @param string $path * @param boolean $rmdirResult * @param boolean $isExcluded * @param boolean $encryptionEnabled */ - public function testRmdir($path, $rmdirResult, $isExcluded, $encryptionEnabled) { + #[\PHPUnit\Framework\Attributes\DataProvider('dataTestRmdir')] + public function testRmdir($path, $rmdirResult, $isExcluded, $encryptionEnabled): void { $sourceStorage = $this->getMockBuilder('\OC\Files\Storage\Storage') ->disableOriginalConstructor()->getMock(); $util = $this->getMockBuilder('\OC\Encryption\Util')->disableOriginalConstructor()->getMock(); $sourceStorage->expects($this->once())->method('rmdir')->willReturn($rmdirResult); - $util->expects($this->any())->method('isExcluded')-> willReturn($isExcluded); + $util->expects($this->any())->method('isExcluded')->willReturn($isExcluded); $this->encryptionManager->expects($this->any())->method('isEnabled')->willReturn($encryptionEnabled); - $encryptionStorage = new \OC\Files\Storage\Wrapper\Encryption( + $encryptionStorage = new Encryption( [ 'storage' => $sourceStorage, 'root' => 'foo', 'mountPoint' => '/mountPoint', 'mount' => $this->mount ], - $this->encryptionManager, $util, $this->logger, $this->file, null, $this->keyStore, $this->update + $this->encryptionManager, + $util, + $this->logger, + $this->file, + null, + $this->keyStore, + $this->mountManager, + $this->arrayCache, ); @@ -515,7 +497,7 @@ class EncryptionTest extends Storage { $encryptionStorage->rmdir($path); } - public function dataTestRmdir() { + public static function dataTestRmdir(): array { return [ ['/file.txt', true, true, true], ['/file.txt', false, true, true], @@ -529,12 +511,12 @@ class EncryptionTest extends Storage { } /** - * @dataProvider dataTestCopyKeys * * @param boolean $excluded * @param boolean $expected */ - public function testCopyKeys($excluded, $expected) { + #[\PHPUnit\Framework\Attributes\DataProvider('dataTestCopyKeys')] + public function testCopyKeys($excluded, $expected): void { $this->util->expects($this->once()) ->method('isExcluded') ->willReturn($excluded); @@ -550,7 +532,7 @@ class EncryptionTest extends Storage { ); } - public function dataTestCopyKeys() { + public static function dataTestCopyKeys(): array { return [ [true, false], [false, true], @@ -558,13 +540,13 @@ class EncryptionTest extends Storage { } /** - * @dataProvider dataTestGetHeader * * @param string $path * @param bool $strippedPathExists * @param string $strippedPath */ - public function testGetHeader($path, $strippedPathExists, $strippedPath) { + #[\PHPUnit\Framework\Attributes\DataProvider('dataTestGetHeader')] + public function testGetHeader($path, $strippedPathExists, $strippedPath): void { $sourceStorage = $this->getMockBuilder('\OC\Files\Storage\Storage') ->disableOriginalConstructor()->getMock(); @@ -574,9 +556,9 @@ class EncryptionTest extends Storage { new View(), new Manager( $this->config, - $this->createMock(EventDispatcherInterface::class), $this->createMock(ICacheFactory::class), - $this->createMock(IEventDispatcher::class) + $this->createMock(IEventDispatcher::class), + $this->createMock(LoggerInterface::class), ), $this->groupManager, $this->config, @@ -592,7 +574,7 @@ class EncryptionTest extends Storage { return ['encrypted' => true, 'path' => $path]; }); - $instance = $this->getMockBuilder('\OC\Files\Storage\Wrapper\Encryption') + $instance = $this->getMockBuilder(Encryption::class) ->setConstructorArgs( [ [ @@ -601,22 +583,29 @@ class EncryptionTest extends Storage { 'mountPoint' => '/', 'mount' => $this->mount ], - $this->encryptionManager, $util, $this->logger, $this->file, null, $this->keyStore, $this->update, $this->mountManager, $this->arrayCache + $this->encryptionManager, + $util, + $this->logger, + $this->file, + null, + $this->keyStore, + $this->mountManager, + $this->arrayCache, ] ) - ->setMethods(['getCache','readFirstBlock', 'parseRawHeader']) + ->onlyMethods(['getCache', 'readFirstBlock']) ->getMock(); - $instance->expects($this->once())->method('getCache')->willReturn($cache); + $instance->method('getCache')->willReturn($cache); - $instance->expects($this->once())->method(('parseRawHeader')) + $util->method('parseRawHeader') ->willReturn([Util::HEADER_ENCRYPTION_MODULE_KEY => 'OC_DEFAULT_MODULE']); if ($strippedPathExists) { - $instance->expects($this->once())->method('readFirstBlock') + $instance->method('readFirstBlock') ->with($strippedPath)->willReturn(''); } else { - $instance->expects($this->once())->method('readFirstBlock') + $instance->method('readFirstBlock') ->with($path)->willReturn(''); } @@ -630,7 +619,7 @@ class EncryptionTest extends Storage { $this->invokePrivate($instance, 'getHeader', [$path]); } - public function dataTestGetHeader() { + public static function dataTestGetHeader(): array { return [ ['/foo/bar.txt', false, '/foo/bar.txt'], ['/foo/bar.txt.part', false, '/foo/bar.txt'], @@ -643,35 +632,40 @@ class EncryptionTest extends Storage { /** * test if getHeader adds the default module correctly to the header for * legacy files - * - * @dataProvider dataTestGetHeaderAddLegacyModule */ - public function testGetHeaderAddLegacyModule($header, $isEncrypted, $exists, $expected) { - $sourceStorage = $this->getMockBuilder('\OC\Files\Storage\Storage') + #[\PHPUnit\Framework\Attributes\DataProvider('dataTestGetHeaderAddLegacyModule')] + public function testGetHeaderAddLegacyModule($header, $isEncrypted, $strippedPathExists, $expected): void { + $sourceStorage = $this->getMockBuilder(\OC\Files\Storage\Storage::class) ->disableOriginalConstructor()->getMock(); $sourceStorage->expects($this->once()) ->method('is_file') - ->willReturn($exists); + ->with('test.txt') + ->willReturn($strippedPathExists); - $util = $this->getMockBuilder('\OC\Encryption\Util') + $util = $this->getMockBuilder(Util::class) + ->onlyMethods(['stripPartialFileExtension', 'parseRawHeader']) ->setConstructorArgs([new View(), new Manager( $this->config, - $this->createMock(EventDispatcherInterface::class), $this->createMock(ICacheFactory::class), - $this->createMock(IEventDispatcher::class) + $this->createMock(IEventDispatcher::class), + $this->createMock(LoggerInterface::class), ), $this->groupManager, $this->config, $this->arrayCache]) ->getMock(); + $util->expects($this->any()) + ->method('stripPartialFileExtension') + ->willReturnCallback(function ($path) { + return $path; + }); - $cache = $this->getMockBuilder('\OC\Files\Cache\Cache') - ->disableOriginalConstructor()->getMock(); + $cache = $this->createMock(Cache::class); $cache->expects($this->any()) ->method('get') ->willReturnCallback(function ($path) use ($isEncrypted) { return ['encrypted' => $isEncrypted, 'path' => $path]; }); - $instance = $this->getMockBuilder('\OC\Files\Storage\Wrapper\Encryption') + $instance = $this->getMockBuilder(Encryption::class) ->setConstructorArgs( [ [ @@ -680,14 +674,23 @@ class EncryptionTest extends Storage { 'mountPoint' => '/', 'mount' => $this->mount ], - $this->encryptionManager, $util, $this->logger, $this->file, null, $this->keyStore, $this->update, $this->mountManager, $this->arrayCache + $this->encryptionManager, + $util, + $this->logger, + $this->file, + null, + $this->keyStore, + $this->mountManager, + $this->arrayCache, ] ) - ->setMethods(['readFirstBlock', 'parseRawHeader', 'getCache']) + ->onlyMethods(['readFirstBlock', 'getCache']) ->getMock(); - $instance->expects($this->any())->method(('parseRawHeader'))->willReturn($header); - $instance->expects($this->once())->method('getCache')->willReturn($cache); + $instance->method('readFirstBlock')->willReturn(''); + + $util->method(('parseRawHeader'))->willReturn($header); + $instance->method('getCache')->willReturn($cache); $result = $this->invokePrivate($instance, 'getHeader', ['test.txt']); $this->assertSameSize($expected, $result); @@ -697,7 +700,7 @@ class EncryptionTest extends Storage { } } - public function dataTestGetHeaderAddLegacyModule() { + public static function dataTestGetHeaderAddLegacyModule(): array { return [ [['cipher' => 'AES-128'], true, true, ['cipher' => 'AES-128', Util::HEADER_ENCRYPTION_MODULE_KEY => 'OC_DEFAULT_MODULE']], [[], true, false, []], @@ -706,45 +709,7 @@ class EncryptionTest extends Storage { ]; } - /** - * @dataProvider dataTestParseRawHeader - */ - public function testParseRawHeader($rawHeader, $expected) { - $instance = new \OC\Files\Storage\Wrapper\Encryption( - [ - 'storage' => $this->sourceStorage, - 'root' => 'foo', - 'mountPoint' => '/', - 'mount' => $this->mount - ], - $this->encryptionManager, $this->util, $this->logger, $this->file, null, $this->keyStore, $this->update, $this->mountManager, $this->arrayCache - - ); - - $result = $this->invokePrivate($instance, 'parseRawHeader', [$rawHeader]); - $this->assertSameSize($expected, $result); - foreach ($result as $key => $value) { - $this->assertArrayHasKey($key, $expected); - $this->assertSame($expected[$key], $value); - } - } - - public function dataTestParseRawHeader() { - return [ - [str_pad('HBEGIN:oc_encryption_module:0:HEND', $this->headerSize, '-', STR_PAD_RIGHT) - , [Util::HEADER_ENCRYPTION_MODULE_KEY => '0']], - [str_pad('HBEGIN:oc_encryption_module:0:custom_header:foo:HEND', $this->headerSize, '-', STR_PAD_RIGHT) - , ['custom_header' => 'foo', Util::HEADER_ENCRYPTION_MODULE_KEY => '0']], - [str_pad('HelloWorld', $this->headerSize, '-', STR_PAD_RIGHT), []], - ['', []], - [str_pad('HBEGIN:oc_encryption_module:0', $this->headerSize, '-', STR_PAD_RIGHT) - , []], - [str_pad('oc_encryption_module:0:HEND', $this->headerSize, '-', STR_PAD_RIGHT) - , []], - ]; - } - - public function dataCopyBetweenStorage() { + public static function dataCopyBetweenStorage(): array { return [ [true, true, true], [true, false, false], @@ -753,7 +718,7 @@ class EncryptionTest extends Storage { ]; } - public function testCopyBetweenStorageMinimumEncryptedVersion() { + public function testCopyBetweenStorageMinimumEncryptedVersion(): void { $storage2 = $this->createMock(\OC\Files\Storage\Storage::class); $sourceInternalPath = $targetInternalPath = 'file.txt'; @@ -762,7 +727,7 @@ class EncryptionTest extends Storage { $storage2->expects($this->any()) ->method('fopen') ->willReturnCallback(function ($path, $mode) { - $temp = \OC::$server->getTempManager(); + $temp = Server::get(ITempManager::class); return fopen($temp->getTemporaryFile(), $mode); }); $storage2->method('getId') @@ -796,13 +761,13 @@ class EncryptionTest extends Storage { } /** - * @dataProvider dataCopyBetweenStorage * * @param bool $encryptionEnabled * @param bool $mountPointEncryptionEnabled * @param bool $expectedEncrypted */ - public function testCopyBetweenStorage($encryptionEnabled, $mountPointEncryptionEnabled, $expectedEncrypted) { + #[\PHPUnit\Framework\Attributes\DataProvider('dataCopyBetweenStorage')] + public function testCopyBetweenStorage($encryptionEnabled, $mountPointEncryptionEnabled, $expectedEncrypted): void { $storage2 = $this->createMock(\OC\Files\Storage\Storage::class); $sourceInternalPath = $targetInternalPath = 'file.txt'; @@ -811,7 +776,7 @@ class EncryptionTest extends Storage { $storage2->expects($this->any()) ->method('fopen') ->willReturnCallback(function ($path, $mode) { - $temp = \OC::$server->getTempManager(); + $temp = Server::get(ITempManager::class); return fopen($temp->getTemporaryFile(), $mode); }); $storage2->method('getId') @@ -830,10 +795,10 @@ class EncryptionTest extends Storage { ->method('isEnabled') ->willReturn($encryptionEnabled); // FIXME can not overwrite the return after definition -// $this->mount->expects($this->at(0)) -// ->method('getOption') -// ->with('encrypt', true) -// ->willReturn($mountPointEncryptionEnabled); + // $this->mount->expects($this->at(0)) + // ->method('getOption') + // ->with('encrypt', true) + // ->willReturn($mountPointEncryptionEnabled); global $mockedMountPointEncryptionEnabled; $mockedMountPointEncryptionEnabled = $mountPointEncryptionEnabled; @@ -856,14 +821,14 @@ class EncryptionTest extends Storage { } /** - * @dataProvider dataTestCopyBetweenStorageVersions * * @param string $sourceInternalPath * @param string $targetInternalPath * @param bool $copyResult * @param bool $encrypted */ - public function testCopyBetweenStorageVersions($sourceInternalPath, $targetInternalPath, $copyResult, $encrypted) { + #[\PHPUnit\Framework\Attributes\DataProvider('dataTestCopyBetweenStorageVersions')] + public function testCopyBetweenStorageVersions($sourceInternalPath, $targetInternalPath, $copyResult, $encrypted): void { $sourceStorage = $this->createMock(\OC\Files\Storage\Storage::class); $targetStorage = $this->createMock(\OC\Files\Storage\Storage::class); @@ -873,8 +838,8 @@ class EncryptionTest extends Storage { $mountPoint = '/mountPoint'; - /** @var \OC\Files\Storage\Wrapper\Encryption |\PHPUnit\Framework\MockObject\MockObject $instance */ - $instance = $this->getMockBuilder('\OC\Files\Storage\Wrapper\Encryption') + /** @var Encryption |MockObject $instance */ + $instance = $this->getMockBuilder(Encryption::class) ->setConstructorArgs( [ [ @@ -889,12 +854,11 @@ class EncryptionTest extends Storage { $this->file, null, $this->keyStore, - $this->update, $this->mountManager, $this->arrayCache ] ) - ->setMethods(['updateUnencryptedSize', 'getCache']) + ->onlyMethods(['updateUnencryptedSize', 'getCache']) ->getMock(); $targetStorage->expects($this->once())->method('copyFromStorage') @@ -936,7 +900,7 @@ class EncryptionTest extends Storage { $this->assertSame($copyResult, $result); } - public function dataTestCopyBetweenStorageVersions() { + public static function dataTestCopyBetweenStorageVersions(): array { return [ ['/files/foo.txt', '/files_versions/foo.txt.768743', true, true], ['/files/foo.txt', '/files_versions/foo.txt.768743', true, false], @@ -951,17 +915,17 @@ class EncryptionTest extends Storage { } /** - * @dataProvider dataTestIsVersion * @param string $path * @param bool $expected */ - public function testIsVersion($path, $expected) { + #[\PHPUnit\Framework\Attributes\DataProvider('dataTestIsVersion')] + public function testIsVersion($path, $expected): void { $this->assertSame($expected, $this->invokePrivate($this->instance, 'isVersion', [$path]) ); } - public function dataTestIsVersion() { + public static function dataTestIsVersion(): array { return [ ['files_versions/foo', true], ['/files_versions/foo', true], @@ -973,25 +937,23 @@ class EncryptionTest extends Storage { } /** - * @dataProvider dataTestShouldEncrypt * * @param bool $encryptMountPoint * @param mixed $encryptionModule * @param bool $encryptionModuleShouldEncrypt * @param bool $expected */ + #[\PHPUnit\Framework\Attributes\DataProvider('dataTestShouldEncrypt')] public function testShouldEncrypt( $encryptMountPoint, $encryptionModule, $encryptionModuleShouldEncrypt, - $expected - ) { + $expected, + ): void { $encryptionManager = $this->createMock(\OC\Encryption\Manager::class); $util = $this->createMock(Util::class); $fileHelper = $this->createMock(IFile::class); - $uid = null; $keyStorage = $this->createMock(IStorage::class); - $update = $this->createMock(Update::class); $mountManager = $this->createMock(\OC\Files\Mount\Manager::class); $mount = $this->createMock(IMountPoint::class); $arrayCache = $this->createMock(ArrayCache::class); @@ -1007,18 +969,17 @@ class EncryptionTest extends Storage { $util, $this->logger, $fileHelper, - $uid, + null, $keyStorage, - $update, $mountManager, $arrayCache ] ) - ->setMethods(['getFullPath', 'getEncryptionModule']) + ->onlyMethods(['getFullPath', 'getEncryptionModule']) ->getMock(); if ($encryptionModule === true) { - /** @var IEncryptionModule|\PHPUnit\Framework\MockObject\MockObject $encryptionModule */ + /** @var IEncryptionModule|MockObject $encryptionModule */ $encryptionModule = $this->createMock(IEncryptionModule::class); } @@ -1056,7 +1017,7 @@ class EncryptionTest extends Storage { $this->assertSame($expected, $result); } - public function dataTestShouldEncrypt() { + public static function dataTestShouldEncrypt(): array { return [ [false, false, false, false], [true, false, false, false], diff --git a/tests/lib/Files/Storage/Wrapper/JailTest.php b/tests/lib/Files/Storage/Wrapper/JailTest.php index 148bd3a4f30..0043e37ba33 100644 --- a/tests/lib/Files/Storage/Wrapper/JailTest.php +++ b/tests/lib/Files/Storage/Wrapper/JailTest.php @@ -1,24 +1,28 @@ <?php + /** - * Copyright (c) 2014 Robin Appelman <icewind@owncloud.com> - * This file is licensed under the Affero General Public License version 3 or - * later. - * See the COPYING-README file. + * SPDX-FileCopyrightText: 2019-2024 Nextcloud GmbH and Nextcloud contributors + * SPDX-FileCopyrightText: 2016 ownCloud, Inc. + * SPDX-License-Identifier: AGPL-3.0-or-later */ namespace Test\Files\Storage\Wrapper; +use OC\Files\Filesystem; +use OC\Files\Storage\Temporary; +use OC\Files\Storage\Wrapper\Jail; + class JailTest extends \Test\Files\Storage\Storage { /** - * @var \OC\Files\Storage\Temporary + * @var Temporary */ private $sourceStorage; protected function setUp(): void { parent::setUp(); - $this->sourceStorage = new \OC\Files\Storage\Temporary([]); + $this->sourceStorage = new Temporary([]); $this->sourceStorage->mkdir('foo'); - $this->instance = new \OC\Files\Storage\Wrapper\Jail([ + $this->instance = new Jail([ 'storage' => $this->sourceStorage, 'root' => 'foo' ]); @@ -28,8 +32,8 @@ class JailTest extends \Test\Files\Storage\Storage { // test that nothing outside our jail is touched $contents = []; $dh = $this->sourceStorage->opendir(''); - while ($file = readdir($dh)) { - if (!\OC\Files\Filesystem::isIgnoredDir($file)) { + while (($file = readdir($dh)) !== false) { + if (!Filesystem::isIgnoredDir($file)) { $contents[] = $file; } } @@ -38,12 +42,12 @@ class JailTest extends \Test\Files\Storage\Storage { parent::tearDown(); } - public function testMkDirRooted() { + public function testMkDirRooted(): void { $this->instance->mkdir('bar'); $this->assertTrue($this->sourceStorage->is_dir('foo/bar')); } - public function testFilePutContentsRooted() { + public function testFilePutContentsRooted(): void { $this->instance->file_put_contents('bar', 'asd'); $this->assertEquals('asd', $this->sourceStorage->file_get_contents('foo/bar')); } diff --git a/tests/lib/Files/Storage/Wrapper/KnownMtimeTest.php b/tests/lib/Files/Storage/Wrapper/KnownMtimeTest.php new file mode 100644 index 00000000000..b1b5582b4ed --- /dev/null +++ b/tests/lib/Files/Storage/Wrapper/KnownMtimeTest.php @@ -0,0 +1,69 @@ +<?php + +/** + * SPDX-FileCopyrightText: 2023 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: AGPL-3.0-or-later + */ + +namespace lib\Files\Storage\Wrapper; + +use OC\Files\Storage\Temporary; +use OC\Files\Storage\Wrapper\KnownMtime; +use PHPUnit\Framework\MockObject\MockObject; +use Psr\Clock\ClockInterface; +use Test\Files\Storage\Storage; + +/** + * @group DB + */ +class KnownMtimeTest extends Storage { + /** @var Temporary */ + private $sourceStorage; + + /** @var ClockInterface|MockObject */ + private $clock; + private int $fakeTime = 0; + + protected function setUp(): void { + parent::setUp(); + $this->fakeTime = 0; + $this->sourceStorage = new Temporary([]); + $this->clock = $this->createMock(ClockInterface::class); + $this->clock->method('now')->willReturnCallback(function () { + if ($this->fakeTime) { + return new \DateTimeImmutable("@{$this->fakeTime}"); + } else { + return new \DateTimeImmutable(); + } + }); + $this->instance = $this->getWrappedStorage(); + } + + protected function tearDown(): void { + $this->sourceStorage->cleanUp(); + parent::tearDown(); + } + + protected function getWrappedStorage() { + return new KnownMtime([ + 'storage' => $this->sourceStorage, + 'clock' => $this->clock, + ]); + } + + public function testNewerKnownMtime(): void { + $future = time() + 1000; + $this->fakeTime = $future; + + $this->instance->file_put_contents('foo.txt', 'bar'); + + // fuzzy match since the clock might have ticked + $this->assertLessThan(2, abs(time() - $this->sourceStorage->filemtime('foo.txt'))); + $this->assertEquals($this->sourceStorage->filemtime('foo.txt'), $this->sourceStorage->stat('foo.txt')['mtime']); + $this->assertEquals($this->sourceStorage->filemtime('foo.txt'), $this->sourceStorage->getMetaData('foo.txt')['mtime']); + + $this->assertEquals($future, $this->instance->filemtime('foo.txt')); + $this->assertEquals($future, $this->instance->stat('foo.txt')['mtime']); + $this->assertEquals($future, $this->instance->getMetaData('foo.txt')['mtime']); + } +} diff --git a/tests/lib/Files/Storage/Wrapper/PermissionsMaskTest.php b/tests/lib/Files/Storage/Wrapper/PermissionsMaskTest.php index ea01a0e3e94..a2f3460c58c 100644 --- a/tests/lib/Files/Storage/Wrapper/PermissionsMaskTest.php +++ b/tests/lib/Files/Storage/Wrapper/PermissionsMaskTest.php @@ -1,13 +1,15 @@ <?php + /** - * Copyright (c) 2014 Robin Appelman <icewind@owncloud.com> - * This file is licensed under the Affero General Public License version 3 or - * later. - * See the COPYING-README file. + * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors + * SPDX-FileCopyrightText: 2016 ownCloud, Inc. + * SPDX-License-Identifier: AGPL-3.0-or-later */ namespace Test\Files\Storage\Wrapper; +use OC\Files\Storage\Temporary; +use OC\Files\Storage\Wrapper\PermissionsMask; use OC\Files\Storage\Wrapper\Wrapper; use OCP\Constants; use OCP\Files\Cache\IScanner; @@ -17,13 +19,13 @@ use OCP\Files\Cache\IScanner; */ class PermissionsMaskTest extends \Test\Files\Storage\Storage { /** - * @var \OC\Files\Storage\Temporary + * @var Temporary */ private $sourceStorage; protected function setUp(): void { parent::setUp(); - $this->sourceStorage = new \OC\Files\Storage\Temporary([]); + $this->sourceStorage = new Temporary([]); $this->instance = $this->getMaskedStorage(Constants::PERMISSION_ALL); } @@ -33,19 +35,19 @@ class PermissionsMaskTest extends \Test\Files\Storage\Storage { } protected function getMaskedStorage($mask) { - return new \OC\Files\Storage\Wrapper\PermissionsMask([ + return new PermissionsMask([ 'storage' => $this->sourceStorage, 'mask' => $mask ]); } - public function testMkdirNoCreate() { + public function testMkdirNoCreate(): void { $storage = $this->getMaskedStorage(Constants::PERMISSION_ALL - Constants::PERMISSION_CREATE); $this->assertFalse($storage->mkdir('foo')); $this->assertFalse($storage->file_exists('foo')); } - public function testRmdirNoDelete() { + public function testRmdirNoDelete(): void { $storage = $this->getMaskedStorage(Constants::PERMISSION_ALL - Constants::PERMISSION_DELETE); $this->assertTrue($storage->mkdir('foo')); $this->assertTrue($storage->file_exists('foo')); @@ -53,25 +55,25 @@ class PermissionsMaskTest extends \Test\Files\Storage\Storage { $this->assertTrue($storage->file_exists('foo')); } - public function testTouchNewFileNoCreate() { + public function testTouchNewFileNoCreate(): void { $storage = $this->getMaskedStorage(Constants::PERMISSION_ALL - Constants::PERMISSION_CREATE); $this->assertFalse($storage->touch('foo')); $this->assertFalse($storage->file_exists('foo')); } - public function testTouchNewFileNoUpdate() { + public function testTouchNewFileNoUpdate(): void { $storage = $this->getMaskedStorage(Constants::PERMISSION_ALL - Constants::PERMISSION_UPDATE); $this->assertTrue($storage->touch('foo')); $this->assertTrue($storage->file_exists('foo')); } - public function testTouchExistingFileNoUpdate() { + public function testTouchExistingFileNoUpdate(): void { $this->sourceStorage->touch('foo'); $storage = $this->getMaskedStorage(Constants::PERMISSION_ALL - Constants::PERMISSION_UPDATE); $this->assertFalse($storage->touch('foo')); } - public function testUnlinkNoDelete() { + public function testUnlinkNoDelete(): void { $storage = $this->getMaskedStorage(Constants::PERMISSION_ALL - Constants::PERMISSION_DELETE); $this->assertTrue($storage->touch('foo')); $this->assertTrue($storage->file_exists('foo')); @@ -79,35 +81,35 @@ class PermissionsMaskTest extends \Test\Files\Storage\Storage { $this->assertTrue($storage->file_exists('foo')); } - public function testPutContentsNewFileNoUpdate() { + public function testPutContentsNewFileNoUpdate(): void { $storage = $this->getMaskedStorage(Constants::PERMISSION_ALL - Constants::PERMISSION_UPDATE); $this->assertEquals(3, $storage->file_put_contents('foo', 'bar')); $this->assertEquals('bar', $storage->file_get_contents('foo')); } - public function testPutContentsNewFileNoCreate() { + public function testPutContentsNewFileNoCreate(): void { $storage = $this->getMaskedStorage(Constants::PERMISSION_ALL - Constants::PERMISSION_CREATE); $this->assertFalse($storage->file_put_contents('foo', 'bar')); } - public function testPutContentsExistingFileNoUpdate() { + public function testPutContentsExistingFileNoUpdate(): void { $this->sourceStorage->touch('foo'); $storage = $this->getMaskedStorage(Constants::PERMISSION_ALL - Constants::PERMISSION_UPDATE); $this->assertFalse($storage->file_put_contents('foo', 'bar')); } - public function testFopenExistingFileNoUpdate() { + public function testFopenExistingFileNoUpdate(): void { $this->sourceStorage->touch('foo'); $storage = $this->getMaskedStorage(Constants::PERMISSION_ALL - Constants::PERMISSION_UPDATE); $this->assertFalse($storage->fopen('foo', 'w')); } - public function testFopenNewFileNoCreate() { + public function testFopenNewFileNoCreate(): void { $storage = $this->getMaskedStorage(Constants::PERMISSION_ALL - Constants::PERMISSION_CREATE); $this->assertFalse($storage->fopen('foo', 'w')); } - public function testScanNewFiles() { + public function testScanNewFiles(): void { $storage = $this->getMaskedStorage(Constants::PERMISSION_READ + Constants::PERMISSION_CREATE); $storage->file_put_contents('foo', 'bar'); $storage->getScanner()->scan(''); @@ -116,7 +118,7 @@ class PermissionsMaskTest extends \Test\Files\Storage\Storage { $this->assertEquals(Constants::PERMISSION_READ, $storage->getCache()->get('foo')->getPermissions()); } - public function testScanNewWrappedFiles() { + public function testScanNewWrappedFiles(): void { $storage = $this->getMaskedStorage(Constants::PERMISSION_READ + Constants::PERMISSION_CREATE); $wrappedStorage = new Wrapper(['storage' => $storage]); $wrappedStorage->file_put_contents('foo', 'bar'); @@ -126,9 +128,9 @@ class PermissionsMaskTest extends \Test\Files\Storage\Storage { $this->assertEquals(Constants::PERMISSION_READ, $storage->getCache()->get('foo')->getPermissions()); } - public function testScanNewFilesNested() { + public function testScanNewFilesNested(): void { $storage = $this->getMaskedStorage(Constants::PERMISSION_READ + Constants::PERMISSION_CREATE + Constants::PERMISSION_UPDATE); - $nestedStorage = new \OC\Files\Storage\Wrapper\PermissionsMask([ + $nestedStorage = new PermissionsMask([ 'storage' => $storage, 'mask' => Constants::PERMISSION_READ + Constants::PERMISSION_CREATE ]); @@ -141,7 +143,7 @@ class PermissionsMaskTest extends \Test\Files\Storage\Storage { $this->assertEquals(Constants::PERMISSION_READ, $wrappedStorage->getCache()->get('foo')->getPermissions()); } - public function testScanUnchanged() { + public function testScanUnchanged(): void { $this->sourceStorage->mkdir('foo'); $this->sourceStorage->file_put_contents('foo/bar.txt', 'bar'); @@ -150,7 +152,7 @@ class PermissionsMaskTest extends \Test\Files\Storage\Storage { $storage = $this->getMaskedStorage(Constants::PERMISSION_READ); $scanner = $storage->getScanner(); $called = false; - $scanner->listen('\OC\Files\Cache\Scanner', 'addToCache', function () use (&$called) { + $scanner->listen('\OC\Files\Cache\Scanner', 'addToCache', function () use (&$called): void { $called = true; }); $scanner->scan('foo', IScanner::SCAN_RECURSIVE, IScanner::REUSE_ETAG | IScanner::REUSE_SIZE); @@ -158,7 +160,7 @@ class PermissionsMaskTest extends \Test\Files\Storage\Storage { $this->assertFalse($called); } - public function testScanUnchangedWrapped() { + public function testScanUnchangedWrapped(): void { $this->sourceStorage->mkdir('foo'); $this->sourceStorage->file_put_contents('foo/bar.txt', 'bar'); @@ -168,7 +170,7 @@ class PermissionsMaskTest extends \Test\Files\Storage\Storage { $wrappedStorage = new Wrapper(['storage' => $storage]); $scanner = $wrappedStorage->getScanner(); $called = false; - $scanner->listen('\OC\Files\Cache\Scanner', 'addToCache', function () use (&$called) { + $scanner->listen('\OC\Files\Cache\Scanner', 'addToCache', function () use (&$called): void { $called = true; }); $scanner->scan('foo', IScanner::SCAN_RECURSIVE, IScanner::REUSE_ETAG | IScanner::REUSE_SIZE); diff --git a/tests/lib/Files/Storage/Wrapper/QuotaTest.php b/tests/lib/Files/Storage/Wrapper/QuotaTest.php index 82b3e3556cb..2878fe6ca92 100644 --- a/tests/lib/Files/Storage/Wrapper/QuotaTest.php +++ b/tests/lib/Files/Storage/Wrapper/QuotaTest.php @@ -1,9 +1,9 @@ <?php + /** - * Copyright (c) 2013 Robin Appelman <icewind@owncloud.com> - * This file is licensed under the Affero General Public License version 3 or - * later. - * See the COPYING-README file. + * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors + * SPDX-FileCopyrightText: 2016 ownCloud, Inc. + * SPDX-License-Identifier: AGPL-3.0-or-later */ namespace Test\Files\Storage\Wrapper; @@ -11,8 +11,10 @@ namespace Test\Files\Storage\Wrapper; //ensure the constants are loaded use OC\Files\Cache\CacheEntry; use OC\Files\Storage\Local; - -\OC::$loader->load('\OC\Files\Filesystem'); +use OC\Files\Storage\Wrapper\Quota; +use OCP\Files; +use OCP\ITempManager; +use OCP\Server; /** * Class QuotaTest @@ -30,13 +32,13 @@ class QuotaTest extends \Test\Files\Storage\Storage { protected function setUp(): void { parent::setUp(); - $this->tmpDir = \OC::$server->getTempManager()->getTemporaryFolder(); - $storage = new \OC\Files\Storage\Local(['datadir' => $this->tmpDir]); - $this->instance = new \OC\Files\Storage\Wrapper\Quota(['storage' => $storage, 'quota' => 10000000]); + $this->tmpDir = Server::get(ITempManager::class)->getTemporaryFolder(); + $storage = new Local(['datadir' => $this->tmpDir]); + $this->instance = new Quota(['storage' => $storage, 'quota' => 10000000]); } protected function tearDown(): void { - \OC_Helper::rmdirr($this->tmpDir); + Files::rmdirr($this->tmpDir); parent::tearDown(); } @@ -44,30 +46,30 @@ class QuotaTest extends \Test\Files\Storage\Storage { * @param integer $limit */ protected function getLimitedStorage($limit) { - $storage = new \OC\Files\Storage\Local(['datadir' => $this->tmpDir]); + $storage = new Local(['datadir' => $this->tmpDir]); $storage->mkdir('files'); $storage->getScanner()->scan(''); - return new \OC\Files\Storage\Wrapper\Quota(['storage' => $storage, 'quota' => $limit]); + return new Quota(['storage' => $storage, 'quota' => $limit]); } - public function testFilePutContentsNotEnoughSpace() { + public function testFilePutContentsNotEnoughSpace(): void { $instance = $this->getLimitedStorage(3); $this->assertFalse($instance->file_put_contents('files/foo', 'foobar')); } - public function testCopyNotEnoughSpace() { + public function testCopyNotEnoughSpace(): void { $instance = $this->getLimitedStorage(9); $this->assertEquals(6, $instance->file_put_contents('files/foo', 'foobar')); $instance->getScanner()->scan(''); $this->assertFalse($instance->copy('files/foo', 'files/bar')); } - public function testFreeSpace() { + public function testFreeSpace(): void { $instance = $this->getLimitedStorage(9); $this->assertEquals(9, $instance->free_space('')); } - public function testFreeSpaceWithUsedSpace() { + public function testFreeSpaceWithUsedSpace(): void { $instance = $this->getLimitedStorage(9); $instance->getCache()->put( '', ['size' => 3] @@ -75,9 +77,9 @@ class QuotaTest extends \Test\Files\Storage\Storage { $this->assertEquals(6, $instance->free_space('')); } - public function testFreeSpaceWithUnknownDiskSpace() { + public function testFreeSpaceWithUnknownDiskSpace(): void { $storage = $this->getMockBuilder(Local::class) - ->setMethods(['free_space']) + ->onlyMethods(['free_space']) ->setConstructorArgs([['datadir' => $this->tmpDir]]) ->getMock(); $storage->expects($this->any()) @@ -85,14 +87,14 @@ class QuotaTest extends \Test\Files\Storage\Storage { ->willReturn(-2); $storage->getScanner()->scan(''); - $instance = new \OC\Files\Storage\Wrapper\Quota(['storage' => $storage, 'quota' => 9]); + $instance = new Quota(['storage' => $storage, 'quota' => 9]); $instance->getCache()->put( '', ['size' => 3] ); $this->assertEquals(6, $instance->free_space('')); } - public function testFreeSpaceWithUsedSpaceAndEncryption() { + public function testFreeSpaceWithUsedSpaceAndEncryption(): void { $instance = $this->getLimitedStorage(9); $instance->getCache()->put( '', ['size' => 7] @@ -100,7 +102,7 @@ class QuotaTest extends \Test\Files\Storage\Storage { $this->assertEquals(2, $instance->free_space('')); } - public function testFWriteNotEnoughSpace() { + public function testFWriteNotEnoughSpace(): void { $instance = $this->getLimitedStorage(9); $stream = $instance->fopen('files/foo', 'w+'); $this->assertEquals(6, fwrite($stream, 'foobar')); @@ -109,7 +111,7 @@ class QuotaTest extends \Test\Files\Storage\Storage { $this->assertEquals('foobarqwe', $instance->file_get_contents('files/foo')); } - public function testStreamCopyWithEnoughSpace() { + public function testStreamCopyWithEnoughSpace(): void { $instance = $this->getLimitedStorage(16); $inputStream = fopen('data://text/plain,foobarqwerty', 'r'); $outputStream = $instance->fopen('files/foo', 'w+'); @@ -120,7 +122,7 @@ class QuotaTest extends \Test\Files\Storage\Storage { fclose($outputStream); } - public function testStreamCopyNotEnoughSpace() { + public function testStreamCopyNotEnoughSpace(): void { $instance = $this->getLimitedStorage(9); $inputStream = fopen('data://text/plain,foobarqwerty', 'r'); $outputStream = $instance->fopen('files/foo', 'w+'); @@ -131,21 +133,21 @@ class QuotaTest extends \Test\Files\Storage\Storage { fclose($outputStream); } - public function testReturnFalseWhenFopenFailed() { + public function testReturnFalseWhenFopenFailed(): void { $failStorage = $this->getMockBuilder(Local::class) - ->setMethods(['fopen']) + ->onlyMethods(['fopen']) ->setConstructorArgs([['datadir' => $this->tmpDir]]) ->getMock(); $failStorage->expects($this->any()) ->method('fopen') ->willReturn(false); - $instance = new \OC\Files\Storage\Wrapper\Quota(['storage' => $failStorage, 'quota' => 1000]); + $instance = new Quota(['storage' => $failStorage, 'quota' => 1000]); $this->assertFalse($instance->fopen('failedfopen', 'r')); } - public function testReturnRegularStreamOnRead() { + public function testReturnRegularStreamOnRead(): void { $instance = $this->getLimitedStorage(9); // create test file first @@ -164,7 +166,7 @@ class QuotaTest extends \Test\Files\Storage\Storage { fclose($stream); } - public function testReturnRegularStreamWhenOutsideFiles() { + public function testReturnRegularStreamWhenOutsideFiles(): void { $instance = $this->getLimitedStorage(9); $instance->mkdir('files_other'); @@ -175,7 +177,7 @@ class QuotaTest extends \Test\Files\Storage\Storage { fclose($stream); } - public function testReturnQuotaStreamOnWrite() { + public function testReturnQuotaStreamOnWrite(): void { $instance = $this->getLimitedStorage(9); $stream = $instance->fopen('files/foo', 'w+'); $meta = stream_get_meta_data($stream); @@ -184,7 +186,7 @@ class QuotaTest extends \Test\Files\Storage\Storage { fclose($stream); } - public function testSpaceRoot() { + public function testSpaceRoot(): void { $storage = $this->getMockBuilder(Local::class)->disableOriginalConstructor()->getMock(); $cache = $this->getMockBuilder('\OC\Files\Cache\Cache')->disableOriginalConstructor()->getMock(); $storage->expects($this->once()) @@ -198,24 +200,24 @@ class QuotaTest extends \Test\Files\Storage\Storage { ->with('files') ->willReturn(new CacheEntry(['size' => 50])); - $instance = new \OC\Files\Storage\Wrapper\Quota(['storage' => $storage, 'quota' => 1024, 'root' => 'files']); + $instance = new Quota(['storage' => $storage, 'quota' => 1024, 'root' => 'files']); $this->assertEquals(1024 - 50, $instance->free_space('')); } - public function testInstanceOfStorageWrapper() { + public function testInstanceOfStorageWrapper(): void { $this->assertTrue($this->instance->instanceOfStorage('\OC\Files\Storage\Local')); $this->assertTrue($this->instance->instanceOfStorage('\OC\Files\Storage\Wrapper\Wrapper')); $this->assertTrue($this->instance->instanceOfStorage('\OC\Files\Storage\Wrapper\Quota')); } - public function testNoMkdirQuotaZero() { + public function testNoMkdirQuotaZero(): void { $instance = $this->getLimitedStorage(0.0); $this->assertFalse($instance->mkdir('files')); $this->assertFalse($instance->mkdir('files/foobar')); } - public function testMkdirQuotaZeroTrashbin() { + public function testMkdirQuotaZeroTrashbin(): void { $instance = $this->getLimitedStorage(0.0); $this->assertTrue($instance->mkdir('files_trashbin')); $this->assertTrue($instance->mkdir('files_trashbin/files')); @@ -223,7 +225,7 @@ class QuotaTest extends \Test\Files\Storage\Storage { $this->assertTrue($instance->mkdir('cache')); } - public function testNoTouchQuotaZero() { + public function testNoTouchQuotaZero(): void { $instance = $this->getLimitedStorage(0.0); $this->assertFalse($instance->touch('foobar')); } diff --git a/tests/lib/Files/Storage/Wrapper/WrapperTest.php b/tests/lib/Files/Storage/Wrapper/WrapperTest.php index b9bb54e09b2..60f139450c7 100644 --- a/tests/lib/Files/Storage/Wrapper/WrapperTest.php +++ b/tests/lib/Files/Storage/Wrapper/WrapperTest.php @@ -1,13 +1,19 @@ <?php + /** - * Copyright (c) 2013 Robin Appelman <icewind@owncloud.com> - * This file is licensed under the Affero General Public License version 3 or - * later. - * See the COPYING-README file. + * SPDX-FileCopyrightText: 2019-2024 Nextcloud GmbH and Nextcloud contributors + * SPDX-FileCopyrightText: 2016 ownCloud, Inc. + * SPDX-License-Identifier: AGPL-3.0-or-later */ namespace Test\Files\Storage\Wrapper; +use OC\Files\Storage\Local; +use OC\Files\Storage\Wrapper\Wrapper; +use OCP\Files; +use OCP\ITempManager; +use OCP\Server; + class WrapperTest extends \Test\Files\Storage\Storage { /** * @var string tmpDir @@ -17,17 +23,17 @@ class WrapperTest extends \Test\Files\Storage\Storage { protected function setUp(): void { parent::setUp(); - $this->tmpDir = \OC::$server->getTempManager()->getTemporaryFolder(); - $storage = new \OC\Files\Storage\Local(['datadir' => $this->tmpDir]); - $this->instance = new \OC\Files\Storage\Wrapper\Wrapper(['storage' => $storage]); + $this->tmpDir = Server::get(ITempManager::class)->getTemporaryFolder(); + $storage = new Local(['datadir' => $this->tmpDir]); + $this->instance = new Wrapper(['storage' => $storage]); } protected function tearDown(): void { - \OC_Helper::rmdirr($this->tmpDir); + Files::rmdirr($this->tmpDir); parent::tearDown(); } - public function testInstanceOfStorageWrapper() { + public function testInstanceOfStorageWrapper(): void { $this->assertTrue($this->instance->instanceOfStorage('\OC\Files\Storage\Local')); $this->assertTrue($this->instance->instanceOfStorage('\OC\Files\Storage\Wrapper\Wrapper')); } |