aboutsummaryrefslogtreecommitdiffstats
path: root/tests/lib/Files
diff options
context:
space:
mode:
Diffstat (limited to 'tests/lib/Files')
-rw-r--r--tests/lib/Files/AppData/AppDataTest.php1
-rw-r--r--tests/lib/Files/AppData/FactoryTest.php1
-rw-r--r--tests/lib/Files/Cache/CacheTest.php109
-rw-r--r--tests/lib/Files/Cache/HomeCacheTest.php29
-rw-r--r--tests/lib/Files/Cache/LocalRootScannerTest.php4
-rw-r--r--tests/lib/Files/Cache/MoveFromCacheTraitTest.php9
-rw-r--r--tests/lib/Files/Cache/PropagatorTest.php1
-rw-r--r--tests/lib/Files/Cache/ScannerTest.php13
-rw-r--r--tests/lib/Files/Cache/SearchBuilderTest.php13
-rw-r--r--tests/lib/Files/Cache/UpdaterLegacyTest.php27
-rw-r--r--tests/lib/Files/Cache/UpdaterTest.php16
-rw-r--r--tests/lib/Files/Cache/WatcherTest.php23
-rw-r--r--tests/lib/Files/Cache/Wrapper/CacheJailTest.php23
-rw-r--r--tests/lib/Files/Cache/Wrapper/CachePermissionsMaskTest.php15
-rw-r--r--tests/lib/Files/Config/UserMountCacheTest.php112
-rw-r--r--tests/lib/Files/EtagTest.php18
-rw-r--r--tests/lib/Files/FileInfoTest.php1
-rw-r--r--tests/lib/Files/FilenameValidatorTest.php170
-rw-r--r--tests/lib/Files/FilesystemTest.php162
-rw-r--r--tests/lib/Files/Mount/ManagerTest.php12
-rw-r--r--tests/lib/Files/Mount/MountPointTest.php10
-rw-r--r--tests/lib/Files/Mount/MountTest.php8
-rw-r--r--tests/lib/Files/Mount/ObjectHomeMountProviderTest.php250
-rw-r--r--tests/lib/Files/Mount/RootMountProviderTest.php7
-rw-r--r--tests/lib/Files/Node/FileTest.php88
-rw-r--r--tests/lib/Files/Node/FolderTest.php84
-rw-r--r--tests/lib/Files/Node/HookConnectorTest.php73
-rw-r--r--tests/lib/Files/Node/IntegrationTest.php11
-rw-r--r--tests/lib/Files/Node/NodeTestCase.php (renamed from tests/lib/Files/Node/NodeTest.php)128
-rw-r--r--tests/lib/Files/Node/RootTest.php38
-rw-r--r--tests/lib/Files/ObjectStore/AzureTest.php7
-rw-r--r--tests/lib/Files/ObjectStore/FailDeleteObjectStore.php7
-rw-r--r--tests/lib/Files/ObjectStore/FailWriteObjectStore.php7
-rw-r--r--tests/lib/Files/ObjectStore/LocalTest.php6
-rw-r--r--tests/lib/Files/ObjectStore/MapperTest.php5
-rw-r--r--tests/lib/Files/ObjectStore/ObjectStoreScannerTest.php1
-rw-r--r--tests/lib/Files/ObjectStore/ObjectStoreStorageTest.php31
-rw-r--r--tests/lib/Files/ObjectStore/ObjectStoreStoragesDifferentBucketTest.php10
-rw-r--r--tests/lib/Files/ObjectStore/ObjectStoreStoragesSameBucketTest.php8
-rw-r--r--tests/lib/Files/ObjectStore/ObjectStoreTestCase.php (renamed from tests/lib/Files/ObjectStore/ObjectStoreTest.php)24
-rw-r--r--tests/lib/Files/ObjectStore/S3Test.php11
-rw-r--r--tests/lib/Files/ObjectStore/SwiftTest.php10
-rw-r--r--tests/lib/Files/PathVerificationTest.php37
-rw-r--r--tests/lib/Files/Search/QueryOptimizer/CombinedTests.php1
-rw-r--r--tests/lib/Files/Search/QueryOptimizer/FlattenNestedBoolTest.php1
-rw-r--r--tests/lib/Files/Search/QueryOptimizer/MergeDistributiveOperationsTest.php1
-rw-r--r--tests/lib/Files/Search/QueryOptimizer/OrEqualsToInTest.php1
-rw-r--r--tests/lib/Files/Search/SearchIntegrationTest.php1
-rw-r--r--tests/lib/Files/SimpleFS/SimpleFileTest.php1
-rw-r--r--tests/lib/Files/SimpleFS/SimpleFolderTest.php1
-rw-r--r--tests/lib/Files/Storage/CommonTest.php7
-rw-r--r--tests/lib/Files/Storage/CopyDirectoryTest.php4
-rw-r--r--tests/lib/Files/Storage/HomeTest.php24
-rw-r--r--tests/lib/Files/Storage/LocalTest.php29
-rw-r--r--tests/lib/Files/Storage/Storage.php51
-rw-r--r--tests/lib/Files/Storage/StorageFactoryTest.php8
-rw-r--r--tests/lib/Files/Storage/StoragesTestCase.php (renamed from tests/lib/Files/Storage/StoragesTest.php)8
-rw-r--r--tests/lib/Files/Storage/Wrapper/AvailabilityTest.php11
-rw-r--r--tests/lib/Files/Storage/Wrapper/EncodingTest.php54
-rw-r--r--tests/lib/Files/Storage/Wrapper/EncryptionTest.php112
-rw-r--r--tests/lib/Files/Storage/Wrapper/JailTest.php13
-rw-r--r--tests/lib/Files/Storage/Wrapper/KnownMtimeTest.php1
-rw-r--r--tests/lib/Files/Storage/Wrapper/PermissionsMaskTest.php15
-rw-r--r--tests/lib/Files/Storage/Wrapper/QuotaTest.php29
-rw-r--r--tests/lib/Files/Storage/Wrapper/WrapperTest.php15
-rw-r--r--tests/lib/Files/Stream/DummyEncryptionWrapper.php5
-rw-r--r--tests/lib/Files/Stream/EncryptionTest.php55
-rw-r--r--tests/lib/Files/Stream/HashWrapperTest.php8
-rw-r--r--tests/lib/Files/Stream/QuotaTest.php9
-rw-r--r--tests/lib/Files/Type/DetectionTest.php16
-rw-r--r--tests/lib/Files/Type/LoaderTest.php4
-rw-r--r--tests/lib/Files/Utils/ScannerTest.php37
-rw-r--r--tests/lib/Files/ViewTest.php170
73 files changed, 1325 insertions, 987 deletions
diff --git a/tests/lib/Files/AppData/AppDataTest.php b/tests/lib/Files/AppData/AppDataTest.php
index 494096d1ac3..ed006622504 100644
--- a/tests/lib/Files/AppData/AppDataTest.php
+++ b/tests/lib/Files/AppData/AppDataTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
diff --git a/tests/lib/Files/AppData/FactoryTest.php b/tests/lib/Files/AppData/FactoryTest.php
index dff999d8b48..6092c931091 100644
--- a/tests/lib/Files/AppData/FactoryTest.php
+++ b/tests/lib/Files/AppData/FactoryTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
diff --git a/tests/lib/Files/Cache/CacheTest.php b/tests/lib/Files/Cache/CacheTest.php
index 204f87d6a18..383962b7224 100644
--- a/tests/lib/Files/Cache/CacheTest.php
+++ b/tests/lib/Files/Cache/CacheTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -11,13 +12,18 @@ use OC\Files\Cache\Cache;
use OC\Files\Cache\CacheEntry;
use OC\Files\Search\SearchComparison;
use OC\Files\Search\SearchQuery;
+use OC\Files\Storage\Temporary;
+use OC\User\User;
use OCP\EventDispatcher\IEventDispatcher;
use OCP\Files\Cache\ICacheEntry;
use OCP\Files\Search\ISearchComparison;
use OCP\IDBConnection;
+use OCP\ITagManager;
use OCP\IUser;
+use OCP\IUserManager;
+use OCP\Server;
-class LongId extends \OC\Files\Storage\Temporary {
+class LongId extends Temporary {
public function getId(): string {
return 'long:' . str_repeat('foo', 50) . parent::getId();
}
@@ -32,23 +38,42 @@ class LongId extends \OC\Files\Storage\Temporary {
*/
class CacheTest extends \Test\TestCase {
/**
- * @var \OC\Files\Storage\Temporary $storage ;
+ * @var Temporary $storage ;
*/
protected $storage;
/**
- * @var \OC\Files\Storage\Temporary $storage2 ;
+ * @var Temporary $storage2 ;
*/
protected $storage2;
/**
- * @var \OC\Files\Cache\Cache $cache
+ * @var Cache $cache
*/
protected $cache;
/**
- * @var \OC\Files\Cache\Cache $cache2
+ * @var Cache $cache2
*/
protected $cache2;
+ protected function setUp(): void {
+ parent::setUp();
+
+ $this->storage = new Temporary([]);
+ $this->storage2 = new Temporary([]);
+ $this->cache = new Cache($this->storage);
+ $this->cache2 = new Cache($this->storage2);
+ $this->cache->insert('', ['size' => 0, 'mtime' => 0, 'mimetype' => ICacheEntry::DIRECTORY_MIMETYPE]);
+ $this->cache2->insert('', ['size' => 0, 'mtime' => 0, 'mimetype' => ICacheEntry::DIRECTORY_MIMETYPE]);
+ }
+
+ protected function tearDown(): void {
+ if ($this->cache) {
+ $this->cache->clear();
+ }
+
+ parent::tearDown();
+ }
+
public function testGetNumericId(): void {
$this->assertNotNull($this->cache->getNumericStorageId());
}
@@ -137,14 +162,12 @@ class CacheTest extends \Test\TestCase {
$this->assertEquals(new CacheEntry(['size' => 12, 'mtime' => 15]), $this->cache->get($file1));
}
- /**
- * @dataProvider folderDataProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('folderDataProvider')]
public function testFolder($folder): void {
if (strpos($folder, 'F09F9890')) {
// 4 byte UTF doesn't work on mysql
- $params = \OC::$server->get(\OC\DB\Connection::class)->getParams();
- if (\OC::$server->getDatabaseConnection()->getDatabaseProvider() === IDBConnection::PLATFORM_MYSQL && $params['charset'] !== 'utf8mb4') {
+ $params = Server::get(\OC\DB\Connection::class)->getParams();
+ if (Server::get(IDBConnection::class)->getDatabaseProvider() === IDBConnection::PLATFORM_MYSQL && $params['charset'] !== 'utf8mb4') {
$this->markTestSkipped('MySQL doesn\'t support 4 byte UTF-8');
}
}
@@ -208,7 +231,7 @@ class CacheTest extends \Test\TestCase {
}
}
- public function folderDataProvider() {
+ public static function folderDataProvider(): array {
return [
['folder'],
// that was too easy, try something harder
@@ -292,16 +315,16 @@ class CacheTest extends \Test\TestCase {
}
public function testStatus(): void {
- $this->assertEquals(\OC\Files\Cache\Cache::NOT_FOUND, $this->cache->getStatus('foo'));
+ $this->assertEquals(Cache::NOT_FOUND, $this->cache->getStatus('foo'));
$this->cache->put('foo', ['size' => -1]);
- $this->assertEquals(\OC\Files\Cache\Cache::PARTIAL, $this->cache->getStatus('foo'));
+ $this->assertEquals(Cache::PARTIAL, $this->cache->getStatus('foo'));
$this->cache->put('foo', ['size' => -1, 'mtime' => 20, 'mimetype' => 'foo/file']);
- $this->assertEquals(\OC\Files\Cache\Cache::SHALLOW, $this->cache->getStatus('foo'));
+ $this->assertEquals(Cache::SHALLOW, $this->cache->getStatus('foo'));
$this->cache->put('foo', ['size' => 10]);
- $this->assertEquals(\OC\Files\Cache\Cache::COMPLETE, $this->cache->getStatus('foo'));
+ $this->assertEquals(Cache::COMPLETE, $this->cache->getStatus('foo'));
}
- public function putWithAllKindOfQuotesData() {
+ public static function putWithAllKindOfQuotesData(): array {
return [
['`backtick`'],
['´forward´'],
@@ -310,11 +333,11 @@ class CacheTest extends \Test\TestCase {
}
/**
- * @dataProvider putWithAllKindOfQuotesData
* @param $fileName
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('putWithAllKindOfQuotesData')]
public function testPutWithAllKindOfQuotes($fileName): void {
- $this->assertEquals(\OC\Files\Cache\Cache::NOT_FOUND, $this->cache->get($fileName));
+ $this->assertEquals(Cache::NOT_FOUND, $this->cache->get($fileName));
$this->cache->put($fileName, ['size' => 20, 'mtime' => 25, 'mimetype' => 'foo/file', 'etag' => $fileName]);
$cacheEntry = $this->cache->get($fileName);
@@ -352,9 +375,9 @@ class CacheTest extends \Test\TestCase {
public function testSearchQueryByTag(): void {
$userId = static::getUniqueID('user');
- \OC::$server->getUserManager()->createUser($userId, $userId);
+ Server::get(IUserManager::class)->createUser($userId, $userId);
static::loginAsUser($userId);
- $user = new \OC\User\User($userId, null, \OC::$server->get(IEventDispatcher::class));
+ $user = new User($userId, null, Server::get(IEventDispatcher::class));
$file1 = 'folder';
$file2 = 'folder/foobar';
@@ -374,7 +397,7 @@ class CacheTest extends \Test\TestCase {
$id4 = $this->cache->put($file4, $fileData['foo2']);
$id5 = $this->cache->put($file5, $fileData['foo3']);
- $tagManager = \OC::$server->getTagManager()->load('files', [], false, $userId);
+ $tagManager = Server::get(ITagManager::class)->load('files', [], false, $userId);
$this->assertTrue($tagManager->tagAs($id1, 'tag1'));
$this->assertTrue($tagManager->tagAs($id1, 'tag2'));
$this->assertTrue($tagManager->tagAs($id2, 'tag2'));
@@ -399,7 +422,7 @@ class CacheTest extends \Test\TestCase {
$tagManager->delete('tag2');
static::logout();
- $user = \OC::$server->getUserManager()->get($userId);
+ $user = Server::get(IUserManager::class)->get($userId);
if ($user !== null) {
try {
$user->delete();
@@ -437,7 +460,7 @@ class CacheTest extends \Test\TestCase {
new SearchComparison(ISearchComparison::COMPARE_GREATER_THAN_EQUAL, 'size', 100), 10, 0, [], $user)));
}
- public function movePathProvider() {
+ public static function movePathProvider(): array {
return [
['folder/foo', 'folder/foobar', ['1', '2']],
['folder/foo', 'foo', ['1', '2']],
@@ -445,9 +468,7 @@ class CacheTest extends \Test\TestCase {
];
}
- /**
- * @dataProvider movePathProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('movePathProvider')]
public function testMove($sourceFolder, $targetFolder, $children): void {
$data = ['size' => 100, 'mtime' => 50, 'mimetype' => 'foo/bar'];
$folderData = ['size' => 100, 'mtime' => 50, 'mimetype' => ICacheEntry::DIRECTORY_MIMETYPE];
@@ -531,7 +552,7 @@ class CacheTest extends \Test\TestCase {
if (strlen($storageId) > 64) {
$storageId = md5($storageId);
}
- $this->assertEquals([$storageId, 'foo'], \OC\Files\Cache\Cache::getById($id));
+ $this->assertEquals([$storageId, 'foo'], Cache::getById($id));
}
public function testStorageMTime(): void {
@@ -558,7 +579,7 @@ class CacheTest extends \Test\TestCase {
$storageId = $storage->getId();
$data = ['size' => 1000, 'mtime' => 20, 'mimetype' => 'foo/file'];
$id = $cache->put('foo', $data);
- $this->assertEquals([md5($storageId), 'foo'], \OC\Files\Cache\Cache::getById($id));
+ $this->assertEquals([md5($storageId), 'foo'], Cache::getById($id));
}
/**
@@ -572,10 +593,10 @@ class CacheTest extends \Test\TestCase {
$folderWith0308 = "\x53\x63\x68\x6f\xcc\x88\x6e";
/**
- * @var \OC\Files\Cache\Cache | \PHPUnit\Framework\MockObject\MockObject $cacheMock
+ * @var Cache|\PHPUnit\Framework\MockObject\MockObject $cacheMock
*/
$cacheMock = $this->getMockBuilder(Cache::class)
- ->setMethods(['normalize'])
+ ->onlyMethods(['normalize'])
->setConstructorArgs([$this->storage])
->getMock();
@@ -646,7 +667,7 @@ class CacheTest extends \Test\TestCase {
$this->assertEquals(1, count($this->cache->getFolderContents('folder')));
}
- public function bogusPathNamesProvider() {
+ public static function bogusPathNamesProvider(): array {
return [
['/bogus.txt', 'bogus.txt'],
['//bogus.txt', 'bogus.txt'],
@@ -657,9 +678,8 @@ class CacheTest extends \Test\TestCase {
/**
* Test bogus paths with leading or doubled slashes
- *
- * @dataProvider bogusPathNamesProvider
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('bogusPathNamesProvider')]
public function testBogusPaths($bogusPath, $fixedBogusPath): void {
$data = ['size' => 100, 'mtime' => 50, 'mimetype' => ICacheEntry::DIRECTORY_MIMETYPE];
$parentId = $this->cache->getId('');
@@ -691,7 +711,7 @@ class CacheTest extends \Test\TestCase {
$this->assertNotEquals($fileId, $fileId2);
}
- public function escapingProvider() {
+ public static function escapingProvider(): array {
return [
['foo'],
['o%'],
@@ -701,8 +721,8 @@ class CacheTest extends \Test\TestCase {
/**
* @param string $name
- * @dataProvider escapingProvider
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('escapingProvider')]
public function testEscaping($name): void {
$data = ['size' => 100, 'mtime' => 50, 'mimetype' => 'text/plain'];
$this->cache->put($name, $data);
@@ -807,23 +827,4 @@ class CacheTest extends \Test\TestCase {
$this->cache->remove('sub');
}
-
- protected function tearDown(): void {
- if ($this->cache) {
- $this->cache->clear();
- }
-
- parent::tearDown();
- }
-
- protected function setUp(): void {
- parent::setUp();
-
- $this->storage = new \OC\Files\Storage\Temporary([]);
- $this->storage2 = new \OC\Files\Storage\Temporary([]);
- $this->cache = new \OC\Files\Cache\Cache($this->storage);
- $this->cache2 = new \OC\Files\Cache\Cache($this->storage2);
- $this->cache->insert('', ['size' => 0, 'mtime' => 0, 'mimetype' => ICacheEntry::DIRECTORY_MIMETYPE]);
- $this->cache2->insert('', ['size' => 0, 'mtime' => 0, 'mimetype' => ICacheEntry::DIRECTORY_MIMETYPE]);
- }
}
diff --git a/tests/lib/Files/Cache/HomeCacheTest.php b/tests/lib/Files/Cache/HomeCacheTest.php
index ad069de1fef..86fda615fd7 100644
--- a/tests/lib/Files/Cache/HomeCacheTest.php
+++ b/tests/lib/Files/Cache/HomeCacheTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2019-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -7,24 +8,20 @@
namespace Test\Files\Cache;
-class DummyUser extends \OC\User\User {
- /**
- * @var string $home
- */
- private $home;
-
- /**
- * @var string $uid
- */
- private $uid;
+use OC\Files\Storage\Home;
+use OC\User\User;
+use OCP\ITempManager;
+use OCP\Server;
+class DummyUser extends User {
/**
* @param string $uid
* @param string $home
*/
- public function __construct($uid, $home) {
- $this->home = $home;
- $this->uid = $uid;
+ public function __construct(
+ private $uid,
+ private $home,
+ ) {
}
/**
@@ -61,15 +58,15 @@ class HomeCacheTest extends \Test\TestCase {
private $cache;
/**
- * @var \OC\User\User $user
+ * @var User $user
*/
private $user;
protected function setUp(): void {
parent::setUp();
- $this->user = new DummyUser('foo', \OC::$server->getTempManager()->getTemporaryFolder());
- $this->storage = new \OC\Files\Storage\Home(['user' => $this->user]);
+ $this->user = new DummyUser('foo', Server::get(ITempManager::class)->getTemporaryFolder());
+ $this->storage = new Home(['user' => $this->user]);
$this->cache = $this->storage->getCache();
}
diff --git a/tests/lib/Files/Cache/LocalRootScannerTest.php b/tests/lib/Files/Cache/LocalRootScannerTest.php
index e683283b7e1..727da2ed698 100644
--- a/tests/lib/Files/Cache/LocalRootScannerTest.php
+++ b/tests/lib/Files/Cache/LocalRootScannerTest.php
@@ -9,6 +9,8 @@ declare(strict_types=1);
namespace Test\Files\Cache;
use OC\Files\Storage\LocalRootStorage;
+use OCP\ITempManager;
+use OCP\Server;
use Test\TestCase;
/**
@@ -21,7 +23,7 @@ class LocalRootScannerTest extends TestCase {
protected function setUp(): void {
parent::setUp();
- $folder = \OC::$server->getTempManager()->getTemporaryFolder();
+ $folder = Server::get(ITempManager::class)->getTemporaryFolder();
$this->storage = new LocalRootStorage(['datadir' => $folder]);
}
diff --git a/tests/lib/Files/Cache/MoveFromCacheTraitTest.php b/tests/lib/Files/Cache/MoveFromCacheTraitTest.php
index e8a6c8acf32..d580cdca4b9 100644
--- a/tests/lib/Files/Cache/MoveFromCacheTraitTest.php
+++ b/tests/lib/Files/Cache/MoveFromCacheTraitTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2019-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -7,10 +8,12 @@
namespace Test\Files\Cache;
+use OC\Files\Cache\Cache;
use OC\Files\Cache\MoveFromCacheTrait;
+use OC\Files\Storage\Temporary;
use OCP\Files\Cache\ICacheEntry;
-class FallBackCrossCacheMoveCache extends \OC\Files\Cache\Cache {
+class FallBackCrossCacheMoveCache extends Cache {
use MoveFromCacheTrait;
}
@@ -23,8 +26,8 @@ class MoveFromCacheTraitTest extends CacheTest {
protected function setUp(): void {
parent::setUp();
- $this->storage = new \OC\Files\Storage\Temporary([]);
- $this->storage2 = new \OC\Files\Storage\Temporary([]);
+ $this->storage = new Temporary([]);
+ $this->storage2 = new Temporary([]);
$this->cache = new FallBackCrossCacheMoveCache($this->storage);
$this->cache2 = new FallBackCrossCacheMoveCache($this->storage2);
diff --git a/tests/lib/Files/Cache/PropagatorTest.php b/tests/lib/Files/Cache/PropagatorTest.php
index e88816dfccc..2ab213e9567 100644
--- a/tests/lib/Files/Cache/PropagatorTest.php
+++ b/tests/lib/Files/Cache/PropagatorTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
diff --git a/tests/lib/Files/Cache/ScannerTest.php b/tests/lib/Files/Cache/ScannerTest.php
index d78b7100d43..123c13893f7 100644
--- a/tests/lib/Files/Cache/ScannerTest.php
+++ b/tests/lib/Files/Cache/ScannerTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -14,6 +15,8 @@ use OC\Files\Cache\Scanner;
use OC\Files\Storage\Storage;
use OC\Files\Storage\Temporary;
use OCP\Files\Cache\IScanner;
+use OCP\IDBConnection;
+use OCP\Server;
use Test\TestCase;
/**
@@ -67,7 +70,7 @@ class ScannerTest extends TestCase {
$data = "dummy file data\n";
$this->storage->file_put_contents('foo🙈.txt', $data);
- if (OC::$server->getDatabaseConnection()->supports4ByteText()) {
+ if (Server::get(IDBConnection::class)->supports4ByteText()) {
$this->assertNotNull($this->scanner->scanFile('foo🙈.txt'));
$this->assertTrue($this->cache->inCache('foo🙈.txt'), true);
@@ -337,7 +340,7 @@ class ScannerTest extends TestCase {
$oldFolderId = $this->cache->getId('folder');
// delete the folder without removing the children
- $query = OC::$server->getDatabaseConnection()->getQueryBuilder();
+ $query = Server::get(IDBConnection::class)->getQueryBuilder();
$query->delete('filecache')
->where($query->expr()->eq('fileid', $query->createNamedParameter($oldFolderId)));
$query->execute();
@@ -363,7 +366,7 @@ class ScannerTest extends TestCase {
$oldFolderId = $this->cache->getId('folder');
// delete the folder without removing the children
- $query = OC::$server->getDatabaseConnection()->getQueryBuilder();
+ $query = Server::get(IDBConnection::class)->getQueryBuilder();
$query->delete('filecache')
->where($query->expr()->eq('fileid', $query->createNamedParameter($oldFolderId)));
$query->execute();
@@ -383,18 +386,18 @@ class ScannerTest extends TestCase {
}
/**
- * @dataProvider dataTestIsPartialFile
*
* @param string $path
* @param bool $expected
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataTestIsPartialFile')]
public function testIsPartialFile($path, $expected): void {
$this->assertSame($expected,
$this->scanner->isPartialFile($path)
);
}
- public function dataTestIsPartialFile() {
+ public static function dataTestIsPartialFile(): array {
return [
['foo.txt.part', true],
['/sub/folder/foo.txt.part', true],
diff --git a/tests/lib/Files/Cache/SearchBuilderTest.php b/tests/lib/Files/Cache/SearchBuilderTest.php
index 17285d44209..ee097044e3b 100644
--- a/tests/lib/Files/Cache/SearchBuilderTest.php
+++ b/tests/lib/Files/Cache/SearchBuilderTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2017 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
@@ -16,6 +17,8 @@ use OCP\Files\Search\ISearchBinaryOperator;
use OCP\Files\Search\ISearchComparison;
use OCP\Files\Search\ISearchOperator;
use OCP\FilesMetadata\IFilesMetadataManager;
+use OCP\IDBConnection;
+use OCP\Server;
use Test\TestCase;
/**
@@ -39,7 +42,7 @@ class SearchBuilderTest extends TestCase {
protected function setUp(): void {
parent::setUp();
- $this->builder = \OC::$server->getDatabaseConnection()->getQueryBuilder();
+ $this->builder = Server::get(IDBConnection::class)->getQueryBuilder();
$this->mimetypeLoader = $this->createMock(IMimeTypeLoader::class);
$this->filesMetadataManager = $this->createMock(IFilesMetadataManager::class);
@@ -76,7 +79,7 @@ class SearchBuilderTest extends TestCase {
protected function tearDown(): void {
parent::tearDown();
- $builder = \OC::$server->getDatabaseConnection()->getQueryBuilder();
+ $builder = Server::get(IDBConnection::class)->getQueryBuilder();
$builder->delete('filecache')
->where($builder->expr()->eq('storage', $builder->createNamedParameter($this->numericStorageId, IQueryBuilder::PARAM_INT)));
@@ -109,7 +112,7 @@ class SearchBuilderTest extends TestCase {
$data['mimetype'] = 1;
}
- $builder = \OC::$server->getDatabaseConnection()->getQueryBuilder();
+ $builder = Server::get(IDBConnection::class)->getQueryBuilder();
$values = [];
foreach ($data as $key => $value) {
@@ -134,7 +137,7 @@ class SearchBuilderTest extends TestCase {
return $rows;
}
- public function comparisonProvider() {
+ public static function comparisonProvider(): array {
return [
[new SearchComparison(ISearchComparison::COMPARE_GREATER_THAN, 'mtime', 125), [1]],
[new SearchComparison(ISearchComparison::COMPARE_LESS_THAN, 'mtime', 125), [0]],
@@ -175,11 +178,11 @@ class SearchBuilderTest extends TestCase {
}
/**
- * @dataProvider comparisonProvider
*
* @param ISearchOperator $operator
* @param array $fileIds
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('comparisonProvider')]
public function testComparison(ISearchOperator $operator, array $fileIds): void {
$fileId = [];
$fileId[] = $this->addCacheEntry([
diff --git a/tests/lib/Files/Cache/UpdaterLegacyTest.php b/tests/lib/Files/Cache/UpdaterLegacyTest.php
index 0f7e9d78d77..c71fac2d2dc 100644
--- a/tests/lib/Files/Cache/UpdaterLegacyTest.php
+++ b/tests/lib/Files/Cache/UpdaterLegacyTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -7,9 +8,15 @@
namespace Test\Files\Cache;
+use OC\Files\Cache\Cache;
+use OC\Files\Cache\Scanner;
use OC\Files\Filesystem as Filesystem;
+use OC\Files\Storage\Storage;
+use OC\Files\Storage\Temporary;
use OC\Files\View;
use OCP\Files\Mount\IMountManager;
+use OCP\IUserManager;
+use OCP\Server;
/**
* Class UpdaterLegacyTest
@@ -20,17 +27,17 @@ use OCP\Files\Mount\IMountManager;
*/
class UpdaterLegacyTest extends \Test\TestCase {
/**
- * @var \OC\Files\Storage\Storage $storage
+ * @var Storage $storage
*/
private $storage;
/**
- * @var \OC\Files\Cache\Scanner $scanner
+ * @var Scanner $scanner
*/
private $scanner;
/**
- * @var \OC\Files\Cache\Cache $cache
+ * @var Cache $cache
*/
private $cache;
@@ -39,7 +46,7 @@ class UpdaterLegacyTest extends \Test\TestCase {
protected function setUp(): void {
parent::setUp();
- $this->storage = new \OC\Files\Storage\Temporary([]);
+ $this->storage = new Temporary([]);
$textData = "dummy file data\n";
$imgData = file_get_contents(\OC::$SERVERROOT . '/core/img/logo/logo.png');
$this->storage->mkdir('folder');
@@ -56,13 +63,13 @@ class UpdaterLegacyTest extends \Test\TestCase {
self::$user = $this->getUniqueID();
}
- \OC::$server->getUserManager()->createUser(self::$user, 'NotAnEasyPassword123456+');
+ Server::get(IUserManager::class)->createUser(self::$user, 'NotAnEasyPassword123456+');
$this->loginAsUser(self::$user);
Filesystem::init(self::$user, '/' . self::$user . '/files');
/** @var IMountManager $manager */
- $manager = \OC::$server->get(IMountManager::class);
+ $manager = Server::get(IMountManager::class);
$manager->removeMount('/' . self::$user);
Filesystem::mount($this->storage, [], '/' . self::$user . '/files');
@@ -76,7 +83,7 @@ class UpdaterLegacyTest extends \Test\TestCase {
}
$result = false;
- $user = \OC::$server->getUserManager()->get(self::$user);
+ $user = Server::get(IUserManager::class)->get(self::$user);
if ($user !== null) {
$result = $user->delete();
}
@@ -122,7 +129,7 @@ class UpdaterLegacyTest extends \Test\TestCase {
}
public function testWriteWithMountPoints(): void {
- $storage2 = new \OC\Files\Storage\Temporary([]);
+ $storage2 = new Temporary([]);
$storage2->getScanner()->scan(''); //initialize etags
$cache2 = $storage2->getCache();
Filesystem::mount($storage2, [], '/' . self::$user . '/files/folder/substorage');
@@ -183,7 +190,7 @@ class UpdaterLegacyTest extends \Test\TestCase {
}
public function testDeleteWithMountPoints(): void {
- $storage2 = new \OC\Files\Storage\Temporary([]);
+ $storage2 = new Temporary([]);
$cache2 = $storage2->getCache();
Filesystem::mount($storage2, [], '/' . self::$user . '/files/folder/substorage');
Filesystem::file_put_contents('folder/substorage/foo.txt', 'asd');
@@ -239,7 +246,7 @@ class UpdaterLegacyTest extends \Test\TestCase {
}
public function testRenameWithMountPoints(): void {
- $storage2 = new \OC\Files\Storage\Temporary([]);
+ $storage2 = new Temporary([]);
$cache2 = $storage2->getCache();
Filesystem::mount($storage2, [], '/' . self::$user . '/files/folder/substorage');
Filesystem::file_put_contents('folder/substorage/foo.txt', 'asd');
diff --git a/tests/lib/Files/Cache/UpdaterTest.php b/tests/lib/Files/Cache/UpdaterTest.php
index ab46bdd4141..65c47cb9ae6 100644
--- a/tests/lib/Files/Cache/UpdaterTest.php
+++ b/tests/lib/Files/Cache/UpdaterTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2019-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -7,10 +8,13 @@
namespace Test\Files\Cache;
+use OC\Files\Cache\Cache;
use OC\Files\Filesystem;
use OC\Files\ObjectStore\ObjectStoreStorage;
use OC\Files\ObjectStore\StorageObjectStore;
+use OC\Files\Storage\Storage;
use OC\Files\Storage\Temporary;
+use OC\Files\View;
use OCP\Files\Storage\IStorage;
/**
@@ -22,17 +26,17 @@ use OCP\Files\Storage\IStorage;
*/
class UpdaterTest extends \Test\TestCase {
/**
- * @var \OC\Files\Storage\Storage
+ * @var Storage
*/
protected $storage;
/**
- * @var \OC\Files\Cache\Cache
+ * @var Cache
*/
protected $cache;
/**
- * @var \OC\Files\View
+ * @var View
*/
protected $view;
@@ -305,16 +309,14 @@ class UpdaterTest extends \Test\TestCase {
}
}
- public function changeExtensionProvider(): array {
+ public static function changeExtensionProvider(): array {
return [
[new Temporary()],
[new ObjectStoreStorage(['objectstore' => new StorageObjectStore(new Temporary())])]
];
}
- /**
- * @dataProvider changeExtensionProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('changeExtensionProvider')]
public function testChangeExtension(IStorage $storage) {
$updater = $storage->getUpdater();
$cache = $storage->getCache();
diff --git a/tests/lib/Files/Cache/WatcherTest.php b/tests/lib/Files/Cache/WatcherTest.php
index 7319aa9b68d..6d0a8e0886b 100644
--- a/tests/lib/Files/Cache/WatcherTest.php
+++ b/tests/lib/Files/Cache/WatcherTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2018-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -7,6 +8,10 @@
namespace Test\Files\Cache;
+use OC\Files\Cache\Watcher;
+use OC\Files\Storage\Storage;
+use OC\Files\Storage\Temporary;
+
/**
* Class WatcherTest
*
@@ -16,7 +21,7 @@ namespace Test\Files\Cache;
*/
class WatcherTest extends \Test\TestCase {
/**
- * @var \OC\Files\Storage\Storage[] $storages
+ * @var Storage[] $storages
*/
private $storages = [];
@@ -44,7 +49,7 @@ class WatcherTest extends \Test\TestCase {
$storage = $this->getTestStorage();
$cache = $storage->getCache();
$updater = $storage->getWatcher();
- $updater->setPolicy(\OC\Files\Cache\Watcher::CHECK_ONCE);
+ $updater->setPolicy(Watcher::CHECK_ONCE);
//set the mtime to the past so it can detect an mtime change
$cache->put('', ['storage_mtime' => 10]);
@@ -85,7 +90,7 @@ class WatcherTest extends \Test\TestCase {
$storage = $this->getTestStorage();
$cache = $storage->getCache();
$updater = $storage->getWatcher();
- $updater->setPolicy(\OC\Files\Cache\Watcher::CHECK_ONCE);
+ $updater->setPolicy(Watcher::CHECK_ONCE);
//set the mtime to the past so it can detect an mtime change
$cache->put('', ['storage_mtime' => 10]);
@@ -102,7 +107,7 @@ class WatcherTest extends \Test\TestCase {
$storage = $this->getTestStorage();
$cache = $storage->getCache();
$updater = $storage->getWatcher();
- $updater->setPolicy(\OC\Files\Cache\Watcher::CHECK_ONCE);
+ $updater->setPolicy(Watcher::CHECK_ONCE);
//set the mtime to the past so it can detect an mtime change
$cache->put('foo.txt', ['storage_mtime' => 10]);
@@ -124,7 +129,7 @@ class WatcherTest extends \Test\TestCase {
//set the mtime to the past so it can detect an mtime change
$cache->put('foo.txt', ['storage_mtime' => 10]);
- $updater->setPolicy(\OC\Files\Cache\Watcher::CHECK_NEVER);
+ $updater->setPolicy(Watcher::CHECK_NEVER);
$storage->file_put_contents('foo.txt', 'q');
$this->assertFalse($updater->checkUpdate('foo.txt'));
@@ -142,7 +147,7 @@ class WatcherTest extends \Test\TestCase {
//set the mtime to the past so it can detect an mtime change
$cache->put('foo.txt', ['storage_mtime' => 10]);
- $updater->setPolicy(\OC\Files\Cache\Watcher::CHECK_ONCE);
+ $updater->setPolicy(Watcher::CHECK_ONCE);
$storage->file_put_contents('foo.txt', 'q');
$this->assertTrue($updater->checkUpdate('foo.txt'));
@@ -160,7 +165,7 @@ class WatcherTest extends \Test\TestCase {
//set the mtime to the past so it can detect an mtime change
$cache->put('foo.txt', ['storage_mtime' => 10]);
- $updater->setPolicy(\OC\Files\Cache\Watcher::CHECK_ALWAYS);
+ $updater->setPolicy(Watcher::CHECK_ALWAYS);
$storage->file_put_contents('foo.txt', 'q');
$this->assertTrue($updater->checkUpdate('foo.txt'));
@@ -172,10 +177,10 @@ class WatcherTest extends \Test\TestCase {
/**
* @param bool $scan
- * @return \OC\Files\Storage\Storage
+ * @return Storage
*/
private function getTestStorage($scan = true) {
- $storage = new \OC\Files\Storage\Temporary([]);
+ $storage = new Temporary([]);
$textData = "dummy file data\n";
$imgData = file_get_contents(\OC::$SERVERROOT . '/core/img/logo/logo.png');
$storage->mkdir('folder');
diff --git a/tests/lib/Files/Cache/Wrapper/CacheJailTest.php b/tests/lib/Files/Cache/Wrapper/CacheJailTest.php
index aed13c41ac0..8ac3492fbd2 100644
--- a/tests/lib/Files/Cache/Wrapper/CacheJailTest.php
+++ b/tests/lib/Files/Cache/Wrapper/CacheJailTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -7,7 +8,9 @@
namespace Test\Files\Cache\Wrapper;
+use OC\Files\Cache\Cache;
use OC\Files\Cache\Wrapper\CacheJail;
+use OC\Files\Cache\Wrapper\CacheWrapper;
use OC\Files\Search\SearchComparison;
use OC\Files\Search\SearchQuery;
use OC\Files\Storage\Wrapper\Jail;
@@ -26,7 +29,7 @@ use Test\Files\Cache\CacheTest;
*/
class CacheJailTest extends CacheTest {
/**
- * @var \OC\Files\Cache\Cache $sourceCache
+ * @var Cache $sourceCache
*/
protected $sourceCache;
@@ -34,7 +37,7 @@ class CacheJailTest extends CacheTest {
parent::setUp();
$this->storage->mkdir('jail');
$this->sourceCache = $this->cache;
- $this->cache = new \OC\Files\Cache\Wrapper\CacheJail($this->sourceCache, 'jail');
+ $this->cache = new CacheJail($this->sourceCache, 'jail');
$this->cache->insert('', ['size' => 0, 'mtime' => 0, 'mimetype' => ICacheEntry::DIRECTORY_MIMETYPE]);
}
@@ -129,7 +132,7 @@ class CacheJailTest extends CacheTest {
$this->assertEquals('bar', $path);
// path from jailed '' of foo/bar is foo/bar
- $this->cache = new \OC\Files\Cache\Wrapper\CacheJail($this->sourceCache, '');
+ $this->cache = new CacheJail($this->sourceCache, '');
$path = $this->cache->getPathById($id);
$this->assertEquals('jail/bar', $path);
}
@@ -199,7 +202,7 @@ class CacheJailTest extends CacheTest {
$this->sourceCache->put($file2, $data1);
$this->sourceCache->put($file3, $data1);
- $nested = new \OC\Files\Cache\Wrapper\CacheJail($this->cache, 'bar');
+ $nested = new CacheJail($this->cache, 'bar');
$result = $nested->search('%asd%');
$this->assertCount(1, $result);
@@ -217,7 +220,7 @@ class CacheJailTest extends CacheTest {
$this->sourceCache->put($file2, $data1);
$this->sourceCache->put($file3, $data1);
- $nested = new \OC\Files\Cache\Wrapper\CacheJail($this->sourceCache, '');
+ $nested = new CacheJail($this->sourceCache, '');
$result = $nested->search('%asd%');
$this->assertCount(1, $result);
@@ -252,4 +255,14 @@ class CacheJailTest extends CacheTest {
$storage->getWatcher()->update('bar', ['mimetype' => 'text/plain']);
$this->assertTrue($this->cache->inCache('bar'));
}
+
+ public function testUnJailedRoot(): void {
+ $jail1 = new CacheJail($this->sourceCache, 'foo');
+ $jail2 = new CacheJail($jail1, 'bar');
+ $this->assertEquals('foo/bar', $jail2->getGetUnjailedRoot());
+
+ $middleWrapper = new CacheWrapper($jail1);
+ $jail3 = new CacheJail($middleWrapper, 'bar');
+ $this->assertEquals('foo/bar', $jail3->getGetUnjailedRoot());
+ }
}
diff --git a/tests/lib/Files/Cache/Wrapper/CachePermissionsMaskTest.php b/tests/lib/Files/Cache/Wrapper/CachePermissionsMaskTest.php
index afb5c6a5d4d..4fbeafc9270 100644
--- a/tests/lib/Files/Cache/Wrapper/CachePermissionsMaskTest.php
+++ b/tests/lib/Files/Cache/Wrapper/CachePermissionsMaskTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2019-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -7,6 +8,8 @@
namespace Test\Files\Cache\Wrapper;
+use OC\Files\Cache\Cache;
+use OC\Files\Cache\Wrapper\CachePermissionsMask;
use OCP\Constants;
use Test\Files\Cache\CacheTest;
@@ -19,7 +22,7 @@ use Test\Files\Cache\CacheTest;
*/
class CachePermissionsMaskTest extends CacheTest {
/**
- * @var \OC\Files\Cache\Cache $sourceCache
+ * @var Cache $sourceCache
*/
protected $sourceCache;
@@ -31,10 +34,10 @@ class CachePermissionsMaskTest extends CacheTest {
}
protected function getMaskedCached($mask) {
- return new \OC\Files\Cache\Wrapper\CachePermissionsMask($this->sourceCache, $mask);
+ return new CachePermissionsMask($this->sourceCache, $mask);
}
- public function maskProvider() {
+ public static function maskProvider(): array {
return [
[Constants::PERMISSION_ALL],
[Constants::PERMISSION_ALL - Constants::PERMISSION_SHARE],
@@ -44,9 +47,9 @@ class CachePermissionsMaskTest extends CacheTest {
}
/**
- * @dataProvider maskProvider
* @param int $mask
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('maskProvider')]
public function testGetMasked($mask): void {
$cache = $this->getMaskedCached($mask);
$data = ['size' => 100, 'mtime' => 50, 'mimetype' => 'text/plain', 'permissions' => Constants::PERMISSION_ALL];
@@ -61,9 +64,9 @@ class CachePermissionsMaskTest extends CacheTest {
}
/**
- * @dataProvider maskProvider
* @param int $mask
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('maskProvider')]
public function testGetFolderContentMasked($mask): void {
$this->storage->mkdir('foo');
$this->storage->file_put_contents('foo/bar', 'asd');
@@ -80,9 +83,9 @@ class CachePermissionsMaskTest extends CacheTest {
}
/**
- * @dataProvider maskProvider
* @param int $mask
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('maskProvider')]
public function testSearchMasked($mask): void {
$this->storage->mkdir('foo');
$this->storage->file_put_contents('foo/bar', 'asd');
diff --git a/tests/lib/Files/Config/UserMountCacheTest.php b/tests/lib/Files/Config/UserMountCacheTest.php
index 1efc56c1908..6a3dc6a6d7e 100644
--- a/tests/lib/Files/Config/UserMountCacheTest.php
+++ b/tests/lib/Files/Config/UserMountCacheTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -9,6 +10,8 @@ namespace Test\Files\Config;
use OC\DB\Exceptions\DbalException;
use OC\DB\QueryBuilder\Literal;
+use OC\Files\Cache\Cache;
+use OC\Files\Config\UserMountCache;
use OC\Files\Mount\MountPoint;
use OC\Files\Storage\Storage;
use OC\User\Manager;
@@ -16,11 +19,15 @@ use OCP\Cache\CappedMemoryCache;
use OCP\DB\QueryBuilder\IQueryBuilder;
use OCP\Diagnostics\IEventLogger;
use OCP\EventDispatcher\IEventDispatcher;
+use OCP\Files\Config\Event\UserMountAddedEvent;
+use OCP\Files\Config\Event\UserMountRemovedEvent;
+use OCP\Files\Config\Event\UserMountUpdatedEvent;
use OCP\Files\Config\ICachedMountInfo;
use OCP\ICacheFactory;
use OCP\IConfig;
use OCP\IDBConnection;
use OCP\IUserManager;
+use OCP\Server;
use Psr\Log\LoggerInterface;
use Test\TestCase;
use Test\Util\User\Dummy;
@@ -29,28 +36,19 @@ use Test\Util\User\Dummy;
* @group DB
*/
class UserMountCacheTest extends TestCase {
- /**
- * @var IDBConnection
- */
- private $connection;
-
- /**
- * @var IUserManager
- */
- private $userManager;
-
- /**
- * @var \OC\Files\Config\UserMountCache
- */
- private $cache;
-
- private $fileIds = [];
+ private IDBConnection $connection;
+ private IUserManager $userManager;
+ private IEventDispatcher $eventDispatcher;
+ private UserMountCache $cache;
+ private array $fileIds = [];
protected function setUp(): void {
parent::setUp();
$this->fileIds = [];
- $this->connection = \OC::$server->getDatabaseConnection();
+
+ $this->connection = Server::get(IDBConnection::class);
+
$config = $this->getMockBuilder(IConfig::class)
->disableOriginalConstructor()
->getMock();
@@ -62,13 +60,22 @@ class UserMountCacheTest extends TestCase {
->expects($this->any())
->method('getAppValue')
->willReturnArgument(2);
+
$this->userManager = new Manager($config, $this->createMock(ICacheFactory::class), $this->createMock(IEventDispatcher::class), $this->createMock(LoggerInterface::class));
$userBackend = new Dummy();
$userBackend->createUser('u1', '');
$userBackend->createUser('u2', '');
$userBackend->createUser('u3', '');
$this->userManager->registerBackend($userBackend);
- $this->cache = new \OC\Files\Config\UserMountCache($this->connection, $this->userManager, $this->createMock(LoggerInterface::class), $this->createMock(IEventLogger::class));
+
+ $this->eventDispatcher = $this->createMock(IEventDispatcher::class);
+
+ $this->cache = new UserMountCache($this->connection,
+ $this->userManager,
+ $this->createMock(LoggerInterface::class),
+ $this->createMock(IEventLogger::class),
+ $this->eventDispatcher,
+ );
}
protected function tearDown(): void {
@@ -88,25 +95,19 @@ class UserMountCacheTest extends TestCase {
private function getStorage($storageId, $rootInternalPath = '') {
$rootId = $this->createCacheEntry($rootInternalPath, $storageId);
- $storageCache = $this->getMockBuilder('\OC\Files\Cache\Storage')
- ->disableOriginalConstructor()
- ->getMock();
+ $storageCache = $this->createMock(\OC\Files\Cache\Storage::class);
$storageCache->expects($this->any())
->method('getNumericId')
->willReturn($storageId);
- $cache = $this->getMockBuilder('\OC\Files\Cache\Cache')
- ->disableOriginalConstructor()
- ->getMock();
+ $cache = $this->createMock(Cache::class);
$cache->expects($this->any())
->method('getId')
->willReturn($rootId);
$cache->method('getNumericStorageId')
->willReturn($storageId);
- $storage = $this->getMockBuilder('\OC\Files\Storage\Storage')
- ->disableOriginalConstructor()
- ->getMock();
+ $storage = $this->createMock(Storage::class);
$storage->expects($this->any())
->method('getStorageCache')
->willReturn($storageCache);
@@ -126,6 +127,11 @@ class UserMountCacheTest extends TestCase {
}
public function testNewMounts(): void {
+ $this->eventDispatcher
+ ->expects($this->once())
+ ->method('dispatchTyped')
+ ->with($this->callback(fn (UserMountAddedEvent $event) => $event->mountPoint->getMountPoint() === '/asd/'));
+
$user = $this->userManager->get('u1');
[$storage] = $this->getStorage(10);
@@ -146,6 +152,11 @@ class UserMountCacheTest extends TestCase {
}
public function testSameMounts(): void {
+ $this->eventDispatcher
+ ->expects($this->once())
+ ->method('dispatchTyped')
+ ->with($this->callback(fn (UserMountAddedEvent $event) => $event->mountPoint->getMountPoint() === '/asd/'));
+
$user = $this->userManager->get('u1');
[$storage] = $this->getStorage(10);
@@ -170,6 +181,18 @@ class UserMountCacheTest extends TestCase {
}
public function testRemoveMounts(): void {
+ $operation = 0;
+ $this->eventDispatcher
+ ->expects($this->exactly(2))
+ ->method('dispatchTyped')
+ ->with($this->callback(function (UserMountAddedEvent|UserMountRemovedEvent $event) use (&$operation) {
+ return match(++$operation) {
+ 1 => $event instanceof UserMountAddedEvent && $event->mountPoint->getMountPoint() === '/asd/',
+ 2 => $event instanceof UserMountRemovedEvent && $event->mountPoint->getMountPoint() === '/asd/',
+ default => false,
+ };
+ }));
+
$user = $this->userManager->get('u1');
[$storage] = $this->getStorage(10);
@@ -189,6 +212,19 @@ class UserMountCacheTest extends TestCase {
}
public function testChangeMounts(): void {
+ $operation = 0;
+ $this->eventDispatcher
+ ->expects($this->exactly(3))
+ ->method('dispatchTyped')
+ ->with($this->callback(function (UserMountAddedEvent|UserMountRemovedEvent $event) use (&$operation) {
+ return match(++$operation) {
+ 1 => $event instanceof UserMountAddedEvent && $event->mountPoint->getMountPoint() === '/bar/',
+ 2 => $event instanceof UserMountAddedEvent && $event->mountPoint->getMountPoint() === '/foo/',
+ 3 => $event instanceof UserMountRemovedEvent && $event->mountPoint->getMountPoint() === '/bar/',
+ default => false,
+ };
+ }));
+
$user = $this->userManager->get('u1');
[$storage] = $this->getStorage(10);
@@ -212,6 +248,18 @@ class UserMountCacheTest extends TestCase {
}
public function testChangeMountId(): void {
+ $operation = 0;
+ $this->eventDispatcher
+ ->expects($this->exactly(2))
+ ->method('dispatchTyped')
+ ->with($this->callback(function (UserMountAddedEvent|UserMountUpdatedEvent $event) use (&$operation) {
+ return match(++$operation) {
+ 1 => $event instanceof UserMountAddedEvent && $event->mountPoint->getMountPoint() === '/foo/',
+ 2 => $event instanceof UserMountUpdatedEvent && $event->oldMountPoint->getMountId() === null && $event->newMountPoint->getMountId() === 1,
+ default => false,
+ };
+ }));
+
$user = $this->userManager->get('u1');
[$storage] = $this->getStorage(10);
@@ -427,9 +475,9 @@ class UserMountCacheTest extends TestCase {
$fileId = $this->createCacheEntry('/foo/bar', 2);
- $mount1 = $this->getMockBuilder('\OC\Files\Mount\MountPoint')
+ $mount1 = $this->getMockBuilder(MountPoint::class)
->setConstructorArgs([$storage1, '/'])
- ->setMethods(['getStorageRootId'])
+ ->onlyMethods(['getStorageRootId'])
->getMock();
$mount1->expects($this->any())
@@ -460,9 +508,9 @@ class UserMountCacheTest extends TestCase {
$folderId = $this->createCacheEntry('/foo', 2);
$fileId = $this->createCacheEntry('/bar/asd', 2);
- $mount1 = $this->getMockBuilder('\OC\Files\Mount\MountPoint')
+ $mount1 = $this->getMockBuilder(MountPoint::class)
->setConstructorArgs([$storage1, '/foo/'])
- ->setMethods(['getStorageRootId'])
+ ->onlyMethods(['getStorageRootId'])
->getMock();
$mount1->expects($this->any())
@@ -509,7 +557,7 @@ class UserMountCacheTest extends TestCase {
$mount1 = $this->getMockBuilder(MountPoint::class)
->setConstructorArgs([$storage1, '/u1/'])
- ->setMethods(['getStorageRootId', 'getNumericStorageId'])
+ ->onlyMethods(['getStorageRootId', 'getNumericStorageId'])
->getMock();
$mount1->expects($this->any())
diff --git a/tests/lib/Files/EtagTest.php b/tests/lib/Files/EtagTest.php
index b0cdff16f4d..d1b344ee997 100644
--- a/tests/lib/Files/EtagTest.php
+++ b/tests/lib/Files/EtagTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -8,8 +9,13 @@
namespace Test\Files;
use OC\Files\Filesystem;
+use OC\Files\Utils\Scanner;
+use OC\Share\Share;
use OCA\Files_Sharing\AppInfo\Application;
use OCP\EventDispatcher\IEventDispatcher;
+use OCP\IConfig;
+use OCP\IDBConnection;
+use OCP\ITempManager;
use OCP\IUserManager;
use OCP\Server;
use Psr\Log\LoggerInterface;
@@ -38,12 +44,12 @@ class EtagTest extends \Test\TestCase {
// init files sharing
new Application();
- \OC\Share\Share::registerBackend('file', 'OCA\Files_Sharing\ShareBackend\File');
- \OC\Share\Share::registerBackend('folder', 'OCA\Files_Sharing\ShareBackend\Folder', 'file');
+ Share::registerBackend('file', 'OCA\Files_Sharing\ShareBackend\File');
+ Share::registerBackend('folder', 'OCA\Files_Sharing\ShareBackend\Folder', 'file');
- $config = \OC::$server->getConfig();
+ $config = Server::get(IConfig::class);
$this->datadir = $config->getSystemValueString('datadirectory');
- $this->tmpDir = \OC::$server->getTempManager()->getTemporaryFolder();
+ $this->tmpDir = Server::get(ITempManager::class)->getTemporaryFolder();
$config->setSystemValue('datadirectory', $this->tmpDir);
$this->userBackend = new \Test\Util\User\Dummy();
@@ -51,7 +57,7 @@ class EtagTest extends \Test\TestCase {
}
protected function tearDown(): void {
- \OC::$server->getConfig()->setSystemValue('datadirectory', $this->datadir);
+ Server::get(IConfig::class)->setSystemValue('datadirectory', $this->datadir);
$this->logout();
parent::tearDown();
@@ -71,7 +77,7 @@ class EtagTest extends \Test\TestCase {
$files = ['/foo.txt', '/folder/bar.txt', '/folder/subfolder', '/folder/subfolder/qwerty.txt'];
$originalEtags = $this->getEtags($files);
- $scanner = new \OC\Files\Utils\Scanner($user1, \OC::$server->getDatabaseConnection(), \OC::$server->query(IEventDispatcher::class), \OC::$server->get(LoggerInterface::class));
+ $scanner = new Scanner($user1, Server::get(IDBConnection::class), Server::get(IEventDispatcher::class), Server::get(LoggerInterface::class));
$scanner->backgroundScan('/');
$newEtags = $this->getEtags($files);
diff --git a/tests/lib/Files/FileInfoTest.php b/tests/lib/Files/FileInfoTest.php
index 2979252f78a..b3d3c9f0fec 100644
--- a/tests/lib/Files/FileInfoTest.php
+++ b/tests/lib/Files/FileInfoTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
diff --git a/tests/lib/Files/FilenameValidatorTest.php b/tests/lib/Files/FilenameValidatorTest.php
index 45f681bd453..162275a2cf8 100644
--- a/tests/lib/Files/FilenameValidatorTest.php
+++ b/tests/lib/Files/FilenameValidatorTest.php
@@ -48,9 +48,7 @@ class FilenameValidatorTest extends TestCase {
$this->database->method('supports4ByteText')->willReturn(true);
}
- /**
- * @dataProvider dataValidateFilename
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataValidateFilename')]
public function testValidateFilename(
string $filename,
array $forbiddenNames,
@@ -87,9 +85,7 @@ class FilenameValidatorTest extends TestCase {
$validator->validateFilename($filename);
}
- /**
- * @dataProvider dataValidateFilename
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataValidateFilename')]
public function testIsFilenameValid(
string $filename,
array $forbiddenNames,
@@ -122,7 +118,7 @@ class FilenameValidatorTest extends TestCase {
$this->assertEquals($exception === null, $validator->isFilenameValid($filename));
}
- public function dataValidateFilename(): array {
+ public static function dataValidateFilename(): array {
return [
'valid name' => [
'a: b.txt', ['.htaccess'], [], [], [], null
@@ -189,9 +185,7 @@ class FilenameValidatorTest extends TestCase {
];
}
- /**
- * @dataProvider data4ByteUnicode
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('data4ByteUnicode')]
public function testDatabaseDoesNotSupport4ByteText($filename): void {
$database = $this->createMock(IDBConnection::class);
$database->expects($this->once())
@@ -202,23 +196,21 @@ class FilenameValidatorTest extends TestCase {
$validator->validateFilename($filename);
}
- public function data4ByteUnicode(): array {
+ public static function data4ByteUnicode(): array {
return [
['plane 1 𐪅'],
['emoji 😶‍🌫️'],
];
}
- /**
- * @dataProvider dataInvalidAsciiCharacters
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataInvalidAsciiCharacters')]
public function testInvalidAsciiCharactersAreAlwaysForbidden(string $filename): void {
$this->expectException(InvalidPathException::class);
$validator = new FilenameValidator($this->l10n, $this->database, $this->config, $this->logger);
$validator->validateFilename($filename);
}
- public function dataInvalidAsciiCharacters(): array {
+ public static function dataInvalidAsciiCharacters(): array {
return [
[\chr(0)],
[\chr(1)],
@@ -255,9 +247,7 @@ class FilenameValidatorTest extends TestCase {
];
}
- /**
- * @dataProvider dataIsForbidden
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataIsForbidden')]
public function testIsForbidden(string $filename, array $forbiddenNames, bool $expected): void {
/** @var FilenameValidator&MockObject */
$validator = $this->getMockBuilder(FilenameValidator::class)
@@ -271,7 +261,7 @@ class FilenameValidatorTest extends TestCase {
$this->assertEquals($expected, $validator->isForbidden($filename));
}
- public function dataIsForbidden(): array {
+ public static function dataIsForbidden(): array {
return [
'valid name' => [
'a: b.txt', ['.htaccess'], false
@@ -291,9 +281,7 @@ class FilenameValidatorTest extends TestCase {
];
}
- /**
- * @dataProvider dataGetForbiddenExtensions
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataGetForbiddenExtensions')]
public function testGetForbiddenExtensions(array $configValue, array $expectedValue): void {
$validator = new FilenameValidator($this->l10n, $this->database, $this->config, $this->logger);
$this->config
@@ -317,9 +305,7 @@ class FilenameValidatorTest extends TestCase {
];
}
- /**
- * @dataProvider dataGetForbiddenFilenames
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataGetForbiddenFilenames')]
public function testGetForbiddenFilenames(array $configValue, array $legacyValue, array $expectedValue): void {
$validator = new FilenameValidator($this->l10n, $this->database, $this->config, $this->logger);
$this->config
@@ -349,9 +335,7 @@ class FilenameValidatorTest extends TestCase {
];
}
- /**
- * @dataProvider dataGetForbiddenBasenames
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataGetForbiddenBasenames')]
public function testGetForbiddenBasenames(array $configValue, array $expectedValue): void {
$validator = new FilenameValidator($this->l10n, $this->database, $this->config, $this->logger);
$this->config
@@ -374,4 +358,134 @@ class FilenameValidatorTest extends TestCase {
[['AuX', 'COM1'], ['aux', 'com1']],
];
}
+
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataSanitizeFilename')]
+ public function testSanitizeFilename(
+ string $filename,
+ array $forbiddenNames,
+ array $forbiddenBasenames,
+ array $forbiddenExtensions,
+ array $forbiddenCharacters,
+ string $expected,
+ ): void {
+ /** @var FilenameValidator&MockObject */
+ $validator = $this->getMockBuilder(FilenameValidator::class)
+ ->onlyMethods([
+ 'getForbiddenBasenames',
+ 'getForbiddenExtensions',
+ 'getForbiddenFilenames',
+ 'getForbiddenCharacters',
+ ])
+ ->setConstructorArgs([$this->l10n, $this->database, $this->config, $this->logger])
+ ->getMock();
+
+ $validator->method('getForbiddenBasenames')
+ ->willReturn($forbiddenBasenames);
+ $validator->method('getForbiddenCharacters')
+ ->willReturn($forbiddenCharacters);
+ $validator->method('getForbiddenExtensions')
+ ->willReturn($forbiddenExtensions);
+ $validator->method('getForbiddenFilenames')
+ ->willReturn($forbiddenNames);
+
+ $this->assertEquals($expected, $validator->sanitizeFilename($filename));
+ }
+
+ public static function dataSanitizeFilename(): array {
+ return [
+ 'valid name' => [
+ 'a * b.txt', ['.htaccess'], [], [], [], 'a * b.txt'
+ ],
+ 'forbidden name in the middle is ok' => [
+ 'a.htaccess.txt', ['.htaccess'], [], [], [], 'a.htaccess.txt'
+ ],
+ 'forbidden name on the beginning' => [
+ '.htaccess.sample', ['.htaccess'], [], [], [], '.htaccess.sample'
+ ],
+ 'forbidden name' => [
+ '.htaccess', ['.htaccess'], [], [], [], '.htaccess (renamed)'
+ ],
+ 'forbidden name - name is case insensitive' => [
+ 'COM1', ['.htaccess', 'com1'], [], [], [], 'COM1 (renamed)'
+ ],
+ 'forbidden basename' => [
+ 'com1.suffix', ['.htaccess'], ['com1'], [], [], 'com1 (renamed).suffix'
+ ],
+ 'forbidden basename case insensitive' => [
+ // needed for Windows namespaces
+ 'COM1.suffix', ['.htaccess'], ['com1'], [], [], 'COM1 (renamed).suffix'
+ ],
+ 'forbidden basename for hidden files' => [
+ // needed for Windows namespaces
+ '.thumbs.db', ['.htaccess'], ['.thumbs'], [], [], '.thumbs (renamed).db'
+ ],
+ 'invalid character' => [
+ 'a: b.txt', ['.htaccess'], [], [], [':'], 'a_ b.txt',
+ ],
+ 'invalid extension' => [
+ 'a: b.txt', ['.htaccess'], [], ['.txt'], [], 'a: b'
+ ],
+ 'invalid extension case insensitive' => [
+ 'a: b.TXT', ['.htaccess'], [], ['.txt'], [], 'a: b'
+ ],
+ 'empty filename' => [
+ '', [], [], [], [], 'renamed file'
+ ],
+ ];
+ }
+
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataSanitizeFilenameCharacterReplacement')]
+ public function testSanitizeFilenameCharacterReplacement(
+ string $filename,
+ array $forbiddenCharacters,
+ ?string $characterReplacement,
+ ?string $expected,
+ ): void {
+ /** @var FilenameValidator&MockObject */
+ $validator = $this->getMockBuilder(FilenameValidator::class)
+ ->onlyMethods([
+ 'getForbiddenBasenames',
+ 'getForbiddenExtensions',
+ 'getForbiddenFilenames',
+ 'getForbiddenCharacters',
+ ])
+ ->setConstructorArgs([$this->l10n, $this->database, $this->config, $this->logger])
+ ->getMock();
+
+ $validator->method('getForbiddenBasenames')
+ ->willReturn([]);
+ $validator->method('getForbiddenCharacters')
+ ->willReturn($forbiddenCharacters);
+ $validator->method('getForbiddenExtensions')
+ ->willReturn([]);
+ $validator->method('getForbiddenFilenames')
+ ->willReturn([]);
+
+ if ($expected === null) {
+ $this->expectException(\InvalidArgumentException::class);
+ $validator->sanitizeFilename($filename, $characterReplacement);
+ } else {
+ $this->assertEquals($expected, $validator->sanitizeFilename($filename, $characterReplacement));
+ }
+ }
+
+ public static function dataSanitizeFilenameCharacterReplacement(): array {
+ return [
+ 'default' => [
+ 'foo*bar', ['*'], null, 'foo_bar'
+ ],
+ 'default - underscore not allowed' => [
+ 'foo*bar', ['*', '_'], null, 'foo-bar'
+ ],
+ 'default - dash and underscore not allowed' => [
+ 'foo*bar', ['*', '-', '_'], null, 'foo bar'
+ ],
+ 'default - no replacement' => [
+ 'foo*bar', ['*', ' ', '_', '-'], null, null
+ ],
+ 'custom replacement' => [
+ 'foo*bar', ['*'], 'x', 'fooxbar'
+ ],
+ ];
+ }
}
diff --git a/tests/lib/Files/FilesystemTest.php b/tests/lib/Files/FilesystemTest.php
index a920dc662da..a819acb1620 100644
--- a/tests/lib/Files/FilesystemTest.php
+++ b/tests/lib/Files/FilesystemTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -7,23 +8,30 @@
namespace Test\Files;
+use OC\Files\Filesystem;
use OC\Files\Mount\MountPoint;
use OC\Files\Storage\Temporary;
+use OC\Files\View;
use OC\User\NoUserException;
+use OCP\Files;
use OCP\Files\Config\IMountProvider;
+use OCP\Files\Config\IMountProviderCollection;
+use OCP\Files\Mount\IMountPoint;
use OCP\Files\Storage\IStorageFactory;
+use OCP\IConfig;
+use OCP\ITempManager;
use OCP\IUser;
use OCP\IUserManager;
+use OCP\IUserSession;
use OCP\Server;
class DummyMountProvider implements IMountProvider {
- private $mounts = [];
-
/**
* @param array $mounts
*/
- public function __construct(array $mounts) {
- $this->mounts = $mounts;
+ public function __construct(
+ private array $mounts,
+ ) {
}
/**
@@ -31,7 +39,7 @@ class DummyMountProvider implements IMountProvider {
*
* @param IUser $user
* @param IStorageFactory $loader
- * @return \OCP\Files\Mount\IMountPoint[]
+ * @return IMountPoint[]
*/
public function getMountsForUser(IUser $user, IStorageFactory $loader) {
return isset($this->mounts[$user->getUID()]) ? $this->mounts[$user->getUID()] : [];
@@ -58,7 +66,7 @@ class FilesystemTest extends \Test\TestCase {
* @return array
*/
private function getStorageData() {
- $dir = \OC::$server->getTempManager()->getTemporaryFolder();
+ $dir = Server::get(ITempManager::class)->getTemporaryFolder();
$this->tmpDirs[] = $dir;
return ['datadir' => $dir];
}
@@ -68,13 +76,13 @@ class FilesystemTest extends \Test\TestCase {
$userBackend = new \Test\Util\User\Dummy();
$userBackend->createUser(self::TEST_FILESYSTEM_USER1, self::TEST_FILESYSTEM_USER1);
$userBackend->createUser(self::TEST_FILESYSTEM_USER2, self::TEST_FILESYSTEM_USER2);
- \OC::$server->getUserManager()->registerBackend($userBackend);
+ Server::get(IUserManager::class)->registerBackend($userBackend);
$this->loginAsUser();
}
protected function tearDown(): void {
foreach ($this->tmpDirs as $dir) {
- \OC_Helper::rmdirr($dir);
+ Files::rmdirr($dir);
}
$this->logout();
@@ -83,24 +91,24 @@ class FilesystemTest extends \Test\TestCase {
}
public function testMount(): void {
- \OC\Files\Filesystem::mount('\OC\Files\Storage\Local', self::getStorageData(), '/');
- $this->assertEquals('/', \OC\Files\Filesystem::getMountPoint('/'));
- $this->assertEquals('/', \OC\Files\Filesystem::getMountPoint('/some/folder'));
- [, $internalPath] = \OC\Files\Filesystem::resolvePath('/');
+ Filesystem::mount('\OC\Files\Storage\Local', self::getStorageData(), '/');
+ $this->assertEquals('/', Filesystem::getMountPoint('/'));
+ $this->assertEquals('/', Filesystem::getMountPoint('/some/folder'));
+ [, $internalPath] = Filesystem::resolvePath('/');
$this->assertEquals('', $internalPath);
- [, $internalPath] = \OC\Files\Filesystem::resolvePath('/some/folder');
+ [, $internalPath] = Filesystem::resolvePath('/some/folder');
$this->assertEquals('some/folder', $internalPath);
- \OC\Files\Filesystem::mount('\OC\Files\Storage\Local', self::getStorageData(), '/some');
- $this->assertEquals('/', \OC\Files\Filesystem::getMountPoint('/'));
- $this->assertEquals('/some/', \OC\Files\Filesystem::getMountPoint('/some/folder'));
- $this->assertEquals('/some/', \OC\Files\Filesystem::getMountPoint('/some/'));
- $this->assertEquals('/some/', \OC\Files\Filesystem::getMountPoint('/some'));
- [, $internalPath] = \OC\Files\Filesystem::resolvePath('/some/folder');
+ Filesystem::mount('\OC\Files\Storage\Local', self::getStorageData(), '/some');
+ $this->assertEquals('/', Filesystem::getMountPoint('/'));
+ $this->assertEquals('/some/', Filesystem::getMountPoint('/some/folder'));
+ $this->assertEquals('/some/', Filesystem::getMountPoint('/some/'));
+ $this->assertEquals('/some/', Filesystem::getMountPoint('/some'));
+ [, $internalPath] = Filesystem::resolvePath('/some/folder');
$this->assertEquals('folder', $internalPath);
}
- public function normalizePathData() {
+ public static function normalizePathData(): array {
return [
['/', ''],
['/', '/'],
@@ -194,14 +202,12 @@ class FilesystemTest extends \Test\TestCase {
];
}
- /**
- * @dataProvider normalizePathData
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('normalizePathData')]
public function testNormalizePath($expected, $path, $stripTrailingSlash = true): void {
- $this->assertEquals($expected, \OC\Files\Filesystem::normalizePath($path, $stripTrailingSlash));
+ $this->assertEquals($expected, Filesystem::normalizePath($path, $stripTrailingSlash));
}
- public function normalizePathKeepUnicodeData() {
+ public static function normalizePathKeepUnicodeData(): array {
$nfdName = 'ümlaut';
$nfcName = 'ümlaut';
return [
@@ -212,22 +218,20 @@ class FilesystemTest extends \Test\TestCase {
];
}
- /**
- * @dataProvider normalizePathKeepUnicodeData
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('normalizePathKeepUnicodeData')]
public function testNormalizePathKeepUnicode($expected, $path, $keepUnicode = false): void {
- $this->assertEquals($expected, \OC\Files\Filesystem::normalizePath($path, true, false, $keepUnicode));
+ $this->assertEquals($expected, Filesystem::normalizePath($path, true, false, $keepUnicode));
}
public function testNormalizePathKeepUnicodeCache(): void {
$nfdName = 'ümlaut';
$nfcName = 'ümlaut';
// call in succession due to cache
- $this->assertEquals('/' . $nfcName, \OC\Files\Filesystem::normalizePath($nfdName, true, false, false));
- $this->assertEquals('/' . $nfdName, \OC\Files\Filesystem::normalizePath($nfdName, true, false, true));
+ $this->assertEquals('/' . $nfcName, Filesystem::normalizePath($nfdName, true, false, false));
+ $this->assertEquals('/' . $nfdName, Filesystem::normalizePath($nfdName, true, false, true));
}
- public function isValidPathData() {
+ public static function isValidPathData(): array {
return [
['/', true],
['/path', true],
@@ -253,14 +257,12 @@ class FilesystemTest extends \Test\TestCase {
];
}
- /**
- * @dataProvider isValidPathData
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('isValidPathData')]
public function testIsValidPath($path, $expected): void {
- $this->assertSame($expected, \OC\Files\Filesystem::isValidPath($path));
+ $this->assertSame($expected, Filesystem::isValidPath($path));
}
- public function isFileBlacklistedData() {
+ public static function isFileBlacklistedData(): array {
return [
['/etc/foo/bar/foo.txt', false],
['\etc\foo/bar\foo.txt', false],
@@ -275,11 +277,9 @@ class FilesystemTest extends \Test\TestCase {
];
}
- /**
- * @dataProvider isFileBlacklistedData
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('isFileBlacklistedData')]
public function testIsFileBlacklisted($path, $expected): void {
- $this->assertSame($expected, \OC\Files\Filesystem::isFileBlacklisted($path));
+ $this->assertSame($expected, Filesystem::isFileBlacklisted($path));
}
public function testNormalizePathUTF8(): void {
@@ -287,36 +287,36 @@ class FilesystemTest extends \Test\TestCase {
$this->markTestSkipped('UTF8 normalizer Patchwork was not found');
}
- $this->assertEquals("/foo/bar\xC3\xBC", \OC\Files\Filesystem::normalizePath("/foo/baru\xCC\x88"));
- $this->assertEquals("/foo/bar\xC3\xBC", \OC\Files\Filesystem::normalizePath("\\foo\\baru\xCC\x88"));
+ $this->assertEquals("/foo/bar\xC3\xBC", Filesystem::normalizePath("/foo/baru\xCC\x88"));
+ $this->assertEquals("/foo/bar\xC3\xBC", Filesystem::normalizePath("\\foo\\baru\xCC\x88"));
}
public function testHooks(): void {
- if (\OC\Files\Filesystem::getView()) {
+ if (Filesystem::getView()) {
$user = \OC_User::getUser();
} else {
$user = self::TEST_FILESYSTEM_USER1;
$backend = new \Test\Util\User\Dummy();
Server::get(IUserManager::class)->registerBackend($backend);
$backend->createUser($user, $user);
- $userObj = \OC::$server->getUserManager()->get($user);
- \OC::$server->getUserSession()->setUser($userObj);
- \OC\Files\Filesystem::init($user, '/' . $user . '/files');
+ $userObj = Server::get(IUserManager::class)->get($user);
+ Server::get(IUserSession::class)->setUser($userObj);
+ Filesystem::init($user, '/' . $user . '/files');
}
\OC_Hook::clear('OC_Filesystem');
\OC_Hook::connect('OC_Filesystem', 'post_write', $this, 'dummyHook');
- \OC\Files\Filesystem::mount('OC\Files\Storage\Temporary', [], '/');
+ Filesystem::mount('OC\Files\Storage\Temporary', [], '/');
- $rootView = new \OC\Files\View('');
+ $rootView = new View('');
$rootView->mkdir('/' . $user);
$rootView->mkdir('/' . $user . '/files');
// \OC\Files\Filesystem::file_put_contents('/foo', 'foo');
- \OC\Files\Filesystem::mkdir('/bar');
+ Filesystem::mkdir('/bar');
// \OC\Files\Filesystem::file_put_contents('/bar//foo', 'foo');
- $tmpFile = \OC::$server->getTempManager()->getTemporaryFile();
+ $tmpFile = Server::get(ITempManager::class)->getTemporaryFile();
file_put_contents($tmpFile, 'foo');
$fh = fopen($tmpFile, 'r');
// \OC\Files\Filesystem::file_put_contents('/bar//foo', $fh);
@@ -327,29 +327,29 @@ class FilesystemTest extends \Test\TestCase {
*
*/
public function testLocalMountWhenUserDoesNotExist(): void {
- $this->expectException(\OC\User\NoUserException::class);
+ $this->expectException(NoUserException::class);
$userId = $this->getUniqueID('user_');
- \OC\Files\Filesystem::initMountPoints($userId);
+ Filesystem::initMountPoints($userId);
}
public function testNullUserThrows(): void {
- $this->expectException(\OC\User\NoUserException::class);
+ $this->expectException(NoUserException::class);
- \OC\Files\Filesystem::initMountPoints(null);
+ Filesystem::initMountPoints(null);
}
public function testNullUserThrowsTwice(): void {
$thrown = 0;
try {
- \OC\Files\Filesystem::initMountPoints(null);
+ Filesystem::initMountPoints(null);
} catch (NoUserException $e) {
$thrown++;
}
try {
- \OC\Files\Filesystem::initMountPoints(null);
+ Filesystem::initMountPoints(null);
} catch (NoUserException $e) {
$thrown++;
}
@@ -364,13 +364,13 @@ class FilesystemTest extends \Test\TestCase {
$userId = $this->getUniqueID('user_');
try {
- \OC\Files\Filesystem::initMountPoints($userId);
+ Filesystem::initMountPoints($userId);
} catch (NoUserException $e) {
$thrown++;
}
try {
- \OC\Files\Filesystem::initMountPoints($userId);
+ Filesystem::initMountPoints($userId);
} catch (NoUserException $e) {
$thrown++;
}
@@ -384,11 +384,11 @@ class FilesystemTest extends \Test\TestCase {
public function testHomeMount(): void {
$userId = $this->getUniqueID('user_');
- \OC::$server->getUserManager()->createUser($userId, $userId);
+ Server::get(IUserManager::class)->createUser($userId, $userId);
- \OC\Files\Filesystem::initMountPoints($userId);
+ Filesystem::initMountPoints($userId);
- $homeMount = \OC\Files\Filesystem::getStorage('/' . $userId . '/');
+ $homeMount = Filesystem::getStorage('/' . $userId . '/');
$this->assertTrue($homeMount->instanceOfStorage('\OCP\Files\IHomeStorage'));
if ($homeMount->instanceOfStorage('\OC\Files\ObjectStore\HomeObjectStoreStorage')) {
@@ -397,7 +397,7 @@ class FilesystemTest extends \Test\TestCase {
$this->assertEquals('home::' . $userId, $homeMount->getId());
}
- $user = \OC::$server->getUserManager()->get($userId);
+ $user = Server::get(IUserManager::class)->get($userId);
if ($user !== null) {
$user->delete();
}
@@ -405,7 +405,7 @@ class FilesystemTest extends \Test\TestCase {
public function dummyHook($arguments) {
$path = $arguments['path'];
- $this->assertEquals($path, \OC\Files\Filesystem::normalizePath($path)); //the path passed to the hook should already be normalized
+ $this->assertEquals($path, Filesystem::normalizePath($path)); //the path passed to the hook should already be normalized
}
/**
@@ -413,22 +413,22 @@ class FilesystemTest extends \Test\TestCase {
*/
public function testMountDefaultCacheDir(): void {
$userId = $this->getUniqueID('user_');
- $config = \OC::$server->getConfig();
+ $config = Server::get(IConfig::class);
$oldCachePath = $config->getSystemValueString('cache_path', '');
// no cache path configured
$config->setSystemValue('cache_path', '');
- \OC::$server->getUserManager()->createUser($userId, $userId);
- \OC\Files\Filesystem::initMountPoints($userId);
+ Server::get(IUserManager::class)->createUser($userId, $userId);
+ Filesystem::initMountPoints($userId);
$this->assertEquals(
'/' . $userId . '/',
- \OC\Files\Filesystem::getMountPoint('/' . $userId . '/cache')
+ Filesystem::getMountPoint('/' . $userId . '/cache')
);
- [$storage, $internalPath] = \OC\Files\Filesystem::resolvePath('/' . $userId . '/cache');
+ [$storage, $internalPath] = Filesystem::resolvePath('/' . $userId . '/cache');
$this->assertTrue($storage->instanceOfStorage('\OCP\Files\IHomeStorage'));
$this->assertEquals('cache', $internalPath);
- $user = \OC::$server->getUserManager()->get($userId);
+ $user = Server::get(IUserManager::class)->get($userId);
if ($user !== null) {
$user->delete();
}
@@ -443,23 +443,23 @@ class FilesystemTest extends \Test\TestCase {
public function testMountExternalCacheDir(): void {
$userId = $this->getUniqueID('user_');
- $config = \OC::$server->getConfig();
+ $config = Server::get(IConfig::class);
$oldCachePath = $config->getSystemValueString('cache_path', '');
// set cache path to temp dir
- $cachePath = \OC::$server->getTempManager()->getTemporaryFolder() . '/extcache';
+ $cachePath = Server::get(ITempManager::class)->getTemporaryFolder() . '/extcache';
$config->setSystemValue('cache_path', $cachePath);
- \OC::$server->getUserManager()->createUser($userId, $userId);
- \OC\Files\Filesystem::initMountPoints($userId);
+ Server::get(IUserManager::class)->createUser($userId, $userId);
+ Filesystem::initMountPoints($userId);
$this->assertEquals(
'/' . $userId . '/cache/',
- \OC\Files\Filesystem::getMountPoint('/' . $userId . '/cache')
+ Filesystem::getMountPoint('/' . $userId . '/cache')
);
- [$storage, $internalPath] = \OC\Files\Filesystem::resolvePath('/' . $userId . '/cache');
+ [$storage, $internalPath] = Filesystem::resolvePath('/' . $userId . '/cache');
$this->assertTrue($storage->instanceOfStorage('\OC\Files\Storage\Local'));
$this->assertEquals('', $internalPath);
- $user = \OC::$server->getUserManager()->get($userId);
+ $user = Server::get(IUserManager::class)->get($userId);
if ($user !== null) {
$user->delete();
}
@@ -468,11 +468,11 @@ class FilesystemTest extends \Test\TestCase {
}
public function testRegisterMountProviderAfterSetup(): void {
- \OC\Files\Filesystem::initMountPoints(self::TEST_FILESYSTEM_USER2);
- $this->assertEquals('/', \OC\Files\Filesystem::getMountPoint('/foo/bar'));
+ Filesystem::initMountPoints(self::TEST_FILESYSTEM_USER2);
+ $this->assertEquals('/', Filesystem::getMountPoint('/foo/bar'));
$mount = new MountPoint(new Temporary([]), '/foo/bar');
$mountProvider = new DummyMountProvider([self::TEST_FILESYSTEM_USER2 => [$mount]]);
- \OC::$server->getMountProviderCollection()->registerProvider($mountProvider);
- $this->assertEquals('/foo/bar/', \OC\Files\Filesystem::getMountPoint('/foo/bar'));
+ Server::get(IMountProviderCollection::class)->registerProvider($mountProvider);
+ $this->assertEquals('/foo/bar/', Filesystem::getMountPoint('/foo/bar'));
}
}
diff --git a/tests/lib/Files/Mount/ManagerTest.php b/tests/lib/Files/Mount/ManagerTest.php
index 12338c18dbd..e6cf3348664 100644
--- a/tests/lib/Files/Mount/ManagerTest.php
+++ b/tests/lib/Files/Mount/ManagerTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -7,6 +8,7 @@
namespace Test\Files\Mount;
+use OC\Files\Mount\MountPoint;
use OC\Files\SetupManagerFactory;
use OC\Files\Storage\Temporary;
@@ -28,33 +30,33 @@ class ManagerTest extends \Test\TestCase {
}
public function testFind(): void {
- $rootMount = new \OC\Files\Mount\MountPoint(new Temporary([]), '/');
+ $rootMount = new MountPoint(new Temporary([]), '/');
$this->manager->addMount($rootMount);
$this->assertEquals($rootMount, $this->manager->find('/'));
$this->assertEquals($rootMount, $this->manager->find('/foo/bar'));
$storage = new Temporary([]);
- $mount1 = new \OC\Files\Mount\MountPoint($storage, '/foo');
+ $mount1 = new MountPoint($storage, '/foo');
$this->manager->addMount($mount1);
$this->assertEquals($rootMount, $this->manager->find('/'));
$this->assertEquals($mount1, $this->manager->find('/foo/bar'));
$this->assertEquals(1, count($this->manager->findIn('/')));
- $mount2 = new \OC\Files\Mount\MountPoint(new Temporary([]), '/bar');
+ $mount2 = new MountPoint(new Temporary([]), '/bar');
$this->manager->addMount($mount2);
$this->assertEquals(2, count($this->manager->findIn('/')));
$id = $mount1->getStorageId();
$this->assertEquals([$mount1], $this->manager->findByStorageId($id));
- $mount3 = new \OC\Files\Mount\MountPoint($storage, '/foo/bar');
+ $mount3 = new MountPoint($storage, '/foo/bar');
$this->manager->addMount($mount3);
$this->assertEquals([$mount1, $mount3], $this->manager->findByStorageId($id));
}
public function testLong(): void {
$storage = new LongId([]);
- $mount = new \OC\Files\Mount\MountPoint($storage, '/foo');
+ $mount = new MountPoint($storage, '/foo');
$this->manager->addMount($mount);
$id = $mount->getStorageId();
diff --git a/tests/lib/Files/Mount/MountPointTest.php b/tests/lib/Files/Mount/MountPointTest.php
index 96987c9f5eb..bcbcc96e3a3 100644
--- a/tests/lib/Files/Mount/MountPointTest.php
+++ b/tests/lib/Files/Mount/MountPointTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -7,6 +8,7 @@
namespace Test\Files\Mount;
+use OC\Files\Mount\MountPoint;
use OC\Files\Storage\StorageFactory;
use OC\Lockdown\Filesystem\NullStorage;
use OCP\Files\Storage\IStorage;
@@ -23,7 +25,7 @@ class MountPointTest extends \Test\TestCase {
->method('wrap')
->willReturn($storage);
- $mountPoint = new \OC\Files\Mount\MountPoint(
+ $mountPoint = new MountPoint(
// just use this because a real class is needed
NullStorage::class,
'/mountpoint',
@@ -43,14 +45,14 @@ class MountPointTest extends \Test\TestCase {
$loader = $this->createMock(StorageFactory::class);
$loader->expects($this->once())
->method('wrap')
- ->will($this->throwException(new \Exception('Test storage init exception')));
+ ->willThrowException(new \Exception('Test storage init exception'));
$called = false;
- $wrapper = function ($mountPoint, $storage) use ($called) {
+ $wrapper = function ($mountPoint, $storage) use ($called): void {
$called = true;
};
- $mountPoint = new \OC\Files\Mount\MountPoint(
+ $mountPoint = new MountPoint(
// just use this because a real class is needed
NullStorage::class,
'/mountpoint',
diff --git a/tests/lib/Files/Mount/MountTest.php b/tests/lib/Files/Mount/MountTest.php
index 76d70cdd214..05c8a7d58e7 100644
--- a/tests/lib/Files/Mount/MountTest.php
+++ b/tests/lib/Files/Mount/MountTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2020-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -7,6 +8,7 @@
namespace Test\Files\Mount;
+use OC\Files\Mount\MountPoint;
use OC\Files\Storage\StorageFactory;
use OC\Files\Storage\Wrapper\Wrapper;
@@ -15,12 +17,12 @@ class MountTest extends \Test\TestCase {
$storage = $this->getMockBuilder('\OC\Files\Storage\Temporary')
->disableOriginalConstructor()
->getMock();
- $mount = new \OC\Files\Mount\MountPoint($storage, '/foo');
+ $mount = new MountPoint($storage, '/foo');
$this->assertInstanceOf('\OC\Files\Storage\Temporary', $mount->getStorage());
}
public function testFromStorageClassname(): void {
- $mount = new \OC\Files\Mount\MountPoint('\OC\Files\Storage\Temporary', '/foo');
+ $mount = new MountPoint('\OC\Files\Storage\Temporary', '/foo');
$this->assertInstanceOf('\OC\Files\Storage\Temporary', $mount->getStorage());
}
@@ -38,7 +40,7 @@ class MountTest extends \Test\TestCase {
$storage = $this->getMockBuilder('\OC\Files\Storage\Temporary')
->disableOriginalConstructor()
->getMock();
- $mount = new \OC\Files\Mount\MountPoint($storage, '/foo', [], $loader);
+ $mount = new MountPoint($storage, '/foo', [], $loader);
$this->assertInstanceOf('\OC\Files\Storage\Wrapper\Wrapper', $mount->getStorage());
}
}
diff --git a/tests/lib/Files/Mount/ObjectHomeMountProviderTest.php b/tests/lib/Files/Mount/ObjectHomeMountProviderTest.php
index 3daf82461cb..dd696279b86 100644
--- a/tests/lib/Files/Mount/ObjectHomeMountProviderTest.php
+++ b/tests/lib/Files/Mount/ObjectHomeMountProviderTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -7,6 +8,9 @@
namespace Test\Files\Mount;
use OC\Files\Mount\ObjectHomeMountProvider;
+use OC\Files\ObjectStore\PrimaryObjectStoreConfig;
+use OCP\App\IAppManager;
+use OCP\Files\ObjectStore\IObjectStore;
use OCP\Files\Storage\IStorageFactory;
use OCP\IConfig;
use OCP\IUser;
@@ -31,51 +35,54 @@ class ObjectHomeMountProviderTest extends \Test\TestCase {
$this->user = $this->createMock(IUser::class);
$this->loader = $this->createMock(IStorageFactory::class);
- $this->provider = new ObjectHomeMountProvider($this->config);
+ $objectStoreConfig = new PrimaryObjectStoreConfig($this->config, $this->createMock(IAppManager::class));
+ $this->provider = new ObjectHomeMountProvider($objectStoreConfig);
}
public function testSingleBucket(): void {
- $this->config->expects($this->once())
- ->method('getSystemValue')
- ->with($this->equalTo('objectstore'), '')
- ->willReturn([
- 'class' => 'Test\Files\Mount\FakeObjectStore',
- ]);
+ $this->config->method('getSystemValue')
+ ->willReturnCallback(function ($key, $default) {
+ if ($key === 'objectstore') {
+ return [
+ 'class' => 'Test\Files\Mount\FakeObjectStore',
+ 'arguments' => [
+ 'foo' => 'bar'
+ ],
+ ];
+ } else {
+ return $default;
+ }
+ });
- $this->user->expects($this->never())->method($this->anything());
- $this->loader->expects($this->never())->method($this->anything());
-
- $config = $this->invokePrivate($this->provider, 'getSingleBucketObjectStoreConfig', [$this->user, $this->loader]);
+ $mount = $this->provider->getHomeMountForUser($this->user, $this->loader);
+ $arguments = $this->invokePrivate($mount, 'arguments');
- $this->assertArrayHasKey('class', $config);
- $this->assertEquals($config['class'], 'Test\Files\Mount\FakeObjectStore');
- $this->assertArrayHasKey('arguments', $config);
- $this->assertArrayHasKey('user', $config['arguments']);
- $this->assertSame($this->user, $config['arguments']['user']);
- $this->assertArrayHasKey('objectstore', $config['arguments']);
- $this->assertInstanceOf('Test\Files\Mount\FakeObjectStore', $config['arguments']['objectstore']);
+ $objectStore = $arguments['objectstore'];
+ $this->assertInstanceOf(FakeObjectStore::class, $objectStore);
+ $this->assertEquals(['foo' => 'bar', 'multibucket' => false], $objectStore->getArguments());
}
public function testMultiBucket(): void {
- $this->config->expects($this->exactly(2))
- ->method('getSystemValue')
- ->with($this->equalTo('objectstore_multibucket'), '')
- ->willReturn([
- 'class' => 'Test\Files\Mount\FakeObjectStore',
- ]);
+ $this->config->method('getSystemValue')
+ ->willReturnCallback(function ($key, $default) {
+ if ($key === 'objectstore_multibucket') {
+ return [
+ 'class' => 'Test\Files\Mount\FakeObjectStore',
+ 'arguments' => [
+ 'foo' => 'bar'
+ ],
+ ];
+ } else {
+ return $default;
+ }
+ });
$this->user->method('getUID')
->willReturn('uid');
$this->loader->expects($this->never())->method($this->anything());
- $this->config->expects($this->once())
- ->method('getUserValue')
- ->with(
- $this->equalTo('uid'),
- $this->equalTo('homeobjectstore'),
- $this->equalTo('bucket'),
- $this->equalTo(null)
- )->willReturn(null);
+ $this->config->method('getUserValue')
+ ->willReturn(null);
$this->config->expects($this->once())
->method('setUserValue')
@@ -87,42 +94,37 @@ class ObjectHomeMountProviderTest extends \Test\TestCase {
$this->equalTo(null)
);
- $config = $this->invokePrivate($this->provider, 'getMultiBucketObjectStoreConfig', [$this->user, $this->loader]);
+ $mount = $this->provider->getHomeMountForUser($this->user, $this->loader);
+ $arguments = $this->invokePrivate($mount, 'arguments');
- $this->assertArrayHasKey('class', $config);
- $this->assertEquals($config['class'], 'Test\Files\Mount\FakeObjectStore');
- $this->assertArrayHasKey('arguments', $config);
- $this->assertArrayHasKey('user', $config['arguments']);
- $this->assertSame($this->user, $config['arguments']['user']);
- $this->assertArrayHasKey('objectstore', $config['arguments']);
- $this->assertInstanceOf('Test\Files\Mount\FakeObjectStore', $config['arguments']['objectstore']);
- $this->assertArrayHasKey('bucket', $config['arguments']);
- $this->assertEquals('49', $config['arguments']['bucket']);
+ $objectStore = $arguments['objectstore'];
+ $this->assertInstanceOf(FakeObjectStore::class, $objectStore);
+ $this->assertEquals(['foo' => 'bar', 'bucket' => 49, 'multibucket' => true], $objectStore->getArguments());
}
public function testMultiBucketWithPrefix(): void {
- $this->config->expects($this->exactly(2))
- ->method('getSystemValue')
- ->with('objectstore_multibucket')
- ->willReturn([
- 'class' => 'Test\Files\Mount\FakeObjectStore',
- 'arguments' => [
- 'bucket' => 'myBucketPrefix',
- ],
- ]);
+ $this->config->method('getSystemValue')
+ ->willReturnCallback(function ($key, $default) {
+ if ($key === 'objectstore_multibucket') {
+ return [
+ 'class' => 'Test\Files\Mount\FakeObjectStore',
+ 'arguments' => [
+ 'foo' => 'bar',
+ 'bucket' => 'myBucketPrefix',
+ ],
+ ];
+ } else {
+ return $default;
+ }
+ });
$this->user->method('getUID')
->willReturn('uid');
$this->loader->expects($this->never())->method($this->anything());
- $this->config->expects($this->once())
+ $this->config
->method('getUserValue')
- ->with(
- $this->equalTo('uid'),
- $this->equalTo('homeobjectstore'),
- $this->equalTo('bucket'),
- $this->equalTo(null)
- )->willReturn(null);
+ ->willReturn(null);
$this->config->expects($this->once())
->method('setUserValue')
@@ -134,66 +136,70 @@ class ObjectHomeMountProviderTest extends \Test\TestCase {
$this->equalTo(null)
);
- $config = $this->invokePrivate($this->provider, 'getMultiBucketObjectStoreConfig', [$this->user, $this->loader]);
+ $mount = $this->provider->getHomeMountForUser($this->user, $this->loader);
+ $arguments = $this->invokePrivate($mount, 'arguments');
- $this->assertArrayHasKey('class', $config);
- $this->assertEquals($config['class'], 'Test\Files\Mount\FakeObjectStore');
- $this->assertArrayHasKey('arguments', $config);
- $this->assertArrayHasKey('user', $config['arguments']);
- $this->assertSame($this->user, $config['arguments']['user']);
- $this->assertArrayHasKey('objectstore', $config['arguments']);
- $this->assertInstanceOf('Test\Files\Mount\FakeObjectStore', $config['arguments']['objectstore']);
- $this->assertArrayHasKey('bucket', $config['arguments']);
- $this->assertEquals('myBucketPrefix49', $config['arguments']['bucket']);
+ $objectStore = $arguments['objectstore'];
+ $this->assertInstanceOf(FakeObjectStore::class, $objectStore);
+ $this->assertEquals(['foo' => 'bar', 'bucket' => 'myBucketPrefix49', 'multibucket' => true], $objectStore->getArguments());
}
public function testMultiBucketBucketAlreadySet(): void {
- $this->config->expects($this->once())
- ->method('getSystemValue')
- ->with('objectstore_multibucket')
- ->willReturn([
- 'class' => 'Test\Files\Mount\FakeObjectStore',
- 'arguments' => [
- 'bucket' => 'myBucketPrefix',
- ],
- ]);
+ $this->config->method('getSystemValue')
+ ->willReturnCallback(function ($key, $default) {
+ if ($key === 'objectstore_multibucket') {
+ return [
+ 'class' => 'Test\Files\Mount\FakeObjectStore',
+ 'arguments' => [
+ 'foo' => 'bar',
+ 'bucket' => 'myBucketPrefix',
+ ],
+ ];
+ } else {
+ return $default;
+ }
+ });
$this->user->method('getUID')
->willReturn('uid');
$this->loader->expects($this->never())->method($this->anything());
- $this->config->expects($this->once())
+ $this->config
->method('getUserValue')
- ->with(
- $this->equalTo('uid'),
- $this->equalTo('homeobjectstore'),
- $this->equalTo('bucket'),
- $this->equalTo(null)
- )->willReturn('awesomeBucket1');
+ ->willReturnCallback(function ($uid, $app, $key, $default) {
+ if ($uid === 'uid' && $app === 'homeobjectstore' && $key === 'bucket') {
+ return 'awesomeBucket1';
+ } else {
+ return $default;
+ }
+ });
$this->config->expects($this->never())
->method('setUserValue');
- $config = $this->invokePrivate($this->provider, 'getMultiBucketObjectStoreConfig', [$this->user, $this->loader]);
+ $mount = $this->provider->getHomeMountForUser($this->user, $this->loader);
+ $arguments = $this->invokePrivate($mount, 'arguments');
- $this->assertArrayHasKey('class', $config);
- $this->assertEquals($config['class'], 'Test\Files\Mount\FakeObjectStore');
- $this->assertArrayHasKey('arguments', $config);
- $this->assertArrayHasKey('user', $config['arguments']);
- $this->assertSame($this->user, $config['arguments']['user']);
- $this->assertArrayHasKey('objectstore', $config['arguments']);
- $this->assertInstanceOf('Test\Files\Mount\FakeObjectStore', $config['arguments']['objectstore']);
- $this->assertArrayHasKey('bucket', $config['arguments']);
- $this->assertEquals('awesomeBucket1', $config['arguments']['bucket']);
+ $objectStore = $arguments['objectstore'];
+ $this->assertInstanceOf(FakeObjectStore::class, $objectStore);
+ $this->assertEquals(['foo' => 'bar', 'bucket' => 'awesomeBucket1', 'multibucket' => true], $objectStore->getArguments());
}
public function testMultiBucketConfigFirst(): void {
- $this->config->expects($this->exactly(2))
- ->method('getSystemValue')
- ->with('objectstore_multibucket')
- ->willReturn([
- 'class' => 'Test\Files\Mount\FakeObjectStore',
- ]);
+ $this->config->method('getSystemValue')
+ ->willReturnCallback(function ($key, $default) {
+ if ($key === 'objectstore_multibucket') {
+ return [
+ 'class' => 'Test\Files\Mount\FakeObjectStore',
+ 'arguments' => [
+ 'foo' => 'bar',
+ 'bucket' => 'myBucketPrefix',
+ ],
+ ];
+ } else {
+ return $default;
+ }
+ });
$this->user->method('getUID')
->willReturn('uid');
@@ -204,11 +210,15 @@ class ObjectHomeMountProviderTest extends \Test\TestCase {
}
public function testMultiBucketConfigFirstFallBackSingle(): void {
- $this->config->expects($this->exactly(2))
+ $this->config
->method('getSystemValue')->willReturnMap([
- ['objectstore_multibucket', '', ''],
- ['objectstore', '', [
+ ['objectstore_multibucket', null, null],
+ ['objectstore', null, [
'class' => 'Test\Files\Mount\FakeObjectStore',
+ 'arguments' => [
+ 'foo' => 'bar',
+ 'bucket' => 'myBucketPrefix',
+ ],
]],
]);
@@ -221,23 +231,41 @@ class ObjectHomeMountProviderTest extends \Test\TestCase {
}
public function testNoObjectStore(): void {
- $this->config->expects($this->exactly(2))
- ->method('getSystemValue')
- ->willReturn('');
+ $this->config->method('getSystemValue')
+ ->willReturnCallback(function ($key, $default) {
+ return $default;
+ });
$mount = $this->provider->getHomeMountForUser($this->user, $this->loader);
$this->assertNull($mount);
}
}
-class FakeObjectStore {
- private $arguments;
-
- public function __construct(array $arguments) {
- $this->arguments = $arguments;
+class FakeObjectStore implements IObjectStore {
+ public function __construct(
+ private array $arguments,
+ ) {
}
public function getArguments() {
return $this->arguments;
}
+
+ public function getStorageId() {
+ }
+
+ public function readObject($urn) {
+ }
+
+ public function writeObject($urn, $stream, ?string $mimetype = null) {
+ }
+
+ public function deleteObject($urn) {
+ }
+
+ public function objectExists($urn) {
+ }
+
+ public function copyObject($from, $to) {
+ }
}
diff --git a/tests/lib/Files/Mount/RootMountProviderTest.php b/tests/lib/Files/Mount/RootMountProviderTest.php
index 2613cfd4b7b..bf29bfa070a 100644
--- a/tests/lib/Files/Mount/RootMountProviderTest.php
+++ b/tests/lib/Files/Mount/RootMountProviderTest.php
@@ -10,11 +10,12 @@ namespace Test\Files\Mount;
use OC\Files\Mount\RootMountProvider;
use OC\Files\ObjectStore\ObjectStoreStorage;
+use OC\Files\ObjectStore\PrimaryObjectStoreConfig;
use OC\Files\ObjectStore\S3;
use OC\Files\Storage\LocalRootStorage;
use OC\Files\Storage\StorageFactory;
+use OCP\App\IAppManager;
use OCP\IConfig;
-use Psr\Log\LoggerInterface;
use Test\TestCase;
/**
@@ -40,8 +41,8 @@ class RootMountProviderTest extends TestCase {
private function getProvider(array $systemConfig): RootMountProvider {
$config = $this->getConfig($systemConfig);
- $provider = new RootMountProvider($config, $this->createMock(LoggerInterface::class));
- return $provider;
+ $objectStoreConfig = new PrimaryObjectStoreConfig($config, $this->createMock(IAppManager::class));
+ return new RootMountProvider($objectStoreConfig, $config);
}
public function testLocal(): void {
diff --git a/tests/lib/Files/Node/FileTest.php b/tests/lib/Files/Node/FileTest.php
index a67c9433663..eec34d156ad 100644
--- a/tests/lib/Files/Node/FileTest.php
+++ b/tests/lib/Files/Node/FileTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -7,6 +8,11 @@
namespace Test\Files\Node;
+use OC\Files\Node\File;
+use OC\Files\Node\Root;
+use OCP\Constants;
+use OCP\Files\NotPermittedException;
+
/**
* Class FileTest
*
@@ -14,12 +20,12 @@ namespace Test\Files\Node;
*
* @package Test\Files\Node
*/
-class FileTest extends NodeTest {
+class FileTest extends NodeTestCase {
protected function createTestNode($root, $view, $path, array $data = [], $internalPath = '', $storage = null) {
if ($data || $internalPath || $storage) {
- return new \OC\Files\Node\File($root, $view, $path, $this->getFileInfo($data, $internalPath, $storage));
+ return new File($root, $view, $path, $this->getFileInfo($data, $internalPath, $storage));
} else {
- return new \OC\Files\Node\File($root, $view, $path);
+ return new File($root, $view, $path);
}
}
@@ -37,11 +43,11 @@ class FileTest extends NodeTest {
public function testGetContent(): void {
/** @var \OC\Files\Node\Root|\PHPUnit\Framework\MockObject\MockObject $root */
- $root = $this->getMockBuilder('\OC\Files\Node\Root')
+ $root = $this->getMockBuilder(Root::class)
->setConstructorArgs([$this->manager, $this->view, $this->user, $this->userMountCache, $this->logger, $this->userManager, $this->eventDispatcher, $this->cacheFactory])
->getMock();
- $hook = function ($file) {
+ $hook = function ($file): void {
throw new \Exception('Hooks are not supposed to be called');
};
@@ -56,18 +62,18 @@ class FileTest extends NodeTest {
$this->view->expects($this->once())
->method('getFileInfo')
->with('/bar/foo')
- ->willReturn($this->getFileInfo(['permissions' => \OCP\Constants::PERMISSION_READ]));
+ ->willReturn($this->getFileInfo(['permissions' => Constants::PERMISSION_READ]));
- $node = new \OC\Files\Node\File($root, $this->view, '/bar/foo');
+ $node = new File($root, $this->view, '/bar/foo');
$this->assertEquals('bar', $node->getContent());
}
public function testGetContentNotPermitted(): void {
- $this->expectException(\OCP\Files\NotPermittedException::class);
+ $this->expectException(NotPermittedException::class);
/** @var \OC\Files\Node\Root|\PHPUnit\Framework\MockObject\MockObject $root */
- $root = $this->getMockBuilder('\OC\Files\Node\Root')
+ $root = $this->getMockBuilder(Root::class)
->setConstructorArgs([$this->manager, $this->view, $this->user, $this->userMountCache, $this->logger, $this->userManager, $this->eventDispatcher, $this->cacheFactory])
->getMock();
@@ -80,13 +86,13 @@ class FileTest extends NodeTest {
->with('/bar/foo')
->willReturn($this->getFileInfo(['permissions' => 0]));
- $node = new \OC\Files\Node\File($root, $this->view, '/bar/foo');
+ $node = new File($root, $this->view, '/bar/foo');
$node->getContent();
}
public function testPutContent(): void {
/** @var \OC\Files\Node\Root|\PHPUnit\Framework\MockObject\MockObject $root */
- $root = $this->getMockBuilder('\OC\Files\Node\Root')
+ $root = $this->getMockBuilder(Root::class)
->setConstructorArgs([$this->manager, $this->view, $this->user, $this->userMountCache, $this->logger, $this->userManager, $this->eventDispatcher, $this->cacheFactory])
->getMock();
@@ -97,38 +103,38 @@ class FileTest extends NodeTest {
$this->view->expects($this->once())
->method('getFileInfo')
->with('/bar/foo')
- ->willReturn($this->getFileInfo(['permissions' => \OCP\Constants::PERMISSION_ALL]));
+ ->willReturn($this->getFileInfo(['permissions' => Constants::PERMISSION_ALL]));
$this->view->expects($this->once())
->method('file_put_contents')
->with('/bar/foo', 'bar')
->willReturn(true);
- $node = new \OC\Files\Node\File($root, $this->view, '/bar/foo');
+ $node = new File($root, $this->view, '/bar/foo');
$node->putContent('bar');
}
public function testPutContentNotPermitted(): void {
- $this->expectException(\OCP\Files\NotPermittedException::class);
+ $this->expectException(NotPermittedException::class);
/** @var \OC\Files\Node\Root|\PHPUnit\Framework\MockObject\MockObject $root */
- $root = $this->getMockBuilder('\OC\Files\Node\Root')
+ $root = $this->getMockBuilder(Root::class)
->setConstructorArgs([$this->manager, $this->view, $this->user, $this->userMountCache, $this->logger, $this->userManager, $this->eventDispatcher, $this->cacheFactory])
->getMock();
$this->view->expects($this->once())
->method('getFileInfo')
->with('/bar/foo')
- ->willReturn($this->getFileInfo(['permissions' => \OCP\Constants::PERMISSION_READ]));
+ ->willReturn($this->getFileInfo(['permissions' => Constants::PERMISSION_READ]));
- $node = new \OC\Files\Node\File($root, $this->view, '/bar/foo');
+ $node = new File($root, $this->view, '/bar/foo');
$node->putContent('bar');
}
public function testGetMimeType(): void {
/** @var \OC\Files\Node\Root|\PHPUnit\Framework\MockObject\MockObject $root */
- $root = $this->getMockBuilder('\OC\Files\Node\Root')
+ $root = $this->getMockBuilder(Root::class)
->setConstructorArgs([$this->manager, $this->view, $this->user, $this->userMountCache, $this->logger, $this->userManager, $this->eventDispatcher, $this->cacheFactory])
->getMock();
@@ -137,7 +143,7 @@ class FileTest extends NodeTest {
->with('/bar/foo')
->willReturn($this->getFileInfo(['mimetype' => 'text/plain']));
- $node = new \OC\Files\Node\File($root, $this->view, '/bar/foo');
+ $node = new File($root, $this->view, '/bar/foo');
$this->assertEquals('text/plain', $node->getMimeType());
}
@@ -146,7 +152,7 @@ class FileTest extends NodeTest {
fwrite($stream, 'bar');
rewind($stream);
- $root = new \OC\Files\Node\Root(
+ $root = new Root(
$this->manager,
$this->view,
$this->user,
@@ -157,7 +163,7 @@ class FileTest extends NodeTest {
$this->cacheFactory,
);
- $hook = function ($file) {
+ $hook = function ($file): void {
throw new \Exception('Hooks are not supposed to be called');
};
@@ -172,9 +178,9 @@ class FileTest extends NodeTest {
$this->view->expects($this->once())
->method('getFileInfo')
->with('/bar/foo')
- ->willReturn($this->getFileInfo(['permissions' => \OCP\Constants::PERMISSION_ALL]));
+ ->willReturn($this->getFileInfo(['permissions' => Constants::PERMISSION_ALL]));
- $node = new \OC\Files\Node\File($root, $this->view, '/bar/foo');
+ $node = new File($root, $this->view, '/bar/foo');
$fh = $node->fopen('r');
$this->assertEquals($stream, $fh);
$this->assertEquals('bar', fread($fh, 3));
@@ -183,7 +189,7 @@ class FileTest extends NodeTest {
public function testFOpenWrite(): void {
$stream = fopen('php://memory', 'w+');
- $root = new \OC\Files\Node\Root(
+ $root = new Root(
$this->manager,
$this->view,
$this->user,
@@ -194,7 +200,7 @@ class FileTest extends NodeTest {
$this->cacheFactory,
);
$hooksCalled = 0;
- $hook = function ($file) use (&$hooksCalled) {
+ $hook = function ($file) use (&$hooksCalled): void {
$hooksCalled++;
};
@@ -209,9 +215,9 @@ class FileTest extends NodeTest {
$this->view->expects($this->once())
->method('getFileInfo')
->with('/bar/foo')
- ->willReturn($this->getFileInfo(['permissions' => \OCP\Constants::PERMISSION_ALL]));
+ ->willReturn($this->getFileInfo(['permissions' => Constants::PERMISSION_ALL]));
- $node = new \OC\Files\Node\File($root, $this->view, '/bar/foo');
+ $node = new File($root, $this->view, '/bar/foo');
$fh = $node->fopen('w');
$this->assertEquals($stream, $fh);
fwrite($fh, 'bar');
@@ -222,9 +228,9 @@ class FileTest extends NodeTest {
public function testFOpenReadNotPermitted(): void {
- $this->expectException(\OCP\Files\NotPermittedException::class);
+ $this->expectException(NotPermittedException::class);
- $root = new \OC\Files\Node\Root(
+ $root = new Root(
$this->manager,
$this->view,
$this->user,
@@ -234,7 +240,7 @@ class FileTest extends NodeTest {
$this->eventDispatcher,
$this->cacheFactory,
);
- $hook = function ($file) {
+ $hook = function ($file): void {
throw new \Exception('Hooks are not supposed to be called');
};
@@ -243,15 +249,15 @@ class FileTest extends NodeTest {
->with('/bar/foo')
->willReturn($this->getFileInfo(['permissions' => 0]));
- $node = new \OC\Files\Node\File($root, $this->view, '/bar/foo');
+ $node = new File($root, $this->view, '/bar/foo');
$node->fopen('r');
}
public function testFOpenReadWriteNoReadPermissions(): void {
- $this->expectException(\OCP\Files\NotPermittedException::class);
+ $this->expectException(NotPermittedException::class);
- $root = new \OC\Files\Node\Root(
+ $root = new Root(
$this->manager,
$this->view,
$this->user,
@@ -261,24 +267,24 @@ class FileTest extends NodeTest {
$this->eventDispatcher,
$this->cacheFactory,
);
- $hook = function () {
+ $hook = function (): void {
throw new \Exception('Hooks are not supposed to be called');
};
$this->view->expects($this->once())
->method('getFileInfo')
->with('/bar/foo')
- ->willReturn($this->getFileInfo(['permissions' => \OCP\Constants::PERMISSION_UPDATE]));
+ ->willReturn($this->getFileInfo(['permissions' => Constants::PERMISSION_UPDATE]));
- $node = new \OC\Files\Node\File($root, $this->view, '/bar/foo');
+ $node = new File($root, $this->view, '/bar/foo');
$node->fopen('w');
}
public function testFOpenReadWriteNoWritePermissions(): void {
- $this->expectException(\OCP\Files\NotPermittedException::class);
+ $this->expectException(NotPermittedException::class);
- $root = new \OC\Files\Node\Root(
+ $root = new Root(
$this->manager,
$this->view,
$this->user,
@@ -288,16 +294,16 @@ class FileTest extends NodeTest {
$this->eventDispatcher,
$this->cacheFactory,
);
- $hook = function () {
+ $hook = function (): void {
throw new \Exception('Hooks are not supposed to be called');
};
$this->view->expects($this->once())
->method('getFileInfo')
->with('/bar/foo')
- ->willReturn($this->getFileInfo(['permissions' => \OCP\Constants::PERMISSION_READ]));
+ ->willReturn($this->getFileInfo(['permissions' => Constants::PERMISSION_READ]));
- $node = new \OC\Files\Node\File($root, $this->view, '/bar/foo');
+ $node = new File($root, $this->view, '/bar/foo');
$node->fopen('w');
}
}
diff --git a/tests/lib/Files/Node/FolderTest.php b/tests/lib/Files/Node/FolderTest.php
index e3edf202f8e..439535cf2c1 100644
--- a/tests/lib/Files/Node/FolderTest.php
+++ b/tests/lib/Files/Node/FolderTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -21,12 +22,17 @@ use OC\Files\Search\SearchBinaryOperator;
use OC\Files\Search\SearchComparison;
use OC\Files\Search\SearchOrder;
use OC\Files\Search\SearchQuery;
+use OC\Files\Storage\Storage;
use OC\Files\Storage\Temporary;
use OC\Files\Storage\Wrapper\Jail;
+use OC\Files\View;
+use OCP\Constants;
use OCP\Files\Cache\ICacheEntry;
+use OCP\Files\InvalidPathException;
use OCP\Files\IRootFolder;
use OCP\Files\Mount\IMountPoint;
use OCP\Files\NotFoundException;
+use OCP\Files\NotPermittedException;
use OCP\Files\Search\ISearchBinaryOperator;
use OCP\Files\Search\ISearchComparison;
use OCP\Files\Search\ISearchOrder;
@@ -40,7 +46,7 @@ use PHPUnit\Framework\MockObject\MockObject;
*
* @package Test\Files\Node
*/
-class FolderTest extends NodeTest {
+class FolderTest extends NodeTestCase {
protected function createTestNode($root, $view, $path, array $data = [], $internalPath = '', $storage = null) {
$view->expects($this->any())
->method('getRoot')
@@ -67,7 +73,7 @@ class FolderTest extends NodeTest {
public function testGetDirectoryContent(): void {
$manager = $this->createMock(Manager::class);
/**
- * @var \OC\Files\View | \PHPUnit\Framework\MockObject\MockObject $view
+ * @var View|\PHPUnit\Framework\MockObject\MockObject $view
*/
$root = $this->getMockBuilder(Root::class)
->setConstructorArgs([$manager, $this->view, $this->user, $this->userMountCache, $this->logger, $this->userManager, $this->eventDispatcher, $this->cacheFactory])
@@ -150,7 +156,7 @@ class FolderTest extends NodeTest {
$root->method('get')
->with('/bar/foo/asd')
- ->will($this->throwException(new NotFoundException()));
+ ->willThrowException(new NotFoundException());
$node = new Folder($root, $view, '/bar/foo');
$this->assertFalse($node->nodeExists('asd'));
@@ -168,7 +174,7 @@ class FolderTest extends NodeTest {
$view->method('getFileInfo')
->with('/bar/foo')
- ->willReturn($this->getFileInfo(['permissions' => \OCP\Constants::PERMISSION_ALL]));
+ ->willReturn($this->getFileInfo(['permissions' => Constants::PERMISSION_ALL]));
$view->method('mkdir')
->with('/bar/foo/asd')
@@ -192,7 +198,7 @@ class FolderTest extends NodeTest {
$view->method('getFileInfo')
->with('/foobar')
- ->willReturn($this->getFileInfo(['permissions' => \OCP\Constants::PERMISSION_ALL]));
+ ->willReturn($this->getFileInfo(['permissions' => Constants::PERMISSION_ALL]));
$view->method('mkdir')
->with('/foobar/asd/sdf')
@@ -206,7 +212,7 @@ class FolderTest extends NodeTest {
public function testNewFolderNotPermitted(): void {
- $this->expectException(\OCP\Files\NotPermittedException::class);
+ $this->expectException(NotPermittedException::class);
$manager = $this->createMock(Manager::class);
$view = $this->getRootViewMock();
@@ -218,7 +224,7 @@ class FolderTest extends NodeTest {
$view->method('getFileInfo')
->with('/bar/foo')
- ->willReturn($this->getFileInfo(['permissions' => \OCP\Constants::PERMISSION_READ]));
+ ->willReturn($this->getFileInfo(['permissions' => Constants::PERMISSION_READ]));
$node = new Folder($root, $view, '/bar/foo');
$node->newFolder('asd');
@@ -236,21 +242,21 @@ class FolderTest extends NodeTest {
$view->method('getFileInfo')
->with('/bar/foo')
- ->willReturn($this->getFileInfo(['permissions' => \OCP\Constants::PERMISSION_ALL]));
+ ->willReturn($this->getFileInfo(['permissions' => Constants::PERMISSION_ALL]));
$view->method('touch')
->with('/bar/foo/asd')
->willReturn(true);
$node = new Folder($root, $view, '/bar/foo');
- $child = new \OC\Files\Node\File($root, $view, '/bar/foo/asd', null, $node);
+ $child = new File($root, $view, '/bar/foo/asd', null, $node);
$result = $node->newFile('asd');
$this->assertEquals($child, $result);
}
public function testNewFileNotPermitted(): void {
- $this->expectException(\OCP\Files\NotPermittedException::class);
+ $this->expectException(NotPermittedException::class);
$manager = $this->createMock(Manager::class);
$view = $this->getRootViewMock();
@@ -262,7 +268,7 @@ class FolderTest extends NodeTest {
$view->method('getFileInfo')
->with('/bar/foo')
- ->willReturn($this->getFileInfo(['permissions' => \OCP\Constants::PERMISSION_READ]));
+ ->willReturn($this->getFileInfo(['permissions' => Constants::PERMISSION_READ]));
$node = new Folder($root, $view, '/bar/foo');
$node->newFile('asd');
@@ -337,7 +343,7 @@ class FolderTest extends NodeTest {
$manager = $this->createMock(Manager::class);
$view = $this->getRootViewMock();
$root = $this->getMockBuilder(Root::class)
- ->setMethods(['getUser', 'getMountsIn', 'getMount'])
+ ->onlyMethods(['getUser', 'getMountsIn', 'getMount'])
->setConstructorArgs([$manager, $view, $this->user, $this->userMountCache, $this->logger, $this->userManager, $this->eventDispatcher, $this->cacheFactory])
->getMock();
$root->expects($this->any())
@@ -499,10 +505,10 @@ class FolderTest extends NodeTest {
$manager = $this->createMock(Manager::class);
$view = $this->getRootViewMock();
$root = $this->getMockBuilder(Root::class)
- ->setMethods(['getMountsIn', 'getMount'])
+ ->onlyMethods(['getMountsIn', 'getMount'])
->setConstructorArgs([$manager, $view, $this->user, $this->userMountCache, $this->logger, $this->userManager, $this->eventDispatcher, $this->cacheFactory])
->getMock();
- $storage = $this->createMock(\OC\Files\Storage\Storage::class);
+ $storage = $this->createMock(Storage::class);
$mount = new MountPoint($storage, '/bar');
$storage->method('getId')->willReturn('');
$cache = $this->getMockBuilder(Cache::class)->setConstructorArgs([$storage])->getMock();
@@ -548,10 +554,10 @@ class FolderTest extends NodeTest {
$manager = $this->createMock(Manager::class);
$view = $this->getRootViewMock();
$root = $this->getMockBuilder(Root::class)
- ->setMethods(['getMountsIn', 'getMount'])
+ ->onlyMethods(['getMountsIn', 'getMount'])
->setConstructorArgs([$manager, $view, $this->user, $this->userMountCache, $this->logger, $this->userManager, $this->eventDispatcher, $this->cacheFactory])
->getMock();
- $storage = $this->createMock(\OC\Files\Storage\Storage::class);
+ $storage = $this->createMock(Storage::class);
$mount = new MountPoint($storage, '/bar');
$storage->method('getId')->willReturn('');
$cache = $this->getMockBuilder(Cache::class)->setConstructorArgs([$storage])->getMock();
@@ -593,10 +599,10 @@ class FolderTest extends NodeTest {
$manager = $this->createMock(Manager::class);
$view = $this->getRootViewMock();
$root = $this->getMockBuilder(Root::class)
- ->setMethods(['getMountsIn', 'getMount'])
+ ->onlyMethods(['getMountsIn', 'getMount'])
->setConstructorArgs([$manager, $view, $this->user, $this->userMountCache, $this->logger, $this->userManager, $this->eventDispatcher, $this->cacheFactory])
->getMock();
- $storage = $this->createMock(\OC\Files\Storage\Storage::class);
+ $storage = $this->createMock(Storage::class);
$mount = new MountPoint($storage, '/bar');
$storage->method('getId')->willReturn('');
$cache = $this->getMockBuilder(Cache::class)->setConstructorArgs([$storage])->getMock();
@@ -637,10 +643,10 @@ class FolderTest extends NodeTest {
$manager = $this->createMock(Manager::class);
$view = $this->getRootViewMock();
$root = $this->getMockBuilder(Root::class)
- ->setMethods(['getMountsIn', 'getMount'])
+ ->onlyMethods(['getMountsIn', 'getMount'])
->setConstructorArgs([$manager, $view, $this->user, $this->userMountCache, $this->logger, $this->userManager, $this->eventDispatcher, $this->cacheFactory])
->getMock();
- $storage = $this->createMock(\OC\Files\Storage\Storage::class);
+ $storage = $this->createMock(Storage::class);
$mount1 = new MountPoint($storage, '/bar');
$mount2 = new MountPoint($storage, '/bar/foo/asd');
$storage->method('getId')->willReturn('');
@@ -681,7 +687,7 @@ class FolderTest extends NodeTest {
$this->assertEquals('/bar/foo/asd/foo/qwerty', $result[1]->getPath());
}
- public function uniqueNameProvider() {
+ public static function uniqueNameProvider(): array {
return [
// input, existing, expected
['foo', [], 'foo'],
@@ -690,15 +696,13 @@ class FolderTest extends NodeTest {
];
}
- /**
- * @dataProvider uniqueNameProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('uniqueNameProvider')]
public function testGetUniqueName($name, $existingFiles, $expected): void {
$manager = $this->createMock(Manager::class);
$folderPath = '/bar/foo';
$view = $this->getRootViewMock();
$root = $this->getMockBuilder(Root::class)
- ->setMethods(['getUser', 'getMountsIn', 'getMount'])
+ ->onlyMethods(['getUser', 'getMountsIn', 'getMount'])
->setConstructorArgs([$manager, $view, $this->user, $this->userMountCache, $this->logger, $this->userManager, $this->eventDispatcher, $this->cacheFactory])
->getMock();
@@ -723,10 +727,10 @@ class FolderTest extends NodeTest {
$view = $this->getRootViewMock();
/** @var \PHPUnit\Framework\MockObject\MockObject|\OC\Files\Node\Root $root */
$root = $this->getMockBuilder(Root::class)
- ->setMethods(['getUser', 'getMountsIn', 'getMount'])
+ ->onlyMethods(['getUser', 'getMountsIn', 'getMount'])
->setConstructorArgs([$manager, $view, $this->user, $this->userMountCache, $this->logger, $this->userManager, $this->eventDispatcher, $this->cacheFactory])
->getMock();
- /** @var \PHPUnit\Framework\MockObject\MockObject|\OC\Files\FileInfo $folderInfo */
+ /** @var \PHPUnit\Framework\MockObject\MockObject|FileInfo $folderInfo */
$folderInfo = $this->getMockBuilder(FileInfo::class)
->disableOriginalConstructor()->getMock();
@@ -753,14 +757,14 @@ class FolderTest extends NodeTest {
'mtime' => $baseTime,
'mimetype' => 'text/plain',
'size' => 3,
- 'permissions' => \OCP\Constants::PERMISSION_ALL,
+ 'permissions' => Constants::PERMISSION_ALL,
]);
$id2 = $cache->put('bar/foo/old.txt', [
'storage_mtime' => $baseTime - 100,
'mtime' => $baseTime - 100,
'mimetype' => 'text/plain',
'size' => 3,
- 'permissions' => \OCP\Constants::PERMISSION_READ,
+ 'permissions' => Constants::PERMISSION_READ,
]);
$cache->put('bar/asd/outside.txt', [
'storage_mtime' => $baseTime,
@@ -773,7 +777,7 @@ class FolderTest extends NodeTest {
'mtime' => $baseTime - 600,
'mimetype' => 'text/plain',
'size' => 3,
- 'permissions' => \OCP\Constants::PERMISSION_ALL,
+ 'permissions' => Constants::PERMISSION_ALL,
]);
$node = new Folder($root, $view, $folderPath, $folderInfo);
@@ -792,10 +796,10 @@ class FolderTest extends NodeTest {
$view = $this->getRootViewMock();
/** @var \PHPUnit\Framework\MockObject\MockObject|\OC\Files\Node\Root $root */
$root = $this->getMockBuilder(Root::class)
- ->setMethods(['getUser', 'getMountsIn', 'getMount'])
+ ->onlyMethods(['getUser', 'getMountsIn', 'getMount'])
->setConstructorArgs([$manager, $view, $this->user, $this->userMountCache, $this->logger, $this->userManager, $this->eventDispatcher, $this->cacheFactory])
->getMock();
- /** @var \PHPUnit\Framework\MockObject\MockObject|\OC\Files\FileInfo $folderInfo */
+ /** @var \PHPUnit\Framework\MockObject\MockObject|FileInfo $folderInfo */
$folderInfo = $this->getMockBuilder(FileInfo::class)
->disableOriginalConstructor()->getMock();
@@ -830,7 +834,7 @@ class FolderTest extends NodeTest {
'mimetype' => 'text/plain',
'size' => 3,
'parent' => $id1,
- 'permissions' => \OCP\Constants::PERMISSION_ALL,
+ 'permissions' => Constants::PERMISSION_ALL,
]);
$id3 = $cache->put('bar/foo/folder/asd.txt', [
'storage_mtime' => $baseTime - 100,
@@ -838,7 +842,7 @@ class FolderTest extends NodeTest {
'mimetype' => 'text/plain',
'size' => 3,
'parent' => $id1,
- 'permissions' => \OCP\Constants::PERMISSION_ALL,
+ 'permissions' => Constants::PERMISSION_ALL,
]);
$node = new Folder($root, $view, $folderPath, $folderInfo);
@@ -859,10 +863,10 @@ class FolderTest extends NodeTest {
$view = $this->getRootViewMock();
/** @var \PHPUnit\Framework\MockObject\MockObject|\OC\Files\Node\Root $root */
$root = $this->getMockBuilder(Root::class)
- ->setMethods(['getUser', 'getMountsIn', 'getMount'])
+ ->onlyMethods(['getUser', 'getMountsIn', 'getMount'])
->setConstructorArgs([$manager, $view, $this->user, $this->userMountCache, $this->logger, $this->userManager, $this->eventDispatcher, $this->cacheFactory])
->getMock();
- /** @var \PHPUnit\Framework\MockObject\MockObject|\OC\Files\FileInfo $folderInfo */
+ /** @var \PHPUnit\Framework\MockObject\MockObject|FileInfo $folderInfo */
$folderInfo = $this->getMockBuilder(FileInfo::class)
->disableOriginalConstructor()->getMock();
@@ -891,7 +895,7 @@ class FolderTest extends NodeTest {
'mtime' => $baseTime,
'mimetype' => 'text/plain',
'size' => 3,
- 'permissions' => \OCP\Constants::PERMISSION_ALL,
+ 'permissions' => Constants::PERMISSION_ALL,
]);
$cache->put('outside.txt', [
@@ -910,7 +914,7 @@ class FolderTest extends NodeTest {
$this->assertEquals([$id1], $ids);
}
- public function offsetLimitProvider() {
+ public static function offsetLimitProvider(): array {
return [
[0, 10, ['/bar/foo/foo1', '/bar/foo/foo2', '/bar/foo/foo3', '/bar/foo/foo4', '/bar/foo/sub1/foo5', '/bar/foo/sub1/foo6', '/bar/foo/sub2/foo7', '/bar/foo/sub2/foo8'], []],
[0, 5, ['/bar/foo/foo1', '/bar/foo/foo2', '/bar/foo/foo3', '/bar/foo/foo4', '/bar/foo/sub1/foo5'], []],
@@ -931,14 +935,14 @@ class FolderTest extends NodeTest {
}
/**
- * @dataProvider offsetLimitProvider
* @param int $offset
* @param int $limit
* @param string[] $expectedPaths
* @param ISearchOrder[] $ordering
* @throws NotFoundException
- * @throws \OCP\Files\InvalidPathException
+ * @throws InvalidPathException
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('offsetLimitProvider')]
public function testSearchSubStoragesLimitOffset(int $offset, int $limit, array $expectedPaths, array $ordering): void {
if (!$ordering) {
$ordering = [new SearchOrder(ISearchOrder::DIRECTION_ASCENDING, 'fileid')];
diff --git a/tests/lib/Files/Node/HookConnectorTest.php b/tests/lib/Files/Node/HookConnectorTest.php
index 1a3337b9ddc..3f3957bab1d 100644
--- a/tests/lib/Files/Node/HookConnectorTest.php
+++ b/tests/lib/Files/Node/HookConnectorTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -15,6 +16,7 @@ use OC\Files\View;
use OC\Memcache\ArrayCache;
use OCP\EventDispatcher\GenericEvent as APIGenericEvent;
use OCP\EventDispatcher\IEventDispatcher;
+use OCP\Files\Config\IUserMountCache;
use OCP\Files\Events\Node\AbstractNodeEvent;
use OCP\Files\Events\Node\AbstractNodesEvent;
use OCP\Files\Events\Node\BeforeNodeCopiedEvent;
@@ -32,6 +34,7 @@ use OCP\Files\Events\Node\NodeWrittenEvent;
use OCP\Files\Node;
use OCP\ICacheFactory;
use OCP\IUserManager;
+use OCP\Server;
use Psr\Log\LoggerInterface;
use Symfony\Component\EventDispatcher\GenericEvent;
use Test\TestCase;
@@ -79,15 +82,15 @@ class HookConnectorTest extends TestCase {
$this->root = new Root(
Filesystem::getMountManager(),
$this->view,
- \OC::$server->getUserManager()->get($this->userId),
- \OC::$server->getUserMountCache(),
+ Server::get(IUserManager::class)->get($this->userId),
+ Server::get(IUserMountCache::class),
$this->createMock(LoggerInterface::class),
$this->createMock(IUserManager::class),
$this->createMock(IEventDispatcher::class),
$cacheFactory,
);
- $this->eventDispatcher = \OC::$server->query(IEventDispatcher::class);
- $this->logger = \OC::$server->query(LoggerInterface::class);
+ $this->eventDispatcher = Server::get(IEventDispatcher::class);
+ $this->logger = Server::get(LoggerInterface::class);
}
protected function tearDown(): void {
@@ -96,51 +99,51 @@ class HookConnectorTest extends TestCase {
\OC_Util::tearDownFS();
}
- public function viewToNodeProvider() {
+ public static function viewToNodeProvider(): array {
return [
- [function () {
+ [function (): void {
Filesystem::file_put_contents('test.txt', 'asd');
}, 'preWrite', '\OCP\Files::preWrite', BeforeNodeWrittenEvent::class],
- [function () {
+ [function (): void {
Filesystem::file_put_contents('test.txt', 'asd');
}, 'postWrite', '\OCP\Files::postWrite', NodeWrittenEvent::class],
- [function () {
+ [function (): void {
Filesystem::file_put_contents('test.txt', 'asd');
}, 'preCreate', '\OCP\Files::preCreate', BeforeNodeCreatedEvent::class],
- [function () {
+ [function (): void {
Filesystem::file_put_contents('test.txt', 'asd');
}, 'postCreate', '\OCP\Files::postCreate', NodeCreatedEvent::class],
- [function () {
+ [function (): void {
Filesystem::mkdir('test.txt');
}, 'preCreate', '\OCP\Files::preCreate', BeforeNodeCreatedEvent::class],
- [function () {
+ [function (): void {
Filesystem::mkdir('test.txt');
}, 'postCreate', '\OCP\Files::postCreate', NodeCreatedEvent::class],
- [function () {
+ [function (): void {
Filesystem::touch('test.txt');
}, 'preTouch', '\OCP\Files::preTouch', BeforeNodeTouchedEvent::class],
- [function () {
+ [function (): void {
Filesystem::touch('test.txt');
}, 'postTouch', '\OCP\Files::postTouch', NodeTouchedEvent::class],
- [function () {
+ [function (): void {
Filesystem::touch('test.txt');
}, 'preCreate', '\OCP\Files::preCreate', BeforeNodeCreatedEvent::class],
- [function () {
+ [function (): void {
Filesystem::touch('test.txt');
}, 'postCreate', '\OCP\Files::postCreate', NodeCreatedEvent::class],
- [function () {
+ [function (): void {
Filesystem::file_put_contents('test.txt', 'asd');
Filesystem::unlink('test.txt');
}, 'preDelete', '\OCP\Files::preDelete', BeforeNodeDeletedEvent::class],
- [function () {
+ [function (): void {
Filesystem::file_put_contents('test.txt', 'asd');
Filesystem::unlink('test.txt');
}, 'postDelete', '\OCP\Files::postDelete', NodeDeletedEvent::class],
- [function () {
+ [function (): void {
Filesystem::mkdir('test.txt');
Filesystem::rmdir('test.txt');
}, 'preDelete', '\OCP\Files::preDelete', BeforeNodeDeletedEvent::class],
- [function () {
+ [function (): void {
Filesystem::mkdir('test.txt');
Filesystem::rmdir('test.txt');
}, 'postDelete', '\OCP\Files::postDelete', NodeDeletedEvent::class],
@@ -150,8 +153,8 @@ class HookConnectorTest extends TestCase {
/**
* @param callable $operation
* @param string $expectedHook
- * @dataProvider viewToNodeProvider
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('viewToNodeProvider')]
public function testViewToNode(callable $operation, $expectedHook, $expectedLegacyEvent, $expectedEvent): void {
$connector = new HookConnector($this->root, $this->view, $this->eventDispatcher, $this->logger);
$connector->viewToNode();
@@ -159,7 +162,7 @@ class HookConnectorTest extends TestCase {
/** @var Node $hookNode */
$hookNode = null;
- $this->root->listen('\OC\Files', $expectedHook, function ($node) use (&$hookNode, &$hookCalled) {
+ $this->root->listen('\OC\Files', $expectedHook, function ($node) use (&$hookNode, &$hookCalled): void {
$hookCalled = true;
$hookNode = $node;
});
@@ -167,7 +170,7 @@ class HookConnectorTest extends TestCase {
$dispatcherCalled = false;
/** @var Node $dispatcherNode */
$dispatcherNode = null;
- $this->eventDispatcher->addListener($expectedLegacyEvent, function ($event) use (&$dispatcherCalled, &$dispatcherNode) {
+ $this->eventDispatcher->addListener($expectedLegacyEvent, function ($event) use (&$dispatcherCalled, &$dispatcherNode): void {
/** @var GenericEvent|APIGenericEvent $event */
$dispatcherCalled = true;
$dispatcherNode = $event->getSubject();
@@ -175,7 +178,7 @@ class HookConnectorTest extends TestCase {
$newDispatcherCalled = false;
$newDispatcherNode = null;
- $this->eventDispatcher->addListener($expectedEvent, function ($event) use ($expectedEvent, &$newDispatcherCalled, &$newDispatcherNode) {
+ $this->eventDispatcher->addListener($expectedEvent, function ($event) use ($expectedEvent, &$newDispatcherCalled, &$newDispatcherNode): void {
if ($event instanceof $expectedEvent) {
/** @var AbstractNodeEvent $event */
$newDispatcherCalled = true;
@@ -195,21 +198,21 @@ class HookConnectorTest extends TestCase {
$this->assertEquals('/' . $this->userId . '/files/test.txt', $newDispatcherNode->getPath());
}
- public function viewToNodeProviderCopyRename() {
+ public static function viewToNodeProviderCopyRename(): array {
return [
- [function () {
+ [function (): void {
Filesystem::file_put_contents('source', 'asd');
Filesystem::rename('source', 'target');
}, 'preRename', '\OCP\Files::preRename', BeforeNodeRenamedEvent::class],
- [function () {
+ [function (): void {
Filesystem::file_put_contents('source', 'asd');
Filesystem::rename('source', 'target');
}, 'postRename', '\OCP\Files::postRename', NodeRenamedEvent::class],
- [function () {
+ [function (): void {
Filesystem::file_put_contents('source', 'asd');
Filesystem::copy('source', 'target');
}, 'preCopy', '\OCP\Files::preCopy', BeforeNodeCopiedEvent::class],
- [function () {
+ [function (): void {
Filesystem::file_put_contents('source', 'asd');
Filesystem::copy('source', 'target');
}, 'postCopy', '\OCP\Files::postCopy', NodeCopiedEvent::class],
@@ -219,8 +222,8 @@ class HookConnectorTest extends TestCase {
/**
* @param callable $operation
* @param string $expectedHook
- * @dataProvider viewToNodeProviderCopyRename
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('viewToNodeProviderCopyRename')]
public function testViewToNodeCopyRename(callable $operation, $expectedHook, $expectedLegacyEvent, $expectedEvent): void {
$connector = new HookConnector($this->root, $this->view, $this->eventDispatcher, $this->logger);
$connector->viewToNode();
@@ -230,7 +233,7 @@ class HookConnectorTest extends TestCase {
/** @var Node $hookTargetNode */
$hookTargetNode = null;
- $this->root->listen('\OC\Files', $expectedHook, function ($sourceNode, $targetNode) use (&$hookCalled, &$hookSourceNode, &$hookTargetNode) {
+ $this->root->listen('\OC\Files', $expectedHook, function ($sourceNode, $targetNode) use (&$hookCalled, &$hookSourceNode, &$hookTargetNode): void {
$hookCalled = true;
$hookSourceNode = $sourceNode;
$hookTargetNode = $targetNode;
@@ -241,7 +244,7 @@ class HookConnectorTest extends TestCase {
$dispatcherSourceNode = null;
/** @var Node $dispatcherTargetNode */
$dispatcherTargetNode = null;
- $this->eventDispatcher->addListener($expectedLegacyEvent, function ($event) use (&$dispatcherSourceNode, &$dispatcherTargetNode, &$dispatcherCalled) {
+ $this->eventDispatcher->addListener($expectedLegacyEvent, function ($event) use (&$dispatcherSourceNode, &$dispatcherTargetNode, &$dispatcherCalled): void {
/** @var GenericEvent|APIGenericEvent $event */
$dispatcherCalled = true;
[$dispatcherSourceNode, $dispatcherTargetNode] = $event->getSubject();
@@ -252,7 +255,7 @@ class HookConnectorTest extends TestCase {
$newDispatcherSourceNode = null;
/** @var Node $dispatcherTargetNode */
$newDispatcherTargetNode = null;
- $this->eventDispatcher->addListener($expectedEvent, function ($event) use ($expectedEvent, &$newDispatcherSourceNode, &$newDispatcherTargetNode, &$newDispatcherCalled) {
+ $this->eventDispatcher->addListener($expectedEvent, function ($event) use ($expectedEvent, &$newDispatcherSourceNode, &$newDispatcherTargetNode, &$newDispatcherCalled): void {
if ($event instanceof $expectedEvent) {
/** @var AbstractNodesEvent$event */
$newDispatcherCalled = true;
@@ -283,7 +286,7 @@ class HookConnectorTest extends TestCase {
/** @var Node $hookNode */
$hookNode = null;
- $this->root->listen('\OC\Files', 'postDelete', function ($node) use (&$hookNode, &$hookCalled) {
+ $this->root->listen('\OC\Files', 'postDelete', function ($node) use (&$hookNode, &$hookCalled): void {
$hookCalled = true;
$hookNode = $node;
});
@@ -291,7 +294,7 @@ class HookConnectorTest extends TestCase {
$dispatcherCalled = false;
/** @var Node $dispatcherNode */
$dispatcherNode = null;
- $this->eventDispatcher->addListener('\OCP\Files::postDelete', function ($event) use (&$dispatcherCalled, &$dispatcherNode) {
+ $this->eventDispatcher->addListener('\OCP\Files::postDelete', function ($event) use (&$dispatcherCalled, &$dispatcherNode): void {
/** @var GenericEvent|APIGenericEvent $event */
$dispatcherCalled = true;
$dispatcherNode = $event->getSubject();
@@ -300,7 +303,7 @@ class HookConnectorTest extends TestCase {
$newDispatcherCalled = false;
/** @var Node $dispatcherNode */
$newDispatcherNode = null;
- $this->eventDispatcher->addListener(NodeDeletedEvent::class, function ($event) use (&$newDispatcherCalled, &$newDispatcherNode) {
+ $this->eventDispatcher->addListener(NodeDeletedEvent::class, function ($event) use (&$newDispatcherCalled, &$newDispatcherNode): void {
if ($event instanceof NodeDeletedEvent) {
/** @var AbstractNodeEvent $event */
$newDispatcherCalled = true;
diff --git a/tests/lib/Files/Node/IntegrationTest.php b/tests/lib/Files/Node/IntegrationTest.php
index c90a6115f2a..f059afa1625 100644
--- a/tests/lib/Files/Node/IntegrationTest.php
+++ b/tests/lib/Files/Node/IntegrationTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -8,6 +9,7 @@
namespace Test\Files\Node;
use OC\Files\Node\Root;
+use OC\Files\Storage\Storage;
use OC\Files\Storage\Temporary;
use OC\Files\View;
use OC\Memcache\ArrayCache;
@@ -16,6 +18,7 @@ use OCP\Files\Config\IUserMountCache;
use OCP\Files\Mount\IMountManager;
use OCP\ICacheFactory;
use OCP\IUserManager;
+use OCP\Server;
use Psr\Log\LoggerInterface;
use Test\Traits\UserTrait;
@@ -35,19 +38,19 @@ class IntegrationTest extends \Test\TestCase {
private $root;
/**
- * @var \OC\Files\Storage\Storage[]
+ * @var Storage[]
*/
private $storages;
/**
- * @var \OC\Files\View $view
+ * @var View $view
*/
private $view;
protected function setUp(): void {
parent::setUp();
- $manager = \OCP\Server::get(IMountManager::class);
+ $manager = Server::get(IMountManager::class);
\OC_Hook::clear('OC_Filesystem');
@@ -64,7 +67,7 @@ class IntegrationTest extends \Test\TestCase {
$manager,
$this->view,
$user,
- \OCP\Server::get(IUserMountCache::class),
+ Server::get(IUserMountCache::class),
$this->createMock(LoggerInterface::class),
$this->createMock(IUserManager::class),
$this->createMock(IEventDispatcher::class),
diff --git a/tests/lib/Files/Node/NodeTest.php b/tests/lib/Files/Node/NodeTestCase.php
index db87aa925d3..4aecd0fef11 100644
--- a/tests/lib/Files/Node/NodeTest.php
+++ b/tests/lib/Files/Node/NodeTestCase.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -9,13 +10,22 @@ namespace Test\Files\Node;
use OC\Files\FileInfo;
use OC\Files\Mount\Manager;
+use OC\Files\Node\File;
+use OC\Files\Node\Folder;
+use OC\Files\Node\Root;
+use OC\Files\Storage\Storage;
use OC\Files\View;
use OC\Memcache\ArrayCache;
+use OC\User\User;
+use OCP\Constants;
use OCP\EventDispatcher\IEventDispatcher;
+use OCP\Files\Config\IUserMountCache;
+use OCP\Files\InvalidPathException;
use OCP\Files\IRootFolder;
use OCP\Files\Mount\IMountPoint;
use OCP\Files\Node;
use OCP\Files\NotFoundException;
+use OCP\Files\NotPermittedException;
use OCP\Files\Storage\IStorage;
use OCP\ICacheFactory;
use OCP\IUser;
@@ -27,16 +37,16 @@ use Psr\Log\LoggerInterface;
*
* @package Test\Files\Node
*/
-abstract class NodeTest extends \Test\TestCase {
- /** @var \OC\User\User */
+abstract class NodeTestCase extends \Test\TestCase {
+ /** @var User */
protected $user;
/** @var \OC\Files\Mount\Manager */
protected $manager;
- /** @var \OC\Files\View|\PHPUnit\Framework\MockObject\MockObject */
+ /** @var View|\PHPUnit\Framework\MockObject\MockObject */
protected $view;
/** @var \OC\Files\Node\Root|\PHPUnit\Framework\MockObject\MockObject */
protected $root;
- /** @var \OCP\Files\Config\IUserMountCache|\PHPUnit\Framework\MockObject\MockObject */
+ /** @var IUserMountCache|\PHPUnit\Framework\MockObject\MockObject */
protected $userMountCache;
/** @var LoggerInterface|\PHPUnit\Framework\MockObject\MockObject */
protected $logger;
@@ -71,13 +81,13 @@ abstract class NodeTest extends \Test\TestCase {
->willReturnCallback(function () {
return new ArrayCache();
});
- $this->root = $this->getMockBuilder('\OC\Files\Node\Root')
+ $this->root = $this->getMockBuilder(Root::class)
->setConstructorArgs([$this->manager, $this->view, $this->user, $this->userMountCache, $this->logger, $this->userManager, $this->eventDispatcher, $this->cacheFactory])
->getMock();
}
/**
- * @return \OC\Files\View | \PHPUnit\Framework\MockObject\MockObject $view
+ * @return View|\PHPUnit\Framework\MockObject\MockObject $view
*/
protected function getRootViewMock() {
$view = $this->createMock(View::class);
@@ -138,7 +148,7 @@ abstract class NodeTest extends \Test\TestCase {
$this->view->expects($this->once())
->method('getFileInfo')
->with('/bar/foo')
- ->willReturn($this->getFileInfo(['permissions' => \OCP\Constants::PERMISSION_ALL]));
+ ->willReturn($this->getFileInfo(['permissions' => Constants::PERMISSION_ALL]));
$this->view->expects($this->once())
->method($this->getViewDeleteMethod())
@@ -155,7 +165,7 @@ abstract class NodeTest extends \Test\TestCase {
/**
* @param \OC\Files\Node\File $node
*/
- $preListener = function ($node) use (&$test, &$hooksRun) {
+ $preListener = function ($node) use (&$test, &$hooksRun): void {
$test->assertInstanceOf($this->getNodeClass(), $node);
$test->assertEquals('foo', $node->getInternalPath());
$test->assertEquals('/bar/foo', $node->getPath());
@@ -166,7 +176,7 @@ abstract class NodeTest extends \Test\TestCase {
/**
* @param \OC\Files\Node\File $node
*/
- $postListener = function ($node) use (&$test, &$hooksRun) {
+ $postListener = function ($node) use (&$test, &$hooksRun): void {
$test->assertInstanceOf($this->getNonExistingNodeClass(), $node);
$test->assertEquals('foo', $node->getInternalPath());
$test->assertEquals('/bar/foo', $node->getPath());
@@ -175,7 +185,7 @@ abstract class NodeTest extends \Test\TestCase {
$hooksRun++;
};
- $root = new \OC\Files\Node\Root(
+ $root = new Root(
$this->manager,
$this->view,
$this->user,
@@ -192,7 +202,7 @@ abstract class NodeTest extends \Test\TestCase {
$this->view->expects($this->any())
->method('getFileInfo')
->with('/bar/foo')
- ->willReturn($this->getFileInfo(['permissions' => \OCP\Constants::PERMISSION_ALL, 'fileid' => 1, 'mimetype' => 'text/plain'], 'foo'));
+ ->willReturn($this->getFileInfo(['permissions' => Constants::PERMISSION_ALL, 'fileid' => 1, 'mimetype' => 'text/plain'], 'foo'));
$this->view->expects($this->once())
->method($this->getViewDeleteMethod())
@@ -206,7 +216,7 @@ abstract class NodeTest extends \Test\TestCase {
public function testDeleteNotPermitted(): void {
- $this->expectException(\OCP\Files\NotPermittedException::class);
+ $this->expectException(NotPermittedException::class);
$this->root->expects($this->any())
->method('getUser')
@@ -215,7 +225,7 @@ abstract class NodeTest extends \Test\TestCase {
$this->view->expects($this->once())
->method('getFileInfo')
->with('/bar/foo')
- ->willReturn($this->getFileInfo(['permissions' => \OCP\Constants::PERMISSION_READ]));
+ ->willReturn($this->getFileInfo(['permissions' => Constants::PERMISSION_READ]));
$node = $this->createTestNode($this->root, $this->view, '/bar/foo');
$node->delete();
@@ -334,7 +344,7 @@ abstract class NodeTest extends \Test\TestCase {
->method('getUser')
->willReturn($this->user);
/**
- * @var \OC\Files\Storage\Storage | \PHPUnit\Framework\MockObject\MockObject $storage
+ * @var Storage|\PHPUnit\Framework\MockObject\MockObject $storage
*/
$storage = $this->getMockBuilder('\OC\Files\Storage\Storage')
->disableOriginalConstructor()
@@ -358,7 +368,7 @@ abstract class NodeTest extends \Test\TestCase {
->method('getUser')
->willReturn($this->user);
/**
- * @var \OC\Files\Storage\Storage | \PHPUnit\Framework\MockObject\MockObject $storage
+ * @var Storage|\PHPUnit\Framework\MockObject\MockObject $storage
*/
$storage = $this->getMockBuilder('\OC\Files\Storage\Storage')
->disableOriginalConstructor()
@@ -396,7 +406,7 @@ abstract class NodeTest extends \Test\TestCase {
$this->view->expects($this->once())
->method('getFileInfo')
->with('/bar/foo')
- ->willReturn($this->getFileInfo(['permissions' => \OCP\Constants::PERMISSION_ALL]));
+ ->willReturn($this->getFileInfo(['permissions' => Constants::PERMISSION_ALL]));
$node = $this->createTestNode($this->root, $this->view, '/bar/foo');
$node->touch(100);
@@ -409,7 +419,7 @@ abstract class NodeTest extends \Test\TestCase {
/**
* @param \OC\Files\Node\File $node
*/
- $preListener = function ($node) use (&$test, &$hooksRun) {
+ $preListener = function ($node) use (&$test, &$hooksRun): void {
$test->assertEquals('foo', $node->getInternalPath());
$test->assertEquals('/bar/foo', $node->getPath());
$hooksRun++;
@@ -418,13 +428,13 @@ abstract class NodeTest extends \Test\TestCase {
/**
* @param \OC\Files\Node\File $node
*/
- $postListener = function ($node) use (&$test, &$hooksRun) {
+ $postListener = function ($node) use (&$test, &$hooksRun): void {
$test->assertEquals('foo', $node->getInternalPath());
$test->assertEquals('/bar/foo', $node->getPath());
$hooksRun++;
};
- $root = new \OC\Files\Node\Root(
+ $root = new Root(
$this->manager,
$this->view,
$this->user,
@@ -445,7 +455,7 @@ abstract class NodeTest extends \Test\TestCase {
$this->view->expects($this->any())
->method('getFileInfo')
->with('/bar/foo')
- ->willReturn($this->getFileInfo(['permissions' => \OCP\Constants::PERMISSION_ALL], 'foo'));
+ ->willReturn($this->getFileInfo(['permissions' => Constants::PERMISSION_ALL], 'foo'));
$node = $this->createTestNode($root, $this->view, '/bar/foo');
$node->touch(100);
@@ -454,7 +464,7 @@ abstract class NodeTest extends \Test\TestCase {
public function testTouchNotPermitted(): void {
- $this->expectException(\OCP\Files\NotPermittedException::class);
+ $this->expectException(NotPermittedException::class);
$this->root->expects($this->any())
->method('getUser')
@@ -463,7 +473,7 @@ abstract class NodeTest extends \Test\TestCase {
$this->view->expects($this->any())
->method('getFileInfo')
->with('/bar/foo')
- ->willReturn($this->getFileInfo(['permissions' => \OCP\Constants::PERMISSION_READ]));
+ ->willReturn($this->getFileInfo(['permissions' => Constants::PERMISSION_READ]));
$node = $this->createTestNode($this->root, $this->view, '/bar/foo');
$node->touch(100);
@@ -471,7 +481,7 @@ abstract class NodeTest extends \Test\TestCase {
public function testInvalidPath(): void {
- $this->expectException(\OCP\Files\InvalidPathException::class);
+ $this->expectException(InvalidPathException::class);
$node = $this->createTestNode($this->root, $this->view, '/../foo');
$node->getFileInfo();
@@ -485,10 +495,10 @@ abstract class NodeTest extends \Test\TestCase {
$this->view->expects($this->any())
->method('getFileInfo')
- ->willReturn($this->getFileInfo(['permissions' => \OCP\Constants::PERMISSION_ALL, 'fileid' => 3]));
+ ->willReturn($this->getFileInfo(['permissions' => Constants::PERMISSION_ALL, 'fileid' => 3]));
$node = $this->createTestNode($this->root, $this->view, '/bar/foo');
- $parentNode = new \OC\Files\Node\Folder($this->root, $this->view, '/bar');
+ $parentNode = new Folder($this->root, $this->view, '/bar');
$newNode = $this->createTestNode($this->root, $this->view, '/bar/asd');
$this->root->method('get')
@@ -504,10 +514,10 @@ abstract class NodeTest extends \Test\TestCase {
public function testCopyNotPermitted(): void {
- $this->expectException(\OCP\Files\NotPermittedException::class);
+ $this->expectException(NotPermittedException::class);
/**
- * @var \OC\Files\Storage\Storage | \PHPUnit\Framework\MockObject\MockObject $storage
+ * @var Storage|\PHPUnit\Framework\MockObject\MockObject $storage
*/
$storage = $this->createMock('\OC\Files\Storage\Storage');
@@ -519,10 +529,10 @@ abstract class NodeTest extends \Test\TestCase {
$this->view->expects($this->any())
->method('getFileInfo')
- ->willReturn($this->getFileInfo(['permissions' => \OCP\Constants::PERMISSION_READ, 'fileid' => 3]));
+ ->willReturn($this->getFileInfo(['permissions' => Constants::PERMISSION_READ, 'fileid' => 3]));
$node = $this->createTestNode($this->root, $this->view, '/bar/foo');
- $parentNode = new \OC\Files\Node\Folder($this->root, $this->view, '/bar');
+ $parentNode = new Folder($this->root, $this->view, '/bar');
$this->root->expects($this->once())
->method('get')
@@ -535,7 +545,7 @@ abstract class NodeTest extends \Test\TestCase {
public function testCopyNoParent(): void {
- $this->expectException(\OCP\Files\NotFoundException::class);
+ $this->expectException(NotFoundException::class);
$this->view->expects($this->never())
->method('copy');
@@ -545,20 +555,20 @@ abstract class NodeTest extends \Test\TestCase {
$this->root->expects($this->once())
->method('get')
->with('/bar/asd')
- ->will($this->throwException(new NotFoundException()));
+ ->willThrowException(new NotFoundException());
$node->copy('/bar/asd/foo');
}
public function testCopyParentIsFile(): void {
- $this->expectException(\OCP\Files\NotPermittedException::class);
+ $this->expectException(NotPermittedException::class);
$this->view->expects($this->never())
->method('copy');
$node = $this->createTestNode($this->root, $this->view, '/bar/foo');
- $parentNode = new \OC\Files\Node\File($this->root, $this->view, '/bar');
+ $parentNode = new File($this->root, $this->view, '/bar');
$this->root->expects($this->once())
->method('get')
@@ -577,10 +587,10 @@ abstract class NodeTest extends \Test\TestCase {
$this->view->expects($this->any())
->method('getFileInfo')
- ->willReturn($this->getFileInfo(['permissions' => \OCP\Constants::PERMISSION_ALL, 'fileid' => 1]));
+ ->willReturn($this->getFileInfo(['permissions' => Constants::PERMISSION_ALL, 'fileid' => 1]));
$node = $this->createTestNode($this->root, $this->view, '/bar/foo');
- $parentNode = new \OC\Files\Node\Folder($this->root, $this->view, '/bar');
+ $parentNode = new Folder($this->root, $this->view, '/bar');
$this->root->expects($this->any())
->method('get')
@@ -592,7 +602,7 @@ abstract class NodeTest extends \Test\TestCase {
$this->assertEquals('/bar/asd', $node->getPath());
}
- public function moveOrCopyProvider() {
+ public static function moveOrCopyProvider(): array {
return [
['move', 'rename', 'preRename', 'postRename'],
['copy', 'copy', 'preCopy', 'postCopy'],
@@ -600,17 +610,17 @@ abstract class NodeTest extends \Test\TestCase {
}
/**
- * @dataProvider moveOrCopyProvider
* @param string $operationMethod
* @param string $viewMethod
* @param string $preHookName
* @param string $postHookName
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('moveOrCopyProvider')]
public function testMoveCopyHooks($operationMethod, $viewMethod, $preHookName, $postHookName): void {
/** @var IRootFolder|\PHPUnit\Framework\MockObject\MockObject $root */
- $root = $this->getMockBuilder('\OC\Files\Node\Root')
+ $root = $this->getMockBuilder(Root::class)
->setConstructorArgs([$this->manager, $this->view, $this->user, $this->userMountCache, $this->logger, $this->userManager, $this->eventDispatcher, $this->cacheFactory])
- ->setMethods(['get'])
+ ->onlyMethods(['get'])
->getMock();
$this->view->expects($this->any())
@@ -620,13 +630,13 @@ abstract class NodeTest extends \Test\TestCase {
$this->view->expects($this->any())
->method('getFileInfo')
- ->willReturn($this->getFileInfo(['permissions' => \OCP\Constants::PERMISSION_ALL, 'fileid' => 1]));
+ ->willReturn($this->getFileInfo(['permissions' => Constants::PERMISSION_ALL, 'fileid' => 1]));
/**
* @var \OC\Files\Node\File|\PHPUnit\Framework\MockObject\MockObject $node
*/
$node = $this->createTestNode($root, $this->view, '/bar/foo');
- $parentNode = new \OC\Files\Node\Folder($root, $this->view, '/bar');
+ $parentNode = new Folder($root, $this->view, '/bar');
$targetTestNode = $this->createTestNode($root, $this->view, '/bar/asd');
$root->expects($this->any())
@@ -635,7 +645,7 @@ abstract class NodeTest extends \Test\TestCase {
$hooksRun = 0;
- $preListener = function (Node $sourceNode, Node $targetNode) use (&$hooksRun, $node) {
+ $preListener = function (Node $sourceNode, Node $targetNode) use (&$hooksRun, $node): void {
$this->assertSame($node, $sourceNode);
$this->assertInstanceOf($this->getNodeClass(), $sourceNode);
$this->assertInstanceOf($this->getNonExistingNodeClass(), $targetNode);
@@ -643,7 +653,7 @@ abstract class NodeTest extends \Test\TestCase {
$hooksRun++;
};
- $postListener = function (Node $sourceNode, Node $targetNode) use (&$hooksRun, $node, $targetTestNode) {
+ $postListener = function (Node $sourceNode, Node $targetNode) use (&$hooksRun, $node, $targetTestNode): void {
$this->assertSame($node, $sourceNode);
$this->assertNotSame($node, $targetNode);
$this->assertSame($targetTestNode, $targetNode);
@@ -652,13 +662,13 @@ abstract class NodeTest extends \Test\TestCase {
$hooksRun++;
};
- $preWriteListener = function (Node $targetNode) use (&$hooksRun) {
+ $preWriteListener = function (Node $targetNode) use (&$hooksRun): void {
$this->assertInstanceOf($this->getNonExistingNodeClass(), $targetNode);
$this->assertEquals('/bar/asd', $targetNode->getPath());
$hooksRun++;
};
- $postWriteListener = function (Node $targetNode) use (&$hooksRun, $targetTestNode) {
+ $postWriteListener = function (Node $targetNode) use (&$hooksRun, $targetTestNode): void {
$this->assertSame($targetTestNode, $targetNode);
$hooksRun++;
};
@@ -675,17 +685,17 @@ abstract class NodeTest extends \Test\TestCase {
public function testMoveNotPermitted(): void {
- $this->expectException(\OCP\Files\NotPermittedException::class);
+ $this->expectException(NotPermittedException::class);
$this->view->expects($this->any())
->method('getFileInfo')
- ->willReturn($this->getFileInfo(['permissions' => \OCP\Constants::PERMISSION_READ]));
+ ->willReturn($this->getFileInfo(['permissions' => Constants::PERMISSION_READ]));
$this->view->expects($this->never())
->method('rename');
$node = $this->createTestNode($this->root, $this->view, '/bar/foo');
- $parentNode = new \OC\Files\Node\Folder($this->root, $this->view, '/bar');
+ $parentNode = new Folder($this->root, $this->view, '/bar');
$this->root->expects($this->once())
->method('get')
@@ -697,10 +707,10 @@ abstract class NodeTest extends \Test\TestCase {
public function testMoveNoParent(): void {
- $this->expectException(\OCP\Files\NotFoundException::class);
+ $this->expectException(NotFoundException::class);
/**
- * @var \OC\Files\Storage\Storage | \PHPUnit\Framework\MockObject\MockObject $storage
+ * @var Storage|\PHPUnit\Framework\MockObject\MockObject $storage
*/
$storage = $this->createMock('\OC\Files\Storage\Storage');
@@ -712,20 +722,20 @@ abstract class NodeTest extends \Test\TestCase {
$this->root->expects($this->once())
->method('get')
->with('/bar')
- ->will($this->throwException(new NotFoundException()));
+ ->willThrowException(new NotFoundException());
$node->move('/bar/asd');
}
public function testMoveParentIsFile(): void {
- $this->expectException(\OCP\Files\NotPermittedException::class);
+ $this->expectException(NotPermittedException::class);
$this->view->expects($this->never())
->method('rename');
$node = $this->createTestNode($this->root, $this->view, '/bar/foo');
- $parentNode = new \OC\Files\Node\File($this->root, $this->view, '/bar');
+ $parentNode = new File($this->root, $this->view, '/bar');
$this->root->expects($this->once())
->method('get')
@@ -737,7 +747,7 @@ abstract class NodeTest extends \Test\TestCase {
public function testMoveFailed(): void {
- $this->expectException(\OCP\Files\NotPermittedException::class);
+ $this->expectException(NotPermittedException::class);
$this->view->expects($this->any())
->method('rename')
@@ -746,10 +756,10 @@ abstract class NodeTest extends \Test\TestCase {
$this->view->expects($this->any())
->method('getFileInfo')
- ->willReturn($this->getFileInfo(['permissions' => \OCP\Constants::PERMISSION_ALL, 'fileid' => 1]));
+ ->willReturn($this->getFileInfo(['permissions' => Constants::PERMISSION_ALL, 'fileid' => 1]));
$node = $this->createTestNode($this->root, $this->view, '/bar/foo');
- $parentNode = new \OC\Files\Node\Folder($this->root, $this->view, '/bar');
+ $parentNode = new Folder($this->root, $this->view, '/bar');
$this->root->expects($this->any())
->method('get')
@@ -760,7 +770,7 @@ abstract class NodeTest extends \Test\TestCase {
public function testCopyFailed(): void {
- $this->expectException(\OCP\Files\NotPermittedException::class);
+ $this->expectException(NotPermittedException::class);
$this->view->expects($this->any())
->method('copy')
@@ -769,10 +779,10 @@ abstract class NodeTest extends \Test\TestCase {
$this->view->expects($this->any())
->method('getFileInfo')
- ->willReturn($this->getFileInfo(['permissions' => \OCP\Constants::PERMISSION_ALL, 'fileid' => 1]));
+ ->willReturn($this->getFileInfo(['permissions' => Constants::PERMISSION_ALL, 'fileid' => 1]));
$node = $this->createTestNode($this->root, $this->view, '/bar/foo');
- $parentNode = new \OC\Files\Node\Folder($this->root, $this->view, '/bar');
+ $parentNode = new Folder($this->root, $this->view, '/bar');
$this->root->expects($this->any())
->method('get')
diff --git a/tests/lib/Files/Node/RootTest.php b/tests/lib/Files/Node/RootTest.php
index f2ef1a0e3ee..d90e6a2cc6e 100644
--- a/tests/lib/Files/Node/RootTest.php
+++ b/tests/lib/Files/Node/RootTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -10,10 +11,17 @@ namespace Test\Files\Node;
use OC\Files\FileInfo;
use OC\Files\Mount\Manager;
use OC\Files\Node\Folder;
+use OC\Files\Node\Root;
+use OC\Files\Storage\Storage;
use OC\Files\View;
use OC\Memcache\ArrayCache;
+use OC\User\NoUserException;
+use OC\User\User;
use OCP\Cache\CappedMemoryCache;
use OCP\EventDispatcher\IEventDispatcher;
+use OCP\Files\Config\IUserMountCache;
+use OCP\Files\NotFoundException;
+use OCP\Files\NotPermittedException;
use OCP\ICacheFactory;
use OCP\IUser;
use OCP\IUserManager;
@@ -25,11 +33,11 @@ use Psr\Log\LoggerInterface;
* @package Test\Files\Node
*/
class RootTest extends \Test\TestCase {
- /** @var \OC\User\User */
+ /** @var User */
private $user;
/** @var \OC\Files\Mount\Manager */
private $manager;
- /** @var \OCP\Files\Config\IUserMountCache|\PHPUnit\Framework\MockObject\MockObject */
+ /** @var IUserMountCache|\PHPUnit\Framework\MockObject\MockObject */
private $userMountCache;
/** @var LoggerInterface|\PHPUnit\Framework\MockObject\MockObject */
private $logger;
@@ -61,7 +69,7 @@ class RootTest extends \Test\TestCase {
}
/**
- * @return \OC\Files\View | \PHPUnit\Framework\MockObject\MockObject $view
+ * @return View|\PHPUnit\Framework\MockObject\MockObject $view
*/
protected function getRootViewMock() {
$view = $this->createMock(View::class);
@@ -77,13 +85,13 @@ class RootTest extends \Test\TestCase {
public function testGet(): void {
/**
- * @var \OC\Files\Storage\Storage $storage
+ * @var Storage $storage
*/
$storage = $this->getMockBuilder('\OC\Files\Storage\Storage')
->disableOriginalConstructor()
->getMock();
$view = $this->getRootViewMock();
- $root = new \OC\Files\Node\Root(
+ $root = new Root(
$this->manager,
$view,
$this->user,
@@ -107,16 +115,16 @@ class RootTest extends \Test\TestCase {
public function testGetNotFound(): void {
- $this->expectException(\OCP\Files\NotFoundException::class);
+ $this->expectException(NotFoundException::class);
/**
- * @var \OC\Files\Storage\Storage $storage
+ * @var Storage $storage
*/
$storage = $this->getMockBuilder('\OC\Files\Storage\Storage')
->disableOriginalConstructor()
->getMock();
$view = $this->getRootViewMock();
- $root = new \OC\Files\Node\Root(
+ $root = new Root(
$this->manager,
$view,
$this->user,
@@ -138,10 +146,10 @@ class RootTest extends \Test\TestCase {
public function testGetInvalidPath(): void {
- $this->expectException(\OCP\Files\NotPermittedException::class);
+ $this->expectException(NotPermittedException::class);
$view = $this->getRootViewMock();
- $root = new \OC\Files\Node\Root(
+ $root = new Root(
$this->manager,
$view,
$this->user,
@@ -157,10 +165,10 @@ class RootTest extends \Test\TestCase {
public function testGetNoStorages(): void {
- $this->expectException(\OCP\Files\NotFoundException::class);
+ $this->expectException(NotFoundException::class);
$view = $this->getRootViewMock();
- $root = new \OC\Files\Node\Root(
+ $root = new Root(
$this->manager,
$view,
$this->user,
@@ -175,7 +183,7 @@ class RootTest extends \Test\TestCase {
}
public function testGetUserFolder(): void {
- $root = new \OC\Files\Node\Root(
+ $root = new Root(
$this->manager,
$this->getRootViewMock(),
$this->user,
@@ -214,10 +222,10 @@ class RootTest extends \Test\TestCase {
public function testGetUserFolderWithNoUserObj(): void {
- $this->expectException(\OC\User\NoUserException::class);
+ $this->expectException(NoUserException::class);
$this->expectExceptionMessage('Backends provided no user object');
- $root = new \OC\Files\Node\Root(
+ $root = new Root(
$this->createMock(Manager::class),
$this->getRootViewMock(),
null,
diff --git a/tests/lib/Files/ObjectStore/AzureTest.php b/tests/lib/Files/ObjectStore/AzureTest.php
index c82ed988434..52d2b9e8657 100644
--- a/tests/lib/Files/ObjectStore/AzureTest.php
+++ b/tests/lib/Files/ObjectStore/AzureTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2018 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
@@ -7,13 +8,15 @@
namespace Test\Files\ObjectStore;
use OC\Files\ObjectStore\Azure;
+use OCP\IConfig;
+use OCP\Server;
/**
* @group PRIMARY-azure
*/
-class AzureTest extends ObjectStoreTest {
+class AzureTest extends ObjectStoreTestCase {
protected function getInstance() {
- $config = \OC::$server->getConfig()->getSystemValue('objectstore');
+ $config = Server::get(IConfig::class)->getSystemValue('objectstore');
if (!is_array($config) || $config['class'] !== 'OC\\Files\\ObjectStore\\Azure') {
$this->markTestSkipped('objectstore not configured for azure');
}
diff --git a/tests/lib/Files/ObjectStore/FailDeleteObjectStore.php b/tests/lib/Files/ObjectStore/FailDeleteObjectStore.php
index b84ee1a1b64..767125d42aa 100644
--- a/tests/lib/Files/ObjectStore/FailDeleteObjectStore.php
+++ b/tests/lib/Files/ObjectStore/FailDeleteObjectStore.php
@@ -11,10 +11,9 @@ namespace Test\Files\ObjectStore;
use OCP\Files\ObjectStore\IObjectStore;
class FailDeleteObjectStore implements IObjectStore {
- private $objectStore;
-
- public function __construct(IObjectStore $objectStore) {
- $this->objectStore = $objectStore;
+ public function __construct(
+ private IObjectStore $objectStore,
+ ) {
}
public function getStorageId() {
diff --git a/tests/lib/Files/ObjectStore/FailWriteObjectStore.php b/tests/lib/Files/ObjectStore/FailWriteObjectStore.php
index b84b123244e..924bbdada4f 100644
--- a/tests/lib/Files/ObjectStore/FailWriteObjectStore.php
+++ b/tests/lib/Files/ObjectStore/FailWriteObjectStore.php
@@ -11,10 +11,9 @@ namespace Test\Files\ObjectStore;
use OCP\Files\ObjectStore\IObjectStore;
class FailWriteObjectStore implements IObjectStore {
- private $objectStore;
-
- public function __construct(IObjectStore $objectStore) {
- $this->objectStore = $objectStore;
+ public function __construct(
+ private IObjectStore $objectStore,
+ ) {
}
public function getStorageId() {
diff --git a/tests/lib/Files/ObjectStore/LocalTest.php b/tests/lib/Files/ObjectStore/LocalTest.php
index 99c5b61534f..d3e9ad56164 100644
--- a/tests/lib/Files/ObjectStore/LocalTest.php
+++ b/tests/lib/Files/ObjectStore/LocalTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
@@ -8,10 +9,11 @@ namespace Test\Files\ObjectStore;
use OC\Files\ObjectStore\StorageObjectStore;
use OC\Files\Storage\Temporary;
+use OCP\Files\ObjectStore\IObjectStore;
-class LocalTest extends ObjectStoreTest {
+class LocalTest extends ObjectStoreTestCase {
/**
- * @return \OCP\Files\ObjectStore\IObjectStore
+ * @return IObjectStore
*/
protected function getInstance() {
$storage = new Temporary();
diff --git a/tests/lib/Files/ObjectStore/MapperTest.php b/tests/lib/Files/ObjectStore/MapperTest.php
index 15a2d497fc3..6448d5ce1f5 100644
--- a/tests/lib/Files/ObjectStore/MapperTest.php
+++ b/tests/lib/Files/ObjectStore/MapperTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -29,7 +30,7 @@ class MapperTest extends \Test\TestCase {
$this->mapper = new Mapper($this->user, $this->config);
}
- public function dataGetBucket() {
+ public static function dataGetBucket(): array {
return [
['user', 64, 0, '17'],
['USER', 64, 0, '0'],
@@ -42,11 +43,11 @@ class MapperTest extends \Test\TestCase {
}
/**
- * @dataProvider dataGetBucket
* @param string $username
* @param int $numBuckets
* @param string $expectedBucket
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataGetBucket')]
public function testGetBucket($username, $numBuckets, $bucketShift, $expectedBucket): void {
$this->user->expects($this->once())
->method('getUID')
diff --git a/tests/lib/Files/ObjectStore/ObjectStoreScannerTest.php b/tests/lib/Files/ObjectStore/ObjectStoreScannerTest.php
index 11c913cd232..ea6ac682c70 100644
--- a/tests/lib/Files/ObjectStore/ObjectStoreScannerTest.php
+++ b/tests/lib/Files/ObjectStore/ObjectStoreScannerTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2023 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
diff --git a/tests/lib/Files/ObjectStore/ObjectStoreStorageTest.php b/tests/lib/Files/ObjectStore/ObjectStoreStorageTest.php
index 3dbdc3afc27..3387808445a 100644
--- a/tests/lib/Files/ObjectStore/ObjectStoreStorageTest.php
+++ b/tests/lib/Files/ObjectStore/ObjectStoreStorageTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -10,6 +11,7 @@ namespace Test\Files\ObjectStore;
use OC\Files\ObjectStore\StorageObjectStore;
use OC\Files\Storage\Temporary;
use OC\Files\Storage\Wrapper\Jail;
+use OCP\Constants;
use OCP\Files\ObjectStore\IObjectStore;
use Test\Files\Storage\Storage;
@@ -71,9 +73,7 @@ class ObjectStoreStorageTest extends Storage {
$this->markTestSkipped('Detecting external changes is not supported on object storages');
}
- /**
- * @dataProvider copyAndMoveProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('copyAndMoveProvider')]
public function testMove($source, $target): void {
$this->initSourceAndTarget($source);
$sourceId = $this->instance->getCache()->getId(ltrim($source, '/'));
@@ -231,13 +231,13 @@ class ObjectStoreStorageTest extends Storage {
$this->instance->file_put_contents('test.txt', 'foo');
$this->assertTrue($cache->inCache('test.txt'));
- $cache->update($cache->getId('test.txt'), ['permissions' => \OCP\Constants::PERMISSION_READ]);
- $this->assertEquals(\OCP\Constants::PERMISSION_READ, $this->instance->getPermissions('test.txt'));
+ $cache->update($cache->getId('test.txt'), ['permissions' => Constants::PERMISSION_READ]);
+ $this->assertEquals(Constants::PERMISSION_READ, $this->instance->getPermissions('test.txt'));
$this->assertTrue($this->instance->copy('test.txt', 'new.txt'));
$this->assertTrue($cache->inCache('new.txt'));
- $this->assertEquals(\OCP\Constants::PERMISSION_READ, $this->instance->getPermissions('new.txt'));
+ $this->assertEquals(Constants::PERMISSION_READ, $this->instance->getPermissions('new.txt'));
}
/**
@@ -254,12 +254,25 @@ class ObjectStoreStorageTest extends Storage {
$instance->file_put_contents('test.txt', 'foo');
$this->assertTrue($cache->inCache('test.txt'));
- $cache->update($cache->getId('test.txt'), ['permissions' => \OCP\Constants::PERMISSION_READ]);
- $this->assertEquals(\OCP\Constants::PERMISSION_READ, $instance->getPermissions('test.txt'));
+ $cache->update($cache->getId('test.txt'), ['permissions' => Constants::PERMISSION_READ]);
+ $this->assertEquals(Constants::PERMISSION_READ, $instance->getPermissions('test.txt'));
$this->assertTrue($instance->copy('test.txt', 'new.txt'));
$this->assertTrue($cache->inCache('new.txt'));
- $this->assertEquals(\OCP\Constants::PERMISSION_ALL, $instance->getPermissions('new.txt'));
+ $this->assertEquals(Constants::PERMISSION_ALL, $instance->getPermissions('new.txt'));
+ }
+
+ public function testCopyFolderSize(): void {
+ $cache = $this->instance->getCache();
+
+ $this->instance->mkdir('source');
+ $this->instance->file_put_contents('source/test.txt', 'foo');
+ $this->instance->getUpdater()->update('source/test.txt');
+ $this->assertEquals(3, $cache->get('source')->getSize());
+
+ $this->assertTrue($this->instance->copy('source', 'target'));
+
+ $this->assertEquals(3, $cache->get('target')->getSize());
}
}
diff --git a/tests/lib/Files/ObjectStore/ObjectStoreStoragesDifferentBucketTest.php b/tests/lib/Files/ObjectStore/ObjectStoreStoragesDifferentBucketTest.php
index a0e18a5557b..d39426ee821 100644
--- a/tests/lib/Files/ObjectStore/ObjectStoreStoragesDifferentBucketTest.php
+++ b/tests/lib/Files/ObjectStore/ObjectStoreStoragesDifferentBucketTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -9,19 +10,20 @@ namespace Test\Files\ObjectStore;
use OC\Files\ObjectStore\StorageObjectStore;
use OC\Files\Storage\Temporary;
-use Test\Files\Storage\StoragesTest;
+use OCP\Files\ObjectStore\IObjectStore;
+use Test\Files\Storage\StoragesTestCase;
/**
* @group DB
*/
-class ObjectStoreStoragesDifferentBucketTest extends StoragesTest {
+class ObjectStoreStoragesDifferentBucketTest extends StoragesTestCase {
/**
- * @var \OCP\Files\ObjectStore\IObjectStore
+ * @var IObjectStore
*/
private $objectStore1;
/**
- * @var \OCP\Files\ObjectStore\IObjectStore
+ * @var IObjectStore
*/
private $objectStore2;
diff --git a/tests/lib/Files/ObjectStore/ObjectStoreStoragesSameBucketTest.php b/tests/lib/Files/ObjectStore/ObjectStoreStoragesSameBucketTest.php
index 19a1f4b7bc5..4e42668cd3f 100644
--- a/tests/lib/Files/ObjectStore/ObjectStoreStoragesSameBucketTest.php
+++ b/tests/lib/Files/ObjectStore/ObjectStoreStoragesSameBucketTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -9,14 +10,15 @@ namespace Test\Files\ObjectStore;
use OC\Files\ObjectStore\StorageObjectStore;
use OC\Files\Storage\Temporary;
-use Test\Files\Storage\StoragesTest;
+use OCP\Files\ObjectStore\IObjectStore;
+use Test\Files\Storage\StoragesTestCase;
/**
* @group DB
*/
-class ObjectStoreStoragesSameBucketTest extends StoragesTest {
+class ObjectStoreStoragesSameBucketTest extends StoragesTestCase {
/**
- * @var \OCP\Files\ObjectStore\IObjectStore
+ * @var IObjectStore
*/
private $objectStore;
diff --git a/tests/lib/Files/ObjectStore/ObjectStoreTest.php b/tests/lib/Files/ObjectStore/ObjectStoreTestCase.php
index 4a4f85dfb91..03e7b9545e0 100644
--- a/tests/lib/Files/ObjectStore/ObjectStoreTest.php
+++ b/tests/lib/Files/ObjectStore/ObjectStoreTestCase.php
@@ -7,14 +7,17 @@
namespace Test\Files\ObjectStore;
+use OCP\Files\ObjectStore\IObjectStore;
use Test\TestCase;
-abstract class ObjectStoreTest extends TestCase {
+abstract class ObjectStoreTestCase extends TestCase {
/** @var string[] */
private $cleanup = [];
+ private $instance = null;
+
/**
- * @return \OCP\Files\ObjectStore\IObjectStore
+ * @return IObjectStore
*/
abstract protected function getInstance();
@@ -22,13 +25,20 @@ abstract class ObjectStoreTest extends TestCase {
$this->cleanup[] = $urn;
}
- public function tearDown(): void {
- parent::tearDown();
+ public function setUp(): void {
+ parent::setUp();
- $instance = $this->getInstance();
- foreach ($this->cleanup as $urn) {
- $instance->deleteObject($urn);
+ $this->instance = $this->getInstance();
+ }
+
+ public function tearDown(): void {
+ if ($this->instance) {
+ foreach ($this->cleanup as $urn) {
+ $this->instance->deleteObject($urn);
+ }
}
+
+ parent::tearDown();
}
protected function stringToStream($data) {
diff --git a/tests/lib/Files/ObjectStore/S3Test.php b/tests/lib/Files/ObjectStore/S3Test.php
index 1501f575f9a..2915ada0aab 100644
--- a/tests/lib/Files/ObjectStore/S3Test.php
+++ b/tests/lib/Files/ObjectStore/S3Test.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
@@ -8,6 +9,8 @@ namespace Test\Files\ObjectStore;
use Icewind\Streams\Wrapper;
use OC\Files\ObjectStore\S3;
+use OCP\IConfig;
+use OCP\Server;
class MultiPartUploadS3 extends S3 {
public function writeObject($urn, $stream, ?string $mimetype = null) {
@@ -44,7 +47,7 @@ class NonSeekableStream extends Wrapper {
/**
* @group PRIMARY-s3
*/
-class S3Test extends ObjectStoreTest {
+class S3Test extends ObjectStoreTestCase {
public function setUp(): void {
parent::setUp();
$s3 = $this->getInstance();
@@ -52,7 +55,7 @@ class S3Test extends ObjectStoreTest {
}
protected function getInstance() {
- $config = \OC::$server->getConfig()->getSystemValue('objectstore');
+ $config = Server::get(IConfig::class)->getSystemValue('objectstore');
if (!is_array($config) || $config['class'] !== S3::class) {
$this->markTestSkipped('objectstore not configured for s3');
}
@@ -126,13 +129,13 @@ class S3Test extends ObjectStoreTest {
}
/** File size to upload in bytes */
- public function dataFileSizes() {
+ public static function dataFileSizes(): array {
return [
[1000000], [2000000], [5242879], [5242880], [5242881], [10000000]
];
}
- /** @dataProvider dataFileSizes */
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataFileSizes')]
public function testFileSizes($size): void {
if (str_starts_with(PHP_VERSION, '8.3') && getenv('CI')) {
$this->markTestSkipped('Test is unreliable and skipped on 8.3');
diff --git a/tests/lib/Files/ObjectStore/SwiftTest.php b/tests/lib/Files/ObjectStore/SwiftTest.php
index 8a34d25e57b..3f919c0dd48 100644
--- a/tests/lib/Files/ObjectStore/SwiftTest.php
+++ b/tests/lib/Files/ObjectStore/SwiftTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -8,16 +9,19 @@
namespace Test\Files\ObjectStore;
use OC\Files\ObjectStore\Swift;
+use OCP\Files\ObjectStore\IObjectStore;
+use OCP\IConfig;
+use OCP\Server;
/**
* @group PRIMARY-swift
*/
-class SwiftTest extends ObjectStoreTest {
+class SwiftTest extends ObjectStoreTestCase {
/**
- * @return \OCP\Files\ObjectStore\IObjectStore
+ * @return IObjectStore
*/
protected function getInstance() {
- $config = \OC::$server->getConfig()->getSystemValue('objectstore');
+ $config = Server::get(IConfig::class)->getSystemValue('objectstore');
if (!is_array($config) || $config['class'] !== 'OC\\Files\\ObjectStore\\Swift') {
$this->markTestSkipped('objectstore not configured for swift');
}
diff --git a/tests/lib/Files/PathVerificationTest.php b/tests/lib/Files/PathVerificationTest.php
index fcbe0a6957f..e13dbe4f207 100644
--- a/tests/lib/Files/PathVerificationTest.php
+++ b/tests/lib/Files/PathVerificationTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -10,6 +11,8 @@ namespace Test\Files;
use OC\Files\Storage\Local;
use OC\Files\View;
use OCP\Files\InvalidPathException;
+use OCP\IDBConnection;
+use OCP\Server;
/**
* Class PathVerificationTest
@@ -20,7 +23,7 @@ use OCP\Files\InvalidPathException;
*/
class PathVerificationTest extends \Test\TestCase {
/**
- * @var \OC\Files\View
+ * @var View
*/
private $view;
@@ -31,7 +34,7 @@ class PathVerificationTest extends \Test\TestCase {
public function testPathVerificationFileNameTooLong(): void {
- $this->expectException(\OCP\Files\InvalidPathException::class);
+ $this->expectException(InvalidPathException::class);
$this->expectExceptionMessage('Filename is too long');
$fileName = str_repeat('a', 500);
@@ -39,34 +42,30 @@ class PathVerificationTest extends \Test\TestCase {
}
- /**
- * @dataProvider providesEmptyFiles
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('providesEmptyFiles')]
public function testPathVerificationEmptyFileName($fileName): void {
- $this->expectException(\OCP\Files\InvalidPathException::class);
+ $this->expectException(InvalidPathException::class);
$this->expectExceptionMessage('Empty filename is not allowed');
$this->view->verifyPath('', $fileName);
}
- public function providesEmptyFiles() {
+ public static function providesEmptyFiles(): array {
return [
[''],
[' '],
];
}
- /**
- * @dataProvider providesDotFiles
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('providesDotFiles')]
public function testPathVerificationDotFiles($fileName): void {
- $this->expectException(\OCP\Files\InvalidPathException::class);
+ $this->expectException(InvalidPathException::class);
$this->expectExceptionMessage('Dot files are not allowed');
$this->view->verifyPath('', $fileName);
}
- public function providesDotFiles() {
+ public static function providesDotFiles(): array {
return [
['.'],
['..'],
@@ -79,11 +78,9 @@ class PathVerificationTest extends \Test\TestCase {
];
}
- /**
- * @dataProvider providesAstralPlane
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('providesAstralPlane')]
public function testPathVerificationAstralPlane($fileName): void {
- $connection = \OC::$server->getDatabaseConnection();
+ $connection = Server::get(IDBConnection::class);
if (!$connection->supports4ByteText()) {
$this->expectException(InvalidPathException::class);
@@ -95,7 +92,7 @@ class PathVerificationTest extends \Test\TestCase {
$this->view->verifyPath('', $fileName);
}
- public function providesAstralPlane() {
+ public static function providesAstralPlane(): array {
return [
// this is the monkey emoji - http://en.wikipedia.org/w/index.php?title=%F0%9F%90%B5&redirect=no
['🐵'],
@@ -106,9 +103,7 @@ class PathVerificationTest extends \Test\TestCase {
];
}
- /**
- * @dataProvider providesValidPosixPaths
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('providesValidPosixPaths')]
public function testPathVerificationValidPaths($fileName): void {
$storage = new Local(['datadir' => '']);
@@ -117,7 +112,7 @@ class PathVerificationTest extends \Test\TestCase {
$this->addToAssertionCount(1);
}
- public function providesValidPosixPaths() {
+ public static function providesValidPosixPaths(): array {
return [
['simple'],
['simple.txt'],
diff --git a/tests/lib/Files/Search/QueryOptimizer/CombinedTests.php b/tests/lib/Files/Search/QueryOptimizer/CombinedTests.php
index e6cb11a7eba..665224cb63e 100644
--- a/tests/lib/Files/Search/QueryOptimizer/CombinedTests.php
+++ b/tests/lib/Files/Search/QueryOptimizer/CombinedTests.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2023 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
diff --git a/tests/lib/Files/Search/QueryOptimizer/FlattenNestedBoolTest.php b/tests/lib/Files/Search/QueryOptimizer/FlattenNestedBoolTest.php
index 6777047d68b..1d43541a5a0 100644
--- a/tests/lib/Files/Search/QueryOptimizer/FlattenNestedBoolTest.php
+++ b/tests/lib/Files/Search/QueryOptimizer/FlattenNestedBoolTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2023 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
diff --git a/tests/lib/Files/Search/QueryOptimizer/MergeDistributiveOperationsTest.php b/tests/lib/Files/Search/QueryOptimizer/MergeDistributiveOperationsTest.php
index 4f933d0c371..9aaa7030aac 100644
--- a/tests/lib/Files/Search/QueryOptimizer/MergeDistributiveOperationsTest.php
+++ b/tests/lib/Files/Search/QueryOptimizer/MergeDistributiveOperationsTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2023 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
diff --git a/tests/lib/Files/Search/QueryOptimizer/OrEqualsToInTest.php b/tests/lib/Files/Search/QueryOptimizer/OrEqualsToInTest.php
index 8b1c3b992b2..d51fe3d0d16 100644
--- a/tests/lib/Files/Search/QueryOptimizer/OrEqualsToInTest.php
+++ b/tests/lib/Files/Search/QueryOptimizer/OrEqualsToInTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2023 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
diff --git a/tests/lib/Files/Search/SearchIntegrationTest.php b/tests/lib/Files/Search/SearchIntegrationTest.php
index 0ca67285fd5..e3e99bbfadd 100644
--- a/tests/lib/Files/Search/SearchIntegrationTest.php
+++ b/tests/lib/Files/Search/SearchIntegrationTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
diff --git a/tests/lib/Files/SimpleFS/SimpleFileTest.php b/tests/lib/Files/SimpleFS/SimpleFileTest.php
index d0676eae70f..6ce5ddad351 100644
--- a/tests/lib/Files/SimpleFS/SimpleFileTest.php
+++ b/tests/lib/Files/SimpleFS/SimpleFileTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
diff --git a/tests/lib/Files/SimpleFS/SimpleFolderTest.php b/tests/lib/Files/SimpleFS/SimpleFolderTest.php
index 6897aab1f02..50038b286a9 100644
--- a/tests/lib/Files/SimpleFS/SimpleFolderTest.php
+++ b/tests/lib/Files/SimpleFS/SimpleFolderTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
diff --git a/tests/lib/Files/Storage/CommonTest.php b/tests/lib/Files/Storage/CommonTest.php
index b51b35be8f9..c5ff6bb0b5f 100644
--- a/tests/lib/Files/Storage/CommonTest.php
+++ b/tests/lib/Files/Storage/CommonTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2019-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -9,10 +10,12 @@ 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;
/**
@@ -32,12 +35,12 @@ class CommonTest extends Storage {
$this->filenameValidator = $this->createMock(IFilenameValidator::class);
$this->overwriteService(IFilenameValidator::class, $this->filenameValidator);
- $this->tmpDir = \OCP\Server::get(ITempManager::class)->getTemporaryFolder();
+ $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();
}
diff --git a/tests/lib/Files/Storage/CopyDirectoryTest.php b/tests/lib/Files/Storage/CopyDirectoryTest.php
index e434c6b787f..b593b7c984f 100644
--- a/tests/lib/Files/Storage/CopyDirectoryTest.php
+++ b/tests/lib/Files/Storage/CopyDirectoryTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2019-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -7,6 +8,7 @@
namespace Test\Files\Storage;
+use OC\Files\Storage\PolyFill\CopyDirectory;
use OC\Files\Storage\Temporary;
class StorageNoRecursiveCopy extends Temporary {
@@ -19,7 +21,7 @@ class StorageNoRecursiveCopy extends Temporary {
}
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 b6d0f1aa85a..84a9816cb0c 100644
--- a/tests/lib/Files/Storage/HomeTest.php
+++ b/tests/lib/Files/Storage/HomeTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -7,20 +8,21 @@
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() {
@@ -48,21 +50,21 @@ 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();
}
diff --git a/tests/lib/Files/Storage/LocalTest.php b/tests/lib/Files/Storage/LocalTest.php
index 65bc538ef17..89449a51351 100644
--- a/tests/lib/Files/Storage/LocalTest.php
+++ b/tests/lib/Files/Storage/LocalTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -7,7 +8,13 @@
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
@@ -25,12 +32,12 @@ 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();
}
@@ -54,19 +61,19 @@ class LocalTest extends Storage {
public function testInvalidArgumentsEmptyArray(): void {
$this->expectException(\InvalidArgumentException::class);
- new \OC\Files\Storage\Local([]);
+ new Local([]);
}
public function testInvalidArgumentsNoArray(): void {
$this->expectException(\InvalidArgumentException::class);
- new \OC\Files\Storage\Local([]);
+ new Local([]);
}
public function testDisallowSymlinksOutsideDatadir(): void {
- $this->expectException(\OCP\Files\ForbiddenException::class);
+ $this->expectException(ForbiddenException::class);
$subDir1 = $this->tmpDir . 'sub1';
$subDir2 = $this->tmpDir . 'sub2';
@@ -76,7 +83,7 @@ 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');
}
@@ -90,7 +97,7 @@ 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);
@@ -128,12 +135,12 @@ class LocalTest extends Storage {
}
public function testUnavailableExternal(): void {
- $this->expectException(\OCP\Files\StorageNotAvailableException::class);
- $this->instance = new \OC\Files\Storage\Local(['datadir' => $this->tmpDir . '/unexist', 'isExternal' => true]);
+ $this->expectException(StorageNotAvailableException::class);
+ $this->instance = new Local(['datadir' => $this->tmpDir . '/unexist', 'isExternal' => true]);
}
public function testUnavailableNonExternal(): void {
- $this->instance = new \OC\Files\Storage\Local(['datadir' => $this->tmpDir . '/unexist']);
+ $this->instance = new Local(['datadir' => $this->tmpDir . '/unexist']);
// no exception thrown
$this->assertNotNull($this->instance);
}
diff --git a/tests/lib/Files/Storage/Storage.php b/tests/lib/Files/Storage/Storage.php
index 36d70965848..51bb5b7c8ad 100644
--- a/tests/lib/Files/Storage/Storage.php
+++ b/tests/lib/Files/Storage/Storage.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -8,6 +9,7 @@
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;
@@ -49,9 +51,7 @@ abstract class Storage extends \Test\TestCase {
$this->assertTrue($this->instance->test());
}
- /**
- * @dataProvider directoryProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('directoryProvider')]
public function testDirectories($directory): void {
$this->assertFalse($this->instance->file_exists('/' . $directory));
@@ -108,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'],
@@ -119,7 +119,7 @@ abstract class Storage extends \Test\TestCase {
];
}
- public function directoryProvider() {
+ public static function directoryProvider(): array {
return [
['folder'],
[' folder'],
@@ -130,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
@@ -142,9 +142,8 @@ abstract class Storage extends \Test\TestCase {
/**
* test the various uses of file_get_contents and file_put_contents
- *
- * @dataProvider loremFileProvider
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('loremFileProvider')]
public function testGetPutContents($sourceFile): void {
$sourceText = file_get_contents($sourceFile);
@@ -179,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'],
@@ -210,9 +209,7 @@ abstract class Storage extends \Test\TestCase {
);
}
- /**
- * @dataProvider copyAndMoveProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('copyAndMoveProvider')]
public function testCopy($source, $target): void {
$this->initSourceAndTarget($source);
@@ -223,9 +220,7 @@ abstract class Storage extends \Test\TestCase {
$this->assertTrue($this->instance->file_exists($source), $source . ' was deleted');
}
- /**
- * @dataProvider copyAndMoveProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('copyAndMoveProvider')]
public function testMove($source, $target): void {
$this->initSourceAndTarget($source);
@@ -237,9 +232,7 @@ abstract class Storage extends \Test\TestCase {
$this->assertSameAsLorem($target);
}
- /**
- * @dataProvider copyAndMoveProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('copyAndMoveProvider')]
public function testCopyOverwrite($source, $target): void {
$this->initSourceAndTarget($source, $target);
@@ -251,9 +244,7 @@ abstract class Storage extends \Test\TestCase {
$this->assertSameAsLorem($source);
}
- /**
- * @dataProvider copyAndMoveProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('copyAndMoveProvider')]
public function testMoveOverwrite($source, $target): void {
$this->initSourceAndTarget($source, $target);
@@ -327,7 +318,7 @@ abstract class Storage extends \Test\TestCase {
* no change.
*/
public function testCheckUpdate(): void {
- if ($this->instance instanceof \OC\Files\Storage\Wrapper\Wrapper) {
+ if ($this->instance instanceof Wrapper) {
$this->markTestSkipped('Cannot test update check on wrappers');
}
$textFile = \OC::$SERVERROOT . '/tests/data/lorem.txt';
@@ -350,9 +341,7 @@ abstract class Storage extends \Test\TestCase {
$this->assertFalse($this->instance->file_exists('/lorem.txt'));
}
- /**
- * @dataProvider fileNameProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('fileNameProvider')]
public function testFOpen($fileName): void {
$textFile = \OC::$SERVERROOT . '/tests/data/lorem.txt';
@@ -414,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'],
@@ -422,9 +411,7 @@ abstract class Storage extends \Test\TestCase {
];
}
- /**
- * @dataProvider hashProvider
- */
+ #[\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'));
@@ -557,7 +544,7 @@ 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'));
}
@@ -578,9 +565,7 @@ abstract class Storage extends \Test\TestCase {
$this->assertFalse($this->instance->instanceOfStorage('\OC'));
}
- /**
- * @dataProvider copyAndMoveProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('copyAndMoveProvider')]
public function testCopyFromSameStorage($source, $target): void {
$this->initSourceAndTarget($source);
diff --git a/tests/lib/Files/Storage/StorageFactoryTest.php b/tests/lib/Files/Storage/StorageFactoryTest.php
index 83e8a7bf6eb..0bb9cbf5824 100644
--- a/tests/lib/Files/Storage/StorageFactoryTest.php
+++ b/tests/lib/Files/Storage/StorageFactoryTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2019-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -8,6 +9,7 @@
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\IStorage;
@@ -26,7 +28,7 @@ class DummyWrapper extends Wrapper {
class StorageFactoryTest extends TestCase {
public function testSimpleWrapper(): void {
- $instance = new \OC\Files\Storage\StorageFactory();
+ $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,7 +41,7 @@ class StorageFactoryTest extends TestCase {
}
public function testRemoveWrapper(): void {
- $instance = new \OC\Files\Storage\StorageFactory();
+ $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,7 +52,7 @@ class StorageFactoryTest extends TestCase {
}
public function testWrapperPriority(): void {
- $instance = new \OC\Files\Storage\StorageFactory();
+ $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/StoragesTest.php b/tests/lib/Files/Storage/StoragesTestCase.php
index 3f8198d331d..565ff1ddfda 100644
--- a/tests/lib/Files/Storage/StoragesTest.php
+++ b/tests/lib/Files/Storage/StoragesTestCase.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -7,16 +8,17 @@
namespace Test\Files\Storage;
+use OC\Files\Storage\Storage;
use Test\TestCase;
-abstract class StoragesTest extends TestCase {
+abstract class StoragesTestCase extends TestCase {
/**
- * @var \OC\Files\Storage\Storage
+ * @var Storage
*/
protected $storage1;
/**
- * @var \OC\Files\Storage\Storage
+ * @var Storage
*/
protected $storage2;
diff --git a/tests/lib/Files/Storage/Wrapper/AvailabilityTest.php b/tests/lib/Files/Storage/Wrapper/AvailabilityTest.php
index 29277772358..d890081cbb6 100644
--- a/tests/lib/Files/Storage/Wrapper/AvailabilityTest.php
+++ b/tests/lib/Files/Storage/Wrapper/AvailabilityTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2019-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -53,7 +54,7 @@ class AvailabilityTest extends \Test\TestCase {
*
*/
public function testUnavailable(): void {
- $this->expectException(\OCP\Files\StorageNotAvailableException::class);
+ $this->expectException(StorageNotAvailableException::class);
$this->storage->expects($this->once())
->method('getAvailability')
@@ -82,7 +83,7 @@ class AvailabilityTest extends \Test\TestCase {
];
$this->storage->expects($this->exactly(2))
->method('setAvailability')
- ->willReturnCallback(function ($value) use (&$calls) {
+ ->willReturnCallback(function ($value) use (&$calls): void {
$expected = array_shift($calls);
$this->assertEquals($expected, $value);
});
@@ -97,7 +98,7 @@ class AvailabilityTest extends \Test\TestCase {
*
*/
public function testAvailableThrowStorageNotAvailable(): void {
- $this->expectException(\OCP\Files\StorageNotAvailableException::class);
+ $this->expectException(StorageNotAvailableException::class);
$this->storage->expects($this->once())
->method('getAvailability')
@@ -106,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));
@@ -148,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 d8b03a891c2..cb6b6de0fb7 100644
--- a/tests/lib/Files/Storage/Wrapper/EncodingTest.php
+++ b/tests/lib/Files/Storage/Wrapper/EncodingTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2019-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -7,19 +8,22 @@
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
]);
}
@@ -29,42 +33,38 @@ 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
- */
+ #[\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
- */
+ #[\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');
@@ -73,9 +73,7 @@ class EncodingTest extends \Test\Files\Storage\Storage {
$this->assertEquals('bar', $data);
}
- /**
- * @dataProvider accessNameProvider
- */
+ #[\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');
@@ -86,17 +84,13 @@ class EncodingTest extends \Test\Files\Storage\Storage {
$this->assertFalse($this->sourceStorage->file_exists(self::NFC_NAME));
}
- /**
- * @dataProvider accessNameProvider
- */
+ #[\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
- */
+ #[\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));
@@ -110,7 +104,7 @@ class EncodingTest extends \Test\Files\Storage\Storage {
$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],
@@ -118,9 +112,7 @@ class EncodingTest extends \Test\Files\Storage\Storage {
];
}
- /**
- * @dataProvider encodedDirectoriesProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('encodedDirectoriesProvider')]
public function testOperationInsideDirectory($sourceDir, $accessDir): void {
$this->sourceStorage->mkdir($sourceDir);
$this->instance->file_put_contents($accessDir . '/test.txt', 'bar');
@@ -150,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'],
@@ -159,9 +151,7 @@ class EncodingTest extends \Test\Files\Storage\Storage {
];
}
- /**
- * @dataProvider sourceAndTargetDirectoryProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('sourceAndTargetDirectoryProvider')]
public function testCopyAndMoveEncodedFolder($sourceDir, $targetDir): void {
$this->sourceStorage->mkdir($sourceDir);
$this->sourceStorage->mkdir($targetDir);
@@ -179,9 +169,7 @@ class EncodingTest extends \Test\Files\Storage\Storage {
$this->assertEquals('bar', $this->instance->file_get_contents(self::NFC_NAME . '2/test2.txt'));
}
- /**
- * @dataProvider sourceAndTargetDirectoryProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('sourceAndTargetDirectoryProvider')]
public function testCopyAndMoveFromStorageEncodedFolder($sourceDir, $targetDir): void {
$this->sourceStorage->mkdir($sourceDir);
$this->sourceStorage->mkdir($targetDir);
diff --git a/tests/lib/Files/Storage/Wrapper/EncryptionTest.php b/tests/lib/Files/Storage/Wrapper/EncryptionTest.php
index bb3df36dec2..3e643714300 100644
--- a/tests/lib/Files/Storage/Wrapper/EncryptionTest.php
+++ b/tests/lib/Files/Storage/Wrapper/EncryptionTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -8,10 +9,8 @@
namespace Test\Files\Storage\Wrapper;
use Exception;
-use OC;
use OC\Encryption\Exceptions\ModuleDoesNotExistsException;
use OC\Encryption\File;
-use OC\Encryption\Update;
use OC\Encryption\Util;
use OC\Files\Cache\Cache;
use OC\Files\Cache\CacheEntry;
@@ -29,6 +28,8 @@ 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 Test\Files\Storage\Storage;
@@ -46,7 +47,6 @@ class EncryptionTest extends Storage {
private Util&MockObject $util;
private \OC\Encryption\Manager&MockObject $encryptionManager;
private IEncryptionModule&MockObject $encryptionModule;
- private Update&MockObject $update;
private Cache&MockObject $cache;
private LoggerInterface&MockObject $logger;
private File&MockObject $file;
@@ -62,9 +62,9 @@ class EncryptionTest extends Storage {
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')
@@ -78,8 +78,8 @@ class EncryptionTest extends Storage {
->disableOriginalConstructor()
->getMock();
- $this->util = $this->getMockBuilder('\OC\Encryption\Util')
- ->setMethods(['getUidAndFilename', 'isFile', 'isExcluded', 'stripPartialFileExtension'])
+ $this->util = $this->getMockBuilder(Util::class)
+ ->onlyMethods(['getUidAndFilename', 'isFile', 'isExcluded', 'stripPartialFileExtension'])
->setConstructorArgs([new View(), new Manager(
$this->config,
$this->createMock(ICacheFactory::class),
@@ -98,9 +98,9 @@ class EncryptionTest extends Storage {
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([]);
@@ -108,15 +108,11 @@ class EncryptionTest extends Storage {
$this->sourceStorage = new Temporary([]);
- $this->keyStore = $this->getMockBuilder('\OC\Encryption\Keys\Storage')
- ->disableOriginalConstructor()->getMock();
+ $this->keyStore = $this->createMock(\OC\Encryption\Keys\Storage::class);
- $this->update = $this->getMockBuilder('\OC\Encryption\Update')
- ->disableOriginalConstructor()->getMock();
-
- $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) {
@@ -155,12 +151,11 @@ class EncryptionTest extends Storage {
$this->file,
null,
$this->keyStore,
- $this->update,
$this->mountManager,
$this->arrayCache
]
)
- ->setMethods(['getMetaData', 'getCache', 'getEncryptionModule'])
+ ->onlyMethods(['getMetaData', 'getCache', 'getEncryptionModule'])
->getMock();
$this->instance->expects($this->any())
@@ -181,7 +176,7 @@ class EncryptionTest extends Storage {
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');
@@ -199,7 +194,6 @@ class EncryptionTest extends Storage {
}
/**
- * @dataProvider dataTestGetMetaData
*
* @param string $path
* @param array $metaData
@@ -208,6 +202,7 @@ class EncryptionTest extends Storage {
* @param int $storedUnencryptedSize
* @param array $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();
@@ -237,12 +232,11 @@ class EncryptionTest extends Storage {
$this->file,
null,
$this->keyStore,
- $this->update,
$this->mountManager,
$this->arrayCache,
]
)
- ->setMethods(['getCache', 'verifyUnencryptedSize'])
+ ->onlyMethods(['getCache', 'verifyUnencryptedSize'])
->getMock();
if ($unencryptedSizeSet) {
@@ -285,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],
@@ -316,12 +310,11 @@ class EncryptionTest extends Storage {
$this->file,
null,
$this->keyStore,
- $this->update,
$this->mountManager,
$this->arrayCache,
]
)
- ->setMethods(['getCache', 'verifyUnencryptedSize'])
+ ->onlyMethods(['getCache', 'verifyUnencryptedSize'])
->getMock();
$this->instance->expects($this->any())->method('getCache')->willReturn($cache);
@@ -335,13 +328,13 @@ class EncryptionTest extends Storage {
}
/**
- * @dataProvider dataTestVerifyUnencryptedSize
*
* @param int $encryptedSize
* @param int $unencryptedSize
* @param bool $failure
* @param int $expected
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataTestVerifyUnencryptedSize')]
public function testVerifyUnencryptedSize($encryptedSize, $unencryptedSize, $failure, $expected): void {
$sourceStorage = $this->getMockBuilder('\OC\Files\Storage\Storage')
->disableOriginalConstructor()->getMock();
@@ -361,12 +354,11 @@ class EncryptionTest extends Storage {
$this->file,
null,
$this->keyStore,
- $this->update,
$this->mountManager,
$this->arrayCache,
]
)
- ->setMethods(['fixUnencryptedSize'])
+ ->onlyMethods(['fixUnencryptedSize'])
->getMock();
$sourceStorage->expects($this->once())->method('filesize')->willReturn($encryptedSize);
@@ -389,7 +381,7 @@ class EncryptionTest extends Storage {
);
}
- public function dataTestVerifyUnencryptedSize() {
+ public static function dataTestVerifyUnencryptedSize(): array {
return [
[120, 80, false, 80],
[120, 120, false, 80],
@@ -399,13 +391,13 @@ 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,
@@ -444,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],
@@ -461,13 +453,13 @@ class EncryptionTest extends Storage {
}
/**
- * @dataProvider dataTestRmdir
*
* @param string $path
* @param boolean $rmdirResult
* @param boolean $isExcluded
* @param boolean $encryptionEnabled
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataTestRmdir')]
public function testRmdir($path, $rmdirResult, $isExcluded, $encryptionEnabled): void {
$sourceStorage = $this->getMockBuilder('\OC\Files\Storage\Storage')
->disableOriginalConstructor()->getMock();
@@ -491,7 +483,6 @@ class EncryptionTest extends Storage {
$this->file,
null,
$this->keyStore,
- $this->update,
$this->mountManager,
$this->arrayCache,
);
@@ -506,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],
@@ -520,11 +511,11 @@ class EncryptionTest extends Storage {
}
/**
- * @dataProvider dataTestCopyKeys
*
* @param boolean $excluded
* @param boolean $expected
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataTestCopyKeys')]
public function testCopyKeys($excluded, $expected): void {
$this->util->expects($this->once())
->method('isExcluded')
@@ -541,7 +532,7 @@ class EncryptionTest extends Storage {
);
}
- public function dataTestCopyKeys() {
+ public static function dataTestCopyKeys(): array {
return [
[true, false],
[false, true],
@@ -549,12 +540,12 @@ class EncryptionTest extends Storage {
}
/**
- * @dataProvider dataTestGetHeader
*
* @param string $path
* @param bool $strippedPathExists
* @param string $strippedPath
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataTestGetHeader')]
public function testGetHeader($path, $strippedPathExists, $strippedPath): void {
$sourceStorage = $this->getMockBuilder('\OC\Files\Storage\Storage')
->disableOriginalConstructor()->getMock();
@@ -598,12 +589,11 @@ class EncryptionTest extends Storage {
$this->file,
null,
$this->keyStore,
- $this->update,
$this->mountManager,
$this->arrayCache,
]
)
- ->setMethods(['getCache', 'readFirstBlock'])
+ ->onlyMethods(['getCache', 'readFirstBlock'])
->getMock();
$instance->method('getCache')->willReturn($cache);
@@ -629,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'],
@@ -642,11 +632,10 @@ class EncryptionTest extends Storage {
/**
* test if getHeader adds the default module correctly to the header for
* legacy files
- *
- * @dataProvider dataTestGetHeaderAddLegacyModule
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataTestGetHeaderAddLegacyModule')]
public function testGetHeaderAddLegacyModule($header, $isEncrypted, $strippedPathExists, $expected): void {
- $sourceStorage = $this->getMockBuilder('\OC\Files\Storage\Storage')
+ $sourceStorage = $this->getMockBuilder(\OC\Files\Storage\Storage::class)
->disableOriginalConstructor()->getMock();
$sourceStorage->expects($this->once())
@@ -654,7 +643,7 @@ class EncryptionTest extends Storage {
->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,
@@ -669,8 +658,7 @@ class EncryptionTest extends Storage {
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) {
@@ -692,12 +680,11 @@ class EncryptionTest extends Storage {
$this->file,
null,
$this->keyStore,
- $this->update,
$this->mountManager,
$this->arrayCache,
]
)
- ->setMethods(['readFirstBlock', 'getCache'])
+ ->onlyMethods(['readFirstBlock', 'getCache'])
->getMock();
$instance->method('readFirstBlock')->willReturn('');
@@ -713,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, []],
@@ -722,7 +709,7 @@ class EncryptionTest extends Storage {
];
}
- public function dataCopyBetweenStorage() {
+ public static function dataCopyBetweenStorage(): array {
return [
[true, true, true],
[true, false, false],
@@ -740,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')
@@ -774,12 +761,12 @@ class EncryptionTest extends Storage {
}
/**
- * @dataProvider dataCopyBetweenStorage
*
* @param bool $encryptionEnabled
* @param bool $mountPointEncryptionEnabled
* @param bool $expectedEncrypted
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataCopyBetweenStorage')]
public function testCopyBetweenStorage($encryptionEnabled, $mountPointEncryptionEnabled, $expectedEncrypted): void {
$storage2 = $this->createMock(\OC\Files\Storage\Storage::class);
@@ -789,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')
@@ -834,13 +821,13 @@ class EncryptionTest extends Storage {
}
/**
- * @dataProvider dataTestCopyBetweenStorageVersions
*
* @param string $sourceInternalPath
* @param string $targetInternalPath
* @param bool $copyResult
* @param bool $encrypted
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataTestCopyBetweenStorageVersions')]
public function testCopyBetweenStorageVersions($sourceInternalPath, $targetInternalPath, $copyResult, $encrypted): void {
$sourceStorage = $this->createMock(\OC\Files\Storage\Storage::class);
@@ -867,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')
@@ -914,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],
@@ -929,17 +915,17 @@ class EncryptionTest extends Storage {
}
/**
- * @dataProvider dataTestIsVersion
* @param string $path
* @param bool $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],
@@ -951,13 +937,13 @@ 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,
@@ -968,7 +954,6 @@ class EncryptionTest extends Storage {
$util = $this->createMock(Util::class);
$fileHelper = $this->createMock(IFile::class);
$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);
@@ -986,12 +971,11 @@ class EncryptionTest extends Storage {
$fileHelper,
null,
$keyStorage,
- $update,
$mountManager,
$arrayCache
]
)
- ->setMethods(['getFullPath', 'getEncryptionModule'])
+ ->onlyMethods(['getFullPath', 'getEncryptionModule'])
->getMock();
if ($encryptionModule === true) {
@@ -1033,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 fbc4e1d09ee..0043e37ba33 100644
--- a/tests/lib/Files/Storage/Wrapper/JailTest.php
+++ b/tests/lib/Files/Storage/Wrapper/JailTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2019-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -7,17 +8,21 @@
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,7 +33,7 @@ class JailTest extends \Test\Files\Storage\Storage {
$contents = [];
$dh = $this->sourceStorage->opendir('');
while (($file = readdir($dh)) !== false) {
- if (!\OC\Files\Filesystem::isIgnoredDir($file)) {
+ if (!Filesystem::isIgnoredDir($file)) {
$contents[] = $file;
}
}
diff --git a/tests/lib/Files/Storage/Wrapper/KnownMtimeTest.php b/tests/lib/Files/Storage/Wrapper/KnownMtimeTest.php
index bbeb48c5cef..b1b5582b4ed 100644
--- a/tests/lib/Files/Storage/Wrapper/KnownMtimeTest.php
+++ b/tests/lib/Files/Storage/Wrapper/KnownMtimeTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2023 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
diff --git a/tests/lib/Files/Storage/Wrapper/PermissionsMaskTest.php b/tests/lib/Files/Storage/Wrapper/PermissionsMaskTest.php
index 5c0a035d094..a2f3460c58c 100644
--- a/tests/lib/Files/Storage/Wrapper/PermissionsMaskTest.php
+++ b/tests/lib/Files/Storage/Wrapper/PermissionsMaskTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -7,6 +8,8 @@
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;
@@ -16,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);
}
@@ -32,7 +35,7 @@ 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
]);
@@ -127,7 +130,7 @@ class PermissionsMaskTest extends \Test\Files\Storage\Storage {
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
]);
@@ -149,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);
@@ -167,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 f07e6021e4e..2878fe6ca92 100644
--- a/tests/lib/Files/Storage/Wrapper/QuotaTest.php
+++ b/tests/lib/Files/Storage/Wrapper/QuotaTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -10,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
@@ -29,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();
}
@@ -43,10 +46,10 @@ 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(): void {
@@ -76,7 +79,7 @@ class QuotaTest extends \Test\Files\Storage\Storage {
public function testFreeSpaceWithUnknownDiskSpace(): void {
$storage = $this->getMockBuilder(Local::class)
- ->setMethods(['free_space'])
+ ->onlyMethods(['free_space'])
->setConstructorArgs([['datadir' => $this->tmpDir]])
->getMock();
$storage->expects($this->any())
@@ -84,7 +87,7 @@ 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]
);
@@ -132,14 +135,14 @@ class QuotaTest extends \Test\Files\Storage\Storage {
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'));
}
@@ -197,7 +200,7 @@ 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(''));
}
diff --git a/tests/lib/Files/Storage/Wrapper/WrapperTest.php b/tests/lib/Files/Storage/Wrapper/WrapperTest.php
index 1d0f41bf3ed..60f139450c7 100644
--- a/tests/lib/Files/Storage/Wrapper/WrapperTest.php
+++ b/tests/lib/Files/Storage/Wrapper/WrapperTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2019-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -7,6 +8,12 @@
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
@@ -16,13 +23,13 @@ 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();
}
diff --git a/tests/lib/Files/Stream/DummyEncryptionWrapper.php b/tests/lib/Files/Stream/DummyEncryptionWrapper.php
index 211050905bd..89904e6de73 100644
--- a/tests/lib/Files/Stream/DummyEncryptionWrapper.php
+++ b/tests/lib/Files/Stream/DummyEncryptionWrapper.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2019-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -7,7 +8,9 @@
namespace Test\Files\Stream;
-class DummyEncryptionWrapper extends \OC\Files\Stream\Encryption {
+use OC\Files\Stream\Encryption;
+
+class DummyEncryptionWrapper extends Encryption {
/**
* simulate a non-seekable stream wrapper by always return false
*
diff --git a/tests/lib/Files/Stream/EncryptionTest.php b/tests/lib/Files/Stream/EncryptionTest.php
index 36e72ea764a..62eaab3cc7e 100644
--- a/tests/lib/Files/Stream/EncryptionTest.php
+++ b/tests/lib/Files/Stream/EncryptionTest.php
@@ -9,8 +9,12 @@ declare(strict_types=1);
*/
namespace Test\Files\Stream;
+use OC\Encryption\File;
+use OC\Encryption\Util;
use OC\Files\Cache\CacheEntry;
+use OC\Files\Storage\Storage;
use OC\Files\Storage\Wrapper\Wrapper;
+use OC\Files\Stream\Encryption;
use OC\Files\View;
use OC\Memcache\ArrayCache;
use OCP\Encryption\IEncryptionModule;
@@ -53,11 +57,11 @@ class EncryptionTest extends \Test\TestCase {
->getMock();
$file = $this->getMockBuilder('\OC\Encryption\File')
->disableOriginalConstructor()
- ->setMethods(['getAccessList'])
+ ->onlyMethods(['getAccessList'])
->getMock();
$file->expects($this->any())->method('getAccessList')->willReturn([]);
$util = $this->getMockBuilder('\OC\Encryption\Util')
- ->setMethods(['getUidAndFilename'])
+ ->onlyMethods(['getUidAndFilename'])
->setConstructorArgs([new View(), new \OC\User\Manager(
$config,
$this->createMock(ICacheFactory::class),
@@ -97,9 +101,7 @@ class EncryptionTest extends \Test\TestCase {
);
}
- /**
- * @dataProvider dataProviderStreamOpen()
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataProviderStreamOpen')]
public function testStreamOpen(
$isMasterKeyUsed,
$mode,
@@ -111,20 +113,17 @@ class EncryptionTest extends \Test\TestCase {
$expectedReadOnly,
): void {
// build mocks
- $encryptionModuleMock = $this->getMockBuilder('\OCP\Encryption\IEncryptionModule')
- ->disableOriginalConstructor()->getMock();
+ $encryptionModuleMock = $this->createMock(IEncryptionModule::class);
$encryptionModuleMock->expects($this->any())->method('needDetailedAccessList')->willReturn(!$isMasterKeyUsed);
$encryptionModuleMock->expects($this->once())
->method('getUnencryptedBlockSize')->willReturn(99);
$encryptionModuleMock->expects($this->once())
->method('begin')->willReturn([]);
- $storageMock = $this->getMockBuilder('\OC\Files\Storage\Storage')
- ->disableOriginalConstructor()->getMock();
+ $storageMock = $this->createMock(Storage::class);
$storageMock->expects($this->once())->method('file_exists')->willReturn($fileExists);
- $fileMock = $this->getMockBuilder('\OC\Encryption\File')
- ->disableOriginalConstructor()->getMock();
+ $fileMock = $this->createMock(File::class);
if ($isMasterKeyUsed) {
$fileMock->expects($this->never())->method('getAccessList');
} else {
@@ -134,18 +133,20 @@ class EncryptionTest extends \Test\TestCase {
return [];
});
}
- $utilMock = $this->getMockBuilder('\OC\Encryption\Util')
+ $utilMock = $this->getMockBuilder(Util::class)
->disableOriginalConstructor()->getMock();
$utilMock->expects($this->any())
->method('getHeaderSize')
->willReturn(8192);
// get a instance of the stream wrapper
- $streamWrapper = $this->getMockBuilder('\OC\Files\Stream\Encryption')
- ->setMethods(['loadContext', 'writeHeader', 'skipHeader'])->disableOriginalConstructor()->getMock();
+ $streamWrapper = $this->getMockBuilder(Encryption::class)
+ ->onlyMethods(['loadContext', 'writeHeader', 'skipHeader'])
+ ->disableOriginalConstructor()
+ ->getMock();
// set internal properties of the stream wrapper
- $stream = new \ReflectionClass('\OC\Files\Stream\Encryption');
+ $stream = new \ReflectionClass(Encryption::class);
$encryptionModule = $stream->getProperty('encryptionModule');
$encryptionModule->setAccessible(true);
$encryptionModule->setValue($streamWrapper, $encryptionModuleMock);
@@ -195,7 +196,7 @@ class EncryptionTest extends \Test\TestCase {
$readOnly->setAccessible(false);
}
- public function dataProviderStreamOpen() {
+ public static function dataProviderStreamOpen(): array {
return [
[false, 'r', '/foo/bar/test.txt', true, '/foo/bar/test.txt', null, null, true],
[false, 'r', '/foo/bar/test.txt', false, '/foo/bar', null, null, true],
@@ -266,7 +267,7 @@ class EncryptionTest extends \Test\TestCase {
unlink($fileName);
}
- public function dataFilesProvider() {
+ public static function dataFilesProvider(): array {
return [
['lorem-big.txt'],
['block-aligned.txt'],
@@ -274,9 +275,7 @@ class EncryptionTest extends \Test\TestCase {
];
}
- /**
- * @dataProvider dataFilesProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataFilesProvider')]
public function testWriteReadBigFile($testFile): void {
$expectedData = file_get_contents(\OC::$SERVERROOT . '/tests/data/' . $testFile);
// write it
@@ -311,13 +310,15 @@ class EncryptionTest extends \Test\TestCase {
/**
* simulate a non-seekable storage
- *
- * @dataProvider dataFilesProvider
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataFilesProvider')]
public function testWriteToNonSeekableStorage($testFile): void {
- $wrapper = $this->getMockBuilder('\OC\Files\Stream\Encryption')
- ->setMethods(['parentSeekStream'])->getMock();
- $wrapper->expects($this->any())->method('parentSeekStream')->willReturn(false);
+ $wrapper = $this->getMockBuilder(Encryption::class)
+ ->onlyMethods(['parentStreamSeek'])
+ ->getMock();
+ $wrapper->expects($this->any())
+ ->method('parentStreamSeek')
+ ->willReturn(false);
$expectedData = file_get_contents(\OC::$SERVERROOT . '/tests/data/' . $testFile);
// write it
@@ -351,9 +352,9 @@ class EncryptionTest extends \Test\TestCase {
}
protected function buildMockModule(): IEncryptionModule&MockObject {
- $encryptionModule = $this->getMockBuilder('\OCP\Encryption\IEncryptionModule')
+ $encryptionModule = $this->getMockBuilder(IEncryptionModule::class)
->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();
$encryptionModule->expects($this->any())->method('getId')->willReturn('UNIT_TEST_MODULE');
diff --git a/tests/lib/Files/Stream/HashWrapperTest.php b/tests/lib/Files/Stream/HashWrapperTest.php
index ee50fe3b13a..459bc5c4318 100644
--- a/tests/lib/Files/Stream/HashWrapperTest.php
+++ b/tests/lib/Files/Stream/HashWrapperTest.php
@@ -12,9 +12,7 @@ use OC\Files\Stream\HashWrapper;
use Test\TestCase;
class HashWrapperTest extends TestCase {
- /**
- * @dataProvider hashProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('hashProvider')]
public function testHashStream($data, string $algo, string $hash): void {
if (!is_resource($data)) {
$tmpData = fopen('php://temp', 'r+');
@@ -25,13 +23,13 @@ class HashWrapperTest extends TestCase {
$data = $tmpData;
}
- $wrapper = HashWrapper::wrap($data, $algo, function ($result) use ($hash) {
+ $wrapper = HashWrapper::wrap($data, $algo, function ($result) use ($hash): void {
$this->assertEquals($hash, $result);
});
stream_get_contents($wrapper);
}
- public function hashProvider() {
+ public static function hashProvider(): array {
return [
['foo', 'md5', 'acbd18db4cc2f85cedef654fccc4a4d8'],
['foo', 'sha1', '0beec7b5ea3f0fdbc95d0dd47f3c5bc275da8a33'],
diff --git a/tests/lib/Files/Stream/QuotaTest.php b/tests/lib/Files/Stream/QuotaTest.php
index 2df767d6c60..4248d14f5a1 100644
--- a/tests/lib/Files/Stream/QuotaTest.php
+++ b/tests/lib/Files/Stream/QuotaTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2017-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -7,6 +8,8 @@
namespace Test\Files\Stream;
+use OC\Files\Stream\Quota;
+
class QuotaTest extends \Test\TestCase {
/**
* @param string $mode
@@ -15,7 +18,7 @@ class QuotaTest extends \Test\TestCase {
*/
protected function getStream($mode, $limit) {
$source = fopen('php://temp', $mode);
- return \OC\Files\Stream\Quota::wrap($source, $limit);
+ return Quota::wrap($source, $limit);
}
public function testWriteEnoughSpace(): void {
@@ -60,7 +63,7 @@ class QuotaTest extends \Test\TestCase {
public function testWriteNotEnoughSpaceExistingStream(): void {
$source = fopen('php://temp', 'w+');
fwrite($source, 'foobar');
- $stream = \OC\Files\Stream\Quota::wrap($source, 3);
+ $stream = Quota::wrap($source, 3);
$this->assertEquals(3, fwrite($stream, 'foobar'));
rewind($stream);
$this->assertEquals('foobarfoo', fread($stream, 100));
@@ -69,7 +72,7 @@ class QuotaTest extends \Test\TestCase {
public function testWriteNotEnoughSpaceExistingStreamRewind(): void {
$source = fopen('php://temp', 'w+');
fwrite($source, 'foobar');
- $stream = \OC\Files\Stream\Quota::wrap($source, 3);
+ $stream = Quota::wrap($source, 3);
rewind($stream);
$this->assertEquals(6, fwrite($stream, 'qwerty'));
rewind($stream);
diff --git a/tests/lib/Files/Type/DetectionTest.php b/tests/lib/Files/Type/DetectionTest.php
index 1005f12786a..c30b21de401 100644
--- a/tests/lib/Files/Type/DetectionTest.php
+++ b/tests/lib/Files/Type/DetectionTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -9,6 +10,7 @@ namespace Test\Files\Type;
use OC\Files\Type\Detection;
use OCP\IURLGenerator;
+use OCP\Server;
use Psr\Log\LoggerInterface;
class DetectionTest extends \Test\TestCase {
@@ -18,8 +20,8 @@ class DetectionTest extends \Test\TestCase {
protected function setUp(): void {
parent::setUp();
$this->detection = new Detection(
- \OC::$server->getURLGenerator(),
- \OC::$server->get(LoggerInterface::class),
+ Server::get(IURLGenerator::class),
+ Server::get(LoggerInterface::class),
\OC::$SERVERROOT . '/config/',
\OC::$SERVERROOT . '/resources/config/'
);
@@ -45,11 +47,11 @@ class DetectionTest extends \Test\TestCase {
}
/**
- * @dataProvider dataDetectPath
*
* @param string $path
* @param string $expected
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataDetectPath')]
public function testDetectPath(string $path, string $expected): void {
$this->assertEquals($expected, $this->detection->detectPath($path));
}
@@ -65,11 +67,11 @@ class DetectionTest extends \Test\TestCase {
}
/**
- * @dataProvider dataDetectContent
*
* @param string $path
* @param string $expected
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataDetectContent')]
public function testDetectContent(string $path, string $expected): void {
$this->assertEquals($expected, $this->detection->detectContent(\OC::$SERVERROOT . '/tests/data' . $path));
}
@@ -85,11 +87,11 @@ class DetectionTest extends \Test\TestCase {
}
/**
- * @dataProvider dataDetect
*
* @param string $path
* @param string $expected
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataDetect')]
public function testDetect(string $path, string $expected): void {
$this->assertEquals($expected, $this->detection->detect(\OC::$SERVERROOT . '/tests/data' . $path));
}
@@ -109,11 +111,11 @@ class DetectionTest extends \Test\TestCase {
}
/**
- * @dataProvider dataMimeTypeCustom
*
* @param string $ext
* @param string $mime
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataMimeTypeCustom')]
public function testDetectMimeTypeCustom(string $ext, string $mime): void {
$confDir = sys_get_temp_dir();
file_put_contents($confDir . '/mimetypemapping.dist.json', json_encode([]));
@@ -143,11 +145,11 @@ class DetectionTest extends \Test\TestCase {
}
/**
- * @dataProvider dataGetSecureMimeType
*
* @param string $mimeType
* @param string $expected
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataGetSecureMimeType')]
public function testGetSecureMimeType(string $mimeType, string $expected): void {
$this->assertEquals($expected, $this->detection->getSecureMimeType($mimeType));
}
diff --git a/tests/lib/Files/Type/LoaderTest.php b/tests/lib/Files/Type/LoaderTest.php
index 6eaf6ac2013..44745a50dc0 100644
--- a/tests/lib/Files/Type/LoaderTest.php
+++ b/tests/lib/Files/Type/LoaderTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2019-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -9,6 +10,7 @@ namespace Test\Files\Type;
use OC\Files\Type\Loader;
use OCP\IDBConnection;
+use OCP\Server;
use Test\TestCase;
class LoaderTest extends TestCase {
@@ -16,7 +18,7 @@ class LoaderTest extends TestCase {
protected Loader $loader;
protected function setUp(): void {
- $this->db = \OC::$server->get(IDBConnection::class);
+ $this->db = Server::get(IDBConnection::class);
$this->loader = new Loader($this->db);
}
diff --git a/tests/lib/Files/Utils/ScannerTest.php b/tests/lib/Files/Utils/ScannerTest.php
index f66bb72e865..49399ef70a6 100644
--- a/tests/lib/Files/Utils/ScannerTest.php
+++ b/tests/lib/Files/Utils/ScannerTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -10,20 +11,25 @@ namespace Test\Files\Utils;
use OC\Files\Filesystem;
use OC\Files\Mount\MountPoint;
use OC\Files\Storage\Temporary;
+use OC\Files\Utils\Scanner;
use OCP\EventDispatcher\IEventDispatcher;
use OCP\Files\Config\IMountProvider;
+use OCP\Files\Config\IMountProviderCollection;
use OCP\Files\Storage\IStorageFactory;
+use OCP\IDBConnection;
use OCP\IUser;
+use OCP\IUserManager;
+use OCP\Server;
use Psr\Log\LoggerInterface;
-class TestScanner extends \OC\Files\Utils\Scanner {
+class TestScanner extends Scanner {
/**
- * @var \OC\Files\Mount\MountPoint[] $mounts
+ * @var MountPoint[] $mounts
*/
private $mounts = [];
/**
- * @param \OC\Files\Mount\MountPoint $mount
+ * @param MountPoint $mount
*/
public function addMount($mount) {
$this->mounts[] = $mount;
@@ -51,13 +57,13 @@ class ScannerTest extends \Test\TestCase {
parent::setUp();
$this->userBackend = new \Test\Util\User\Dummy();
- \OC::$server->getUserManager()->registerBackend($this->userBackend);
+ Server::get(IUserManager::class)->registerBackend($this->userBackend);
$this->loginAsUser();
}
protected function tearDown(): void {
$this->logout();
- \OC::$server->getUserManager()->removeBackend($this->userBackend);
+ Server::get(IUserManager::class)->removeBackend($this->userBackend);
parent::tearDown();
}
@@ -71,7 +77,7 @@ class ScannerTest extends \Test\TestCase {
$storage->file_put_contents('foo.txt', 'qwerty');
$storage->file_put_contents('folder/bar.txt', 'qwerty');
- $scanner = new TestScanner('', \OC::$server->getDatabaseConnection(), $this->createMock(IEventDispatcher::class), \OC::$server->get(LoggerInterface::class));
+ $scanner = new TestScanner('', Server::get(IDBConnection::class), $this->createMock(IEventDispatcher::class), Server::get(LoggerInterface::class));
$scanner->addMount($mount);
$scanner->scan('');
@@ -93,7 +99,7 @@ class ScannerTest extends \Test\TestCase {
$storage->file_put_contents('foo.txt', 'qwerty');
$storage->file_put_contents('folder/bar.txt', 'qwerty');
- $scanner = new TestScanner('', \OC::$server->getDatabaseConnection(), $this->createMock(IEventDispatcher::class), \OC::$server->get(LoggerInterface::class));
+ $scanner = new TestScanner('', Server::get(IDBConnection::class), $this->createMock(IEventDispatcher::class), Server::get(LoggerInterface::class));
$scanner->addMount($mount);
$scanner->scan('');
@@ -124,24 +130,21 @@ class ScannerTest extends \Test\TestCase {
}
});
- \OC::$server->getMountProviderCollection()->registerProvider($mountProvider);
+ Server::get(IMountProviderCollection::class)->registerProvider($mountProvider);
$cache = $storage->getCache();
$storage->mkdir('folder');
$storage->file_put_contents('foo.txt', 'qwerty');
$storage->file_put_contents('folder/bar.txt', 'qwerty');
- $scanner = new \OC\Files\Utils\Scanner($uid, \OC::$server->getDatabaseConnection(), \OC::$server->query(IEventDispatcher::class), \OC::$server->get(LoggerInterface::class));
+ $scanner = new Scanner($uid, Server::get(IDBConnection::class), Server::get(IEventDispatcher::class), Server::get(LoggerInterface::class));
$this->assertFalse($cache->inCache('folder/bar.txt'));
$scanner->scan('/' . $uid . '/files/foo');
$this->assertTrue($cache->inCache('folder/bar.txt'));
}
- /**
- * @return array
- */
- public function invalidPathProvider() {
+ public static function invalidPathProvider(): array {
return [
[
'../',
@@ -156,14 +159,14 @@ class ScannerTest extends \Test\TestCase {
}
/**
- * @dataProvider invalidPathProvider
* @param string $invalidPath
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('invalidPathProvider')]
public function testInvalidPathScanning($invalidPath): void {
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage('Invalid path to scan');
- $scanner = new TestScanner('', \OC::$server->getDatabaseConnection(), $this->createMock(IEventDispatcher::class), \OC::$server->get(LoggerInterface::class));
+ $scanner = new TestScanner('', Server::get(IDBConnection::class), $this->createMock(IEventDispatcher::class), Server::get(LoggerInterface::class));
$scanner->scan($invalidPath);
}
@@ -177,7 +180,7 @@ class ScannerTest extends \Test\TestCase {
$storage->file_put_contents('folder/bar.txt', 'qwerty');
$storage->touch('folder/bar.txt', time() - 200);
- $scanner = new TestScanner('', \OC::$server->getDatabaseConnection(), $this->createMock(IEventDispatcher::class), \OC::$server->get(LoggerInterface::class));
+ $scanner = new TestScanner('', Server::get(IDBConnection::class), $this->createMock(IEventDispatcher::class), Server::get(LoggerInterface::class));
$scanner->addMount($mount);
$scanner->scan('');
@@ -203,7 +206,7 @@ class ScannerTest extends \Test\TestCase {
$storage->file_put_contents('folder/bar.txt', 'qwerty');
$storage->file_put_contents('folder/subfolder/foobar.txt', 'qwerty');
- $scanner = new TestScanner('', \OC::$server->getDatabaseConnection(), $this->createMock(IEventDispatcher::class), \OC::$server->get(LoggerInterface::class));
+ $scanner = new TestScanner('', Server::get(IDBConnection::class), $this->createMock(IEventDispatcher::class), Server::get(LoggerInterface::class));
$scanner->addMount($mount);
$scanner->scan('', $recusive = false);
diff --git a/tests/lib/Files/ViewTest.php b/tests/lib/Files/ViewTest.php
index 53e5855d0e9..c490cd08dae 100644
--- a/tests/lib/Files/ViewTest.php
+++ b/tests/lib/Files/ViewTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -7,6 +8,7 @@
namespace Test\Files;
+use OC\Files\Cache\Scanner;
use OC\Files\Cache\Watcher;
use OC\Files\Filesystem;
use OC\Files\Mount\MountPoint;
@@ -20,12 +22,21 @@ use OCA\Files_Trashbin\Trash\ITrashManager;
use OCP\Cache\CappedMemoryCache;
use OCP\Constants;
use OCP\Files\Config\IMountProvider;
+use OCP\Files\Config\IMountProviderCollection;
use OCP\Files\FileInfo;
use OCP\Files\ForbiddenException;
use OCP\Files\GenericFileException;
+use OCP\Files\InvalidPathException;
use OCP\Files\Mount\IMountManager;
+use OCP\Files\NotFoundException;
use OCP\Files\Storage\IStorage;
+use OCP\Files\Storage\IStorageFactory;
+use OCP\IConfig;
use OCP\IDBConnection;
+use OCP\IGroup;
+use OCP\IGroupManager;
+use OCP\ITempManager;
+use OCP\IUser;
use OCP\IUserManager;
use OCP\Lock\ILockingProvider;
use OCP\Lock\LockedException;
@@ -86,7 +97,7 @@ class ViewTest extends \Test\TestCase {
use UserTrait;
/**
- * @var \OC\Files\Storage\Storage[] $storages
+ * @var Storage[] $storages
*/
private $storages = [];
@@ -96,16 +107,16 @@ class ViewTest extends \Test\TestCase {
private $user;
/**
- * @var \OCP\IUser
+ * @var IUser
*/
private $userObject;
/**
- * @var \OCP\IGroup
+ * @var IGroup
*/
private $groupObject;
- /** @var \OC\Files\Storage\Storage */
+ /** @var Storage */
private $tempStorage;
protected function setUp(): void {
@@ -116,8 +127,8 @@ class ViewTest extends \Test\TestCase {
Server::get(IUserManager::class)->registerBackend(new \Test\Util\User\Dummy());
//login
- $userManager = \OC::$server->getUserManager();
- $groupManager = \OC::$server->getGroupManager();
+ $userManager = Server::get(IUserManager::class);
+ $groupManager = Server::get(IGroupManager::class);
$this->user = 'test';
$this->userObject = $userManager->createUser('test', 'test');
@@ -127,7 +138,7 @@ class ViewTest extends \Test\TestCase {
self::loginAsUser($this->user);
/** @var IMountManager $manager */
- $manager = \OC::$server->get(IMountManager::class);
+ $manager = Server::get(IMountManager::class);
$manager->removeMount('/test');
$this->tempStorage = null;
@@ -148,13 +159,13 @@ class ViewTest extends \Test\TestCase {
self::logout();
/** @var SetupManager $setupManager */
- $setupManager = \OC::$server->get(SetupManager::class);
+ $setupManager = Server::get(SetupManager::class);
$setupManager->setupRoot();
$this->userObject->delete();
$this->groupObject->delete();
- $mountProviderCollection = \OC::$server->getMountProviderCollection();
+ $mountProviderCollection = Server::get(IMountProviderCollection::class);
self::invokePrivate($mountProviderCollection, 'providers', [[]]);
parent::tearDown();
@@ -274,7 +285,7 @@ class ViewTest extends \Test\TestCase {
public function testGetPathNotExisting(): void {
- $this->expectException(\OCP\Files\NotFoundException::class);
+ $this->expectException(NotFoundException::class);
$storage1 = $this->getTestStorage();
Filesystem::mount($storage1, [], '/');
@@ -309,14 +320,12 @@ class ViewTest extends \Test\TestCase {
];
}
- /**
- * @dataProvider sharingDisabledPermissionProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('sharingDisabledPermissionProvider')]
public function testRemoveSharePermissionWhenSharingDisabledForUser($excludeGroups, $excludeGroupsList, $expectedShareable): void {
// Reset sharing disabled for users cache
- self::invokePrivate(\OC::$server->get(ShareDisableChecker::class), 'sharingDisabledForUsersCache', [new CappedMemoryCache()]);
+ self::invokePrivate(Server::get(ShareDisableChecker::class), 'sharingDisabledForUsersCache', [new CappedMemoryCache()]);
- $config = \OC::$server->getConfig();
+ $config = Server::get(IConfig::class);
$oldExcludeGroupsFlag = $config->getAppValue('core', 'shareapi_exclude_groups', 'no');
$oldExcludeGroupsList = $config->getAppValue('core', 'shareapi_exclude_groups_list', '');
$config->setAppValue('core', 'shareapi_exclude_groups', $excludeGroups);
@@ -339,7 +348,7 @@ class ViewTest extends \Test\TestCase {
$config->setAppValue('core', 'shareapi_exclude_groups_list', $oldExcludeGroupsList);
// Reset sharing disabled for users cache
- self::invokePrivate(\OC::$server->get(ShareDisableChecker::class), 'sharingDisabledForUsersCache', [new CappedMemoryCache()]);
+ self::invokePrivate(Server::get(ShareDisableChecker::class), 'sharingDisabledForUsersCache', [new CappedMemoryCache()]);
}
public function testCacheIncompleteFolder(): void {
@@ -518,10 +527,10 @@ class ViewTest extends \Test\TestCase {
}
public function moveBetweenStorages($storage1, $storage2) {
- Filesystem::mount($storage1, [], '/');
- Filesystem::mount($storage2, [], '/substorage');
+ Filesystem::mount($storage1, [], '/' . $this->user . '/');
+ Filesystem::mount($storage2, [], '/' . $this->user . '/substorage');
- $rootView = new View('');
+ $rootView = new View('/' . $this->user);
$rootView->rename('foo.txt', 'substorage/folder/foo.txt');
$this->assertFalse($rootView->file_exists('foo.txt'));
$this->assertTrue($rootView->file_exists('substorage/folder/foo.txt'));
@@ -558,9 +567,7 @@ class ViewTest extends \Test\TestCase {
return [['rmdir'], ['unlink']];
}
- /**
- * @dataProvider rmdirOrUnlinkDataProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('rmdirOrUnlinkDataProvider')]
public function testRmdir($method): void {
$storage1 = $this->getTestStorage();
Filesystem::mount($storage1, [], '/');
@@ -681,11 +688,11 @@ class ViewTest extends \Test\TestCase {
/**
* @param bool $scan
* @param string $class
- * @return \OC\Files\Storage\Storage
+ * @return Storage
*/
private function getTestStorage($scan = true, $class = Temporary::class) {
/**
- * @var \OC\Files\Storage\Storage $storage
+ * @var Storage $storage
*/
$storage = new $class([]);
$textData = "dummy file data\n";
@@ -767,9 +774,7 @@ class ViewTest extends \Test\TestCase {
\OC_Hook::clear('OC_Filesystem', 'post_write');
}
- /**
- * @dataProvider resolvePathTestProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('resolvePathTestProvider')]
public function testResolvePath($expected, $pathToTest): void {
$storage1 = $this->getTestStorage();
Filesystem::mount($storage1, [], '/');
@@ -844,7 +849,7 @@ class ViewTest extends \Test\TestCase {
* 1024 is the max path length in mac
*/
$folderName = 'abcdefghijklmnopqrstuvwxyz012345678901234567890123456789';
- $tmpdirLength = strlen(\OC::$server->getTempManager()->getTemporaryFolder());
+ $tmpdirLength = strlen(Server::get(ITempManager::class)->getTemporaryFolder());
if (\OC_Util::runningOnMac()) {
$depth = ((1024 - $tmpdirLength) / 57);
} else {
@@ -891,7 +896,7 @@ class ViewTest extends \Test\TestCase {
$info = $view->getFileInfo('/test/test');
$view->touch('/test/test', $past);
- $scanner->scanFile('test', \OC\Files\Cache\Scanner::REUSE_ETAG);
+ $scanner->scanFile('test', Scanner::REUSE_ETAG);
$info2 = $view->getFileInfo('/test/test');
$this->assertSame($info['etag'], $info2['etag']);
@@ -929,9 +934,7 @@ class ViewTest extends \Test\TestCase {
$this->assertNotEquals($newFolderInfo->getEtag(), $oldEtag);
}
- /**
- * @dataProvider absolutePathProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('absolutePathProvider')]
public function testGetAbsolutePath($expectedPath, $relativePath): void {
$view = new View('/files');
$this->assertEquals($expectedPath, $view->getAbsolutePath($relativePath));
@@ -941,14 +944,16 @@ class ViewTest extends \Test\TestCase {
$storage = new Temporary([]);
$scanner = $storage->getScanner();
Filesystem::mount($storage, [], '/test/');
- $storage->file_put_contents('test.part', 'foobar');
+ $sizeWritten = $storage->file_put_contents('test.part', 'foobar');
$scanner->scan('');
$view = new View('/test');
$info = $view->getFileInfo('test.part');
$this->assertInstanceOf('\OCP\Files\FileInfo', $info);
$this->assertNull($info->getId());
+ $this->assertEquals(6, $sizeWritten);
$this->assertEquals(6, $info->getSize());
+ $this->assertEquals('foobar', $view->file_get_contents('test.part'));
}
public static function absolutePathProvider(): array {
@@ -963,9 +968,7 @@ class ViewTest extends \Test\TestCase {
];
}
- /**
- * @dataProvider chrootRelativePathProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('chrootRelativePathProvider')]
public function testChrootGetRelativePath($root, $absolutePath, $expectedPath): void {
$view = new View('/files');
$view->chroot($root);
@@ -976,9 +979,7 @@ class ViewTest extends \Test\TestCase {
return self::relativePathProvider('/');
}
- /**
- * @dataProvider initRelativePathProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('initRelativePathProvider')]
public function testInitGetRelativePath($root, $absolutePath, $expectedPath): void {
$view = new View($root);
$this->assertEquals($expectedPath, $view->getRelativePath($absolutePath));
@@ -1075,11 +1076,9 @@ class ViewTest extends \Test\TestCase {
$this->assertEquals('foo', $view->file_get_contents(''));
}
- /**
- * @dataProvider tooLongPathDataProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('tooLongPathDataProvider')]
public function testTooLongPath($operation, $param0 = null): void {
- $this->expectException(\OCP\Files\InvalidPathException::class);
+ $this->expectException(InvalidPathException::class);
$longPath = '';
@@ -1263,9 +1262,9 @@ class ViewTest extends \Test\TestCase {
}
/**
- * @dataProvider directoryTraversalProvider
* @param string $root
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('directoryTraversalProvider')]
public function testConstructDirectoryTraversalException($root): void {
$this->expectException(\Exception::class);
@@ -1288,7 +1287,7 @@ class ViewTest extends \Test\TestCase {
public function testSetMountOptionsInStorage(): void {
$mount = new MountPoint(Temporary::class, '/asd/', [[]], Filesystem::getLoader(), ['foo' => 'bar']);
Filesystem::getMountManager()->addMount($mount);
- /** @var \OC\Files\Storage\Common $storage */
+ /** @var Common $storage */
$storage = $mount->getStorage();
$this->assertEquals($storage->getMountOption('foo'), 'bar');
}
@@ -1296,7 +1295,7 @@ class ViewTest extends \Test\TestCase {
public function testSetMountOptionsWatcherPolicy(): void {
$mount = new MountPoint(Temporary::class, '/asd/', [[]], Filesystem::getLoader(), ['filesystem_check_changes' => Watcher::CHECK_NEVER]);
Filesystem::getMountManager()->addMount($mount);
- /** @var \OC\Files\Storage\Common $storage */
+ /** @var Common $storage */
$storage = $mount->getStorage();
$watcher = $storage->getWatcher();
$this->assertEquals(Watcher::CHECK_NEVER, $watcher->getPolicy());
@@ -1323,13 +1322,13 @@ class ViewTest extends \Test\TestCase {
* e.g. reading from a folder that's being renamed
*
*
- * @dataProvider dataLockPaths
*
* @param string $rootPath
* @param string $pathPrefix
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataLockPaths')]
public function testReadFromWriteLockedPath($rootPath, $pathPrefix): void {
- $this->expectException(\OCP\Lock\LockedException::class);
+ $this->expectException(LockedException::class);
$rootPath = str_replace('{folder}', 'files', $rootPath);
$pathPrefix = str_replace('{folder}', 'files', $pathPrefix);
@@ -1344,11 +1343,11 @@ class ViewTest extends \Test\TestCase {
/**
* Reading from a files_encryption folder that's being renamed
*
- * @dataProvider dataLockPaths
*
* @param string $rootPath
* @param string $pathPrefix
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataLockPaths')]
public function testReadFromWriteUnlockablePath($rootPath, $pathPrefix): void {
$rootPath = str_replace('{folder}', 'files_encryption', $rootPath);
$pathPrefix = str_replace('{folder}', 'files_encryption', $pathPrefix);
@@ -1364,13 +1363,13 @@ class ViewTest extends \Test\TestCase {
* e.g. writing a file that's being downloaded
*
*
- * @dataProvider dataLockPaths
*
* @param string $rootPath
* @param string $pathPrefix
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataLockPaths')]
public function testWriteToReadLockedFile($rootPath, $pathPrefix): void {
- $this->expectException(\OCP\Lock\LockedException::class);
+ $this->expectException(LockedException::class);
$rootPath = str_replace('{folder}', 'files', $rootPath);
$pathPrefix = str_replace('{folder}', 'files', $pathPrefix);
@@ -1385,11 +1384,11 @@ class ViewTest extends \Test\TestCase {
/**
* Writing a file that's being downloaded
*
- * @dataProvider dataLockPaths
*
* @param string $rootPath
* @param string $pathPrefix
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataLockPaths')]
public function testWriteToReadUnlockableFile($rootPath, $pathPrefix): void {
$rootPath = str_replace('{folder}', 'files_encryption', $rootPath);
$pathPrefix = str_replace('{folder}', 'files_encryption', $pathPrefix);
@@ -1405,7 +1404,7 @@ class ViewTest extends \Test\TestCase {
* Test that locks are on mount point paths instead of mount root
*/
public function testLockLocalMountPointPathInsteadOfStorageRoot(): void {
- $lockingProvider = \OC::$server->get(ILockingProvider::class);
+ $lockingProvider = Server::get(ILockingProvider::class);
$view = new View('/testuser/files/');
$storage = new Temporary([]);
Filesystem::mount($storage, [], '/');
@@ -1435,7 +1434,7 @@ class ViewTest extends \Test\TestCase {
* Test that locks are on mount point paths and also mount root when requested
*/
public function testLockStorageRootButNotLocalMountPoint(): void {
- $lockingProvider = \OC::$server->get(ILockingProvider::class);
+ $lockingProvider = Server::get(ILockingProvider::class);
$view = new View('/testuser/files/');
$storage = new Temporary([]);
Filesystem::mount($storage, [], '/');
@@ -1465,7 +1464,7 @@ class ViewTest extends \Test\TestCase {
* Test that locks are on mount point paths and also mount root when requested
*/
public function testLockMountPointPathFailReleasesBoth(): void {
- $lockingProvider = \OC::$server->get(ILockingProvider::class);
+ $lockingProvider = Server::get(ILockingProvider::class);
$view = new View('/testuser/files/');
$storage = new Temporary([]);
Filesystem::mount($storage, [], '/');
@@ -1512,9 +1511,7 @@ class ViewTest extends \Test\TestCase {
];
}
- /**
- * @dataProvider pathRelativeToFilesProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('pathRelativeToFilesProvider')]
public function testGetPathRelativeToFiles($path, $expectedPath): void {
$view = new View();
$this->assertEquals($expectedPath, $view->getPathRelativeToFiles($path));
@@ -1531,9 +1528,9 @@ class ViewTest extends \Test\TestCase {
}
/**
- * @dataProvider pathRelativeToFilesProviderExceptionCases
* @param string $path
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('pathRelativeToFilesProviderExceptionCases')]
public function testGetPathRelativeToFilesWithInvalidArgument($path): void {
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage('$absolutePath must be relative to "files"');
@@ -1576,11 +1573,11 @@ class ViewTest extends \Test\TestCase {
}
/**
- * @dataProvider hookPathProvider
* @param $root
* @param $path
* @param $shouldEmit
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('hookPathProvider')]
public function testHookPaths($root, $path, $shouldEmit): void {
$filesystemReflection = new \ReflectionClass(Filesystem::class);
$defaultRootValue = $filesystemReflection->getProperty('defaultInstance');
@@ -1608,7 +1605,7 @@ class ViewTest extends \Test\TestCase {
->getMock();
$storage->method('getId')->willReturn('non-null-id');
$storage->method('getStorageCache')->willReturnCallback(function () use ($storage) {
- return new \OC\Files\Cache\Storage($storage, true, \OC::$server->get(IDBConnection::class));
+ return new \OC\Files\Cache\Storage($storage, true, Server::get(IDBConnection::class));
});
$mounts[] = $this->getMockBuilder(TestMoveableMountPoint::class)
@@ -1623,7 +1620,7 @@ class ViewTest extends \Test\TestCase {
->method('getMountsForUser')
->willReturn($mounts);
- $mountProviderCollection = \OC::$server->getMountProviderCollection();
+ $mountProviderCollection = Server::get(IMountProviderCollection::class);
$mountProviderCollection->registerProvider($mountProvider);
return $mounts;
@@ -1720,16 +1717,16 @@ class ViewTest extends \Test\TestCase {
$view->mkdir('shareddir notshared');
$fileId = $view->getFileInfo('shareddir')->getId();
- $userObject = \OC::$server->getUserManager()->createUser('test2', 'IHateNonMockableStaticClasses');
+ $userObject = Server::get(IUserManager::class)->createUser('test2', 'IHateNonMockableStaticClasses');
$userFolder = \OC::$server->getUserFolder($this->user);
$shareDir = $userFolder->get('shareddir');
- $shareManager = \OC::$server->get(IShareManager::class);
+ $shareManager = Server::get(IShareManager::class);
$share = $shareManager->newShare();
$share->setSharedWith('test2')
->setSharedBy($this->user)
->setShareType(IShare::TYPE_USER)
- ->setPermissions(\OCP\Constants::PERMISSION_READ)
+ ->setPermissions(Constants::PERMISSION_READ)
->setNode($shareDir);
$shareManager->createShare($share);
@@ -1915,7 +1912,6 @@ class ViewTest extends \Test\TestCase {
/**
* Test whether locks are set before and after the operation
*
- * @dataProvider basicOperationProviderForLocks
*
* @param string $operation operation name on the view
* @param array $operationArgs arguments for the operation
@@ -1927,6 +1923,7 @@ class ViewTest extends \Test\TestCase {
* @param int $expectedStrayLock expected lock after returning, should
* be null (unlock) for most operations
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('basicOperationProviderForLocks')]
public function testLockBasicOperation(
$operation,
$operationArgs,
@@ -1947,6 +1944,8 @@ class ViewTest extends \Test\TestCase {
/* Pause trash to avoid the trashbin intercepting rmdir and unlink calls */
Server::get(ITrashManager::class)->pauseTrash();
+ /* Same thing with encryption wrapper */
+ Server::get(IStorageFactory::class)->removeStorageWrapper('oc_encryption');
Filesystem::mount($storage, [], $this->user . '/');
@@ -2074,12 +2073,12 @@ class ViewTest extends \Test\TestCase {
/**
* Test locks for fopen with fclose at the end
*
- * @dataProvider basicOperationProviderForLocks
*
* @param string $operation operation name on the view
* @param array $operationArgs arguments for the operation
* @param string $path path of the locked item to check
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('basicOperationProviderForLocks')]
public function testLockBasicOperationUnlocksAfterException(
$operation,
$operationArgs,
@@ -2097,6 +2096,8 @@ class ViewTest extends \Test\TestCase {
/* Pause trash to avoid the trashbin intercepting rmdir and unlink calls */
Server::get(ITrashManager::class)->pauseTrash();
+ /* Same thing with encryption wrapper */
+ Server::get(IStorageFactory::class)->removeStorageWrapper('oc_encryption');
Filesystem::mount($storage, [], $this->user . '/');
@@ -2110,7 +2111,7 @@ class ViewTest extends \Test\TestCase {
$storage->expects($this->once())
->method($operation)
->willReturnCallback(
- function () {
+ function (): void {
throw new \Exception('Simulated exception');
}
);
@@ -2163,13 +2164,13 @@ class ViewTest extends \Test\TestCase {
/**
* Test locks for fopen with fclose at the end
*
- * @dataProvider basicOperationProviderForLocks
*
* @param string $operation operation name on the view
* @param array $operationArgs arguments for the operation
* @param string $path path of the locked item to check
* @param string $hookType hook type
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('basicOperationProviderForLocks')]
public function testLockBasicOperationUnlocksAfterCancelledHook(
$operation,
$operationArgs,
@@ -2208,12 +2209,12 @@ class ViewTest extends \Test\TestCase {
/**
* Test locks for rename or copy operation
*
- * @dataProvider lockFileRenameOrCopyDataProvider
*
* @param string $operation operation to be done on the view
* @param int $expectedLockTypeSourceDuring expected lock type on source file during
* the operation
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('lockFileRenameOrCopyDataProvider')]
public function testLockFileRename($operation, $expectedLockTypeSourceDuring): void {
$view = new View('/' . $this->user . '/files/');
@@ -2224,13 +2225,13 @@ class ViewTest extends \Test\TestCase {
$storage->expects($this->any())
->method('getMetaData')
- ->will($this->returnValue([
+ ->willReturn([
'mtime' => 1885434487,
'etag' => '',
'mimetype' => 'text/plain',
'permissions' => Constants::PERMISSION_ALL,
'size' => 3
- ]));
+ ]);
$storage->expects($this->any())
->method('filemtime')
->willReturn(123456789);
@@ -2238,6 +2239,9 @@ class ViewTest extends \Test\TestCase {
$sourcePath = 'original.txt';
$targetPath = 'target.txt';
+ /* Disable encryption wrapper to avoid it intercepting mocked call */
+ Server::get(IStorageFactory::class)->removeStorageWrapper('oc_encryption');
+
Filesystem::mount($storage, [], $this->user . '/');
$storage->mkdir('files');
$view->file_put_contents($sourcePath, 'meh');
@@ -2291,6 +2295,9 @@ class ViewTest extends \Test\TestCase {
$sourcePath = 'original.txt';
$targetPath = 'target.txt';
+ /* Disable encryption wrapper to avoid it intercepting mocked call */
+ Server::get(IStorageFactory::class)->removeStorageWrapper('oc_encryption');
+
Filesystem::mount($storage, [], $this->user . '/');
$storage->mkdir('files');
$view->file_put_contents($sourcePath, 'meh');
@@ -2298,7 +2305,7 @@ class ViewTest extends \Test\TestCase {
$storage->expects($this->once())
->method('copy')
->willReturnCallback(
- function () {
+ function (): void {
throw new \Exception();
}
);
@@ -2392,13 +2399,13 @@ class ViewTest extends \Test\TestCase {
/**
* Test locks for rename or copy operation cross-storage
*
- * @dataProvider lockFileRenameOrCopyCrossStorageDataProvider
*
* @param string $viewOperation operation to be done on the view
* @param string $storageOperation operation to be mocked on the storage
* @param int $expectedLockTypeSourceDuring expected lock type on source file during
* the operation
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('lockFileRenameOrCopyCrossStorageDataProvider')]
public function testLockFileRenameCrossStorage($viewOperation, $storageOperation, $expectedLockTypeSourceDuring): void {
$view = new View('/' . $this->user . '/files/');
@@ -2413,13 +2420,13 @@ class ViewTest extends \Test\TestCase {
$storage2->expects($this->any())
->method('getMetaData')
- ->will($this->returnValue([
+ ->willReturn([
'mtime' => 1885434487,
'etag' => '',
'mimetype' => 'text/plain',
'permissions' => Constants::PERMISSION_ALL,
'size' => 3
- ]));
+ ]);
$storage2->expects($this->any())
->method('filemtime')
->willReturn(123456789);
@@ -2427,6 +2434,9 @@ class ViewTest extends \Test\TestCase {
$sourcePath = 'original.txt';
$targetPath = 'substorage/target.txt';
+ /* Disable encryption wrapper to avoid it intercepting mocked call */
+ Server::get(IStorageFactory::class)->removeStorageWrapper('oc_encryption');
+
Filesystem::mount($storage, [], $this->user . '/');
Filesystem::mount($storage2, [], $this->user . '/files/substorage');
$storage->mkdir('files');
@@ -2550,14 +2560,14 @@ class ViewTest extends \Test\TestCase {
$eventHandler->expects($this->any())
->method('preCallback')
->willReturnCallback(
- function () use ($view, $path, $onMountPoint, &$lockTypePre) {
+ function () use ($view, $path, $onMountPoint, &$lockTypePre): void {
$lockTypePre = $this->getFileLockType($view, $path, $onMountPoint);
}
);
$eventHandler->expects($this->any())
->method('postCallback')
->willReturnCallback(
- function () use ($view, $path, $onMountPoint, &$lockTypePost) {
+ function () use ($view, $path, $onMountPoint, &$lockTypePost): void {
$lockTypePost = $this->getFileLockType($view, $path, $onMountPoint);
}
);
@@ -2657,8 +2667,8 @@ class ViewTest extends \Test\TestCase {
/**
* @param string $filter
* @param string[] $expected
- * @dataProvider mimeFilterProvider
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('mimeFilterProvider')]
public function testGetDirectoryContentMimeFilter($filter, $expected): void {
$storage1 = new Temporary();
$root = self::getUniqueID('/');
@@ -2778,7 +2788,7 @@ class ViewTest extends \Test\TestCase {
$calls = ['/new/folder', '/new/folder/structure'];
$view->expects($this->exactly(2))
->method('mkdir')
- ->willReturnCallback(function ($dir) use (&$calls) {
+ ->willReturnCallback(function ($dir) use (&$calls): void {
$expected = array_shift($calls);
$this->assertEquals($expected, $dir);
});