aboutsummaryrefslogtreecommitdiffstats
path: root/apps/files_sharing/tests
diff options
context:
space:
mode:
Diffstat (limited to 'apps/files_sharing/tests')
-rw-r--r--apps/files_sharing/tests/ApiTest.php326
-rw-r--r--apps/files_sharing/tests/ApplicationTest.php72
-rw-r--r--apps/files_sharing/tests/CacheTest.php178
-rw-r--r--apps/files_sharing/tests/CapabilitiesTest.php117
-rw-r--r--apps/files_sharing/tests/Collaboration/ShareRecipientSorterTest.php164
-rw-r--r--apps/files_sharing/tests/Command/CleanupRemoteStoragesTest.php134
-rw-r--r--apps/files_sharing/tests/Command/FixShareOwnersTest.php117
-rw-r--r--apps/files_sharing/tests/Controller/ExternalShareControllerTest.php119
-rw-r--r--apps/files_sharing/tests/Controller/PublicPreviewControllerTest.php157
-rw-r--r--apps/files_sharing/tests/Controller/ShareAPIControllerTest.php2009
-rw-r--r--apps/files_sharing/tests/Controller/ShareControllerTest.php625
-rw-r--r--apps/files_sharing/tests/Controller/ShareInfoControllerTest.php56
-rw-r--r--apps/files_sharing/tests/Controller/ShareesAPIControllerTest.php85
-rw-r--r--apps/files_sharing/tests/DeleteOrphanedSharesJobTest.php58
-rw-r--r--apps/files_sharing/tests/EncryptedSizePropagationTest.php46
-rw-r--r--apps/files_sharing/tests/EtagPropagationTest.php108
-rw-r--r--apps/files_sharing/tests/ExpireSharesJobTest.php59
-rw-r--r--apps/files_sharing/tests/External/CacheTest.php50
-rw-r--r--apps/files_sharing/tests/External/ManagerTest.php196
-rw-r--r--apps/files_sharing/tests/External/ScannerTest.php34
-rw-r--r--apps/files_sharing/tests/ExternalStorageTest.php48
-rw-r--r--apps/files_sharing/tests/GroupEtagPropagationTest.php41
-rw-r--r--apps/files_sharing/tests/HelperTest.php45
-rw-r--r--apps/files_sharing/tests/Listener/LoadAdditionalListenerTest.php120
-rw-r--r--apps/files_sharing/tests/LockingTest.php44
-rw-r--r--apps/files_sharing/tests/Middleware/OCSShareAPIMiddlewareTest.php33
-rw-r--r--apps/files_sharing/tests/Middleware/ShareInfoMiddlewareTest.php48
-rw-r--r--apps/files_sharing/tests/Middleware/SharingCheckMiddlewareTest.php61
-rw-r--r--apps/files_sharing/tests/Migration/SetPasswordColumnTest.php33
-rw-r--r--apps/files_sharing/tests/MountProviderTest.php155
-rw-r--r--apps/files_sharing/tests/PropagationTestCase.php37
-rw-r--r--apps/files_sharing/tests/ShareTest.php108
-rw-r--r--apps/files_sharing/tests/SharedMountTest.php130
-rw-r--r--apps/files_sharing/tests/SharedStorageTest.php205
-rw-r--r--apps/files_sharing/tests/SharesReminderJobTest.php193
-rw-r--r--apps/files_sharing/tests/SizePropagationTest.php39
-rw-r--r--apps/files_sharing/tests/TestCase.php129
-rw-r--r--apps/files_sharing/tests/UnshareChildrenTest.php46
-rw-r--r--apps/files_sharing/tests/UpdaterTest.php140
-rw-r--r--apps/files_sharing/tests/WatcherTest.php51
-rw-r--r--apps/files_sharing/tests/js/fileDropSpec.js98
-rw-r--r--apps/files_sharing/tests/js/publicAppSpec.js159
-rw-r--r--apps/files_sharing/tests/js/shareSpec.js343
43 files changed, 3325 insertions, 3691 deletions
diff --git a/apps/files_sharing/tests/ApiTest.php b/apps/files_sharing/tests/ApiTest.php
index cdb6d2ddcca..960f29224bb 100644
--- a/apps/files_sharing/tests/ApiTest.php
+++ b/apps/files_sharing/tests/ApiTest.php
@@ -1,55 +1,44 @@
<?php
+
/**
- * @copyright Copyright (c) 2016, ownCloud, Inc.
- *
- * @author Bjoern Schiessle <bjoern@schiessle.org>
- * @author Björn Schießle <bjoern@schiessle.org>
- * @author Christoph Wurst <christoph@winzerhof-wurst.at>
- * @author Daniel Calviño Sánchez <danxuliu@gmail.com>
- * @author Georg Ehrke <oc.list@georgehrke.com>
- * @author Joas Schilling <coding@schilljs.com>
- * @author Julius Härtl <jus@bitgrid.net>
- * @author Morris Jobke <hey@morrisjobke.de>
- * @author Richard Steinmetz <richard@steinmetz.cloud>
- * @author Robin Appelman <robin@icewind.nl>
- * @author Robin McCorkell <robin@mccorkell.me.uk>
- * @author Roeland Jago Douma <roeland@famdouma.nl>
- * @author Thomas Müller <thomas.mueller@tmit.eu>
- * @author Valdnet <47037905+Valdnet@users.noreply.github.com>
- * @author Vincent Petry <vincent@nextcloud.com>
- *
- * @license AGPL-3.0
- *
- * This code is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License, version 3,
- * as published by the Free Software Foundation.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU Affero General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License, version 3,
- * along with this program. If not, see <http://www.gnu.org/licenses/>
- *
+ * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
+ * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
+ * SPDX-License-Identifier: AGPL-3.0-only
*/
namespace OCA\Files_Sharing\Tests;
+use OC\Core\AppInfo\ConfigLexicon;
use OC\Files\Cache\Scanner;
+use OC\Files\FileInfo;
use OC\Files\Filesystem;
+use OC\Files\Storage\Temporary;
+use OC\Files\View;
+use OCA\Federation\TrustedServers;
use OCA\Files_Sharing\Controller\ShareAPIController;
use OCP\App\IAppManager;
use OCP\AppFramework\OCS\OCSBadRequestException;
use OCP\AppFramework\OCS\OCSException;
use OCP\AppFramework\OCS\OCSForbiddenException;
use OCP\AppFramework\OCS\OCSNotFoundException;
+use OCP\Constants;
+use OCP\Files\Folder;
+use OCP\Files\IRootFolder;
+use OCP\IAppConfig;
use OCP\IConfig;
use OCP\IDateTimeZone;
+use OCP\IGroupManager;
use OCP\IL10N;
use OCP\IPreview;
use OCP\IRequest;
+use OCP\ITagManager;
+use OCP\IURLGenerator;
+use OCP\IUserManager;
+use OCP\Mail\IMailer;
+use OCP\Server;
+use OCP\Share\IProviderFactory;
use OCP\Share\IShare;
use OCP\UserStatus\IManager as IUserStatusManager;
+use PHPUnit\Framework\MockObject\MockObject;
use Psr\Container\ContainerInterface;
use Psr\Log\LoggerInterface;
@@ -65,17 +54,15 @@ class ApiTest extends TestCase {
private static $tempStorage;
- /** @var \OCP\Files\Folder */
- private $userFolder;
-
- /** @var string */
- private $subsubfolder;
+ private Folder $userFolder;
+ private string $subsubfolder;
+ protected IAppConfig&MockObject $appConfig;
protected function setUp(): void {
parent::setUp();
- \OC::$server->getConfig()->setAppValue('core', 'shareapi_exclude_groups', 'no');
- \OC::$server->getConfig()->setAppValue('core', 'shareapi_expire_after_n_days', '7');
+ Server::get(IConfig::class)->setAppValue('core', 'shareapi_exclude_groups', 'no');
+ Server::get(IConfig::class)->setAppValue('core', 'shareapi_expire_after_n_days', '7');
Filesystem::getLoader()->removeStorageWrapper('sharing_mask');
@@ -90,16 +77,18 @@ class ApiTest extends TestCase {
$this->view->mkdir($this->folder);
$this->view->mkdir($this->folder . $this->subfolder);
$this->view->mkdir($this->folder . $this->subfolder . $this->subsubfolder);
- $this->view->file_put_contents($this->folder.$this->filename, $this->data);
+ $this->view->file_put_contents($this->folder . $this->filename, $this->data);
$this->view->file_put_contents($this->folder . $this->subfolder . $this->filename, $this->data);
$mount = $this->view->getMount($this->filename);
$mount->getStorage()->getScanner()->scan('', Scanner::SCAN_RECURSIVE);
$this->userFolder = \OC::$server->getUserFolder(self::TEST_FILES_SHARING_API_USER1);
+
+ $this->appConfig = $this->createMock(IAppConfig::class);
}
protected function tearDown(): void {
- if ($this->view instanceof \OC\Files\View) {
+ if ($this->view instanceof View) {
$this->view->unlink($this->filename);
$this->view->deleteAll($this->folder);
}
@@ -111,7 +100,7 @@ class ApiTest extends TestCase {
/**
* @param string $userId The userId of the caller
- * @return \OCA\Files_Sharing\Controller\ShareAPIController
+ * @return ShareAPIController
*/
private function createOCS($userId) {
$l = $this->getMockBuilder(IL10N::class)->getMock();
@@ -126,39 +115,48 @@ class ApiTest extends TestCase {
$previewManager = $this->createMock(IPreview::class);
$dateTimeZone = $this->createMock(IDateTimeZone::class);
$logger = $this->createMock(LoggerInterface::class);
+ $providerFactory = $this->createMock(IProviderFactory::class);
+ $mailer = $this->createMock(IMailer::class);
+ $tagManager = $this->createMock(ITagManager::class);
+ $trustedServers = $this->createMock(TrustedServers::class);
$dateTimeZone->method('getTimeZone')->willReturn(new \DateTimeZone(date_default_timezone_get()));
return new ShareAPIController(
self::APP_NAME,
$this->getMockBuilder(IRequest::class)->getMock(),
$this->shareManager,
- \OC::$server->getGroupManager(),
- \OC::$server->getUserManager(),
- \OC::$server->getRootFolder(),
- \OC::$server->getURLGenerator(),
+ Server::get(IGroupManager::class),
+ Server::get(IUserManager::class),
+ Server::get(IRootFolder::class),
+ Server::get(IURLGenerator::class),
$l,
$config,
+ $this->appConfig,
$appManager,
$serverContainer,
$userStatusManager,
$previewManager,
$dateTimeZone,
$logger,
+ $providerFactory,
+ $mailer,
+ $tagManager,
+ $trustedServers,
$userId,
);
}
- public function testCreateShareUserFile() {
+ public function testCreateShareUserFile(): void {
$this->setUp(); // for some reasons phpunit refuses to do this for us only for this test
$ocs = $this->createOCS(self::TEST_FILES_SHARING_API_USER1);
- $result = $ocs->createShare($this->filename, \OCP\Constants::PERMISSION_ALL, IShare::TYPE_USER, self::TEST_FILES_SHARING_API_USER2);
+ $result = $ocs->createShare($this->filename, Constants::PERMISSION_ALL, IShare::TYPE_USER, self::TEST_FILES_SHARING_API_USER2);
$ocs->cleanup();
$data = $result->getData();
$this->assertEquals(19, $data['permissions']);
$this->assertEmpty($data['expiration']);
- $this->shareManager->getShareById('ocinternal:'.$data['id']);
+ $this->shareManager->getShareById('ocinternal:' . $data['id']);
$ocs = $this->createOCS(self::TEST_FILES_SHARING_API_USER1);
$ocs->deleteShare($data['id']);
@@ -166,16 +164,16 @@ class ApiTest extends TestCase {
$ocs->cleanup();
}
- public function testCreateShareUserFolder() {
+ public function testCreateShareUserFolder(): void {
$ocs = $this->createOCS(self::TEST_FILES_SHARING_API_USER1);
- $result = $ocs->createShare($this->folder, \OCP\Constants::PERMISSION_ALL, IShare::TYPE_USER, self::TEST_FILES_SHARING_API_USER2);
+ $result = $ocs->createShare($this->folder, Constants::PERMISSION_ALL, IShare::TYPE_USER, self::TEST_FILES_SHARING_API_USER2);
$ocs->cleanup();
$data = $result->getData();
$this->assertEquals(31, $data['permissions']);
$this->assertEmpty($data['expiration']);
- $this->shareManager->getShareById('ocinternal:'.$data['id']);
+ $this->shareManager->getShareById('ocinternal:' . $data['id']);
$ocs = $this->createOCS(self::TEST_FILES_SHARING_API_USER1);
$ocs->deleteShare($data['id']);
@@ -183,32 +181,32 @@ class ApiTest extends TestCase {
}
- public function testCreateShareGroupFile() {
+ public function testCreateShareGroupFile(): void {
$ocs = $this->createOCS(self::TEST_FILES_SHARING_API_USER1);
- $result = $ocs->createShare($this->filename, \OCP\Constants::PERMISSION_ALL, IShare::TYPE_GROUP, self::TEST_FILES_SHARING_API_GROUP1);
+ $result = $ocs->createShare($this->filename, Constants::PERMISSION_ALL, IShare::TYPE_GROUP, self::TEST_FILES_SHARING_API_GROUP1);
$ocs->cleanup();
$data = $result->getData();
$this->assertEquals(19, $data['permissions']);
$this->assertEmpty($data['expiration']);
- $this->shareManager->getShareById('ocinternal:'.$data['id']);
+ $this->shareManager->getShareById('ocinternal:' . $data['id']);
$ocs = $this->createOCS(self::TEST_FILES_SHARING_API_USER1);
$ocs->deleteShare($data['id']);
$ocs->cleanup();
}
- public function testCreateShareGroupFolder() {
+ public function testCreateShareGroupFolder(): void {
$ocs = $this->createOCS(self::TEST_FILES_SHARING_API_USER1);
- $result = $ocs->createShare($this->folder, \OCP\Constants::PERMISSION_ALL, IShare::TYPE_GROUP, self::TEST_FILES_SHARING_API_GROUP1);
+ $result = $ocs->createShare($this->folder, Constants::PERMISSION_ALL, IShare::TYPE_GROUP, self::TEST_FILES_SHARING_API_GROUP1);
$ocs->cleanup();
$data = $result->getData();
$this->assertEquals(31, $data['permissions']);
$this->assertEmpty($data['expiration']);
- $this->shareManager->getShareById('ocinternal:'.$data['id']);
+ $this->shareManager->getShareById('ocinternal:' . $data['id']);
$ocs = $this->createOCS(self::TEST_FILES_SHARING_API_USER1);
$ocs->deleteShare($data['id']);
@@ -218,22 +216,22 @@ class ApiTest extends TestCase {
/**
* @group RoutingWeirdness
*/
- public function testCreateShareLink() {
+ public function testCreateShareLink(): void {
$ocs = $this->createOCS(self::TEST_FILES_SHARING_API_USER1);
- $result = $ocs->createShare($this->folder, \OCP\Constants::PERMISSION_ALL, IShare::TYPE_LINK);
+ $result = $ocs->createShare($this->folder, Constants::PERMISSION_ALL, IShare::TYPE_LINK);
$ocs->cleanup();
$data = $result->getData();
- $this->assertEquals(\OCP\Constants::PERMISSION_ALL,
+ $this->assertEquals(Constants::PERMISSION_ALL,
$data['permissions']);
$this->assertEmpty($data['expiration']);
$this->assertTrue(is_string($data['token']));
// check for correct link
- $url = \OC::$server->getURLGenerator()->getAbsoluteURL('/index.php/s/' . $data['token']);
+ $url = Server::get(IURLGenerator::class)->getAbsoluteURL('/index.php/s/' . $data['token']);
$this->assertEquals($url, $data['url']);
- $this->shareManager->getShareById('ocinternal:'.$data['id']);
+ $this->shareManager->getShareById('ocinternal:' . $data['id']);
$ocs = $this->createOCS(self::TEST_FILES_SHARING_API_USER1);
$ocs->deleteShare($data['id']);
@@ -242,43 +240,47 @@ class ApiTest extends TestCase {
/**
* @group RoutingWeirdness
+ * @dataProvider dataAllowFederationOnPublicShares
*/
- public function testCreateShareLinkPublicUpload() {
+ public function testCreateShareLinkPublicUpload(array $appConfig, int $permissions): void {
+ $this->appConfig->method('getValueBool')
+ ->willReturnMap([$appConfig]);
+
$ocs = $this->createOCS(self::TEST_FILES_SHARING_API_USER1);
- $result = $ocs->createShare($this->folder, \OCP\Constants::PERMISSION_ALL, IShare::TYPE_LINK, null, 'true');
+ $result = $ocs->createShare($this->folder, Constants::PERMISSION_ALL, IShare::TYPE_LINK, null, 'true');
$ocs->cleanup();
$data = $result->getData();
$this->assertEquals(
- \OCP\Constants::PERMISSION_READ |
- \OCP\Constants::PERMISSION_CREATE |
- \OCP\Constants::PERMISSION_UPDATE |
- \OCP\Constants::PERMISSION_DELETE |
- \OCP\Constants::PERMISSION_SHARE,
+ Constants::PERMISSION_READ
+ | Constants::PERMISSION_CREATE
+ | Constants::PERMISSION_UPDATE
+ | Constants::PERMISSION_DELETE
+ | $permissions,
$data['permissions']
);
$this->assertEmpty($data['expiration']);
$this->assertTrue(is_string($data['token']));
// check for correct link
- $url = \OC::$server->getURLGenerator()->getAbsoluteURL('/index.php/s/' . $data['token']);
+ $url = Server::get(IURLGenerator::class)->getAbsoluteURL('/index.php/s/' . $data['token']);
$this->assertEquals($url, $data['url']);
- $this->shareManager->getShareById('ocinternal:'.$data['id']);
+ $this->shareManager->getShareById('ocinternal:' . $data['id']);
$ocs = $this->createOCS(self::TEST_FILES_SHARING_API_USER1);
$ocs->deleteShare($data['id']);
$ocs->cleanup();
}
- public function testEnforceLinkPassword() {
+ public function testEnforceLinkPassword(): void {
$password = md5(time());
- $config = \OC::$server->getConfig();
+ $config = Server::get(IConfig::class);
$config->setAppValue('core', 'shareapi_enforce_links_password', 'yes');
$ocs = $this->createOCS(self::TEST_FILES_SHARING_API_USER1);
try {
- $ocs->createShare($this->folder, \OCP\Constants::PERMISSION_ALL, IShare::TYPE_LINK);
+ $ocs->createShare($this->folder, Constants::PERMISSION_ALL, IShare::TYPE_LINK);
$this->fail();
} catch (OCSForbiddenException $e) {
}
@@ -286,7 +288,7 @@ class ApiTest extends TestCase {
$ocs = $this->createOCS(self::TEST_FILES_SHARING_API_USER1);
try {
- $ocs->createShare($this->folder, \OCP\Constants::PERMISSION_ALL, IShare::TYPE_LINK, null, 'false', '');
+ $ocs->createShare($this->folder, Constants::PERMISSION_ALL, IShare::TYPE_LINK, null, 'false', '');
$this->fail();
} catch (OCSForbiddenException $e) {
}
@@ -294,7 +296,7 @@ class ApiTest extends TestCase {
// share with password should succeed
$ocs = $this->createOCS(self::TEST_FILES_SHARING_API_USER1);
- $result = $ocs->createShare($this->folder, \OCP\Constants::PERMISSION_ALL, IShare::TYPE_LINK, null, 'false', $password);
+ $result = $ocs->createShare($this->folder, Constants::PERMISSION_ALL, IShare::TYPE_LINK, null, 'false', $password);
$ocs->cleanup();
$data = $result->getData();
@@ -325,29 +327,29 @@ class ApiTest extends TestCase {
/**
* @medium
*/
- public function testSharePermissions() {
+ public function testSharePermissions(): void {
// sharing file to a user should work if shareapi_exclude_groups is set
// to no
- \OC::$server->getConfig()->setAppValue('core', 'shareapi_exclude_groups', 'no');
+ Server::get(IConfig::class)->setAppValue('core', 'shareapi_exclude_groups', 'no');
$ocs = $this->createOCS(self::TEST_FILES_SHARING_API_USER1);
- $result = $ocs->createShare($this->filename, \OCP\Constants::PERMISSION_ALL, IShare::TYPE_USER, self::TEST_FILES_SHARING_API_USER2);
+ $result = $ocs->createShare($this->filename, Constants::PERMISSION_ALL, IShare::TYPE_USER, self::TEST_FILES_SHARING_API_USER2);
$ocs->cleanup();
$data = $result->getData();
- $this->shareManager->getShareById('ocinternal:'.$data['id']);
+ $this->shareManager->getShareById('ocinternal:' . $data['id']);
$ocs = $this->createOCS(self::TEST_FILES_SHARING_API_USER1);
$ocs->deleteShare($data['id']);
$ocs->cleanup();
// exclude groups, but not the group the user belongs to. Sharing should still work
- \OC::$server->getConfig()->setAppValue('core', 'shareapi_exclude_groups', 'yes');
- \OC::$server->getConfig()->setAppValue('core', 'shareapi_exclude_groups_list', 'admin,group1,group2');
+ Server::get(IConfig::class)->setAppValue('core', 'shareapi_exclude_groups', 'yes');
+ Server::get(IConfig::class)->setAppValue('core', 'shareapi_exclude_groups_list', 'admin,group1,group2');
$ocs = $this->createOCS(self::TEST_FILES_SHARING_API_USER1);
- $result = $ocs->createShare($this->filename, \OCP\Constants::PERMISSION_ALL, IShare::TYPE_USER, self::TEST_FILES_SHARING_API_USER2);
+ $result = $ocs->createShare($this->filename, Constants::PERMISSION_ALL, IShare::TYPE_USER, self::TEST_FILES_SHARING_API_USER2);
$ocs->cleanup();
$data = $result->getData();
@@ -359,15 +361,15 @@ class ApiTest extends TestCase {
$ocs->cleanup();
// now we exclude the group the user belongs to ('group'), sharing should fail now
- \OC::$server->getConfig()->setAppValue('core', 'shareapi_exclude_groups_list', 'admin,group');
+ Server::get(IConfig::class)->setAppValue('core', 'shareapi_exclude_groups_list', 'admin,group');
$ocs = $this->createOCS(self::TEST_FILES_SHARING_API_USER1);
- $ocs->createShare($this->filename, \OCP\Constants::PERMISSION_ALL, IShare::TYPE_USER, self::TEST_FILES_SHARING_API_USER2);
+ $ocs->createShare($this->filename, Constants::PERMISSION_ALL, IShare::TYPE_USER, self::TEST_FILES_SHARING_API_USER2);
$ocs->cleanup();
// cleanup
- \OC::$server->getConfig()->setAppValue('core', 'shareapi_exclude_groups', 'no');
- \OC::$server->getConfig()->setAppValue('core', 'shareapi_exclude_groups_list', '');
+ Server::get(IConfig::class)->setAppValue('core', 'shareapi_exclude_groups', 'no');
+ Server::get(IConfig::class)->setAppValue('core', 'shareapi_exclude_groups_list', '');
$this->addToAssertionCount(1);
}
@@ -376,7 +378,7 @@ class ApiTest extends TestCase {
/**
* @medium
*/
- public function testGetAllShares() {
+ public function testGetAllShares(): void {
$node = $this->userFolder->get($this->filename);
$share = $this->shareManager->newShare();
@@ -397,7 +399,7 @@ class ApiTest extends TestCase {
$this->shareManager->deleteShare($share);
}
- public function testGetAllSharesWithMe() {
+ public function testGetAllSharesWithMe(): void {
$this->loginAsUser(self::TEST_FILES_SHARING_API_USER2);
$this->logout();
@@ -437,9 +439,9 @@ class ApiTest extends TestCase {
* @medium
* @group RoutingWeirdness
*/
- public function testPublicLinkUrl() {
+ public function testPublicLinkUrl(): void {
$ocs = $this->createOCS(self::TEST_FILES_SHARING_API_USER1);
- $result = $ocs->createShare($this->folder, \OCP\Constants::PERMISSION_ALL, IShare::TYPE_LINK);
+ $result = $ocs->createShare($this->folder, Constants::PERMISSION_ALL, IShare::TYPE_LINK);
$ocs->cleanup();
$data = $result->getData();
@@ -449,7 +451,7 @@ class ApiTest extends TestCase {
$id = $data['id'];
// check for correct link
- $url = \OC::$server->getURLGenerator()->getAbsoluteURL('/index.php/s/' . $data['token']);
+ $url = Server::get(IURLGenerator::class)->getAbsoluteURL('/index.php/s/' . $data['token']);
$this->assertEquals($url, $data['url']);
// check for link in getall shares
@@ -486,7 +488,7 @@ class ApiTest extends TestCase {
* @depends testCreateShareUserFile
* @depends testCreateShareLink
*/
- public function testGetShareFromSource() {
+ public function testGetShareFromSource(): void {
$node = $this->userFolder->get($this->filename);
$share = $this->shareManager->newShare();
$share->setNode($node)
@@ -519,7 +521,7 @@ class ApiTest extends TestCase {
* @depends testCreateShareUserFile
* @depends testCreateShareLink
*/
- public function testGetShareFromSourceWithReshares() {
+ public function testGetShareFromSourceWithReshares(): void {
$node = $this->userFolder->get($this->filename);
$share1 = $this->shareManager->newShare();
$share1->setNode($node)
@@ -560,7 +562,7 @@ class ApiTest extends TestCase {
* @medium
* @depends testCreateShareUserFile
*/
- public function testGetShareFromId() {
+ public function testGetShareFromId(): void {
$node = $this->userFolder->get($this->filename);
$share1 = $this->shareManager->newShare();
$share1->setNode($node)
@@ -584,7 +586,7 @@ class ApiTest extends TestCase {
/**
* @medium
*/
- public function testGetShareFromFolder() {
+ public function testGetShareFromFolder(): void {
$node1 = $this->userFolder->get($this->filename);
$share1 = $this->shareManager->newShare();
$share1->setNode($node1)
@@ -594,7 +596,7 @@ class ApiTest extends TestCase {
->setPermissions(19);
$share1 = $this->shareManager->createShare($share1);
- $node2 = $this->userFolder->get($this->folder.'/'.$this->filename);
+ $node2 = $this->userFolder->get($this->folder . '/' . $this->filename);
$share2 = $this->shareManager->newShare();
$share2->setNode($node2)
->setSharedBy(self::TEST_FILES_SHARING_API_USER1)
@@ -614,7 +616,7 @@ class ApiTest extends TestCase {
$this->shareManager->deleteShare($share2);
}
- public function testGetShareFromFolderWithFile() {
+ public function testGetShareFromFolderWithFile(): void {
$node1 = $this->userFolder->get($this->filename);
$share1 = $this->shareManager->newShare();
$share1->setNode($node1)
@@ -640,7 +642,7 @@ class ApiTest extends TestCase {
* share a folder, than reshare a file within the shared folder and check if we construct the correct path
* @medium
*/
- public function testGetShareFromFolderReshares() {
+ public function testGetShareFromFolderReshares(): void {
$node1 = $this->userFolder->get($this->folder);
$share1 = $this->shareManager->newShare();
$share1->setNode($node1)
@@ -652,7 +654,7 @@ class ApiTest extends TestCase {
$share1->setStatus(IShare::STATUS_ACCEPTED);
$this->shareManager->updateShare($share1);
- $node2 = $this->userFolder->get($this->folder.'/'.$this->filename);
+ $node2 = $this->userFolder->get($this->folder . '/' . $this->filename);
$share2 = $this->shareManager->newShare();
$share2->setNode($node2)
->setSharedBy(self::TEST_FILES_SHARING_API_USER2)
@@ -662,7 +664,7 @@ class ApiTest extends TestCase {
$share2->setStatus(IShare::STATUS_ACCEPTED);
$this->shareManager->updateShare($share2);
- $node3 = $this->userFolder->get($this->folder.'/'.$this->subfolder.'/'.$this->filename);
+ $node3 = $this->userFolder->get($this->folder . '/' . $this->subfolder . '/' . $this->filename);
$share3 = $this->shareManager->newShare();
$share3->setNode($node3)
->setSharedBy(self::TEST_FILES_SHARING_API_USER2)
@@ -700,7 +702,7 @@ class ApiTest extends TestCase {
* reshare a sub folder and check if we get the correct path
* @medium
*/
- public function testGetShareFromSubFolderReShares() {
+ public function testGetShareFromSubFolderReShares(): void {
$node1 = $this->userFolder->get($this->folder . $this->subfolder);
$share1 = $this->shareManager->newShare();
$share1->setNode($node1)
@@ -712,7 +714,7 @@ class ApiTest extends TestCase {
$share1->setStatus(IShare::STATUS_ACCEPTED);
$this->shareManager->updateShare($share1);
- $node2 = \OC::$server->getRootFolder()->getUserFolder(self::TEST_FILES_SHARING_API_USER2)->get($this->subfolder);
+ $node2 = Server::get(IRootFolder::class)->getUserFolder(self::TEST_FILES_SHARING_API_USER2)->get($this->subfolder);
$share2 = $this->shareManager->newShare();
$share2->setNode($node2)
->setSharedBy(self::TEST_FILES_SHARING_API_USER2)
@@ -819,7 +821,7 @@ class ApiTest extends TestCase {
* test multiple shared folder if the path gets constructed correctly
* @medium
*/
- public function testGetShareMultipleSharedFolder() {
+ public function testGetShareMultipleSharedFolder(): void {
$this->setUp();
$node1 = $this->userFolder->get($this->folder . $this->subfolder);
$share1 = $this->shareManager->newShare();
@@ -873,7 +875,7 @@ class ApiTest extends TestCase {
$s2 = reset($data2);
$this->assertEquals($this->subfolder, $s1['path']);
- $this->assertEquals($this->folder.$this->subfolder, $s2['path']);
+ $this->assertEquals($this->folder . $this->subfolder, $s2['path']);
$this->shareManager->deleteShare($share1);
$this->shareManager->deleteShare($share2);
@@ -884,7 +886,7 @@ class ApiTest extends TestCase {
* test re-re-share of folder if the path gets constructed correctly
* @medium
*/
- public function testGetShareFromFileReReShares() {
+ public function testGetShareFromFileReReShares(): void {
$node1 = $this->userFolder->get($this->folder . $this->subfolder);
$share1 = $this->shareManager->newShare();
$share1->setNode($node1)
@@ -939,7 +941,7 @@ class ApiTest extends TestCase {
/**
* @medium
*/
- public function testGetShareFromUnknownId() {
+ public function testGetShareFromUnknownId(): void {
$ocs = $this->createOCS(self::TEST_FILES_SHARING_API_USER3);
try {
$ocs->getShare(0);
@@ -955,7 +957,7 @@ class ApiTest extends TestCase {
* @depends testCreateShareUserFile
* @depends testCreateShareLink
*/
- public function testUpdateShare() {
+ public function testUpdateShare(): void {
$password = md5(time());
$node1 = $this->userFolder->get($this->filename);
@@ -983,7 +985,7 @@ class ApiTest extends TestCase {
$ocs = $this->createOCS(self::TEST_FILES_SHARING_API_USER1);
$ocs->updateShare(
$share1->getId(), 1, null, null, null, null, null, null, null,
- '[{"scope": "app1", "key": "attr1", "enabled": true}]'
+ '[{"scope": "app1", "key": "attr1", "value": true}]'
);
$ocs->cleanup();
@@ -1014,8 +1016,13 @@ class ApiTest extends TestCase {
/**
* @medium
+ * @dataProvider dataAllowFederationOnPublicShares
*/
- public function testUpdateShareUpload() {
+ public function testUpdateShareUpload(array $appConfig, int $permissions): void {
+ $this->appConfig->method('getValueBool')->willReturnMap([
+ $appConfig,
+ ]);
+
$node1 = $this->userFolder->get($this->folder);
$share1 = $this->shareManager->newShare();
$share1->setNode($node1)
@@ -1031,11 +1038,11 @@ class ApiTest extends TestCase {
$share1 = $this->shareManager->getShareById($share1->getFullId());
$this->assertEquals(
- \OCP\Constants::PERMISSION_READ |
- \OCP\Constants::PERMISSION_CREATE |
- \OCP\Constants::PERMISSION_UPDATE |
- \OCP\Constants::PERMISSION_DELETE |
- \OCP\Constants::PERMISSION_SHARE,
+ Constants::PERMISSION_READ
+ | Constants::PERMISSION_CREATE
+ | Constants::PERMISSION_UPDATE
+ | Constants::PERMISSION_DELETE
+ | $permissions,
$share1->getPermissions()
);
@@ -1043,10 +1050,17 @@ class ApiTest extends TestCase {
$this->shareManager->deleteShare($share1);
}
+ public static function dataAllowFederationOnPublicShares(): array {
+ return [
+ [['core', ConfigLexicon::SHAREAPI_ALLOW_FEDERATION_ON_PUBLIC_SHARES, false, false], 0],
+ [['core', ConfigLexicon::SHAREAPI_ALLOW_FEDERATION_ON_PUBLIC_SHARES, false, true], Constants::PERMISSION_SHARE],
+ ];
+ }
+
/**
* @medium
*/
- public function testUpdateShareExpireDate() {
+ public function testUpdateShareExpireDate(): void {
$node1 = $this->userFolder->get($this->folder);
$share1 = $this->shareManager->newShare();
$share1->setNode($node1)
@@ -1057,7 +1071,7 @@ class ApiTest extends TestCase {
$share1->setStatus(IShare::STATUS_ACCEPTED);
$this->shareManager->updateShare($share1);
- $config = \OC::$server->getConfig();
+ $config = Server::get(IConfig::class);
// enforce expire date, by default 7 days after the file was shared
$config->setAppValue('core', 'shareapi_default_expire_date', 'yes');
@@ -1119,7 +1133,7 @@ class ApiTest extends TestCase {
* @medium
* @depends testCreateShareUserFile
*/
- public function testDeleteShare() {
+ public function testDeleteShare(): void {
$node1 = $this->userFolder->get($this->filename);
$share1 = $this->shareManager->newShare();
$share1->setNode($node1)
@@ -1151,7 +1165,7 @@ class ApiTest extends TestCase {
/**
* test unshare of a reshared file
*/
- public function testDeleteReshare() {
+ public function testDeleteReshare(): void {
$node1 = $this->userFolder->get($this->folder);
$share1 = $this->shareManager->newShare();
$share1->setNode($node1)
@@ -1164,7 +1178,7 @@ class ApiTest extends TestCase {
$this->shareManager->updateShare($share1);
$user2folder = \OC::$server->getUserFolder(self::TEST_FILES_SHARING_API_USER2);
- $node2 = $user2folder->get($this->folder.'/'.$this->filename);
+ $node2 = $user2folder->get($this->folder . '/' . $this->filename);
$share2 = $this->shareManager->newShare();
$share2->setNode($node2)
->setSharedBy(self::TEST_FILES_SHARING_API_USER2)
@@ -1186,7 +1200,7 @@ class ApiTest extends TestCase {
/**
* share a folder which contains a share mount point, should be forbidden
*/
- public function testShareFolderWithAMountPoint() {
+ public function testShareFolderWithAMountPoint(): void {
// user 1 shares a folder with user2
self::loginHelper(self::TEST_FILES_SHARING_API_USER1);
@@ -1195,7 +1209,7 @@ class ApiTest extends TestCase {
$this->folder,
self::TEST_FILES_SHARING_API_USER1,
self::TEST_FILES_SHARING_API_USER2,
- \OCP\Constants::PERMISSION_ALL
+ Constants::PERMISSION_ALL
);
$share->setStatus(IShare::STATUS_ACCEPTED);
$this->shareManager->updateShare($share);
@@ -1203,17 +1217,17 @@ class ApiTest extends TestCase {
// user2 shares a file from the folder as link
self::loginHelper(self::TEST_FILES_SHARING_API_USER2);
- $view = new \OC\Files\View('/' . self::TEST_FILES_SHARING_API_USER2 . '/files');
- $view->mkdir("localDir");
+ $view = new View('/' . self::TEST_FILES_SHARING_API_USER2 . '/files');
+ $view->mkdir('localDir');
// move mount point to the folder "localDir"
- $result = $view->rename($this->folder, 'localDir/'.$this->folder);
+ $result = $view->rename($this->folder, 'localDir/' . $this->folder);
$this->assertTrue($result !== false);
// try to share "localDir"
$fileInfo2 = $view->getFileInfo('localDir');
- $this->assertTrue($fileInfo2 instanceof \OC\Files\FileInfo);
+ $this->assertTrue($fileInfo2 instanceof FileInfo);
$pass = true;
try {
@@ -1222,7 +1236,7 @@ class ApiTest extends TestCase {
'localDir',
self::TEST_FILES_SHARING_API_USER2,
self::TEST_FILES_SHARING_API_USER3,
- \OCP\Constants::PERMISSION_ALL
+ Constants::PERMISSION_ALL
);
} catch (\Exception $e) {
$pass = false;
@@ -1246,15 +1260,15 @@ class ApiTest extends TestCase {
*/
public static function initTestMountPointsHook($data) {
if ($data['user'] === self::TEST_FILES_SHARING_API_USER1) {
- \OC\Files\Filesystem::mount(self::$tempStorage, [], '/' . self::TEST_FILES_SHARING_API_USER1 . '/files' . self::TEST_FOLDER_NAME);
+ Filesystem::mount(self::$tempStorage, [], '/' . self::TEST_FILES_SHARING_API_USER1 . '/files' . self::TEST_FOLDER_NAME);
}
}
/**
* Tests mounting a folder that is an external storage mount point.
*/
- public function testShareStorageMountPoint() {
- $tempStorage = new \OC\Files\Storage\Temporary([]);
+ public function testShareStorageMountPoint(): void {
+ $tempStorage = new Temporary([]);
$tempStorage->file_put_contents('test.txt', 'abcdef');
$tempStorage->getScanner()->scan('');
@@ -1269,7 +1283,7 @@ class ApiTest extends TestCase {
$this->folder,
self::TEST_FILES_SHARING_API_USER1,
self::TEST_FILES_SHARING_API_USER2,
- \OCP\Constants::PERMISSION_ALL
+ Constants::PERMISSION_ALL
);
$share->setStatus(IShare::STATUS_ACCEPTED);
$this->shareManager->updateShare($share);
@@ -1277,7 +1291,7 @@ class ApiTest extends TestCase {
// user2: check that mount point name appears correctly
self::loginHelper(self::TEST_FILES_SHARING_API_USER2);
- $view = new \OC\Files\View('/' . self::TEST_FILES_SHARING_API_USER2 . '/files');
+ $view = new View('/' . self::TEST_FILES_SHARING_API_USER2 . '/files');
$this->assertTrue($view->file_exists($this->folder));
$this->assertTrue($view->file_exists($this->folder . '/test.txt'));
@@ -1290,7 +1304,7 @@ class ApiTest extends TestCase {
\OC_Hook::clear('\OCA\Files_Sharing\Tests\ApiTest', 'initTestMountPointsHook');
}
- public function datesProvider() {
+ public static function datesProvider() {
$date = new \DateTime();
$date->setTime(0, 0);
$date->add(new \DateInterval('P5D'));
@@ -1306,18 +1320,18 @@ class ApiTest extends TestCase {
/**
* Make sure only ISO 8601 dates are accepted
*
- * @dataProvider datesProvider
* @group RoutingWeirdness
*/
- public function testPublicLinkExpireDate($date, $valid) {
+ #[\PHPUnit\Framework\Attributes\DataProvider('datesProvider')]
+ public function testPublicLinkExpireDate($date, $valid): void {
$ocs = $this->createOCS(self::TEST_FILES_SHARING_API_USER1);
try {
- $result = $ocs->createShare($this->folder, \OCP\Constants::PERMISSION_ALL, IShare::TYPE_LINK, null, 'false', '', null, $date);
+ $result = $ocs->createShare($this->folder, Constants::PERMISSION_ALL, IShare::TYPE_LINK, null, 'false', '', null, $date);
$this->assertTrue($valid);
} catch (OCSNotFoundException $e) {
$this->assertFalse($valid);
- $this->assertEquals('Invalid date, date format must be YYYY-MM-DD', $e->getMessage());
+ $this->assertEquals('Invalid date. Format must be YYYY-MM-DD', $e->getMessage());
$ocs->cleanup();
return;
}
@@ -1328,10 +1342,10 @@ class ApiTest extends TestCase {
$this->assertEquals(substr($date, 0, 10), substr($data['expiration'], 0, 10));
// check for correct link
- $url = \OC::$server->getURLGenerator()->getAbsoluteURL('/index.php/s/' . $data['token']);
+ $url = Server::get(IURLGenerator::class)->getAbsoluteURL('/index.php/s/' . $data['token']);
$this->assertEquals($url, $data['url']);
- $share = $this->shareManager->getShareById('ocinternal:'.$data['id']);
+ $share = $this->shareManager->getShareById('ocinternal:' . $data['id']);
$this->assertEquals($date, $share->getExpirationDate()->format('Y-m-d H:i:s'));
@@ -1341,8 +1355,8 @@ class ApiTest extends TestCase {
/**
* @group RoutingWeirdness
*/
- public function testCreatePublicLinkExpireDateValid() {
- $config = \OC::$server->getConfig();
+ public function testCreatePublicLinkExpireDateValid(): void {
+ $config = Server::get(IConfig::class);
// enforce expire date, by default 7 days after the file was shared
$config->setAppValue('core', 'shareapi_default_expire_date', 'yes');
@@ -1352,7 +1366,7 @@ class ApiTest extends TestCase {
$date->add(new \DateInterval('P5D'));
$ocs = $this->createOCS(self::TEST_FILES_SHARING_API_USER1);
- $result = $ocs->createShare($this->filename, \OCP\Constants::PERMISSION_ALL, IShare::TYPE_LINK, null, 'false', '', null, $date->format('Y-m-d'));
+ $result = $ocs->createShare($this->filename, Constants::PERMISSION_ALL, IShare::TYPE_LINK, null, 'false', '', null, $date->format('Y-m-d'));
$ocs->cleanup();
$data = $result->getData();
@@ -1360,10 +1374,10 @@ class ApiTest extends TestCase {
$this->assertEquals($date->format('Y-m-d 00:00:00'), $data['expiration']);
// check for correct link
- $url = \OC::$server->getURLGenerator()->getAbsoluteURL('/index.php/s/' . $data['token']);
+ $url = Server::get(IURLGenerator::class)->getAbsoluteURL('/index.php/s/' . $data['token']);
$this->assertEquals($url, $data['url']);
- $share = $this->shareManager->getShareById('ocinternal:'.$data['id']);
+ $share = $this->shareManager->getShareById('ocinternal:' . $data['id']);
$date->setTime(0, 0, 0);
$this->assertEquals($date, $share->getExpirationDate());
@@ -1373,8 +1387,8 @@ class ApiTest extends TestCase {
$config->setAppValue('core', 'shareapi_enforce_expire_date', 'no');
}
- public function testCreatePublicLinkExpireDateInvalidFuture() {
- $config = \OC::$server->getConfig();
+ public function testCreatePublicLinkExpireDateInvalidFuture(): void {
+ $config = Server::get(IConfig::class);
// enforce expire date, by default 7 days after the file was shared
$config->setAppValue('core', 'shareapi_default_expire_date', 'yes');
@@ -1386,7 +1400,7 @@ class ApiTest extends TestCase {
$ocs = $this->createOCS(self::TEST_FILES_SHARING_API_USER1);
try {
- $ocs->createShare($this->filename, \OCP\Constants::PERMISSION_ALL, IShare::TYPE_LINK, null, 'false', '', null, $date->format('Y-m-d'));
+ $ocs->createShare($this->filename, Constants::PERMISSION_ALL, IShare::TYPE_LINK, null, 'false', '', null, $date->format('Y-m-d'));
$this->fail();
} catch (OCSException $e) {
$this->assertEquals(404, $e->getCode());
@@ -1399,7 +1413,7 @@ class ApiTest extends TestCase {
}
public function XtestCreatePublicLinkExpireDateInvalidPast() {
- $config = \OC::$server->getConfig();
+ $config = Server::get(IConfig::class);
$date = new \DateTime();
$date->sub(new \DateInterval('P8D'));
@@ -1407,7 +1421,7 @@ class ApiTest extends TestCase {
$ocs = $this->createOCS(self::TEST_FILES_SHARING_API_USER1);
try {
- $ocs->createShare($this->filename, \OCP\Constants::PERMISSION_ALL, IShare::TYPE_LINK, null, 'false', '', null, $date->format('Y-m-d'));
+ $ocs->createShare($this->filename, Constants::PERMISSION_ALL, IShare::TYPE_LINK, null, 'false', '', null, $date->format('Y-m-d'));
$this->fail();
} catch (OCSException $e) {
$this->assertEquals(404, $e->getCode());
@@ -1423,10 +1437,10 @@ class ApiTest extends TestCase {
* test for no invisible shares
* See: https://github.com/owncloud/core/issues/22295
*/
- public function testInvisibleSharesUser() {
+ public function testInvisibleSharesUser(): void {
// simulate a post request
$ocs = $this->createOCS(self::TEST_FILES_SHARING_API_USER1);
- $result = $ocs->createShare($this->folder, \OCP\Constants::PERMISSION_ALL, IShare::TYPE_USER, self::TEST_FILES_SHARING_API_USER2);
+ $result = $ocs->createShare($this->folder, Constants::PERMISSION_ALL, IShare::TYPE_USER, self::TEST_FILES_SHARING_API_USER2);
$ocs->cleanup();
$data = $result->getData();
@@ -1437,7 +1451,7 @@ class ApiTest extends TestCase {
$ocs->cleanup();
$ocs = $this->createOCS(self::TEST_FILES_SHARING_API_USER2);
- $ocs->createShare($this->folder, \OCP\Constants::PERMISSION_ALL, IShare::TYPE_LINK);
+ $ocs->createShare($this->folder, Constants::PERMISSION_ALL, IShare::TYPE_LINK);
$ocs->cleanup();
$ocs = $this->createOCS(self::TEST_FILES_SHARING_API_USER1);
@@ -1455,10 +1469,10 @@ class ApiTest extends TestCase {
* test for no invisible shares
* See: https://github.com/owncloud/core/issues/22295
*/
- public function testInvisibleSharesGroup() {
+ public function testInvisibleSharesGroup(): void {
// simulate a post request
$ocs = $this->createOCS(self::TEST_FILES_SHARING_API_USER1);
- $result = $ocs->createShare($this->folder, \OCP\Constants::PERMISSION_ALL, IShare::TYPE_GROUP, self::TEST_FILES_SHARING_API_GROUP1);
+ $result = $ocs->createShare($this->folder, Constants::PERMISSION_ALL, IShare::TYPE_GROUP, self::TEST_FILES_SHARING_API_GROUP1);
$ocs->cleanup();
$data = $result->getData();
@@ -1471,7 +1485,7 @@ class ApiTest extends TestCase {
\OC_Util::tearDownFS();
$ocs = $this->createOCS(self::TEST_FILES_SHARING_API_USER2);
- $ocs->createShare($this->folder, \OCP\Constants::PERMISSION_ALL, IShare::TYPE_LINK);
+ $ocs->createShare($this->folder, Constants::PERMISSION_ALL, IShare::TYPE_LINK);
$ocs->cleanup();
$ocs = $this->createOCS(self::TEST_FILES_SHARING_API_USER1);
diff --git a/apps/files_sharing/tests/ApplicationTest.php b/apps/files_sharing/tests/ApplicationTest.php
index 270a56504f9..84a3f4b372b 100644
--- a/apps/files_sharing/tests/ApplicationTest.php
+++ b/apps/files_sharing/tests/ApplicationTest.php
@@ -1,50 +1,29 @@
<?php
+
/**
- * @copyright 2022, Vincent Petry <vincent@nextcloud.com>
- *
- * @author Vincent Petry <vincent@nextcloud.com>
- *
- * @license GNU AGPL version 3 or any later version
- *
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License as
- * published by the Free Software Foundation, either version 3 of the
- * License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU Affero General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- *
+ * SPDX-FileCopyrightText: 2022 Nextcloud GmbH and Nextcloud contributors
+ * SPDX-License-Identifier: AGPL-3.0-or-later
*/
namespace OCA\Files_Sharing\Tests;
-use OC\EventDispatcher\EventDispatcher;
-use OC\Share20\Manager;
use OCA\Files_Sharing\AppInfo\Application;
+use OCA\Files_Sharing\Listener\BeforeDirectFileDownloadListener;
+use OCA\Files_Sharing\Listener\BeforeZipCreatedListener;
use OCA\Files_Sharing\SharedStorage;
-use OCP\EventDispatcher\IEventDispatcher;
use OCP\Files\Events\BeforeDirectFileDownloadEvent;
use OCP\Files\Events\BeforeZipCreatedEvent;
use OCP\Files\File;
use OCP\Files\Folder;
use OCP\Files\IRootFolder;
use OCP\Files\Storage\IStorage;
-use OCP\IServerContainer;
use OCP\IUser;
use OCP\IUserSession;
use OCP\Share\IAttributes;
use OCP\Share\IShare;
-use Psr\Log\LoggerInterface;
-use Symfony\Component\EventDispatcher\EventDispatcher as SymfonyDispatcher;
use Test\TestCase;
class ApplicationTest extends TestCase {
private Application $application;
- private IEventDispatcher $eventDispatcher;
/** @var IUserSession */
private $userSession;
@@ -52,28 +31,14 @@ class ApplicationTest extends TestCase {
/** @var IRootFolder */
private $rootFolder;
- /** @var Manager */
- private $manager;
protected function setUp(): void {
parent::setUp();
$this->application = new Application([]);
- $symfonyDispatcher = new SymfonyDispatcher();
- $this->eventDispatcher = new EventDispatcher(
- $symfonyDispatcher,
- $this->createMock(IServerContainer::class),
- $this->createMock(LoggerInterface::class)
- );
$this->userSession = $this->createMock(IUserSession::class);
$this->rootFolder = $this->createMock(IRootFolder::class);
-
- $this->application->registerDownloadEvents(
- $this->eventDispatcher,
- $this->userSession,
- $this->rootFolder
- );
}
public function providesDataForCanGet(): array {
@@ -122,9 +87,7 @@ class ApplicationTest extends TestCase {
return $result;
}
- /**
- * @dataProvider providesDataForCanGet
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('providesDataForCanGet')]
public function testCheckDirectCanBeDownloaded(string $path, Folder $userFolder, bool $run): void {
$user = $this->createMock(IUser::class);
$user->method('getUID')->willReturn('test');
@@ -134,7 +97,11 @@ class ApplicationTest extends TestCase {
// Simulate direct download of file
$event = new BeforeDirectFileDownloadEvent($path);
- $this->eventDispatcher->dispatchTyped($event);
+ $listener = new BeforeDirectFileDownloadListener(
+ $this->userSession,
+ $this->rootFolder
+ );
+ $listener->handle($event);
$this->assertEquals($run, $event->isSuccessful());
}
@@ -199,9 +166,7 @@ class ApplicationTest extends TestCase {
return $return;
}
- /**
- * @dataProvider providesDataForCanZip
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('providesDataForCanZip')]
public function testCheckZipCanBeDownloaded(string $dir, array $files, Folder $userFolder, bool $run): void {
$user = $this->createMock(IUser::class);
$user->method('getUID')->willReturn('test');
@@ -212,7 +177,12 @@ class ApplicationTest extends TestCase {
// Simulate zip download of folder folder
$event = new BeforeZipCreatedEvent($dir, $files);
- $this->eventDispatcher->dispatchTyped($event);
+ $listener = new BeforeZipCreatedListener(
+ $this->userSession,
+ $this->rootFolder
+ );
+ $listener->handle($event);
+
$this->assertEquals($run, $event->isSuccessful());
$this->assertEquals($run, $event->getErrorMessage() === null);
@@ -223,7 +193,11 @@ class ApplicationTest extends TestCase {
// Simulate zip download of folder folder
$event = new BeforeZipCreatedEvent('/test', ['test.txt']);
- $this->eventDispatcher->dispatchTyped($event);
+ $listener = new BeforeZipCreatedListener(
+ $this->userSession,
+ $this->rootFolder
+ );
+ $listener->handle($event);
// It should run as this would restrict e.g. share links otherwise
$this->assertTrue($event->isSuccessful());
diff --git a/apps/files_sharing/tests/CacheTest.php b/apps/files_sharing/tests/CacheTest.php
index 729b701b1a0..e95d3d4f91a 100644
--- a/apps/files_sharing/tests/CacheTest.php
+++ b/apps/files_sharing/tests/CacheTest.php
@@ -1,37 +1,23 @@
<?php
+
/**
- * @copyright Copyright (c) 2016, ownCloud, Inc.
- *
- * @author Björn Schießle <bjoern@schiessle.org>
- * @author Christoph Wurst <christoph@winzerhof-wurst.at>
- * @author Joas Schilling <coding@schilljs.com>
- * @author Jörn Friedrich Dreyer <jfd@butonic.de>
- * @author Morris Jobke <hey@morrisjobke.de>
- * @author Robin Appelman <robin@icewind.nl>
- * @author Roeland Jago Douma <roeland@famdouma.nl>
- * @author Thomas Müller <thomas.mueller@tmit.eu>
- * @author Vincent Petry <vincent@nextcloud.com>
- *
- * @license AGPL-3.0
- *
- * This code is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License, version 3,
- * as published by the Free Software Foundation.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU Affero General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License, version 3,
- * along with this program. If not, see <http://www.gnu.org/licenses/>
- *
+ * SPDX-FileCopyrightText: 2017-2024 Nextcloud GmbH and Nextcloud contributors
+ * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
+ * SPDX-License-Identifier: AGPL-3.0-only
*/
namespace OCA\Files_Sharing\Tests;
+use OC\Files\Cache\Cache;
+use OC\Files\Filesystem;
+use OC\Files\Storage\Storage;
use OC\Files\Storage\Temporary;
use OC\Files\Storage\Wrapper\Jail;
+use OC\Files\View;
use OCA\Files_Sharing\SharedStorage;
+use OCP\Constants;
+use OCP\Files\Cache\IWatcher;
+use OCP\IUserManager;
+use OCP\Server;
use OCP\Share\IShare;
/**
@@ -42,20 +28,20 @@ use OCP\Share\IShare;
class CacheTest extends TestCase {
/**
- * @var \OC\Files\View
+ * @var View
*/
public $user2View;
- /** @var \OC\Files\Cache\Cache */
+ /** @var Cache */
protected $ownerCache;
- /** @var \OC\Files\Cache\Cache */
+ /** @var Cache */
protected $sharedCache;
- /** @var \OC\Files\Storage\Storage */
+ /** @var Storage */
protected $ownerStorage;
- /** @var \OC\Files\Storage\Storage */
+ /** @var Storage */
protected $sharedStorage;
/** @var \OCP\Share\IManager */
@@ -64,16 +50,16 @@ class CacheTest extends TestCase {
protected function setUp(): void {
parent::setUp();
- $this->shareManager = \OC::$server->getShareManager();
+ $this->shareManager = Server::get(\OCP\Share\IManager::class);
- $userManager = \OC::$server->getUserManager();
+ $userManager = Server::get(IUserManager::class);
$userManager->get(self::TEST_FILES_SHARING_API_USER1)->setDisplayName('User One');
$userManager->get(self::TEST_FILES_SHARING_API_USER2)->setDisplayName('User Two');
self::loginHelper(self::TEST_FILES_SHARING_API_USER1);
- $this->user2View = new \OC\Files\View('/'. self::TEST_FILES_SHARING_API_USER2 . '/files');
+ $this->user2View = new View('/' . self::TEST_FILES_SHARING_API_USER2 . '/files');
// prepare user1's dir structure
$this->view->mkdir('container');
@@ -103,7 +89,7 @@ class CacheTest extends TestCase {
->setShareType(IShare::TYPE_USER)
->setSharedWith(self::TEST_FILES_SHARING_API_USER2)
->setSharedBy(self::TEST_FILES_SHARING_API_USER1)
- ->setPermissions(\OCP\Constants::PERMISSION_ALL);
+ ->setPermissions(Constants::PERMISSION_ALL);
$share = $this->shareManager->createShare($share);
$share->setStatus(IShare::STATUS_ACCEPTED);
$this->shareManager->updateShare($share);
@@ -114,7 +100,7 @@ class CacheTest extends TestCase {
->setShareType(IShare::TYPE_USER)
->setSharedWith(self::TEST_FILES_SHARING_API_USER2)
->setSharedBy(self::TEST_FILES_SHARING_API_USER1)
- ->setPermissions(\OCP\Constants::PERMISSION_ALL & ~(\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_DELETE));
+ ->setPermissions(Constants::PERMISSION_ALL & ~(Constants::PERMISSION_CREATE | Constants::PERMISSION_DELETE));
$share = $this->shareManager->createShare($share);
$share->setStatus(IShare::STATUS_ACCEPTED);
$this->shareManager->updateShare($share);
@@ -123,7 +109,7 @@ class CacheTest extends TestCase {
self::loginHelper(self::TEST_FILES_SHARING_API_USER2);
// retrieve the shared storage
- $secondView = new \OC\Files\View('/' . self::TEST_FILES_SHARING_API_USER2);
+ $secondView = new View('/' . self::TEST_FILES_SHARING_API_USER2);
[$this->sharedStorage,] = $secondView->resolvePath('files/shareddir');
$this->sharedCache = $this->sharedStorage->getCache();
}
@@ -211,7 +197,7 @@ class CacheTest extends TestCase {
* we cannot use a dataProvider because that would cause the stray hook detection to remove the hooks
* that were added in setUpBeforeClass.
*/
- public function testSearch() {
+ public function testSearch(): void {
foreach ($this->searchDataProvider() as $data) {
[$pattern, $expectedFiles] = $data;
@@ -223,7 +209,7 @@ class CacheTest extends TestCase {
/**
* Test searching by mime type
*/
- public function testSearchByMime() {
+ public function testSearchByMime(): void {
$results = $this->sharedStorage->getCache()->searchByMime('text');
$check = [
[
@@ -242,7 +228,7 @@ class CacheTest extends TestCase {
$this->verifyFiles($check, $results);
}
- public function testGetFolderContentsInRoot() {
+ public function testGetFolderContentsInRoot(): void {
$results = $this->user2View->getDirectoryContent('/');
$results = (array_filter($results, function ($file) {
return $file->getName() !== 'welcome.txt';
@@ -272,7 +258,7 @@ class CacheTest extends TestCase {
);
}
- public function testGetFolderContentsInSubdir() {
+ public function testGetFolderContentsInSubdir(): void {
$results = $this->user2View->getDirectoryContent('/shareddir');
$this->verifyFiles(
@@ -310,7 +296,7 @@ class CacheTest extends TestCase {
*
* https://github.com/nextcloud/server/issues/39879
*/
- public function testShareRenameOriginalFileInRecentResults() {
+ public function testShareRenameOriginalFileInRecentResults(): void {
self::loginHelper(self::TEST_FILES_SHARING_API_USER1);
$rootFolder = \OC::$server->getUserFolder(self::TEST_FILES_SHARING_API_USER1);
@@ -320,7 +306,7 @@ class CacheTest extends TestCase {
->setShareType(IShare::TYPE_USER)
->setSharedWith(self::TEST_FILES_SHARING_API_USER3)
->setSharedBy(self::TEST_FILES_SHARING_API_USER1)
- ->setPermissions(\OCP\Constants::PERMISSION_READ);
+ ->setPermissions(Constants::PERMISSION_READ);
$share = $this->shareManager->createShare($share);
$share->setStatus(IShare::STATUS_ACCEPTED);
$this->shareManager->updateShare($share);
@@ -339,7 +325,7 @@ class CacheTest extends TestCase {
}, $recents));
}
- public function testGetFolderContentsWhenSubSubdirShared() {
+ public function testGetFolderContentsWhenSubSubdirShared(): void {
self::loginHelper(self::TEST_FILES_SHARING_API_USER1);
$rootFolder = \OC::$server->getUserFolder(self::TEST_FILES_SHARING_API_USER1);
@@ -349,14 +335,14 @@ class CacheTest extends TestCase {
->setShareType(IShare::TYPE_USER)
->setSharedWith(self::TEST_FILES_SHARING_API_USER3)
->setSharedBy(self::TEST_FILES_SHARING_API_USER1)
- ->setPermissions(\OCP\Constants::PERMISSION_ALL);
+ ->setPermissions(Constants::PERMISSION_ALL);
$share = $this->shareManager->createShare($share);
$share->setStatus(IShare::STATUS_ACCEPTED);
$this->shareManager->updateShare($share);
self::loginHelper(self::TEST_FILES_SHARING_API_USER3);
- $thirdView = new \OC\Files\View('/' . self::TEST_FILES_SHARING_API_USER3 . '/files');
+ $thirdView = new View('/' . self::TEST_FILES_SHARING_API_USER3 . '/files');
$results = $thirdView->getDirectoryContent('/subdir');
$this->verifyFiles(
@@ -423,10 +409,10 @@ class CacheTest extends TestCase {
}
}
- public function testGetPathByIdDirectShare() {
+ public function testGetPathByIdDirectShare(): void {
self::loginHelper(self::TEST_FILES_SHARING_API_USER1);
- \OC\Files\Filesystem::file_put_contents('test.txt', 'foo');
- $info = \OC\Files\Filesystem::getFileInfo('test.txt');
+ Filesystem::file_put_contents('test.txt', 'foo');
+ $info = Filesystem::getFileInfo('test.txt');
$rootFolder = \OC::$server->getUserFolder(self::TEST_FILES_SHARING_API_USER1);
$node = $rootFolder->get('test.txt');
@@ -435,7 +421,7 @@ class CacheTest extends TestCase {
->setShareType(IShare::TYPE_USER)
->setSharedWith(self::TEST_FILES_SHARING_API_USER2)
->setSharedBy(self::TEST_FILES_SHARING_API_USER1)
- ->setPermissions(\OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_SHARE);
+ ->setPermissions(Constants::PERMISSION_READ | Constants::PERMISSION_UPDATE | Constants::PERMISSION_SHARE);
$share = $this->shareManager->createShare($share);
$share->setStatus(IShare::STATUS_ACCEPTED);
$this->shareManager->updateShare($share);
@@ -443,23 +429,22 @@ class CacheTest extends TestCase {
\OC_Util::tearDownFS();
self::loginHelper(self::TEST_FILES_SHARING_API_USER2);
- $this->assertTrue(\OC\Files\Filesystem::file_exists('/test.txt'));
- [$sharedStorage] = \OC\Files\Filesystem::resolvePath('/' . self::TEST_FILES_SHARING_API_USER2 . '/files/test.txt');
+ $this->assertTrue(Filesystem::file_exists('/test.txt'));
+ [$sharedStorage] = Filesystem::resolvePath('/' . self::TEST_FILES_SHARING_API_USER2 . '/files/test.txt');
/**
- * @var \OCA\Files_Sharing\SharedStorage $sharedStorage
+ * @var SharedStorage $sharedStorage
*/
-
$sharedCache = $sharedStorage->getCache();
$this->assertEquals('', $sharedCache->getPathById($info->getId()));
}
- public function testGetPathByIdShareSubFolder() {
+ public function testGetPathByIdShareSubFolder(): void {
self::loginHelper(self::TEST_FILES_SHARING_API_USER1);
- \OC\Files\Filesystem::mkdir('foo');
- \OC\Files\Filesystem::mkdir('foo/bar');
- \OC\Files\Filesystem::touch('foo/bar/test.txt');
- $folderInfo = \OC\Files\Filesystem::getFileInfo('foo');
- $fileInfo = \OC\Files\Filesystem::getFileInfo('foo/bar/test.txt');
+ Filesystem::mkdir('foo');
+ Filesystem::mkdir('foo/bar');
+ Filesystem::touch('foo/bar/test.txt');
+ $folderInfo = Filesystem::getFileInfo('foo');
+ $fileInfo = Filesystem::getFileInfo('foo/bar/test.txt');
$rootFolder = \OC::$server->getUserFolder(self::TEST_FILES_SHARING_API_USER1);
$node = $rootFolder->get('foo');
@@ -468,27 +453,26 @@ class CacheTest extends TestCase {
->setShareType(IShare::TYPE_USER)
->setSharedWith(self::TEST_FILES_SHARING_API_USER2)
->setSharedBy(self::TEST_FILES_SHARING_API_USER1)
- ->setPermissions(\OCP\Constants::PERMISSION_ALL);
+ ->setPermissions(Constants::PERMISSION_ALL);
$share = $this->shareManager->createShare($share);
$share->setStatus(IShare::STATUS_ACCEPTED);
$this->shareManager->updateShare($share);
\OC_Util::tearDownFS();
self::loginHelper(self::TEST_FILES_SHARING_API_USER2);
- $this->assertTrue(\OC\Files\Filesystem::file_exists('/foo'));
- [$sharedStorage] = \OC\Files\Filesystem::resolvePath('/' . self::TEST_FILES_SHARING_API_USER2 . '/files/foo');
+ $this->assertTrue(Filesystem::file_exists('/foo'));
+ [$sharedStorage] = Filesystem::resolvePath('/' . self::TEST_FILES_SHARING_API_USER2 . '/files/foo');
/**
- * @var \OCA\Files_Sharing\SharedStorage $sharedStorage
+ * @var SharedStorage $sharedStorage
*/
-
$sharedCache = $sharedStorage->getCache();
$this->assertEquals('', $sharedCache->getPathById($folderInfo->getId()));
$this->assertEquals('bar/test.txt', $sharedCache->getPathById($fileInfo->getId()));
}
- public function testNumericStorageId() {
+ public function testNumericStorageId(): void {
self::loginHelper(self::TEST_FILES_SHARING_API_USER1);
- \OC\Files\Filesystem::mkdir('foo');
+ Filesystem::mkdir('foo');
$rootFolder = \OC::$server->getUserFolder(self::TEST_FILES_SHARING_API_USER1);
$node = $rootFolder->get('foo');
@@ -497,23 +481,23 @@ class CacheTest extends TestCase {
->setShareType(IShare::TYPE_USER)
->setSharedWith(self::TEST_FILES_SHARING_API_USER2)
->setSharedBy(self::TEST_FILES_SHARING_API_USER1)
- ->setPermissions(\OCP\Constants::PERMISSION_ALL);
+ ->setPermissions(Constants::PERMISSION_ALL);
$share = $this->shareManager->createShare($share);
$share->setStatus(IShare::STATUS_ACCEPTED);
$this->shareManager->updateShare($share);
\OC_Util::tearDownFS();
- [$sourceStorage] = \OC\Files\Filesystem::resolvePath('/' . self::TEST_FILES_SHARING_API_USER1 . '/files/foo');
+ [$sourceStorage] = Filesystem::resolvePath('/' . self::TEST_FILES_SHARING_API_USER1 . '/files/foo');
self::loginHelper(self::TEST_FILES_SHARING_API_USER2);
- $this->assertTrue(\OC\Files\Filesystem::file_exists('/foo'));
+ $this->assertTrue(Filesystem::file_exists('/foo'));
/** @var SharedStorage $sharedStorage */
- [$sharedStorage] = \OC\Files\Filesystem::resolvePath('/' . self::TEST_FILES_SHARING_API_USER2 . '/files/foo');
+ [$sharedStorage] = Filesystem::resolvePath('/' . self::TEST_FILES_SHARING_API_USER2 . '/files/foo');
$this->assertEquals($sourceStorage->getCache()->getNumericStorageId(), $sharedStorage->getCache()->getNumericStorageId());
}
- public function testShareJailedStorage() {
+ public function testShareJailedStorage(): void {
$sourceStorage = new Temporary();
$sourceStorage->mkdir('jail');
$sourceStorage->mkdir('jail/sub');
@@ -534,25 +518,25 @@ class CacheTest extends TestCase {
->setShareType(IShare::TYPE_USER)
->setSharedWith(self::TEST_FILES_SHARING_API_USER2)
->setSharedBy(self::TEST_FILES_SHARING_API_USER1)
- ->setPermissions(\OCP\Constants::PERMISSION_ALL);
+ ->setPermissions(Constants::PERMISSION_ALL);
$share = $this->shareManager->createShare($share);
$share->setStatus(IShare::STATUS_ACCEPTED);
$this->shareManager->updateShare($share);
\OC_Util::tearDownFS();
self::loginHelper(self::TEST_FILES_SHARING_API_USER2);
- $this->assertEquals('foo', \OC\Files\Filesystem::file_get_contents('/sub/foo.txt'));
+ $this->assertEquals('foo', Filesystem::file_get_contents('/sub/foo.txt'));
- \OC\Files\Filesystem::file_put_contents('/sub/bar.txt', 'bar');
+ Filesystem::file_put_contents('/sub/bar.txt', 'bar');
/** @var SharedStorage $sharedStorage */
- [$sharedStorage] = \OC\Files\Filesystem::resolvePath('/' . self::TEST_FILES_SHARING_API_USER2 . '/files/sub');
+ [$sharedStorage] = Filesystem::resolvePath('/' . self::TEST_FILES_SHARING_API_USER2 . '/files/sub');
$this->assertTrue($sharedStorage->getCache()->inCache('bar.txt'));
$this->assertTrue($sourceStorage->getCache()->inCache('jail/sub/bar.txt'));
}
- public function testSearchShareJailedStorage() {
+ public function testSearchShareJailedStorage(): void {
$sourceStorage = new Temporary();
$sourceStorage->mkdir('jail');
$sourceStorage->mkdir('jail/sub');
@@ -573,7 +557,7 @@ class CacheTest extends TestCase {
->setShareType(IShare::TYPE_USER)
->setSharedWith(self::TEST_FILES_SHARING_API_USER2)
->setSharedBy(self::TEST_FILES_SHARING_API_USER1)
- ->setPermissions(\OCP\Constants::PERMISSION_ALL);
+ ->setPermissions(Constants::PERMISSION_ALL);
$share = $this->shareManager->createShare($share);
$share->setStatus(IShare::STATUS_ACCEPTED);
$this->shareManager->updateShare($share);
@@ -582,9 +566,43 @@ class CacheTest extends TestCase {
self::loginHelper(self::TEST_FILES_SHARING_API_USER2);
/** @var SharedStorage $sharedStorage */
- [$sharedStorage] = \OC\Files\Filesystem::resolvePath('/' . self::TEST_FILES_SHARING_API_USER2 . '/files/sub');
+ [$sharedStorage] = Filesystem::resolvePath('/' . self::TEST_FILES_SHARING_API_USER2 . '/files/sub');
- $results = $sharedStorage->getCache()->search("foo.txt");
+ $results = $sharedStorage->getCache()->search('foo.txt');
$this->assertCount(1, $results);
}
+
+ public function testWatcherRootChange() {
+ $sourceStorage = new Temporary();
+ $sourceStorage->mkdir('shared');
+ $sourceStorage->file_put_contents('shared/foo.txt', 'foo');
+ $sourceStorage->getScanner()->scan('');
+ $sourceStorage->getWatcher()->setPolicy(IWatcher::CHECK_ALWAYS);
+ $this->registerMount(self::TEST_FILES_SHARING_API_USER1, $sourceStorage, '/' . self::TEST_FILES_SHARING_API_USER1 . '/files/foo');
+
+ self::loginHelper(self::TEST_FILES_SHARING_API_USER1);
+
+ $rootFolder = \OC::$server->getUserFolder(self::TEST_FILES_SHARING_API_USER1);
+ $node = $rootFolder->get('foo/shared');
+ $this->assertEquals(3, $node->getSize());
+
+ $share = $this->shareManager->newShare();
+ $share->setNode($node)
+ ->setShareType(IShare::TYPE_USER)
+ ->setSharedWith(self::TEST_FILES_SHARING_API_USER2)
+ ->setSharedBy(self::TEST_FILES_SHARING_API_USER1)
+ ->setPermissions(Constants::PERMISSION_ALL);
+ $share = $this->shareManager->createShare($share);
+ $share->setStatus(IShare::STATUS_ACCEPTED);
+ $this->shareManager->updateShare($share);
+ \OC_Util::tearDownFS();
+
+ self::loginHelper(self::TEST_FILES_SHARING_API_USER2);
+
+ $view = Filesystem::getView();
+
+ $sourceStorage->rmdir('shared');
+
+ $this->assertFalse($view->getFileInfo('shared'));
+ }
}
diff --git a/apps/files_sharing/tests/CapabilitiesTest.php b/apps/files_sharing/tests/CapabilitiesTest.php
index 100c7759900..9a076d7a171 100644
--- a/apps/files_sharing/tests/CapabilitiesTest.php
+++ b/apps/files_sharing/tests/CapabilitiesTest.php
@@ -1,30 +1,9 @@
<?php
+
/**
- * @copyright Copyright (c) 2016, ownCloud, Inc.
- *
- * @author Bjoern Schiessle <bjoern@schiessle.org>
- * @author Christoph Wurst <christoph@winzerhof-wurst.at>
- * @author Joas Schilling <coding@schilljs.com>
- * @author Morris Jobke <hey@morrisjobke.de>
- * @author Robin Appelman <robin@icewind.nl>
- * @author Roeland Jago Douma <roeland@famdouma.nl>
- * @author Thomas Müller <thomas.mueller@tmit.eu>
- * @author Vincent Petry <vincent@nextcloud.com>
- *
- * @license AGPL-3.0
- *
- * This code is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License, version 3,
- * as published by the Free Software Foundation.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU Affero General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License, version 3,
- * along with this program. If not, see <http://www.gnu.org/licenses/>
- *
+ * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
+ * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
+ * SPDX-License-Identifier: AGPL-3.0-only
*/
namespace OCA\Files_Sharing\Tests;
@@ -32,9 +11,11 @@ use OC\KnownUser\KnownUserService;
use OC\Share20\Manager;
use OC\Share20\ShareDisableChecker;
use OCA\Files_Sharing\Capabilities;
+use OCP\App\IAppManager;
use OCP\EventDispatcher\IEventDispatcher;
use OCP\Files\IRootFolder;
use OCP\Files\Mount\IMountManager;
+use OCP\IAppConfig;
use OCP\IConfig;
use OCP\IDateTimeZone;
use OCP\IGroupManager;
@@ -75,9 +56,30 @@ class CapabilitiesTest extends \Test\TestCase {
* @param (string[])[] $map Map of arguments to return types for the getAppValue function in the mock
* @return string[]
*/
- private function getResults(array $map) {
+ private function getResults(array $map, array $typedMap = [], bool $federationEnabled = true) {
$config = $this->getMockBuilder(IConfig::class)->disableOriginalConstructor()->getMock();
+ $appManager = $this->getMockBuilder(IAppManager::class)->disableOriginalConstructor()->getMock();
$config->method('getAppValue')->willReturnMap($map);
+ $appManager->method('isEnabledForAnyone')->with('federation')->willReturn($federationEnabled);
+
+ if (empty($typedMap)) {
+ $appConfig = $this->createMock(IAppConfig::class);
+ } else {
+ // hack to help transition from old IConfig to new IAppConfig
+ $appConfig = $this->getMockBuilder(IAppConfig::class)->disableOriginalConstructor()->getMock();
+ $appConfig->expects($this->any())->method('getValueBool')->willReturnCallback(function (...$args) use ($typedMap): bool {
+ foreach ($typedMap as $entry) {
+ if ($entry[0] !== $args[0] || $entry[1] !== $args[1]) {
+ continue;
+ }
+
+ return $entry[2];
+ }
+
+ return false;
+ });
+ }
+
$shareManager = new Manager(
$this->createMock(LoggerInterface::class),
$config,
@@ -97,13 +99,15 @@ class CapabilitiesTest extends \Test\TestCase {
$this->createMock(KnownUserService::class),
$this->createMock(ShareDisableChecker::class),
$this->createMock(IDateTimeZone::class),
+ $appConfig,
);
- $cap = new Capabilities($config, $shareManager);
+
+ $cap = new Capabilities($config, $appConfig, $shareManager, $appManager);
$result = $this->getFilesSharingPart($cap->getCapabilities());
return $result;
}
- public function testEnabledSharingAPI() {
+ public function testEnabledSharingAPI(): void {
$map = [
['core', 'shareapi_enabled', 'yes', 'yes'],
];
@@ -114,7 +118,7 @@ class CapabilitiesTest extends \Test\TestCase {
$this->assertArrayHasKey('resharing', $result);
}
- public function testDisabledSharingAPI() {
+ public function testDisabledSharingAPI(): void {
$map = [
['core', 'shareapi_enabled', 'yes', 'no'],
];
@@ -125,7 +129,7 @@ class CapabilitiesTest extends \Test\TestCase {
$this->assertFalse($result['resharing']);
}
- public function testNoLinkSharing() {
+ public function testNoLinkSharing(): void {
$map = [
['core', 'shareapi_enabled', 'yes', 'yes'],
['core', 'shareapi_allow_links', 'yes', 'no'],
@@ -135,7 +139,7 @@ class CapabilitiesTest extends \Test\TestCase {
$this->assertFalse($result['public']['enabled']);
}
- public function testOnlyLinkSharing() {
+ public function testOnlyLinkSharing(): void {
$map = [
['core', 'shareapi_enabled', 'yes', 'yes'],
['core', 'shareapi_allow_links', 'yes', 'yes'],
@@ -146,20 +150,22 @@ class CapabilitiesTest extends \Test\TestCase {
$this->assertTrue($result['public']['enabled']);
}
- public function testLinkPassword() {
+ public function testLinkPassword(): void {
$map = [
['core', 'shareapi_enabled', 'yes', 'yes'],
['core', 'shareapi_allow_links', 'yes', 'yes'],
['core', 'shareapi_enforce_links_password_excluded_groups', '', ''],
- ['core', 'shareapi_enforce_links_password', 'no', 'yes'],
];
- $result = $this->getResults($map);
+ $typedMap = [
+ ['core', 'shareapi_enforce_links_password', true],
+ ];
+ $result = $this->getResults($map, $typedMap);
$this->assertArrayHasKey('password', $result['public']);
$this->assertArrayHasKey('enforced', $result['public']['password']);
$this->assertTrue($result['public']['password']['enforced']);
}
- public function testLinkNoPassword() {
+ public function testLinkNoPassword(): void {
$map = [
['core', 'shareapi_enabled', 'yes', 'yes'],
['core', 'shareapi_allow_links', 'yes', 'yes'],
@@ -172,7 +178,7 @@ class CapabilitiesTest extends \Test\TestCase {
$this->assertFalse($result['public']['password']['enforced']);
}
- public function testLinkNoExpireDate() {
+ public function testLinkNoExpireDate(): void {
$map = [
['core', 'shareapi_enabled', 'yes', 'yes'],
['core', 'shareapi_allow_links', 'yes', 'yes'],
@@ -185,7 +191,7 @@ class CapabilitiesTest extends \Test\TestCase {
$this->assertFalse($result['public']['expire_date']['enabled']);
}
- public function testLinkExpireDate() {
+ public function testLinkExpireDate(): void {
$map = [
['core', 'shareapi_enabled', 'yes', 'yes'],
['core', 'shareapi_allow_links', 'yes', 'yes'],
@@ -202,7 +208,7 @@ class CapabilitiesTest extends \Test\TestCase {
$this->assertFalse($result['public']['expire_date']['enforced']);
}
- public function testLinkExpireDateEnforced() {
+ public function testLinkExpireDateEnforced(): void {
$map = [
['core', 'shareapi_enabled', 'yes', 'yes'],
['core', 'shareapi_allow_links', 'yes', 'yes'],
@@ -216,7 +222,7 @@ class CapabilitiesTest extends \Test\TestCase {
$this->assertTrue($result['public']['expire_date']['enforced']);
}
- public function testLinkSendMail() {
+ public function testLinkSendMail(): void {
$map = [
['core', 'shareapi_enabled', 'yes', 'yes'],
['core', 'shareapi_allow_links', 'yes', 'yes'],
@@ -227,7 +233,7 @@ class CapabilitiesTest extends \Test\TestCase {
$this->assertTrue($result['public']['send_mail']);
}
- public function testLinkNoSendMail() {
+ public function testLinkNoSendMail(): void {
$map = [
['core', 'shareapi_enabled', 'yes', 'yes'],
['core', 'shareapi_allow_links', 'yes', 'yes'],
@@ -238,7 +244,7 @@ class CapabilitiesTest extends \Test\TestCase {
$this->assertFalse($result['public']['send_mail']);
}
- public function testResharing() {
+ public function testResharing(): void {
$map = [
['core', 'shareapi_enabled', 'yes', 'yes'],
['core', 'shareapi_allow_resharing', 'yes', 'yes'],
@@ -248,7 +254,7 @@ class CapabilitiesTest extends \Test\TestCase {
$this->assertTrue($result['resharing']);
}
- public function testNoResharing() {
+ public function testNoResharing(): void {
$map = [
['core', 'shareapi_enabled', 'yes', 'yes'],
['core', 'shareapi_allow_resharing', 'yes', 'no'],
@@ -258,7 +264,7 @@ class CapabilitiesTest extends \Test\TestCase {
$this->assertFalse($result['resharing']);
}
- public function testLinkPublicUpload() {
+ public function testLinkPublicUpload(): void {
$map = [
['core', 'shareapi_enabled', 'yes', 'yes'],
['core', 'shareapi_allow_links', 'yes', 'yes'],
@@ -270,7 +276,7 @@ class CapabilitiesTest extends \Test\TestCase {
$this->assertTrue($result['public']['upload_files_drop']);
}
- public function testLinkNoPublicUpload() {
+ public function testLinkNoPublicUpload(): void {
$map = [
['core', 'shareapi_enabled', 'yes', 'yes'],
['core', 'shareapi_allow_links', 'yes', 'yes'],
@@ -282,7 +288,7 @@ class CapabilitiesTest extends \Test\TestCase {
$this->assertFalse($result['public']['upload_files_drop']);
}
- public function testNoGroupSharing() {
+ public function testNoGroupSharing(): void {
$map = [
['core', 'shareapi_enabled', 'yes', 'yes'],
['core', 'shareapi_allow_group_sharing', 'yes', 'no'],
@@ -291,7 +297,7 @@ class CapabilitiesTest extends \Test\TestCase {
$this->assertFalse($result['group_sharing']);
}
- public function testGroupSharing() {
+ public function testGroupSharing(): void {
$map = [
['core', 'shareapi_enabled', 'yes', 'yes'],
['core', 'shareapi_allow_group_sharing', 'yes', 'yes'],
@@ -300,7 +306,7 @@ class CapabilitiesTest extends \Test\TestCase {
$this->assertTrue($result['group_sharing']);
}
- public function testFederatedSharingIncoming() {
+ public function testFederatedSharingIncoming(): void {
$map = [
['files_sharing', 'incoming_server2server_share_enabled', 'yes', 'yes'],
];
@@ -309,7 +315,7 @@ class CapabilitiesTest extends \Test\TestCase {
$this->assertTrue($result['federation']['incoming']);
}
- public function testFederatedSharingNoIncoming() {
+ public function testFederatedSharingNoIncoming(): void {
$map = [
['files_sharing', 'incoming_server2server_share_enabled', 'yes', 'no'],
];
@@ -318,7 +324,7 @@ class CapabilitiesTest extends \Test\TestCase {
$this->assertFalse($result['federation']['incoming']);
}
- public function testFederatedSharingOutgoing() {
+ public function testFederatedSharingOutgoing(): void {
$map = [
['files_sharing', 'outgoing_server2server_share_enabled', 'yes', 'yes'],
];
@@ -327,7 +333,7 @@ class CapabilitiesTest extends \Test\TestCase {
$this->assertTrue($result['federation']['outgoing']);
}
- public function testFederatedSharingNoOutgoing() {
+ public function testFederatedSharingNoOutgoing(): void {
$map = [
['files_sharing', 'outgoing_server2server_share_enabled', 'yes', 'no'],
];
@@ -336,10 +342,19 @@ class CapabilitiesTest extends \Test\TestCase {
$this->assertFalse($result['federation']['outgoing']);
}
- public function testFederatedSharingExpirationDate() {
+ public function testFederatedSharingExpirationDate(): void {
$result = $this->getResults([]);
$this->assertArrayHasKey('federation', $result);
$this->assertEquals(['enabled' => true], $result['federation']['expire_date']);
$this->assertEquals(['enabled' => true], $result['federation']['expire_date_supported']);
}
+
+ public function testFederatedSharingDisabled(): void {
+ $result = $this->getResults([], federationEnabled: false);
+ $this->assertArrayHasKey('federation', $result);
+ $this->assertFalse($result['federation']['incoming']);
+ $this->assertFalse($result['federation']['outgoing']);
+ $this->assertEquals(['enabled' => false], $result['federation']['expire_date']);
+ $this->assertEquals(['enabled' => false], $result['federation']['expire_date_supported']);
+ }
}
diff --git a/apps/files_sharing/tests/Collaboration/ShareRecipientSorterTest.php b/apps/files_sharing/tests/Collaboration/ShareRecipientSorterTest.php
index 6e1aa65cea8..572463a9ebc 100644
--- a/apps/files_sharing/tests/Collaboration/ShareRecipientSorterTest.php
+++ b/apps/files_sharing/tests/Collaboration/ShareRecipientSorterTest.php
@@ -1,26 +1,8 @@
<?php
+
/**
- * @copyright Copyright (c) 2017 Arthur Schiwon <blizzz@arthur-schiwon.de>
- *
- * @author Arthur Schiwon <blizzz@arthur-schiwon.de>
- * @author Morris Jobke <hey@morrisjobke.de>
- * @author Roeland Jago Douma <roeland@famdouma.nl>
- *
- * @license GNU AGPL version 3 or any later version
- *
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License as
- * published by the Free Software Foundation, either version 3 of the
- * License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU Affero General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- *
+ * SPDX-FileCopyrightText: 2017 Nextcloud GmbH and Nextcloud contributors
+ * SPDX-License-Identifier: AGPL-3.0-or-later
*/
namespace OCA\Files_Sharing\Tests\Collaboration;
@@ -34,13 +16,13 @@ use OCP\Share\IManager;
use Test\TestCase;
class ShareRecipientSorterTest extends TestCase {
- /** @var IManager|\PHPUnit\Framework\MockObject\MockObject */
+ /** @var IManager|\PHPUnit\Framework\MockObject\MockObject */
protected $shareManager;
- /** @var IRootFolder|\PHPUnit\Framework\MockObject\MockObject */
+ /** @var IRootFolder|\PHPUnit\Framework\MockObject\MockObject */
protected $rootFolder;
- /** @var IUserSession|\PHPUnit\Framework\MockObject\MockObject */
+ /** @var IUserSession|\PHPUnit\Framework\MockObject\MockObject */
protected $userSession;
- /** @var ShareRecipientSorter */
+ /** @var ShareRecipientSorter */
protected $sorter;
protected function setUp(): void {
@@ -54,10 +36,10 @@ class ShareRecipientSorterTest extends TestCase {
}
/**
- * @dataProvider sortDataProvider
* @param $data
*/
- public function testSort($data) {
+ #[\PHPUnit\Framework\Attributes\DataProvider('sortDataProvider')]
+ public function testSort($data): void {
$node = $this->createMock(Node::class);
/** @var Folder|\PHPUnit\Framework\MockObject\MockObject $folder */
@@ -98,7 +80,7 @@ class ShareRecipientSorterTest extends TestCase {
$this->assertEquals($data['expected'], $workArray);
}
- public function testSortNoNodes() {
+ public function testSortNoNodes(): void {
/** @var Folder|\PHPUnit\Framework\MockObject\MockObject $folder */
$folder = $this->createMock(Folder::class);
$this->rootFolder->expects($this->any())
@@ -128,44 +110,42 @@ class ShareRecipientSorterTest extends TestCase {
]
];
$workArray = $originalArray;
- $this->sorter->sort($workArray, ['itemType' => 'files', 'itemId' => 404]);
+ $this->sorter->sort($workArray, ['itemType' => 'files', 'itemId' => '404']);
$this->assertEquals($originalArray, $workArray);
}
- public function sortDataProvider() {
+ public static function sortDataProvider() {
return [[
[
#0 – sort properly and otherwise keep existing order
- 'context' => ['itemType' => 'files', 'itemId' => 42],
+ 'context' => ['itemType' => 'files', 'itemId' => '42'],
'accessList' => ['users' => ['celia', 'darius', 'faruk', 'gail'], 'bots' => ['r2-d2']],
'input' => [
- 'users' =>
- [
- ['value' => ['shareWith' => 'alice']],
- ['value' => ['shareWith' => 'bob']],
- ['value' => ['shareWith' => 'celia']],
- ['value' => ['shareWith' => 'darius']],
- ['value' => ['shareWith' => 'elena']],
- ['value' => ['shareWith' => 'faruk']],
- ['value' => ['shareWith' => 'gail']],
- ],
+ 'users' => [
+ ['value' => ['shareWith' => 'alice']],
+ ['value' => ['shareWith' => 'bob']],
+ ['value' => ['shareWith' => 'celia']],
+ ['value' => ['shareWith' => 'darius']],
+ ['value' => ['shareWith' => 'elena']],
+ ['value' => ['shareWith' => 'faruk']],
+ ['value' => ['shareWith' => 'gail']],
+ ],
'bots' => [
['value' => ['shareWith' => 'c-3po']],
['value' => ['shareWith' => 'r2-d2']],
]
],
'expected' => [
- 'users' =>
- [
- ['value' => ['shareWith' => 'celia']],
- ['value' => ['shareWith' => 'darius']],
- ['value' => ['shareWith' => 'faruk']],
- ['value' => ['shareWith' => 'gail']],
- ['value' => ['shareWith' => 'alice']],
- ['value' => ['shareWith' => 'bob']],
- ['value' => ['shareWith' => 'elena']],
- ],
+ 'users' => [
+ ['value' => ['shareWith' => 'celia']],
+ ['value' => ['shareWith' => 'darius']],
+ ['value' => ['shareWith' => 'faruk']],
+ ['value' => ['shareWith' => 'gail']],
+ ['value' => ['shareWith' => 'alice']],
+ ['value' => ['shareWith' => 'bob']],
+ ['value' => ['shareWith' => 'elena']],
+ ],
'bots' => [
['value' => ['shareWith' => 'r2-d2']],
['value' => ['shareWith' => 'c-3po']],
@@ -174,35 +154,33 @@ class ShareRecipientSorterTest extends TestCase {
],
[
#1 – no recipients
- 'context' => ['itemType' => 'files', 'itemId' => 42],
+ 'context' => ['itemType' => 'files', 'itemId' => '42'],
'accessList' => ['users' => false],
'input' => [
- 'users' =>
- [
- ['value' => ['shareWith' => 'alice']],
- ['value' => ['shareWith' => 'bob']],
- ['value' => ['shareWith' => 'celia']],
- ['value' => ['shareWith' => 'darius']],
- ['value' => ['shareWith' => 'elena']],
- ['value' => ['shareWith' => 'faruk']],
- ['value' => ['shareWith' => 'gail']],
- ],
+ 'users' => [
+ ['value' => ['shareWith' => 'alice']],
+ ['value' => ['shareWith' => 'bob']],
+ ['value' => ['shareWith' => 'celia']],
+ ['value' => ['shareWith' => 'darius']],
+ ['value' => ['shareWith' => 'elena']],
+ ['value' => ['shareWith' => 'faruk']],
+ ['value' => ['shareWith' => 'gail']],
+ ],
'bots' => [
['value' => ['shareWith' => 'c-3po']],
['value' => ['shareWith' => 'r2-d2']],
]
],
'expected' => [
- 'users' =>
- [
- ['value' => ['shareWith' => 'alice']],
- ['value' => ['shareWith' => 'bob']],
- ['value' => ['shareWith' => 'celia']],
- ['value' => ['shareWith' => 'darius']],
- ['value' => ['shareWith' => 'elena']],
- ['value' => ['shareWith' => 'faruk']],
- ['value' => ['shareWith' => 'gail']],
- ],
+ 'users' => [
+ ['value' => ['shareWith' => 'alice']],
+ ['value' => ['shareWith' => 'bob']],
+ ['value' => ['shareWith' => 'celia']],
+ ['value' => ['shareWith' => 'darius']],
+ ['value' => ['shareWith' => 'elena']],
+ ['value' => ['shareWith' => 'faruk']],
+ ['value' => ['shareWith' => 'gail']],
+ ],
'bots' => [
['value' => ['shareWith' => 'c-3po']],
['value' => ['shareWith' => 'r2-d2']],
@@ -211,35 +189,33 @@ class ShareRecipientSorterTest extends TestCase {
],
[
#2 – unsupported item type
- 'context' => ['itemType' => 'announcements', 'itemId' => 42],
+ 'context' => ['itemType' => 'announcements', 'itemId' => '42'],
'accessList' => null, // not needed
'input' => [
- 'users' =>
- [
- ['value' => ['shareWith' => 'alice']],
- ['value' => ['shareWith' => 'bob']],
- ['value' => ['shareWith' => 'celia']],
- ['value' => ['shareWith' => 'darius']],
- ['value' => ['shareWith' => 'elena']],
- ['value' => ['shareWith' => 'faruk']],
- ['value' => ['shareWith' => 'gail']],
- ],
+ 'users' => [
+ ['value' => ['shareWith' => 'alice']],
+ ['value' => ['shareWith' => 'bob']],
+ ['value' => ['shareWith' => 'celia']],
+ ['value' => ['shareWith' => 'darius']],
+ ['value' => ['shareWith' => 'elena']],
+ ['value' => ['shareWith' => 'faruk']],
+ ['value' => ['shareWith' => 'gail']],
+ ],
'bots' => [
['value' => ['shareWith' => 'c-3po']],
['value' => ['shareWith' => 'r2-d2']],
]
],
'expected' => [
- 'users' =>
- [
- ['value' => ['shareWith' => 'alice']],
- ['value' => ['shareWith' => 'bob']],
- ['value' => ['shareWith' => 'celia']],
- ['value' => ['shareWith' => 'darius']],
- ['value' => ['shareWith' => 'elena']],
- ['value' => ['shareWith' => 'faruk']],
- ['value' => ['shareWith' => 'gail']],
- ],
+ 'users' => [
+ ['value' => ['shareWith' => 'alice']],
+ ['value' => ['shareWith' => 'bob']],
+ ['value' => ['shareWith' => 'celia']],
+ ['value' => ['shareWith' => 'darius']],
+ ['value' => ['shareWith' => 'elena']],
+ ['value' => ['shareWith' => 'faruk']],
+ ['value' => ['shareWith' => 'gail']],
+ ],
'bots' => [
['value' => ['shareWith' => 'c-3po']],
['value' => ['shareWith' => 'r2-d2']],
@@ -248,7 +224,7 @@ class ShareRecipientSorterTest extends TestCase {
],
[
#3 – no nothing
- 'context' => ['itemType' => 'files', 'itemId' => 42],
+ 'context' => ['itemType' => 'files', 'itemId' => '42'],
'accessList' => [],
'input' => [],
'expected' => [],
diff --git a/apps/files_sharing/tests/Command/CleanupRemoteStoragesTest.php b/apps/files_sharing/tests/Command/CleanupRemoteStoragesTest.php
index 5738610d0a5..6f0960bf46c 100644
--- a/apps/files_sharing/tests/Command/CleanupRemoteStoragesTest.php
+++ b/apps/files_sharing/tests/Command/CleanupRemoteStoragesTest.php
@@ -1,33 +1,18 @@
<?php
+
/**
- * @copyright Copyright (c) 2016, ownCloud GmbH.
- *
- * @author Daniel Calviño Sánchez <danxuliu@gmail.com>
- * @author Joas Schilling <coding@schilljs.com>
- * @author Jörn Friedrich Dreyer <jfd@butonic.de>
- * @author Morris Jobke <hey@morrisjobke.de>
- * @author Roeland Jago Douma <roeland@famdouma.nl>
- *
- * @license AGPL-3.0
- *
- * This code is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License, version 3,
- * as published by the Free Software Foundation.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU Affero General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License, version 3,
- * along with this program. If not, see <http://www.gnu.org/licenses/>
- *
+ * SPDX-FileCopyrightText: 2017-2024 Nextcloud GmbH and Nextcloud contributors
+ * SPDX-FileCopyrightText: 2016 ownCloud GmbH.
+ * SPDX-License-Identifier: AGPL-3.0-only
*/
namespace OCA\Files_Sharing\Tests\Command;
use OCA\Files_Sharing\Command\CleanupRemoteStorages;
use OCP\Federation\ICloudId;
use OCP\Federation\ICloudIdManager;
+use OCP\IDBConnection;
+use OCP\Server;
+use PHPUnit\Framework\MockObject\MockObject;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Test\TestCase;
@@ -41,20 +26,9 @@ use Test\TestCase;
*/
class CleanupRemoteStoragesTest extends TestCase {
- /**
- * @var CleanupRemoteStorages
- */
- private $command;
-
- /**
- * @var \OCP\IDBConnection
- */
- private $connection;
-
- /**
- * @var ICloudIdManager|\PHPUnit\Framework\MockObject\MockObject
- */
- private $cloudIdManager;
+ protected IDBConnection $connection;
+ protected CleanupRemoteStorages $command;
+ private ICloudIdManager&MockObject $cloudIdManager;
private $storages = [
['id' => 'shared::7b4a322b22f9d0047c38d77d471ce3cf', 'share_token' => 'f2c69dad1dc0649f26976fd210fc62e1', 'remote' => 'https://hostname.tld/owncloud1', 'user' => 'user1'],
@@ -69,52 +43,52 @@ class CleanupRemoteStoragesTest extends TestCase {
protected function setUp(): void {
parent::setUp();
- $this->connection = \OC::$server->getDatabaseConnection();
+ $this->connection = Server::get(IDBConnection::class);
- $storageQuery = \OC::$server->getDatabaseConnection()->getQueryBuilder();
+ $storageQuery = Server::get(IDBConnection::class)->getQueryBuilder();
$storageQuery->insert('storages')
- ->setValue('id', '?');
+ ->setValue('id', $storageQuery->createParameter('id'));
- $shareExternalQuery = \OC::$server->getDatabaseConnection()->getQueryBuilder();
+ $shareExternalQuery = Server::get(IDBConnection::class)->getQueryBuilder();
$shareExternalQuery->insert('share_external')
- ->setValue('share_token', '?')
- ->setValue('remote', '?')
- ->setValue('name', '?')
- ->setValue('owner', '?')
- ->setValue('user', '?')
- ->setValue('mountpoint', '?')
- ->setValue('mountpoint_hash', '?');
-
- $filesQuery = \OC::$server->getDatabaseConnection()->getQueryBuilder();
+ ->setValue('share_token', $shareExternalQuery->createParameter('share_token'))
+ ->setValue('remote', $shareExternalQuery->createParameter('remote'))
+ ->setValue('name', $shareExternalQuery->createParameter('name'))
+ ->setValue('owner', $shareExternalQuery->createParameter('owner'))
+ ->setValue('user', $shareExternalQuery->createParameter('user'))
+ ->setValue('mountpoint', $shareExternalQuery->createParameter('mountpoint'))
+ ->setValue('mountpoint_hash', $shareExternalQuery->createParameter('mountpoint_hash'));
+
+ $filesQuery = Server::get(IDBConnection::class)->getQueryBuilder();
$filesQuery->insert('filecache')
- ->setValue('storage', '?')
- ->setValue('path', '?')
- ->setValue('path_hash', '?');
+ ->setValue('storage', $filesQuery->createParameter('storage'))
+ ->setValue('path', $filesQuery->createParameter('path'))
+ ->setValue('path_hash', $filesQuery->createParameter('path_hash'));
foreach ($this->storages as &$storage) {
if (isset($storage['id'])) {
- $storageQuery->setParameter(0, $storage['id']);
- $storageQuery->execute();
+ $storageQuery->setParameter('id', $storage['id']);
+ $storageQuery->executeStatement();
$storage['numeric_id'] = $storageQuery->getLastInsertId();
}
if (isset($storage['share_token'])) {
$shareExternalQuery
- ->setParameter(0, $storage['share_token'])
- ->setParameter(1, $storage['remote'])
- ->setParameter(2, 'irrelevant')
- ->setParameter(3, 'irrelevant')
- ->setParameter(4, $storage['user'])
- ->setParameter(5, 'irrelevant')
- ->setParameter(6, 'irrelevant');
+ ->setParameter('share_token', $storage['share_token'])
+ ->setParameter('remote', $storage['remote'])
+ ->setParameter('name', 'irrelevant')
+ ->setParameter('owner', 'irrelevant')
+ ->setParameter('user', $storage['user'])
+ ->setParameter('mountpoint', 'irrelevant')
+ ->setParameter('mountpoint_hash', 'irrelevant');
$shareExternalQuery->executeStatement();
}
if (isset($storage['files_count'])) {
for ($i = 0; $i < $storage['files_count']; $i++) {
- $filesQuery->setParameter(0, $storage['numeric_id']);
- $filesQuery->setParameter(1, 'file' . $i);
- $filesQuery->setParameter(2, md5('file' . $i));
+ $filesQuery->setParameter('storage', $storage['numeric_id']);
+ $filesQuery->setParameter('path', 'file' . $i);
+ $filesQuery->setParameter('path_hash', md5('file' . $i));
$filesQuery->executeStatement();
}
}
@@ -126,11 +100,11 @@ class CleanupRemoteStoragesTest extends TestCase {
}
protected function tearDown(): void {
- $storageQuery = \OC::$server->getDatabaseConnection()->getQueryBuilder();
+ $storageQuery = Server::get(IDBConnection::class)->getQueryBuilder();
$storageQuery->delete('storages')
->where($storageQuery->expr()->eq('id', $storageQuery->createParameter('id')));
- $shareExternalQuery = \OC::$server->getDatabaseConnection()->getQueryBuilder();
+ $shareExternalQuery = Server::get(IDBConnection::class)->getQueryBuilder();
$shareExternalQuery->delete('share_external')
->where($shareExternalQuery->expr()->eq('share_token', $shareExternalQuery->createParameter('share_token')))
->andWhere($shareExternalQuery->expr()->eq('remote', $shareExternalQuery->createParameter('remote')));
@@ -138,13 +112,13 @@ class CleanupRemoteStoragesTest extends TestCase {
foreach ($this->storages as $storage) {
if (isset($storage['id'])) {
$storageQuery->setParameter('id', $storage['id']);
- $storageQuery->execute();
+ $storageQuery->executeStatement();
}
if (isset($storage['share_token'])) {
$shareExternalQuery->setParameter('share_token', $storage['share_token']);
$shareExternalQuery->setParameter('remote', $storage['remote']);
- $shareExternalQuery->execute();
+ $shareExternalQuery->executeStatement();
}
}
@@ -152,7 +126,7 @@ class CleanupRemoteStoragesTest extends TestCase {
}
private function doesStorageExist($numericId) {
- $qb = \OC::$server->getDatabaseConnection()->getQueryBuilder();
+ $qb = Server::get(IDBConnection::class)->getQueryBuilder();
$qb->select('*')
->from('storages')
->where($qb->expr()->eq('numeric_id', $qb->createNamedParameter($numericId)));
@@ -164,7 +138,7 @@ class CleanupRemoteStoragesTest extends TestCase {
return true;
}
- $qb = \OC::$server->getDatabaseConnection()->getQueryBuilder();
+ $qb = Server::get(IDBConnection::class)->getQueryBuilder();
$qb->select('*')
->from('filecache')
->where($qb->expr()->eq('storage', $qb->createNamedParameter($numericId)));
@@ -182,7 +156,7 @@ class CleanupRemoteStoragesTest extends TestCase {
/**
* Test cleanup of orphaned storages
*/
- public function testCleanup() {
+ public function testCleanup(): void {
$input = $this->getMockBuilder(InputInterface::class)
->disableOriginalConstructor()
->getMock();
@@ -191,19 +165,18 @@ class CleanupRemoteStoragesTest extends TestCase {
->getMock();
// parent folder, `files`, ´test` and `welcome.txt` => 4 elements
-
+ $outputCalls = [];
$output
->expects($this->any())
->method('writeln')
- ->withConsecutive(
- ['5 remote storage(s) need(s) to be checked'],
- ['5 remote share(s) exist'],
- );
+ ->willReturnCallback(function (string $text) use (&$outputCalls): void {
+ $outputCalls[] = $text;
+ });
$this->cloudIdManager
->expects($this->any())
->method('getCloudId')
- ->will($this->returnCallback(function (string $user, string $remote) {
+ ->willReturnCallback(function (string $user, string $remote) {
$cloudIdMock = $this->createMock(ICloudId::class);
// The remotes are already sanitized in the original data, so
@@ -214,7 +187,7 @@ class CleanupRemoteStoragesTest extends TestCase {
->willReturn($remote);
return $cloudIdMock;
- }));
+ });
$this->command->execute($input, $output);
@@ -223,5 +196,10 @@ class CleanupRemoteStoragesTest extends TestCase {
$this->assertFalse($this->doesStorageExist($this->storages[3]['numeric_id']));
$this->assertTrue($this->doesStorageExist($this->storages[4]['numeric_id']));
$this->assertFalse($this->doesStorageExist($this->storages[5]['numeric_id']));
+
+ $this->assertEquals([
+ '5 remote storage(s) need(s) to be checked',
+ '5 remote share(s) exist',
+ ], array_slice($outputCalls, 0, 2));
}
}
diff --git a/apps/files_sharing/tests/Command/FixShareOwnersTest.php b/apps/files_sharing/tests/Command/FixShareOwnersTest.php
new file mode 100644
index 00000000000..0fde61895b1
--- /dev/null
+++ b/apps/files_sharing/tests/Command/FixShareOwnersTest.php
@@ -0,0 +1,117 @@
+<?php
+
+/**
+ * SPDX-FileCopyrightText: 2017-2024 Nextcloud GmbH and Nextcloud contributors
+ * SPDX-License-Identifier: AGPL-3.0-only
+ */
+namespace OCA\Files_Sharing\Tests\Command;
+
+use OCA\Files_Sharing\Command\FixShareOwners;
+use OCA\Files_Sharing\OrphanHelper;
+use Symfony\Component\Console\Input\InputInterface;
+use Symfony\Component\Console\Output\OutputInterface;
+use Test\TestCase;
+
+/**
+ * Class FixShareOwnersTest
+ *
+ * @package OCA\Files_Sharing\Tests\Command
+ */
+class FixShareOwnersTest extends TestCase {
+ /**
+ * @var FixShareOwners
+ */
+ private $command;
+
+ /**
+ * @var OrphanHelper|\PHPUnit\Framework\MockObject\MockObject
+ */
+ private $orphanHelper;
+
+ protected function setUp(): void {
+ parent::setUp();
+
+ $this->orphanHelper = $this->createMock(OrphanHelper::class);
+ $this->command = new FixShareOwners($this->orphanHelper);
+ }
+
+ public function testExecuteNoSharesDetected() {
+ $this->orphanHelper->expects($this->once())
+ ->method('getAllShares')
+ ->willReturn([
+ ['id' => 1, 'owner' => 'user1', 'fileid' => 1, 'target' => 'target1'],
+ ['id' => 2, 'owner' => 'user2', 'fileid' => 2, 'target' => 'target2'],
+ ]);
+ $this->orphanHelper->expects($this->exactly(2))
+ ->method('isShareValid')
+ ->willReturn(true);
+
+ $input = $this->createMock(InputInterface::class);
+ $output = $this->createMock(OutputInterface::class);
+
+ $output->expects($this->once())
+ ->method('writeln')
+ ->with('No broken shares detected');
+ $this->command->execute($input, $output);
+ }
+
+ public function testExecuteSharesDetected() {
+ $this->orphanHelper->expects($this->once())
+ ->method('getAllShares')
+ ->willReturn([
+ ['id' => 1, 'owner' => 'user1', 'fileid' => 1, 'target' => 'target1'],
+ ['id' => 2, 'owner' => 'user2', 'fileid' => 2, 'target' => 'target2'],
+ ]);
+ $this->orphanHelper->expects($this->exactly(2))
+ ->method('isShareValid')
+ ->willReturnOnConsecutiveCalls(true, false);
+ $this->orphanHelper->expects($this->once())
+ ->method('fileExists')
+ ->willReturn(true);
+ $this->orphanHelper->expects($this->once())
+ ->method('findOwner')
+ ->willReturn('newOwner');
+ $this->orphanHelper->expects($this->once())
+ ->method('updateShareOwner');
+
+ $input = $this->createMock(InputInterface::class);
+ $output = $this->createMock(OutputInterface::class);
+
+ $output->expects($this->once())
+ ->method('writeln')
+ ->with('Share with id <info>2</info> (target: <info>target2</info>) updated to owner <info>newOwner</info>');
+ $this->command->execute($input, $output);
+ }
+
+ public function testExecuteSharesDetectedDryRun() {
+ $this->orphanHelper->expects($this->once())
+ ->method('getAllShares')
+ ->willReturn([
+ ['id' => 1, 'owner' => 'user1', 'fileid' => 1, 'target' => 'target1'],
+ ['id' => 2, 'owner' => 'user2', 'fileid' => 2, 'target' => 'target2'],
+ ]);
+ $this->orphanHelper->expects($this->exactly(2))
+ ->method('isShareValid')
+ ->willReturnOnConsecutiveCalls(true, false);
+ $this->orphanHelper->expects($this->once())
+ ->method('fileExists')
+ ->willReturn(true);
+ $this->orphanHelper->expects($this->once())
+ ->method('findOwner')
+ ->willReturn('newOwner');
+ $this->orphanHelper->expects($this->never())
+ ->method('updateShareOwner');
+
+ $input = $this->createMock(InputInterface::class);
+ $output = $this->createMock(OutputInterface::class);
+
+ $output->expects($this->once())
+ ->method('writeln')
+ ->with('Share with id <info>2</info> (target: <info>target2</info>) can be updated to owner <info>newOwner</info>');
+ $input->expects($this->once())
+ ->method('getOption')
+ ->with('dry-run')
+ ->willReturn(true);
+ $this->command->execute($input, $output);
+ }
+}
diff --git a/apps/files_sharing/tests/Controller/ExternalShareControllerTest.php b/apps/files_sharing/tests/Controller/ExternalShareControllerTest.php
index c4906b9119b..7e054d9a6dc 100644
--- a/apps/files_sharing/tests/Controller/ExternalShareControllerTest.php
+++ b/apps/files_sharing/tests/Controller/ExternalShareControllerTest.php
@@ -1,35 +1,16 @@
<?php
+
/**
- * @copyright Copyright (c) 2016, ownCloud, Inc.
- *
- * @author Joas Schilling <coding@schilljs.com>
- * @author Lukas Reschke <lukas@statuscode.ch>
- * @author Roeland Jago Douma <roeland@famdouma.nl>
- *
- * @license AGPL-3.0
- *
- * This code is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License, version 3,
- * as published by the Free Software Foundation.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU Affero General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License, version 3,
- * along with this program. If not, see <http://www.gnu.org/licenses/>
- *
+ * SPDX-FileCopyrightText: 2019-2024 Nextcloud GmbH and Nextcloud contributors
+ * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
+ * SPDX-License-Identifier: AGPL-3.0-only
*/
namespace OCA\Files_Sharing\Tests\Controllers;
use OCA\Files_Sharing\Controller\ExternalSharesController;
use OCA\Files_Sharing\External\Manager;
-use OCP\AppFramework\Http\DataResponse;
use OCP\AppFramework\Http\JSONResponse;
-use OCP\Http\Client\IClient;
use OCP\Http\Client\IClientService;
-use OCP\Http\Client\IResponse;
use OCP\IConfig;
use OCP\IRequest;
use PHPUnit\Framework\MockObject\MockObject;
@@ -70,7 +51,7 @@ class ExternalShareControllerTest extends \Test\TestCase {
);
}
- public function testIndex() {
+ public function testIndex(): void {
$this->externalManager
->expects($this->once())
->method('getOpenShares')
@@ -79,7 +60,7 @@ class ExternalShareControllerTest extends \Test\TestCase {
$this->assertEquals(new JSONResponse(['MyDummyArray']), $this->getExternalShareController()->index());
}
- public function testCreate() {
+ public function testCreate(): void {
$this->externalManager
->expects($this->once())
->method('acceptShare')
@@ -88,7 +69,7 @@ class ExternalShareControllerTest extends \Test\TestCase {
$this->assertEquals(new JSONResponse(), $this->getExternalShareController()->create(4));
}
- public function testDestroy() {
+ public function testDestroy(): void {
$this->externalManager
->expects($this->once())
->method('declineShare')
@@ -96,90 +77,4 @@ class ExternalShareControllerTest extends \Test\TestCase {
$this->assertEquals(new JSONResponse(), $this->getExternalShareController()->destroy(4));
}
-
- public function testRemoteWithValidHttps() {
- $client = $this->createMock(IClient::class);
- $response = $this->createMock(IResponse::class);
- $response
- ->expects($this->exactly(2))
- ->method('getBody')
- ->willReturnOnConsecutiveCalls(
- 'Certainly not a JSON string',
- '{"installed":true,"maintenance":false,"version":"8.1.0.8","versionstring":"8.1.0","edition":""}'
- );
- $client
- ->expects($this->any())
- ->method('get')
- ->willReturn($response);
-
- $this->clientService
- ->expects($this->exactly(2))
- ->method('newClient')
- ->willReturn($client);
-
- $this->assertEquals(new DataResponse('https'), $this->getExternalShareController()->testRemote('nextcloud.com'));
- }
-
- public function testRemoteWithWorkingHttp() {
- $client = $this->createMock(IClient::class);
- $response = $this->createMock(IResponse::class);
- $client
- ->method('get')
- ->willReturn($response);
- $response
- ->expects($this->exactly(5))
- ->method('getBody')
- ->willReturnOnConsecutiveCalls(
- 'Certainly not a JSON string',
- 'Certainly not a JSON string',
- 'Certainly not a JSON string',
- 'Certainly not a JSON string',
- '{"installed":true,"maintenance":false,"version":"8.1.0.8","versionstring":"8.1.0","edition":""}'
- );
- $this->clientService
- ->expects($this->exactly(5))
- ->method('newClient')
- ->willReturn($client);
-
- $this->assertEquals(new DataResponse('http'), $this->getExternalShareController()->testRemote('nextcloud.com'));
- }
-
- public function testRemoteWithInvalidRemote() {
- $client = $this->createMock(IClient::class);
- $response = $this->createMock(IResponse::class);
- $client
- ->expects($this->exactly(6))
- ->method('get')
- ->willReturn($response);
- $response
- ->expects($this->exactly(6))
- ->method('getBody')
- ->willReturn('Certainly not a JSON string');
- $this->clientService
- ->expects($this->exactly(6))
- ->method('newClient')
- ->willReturn($client);
-
- $this->assertEquals(new DataResponse(false), $this->getExternalShareController()->testRemote('nextcloud.com'));
- }
-
- public function dataRemoteWithInvalidRemoteURLs(): array {
- return [
- ['nextcloud.com?query'],
- ['nextcloud.com/#anchor'],
- ['nextcloud.com/;tomcat'],
- ];
- }
-
- /**
- * @dataProvider dataRemoteWithInvalidRemoteURLs
- * @param string $remote
- */
- public function testRemoteWithInvalidRemoteURLs(string $remote) {
- $this->clientService
- ->expects($this->never())
- ->method('newClient');
-
- $this->assertEquals(new DataResponse(false), $this->getExternalShareController()->testRemote($remote));
- }
}
diff --git a/apps/files_sharing/tests/Controller/PublicPreviewControllerTest.php b/apps/files_sharing/tests/Controller/PublicPreviewControllerTest.php
index 9f852721678..f49d839e8d4 100644
--- a/apps/files_sharing/tests/Controller/PublicPreviewControllerTest.php
+++ b/apps/files_sharing/tests/Controller/PublicPreviewControllerTest.php
@@ -1,26 +1,8 @@
<?php
+
/**
- * @copyright Copyright (c) 2016, Roeland Jago Douma <roeland@famdouma.nl>
- *
- * @author Julius Härtl <jus@bitgrid.net>
- * @author Morris Jobke <hey@morrisjobke.de>
- * @author Roeland Jago Douma <roeland@famdouma.nl>
- *
- * @license GNU AGPL version 3 or any later version
- *
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License as
- * published by the Free Software Foundation, either version 3 of the
- * License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU Affero General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- *
+ * SPDX-FileCopyrightText: 2016 Nextcloud GmbH and Nextcloud contributors
+ * SPDX-License-Identifier: AGPL-3.0-or-later
*/
namespace OCA\Files_Sharing\Tests\Controller;
@@ -37,6 +19,7 @@ use OCP\Files\SimpleFS\ISimpleFile;
use OCP\IPreview;
use OCP\IRequest;
use OCP\ISession;
+use OCP\Preview\IMimeIconProvider;
use OCP\Share\Exceptions\ShareNotFound;
use OCP\Share\IManager;
use OCP\Share\IShare;
@@ -45,15 +28,12 @@ use Test\TestCase;
class PublicPreviewControllerTest extends TestCase {
- /** @var IPreview|\PHPUnit\Framework\MockObject\MockObject */
- private $previewManager;
- /** @var IManager|\PHPUnit\Framework\MockObject\MockObject */
- private $shareManager;
- /** @var ITimeFactory|MockObject */
- private $timeFactory;
+ private IPreview&MockObject $previewManager;
+ private IManager&MockObject $shareManager;
+ private ITimeFactory&MockObject $timeFactory;
+ private IRequest&MockObject $request;
- /** @var PublicPreviewController */
- private $controller;
+ private PublicPreviewController $controller;
protected function setUp(): void {
parent::setUp();
@@ -61,6 +41,7 @@ class PublicPreviewControllerTest extends TestCase {
$this->previewManager = $this->createMock(IPreview::class);
$this->shareManager = $this->createMock(IManager::class);
$this->timeFactory = $this->createMock(ITimeFactory::class);
+ $this->request = $this->createMock(IRequest::class);
$this->timeFactory->method('getTime')
->willReturn(1337);
@@ -69,35 +50,36 @@ class PublicPreviewControllerTest extends TestCase {
$this->controller = new PublicPreviewController(
'files_sharing',
- $this->createMock(IRequest::class),
+ $this->request,
$this->shareManager,
$this->createMock(ISession::class),
- $this->previewManager
+ $this->previewManager,
+ $this->createMock(IMimeIconProvider::class),
);
}
- public function testInvalidToken() {
+ public function testInvalidToken(): void {
$res = $this->controller->getPreview('', 'file', 10, 10, '');
$expected = new DataResponse([], Http::STATUS_BAD_REQUEST);
$this->assertEquals($expected, $res);
}
- public function testInvalidWidth() {
+ public function testInvalidWidth(): void {
$res = $this->controller->getPreview('token', 'file', 0);
$expected = new DataResponse([], Http::STATUS_BAD_REQUEST);
$this->assertEquals($expected, $res);
}
- public function testInvalidHeight() {
+ public function testInvalidHeight(): void {
$res = $this->controller->getPreview('token', 'file', 10, 0);
$expected = new DataResponse([], Http::STATUS_BAD_REQUEST);
$this->assertEquals($expected, $res);
}
- public function testInvalidShare() {
+ public function testInvalidShare(): void {
$this->shareManager->method('getShareByToken')
->with($this->equalTo('token'))
->willThrowException(new ShareNotFound());
@@ -108,7 +90,7 @@ class PublicPreviewControllerTest extends TestCase {
$this->assertEquals($expected, $res);
}
- public function testShareNotAccessable() {
+ public function testShareNotAccessable(): void {
$share = $this->createMock(IShare::class);
$this->shareManager->method('getShareByToken')
->with($this->equalTo('token'))
@@ -123,6 +105,96 @@ class PublicPreviewControllerTest extends TestCase {
$this->assertEquals($expected, $res);
}
+ public function testShareNoDownload() {
+ $share = $this->createMock(IShare::class);
+ $this->shareManager->method('getShareByToken')
+ ->with($this->equalTo('token'))
+ ->willReturn($share);
+
+ $share->method('getPermissions')
+ ->willReturn(Constants::PERMISSION_READ);
+
+ $share->method('canSeeContent')
+ ->willReturn(false);
+
+ $res = $this->controller->getPreview('token', 'file', 10, 10);
+ $expected = new DataResponse([], Http::STATUS_FORBIDDEN);
+
+ $this->assertEquals($expected, $res);
+ }
+
+ public function testShareNoDownloadButPreviewHeader() {
+ $share = $this->createMock(IShare::class);
+ $this->shareManager->method('getShareByToken')
+ ->with($this->equalTo('token'))
+ ->willReturn($share);
+
+ $share->method('getPermissions')
+ ->willReturn(Constants::PERMISSION_READ);
+
+ $share->method('canSeeContent')
+ ->willReturn(false);
+
+ $this->request->method('getHeader')
+ ->with('x-nc-preview')
+ ->willReturn('true');
+
+ $file = $this->createMock(File::class);
+ $share->method('getNode')
+ ->willReturn($file);
+
+ $preview = $this->createMock(ISimpleFile::class);
+ $preview->method('getName')->willReturn('name');
+ $preview->method('getMTime')->willReturn(42);
+ $this->previewManager->method('getPreview')
+ ->with($this->equalTo($file), 10, 10, false)
+ ->willReturn($preview);
+
+ $preview->method('getMimeType')
+ ->willReturn('myMime');
+
+ $res = $this->controller->getPreview('token', 'file', 10, 10, true);
+ $expected = new FileDisplayResponse($preview, Http::STATUS_OK, ['Content-Type' => 'myMime']);
+ $expected->cacheFor(15 * 60);
+ $this->assertEquals($expected, $res);
+ }
+
+ public function testShareWithAttributes() {
+ $share = $this->createMock(IShare::class);
+ $this->shareManager->method('getShareByToken')
+ ->with($this->equalTo('token'))
+ ->willReturn($share);
+
+ $share->method('getPermissions')
+ ->willReturn(Constants::PERMISSION_READ);
+
+ $share->method('canSeeContent')
+ ->willReturn(true);
+
+ $this->request->method('getHeader')
+ ->with('x-nc-preview')
+ ->willReturn('true');
+
+ $file = $this->createMock(File::class);
+ $share->method('getNode')
+ ->willReturn($file);
+
+ $preview = $this->createMock(ISimpleFile::class);
+ $preview->method('getName')->willReturn('name');
+ $preview->method('getMTime')->willReturn(42);
+ $this->previewManager->method('getPreview')
+ ->with($this->equalTo($file), 10, 10, false)
+ ->willReturn($preview);
+
+ $preview->method('getMimeType')
+ ->willReturn('myMime');
+
+ $res = $this->controller->getPreview('token', 'file', 10, 10, true);
+ $expected = new FileDisplayResponse($preview, Http::STATUS_OK, ['Content-Type' => 'myMime']);
+ $expected->cacheFor(3600 * 24);
+ $this->assertEquals($expected, $res);
+ }
+
public function testPreviewFile() {
$share = $this->createMock(IShare::class);
$this->shareManager->method('getShareByToken')
@@ -136,6 +208,9 @@ class PublicPreviewControllerTest extends TestCase {
$share->method('getNode')
->willReturn($file);
+ $share->method('canSeeContent')
+ ->willReturn(true);
+
$preview = $this->createMock(ISimpleFile::class);
$preview->method('getName')->willReturn('name');
$preview->method('getMTime')->willReturn(42);
@@ -152,7 +227,7 @@ class PublicPreviewControllerTest extends TestCase {
$this->assertEquals($expected, $res);
}
- public function testPreviewFolderInvalidFile() {
+ public function testPreviewFolderInvalidFile(): void {
$share = $this->createMock(IShare::class);
$this->shareManager->method('getShareByToken')
->with($this->equalTo('token'))
@@ -165,6 +240,9 @@ class PublicPreviewControllerTest extends TestCase {
$share->method('getNode')
->willReturn($folder);
+ $share->method('canSeeContent')
+ ->willReturn(true);
+
$folder->method('get')
->with($this->equalTo('file'))
->willThrowException(new NotFoundException());
@@ -175,7 +253,7 @@ class PublicPreviewControllerTest extends TestCase {
}
- public function testPreviewFolderValidFile() {
+ public function testPreviewFolderValidFile(): void {
$share = $this->createMock(IShare::class);
$this->shareManager->method('getShareByToken')
->with($this->equalTo('token'))
@@ -188,6 +266,9 @@ class PublicPreviewControllerTest extends TestCase {
$share->method('getNode')
->willReturn($folder);
+ $share->method('canSeeContent')
+ ->willReturn(true);
+
$file = $this->createMock(File::class);
$folder->method('get')
->with($this->equalTo('file'))
diff --git a/apps/files_sharing/tests/Controller/ShareAPIControllerTest.php b/apps/files_sharing/tests/Controller/ShareAPIControllerTest.php
index b9b3e6fdecf..e6be0342c26 100644
--- a/apps/files_sharing/tests/Controller/ShareAPIControllerTest.php
+++ b/apps/files_sharing/tests/Controller/ShareAPIControllerTest.php
@@ -1,51 +1,29 @@
<?php
+
/**
- * @copyright Copyright (c) 2016, ownCloud, Inc.
- *
- * @author Bjoern Schiessle <bjoern@schiessle.org>
- * @author Christoph Wurst <christoph@winzerhof-wurst.at>
- * @author Daniel Calviño Sánchez <danxuliu@gmail.com>
- * @author Georg Ehrke <oc.list@georgehrke.com>
- * @author Joas Schilling <coding@schilljs.com>
- * @author John Molakvoæ <skjnldsv@protonmail.com>
- * @author Julius Härtl <jus@bitgrid.net>
- * @author Maxence Lange <maxence@artificial-owl.com>
- * @author Maxence Lange <maxence@nextcloud.com>
- * @author Morris Jobke <hey@morrisjobke.de>
- * @author Richard Steinmetz <richard@steinmetz.cloud>
- * @author Roeland Jago Douma <roeland@famdouma.nl>
- * @author Thomas Müller <thomas.mueller@tmit.eu>
- * @author Valdnet <47037905+Valdnet@users.noreply.github.com>
- * @author Vincent Petry <vincent@nextcloud.com>
- *
- * @license AGPL-3.0
- *
- * This code is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License, version 3,
- * as published by the Free Software Foundation.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU Affero General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License, version 3,
- * along with this program. If not, see <http://www.gnu.org/licenses/>
- *
+ * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
+ * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
+ * SPDX-License-Identifier: AGPL-3.0-only
*/
namespace OCA\Files_Sharing\Tests\Controller;
+use OCA\Federation\TrustedServers;
use OCA\Files_Sharing\Controller\ShareAPIController;
use OCP\App\IAppManager;
use OCP\AppFramework\Http\DataResponse;
+use OCP\AppFramework\OCS\OCSBadRequestException;
use OCP\AppFramework\OCS\OCSException;
+use OCP\AppFramework\OCS\OCSForbiddenException;
use OCP\AppFramework\OCS\OCSNotFoundException;
+use OCP\Constants;
use OCP\Files\File;
use OCP\Files\Folder;
use OCP\Files\IRootFolder;
use OCP\Files\Mount\IMountPoint;
+use OCP\Files\Mount\IShareOwnerlessMount;
use OCP\Files\NotFoundException;
-use OCP\Files\Storage;
+use OCP\Files\Storage\IStorage;
+use OCP\IAppConfig;
use OCP\IConfig;
use OCP\IDateTimeZone;
use OCP\IGroup;
@@ -53,15 +31,23 @@ use OCP\IGroupManager;
use OCP\IL10N;
use OCP\IPreview;
use OCP\IRequest;
+use OCP\ITagManager;
+use OCP\ITags;
use OCP\IURLGenerator;
use OCP\IUser;
use OCP\IUserManager;
+use OCP\Lock\ILockingProvider;
use OCP\Lock\LockedException;
+use OCP\Mail\IMailer;
+use OCP\Server;
use OCP\Share\Exceptions\GenericShareException;
+use OCP\Share\Exceptions\ShareNotFound;
use OCP\Share\IAttributes as IShareAttributes;
use OCP\Share\IManager;
+use OCP\Share\IProviderFactory;
use OCP\Share\IShare;
use OCP\UserStatus\IManager as IUserStatusManager;
+use PHPUnit\Framework\MockObject\MockObject;
use Psr\Container\ContainerInterface;
use Psr\Log\LoggerInterface;
use Test\TestCase;
@@ -75,22 +61,29 @@ use Test\TestCase;
class ShareAPIControllerTest extends TestCase {
private string $appName = 'files_sharing';
- private \OC\Share20\Manager|\PHPUnit\Framework\MockObject\MockObject $shareManager;
- private IGroupManager|\PHPUnit\Framework\MockObject\MockObject $groupManager;
- private IUserManager|\PHPUnit\Framework\MockObject\MockObject $userManager;
- private IRequest|\PHPUnit\Framework\MockObject\MockObject $request;
- private IRootFolder|\PHPUnit\Framework\MockObject\MockObject $rootFolder;
- private IURLGenerator|\PHPUnit\Framework\MockObject\MockObject $urlGenerator;
- private string|\PHPUnit\Framework\MockObject\MockObject $currentUser;
- private ShareAPIController $ocs;
- private IL10N|\PHPUnit\Framework\MockObject\MockObject $l;
- private IConfig|\PHPUnit\Framework\MockObject\MockObject $config;
- private IAppManager|\PHPUnit\Framework\MockObject\MockObject $appManager;
- private IServerContainer|\PHPUnit\Framework\MockObject\MockObject $serverContainer;
- private IUserStatusManager|\PHPUnit\Framework\MockObject\MockObject $userStatusManager;
- private IPreview|\PHPUnit\Framework\MockObject\MockObject $previewManager;
- private IDateTimeZone|\PHPUnit\Framework\MockObject\MockObject $dateTimeZone;
- private LoggerInterface $logger;
+ private string $currentUser;
+
+ private ShareAPIController $ocs;
+
+ private IManager&MockObject $shareManager;
+ private IGroupManager&MockObject $groupManager;
+ private IUserManager&MockObject $userManager;
+ private IRequest&MockObject $request;
+ private IRootFolder&MockObject $rootFolder;
+ private IURLGenerator&MockObject $urlGenerator;
+ private IL10N&MockObject $l;
+ private IConfig&MockObject $config;
+ private IAppConfig&MockObject $appConfig;
+ private IAppManager&MockObject $appManager;
+ private ContainerInterface&MockObject $serverContainer;
+ private IUserStatusManager&MockObject $userStatusManager;
+ private IPreview&MockObject $previewManager;
+ private IDateTimeZone&MockObject $dateTimeZone;
+ private LoggerInterface&MockObject $logger;
+ private IProviderFactory&MockObject $factory;
+ private IMailer&MockObject $mailer;
+ private ITagManager&MockObject $tagManager;
+ private TrustedServers&MockObject $trustedServers;
protected function setUp(): void {
$this->shareManager = $this->createMock(IManager::class);
@@ -114,6 +107,7 @@ class ShareAPIControllerTest extends TestCase {
return vsprintf($text, $parameters);
});
$this->config = $this->createMock(IConfig::class);
+ $this->appConfig = $this->createMock(IAppConfig::class);
$this->appManager = $this->createMock(IAppManager::class);
$this->serverContainer = $this->createMock(ContainerInterface::class);
$this->userStatusManager = $this->createMock(IUserStatusManager::class);
@@ -124,6 +118,10 @@ class ShareAPIControllerTest extends TestCase {
});
$this->dateTimeZone = $this->createMock(IDateTimeZone::class);
$this->logger = $this->createMock(LoggerInterface::class);
+ $this->factory = $this->createMock(IProviderFactory::class);
+ $this->mailer = $this->createMock(IMailer::class);
+ $this->tagManager = $this->createMock(ITagManager::class);
+ $this->trustedServers = $this->createMock(TrustedServers::class);
$this->ocs = new ShareAPIController(
$this->appName,
@@ -135,18 +133,24 @@ class ShareAPIControllerTest extends TestCase {
$this->urlGenerator,
$this->l,
$this->config,
+ $this->appConfig,
$this->appManager,
$this->serverContainer,
$this->userStatusManager,
$this->previewManager,
$this->dateTimeZone,
$this->logger,
- $this->currentUser,
+ $this->factory,
+ $this->mailer,
+ $this->tagManager,
+ $this->trustedServers,
+ $this->currentUser
);
+
}
/**
- * @return ShareAPIController|\PHPUnit\Framework\MockObject\MockObject
+ * @return ShareAPIController&MockObject
*/
private function mockFormatShare() {
return $this->getMockBuilder(ShareAPIController::class)
@@ -160,19 +164,24 @@ class ShareAPIControllerTest extends TestCase {
$this->urlGenerator,
$this->l,
$this->config,
+ $this->appConfig,
$this->appManager,
$this->serverContainer,
$this->userStatusManager,
$this->previewManager,
$this->dateTimeZone,
$this->logger,
+ $this->factory,
+ $this->mailer,
+ $this->tagManager,
+ $this->trustedServers,
$this->currentUser,
- ])->setMethods(['formatShare'])
+ ])->onlyMethods(['formatShare'])
->getMock();
}
private function newShare() {
- return \OC::$server->getShareManager()->newShare();
+ return Server::get(IManager::class)->newShare();
}
@@ -181,7 +190,7 @@ class ShareAPIControllerTest extends TestCase {
[
'scope' => 'permissions',
'key' => 'download',
- 'enabled' => true
+ 'value' => true
]
];
@@ -193,16 +202,16 @@ class ShareAPIControllerTest extends TestCase {
return [$shareAttributes, \json_encode($formattedShareAttributes)];
}
- public function testDeleteShareShareNotFound() {
- $this->expectException(\OCP\AppFramework\OCS\OCSNotFoundException::class);
+ public function testDeleteShareShareNotFound(): void {
+ $this->expectException(OCSNotFoundException::class);
$this->expectExceptionMessage('Wrong share ID, share does not exist');
$this->shareManager
->expects($this->exactly(7))
->method('getShareById')
- ->willReturnCallback(function ($id) {
+ ->willReturnCallback(function ($id): void {
if ($id === 'ocinternal:42' || $id === 'ocRoomShare:42' || $id === 'ocFederatedSharing:42' || $id === 'ocCircleShare:42' || $id === 'ocMailShare:42' || $id === 'deck:42' || $id === 'sciencemesh:42') {
- throw new \OCP\Share\Exceptions\ShareNotFound();
+ throw new ShareNotFound();
} else {
throw new \Exception();
}
@@ -213,7 +222,7 @@ class ShareAPIControllerTest extends TestCase {
$this->ocs->deleteShare(42);
}
- public function testDeleteShare() {
+ public function testDeleteShare(): void {
$node = $this->getMockBuilder(File::class)->getMock();
$share = $this->newShare();
@@ -231,7 +240,7 @@ class ShareAPIControllerTest extends TestCase {
$node->expects($this->once())
->method('lock')
- ->with(\OCP\Lock\ILockingProvider::LOCK_SHARED);
+ ->with(ILockingProvider::LOCK_SHARED);
$expected = new DataResponse();
$result = $this->ocs->deleteShare(42);
@@ -241,15 +250,25 @@ class ShareAPIControllerTest extends TestCase {
}
- public function testDeleteShareLocked() {
- $this->expectException(\OCP\AppFramework\OCS\OCSNotFoundException::class);
+ public function testDeleteShareLocked(): void {
+ $this->expectException(OCSNotFoundException::class);
$this->expectExceptionMessage('Could not delete share');
$node = $this->getMockBuilder(File::class)->getMock();
+ $node->method('getId')->willReturn(1);
$share = $this->newShare();
$share->setNode($node);
+ $userFolder = $this->getMockBuilder(Folder::class)->getMock();
+ $this->rootFolder->method('getUserFolder')
+ ->with($this->currentUser)
+ ->willReturn($userFolder);
+
+ $userFolder->method('getById')
+ ->with($share->getNodeId())
+ ->willReturn([$node]);
+
$this->shareManager
->expects($this->once())
->method('getShareById')
@@ -263,8 +282,8 @@ class ShareAPIControllerTest extends TestCase {
$node->expects($this->once())
->method('lock')
- ->with(\OCP\Lock\ILockingProvider::LOCK_SHARED)
- ->will($this->throwException(new LockedException('mypath')));
+ ->with(ILockingProvider::LOCK_SHARED)
+ ->willThrowException(new LockedException('mypath'));
$this->assertFalse($this->invokePrivate($this->ocs, 'canDeleteFromSelf', [$share]));
$this->assertFalse($this->invokePrivate($this->ocs, 'canDeleteShare', [$share]));
@@ -275,7 +294,7 @@ class ShareAPIControllerTest extends TestCase {
/**
* You can always remove a share that was shared with you
*/
- public function testDeleteShareWithMe() {
+ public function testDeleteShareWithMe(): void {
$node = $this->getMockBuilder(File::class)->getMock();
$share = $this->newShare();
@@ -296,7 +315,7 @@ class ShareAPIControllerTest extends TestCase {
$node->expects($this->once())
->method('lock')
- ->with(\OCP\Lock\ILockingProvider::LOCK_SHARED);
+ ->with(ILockingProvider::LOCK_SHARED);
$this->assertFalse($this->invokePrivate($this->ocs, 'canDeleteFromSelf', [$share]));
$this->assertTrue($this->invokePrivate($this->ocs, 'canDeleteShare', [$share]));
@@ -307,7 +326,7 @@ class ShareAPIControllerTest extends TestCase {
/**
* You can always delete a share you own
*/
- public function testDeleteShareOwner() {
+ public function testDeleteShareOwner(): void {
$node = $this->getMockBuilder(File::class)->getMock();
$share = $this->newShare();
@@ -327,7 +346,7 @@ class ShareAPIControllerTest extends TestCase {
$node->expects($this->once())
->method('lock')
- ->with(\OCP\Lock\ILockingProvider::LOCK_SHARED);
+ ->with(ILockingProvider::LOCK_SHARED);
$this->assertFalse($this->invokePrivate($this->ocs, 'canDeleteFromSelf', [$share]));
$this->assertTrue($this->invokePrivate($this->ocs, 'canDeleteShare', [$share]));
@@ -339,7 +358,7 @@ class ShareAPIControllerTest extends TestCase {
* You can always delete a share when you own
* the file path it belong to
*/
- public function testDeleteShareFileOwner() {
+ public function testDeleteShareFileOwner(): void {
$node = $this->getMockBuilder(File::class)->getMock();
$node->method('getId')->willReturn(1);
@@ -360,7 +379,7 @@ class ShareAPIControllerTest extends TestCase {
$node->expects($this->once())
->method('lock')
- ->with(\OCP\Lock\ILockingProvider::LOCK_SHARED);
+ ->with(ILockingProvider::LOCK_SHARED);
$this->assertFalse($this->invokePrivate($this->ocs, 'canDeleteFromSelf', [$share]));
$this->assertTrue($this->invokePrivate($this->ocs, 'canDeleteShare', [$share]));
@@ -372,7 +391,7 @@ class ShareAPIControllerTest extends TestCase {
* You can remove (the mountpoint, not the share)
* a share if you're in the group the share is shared with
*/
- public function testDeleteSharedWithMyGroup() {
+ public function testDeleteSharedWithMyGroup(): void {
$node = $this->getMockBuilder(File::class)->getMock();
$node->method('getId')->willReturn(1);
@@ -389,7 +408,7 @@ class ShareAPIControllerTest extends TestCase {
// canDeleteShareFromSelf
$user = $this->createMock(IUser::class);
- $group = $this->getMockBuilder('OCP\IGroup')->getMock();
+ $group = $this->getMockBuilder(IGroup::class)->getMock();
$this->groupManager
->method('get')
->with('group')
@@ -404,16 +423,16 @@ class ShareAPIControllerTest extends TestCase {
$node->expects($this->once())
->method('lock')
- ->with(\OCP\Lock\ILockingProvider::LOCK_SHARED);
+ ->with(ILockingProvider::LOCK_SHARED);
- $userFolder = $this->getMockBuilder('OCP\Files\Folder')->getMock();
+ $userFolder = $this->getMockBuilder(Folder::class)->getMock();
$this->rootFolder->method('getUserFolder')
->with($this->currentUser)
->willReturn($userFolder);
- $userFolder->method('getFirstNodeById')
+ $userFolder->method('getById')
->with($share->getNodeId())
- ->willReturn($share->getNode());
+ ->willReturn([$share->getNode()]);
$this->shareManager->expects($this->once())
->method('deleteFromSelf')
@@ -432,8 +451,8 @@ class ShareAPIControllerTest extends TestCase {
* You cannot remove a share if you're not
* in the group the share is shared with
*/
- public function testDeleteSharedWithGroupIDontBelongTo() {
- $this->expectException(\OCP\AppFramework\OCS\OCSNotFoundException::class);
+ public function testDeleteSharedWithGroupIDontBelongTo(): void {
+ $this->expectException(OCSNotFoundException::class);
$this->expectExceptionMessage('Wrong share ID, share does not exist');
$node = $this->getMockBuilder(File::class)->getMock();
@@ -452,7 +471,7 @@ class ShareAPIControllerTest extends TestCase {
// canDeleteShareFromSelf
$user = $this->createMock(IUser::class);
- $group = $this->getMockBuilder('OCP\IGroup')->getMock();
+ $group = $this->getMockBuilder(IGroup::class)->getMock();
$this->groupManager
->method('get')
->with('group')
@@ -467,16 +486,16 @@ class ShareAPIControllerTest extends TestCase {
$node->expects($this->once())
->method('lock')
- ->with(\OCP\Lock\ILockingProvider::LOCK_SHARED);
+ ->with(ILockingProvider::LOCK_SHARED);
- $userFolder = $this->getMockBuilder('OCP\Files\Folder')->getMock();
+ $userFolder = $this->getMockBuilder(Folder::class)->getMock();
$this->rootFolder->method('getUserFolder')
->with($this->currentUser)
->willReturn($userFolder);
- $userFolder->method('getFirstNodeById')
+ $userFolder->method('getById')
->with($share->getNodeId())
- ->willReturn($share->getNode());
+ ->willReturn([$share->getNode()]);
$this->shareManager->expects($this->never())
->method('deleteFromSelf');
@@ -490,6 +509,63 @@ class ShareAPIControllerTest extends TestCase {
$this->ocs->deleteShare(42);
}
+ public function testDeleteShareOwnerless(): void {
+ $ocs = $this->mockFormatShare();
+
+ $mount = $this->createMock(IShareOwnerlessMount::class);
+
+ $file = $this->createMock(File::class);
+ $file
+ ->expects($this->exactly(2))
+ ->method('getPermissions')
+ ->willReturn(Constants::PERMISSION_SHARE);
+ $file
+ ->expects($this->once())
+ ->method('getMountPoint')
+ ->willReturn($mount);
+
+ $userFolder = $this->createMock(Folder::class);
+ $userFolder->method('getById')
+ ->with(2)
+ ->willReturn([$file]);
+ $userFolder->method('getFirstNodeById')
+ ->with(2)
+ ->willReturn($file);
+
+ $this->rootFolder
+ ->method('getUserFolder')
+ ->with($this->currentUser)
+ ->willReturn($userFolder);
+
+ $share = $this->createMock(IShare::class);
+ $share
+ ->expects($this->once())
+ ->method('getNode')
+ ->willReturn($file);
+ $share
+ ->expects($this->exactly(2))
+ ->method('getNodeId')
+ ->willReturn(2);
+ $share
+ ->expects($this->exactly(2))
+ ->method('getPermissions')
+ ->willReturn(Constants::PERMISSION_SHARE);
+
+ $this->shareManager
+ ->expects($this->once())
+ ->method('getShareById')
+ ->with('ocinternal:1', $this->currentUser)
+ ->willReturn($share);
+
+ $this->shareManager
+ ->expects($this->once())
+ ->method('deleteShare')
+ ->with($share);
+
+ $result = $ocs->deleteShare(1);
+ $this->assertInstanceOf(DataResponse::class, $result);
+ }
+
/*
* FIXME: Enable once we have a federated Share Provider
@@ -528,10 +604,10 @@ class ShareAPIControllerTest extends TestCase {
$share->method('getToken')->willReturn($token);
$share->method('getPassword')->willReturn($password);
- if ($shareType === IShare::TYPE_USER ||
- $shareType === IShare::TYPE_GROUP ||
- $shareType === IShare::TYPE_LINK) {
- $share->method('getFullId')->willReturn('ocinternal:'.$id);
+ if ($shareType === IShare::TYPE_USER
+ || $shareType === IShare::TYPE_GROUP
+ || $shareType === IShare::TYPE_LINK) {
+ $share->method('getFullId')->willReturn('ocinternal:' . $id);
}
return $share;
@@ -545,14 +621,16 @@ class ShareAPIControllerTest extends TestCase {
->getMock();
$cache->method('getNumericStorageId')->willReturn(101);
- $storage = $this->getMockBuilder(Storage::class)
+ $storage = $this->getMockBuilder(IStorage::class)
->disableOriginalConstructor()
->getMock();
$storage->method('getId')->willReturn('STORAGE');
$storage->method('getCache')->willReturn($cache);
- $parentFolder = $this->getMockBuilder('OCP\Files\Folder')->getMock();
+ $parentFolder = $this->getMockBuilder(Folder::class)->getMock();
$parentFolder->method('getId')->willReturn(3);
+ $mountPoint = $this->createMock(IMountPoint::class);
+ $mountPoint->method('getMountType')->willReturn('');
$file = $this->getMockBuilder('OCP\Files\File')->getMock();
$file->method('getId')->willReturn(1);
@@ -562,8 +640,9 @@ class ShareAPIControllerTest extends TestCase {
$file->method('getSize')->willReturn(123465);
$file->method('getMTime')->willReturn(1234567890);
$file->method('getMimeType')->willReturn('myMimeType');
+ $file->method('getMountPoint')->willReturn($mountPoint);
- $folder = $this->getMockBuilder('OCP\Files\Folder')->getMock();
+ $folder = $this->getMockBuilder(Folder::class)->getMock();
$folder->method('getId')->willReturn(2);
$folder->method('getPath')->willReturn('folder');
$folder->method('getStorage')->willReturn($storage);
@@ -571,6 +650,7 @@ class ShareAPIControllerTest extends TestCase {
$folder->method('getSize')->willReturn(123465);
$folder->method('getMTime')->willReturn(1234567890);
$folder->method('getMimeType')->willReturn('myFolderMimeType');
+ $folder->method('getMountPoint')->willReturn($mountPoint);
[$shareAttributes, $shareAttributesReturnJson] = $this->mockShareAttributes();
@@ -626,6 +706,9 @@ class ShareAPIControllerTest extends TestCase {
'item_size' => 123465,
'item_mtime' => 1234567890,
'attributes' => null,
+ 'item_permissions' => 4,
+ 'is-mount-root' => false,
+ 'mount-type' => '',
];
$data[] = [$share, $expected];
@@ -680,6 +763,9 @@ class ShareAPIControllerTest extends TestCase {
'item_size' => 123465,
'item_mtime' => 1234567890,
'attributes' => null,
+ 'item_permissions' => 4,
+ 'is-mount-root' => false,
+ 'mount-type' => '',
];
$data[] = [$share, $expected];
@@ -740,38 +826,44 @@ class ShareAPIControllerTest extends TestCase {
'item_size' => 123465,
'item_mtime' => 1234567890,
'attributes' => null,
+ 'item_permissions' => 4,
+ 'is-mount-root' => false,
+ 'mount-type' => '',
];
$data[] = [$share, $expected];
return $data;
}
- /**
- * @dataProvider dataGetShare
- */
- public function testGetShare(\OCP\Share\IShare $share, array $result) {
- /** @var ShareAPIController|\PHPUnit\Framework\MockObject\MockObject $ocs */
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataGetShare')]
+ public function testGetShare(IShare $share, array $result): void {
+ /** @var ShareAPIController&MockObject $ocs */
$ocs = $this->getMockBuilder(ShareAPIController::class)
- ->setConstructorArgs([
- $this->appName,
- $this->request,
- $this->shareManager,
- $this->groupManager,
- $this->userManager,
- $this->rootFolder,
- $this->urlGenerator,
- $this->l,
- $this->config,
- $this->appManager,
- $this->serverContainer,
- $this->userStatusManager,
- $this->previewManager,
- $this->dateTimeZone,
- $this->logger,
- $this->currentUser,
-
- ])->setMethods(['canAccessShare'])
- ->getMock();
+ ->setConstructorArgs([
+ $this->appName,
+ $this->request,
+ $this->shareManager,
+ $this->groupManager,
+ $this->userManager,
+ $this->rootFolder,
+ $this->urlGenerator,
+ $this->l,
+ $this->config,
+ $this->appConfig,
+ $this->appManager,
+ $this->serverContainer,
+ $this->userStatusManager,
+ $this->previewManager,
+ $this->dateTimeZone,
+ $this->logger,
+ $this->factory,
+ $this->mailer,
+ $this->tagManager,
+ $this->trustedServers,
+ $this->currentUser,
+ ])
+ ->onlyMethods(['canAccessShare'])
+ ->getMock();
$ocs->expects($this->any())
->method('canAccessShare')
@@ -783,7 +875,7 @@ class ShareAPIControllerTest extends TestCase {
->with($share->getFullId(), 'currentUser')
->willReturn($share);
- $userFolder = $this->getMockBuilder('OCP\Files\Folder')->getMock();
+ $userFolder = $this->getMockBuilder(Folder::class)->getMock();
$userFolder
->method('getRelativePath')
->willReturnArgument(0);
@@ -791,7 +883,6 @@ class ShareAPIControllerTest extends TestCase {
$userFolder->method('getById')
->with($share->getNodeId())
->willReturn([$share->getNode()]);
-
$userFolder->method('getFirstNodeById')
->with($share->getNodeId())
->willReturn($share->getNode());
@@ -817,7 +908,7 @@ class ShareAPIControllerTest extends TestCase {
$user->method('getDisplayName')->willReturn('userDisplay');
$user->method('getSystemEMailAddress')->willReturn('userId@example.com');
- $group = $this->getMockBuilder('OCP\IGroup')->getMock();
+ $group = $this->getMockBuilder(IGroup::class)->getMock();
$group->method('getGID')->willReturn('groupId');
$this->userManager->method('get')->willReturnMap([
@@ -830,17 +921,16 @@ class ShareAPIControllerTest extends TestCase {
]);
$this->dateTimeZone->method('getTimezone')->willReturn(new \DateTimeZone('UTC'));
- $d = $ocs->getShare($share->getId())->getData()[0];
-
- $this->assertEquals($result, $ocs->getShare($share->getId())->getData()[0]);
+ $data = $ocs->getShare($share->getId())->getData()[0];
+ $this->assertEquals($result, $data);
}
- public function testGetShareInvalidNode() {
- $this->expectException(\OCP\AppFramework\OCS\OCSNotFoundException::class);
+ public function testGetShareInvalidNode(): void {
+ $this->expectException(OCSNotFoundException::class);
$this->expectExceptionMessage('Wrong share ID, share does not exist');
- $share = \OC::$server->getShareManager()->newShare();
+ $share = Server::get(IManager::class)->newShare();
$share->setSharedBy('initiator')
->setSharedWith('recipient')
->setShareOwner('owner');
@@ -851,7 +941,7 @@ class ShareAPIControllerTest extends TestCase {
->with('ocinternal:42', 'currentUser')
->willReturn($share);
- $userFolder = $this->getMockBuilder('OCP\Files\Folder')->getMock();
+ $userFolder = $this->getMockBuilder(Folder::class)->getMock();
$this->rootFolder->method('getUserFolder')
->with($this->currentUser)
->willReturn($userFolder);
@@ -871,12 +961,12 @@ class ShareAPIControllerTest extends TestCase {
$folder->method('getDirectoryListing')
->willReturn([$file1, $file2]);
- $file1UserShareOwner = \OC::$server->getShareManager()->newShare();
+ $file1UserShareOwner = Server::get(IManager::class)->newShare();
$file1UserShareOwner->setShareType(IShare::TYPE_USER)
->setSharedWith('recipient')
->setSharedBy('initiator')
->setShareOwner('currentUser')
- ->setPermissions(\OCP\Constants::PERMISSION_READ)
+ ->setPermissions(Constants::PERMISSION_READ)
->setNode($file1)
->setId(4);
@@ -885,12 +975,12 @@ class ShareAPIControllerTest extends TestCase {
'share_type' => IShare::TYPE_USER,
];
- $file1UserShareInitiator = \OC::$server->getShareManager()->newShare();
+ $file1UserShareInitiator = Server::get(IManager::class)->newShare();
$file1UserShareInitiator->setShareType(IShare::TYPE_USER)
->setSharedWith('recipient')
->setSharedBy('currentUser')
->setShareOwner('owner')
- ->setPermissions(\OCP\Constants::PERMISSION_READ)
+ ->setPermissions(Constants::PERMISSION_READ)
->setNode($file1)
->setId(8);
@@ -899,12 +989,12 @@ class ShareAPIControllerTest extends TestCase {
'share_type' => IShare::TYPE_USER,
];
- $file1UserShareRecipient = \OC::$server->getShareManager()->newShare();
+ $file1UserShareRecipient = Server::get(IManager::class)->newShare();
$file1UserShareRecipient->setShareType(IShare::TYPE_USER)
->setSharedWith('currentUser')
->setSharedBy('initiator')
->setShareOwner('owner')
- ->setPermissions(\OCP\Constants::PERMISSION_READ)
+ ->setPermissions(Constants::PERMISSION_READ)
->setNode($file1)
->setId(15);
@@ -913,12 +1003,12 @@ class ShareAPIControllerTest extends TestCase {
'share_type' => IShare::TYPE_USER,
];
- $file1UserShareOther = \OC::$server->getShareManager()->newShare();
+ $file1UserShareOther = Server::get(IManager::class)->newShare();
$file1UserShareOther->setShareType(IShare::TYPE_USER)
->setSharedWith('recipient')
->setSharedBy('initiator')
->setShareOwner('owner')
- ->setPermissions(\OCP\Constants::PERMISSION_READ)
+ ->setPermissions(Constants::PERMISSION_READ)
->setNode($file1)
->setId(16);
@@ -927,12 +1017,12 @@ class ShareAPIControllerTest extends TestCase {
'share_type' => IShare::TYPE_USER,
];
- $file1GroupShareOwner = \OC::$server->getShareManager()->newShare();
+ $file1GroupShareOwner = Server::get(IManager::class)->newShare();
$file1GroupShareOwner->setShareType(IShare::TYPE_GROUP)
->setSharedWith('recipient')
->setSharedBy('initiator')
->setShareOwner('currentUser')
- ->setPermissions(\OCP\Constants::PERMISSION_READ)
+ ->setPermissions(Constants::PERMISSION_READ)
->setNode($file1)
->setId(23);
@@ -941,12 +1031,12 @@ class ShareAPIControllerTest extends TestCase {
'share_type' => IShare::TYPE_GROUP,
];
- $file1GroupShareRecipient = \OC::$server->getShareManager()->newShare();
+ $file1GroupShareRecipient = Server::get(IManager::class)->newShare();
$file1GroupShareRecipient->setShareType(IShare::TYPE_GROUP)
->setSharedWith('currentUserGroup')
->setSharedBy('initiator')
->setShareOwner('owner')
- ->setPermissions(\OCP\Constants::PERMISSION_READ)
+ ->setPermissions(Constants::PERMISSION_READ)
->setNode($file1)
->setId(42);
@@ -955,21 +1045,21 @@ class ShareAPIControllerTest extends TestCase {
'share_type' => IShare::TYPE_GROUP,
];
- $file1GroupShareOther = \OC::$server->getShareManager()->newShare();
+ $file1GroupShareOther = Server::get(IManager::class)->newShare();
$file1GroupShareOther->setShareType(IShare::TYPE_GROUP)
->setSharedWith('recipient')
->setSharedBy('initiator')
->setShareOwner('owner')
- ->setPermissions(\OCP\Constants::PERMISSION_READ)
+ ->setPermissions(Constants::PERMISSION_READ)
->setNode($file1)
->setId(108);
- $file1LinkShareOwner = \OC::$server->getShareManager()->newShare();
+ $file1LinkShareOwner = Server::get(IManager::class)->newShare();
$file1LinkShareOwner->setShareType(IShare::TYPE_LINK)
->setSharedWith('recipient')
->setSharedBy('initiator')
->setShareOwner('currentUser')
- ->setPermissions(\OCP\Constants::PERMISSION_READ)
+ ->setPermissions(Constants::PERMISSION_READ)
->setNode($file1)
->setId(415);
@@ -978,12 +1068,12 @@ class ShareAPIControllerTest extends TestCase {
'share_type' => IShare::TYPE_LINK,
];
- $file1EmailShareOwner = \OC::$server->getShareManager()->newShare();
+ $file1EmailShareOwner = Server::get(IManager::class)->newShare();
$file1EmailShareOwner->setShareType(IShare::TYPE_EMAIL)
->setSharedWith('recipient')
->setSharedBy('initiator')
->setShareOwner('currentUser')
- ->setPermissions(\OCP\Constants::PERMISSION_READ)
+ ->setPermissions(Constants::PERMISSION_READ)
->setNode($file1)
->setId(416);
@@ -992,12 +1082,12 @@ class ShareAPIControllerTest extends TestCase {
'share_type' => IShare::TYPE_EMAIL,
];
- $file1CircleShareOwner = \OC::$server->getShareManager()->newShare();
+ $file1CircleShareOwner = Server::get(IManager::class)->newShare();
$file1CircleShareOwner->setShareType(IShare::TYPE_CIRCLE)
->setSharedWith('recipient')
->setSharedBy('initiator')
->setShareOwner('currentUser')
- ->setPermissions(\OCP\Constants::PERMISSION_READ)
+ ->setPermissions(Constants::PERMISSION_READ)
->setNode($file1)
->setId(423);
@@ -1006,12 +1096,12 @@ class ShareAPIControllerTest extends TestCase {
'share_type' => IShare::TYPE_CIRCLE,
];
- $file1RoomShareOwner = \OC::$server->getShareManager()->newShare();
+ $file1RoomShareOwner = Server::get(IManager::class)->newShare();
$file1RoomShareOwner->setShareType(IShare::TYPE_ROOM)
->setSharedWith('recipient')
->setSharedBy('initiator')
->setShareOwner('currentUser')
- ->setPermissions(\OCP\Constants::PERMISSION_READ)
+ ->setPermissions(Constants::PERMISSION_READ)
->setNode($file1)
->setId(442);
@@ -1020,12 +1110,12 @@ class ShareAPIControllerTest extends TestCase {
'share_type' => IShare::TYPE_ROOM,
];
- $file1RemoteShareOwner = \OC::$server->getShareManager()->newShare();
+ $file1RemoteShareOwner = Server::get(IManager::class)->newShare();
$file1RemoteShareOwner->setShareType(IShare::TYPE_REMOTE)
->setSharedWith('recipient')
->setSharedBy('initiator')
->setShareOwner('currentUser')
- ->setPermissions(\OCP\Constants::PERMISSION_READ)
+ ->setPermissions(Constants::PERMISSION_READ)
->setExpirationDate(new \DateTime('2000-01-01T01:02:03'))
->setNode($file1)
->setId(815);
@@ -1035,12 +1125,12 @@ class ShareAPIControllerTest extends TestCase {
'share_type' => IShare::TYPE_REMOTE,
];
- $file1RemoteGroupShareOwner = \OC::$server->getShareManager()->newShare();
+ $file1RemoteGroupShareOwner = Server::get(IManager::class)->newShare();
$file1RemoteGroupShareOwner->setShareType(IShare::TYPE_REMOTE_GROUP)
->setSharedWith('recipient')
->setSharedBy('initiator')
->setShareOwner('currentUser')
- ->setPermissions(\OCP\Constants::PERMISSION_READ)
+ ->setPermissions(Constants::PERMISSION_READ)
->setExpirationDate(new \DateTime('2000-01-02T01:02:03'))
->setNode($file1)
->setId(816);
@@ -1050,12 +1140,12 @@ class ShareAPIControllerTest extends TestCase {
'share_type' => IShare::TYPE_REMOTE_GROUP,
];
- $file2UserShareOwner = \OC::$server->getShareManager()->newShare();
+ $file2UserShareOwner = Server::get(IManager::class)->newShare();
$file2UserShareOwner->setShareType(IShare::TYPE_USER)
->setSharedWith('recipient')
->setSharedBy('initiator')
->setShareOwner('currentUser')
- ->setPermissions(\OCP\Constants::PERMISSION_READ)
+ ->setPermissions(Constants::PERMISSION_READ)
->setNode($file2)
->setId(823);
@@ -1378,11 +1468,9 @@ class ShareAPIControllerTest extends TestCase {
return $data;
}
- /**
- * @dataProvider dataGetShares
- */
- public function testGetShares(array $getSharesParameters, array $shares, array $extraShareTypes, array $expected) {
- /** @var \OCA\Files_Sharing\Controller\ShareAPIController $ocs */
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataGetShares')]
+ public function testGetShares(array $getSharesParameters, array $shares, array $extraShareTypes, array $expected): void {
+ /** @var ShareAPIController&MockObject $ocs */
$ocs = $this->getMockBuilder(ShareAPIController::class)
->setConstructorArgs([
$this->appName,
@@ -1394,14 +1482,20 @@ class ShareAPIControllerTest extends TestCase {
$this->urlGenerator,
$this->l,
$this->config,
+ $this->appConfig,
$this->appManager,
$this->serverContainer,
$this->userStatusManager,
$this->previewManager,
$this->dateTimeZone,
$this->logger,
+ $this->factory,
+ $this->mailer,
+ $this->tagManager,
+ $this->trustedServers,
$this->currentUser,
- ])->setMethods(['formatShare'])
+ ])
+ ->onlyMethods(['formatShare'])
->getMock();
$ocs->method('formatShare')
@@ -1414,7 +1508,7 @@ class ShareAPIControllerTest extends TestCase {
}
);
- $userFolder = $this->getMockBuilder('OCP\Files\Folder')->getMock();
+ $userFolder = $this->getMockBuilder(Folder::class)->getMock();
$userFolder->method('get')
->with('path')
->willReturn($getSharesParameters['path']);
@@ -1460,81 +1554,125 @@ class ShareAPIControllerTest extends TestCase {
$this->assertEquals($expected, $result->getData());
}
- public function testCanAccessShare() {
- $share = $this->getMockBuilder(IShare::class)->getMock();
+ public function testCanAccessShareAsOwner(): void {
+ $share = $this->createMock(IShare::class);
$share->method('getShareOwner')->willReturn($this->currentUser);
$this->assertTrue($this->invokePrivate($this->ocs, 'canAccessShare', [$share]));
+ }
- $share = $this->getMockBuilder(IShare::class)->getMock();
+ public function testCanAccessShareAsSharer(): void {
+ $share = $this->createMock(IShare::class);
$share->method('getSharedBy')->willReturn($this->currentUser);
$this->assertTrue($this->invokePrivate($this->ocs, 'canAccessShare', [$share]));
+ }
- $share = $this->getMockBuilder(IShare::class)->getMock();
+ public function testCanAccessShareAsSharee(): void {
+ $share = $this->createMock(IShare::class);
$share->method('getShareType')->willReturn(IShare::TYPE_USER);
$share->method('getSharedWith')->willReturn($this->currentUser);
$this->assertTrue($this->invokePrivate($this->ocs, 'canAccessShare', [$share]));
+ }
- $file = $this->getMockBuilder(File::class)->getMock();
+ public function testCannotAccessLinkShare(): void {
+ $share = $this->createMock(IShare::class);
+ $share->method('getShareType')->willReturn(IShare::TYPE_LINK);
+ $share->method('getNodeId')->willReturn(42);
- $userFolder = $this->getMockBuilder('OCP\Files\Folder')->getMock();
+ $userFolder = $this->createMock(Folder::class);
$this->rootFolder->method('getUserFolder')
->with($this->currentUser)
->willReturn($userFolder);
+ $this->assertFalse($this->invokePrivate($this->ocs, 'canAccessShare', [$share]));
+ }
+
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataCanAccessShareWithPermissions')]
+ public function testCanAccessShareWithPermissions(int $permissions, bool $expected): void {
+ $share = $this->createMock(IShare::class);
+ $share->method('getShareType')->willReturn(IShare::TYPE_USER);
+ $share->method('getSharedWith')->willReturn($this->createMock(IUser::class));
+ $share->method('getNodeId')->willReturn(42);
+
+ $file = $this->createMock(File::class);
+
+ $userFolder = $this->getMockBuilder(Folder::class)->getMock();
$userFolder->method('getFirstNodeById')
->with($share->getNodeId())
->willReturn($file);
+ $userFolder->method('getById')
+ ->with($share->getNodeId())
+ ->willReturn([$file]);
+ $this->rootFolder->method('getUserFolder')
+ ->with($this->currentUser)
+ ->willReturn($userFolder);
$file->method('getPermissions')
- ->will($this->onConsecutiveCalls(\OCP\Constants::PERMISSION_SHARE, \OCP\Constants::PERMISSION_READ));
+ ->willReturn($permissions);
- // getPermissions -> share
- $share = $this->getMockBuilder(IShare::class)->getMock();
- $share->method('getShareType')->willReturn(IShare::TYPE_USER);
- $share->method('getSharedWith')->willReturn($this->getMockBuilder(IUser::class)->getMock());
- $this->assertTrue($this->invokePrivate($this->ocs, 'canAccessShare', [$share]));
+ if ($expected) {
+ $this->assertTrue($this->invokePrivate($this->ocs, 'canAccessShare', [$share]));
+ } else {
+ $this->assertFalse($this->invokePrivate($this->ocs, 'canAccessShare', [$share]));
+ }
+ }
- // getPermissions -> read
- $share = $this->getMockBuilder(IShare::class)->getMock();
- $share->method('getShareType')->willReturn(IShare::TYPE_USER);
- $share->method('getSharedWith')->willReturn($this->getMockBuilder(IUser::class)->getMock());
- $this->assertFalse($this->invokePrivate($this->ocs, 'canAccessShare', [$share]));
+ public static function dataCanAccessShareWithPermissions(): array {
+ return [
+ [Constants::PERMISSION_SHARE, true],
+ [Constants::PERMISSION_READ, false],
+ [Constants::PERMISSION_READ | Constants::PERMISSION_SHARE, true],
+ ];
+ }
- $share = $this->getMockBuilder(IShare::class)->getMock();
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataCanAccessShareAsGroupMember')]
+ public function testCanAccessShareAsGroupMember(string $group, bool $expected): void {
+ $share = $this->createMock(IShare::class);
$share->method('getShareType')->willReturn(IShare::TYPE_GROUP);
- $share->method('getSharedWith')->willReturn('group');
+ $share->method('getSharedWith')->willReturn($group);
+ $share->method('getNodeId')->willReturn(42);
+
+ $file = $this->createMock(File::class);
+
+ $userFolder = $this->createMock(Folder::class);
+ $userFolder->method('getFirstNodeById')
+ ->with($share->getNodeId())
+ ->willReturn($file);
+ $userFolder->method('getById')
+ ->with($share->getNodeId())
+ ->willReturn([$file]);
+ $this->rootFolder->method('getUserFolder')
+ ->with($this->currentUser)
+ ->willReturn($userFolder);
$user = $this->createMock(IUser::class);
$this->userManager->method('get')
->with($this->currentUser)
->willReturn($user);
- $group = $this->getMockBuilder('OCP\IGroup')->getMock();
+ $group = $this->createMock(IGroup::class);
$group->method('inGroup')->with($user)->willReturn(true);
- $group2 = $this->getMockBuilder('OCP\IGroup')->getMock();
+ $group2 = $this->createMock(IGroup::class);
$group2->method('inGroup')->with($user)->willReturn(false);
$this->groupManager->method('get')->willReturnMap([
['group', $group],
['group2', $group2],
- ['groupnull', null],
+ ['group-null', null],
]);
- $this->assertTrue($this->invokePrivate($this->ocs, 'canAccessShare', [$share]));
-
- $share = $this->createMock(IShare::class);
- $share->method('getShareType')->willReturn(IShare::TYPE_GROUP);
- $share->method('getSharedWith')->willReturn('group2');
- $this->assertFalse($this->invokePrivate($this->ocs, 'canAccessShare', [$share]));
- // null group
- $share = $this->createMock(IShare::class);
- $share->method('getShareType')->willReturn(IShare::TYPE_GROUP);
- $share->method('getSharedWith')->willReturn('groupnull');
- $this->assertFalse($this->invokePrivate($this->ocs, 'canAccessShare', [$share]));
+ if ($expected) {
+ $this->assertTrue($this->invokePrivate($this->ocs, 'canAccessShare', [$share]));
+ } else {
+ $this->assertFalse($this->invokePrivate($this->ocs, 'canAccessShare', [$share]));
+ }
+ }
- $share = $this->createMock(IShare::class);
- $share->method('getShareType')->willReturn(IShare::TYPE_LINK);
- $this->assertFalse($this->invokePrivate($this->ocs, 'canAccessShare', [$share]));
+ public static function dataCanAccessShareAsGroupMember(): array {
+ return [
+ ['group', true],
+ ['group2', false],
+ ['group-null', false],
+ ];
}
public function dataCanAccessRoomShare() {
@@ -1564,22 +1702,22 @@ class ShareAPIControllerTest extends TestCase {
}
/**
- * @dataProvider dataCanAccessRoomShare
*
* @param bool $expects
- * @param \OCP\Share\IShare $share
+ * @param IShare $share
* @param bool helperAvailable
* @param bool canAccessShareByHelper
*/
- public function testCanAccessRoomShare(bool $expected, \OCP\Share\IShare $share, bool $helperAvailable, bool $canAccessShareByHelper) {
- $userFolder = $this->getMockBuilder('OCP\Files\Folder')->getMock();
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataCanAccessRoomShare')]
+ public function testCanAccessRoomShare(bool $expected, IShare $share, bool $helperAvailable, bool $canAccessShareByHelper): void {
+ $userFolder = $this->getMockBuilder(Folder::class)->getMock();
$this->rootFolder->method('getUserFolder')
->with($this->currentUser)
->willReturn($userFolder);
- $userFolder->method('getFirstNodeById')
+ $userFolder->method('getById')
->with($share->getNodeId())
- ->willReturn($share->getNode());
+ ->willReturn([$share->getNode()]);
if (!$helperAvailable) {
$this->appManager->method('isEnabledForUser')
@@ -1590,8 +1728,11 @@ class ShareAPIControllerTest extends TestCase {
->with('spreed')
->willReturn(true);
- $helper = $this->getMockBuilder('\OCA\Talk\Share\Helper\ShareAPIController')
- ->setMethods(['canAccessShare'])
+ // This is not possible anymore with PHPUnit 10+
+ // as `setMethods` was removed and now real reflection is used, thus the class needs to exist.
+ // $helper = $this->getMockBuilder('\OCA\Talk\Share\Helper\ShareAPIController')
+ $helper = $this->getMockBuilder(\stdClass::class)
+ ->addMethods(['canAccessShare'])
->getMock();
$helper->method('canAccessShare')
->with($share, $this->currentUser)
@@ -1606,16 +1747,16 @@ class ShareAPIControllerTest extends TestCase {
}
- public function testCreateShareNoPath() {
- $this->expectException(\OCP\AppFramework\OCS\OCSNotFoundException::class);
+ public function testCreateShareNoPath(): void {
+ $this->expectException(OCSNotFoundException::class);
$this->expectExceptionMessage('Please specify a file or folder path');
$this->ocs->createShare();
}
- public function testCreateShareInvalidPath() {
- $this->expectException(\OCP\AppFramework\OCS\OCSNotFoundException::class);
+ public function testCreateShareInvalidPath(): void {
+ $this->expectException(OCSNotFoundException::class);
$this->expectExceptionMessage('Wrong path, file/folder does not exist');
$userFolder = $this->getMockBuilder(Folder::class)->getMock();
@@ -1627,51 +1768,47 @@ class ShareAPIControllerTest extends TestCase {
$userFolder->expects($this->once())
->method('get')
->with('invalid-path')
- ->will($this->throwException(new \OCP\Files\NotFoundException()));
+ ->willThrowException(new NotFoundException());
$this->ocs->createShare('invalid-path');
}
-
- public function testCreateShareInvalidPermissions() {
- $this->expectException(\OCP\AppFramework\OCS\OCSNotFoundException::class);
- $this->expectExceptionMessage('Invalid permissions');
+ public function testCreateShareInvalidShareType(): void {
+ $this->expectException(OCSBadRequestException::class);
+ $this->expectExceptionMessage('Unknown share type');
$share = $this->newShare();
$this->shareManager->method('newShare')->willReturn($share);
- $userFolder = $this->getMockBuilder(Folder::class)->getMock();
- $this->rootFolder->expects($this->once())
- ->method('getUserFolder')
- ->with('currentUser')
- ->willReturn($userFolder);
+ [$userFolder, $file] = $this->getNonSharedUserFile();
+ $this->rootFolder->expects($this->atLeastOnce())
+ ->method('getUserFolder')
+ ->with('currentUser')
+ ->willReturn($userFolder);
- $path = $this->getMockBuilder(File::class)->getMock();
- $userFolder->expects($this->once())
- ->method('get')
- ->with('valid-path')
- ->willReturn($path);
+ $userFolder->expects($this->atLeastOnce())
+ ->method('get')
+ ->with('valid-path')
+ ->willReturn($file);
$userFolder->method('getById')
->willReturn([]);
- $path->expects($this->once())
+ $file->expects($this->once())
->method('lock')
- ->with(\OCP\Lock\ILockingProvider::LOCK_SHARED);
+ ->with(ILockingProvider::LOCK_SHARED);
- $this->ocs->createShare('valid-path', 32);
+ $this->ocs->createShare('valid-path', 31);
}
-
- public function testCreateShareUserNoShareWith() {
- $this->expectException(\OCP\AppFramework\OCS\OCSNotFoundException::class);
+ public function testCreateShareUserNoShareWith(): void {
+ $this->expectException(OCSNotFoundException::class);
$this->expectExceptionMessage('Please specify a valid account to share with');
$share = $this->newShare();
$this->shareManager->method('newShare')->willReturn($share);
[$userFolder, $path] = $this->getNonSharedUserFile();
- $this->rootFolder->expects($this->exactly(2))
- ->method('getUserFolder')
+ $this->rootFolder->method('getUserFolder')
->with('currentUser')
->willReturn($userFolder);
@@ -1684,22 +1821,21 @@ class ShareAPIControllerTest extends TestCase {
$path->expects($this->once())
->method('lock')
- ->with(\OCP\Lock\ILockingProvider::LOCK_SHARED);
+ ->with(ILockingProvider::LOCK_SHARED);
- $this->ocs->createShare('valid-path', \OCP\Constants::PERMISSION_ALL, IShare::TYPE_USER);
+ $this->ocs->createShare('valid-path', Constants::PERMISSION_ALL, IShare::TYPE_USER);
}
- public function testCreateShareUserNoValidShareWith() {
- $this->expectException(\OCP\AppFramework\OCS\OCSNotFoundException::class);
+ public function testCreateShareUserNoValidShareWith(): void {
+ $this->expectException(OCSNotFoundException::class);
$this->expectExceptionMessage('Please specify a valid account to share with');
$share = $this->newShare();
$this->shareManager->method('newShare')->willReturn($share);
[$userFolder, $path] = $this->getNonSharedUserFile();
- $this->rootFolder->expects($this->exactly(2))
- ->method('getUserFolder')
+ $this->rootFolder->method('getUserFolder')
->with('currentUser')
->willReturn($userFolder);
@@ -1711,19 +1847,19 @@ class ShareAPIControllerTest extends TestCase {
->willReturn([]);
$path->expects($this->once())
->method('lock')
- ->with(\OCP\Lock\ILockingProvider::LOCK_SHARED);
+ ->with(ILockingProvider::LOCK_SHARED);
$this->userManager->method('userExists')
->with('invalidUser')
->willReturn(false);
- $this->ocs->createShare('valid-path', \OCP\Constants::PERMISSION_ALL, IShare::TYPE_USER, 'invalidUser');
+ $this->ocs->createShare('valid-path', Constants::PERMISSION_ALL, IShare::TYPE_USER, 'invalidUser');
}
- public function testCreateShareUser() {
+ public function testCreateShareUser(): void {
$share = $this->newShare();
$this->shareManager->method('newShare')->willReturn($share);
- /** @var \OCA\Files_Sharing\Controller\ShareAPIController $ocs */
+ /** @var ShareAPIController $ocs */
$ocs = $this->getMockBuilder(ShareAPIController::class)
->setConstructorArgs([
$this->appName,
@@ -1735,26 +1871,31 @@ class ShareAPIControllerTest extends TestCase {
$this->urlGenerator,
$this->l,
$this->config,
+ $this->appConfig,
$this->appManager,
$this->serverContainer,
$this->userStatusManager,
$this->previewManager,
$this->dateTimeZone,
$this->logger,
+ $this->factory,
+ $this->mailer,
+ $this->tagManager,
+ $this->trustedServers,
$this->currentUser,
- ])->setMethods(['formatShare'])
+ ])->onlyMethods(['formatShare'])
->getMock();
[$userFolder, $path] = $this->getNonSharedUserFile();
$this->rootFolder->expects($this->exactly(2))
- ->method('getUserFolder')
- ->with('currentUser')
- ->willReturn($userFolder);
+ ->method('getUserFolder')
+ ->with('currentUser')
+ ->willReturn($userFolder);
$userFolder->expects($this->once())
- ->method('get')
- ->with('valid-path')
- ->willReturn($path);
+ ->method('get')
+ ->with('valid-path')
+ ->willReturn($path);
$userFolder->method('getById')
->willReturn([]);
@@ -1762,32 +1903,32 @@ class ShareAPIControllerTest extends TestCase {
$path->expects($this->once())
->method('lock')
- ->with(\OCP\Lock\ILockingProvider::LOCK_SHARED);
+ ->with(ILockingProvider::LOCK_SHARED);
$this->shareManager->method('createShare')
- ->with($this->callback(function (\OCP\Share\IShare $share) use ($path) {
- return $share->getNode() === $path &&
- $share->getPermissions() === (
- \OCP\Constants::PERMISSION_ALL &
- ~\OCP\Constants::PERMISSION_DELETE &
- ~\OCP\Constants::PERMISSION_CREATE
- ) &&
- $share->getShareType() === IShare::TYPE_USER &&
- $share->getSharedWith() === 'validUser' &&
- $share->getSharedBy() === 'currentUser';
+ ->with($this->callback(function (IShare $share) use ($path) {
+ return $share->getNode() === $path
+ && $share->getPermissions() === (
+ Constants::PERMISSION_ALL
+ & ~Constants::PERMISSION_DELETE
+ & ~Constants::PERMISSION_CREATE
+ )
+ && $share->getShareType() === IShare::TYPE_USER
+ && $share->getSharedWith() === 'validUser'
+ && $share->getSharedBy() === 'currentUser';
}))
->willReturnArgument(0);
$expected = new DataResponse([]);
- $result = $ocs->createShare('valid-path', \OCP\Constants::PERMISSION_ALL, IShare::TYPE_USER, 'validUser');
+ $result = $ocs->createShare('valid-path', Constants::PERMISSION_ALL, IShare::TYPE_USER, 'validUser');
$this->assertInstanceOf(get_class($expected), $result);
$this->assertEquals($expected->getData(), $result->getData());
}
- public function testCreateShareGroupNoValidShareWith() {
- $this->expectException(\OCP\AppFramework\OCS\OCSNotFoundException::class);
+ public function testCreateShareGroupNoValidShareWith(): void {
+ $this->expectException(OCSNotFoundException::class);
$this->expectExceptionMessage('Please specify a valid group');
$share = $this->newShare();
@@ -1796,30 +1937,29 @@ class ShareAPIControllerTest extends TestCase {
$this->shareManager->method('allowGroupSharing')->willReturn(true);
[$userFolder, $path] = $this->getNonSharedUserFile();
- $this->rootFolder->expects($this->exactly(2))
- ->method('getUserFolder')
- ->with('currentUser')
- ->willReturn($userFolder);
+ $this->rootFolder->method('getUserFolder')
+ ->with('currentUser')
+ ->willReturn($userFolder);
$userFolder->expects($this->once())
- ->method('get')
- ->with('valid-path')
- ->willReturn($path);
+ ->method('get')
+ ->with('valid-path')
+ ->willReturn($path);
$userFolder->method('getById')
->willReturn([]);
$path->expects($this->once())
->method('lock')
- ->with(\OCP\Lock\ILockingProvider::LOCK_SHARED);
+ ->with(ILockingProvider::LOCK_SHARED);
- $this->ocs->createShare('valid-path', \OCP\Constants::PERMISSION_ALL, IShare::TYPE_GROUP, 'invalidGroup');
+ $this->ocs->createShare('valid-path', Constants::PERMISSION_ALL, IShare::TYPE_GROUP, 'invalidGroup');
}
- public function testCreateShareGroup() {
+ public function testCreateShareGroup(): void {
$share = $this->newShare();
$this->shareManager->method('newShare')->willReturn($share);
- /** @var ShareAPIController|\PHPUnit\Framework\MockObject\MockObject $ocs */
+ /** @var ShareAPIController&MockObject $ocs */
$ocs = $this->getMockBuilder(ShareAPIController::class)
->setConstructorArgs([
$this->appName,
@@ -1831,21 +1971,26 @@ class ShareAPIControllerTest extends TestCase {
$this->urlGenerator,
$this->l,
$this->config,
+ $this->appConfig,
$this->appManager,
$this->serverContainer,
$this->userStatusManager,
$this->previewManager,
$this->dateTimeZone,
$this->logger,
+ $this->factory,
+ $this->mailer,
+ $this->tagManager,
+ $this->trustedServers,
$this->currentUser,
- ])->setMethods(['formatShare'])
+ ])->onlyMethods(['formatShare'])
->getMock();
$this->request
->method('getParam')
->willReturnMap([
['path', null, 'valid-path'],
- ['permissions', null, \OCP\Constants::PERMISSION_ALL],
+ ['permissions', null, Constants::PERMISSION_ALL],
['shareType', '-1', IShare::TYPE_GROUP],
['shareWith', null, 'validGroup'],
]);
@@ -1871,36 +2016,35 @@ class ShareAPIControllerTest extends TestCase {
$path->expects($this->once())
->method('lock')
- ->with(\OCP\Lock\ILockingProvider::LOCK_SHARED);
+ ->with(ILockingProvider::LOCK_SHARED);
$this->shareManager->method('createShare')
- ->with($this->callback(function (\OCP\Share\IShare $share) use ($path) {
- return $share->getNode() === $path &&
- $share->getPermissions() === \OCP\Constants::PERMISSION_ALL &&
- $share->getShareType() === IShare::TYPE_GROUP &&
- $share->getSharedWith() === 'validGroup' &&
- $share->getSharedBy() === 'currentUser';
+ ->with($this->callback(function (IShare $share) use ($path) {
+ return $share->getNode() === $path
+ && $share->getPermissions() === Constants::PERMISSION_ALL
+ && $share->getShareType() === IShare::TYPE_GROUP
+ && $share->getSharedWith() === 'validGroup'
+ && $share->getSharedBy() === 'currentUser';
}))
->willReturnArgument(0);
$expected = new DataResponse([]);
- $result = $ocs->createShare('valid-path', \OCP\Constants::PERMISSION_ALL, IShare::TYPE_GROUP, 'validGroup');
+ $result = $ocs->createShare('valid-path', Constants::PERMISSION_ALL, IShare::TYPE_GROUP, 'validGroup');
$this->assertInstanceOf(get_class($expected), $result);
$this->assertEquals($expected->getData(), $result->getData());
}
- public function testCreateShareGroupNotAllowed() {
- $this->expectException(\OCP\AppFramework\OCS\OCSNotFoundException::class);
+ public function testCreateShareGroupNotAllowed(): void {
+ $this->expectException(OCSNotFoundException::class);
$this->expectExceptionMessage('Group sharing is disabled by the administrator');
$share = $this->newShare();
$this->shareManager->method('newShare')->willReturn($share);
[$userFolder, $path] = $this->getNonSharedUserFolder();
- $this->rootFolder->expects($this->exactly(2))
- ->method('getUserFolder')
+ $this->rootFolder->method('getUserFolder')
->with('currentUser')
->willReturn($userFolder);
@@ -1917,12 +2061,12 @@ class ShareAPIControllerTest extends TestCase {
->method('allowGroupSharing')
->willReturn(false);
- $this->ocs->createShare('valid-path', \OCP\Constants::PERMISSION_ALL, IShare::TYPE_GROUP, 'invalidGroup');
+ $this->ocs->createShare('valid-path', Constants::PERMISSION_ALL, IShare::TYPE_GROUP, 'invalidGroup');
}
- public function testCreateShareLinkNoLinksAllowed() {
- $this->expectException(\OCP\AppFramework\OCS\OCSNotFoundException::class);
+ public function testCreateShareLinkNoLinksAllowed(): void {
+ $this->expectException(OCSNotFoundException::class);
$this->expectExceptionMessage('Public link sharing is disabled by the administrator');
$this->request
@@ -1934,7 +2078,7 @@ class ShareAPIControllerTest extends TestCase {
$path = $this->getMockBuilder(Folder::class)->getMock();
$path->method('getId')->willReturn(42);
- $storage = $this->createMock(Storage::class);
+ $storage = $this->createMock(IStorage::class);
$storage->method('instanceOfStorage')
->willReturnMap([
['OCA\Files_Sharing\External\Storage', false],
@@ -1946,19 +2090,21 @@ class ShareAPIControllerTest extends TestCase {
$this->rootFolder->method('getById')
->willReturn([]);
- $this->shareManager->method('newShare')->willReturn(\OC::$server->getShareManager()->newShare());
+ $this->shareManager->method('newShare')->willReturn(Server::get(IManager::class)->newShare());
+ $this->shareManager->method('shareApiLinkAllowPublicUpload')->willReturn(true);
+ $this->shareManager->method('shareApiAllowLinks')->willReturn(false);
- $this->ocs->createShare('valid-path', \OCP\Constants::PERMISSION_ALL, IShare::TYPE_LINK);
+ $this->ocs->createShare('valid-path', Constants::PERMISSION_ALL, IShare::TYPE_LINK);
}
- public function testCreateShareLinkNoPublicUpload() {
- $this->expectException(\OCP\AppFramework\OCS\OCSForbiddenException::class);
+ public function testCreateShareLinkNoPublicUpload(): void {
+ $this->expectException(OCSForbiddenException::class);
$this->expectExceptionMessage('Public upload disabled by the administrator');
$path = $this->getMockBuilder(Folder::class)->getMock();
$path->method('getId')->willReturn(42);
- $storage = $this->createMock(Storage::class);
+ $storage = $this->createMock(IStorage::class);
$storage->method('instanceOfStorage')
->willReturnMap([
['OCA\Files_Sharing\External\Storage', false],
@@ -1970,44 +2116,46 @@ class ShareAPIControllerTest extends TestCase {
$this->rootFolder->method('getById')
->willReturn([]);
- $this->shareManager->method('newShare')->willReturn(\OC::$server->getShareManager()->newShare());
+ $this->shareManager->method('newShare')->willReturn(Server::get(IManager::class)->newShare());
$this->shareManager->method('shareApiAllowLinks')->willReturn(true);
- $this->ocs->createShare('valid-path', \OCP\Constants::PERMISSION_ALL, IShare::TYPE_LINK, null, 'true');
+ $this->ocs->createShare('valid-path', Constants::PERMISSION_ALL, IShare::TYPE_LINK, null, 'true');
}
- public function testCreateShareLinkPublicUploadFile() {
- $this->expectException(\OCP\AppFramework\OCS\OCSNotFoundException::class);
+ public function testCreateShareLinkPublicUploadFile(): void {
+ $this->expectException(OCSBadRequestException::class);
$this->expectExceptionMessage('Public upload is only possible for publicly shared folders');
- $path = $this->getMockBuilder(File::class)->getMock();
- $path->method('getId')->willReturn(42);
- $storage = $this->createMock(Storage::class);
+ $storage = $this->createMock(IStorage::class);
$storage->method('instanceOfStorage')
->willReturnMap([
['OCA\Files_Sharing\External\Storage', false],
['OCA\Files_Sharing\SharedStorage', false],
]);
- $path->method('getStorage')->willReturn($storage);
+
+ $file = $this->createMock(File::class);
+ $file->method('getId')->willReturn(42);
+ $file->method('getStorage')->willReturn($storage);
+
$this->rootFolder->method('getUserFolder')->with($this->currentUser)->willReturnSelf();
- $this->rootFolder->method('get')->with('valid-path')->willReturn($path);
+ $this->rootFolder->method('get')->with('valid-path')->willReturn($file);
$this->rootFolder->method('getById')
->willReturn([]);
- $this->shareManager->method('newShare')->willReturn(\OC::$server->getShareManager()->newShare());
+ $this->shareManager->method('newShare')->willReturn(Server::get(IManager::class)->newShare());
$this->shareManager->method('shareApiAllowLinks')->willReturn(true);
$this->shareManager->method('shareApiLinkAllowPublicUpload')->willReturn(true);
- $this->ocs->createShare('valid-path', \OCP\Constants::PERMISSION_ALL, IShare::TYPE_LINK, null, 'true');
+ $this->ocs->createShare('valid-path', Constants::PERMISSION_ALL, IShare::TYPE_LINK, null, 'true');
}
- public function testCreateShareLinkPublicUploadFolder() {
+ public function testCreateShareLinkPublicUploadFolder(): void {
$ocs = $this->mockFormatShare();
$path = $this->getMockBuilder(Folder::class)->getMock();
$path->method('getId')->willReturn(1);
- $storage = $this->createMock(Storage::class);
+ $storage = $this->createMock(IStorage::class);
$storage->method('instanceOfStorage')
->willReturnMap([
['OCA\Files_Sharing\External\Storage', false],
@@ -2019,34 +2167,34 @@ class ShareAPIControllerTest extends TestCase {
$this->rootFolder->method('getById')
->willReturn([]);
- $this->shareManager->method('newShare')->willReturn(\OC::$server->getShareManager()->newShare());
+ $this->shareManager->method('newShare')->willReturn(Server::get(IManager::class)->newShare());
$this->shareManager->method('shareApiAllowLinks')->willReturn(true);
$this->shareManager->method('shareApiLinkAllowPublicUpload')->willReturn(true);
$this->shareManager->expects($this->once())->method('createShare')->with(
- $this->callback(function (\OCP\Share\IShare $share) use ($path) {
- return $share->getNode() === $path &&
- $share->getShareType() === IShare::TYPE_LINK &&
- $share->getPermissions() === (\OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE) &&
- $share->getSharedBy() === 'currentUser' &&
- $share->getPassword() === null &&
- $share->getExpirationDate() === null;
+ $this->callback(function (IShare $share) use ($path) {
+ return $share->getNode() === $path
+ && $share->getShareType() === IShare::TYPE_LINK
+ && $share->getPermissions() === (Constants::PERMISSION_READ | Constants::PERMISSION_CREATE | Constants::PERMISSION_UPDATE | Constants::PERMISSION_DELETE)
+ && $share->getSharedBy() === 'currentUser'
+ && $share->getPassword() === null
+ && $share->getExpirationDate() === null;
})
)->willReturnArgument(0);
$expected = new DataResponse([]);
- $result = $ocs->createShare('valid-path', \OCP\Constants::PERMISSION_ALL, IShare::TYPE_LINK, null, 'true', '', null, '');
+ $result = $ocs->createShare('valid-path', Constants::PERMISSION_ALL, IShare::TYPE_LINK, null, 'true', '', null, '');
$this->assertInstanceOf(get_class($expected), $result);
$this->assertEquals($expected->getData(), $result->getData());
}
- public function testCreateShareLinkPassword() {
+ public function testCreateShareLinkPassword(): void {
$ocs = $this->mockFormatShare();
$path = $this->getMockBuilder(Folder::class)->getMock();
$path->method('getId')->willReturn(42);
- $storage = $this->createMock(Storage::class);
+ $storage = $this->createMock(IStorage::class);
$storage->method('instanceOfStorage')
->willReturnMap([
['OCA\Files_Sharing\External\Storage', false],
@@ -2058,34 +2206,34 @@ class ShareAPIControllerTest extends TestCase {
$this->rootFolder->method('getById')
->willReturn([]);
- $this->shareManager->method('newShare')->willReturn(\OC::$server->getShareManager()->newShare());
+ $this->shareManager->method('newShare')->willReturn(Server::get(IManager::class)->newShare());
$this->shareManager->method('shareApiAllowLinks')->willReturn(true);
$this->shareManager->method('shareApiLinkAllowPublicUpload')->willReturn(true);
$this->shareManager->expects($this->once())->method('createShare')->with(
- $this->callback(function (\OCP\Share\IShare $share) use ($path) {
- return $share->getNode() === $path &&
- $share->getShareType() === IShare::TYPE_LINK &&
- $share->getPermissions() === \OCP\Constants::PERMISSION_ALL &&
- $share->getSharedBy() === 'currentUser' &&
- $share->getPassword() === 'password' &&
- $share->getExpirationDate() === null;
+ $this->callback(function (IShare $share) use ($path) {
+ return $share->getNode() === $path
+ && $share->getShareType() === IShare::TYPE_LINK
+ && $share->getPermissions() === Constants::PERMISSION_READ // publicUpload was set to false
+ && $share->getSharedBy() === 'currentUser'
+ && $share->getPassword() === 'password'
+ && $share->getExpirationDate() === null;
})
)->willReturnArgument(0);
$expected = new DataResponse([]);
- $result = $ocs->createShare('valid-path', \OCP\Constants::PERMISSION_ALL, IShare::TYPE_LINK, null, 'false', 'password', null, '');
+ $result = $ocs->createShare('valid-path', Constants::PERMISSION_READ, IShare::TYPE_LINK, null, 'false', 'password', null, '');
$this->assertInstanceOf(get_class($expected), $result);
$this->assertEquals($expected->getData(), $result->getData());
}
- public function testCreateShareLinkSendPasswordByTalk() {
+ public function testCreateShareLinkSendPasswordByTalk(): void {
$ocs = $this->mockFormatShare();
$path = $this->getMockBuilder(Folder::class)->getMock();
$path->method('getId')->willReturn(42);
- $storage = $this->createMock(Storage::class);
+ $storage = $this->createMock(IStorage::class);
$storage->method('instanceOfStorage')
->willReturnMap([
['OCA\Files_Sharing\External\Storage', false],
@@ -2097,41 +2245,41 @@ class ShareAPIControllerTest extends TestCase {
$this->rootFolder->method('getById')
->willReturn([]);
- $this->shareManager->method('newShare')->willReturn(\OC::$server->getShareManager()->newShare());
+ $this->shareManager->method('newShare')->willReturn(Server::get(IManager::class)->newShare());
$this->shareManager->method('shareApiAllowLinks')->willReturn(true);
$this->shareManager->method('shareApiLinkAllowPublicUpload')->willReturn(true);
$this->appManager->method('isEnabledForUser')->with('spreed')->willReturn(true);
$this->shareManager->expects($this->once())->method('createShare')->with(
- $this->callback(function (\OCP\Share\IShare $share) use ($path) {
- return $share->getNode() === $path &&
- $share->getShareType() === IShare::TYPE_LINK &&
- $share->getPermissions() === \OCP\Constants::PERMISSION_ALL &&
- $share->getSharedBy() === 'currentUser' &&
- $share->getPassword() === 'password' &&
- $share->getSendPasswordByTalk() === true &&
- $share->getExpirationDate() === null;
+ $this->callback(function (IShare $share) use ($path) {
+ return $share->getNode() === $path
+ && $share->getShareType() === IShare::TYPE_LINK
+ && $share->getPermissions() === (Constants::PERMISSION_ALL & ~(Constants::PERMISSION_SHARE))
+ && $share->getSharedBy() === 'currentUser'
+ && $share->getPassword() === 'password'
+ && $share->getSendPasswordByTalk() === true
+ && $share->getExpirationDate() === null;
})
)->willReturnArgument(0);
$expected = new DataResponse([]);
- $result = $ocs->createShare('valid-path', \OCP\Constants::PERMISSION_ALL, IShare::TYPE_LINK, null, 'false', 'password', 'true', '');
+ $result = $ocs->createShare('valid-path', Constants::PERMISSION_ALL, IShare::TYPE_LINK, null, 'true', 'password', 'true', '');
$this->assertInstanceOf(get_class($expected), $result);
$this->assertEquals($expected->getData(), $result->getData());
}
- public function testCreateShareLinkSendPasswordByTalkWithTalkDisabled() {
- $this->expectException(\OCP\AppFramework\OCS\OCSForbiddenException::class);
+ public function testCreateShareLinkSendPasswordByTalkWithTalkDisabled(): void {
+ $this->expectException(OCSForbiddenException::class);
$this->expectExceptionMessage('Sharing valid-path sending the password by Nextcloud Talk failed because Nextcloud Talk is not enabled');
$ocs = $this->mockFormatShare();
$path = $this->getMockBuilder(Folder::class)->getMock();
$path->method('getId')->willReturn(42);
- $storage = $this->createMock(Storage::class);
+ $storage = $this->createMock(IStorage::class);
$storage->method('instanceOfStorage')
->willReturnMap([
['OCA\Files_Sharing\External\Storage', false],
@@ -2144,7 +2292,7 @@ class ShareAPIControllerTest extends TestCase {
$this->rootFolder->method('getById')
->willReturn([]);
- $this->shareManager->method('newShare')->willReturn(\OC::$server->getShareManager()->newShare());
+ $this->shareManager->method('newShare')->willReturn(Server::get(IManager::class)->newShare());
$this->shareManager->method('shareApiAllowLinks')->willReturn(true);
$this->shareManager->method('shareApiLinkAllowPublicUpload')->willReturn(true);
@@ -2152,10 +2300,10 @@ class ShareAPIControllerTest extends TestCase {
$this->shareManager->expects($this->never())->method('createShare');
- $ocs->createShare('valid-path', \OCP\Constants::PERMISSION_ALL, IShare::TYPE_LINK, null, 'false', 'password', 'true', '');
+ $ocs->createShare('valid-path', Constants::PERMISSION_ALL, IShare::TYPE_LINK, null, 'false', 'password', 'true', '');
}
- public function testCreateShareValidExpireDate() {
+ public function testCreateShareValidExpireDate(): void {
$ocs = $this->mockFormatShare();
$this->request
@@ -2170,7 +2318,7 @@ class ShareAPIControllerTest extends TestCase {
$path = $this->getMockBuilder(Folder::class)->getMock();
$path->method('getId')->willReturn(42);
- $storage = $this->createMock(Storage::class);
+ $storage = $this->createMock(IStorage::class);
$storage->method('instanceOfStorage')
->willReturnMap([
['OCA\Files_Sharing\External\Storage', false],
@@ -2182,21 +2330,21 @@ class ShareAPIControllerTest extends TestCase {
$this->rootFolder->method('getById')
->willReturn([]);
- $this->shareManager->method('newShare')->willReturn(\OC::$server->getShareManager()->newShare());
+ $this->shareManager->method('newShare')->willReturn(Server::get(IManager::class)->newShare());
$this->shareManager->method('shareApiAllowLinks')->willReturn(true);
$this->shareManager->method('shareApiLinkAllowPublicUpload')->willReturn(true);
$this->shareManager->expects($this->once())->method('createShare')->with(
- $this->callback(function (\OCP\Share\IShare $share) use ($path) {
+ $this->callback(function (IShare $share) use ($path) {
$date = new \DateTime('2000-01-01');
$date->setTime(0, 0, 0);
- return $share->getNode() === $path &&
- $share->getShareType() === IShare::TYPE_LINK &&
- $share->getPermissions() === \OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_SHARE &&
- $share->getSharedBy() === 'currentUser' &&
- $share->getPassword() === null &&
- $share->getExpirationDate() == $date;
+ return $share->getNode() === $path
+ && $share->getShareType() === IShare::TYPE_LINK
+ && $share->getPermissions() === Constants::PERMISSION_READ | Constants::PERMISSION_SHARE
+ && $share->getSharedBy() === 'currentUser'
+ && $share->getPassword() === null
+ && $share->getExpirationDate() == $date;
})
)->willReturnArgument(0);
@@ -2208,15 +2356,15 @@ class ShareAPIControllerTest extends TestCase {
}
- public function testCreateShareInvalidExpireDate() {
- $this->expectException(\OCP\AppFramework\OCS\OCSNotFoundException::class);
- $this->expectExceptionMessage('Invalid date, date format must be YYYY-MM-DD');
+ public function testCreateShareInvalidExpireDate(): void {
+ $this->expectException(OCSNotFoundException::class);
+ $this->expectExceptionMessage('Invalid date. Format must be YYYY-MM-DD');
$ocs = $this->mockFormatShare();
$path = $this->getMockBuilder(Folder::class)->getMock();
$path->method('getId')->willReturn(42);
- $storage = $this->createMock(Storage::class);
+ $storage = $this->createMock(IStorage::class);
$storage->method('instanceOfStorage')
->willReturnMap([
['OCA\Files_Sharing\External\Storage', false],
@@ -2228,18 +2376,18 @@ class ShareAPIControllerTest extends TestCase {
$this->rootFolder->method('getById')
->willReturn([]);
- $this->shareManager->method('newShare')->willReturn(\OC::$server->getShareManager()->newShare());
+ $this->shareManager->method('newShare')->willReturn(Server::get(IManager::class)->newShare());
$this->shareManager->method('shareApiAllowLinks')->willReturn(true);
$this->shareManager->method('shareApiLinkAllowPublicUpload')->willReturn(true);
- $ocs->createShare('valid-path', \OCP\Constants::PERMISSION_ALL, IShare::TYPE_LINK, null, 'false', '', null, 'a1b2d3');
+ $ocs->createShare('valid-path', Constants::PERMISSION_ALL, IShare::TYPE_LINK, null, 'false', '', null, 'a1b2d3');
}
- public function testCreateShareRemote() {
+ public function testCreateShareRemote(): void {
$share = $this->newShare();
$this->shareManager->method('newShare')->willReturn($share);
- /** @var \OCA\Files_Sharing\Controller\ShareAPIController $ocs */
+ /** @var ShareAPIController $ocs */
$ocs = $this->getMockBuilder(ShareAPIController::class)
->setConstructorArgs([
$this->appName,
@@ -2251,26 +2399,31 @@ class ShareAPIControllerTest extends TestCase {
$this->urlGenerator,
$this->l,
$this->config,
+ $this->appConfig,
$this->appManager,
$this->serverContainer,
$this->userStatusManager,
$this->previewManager,
$this->dateTimeZone,
$this->logger,
+ $this->factory,
+ $this->mailer,
+ $this->tagManager,
+ $this->trustedServers,
$this->currentUser,
- ])->setMethods(['formatShare'])
+ ])->onlyMethods(['formatShare'])
->getMock();
[$userFolder, $path] = $this->getNonSharedUserFile();
$this->rootFolder->expects($this->exactly(2))
- ->method('getUserFolder')
- ->with('currentUser')
- ->willReturn($userFolder);
+ ->method('getUserFolder')
+ ->with('currentUser')
+ ->willReturn($userFolder);
$userFolder->expects($this->once())
- ->method('get')
- ->with('valid-path')
- ->willReturn($path);
+ ->method('get')
+ ->with('valid-path')
+ ->willReturn($path);
$userFolder->method('getById')
->willReturn([]);
@@ -2278,36 +2431,36 @@ class ShareAPIControllerTest extends TestCase {
$path->expects($this->once())
->method('lock')
- ->with(\OCP\Lock\ILockingProvider::LOCK_SHARED);
+ ->with(ILockingProvider::LOCK_SHARED);
$this->shareManager->method('createShare')
- ->with($this->callback(function (\OCP\Share\IShare $share) use ($path) {
- return $share->getNode() === $path &&
- $share->getPermissions() === (
- \OCP\Constants::PERMISSION_ALL &
- ~\OCP\Constants::PERMISSION_DELETE &
- ~\OCP\Constants::PERMISSION_CREATE
- ) &&
- $share->getShareType() === IShare::TYPE_REMOTE &&
- $share->getSharedWith() === 'user@example.org' &&
- $share->getSharedBy() === 'currentUser';
+ ->with($this->callback(function (IShare $share) use ($path) {
+ return $share->getNode() === $path
+ && $share->getPermissions() === (
+ Constants::PERMISSION_ALL
+ & ~Constants::PERMISSION_DELETE
+ & ~Constants::PERMISSION_CREATE
+ )
+ && $share->getShareType() === IShare::TYPE_REMOTE
+ && $share->getSharedWith() === 'user@example.org'
+ && $share->getSharedBy() === 'currentUser';
}))
->willReturnArgument(0);
$this->shareManager->method('outgoingServer2ServerSharesAllowed')->willReturn(true);
$expected = new DataResponse([]);
- $result = $ocs->createShare('valid-path', \OCP\Constants::PERMISSION_ALL, IShare::TYPE_REMOTE, 'user@example.org');
+ $result = $ocs->createShare('valid-path', Constants::PERMISSION_ALL, IShare::TYPE_REMOTE, 'user@example.org');
$this->assertInstanceOf(get_class($expected), $result);
$this->assertEquals($expected->getData(), $result->getData());
}
- public function testCreateShareRemoteGroup() {
+ public function testCreateShareRemoteGroup(): void {
$share = $this->newShare();
$this->shareManager->method('newShare')->willReturn($share);
- /** @var \OCA\Files_Sharing\Controller\ShareAPIController $ocs */
+ /** @var ShareAPIController $ocs */
$ocs = $this->getMockBuilder(ShareAPIController::class)
->setConstructorArgs([
$this->appName,
@@ -2319,26 +2472,31 @@ class ShareAPIControllerTest extends TestCase {
$this->urlGenerator,
$this->l,
$this->config,
+ $this->appConfig,
$this->appManager,
$this->serverContainer,
$this->userStatusManager,
$this->previewManager,
$this->dateTimeZone,
$this->logger,
+ $this->factory,
+ $this->mailer,
+ $this->tagManager,
+ $this->trustedServers,
$this->currentUser,
- ])->setMethods(['formatShare'])
+ ])->onlyMethods(['formatShare'])
->getMock();
[$userFolder, $path] = $this->getNonSharedUserFile();
$this->rootFolder->expects($this->exactly(2))
- ->method('getUserFolder')
- ->with('currentUser')
- ->willReturn($userFolder);
+ ->method('getUserFolder')
+ ->with('currentUser')
+ ->willReturn($userFolder);
$userFolder->expects($this->once())
- ->method('get')
- ->with('valid-path')
- ->willReturn($path);
+ ->method('get')
+ ->with('valid-path')
+ ->willReturn($path);
$userFolder->method('getById')
->willReturn([]);
@@ -2346,32 +2504,32 @@ class ShareAPIControllerTest extends TestCase {
$path->expects($this->once())
->method('lock')
- ->with(\OCP\Lock\ILockingProvider::LOCK_SHARED);
+ ->with(ILockingProvider::LOCK_SHARED);
$this->shareManager->method('createShare')
- ->with($this->callback(function (\OCP\Share\IShare $share) use ($path) {
- return $share->getNode() === $path &&
- $share->getPermissions() === (
- \OCP\Constants::PERMISSION_ALL &
- ~\OCP\Constants::PERMISSION_DELETE &
- ~\OCP\Constants::PERMISSION_CREATE
- ) &&
- $share->getShareType() === IShare::TYPE_REMOTE_GROUP &&
- $share->getSharedWith() === 'group@example.org' &&
- $share->getSharedBy() === 'currentUser';
+ ->with($this->callback(function (IShare $share) use ($path) {
+ return $share->getNode() === $path
+ && $share->getPermissions() === (
+ Constants::PERMISSION_ALL
+ & ~Constants::PERMISSION_DELETE
+ & ~Constants::PERMISSION_CREATE
+ )
+ && $share->getShareType() === IShare::TYPE_REMOTE_GROUP
+ && $share->getSharedWith() === 'group@example.org'
+ && $share->getSharedBy() === 'currentUser';
}))
->willReturnArgument(0);
$this->shareManager->method('outgoingServer2ServerGroupSharesAllowed')->willReturn(true);
$expected = new DataResponse([]);
- $result = $ocs->createShare('valid-path', \OCP\Constants::PERMISSION_ALL, IShare::TYPE_REMOTE_GROUP, 'group@example.org');
+ $result = $ocs->createShare('valid-path', Constants::PERMISSION_ALL, IShare::TYPE_REMOTE_GROUP, 'group@example.org');
$this->assertInstanceOf(get_class($expected), $result);
$this->assertEquals($expected->getData(), $result->getData());
}
- public function testCreateShareRoom() {
+ public function testCreateShareRoom(): void {
$ocs = $this->mockFormatShare();
$share = $this->newShare();
@@ -2379,44 +2537,43 @@ class ShareAPIControllerTest extends TestCase {
[$userFolder, $path] = $this->getNonSharedUserFile();
$this->rootFolder->expects($this->exactly(2))
- ->method('getUserFolder')
- ->with('currentUser')
- ->willReturn($userFolder);
+ ->method('getUserFolder')
+ ->with('currentUser')
+ ->willReturn($userFolder);
$userFolder->expects($this->once())
- ->method('get')
- ->with('valid-path')
- ->willReturn($path);
+ ->method('get')
+ ->with('valid-path')
+ ->willReturn($path);
$userFolder->method('getById')
->willReturn([]);
$path->expects($this->once())
->method('lock')
- ->with(\OCP\Lock\ILockingProvider::LOCK_SHARED);
+ ->with(ILockingProvider::LOCK_SHARED);
$this->appManager->method('isEnabledForUser')
->with('spreed')
->willReturn(true);
- $helper = $this->getMockBuilder('\OCA\Talk\Share\Helper\ShareAPIController')
- ->setMethods(['createShare'])
+ // This is not possible anymore with PHPUnit 10+
+ // as `setMethods` was removed and now real reflection is used, thus the class needs to exist.
+ // $helper = $this->getMockBuilder('\OCA\Talk\Share\Helper\ShareAPIController')
+ $helper = $this->getMockBuilder(\stdClass::class)
+ ->addMethods(['createShare'])
->getMock();
$helper->method('createShare')
->with(
$share,
'recipientRoom',
- \OCP\Constants::PERMISSION_ALL &
- ~\OCP\Constants::PERMISSION_DELETE &
- ~\OCP\Constants::PERMISSION_CREATE,
+ Constants::PERMISSION_ALL
+ & ~Constants::PERMISSION_DELETE
+ & ~Constants::PERMISSION_CREATE,
''
)->willReturnCallback(
- function ($share) {
+ function ($share): void {
$share->setSharedWith('recipientRoom');
- $share->setPermissions(
- \OCP\Constants::PERMISSION_ALL &
- ~\OCP\Constants::PERMISSION_DELETE &
- ~\OCP\Constants::PERMISSION_CREATE
- );
+ $share->setPermissions(Constants::PERMISSION_ALL);
}
);
@@ -2425,29 +2582,25 @@ class ShareAPIControllerTest extends TestCase {
->willReturn($helper);
$this->shareManager->method('createShare')
- ->with($this->callback(function (\OCP\Share\IShare $share) use ($path) {
- return $share->getNode() === $path &&
- $share->getPermissions() === (
- \OCP\Constants::PERMISSION_ALL &
- ~\OCP\Constants::PERMISSION_DELETE &
- ~\OCP\Constants::PERMISSION_CREATE
- ) &&
- $share->getShareType() === IShare::TYPE_ROOM &&
- $share->getSharedWith() === 'recipientRoom' &&
- $share->getSharedBy() === 'currentUser';
+ ->with($this->callback(function (IShare $share) use ($path) {
+ return $share->getNode() === $path
+ && $share->getPermissions() === Constants::PERMISSION_ALL
+ && $share->getShareType() === IShare::TYPE_ROOM
+ && $share->getSharedWith() === 'recipientRoom'
+ && $share->getSharedBy() === 'currentUser';
}))
->willReturnArgument(0);
$expected = new DataResponse([]);
- $result = $ocs->createShare('valid-path', \OCP\Constants::PERMISSION_ALL, IShare::TYPE_ROOM, 'recipientRoom');
+ $result = $ocs->createShare('valid-path', Constants::PERMISSION_ALL, IShare::TYPE_ROOM, 'recipientRoom');
$this->assertInstanceOf(get_class($expected), $result);
$this->assertEquals($expected->getData(), $result->getData());
}
- public function testCreateShareRoomHelperNotAvailable() {
- $this->expectException(\OCP\AppFramework\OCS\OCSForbiddenException::class);
+ public function testCreateShareRoomHelperNotAvailable(): void {
+ $this->expectException(OCSForbiddenException::class);
$this->expectExceptionMessage('Sharing valid-path failed because the back end does not support room shares');
$ocs = $this->mockFormatShare();
@@ -2456,22 +2609,21 @@ class ShareAPIControllerTest extends TestCase {
$this->shareManager->method('newShare')->willReturn($share);
[$userFolder, $path] = $this->getNonSharedUserFolder();
- $this->rootFolder->expects($this->exactly(2))
- ->method('getUserFolder')
- ->with('currentUser')
- ->willReturn($userFolder);
+ $this->rootFolder->method('getUserFolder')
+ ->with('currentUser')
+ ->willReturn($userFolder);
$path->method('getPath')->willReturn('valid-path');
$userFolder->expects($this->once())
- ->method('get')
- ->with('valid-path')
- ->willReturn($path);
+ ->method('get')
+ ->with('valid-path')
+ ->willReturn($path);
$userFolder->method('getById')
->willReturn([]);
$path->expects($this->once())
->method('lock')
- ->with(\OCP\Lock\ILockingProvider::LOCK_SHARED);
+ ->with(ILockingProvider::LOCK_SHARED);
$this->appManager->method('isEnabledForUser')
->with('spreed')
@@ -2479,12 +2631,12 @@ class ShareAPIControllerTest extends TestCase {
$this->shareManager->expects($this->never())->method('createShare');
- $ocs->createShare('valid-path', \OCP\Constants::PERMISSION_ALL, IShare::TYPE_ROOM, 'recipientRoom');
+ $ocs->createShare('valid-path', Constants::PERMISSION_ALL, IShare::TYPE_ROOM, 'recipientRoom');
}
- public function testCreateShareRoomHelperThrowException() {
- $this->expectException(\OCP\AppFramework\OCS\OCSNotFoundException::class);
+ public function testCreateShareRoomHelperThrowException(): void {
+ $this->expectException(OCSNotFoundException::class);
$this->expectExceptionMessage('Exception thrown by the helper');
$ocs = $this->mockFormatShare();
@@ -2494,40 +2646,40 @@ class ShareAPIControllerTest extends TestCase {
$this->shareManager->method('newShare')->willReturn($share);
[$userFolder, $path] = $this->getNonSharedUserFile();
- $this->rootFolder->expects($this->exactly(2))
- ->method('getUserFolder')
- ->with('currentUser')
- ->willReturn($userFolder);
+ $this->rootFolder->method('getUserFolder')
+ ->with('currentUser')
+ ->willReturn($userFolder);
$userFolder->expects($this->once())
- ->method('get')
- ->with('valid-path')
- ->willReturn($path);
+ ->method('get')
+ ->with('valid-path')
+ ->willReturn($path);
$userFolder->method('getById')
->willReturn([]);
$path->expects($this->once())
->method('lock')
- ->with(\OCP\Lock\ILockingProvider::LOCK_SHARED);
+ ->with(ILockingProvider::LOCK_SHARED);
$this->appManager->method('isEnabledForUser')
->with('spreed')
->willReturn(true);
- $helper = $this->getMockBuilder('\OCA\Talk\Share\Helper\ShareAPIController')
- ->setMethods(['createShare'])
+ // This is not possible anymore with PHPUnit 10+
+ // as `setMethods` was removed and now real reflection is used, thus the class needs to exist.
+ // $helper = $this->getMockBuilder('\OCA\Talk\Share\Helper\ShareAPIController')
+ $helper = $this->getMockBuilder(\stdClass::class)
+ ->addMethods(['createShare'])
->getMock();
$helper->method('createShare')
->with(
$share,
'recipientRoom',
- \OCP\Constants::PERMISSION_ALL &
- ~\OCP\Constants::PERMISSION_DELETE &
- ~\OCP\Constants::PERMISSION_CREATE,
+ Constants::PERMISSION_ALL & ~(Constants::PERMISSION_CREATE | Constants::PERMISSION_DELETE),
''
)->willReturnCallback(
- function ($share) {
- throw new OCSNotFoundException("Exception thrown by the helper");
+ function ($share): void {
+ throw new OCSNotFoundException('Exception thrown by the helper');
}
);
@@ -2537,18 +2689,18 @@ class ShareAPIControllerTest extends TestCase {
$this->shareManager->expects($this->never())->method('createShare');
- $ocs->createShare('valid-path', \OCP\Constants::PERMISSION_ALL, IShare::TYPE_ROOM, 'recipientRoom');
+ $ocs->createShare('valid-path', Constants::PERMISSION_ALL, IShare::TYPE_ROOM, 'recipientRoom');
}
/**
* Test for https://github.com/owncloud/core/issues/22587
* TODO: Remove once proper solution is in place
*/
- public function testCreateReshareOfFederatedMountNoDeletePermissions() {
- $share = \OC::$server->getShareManager()->newShare();
+ public function testCreateReshareOfFederatedMountNoDeletePermissions(): void {
+ $share = Server::get(IManager::class)->newShare();
$this->shareManager->method('newShare')->willReturn($share);
- /** @var ShareAPIController|\PHPUnit\Framework\MockObject\MockObject $ocs */
+ /** @var ShareAPIController&MockObject $ocs */
$ocs = $this->getMockBuilder(ShareAPIController::class)
->setConstructorArgs([
$this->appName,
@@ -2560,14 +2712,19 @@ class ShareAPIControllerTest extends TestCase {
$this->urlGenerator,
$this->l,
$this->config,
+ $this->appConfig,
$this->appManager,
$this->serverContainer,
$this->userStatusManager,
$this->previewManager,
$this->dateTimeZone,
$this->logger,
+ $this->factory,
+ $this->mailer,
+ $this->tagManager,
+ $this->trustedServers,
$this->currentUser,
- ])->setMethods(['formatShare'])
+ ])->onlyMethods(['formatShare'])
->getMock();
$userFolder = $this->getMockBuilder(Folder::class)->getMock();
@@ -2579,7 +2736,7 @@ class ShareAPIControllerTest extends TestCase {
$path = $this->getMockBuilder(Folder::class)->getMock();
$path->method('getId')->willReturn(42);
- $storage = $this->createMock(Storage::class);
+ $storage = $this->createMock(IStorage::class);
$storage->method('instanceOfStorage')
->willReturnMap([
['OCA\Files_Sharing\External\Storage', true],
@@ -2588,7 +2745,7 @@ class ShareAPIControllerTest extends TestCase {
$userFolder->method('getStorage')->willReturn($storage);
$path->method('getStorage')->willReturn($storage);
- $path->method('getPermissions')->willReturn(\OCP\Constants::PERMISSION_READ);
+ $path->method('getPermissions')->willReturn(Constants::PERMISSION_READ);
$userFolder->expects($this->once())
->method('get')
->with('valid-path')
@@ -2601,17 +2758,17 @@ class ShareAPIControllerTest extends TestCase {
$this->shareManager
->expects($this->once())
->method('createShare')
- ->with($this->callback(function (\OCP\Share\IShare $share) {
- return $share->getPermissions() === \OCP\Constants::PERMISSION_READ;
+ ->with($this->callback(function (IShare $share) {
+ return $share->getPermissions() === Constants::PERMISSION_READ;
}))
->willReturnArgument(0);
- $ocs->createShare('valid-path', \OCP\Constants::PERMISSION_ALL, IShare::TYPE_USER, 'validUser');
+ $ocs->createShare('valid-path', Constants::PERMISSION_ALL, IShare::TYPE_USER, 'validUser');
}
- public function testUpdateShareCantAccess() {
- $this->expectException(\OCP\AppFramework\OCS\OCSNotFoundException::class);
+ public function testUpdateShareCantAccess(): void {
+ $this->expectException(OCSNotFoundException::class);
$this->expectExceptionMessage('Wrong share ID, share does not exist');
[$userFolder, $node] = $this->getNonSharedUserFolder();
@@ -2620,7 +2777,7 @@ class ShareAPIControllerTest extends TestCase {
$node->expects($this->once())
->method('lock')
- ->with(\OCP\Lock\ILockingProvider::LOCK_SHARED);
+ ->with(ILockingProvider::LOCK_SHARED);
$this->shareManager->method('getShareById')->with('ocinternal:42')->willReturn($share);
@@ -2628,28 +2785,28 @@ class ShareAPIControllerTest extends TestCase {
->with($this->currentUser)
->willReturn($userFolder);
- $userFolder->method('getFirstNodeById')
+ $userFolder->method('getById')
->with($share->getNodeId())
- ->willReturn($share->getNode());
+ ->willReturn([$share->getNode()]);
$this->ocs->updateShare(42);
}
- public function testUpdateNoParametersLink() {
- $this->expectException(\OCP\AppFramework\OCS\OCSBadRequestException::class);
+ public function testUpdateNoParametersLink(): void {
+ $this->expectException(OCSBadRequestException::class);
$this->expectExceptionMessage('Wrong or no update parameter given');
$node = $this->getMockBuilder(Folder::class)->getMock();
$share = $this->newShare();
- $share->setPermissions(\OCP\Constants::PERMISSION_ALL)
+ $share->setPermissions(Constants::PERMISSION_ALL)
->setSharedBy($this->currentUser)
->setShareType(IShare::TYPE_LINK)
->setNode($node);
$node->expects($this->once())
->method('lock')
- ->with(\OCP\Lock\ILockingProvider::LOCK_SHARED);
+ ->with(ILockingProvider::LOCK_SHARED);
$this->shareManager->method('getShareById')->with('ocinternal:42')->willReturn($share);
@@ -2657,34 +2814,34 @@ class ShareAPIControllerTest extends TestCase {
}
- public function testUpdateNoParametersOther() {
- $this->expectException(\OCP\AppFramework\OCS\OCSBadRequestException::class);
+ public function testUpdateNoParametersOther(): void {
+ $this->expectException(OCSBadRequestException::class);
$this->expectExceptionMessage('Wrong or no update parameter given');
$node = $this->getMockBuilder(Folder::class)->getMock();
$share = $this->newShare();
- $share->setPermissions(\OCP\Constants::PERMISSION_ALL)
+ $share->setPermissions(Constants::PERMISSION_ALL)
->setSharedBy($this->currentUser)
->setShareType(IShare::TYPE_GROUP)
->setNode($node);
$node->expects($this->once())
->method('lock')
- ->with(\OCP\Lock\ILockingProvider::LOCK_SHARED);
+ ->with(ILockingProvider::LOCK_SHARED);
$this->shareManager->method('getShareById')->with('ocinternal:42')->willReturn($share);
$this->ocs->updateShare(42);
}
- public function testUpdateLinkShareClear() {
+ public function testUpdateLinkShareClear(): void {
$ocs = $this->mockFormatShare();
[$userFolder, $node] = $this->getNonSharedUserFolder();
$node->method('getId')
->willReturn(42);
$share = $this->newShare();
- $share->setPermissions(\OCP\Constants::PERMISSION_ALL)
+ $share->setPermissions(Constants::PERMISSION_ALL)
->setSharedBy($this->currentUser)
->setShareType(IShare::TYPE_LINK)
->setPassword('password')
@@ -2692,25 +2849,25 @@ class ShareAPIControllerTest extends TestCase {
->setNote('note')
->setLabel('label')
->setHideDownload(true)
- ->setPermissions(\OCP\Constants::PERMISSION_ALL)
+ ->setPermissions(Constants::PERMISSION_ALL)
->setNode($node);
$node->expects($this->once())
->method('lock')
- ->with(\OCP\Lock\ILockingProvider::LOCK_SHARED);
+ ->with(ILockingProvider::LOCK_SHARED);
$this->shareManager->method('getShareById')->with('ocinternal:42')->willReturn($share);
$this->shareManager->expects($this->once())->method('updateShare')->with(
- $this->callback(function (\OCP\Share\IShare $share) {
- return $share->getPermissions() === \OCP\Constants::PERMISSION_READ &&
- $share->getPassword() === null &&
- $share->getExpirationDate() === null &&
+ $this->callback(function (IShare $share) {
+ return $share->getPermissions() === Constants::PERMISSION_READ
+ && $share->getPassword() === null
+ && $share->getExpirationDate() === null
// Once set a note or a label are never back to null, only to an
// empty string.
- $share->getNote() === '' &&
- $share->getLabel() === '' &&
- $share->getHideDownload() === false;
+ && $share->getNote() === ''
+ && $share->getLabel() === ''
+ && $share->getHideDownload() === false;
})
)->willReturnArgument(0);
@@ -2721,6 +2878,9 @@ class ShareAPIControllerTest extends TestCase {
->with($this->currentUser)
->willReturn($userFolder);
+ $userFolder->method('getById')
+ ->with(42)
+ ->willReturn([$node]);
$userFolder->method('getFirstNodeById')
->with(42)
->willReturn($node);
@@ -2738,15 +2898,15 @@ class ShareAPIControllerTest extends TestCase {
$this->assertEquals($expected->getData(), $result->getData());
}
- public function testUpdateLinkShareSet() {
+ public function testUpdateLinkShareSet(): void {
$ocs = $this->mockFormatShare();
[$userFolder, $folder] = $this->getNonSharedUserFolder();
$folder->method('getId')
->willReturn(42);
- $share = \OC::$server->getShareManager()->newShare();
- $share->setPermissions(\OCP\Constants::PERMISSION_ALL)
+ $share = Server::get(IManager::class)->newShare();
+ $share->setPermissions(Constants::PERMISSION_ALL)
->setSharedBy($this->currentUser)
->setShareType(IShare::TYPE_LINK)
->setNode($folder);
@@ -2755,16 +2915,16 @@ class ShareAPIControllerTest extends TestCase {
$this->shareManager->method('shareApiLinkAllowPublicUpload')->willReturn(true);
$this->shareManager->expects($this->once())->method('updateShare')->with(
- $this->callback(function (\OCP\Share\IShare $share) {
+ $this->callback(function (IShare $share) {
$date = new \DateTime('2000-01-01');
$date->setTime(0, 0, 0);
- return $share->getPermissions() === (\OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE) &&
- $share->getPassword() === 'password' &&
- $share->getExpirationDate() == $date &&
- $share->getNote() === 'note' &&
- $share->getLabel() === 'label' &&
- $share->getHideDownload() === true;
+ return $share->getPermissions() === (Constants::PERMISSION_READ | Constants::PERMISSION_CREATE | Constants::PERMISSION_UPDATE | Constants::PERMISSION_DELETE)
+ && $share->getPassword() === 'password'
+ && $share->getExpirationDate() == $date
+ && $share->getNote() === 'note'
+ && $share->getLabel() === 'label'
+ && $share->getHideDownload() === true;
})
)->willReturnArgument(0);
@@ -2775,9 +2935,9 @@ class ShareAPIControllerTest extends TestCase {
->with($this->currentUser)
->willReturn($userFolder);
- $userFolder->method('getFirstNodeById')
+ $userFolder->method('getById')
->with(42)
- ->willReturn($folder);
+ ->willReturn([$folder]);
$mountPoint = $this->createMock(IMountPoint::class);
$folder->method('getMountPoint')
@@ -2792,18 +2952,16 @@ class ShareAPIControllerTest extends TestCase {
$this->assertEquals($expected->getData(), $result->getData());
}
- /**
- * @dataProvider publicUploadParamsProvider
- */
- public function testUpdateLinkShareEnablePublicUpload($permissions, $publicUpload, $expireDate, $password) {
+ #[\PHPUnit\Framework\Attributes\DataProvider('publicUploadParamsProvider')]
+ public function testUpdateLinkShareEnablePublicUpload($permissions, $publicUpload, $expireDate, $password): void {
$ocs = $this->mockFormatShare();
[$userFolder, $folder] = $this->getNonSharedUserFolder();
$folder->method('getId')
->willReturn(42);
- $share = \OC::$server->getShareManager()->newShare();
- $share->setPermissions(\OCP\Constants::PERMISSION_ALL)
+ $share = Server::get(IManager::class)->newShare();
+ $share->setPermissions(Constants::PERMISSION_ALL)
->setSharedBy($this->currentUser)
->setShareType(IShare::TYPE_LINK)
->setPassword('password')
@@ -2814,10 +2972,10 @@ class ShareAPIControllerTest extends TestCase {
$this->shareManager->method('getSharedWith')->willReturn([]);
$this->shareManager->expects($this->once())->method('updateShare')->with(
- $this->callback(function (\OCP\Share\IShare $share) {
- return $share->getPermissions() === (\OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE) &&
- $share->getPassword() === 'password' &&
- $share->getExpirationDate() === null;
+ $this->callback(function (IShare $share) {
+ return $share->getPermissions() === (Constants::PERMISSION_READ | Constants::PERMISSION_CREATE | Constants::PERMISSION_UPDATE | Constants::PERMISSION_DELETE)
+ && $share->getPassword() === 'password'
+ && $share->getExpirationDate() === null;
})
)->willReturnArgument(0);
@@ -2825,9 +2983,9 @@ class ShareAPIControllerTest extends TestCase {
->with($this->currentUser)
->willReturn($userFolder);
- $userFolder->method('getFirstNodeById')
+ $userFolder->method('getById')
->with(42)
- ->willReturn($folder);
+ ->willReturn([$folder]);
$mountPoint = $this->createMock(IMountPoint::class);
$folder->method('getMountPoint')
@@ -2843,28 +3001,26 @@ class ShareAPIControllerTest extends TestCase {
}
- public function publicLinkValidPermissionsProvider() {
+ public static function publicLinkValidPermissionsProvider() {
return [
- [\OCP\Constants::PERMISSION_CREATE],
- [\OCP\Constants::PERMISSION_READ],
- [\OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_UPDATE],
- [\OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_DELETE],
- [\OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_CREATE],
+ [Constants::PERMISSION_CREATE],
+ [Constants::PERMISSION_READ],
+ [Constants::PERMISSION_READ | Constants::PERMISSION_UPDATE],
+ [Constants::PERMISSION_READ | Constants::PERMISSION_DELETE],
+ [Constants::PERMISSION_READ | Constants::PERMISSION_CREATE],
];
}
- /**
- * @dataProvider publicLinkValidPermissionsProvider
- */
- public function testUpdateLinkShareSetCRUDPermissions($permissions) {
+ #[\PHPUnit\Framework\Attributes\DataProvider('publicLinkValidPermissionsProvider')]
+ public function testUpdateLinkShareSetCRUDPermissions($permissions): void {
$ocs = $this->mockFormatShare();
[$userFolder, $folder] = $this->getNonSharedUserFolder();
$folder->method('getId')
->willReturn(42);
- $share = \OC::$server->getShareManager()->newShare();
- $share->setPermissions(\OCP\Constants::PERMISSION_ALL)
+ $share = Server::get(IManager::class)->newShare();
+ $share->setPermissions(Constants::PERMISSION_ALL)
->setSharedBy($this->currentUser)
->setShareType(IShare::TYPE_LINK)
->setPassword('password')
@@ -2883,9 +3039,9 @@ class ShareAPIControllerTest extends TestCase {
->with($this->currentUser)
->willReturn($userFolder);
- $userFolder->method('getFirstNodeById')
+ $userFolder->method('getById')
->with(42)
- ->willReturn($folder);
+ ->willReturn([$folder]);
$mountPoint = $this->createMock(IMountPoint::class);
$folder->method('getMountPoint')
@@ -2894,56 +3050,52 @@ class ShareAPIControllerTest extends TestCase {
->willReturn(42);
$expected = new DataResponse([]);
- $result = $ocs->updateShare(42, $permissions, 'password', null, 'true', null);
+ $result = $ocs->updateShare(42, $permissions, 'password', null, null, null);
$this->assertInstanceOf(get_class($expected), $result);
$this->assertEquals($expected->getData(), $result->getData());
}
- public function publicLinkInvalidPermissionsProvider1() {
+ public static function publicLinkInvalidPermissionsProvider1() {
return [
- [\OCP\Constants::PERMISSION_DELETE],
- [\OCP\Constants::PERMISSION_UPDATE],
- [\OCP\Constants::PERMISSION_SHARE],
+ [Constants::PERMISSION_DELETE],
+ [Constants::PERMISSION_UPDATE],
+ [Constants::PERMISSION_SHARE],
];
}
- /**
- * @dataProvider publicLinkInvalidPermissionsProvider1
- */
- public function testUpdateLinkShareSetInvalidCRUDPermissions1($permissions) {
- $this->expectException(\OCP\AppFramework\OCS\OCSBadRequestException::class);
+ #[\PHPUnit\Framework\Attributes\DataProvider('publicLinkInvalidPermissionsProvider1')]
+ public function testUpdateLinkShareSetInvalidCRUDPermissions1($permissions): void {
+ $this->expectException(OCSBadRequestException::class);
$this->expectExceptionMessage('Share must at least have READ or CREATE permissions');
- $this->testUpdateLinkShareSetCRUDPermissions($permissions);
+ $this->testUpdateLinkShareSetCRUDPermissions($permissions, null);
}
- public function publicLinkInvalidPermissionsProvider2() {
+ public static function publicLinkInvalidPermissionsProvider2() {
return [
- [\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_DELETE],
- [\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE],
+ [Constants::PERMISSION_CREATE | Constants::PERMISSION_DELETE],
+ [Constants::PERMISSION_CREATE | Constants::PERMISSION_UPDATE],
];
}
- /**
- * @dataProvider publicLinkInvalidPermissionsProvider2
- */
- public function testUpdateLinkShareSetInvalidCRUDPermissions2($permissions) {
- $this->expectException(\OCP\AppFramework\OCS\OCSBadRequestException::class);
+ #[\PHPUnit\Framework\Attributes\DataProvider('publicLinkInvalidPermissionsProvider2')]
+ public function testUpdateLinkShareSetInvalidCRUDPermissions2($permissions): void {
+ $this->expectException(OCSBadRequestException::class);
$this->expectExceptionMessage('Share must have READ permission if UPDATE or DELETE permission is set');
$this->testUpdateLinkShareSetCRUDPermissions($permissions);
}
- public function testUpdateLinkShareInvalidDate() {
- $this->expectException(\OCP\AppFramework\OCS\OCSBadRequestException::class);
+ public function testUpdateLinkShareInvalidDate(): void {
+ $this->expectException(OCSBadRequestException::class);
$this->expectExceptionMessage('Invalid date. Format must be YYYY-MM-DD');
$ocs = $this->mockFormatShare();
[$userFolder, $folder] = $this->getNonSharedUserFolder();
- $userFolder->method('getFirstNodeById')
+ $userFolder->method('getById')
->with(42)
- ->willReturn($folder);
+ ->willReturn([$folder]);
$this->rootFolder->method('getUserFolder')
->with($this->currentUser)
->willReturn($userFolder);
@@ -2951,8 +3103,8 @@ class ShareAPIControllerTest extends TestCase {
$folder->method('getId')
->willReturn(42);
- $share = \OC::$server->getShareManager()->newShare();
- $share->setPermissions(\OCP\Constants::PERMISSION_ALL)
+ $share = Server::get(IManager::class)->newShare();
+ $share->setPermissions(Constants::PERMISSION_ALL)
->setSharedBy($this->currentUser)
->setShareType(IShare::TYPE_LINK)
->setNode($folder);
@@ -2963,42 +3115,40 @@ class ShareAPIControllerTest extends TestCase {
$ocs->updateShare(42, null, 'password', null, 'true', '2000-01-a');
}
- public function publicUploadParamsProvider() {
+ public static function publicUploadParamsProvider() {
return [
[null, 'true', null, 'password'],
// legacy had no delete
[
- \OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE,
+ Constants::PERMISSION_READ | Constants::PERMISSION_CREATE | Constants::PERMISSION_UPDATE,
'true', null, 'password'
],
// correct
[
- \OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE,
+ Constants::PERMISSION_READ | Constants::PERMISSION_CREATE | Constants::PERMISSION_UPDATE | Constants::PERMISSION_DELETE,
null, null, 'password'
],
];
}
- /**
- * @dataProvider publicUploadParamsProvider
- */
- public function testUpdateLinkSharePublicUploadNotAllowed($permissions, $publicUpload, $expireDate, $password) {
- $this->expectException(\OCP\AppFramework\OCS\OCSForbiddenException::class);
+ #[\PHPUnit\Framework\Attributes\DataProvider('publicUploadParamsProvider')]
+ public function testUpdateLinkSharePublicUploadNotAllowed($permissions, $publicUpload, $expireDate, $password): void {
+ $this->expectException(OCSForbiddenException::class);
$this->expectExceptionMessage('Public upload disabled by the administrator');
$ocs = $this->mockFormatShare();
[$userFolder, $folder] = $this->getNonSharedUserFolder();
- $userFolder->method('getFirstNodeById')
+ $userFolder->method('getById')
->with(42)
- ->willReturn($folder);
+ ->willReturn([$folder]);
$this->rootFolder->method('getUserFolder')
->with($this->currentUser)
->willReturn($userFolder);
$folder->method('getId')->willReturn(42);
- $share = \OC::$server->getShareManager()->newShare();
- $share->setPermissions(\OCP\Constants::PERMISSION_ALL)
+ $share = Server::get(IManager::class)->newShare();
+ $share->setPermissions(Constants::PERMISSION_ALL)
->setSharedBy($this->currentUser)
->setShareType(IShare::TYPE_LINK)
->setNode($folder);
@@ -3010,8 +3160,8 @@ class ShareAPIControllerTest extends TestCase {
}
- public function testUpdateLinkSharePublicUploadOnFile() {
- $this->expectException(\OCP\AppFramework\OCS\OCSBadRequestException::class);
+ public function testUpdateLinkSharePublicUploadOnFile(): void {
+ $this->expectException(OCSBadRequestException::class);
$this->expectExceptionMessage('Public upload is only possible for publicly shared folders');
$ocs = $this->mockFormatShare();
@@ -3020,21 +3170,30 @@ class ShareAPIControllerTest extends TestCase {
$file->method('getId')
->willReturn(42);
[$userFolder, $folder] = $this->getNonSharedUserFolder();
- $userFolder->method('getFirstNodeById')
+ $userFolder->method('getById')
->with(42)
- ->willReturn($folder);
+ ->willReturn([$folder]);
$this->rootFolder->method('getUserFolder')
->with($this->currentUser)
->willReturn($userFolder);
- $share = \OC::$server->getShareManager()->newShare();
- $share->setPermissions(\OCP\Constants::PERMISSION_ALL)
+ $share = Server::get(IManager::class)->newShare();
+ $share->setPermissions(Constants::PERMISSION_ALL)
->setSharedBy($this->currentUser)
->setShareType(IShare::TYPE_LINK)
->setNode($file);
- $this->shareManager->method('getShareById')->with('ocinternal:42')->willReturn($share);
- $this->shareManager->method('shareApiLinkAllowPublicUpload')->willReturn(true);
+ $this->shareManager
+ ->method('getShareById')
+ ->with('ocinternal:42')
+ ->willReturn($share);
+ $this->shareManager
+ ->method('shareApiLinkAllowPublicUpload')
+ ->willReturn(true);
+ $this->shareManager
+ ->method('updateShare')
+ ->with($share)
+ ->willThrowException(new \InvalidArgumentException('File shares cannot have create or delete permissions'));
$ocs->updateShare(42, null, 'password', null, 'true', '');
}
@@ -3047,14 +3206,14 @@ class ShareAPIControllerTest extends TestCase {
[$userFolder, $node] = $this->getNonSharedUserFolder();
$node->method('getId')->willReturn(42);
- $userFolder->method('getFirstNodeById')
+ $userFolder->method('getById')
->with(42)
- ->willReturn($node);
+ ->willReturn([$node]);
$this->rootFolder->method('getUserFolder')
->with($this->currentUser)
->willReturn($userFolder);
$share = $this->newShare();
- $share->setPermissions(\OCP\Constants::PERMISSION_ALL)
+ $share->setPermissions(Constants::PERMISSION_ALL)
->setSharedBy($this->currentUser)
->setShareType(IShare::TYPE_LINK)
->setPassword('password')
@@ -3063,24 +3222,24 @@ class ShareAPIControllerTest extends TestCase {
->setNote('note')
->setLabel('label')
->setHideDownload(true)
- ->setPermissions(\OCP\Constants::PERMISSION_ALL)
+ ->setPermissions(Constants::PERMISSION_ALL)
->setNode($node);
$node->expects($this->once())
->method('lock')
- ->with(\OCP\Lock\ILockingProvider::LOCK_SHARED);
+ ->with(ILockingProvider::LOCK_SHARED);
$this->shareManager->method('getShareById')->with('ocinternal:42')->willReturn($share);
$this->shareManager->expects($this->once())->method('updateShare')->with(
- $this->callback(function (\OCP\Share\IShare $share) use ($date) {
- return $share->getPermissions() === \OCP\Constants::PERMISSION_ALL &&
- $share->getPassword() === 'newpassword' &&
- $share->getSendPasswordByTalk() === true &&
- $share->getExpirationDate() === $date &&
- $share->getNote() === 'note' &&
- $share->getLabel() === 'label' &&
- $share->getHideDownload() === true;
+ $this->callback(function (IShare $share) use ($date) {
+ return $share->getPermissions() === Constants::PERMISSION_ALL
+ && $share->getPassword() === 'newpassword'
+ && $share->getSendPasswordByTalk() === true
+ && $share->getExpirationDate() === $date
+ && $share->getNote() === 'note'
+ && $share->getLabel() === 'label'
+ && $share->getHideDownload() === true;
})
)->willReturnArgument(0);
@@ -3091,22 +3250,22 @@ class ShareAPIControllerTest extends TestCase {
$this->assertEquals($expected->getData(), $result->getData());
}
- public function testUpdateLinkShareSendPasswordByTalkDoesNotChangeOther() {
+ public function testUpdateLinkShareSendPasswordByTalkDoesNotChangeOther(): void {
$ocs = $this->mockFormatShare();
$date = new \DateTime('2000-01-01');
$date->setTime(0, 0, 0);
[$userFolder, $node] = $this->getNonSharedUserFolder();
- $userFolder->method('getFirstNodeById')
+ $userFolder->method('getById')
->with(42)
- ->willReturn($node);
+ ->willReturn([$node]);
$this->rootFolder->method('getUserFolder')
->with($this->currentUser)
->willReturn($userFolder);
$node->method('getId')->willReturn(42);
$share = $this->newShare();
- $share->setPermissions(\OCP\Constants::PERMISSION_ALL)
+ $share->setPermissions(Constants::PERMISSION_ALL)
->setSharedBy($this->currentUser)
->setShareType(IShare::TYPE_LINK)
->setPassword('password')
@@ -3115,26 +3274,26 @@ class ShareAPIControllerTest extends TestCase {
->setNote('note')
->setLabel('label')
->setHideDownload(true)
- ->setPermissions(\OCP\Constants::PERMISSION_ALL)
+ ->setPermissions(Constants::PERMISSION_ALL)
->setNode($node);
$node->expects($this->once())
->method('lock')
- ->with(\OCP\Lock\ILockingProvider::LOCK_SHARED);
+ ->with(ILockingProvider::LOCK_SHARED);
$this->shareManager->method('getShareById')->with('ocinternal:42')->willReturn($share);
$this->appManager->method('isEnabledForUser')->with('spreed')->willReturn(true);
$this->shareManager->expects($this->once())->method('updateShare')->with(
- $this->callback(function (\OCP\Share\IShare $share) use ($date) {
- return $share->getPermissions() === \OCP\Constants::PERMISSION_ALL &&
- $share->getPassword() === 'password' &&
- $share->getSendPasswordByTalk() === true &&
- $share->getExpirationDate() === $date &&
- $share->getNote() === 'note' &&
- $share->getLabel() === 'label' &&
- $share->getHideDownload() === true;
+ $this->callback(function (IShare $share) use ($date) {
+ return $share->getPermissions() === Constants::PERMISSION_ALL
+ && $share->getPassword() === 'password'
+ && $share->getSendPasswordByTalk() === true
+ && $share->getExpirationDate() === $date
+ && $share->getNote() === 'note'
+ && $share->getLabel() === 'label'
+ && $share->getHideDownload() === true;
})
)->willReturnArgument(0);
@@ -3146,8 +3305,8 @@ class ShareAPIControllerTest extends TestCase {
}
- public function testUpdateLinkShareSendPasswordByTalkWithTalkDisabledDoesNotChangeOther() {
- $this->expectException(\OCP\AppFramework\OCS\OCSForbiddenException::class);
+ public function testUpdateLinkShareSendPasswordByTalkWithTalkDisabledDoesNotChangeOther(): void {
+ $this->expectException(OCSForbiddenException::class);
$this->expectExceptionMessage('"Sending the password by Nextcloud Talk" for sharing a file or folder failed because Nextcloud Talk is not enabled.');
$ocs = $this->mockFormatShare();
@@ -3156,15 +3315,15 @@ class ShareAPIControllerTest extends TestCase {
$date->setTime(0, 0, 0);
[$userFolder, $node] = $this->getNonSharedUserFolder();
- $userFolder->method('getFirstNodeById')
+ $userFolder->method('getById')
->with(42)
- ->willReturn($node);
+ ->willReturn([$node]);
$this->rootFolder->method('getUserFolder')
->with($this->currentUser)
->willReturn($userFolder);
$node->method('getId')->willReturn(42);
$share = $this->newShare();
- $share->setPermissions(\OCP\Constants::PERMISSION_ALL)
+ $share->setPermissions(Constants::PERMISSION_ALL)
->setSharedBy($this->currentUser)
->setShareType(IShare::TYPE_LINK)
->setPassword('password')
@@ -3173,12 +3332,12 @@ class ShareAPIControllerTest extends TestCase {
->setNote('note')
->setLabel('label')
->setHideDownload(true)
- ->setPermissions(\OCP\Constants::PERMISSION_ALL)
+ ->setPermissions(Constants::PERMISSION_ALL)
->setNode($node);
$node->expects($this->once())
->method('lock')
- ->with(\OCP\Lock\ILockingProvider::LOCK_SHARED);
+ ->with(ILockingProvider::LOCK_SHARED);
$this->shareManager->method('getShareById')->with('ocinternal:42')->willReturn($share);
@@ -3189,22 +3348,22 @@ class ShareAPIControllerTest extends TestCase {
$ocs->updateShare(42, null, null, 'true', null, null, null, null, null);
}
- public function testUpdateLinkShareDoNotSendPasswordByTalkDoesNotChangeOther() {
+ public function testUpdateLinkShareDoNotSendPasswordByTalkDoesNotChangeOther(): void {
$ocs = $this->mockFormatShare();
$date = new \DateTime('2000-01-01');
$date->setTime(0, 0, 0);
[$userFolder, $node] = $this->getNonSharedUserFolder();
- $userFolder->method('getFirstNodeById')
+ $userFolder->method('getById')
->with(42)
- ->willReturn($node);
+ ->willReturn([$node]);
$this->rootFolder->method('getUserFolder')
->with($this->currentUser)
->willReturn($userFolder);
$node->method('getId')->willReturn(42);
$share = $this->newShare();
- $share->setPermissions(\OCP\Constants::PERMISSION_ALL)
+ $share->setPermissions(Constants::PERMISSION_ALL)
->setSharedBy($this->currentUser)
->setShareType(IShare::TYPE_LINK)
->setPassword('password')
@@ -3213,26 +3372,26 @@ class ShareAPIControllerTest extends TestCase {
->setNote('note')
->setLabel('label')
->setHideDownload(true)
- ->setPermissions(\OCP\Constants::PERMISSION_ALL)
+ ->setPermissions(Constants::PERMISSION_ALL)
->setNode($node);
$node->expects($this->once())
->method('lock')
- ->with(\OCP\Lock\ILockingProvider::LOCK_SHARED);
+ ->with(ILockingProvider::LOCK_SHARED);
$this->shareManager->method('getShareById')->with('ocinternal:42')->willReturn($share);
$this->appManager->method('isEnabledForUser')->with('spreed')->willReturn(true);
$this->shareManager->expects($this->once())->method('updateShare')->with(
- $this->callback(function (\OCP\Share\IShare $share) use ($date) {
- return $share->getPermissions() === \OCP\Constants::PERMISSION_ALL &&
- $share->getPassword() === 'password' &&
- $share->getSendPasswordByTalk() === false &&
- $share->getExpirationDate() === $date &&
- $share->getNote() === 'note' &&
- $share->getLabel() === 'label' &&
- $share->getHideDownload() === true;
+ $this->callback(function (IShare $share) use ($date) {
+ return $share->getPermissions() === Constants::PERMISSION_ALL
+ && $share->getPassword() === 'password'
+ && $share->getSendPasswordByTalk() === false
+ && $share->getExpirationDate() === $date
+ && $share->getNote() === 'note'
+ && $share->getLabel() === 'label'
+ && $share->getHideDownload() === true;
})
)->willReturnArgument(0);
@@ -3243,7 +3402,7 @@ class ShareAPIControllerTest extends TestCase {
$this->assertEquals($expected->getData(), $result->getData());
}
- public function testUpdateLinkShareDoNotSendPasswordByTalkWithTalkDisabledDoesNotChangeOther() {
+ public function testUpdateLinkShareDoNotSendPasswordByTalkWithTalkDisabledDoesNotChangeOther(): void {
$ocs = $this->mockFormatShare();
$date = new \DateTime('2000-01-01');
@@ -3254,7 +3413,7 @@ class ShareAPIControllerTest extends TestCase {
->willReturn(42);
$share = $this->newShare();
- $share->setPermissions(\OCP\Constants::PERMISSION_ALL)
+ $share->setPermissions(Constants::PERMISSION_ALL)
->setSharedBy($this->currentUser)
->setShareType(IShare::TYPE_LINK)
->setPassword('password')
@@ -3263,26 +3422,26 @@ class ShareAPIControllerTest extends TestCase {
->setNote('note')
->setLabel('label')
->setHideDownload(true)
- ->setPermissions(\OCP\Constants::PERMISSION_ALL)
+ ->setPermissions(Constants::PERMISSION_ALL)
->setNode($node);
$node->expects($this->once())
->method('lock')
- ->with(\OCP\Lock\ILockingProvider::LOCK_SHARED);
+ ->with(ILockingProvider::LOCK_SHARED);
$this->shareManager->method('getShareById')->with('ocinternal:42')->willReturn($share);
$this->appManager->method('isEnabledForUser')->with('spreed')->willReturn(false);
$this->shareManager->expects($this->once())->method('updateShare')->with(
- $this->callback(function (\OCP\Share\IShare $share) use ($date) {
- return $share->getPermissions() === \OCP\Constants::PERMISSION_ALL &&
- $share->getPassword() === 'password' &&
- $share->getSendPasswordByTalk() === false &&
- $share->getExpirationDate() === $date &&
- $share->getNote() === 'note' &&
- $share->getLabel() === 'label' &&
- $share->getHideDownload() === true;
+ $this->callback(function (IShare $share) use ($date) {
+ return $share->getPermissions() === Constants::PERMISSION_ALL
+ && $share->getPassword() === 'password'
+ && $share->getSendPasswordByTalk() === false
+ && $share->getExpirationDate() === $date
+ && $share->getNote() === 'note'
+ && $share->getLabel() === 'label'
+ && $share->getHideDownload() === true;
})
)->willReturnArgument(0);
@@ -3290,9 +3449,9 @@ class ShareAPIControllerTest extends TestCase {
->with($this->currentUser)
->willReturn($userFolder);
- $userFolder->method('getFirstNodeById')
+ $userFolder->method('getById')
->with(42)
- ->willReturn($node);
+ ->willReturn([$node]);
$mountPoint = $this->createMock(IMountPoint::class);
$node->method('getMountPoint')
@@ -3313,7 +3472,7 @@ class ShareAPIControllerTest extends TestCase {
$this->assertEquals($expected->getData(), $result->getData());
}
- public function testUpdateLinkShareExpireDateDoesNotChangeOther() {
+ public function testUpdateLinkShareExpireDateDoesNotChangeOther(): void {
$ocs = $this->mockFormatShare();
[$userFolder, $node] = $this->getNonSharedUserFolder();
@@ -3321,7 +3480,7 @@ class ShareAPIControllerTest extends TestCase {
->willReturn(42);
$share = $this->newShare();
- $share->setPermissions(\OCP\Constants::PERMISSION_ALL)
+ $share->setPermissions(Constants::PERMISSION_ALL)
->setSharedBy($this->currentUser)
->setShareType(IShare::TYPE_LINK)
->setPassword('password')
@@ -3330,27 +3489,27 @@ class ShareAPIControllerTest extends TestCase {
->setNote('note')
->setLabel('label')
->setHideDownload(true)
- ->setPermissions(\OCP\Constants::PERMISSION_ALL)
+ ->setPermissions(Constants::PERMISSION_ALL)
->setNode($node);
$node->expects($this->once())
->method('lock')
- ->with(\OCP\Lock\ILockingProvider::LOCK_SHARED);
+ ->with(ILockingProvider::LOCK_SHARED);
$this->shareManager->method('getShareById')->with('ocinternal:42')->willReturn($share);
$this->shareManager->expects($this->once())->method('updateShare')->with(
- $this->callback(function (\OCP\Share\IShare $share) {
+ $this->callback(function (IShare $share) {
$date = new \DateTime('2010-12-23');
$date->setTime(0, 0, 0);
- return $share->getPermissions() === \OCP\Constants::PERMISSION_ALL &&
- $share->getPassword() === 'password' &&
- $share->getSendPasswordByTalk() === true &&
- $share->getExpirationDate() == $date &&
- $share->getNote() === 'note' &&
- $share->getLabel() === 'label' &&
- $share->getHideDownload() === true;
+ return $share->getPermissions() === Constants::PERMISSION_ALL
+ && $share->getPassword() === 'password'
+ && $share->getSendPasswordByTalk() === true
+ && $share->getExpirationDate() == $date
+ && $share->getNote() === 'note'
+ && $share->getLabel() === 'label'
+ && $share->getHideDownload() === true;
})
)->willReturnArgument(0);
@@ -3358,9 +3517,9 @@ class ShareAPIControllerTest extends TestCase {
->with($this->currentUser)
->willReturn($userFolder);
- $userFolder->method('getFirstNodeById')
+ $userFolder->method('getById')
->with(42)
- ->willReturn($node);
+ ->willReturn([$node]);
$mountPoint = $this->createMock(IMountPoint::class);
$node->method('getMountPoint')
@@ -3375,7 +3534,7 @@ class ShareAPIControllerTest extends TestCase {
$this->assertEquals($expected->getData(), $result->getData());
}
- public function testUpdateLinkSharePublicUploadDoesNotChangeOther() {
+ public function testUpdateLinkSharePublicUploadDoesNotChangeOther(): void {
$ocs = $this->mockFormatShare();
$date = new \DateTime('2000-01-01');
@@ -3384,8 +3543,8 @@ class ShareAPIControllerTest extends TestCase {
$folder->method('getId')
->willReturn(42);
- $share = \OC::$server->getShareManager()->newShare();
- $share->setPermissions(\OCP\Constants::PERMISSION_ALL)
+ $share = Server::get(IManager::class)->newShare();
+ $share->setPermissions(Constants::PERMISSION_ALL)
->setSharedBy($this->currentUser)
->setShareType(IShare::TYPE_LINK)
->setPassword('password')
@@ -3394,21 +3553,21 @@ class ShareAPIControllerTest extends TestCase {
->setNote('note')
->setLabel('label')
->setHideDownload(true)
- ->setPermissions(\OCP\Constants::PERMISSION_ALL)
+ ->setPermissions(Constants::PERMISSION_ALL)
->setNode($folder);
$this->shareManager->method('getShareById')->with('ocinternal:42')->willReturn($share);
$this->shareManager->method('shareApiLinkAllowPublicUpload')->willReturn(true);
$this->shareManager->expects($this->once())->method('updateShare')->with(
- $this->callback(function (\OCP\Share\IShare $share) use ($date) {
- return $share->getPermissions() === (\OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE) &&
- $share->getPassword() === 'password' &&
- $share->getSendPasswordByTalk() === true &&
- $share->getExpirationDate() === $date &&
- $share->getNote() === 'note' &&
- $share->getLabel() === 'label' &&
- $share->getHideDownload() === true;
+ $this->callback(function (IShare $share) use ($date) {
+ return $share->getPermissions() === (Constants::PERMISSION_READ | Constants::PERMISSION_CREATE | Constants::PERMISSION_UPDATE | Constants::PERMISSION_DELETE)
+ && $share->getPassword() === 'password'
+ && $share->getSendPasswordByTalk() === true
+ && $share->getExpirationDate() === $date
+ && $share->getNote() === 'note'
+ && $share->getLabel() === 'label'
+ && $share->getHideDownload() === true;
})
)->willReturnArgument(0);
@@ -3419,9 +3578,9 @@ class ShareAPIControllerTest extends TestCase {
->with($this->currentUser)
->willReturn($userFolder);
- $userFolder->method('getFirstNodeById')
+ $userFolder->method('getById')
->with(42)
- ->willReturn($folder);
+ ->willReturn([$folder]);
$mountPoint = $this->createMock(IMountPoint::class);
$folder->method('getMountPoint')
@@ -3436,7 +3595,7 @@ class ShareAPIControllerTest extends TestCase {
$this->assertEquals($expected->getData(), $result->getData());
}
- public function testUpdateLinkSharePermissions() {
+ public function testUpdateLinkSharePermissions(): void {
$ocs = $this->mockFormatShare();
$date = new \DateTime('2000-01-01');
@@ -3445,8 +3604,8 @@ class ShareAPIControllerTest extends TestCase {
$folder->method('getId')
->willReturn(42);
- $share = \OC::$server->getShareManager()->newShare();
- $share->setPermissions(\OCP\Constants::PERMISSION_ALL)
+ $share = Server::get(IManager::class)->newShare();
+ $share->setPermissions(Constants::PERMISSION_ALL)
->setSharedBy($this->currentUser)
->setShareType(IShare::TYPE_LINK)
->setPassword('password')
@@ -3455,21 +3614,21 @@ class ShareAPIControllerTest extends TestCase {
->setNote('note')
->setLabel('label')
->setHideDownload(true)
- ->setPermissions(\OCP\Constants::PERMISSION_ALL)
+ ->setPermissions(Constants::PERMISSION_ALL)
->setNode($folder);
$this->shareManager->method('getShareById')->with('ocinternal:42')->willReturn($share);
$this->shareManager->method('shareApiLinkAllowPublicUpload')->willReturn(true);
$this->shareManager->expects($this->once())->method('updateShare')->with(
- $this->callback(function (\OCP\Share\IShare $share) use ($date): bool {
- return $share->getPermissions() === (\OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE) &&
- $share->getPassword() === 'password' &&
- $share->getSendPasswordByTalk() === true &&
- $share->getExpirationDate() === $date &&
- $share->getNote() === 'note' &&
- $share->getLabel() === 'label' &&
- $share->getHideDownload() === true;
+ $this->callback(function (IShare $share) use ($date): bool {
+ return $share->getPermissions() === (Constants::PERMISSION_READ | Constants::PERMISSION_CREATE | Constants::PERMISSION_UPDATE | Constants::PERMISSION_DELETE)
+ && $share->getPassword() === 'password'
+ && $share->getSendPasswordByTalk() === true
+ && $share->getExpirationDate() === $date
+ && $share->getNote() === 'note'
+ && $share->getLabel() === 'label'
+ && $share->getHideDownload() === true;
})
)->willReturnArgument(0);
@@ -3479,9 +3638,9 @@ class ShareAPIControllerTest extends TestCase {
->with($this->currentUser)
->willReturn($userFolder);
- $userFolder->method('getFirstNodeById')
+ $userFolder->method('getById')
->with(42)
- ->willReturn($folder);
+ ->willReturn([$folder]);
$mountPoint = $this->createMock(IMountPoint::class);
$folder->method('getMountPoint')
@@ -3496,7 +3655,7 @@ class ShareAPIControllerTest extends TestCase {
$this->assertEquals($expected->getData(), $result->getData());
}
- public function testUpdateLinkSharePermissionsShare() {
+ public function testUpdateLinkSharePermissionsShare(): void {
$ocs = $this->mockFormatShare();
$date = new \DateTime('2000-01-01');
@@ -3505,8 +3664,8 @@ class ShareAPIControllerTest extends TestCase {
$folder->method('getId')
->willReturn(42);
- $share = \OC::$server->getShareManager()->newShare();
- $share->setPermissions(\OCP\Constants::PERMISSION_ALL)
+ $share = Server::get(IManager::class)->newShare();
+ $share->setPermissions(Constants::PERMISSION_ALL)
->setSharedBy($this->currentUser)
->setShareType(IShare::TYPE_LINK)
->setPassword('password')
@@ -3515,31 +3674,33 @@ class ShareAPIControllerTest extends TestCase {
->setNote('note')
->setLabel('label')
->setHideDownload(true)
- ->setPermissions(\OCP\Constants::PERMISSION_READ)
+ ->setPermissions(Constants::PERMISSION_READ)
->setNode($folder);
$this->shareManager->method('getShareById')->with('ocinternal:42')->willReturn($share);
$this->shareManager->method('shareApiLinkAllowPublicUpload')->willReturn(true);
- $this->shareManager->expects($this->once())->method('updateShare')->with(
- $this->callback(function (\OCP\Share\IShare $share) use ($date) {
- return $share->getPermissions() === (\OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE) &&
- $share->getPassword() === 'password' &&
- $share->getSendPasswordByTalk() === true &&
- $share->getExpirationDate() === $date &&
- $share->getNote() === 'note' &&
- $share->getLabel() === 'label' &&
- $share->getHideDownload() === true;
- })
- )->willReturnArgument(0);
+ $this->shareManager->expects($this->once())
+ ->method('updateShare')
+ ->with(
+ $this->callback(function (IShare $share) use ($date) {
+ return $share->getPermissions() === Constants::PERMISSION_ALL
+ && $share->getPassword() === 'password'
+ && $share->getSendPasswordByTalk() === true
+ && $share->getExpirationDate() === $date
+ && $share->getNote() === 'note'
+ && $share->getLabel() === 'label'
+ && $share->getHideDownload() === true;
+ })
+ )->willReturnArgument(0);
$this->rootFolder->method('getUserFolder')
->with($this->currentUser)
->willReturn($userFolder);
- $userFolder->method('getFirstNodeById')
+ $userFolder->method('getById')
->with(42)
- ->willReturn($folder);
+ ->willReturn([$folder]);
$mountPoint = $this->createMock(IMountPoint::class);
$folder->method('getMountPoint')
@@ -3550,21 +3711,21 @@ class ShareAPIControllerTest extends TestCase {
$this->shareManager->method('getSharedWith')->willReturn([]);
$expected = new DataResponse([]);
- $result = $ocs->updateShare(42, 31, null, null, null, null, null, null, null);
+ $result = $ocs->updateShare(42, Constants::PERMISSION_ALL, null, null, null, null, null, null, null);
$this->assertInstanceOf(get_class($expected), $result);
$this->assertEquals($expected->getData(), $result->getData());
}
- public function testUpdateOtherPermissions() {
+ public function testUpdateOtherPermissions(): void {
$ocs = $this->mockFormatShare();
[$userFolder, $file] = $this->getNonSharedUserFolder();
$file->method('getId')
->willReturn(42);
- $share = \OC::$server->getShareManager()->newShare();
- $share->setPermissions(\OCP\Constants::PERMISSION_ALL)
+ $share = Server::get(IManager::class)->newShare();
+ $share->setPermissions(Constants::PERMISSION_ALL)
->setSharedBy($this->currentUser)
->setShareType(IShare::TYPE_USER)
->setNode($file);
@@ -3573,8 +3734,8 @@ class ShareAPIControllerTest extends TestCase {
$this->shareManager->method('shareApiLinkAllowPublicUpload')->willReturn(true);
$this->shareManager->expects($this->once())->method('updateShare')->with(
- $this->callback(function (\OCP\Share\IShare $share) {
- return $share->getPermissions() === \OCP\Constants::PERMISSION_ALL;
+ $this->callback(function (IShare $share) {
+ return $share->getPermissions() === Constants::PERMISSION_ALL;
})
)->willReturnArgument(0);
@@ -3585,9 +3746,9 @@ class ShareAPIControllerTest extends TestCase {
->with($this->currentUser)
->willReturn($userFolder);
- $userFolder->method('getFirstNodeById')
+ $userFolder->method('getById')
->with(42)
- ->willReturn($file);
+ ->willReturn([$file]);
$mountPoint = $this->createMock(IMountPoint::class);
$file->method('getMountPoint')
@@ -3602,33 +3763,33 @@ class ShareAPIControllerTest extends TestCase {
$this->assertEquals($expected->getData(), $result->getData());
}
- public function testUpdateShareCannotIncreasePermissions() {
+ public function testUpdateShareCannotIncreasePermissions(): void {
$ocs = $this->mockFormatShare();
[$userFolder, $folder] = $this->getNonSharedUserFolder();
$folder->method('getId')
->willReturn(42);
- $share = \OC::$server->getShareManager()->newShare();
+ $share = Server::get(IManager::class)->newShare();
$share
->setId(42)
->setSharedBy($this->currentUser)
->setShareOwner('anotheruser')
->setShareType(IShare::TYPE_GROUP)
->setSharedWith('group1')
- ->setPermissions(\OCP\Constants::PERMISSION_READ)
+ ->setPermissions(Constants::PERMISSION_READ)
->setNode($folder);
// note: updateShare will modify the received instance but getSharedWith will reread from the database,
// so their values will be different
- $incomingShare = \OC::$server->getShareManager()->newShare();
+ $incomingShare = Server::get(IManager::class)->newShare();
$incomingShare
->setId(42)
->setSharedBy($this->currentUser)
->setShareOwner('anotheruser')
->setShareType(IShare::TYPE_GROUP)
->setSharedWith('group1')
- ->setPermissions(\OCP\Constants::PERMISSION_READ)
+ ->setPermissions(Constants::PERMISSION_READ)
->setNode($folder);
$this->request
@@ -3651,6 +3812,9 @@ class ShareAPIControllerTest extends TestCase {
->with($this->currentUser)
->willReturn($userFolder);
+ $userFolder->method('getById')
+ ->with(42)
+ ->willReturn([$folder]);
$userFolder->method('getFirstNodeById')
->with(42)
->willReturn($folder);
@@ -3674,33 +3838,33 @@ class ShareAPIControllerTest extends TestCase {
}
}
- public function testUpdateShareCanIncreasePermissionsIfOwner() {
+ public function testUpdateShareCanIncreasePermissionsIfOwner(): void {
$ocs = $this->mockFormatShare();
[$userFolder, $folder] = $this->getNonSharedUserFolder();
$folder->method('getId')
->willReturn(42);
- $share = \OC::$server->getShareManager()->newShare();
+ $share = Server::get(IManager::class)->newShare();
$share
->setId(42)
->setSharedBy($this->currentUser)
->setShareOwner($this->currentUser)
->setShareType(IShare::TYPE_GROUP)
->setSharedWith('group1')
- ->setPermissions(\OCP\Constants::PERMISSION_READ)
+ ->setPermissions(Constants::PERMISSION_READ)
->setNode($folder);
// note: updateShare will modify the received instance but getSharedWith will reread from the database,
// so their values will be different
- $incomingShare = \OC::$server->getShareManager()->newShare();
+ $incomingShare = Server::get(IManager::class)->newShare();
$incomingShare
->setId(42)
->setSharedBy($this->currentUser)
->setShareOwner($this->currentUser)
->setShareType(IShare::TYPE_GROUP)
->setSharedWith('group1')
- ->setPermissions(\OCP\Constants::PERMISSION_READ)
+ ->setPermissions(Constants::PERMISSION_READ)
->setNode($folder);
$this->shareManager->method('getShareById')->with('ocinternal:42')->willReturn($share);
@@ -3721,9 +3885,9 @@ class ShareAPIControllerTest extends TestCase {
->with($this->currentUser)
->willReturn($userFolder);
- $userFolder->method('getFirstNodeById')
+ $userFolder->method('getById')
->with(42)
- ->willReturn($folder);
+ ->willReturn([$folder]);
$mountPoint = $this->createMock(IMountPoint::class);
$folder->method('getMountPoint')
@@ -3735,6 +3899,64 @@ class ShareAPIControllerTest extends TestCase {
$this->assertInstanceOf(DataResponse::class, $result);
}
+ public function testUpdateShareOwnerless(): void {
+ $ocs = $this->mockFormatShare();
+
+ $mount = $this->createMock(IShareOwnerlessMount::class);
+
+ $file = $this->createMock(File::class);
+ $file
+ ->expects($this->exactly(2))
+ ->method('getPermissions')
+ ->willReturn(Constants::PERMISSION_SHARE);
+ $file
+ ->expects($this->once())
+ ->method('getMountPoint')
+ ->willReturn($mount);
+
+ $userFolder = $this->createMock(Folder::class);
+ $userFolder->method('getById')
+ ->with(2)
+ ->willReturn([$file]);
+ $userFolder->method('getFirstNodeById')
+ ->with(2)
+ ->willReturn($file);
+
+ $this->rootFolder
+ ->method('getUserFolder')
+ ->with($this->currentUser)
+ ->willReturn($userFolder);
+
+ $share = $this->createMock(IShare::class);
+ $share
+ ->expects($this->once())
+ ->method('getNode')
+ ->willReturn($file);
+ $share
+ ->expects($this->exactly(2))
+ ->method('getNodeId')
+ ->willReturn(2);
+ $share
+ ->expects($this->exactly(2))
+ ->method('getPermissions')
+ ->willReturn(Constants::PERMISSION_SHARE);
+
+ $this->shareManager
+ ->expects($this->once())
+ ->method('getShareById')
+ ->with('ocinternal:1', $this->currentUser)
+ ->willReturn($share);
+
+ $this->shareManager
+ ->expects($this->once())
+ ->method('updateShare')
+ ->with($share)
+ ->willReturn($share);
+
+ $result = $ocs->updateShare(1, Constants::PERMISSION_ALL);
+ $this->assertInstanceOf(DataResponse::class, $result);
+ }
+
public function dataFormatShare() {
$file = $this->getMockBuilder(File::class)->getMock();
$folder = $this->getMockBuilder(Folder::class)->getMock();
@@ -3745,6 +3967,12 @@ class ShareAPIControllerTest extends TestCase {
$folder->method('getMimeType')->willReturn('myFolderMimeType');
$fileWithPreview->method('getMimeType')->willReturn('mimeWithPreview');
+ $mountPoint = $this->createMock(IMountPoint::class);
+ $mountPoint->method('getMountType')->willReturn('');
+ $file->method('getMountPoint')->willReturn($mountPoint);
+ $folder->method('getMountPoint')->willReturn($mountPoint);
+ $fileWithPreview->method('getMountPoint')->willReturn($mountPoint);
+
$file->method('getPath')->willReturn('file');
$folder->method('getPath')->willReturn('folder');
$fileWithPreview->method('getPath')->willReturn('fileWithPreview');
@@ -3767,7 +3995,7 @@ class ShareAPIControllerTest extends TestCase {
$cache = $this->getMockBuilder('OCP\Files\Cache\ICache')->getMock();
$cache->method('getNumericStorageId')->willReturn(100);
- $storage = $this->createMock(Storage::class);
+ $storage = $this->createMock(IStorage::class);
$storage->method('getId')->willReturn('storageId');
$storage->method('getCache')->willReturn($cache);
@@ -3775,6 +4003,12 @@ class ShareAPIControllerTest extends TestCase {
$folder->method('getStorage')->willReturn($storage);
$fileWithPreview->method('getStorage')->willReturn($storage);
+
+ $mountPoint = $this->getMockBuilder(IMountPoint::class)->getMock();
+ $mountPoint->method('getMountType')->willReturn('');
+ $file->method('getMountPoint')->willReturn($mountPoint);
+ $folder->method('getMountPoint')->willReturn($mountPoint);
+
$owner = $this->getMockBuilder(IUser::class)->getMock();
$owner->method('getDisplayName')->willReturn('ownerDN');
$initiator = $this->getMockBuilder(IUser::class)->getMock();
@@ -3786,12 +4020,12 @@ class ShareAPIControllerTest extends TestCase {
$result = [];
- $share = \OC::$server->getShareManager()->newShare();
+ $share = Server::get(IManager::class)->newShare();
$share->setShareType(IShare::TYPE_USER)
->setSharedWith('recipient')
->setSharedBy('initiator')
->setShareOwner('owner')
- ->setPermissions(\OCP\Constants::PERMISSION_READ)
+ ->setPermissions(Constants::PERMISSION_READ)
->setAttributes($shareAttributes)
->setNode($file)
->setShareTime(new \DateTime('2000-01-01T00:01:02'))
@@ -3835,7 +4069,10 @@ class ShareAPIControllerTest extends TestCase {
'can_delete' => false,
'item_size' => 123456,
'item_mtime' => 1234567890,
- 'attributes' => '[{"scope":"permissions","key":"download","enabled":true}]',
+ 'is-mount-root' => false,
+ 'mount-type' => '',
+ 'attributes' => '[{"scope":"permissions","key":"download","value":true}]',
+ 'item_permissions' => 1,
], $share, [], false
];
// User backend up
@@ -3874,7 +4111,10 @@ class ShareAPIControllerTest extends TestCase {
'can_delete' => false,
'item_size' => 123456,
'item_mtime' => 1234567890,
- 'attributes' => '[{"scope":"permissions","key":"download","enabled":true}]',
+ 'is-mount-root' => false,
+ 'mount-type' => '',
+ 'attributes' => '[{"scope":"permissions","key":"download","value":true}]',
+ 'item_permissions' => 1,
], $share, [
['owner', $owner],
['initiator', $initiator],
@@ -3882,12 +4122,12 @@ class ShareAPIControllerTest extends TestCase {
], false
];
- $share = \OC::$server->getShareManager()->newShare();
+ $share = Server::get(IManager::class)->newShare();
$share->setShareType(IShare::TYPE_USER)
->setSharedWith('recipient')
->setSharedBy('initiator')
->setShareOwner('owner')
- ->setPermissions(\OCP\Constants::PERMISSION_READ)
+ ->setPermissions(Constants::PERMISSION_READ)
->setNode($file)
->setShareTime(new \DateTime('2000-01-01T00:01:02'))
->setTarget('myTarget')
@@ -3929,16 +4169,19 @@ class ShareAPIControllerTest extends TestCase {
'can_delete' => false,
'item_size' => 123456,
'item_mtime' => 1234567890,
+ 'is-mount-root' => false,
+ 'mount-type' => '',
'attributes' => null,
+ 'item_permissions' => 1,
], $share, [], false
];
- $share = \OC::$server->getShareManager()->newShare();
+ $share = Server::get(IManager::class)->newShare();
$share->setShareType(IShare::TYPE_USER)
->setSharedWith('recipient')
->setSharedBy('initiator')
->setShareOwner('currentUser')
- ->setPermissions(\OCP\Constants::PERMISSION_READ)
+ ->setPermissions(Constants::PERMISSION_READ)
->setNode($file)
->setShareTime(new \DateTime('2000-01-01T00:01:02'))
->setTarget('myTarget')
@@ -3980,18 +4223,21 @@ class ShareAPIControllerTest extends TestCase {
'can_delete' => true,
'item_size' => 123456,
'item_mtime' => 1234567890,
+ 'is-mount-root' => false,
+ 'mount-type' => '',
'attributes' => null,
+ 'item_permissions' => 11,
], $share, [], false
];
// with existing group
- $share = \OC::$server->getShareManager()->newShare();
+ $share = Server::get(IManager::class)->newShare();
$share->setShareType(IShare::TYPE_GROUP)
->setSharedWith('recipientGroup')
->setSharedBy('initiator')
->setShareOwner('owner')
- ->setPermissions(\OCP\Constants::PERMISSION_READ)
+ ->setPermissions(Constants::PERMISSION_READ)
->setNode($file)
->setShareTime(new \DateTime('2000-01-01T00:01:02'))
->setTarget('myTarget')
@@ -4032,17 +4278,20 @@ class ShareAPIControllerTest extends TestCase {
'can_delete' => false,
'item_size' => 123456,
'item_mtime' => 1234567890,
+ 'is-mount-root' => false,
+ 'mount-type' => '',
'attributes' => null,
+ 'item_permissions' => 1,
], $share, [], false
];
// with unknown group / no group backend
- $share = \OC::$server->getShareManager()->newShare();
+ $share = Server::get(IManager::class)->newShare();
$share->setShareType(IShare::TYPE_GROUP)
->setSharedWith('recipientGroup2')
->setSharedBy('initiator')
->setShareOwner('owner')
- ->setPermissions(\OCP\Constants::PERMISSION_READ)
+ ->setPermissions(Constants::PERMISSION_READ)
->setNode($file)
->setShareTime(new \DateTime('2000-01-01T00:01:02'))
->setTarget('myTarget')
@@ -4081,15 +4330,18 @@ class ShareAPIControllerTest extends TestCase {
'can_delete' => false,
'item_size' => 123456,
'item_mtime' => 1234567890,
+ 'is-mount-root' => false,
+ 'mount-type' => '',
'attributes' => null,
+ 'item_permissions' => 1,
], $share, [], false
];
- $share = \OC::$server->getShareManager()->newShare();
+ $share = Server::get(IManager::class)->newShare();
$share->setShareType(IShare::TYPE_LINK)
->setSharedBy('initiator')
->setShareOwner('owner')
- ->setPermissions(\OCP\Constants::PERMISSION_READ)
+ ->setPermissions(Constants::PERMISSION_READ)
->setNode($file)
->setShareTime(new \DateTime('2000-01-01T00:01:02'))
->setTarget('myTarget')
@@ -4137,15 +4389,18 @@ class ShareAPIControllerTest extends TestCase {
'can_delete' => false,
'item_size' => 123456,
'item_mtime' => 1234567890,
+ 'is-mount-root' => false,
+ 'mount-type' => '',
'attributes' => null,
+ 'item_permissions' => 1,
], $share, [], false
];
- $share = \OC::$server->getShareManager()->newShare();
+ $share = Server::get(IManager::class)->newShare();
$share->setShareType(IShare::TYPE_LINK)
->setSharedBy('initiator')
->setShareOwner('owner')
- ->setPermissions(\OCP\Constants::PERMISSION_READ)
+ ->setPermissions(Constants::PERMISSION_READ)
->setNode($file)
->setShareTime(new \DateTime('2000-01-01T00:01:02'))
->setTarget('myTarget')
@@ -4193,16 +4448,19 @@ class ShareAPIControllerTest extends TestCase {
'can_delete' => false,
'item_size' => 123456,
'item_mtime' => 1234567890,
+ 'is-mount-root' => false,
+ 'mount-type' => '',
'attributes' => null,
+ 'item_permissions' => 1,
], $share, [], false
];
- $share = \OC::$server->getShareManager()->newShare();
+ $share = Server::get(IManager::class)->newShare();
$share->setShareType(IShare::TYPE_REMOTE)
->setSharedBy('initiator')
->setSharedWith('user@server.com')
->setShareOwner('owner')
- ->setPermissions(\OCP\Constants::PERMISSION_READ)
+ ->setPermissions(Constants::PERMISSION_READ)
->setNode($folder)
->setShareTime(new \DateTime('2000-01-01T00:01:02'))
->setExpirationDate(new \DateTime('2001-02-03T04:05:06'))
@@ -4243,16 +4501,20 @@ class ShareAPIControllerTest extends TestCase {
'can_delete' => false,
'item_size' => 123456,
'item_mtime' => 1234567890,
+ 'is-mount-root' => false,
+ 'mount-type' => '',
'attributes' => null,
+ 'item_permissions' => 1,
+ 'is_trusted_server' => false,
], $share, [], false
];
- $share = \OC::$server->getShareManager()->newShare();
+ $share = Server::get(IManager::class)->newShare();
$share->setShareType(IShare::TYPE_REMOTE_GROUP)
->setSharedBy('initiator')
->setSharedWith('user@server.com')
->setShareOwner('owner')
- ->setPermissions(\OCP\Constants::PERMISSION_READ)
+ ->setPermissions(Constants::PERMISSION_READ)
->setNode($folder)
->setShareTime(new \DateTime('2000-01-01T00:01:02'))
->setExpirationDate(new \DateTime('2001-02-03T04:05:06'))
@@ -4293,19 +4555,23 @@ class ShareAPIControllerTest extends TestCase {
'can_delete' => false,
'item_size' => 123456,
'item_mtime' => 1234567890,
+ 'is-mount-root' => false,
+ 'mount-type' => '',
'attributes' => null,
+ 'item_permissions' => 1,
+ 'is_trusted_server' => false,
], $share, [], false
];
// Circle with id, display name and avatar set by the Circles app
- $share = \OC::$server->getShareManager()->newShare();
+ $share = Server::get(IManager::class)->newShare();
$share->setShareType(IShare::TYPE_CIRCLE)
->setSharedBy('initiator')
->setSharedWith('Circle (Public circle, circleOwner) [4815162342]')
->setSharedWithDisplayName('The display name')
->setSharedWithAvatar('path/to/the/avatar')
->setShareOwner('owner')
- ->setPermissions(\OCP\Constants::PERMISSION_READ)
+ ->setPermissions(Constants::PERMISSION_READ)
->setNode($folder)
->setShareTime(new \DateTime('2000-01-01T00:01:02'))
->setTarget('myTarget')
@@ -4346,17 +4612,20 @@ class ShareAPIControllerTest extends TestCase {
'can_delete' => false,
'item_size' => 123456,
'item_mtime' => 1234567890,
+ 'is-mount-root' => false,
+ 'mount-type' => '',
'attributes' => null,
+ 'item_permissions' => 1,
], $share, [], false
];
// Circle with id set by the Circles app
- $share = \OC::$server->getShareManager()->newShare();
+ $share = Server::get(IManager::class)->newShare();
$share->setShareType(IShare::TYPE_CIRCLE)
->setSharedBy('initiator')
->setSharedWith('Circle (Public circle, circleOwner) [4815162342]')
->setShareOwner('owner')
- ->setPermissions(\OCP\Constants::PERMISSION_READ)
+ ->setPermissions(Constants::PERMISSION_READ)
->setNode($folder)
->setShareTime(new \DateTime('2000-01-01T00:01:02'))
->setTarget('myTarget')
@@ -4396,17 +4665,20 @@ class ShareAPIControllerTest extends TestCase {
'can_delete' => false,
'item_size' => 123456,
'item_mtime' => 1234567890,
+ 'is-mount-root' => false,
+ 'mount-type' => '',
'attributes' => null,
+ 'item_permissions' => 1,
], $share, [], false
];
// Circle with id not set by the Circles app
- $share = \OC::$server->getShareManager()->newShare();
+ $share = Server::get(IManager::class)->newShare();
$share->setShareType(IShare::TYPE_CIRCLE)
->setSharedBy('initiator')
->setSharedWith('Circle (Public circle, circleOwner)')
->setShareOwner('owner')
- ->setPermissions(\OCP\Constants::PERMISSION_READ)
+ ->setPermissions(Constants::PERMISSION_READ)
->setNode($folder)
->setShareTime(new \DateTime('2000-01-01T00:01:02'))
->setTarget('myTarget')
@@ -4446,16 +4718,19 @@ class ShareAPIControllerTest extends TestCase {
'can_delete' => false,
'item_size' => 123456,
'item_mtime' => 1234567890,
+ 'is-mount-root' => false,
+ 'mount-type' => '',
'attributes' => null,
+ 'item_permissions' => 1,
], $share, [], false
];
- $share = \OC::$server->getShareManager()->newShare();
+ $share = Server::get(IManager::class)->newShare();
$share->setShareType(IShare::TYPE_USER)
->setSharedBy('initiator')
->setSharedWith('recipient')
->setShareOwner('owner')
- ->setPermissions(\OCP\Constants::PERMISSION_READ)
+ ->setPermissions(Constants::PERMISSION_READ)
->setShareTime(new \DateTime('2000-01-01T00:01:02'))
->setTarget('myTarget')
->setNote('personal note')
@@ -4465,12 +4740,12 @@ class ShareAPIControllerTest extends TestCase {
[], $share, [], true
];
- $share = \OC::$server->getShareManager()->newShare();
+ $share = Server::get(IManager::class)->newShare();
$share->setShareType(IShare::TYPE_EMAIL)
->setSharedBy('initiator')
->setSharedWith('user@server.com')
->setShareOwner('owner')
- ->setPermissions(\OCP\Constants::PERMISSION_READ)
+ ->setPermissions(Constants::PERMISSION_READ)
->setNode($folder)
->setShareTime(new \DateTime('2000-01-01T00:01:02'))
->setTarget('myTarget')
@@ -4513,16 +4788,19 @@ class ShareAPIControllerTest extends TestCase {
'password_expiration_time' => null,
'item_size' => 123456,
'item_mtime' => 1234567890,
+ 'is-mount-root' => false,
+ 'mount-type' => '',
'attributes' => null,
+ 'item_permissions' => 1,
], $share, [], false
];
- $share = \OC::$server->getShareManager()->newShare();
+ $share = Server::get(IManager::class)->newShare();
$share->setShareType(IShare::TYPE_EMAIL)
->setSharedBy('initiator')
->setSharedWith('user@server.com')
->setShareOwner('owner')
- ->setPermissions(\OCP\Constants::PERMISSION_READ)
+ ->setPermissions(Constants::PERMISSION_READ)
->setNode($folder)
->setShareTime(new \DateTime('2000-01-01T00:01:02'))
->setTarget('myTarget')
@@ -4566,17 +4844,20 @@ class ShareAPIControllerTest extends TestCase {
'password_expiration_time' => null,
'item_size' => 123456,
'item_mtime' => 1234567890,
+ 'is-mount-root' => false,
+ 'mount-type' => '',
'attributes' => null,
+ 'item_permissions' => 1,
], $share, [], false
];
// Preview is available
- $share = \OC::$server->getShareManager()->newShare();
+ $share = Server::get(IManager::class)->newShare();
$share->setShareType(IShare::TYPE_USER)
->setSharedWith('recipient')
->setSharedBy('initiator')
->setShareOwner('currentUser')
- ->setPermissions(\OCP\Constants::PERMISSION_READ)
+ ->setPermissions(Constants::PERMISSION_READ)
->setNode($fileWithPreview)
->setShareTime(new \DateTime('2000-01-01T00:01:02'))
->setTarget('myTarget')
@@ -4617,7 +4898,10 @@ class ShareAPIControllerTest extends TestCase {
'can_delete' => true,
'item_size' => 123456,
'item_mtime' => 1234567890,
+ 'is-mount-root' => false,
+ 'mount-type' => '',
'attributes' => null,
+ 'item_permissions' => 11,
], $share, [], false
];
@@ -4625,14 +4909,14 @@ class ShareAPIControllerTest extends TestCase {
}
/**
- * @dataProvider dataFormatShare
*
* @param array $expects
- * @param \OCP\Share\IShare $share
+ * @param IShare $share
* @param array $users
* @param $exception
*/
- public function testFormatShare(array $expects, \OCP\Share\IShare $share, array $users, $exception) {
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataFormatShare')]
+ public function testFormatShare(array $expects, IShare $share, array $users, $exception): void {
$this->userManager->method('get')->willReturnMap($users);
$recipientGroup = $this->createMock(IGroup::class);
@@ -4720,9 +5004,13 @@ class ShareAPIControllerTest extends TestCase {
$file->method('getSize')->willReturn(123456);
$file->method('getMTime')->willReturn(1234567890);
+ $mountPoint = $this->getMockBuilder(IMountPoint::class)->getMock();
+ $mountPoint->method('getMountType')->willReturn('');
+ $file->method('getMountPoint')->willReturn($mountPoint);
+
$cache = $this->getMockBuilder('OCP\Files\Cache\ICache')->getMock();
$cache->method('getNumericStorageId')->willReturn(100);
- $storage = $this->createMock(Storage::class);
+ $storage = $this->createMock(IStorage::class);
$storage->method('getId')->willReturn('storageId');
$storage->method('getCache')->willReturn($cache);
@@ -4730,12 +5018,12 @@ class ShareAPIControllerTest extends TestCase {
$result = [];
- $share = \OC::$server->getShareManager()->newShare();
+ $share = Server::get(IManager::class)->newShare();
$share->setShareType(IShare::TYPE_ROOM)
->setSharedWith('recipientRoom')
->setSharedBy('initiator')
->setShareOwner('owner')
- ->setPermissions(\OCP\Constants::PERMISSION_READ)
+ ->setPermissions(Constants::PERMISSION_READ)
->setNode($file)
->setShareTime(new \DateTime('2000-01-01T00:01:02'))
->setTarget('myTarget')
@@ -4775,16 +5063,19 @@ class ShareAPIControllerTest extends TestCase {
'can_delete' => false,
'item_size' => 123456,
'item_mtime' => 1234567890,
+ 'is-mount-root' => false,
+ 'mount-type' => '',
'attributes' => null,
+ 'item_permissions' => 1,
], $share, false, []
];
- $share = \OC::$server->getShareManager()->newShare();
+ $share = Server::get(IManager::class)->newShare();
$share->setShareType(IShare::TYPE_ROOM)
->setSharedWith('recipientRoom')
->setSharedBy('initiator')
->setShareOwner('owner')
- ->setPermissions(\OCP\Constants::PERMISSION_READ)
+ ->setPermissions(Constants::PERMISSION_READ)
->setNode($file)
->setShareTime(new \DateTime('2000-01-01T00:01:02'))
->setTarget('myTarget')
@@ -4824,7 +5115,10 @@ class ShareAPIControllerTest extends TestCase {
'can_delete' => false,
'item_size' => 123456,
'item_mtime' => 1234567890,
+ 'is-mount-root' => false,
+ 'mount-type' => '',
'attributes' => null,
+ 'item_permissions' => 9,
], $share, true, [
'share_with_displayname' => 'recipientRoomName'
]
@@ -4834,14 +5128,14 @@ class ShareAPIControllerTest extends TestCase {
}
/**
- * @dataProvider dataFormatRoomShare
*
* @param array $expects
- * @param \OCP\Share\IShare $share
+ * @param IShare $share
* @param bool $helperAvailable
* @param array $formatShareByHelper
*/
- public function testFormatRoomShare(array $expects, \OCP\Share\IShare $share, bool $helperAvailable, array $formatShareByHelper) {
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataFormatRoomShare')]
+ public function testFormatRoomShare(array $expects, IShare $share, bool $helperAvailable, array $formatShareByHelper): void {
$this->rootFolder->method('getUserFolder')
->with($this->currentUser)
->willReturnSelf();
@@ -4863,12 +5157,18 @@ class ShareAPIControllerTest extends TestCase {
->with('spreed')
->willReturn(true);
- $helper = $this->getMockBuilder('\OCA\Talk\Share\Helper\ShareAPIController')
- ->setMethods(['formatShare'])
+ // This is not possible anymore with PHPUnit 10+
+ // as `setMethods` was removed and now real reflection is used, thus the class needs to exist.
+ // $helper = $this->getMockBuilder('\OCA\Talk\Share\Helper\ShareAPIController')
+ $helper = $this->getMockBuilder(\stdClass::class)
+ ->addMethods(['formatShare', 'canAccessShare'])
->getMock();
$helper->method('formatShare')
->with($share)
->willReturn($formatShareByHelper);
+ $helper->method('canAccessShare')
+ ->with($share)
+ ->willReturn(true);
$this->serverContainer->method('get')
->with('\OCA\Talk\Share\Helper\ShareAPIController')
@@ -4879,10 +5179,13 @@ class ShareAPIControllerTest extends TestCase {
$this->assertEquals($expects, $result);
}
+ /**
+ * @return list{Folder, Folder}
+ */
private function getNonSharedUserFolder(): array {
$node = $this->getMockBuilder(Folder::class)->getMock();
$userFolder = $this->getMockBuilder(Folder::class)->getMock();
- $storage = $this->createMock(Storage::class);
+ $storage = $this->createMock(IStorage::class);
$storage->method('instanceOfStorage')
->willReturnMap([
['OCA\Files_Sharing\External\Storage', false],
@@ -4891,13 +5194,19 @@ class ShareAPIControllerTest extends TestCase {
$userFolder->method('getStorage')->willReturn($storage);
$node->method('getStorage')->willReturn($storage);
$node->method('getId')->willReturn(42);
+ $user = $this->createMock(IUser::class);
+ $user->method('getUID')->willReturn($this->currentUser);
+ $node->method('getOwner')->willReturn($user);
return [$userFolder, $node];
}
+ /**
+ * @return list{Folder, File}
+ */
private function getNonSharedUserFile(): array {
$node = $this->getMockBuilder(File::class)->getMock();
$userFolder = $this->getMockBuilder(Folder::class)->getMock();
- $storage = $this->createMock(Storage::class);
+ $storage = $this->createMock(IStorage::class);
$storage->method('instanceOfStorage')
->willReturnMap([
['OCA\Files_Sharing\External\Storage', false],
@@ -4908,4 +5217,164 @@ class ShareAPIControllerTest extends TestCase {
$node->method('getId')->willReturn(42);
return [$userFolder, $node];
}
+
+ public function testPopulateTags(): void {
+ $tagger = $this->createMock(ITags::class);
+ $this->tagManager->method('load')
+ ->with('files')
+ ->willReturn($tagger);
+ $data = [
+ ['file_source' => 10],
+ ['file_source' => 22, 'foo' => 'bar'],
+ ['file_source' => 42, 'x' => 'y'],
+ ];
+ $tags = [
+ 10 => ['tag3'],
+ 42 => ['tag1', 'tag2'],
+ ];
+ $tagger->method('getTagsForObjects')
+ ->with([10, 22, 42])
+ ->willReturn($tags);
+
+ $result = self::invokePrivate($this->ocs, 'populateTags', [$data]);
+ $this->assertSame([
+ ['file_source' => 10, 'tags' => ['tag3']],
+ ['file_source' => 22, 'foo' => 'bar', 'tags' => []],
+ ['file_source' => 42, 'x' => 'y', 'tags' => ['tag1', 'tag2']],
+ ], $result);
+ }
+
+ public function trustedServerProvider(): array {
+ return [
+ 'Trusted server' => [true, true],
+ 'Untrusted server' => [false, false],
+ ];
+ }
+
+ /**
+ * @dataProvider trustedServerProvider
+ */
+ public function testFormatShareWithFederatedShare(bool $isKnownServer, bool $isTrusted): void {
+ $nodeId = 12;
+ $nodePath = '/test.txt';
+ $share = $this->createShare(
+ 1,
+ IShare::TYPE_REMOTE,
+ 'recipient@remoteserver.com', // shared with
+ 'sender@testserver.com', // shared by
+ 'shareOwner', // share owner
+ $nodePath, // path
+ Constants::PERMISSION_READ,
+ time(),
+ null,
+ null,
+ $nodePath,
+ $nodeId
+ );
+
+ $node = $this->createMock(\OCP\Files\File::class);
+ $node->method('getId')->willReturn($nodeId);
+ $node->method('getPath')->willReturn($nodePath);
+ $node->method('getInternalPath')->willReturn(ltrim($nodePath, '/'));
+ $mountPoint = $this->createMock(\OCP\Files\Mount\IMountPoint::class);
+ $mountPoint->method('getMountType')->willReturn('local');
+ $node->method('getMountPoint')->willReturn($mountPoint);
+ $node->method('getMimetype')->willReturn('text/plain');
+ $storage = $this->createMock(\OCP\Files\Storage\IStorage::class);
+ $storageCache = $this->createMock(\OCP\Files\Cache\ICache::class);
+ $storageCache->method('getNumericStorageId')->willReturn(1);
+ $storage->method('getCache')->willReturn($storageCache);
+ $storage->method('getId')->willReturn('home::shareOwner');
+ $node->method('getStorage')->willReturn($storage);
+ $parent = $this->createMock(\OCP\Files\Folder::class);
+ $parent->method('getId')->willReturn(2);
+ $node->method('getParent')->willReturn($parent);
+ $node->method('getSize')->willReturn(1234);
+ $node->method('getMTime')->willReturn(1234567890);
+
+ $this->previewManager->method('isAvailable')->with($node)->willReturn(false);
+
+ $this->rootFolder->method('getUserFolder')
+ ->with($this->currentUser)
+ ->willReturnSelf();
+
+ $this->rootFolder->method('getFirstNodeById')
+ ->with($share->getNodeId())
+ ->willReturn($node);
+
+ $this->rootFolder->method('getRelativePath')
+ ->with($node->getPath())
+ ->willReturnArgument(0);
+
+ $serverName = 'remoteserver.com';
+ $this->trustedServers->method('isTrustedServer')
+ ->with($serverName)
+ ->willReturn($isKnownServer);
+
+ $result = $this->invokePrivate($this->ocs, 'formatShare', [$share]);
+
+ $this->assertSame($isTrusted, $result['is_trusted_server']);
+ }
+
+ public function testFormatShareWithFederatedShareWithAtInUsername(): void {
+ $nodeId = 12;
+ $nodePath = '/test.txt';
+ $share = $this->createShare(
+ 1,
+ IShare::TYPE_REMOTE,
+ 'recipient@domain.com@remoteserver.com',
+ 'sender@testserver.com',
+ 'shareOwner',
+ $nodePath,
+ Constants::PERMISSION_READ,
+ time(),
+ null,
+ null,
+ $nodePath,
+ $nodeId
+ );
+
+ $node = $this->createMock(\OCP\Files\File::class);
+ $node->method('getId')->willReturn($nodeId);
+ $node->method('getPath')->willReturn($nodePath);
+ $node->method('getInternalPath')->willReturn(ltrim($nodePath, '/'));
+ $mountPoint = $this->createMock(\OCP\Files\Mount\IMountPoint::class);
+ $mountPoint->method('getMountType')->willReturn('local');
+ $node->method('getMountPoint')->willReturn($mountPoint);
+ $node->method('getMimetype')->willReturn('text/plain');
+ $storage = $this->createMock(\OCP\Files\Storage\IStorage::class);
+ $storageCache = $this->createMock(\OCP\Files\Cache\ICache::class);
+ $storageCache->method('getNumericStorageId')->willReturn(1);
+ $storage->method('getCache')->willReturn($storageCache);
+ $storage->method('getId')->willReturn('home::shareOwner');
+ $node->method('getStorage')->willReturn($storage);
+ $parent = $this->createMock(\OCP\Files\Folder::class);
+ $parent->method('getId')->willReturn(2);
+ $node->method('getParent')->willReturn($parent);
+ $node->method('getSize')->willReturn(1234);
+ $node->method('getMTime')->willReturn(1234567890);
+
+ $this->previewManager->method('isAvailable')->with($node)->willReturn(false);
+
+ $this->rootFolder->method('getUserFolder')
+ ->with($this->currentUser)
+ ->willReturnSelf();
+
+ $this->rootFolder->method('getFirstNodeById')
+ ->with($share->getNodeId())
+ ->willReturn($node);
+
+ $this->rootFolder->method('getRelativePath')
+ ->with($node->getPath())
+ ->willReturnArgument(0);
+
+ $serverName = 'remoteserver.com';
+ $this->trustedServers->method('isTrustedServer')
+ ->with($serverName)
+ ->willReturn(true);
+
+ $result = $this->invokePrivate($this->ocs, 'formatShare', [$share]);
+
+ $this->assertTrue($result['is_trusted_server']);
+ }
}
diff --git a/apps/files_sharing/tests/Controller/ShareControllerTest.php b/apps/files_sharing/tests/Controller/ShareControllerTest.php
index c8dc6c5de66..011210aff42 100644
--- a/apps/files_sharing/tests/Controller/ShareControllerTest.php
+++ b/apps/files_sharing/tests/Controller/ShareControllerTest.php
@@ -1,37 +1,9 @@
<?php
+
/**
- * @copyright Copyright (c) 2016, ownCloud, Inc.
- *
- * @author Bjoern Schiessle <bjoern@schiessle.org>
- * @author Björn Schießle <bjoern@schiessle.org>
- * @author Christoph Wurst <christoph@winzerhof-wurst.at>
- * @author Daniel Calviño Sánchez <danxuliu@gmail.com>
- * @author Georg Ehrke <oc.list@georgehrke.com>
- * @author Joas Schilling <coding@schilljs.com>
- * @author John Molakvoæ <skjnldsv@protonmail.com>
- * @author Julius Härtl <jus@bitgrid.net>
- * @author Lukas Reschke <lukas@statuscode.ch>
- * @author Michael Weimann <mail@michael-weimann.eu>
- * @author Morris Jobke <hey@morrisjobke.de>
- * @author Robin Appelman <robin@icewind.nl>
- * @author Roeland Jago Douma <roeland@famdouma.nl>
- * @author Thomas Müller <thomas.mueller@tmit.eu>
- * @author Vincent Petry <vincent@nextcloud.com>
- *
- * @license AGPL-3.0
- *
- * This code is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License, version 3,
- * as published by the Free Software Foundation.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU Affero General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License, version 3,
- * along with this program. If not, see <http://www.gnu.org/licenses/>
- *
+ * SPDX-FileCopyrightText: 2017-2024 Nextcloud GmbH and Nextcloud contributors
+ * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
+ * SPDX-License-Identifier: AGPL-3.0-only
*/
namespace OCA\Files_Sharing\Tests\Controllers;
@@ -46,18 +18,20 @@ use OCP\Accounts\IAccount;
use OCP\Accounts\IAccountManager;
use OCP\Accounts\IAccountProperty;
use OCP\Activity\IManager;
+use OCP\AppFramework\Http\ContentSecurityPolicy;
use OCP\AppFramework\Http\DataResponse;
use OCP\AppFramework\Http\Template\ExternalShareMenuAction;
use OCP\AppFramework\Http\Template\LinkMenuAction;
use OCP\AppFramework\Http\Template\PublicTemplateResponse;
use OCP\AppFramework\Http\Template\SimpleMenuAction;
+use OCP\AppFramework\Services\IInitialState;
use OCP\Constants;
use OCP\Defaults;
use OCP\EventDispatcher\IEventDispatcher;
use OCP\Files\File;
use OCP\Files\IRootFolder;
use OCP\Files\NotFoundException;
-use OCP\Files\Storage;
+use OCP\IAppConfig;
use OCP\IConfig;
use OCP\IL10N;
use OCP\IPreview;
@@ -67,7 +41,9 @@ use OCP\IURLGenerator;
use OCP\IUser;
use OCP\IUserManager;
use OCP\Security\ISecureRandom;
+use OCP\Server;
use OCP\Share\Exceptions\ShareNotFound;
+use OCP\Share\IAttributes;
use OCP\Share\IPublicShareTemplateFactory;
use OCP\Share\IShare;
use PHPUnit\Framework\MockObject\MockObject;
@@ -78,41 +54,27 @@ use PHPUnit\Framework\MockObject\MockObject;
* @package OCA\Files_Sharing\Controllers
*/
class ShareControllerTest extends \Test\TestCase {
- /** @var string */
- private $user;
- /** @var string */
- private $oldUser;
-
- /** @var string */
- private $appName = 'files_sharing';
- /** @var ShareController */
- private $shareController;
- /** @var IURLGenerator|MockObject */
- private $urlGenerator;
- /** @var ISession|MockObject */
- private $session;
- /** @var \OCP\IPreview|MockObject */
- private $previewManager;
- /** @var \OCP\IConfig|MockObject */
- private $config;
- /** @var \OC\Share20\Manager|MockObject */
- private $shareManager;
- /** @var IUserManager|MockObject */
- private $userManager;
- /** @var FederatedShareProvider|MockObject */
- private $federatedShareProvider;
- /** @var IAccountManager|MockObject */
- private $accountManager;
- /** @var IEventDispatcher|MockObject */
- private $eventDispatcher;
- /** @var IL10N */
- private $l10n;
- /** @var ISecureRandom */
- private $secureRandom;
- /** @var Defaults|MockObject */
- private $defaults;
- /** @var IPublicShareTemplateFactory|MockObject */
- private $publicShareTemplateFactory;
+
+ private string $user;
+ private string $oldUser;
+ private string $appName = 'files_sharing';
+ private ShareController $shareController;
+
+ private IL10N&MockObject $l10n;
+ private IConfig&MockObject $config;
+ private ISession&MockObject $session;
+ private Defaults&MockObject $defaults;
+ private IAppConfig&MockObject $appConfig;
+ private Manager&MockObject $shareManager;
+ private IPreview&MockObject $previewManager;
+ private IUserManager&MockObject $userManager;
+ private IInitialState&MockObject $initialState;
+ private IURLGenerator&MockObject $urlGenerator;
+ private ISecureRandom&MockObject $secureRandom;
+ private IAccountManager&MockObject $accountManager;
+ private IEventDispatcher&MockObject $eventDispatcher;
+ private FederatedShareProvider&MockObject $federatedShareProvider;
+ private IPublicShareTemplateFactory&MockObject $publicShareTemplateFactory;
protected function setUp(): void {
parent::setUp();
@@ -123,7 +85,9 @@ class ShareControllerTest extends \Test\TestCase {
$this->session = $this->createMock(ISession::class);
$this->previewManager = $this->createMock(IPreview::class);
$this->config = $this->createMock(IConfig::class);
+ $this->appConfig = $this->createMock(IAppConfig::class);
$this->userManager = $this->createMock(IUserManager::class);
+ $this->initialState = $this->createMock(IInitialState::class);
$this->federatedShareProvider = $this->createMock(FederatedShareProvider::class);
$this->federatedShareProvider->expects($this->any())
->method('isOutgoingServer2serverShareEnabled')->willReturn(true);
@@ -150,10 +114,12 @@ class ShareControllerTest extends \Test\TestCase {
$this->defaults,
$this->config,
$this->createMock(IRequest::class),
+ $this->initialState,
+ $this->appConfig,
)
);
- $this->shareController = new \OCA\Files_Sharing\Controller\ShareController(
+ $this->shareController = new ShareController(
$this->appName,
$this->createMock(IRequest::class),
$this->config,
@@ -178,9 +144,9 @@ class ShareControllerTest extends \Test\TestCase {
$this->oldUser = \OC_User::getUser();
// Create a dummy user
- $this->user = \OC::$server->getSecureRandom()->generate(12, ISecureRandom::CHAR_LOWER);
+ $this->user = Server::get(ISecureRandom::class)->generate(12, ISecureRandom::CHAR_LOWER);
- \OC::$server->getUserManager()->createUser($this->user, $this->user);
+ Server::get(IUserManager::class)->createUser($this->user, $this->user);
\OC_Util::tearDownFS();
$this->loginAsUser($this->user);
}
@@ -189,13 +155,13 @@ class ShareControllerTest extends \Test\TestCase {
\OC_Util::tearDownFS();
\OC_User::setUserId('');
Filesystem::tearDown();
- $user = \OC::$server->getUserManager()->get($this->user);
+ $user = Server::get(IUserManager::class)->get($this->user);
if ($user !== null) {
$user->delete();
}
\OC_User::setIncognitoMode(false);
- \OC::$server->getSession()->set('public_link_authenticated', '');
+ Server::get(ISession::class)->set('public_link_authenticated', '');
// Set old user
\OC_User::setUserId($this->oldUser);
@@ -203,14 +169,14 @@ class ShareControllerTest extends \Test\TestCase {
parent::tearDown();
}
- public function testShowShareInvalidToken() {
+ public function testShowShareInvalidToken(): void {
$this->shareController->setToken('invalidtoken');
$this->shareManager
->expects($this->once())
->method('getShareByToken')
->with('invalidtoken')
- ->will($this->throwException(new ShareNotFound()));
+ ->willThrowException(new ShareNotFound());
$this->expectException(NotFoundException::class);
@@ -218,10 +184,10 @@ class ShareControllerTest extends \Test\TestCase {
$this->shareController->showShare();
}
- public function testShowShareNotAuthenticated() {
+ public function testShowShareNotAuthenticated(): void {
$this->shareController->setToken('validtoken');
- $share = \OC::$server->getShareManager()->newShare();
+ $share = Server::get(\OCP\Share\IManager::class)->newShare();
$share->setPassword('password');
$this->shareManager
@@ -237,7 +203,7 @@ class ShareControllerTest extends \Test\TestCase {
}
- public function testShowShare() {
+ public function testShowShare(): void {
$note = 'personal note';
$filename = 'file1.txt';
@@ -273,29 +239,36 @@ class ShareControllerTest extends \Test\TestCase {
->with($owner)
->willReturn($account);
- $share = \OC::$server->getShareManager()->newShare();
- $share->setId(42);
- $share->setPassword('password')
+ /** @var Manager */
+ $manager = Server::get(Manager::class);
+ $share = $manager->newShare();
+ $share->setId(42)
+ ->setPermissions(Constants::PERMISSION_READ | Constants::PERMISSION_UPDATE)
+ ->setPassword('password')
->setShareOwner('ownerUID')
->setSharedBy('initiatorUID')
->setNode($file)
->setNote($note)
- ->setTarget("/$filename");
+ ->setTarget("/$filename")
+ ->setToken('token');
$this->session->method('exists')->with('public_link_authenticated')->willReturn(true);
$this->session->method('get')->with('public_link_authenticated')->willReturn('42');
- $this->urlGenerator->expects($this->exactly(3))
+ $this->urlGenerator->expects(self::atLeast(2))
->method('linkToRouteAbsolute')
- ->withConsecutive(
- ['files_sharing.sharecontroller.downloadShare', ['token' => 'token', 'filename' => $filename]],
- ['files_sharing.sharecontroller.showShare', ['token' => 'token']],
- ['files_sharing.PublicPreview.getPreview', ['token' => 'token', 'x' => 200, 'y' => 200, 'file' => '/'.$filename]],
- )->willReturnOnConsecutiveCalls(
- 'downloadURL',
- 'shareUrl',
- 'previewImage',
- );
+ ->willReturnMap([
+ // every file has the show show share url in the opengraph url prop
+ ['files_sharing.sharecontroller.showShare', ['token' => 'token'], 'shareUrl'],
+ // this share is not an image to the default preview is used
+ ['files_sharing.PublicPreview.getPreview', ['x' => 256, 'y' => 256, 'file' => $share->getTarget(), 'token' => 'token'], 'previewUrl'],
+ ]);
+
+ $this->urlGenerator->expects($this->once())
+ ->method('getAbsoluteURL')
+ ->willReturnMap([
+ ['/public.php/dav/files/token/?accept=zip', 'downloadUrl'],
+ ]);
$this->previewManager->method('isMimeSupported')->with('text/plain')->willReturn(true);
@@ -308,19 +281,12 @@ class ShareControllerTest extends \Test\TestCase {
['preview_max_y', 1024, 1024],
]
);
- $shareTmpl['maxSizeAnimateGif'] = $this->config->getSystemValue('max_filesize_animated_gifs_public_sharing', 10);
- $shareTmpl['previewEnabled'] = $this->config->getSystemValue('enable_previews', true);
$this->shareManager
->expects($this->once())
->method('getShareByToken')
->with('token')
->willReturn($share);
- $this->config
- ->expects($this->once())
- ->method('getAppValue')
- ->with('core', 'shareapi_public_link_disclaimertext', null)
- ->willReturn('My disclaimer text');
$this->userManager->method('get')->willReturnCallback(function (string $uid) use ($owner, $initiator) {
if ($uid === 'ownerUID') {
@@ -352,55 +318,50 @@ class ShareControllerTest extends \Test\TestCase {
->method('getProductName')
->willReturn('Nextcloud');
- $response = $this->shareController->showShare();
- $sharedTmplParams = [
- 'owner' => 'ownerUID',
- 'filename' => $filename,
- 'directory_path' => "/$filename",
- 'mimetype' => 'text/plain',
- 'dirToken' => 'token',
+ // Ensure the correct initial state is setup
+ // Shared node is a file so this is a single file share:
+ $view = 'public-file-share';
+ // Set up initial state
+ $initialState = [];
+ $this->initialState->expects(self::any())
+ ->method('provideInitialState')
+ ->willReturnCallback(function ($key, $value) use (&$initialState): void {
+ $initialState[$key] = $value;
+ });
+ $expectedInitialState = [
+ 'isPublic' => true,
'sharingToken' => 'token',
- 'server2serversharing' => true,
- 'protected' => 'true',
- 'dir' => '',
- 'downloadURL' => 'downloadURL',
- 'fileSize' => '33 B',
- 'nonHumanFileSize' => 33,
- 'maxSizeAnimateGif' => 10,
- 'previewSupported' => true,
- 'previewEnabled' => true,
- 'previewMaxX' => 1024,
- 'previewMaxY' => 1024,
- 'hideFileList' => false,
- 'shareOwner' => 'ownerDisplay',
- 'disclaimer' => 'My disclaimer text',
- 'shareUrl' => 'shareUrl',
- 'previewImage' => 'previewImage',
- 'previewURL' => 'downloadURL',
- 'note' => $note,
- 'hideDownload' => false,
- 'showgridview' => false
+ 'sharePermissions' => (Constants::PERMISSION_READ | Constants::PERMISSION_UPDATE),
+ 'filename' => $filename,
+ 'view' => $view,
+ 'fileId' => 111,
+ 'owner' => 'ownerUID',
+ 'ownerDisplayName' => 'ownerDisplay',
+ 'isFileRequest' => false,
];
- $csp = new \OCP\AppFramework\Http\ContentSecurityPolicy();
+ $response = $this->shareController->showShare();
+
+ $this->assertEquals($expectedInitialState, $initialState);
+
+ $csp = new ContentSecurityPolicy();
$csp->addAllowedFrameDomain('\'self\'');
- $expectedResponse = new PublicTemplateResponse($this->appName, 'public', $sharedTmplParams);
+ $expectedResponse = new PublicTemplateResponse('files', 'index');
+ $expectedResponse->setParams(['pageTitle' => $filename]);
$expectedResponse->setContentSecurityPolicy($csp);
- $expectedResponse->setHeaderTitle($sharedTmplParams['filename']);
- $expectedResponse->setHeaderDetails('shared by ' . $sharedTmplParams['shareOwner']);
+ $expectedResponse->setHeaderTitle($filename);
+ $expectedResponse->setHeaderDetails('shared by ownerDisplay');
$expectedResponse->setHeaderActions([
- new SimpleMenuAction('download', $this->l10n->t('Download'), 'icon-download-white', $sharedTmplParams['downloadURL'], 0),
- new SimpleMenuAction('download', $this->l10n->t('Download'), 'icon-download', $sharedTmplParams['downloadURL'], 10, $sharedTmplParams['fileSize']),
- new LinkMenuAction($this->l10n->t('Direct link'), 'icon-public', $sharedTmplParams['previewURL']),
- new ExternalShareMenuAction($this->l10n->t('Add to your Nextcloud'), 'icon-external', $sharedTmplParams['owner'], $sharedTmplParams['shareOwner'], $sharedTmplParams['filename']),
+ new SimpleMenuAction('download', $this->l10n->t('Download'), 'icon-download', 'downloadUrl', 0, '33'),
+ new ExternalShareMenuAction($this->l10n->t('Add to your Nextcloud'), 'icon-external', 'owner', 'ownerDisplay', $filename),
+ new LinkMenuAction($this->l10n->t('Direct link'), 'icon-public', 'downloadUrl'),
]);
$this->assertEquals($expectedResponse, $response);
}
- public function testShowShareWithPrivateName() {
- $note = 'personal note';
- $filename = 'file1.txt';
+ public function testShowFileDropShare(): void {
+ $filename = 'folder1';
$this->shareController->setToken('token');
@@ -414,17 +375,15 @@ class ShareControllerTest extends \Test\TestCase {
$initiator->method('getUID')->willReturn('initiatorUID');
$initiator->method('isEnabled')->willReturn(true);
- $file = $this->createMock(File::class);
- $file->method('getName')->willReturn($filename);
- $file->method('getMimetype')->willReturn('text/plain');
- $file->method('getSize')->willReturn(33);
+ $file = $this->createMock(Folder::class);
$file->method('isReadable')->willReturn(true);
$file->method('isShareable')->willReturn(true);
- $file->method('getId')->willReturn(111);
+ $file->method('getId')->willReturn(1234);
+ $file->method('getName')->willReturn($filename);
$accountName = $this->createMock(IAccountProperty::class);
$accountName->method('getScope')
- ->willReturn(IAccountManager::SCOPE_LOCAL);
+ ->willReturn(IAccountManager::SCOPE_PUBLISHED);
$account = $this->createMock(IAccount::class);
$account->method('getProperty')
->with(IAccountManager::PROPERTY_DISPLAYNAME)
@@ -434,31 +393,36 @@ class ShareControllerTest extends \Test\TestCase {
->with($owner)
->willReturn($account);
- $share = \OC::$server->getShareManager()->newShare();
- $share->setId(42);
- $share->setPassword('password')
+ /** @var Manager */
+ $manager = Server::get(Manager::class);
+ $share = $manager->newShare();
+ $share->setId(42)
+ ->setPermissions(Constants::PERMISSION_CREATE)
+ ->setPassword('password')
->setShareOwner('ownerUID')
->setSharedBy('initiatorUID')
+ ->setNote('The note')
+ ->setLabel('A label')
->setNode($file)
- ->setNote($note)
- ->setTarget("/$filename");
+ ->setTarget("/$filename")
+ ->setToken('token');
+
+ $this->appConfig
+ ->expects($this->once())
+ ->method('getValueString')
+ ->with('core', 'shareapi_public_link_disclaimertext', '')
+ ->willReturn('My disclaimer text');
$this->session->method('exists')->with('public_link_authenticated')->willReturn(true);
$this->session->method('get')->with('public_link_authenticated')->willReturn('42');
- $this->urlGenerator->expects($this->exactly(3))
+ $this->urlGenerator->expects(self::atLeastOnce())
->method('linkToRouteAbsolute')
- ->withConsecutive(
- ['files_sharing.sharecontroller.downloadShare', ['token' => 'token', 'filename' => $filename]],
- ['files_sharing.sharecontroller.showShare', ['token' => 'token']],
- ['files_sharing.PublicPreview.getPreview', ['token' => 'token', 'x' => 200, 'y' => 200, 'file' => '/'.$filename]],
- )->willReturnOnConsecutiveCalls(
- 'downloadURL',
- 'shareUrl',
- 'previewImage',
- );
-
- $this->previewManager->method('isMimeSupported')->with('text/plain')->willReturn(true);
+ ->willReturnMap([
+ // every file has the show show share url in the opengraph url prop
+ ['files_sharing.sharecontroller.showShare', ['token' => 'token'], 'shareUrl'],
+ // there is no preview or folders so no other link for opengraph
+ ]);
$this->config->method('getSystemValue')
->willReturnMap(
@@ -469,19 +433,12 @@ class ShareControllerTest extends \Test\TestCase {
['preview_max_y', 1024, 1024],
]
);
- $shareTmpl['maxSizeAnimateGif'] = $this->config->getSystemValue('max_filesize_animated_gifs_public_sharing', 10);
- $shareTmpl['previewEnabled'] = $this->config->getSystemValue('enable_previews', true);
$this->shareManager
->expects($this->once())
->method('getShareByToken')
->with('token')
->willReturn($share);
- $this->config
- ->expects($this->once())
- ->method('getAppValue')
- ->with('core', 'shareapi_public_link_disclaimertext', null)
- ->willReturn('My disclaimer text');
$this->userManager->method('get')->willReturnCallback(function (string $uid) use ($owner, $initiator) {
if ($uid === 'ownerUID') {
@@ -505,67 +462,56 @@ class ShareControllerTest extends \Test\TestCase {
$this->l10n->expects($this->any())
->method('t')
- ->will($this->returnCallback(function ($text, $parameters) {
+ ->willReturnCallback(function ($text, $parameters) {
return vsprintf($text, $parameters);
- }));
-
- $this->defaults->expects(self::any())
- ->method('getProductName')
- ->willReturn('Nextcloud');
+ });
- $response = $this->shareController->showShare();
- $sharedTmplParams = [
- 'owner' => '',
- 'filename' => $filename,
- 'directory_path' => "/$filename",
- 'mimetype' => 'text/plain',
- 'dirToken' => 'token',
+ // Set up initial state
+ $initialState = [];
+ $this->initialState->expects(self::any())
+ ->method('provideInitialState')
+ ->willReturnCallback(function ($key, $value) use (&$initialState): void {
+ $initialState[$key] = $value;
+ });
+ $expectedInitialState = [
+ 'isPublic' => true,
'sharingToken' => 'token',
- 'server2serversharing' => true,
- 'protected' => 'true',
- 'dir' => '',
- 'downloadURL' => 'downloadURL',
- 'fileSize' => '33 B',
- 'nonHumanFileSize' => 33,
- 'maxSizeAnimateGif' => 10,
- 'previewSupported' => true,
- 'previewEnabled' => true,
- 'previewMaxX' => 1024,
- 'previewMaxY' => 1024,
- 'hideFileList' => false,
- 'shareOwner' => '',
+ 'sharePermissions' => Constants::PERMISSION_CREATE,
+ 'filename' => $filename,
+ 'view' => 'public-file-drop',
'disclaimer' => 'My disclaimer text',
- 'shareUrl' => 'shareUrl',
- 'previewImage' => 'previewImage',
- 'previewURL' => 'downloadURL',
- 'note' => $note,
- 'hideDownload' => false,
- 'showgridview' => false
+ 'owner' => 'ownerUID',
+ 'ownerDisplayName' => 'ownerDisplay',
+ 'isFileRequest' => false,
+ 'note' => 'The note',
+ 'label' => 'A label',
];
- $csp = new \OCP\AppFramework\Http\ContentSecurityPolicy();
+ $response = $this->shareController->showShare();
+
+ $this->assertEquals($expectedInitialState, $initialState);
+
+ $csp = new ContentSecurityPolicy();
$csp->addAllowedFrameDomain('\'self\'');
- $expectedResponse = new PublicTemplateResponse($this->appName, 'public', $sharedTmplParams);
+ $expectedResponse = new PublicTemplateResponse('files', 'index');
+ $expectedResponse->setParams(['pageTitle' => 'A label']);
$expectedResponse->setContentSecurityPolicy($csp);
- $expectedResponse->setHeaderTitle($sharedTmplParams['filename']);
- $expectedResponse->setHeaderDetails('');
+ $expectedResponse->setHeaderTitle('A label');
+ $expectedResponse->setHeaderDetails('shared by ownerDisplay');
$expectedResponse->setHeaderActions([
- new SimpleMenuAction('download', $this->l10n->t('Download'), 'icon-download-white', $sharedTmplParams['downloadURL'], 0),
- new SimpleMenuAction('download', $this->l10n->t('Download'), 'icon-download', $sharedTmplParams['downloadURL'], 10, $sharedTmplParams['fileSize']),
- new LinkMenuAction($this->l10n->t('Direct link'), 'icon-public', $sharedTmplParams['previewURL']),
- new ExternalShareMenuAction($this->l10n->t('Add to your Nextcloud'), 'icon-external', $sharedTmplParams['owner'], $sharedTmplParams['shareOwner'], $sharedTmplParams['filename']),
+ new LinkMenuAction($this->l10n->t('Direct link'), 'icon-public', 'shareUrl'),
]);
$this->assertEquals($expectedResponse, $response);
}
- public function testShowShareHideDownload() {
+ public function testShowShareWithPrivateName(): void {
$note = 'personal note';
$filename = 'file1.txt';
$this->shareController->setToken('token');
- $owner = $this->getMockBuilder(IUser::class)->getMock();
+ $owner = $this->createMock(IUser::class);
$owner->method('getDisplayName')->willReturn('ownerDisplay');
$owner->method('getUID')->willReturn('ownerUID');
$owner->method('isEnabled')->willReturn(true);
@@ -575,7 +521,7 @@ class ShareControllerTest extends \Test\TestCase {
$initiator->method('getUID')->willReturn('initiatorUID');
$initiator->method('isEnabled')->willReturn(true);
- $file = $this->getMockBuilder('OCP\Files\File')->getMock();
+ $file = $this->createMock(File::class);
$file->method('getName')->willReturn($filename);
$file->method('getMimetype')->willReturn('text/plain');
$file->method('getSize')->willReturn(33);
@@ -585,7 +531,7 @@ class ShareControllerTest extends \Test\TestCase {
$accountName = $this->createMock(IAccountProperty::class);
$accountName->method('getScope')
- ->willReturn(IAccountManager::SCOPE_PUBLISHED);
+ ->willReturn(IAccountManager::SCOPE_LOCAL);
$account = $this->createMock(IAccount::class);
$account->method('getProperty')
->with(IAccountManager::PROPERTY_DISPLAYNAME)
@@ -595,33 +541,35 @@ class ShareControllerTest extends \Test\TestCase {
->with($owner)
->willReturn($account);
- $share = \OC::$server->getShareManager()->newShare();
+ /** @var IShare */
+ $share = Server::get(Manager::class)->newShare();
$share->setId(42);
$share->setPassword('password')
->setShareOwner('ownerUID')
->setSharedBy('initiatorUID')
->setNode($file)
->setNote($note)
- ->setTarget("/$filename")
- ->setHideDownload(true);
+ ->setToken('token')
+ ->setPermissions(Constants::PERMISSION_ALL & ~Constants::PERMISSION_SHARE)
+ ->setTarget("/$filename");
$this->session->method('exists')->with('public_link_authenticated')->willReturn(true);
$this->session->method('get')->with('public_link_authenticated')->willReturn('42');
- // Even if downloads are disabled the "downloadURL" parameter is
- // provided to the template, as it is needed to preview audio and GIF
- // files.
- $this->urlGenerator->expects($this->exactly(3))
+ $this->urlGenerator->expects(self::atLeast(2))
->method('linkToRouteAbsolute')
- ->withConsecutive(
- ['files_sharing.sharecontroller.downloadShare', ['token' => 'token', 'filename' => $filename]],
- ['files_sharing.sharecontroller.showShare', ['token' => 'token']],
- ['files_sharing.PublicPreview.getPreview', ['token' => 'token', 'x' => 200, 'y' => 200, 'file' => '/'.$filename]],
- )->willReturnOnConsecutiveCalls(
- 'downloadURL',
- 'shareUrl',
- 'previewImage',
- );
+ ->willReturnMap([
+ // every file has the show show share url in the opengraph url prop
+ ['files_sharing.sharecontroller.showShare', ['token' => 'token'], 'shareUrl'],
+ // this share is not an image to the default preview is used
+ ['files_sharing.PublicPreview.getPreview', ['x' => 256, 'y' => 256, 'file' => $share->getTarget(), 'token' => 'token'], 'previewUrl'],
+ ]);
+
+ $this->urlGenerator->expects($this->once())
+ ->method('getAbsoluteURL')
+ ->willReturnMap([
+ ['/public.php/dav/files/token/?accept=zip', 'downloadUrl'],
+ ]);
$this->previewManager->method('isMimeSupported')->with('text/plain')->willReturn(true);
@@ -642,11 +590,6 @@ class ShareControllerTest extends \Test\TestCase {
->method('getShareByToken')
->with('token')
->willReturn($share);
- $this->config
- ->expects($this->once())
- ->method('getAppValue')
- ->with('core', 'shareapi_public_link_disclaimertext', null)
- ->willReturn('My disclaimer text');
$this->userManager->method('get')->willReturnCallback(function (string $uid) use ($owner, $initiator) {
if ($uid === 'ownerUID') {
@@ -674,175 +617,31 @@ class ShareControllerTest extends \Test\TestCase {
return vsprintf($text, $parameters);
});
- $response = $this->shareController->showShare();
- $sharedTmplParams = [
- 'owner' => 'ownerUID',
- 'filename' => $filename,
- 'directory_path' => "/$filename",
- 'mimetype' => 'text/plain',
- 'dirToken' => 'token',
- 'sharingToken' => 'token',
- 'server2serversharing' => true,
- 'protected' => 'true',
- 'dir' => '',
- 'downloadURL' => 'downloadURL',
- 'fileSize' => '33 B',
- 'nonHumanFileSize' => 33,
- 'maxSizeAnimateGif' => 10,
- 'previewSupported' => true,
- 'previewEnabled' => true,
- 'previewMaxX' => 1024,
- 'previewMaxY' => 1024,
- 'hideFileList' => false,
- 'shareOwner' => 'ownerDisplay',
- 'disclaimer' => 'My disclaimer text',
- 'shareUrl' => 'shareUrl',
- 'previewImage' => 'previewImage',
- 'previewURL' => 'downloadURL',
- 'note' => $note,
- 'hideDownload' => true,
- 'showgridview' => false
- ];
-
- $csp = new \OCP\AppFramework\Http\ContentSecurityPolicy();
- $csp->addAllowedFrameDomain('\'self\'');
- $expectedResponse = new PublicTemplateResponse($this->appName, 'public', $sharedTmplParams);
- $expectedResponse->setContentSecurityPolicy($csp);
- $expectedResponse->setHeaderTitle($sharedTmplParams['filename']);
- $expectedResponse->setHeaderDetails('shared by ' . $sharedTmplParams['shareOwner']);
- $expectedResponse->setHeaderActions([]);
-
- $this->assertEquals($expectedResponse, $response);
- }
-
- /**
- * Checks file drop shares:
- * - there must not be any header action
- * - the template param "hideFileList" should be true
- *
- * @test
- * @return void
- */
- public function testShareFileDrop() {
- $this->shareController->setToken('token');
-
- $owner = $this->getMockBuilder(IUser::class)->getMock();
- $owner->method('getDisplayName')->willReturn('ownerDisplay');
- $owner->method('getUID')->willReturn('ownerUID');
- $owner->method('isEnabled')->willReturn(true);
-
- $initiator = $this->createMock(IUser::class);
- $initiator->method('getDisplayName')->willReturn('initiatorDisplay');
- $initiator->method('getUID')->willReturn('initiatorUID');
- $initiator->method('isEnabled')->willReturn(true);
-
- /* @var MockObject|Storage $storage */
- $storage = $this->getMockBuilder(Storage::class)
- ->disableOriginalConstructor()
- ->getMock();
-
- /* @var MockObject|Folder $folder */
- $folder = $this->getMockBuilder(Folder::class)
- ->disableOriginalConstructor()
- ->getMock();
- $folder->method('getName')->willReturn('/fileDrop');
- $folder->method('isReadable')->willReturn(true);
- $folder->method('isShareable')->willReturn(true);
- $folder->method('getStorage')->willReturn($storage);
- $folder->method('get')->with('')->willReturn($folder);
- $folder->method('getSize')->willReturn(1337);
- $folder->method('getId')->willReturn(111);
-
- $accountName = $this->createMock(IAccountProperty::class);
- $accountName->method('getScope')
- ->willReturn(IAccountManager::SCOPE_PUBLISHED);
- $account = $this->createMock(IAccount::class);
- $account->method('getProperty')
- ->with(IAccountManager::PROPERTY_DISPLAYNAME)
- ->willReturn($accountName);
- $this->accountManager->expects($this->once())
- ->method('getAccount')
- ->with($owner)
- ->willReturn($account);
-
- $share = \OC::$server->getShareManager()->newShare();
- $share->setId(42);
- $share->setPermissions(Constants::PERMISSION_CREATE)
- ->setShareOwner('ownerUID')
- ->setSharedBy('initiatorUID')
- ->setNode($folder)
- ->setTarget('/fileDrop');
-
- $this->shareManager
- ->expects($this->once())
- ->method('getShareByToken')
- ->with('token')
- ->willReturn($share);
-
- $this->userManager->method('get')->willReturnCallback(function (string $uid) use ($owner, $initiator) {
- if ($uid === 'ownerUID') {
- return $owner;
- }
- if ($uid === 'initiatorUID') {
- return $initiator;
- }
- return null;
- });
-
- $this->l10n->expects($this->any())
- ->method('t')
- ->willReturnCallback(function ($text, $parameters) {
- return vsprintf($text, $parameters);
- });
+ $this->defaults->expects(self::any())
+ ->method('getProductName')
+ ->willReturn('Nextcloud');
$response = $this->shareController->showShare();
- // skip the "folder" param for tests
- $responseParams = $response->getParams();
- unset($responseParams['folder']);
- $response->setParams($responseParams);
-
- $sharedTmplParams = [
- 'owner' => 'ownerUID',
- 'filename' => '/fileDrop',
- 'directory_path' => '/fileDrop',
- 'mimetype' => null,
- 'dirToken' => 'token',
- 'sharingToken' => 'token',
- 'server2serversharing' => true,
- 'protected' => 'false',
- 'dir' => null,
- 'downloadURL' => '',
- 'fileSize' => '1 KB',
- 'nonHumanFileSize' => 1337,
- 'maxSizeAnimateGif' => null,
- 'previewSupported' => null,
- 'previewEnabled' => null,
- 'previewMaxX' => null,
- 'previewMaxY' => null,
- 'hideFileList' => true,
- 'shareOwner' => 'ownerDisplay',
- 'disclaimer' => null,
- 'shareUrl' => '',
- 'previewImage' => '',
- 'previewURL' => '',
- 'note' => '',
- 'hideDownload' => false,
- 'showgridview' => false
- ];
- $csp = new \OCP\AppFramework\Http\ContentSecurityPolicy();
+ $csp = new ContentSecurityPolicy();
$csp->addAllowedFrameDomain('\'self\'');
- $expectedResponse = new PublicTemplateResponse($this->appName, 'public', $sharedTmplParams);
+ $expectedResponse = new PublicTemplateResponse('files', 'index');
+ $expectedResponse->setParams(['pageTitle' => $filename]);
$expectedResponse->setContentSecurityPolicy($csp);
- $expectedResponse->setHeaderTitle($sharedTmplParams['filename']);
- $expectedResponse->setHeaderDetails('shared by ' . $sharedTmplParams['shareOwner']);
+ $expectedResponse->setHeaderTitle($filename);
+ $expectedResponse->setHeaderDetails('');
+ $expectedResponse->setHeaderActions([
+ new SimpleMenuAction('download', $this->l10n->t('Download'), 'icon-download', 'downloadUrl', 0, '33'),
+ new ExternalShareMenuAction($this->l10n->t('Add to your Nextcloud'), 'icon-external', 'owner', 'ownerDisplay', $filename),
+ new LinkMenuAction($this->l10n->t('Direct link'), 'icon-public', 'downloadUrl'),
+ ]);
- self::assertEquals($expectedResponse, $response);
+ $this->assertEquals($expectedResponse, $response);
}
- public function testShowShareInvalid() {
- $this->expectException(\OCP\Files\NotFoundException::class);
+ public function testShowShareInvalid(): void {
+ $this->expectException(NotFoundException::class);
$filename = 'file1.txt';
$this->shareController->setToken('token');
@@ -858,7 +657,7 @@ class ShareControllerTest extends \Test\TestCase {
$file->method('isShareable')->willReturn(false);
$file->method('isReadable')->willReturn(true);
- $share = \OC::$server->getShareManager()->newShare();
+ $share = Server::get(\OCP\Share\IManager::class)->newShare();
$share->setId(42);
$share->setPassword('password')
->setShareOwner('ownerUID')
@@ -891,13 +690,13 @@ class ShareControllerTest extends \Test\TestCase {
$this->shareController->showShare();
}
- public function testDownloadShareWithCreateOnlyShare() {
+ public function testDownloadShareWithCreateOnlyShare(): void {
$share = $this->getMockBuilder(IShare::class)->getMock();
$share->method('getPassword')->willReturn('password');
$share
->expects($this->once())
->method('getPermissions')
- ->willReturn(\OCP\Constants::PERMISSION_CREATE);
+ ->willReturn(Constants::PERMISSION_CREATE);
$this->shareManager
->expects($this->once())
@@ -911,7 +710,35 @@ class ShareControllerTest extends \Test\TestCase {
$this->assertEquals($expectedResponse, $response);
}
- public function testDisabledOwner() {
+ public function testDownloadShareWithoutDownloadPermission(): void {
+ $attributes = $this->createMock(IAttributes::class);
+ $attributes->expects(self::once())
+ ->method('getAttribute')
+ ->with('permissions', 'download')
+ ->willReturn(false);
+
+ $share = $this->createMock(IShare::class);
+ $share->method('getPassword')->willReturn('password');
+ $share->expects(self::once())
+ ->method('getPermissions')
+ ->willReturn(Constants::PERMISSION_READ);
+ $share->expects(self::once())
+ ->method('getAttributes')
+ ->willReturn($attributes);
+
+ $this->shareManager
+ ->expects(self::once())
+ ->method('getShareByToken')
+ ->with('validtoken')
+ ->willReturn($share);
+
+ // Test with a password protected share and no authentication
+ $response = $this->shareController->downloadShare('validtoken');
+ $expectedResponse = new DataResponse('Share has no download permission');
+ $this->assertEquals($expectedResponse, $response);
+ }
+
+ public function testDisabledOwner(): void {
$this->shareController->setToken('token');
$owner = $this->getMockBuilder(IUser::class)->getMock();
@@ -923,7 +750,7 @@ class ShareControllerTest extends \Test\TestCase {
/* @var MockObject|Folder $folder */
$folder = $this->createMock(Folder::class);
- $share = \OC::$server->getShareManager()->newShare();
+ $share = Server::get(\OCP\Share\IManager::class)->newShare();
$share->setId(42);
$share->setPermissions(Constants::PERMISSION_CREATE)
->setShareOwner('ownerUID')
@@ -952,7 +779,7 @@ class ShareControllerTest extends \Test\TestCase {
$this->shareController->showShare();
}
- public function testDisabledInitiator() {
+ public function testDisabledInitiator(): void {
$this->shareController->setToken('token');
$owner = $this->getMockBuilder(IUser::class)->getMock();
@@ -964,7 +791,7 @@ class ShareControllerTest extends \Test\TestCase {
/* @var MockObject|Folder $folder */
$folder = $this->createMock(Folder::class);
- $share = \OC::$server->getShareManager()->newShare();
+ $share = Server::get(\OCP\Share\IManager::class)->newShare();
$share->setId(42);
$share->setPermissions(Constants::PERMISSION_CREATE)
->setShareOwner('ownerUID')
diff --git a/apps/files_sharing/tests/Controller/ShareInfoControllerTest.php b/apps/files_sharing/tests/Controller/ShareInfoControllerTest.php
index 18bda2f488d..1a678610805 100644
--- a/apps/files_sharing/tests/Controller/ShareInfoControllerTest.php
+++ b/apps/files_sharing/tests/Controller/ShareInfoControllerTest.php
@@ -1,25 +1,8 @@
<?php
+
/**
- * @copyright Copyright (c) 2016 Roeland Jago Douma <roeland@famdouma.nl>
- *
- * @author Morris Jobke <hey@morrisjobke.de>
- * @author Roeland Jago Douma <roeland@famdouma.nl>
- *
- * @license GNU AGPL version 3 or any later version
- *
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License as
- * published by the Free Software Foundation, either version 3 of the
- * License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU Affero General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- *
+ * SPDX-FileCopyrightText: 2016 Nextcloud GmbH and Nextcloud contributors
+ * SPDX-License-Identifier: AGPL-3.0-or-later
*/
namespace OCA\Files_Sharing\Tests\Controller;
@@ -33,15 +16,13 @@ use OCP\IRequest;
use OCP\Share\Exceptions\ShareNotFound;
use OCP\Share\IManager as ShareManager;
use OCP\Share\IShare;
+use PHPUnit\Framework\MockObject\MockObject;
use Test\TestCase;
class ShareInfoControllerTest extends TestCase {
- /** @var ShareInfoController */
- private $controller;
-
- /** @var ShareManager|\PHPUnit\Framework\MockObject\MockObject */
- private $shareManager;
+ protected ShareInfoController $controller;
+ protected ShareManager&MockObject $shareManager;
protected function setUp(): void {
@@ -49,17 +30,14 @@ class ShareInfoControllerTest extends TestCase {
$this->shareManager = $this->createMock(ShareManager::class);
- $this->controller = $this->getMockBuilder(ShareInfoController::class)
- ->setConstructorArgs([
- 'files_sharing',
- $this->createMock(IRequest::class),
- $this->shareManager
- ])
- ->setMethods(['addROWrapper'])
- ->getMock();
+ $this->controller = new ShareInfoController(
+ 'files_sharing',
+ $this->createMock(IRequest::class),
+ $this->shareManager
+ );
}
- public function testNoShare() {
+ public function testNoShare(): void {
$this->shareManager->method('getShareByToken')
->with('token')
->willThrowException(new ShareNotFound());
@@ -69,7 +47,7 @@ class ShareInfoControllerTest extends TestCase {
$this->assertEquals($expected, $this->controller->info('token'));
}
- public function testWrongPassword() {
+ public function testWrongPassword(): void {
$share = $this->createMock(IShare::class);
$share->method('getPassword')
->willReturn('sharePass');
@@ -86,7 +64,7 @@ class ShareInfoControllerTest extends TestCase {
$this->assertEquals($expected, $this->controller->info('token', 'pass'));
}
- public function testNoReadPermissions() {
+ public function testNoReadPermissions(): void {
$share = $this->createMock(IShare::class);
$share->method('getPassword')
->willReturn('sharePass');
@@ -125,7 +103,7 @@ class ShareInfoControllerTest extends TestCase {
return $file;
}
- public function testInfoFile() {
+ public function testInfoFile(): void {
$file = $this->prepareFile();
$share = $this->createMock(IShare::class);
@@ -157,7 +135,7 @@ class ShareInfoControllerTest extends TestCase {
$this->assertEquals($expected, $this->controller->info('token', 'pass'));
}
- public function testInfoFileRO() {
+ public function testInfoFileRO(): void {
$file = $this->prepareFile();
$share = $this->createMock(IShare::class);
@@ -239,7 +217,7 @@ class ShareInfoControllerTest extends TestCase {
return $root;
}
- public function testInfoFolder() {
+ public function testInfoFolder(): void {
$file = $this->prepareFolder();
$share = $this->createMock(IShare::class);
diff --git a/apps/files_sharing/tests/Controller/ShareesAPIControllerTest.php b/apps/files_sharing/tests/Controller/ShareesAPIControllerTest.php
index b56e57d272a..18e1bf0347b 100644
--- a/apps/files_sharing/tests/Controller/ShareesAPIControllerTest.php
+++ b/apps/files_sharing/tests/Controller/ShareesAPIControllerTest.php
@@ -1,41 +1,18 @@
<?php
+
/**
- * @copyright Copyright (c) 2016, ownCloud, Inc.
- *
- * @author Arthur Schiwon <blizzz@arthur-schiwon.de>
- * @author Bjoern Schiessle <bjoern@schiessle.org>
- * @author Christoph Wurst <christoph@winzerhof-wurst.at>
- * @author Joas Schilling <coding@schilljs.com>
- * @author Julius Härtl <jus@bitgrid.net>
- * @author Lukas Reschke <lukas@statuscode.ch>
- * @author Robin Appelman <robin@icewind.nl>
- * @author Roeland Jago Douma <roeland@famdouma.nl>
- * @author Thomas Citharel <nextcloud@tcit.fr>
- * @author Thomas Müller <thomas.mueller@tmit.eu>
- *
- * @license AGPL-3.0
- *
- * This code is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License, version 3,
- * as published by the Free Software Foundation.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU Affero General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License, version 3,
- * along with this program. If not, see <http://www.gnu.org/licenses/>
- *
+ * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
+ * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
+ * SPDX-License-Identifier: AGPL-3.0-only
*/
namespace OCA\Files_Sharing\Tests\Controller;
use OCA\Files_Sharing\Controller\ShareesAPIController;
use OCA\Files_Sharing\Tests\TestCase;
-use OCP\AppFramework\Http;
use OCP\AppFramework\Http\DataResponse;
use OCP\AppFramework\OCS\OCSBadRequestException;
use OCP\Collaboration\Collaborators\ISearch;
+use OCP\GlobalScale\IConfig as GlobalScaleIConfig;
use OCP\IConfig;
use OCP\IRequest;
use OCP\IURLGenerator;
@@ -63,7 +40,7 @@ class ShareesAPIControllerTest extends TestCase {
/** @var IManager|MockObject */
protected $shareManager;
- /** @var ISearch|MockObject */
+ /** @var ISearch|MockObject */
protected $collaboratorSearch;
/** @var IConfig|MockObject */
@@ -93,7 +70,7 @@ class ShareesAPIControllerTest extends TestCase {
);
}
- public function dataSearch(): array {
+ public static function dataSearch(): array {
$noRemote = [IShare::TYPE_USER, IShare::TYPE_GROUP, IShare::TYPE_EMAIL];
$allTypes = [IShare::TYPE_USER, IShare::TYPE_GROUP, IShare::TYPE_REMOTE, IShare::TYPE_REMOTE_GROUP, IShare::TYPE_EMAIL];
@@ -221,7 +198,6 @@ class ShareesAPIControllerTest extends TestCase {
}
/**
- * @dataProvider dataSearch
*
* @param array $getData
* @param string $apiSetting
@@ -235,6 +211,7 @@ class ShareesAPIControllerTest extends TestCase {
* @param bool $allowGroupSharing
* @throws OCSBadRequestException
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataSearch')]
public function testSearch(
array $getData,
string $apiSetting,
@@ -247,21 +224,21 @@ class ShareesAPIControllerTest extends TestCase {
bool $shareWithGroupOnly,
bool $shareeEnumeration,
bool $allowGroupSharing,
- ) {
+ ): void {
$search = $getData['search'] ?? '';
$itemType = $getData['itemType'] ?? 'irrelevant';
$page = $getData['page'] ?? 1;
$perPage = $getData['perPage'] ?? 200;
$shareType = $getData['shareType'] ?? null;
+ $globalConfig = $this->createMock(GlobalScaleIConfig::class);
+ $globalConfig->expects(self::once())
+ ->method('isGlobalScaleEnabled')
+ ->willReturn(true);
+ $this->overwriteService(GlobalScaleIConfig::class, $globalConfig);
+
/** @var IConfig|MockObject $config */
$config = $this->createMock(IConfig::class);
- $config->expects($this->exactly(1))
- ->method('getAppValue')
- ->with($this->anything(), $this->anything(), $this->anything())
- ->willReturnMap([
- ['files_sharing', 'lookupServerEnabled', 'yes', 'yes'],
- ]);
$this->shareManager->expects($this->once())
->method('allowGroupSharing')
@@ -322,10 +299,10 @@ class ShareesAPIControllerTest extends TestCase {
}
});
- $this->assertInstanceOf(Http\DataResponse::class, $sharees->search($search, $itemType, $page, $perPage, $shareType));
+ $this->assertInstanceOf(DataResponse::class, $sharees->search($search, $itemType, $page, $perPage, $shareType));
}
- public function dataSearchInvalid(): array {
+ public static function dataSearchInvalid(): array {
return [
// Test invalid pagination
[[
@@ -352,12 +329,12 @@ class ShareesAPIControllerTest extends TestCase {
}
/**
- * @dataProvider dataSearchInvalid
*
* @param array $getData
* @param string $message
*/
- public function testSearchInvalid($getData, $message) {
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataSearchInvalid')]
+ public function testSearchInvalid($getData, $message): void {
$page = $getData['page'] ?? 1;
$perPage = $getData['perPage'] ?? 200;
@@ -400,7 +377,7 @@ class ShareesAPIControllerTest extends TestCase {
}
}
- public function dataIsRemoteSharingAllowed() {
+ public static function dataIsRemoteSharingAllowed() {
return [
['file', true],
['folder', true],
@@ -410,16 +387,16 @@ class ShareesAPIControllerTest extends TestCase {
}
/**
- * @dataProvider dataIsRemoteSharingAllowed
*
* @param string $itemType
* @param bool $expected
*/
- public function testIsRemoteSharingAllowed($itemType, $expected) {
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataIsRemoteSharingAllowed')]
+ public function testIsRemoteSharingAllowed($itemType, $expected): void {
$this->assertSame($expected, $this->invokePrivate($this->sharees, 'isRemoteSharingAllowed', [$itemType]));
}
- public function testSearchSharingDisabled() {
+ public function testSearchSharingDisabled(): void {
$this->shareManager->expects($this->once())
->method('sharingDisabledForUser')
->with($this->uid)
@@ -436,14 +413,14 @@ class ShareesAPIControllerTest extends TestCase {
$this->assertInstanceOf(DataResponse::class, $this->sharees->search('', null, 1, 10, [], false));
}
- public function testSearchNoItemType() {
- $this->expectException(\OCP\AppFramework\OCS\OCSBadRequestException::class);
+ public function testSearchNoItemType(): void {
+ $this->expectException(OCSBadRequestException::class);
$this->expectExceptionMessage('Missing itemType');
$this->sharees->search('', null, 1, 10, [], false);
}
- public function dataGetPaginationLink() {
+ public static function dataGetPaginationLink() {
return [
[1, '/ocs/v1.php', ['perPage' => 2], '<?perPage=2&page=2>; rel="next"'],
[10, '/ocs/v2.php', ['perPage' => 2], '<?perPage=2&page=11>; rel="next"'],
@@ -451,14 +428,14 @@ class ShareesAPIControllerTest extends TestCase {
}
/**
- * @dataProvider dataGetPaginationLink
*
* @param int $page
* @param string $scriptName
* @param array $params
* @param array $expected
*/
- public function testGetPaginationLink($page, $scriptName, $params, $expected) {
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataGetPaginationLink')]
+ public function testGetPaginationLink($page, $scriptName, $params, $expected): void {
$this->request->expects($this->once())
->method('getScriptName')
->willReturn($scriptName);
@@ -466,7 +443,7 @@ class ShareesAPIControllerTest extends TestCase {
$this->assertEquals($expected, $this->invokePrivate($this->sharees, 'getPaginationLink', [$page, $params]));
}
- public function dataIsV2() {
+ public static function dataIsV2() {
return [
['/ocs/v1.php', false],
['/ocs/v2.php', true],
@@ -474,12 +451,12 @@ class ShareesAPIControllerTest extends TestCase {
}
/**
- * @dataProvider dataIsV2
*
* @param string $scriptName
* @param bool $expected
*/
- public function testIsV2($scriptName, $expected) {
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataIsV2')]
+ public function testIsV2($scriptName, $expected): void {
$this->request->expects($this->once())
->method('getScriptName')
->willReturn($scriptName);
diff --git a/apps/files_sharing/tests/DeleteOrphanedSharesJobTest.php b/apps/files_sharing/tests/DeleteOrphanedSharesJobTest.php
index 0a39246e030..c245d157151 100644
--- a/apps/files_sharing/tests/DeleteOrphanedSharesJobTest.php
+++ b/apps/files_sharing/tests/DeleteOrphanedSharesJobTest.php
@@ -1,32 +1,20 @@
<?php
+
/**
- * @copyright Copyright (c) 2016, ownCloud, Inc.
- *
- * @author Christoph Wurst <christoph@winzerhof-wurst.at>
- * @author Joas Schilling <coding@schilljs.com>
- * @author Morris Jobke <hey@morrisjobke.de>
- * @author Roeland Jago Douma <roeland@famdouma.nl>
- * @author Thomas Müller <thomas.mueller@tmit.eu>
- * @author Vincent Petry <vincent@nextcloud.com>
- *
- * @license AGPL-3.0
- *
- * This code is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License, version 3,
- * as published by the Free Software Foundation.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU Affero General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License, version 3,
- * along with this program. If not, see <http://www.gnu.org/licenses/>
- *
+ * SPDX-FileCopyrightText: 2017-2024 Nextcloud GmbH and Nextcloud contributors
+ * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
+ * SPDX-License-Identifier: AGPL-3.0-only
*/
namespace OCA\Files_Sharing\Tests;
+use OC\Files\Filesystem;
+use OC\SystemConfig;
use OCA\Files_Sharing\DeleteOrphanedSharesJob;
+use OCP\App\IAppManager;
+use OCP\Constants;
+use OCP\IDBConnection;
+use OCP\IUserManager;
+use OCP\Server;
use OCP\Share\IShare;
/**
@@ -48,7 +36,7 @@ class DeleteOrphanedSharesJobTest extends \Test\TestCase {
private $job;
/**
- * @var \OCP\IDBConnection
+ * @var IDBConnection
*/
private $connection;
@@ -63,43 +51,43 @@ class DeleteOrphanedSharesJobTest extends \Test\TestCase {
private $user2;
public static function setUpBeforeClass(): void {
- $appManager = \OC::$server->getAppManager();
+ $appManager = Server::get(IAppManager::class);
self::$trashBinStatus = $appManager->isEnabledForUser('files_trashbin');
$appManager->disableApp('files_trashbin');
// just in case...
- \OC\Files\Filesystem::getLoader()->removeStorageWrapper('oc_trashbin');
+ Filesystem::getLoader()->removeStorageWrapper('oc_trashbin');
}
public static function tearDownAfterClass(): void {
if (self::$trashBinStatus) {
- \OC::$server->getAppManager()->enableApp('files_trashbin');
+ Server::get(IAppManager::class)->enableApp('files_trashbin');
}
}
protected function setUp(): void {
parent::setUp();
- $this->connection = \OC::$server->getDatabaseConnection();
+ $this->connection = Server::get(IDBConnection::class);
// clear occasional leftover shares from other tests
$this->connection->executeUpdate('DELETE FROM `*PREFIX*share`');
$this->user1 = $this->getUniqueID('user1_');
$this->user2 = $this->getUniqueID('user2_');
- $userManager = \OC::$server->getUserManager();
+ $userManager = Server::get(IUserManager::class);
$userManager->createUser($this->user1, 'pass');
$userManager->createUser($this->user2, 'pass');
- \OC::registerShareHooks(\OC::$server->getSystemConfig());
+ \OC::registerShareHooks(Server::get(SystemConfig::class));
- $this->job = \OCP\Server::get(DeleteOrphanedSharesJob::class);
+ $this->job = Server::get(DeleteOrphanedSharesJob::class);
}
protected function tearDown(): void {
$this->connection->executeUpdate('DELETE FROM `*PREFIX*share`');
- $userManager = \OC::$server->getUserManager();
+ $userManager = Server::get(IUserManager::class);
$user1 = $userManager->get($this->user1);
if ($user1) {
$user1->delete();
@@ -127,19 +115,19 @@ class DeleteOrphanedSharesJobTest extends \Test\TestCase {
/**
* Test clearing orphaned shares
*/
- public function testClearShares() {
+ public function testClearShares(): void {
$this->loginAsUser($this->user1);
$user1Folder = \OC::$server->getUserFolder($this->user1);
$testFolder = $user1Folder->newFolder('test');
$testSubFolder = $testFolder->newFolder('sub');
- $shareManager = \OC::$server->getShareManager();
+ $shareManager = Server::get(\OCP\Share\IManager::class);
$share = $shareManager->newShare();
$share->setNode($testSubFolder)
->setShareType(IShare::TYPE_USER)
- ->setPermissions(\OCP\Constants::PERMISSION_READ)
+ ->setPermissions(Constants::PERMISSION_READ)
->setSharedWith($this->user2)
->setSharedBy($this->user1);
diff --git a/apps/files_sharing/tests/EncryptedSizePropagationTest.php b/apps/files_sharing/tests/EncryptedSizePropagationTest.php
index 37eec01b9d7..1be17df3957 100644
--- a/apps/files_sharing/tests/EncryptedSizePropagationTest.php
+++ b/apps/files_sharing/tests/EncryptedSizePropagationTest.php
@@ -1,29 +1,15 @@
<?php
+
/**
- * @copyright Copyright (c) 2016, ownCloud, Inc.
- *
- * @author Bjoern Schiessle <bjoern@schiessle.org>
- * @author Joas Schilling <coding@schilljs.com>
- * @author Robin Appelman <robin@icewind.nl>
- *
- * @license AGPL-3.0
- *
- * This code is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License, version 3,
- * as published by the Free Software Foundation.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU Affero General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License, version 3,
- * along with this program. If not, see <http://www.gnu.org/licenses/>
- *
+ * SPDX-FileCopyrightText: 2017-2024 Nextcloud GmbH and Nextcloud contributors
+ * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
+ * SPDX-License-Identifier: AGPL-3.0-only
*/
namespace OCA\Files_Sharing\Tests;
use OC\Files\View;
+use OCP\ITempManager;
+use OCP\Server;
use Test\Traits\EncryptionTrait;
/**
@@ -32,13 +18,27 @@ use Test\Traits\EncryptionTrait;
class EncryptedSizePropagationTest extends SizePropagationTest {
use EncryptionTrait;
+ protected function setUp(): void {
+ parent::setUp();
+ $this->config->setAppValue('encryption', 'useMasterKey', '0');
+ }
+
protected function setupUser($name, $password = '') {
$this->createUser($name, $password);
- $tmpFolder = \OC::$server->getTempManager()->getTemporaryFolder();
- $this->registerMount($name, '\OC\Files\Storage\Local', '/' . $name, ['datadir' => $tmpFolder]);
- $this->config->setAppValue('encryption', 'useMasterKey', '0');
+ $this->registerMountForUser($name);
$this->setupForUser($name, $password);
$this->loginWithEncryption($name);
return new View('/' . $name . '/files');
}
+
+ private function registerMountForUser($user): void {
+ $tmpFolder = Server::get(ITempManager::class)->getTemporaryFolder();
+ $this->registerMount($user, '\OC\Files\Storage\Local', '/' . $user, ['datadir' => $tmpFolder]);
+ }
+
+ protected function loginHelper($user, $create = false, $password = false) {
+ $this->registerMountForUser($user);
+ $this->setupForUser($user, $password);
+ parent::loginHelper($user, $create, $password);
+ }
}
diff --git a/apps/files_sharing/tests/EtagPropagationTest.php b/apps/files_sharing/tests/EtagPropagationTest.php
index 77149ae388e..d8580ea92d5 100644
--- a/apps/files_sharing/tests/EtagPropagationTest.php
+++ b/apps/files_sharing/tests/EtagPropagationTest.php
@@ -1,35 +1,17 @@
<?php
+
/**
- * @copyright Copyright (c) 2016, ownCloud, Inc.
- *
- * @author Christoph Wurst <christoph@winzerhof-wurst.at>
- * @author Joas Schilling <coding@schilljs.com>
- * @author Jörn Friedrich Dreyer <jfd@butonic.de>
- * @author Lukas Reschke <lukas@statuscode.ch>
- * @author Robin Appelman <robin@icewind.nl>
- * @author Roeland Jago Douma <roeland@famdouma.nl>
- * @author Thomas Müller <thomas.mueller@tmit.eu>
- * @author Vincent Petry <vincent@nextcloud.com>
- *
- * @license AGPL-3.0
- *
- * This code is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License, version 3,
- * as published by the Free Software Foundation.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU Affero General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License, version 3,
- * along with this program. If not, see <http://www.gnu.org/licenses/>
- *
+ * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
+ * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
+ * SPDX-License-Identifier: AGPL-3.0-only
*/
namespace OCA\Files_Sharing\Tests;
use OC\Files\Filesystem;
use OC\Files\View;
+use OCP\Constants;
+use OCP\Files\IRootFolder;
+use OCP\Server;
use OCP\Share\IShare;
/**
@@ -54,8 +36,8 @@ class EtagPropagationTest extends PropagationTestCase {
$this->fileIds[self::TEST_FILES_SHARING_API_USER3] = [];
$this->fileIds[self::TEST_FILES_SHARING_API_USER4] = [];
- $rootFolder = \OC::$server->getRootFolder();
- $shareManager = \OC::$server->getShareManager();
+ $rootFolder = Server::get(IRootFolder::class);
+ $shareManager = Server::get(\OCP\Share\IManager::class);
$this->rootView = new View('');
$this->loginAsUser(self::TEST_FILES_SHARING_API_USER1);
@@ -78,7 +60,7 @@ class EtagPropagationTest extends PropagationTestCase {
->setShareType(IShare::TYPE_USER)
->setSharedWith(self::TEST_FILES_SHARING_API_USER2)
->setSharedBy(self::TEST_FILES_SHARING_API_USER1)
- ->setPermissions(\OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_SHARE);
+ ->setPermissions(Constants::PERMISSION_READ | Constants::PERMISSION_UPDATE | Constants::PERMISSION_SHARE);
$share = $shareManager->createShare($share);
$this->shareManager->acceptShare($share, self::TEST_FILES_SHARING_API_USER2);
$node = $rootFolder->getUserFolder(self::TEST_FILES_SHARING_API_USER1)
@@ -89,7 +71,7 @@ class EtagPropagationTest extends PropagationTestCase {
->setShareType(IShare::TYPE_USER)
->setSharedWith(self::TEST_FILES_SHARING_API_USER2)
->setSharedBy(self::TEST_FILES_SHARING_API_USER1)
- ->setPermissions(\OCP\Constants::PERMISSION_ALL);
+ ->setPermissions(Constants::PERMISSION_ALL);
$share = $shareManager->createShare($share);
$this->shareManager->acceptShare($share, self::TEST_FILES_SHARING_API_USER2);
@@ -98,7 +80,7 @@ class EtagPropagationTest extends PropagationTestCase {
->setShareType(IShare::TYPE_USER)
->setSharedWith(self::TEST_FILES_SHARING_API_USER3)
->setSharedBy(self::TEST_FILES_SHARING_API_USER1)
- ->setPermissions(\OCP\Constants::PERMISSION_ALL);
+ ->setPermissions(Constants::PERMISSION_ALL);
$share = $shareManager->createShare($share);
$this->shareManager->acceptShare($share, self::TEST_FILES_SHARING_API_USER3);
@@ -112,7 +94,7 @@ class EtagPropagationTest extends PropagationTestCase {
->setShareType(IShare::TYPE_USER)
->setSharedWith(self::TEST_FILES_SHARING_API_USER2)
->setSharedBy(self::TEST_FILES_SHARING_API_USER1)
- ->setPermissions(\OCP\Constants::PERMISSION_ALL);
+ ->setPermissions(Constants::PERMISSION_ALL);
$share = $shareManager->createShare($share);
$this->shareManager->acceptShare($share, self::TEST_FILES_SHARING_API_USER2);
@@ -139,7 +121,7 @@ class EtagPropagationTest extends PropagationTestCase {
->setShareType(IShare::TYPE_USER)
->setSharedWith(self::TEST_FILES_SHARING_API_USER4)
->setSharedBy(self::TEST_FILES_SHARING_API_USER2)
- ->setPermissions(\OCP\Constants::PERMISSION_ALL);
+ ->setPermissions(Constants::PERMISSION_ALL);
$share = $shareManager->createShare($share);
$this->shareManager->acceptShare($share, self::TEST_FILES_SHARING_API_USER4);
@@ -153,7 +135,7 @@ class EtagPropagationTest extends PropagationTestCase {
->setShareType(IShare::TYPE_USER)
->setSharedWith(self::TEST_FILES_SHARING_API_USER4)
->setSharedBy(self::TEST_FILES_SHARING_API_USER2)
- ->setPermissions(\OCP\Constants::PERMISSION_ALL);
+ ->setPermissions(Constants::PERMISSION_ALL);
$share = $shareManager->createShare($share);
$this->shareManager->acceptShare($share, self::TEST_FILES_SHARING_API_USER4);
@@ -193,7 +175,7 @@ class EtagPropagationTest extends PropagationTestCase {
}
}
- public function testOwnerWritesToShare() {
+ public function testOwnerWritesToShare(): void {
$this->loginAsUser(self::TEST_FILES_SHARING_API_USER1);
Filesystem::file_put_contents('/sub1/sub2/folder/asd.txt', 'bar');
$this->assertEtagsNotChanged([self::TEST_FILES_SHARING_API_USER4]);
@@ -203,7 +185,7 @@ class EtagPropagationTest extends PropagationTestCase {
$this->assertAllUnchanged();
}
- public function testOwnerWritesToSingleFileShare() {
+ public function testOwnerWritesToSingleFileShare(): void {
$this->loginAsUser(self::TEST_FILES_SHARING_API_USER1);
Filesystem::file_put_contents('/foo.txt', 'longer_bar');
$t = (int)Filesystem::filemtime('/foo.txt') - 1;
@@ -214,7 +196,7 @@ class EtagPropagationTest extends PropagationTestCase {
$this->assertAllUnchanged();
}
- public function testOwnerWritesToShareWithReshare() {
+ public function testOwnerWritesToShareWithReshare(): void {
$this->loginAsUser(self::TEST_FILES_SHARING_API_USER1);
Filesystem::file_put_contents('/sub1/sub2/folder/inside/bar.txt', 'bar');
$this->assertEtagsForFoldersChanged([self::TEST_FILES_SHARING_API_USER1, self::TEST_FILES_SHARING_API_USER2,
@@ -223,7 +205,7 @@ class EtagPropagationTest extends PropagationTestCase {
$this->assertAllUnchanged();
}
- public function testOwnerRenameInShare() {
+ public function testOwnerRenameInShare(): void {
$this->loginAsUser(self::TEST_FILES_SHARING_API_USER1);
$this->assertEtagsNotChanged([self::TEST_FILES_SHARING_API_USER4]);
Filesystem::rename('/sub1/sub2/folder/file.txt', '/sub1/sub2/folder/renamed.txt');
@@ -233,7 +215,7 @@ class EtagPropagationTest extends PropagationTestCase {
$this->assertAllUnchanged();
}
- public function testOwnerRenameInReShare() {
+ public function testOwnerRenameInReShare(): void {
$this->loginAsUser(self::TEST_FILES_SHARING_API_USER1);
Filesystem::rename('/sub1/sub2/folder/inside/file.txt', '/sub1/sub2/folder/inside/renamed.txt');
$this->assertEtagsForFoldersChanged([self::TEST_FILES_SHARING_API_USER1, self::TEST_FILES_SHARING_API_USER2,
@@ -242,7 +224,7 @@ class EtagPropagationTest extends PropagationTestCase {
$this->assertAllUnchanged();
}
- public function testOwnerRenameIntoReShare() {
+ public function testOwnerRenameIntoReShare(): void {
$this->loginAsUser(self::TEST_FILES_SHARING_API_USER1);
Filesystem::rename('/sub1/sub2/folder/file.txt', '/sub1/sub2/folder/inside/renamed.txt');
$this->assertEtagsForFoldersChanged([self::TEST_FILES_SHARING_API_USER1, self::TEST_FILES_SHARING_API_USER2,
@@ -251,7 +233,7 @@ class EtagPropagationTest extends PropagationTestCase {
$this->assertAllUnchanged();
}
- public function testOwnerRenameOutOfReShare() {
+ public function testOwnerRenameOutOfReShare(): void {
$this->loginAsUser(self::TEST_FILES_SHARING_API_USER1);
Filesystem::rename('/sub1/sub2/folder/inside/file.txt', '/sub1/sub2/folder/renamed.txt');
$this->assertEtagsForFoldersChanged([self::TEST_FILES_SHARING_API_USER1, self::TEST_FILES_SHARING_API_USER2,
@@ -260,7 +242,7 @@ class EtagPropagationTest extends PropagationTestCase {
$this->assertAllUnchanged();
}
- public function testOwnerDeleteInShare() {
+ public function testOwnerDeleteInShare(): void {
$this->loginAsUser(self::TEST_FILES_SHARING_API_USER1);
Filesystem::unlink('/sub1/sub2/folder/file.txt');
$this->assertEtagsNotChanged([self::TEST_FILES_SHARING_API_USER4]);
@@ -270,7 +252,7 @@ class EtagPropagationTest extends PropagationTestCase {
$this->assertAllUnchanged();
}
- public function testOwnerDeleteInReShare() {
+ public function testOwnerDeleteInReShare(): void {
$this->loginAsUser(self::TEST_FILES_SHARING_API_USER1);
Filesystem::unlink('/sub1/sub2/folder/inside/file.txt');
$this->assertEtagsForFoldersChanged([self::TEST_FILES_SHARING_API_USER1, self::TEST_FILES_SHARING_API_USER2,
@@ -279,13 +261,13 @@ class EtagPropagationTest extends PropagationTestCase {
$this->assertAllUnchanged();
}
- public function testOwnerUnshares() {
+ public function testOwnerUnshares(): void {
$this->loginAsUser(self::TEST_FILES_SHARING_API_USER1);
$folderInfo = $this->rootView->getFileInfo('/' . self::TEST_FILES_SHARING_API_USER1 . '/files/sub1/sub2/folder');
$this->assertInstanceOf('\OC\Files\FileInfo', $folderInfo);
$node = \OC::$server->getUserFolder(self::TEST_FILES_SHARING_API_USER1)->get('/sub1/sub2/folder');
- $shareManager = \OC::$server->getShareManager();
+ $shareManager = Server::get(\OCP\Share\IManager::class);
$shares = $shareManager->getSharesBy(self::TEST_FILES_SHARING_API_USER1, IShare::TYPE_USER, $node, true);
foreach ($shares as $share) {
@@ -302,13 +284,13 @@ class EtagPropagationTest extends PropagationTestCase {
$this->assertAllUnchanged();
}
- public function testOwnerUnsharesFlatReshares() {
+ public function testOwnerUnsharesFlatReshares(): void {
$this->loginAsUser(self::TEST_FILES_SHARING_API_USER1);
$folderInfo = $this->rootView->getFileInfo('/' . self::TEST_FILES_SHARING_API_USER1 . '/files/sub1/sub2/folder/inside');
$this->assertInstanceOf('\OC\Files\FileInfo', $folderInfo);
$node = \OC::$server->getUserFolder(self::TEST_FILES_SHARING_API_USER1)->get('/sub1/sub2/folder/inside');
- $shareManager = \OC::$server->getShareManager();
+ $shareManager = Server::get(\OCP\Share\IManager::class);
$shares = $shareManager->getSharesBy(self::TEST_FILES_SHARING_API_USER1, IShare::TYPE_USER, $node, true);
foreach ($shares as $share) {
@@ -323,7 +305,7 @@ class EtagPropagationTest extends PropagationTestCase {
$this->assertAllUnchanged();
}
- public function testRecipientUnsharesFromSelf() {
+ public function testRecipientUnsharesFromSelf(): void {
$this->loginAsUser(self::TEST_FILES_SHARING_API_USER2);
$ls = $this->rootView->getDirectoryContent('/' . self::TEST_FILES_SHARING_API_USER2 . '/files/sub1/sub2/');
$this->assertTrue(
@@ -337,7 +319,7 @@ class EtagPropagationTest extends PropagationTestCase {
$this->assertAllUnchanged();
}
- public function testRecipientWritesToShare() {
+ public function testRecipientWritesToShare(): void {
$this->loginAsUser(self::TEST_FILES_SHARING_API_USER2);
Filesystem::file_put_contents('/sub1/sub2/folder/asd.txt', 'bar');
$this->assertEtagsNotChanged([self::TEST_FILES_SHARING_API_USER4]);
@@ -350,7 +332,7 @@ class EtagPropagationTest extends PropagationTestCase {
$this->assertAllUnchanged();
}
- public function testRecipientWritesToReshare() {
+ public function testRecipientWritesToReshare(): void {
$this->loginAsUser(self::TEST_FILES_SHARING_API_USER2);
Filesystem::file_put_contents('/sub1/sub2/folder/inside/asd.txt', 'bar');
$this->assertEtagsForFoldersChanged([self::TEST_FILES_SHARING_API_USER1, self::TEST_FILES_SHARING_API_USER2,
@@ -359,7 +341,7 @@ class EtagPropagationTest extends PropagationTestCase {
$this->assertAllUnchanged();
}
- public function testRecipientWritesToOtherRecipientsReshare() {
+ public function testRecipientWritesToOtherRecipientsReshare(): void {
$this->loginAsUser(self::TEST_FILES_SHARING_API_USER3);
Filesystem::file_put_contents('/sub1/sub2/folder/inside/asd.txt', 'bar');
$this->assertEtagsForFoldersChanged([self::TEST_FILES_SHARING_API_USER1, self::TEST_FILES_SHARING_API_USER2,
@@ -368,7 +350,7 @@ class EtagPropagationTest extends PropagationTestCase {
$this->assertAllUnchanged();
}
- public function testRecipientRenameInShare() {
+ public function testRecipientRenameInShare(): void {
$this->loginAsUser(self::TEST_FILES_SHARING_API_USER2);
Filesystem::rename('/sub1/sub2/folder/file.txt', '/sub1/sub2/folder/renamed.txt');
$this->assertEtagsNotChanged([self::TEST_FILES_SHARING_API_USER4]);
@@ -378,7 +360,7 @@ class EtagPropagationTest extends PropagationTestCase {
$this->assertAllUnchanged();
}
- public function testRecipientRenameInReShare() {
+ public function testRecipientRenameInReShare(): void {
$this->loginAsUser(self::TEST_FILES_SHARING_API_USER2);
Filesystem::rename('/sub1/sub2/folder/inside/file.txt', '/sub1/sub2/folder/inside/renamed.txt');
$this->assertEtagsForFoldersChanged([self::TEST_FILES_SHARING_API_USER1, self::TEST_FILES_SHARING_API_USER2,
@@ -387,7 +369,7 @@ class EtagPropagationTest extends PropagationTestCase {
$this->assertAllUnchanged();
}
- public function testRecipientRenameResharedFolder() {
+ public function testRecipientRenameResharedFolder(): void {
$this->loginAsUser(self::TEST_FILES_SHARING_API_USER2);
Filesystem::rename('/directReshare', '/sub1/directReshare');
$this->assertEtagsNotChanged([self::TEST_FILES_SHARING_API_USER1, self::TEST_FILES_SHARING_API_USER3, self::TEST_FILES_SHARING_API_USER4]);
@@ -398,7 +380,7 @@ class EtagPropagationTest extends PropagationTestCase {
$this->assertAllUnchanged();
}
- public function testRecipientDeleteInShare() {
+ public function testRecipientDeleteInShare(): void {
$this->loginAsUser(self::TEST_FILES_SHARING_API_USER2);
Filesystem::unlink('/sub1/sub2/folder/file.txt');
$this->assertEtagsNotChanged([self::TEST_FILES_SHARING_API_USER4]);
@@ -408,7 +390,7 @@ class EtagPropagationTest extends PropagationTestCase {
$this->assertAllUnchanged();
}
- public function testRecipientDeleteInReShare() {
+ public function testRecipientDeleteInReShare(): void {
$this->loginAsUser(self::TEST_FILES_SHARING_API_USER2);
Filesystem::unlink('/sub1/sub2/folder/inside/file.txt');
$this->assertEtagsForFoldersChanged([self::TEST_FILES_SHARING_API_USER1, self::TEST_FILES_SHARING_API_USER2,
@@ -417,7 +399,7 @@ class EtagPropagationTest extends PropagationTestCase {
$this->assertAllUnchanged();
}
- public function testReshareRecipientWritesToReshare() {
+ public function testReshareRecipientWritesToReshare(): void {
$this->loginAsUser(self::TEST_FILES_SHARING_API_USER4);
Filesystem::file_put_contents('/sub1/sub2/inside/asd.txt', 'bar');
$this->assertEtagsForFoldersChanged([self::TEST_FILES_SHARING_API_USER1, self::TEST_FILES_SHARING_API_USER2,
@@ -426,7 +408,7 @@ class EtagPropagationTest extends PropagationTestCase {
$this->assertAllUnchanged();
}
- public function testReshareRecipientRenameInReShare() {
+ public function testReshareRecipientRenameInReShare(): void {
$this->loginAsUser(self::TEST_FILES_SHARING_API_USER4);
Filesystem::rename('/sub1/sub2/inside/file.txt', '/sub1/sub2/inside/renamed.txt');
$this->assertEtagsForFoldersChanged([self::TEST_FILES_SHARING_API_USER1, self::TEST_FILES_SHARING_API_USER2,
@@ -435,7 +417,7 @@ class EtagPropagationTest extends PropagationTestCase {
$this->assertAllUnchanged();
}
- public function testReshareRecipientDeleteInReShare() {
+ public function testReshareRecipientDeleteInReShare(): void {
$this->loginAsUser(self::TEST_FILES_SHARING_API_USER4);
Filesystem::unlink('/sub1/sub2/inside/file.txt');
$this->assertEtagsForFoldersChanged([self::TEST_FILES_SHARING_API_USER1, self::TEST_FILES_SHARING_API_USER2,
@@ -444,7 +426,7 @@ class EtagPropagationTest extends PropagationTestCase {
$this->assertAllUnchanged();
}
- public function testRecipientUploadInDirectReshare() {
+ public function testRecipientUploadInDirectReshare(): void {
$this->loginAsUser(self::TEST_FILES_SHARING_API_USER2);
Filesystem::file_put_contents('/directReshare/test.txt', 'sad');
$this->assertEtagsNotChanged([self::TEST_FILES_SHARING_API_USER3]);
@@ -453,19 +435,19 @@ class EtagPropagationTest extends PropagationTestCase {
$this->assertAllUnchanged();
}
- public function testEtagChangeOnPermissionsChange() {
+ public function testEtagChangeOnPermissionsChange(): void {
$userFolder = $this->rootFolder->getUserFolder(self::TEST_FILES_SHARING_API_USER1);
$node = $userFolder->get('/sub1/sub2/folder');
$shares = $this->shareManager->getSharesBy(self::TEST_FILES_SHARING_API_USER1, IShare::TYPE_USER, $node);
- /** @var \OCP\Share\IShare[] $shares */
- $shares = array_filter($shares, function (\OCP\Share\IShare $share) {
+ /** @var IShare[] $shares */
+ $shares = array_filter($shares, function (IShare $share) {
return $share->getSharedWith() === self::TEST_FILES_SHARING_API_USER2;
});
$this->assertCount(1, $shares);
$share = $shares[0];
- $share->setPermissions(\OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_SHARE);
+ $share->setPermissions(Constants::PERMISSION_READ | Constants::PERMISSION_SHARE);
$this->shareManager->updateShare($share);
$this->assertEtagsForFoldersChanged([self::TEST_FILES_SHARING_API_USER2]);
diff --git a/apps/files_sharing/tests/ExpireSharesJobTest.php b/apps/files_sharing/tests/ExpireSharesJobTest.php
index e12eac5ba06..42bc5a4b659 100644
--- a/apps/files_sharing/tests/ExpireSharesJobTest.php
+++ b/apps/files_sharing/tests/ExpireSharesJobTest.php
@@ -1,32 +1,19 @@
<?php
+
/**
- * @copyright Copyright (c) 2016, ownCloud, Inc.
- *
- * @author Christoph Wurst <christoph@winzerhof-wurst.at>
- * @author Joas Schilling <coding@schilljs.com>
- * @author Morris Jobke <hey@morrisjobke.de>
- * @author Roeland Jago Douma <roeland@famdouma.nl>
- * @author Thomas Müller <thomas.mueller@tmit.eu>
- *
- * @license AGPL-3.0
- *
- * This code is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License, version 3,
- * as published by the Free Software Foundation.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU Affero General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License, version 3,
- * along with this program. If not, see <http://www.gnu.org/licenses/>
- *
+ * SPDX-FileCopyrightText: 2017-2024 Nextcloud GmbH and Nextcloud contributors
+ * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
+ * SPDX-License-Identifier: AGPL-3.0-only
*/
namespace OCA\Files_Sharing\Tests;
+use OC\SystemConfig;
use OCA\Files_Sharing\ExpireSharesJob;
use OCP\AppFramework\Utility\ITimeFactory;
+use OCP\Constants;
+use OCP\IDBConnection;
+use OCP\IUserManager;
+use OCP\Server;
use OCP\Share\IManager;
use OCP\Share\IShare;
@@ -42,7 +29,7 @@ class ExpireSharesJobTest extends \Test\TestCase {
/** @var ExpireSharesJob */
private $job;
- /** @var \OCP\IDBConnection */
+ /** @var IDBConnection */
private $connection;
/** @var string */
@@ -54,26 +41,26 @@ class ExpireSharesJobTest extends \Test\TestCase {
protected function setUp(): void {
parent::setUp();
- $this->connection = \OC::$server->getDatabaseConnection();
+ $this->connection = Server::get(IDBConnection::class);
// clear occasional leftover shares from other tests
$this->connection->executeUpdate('DELETE FROM `*PREFIX*share`');
$this->user1 = $this->getUniqueID('user1_');
$this->user2 = $this->getUniqueID('user2_');
- $userManager = \OC::$server->getUserManager();
+ $userManager = Server::get(IUserManager::class);
$userManager->createUser($this->user1, 'longrandompassword');
$userManager->createUser($this->user2, 'longrandompassword');
- \OC::registerShareHooks(\OC::$server->getSystemConfig());
+ \OC::registerShareHooks(Server::get(SystemConfig::class));
- $this->job = new ExpireSharesJob(\OC::$server->get(ITimeFactory::class), \OC::$server->get(IManager::class), $this->connection);
+ $this->job = new ExpireSharesJob(Server::get(ITimeFactory::class), Server::get(IManager::class), $this->connection);
}
protected function tearDown(): void {
$this->connection->executeUpdate('DELETE FROM `*PREFIX*share`');
- $userManager = \OC::$server->getUserManager();
+ $userManager = Server::get(IUserManager::class);
$user1 = $userManager->get($this->user1);
if ($user1) {
$user1->delete();
@@ -103,7 +90,7 @@ class ExpireSharesJobTest extends \Test\TestCase {
return $shares;
}
- public function dataExpireLinkShare() {
+ public static function dataExpireLinkShare() {
return [
[false, '', false, false],
[false, '', true, false],
@@ -119,25 +106,25 @@ class ExpireSharesJobTest extends \Test\TestCase {
}
/**
- * @dataProvider dataExpireLinkShare
*
* @param bool addExpiration Should we add an expire date
* @param string $interval The dateInterval
* @param bool $addInterval If true add to the current time if false subtract
* @param bool $shouldExpire Should this share be expired
*/
- public function testExpireLinkShare($addExpiration, $interval, $addInterval, $shouldExpire) {
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataExpireLinkShare')]
+ public function testExpireLinkShare($addExpiration, $interval, $addInterval, $shouldExpire): void {
$this->loginAsUser($this->user1);
$user1Folder = \OC::$server->getUserFolder($this->user1);
$testFolder = $user1Folder->newFolder('test');
- $shareManager = \OC::$server->getShareManager();
+ $shareManager = Server::get(\OCP\Share\IManager::class);
$share = $shareManager->newShare();
$share->setNode($testFolder)
->setShareType(IShare::TYPE_LINK)
- ->setPermissions(\OCP\Constants::PERMISSION_READ)
+ ->setPermissions(Constants::PERMISSION_READ)
->setSharedBy($this->user1);
$shareManager->createShare($share);
@@ -183,18 +170,18 @@ class ExpireSharesJobTest extends \Test\TestCase {
}
}
- public function testDoNotExpireOtherShares() {
+ public function testDoNotExpireOtherShares(): void {
$this->loginAsUser($this->user1);
$user1Folder = \OC::$server->getUserFolder($this->user1);
$testFolder = $user1Folder->newFolder('test');
- $shareManager = \OC::$server->getShareManager();
+ $shareManager = Server::get(\OCP\Share\IManager::class);
$share = $shareManager->newShare();
$share->setNode($testFolder)
->setShareType(IShare::TYPE_USER)
- ->setPermissions(\OCP\Constants::PERMISSION_READ)
+ ->setPermissions(Constants::PERMISSION_READ)
->setSharedBy($this->user1)
->setSharedWith($this->user2);
diff --git a/apps/files_sharing/tests/External/CacheTest.php b/apps/files_sharing/tests/External/CacheTest.php
index c77012c3e44..39e2057a24c 100644
--- a/apps/files_sharing/tests/External/CacheTest.php
+++ b/apps/files_sharing/tests/External/CacheTest.php
@@ -1,37 +1,20 @@
<?php
+
/**
- * @copyright Copyright (c) 2016, ownCloud, Inc.
- *
- * @author Arthur Schiwon <blizzz@arthur-schiwon.de>
- * @author Christoph Wurst <christoph@winzerhof-wurst.at>
- * @author Joas Schilling <coding@schilljs.com>
- * @author Robin Appelman <robin@icewind.nl>
- * @author Roeland Jago Douma <roeland@famdouma.nl>
- * @author Thomas Müller <thomas.mueller@tmit.eu>
- * @author Vincent Petry <vincent@nextcloud.com>
- *
- * @license AGPL-3.0
- *
- * This code is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License, version 3,
- * as published by the Free Software Foundation.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU Affero General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License, version 3,
- * along with this program. If not, see <http://www.gnu.org/licenses/>
- *
+ * SPDX-FileCopyrightText: 2017-2024 Nextcloud GmbH and Nextcloud contributors
+ * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
+ * SPDX-License-Identifier: AGPL-3.0-only
*/
namespace OCA\Files_Sharing\Tests\External;
use OC\Federation\CloudIdManager;
+use OC\Files\Storage\Storage;
+use OCA\Files_Sharing\External\Cache;
use OCA\Files_Sharing\Tests\TestCase;
use OCP\Contacts\IManager;
use OCP\EventDispatcher\IEventDispatcher;
use OCP\Federation\ICloudIdManager;
+use OCP\Files\Cache\ICacheEntry;
use OCP\ICacheFactory;
use OCP\IURLGenerator;
use OCP\IUserManager;
@@ -48,12 +31,12 @@ class CacheTest extends TestCase {
protected $contactsManager;
/**
- * @var \OC\Files\Storage\Storage
+ * @var Storage
**/
private $storage;
/**
- * @var \OCA\Files_Sharing\External\Cache
+ * @var Cache
*/
private $cache;
@@ -62,7 +45,7 @@ class CacheTest extends TestCase {
*/
private $remoteUser;
- /** @var ICloudIdManager */
+ /** @var ICloudIdManager */
private $cloudIdManager;
protected function setUp(): void {
@@ -71,11 +54,11 @@ class CacheTest extends TestCase {
$this->contactsManager = $this->createMock(IManager::class);
$this->cloudIdManager = new CloudIdManager(
+ $this->createMock(ICacheFactory::class),
+ $this->createMock(IEventDispatcher::class),
$this->contactsManager,
$this->createMock(IURLGenerator::class),
$this->createMock(IUserManager::class),
- $this->createMock(ICacheFactory::class),
- $this->createMock(IEventDispatcher::class)
);
$this->remoteUser = $this->getUniqueID('remoteuser');
@@ -91,10 +74,11 @@ class CacheTest extends TestCase {
->method('search')
->willReturn([]);
- $this->cache = new \OCA\Files_Sharing\External\Cache(
+ $this->cache = new Cache(
$this->storage,
$this->cloudIdManager->getCloudId($this->remoteUser, 'http://example.com/owncloud')
);
+ $this->cache->insert('', ['size' => 0, 'mtime' => 0, 'mimetype' => ICacheEntry::DIRECTORY_MIMETYPE]);
$this->cache->put(
'test.txt',
[
@@ -112,7 +96,7 @@ class CacheTest extends TestCase {
parent::tearDown();
}
- public function testGetInjectsOwnerDisplayName() {
+ public function testGetInjectsOwnerDisplayName(): void {
$info = $this->cache->get('test.txt');
$this->assertEquals(
$this->remoteUser . '@example.com/owncloud',
@@ -120,12 +104,12 @@ class CacheTest extends TestCase {
);
}
- public function testGetReturnsFalseIfNotFound() {
+ public function testGetReturnsFalseIfNotFound(): void {
$info = $this->cache->get('unexisting-entry.txt');
$this->assertFalse($info);
}
- public function testGetFolderPopulatesOwner() {
+ public function testGetFolderPopulatesOwner(): void {
$dirId = $this->cache->put(
'subdir',
[
diff --git a/apps/files_sharing/tests/External/ManagerTest.php b/apps/files_sharing/tests/External/ManagerTest.php
index 0e80479eafe..14c6afec4d8 100644
--- a/apps/files_sharing/tests/External/ManagerTest.php
+++ b/apps/files_sharing/tests/External/ManagerTest.php
@@ -1,32 +1,9 @@
<?php
+
/**
- * @copyright Copyright (c) 2016, ownCloud, Inc.
- *
- * @author Arthur Schiwon <blizzz@arthur-schiwon.de>
- * @author Bjoern Schiessle <bjoern@schiessle.org>
- * @author Christoph Wurst <christoph@winzerhof-wurst.at>
- * @author Daniel Kesselberg <mail@danielkesselberg.de>
- * @author Joas Schilling <coding@schilljs.com>
- * @author Julius Härtl <jus@bitgrid.net>
- * @author Morris Jobke <hey@morrisjobke.de>
- * @author Robin Appelman <robin@icewind.nl>
- * @author Roeland Jago Douma <roeland@famdouma.nl>
- * @author Thomas Müller <thomas.mueller@tmit.eu>
- *
- * @license AGPL-3.0
- *
- * This code is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License, version 3,
- * as published by the Free Software Foundation.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU Affero General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License, version 3,
- * along with this program. If not, see <http://www.gnu.org/licenses/>
- *
+ * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
+ * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
+ * SPDX-License-Identifier: AGPL-3.0-only
*/
namespace OCA\Files_Sharing\Tests\External;
@@ -43,16 +20,21 @@ use OCP\EventDispatcher\IEventDispatcher;
use OCP\Federation\ICloudFederationFactory;
use OCP\Federation\ICloudFederationProviderManager;
use OCP\Files\NotFoundException;
+use OCP\Http\Client\IClient;
use OCP\Http\Client\IClientService;
use OCP\Http\Client\IResponse;
use OCP\ICacheFactory;
+use OCP\IDBConnection;
use OCP\IGroup;
use OCP\IGroupManager;
use OCP\IURLGenerator;
use OCP\IUser;
use OCP\IUserManager;
use OCP\IUserSession;
+use OCP\OCS\IDiscoveryService;
+use OCP\Server;
use OCP\Share\IShare;
+use PHPUnit\Framework\MockObject\MockObject;
use Psr\Log\LoggerInterface;
use Test\Traits\UserTrait;
@@ -66,42 +48,19 @@ use Test\Traits\UserTrait;
class ManagerTest extends TestCase {
use UserTrait;
- /** @var IManager|\PHPUnit\Framework\MockObject\MockObject */
- protected $contactsManager;
-
- /** @var Manager|\PHPUnit\Framework\MockObject\MockObject **/
- private $manager;
-
- /** @var \OC\Files\Mount\Manager */
- private $mountManager;
-
- /** @var IClientService|\PHPUnit\Framework\MockObject\MockObject */
- private $clientService;
-
- /** @var ICloudFederationProviderManager|\PHPUnit\Framework\MockObject\MockObject */
- private $cloudFederationProviderManager;
-
- /** @var ICloudFederationFactory|\PHPUnit\Framework\MockObject\MockObject */
- private $cloudFederationFactory;
-
- /** @var \PHPUnit\Framework\MockObject\MockObject|IGroupManager */
- private $groupManager;
-
- /** @var \PHPUnit\Framework\MockObject\MockObject|IUserManager */
- private $userManager;
-
- /** @var LoggerInterface */
- private $logger;
-
- private $uid;
-
- /**
- * @var \OCP\IUser
- */
- private $user;
- private $testMountProvider;
- /** @var IEventDispatcher|\PHPUnit\Framework\MockObject\MockObject */
- private $eventDispatcher;
+ protected string $uid;
+ protected IUser $user;
+ protected MountProvider $testMountProvider;
+ protected IEventDispatcher&MockObject $eventDispatcher;
+ protected LoggerInterface&MockObject $logger;
+ protected \OC\Files\Mount\Manager $mountManager;
+ protected IManager&MockObject $contactsManager;
+ protected Manager&MockObject $manager;
+ protected IClientService&MockObject $clientService;
+ protected ICloudFederationProviderManager&MockObject $cloudFederationProviderManager;
+ protected ICloudFederationFactory&MockObject $cloudFederationFactory;
+ protected IGroupManager&MockObject $groupManager;
+ protected IUserManager&MockObject $userManager;
protected function setUp(): void {
parent::setUp();
@@ -128,14 +87,14 @@ class ManagerTest extends TestCase {
$this->manager = $this->createManagerForUser($this->uid);
- $this->testMountProvider = new MountProvider(\OC::$server->getDatabaseConnection(), function () {
+ $this->testMountProvider = new MountProvider(Server::get(IDBConnection::class), function () {
return $this->manager;
}, new CloudIdManager(
+ $this->createMock(ICacheFactory::class),
+ $this->createMock(IEventDispatcher::class),
$this->contactsManager,
$this->createMock(IURLGenerator::class),
$this->userManager,
- $this->createMock(ICacheFactory::class),
- $this->createMock(IEventDispatcher::class)
));
$group1 = $this->createMock(IGroup::class);
@@ -149,15 +108,15 @@ class ManagerTest extends TestCase {
$this->userManager->expects($this->any())->method('get')->willReturn($this->user);
$this->groupManager->expects($this->any())->method(('getUserGroups'))->willReturn([$group1, $group2]);
$this->groupManager->expects($this->any())->method(('get'))
- ->will($this->returnValueMap([
+ ->willReturnMap([
['group1', $group1],
['group2', $group2],
- ]));
+ ]);
}
protected function tearDown(): void {
// clear the share external table to avoid side effects
- $query = \OC::$server->getDatabaseConnection()->prepare('DELETE FROM `*PREFIX*share_external`');
+ $query = Server::get(IDBConnection::class)->prepare('DELETE FROM `*PREFIX*share_external`');
$result = $query->execute();
$result->closeCursor();
@@ -175,12 +134,12 @@ class ManagerTest extends TestCase {
return $this->getMockBuilder(Manager::class)
->setConstructorArgs(
[
- \OC::$server->getDatabaseConnection(),
+ Server::get(IDBConnection::class),
$this->mountManager,
new StorageFactory(),
$this->clientService,
- \OC::$server->getNotificationManager(),
- \OC::$server->query(\OCP\OCS\IDiscoveryService::class),
+ Server::get(\OCP\Notification\IManager::class),
+ Server::get(IDiscoveryService::class),
$this->cloudFederationProviderManager,
$this->cloudFederationFactory,
$this->groupManager,
@@ -189,7 +148,7 @@ class ManagerTest extends TestCase {
$this->eventDispatcher,
$this->logger,
]
- )->setMethods(['tryOCMEndPoint'])->getMock();
+ )->onlyMethods(['tryOCMEndPoint'])->getMock();
}
private function setupMounts() {
@@ -205,7 +164,7 @@ class ManagerTest extends TestCase {
$this->mountManager->addMount(new MountPoint(Temporary::class, '', []));
}
- public function testAddUserShare() {
+ public function testAddUserShare(): void {
$this->doTestAddShare([
'remote' => 'http://localhost',
'token' => 'token1',
@@ -219,7 +178,7 @@ class ManagerTest extends TestCase {
], false);
}
- public function testAddGroupShare() {
+ public function testAddGroupShare(): void {
$this->doTestAddShare([
'remote' => 'http://localhost',
'token' => 'token1',
@@ -242,14 +201,12 @@ class ManagerTest extends TestCase {
if ($isGroup) {
$this->manager->expects($this->never())->method('tryOCMEndPoint');
} else {
- $this->manager->method('tryOCMEndPoint')
- ->withConsecutive(
- ['http://localhost', 'token1', '2342', 'accept'],
- ['http://localhost', 'token3', '2342', 'decline'],
- )->willReturnOnConsecutiveCalls(
- false,
- false,
- );
+ $this->manager->expects(self::atLeast(2))
+ ->method('tryOCMEndPoint')
+ ->willReturnMap([
+ ['http://localhost', 'token1', '2342', 'accept', false],
+ ['http://localhost', 'token3', '2342', 'decline', false],
+ ]);
}
// Add a share for "user"
@@ -275,12 +232,18 @@ class ManagerTest extends TestCase {
$this->assertNotMount('{{TemporaryMountPointName#' . $shareData1['name'] . '}}');
$this->assertNotMount('{{TemporaryMountPointName#' . $shareData1['name'] . '}}-1');
+ $newClientCalls = [];
+ $this->clientService
+ ->method('newClient')
+ ->willReturnCallback(function () use (&$newClientCalls): IClient {
+ if (!empty($newClientCalls)) {
+ return array_shift($newClientCalls);
+ }
+ return $this->createMock(IClient::class);
+ });
if (!$isGroup) {
- $client = $this->getMockBuilder('OCP\Http\Client\IClient')
- ->disableOriginalConstructor()->getMock();
- $this->clientService->expects($this->at(0))
- ->method('newClient')
- ->willReturn($client);
+ $client = $this->createMock(IClient::class);
+ $newClientCalls[] = $client;
$response = $this->createMock(IResponse::class);
$response->method('getBody')
->willReturn(json_encode([
@@ -332,11 +295,8 @@ class ManagerTest extends TestCase {
$this->assertNotMount('{{TemporaryMountPointName#' . $shareData1['name'] . '}}-1');
if (!$isGroup) {
- $client = $this->getMockBuilder('OCP\Http\Client\IClient')
- ->disableOriginalConstructor()->getMock();
- $this->clientService->expects($this->at(0))
- ->method('newClient')
- ->willReturn($client);
+ $client = $this->createMock(IClient::class);
+ $newClientCalls[] = $client;
$response = $this->createMock(IResponse::class);
$response->method('getBody')
->willReturn(json_encode([
@@ -388,16 +348,10 @@ class ManagerTest extends TestCase {
// no http requests here
$this->manager->removeGroupShares('group1');
} else {
- $client1 = $this->getMockBuilder('OCP\Http\Client\IClient')
- ->disableOriginalConstructor()->getMock();
- $client2 = $this->getMockBuilder('OCP\Http\Client\IClient')
- ->disableOriginalConstructor()->getMock();
- $this->clientService->expects($this->exactly(2))
- ->method('newClient')
- ->willReturnOnConsecutiveCalls(
- $client1,
- $client2,
- );
+ $client1 = $this->createMock(IClient::class);
+ $client2 = $this->createMock(IClient::class);
+ $newClientCalls[] = $client1;
+ $newClientCalls[] = $client2;
$response = $this->createMock(IResponse::class);
$response->method('getBody')
->willReturn(json_encode([
@@ -498,7 +452,7 @@ class ManagerTest extends TestCase {
return [$shareData, $groupShare];
}
- public function testAcceptOriginalGroupShare() {
+ public function testAcceptOriginalGroupShare(): void {
[$shareData, $groupShare] = $this->createTestGroupShare();
$this->assertTrue($this->manager->acceptShare($groupShare['id']));
$this->verifyAcceptedGroupShare($shareData);
@@ -508,7 +462,7 @@ class ManagerTest extends TestCase {
$this->verifyAcceptedGroupShare($shareData);
}
- public function testAcceptGroupShareAgainThroughGroupShare() {
+ public function testAcceptGroupShareAgainThroughGroupShare(): void {
[$shareData, $groupShare] = $this->createTestGroupShare();
$this->assertTrue($this->manager->acceptShare($groupShare['id']));
$this->verifyAcceptedGroupShare($shareData);
@@ -530,7 +484,7 @@ class ManagerTest extends TestCase {
$this->verifyAcceptedGroupShare($shareData, '/SharedFolder');
}
- public function testAcceptGroupShareAgainThroughSubShare() {
+ public function testAcceptGroupShareAgainThroughSubShare(): void {
[$shareData, $groupShare] = $this->createTestGroupShare();
$this->assertTrue($this->manager->acceptShare($groupShare['id']));
$this->verifyAcceptedGroupShare($shareData);
@@ -552,7 +506,7 @@ class ManagerTest extends TestCase {
$this->verifyAcceptedGroupShare($shareData);
}
- public function testDeclineOriginalGroupShare() {
+ public function testDeclineOriginalGroupShare(): void {
[$shareData, $groupShare] = $this->createTestGroupShare();
$this->assertTrue($this->manager->declineShare($groupShare['id']));
$this->verifyDeclinedGroupShare($shareData);
@@ -562,7 +516,7 @@ class ManagerTest extends TestCase {
$this->verifyDeclinedGroupShare($shareData);
}
- public function testDeclineGroupShareAgainThroughGroupShare() {
+ public function testDeclineGroupShareAgainThroughGroupShare(): void {
[$shareData, $groupShare] = $this->createTestGroupShare();
$this->assertTrue($this->manager->acceptShare($groupShare['id']));
$this->verifyAcceptedGroupShare($shareData);
@@ -576,7 +530,7 @@ class ManagerTest extends TestCase {
$this->verifyDeclinedGroupShare($shareData, '/SharedFolder');
}
- public function testDeclineGroupShareAgainThroughSubshare() {
+ public function testDeclineGroupShareAgainThroughSubshare(): void {
[$shareData, $groupShare] = $this->createTestGroupShare();
$this->assertTrue($this->manager->acceptShare($groupShare['id']));
$this->verifyAcceptedGroupShare($shareData);
@@ -594,7 +548,7 @@ class ManagerTest extends TestCase {
$this->verifyDeclinedGroupShare($shareData, '/SharedFolder');
}
- public function testDeclineGroupShareAgainThroughMountPoint() {
+ public function testDeclineGroupShareAgainThroughMountPoint(): void {
[$shareData, $groupShare] = $this->createTestGroupShare();
$this->assertTrue($this->manager->acceptShare($groupShare['id']));
$this->verifyAcceptedGroupShare($shareData);
@@ -607,7 +561,7 @@ class ManagerTest extends TestCase {
$this->assertFalse($this->manager->removeShare($this->uid . '/files/' . $shareData['name']));
}
- public function testDeclineThenAcceptGroupShareAgainThroughGroupShare() {
+ public function testDeclineThenAcceptGroupShareAgainThroughGroupShare(): void {
[$shareData, $groupShare] = $this->createTestGroupShare();
// decline, this creates a declined sub-share
$this->assertTrue($this->manager->declineShare($groupShare['id']));
@@ -625,7 +579,7 @@ class ManagerTest extends TestCase {
$this->verifyAcceptedGroupShare($shareData, '/SharedFolder');
}
- public function testDeclineThenAcceptGroupShareAgainThroughSubShare() {
+ public function testDeclineThenAcceptGroupShareAgainThroughSubShare(): void {
[$shareData, $groupShare] = $this->createTestGroupShare();
// decline, this creates a declined sub-share
$this->assertTrue($this->manager->declineShare($groupShare['id']));
@@ -643,7 +597,7 @@ class ManagerTest extends TestCase {
$this->verifyAcceptedGroupShare($shareData);
}
- public function testDeleteUserShares() {
+ public function testDeleteUserShares(): void {
// user 1 shares
$shareData = $this->createTestUserShare($this->uid);
@@ -668,10 +622,10 @@ class ManagerTest extends TestCase {
'user' => 'user2',
'remoteId' => '2342'
];
- $this->assertSame(null, call_user_func_array([$manager2, 'addShare'], $shareData2));
- $user2Shares = $manager2->getOpenShares();
- $this->assertCount(2, $user2Shares);
+ $this->assertCount(1, $manager2->getOpenShares());
+ $this->assertSame(null, call_user_func_array([$manager2, 'addShare'], $shareData2));
+ $this->assertCount(2, $manager2->getOpenShares());
$this->manager->expects($this->once())->method('tryOCMEndPoint')->with('http://localhost', 'token1', '2342', 'decline')->willReturn([]);
$this->manager->removeUserShares($this->uid);
@@ -690,7 +644,7 @@ class ManagerTest extends TestCase {
$this->assertEquals($user2Shares[1]['user'], 'user2');
}
- public function testDeleteGroupShares() {
+ public function testDeleteGroupShares(): void {
$shareData = $this->createTestUserShare($this->uid);
[$shareData, $groupShare] = $this->createTestGroupShare();
@@ -713,10 +667,10 @@ class ManagerTest extends TestCase {
'user' => 'user2',
'remoteId' => '2342'
];
- $this->assertSame(null, call_user_func_array([$manager2, 'addShare'], $shareData2));
- $user2Shares = $manager2->getOpenShares();
- $this->assertCount(2, $user2Shares);
+ $this->assertCount(1, $manager2->getOpenShares());
+ $this->assertSame(null, call_user_func_array([$manager2, 'addShare'], $shareData2));
+ $this->assertCount(2, $manager2->getOpenShares());
$this->manager->expects($this->never())->method('tryOCMEndPoint');
$this->manager->removeGroupShares('group1');
@@ -744,7 +698,7 @@ class ManagerTest extends TestCase {
$this->assertEquals($expected['token'], $actual['share_token'], 'Asserting token of a share #' . $share);
$this->assertEquals($expected['name'], $actual['name'], 'Asserting name of a share #' . $share);
$this->assertEquals($expected['owner'], $actual['owner'], 'Asserting owner of a share #' . $share);
- $this->assertEquals($expected['accepted'], (int) $actual['accepted'], 'Asserting accept of a share #' . $share);
+ $this->assertEquals($expected['accepted'], (int)$actual['accepted'], 'Asserting accept of a share #' . $share);
$this->assertEquals($targetEntity, $actual['user'], 'Asserting user of a share #' . $share);
$this->assertEquals($mountPoint, $actual['mountpoint'], 'Asserting mountpoint of a share #' . $share);
}
diff --git a/apps/files_sharing/tests/External/ScannerTest.php b/apps/files_sharing/tests/External/ScannerTest.php
index 8d077715b2d..8b44d47f2b1 100644
--- a/apps/files_sharing/tests/External/ScannerTest.php
+++ b/apps/files_sharing/tests/External/ScannerTest.php
@@ -1,29 +1,15 @@
<?php
+
/**
- * @copyright Copyright (c) 2016, ownCloud, Inc.
- *
- * @author Joas Schilling <coding@schilljs.com>
- * @author Morris Jobke <hey@morrisjobke.de>
- * @author Roeland Jago Douma <roeland@famdouma.nl>
- *
- * @license AGPL-3.0
- *
- * This code is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License, version 3,
- * as published by the Free Software Foundation.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU Affero General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License, version 3,
- * along with this program. If not, see <http://www.gnu.org/licenses/>
- *
+ * SPDX-FileCopyrightText: 2018-2024 Nextcloud GmbH and Nextcloud contributors
+ * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
+ * SPDX-License-Identifier: AGPL-3.0-only
*/
namespace OCA\Files_Sharing\Tests\External;
+use OC\Files\Cache\Cache;
use OCA\Files_Sharing\External\Scanner;
+use OCA\Files_Sharing\External\Storage;
use Test\TestCase;
/**
@@ -31,9 +17,9 @@ use Test\TestCase;
*/
class ScannerTest extends TestCase {
protected Scanner $scanner;
- /** @var \OCA\Files_Sharing\External\Storage|\PHPUnit\Framework\MockObject\MockObject */
+ /** @var Storage|\PHPUnit\Framework\MockObject\MockObject */
protected $storage;
- /** @var \OC\Files\Cache\Cache|\PHPUnit\Framework\MockObject\MockObject */
+ /** @var Cache|\PHPUnit\Framework\MockObject\MockObject */
protected $cache;
protected function setUp(): void {
@@ -52,7 +38,7 @@ class ScannerTest extends TestCase {
$this->scanner = new Scanner($this->storage);
}
- public function testScan() {
+ public function testScan(): void {
$this->storage->expects($this->any())
->method('getShareInfo')
->willReturn(['status' => 'success', 'data' => []]);
@@ -64,7 +50,7 @@ class ScannerTest extends TestCase {
$this->addToAssertionCount(1);
}
- public function testScanFile() {
+ public function testScanFile(): void {
// FIXME add real tests, we are currently only checking for
// Declaration of OCA\Files_Sharing\External\Scanner::*() should be
// compatible with OC\Files\Cache\Scanner::*()
diff --git a/apps/files_sharing/tests/ExternalStorageTest.php b/apps/files_sharing/tests/ExternalStorageTest.php
index d180b06d641..1d9d2eed7bd 100644
--- a/apps/files_sharing/tests/ExternalStorageTest.php
+++ b/apps/files_sharing/tests/ExternalStorageTest.php
@@ -1,34 +1,15 @@
<?php
+
/**
- * @copyright Copyright (c) 2016, ownCloud, Inc.
- *
- * @author Christoph Wurst <christoph@winzerhof-wurst.at>
- * @author Joas Schilling <coding@schilljs.com>
- * @author Lukas Reschke <lukas@statuscode.ch>
- * @author Morris Jobke <hey@morrisjobke.de>
- * @author Robin Appelman <robin@icewind.nl>
- * @author Thomas Müller <thomas.mueller@tmit.eu>
- * @author Vincent Petry <vincent@nextcloud.com>
- *
- * @license AGPL-3.0
- *
- * This code is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License, version 3,
- * as published by the Free Software Foundation.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU Affero General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License, version 3,
- * along with this program. If not, see <http://www.gnu.org/licenses/>
- *
+ * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
+ * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
+ * SPDX-License-Identifier: AGPL-3.0-only
*/
namespace OCA\Files_Sharing\Tests;
use OC\Federation\CloudId;
use OCA\Files_Sharing\External\Manager as ExternalShareManager;
+use OCA\Files_Sharing\External\Storage;
use OCP\Http\Client\IClient;
use OCP\Http\Client\IClientService;
use OCP\Http\Client\IResponse;
@@ -39,7 +20,7 @@ use OCP\Http\Client\IResponse;
* @group DB
*/
class ExternalStorageTest extends \Test\TestCase {
- public function optionsProvider() {
+ public static function optionsProvider() {
return [
[
'http://remoteserver:8080/owncloud',
@@ -107,16 +88,15 @@ class ExternalStorageTest extends \Test\TestCase {
);
}
- /**
- * @dataProvider optionsProvider
- */
- public function testStorageMountOptions($inputUri, $baseUri) {
+ #[\PHPUnit\Framework\Attributes\DataProvider('optionsProvider')]
+ public function testStorageMountOptions($inputUri, $baseUri): void {
$storage = $this->getTestStorage($inputUri);
$this->assertEquals($baseUri, $storage->getBaseUri());
}
- public function testIfTestReturnsTheValue() {
- $result = $this->getTestStorage('https://remoteserver')->test();
+ public function testIfTestReturnsTheValue(): void {
+ $storage = $this->getTestStorage('https://remoteserver');
+ $result = $storage->test();
$this->assertSame(true, $result);
}
}
@@ -124,14 +104,14 @@ class ExternalStorageTest extends \Test\TestCase {
/**
* Dummy subclass to make it possible to access private members
*/
-class TestSharingExternalStorage extends \OCA\Files_Sharing\External\Storage {
+class TestSharingExternalStorage extends Storage {
public function getBaseUri() {
return $this->createBaseUri();
}
- public function stat($path) {
+ public function stat(string $path): array|false {
if ($path === '') {
- return true;
+ return ['key' => 'value'];
}
return parent::stat($path);
}
diff --git a/apps/files_sharing/tests/GroupEtagPropagationTest.php b/apps/files_sharing/tests/GroupEtagPropagationTest.php
index 1a7c075ddf8..da9c7c6bd07 100644
--- a/apps/files_sharing/tests/GroupEtagPropagationTest.php
+++ b/apps/files_sharing/tests/GroupEtagPropagationTest.php
@@ -1,32 +1,15 @@
<?php
+
/**
- * @copyright Copyright (c) 2016, ownCloud, Inc.
- *
- * @author Joas Schilling <coding@schilljs.com>
- * @author Lukas Reschke <lukas@statuscode.ch>
- * @author Robin Appelman <robin@icewind.nl>
- * @author Roeland Jago Douma <roeland@famdouma.nl>
- * @author Vincent Petry <vincent@nextcloud.com>
- *
- * @license AGPL-3.0
- *
- * This code is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License, version 3,
- * as published by the Free Software Foundation.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU Affero General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License, version 3,
- * along with this program. If not, see <http://www.gnu.org/licenses/>
- *
+ * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
+ * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
+ * SPDX-License-Identifier: AGPL-3.0-only
*/
namespace OCA\Files_Sharing\Tests;
use OC\Files\Filesystem;
use OC\Files\View;
+use OCP\Constants;
use OCP\Share\IShare;
/**
@@ -57,7 +40,7 @@ class GroupEtagPropagationTest extends PropagationTestCase {
'/test',
self::TEST_FILES_SHARING_API_USER1,
'group1',
- \OCP\Constants::PERMISSION_ALL
+ Constants::PERMISSION_ALL
);
$this->shareManager->acceptShare($share, self::TEST_FILES_SHARING_API_USER2);
$this->fileIds[self::TEST_FILES_SHARING_API_USER1][''] = $view1->getFileInfo('')->getId();
@@ -72,7 +55,7 @@ class GroupEtagPropagationTest extends PropagationTestCase {
'/test',
self::TEST_FILES_SHARING_API_USER2,
'group2',
- \OCP\Constants::PERMISSION_ALL
+ Constants::PERMISSION_ALL
);
$this->shareManager->acceptShare($share, self::TEST_FILES_SHARING_API_USER3);
$share = $this->share(
@@ -80,7 +63,7 @@ class GroupEtagPropagationTest extends PropagationTestCase {
'/test/sub',
self::TEST_FILES_SHARING_API_USER2,
'group3',
- \OCP\Constants::PERMISSION_ALL
+ Constants::PERMISSION_ALL
);
$this->shareManager->acceptShare($share, self::TEST_FILES_SHARING_API_USER4);
@@ -108,7 +91,7 @@ class GroupEtagPropagationTest extends PropagationTestCase {
}
}
- public function testGroupReShareRecipientWrites() {
+ public function testGroupReShareRecipientWrites(): void {
$this->loginAsUser(self::TEST_FILES_SHARING_API_USER3);
Filesystem::file_put_contents('/test/sub/file.txt', 'asd');
@@ -118,7 +101,7 @@ class GroupEtagPropagationTest extends PropagationTestCase {
$this->assertAllUnchanged();
}
- public function testGroupReShareSubFolderRecipientWrites() {
+ public function testGroupReShareSubFolderRecipientWrites(): void {
$this->loginAsUser(self::TEST_FILES_SHARING_API_USER4);
Filesystem::file_put_contents('/sub/file.txt', 'asd');
@@ -128,7 +111,7 @@ class GroupEtagPropagationTest extends PropagationTestCase {
$this->assertAllUnchanged();
}
- public function testRecipientUnsharesFromSelf() {
+ public function testRecipientUnsharesFromSelf(): void {
$this->loginAsUser(self::TEST_FILES_SHARING_API_USER2);
$this->assertTrue(
$this->rootView->unlink('/' . self::TEST_FILES_SHARING_API_USER2 . '/files/test')
@@ -138,7 +121,7 @@ class GroupEtagPropagationTest extends PropagationTestCase {
$this->assertAllUnchanged();
}
- public function testRecipientUnsharesFromSelfUniqueGroupShare() {
+ public function testRecipientUnsharesFromSelfUniqueGroupShare(): void {
$this->loginAsUser(self::TEST_FILES_SHARING_API_USER2);
// rename to create an extra entry in the share table
$this->rootView->rename('/' . self::TEST_FILES_SHARING_API_USER2 . '/files/test', '/' . self::TEST_FILES_SHARING_API_USER2 . '/files/test_renamed');
diff --git a/apps/files_sharing/tests/HelperTest.php b/apps/files_sharing/tests/HelperTest.php
index 5b8fb2cded1..4d0d747b3e4 100644
--- a/apps/files_sharing/tests/HelperTest.php
+++ b/apps/files_sharing/tests/HelperTest.php
@@ -1,30 +1,17 @@
<?php
+
/**
- * @copyright Copyright (c) 2016, ownCloud, Inc.
- *
- * @author Björn Schießle <bjoern@schiessle.org>
- * @author Joas Schilling <coding@schilljs.com>
- * @author Morris Jobke <hey@morrisjobke.de>
- * @author Roeland Jago Douma <roeland@famdouma.nl>
- * @author Thomas Müller <thomas.mueller@tmit.eu>
- *
- * @license AGPL-3.0
- *
- * This code is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License, version 3,
- * as published by the Free Software Foundation.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU Affero General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License, version 3,
- * along with this program. If not, see <http://www.gnu.org/licenses/>
- *
+ * SPDX-FileCopyrightText: 2017-2024 Nextcloud GmbH and Nextcloud contributors
+ * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
+ * SPDX-License-Identifier: AGPL-3.0-only
*/
namespace OCA\Files_Sharing\Tests;
+use OC\Files\Filesystem;
+use OCA\Files_Sharing\Helper;
+use OCP\IConfig;
+use OCP\Server;
+
/**
* Class HelperTest
*
@@ -35,16 +22,16 @@ class HelperTest extends TestCase {
/**
* test set and get share folder
*/
- public function testSetGetShareFolder() {
- $this->assertSame('/', \OCA\Files_Sharing\Helper::getShareFolder());
+ public function testSetGetShareFolder(): void {
+ $this->assertSame('/', Helper::getShareFolder());
- \OCA\Files_Sharing\Helper::setShareFolder('/Shared/Folder');
+ Helper::setShareFolder('/Shared/Folder');
- $sharedFolder = \OCA\Files_Sharing\Helper::getShareFolder();
- $this->assertSame('/Shared/Folder', \OCA\Files_Sharing\Helper::getShareFolder());
- $this->assertTrue(\OC\Files\Filesystem::is_dir($sharedFolder));
+ $sharedFolder = Helper::getShareFolder();
+ $this->assertSame('/Shared/Folder', Helper::getShareFolder());
+ $this->assertTrue(Filesystem::is_dir($sharedFolder));
// cleanup
- \OC::$server->getConfig()->deleteSystemValue('share_folder');
+ Server::get(IConfig::class)->deleteSystemValue('share_folder');
}
}
diff --git a/apps/files_sharing/tests/Listener/LoadAdditionalListenerTest.php b/apps/files_sharing/tests/Listener/LoadAdditionalListenerTest.php
new file mode 100644
index 00000000000..75bee35d58a
--- /dev/null
+++ b/apps/files_sharing/tests/Listener/LoadAdditionalListenerTest.php
@@ -0,0 +1,120 @@
+<?php
+
+declare(strict_types=1);
+
+/**
+ * SPDX-FileCopyrightText: 2025 Nextcloud GmbH and Nextcloud contributors
+ * SPDX-License-Identifier: AGPL-3.0-or-later
+ */
+
+namespace OCA\Files_Sharing\Tests\Listener;
+
+use OC\InitialStateService;
+use OCA\Files\Event\LoadAdditionalScriptsEvent;
+use OCA\Files_Sharing\Listener\LoadAdditionalListener;
+use OCP\EventDispatcher\Event;
+use OCP\IConfig;
+use OCP\L10N\IFactory;
+use OCP\Share\IManager;
+use OCP\Util;
+use PHPUnit\Framework\MockObject\MockObject;
+use Psr\Log\LoggerInterface;
+use Test\TestCase;
+
+class LoadAdditionalListenerTest extends TestCase {
+ protected LoggerInterface&MockObject $logger;
+ protected LoadAdditionalScriptsEvent&MockObject $event;
+ protected IManager&MockObject $shareManager;
+ protected IFactory&MockObject $factory;
+ protected InitialStateService&MockObject $initialStateService;
+ protected IConfig&MockObject $config;
+
+ protected function setUp(): void {
+ parent::setUp();
+
+ $this->logger = $this->createMock(LoggerInterface::class);
+ $this->event = $this->createMock(LoadAdditionalScriptsEvent::class);
+ $this->shareManager = $this->createMock(IManager::class);
+ $this->factory = $this->createMock(IFactory::class);
+ $this->initialStateService = $this->createMock(InitialStateService::class);
+ $this->config = $this->createMock(IConfig::class);
+
+ /* Empty static array to avoid inter-test conflicts */
+ \OC_Util::$styles = [];
+ self::invokePrivate(Util::class, 'scripts', [[]]);
+ self::invokePrivate(Util::class, 'scriptDeps', [[]]);
+ self::invokePrivate(Util::class, 'scriptsInit', [[]]);
+ }
+
+ protected function tearDown(): void {
+ parent::tearDown();
+
+ \OC_Util::$styles = [];
+ self::invokePrivate(Util::class, 'scripts', [[]]);
+ self::invokePrivate(Util::class, 'scriptDeps', [[]]);
+ self::invokePrivate(Util::class, 'scriptsInit', [[]]);
+ }
+
+ public function testHandleIgnoresNonMatchingEvent(): void {
+ $listener = new LoadAdditionalListener();
+ $event = $this->createMock(Event::class);
+
+ // Should not throw or call anything
+ $listener->handle($event);
+
+ $this->assertTrue(true); // No exception means pass
+ }
+
+ public function testHandleWithLoadAdditionalScriptsEvent(): void {
+ $listener = new LoadAdditionalListener();
+
+ $this->shareManager->method('shareApiEnabled')->willReturn(false);
+ $this->factory->method('findLanguage')->willReturn('language_mock');
+ $this->config->method('getSystemValueBool')->willReturn(true);
+
+ $this->overwriteService(IManager::class, $this->shareManager);
+ $this->overwriteService(IFactory::class, $this->factory);
+ $this->overwriteService(InitialStateService::class, $this->initialStateService);
+ $this->overwriteService(IConfig::class, $this->config);
+
+ $scriptsBefore = Util::getScripts();
+ $this->assertNotContains('files_sharing/l10n/language_mock', $scriptsBefore);
+ $this->assertNotContains('files_sharing/js/additionalScripts', $scriptsBefore);
+ $this->assertNotContains('files_sharing/js/init', $scriptsBefore);
+ $this->assertNotContains('files_sharing/css/icons', \OC_Util::$styles);
+
+ // Util static methods can't be easily mocked, so just ensure no exceptions
+ $listener->handle($this->event);
+
+ // assert array $scripts contains the expected scripts
+ $scriptsAfter = Util::getScripts();
+ $this->assertContains('files_sharing/l10n/language_mock', $scriptsAfter);
+ $this->assertContains('files_sharing/js/additionalScripts', $scriptsAfter);
+ $this->assertNotContains('files_sharing/js/init', $scriptsAfter);
+
+ $this->assertContains('files_sharing/css/icons', \OC_Util::$styles);
+ }
+
+ public function testHandleWithLoadAdditionalScriptsEventWithShareApiEnabled(): void {
+ $listener = new LoadAdditionalListener();
+
+ $this->shareManager->method('shareApiEnabled')->willReturn(true);
+ $this->config->method('getSystemValueBool')->willReturn(true);
+
+ $this->overwriteService(IManager::class, $this->shareManager);
+ $this->overwriteService(InitialStateService::class, $this->initialStateService);
+ $this->overwriteService(IConfig::class, $this->config);
+ $this->overwriteService(IFactory::class, $this->factory);
+
+ $scriptsBefore = Util::getScripts();
+ $this->assertNotContains('files_sharing/js/init', $scriptsBefore);
+
+ // Util static methods can't be easily mocked, so just ensure no exceptions
+ $listener->handle($this->event);
+
+ $scriptsAfter = Util::getScripts();
+
+ // assert array $scripts contains the expected scripts
+ $this->assertContains('files_sharing/js/init', $scriptsAfter);
+ }
+}
diff --git a/apps/files_sharing/tests/LockingTest.php b/apps/files_sharing/tests/LockingTest.php
index 5d6d7b30ec0..280c364a136 100644
--- a/apps/files_sharing/tests/LockingTest.php
+++ b/apps/files_sharing/tests/LockingTest.php
@@ -1,33 +1,19 @@
<?php
+
/**
- * @copyright Copyright (c) 2016, ownCloud, Inc.
- *
- * @author Joas Schilling <coding@schilljs.com>
- * @author Lukas Reschke <lukas@statuscode.ch>
- * @author Robin Appelman <robin@icewind.nl>
- * @author Roeland Jago Douma <roeland@famdouma.nl>
- * @author Thomas Müller <thomas.mueller@tmit.eu>
- *
- * @license AGPL-3.0
- *
- * This code is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License, version 3,
- * as published by the Free Software Foundation.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU Affero General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License, version 3,
- * along with this program. If not, see <http://www.gnu.org/licenses/>
- *
+ * SPDX-FileCopyrightText: 2018-2024 Nextcloud GmbH and Nextcloud contributors
+ * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
+ * SPDX-License-Identifier: AGPL-3.0-only
*/
namespace OCA\Files_Sharing\Tests;
use OC\Files\Filesystem;
use OC\Files\View;
+use OCP\Constants;
+use OCP\IUserManager;
use OCP\Lock\ILockingProvider;
+use OCP\Lock\LockedException;
+use OCP\Server;
use OCP\Share\IShare;
/**
@@ -50,7 +36,7 @@ class LockingTest extends TestCase {
parent::setUp();
$this->userBackend = new \Test\Util\User\Dummy();
- \OC::$server->getUserManager()->registerBackend($this->userBackend);
+ Server::get(IUserManager::class)->registerBackend($this->userBackend);
$this->ownerUid = $this->getUniqueID('owner_');
$this->recipientUid = $this->getUniqueID('recipient_');
@@ -67,7 +53,7 @@ class LockingTest extends TestCase {
'/foo/bar.txt',
$this->ownerUid,
$this->recipientUid,
- \OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_SHARE
+ Constants::PERMISSION_READ | Constants::PERMISSION_UPDATE | Constants::PERMISSION_SHARE
);
$this->loginAsUser($this->recipientUid);
@@ -75,13 +61,13 @@ class LockingTest extends TestCase {
}
protected function tearDown(): void {
- \OC::$server->getUserManager()->removeBackend($this->userBackend);
+ Server::get(IUserManager::class)->removeBackend($this->userBackend);
parent::tearDown();
}
- public function testLockAsRecipient() {
- $this->expectException(\OCP\Lock\LockedException::class);
+ public function testLockAsRecipient(): void {
+ $this->expectException(LockedException::class);
$this->loginAsUser($this->ownerUid);
@@ -92,7 +78,7 @@ class LockingTest extends TestCase {
Filesystem::rename('/foo', '/asd');
}
- public function testUnLockAsRecipient() {
+ public function testUnLockAsRecipient(): void {
$this->loginAsUser($this->ownerUid);
Filesystem::initMountPoints($this->recipientUid);
@@ -103,7 +89,7 @@ class LockingTest extends TestCase {
$this->assertTrue(Filesystem::rename('/foo', '/asd'));
}
- public function testChangeLock() {
+ public function testChangeLock(): void {
Filesystem::initMountPoints($this->recipientUid);
$recipientView = new View('/' . $this->recipientUid . '/files');
$recipientView->lockFile('bar.txt', ILockingProvider::LOCK_SHARED);
diff --git a/apps/files_sharing/tests/Middleware/OCSShareAPIMiddlewareTest.php b/apps/files_sharing/tests/Middleware/OCSShareAPIMiddlewareTest.php
index 7a579c9cddb..efc6b3f7f7f 100644
--- a/apps/files_sharing/tests/Middleware/OCSShareAPIMiddlewareTest.php
+++ b/apps/files_sharing/tests/Middleware/OCSShareAPIMiddlewareTest.php
@@ -1,27 +1,8 @@
<?php
+
/**
- * @copyright Copyright (c) 2016 Roeland Jago Douma <roeland@famdouma.nl>
- *
- * @author Christoph Wurst <christoph@winzerhof-wurst.at>
- * @author Joas Schilling <coding@schilljs.com>
- * @author Morris Jobke <hey@morrisjobke.de>
- * @author Roeland Jago Douma <roeland@famdouma.nl>
- *
- * @license GNU AGPL version 3 or any later version
- *
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License as
- * published by the Free Software Foundation, either version 3 of the
- * License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU Affero General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- *
+ * SPDX-FileCopyrightText: 2016 Nextcloud GmbH and Nextcloud contributors
+ * SPDX-License-Identifier: AGPL-3.0-or-later
*/
namespace OCA\Files_Sharing\Tests\Middleware;
@@ -92,13 +73,13 @@ class OCSShareAPIMiddlewareTest extends \Test\TestCase {
}
/**
- * @dataProvider dataBeforeController
*
* @param Controller $controller
* @param bool $enabled
* @param bool $exception
*/
- public function testBeforeController(Controller $controller, $enabled, $exception) {
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataBeforeController')]
+ public function testBeforeController(Controller $controller, $enabled, $exception): void {
$this->shareManager->method('shareApiEnabled')->willReturn($enabled);
try {
@@ -124,12 +105,12 @@ class OCSShareAPIMiddlewareTest extends \Test\TestCase {
}
/**
- * @dataProvider dataAfterController
*
* @param Controller $controller
* @param bool $called
*/
- public function testAfterController(Controller $controller) {
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataAfterController')]
+ public function testAfterController(Controller $controller): void {
if ($controller instanceof ShareAPIController) {
$controller->expects($this->once())->method('cleanup');
}
diff --git a/apps/files_sharing/tests/Middleware/ShareInfoMiddlewareTest.php b/apps/files_sharing/tests/Middleware/ShareInfoMiddlewareTest.php
index 41f104fe20b..631b6a0f51c 100644
--- a/apps/files_sharing/tests/Middleware/ShareInfoMiddlewareTest.php
+++ b/apps/files_sharing/tests/Middleware/ShareInfoMiddlewareTest.php
@@ -1,25 +1,8 @@
<?php
+
/**
- * @copyright Copyright (c) 2016 Roeland Jago Douma <roeland@famdouma.nl>
- *
- * @author Morris Jobke <hey@morrisjobke.de>
- * @author Roeland Jago Douma <roeland@famdouma.nl>
- *
- * @license GNU AGPL version 3 or any later version
- *
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License as
- * published by the Free Software Foundation, either version 3 of the
- * License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU Affero General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- *
+ * SPDX-FileCopyrightText: 2016 Nextcloud GmbH and Nextcloud contributors
+ * SPDX-License-Identifier: AGPL-3.0-or-later
*/
namespace OCA\Files_Sharing\Tests\Middleware;
@@ -29,6 +12,7 @@ use OCA\Files_Sharing\Middleware\ShareInfoMiddleware;
use OCP\AppFramework\Controller;
use OCP\AppFramework\Http;
use OCP\AppFramework\Http\JSONResponse;
+use OCP\AppFramework\Http\Response;
use OCP\Share\IManager as ShareManager;
use Test\TestCase;
@@ -47,14 +31,14 @@ class ShareInfoMiddlewareTest extends TestCase {
$this->middleware = new ShareInfoMiddleware($this->shareManager);
}
- public function testBeforeControllerNoShareInfo() {
+ public function testBeforeControllerNoShareInfo(): void {
$this->shareManager->expects($this->never())
->method($this->anything());
$this->middleware->beforeController($this->createMock(ShareInfoMiddlewareTestController::class), 'foo');
}
- public function testBeforeControllerShareInfoNoS2s() {
+ public function testBeforeControllerShareInfoNoS2s(): void {
$this->shareManager->expects($this->once())
->method('outgoingServer2ServerSharesAllowed')
->willReturn(false);
@@ -63,7 +47,7 @@ class ShareInfoMiddlewareTest extends TestCase {
$this->middleware->beforeController($this->createMock(ShareInfoController::class), 'foo');
}
- public function testBeforeControllerShareInfo() {
+ public function testBeforeControllerShareInfo(): void {
$this->shareManager->expects($this->once())
->method('outgoingServer2ServerSharesAllowed')
->willReturn(true);
@@ -71,7 +55,7 @@ class ShareInfoMiddlewareTest extends TestCase {
$this->middleware->beforeController($this->createMock(ShareInfoController::class), 'foo');
}
- public function testAfterExceptionNoShareInfo() {
+ public function testAfterExceptionNoShareInfo(): void {
$exeption = new \Exception();
try {
@@ -83,7 +67,7 @@ class ShareInfoMiddlewareTest extends TestCase {
}
- public function testAfterExceptionNoS2S() {
+ public function testAfterExceptionNoS2S(): void {
$exeption = new \Exception();
try {
@@ -94,7 +78,7 @@ class ShareInfoMiddlewareTest extends TestCase {
}
}
- public function testAfterExceptionS2S() {
+ public function testAfterExceptionS2S(): void {
$expected = new JSONResponse([], Http::STATUS_NOT_FOUND);
$this->assertEquals(
@@ -103,8 +87,8 @@ class ShareInfoMiddlewareTest extends TestCase {
);
}
- public function testAfterControllerNoShareInfo() {
- $response = $this->createMock(Http\Response::class);
+ public function testAfterControllerNoShareInfo(): void {
+ $response = $this->createMock(Response::class);
$this->assertEquals(
$response,
@@ -112,8 +96,8 @@ class ShareInfoMiddlewareTest extends TestCase {
);
}
- public function testAfterControllerNoJSON() {
- $response = $this->createMock(Http\Response::class);
+ public function testAfterControllerNoJSON(): void {
+ $response = $this->createMock(Response::class);
$this->assertEquals(
$response,
@@ -121,7 +105,7 @@ class ShareInfoMiddlewareTest extends TestCase {
);
}
- public function testAfterControllerJSONok() {
+ public function testAfterControllerJSONok(): void {
$data = ['foo' => 'bar'];
$response = new JSONResponse($data);
@@ -136,7 +120,7 @@ class ShareInfoMiddlewareTest extends TestCase {
);
}
- public function testAfterControllerJSONerror() {
+ public function testAfterControllerJSONerror(): void {
$data = ['foo' => 'bar'];
$response = new JSONResponse($data, Http::STATUS_FORBIDDEN);
diff --git a/apps/files_sharing/tests/Middleware/SharingCheckMiddlewareTest.php b/apps/files_sharing/tests/Middleware/SharingCheckMiddlewareTest.php
index 379cb88567e..3d86007a54c 100644
--- a/apps/files_sharing/tests/Middleware/SharingCheckMiddlewareTest.php
+++ b/apps/files_sharing/tests/Middleware/SharingCheckMiddlewareTest.php
@@ -1,28 +1,9 @@
<?php
+
/**
- * @copyright Copyright (c) 2016, ownCloud, Inc.
- *
- * @author Bjoern Schiessle <bjoern@schiessle.org>
- * @author Christoph Wurst <christoph@winzerhof-wurst.at>
- * @author Lukas Reschke <lukas@statuscode.ch>
- * @author Morris Jobke <hey@morrisjobke.de>
- * @author Roeland Jago Douma <roeland@famdouma.nl>
- * @author Thomas Müller <thomas.mueller@tmit.eu>
- *
- * @license AGPL-3.0
- *
- * This code is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License, version 3,
- * as published by the Free Software Foundation.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU Affero General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License, version 3,
- * along with this program. If not, see <http://www.gnu.org/licenses/>
- *
+ * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
+ * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
+ * SPDX-License-Identifier: AGPL-3.0-only
*/
namespace OCA\Files_Sharing\Middleware;
@@ -55,9 +36,9 @@ class SharingCheckMiddlewareTest extends \Test\TestCase {
private $controllerMock;
/** @var IControllerMethodReflector|\PHPUnit\Framework\MockObject\MockObject */
private $reflector;
- /** @var IManager | \PHPUnit\Framework\MockObject\MockObject */
+ /** @var IManager | \PHPUnit\Framework\MockObject\MockObject */
private $shareManager;
- /** @var IRequest | \PHPUnit\Framework\MockObject\MockObject */
+ /** @var IRequest | \PHPUnit\Framework\MockObject\MockObject */
private $request;
protected function setUp(): void {
@@ -79,7 +60,7 @@ class SharingCheckMiddlewareTest extends \Test\TestCase {
$this->request);
}
- public function testIsSharingEnabledWithAppEnabled() {
+ public function testIsSharingEnabledWithAppEnabled(): void {
$this->appManager
->expects($this->once())
->method('isEnabledForUser')
@@ -89,7 +70,7 @@ class SharingCheckMiddlewareTest extends \Test\TestCase {
$this->assertTrue(self::invokePrivate($this->sharingCheckMiddleware, 'isSharingEnabled'));
}
- public function testIsSharingEnabledWithAppDisabled() {
+ public function testIsSharingEnabledWithAppDisabled(): void {
$this->appManager
->expects($this->once())
->method('isEnabledForUser')
@@ -99,7 +80,7 @@ class SharingCheckMiddlewareTest extends \Test\TestCase {
$this->assertFalse(self::invokePrivate($this->sharingCheckMiddleware, 'isSharingEnabled'));
}
- public function externalSharesChecksDataProvider() {
+ public static function externalSharesChecksDataProvider() {
$data = [];
foreach ([false, true] as $annIn) {
@@ -134,10 +115,8 @@ class SharingCheckMiddlewareTest extends \Test\TestCase {
return $data;
}
- /**
- * @dataProvider externalSharesChecksDataProvider
- */
- public function testExternalSharesChecks($annotations, $config, $expectedResult) {
+ #[\PHPUnit\Framework\Attributes\DataProvider('externalSharesChecksDataProvider')]
+ public function testExternalSharesChecks($annotations, $config, $expectedResult): void {
$this->reflector
->expects($this->atLeastOnce())
->method('hasAnnotation')
@@ -150,10 +129,8 @@ class SharingCheckMiddlewareTest extends \Test\TestCase {
$this->assertEquals($expectedResult, self::invokePrivate($this->sharingCheckMiddleware, 'externalSharesChecks'));
}
- /**
- * @dataProvider externalSharesChecksDataProvider
- */
- public function testBeforeControllerWithExternalShareControllerWithSharingEnabled($annotations, $config, $noException) {
+ #[\PHPUnit\Framework\Attributes\DataProvider('externalSharesChecksDataProvider')]
+ public function testBeforeControllerWithExternalShareControllerWithSharingEnabled($annotations, $config, $noException): void {
$this->appManager
->expects($this->once())
->method('isEnabledForUser')
@@ -182,7 +159,7 @@ class SharingCheckMiddlewareTest extends \Test\TestCase {
$this->assertNotEquals($noException, $exceptionThrown);
}
- public function testBeforeControllerWithShareControllerWithSharingEnabled() {
+ public function testBeforeControllerWithShareControllerWithSharingEnabled(): void {
$share = $this->createMock(IShare::class);
$this->appManager
@@ -197,8 +174,8 @@ class SharingCheckMiddlewareTest extends \Test\TestCase {
}
- public function testBeforeControllerWithSharingDisabled() {
- $this->expectException(\OCP\Files\NotFoundException::class);
+ public function testBeforeControllerWithSharingDisabled(): void {
+ $this->expectException(NotFoundException::class);
$this->expectExceptionMessage('Sharing is disabled.');
$this->appManager
@@ -211,18 +188,18 @@ class SharingCheckMiddlewareTest extends \Test\TestCase {
}
- public function testAfterExceptionWithRegularException() {
+ public function testAfterExceptionWithRegularException(): void {
$this->expectException(\Exception::class);
$this->expectExceptionMessage('My Exception message');
$this->sharingCheckMiddleware->afterException($this->controllerMock, 'myMethod', new \Exception('My Exception message'));
}
- public function testAfterExceptionWithNotFoundException() {
+ public function testAfterExceptionWithNotFoundException(): void {
$this->assertEquals(new NotFoundResponse(), $this->sharingCheckMiddleware->afterException($this->controllerMock, 'myMethod', new NotFoundException('My Exception message')));
}
- public function testAfterExceptionWithS2SException() {
+ public function testAfterExceptionWithS2SException(): void {
$this->assertEquals(new JSONResponse('My Exception message', 405), $this->sharingCheckMiddleware->afterException($this->controllerMock, 'myMethod', new S2SException('My Exception message')));
}
}
diff --git a/apps/files_sharing/tests/Migration/SetPasswordColumnTest.php b/apps/files_sharing/tests/Migration/SetPasswordColumnTest.php
index 20eb6e96171..3cbbad0f8bc 100644
--- a/apps/files_sharing/tests/Migration/SetPasswordColumnTest.php
+++ b/apps/files_sharing/tests/Migration/SetPasswordColumnTest.php
@@ -1,33 +1,18 @@
<?php
+
/**
- * @copyright Copyright (c) 2016, ownCloud, Inc.
- *
- * @author Christoph Wurst <christoph@winzerhof-wurst.at>
- * @author Joas Schilling <coding@schilljs.com>
- * @author Morris Jobke <hey@morrisjobke.de>
- * @author Roeland Jago Douma <roeland@famdouma.nl>
- *
- * @license AGPL-3.0
- *
- * This code is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License, version 3,
- * as published by the Free Software Foundation.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU Affero General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License, version 3,
- * along with this program. If not, see <http://www.gnu.org/licenses/>
- *
+ * SPDX-FileCopyrightText: 2017-2024 Nextcloud GmbH and Nextcloud contributors
+ * SPDX-FileCopyrightText: 2017 ownCloud, Inc.
+ * SPDX-License-Identifier: AGPL-3.0-only
*/
namespace OCA\Files_Sharing\Tests\Migration;
use OCA\Files_Sharing\Migration\SetPasswordColumn;
use OCA\Files_Sharing\Tests\TestCase;
use OCP\IConfig;
+use OCP\IDBConnection;
use OCP\Migration\IOutput;
+use OCP\Server;
use OCP\Share\IShare;
/**
@@ -37,7 +22,7 @@ use OCP\Share\IShare;
*/
class SetPasswordColumnTest extends TestCase {
- /** @var \OCP\IDBConnection */
+ /** @var IDBConnection */
private $connection;
/** @var IConfig|\PHPUnit\Framework\MockObject\MockObject */
@@ -51,7 +36,7 @@ class SetPasswordColumnTest extends TestCase {
protected function setUp(): void {
parent::setUp();
- $this->connection = \OC::$server->getDatabaseConnection();
+ $this->connection = Server::get(IDBConnection::class);
$this->config = $this->createMock(IConfig::class);
$this->migration = new SetPasswordColumn($this->connection, $this->config);
@@ -68,7 +53,7 @@ class SetPasswordColumnTest extends TestCase {
$query->delete($this->table)->execute();
}
- public function testAddPasswordColumn() {
+ public function testAddPasswordColumn(): void {
$this->config->expects($this->once())
->method('getAppValue')
->with('files_sharing', 'installed_version', '0.0.0')
diff --git a/apps/files_sharing/tests/MountProviderTest.php b/apps/files_sharing/tests/MountProviderTest.php
index af552f48218..e043a1cb1ef 100644
--- a/apps/files_sharing/tests/MountProviderTest.php
+++ b/apps/files_sharing/tests/MountProviderTest.php
@@ -1,38 +1,19 @@
<?php
+
/**
- * @copyright Copyright (c) 2016, ownCloud, Inc.
- *
- * @author Christoph Wurst <christoph@winzerhof-wurst.at>
- * @author Daniel Calviño Sánchez <danxuliu@gmail.com>
- * @author Joas Schilling <coding@schilljs.com>
- * @author Julius Härtl <jus@bitgrid.net>
- * @author Maxence Lange <maxence@nextcloud.com>
- * @author Morris Jobke <hey@morrisjobke.de>
- * @author Roeland Jago Douma <roeland@famdouma.nl>
- * @author Thomas Müller <thomas.mueller@tmit.eu>
- * @author Vincent Petry <vincent@nextcloud.com>
- *
- * @license AGPL-3.0
- *
- * This code is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License, version 3,
- * as published by the Free Software Foundation.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU Affero General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License, version 3,
- * along with this program. If not, see <http://www.gnu.org/licenses/>
- *
+ * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
+ * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
+ * SPDX-License-Identifier: AGPL-3.0-only
*/
namespace OCA\Files_Sharing\Tests;
use OC\Memcache\NullCache;
+use OC\Share20\Share;
use OCA\Files_Sharing\MountProvider;
+use OCA\Files_Sharing\SharedMount;
use OCP\EventDispatcher\IEventDispatcher;
use OCP\Files\IRootFolder;
+use OCP\Files\Mount\IMountManager;
use OCP\Files\Storage\IStorageFactory;
use OCP\ICacheFactory;
use OCP\IConfig;
@@ -41,29 +22,21 @@ use OCP\IUserManager;
use OCP\Share\IAttributes as IShareAttributes;
use OCP\Share\IManager;
use OCP\Share\IShare;
+use PHPUnit\Framework\MockObject\MockObject;
use Psr\Log\LoggerInterface;
/**
* @group DB
*/
class MountProviderTest extends \Test\TestCase {
- /** @var MountProvider */
- private $provider;
-
- /** @var IConfig|MockObject */
- private $config;
-
- /** @var IUser|MockObject */
- private $user;
- /** @var IStorageFactory|MockObject */
- private $loader;
+ protected MountProvider $provider;
- /** @var IManager|MockObject */
- private $shareManager;
-
- /** @var LoggerInterface|MockObject */
- private $logger;
+ protected IUser&MockObject $user;
+ protected IConfig&MockObject $config;
+ protected IManager&MockObject $shareManager;
+ protected IStorageFactory&MockObject $loader;
+ protected LoggerInterface&MockObject $logger;
protected function setUp(): void {
parent::setUp();
@@ -77,8 +50,9 @@ class MountProviderTest extends \Test\TestCase {
$cacheFactory = $this->createMock(ICacheFactory::class);
$cacheFactory->method('createLocal')
->willReturn(new NullCache());
+ $mountManager = $this->createMock(IMountManager::class);
- $this->provider = new MountProvider($this->config, $this->shareManager, $this->logger, $eventDispatcher, $cacheFactory);
+ $this->provider = new MountProvider($this->config, $this->shareManager, $this->logger, $eventDispatcher, $cacheFactory, $mountManager);
}
private function makeMockShareAttributes($attrs) {
@@ -88,16 +62,16 @@ class MountProviderTest extends \Test\TestCase {
$shareAttributes = $this->createMock(IShareAttributes::class);
$shareAttributes->method('toArray')->willReturn($attrs);
- $shareAttributes->method('getAttribute')->will(
- $this->returnCallback(function ($scope, $key) use ($attrs) {
+ $shareAttributes->method('getAttribute')->willReturnCallback(
+ function ($scope, $key) use ($attrs) {
$result = null;
foreach ($attrs as $attr) {
if ($attr['key'] === $key && $attr['scope'] === $scope) {
- $result = $attr['enabled'];
+ $result = $attr['value'];
}
}
return $result;
- })
+ }
);
return $shareAttributes;
}
@@ -109,7 +83,7 @@ class MountProviderTest extends \Test\TestCase {
->willReturn($permissions);
$share->expects($this->any())
->method('getAttributes')
- ->will($this->returnValue($this->makeMockShareAttributes($attributes)));
+ ->willReturn($this->makeMockShareAttributes($attributes));
$share->expects($this->any())
->method('getShareOwner')
->willReturn($owner);
@@ -136,11 +110,11 @@ class MountProviderTest extends \Test\TestCase {
* - shares that were opted out of (permissions === 0)
* - shares with a group in which the owner is already in
*/
- public function testExcludeShares() {
+ public function testExcludeShares(): void {
$rootFolder = $this->createMock(IRootFolder::class);
$userManager = $this->createMock(IUserManager::class);
$attr1 = [];
- $attr2 = [['scope' => 'permission', 'key' => 'download', 'enabled' => true]];
+ $attr2 = [['scope' => 'permission', 'key' => 'download', 'value' => true]];
$userShares = [
$this->makeMockShare(1, 100, 'user2', '/share2', 0, $attr1),
$this->makeMockShare(2, 100, 'user2', '/share2', 31, $attr2),
@@ -164,38 +138,34 @@ class MountProviderTest extends \Test\TestCase {
];
// tests regarding circles and sciencemesh are made in the apps themselves.
$circleShares = [];
- $sciencemeshShares = [];
+ $scienceMeshShares = [];
$this->user->expects($this->any())
->method('getUID')
->willReturn('user1');
$this->shareManager->expects($this->exactly(6))
->method('getSharedWith')
- ->withConsecutive(
- ['user1', IShare::TYPE_USER],
- ['user1', IShare::TYPE_GROUP, null, -1],
- ['user1', IShare::TYPE_CIRCLE, null, -1],
- ['user1', IShare::TYPE_ROOM, null, -1],
- ['user1', IShare::TYPE_DECK, null, -1],
- ['user1', IShare::TYPE_SCIENCEMESH, null, -1],
- )->willReturnOnConsecutiveCalls(
- $userShares,
- $groupShares,
- $circleShares,
- $roomShares,
- $deckShares,
- $sciencemeshShares
- );
+ ->willReturnMap([
+ ['user1', IShare::TYPE_USER, null, -1, 0, $userShares],
+ ['user1', IShare::TYPE_GROUP, null, -1, 0, $groupShares],
+ ['user1', IShare::TYPE_CIRCLE, null, -1, 0, $circleShares],
+ ['user1', IShare::TYPE_ROOM, null, -1, 0, $roomShares],
+ ['user1', IShare::TYPE_DECK, null, -1, 0, $deckShares],
+ ['user1', IShare::TYPE_SCIENCEMESH, null, -1, 0, $scienceMeshShares],
+ ]);
+
$this->shareManager->expects($this->any())
->method('newShare')
->willReturnCallback(function () use ($rootFolder, $userManager) {
- return new \OC\Share20\Share($rootFolder, $userManager);
+ return new Share($rootFolder, $userManager);
});
+
$mounts = $this->provider->getMountsForUser($this->user, $this->loader);
$this->assertCount(4, $mounts);
$this->assertInstanceOf('OCA\Files_Sharing\SharedMount', $mounts[0]);
$this->assertInstanceOf('OCA\Files_Sharing\SharedMount', $mounts[1]);
$this->assertInstanceOf('OCA\Files_Sharing\SharedMount', $mounts[2]);
$this->assertInstanceOf('OCA\Files_Sharing\SharedMount', $mounts[3]);
+ /** @var SharedMount[] $mounts */
$mountedShare1 = $mounts[0]->getShare();
$this->assertEquals('2', $mountedShare1->getId());
$this->assertEquals('user2', $mountedShare1->getShareOwner());
@@ -224,7 +194,7 @@ class MountProviderTest extends \Test\TestCase {
$this->assertEquals(31, $mountedShare4->getPermissions());
}
- public function mergeSharesDataProvider() {
+ public static function mergeSharesDataProvider(): array {
// note: the user in the specs here is the shareOwner not recipient
// the recipient is always "user1"
return [
@@ -244,14 +214,14 @@ class MountProviderTest extends \Test\TestCase {
// #1: share as outsider with "group1" and "user1" with different permissions
[
[
- [1, 100, 'user2', '/share', 31, [['scope' => 'permission', 'key' => 'download', 'enabled' => true], ['scope' => 'app', 'key' => 'attribute1', 'enabled' => true]]],
+ [1, 100, 'user2', '/share', 31, [['scope' => 'permission', 'key' => 'download', 'value' => true], ['scope' => 'app', 'key' => 'attribute1', 'value' => true]]],
],
[
- [2, 100, 'user2', '/share', 15, [['scope' => 'permission', 'key' => 'download', 'enabled' => false], ['scope' => 'app', 'key' => 'attribute2', 'enabled' => false]]],
+ [2, 100, 'user2', '/share', 15, [['scope' => 'permission', 'key' => 'download', 'value' => false], ['scope' => 'app', 'key' => 'attribute2', 'value' => false]]],
],
[
// use highest permissions
- ['1', 100, 'user2', '/share', 31, [['scope' => 'permission', 'key' => 'download', 'enabled' => true], ['scope' => 'app', 'key' => 'attribute1', 'enabled' => true], ['scope' => 'app', 'key' => 'attribute2', 'enabled' => false]]],
+ ['1', 100, 'user2', '/share', 31, [['scope' => 'permission', 'key' => 'download', 'value' => true], ['scope' => 'app', 'key' => 'attribute1', 'value' => true], ['scope' => 'app', 'key' => 'attribute2', 'value' => false]]],
],
],
// #2: share as outsider with "group1" and "group2" with same permissions
@@ -272,12 +242,12 @@ class MountProviderTest extends \Test\TestCase {
[
],
[
- [1, 100, 'user2', '/share', 31, [['scope' => 'permission', 'key' => 'download', 'enabled' => false]]],
- [2, 100, 'user2', '/share', 15, [['scope' => 'permission', 'key' => 'download', 'enabled' => true]]],
+ [1, 100, 'user2', '/share', 31, [['scope' => 'permission', 'key' => 'download', 'value' => false]]],
+ [2, 100, 'user2', '/share', 15, [['scope' => 'permission', 'key' => 'download', 'value' => true]]],
],
[
// use higher permissions (most permissive)
- ['1', 100, 'user2', '/share', 31, [['scope' => 'permission', 'key' => 'download', 'enabled' => true]]],
+ ['1', 100, 'user2', '/share', 31, [['scope' => 'permission', 'key' => 'download', 'value' => true]]],
],
],
// #4: share as insider with "group1"
@@ -296,8 +266,8 @@ class MountProviderTest extends \Test\TestCase {
[
],
[
- [1, 100, 'user1', '/share', 31, [['scope' => 'permission', 'key' => 'download', 'enabled' => true]]],
- [2, 100, 'user1', '/share', 15, [['scope' => 'permission', 'key' => 'download', 'enabled' => false]]],
+ [1, 100, 'user1', '/share', 31, [['scope' => 'permission', 'key' => 'download', 'value' => true]]],
+ [2, 100, 'user1', '/share', 15, [['scope' => 'permission', 'key' => 'download', 'value' => false]]],
],
[
// no received share since "user1" is the sharer/owner
@@ -363,13 +333,13 @@ class MountProviderTest extends \Test\TestCase {
* Happens when sharing the same entry to a user through multiple ways,
* like several groups and also direct shares at the same time.
*
- * @dataProvider mergeSharesDataProvider
*
* @param array $userShares array of user share specs
* @param array $groupShares array of group share specs
* @param array $expectedShares array of expected supershare specs
*/
- public function testMergeShares($userShares, $groupShares, $expectedShares, $moveFails = false) {
+ #[\PHPUnit\Framework\Attributes\DataProvider('mergeSharesDataProvider')]
+ public function testMergeShares($userShares, $groupShares, $expectedShares, $moveFails = false): void {
$rootFolder = $this->createMock(IRootFolder::class);
$userManager = $this->createMock(IUserManager::class);
@@ -388,34 +358,28 @@ class MountProviderTest extends \Test\TestCase {
$circleShares = [];
$roomShares = [];
$deckShares = [];
- $sciencemeshShares = [];
+ $scienceMeshShares = [];
$this->shareManager->expects($this->exactly(6))
->method('getSharedWith')
- ->withConsecutive(
- ['user1', IShare::TYPE_USER],
- ['user1', IShare::TYPE_GROUP, null, -1],
- ['user1', IShare::TYPE_CIRCLE, null, -1],
- ['user1', IShare::TYPE_ROOM, null, -1],
- ['user1', IShare::TYPE_DECK, null, -1],
- ['user1', IShare::TYPE_SCIENCEMESH, null, -1],
- )->willReturnOnConsecutiveCalls(
- $userShares,
- $groupShares,
- $circleShares,
- $roomShares,
- $deckShares,
- $sciencemeshShares
- );
+ ->willReturnMap([
+ ['user1', IShare::TYPE_USER, null, -1, 0, $userShares],
+ ['user1', IShare::TYPE_GROUP, null, -1, 0, $groupShares],
+ ['user1', IShare::TYPE_CIRCLE, null, -1, 0, $circleShares],
+ ['user1', IShare::TYPE_ROOM, null, -1, 0, $roomShares],
+ ['user1', IShare::TYPE_DECK, null, -1, 0, $deckShares],
+ ['user1', IShare::TYPE_SCIENCEMESH, null, -1, 0, $scienceMeshShares],
+ ]);
+
$this->shareManager->expects($this->any())
->method('newShare')
->willReturnCallback(function () use ($rootFolder, $userManager) {
- return new \OC\Share20\Share($rootFolder, $userManager);
+ return new Share($rootFolder, $userManager);
});
if ($moveFails) {
$this->shareManager->expects($this->any())
->method('moveShare')
- ->will($this->throwException(new \InvalidArgumentException()));
+ ->willThrowException(new \InvalidArgumentException());
}
$mounts = $this->provider->getMountsForUser($this->user, $this->loader);
@@ -427,6 +391,7 @@ class MountProviderTest extends \Test\TestCase {
$this->assertInstanceOf('OCA\Files_Sharing\SharedMount', $mount);
// supershare
+ /** @var SharedMount $mount */
$share = $mount->getShare();
$this->assertEquals($expectedShare[0], $share->getId());
diff --git a/apps/files_sharing/tests/PropagationTestCase.php b/apps/files_sharing/tests/PropagationTestCase.php
index dbe711c9583..98bf5ad92fd 100644
--- a/apps/files_sharing/tests/PropagationTestCase.php
+++ b/apps/files_sharing/tests/PropagationTestCase.php
@@ -1,31 +1,20 @@
<?php
+
/**
- * @copyright Copyright (c) 2016, ownCloud, Inc.
- *
- * @author Joas Schilling <coding@schilljs.com>
- * @author Robin Appelman <robin@icewind.nl>
- * @author Roeland Jago Douma <roeland@famdouma.nl>
- *
- * @license AGPL-3.0
- *
- * This code is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License, version 3,
- * as published by the Free Software Foundation.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU Affero General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License, version 3,
- * along with this program. If not, see <http://www.gnu.org/licenses/>
- *
+ * SPDX-FileCopyrightText: 2019-2024 Nextcloud GmbH and Nextcloud contributors
+ * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
+ * SPDX-License-Identifier: AGPL-3.0-only
*/
namespace OCA\Files_Sharing\Tests;
+use OC\Files\View;
+use OCA\Files_Sharing\Helper;
+use OCP\IUserSession;
+use OCP\Server;
+
abstract class PropagationTestCase extends TestCase {
/**
- * @var \OC\Files\View
+ * @var View
*/
protected $rootView;
protected $fileIds = []; // [$user=>[$path=>$id]]
@@ -33,7 +22,7 @@ abstract class PropagationTestCase extends TestCase {
public static function setUpBeforeClass(): void {
parent::setUpBeforeClass();
- \OCA\Files_Sharing\Helper::registerHooks();
+ Helper::registerHooks();
}
protected function setUp(): void {
@@ -56,7 +45,7 @@ abstract class PropagationTestCase extends TestCase {
* @param string $subPath
*/
protected function assertEtagsChanged($users, $subPath = '') {
- $oldUser = \OC::$server->getUserSession()->getUser();
+ $oldUser = Server::get(IUserSession::class)->getUser();
foreach ($users as $user) {
$this->loginAsUser($user);
$id = $this->fileIds[$user][$subPath];
@@ -73,7 +62,7 @@ abstract class PropagationTestCase extends TestCase {
* @param string $subPath
*/
protected function assertEtagsNotChanged($users, $subPath = '') {
- $oldUser = \OC::$server->getUserSession()->getUser();
+ $oldUser = Server::get(IUserSession::class)->getUser();
foreach ($users as $user) {
$this->loginAsUser($user);
$id = $this->fileIds[$user][$subPath];
diff --git a/apps/files_sharing/tests/ShareTest.php b/apps/files_sharing/tests/ShareTest.php
index 45bd5a3d707..737ad6dcb4e 100644
--- a/apps/files_sharing/tests/ShareTest.php
+++ b/apps/files_sharing/tests/ShareTest.php
@@ -1,32 +1,20 @@
<?php
+
/**
- * @copyright Copyright (c) 2016, ownCloud, Inc.
- *
- * @author Björn Schießle <bjoern@schiessle.org>
- * @author Christoph Wurst <christoph@winzerhof-wurst.at>
- * @author Joas Schilling <coding@schilljs.com>
- * @author Morris Jobke <hey@morrisjobke.de>
- * @author Robin Appelman <robin@icewind.nl>
- * @author Roeland Jago Douma <roeland@famdouma.nl>
- * @author Thomas Müller <thomas.mueller@tmit.eu>
- *
- * @license AGPL-3.0
- *
- * This code is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License, version 3,
- * as published by the Free Software Foundation.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU Affero General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License, version 3,
- * along with this program. If not, see <http://www.gnu.org/licenses/>
- *
+ * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
+ * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
+ * SPDX-License-Identifier: AGPL-3.0-only
*/
namespace OCA\Files_Sharing\Tests;
+use OC\Files\FileInfo;
+use OC\Files\Filesystem;
+use OCA\Files_Sharing\Helper;
+use OCP\Constants;
+use OCP\IConfig;
+use OCP\IGroupManager;
+use OCP\IUserManager;
+use OCP\Server;
use OCP\Share\IShare;
/**
@@ -55,7 +43,7 @@ class ShareTest extends TestCase {
$this->view->mkdir($this->folder);
$this->view->mkdir($this->folder . $this->subfolder);
$this->view->mkdir($this->folder . $this->subfolder . $this->subsubfolder);
- $this->view->file_put_contents($this->folder.$this->filename, $this->data);
+ $this->view->file_put_contents($this->folder . $this->filename, $this->data);
$this->view->file_put_contents($this->folder . $this->subfolder . $this->filename, $this->data);
}
@@ -69,9 +57,9 @@ class ShareTest extends TestCase {
parent::tearDown();
}
- public function testUnshareFromSelf() {
- $groupManager = \OC::$server->getGroupManager();
- $userManager = \OC::$server->getUserManager();
+ public function testUnshareFromSelf(): void {
+ $groupManager = Server::get(IGroupManager::class);
+ $userManager = Server::get(IUserManager::class);
$testGroup = $groupManager->createGroup('testGroup');
$user1 = $userManager->get(self::TEST_FILES_SHARING_API_USER2);
@@ -84,7 +72,7 @@ class ShareTest extends TestCase {
$this->filename,
self::TEST_FILES_SHARING_API_USER1,
self::TEST_FILES_SHARING_API_USER2,
- \OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_SHARE
+ Constants::PERMISSION_READ | Constants::PERMISSION_UPDATE | Constants::PERMISSION_SHARE
);
$share2 = $this->share(
@@ -92,44 +80,44 @@ class ShareTest extends TestCase {
$this->filename,
self::TEST_FILES_SHARING_API_USER1,
'testGroup',
- \OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_SHARE
+ Constants::PERMISSION_READ | Constants::PERMISSION_UPDATE | Constants::PERMISSION_SHARE
);
$this->shareManager->acceptShare($share2, self::TEST_FILES_SHARING_API_USER2);
$this->shareManager->acceptShare($share2, self::TEST_FILES_SHARING_API_USER3);
self::loginHelper(self::TEST_FILES_SHARING_API_USER2);
- $this->assertTrue(\OC\Files\Filesystem::file_exists($this->filename));
+ $this->assertTrue(Filesystem::file_exists($this->filename));
self::loginHelper(self::TEST_FILES_SHARING_API_USER3);
- $this->assertTrue(\OC\Files\Filesystem::file_exists($this->filename));
+ $this->assertTrue(Filesystem::file_exists($this->filename));
self::loginHelper(self::TEST_FILES_SHARING_API_USER2);
- \OC\Files\Filesystem::unlink($this->filename);
+ Filesystem::unlink($this->filename);
self::loginHelper(self::TEST_FILES_SHARING_API_USER2);
// both group share and user share should be gone
- $this->assertFalse(\OC\Files\Filesystem::file_exists($this->filename));
+ $this->assertFalse(Filesystem::file_exists($this->filename));
// for user3 nothing should change
self::loginHelper(self::TEST_FILES_SHARING_API_USER3);
- $this->assertTrue(\OC\Files\Filesystem::file_exists($this->filename));
+ $this->assertTrue(Filesystem::file_exists($this->filename));
$this->shareManager->deleteShare($share1);
$this->shareManager->deleteShare($share2);
}
/**
- * @param \OC\Files\FileInfo[] $content
+ * @param FileInfo[] $content
* @param string[] $expected
*/
public function verifyDirContent($content, $expected) {
foreach ($content as $c) {
if (!in_array($c['name'], $expected)) {
- $this->assertTrue(false, "folder should only contain '" . implode(',', $expected) . "', found: " .$c['name']);
+ $this->assertTrue(false, "folder should only contain '" . implode(',', $expected) . "', found: " . $c['name']);
}
}
}
- public function testShareWithDifferentShareFolder() {
+ public function testShareWithDifferentShareFolder(): void {
$fileinfo = $this->view->getFileInfo($this->filename);
$folderinfo = $this->view->getFileInfo($this->folder);
@@ -138,40 +126,40 @@ class ShareTest extends TestCase {
$this->filename,
self::TEST_FILES_SHARING_API_USER1,
self::TEST_FILES_SHARING_API_USER2,
- \OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_SHARE
+ Constants::PERMISSION_READ | Constants::PERMISSION_UPDATE | Constants::PERMISSION_SHARE
);
- \OCA\Files_Sharing\Helper::setShareFolder('/Shared/subfolder');
+ Helper::setShareFolder('/Shared/subfolder');
$share = $this->share(
IShare::TYPE_USER,
$this->folder,
self::TEST_FILES_SHARING_API_USER1,
self::TEST_FILES_SHARING_API_USER2,
- \OCP\Constants::PERMISSION_ALL
+ Constants::PERMISSION_ALL
);
self::loginHelper(self::TEST_FILES_SHARING_API_USER2);
- $this->assertTrue(\OC\Files\Filesystem::file_exists($this->filename));
- $this->assertTrue(\OC\Files\Filesystem::file_exists('/Shared/subfolder/' . $this->folder));
+ $this->assertTrue(Filesystem::file_exists($this->filename));
+ $this->assertTrue(Filesystem::file_exists('/Shared/subfolder/' . $this->folder));
//cleanup
- \OC::$server->getConfig()->deleteSystemValue('share_folder');
+ Server::get(IConfig::class)->deleteSystemValue('share_folder');
}
- public function testShareWithGroupUniqueName() {
+ public function testShareWithGroupUniqueName(): void {
$this->markTestSkipped('TODO: Disable because fails on drone');
$this->loginHelper(self::TEST_FILES_SHARING_API_USER1);
- \OC\Files\Filesystem::file_put_contents('test.txt', 'test');
+ Filesystem::file_put_contents('test.txt', 'test');
$share = $this->share(
IShare::TYPE_GROUP,
'test.txt',
self::TEST_FILES_SHARING_API_USER1,
self::TEST_FILES_SHARING_API_GROUP1,
- \OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_SHARE
+ Constants::PERMISSION_READ | Constants::PERMISSION_UPDATE | Constants::PERMISSION_SHARE
);
$this->loginHelper(self::TEST_FILES_SHARING_API_USER2);
@@ -181,14 +169,14 @@ class ShareTest extends TestCase {
$this->assertSame('/test.txt', $share->getTarget());
$this->assertSame(19, $share->getPermissions());
- \OC\Files\Filesystem::rename('test.txt', 'new test.txt');
+ Filesystem::rename('test.txt', 'new test.txt');
$shares = $this->shareManager->getSharedWith(self::TEST_FILES_SHARING_API_USER2, IShare::TYPE_GROUP);
$share = $shares[0];
$this->assertSame('/new test.txt', $share->getTarget());
$this->assertSame(19, $share->getPermissions());
- $share->setPermissions(\OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_UPDATE);
+ $share->setPermissions(Constants::PERMISSION_READ | Constants::PERMISSION_UPDATE);
$this->shareManager->updateShare($share);
$this->loginHelper(self::TEST_FILES_SHARING_API_USER2);
@@ -201,9 +189,9 @@ class ShareTest extends TestCase {
/**
* shared files should never have delete permissions
- * @dataProvider dataProviderTestFileSharePermissions
*/
- public function testFileSharePermissions($permission, $expectedvalid) {
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataProviderTestFileSharePermissions')]
+ public function testFileSharePermissions($permission, $expectedvalid): void {
$pass = true;
try {
$this->share(
@@ -220,12 +208,12 @@ class ShareTest extends TestCase {
$this->assertEquals($expectedvalid, $pass);
}
- public function dataProviderTestFileSharePermissions() {
- $permission1 = \OCP\Constants::PERMISSION_ALL;
- $permission3 = \OCP\Constants::PERMISSION_READ;
- $permission4 = \OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_UPDATE;
- $permission5 = \OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_DELETE;
- $permission6 = \OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE;
+ public static function dataProviderTestFileSharePermissions() {
+ $permission1 = Constants::PERMISSION_ALL;
+ $permission3 = Constants::PERMISSION_READ;
+ $permission4 = Constants::PERMISSION_READ | Constants::PERMISSION_UPDATE;
+ $permission5 = Constants::PERMISSION_READ | Constants::PERMISSION_DELETE;
+ $permission6 = Constants::PERMISSION_READ | Constants::PERMISSION_UPDATE | Constants::PERMISSION_DELETE;
return [
[$permission1, false],
@@ -236,18 +224,18 @@ class ShareTest extends TestCase {
];
}
- public function testFileOwner() {
+ public function testFileOwner(): void {
$this->share(
IShare::TYPE_USER,
$this->filename,
self::TEST_FILES_SHARING_API_USER1,
self::TEST_FILES_SHARING_API_USER2,
- \OCP\Constants::PERMISSION_READ
+ Constants::PERMISSION_READ
);
$this->loginHelper(self::TEST_FILES_SHARING_API_USER2);
- $info = \OC\Files\Filesystem::getFileInfo($this->filename);
+ $info = Filesystem::getFileInfo($this->filename);
$this->assertSame(self::TEST_FILES_SHARING_API_USER1, $info->getOwner()->getUID());
}
diff --git a/apps/files_sharing/tests/SharedMountTest.php b/apps/files_sharing/tests/SharedMountTest.php
index e320b85cb22..cc9c70a241f 100644
--- a/apps/files_sharing/tests/SharedMountTest.php
+++ b/apps/files_sharing/tests/SharedMountTest.php
@@ -1,39 +1,23 @@
<?php
+
/**
- * @copyright Copyright (c) 2016, ownCloud, Inc.
- *
- * @author Björn Schießle <bjoern@schiessle.org>
- * @author Christoph Wurst <christoph@winzerhof-wurst.at>
- * @author Joas Schilling <coding@schilljs.com>
- * @author Lukas Reschke <lukas@statuscode.ch>
- * @author Morris Jobke <hey@morrisjobke.de>
- * @author Robin Appelman <robin@icewind.nl>
- * @author Roeland Jago Douma <roeland@famdouma.nl>
- * @author Thomas Müller <thomas.mueller@tmit.eu>
- * @author Vincent Petry <vincent@nextcloud.com>
- *
- * @license AGPL-3.0
- *
- * This code is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License, version 3,
- * as published by the Free Software Foundation.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU Affero General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License, version 3,
- * along with this program. If not, see <http://www.gnu.org/licenses/>
- *
+ * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
+ * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
+ * SPDX-License-Identifier: AGPL-3.0-only
*/
namespace OCA\Files_Sharing\Tests;
+use OC\Files\Filesystem;
+use OC\Files\View;
use OC\Memcache\ArrayCache;
use OCA\Files_Sharing\MountProvider;
+use OCA\Files_Sharing\SharedMount;
+use OCP\Constants;
use OCP\ICacheFactory;
+use OCP\IDBConnection;
use OCP\IGroupManager;
use OCP\IUserManager;
+use OCP\Server;
use OCP\Share\IShare;
/**
@@ -68,8 +52,8 @@ class SharedMountTest extends TestCase {
$this->view->file_put_contents($this->folder . $this->filename, 'file in subfolder');
$this->view->file_put_contents($this->folder2 . $this->filename, 'file in subfolder2');
- $this->groupManager = \OC::$server->getGroupManager();
- $this->userManager = \OC::$server->getUserManager();
+ $this->groupManager = Server::get(IGroupManager::class);
+ $this->userManager = Server::get(IUserManager::class);
}
protected function tearDown(): void {
@@ -88,7 +72,7 @@ class SharedMountTest extends TestCase {
/**
* test if the mount point moves up if the parent folder no longer exists
*/
- public function testShareMountLoseParentFolder() {
+ public function testShareMountLoseParentFolder(): void {
// share to user
$share = $this->share(
@@ -96,7 +80,7 @@ class SharedMountTest extends TestCase {
$this->folder,
self::TEST_FILES_SHARING_API_USER1,
self::TEST_FILES_SHARING_API_USER2,
- \OCP\Constants::PERMISSION_ALL);
+ Constants::PERMISSION_ALL);
$this->shareManager->acceptShare($share, self::TEST_FILES_SHARING_API_USER2);
$share->setTarget('/foo/bar' . $this->folder);
@@ -120,18 +104,18 @@ class SharedMountTest extends TestCase {
/**
* @medium
*/
- public function testDeleteParentOfMountPoint() {
+ public function testDeleteParentOfMountPoint(): void {
// share to user
$share = $this->share(
IShare::TYPE_USER,
$this->folder,
self::TEST_FILES_SHARING_API_USER1,
self::TEST_FILES_SHARING_API_USER2,
- \OCP\Constants::PERMISSION_ALL
+ Constants::PERMISSION_ALL
);
self::loginHelper(self::TEST_FILES_SHARING_API_USER2);
- $user2View = new \OC\Files\View('/' . self::TEST_FILES_SHARING_API_USER2 . '/files');
+ $user2View = new View('/' . self::TEST_FILES_SHARING_API_USER2 . '/files');
$this->assertTrue($user2View->file_exists($this->folder));
// create a local folder
@@ -160,31 +144,31 @@ class SharedMountTest extends TestCase {
$this->view->unlink($this->folder);
}
- public function testMoveSharedFile() {
+ public function testMoveSharedFile(): void {
$share = $this->share(
IShare::TYPE_USER,
$this->filename,
self::TEST_FILES_SHARING_API_USER1,
self::TEST_FILES_SHARING_API_USER2,
- \OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_SHARE
+ Constants::PERMISSION_READ | Constants::PERMISSION_UPDATE | Constants::PERMISSION_SHARE
);
self::loginHelper(self::TEST_FILES_SHARING_API_USER2);
- \OC\Files\Filesystem::rename($this->filename, $this->filename . '_renamed');
+ Filesystem::rename($this->filename, $this->filename . '_renamed');
- $this->assertTrue(\OC\Files\Filesystem::file_exists($this->filename . '_renamed'));
- $this->assertFalse(\OC\Files\Filesystem::file_exists($this->filename));
+ $this->assertTrue(Filesystem::file_exists($this->filename . '_renamed'));
+ $this->assertFalse(Filesystem::file_exists($this->filename));
self::loginHelper(self::TEST_FILES_SHARING_API_USER1);
- $this->assertTrue(\OC\Files\Filesystem::file_exists($this->filename));
- $this->assertFalse(\OC\Files\Filesystem::file_exists($this->filename . '_renamed'));
+ $this->assertTrue(Filesystem::file_exists($this->filename));
+ $this->assertFalse(Filesystem::file_exists($this->filename . '_renamed'));
// rename back to original name
self::loginHelper(self::TEST_FILES_SHARING_API_USER2);
- \OC\Files\Filesystem::rename($this->filename . '_renamed', $this->filename);
- $this->assertFalse(\OC\Files\Filesystem::file_exists($this->filename . '_renamed'));
- $this->assertTrue(\OC\Files\Filesystem::file_exists($this->filename));
+ Filesystem::rename($this->filename . '_renamed', $this->filename);
+ $this->assertFalse(Filesystem::file_exists($this->filename . '_renamed'));
+ $this->assertTrue(Filesystem::file_exists($this->filename));
//cleanup
$this->shareManager->deleteShare($share);
@@ -194,7 +178,7 @@ class SharedMountTest extends TestCase {
* share file with a group if a user renames the file the filename should not change
* for the other users
*/
- public function testMoveGroupShare() {
+ public function testMoveGroupShare(): void {
$testGroup = $this->groupManager->createGroup('testGroup');
$user1 = $this->userManager->get(self::TEST_FILES_SHARING_API_USER1);
$user2 = $this->userManager->get(self::TEST_FILES_SHARING_API_USER2);
@@ -209,7 +193,7 @@ class SharedMountTest extends TestCase {
$this->filename,
self::TEST_FILES_SHARING_API_USER1,
'testGroup',
- \OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_SHARE
+ Constants::PERMISSION_READ | Constants::PERMISSION_UPDATE | Constants::PERMISSION_SHARE
);
$this->shareManager->acceptShare($share, $user1->getUID());
$this->shareManager->acceptShare($share, $user2->getUID());
@@ -217,20 +201,20 @@ class SharedMountTest extends TestCase {
self::loginHelper(self::TEST_FILES_SHARING_API_USER2);
- $this->assertTrue(\OC\Files\Filesystem::file_exists($this->filename));
+ $this->assertTrue(Filesystem::file_exists($this->filename));
- \OC\Files\Filesystem::rename($this->filename, 'newFileName');
+ Filesystem::rename($this->filename, 'newFileName');
- $this->assertTrue(\OC\Files\Filesystem::file_exists('newFileName'));
- $this->assertFalse(\OC\Files\Filesystem::file_exists($this->filename));
+ $this->assertTrue(Filesystem::file_exists('newFileName'));
+ $this->assertFalse(Filesystem::file_exists($this->filename));
self::loginHelper(self::TEST_FILES_SHARING_API_USER3);
- $this->assertTrue(\OC\Files\Filesystem::file_exists($this->filename));
- $this->assertFalse(\OC\Files\Filesystem::file_exists('newFileName'));
+ $this->assertTrue(Filesystem::file_exists($this->filename));
+ $this->assertFalse(Filesystem::file_exists('newFileName'));
self::loginHelper(self::TEST_FILES_SHARING_API_USER3);
- $this->assertTrue(\OC\Files\Filesystem::file_exists($this->filename));
- $this->assertFalse(\OC\Files\Filesystem::file_exists('newFileName'));
+ $this->assertTrue(Filesystem::file_exists($this->filename));
+ $this->assertFalse(Filesystem::file_exists('newFileName'));
//cleanup
self::loginHelper(self::TEST_FILES_SHARING_API_USER1);
@@ -241,12 +225,12 @@ class SharedMountTest extends TestCase {
}
/**
- * @dataProvider dataProviderTestStripUserFilesPath
* @param string $path
* @param string $expectedResult
* @param bool $exception if a exception is expected
*/
- public function testStripUserFilesPath($path, $expectedResult, $exception) {
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataProviderTestStripUserFilesPath')]
+ public function testStripUserFilesPath($path, $expectedResult, $exception): void {
$testClass = new DummyTestClassSharedMount(null, null);
try {
$result = $testClass->stripUserFilesPathDummy($path);
@@ -260,7 +244,7 @@ class SharedMountTest extends TestCase {
}
}
- public function dataProviderTestStripUserFilesPath() {
+ public static function dataProviderTestStripUserFilesPath() {
return [
['/user/files/foo.txt', '/foo.txt', false],
['/user/files/folder/foo.txt', '/folder/foo.txt', false],
@@ -275,7 +259,7 @@ class SharedMountTest extends TestCase {
* If the permissions on a group share are upgraded be sure to still respect
* removed shares by a member of that group
*/
- public function testPermissionUpgradeOnUserDeletedGroupShare() {
+ public function testPermissionUpgradeOnUserDeletedGroupShare(): void {
$testGroup = $this->groupManager->createGroup('testGroup');
$user1 = $this->userManager->get(self::TEST_FILES_SHARING_API_USER1);
$user2 = $this->userManager->get(self::TEST_FILES_SHARING_API_USER2);
@@ -284,7 +268,7 @@ class SharedMountTest extends TestCase {
$testGroup->addUser($user2);
$testGroup->addUser($user3);
- $connection = \OC::$server->getDatabaseConnection();
+ $connection = Server::get(IDBConnection::class);
// Share item with group
$fileinfo = $this->view->getFileInfo($this->folder);
@@ -293,7 +277,7 @@ class SharedMountTest extends TestCase {
$this->folder,
self::TEST_FILES_SHARING_API_USER1,
'testGroup',
- \OCP\Constants::PERMISSION_READ
+ Constants::PERMISSION_READ
);
$this->shareManager->acceptShare($share, $user1->getUID());
$this->shareManager->acceptShare($share, $user2->getUID());
@@ -301,14 +285,14 @@ class SharedMountTest extends TestCase {
// Login as user 2 and verify the item exists
self::loginHelper(self::TEST_FILES_SHARING_API_USER2);
- $this->assertTrue(\OC\Files\Filesystem::file_exists($this->folder));
+ $this->assertTrue(Filesystem::file_exists($this->folder));
$result = $this->shareManager->getShareById($share->getFullId(), self::TEST_FILES_SHARING_API_USER2);
$this->assertNotEmpty($result);
- $this->assertEquals(\OCP\Constants::PERMISSION_READ, $result->getPermissions());
+ $this->assertEquals(Constants::PERMISSION_READ, $result->getPermissions());
// Delete the share
- $this->assertTrue(\OC\Files\Filesystem::rmdir($this->folder));
- $this->assertFalse(\OC\Files\Filesystem::file_exists($this->folder));
+ $this->assertTrue(Filesystem::rmdir($this->folder));
+ $this->assertFalse(Filesystem::file_exists($this->folder));
// Verify we do not get a share
$result = $this->shareManager->getShareById($share->getFullId(), self::TEST_FILES_SHARING_API_USER2);
@@ -316,12 +300,12 @@ class SharedMountTest extends TestCase {
// Login as user 1 again and change permissions
self::loginHelper(self::TEST_FILES_SHARING_API_USER1);
- $share->setPermissions(\OCP\Constants::PERMISSION_ALL);
+ $share->setPermissions(Constants::PERMISSION_ALL);
$share = $this->shareManager->updateShare($share);
// Login as user 2 and verify
self::loginHelper(self::TEST_FILES_SHARING_API_USER2);
- $this->assertFalse(\OC\Files\Filesystem::file_exists($this->folder));
+ $this->assertFalse(Filesystem::file_exists($this->folder));
$result = $this->shareManager->getShareById($share->getFullId(), self::TEST_FILES_SHARING_API_USER2);
$this->assertEquals(0, $result->getPermissions());
@@ -337,7 +321,7 @@ class SharedMountTest extends TestCase {
/**
* test if the mount point gets renamed if a folder exists at the target
*/
- public function testShareMountOverFolder() {
+ public function testShareMountOverFolder(): void {
self::loginHelper(self::TEST_FILES_SHARING_API_USER2);
$this->view2->mkdir('bar');
@@ -349,7 +333,7 @@ class SharedMountTest extends TestCase {
$this->folder,
self::TEST_FILES_SHARING_API_USER1,
self::TEST_FILES_SHARING_API_USER2,
- \OCP\Constants::PERMISSION_ALL);
+ Constants::PERMISSION_ALL);
$this->shareManager->acceptShare($share, self::TEST_FILES_SHARING_API_USER2);
$share->setTarget('/bar');
@@ -372,7 +356,7 @@ class SharedMountTest extends TestCase {
/**
* test if the mount point gets renamed if another share exists at the target
*/
- public function testShareMountOverShare() {
+ public function testShareMountOverShare(): void {
// create a shared cache
$caches = [];
$cacheFactory = $this->createMock(ICacheFactory::class);
@@ -392,9 +376,9 @@ class SharedMountTest extends TestCase {
});
// hack to overwrite the cache factory, we can't use the proper "overwriteService" since the mount provider is created before this test is called
- $mountProvider = \OCP\Server::get(MountProvider::class);
+ $mountProvider = Server::get(MountProvider::class);
$reflectionClass = new \ReflectionClass($mountProvider);
- $reflectionCacheFactory = $reflectionClass->getProperty("cacheFactory");
+ $reflectionCacheFactory = $reflectionClass->getProperty('cacheFactory');
$reflectionCacheFactory->setAccessible(true);
$reflectionCacheFactory->setValue($mountProvider, $cacheFactory);
@@ -404,7 +388,7 @@ class SharedMountTest extends TestCase {
$this->folder,
self::TEST_FILES_SHARING_API_USER1,
self::TEST_FILES_SHARING_API_USER2,
- \OCP\Constants::PERMISSION_ALL);
+ Constants::PERMISSION_ALL);
$this->shareManager->acceptShare($share, self::TEST_FILES_SHARING_API_USER2);
$share->setTarget('/foobar');
@@ -417,7 +401,7 @@ class SharedMountTest extends TestCase {
$this->folder2,
self::TEST_FILES_SHARING_API_USER1,
self::TEST_FILES_SHARING_API_USER2,
- \OCP\Constants::PERMISSION_ALL);
+ Constants::PERMISSION_ALL);
$this->shareManager->acceptShare($share2, self::TEST_FILES_SHARING_API_USER2);
$share2->setTarget('/foobar');
@@ -441,7 +425,7 @@ class SharedMountTest extends TestCase {
}
}
-class DummyTestClassSharedMount extends \OCA\Files_Sharing\SharedMount {
+class DummyTestClassSharedMount extends SharedMount {
public function __construct($storage, $mountpoint, $arguments = null, $loader = null) {
// noop
}
diff --git a/apps/files_sharing/tests/SharedStorageTest.php b/apps/files_sharing/tests/SharedStorageTest.php
index 5209a30634a..1c1f0a7b71d 100644
--- a/apps/files_sharing/tests/SharedStorageTest.php
+++ b/apps/files_sharing/tests/SharedStorageTest.php
@@ -1,38 +1,26 @@
<?php
+
/**
- * @copyright Copyright (c) 2016, ownCloud, Inc.
- *
- * @author Björn Schießle <bjoern@schiessle.org>
- * @author Christoph Wurst <christoph@winzerhof-wurst.at>
- * @author Joas Schilling <coding@schilljs.com>
- * @author Morris Jobke <hey@morrisjobke.de>
- * @author Robin Appelman <robin@icewind.nl>
- * @author Roeland Jago Douma <roeland@famdouma.nl>
- * @author Thomas Müller <thomas.mueller@tmit.eu>
- * @author Vincent Petry <vincent@nextcloud.com>
- *
- * @license AGPL-3.0
- *
- * This code is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License, version 3,
- * as published by the Free Software Foundation.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU Affero General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License, version 3,
- * along with this program. If not, see <http://www.gnu.org/licenses/>
- *
+ * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
+ * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
+ * SPDX-License-Identifier: AGPL-3.0-only
*/
namespace OCA\Files_Sharing\Tests;
+use OC\Files\Cache\FailedCache;
+use OC\Files\Filesystem;
+use OC\Files\Storage\FailedStorage;
+use OC\Files\Storage\Storage;
+use OC\Files\Storage\Temporary;
use OC\Files\View;
use OCA\Files_Sharing\SharedStorage;
use OCA\Files_Trashbin\AppInfo\Application;
use OCP\AppFramework\Bootstrap\IBootContext;
+use OCP\Constants;
+use OCP\Files\Config\IMountProviderCollection;
use OCP\Files\NotFoundException;
+use OCP\IUserManager;
+use OCP\Server;
use OCP\Share\IShare;
/**
@@ -54,8 +42,8 @@ class SharedStorageTest extends TestCase {
$this->view->mkdir($this->folder);
// save file with content
- $this->view->file_put_contents($this->filename, "root file");
- $this->view->file_put_contents($this->folder . $this->filename, "file in subfolder");
+ $this->view->file_put_contents($this->filename, 'root file');
+ $this->view->file_put_contents($this->folder . $this->filename, 'file in subfolder');
}
protected function tearDown(): void {
@@ -68,7 +56,7 @@ class SharedStorageTest extends TestCase {
}
}
- \OC\Files\Filesystem::getLoader()->removeStorageWrapper('oc_trashbin');
+ Filesystem::getLoader()->removeStorageWrapper('oc_trashbin');
parent::tearDown();
}
@@ -78,7 +66,7 @@ class SharedStorageTest extends TestCase {
*
* @medium
*/
- public function testParentOfMountPointIsGone() {
+ public function testParentOfMountPointIsGone(): void {
// share to user
$share = $this->share(
@@ -86,11 +74,11 @@ class SharedStorageTest extends TestCase {
$this->folder,
self::TEST_FILES_SHARING_API_USER1,
self::TEST_FILES_SHARING_API_USER2,
- \OCP\Constants::PERMISSION_ALL
+ Constants::PERMISSION_ALL
);
self::loginHelper(self::TEST_FILES_SHARING_API_USER2);
- $user2View = new \OC\Files\View('/' . self::TEST_FILES_SHARING_API_USER2 . '/files');
+ $user2View = new View('/' . self::TEST_FILES_SHARING_API_USER2 . '/files');
$this->assertTrue($user2View->file_exists($this->folder));
// create a local folder
@@ -105,8 +93,8 @@ class SharedStorageTest extends TestCase {
$this->assertFalse($user2View->is_dir($this->folder));
// delete the local folder
- /** @var \OC\Files\Storage\Storage $storage */
- [$storage, $internalPath] = \OC\Files\Filesystem::resolvePath('/' . self::TEST_FILES_SHARING_API_USER2 . '/files/localfolder');
+ /** @var Storage $storage */
+ [$storage, $internalPath] = Filesystem::resolvePath('/' . self::TEST_FILES_SHARING_API_USER2 . '/files/localfolder');
$storage->rmdir($internalPath);
//enforce reload of the mount points
@@ -123,7 +111,7 @@ class SharedStorageTest extends TestCase {
/**
* @medium
*/
- public function testRenamePartFile() {
+ public function testRenamePartFile(): void {
// share to user
$share = $this->share(
@@ -131,12 +119,12 @@ class SharedStorageTest extends TestCase {
$this->folder,
self::TEST_FILES_SHARING_API_USER1,
self::TEST_FILES_SHARING_API_USER2,
- \OCP\Constants::PERMISSION_ALL
+ Constants::PERMISSION_ALL
);
self::loginHelper(self::TEST_FILES_SHARING_API_USER2);
- $user2View = new \OC\Files\View('/' . self::TEST_FILES_SHARING_API_USER2 . '/files');
+ $user2View = new View('/' . self::TEST_FILES_SHARING_API_USER2 . '/files');
$this->assertTrue($user2View->file_exists($this->folder));
@@ -161,7 +149,7 @@ class SharedStorageTest extends TestCase {
$this->shareManager->deleteShare($share);
}
- public function testFilesize() {
+ public function testFilesize(): void {
$folderSize = $this->view->filesize($this->folder);
$file1Size = $this->view->filesize($this->folder . $this->filename);
$file2Size = $this->view->filesize($this->filename);
@@ -171,7 +159,7 @@ class SharedStorageTest extends TestCase {
$this->folder,
self::TEST_FILES_SHARING_API_USER1,
self::TEST_FILES_SHARING_API_USER2,
- \OCP\Constants::PERMISSION_ALL
+ Constants::PERMISSION_ALL
);
$share2 = $this->share(
@@ -179,45 +167,45 @@ class SharedStorageTest extends TestCase {
$this->filename,
self::TEST_FILES_SHARING_API_USER1,
self::TEST_FILES_SHARING_API_USER2,
- \OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_SHARE
+ Constants::PERMISSION_READ | Constants::PERMISSION_UPDATE | Constants::PERMISSION_SHARE
);
self::loginHelper(self::TEST_FILES_SHARING_API_USER2);
// compare file size between user1 and user2, should always be the same
- $this->assertSame($folderSize, \OC\Files\Filesystem::filesize($this->folder));
- $this->assertSame($file1Size, \OC\Files\Filesystem::filesize($this->folder . $this->filename));
- $this->assertSame($file2Size, \OC\Files\Filesystem::filesize($this->filename));
+ $this->assertSame($folderSize, Filesystem::filesize($this->folder));
+ $this->assertSame($file1Size, Filesystem::filesize($this->folder . $this->filename));
+ $this->assertSame($file2Size, Filesystem::filesize($this->filename));
//cleanup
$this->shareManager->deleteShare($share1);
$this->shareManager->deleteShare($share2);
}
- public function testGetPermissions() {
+ public function testGetPermissions(): void {
$share = $this->share(
IShare::TYPE_USER,
$this->folder,
self::TEST_FILES_SHARING_API_USER1,
self::TEST_FILES_SHARING_API_USER2,
- \OCP\Constants::PERMISSION_READ
+ Constants::PERMISSION_READ
);
self::loginHelper(self::TEST_FILES_SHARING_API_USER2);
- $this->assertTrue(\OC\Files\Filesystem::is_dir($this->folder));
+ $this->assertTrue(Filesystem::is_dir($this->folder));
// for the share root we expect:
// the read permissions (1)
// the delete permission (8), to enable unshare
- $rootInfo = \OC\Files\Filesystem::getFileInfo($this->folder);
+ $rootInfo = Filesystem::getFileInfo($this->folder);
$this->assertSame(9, $rootInfo->getPermissions());
// for the file within the shared folder we expect:
// the read permissions (1)
- $subfileInfo = \OC\Files\Filesystem::getFileInfo($this->folder . $this->filename);
+ $subfileInfo = Filesystem::getFileInfo($this->folder . $this->filename);
$this->assertSame(1, $subfileInfo->getPermissions());
@@ -225,7 +213,7 @@ class SharedStorageTest extends TestCase {
$this->shareManager->deleteShare($share);
}
- public function testFopenWithReadOnlyPermission() {
+ public function testFopenWithReadOnlyPermission(): void {
$this->view->file_put_contents($this->folder . '/existing.txt', 'foo');
$share = $this->share(
@@ -233,11 +221,11 @@ class SharedStorageTest extends TestCase {
$this->folder,
self::TEST_FILES_SHARING_API_USER1,
self::TEST_FILES_SHARING_API_USER2,
- \OCP\Constants::PERMISSION_READ
+ Constants::PERMISSION_READ
);
self::loginHelper(self::TEST_FILES_SHARING_API_USER2);
- $user2View = new \OC\Files\View('/' . self::TEST_FILES_SHARING_API_USER2 . '/files');
+ $user2View = new View('/' . self::TEST_FILES_SHARING_API_USER2 . '/files');
// part file should be forbidden
$handle = $user2View->fopen($this->folder . '/test.txt.part', 'w');
@@ -257,7 +245,7 @@ class SharedStorageTest extends TestCase {
$this->shareManager->deleteShare($share);
}
- public function testFopenWithCreateOnlyPermission() {
+ public function testFopenWithCreateOnlyPermission(): void {
$this->view->file_put_contents($this->folder . '/existing.txt', 'foo');
$fileinfoFolder = $this->view->getFileInfo($this->folder);
@@ -266,11 +254,11 @@ class SharedStorageTest extends TestCase {
$this->folder,
self::TEST_FILES_SHARING_API_USER1,
self::TEST_FILES_SHARING_API_USER2,
- \OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_CREATE
+ Constants::PERMISSION_READ | Constants::PERMISSION_CREATE
);
self::loginHelper(self::TEST_FILES_SHARING_API_USER2);
- $user2View = new \OC\Files\View('/' . self::TEST_FILES_SHARING_API_USER2 . '/files');
+ $user2View = new View('/' . self::TEST_FILES_SHARING_API_USER2 . '/files');
// create part file allowed
$handle = $user2View->fopen($this->folder . '/test.txt.part', 'w');
@@ -304,7 +292,7 @@ class SharedStorageTest extends TestCase {
$this->shareManager->deleteShare($share);
}
- public function testFopenWithUpdateOnlyPermission() {
+ public function testFopenWithUpdateOnlyPermission(): void {
$this->view->file_put_contents($this->folder . '/existing.txt', 'foo');
$share = $this->share(
@@ -312,11 +300,11 @@ class SharedStorageTest extends TestCase {
$this->folder,
self::TEST_FILES_SHARING_API_USER1,
self::TEST_FILES_SHARING_API_USER2,
- \OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_UPDATE
+ Constants::PERMISSION_READ | Constants::PERMISSION_UPDATE
);
self::loginHelper(self::TEST_FILES_SHARING_API_USER2);
- $user2View = new \OC\Files\View('/' . self::TEST_FILES_SHARING_API_USER2 . '/files');
+ $user2View = new View('/' . self::TEST_FILES_SHARING_API_USER2 . '/files');
// create part file allowed
$handle = $user2View->fopen($this->folder . '/test.txt.part', 'w');
@@ -350,7 +338,7 @@ class SharedStorageTest extends TestCase {
$this->shareManager->deleteShare($share);
}
- public function testFopenWithDeleteOnlyPermission() {
+ public function testFopenWithDeleteOnlyPermission(): void {
$this->view->file_put_contents($this->folder . '/existing.txt', 'foo');
$share = $this->share(
@@ -358,11 +346,11 @@ class SharedStorageTest extends TestCase {
$this->folder,
self::TEST_FILES_SHARING_API_USER1,
self::TEST_FILES_SHARING_API_USER2,
- \OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_DELETE
+ Constants::PERMISSION_READ | Constants::PERMISSION_DELETE
);
self::loginHelper(self::TEST_FILES_SHARING_API_USER2);
- $user2View = new \OC\Files\View('/' . self::TEST_FILES_SHARING_API_USER2 . '/files');
+ $user2View = new View('/' . self::TEST_FILES_SHARING_API_USER2 . '/files');
// part file should be forbidden
$handle = $user2View->fopen($this->folder . '/test.txt.part', 'w');
@@ -382,8 +370,8 @@ class SharedStorageTest extends TestCase {
$this->shareManager->deleteShare($share);
}
- public function testMountSharesOtherUser() {
- $rootView = new \OC\Files\View('');
+ public function testMountSharesOtherUser(): void {
+ $rootView = new View('');
self::loginHelper(self::TEST_FILES_SHARING_API_USER1);
// share 2 different files with 2 different users
@@ -392,22 +380,22 @@ class SharedStorageTest extends TestCase {
$this->folder,
self::TEST_FILES_SHARING_API_USER1,
self::TEST_FILES_SHARING_API_USER2,
- \OCP\Constants::PERMISSION_ALL
+ Constants::PERMISSION_ALL
);
$share2 = $this->share(
IShare::TYPE_USER,
$this->filename,
self::TEST_FILES_SHARING_API_USER1,
self::TEST_FILES_SHARING_API_USER3,
- \OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_SHARE
+ Constants::PERMISSION_READ | Constants::PERMISSION_UPDATE | Constants::PERMISSION_SHARE
);
self::loginHelper(self::TEST_FILES_SHARING_API_USER2);
$this->assertTrue($rootView->file_exists('/' . self::TEST_FILES_SHARING_API_USER2 . '/files/' . $this->folder));
- $mountConfigManager = \OC::$server->getMountProviderCollection();
- $mounts = $mountConfigManager->getMountsForUser(\OC::$server->getUserManager()->get(self::TEST_FILES_SHARING_API_USER3));
- array_walk($mounts, [\OC\Files\Filesystem::getMountManager(), 'addMount']);
+ $mountConfigManager = Server::get(IMountProviderCollection::class);
+ $mounts = $mountConfigManager->getMountsForUser(Server::get(IUserManager::class)->get(self::TEST_FILES_SHARING_API_USER3));
+ array_walk($mounts, [Filesystem::getMountManager(), 'addMount']);
$this->assertTrue($rootView->file_exists('/' . self::TEST_FILES_SHARING_API_USER3 . '/files/' . $this->filename));
@@ -423,7 +411,7 @@ class SharedStorageTest extends TestCase {
$this->shareManager->deleteShare($share2);
}
- public function testCopyFromStorage() {
+ public function testCopyFromStorage(): void {
self::loginHelper(self::TEST_FILES_SHARING_API_USER1);
$share = $this->share(
@@ -431,20 +419,17 @@ class SharedStorageTest extends TestCase {
$this->folder,
self::TEST_FILES_SHARING_API_USER1,
self::TEST_FILES_SHARING_API_USER2,
- \OCP\Constants::PERMISSION_ALL
+ Constants::PERMISSION_ALL
);
self::loginHelper(self::TEST_FILES_SHARING_API_USER2);
- $view = new \OC\Files\View('/' . self::TEST_FILES_SHARING_API_USER2 . '/files');
+ $view = new View('/' . self::TEST_FILES_SHARING_API_USER2 . '/files');
$this->assertTrue($view->file_exists($this->folder));
- /**
- * @var \OCP\Files\Storage $sharedStorage
- */
[$sharedStorage,] = $view->resolvePath($this->folder);
$this->assertTrue($sharedStorage->instanceOfStorage('OCA\Files_Sharing\ISharedStorage'));
- $sourceStorage = new \OC\Files\Storage\Temporary([]);
+ $sourceStorage = new Temporary([]);
$sourceStorage->file_put_contents('foo.txt', 'asd');
$sharedStorage->copyFromStorage($sourceStorage, 'foo.txt', 'bar.txt');
@@ -456,7 +441,7 @@ class SharedStorageTest extends TestCase {
$this->shareManager->deleteShare($share);
}
- public function testMoveFromStorage() {
+ public function testMoveFromStorage(): void {
self::loginHelper(self::TEST_FILES_SHARING_API_USER1);
$share = $this->share(
@@ -464,21 +449,19 @@ class SharedStorageTest extends TestCase {
$this->folder,
self::TEST_FILES_SHARING_API_USER1,
self::TEST_FILES_SHARING_API_USER2,
- \OCP\Constants::PERMISSION_ALL
+ Constants::PERMISSION_ALL
);
self::loginHelper(self::TEST_FILES_SHARING_API_USER2);
- $view = new \OC\Files\View('/' . self::TEST_FILES_SHARING_API_USER2 . '/files');
+ $view = new View('/' . self::TEST_FILES_SHARING_API_USER2 . '/files');
$this->assertTrue($view->file_exists($this->folder));
- /**
- * @var \OCP\Files\Storage $sharedStorage
- */
[$sharedStorage,] = $view->resolvePath($this->folder);
$this->assertTrue($sharedStorage->instanceOfStorage('OCA\Files_Sharing\ISharedStorage'));
- $sourceStorage = new \OC\Files\Storage\Temporary([]);
+ $sourceStorage = new Temporary([]);
$sourceStorage->file_put_contents('foo.txt', 'asd');
+ $sourceStorage->getScanner()->scan('');
$sharedStorage->moveFromStorage($sourceStorage, 'foo.txt', 'bar.txt');
$this->assertTrue($sharedStorage->file_exists('bar.txt'));
@@ -489,13 +472,13 @@ class SharedStorageTest extends TestCase {
$this->shareManager->deleteShare($share);
}
- public function testNameConflict() {
+ public function testNameConflict(): void {
self::loginHelper(self::TEST_FILES_SHARING_API_USER1);
- $view1 = new \OC\Files\View('/' . self::TEST_FILES_SHARING_API_USER1 . '/files');
+ $view1 = new View('/' . self::TEST_FILES_SHARING_API_USER1 . '/files');
$view1->mkdir('foo');
self::loginHelper(self::TEST_FILES_SHARING_API_USER3);
- $view3 = new \OC\Files\View('/' . self::TEST_FILES_SHARING_API_USER3 . '/files');
+ $view3 = new View('/' . self::TEST_FILES_SHARING_API_USER3 . '/files');
$view3->mkdir('foo');
// share a folder with the same name from two different users to the same user
@@ -506,7 +489,7 @@ class SharedStorageTest extends TestCase {
'foo',
self::TEST_FILES_SHARING_API_USER1,
self::TEST_FILES_SHARING_API_GROUP1,
- \OCP\Constants::PERMISSION_ALL
+ Constants::PERMISSION_ALL
);
$this->shareManager->acceptShare($share1, self::TEST_FILES_SHARING_API_USER2);
@@ -519,19 +502,19 @@ class SharedStorageTest extends TestCase {
'foo',
self::TEST_FILES_SHARING_API_USER3,
self::TEST_FILES_SHARING_API_GROUP1,
- \OCP\Constants::PERMISSION_ALL
+ Constants::PERMISSION_ALL
);
$this->shareManager->acceptShare($share2, self::TEST_FILES_SHARING_API_USER2);
self::loginHelper(self::TEST_FILES_SHARING_API_USER2);
- $view2 = new \OC\Files\View('/' . self::TEST_FILES_SHARING_API_USER2 . '/files');
+ $view2 = new View('/' . self::TEST_FILES_SHARING_API_USER2 . '/files');
$this->assertTrue($view2->file_exists('/foo'));
$this->assertTrue($view2->file_exists('/foo (2)'));
$mount = $view2->getMount('/foo');
$this->assertInstanceOf('\OCA\Files_Sharing\SharedMount', $mount);
- /** @var \OCA\Files_Sharing\SharedStorage $storage */
+ /** @var SharedStorage $storage */
$storage = $mount->getStorage();
$this->assertEquals(self::TEST_FILES_SHARING_API_USER1, $storage->getOwner(''));
@@ -540,7 +523,7 @@ class SharedStorageTest extends TestCase {
$this->shareManager->deleteShare($share2);
}
- public function testOwnerPermissions() {
+ public function testOwnerPermissions(): void {
self::loginHelper(self::TEST_FILES_SHARING_API_USER1);
$share = $this->share(
@@ -548,11 +531,11 @@ class SharedStorageTest extends TestCase {
$this->folder,
self::TEST_FILES_SHARING_API_USER1,
self::TEST_FILES_SHARING_API_USER2,
- \OCP\Constants::PERMISSION_ALL - \OCP\Constants::PERMISSION_DELETE
+ Constants::PERMISSION_ALL - Constants::PERMISSION_DELETE
);
self::loginHelper(self::TEST_FILES_SHARING_API_USER2);
- $view = new \OC\Files\View('/' . self::TEST_FILES_SHARING_API_USER2 . '/files');
+ $view = new View('/' . self::TEST_FILES_SHARING_API_USER2 . '/files');
$this->assertTrue($view->file_exists($this->folder));
$view->file_put_contents($this->folder . '/newfile.txt', 'asd');
@@ -560,14 +543,14 @@ class SharedStorageTest extends TestCase {
self::loginHelper(self::TEST_FILES_SHARING_API_USER1);
$this->assertTrue($this->view->file_exists($this->folder . '/newfile.txt'));
- $this->assertEquals(\OCP\Constants::PERMISSION_ALL - \OCP\Constants::PERMISSION_CREATE,
+ $this->assertEquals(Constants::PERMISSION_ALL - Constants::PERMISSION_CREATE,
$this->view->getFileInfo($this->folder . '/newfile.txt')->getPermissions());
$this->view->unlink($this->folder);
$this->shareManager->deleteShare($share);
}
- public function testInitWithNonExistingUser() {
+ public function testInitWithNonExistingUser(): void {
$share = $this->createMock(IShare::class);
$share->method('getShareOwner')->willReturn('unexist');
$ownerView = $this->createMock(View::class);
@@ -579,16 +562,16 @@ class SharedStorageTest extends TestCase {
]);
// trigger init
- $this->assertInstanceOf(\OC\Files\Storage\FailedStorage::class, $storage->getSourceStorage());
- $this->assertInstanceOf(\OC\Files\Cache\FailedCache::class, $storage->getCache());
+ $this->assertInstanceOf(FailedStorage::class, $storage->getSourceStorage());
+ $this->assertInstanceOf(FailedCache::class, $storage->getCache());
}
- public function testInitWithNotFoundSource() {
+ public function testInitWithNotFoundSource(): void {
$share = $this->createMock(IShare::class);
$share->method('getShareOwner')->willReturn(self::TEST_FILES_SHARING_API_USER1);
$share->method('getNodeId')->willReturn(1);
$ownerView = $this->createMock(View::class);
- $ownerView->method('getPath')->will($this->throwException(new NotFoundException()));
+ $ownerView->method('getPath')->willThrowException(new NotFoundException());
$storage = new SharedStorage([
'ownerView' => $ownerView,
'superShare' => $share,
@@ -597,7 +580,33 @@ class SharedStorageTest extends TestCase {
]);
// trigger init
- $this->assertInstanceOf(\OC\Files\Storage\FailedStorage::class, $storage->getSourceStorage());
- $this->assertInstanceOf(\OC\Files\Cache\FailedCache::class, $storage->getCache());
+ $this->assertInstanceOf(FailedStorage::class, $storage->getSourceStorage());
+ $this->assertInstanceOf(FailedCache::class, $storage->getCache());
+ }
+
+ public function testCopyPermissions(): void {
+ self::loginHelper(self::TEST_FILES_SHARING_API_USER1);
+
+ $share = $this->share(
+ IShare::TYPE_USER,
+ $this->filename,
+ self::TEST_FILES_SHARING_API_USER1,
+ self::TEST_FILES_SHARING_API_USER2,
+ Constants::PERMISSION_ALL - Constants::PERMISSION_CREATE - Constants::PERMISSION_DELETE
+ );
+
+ self::loginHelper(self::TEST_FILES_SHARING_API_USER2);
+ $view = new View('/' . self::TEST_FILES_SHARING_API_USER2 . '/files');
+ $this->assertTrue($view->file_exists($this->filename));
+
+ $this->assertTrue($view->copy($this->filename, '/target.txt'));
+
+ $this->assertTrue($view->file_exists('/target.txt'));
+
+ $info = $view->getFileInfo('/target.txt');
+ $this->assertEquals(Constants::PERMISSION_ALL - Constants::PERMISSION_CREATE, $info->getPermissions());
+
+ $this->view->unlink($this->filename);
+ $this->shareManager->deleteShare($share);
}
}
diff --git a/apps/files_sharing/tests/SharesReminderJobTest.php b/apps/files_sharing/tests/SharesReminderJobTest.php
new file mode 100644
index 00000000000..ce468e279ec
--- /dev/null
+++ b/apps/files_sharing/tests/SharesReminderJobTest.php
@@ -0,0 +1,193 @@
+<?php
+
+declare(strict_types=1);
+/**
+ * SPDX-FileCopyrightText: 2024 Nextcloud GmbH and Nextcloud contributors
+ * SPDX-License-Identifier: AGPL-3.0-or-later
+ */
+namespace OCA\Files_Sharing\Tests;
+
+use OC\SystemConfig;
+use OCA\Files_Sharing\SharesReminderJob;
+use OCP\AppFramework\Utility\ITimeFactory;
+use OCP\Constants;
+use OCP\Defaults;
+use OCP\Files\IMimeTypeLoader;
+use OCP\Files\IRootFolder;
+use OCP\IDBConnection;
+use OCP\IURLGenerator;
+use OCP\IUserManager;
+use OCP\L10N\IFactory;
+use OCP\Mail\IMailer;
+use OCP\Mail\IMessage;
+use OCP\Server;
+use OCP\Share\IManager;
+use OCP\Share\IShare;
+use PHPUnit\Framework\MockObject\MockObject;
+use Psr\Log\LoggerInterface;
+
+/**
+ * Class SharesReminderJobTest
+ *
+ * @group DB
+ *
+ * @package OCA\Files_Sharing\Tests
+ */
+class SharesReminderJobTest extends \Test\TestCase {
+ private SharesReminderJob $job;
+ private IDBConnection $db;
+ private IManager $shareManager;
+ private IUserManager $userManager;
+ private IMailer|MockObject $mailer;
+ private string $user1;
+ private string $user2;
+
+ protected function setUp(): void {
+ parent::setUp();
+
+ $this->db = Server::get(IDBConnection::class);
+ $this->shareManager = Server::get(IManager::class);
+ $this->userManager = Server::get(IUserManager::class);
+ $this->mailer = $this->createMock(IMailer::class);
+
+ // Clear occasional leftover shares from other tests
+ $this->db->executeUpdate('DELETE FROM `*PREFIX*share`');
+
+ $this->user1 = $this->getUniqueID('user1_');
+ $this->user2 = $this->getUniqueID('user2_');
+
+ $user1 = $this->userManager->createUser($this->user1, 'longrandompassword');
+ $user2 = $this->userManager->createUser($this->user2, 'longrandompassword');
+ $user1->setSystemEMailAddress('user1@test.com');
+ $user2->setSystemEMailAddress('user2@test.com');
+
+ \OC::registerShareHooks(Server::get(SystemConfig::class));
+
+ $this->job = new SharesReminderJob(
+ Server::get(ITimeFactory::class),
+ $this->db,
+ Server::get(IManager::class),
+ $this->userManager,
+ Server::get(LoggerInterface::class),
+ Server::get(IURLGenerator::class),
+ Server::get(IFactory::class),
+ $this->mailer,
+ Server::get(Defaults::class),
+ Server::get(IMimeTypeLoader::class),
+ );
+ }
+
+ protected function tearDown(): void {
+ $this->db->executeUpdate('DELETE FROM `*PREFIX*share`');
+
+ $userManager = Server::get(IUserManager::class);
+ $user1 = $userManager->get($this->user1);
+ if ($user1) {
+ $user1->delete();
+ }
+ $user2 = $userManager->get($this->user2);
+ if ($user2) {
+ $user2->delete();
+ }
+
+ $this->logout();
+
+ parent::tearDown();
+ }
+
+ public static function dataSharesReminder() {
+ $someMail = 'test@test.com';
+ $noExpirationDate = null;
+ $today = new \DateTime();
+ // For expiration dates, the time is always automatically set to zero by ShareAPIController
+ $today->setTime(0, 0);
+ $nearFuture = new \DateTime();
+ $nearFuture->setTimestamp($today->getTimestamp() + 86400 * 1);
+ $farFuture = new \DateTime();
+ $farFuture->setTimestamp($today->getTimestamp() + 86400 * 2);
+ $permissionRead = Constants::PERMISSION_READ;
+ $permissionCreate = $permissionRead | Constants::PERMISSION_CREATE;
+ $permissionUpdate = $permissionRead | Constants::PERMISSION_UPDATE;
+ $permissionDelete = $permissionRead | Constants::PERMISSION_DELETE;
+ $permissionAll = Constants::PERMISSION_ALL;
+
+ return [
+ // No reminders for folders without expiration date
+ [$noExpirationDate, '', false, $permissionRead, false],
+ [$noExpirationDate, '', false, $permissionCreate, false],
+ [$noExpirationDate, '', true, $permissionDelete, false],
+ [$noExpirationDate, '', true, $permissionCreate, false],
+ [$noExpirationDate, $someMail, false, $permissionUpdate, false],
+ [$noExpirationDate, $someMail, false, $permissionCreate, false],
+ [$noExpirationDate, $someMail, true, $permissionRead, false],
+ [$noExpirationDate, $someMail, true, $permissionAll, false],
+ // No reminders for folders with expiration date in the far future
+ [$farFuture, '', false, $permissionRead, false],
+ [$farFuture, '', false, $permissionCreate, false],
+ [$farFuture, '', true, $permissionDelete, false],
+ [$farFuture, '', true, $permissionCreate, false],
+ [$farFuture, $someMail, false, $permissionUpdate, false],
+ [$farFuture, $someMail, false, $permissionCreate, false],
+ [$farFuture, $someMail, true, $permissionRead, false],
+ [$farFuture, $someMail, true, $permissionAll, false],
+ /* Should send reminders for folders with expiration date in the near future
+ if the folder is empty and the user has write permission */
+ [$nearFuture, '', false, $permissionRead, false],
+ [$nearFuture, '', false, $permissionCreate, false],
+ [$nearFuture, '', true, $permissionDelete, false],
+ [$nearFuture, '', true, $permissionCreate, true],
+ [$nearFuture, $someMail, false, $permissionUpdate, false],
+ [$nearFuture, $someMail, false, $permissionCreate, false],
+ [$nearFuture, $someMail, true, $permissionRead, false],
+ [$nearFuture, $someMail, true, $permissionAll, true],
+ ];
+ }
+
+ /**
+ *
+ * @param \DateTime|null $expirationDate Share expiration date
+ * @param string $email Share with this email. If empty, the share is of type TYPE_USER and the sharee is user2
+ * @param bool $isEmpty Is share folder empty?
+ * @param int $permissions
+ * @param bool $shouldBeReminded
+ */
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataSharesReminder')]
+ public function testSharesReminder(
+ ?\DateTime $expirationDate, string $email, bool $isEmpty, int $permissions, bool $shouldBeReminded,
+ ): void {
+ $this->loginAsUser($this->user1);
+
+ $user1Folder = Server::get(IRootFolder::class)->getUserFolder($this->user1);
+ $testFolder = $user1Folder->newFolder('test');
+
+ if (!$isEmpty) {
+ $testFolder->newFile('some_file.txt', 'content');
+ }
+
+ $share = $this->shareManager->newShare();
+
+ $share->setNode($testFolder)
+ ->setShareType(($email ? IShare::TYPE_EMAIL : IShare::TYPE_USER))
+ ->setPermissions($permissions)
+ ->setSharedBy($this->user1)
+ ->setSharedWith(($email ?: $this->user2))
+ ->setExpirationDate($expirationDate);
+ $share = $this->shareManager->createShare($share);
+
+ $this->logout();
+ $messageMock = $this->createMock(IMessage::class);
+ $this->mailer->method('createMessage')->willReturn($messageMock);
+ $this->mailer
+ ->expects(($shouldBeReminded ? $this->once() : $this->never()))
+ ->method('send')
+ ->with($messageMock);
+ $messageMock
+ ->expects(($shouldBeReminded ? $this->once() : $this->never()))
+ ->method('setTo')
+ ->with([$email ?: $this->userManager->get($this->user2)->getSystemEMailAddress()]);
+ $this->assertSame(false, $share->getReminderSent());
+ $this->job->run([]);
+ $share = $this->shareManager->getShareById($share->getFullId());
+ $this->assertEquals($shouldBeReminded, $share->getReminderSent());
+ }
+}
diff --git a/apps/files_sharing/tests/SizePropagationTest.php b/apps/files_sharing/tests/SizePropagationTest.php
index ddb77459073..e1b67abca90 100644
--- a/apps/files_sharing/tests/SizePropagationTest.php
+++ b/apps/files_sharing/tests/SizePropagationTest.php
@@ -1,31 +1,16 @@
<?php
+
/**
- * @copyright Copyright (c) 2016, ownCloud, Inc.
- *
- * @author Christoph Wurst <christoph@winzerhof-wurst.at>
- * @author Joas Schilling <coding@schilljs.com>
- * @author Robin Appelman <robin@icewind.nl>
- * @author Roeland Jago Douma <roeland@famdouma.nl>
- * @author Thomas Müller <thomas.mueller@tmit.eu>
- *
- * @license AGPL-3.0
- *
- * This code is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License, version 3,
- * as published by the Free Software Foundation.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU Affero General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License, version 3,
- * along with this program. If not, see <http://www.gnu.org/licenses/>
- *
+ * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
+ * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
+ * SPDX-License-Identifier: AGPL-3.0-only
*/
namespace OCA\Files_Sharing\Tests;
use OC\Files\View;
+use OCP\Constants;
+use OCP\ITempManager;
+use OCP\Server;
use OCP\Share\IShare;
use Test\Traits\UserTrait;
@@ -41,13 +26,13 @@ class SizePropagationTest extends TestCase {
protected function setupUser($name, $password = '') {
$this->createUser($name, $password);
- $tmpFolder = \OC::$server->getTempManager()->getTemporaryFolder();
+ $tmpFolder = Server::get(ITempManager::class)->getTemporaryFolder();
$this->registerMount($name, '\OC\Files\Storage\Local', '/' . $name, ['datadir' => $tmpFolder]);
$this->loginAsUser($name);
return new View('/' . $name . '/files');
}
- public function testSizePropagationWhenOwnerChangesFile() {
+ public function testSizePropagationWhenOwnerChangesFile(): void {
$recipientView = $this->setupUser(self::TEST_FILES_SHARING_API_USER1);
$ownerView = $this->setupUser(self::TEST_FILES_SHARING_API_USER2);
@@ -59,7 +44,7 @@ class SizePropagationTest extends TestCase {
'/sharedfolder',
self::TEST_FILES_SHARING_API_USER2,
self::TEST_FILES_SHARING_API_USER1,
- \OCP\Constants::PERMISSION_ALL
+ Constants::PERMISSION_ALL
);
$ownerRootInfo = $ownerView->getFileInfo('', false);
@@ -82,7 +67,7 @@ class SizePropagationTest extends TestCase {
$this->assertEquals($ownerRootInfo->getSize() + 3, $newOwnerRootInfo->getSize());
}
- public function testSizePropagationWhenRecipientChangesFile() {
+ public function testSizePropagationWhenRecipientChangesFile(): void {
$recipientView = $this->setupUser(self::TEST_FILES_SHARING_API_USER1);
$ownerView = $this->setupUser(self::TEST_FILES_SHARING_API_USER2);
@@ -94,7 +79,7 @@ class SizePropagationTest extends TestCase {
'/sharedfolder',
self::TEST_FILES_SHARING_API_USER2,
self::TEST_FILES_SHARING_API_USER1,
- \OCP\Constants::PERMISSION_ALL
+ Constants::PERMISSION_ALL
);
$ownerRootInfo = $ownerView->getFileInfo('', false);
diff --git a/apps/files_sharing/tests/TestCase.php b/apps/files_sharing/tests/TestCase.php
index 84e436b17cd..9a6935e46b6 100644
--- a/apps/files_sharing/tests/TestCase.php
+++ b/apps/files_sharing/tests/TestCase.php
@@ -1,43 +1,28 @@
<?php
+
/**
- * @copyright Copyright (c) 2016, ownCloud, Inc.
- *
- * @author Björn Schießle <bjoern@schiessle.org>
- * @author Christoph Wurst <christoph@winzerhof-wurst.at>
- * @author Joas Schilling <coding@schilljs.com>
- * @author John Molakvoæ <skjnldsv@protonmail.com>
- * @author Jörn Friedrich Dreyer <jfd@butonic.de>
- * @author Lukas Reschke <lukas@statuscode.ch>
- * @author Morris Jobke <hey@morrisjobke.de>
- * @author Robin Appelman <robin@icewind.nl>
- * @author Robin McCorkell <robin@mccorkell.me.uk>
- * @author Roeland Jago Douma <roeland@famdouma.nl>
- * @author Thomas Müller <thomas.mueller@tmit.eu>
- * @author Vincent Petry <vincent@nextcloud.com>
- *
- * @license AGPL-3.0
- *
- * This code is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License, version 3,
- * as published by the Free Software Foundation.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU Affero General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License, version 3,
- * along with this program. If not, see <http://www.gnu.org/licenses/>
- *
+ * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
+ * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
+ * SPDX-License-Identifier: AGPL-3.0-only
*/
namespace OCA\Files_Sharing\Tests;
+use OC\Files\Cache\Storage;
use OC\Files\Filesystem;
+use OC\Files\View;
+use OC\Group\Database;
+use OC\SystemConfig;
use OC\User\DisplayNameCache;
use OCA\Files_Sharing\AppInfo\Application;
use OCA\Files_Sharing\External\MountProvider as ExternalMountProvider;
use OCA\Files_Sharing\MountProvider;
use OCP\Files\Config\IMountProviderCollection;
+use OCP\Files\IRootFolder;
+use OCP\IDBConnection;
+use OCP\IGroupManager;
+use OCP\IUserManager;
+use OCP\IUserSession;
+use OCP\Server;
use OCP\Share\IShare;
use Test\Traits\MountProviderTrait;
@@ -51,21 +36,21 @@ use Test\Traits\MountProviderTrait;
abstract class TestCase extends \Test\TestCase {
use MountProviderTrait;
- public const TEST_FILES_SHARING_API_USER1 = "test-share-user1";
- public const TEST_FILES_SHARING_API_USER2 = "test-share-user2";
- public const TEST_FILES_SHARING_API_USER3 = "test-share-user3";
- public const TEST_FILES_SHARING_API_USER4 = "test-share-user4";
+ public const TEST_FILES_SHARING_API_USER1 = 'test-share-user1';
+ public const TEST_FILES_SHARING_API_USER2 = 'test-share-user2';
+ public const TEST_FILES_SHARING_API_USER3 = 'test-share-user3';
+ public const TEST_FILES_SHARING_API_USER4 = 'test-share-user4';
- public const TEST_FILES_SHARING_API_GROUP1 = "test-share-group1";
+ public const TEST_FILES_SHARING_API_GROUP1 = 'test-share-group1';
public $filename;
public $data;
/**
- * @var \OC\Files\View
+ * @var View
*/
public $view;
/**
- * @var \OC\Files\View
+ * @var View
*/
public $view2;
public $folder;
@@ -73,7 +58,7 @@ abstract class TestCase extends \Test\TestCase {
/** @var \OCP\Share\IManager */
protected $shareManager;
- /** @var \OCP\Files\IRootFolder */
+ /** @var IRootFolder */
protected $rootFolder;
public static function setUpBeforeClass(): void {
@@ -81,22 +66,22 @@ abstract class TestCase extends \Test\TestCase {
$app = new Application();
$app->registerMountProviders(
- \OC::$server->get(IMountProviderCollection::class),
- \OC::$server->get(MountProvider::class),
- \OC::$server->get(ExternalMountProvider::class),
+ Server::get(IMountProviderCollection::class),
+ Server::get(MountProvider::class),
+ Server::get(ExternalMountProvider::class),
);
// reset backend
- \OC_User::clearBackends();
- \OC::$server->getGroupManager()->clearBackends();
+ Server::get(IUserManager::class)->clearBackends();
+ Server::get(IGroupManager::class)->clearBackends();
// clear share hooks
\OC_Hook::clear('OCP\\Share');
- \OC::registerShareHooks(\OC::$server->getSystemConfig());
+ \OC::registerShareHooks(Server::get(SystemConfig::class));
// create users
$backend = new \Test\Util\User\Dummy();
- \OC_User::useBackend($backend);
+ Server::get(IUserManager::class)->registerBackend($backend);
$backend->createUser(self::TEST_FILES_SHARING_API_USER1, self::TEST_FILES_SHARING_API_USER1);
$backend->createUser(self::TEST_FILES_SHARING_API_USER2, self::TEST_FILES_SHARING_API_USER2);
$backend->createUser(self::TEST_FILES_SHARING_API_USER3, self::TEST_FILES_SHARING_API_USER3);
@@ -116,35 +101,35 @@ abstract class TestCase extends \Test\TestCase {
$groupBackend->addToGroup(self::TEST_FILES_SHARING_API_USER3, 'group2');
$groupBackend->addToGroup(self::TEST_FILES_SHARING_API_USER4, 'group3');
$groupBackend->addToGroup(self::TEST_FILES_SHARING_API_USER2, self::TEST_FILES_SHARING_API_GROUP1);
- \OC::$server->getGroupManager()->addBackend($groupBackend);
+ Server::get(IGroupManager::class)->addBackend($groupBackend);
}
protected function setUp(): void {
parent::setUp();
- \OC::$server->get(DisplayNameCache::class)->clear();
+ Server::get(DisplayNameCache::class)->clear();
//login as user1
- self::loginHelper(self::TEST_FILES_SHARING_API_USER1);
+ $this->loginHelper(self::TEST_FILES_SHARING_API_USER1);
$this->data = 'foobar';
- $this->view = new \OC\Files\View('/' . self::TEST_FILES_SHARING_API_USER1 . '/files');
- $this->view2 = new \OC\Files\View('/' . self::TEST_FILES_SHARING_API_USER2 . '/files');
+ $this->view = new View('/' . self::TEST_FILES_SHARING_API_USER1 . '/files');
+ $this->view2 = new View('/' . self::TEST_FILES_SHARING_API_USER2 . '/files');
- $this->shareManager = \OC::$server->getShareManager();
- $this->rootFolder = \OC::$server->getRootFolder();
+ $this->shareManager = Server::get(\OCP\Share\IManager::class);
+ $this->rootFolder = Server::get(IRootFolder::class);
}
protected function tearDown(): void {
- $qb = \OC::$server->getDatabaseConnection()->getQueryBuilder();
+ $qb = Server::get(IDBConnection::class)->getQueryBuilder();
$qb->delete('share');
$qb->execute();
- $qb = \OC::$server->getDatabaseConnection()->getQueryBuilder();
+ $qb = Server::get(IDBConnection::class)->getQueryBuilder();
$qb->delete('mounts');
$qb->execute();
- $qb = \OC::$server->getDatabaseConnection()->getQueryBuilder();
- $qb->delete('filecache');
+ $qb = Server::get(IDBConnection::class)->getQueryBuilder();
+ $qb->delete('filecache')->runAcrossAllShards();
$qb->execute();
parent::tearDown();
@@ -152,21 +137,21 @@ abstract class TestCase extends \Test\TestCase {
public static function tearDownAfterClass(): void {
// cleanup users
- $user = \OC::$server->getUserManager()->get(self::TEST_FILES_SHARING_API_USER1);
+ $user = Server::get(IUserManager::class)->get(self::TEST_FILES_SHARING_API_USER1);
if ($user !== null) {
$user->delete();
}
- $user = \OC::$server->getUserManager()->get(self::TEST_FILES_SHARING_API_USER2);
+ $user = Server::get(IUserManager::class)->get(self::TEST_FILES_SHARING_API_USER2);
if ($user !== null) {
$user->delete();
}
- $user = \OC::$server->getUserManager()->get(self::TEST_FILES_SHARING_API_USER3);
+ $user = Server::get(IUserManager::class)->get(self::TEST_FILES_SHARING_API_USER3);
if ($user !== null) {
$user->delete();
}
// delete group
- $group = \OC::$server->getGroupManager()->get(self::TEST_FILES_SHARING_API_GROUP1);
+ $group = Server::get(IGroupManager::class)->get(self::TEST_FILES_SHARING_API_GROUP1);
if ($group) {
$group->delete();
}
@@ -176,10 +161,10 @@ abstract class TestCase extends \Test\TestCase {
Filesystem::tearDown();
// reset backend
- \OC_User::clearBackends();
- \OC_User::useBackend('database');
- \OC::$server->getGroupManager()->clearBackends();
- \OC::$server->getGroupManager()->addBackend(new \OC\Group\Database());
+ Server::get(IUserManager::class)->clearBackends();
+ Server::get(IUserManager::class)->registerBackend(new \OC\User\Database());
+ Server::get(IGroupManager::class)->clearBackends();
+ Server::get(IGroupManager::class)->addBackend(new Database());
parent::tearDownAfterClass();
}
@@ -189,14 +174,14 @@ abstract class TestCase extends \Test\TestCase {
* @param bool $create
* @param bool $password
*/
- protected static function loginHelper($user, $create = false, $password = false) {
+ protected function loginHelper($user, $create = false, $password = false) {
if ($password === false) {
$password = $user;
}
if ($create) {
- $userManager = \OC::$server->getUserManager();
- $groupManager = \OC::$server->getGroupManager();
+ $userManager = Server::get(IUserManager::class);
+ $groupManager = Server::get(IGroupManager::class);
$userObject = $userManager->createUser($user, $password);
$group = $groupManager->createGroup('group');
@@ -207,10 +192,10 @@ abstract class TestCase extends \Test\TestCase {
}
\OC_Util::tearDownFS();
- \OC\Files\Cache\Storage::getGlobalCache()->clearCache();
- \OC::$server->getUserSession()->setUser(null);
- \OC\Files\Filesystem::tearDown();
- \OC::$server->getUserSession()->login($user, $password);
+ Storage::getGlobalCache()->clearCache();
+ Server::get(IUserSession::class)->setUser(null);
+ Filesystem::tearDown();
+ Server::get(IUserSession::class)->login($user, $password);
\OC::$server->getUserFolder($user);
\OC_Util::setupFS($user);
@@ -222,7 +207,7 @@ abstract class TestCase extends \Test\TestCase {
* @return array with: item_source, share_type, share_with, item_type, permissions
*/
protected function getShareFromId($shareID) {
- $qb = \OC::$server->getDatabaseConnection()->getQueryBuilder();
+ $qb = Server::get(IDBConnection::class)->getQueryBuilder();
$qb->select('item_source', '`share_type', 'share_with', 'item_type', 'permissions')
->from('share')
->where(
@@ -241,7 +226,7 @@ abstract class TestCase extends \Test\TestCase {
* @param string $initiator
* @param string $recipient
* @param int $permissions
- * @return \OCP\Share\IShare
+ * @return IShare
*/
protected function share($type, $path, $initiator, $recipient, $permissions) {
$userFolder = $this->rootFolder->getUserFolder($initiator);
diff --git a/apps/files_sharing/tests/UnshareChildrenTest.php b/apps/files_sharing/tests/UnshareChildrenTest.php
index db6f0912419..ac870212c99 100644
--- a/apps/files_sharing/tests/UnshareChildrenTest.php
+++ b/apps/files_sharing/tests/UnshareChildrenTest.php
@@ -1,32 +1,16 @@
<?php
+
/**
- * @copyright Copyright (c) 2016, ownCloud, Inc.
- *
- * @author Björn Schießle <bjoern@schiessle.org>
- * @author Christoph Wurst <christoph@winzerhof-wurst.at>
- * @author Joas Schilling <coding@schilljs.com>
- * @author Robin Appelman <robin@icewind.nl>
- * @author Roeland Jago Douma <roeland@famdouma.nl>
- * @author Thomas Müller <thomas.mueller@tmit.eu>
- *
- * @license AGPL-3.0
- *
- * This code is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License, version 3,
- * as published by the Free Software Foundation.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU Affero General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License, version 3,
- * along with this program. If not, see <http://www.gnu.org/licenses/>
- *
+ * SPDX-FileCopyrightText: 2019-2024 Nextcloud GmbH and Nextcloud contributors
+ * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
+ * SPDX-License-Identifier: AGPL-3.0-only
*/
namespace OCA\Files_Sharing\Tests;
+use OC\Files\Filesystem;
+use OCP\Constants;
use OCP\Share\IShare;
+use OCP\Util;
/**
* Class UnshareChildrenTest
@@ -45,7 +29,7 @@ class UnshareChildrenTest extends TestCase {
protected function setUp(): void {
parent::setUp();
- \OCP\Util::connectHook('OC_Filesystem', 'post_delete', '\OCA\Files_Sharing\Hooks', 'unshareChildren');
+ Util::connectHook('OC_Filesystem', 'post_delete', '\OCA\Files_Sharing\Hooks', 'unshareChildren');
$this->folder = self::TEST_FOLDER_NAME;
$this->subfolder = '/subfolder_share_api_test';
@@ -74,15 +58,15 @@ class UnshareChildrenTest extends TestCase {
/**
* @medium
*/
- public function testUnshareChildren() {
- $fileInfo2 = \OC\Files\Filesystem::getFileInfo($this->folder);
+ public function testUnshareChildren(): void {
+ $fileInfo2 = Filesystem::getFileInfo($this->folder);
$this->share(
IShare::TYPE_USER,
$this->folder,
self::TEST_FILES_SHARING_API_USER1,
self::TEST_FILES_SHARING_API_USER2,
- \OCP\Constants::PERMISSION_ALL
+ Constants::PERMISSION_ALL
);
self::loginHelper(self::TEST_FILES_SHARING_API_USER2);
@@ -92,11 +76,11 @@ class UnshareChildrenTest extends TestCase {
$this->assertCount(1, $shares);
// move shared folder to 'localDir'
- \OC\Files\Filesystem::mkdir('localDir');
- $result = \OC\Files\Filesystem::rename($this->folder, '/localDir/' . $this->folder);
+ Filesystem::mkdir('localDir');
+ $result = Filesystem::rename($this->folder, '/localDir/' . $this->folder);
$this->assertTrue($result);
- \OC\Files\Filesystem::unlink('localDir');
+ Filesystem::unlink('localDir');
self::loginHelper(self::TEST_FILES_SHARING_API_USER2);
@@ -107,6 +91,6 @@ class UnshareChildrenTest extends TestCase {
self::loginHelper(self::TEST_FILES_SHARING_API_USER1);
// the folder for the owner should still exists
- $this->assertTrue(\OC\Files\Filesystem::file_exists($this->folder));
+ $this->assertTrue(Filesystem::file_exists($this->folder));
}
}
diff --git a/apps/files_sharing/tests/UpdaterTest.php b/apps/files_sharing/tests/UpdaterTest.php
index 98e34a272e0..23044e0b2f3 100644
--- a/apps/files_sharing/tests/UpdaterTest.php
+++ b/apps/files_sharing/tests/UpdaterTest.php
@@ -1,37 +1,22 @@
<?php
+
/**
- * @copyright Copyright (c) 2016, ownCloud, Inc.
- *
- * @author Björn Schießle <bjoern@schiessle.org>
- * @author Christoph Wurst <christoph@winzerhof-wurst.at>
- * @author Joas Schilling <coding@schilljs.com>
- * @author Lukas Reschke <lukas@statuscode.ch>
- * @author Morris Jobke <hey@morrisjobke.de>
- * @author Robin Appelman <robin@icewind.nl>
- * @author Roeland Jago Douma <roeland@famdouma.nl>
- * @author Thomas Müller <thomas.mueller@tmit.eu>
- * @author Tobia De Koninck <tobia@ledfan.be>
- * @author Vincent Petry <vincent@nextcloud.com>
- *
- * @license AGPL-3.0
- *
- * This code is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License, version 3,
- * as published by the Free Software Foundation.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU Affero General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License, version 3,
- * along with this program. If not, see <http://www.gnu.org/licenses/>
- *
+ * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
+ * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
+ * SPDX-License-Identifier: AGPL-3.0-only
*/
namespace OCA\Files_Sharing\Tests;
+use OC\Files\FileInfo;
+use OC\Files\Filesystem;
+use OC\Files\View;
+use OCA\Files_Sharing\Helper;
use OCA\Files_Trashbin\AppInfo\Application;
+use OCP\App\IAppManager;
use OCP\AppFramework\Bootstrap\IBootContext;
+use OCP\Constants;
+use OCP\IConfig;
+use OCP\Server;
use OCP\Share\IShare;
/**
@@ -44,7 +29,7 @@ class UpdaterTest extends TestCase {
public static function setUpBeforeClass(): void {
parent::setUpBeforeClass();
- \OCA\Files_Sharing\Helper::registerHooks();
+ Helper::registerHooks();
}
protected function setUp(): void {
@@ -74,27 +59,28 @@ class UpdaterTest extends TestCase {
* points should be unshared before the folder gets deleted so
* that the mount point doesn't end up at the trash bin
*/
- public function testDeleteParentFolder() {
- $status = \OC::$server->getAppManager()->isEnabledForUser('files_trashbin');
- (new \OC_App())->enable('files_trashbin');
+ public function testDeleteParentFolder(): void {
+ $appManager = Server::get(IAppManager::class);
+ $status = $appManager->isEnabledForUser('files_trashbin');
+ $appManager->enableApp('files_trashbin');
// register trashbin hooks
$trashbinApp = new Application();
$trashbinApp->boot($this->createMock(IBootContext::class));
- $fileinfo = \OC\Files\Filesystem::getFileInfo($this->folder);
- $this->assertTrue($fileinfo instanceof \OC\Files\FileInfo);
+ $fileinfo = Filesystem::getFileInfo($this->folder);
+ $this->assertTrue($fileinfo instanceof FileInfo);
$this->share(
IShare::TYPE_USER,
$this->folder,
self::TEST_FILES_SHARING_API_USER1,
self::TEST_FILES_SHARING_API_USER2,
- \OCP\Constants::PERMISSION_ALL
+ Constants::PERMISSION_ALL
);
$this->loginHelper(self::TEST_FILES_SHARING_API_USER2);
- $view = new \OC\Files\View('/' . self::TEST_FILES_SHARING_API_USER2 . '/files');
+ $view = new View('/' . self::TEST_FILES_SHARING_API_USER2 . '/files');
// check if user2 can see the shared folder
$this->assertTrue($view->file_exists($this->folder));
@@ -109,7 +95,7 @@ class UpdaterTest extends TestCase {
// share mount point should now be moved to the subfolder
$this->assertFalse($view->file_exists($this->folder));
- $this->assertTrue($view->file_exists('localFolder/' .$this->folder));
+ $this->assertTrue($view->file_exists('localFolder/' . $this->folder));
$view->unlink('localFolder');
@@ -120,7 +106,7 @@ class UpdaterTest extends TestCase {
$this->assertCount(0, $foldersShared);
// trashbin should contain the local file but not the mount point
- $rootView = new \OC\Files\View('/' . self::TEST_FILES_SHARING_API_USER2);
+ $rootView = new View('/' . self::TEST_FILES_SHARING_API_USER2);
$trashContent = \OCA\Files_Trashbin\Helper::getTrashFiles('/', self::TEST_FILES_SHARING_API_USER2);
$this->assertSame(1, count($trashContent));
$firstElement = reset($trashContent);
@@ -132,13 +118,13 @@ class UpdaterTest extends TestCase {
$rootView->deleteAll('files_trashin');
if ($status === false) {
- \OC::$server->getAppManager()->disableApp('files_trashbin');
+ $appManager->disableApp('files_trashbin');
}
- \OC\Files\Filesystem::getLoader()->removeStorageWrapper('oc_trashbin');
+ Filesystem::getLoader()->removeStorageWrapper('oc_trashbin');
}
- public function shareFolderProvider() {
+ public static function shareFolderProvider() {
return [
['/'],
['/my_shares'],
@@ -148,23 +134,23 @@ class UpdaterTest extends TestCase {
/**
* if a file gets shared the etag for the recipients root should change
*
- * @dataProvider shareFolderProvider
*
* @param string $shareFolder share folder to use
*/
- public function testShareFile($shareFolder) {
- $config = \OC::$server->getConfig();
+ #[\PHPUnit\Framework\Attributes\DataProvider('shareFolderProvider')]
+ public function testShareFile($shareFolder): void {
+ $config = Server::get(IConfig::class);
$oldShareFolder = $config->getSystemValue('share_folder');
$config->setSystemValue('share_folder', $shareFolder);
$this->loginHelper(self::TEST_FILES_SHARING_API_USER2);
- $beforeShareRoot = \OC\Files\Filesystem::getFileInfo('');
+ $beforeShareRoot = Filesystem::getFileInfo('');
$etagBeforeShareRoot = $beforeShareRoot->getEtag();
- \OC\Files\Filesystem::mkdir($shareFolder);
+ Filesystem::mkdir($shareFolder);
- $beforeShareDir = \OC\Files\Filesystem::getFileInfo($shareFolder);
+ $beforeShareDir = Filesystem::getFileInfo($shareFolder);
$etagBeforeShareDir = $beforeShareDir->getEtag();
$this->loginHelper(self::TEST_FILES_SHARING_API_USER1);
@@ -174,15 +160,15 @@ class UpdaterTest extends TestCase {
$this->folder,
self::TEST_FILES_SHARING_API_USER1,
self::TEST_FILES_SHARING_API_USER2,
- \OCP\Constants::PERMISSION_ALL
+ Constants::PERMISSION_ALL
);
$this->loginHelper(self::TEST_FILES_SHARING_API_USER2);
- $afterShareRoot = \OC\Files\Filesystem::getFileInfo('');
+ $afterShareRoot = Filesystem::getFileInfo('');
$etagAfterShareRoot = $afterShareRoot->getEtag();
- $afterShareDir = \OC\Files\Filesystem::getFileInfo($shareFolder);
+ $afterShareDir = Filesystem::getFileInfo($shareFolder);
$etagAfterShareDir = $afterShareDir->getEtag();
$this->assertTrue(is_string($etagBeforeShareRoot));
@@ -202,37 +188,37 @@ class UpdaterTest extends TestCase {
/**
* if a folder gets renamed all children mount points should be renamed too
*/
- public function testRename() {
- $fileinfo = \OC\Files\Filesystem::getFileInfo($this->folder);
+ public function testRename(): void {
+ $fileinfo = Filesystem::getFileInfo($this->folder);
$share = $this->share(
IShare::TYPE_USER,
$this->folder,
self::TEST_FILES_SHARING_API_USER1,
self::TEST_FILES_SHARING_API_USER2,
- \OCP\Constants::PERMISSION_ALL
+ Constants::PERMISSION_ALL
);
$this->loginHelper(self::TEST_FILES_SHARING_API_USER2);
// make sure that the shared folder exists
- $this->assertTrue(\OC\Files\Filesystem::file_exists($this->folder));
+ $this->assertTrue(Filesystem::file_exists($this->folder));
- \OC\Files\Filesystem::mkdir('oldTarget');
- \OC\Files\Filesystem::mkdir('oldTarget/subfolder');
- \OC\Files\Filesystem::mkdir('newTarget');
+ Filesystem::mkdir('oldTarget');
+ Filesystem::mkdir('oldTarget/subfolder');
+ Filesystem::mkdir('newTarget');
- \OC\Files\Filesystem::rename($this->folder, 'oldTarget/subfolder/' . $this->folder);
+ Filesystem::rename($this->folder, 'oldTarget/subfolder/' . $this->folder);
// re-login to make sure that the new mount points are initialized
$this->loginHelper(self::TEST_FILES_SHARING_API_USER2);
- \OC\Files\Filesystem::rename('/oldTarget', '/newTarget/oldTarget');
+ Filesystem::rename('/oldTarget', '/newTarget/oldTarget');
// re-login to make sure that the new mount points are initialized
$this->loginHelper(self::TEST_FILES_SHARING_API_USER2);
- $this->assertTrue(\OC\Files\Filesystem::file_exists('/newTarget/oldTarget/subfolder/' . $this->folder));
+ $this->assertTrue(Filesystem::file_exists('/newTarget/oldTarget/subfolder/' . $this->folder));
// cleanup
$this->shareManager->deleteShare($share);
@@ -249,11 +235,11 @@ class UpdaterTest extends TestCase {
* |-subfolder2
* |-file2.txt --> shared with user3
*/
- public function testMovedIntoShareChangeOwner() {
+ public function testMovedIntoShareChangeOwner(): void {
$this->markTestSkipped('Skipped because this is failing with S3 as primary as file id are change when moved.');
// user1 creates folder1
- $viewUser1 = new \OC\Files\View('/' . self::TEST_FILES_SHARING_API_USER1 . '/files');
+ $viewUser1 = new View('/' . self::TEST_FILES_SHARING_API_USER1 . '/files');
$folder1 = 'folder1';
$viewUser1->mkdir($folder1);
@@ -263,11 +249,11 @@ class UpdaterTest extends TestCase {
$folder1,
self::TEST_FILES_SHARING_API_USER1,
self::TEST_FILES_SHARING_API_USER2,
- \OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_SHARE
+ Constants::PERMISSION_READ | Constants::PERMISSION_SHARE
);
$this->loginHelper(self::TEST_FILES_SHARING_API_USER2);
- $viewUser2 = new \OC\Files\View('/' . self::TEST_FILES_SHARING_API_USER2 . '/files');
+ $viewUser2 = new View('/' . self::TEST_FILES_SHARING_API_USER2 . '/files');
// Create user2 files
$folder2 = 'folder2';
$viewUser2->mkdir($folder2);
@@ -286,7 +272,7 @@ class UpdaterTest extends TestCase {
$folder2,
self::TEST_FILES_SHARING_API_USER2,
self::TEST_FILES_SHARING_API_USER3,
- \OCP\Constants::PERMISSION_ALL
+ Constants::PERMISSION_ALL
);
// user2 shares folder2/file1 to user3
$file1Share = $this->share(
@@ -294,7 +280,7 @@ class UpdaterTest extends TestCase {
$file1,
self::TEST_FILES_SHARING_API_USER2,
self::TEST_FILES_SHARING_API_USER3,
- \OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_SHARE
+ Constants::PERMISSION_READ | Constants::PERMISSION_SHARE
);
// user2 shares subfolder1 to user3
$subfolder1Share = $this->share(
@@ -302,7 +288,7 @@ class UpdaterTest extends TestCase {
$subfolder1,
self::TEST_FILES_SHARING_API_USER2,
self::TEST_FILES_SHARING_API_USER3,
- \OCP\Constants::PERMISSION_ALL
+ Constants::PERMISSION_ALL
);
// user2 shares subfolder2/file2.txt to user3
$file2Share = $this->share(
@@ -310,11 +296,11 @@ class UpdaterTest extends TestCase {
$file2,
self::TEST_FILES_SHARING_API_USER2,
self::TEST_FILES_SHARING_API_USER3,
- \OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_SHARE
+ Constants::PERMISSION_READ | Constants::PERMISSION_SHARE
);
// user2 moves folder2 into folder1
- $viewUser2->rename($folder2, $folder1.'/'.$folder2);
+ $viewUser2->rename($folder2, $folder1 . '/' . $folder2);
$folder2Share = $this->shareManager->getShareById($folder2Share->getFullId());
$file1Share = $this->shareManager->getShareById($file1Share->getFullId());
$subfolder1Share = $this->shareManager->getShareById($subfolder1Share->getFullId());
@@ -326,13 +312,13 @@ class UpdaterTest extends TestCase {
$this->assertEquals(self::TEST_FILES_SHARING_API_USER1, $subfolder1Share->getShareOwner());
$this->assertEquals(self::TEST_FILES_SHARING_API_USER1, $file2Share->getShareOwner());
// Expect permissions to be limited by the permissions of the destination share
- $this->assertEquals(\OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_SHARE, $folder2Share->getPermissions());
- $this->assertEquals(\OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_SHARE, $file1Share->getPermissions());
- $this->assertEquals(\OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_SHARE, $subfolder1Share->getPermissions());
- $this->assertEquals(\OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_SHARE, $file2Share->getPermissions());
+ $this->assertEquals(Constants::PERMISSION_READ | Constants::PERMISSION_SHARE, $folder2Share->getPermissions());
+ $this->assertEquals(Constants::PERMISSION_READ | Constants::PERMISSION_SHARE, $file1Share->getPermissions());
+ $this->assertEquals(Constants::PERMISSION_READ | Constants::PERMISSION_SHARE, $subfolder1Share->getPermissions());
+ $this->assertEquals(Constants::PERMISSION_READ | Constants::PERMISSION_SHARE, $file2Share->getPermissions());
// user2 moves folder2 out of folder1
- $viewUser2->rename($folder1.'/'.$folder2, $folder2);
+ $viewUser2->rename($folder1 . '/' . $folder2, $folder2);
$folder2Share = $this->shareManager->getShareById($folder2Share->getFullId());
$file1Share = $this->shareManager->getShareById($file1Share->getFullId());
$subfolder1Share = $this->shareManager->getShareById($subfolder1Share->getFullId());
@@ -344,10 +330,10 @@ class UpdaterTest extends TestCase {
$this->assertEquals(self::TEST_FILES_SHARING_API_USER2, $subfolder1Share->getShareOwner());
$this->assertEquals(self::TEST_FILES_SHARING_API_USER2, $file2Share->getShareOwner());
// Expect permissions to not change
- $this->assertEquals(\OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_SHARE, $folder2Share->getPermissions());
- $this->assertEquals(\OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_SHARE, $file1Share->getPermissions());
- $this->assertEquals(\OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_SHARE, $subfolder1Share->getPermissions());
- $this->assertEquals(\OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_SHARE, $file2Share->getPermissions());
+ $this->assertEquals(Constants::PERMISSION_READ | Constants::PERMISSION_SHARE, $folder2Share->getPermissions());
+ $this->assertEquals(Constants::PERMISSION_READ | Constants::PERMISSION_SHARE, $file1Share->getPermissions());
+ $this->assertEquals(Constants::PERMISSION_READ | Constants::PERMISSION_SHARE, $subfolder1Share->getPermissions());
+ $this->assertEquals(Constants::PERMISSION_READ | Constants::PERMISSION_SHARE, $file2Share->getPermissions());
// cleanup
$this->shareManager->deleteShare($folder1Share);
diff --git a/apps/files_sharing/tests/WatcherTest.php b/apps/files_sharing/tests/WatcherTest.php
index 49f91ca3027..15676836915 100644
--- a/apps/files_sharing/tests/WatcherTest.php
+++ b/apps/files_sharing/tests/WatcherTest.php
@@ -1,33 +1,16 @@
<?php
+
/**
- * @copyright Copyright (c) 2016, ownCloud, Inc.
- *
- * @author Björn Schießle <bjoern@schiessle.org>
- * @author Christoph Wurst <christoph@winzerhof-wurst.at>
- * @author Joas Schilling <coding@schilljs.com>
- * @author Jörn Friedrich Dreyer <jfd@butonic.de>
- * @author Robin Appelman <robin@icewind.nl>
- * @author Roeland Jago Douma <roeland@famdouma.nl>
- * @author Thomas Müller <thomas.mueller@tmit.eu>
- * @author Vincent Petry <vincent@nextcloud.com>
- *
- * @license AGPL-3.0
- *
- * This code is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License, version 3,
- * as published by the Free Software Foundation.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU Affero General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License, version 3,
- * along with this program. If not, see <http://www.gnu.org/licenses/>
- *
+ * SPDX-FileCopyrightText: 2019-2024 Nextcloud GmbH and Nextcloud contributors
+ * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
+ * SPDX-License-Identifier: AGPL-3.0-only
*/
namespace OCA\Files_Sharing\Tests;
+use OC\Files\Cache\Cache;
+use OC\Files\Storage\Storage;
+use OC\Files\View;
+use OCP\Constants;
use OCP\Share\IShare;
/**
@@ -37,19 +20,19 @@ use OCP\Share\IShare;
*/
class WatcherTest extends TestCase {
- /** @var \OC\Files\Storage\Storage */
+ /** @var Storage */
private $ownerStorage;
- /** @var \OC\Files\Cache\Cache */
+ /** @var Cache */
private $ownerCache;
- /** @var \OC\Files\Storage\Storage */
+ /** @var Storage */
private $sharedStorage;
- /** @var \OC\Files\Cache\Cache */
+ /** @var Cache */
private $sharedCache;
- /** @var \OCP\Share\IShare */
+ /** @var IShare */
private $_share;
protected function setUp(): void {
@@ -72,7 +55,7 @@ class WatcherTest extends TestCase {
'container/shareddir',
self::TEST_FILES_SHARING_API_USER1,
self::TEST_FILES_SHARING_API_USER2,
- \OCP\Constants::PERMISSION_ALL
+ Constants::PERMISSION_ALL
);
$this->_share->setStatus(IShare::STATUS_ACCEPTED);
@@ -82,7 +65,7 @@ class WatcherTest extends TestCase {
self::loginHelper(self::TEST_FILES_SHARING_API_USER2);
// retrieve the shared storage
- $secondView = new \OC\Files\View('/' . self::TEST_FILES_SHARING_API_USER2);
+ $secondView = new View('/' . self::TEST_FILES_SHARING_API_USER2);
[$this->sharedStorage, $internalPath] = $secondView->resolvePath('files/shareddir');
$this->sharedCache = $this->sharedStorage->getCache();
}
@@ -109,7 +92,7 @@ class WatcherTest extends TestCase {
* Tests that writing a file using the shared storage will propagate the file
* size to the owner's parent folders.
*/
- public function testFolderSizePropagationToOwnerStorage() {
+ public function testFolderSizePropagationToOwnerStorage(): void {
$initialSizes = self::getOwnerDirSizes('files/container/shareddir');
$textData = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
@@ -139,7 +122,7 @@ class WatcherTest extends TestCase {
* Tests that writing a file using the shared storage will propagate the file
* size to the owner's parent folders.
*/
- public function testSubFolderSizePropagationToOwnerStorage() {
+ public function testSubFolderSizePropagationToOwnerStorage(): void {
$initialSizes = self::getOwnerDirSizes('files/container/shareddir/subdir');
$textData = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
diff --git a/apps/files_sharing/tests/js/fileDropSpec.js b/apps/files_sharing/tests/js/fileDropSpec.js
deleted file mode 100644
index 18eee661e7f..00000000000
--- a/apps/files_sharing/tests/js/fileDropSpec.js
+++ /dev/null
@@ -1,98 +0,0 @@
-/**
- * @copyright Copyright (c) 2017, Artur Neumann (info@individual-it.net)
- *
- * @author Artur Neumann <info@individual-it.net>
- *
- * @license AGPL-3.0-or-later
- *
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License as
- * published by the Free Software Foundation, either version 3 of the
- * License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU Affero General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- *
- */
-
-describe("files Drop tests", function() {
- //some testing data
- var sharingToken = "fVCiSMhScgWfiuv";
- var testFiles = [
- { name: 'test.txt', expectedValidationResult: true },
- { name: 'testनेपाल.txt', expectedValidationResult: true },
- { name: 'test.part', expectedValidationResult: false },
- { name: 'test.filepart', expectedValidationResult: false },
- { name: '.', expectedValidationResult: false },
- { name: '..', expectedValidationResult: false },
- ];
-
- //this pre/post positions should not change the result of the file name validation
- var prePostPositions = [""," "," "," "];
-
- //use the testFiles and the pre/post positions to generate more testing data
- var replicatedTestFiles = [];
- prePostPositions.map(function (prePostPosition) {
- testFiles.map(function (testFile) {
- replicatedTestFiles.push(
- {
- name: testFile.name + prePostPosition,
- expectedValidationResult: testFile.expectedValidationResult
- }
- );
- replicatedTestFiles.push(
- {
- name: prePostPosition + testFile.name,
- expectedValidationResult: testFile.expectedValidationResult
- }
- );
- replicatedTestFiles.push(
- {
- name: prePostPosition + testFile.name + prePostPosition,
- expectedValidationResult: testFile.expectedValidationResult
- }
- );
- });
- });
-
- beforeEach (function () {
- //fake input for the sharing token
- $('#testArea').append(
- '<input name="sharingToken" value="" id="sharingToken" type="hidden">'
- );
- });
-
-
- replicatedTestFiles.map(function (testFile) {
- it("validates the filenames correctly", function() {
- data = {
- 'submit': function() {},
- 'files': [testFile]
- }
- expect(OCA.FilesSharingDrop.addFileToUpload('',data)).
- toBe(
- testFile.expectedValidationResult,
- 'wrongly validated file named "'+testFile.name+'"'
- );
- });
-
- if (testFile.expectedValidationResult === true) {
- it("should set correct PUT URL, Auth header and submit", function () {
- data = {
- 'submit': sinon.stub(),
- 'files': [testFile]
- }
- $('#sharingToken').val(sharingToken);
-
- OCA.FilesSharingDrop.addFileToUpload('',data);
- expect(data.submit.calledOnce).toEqual(true);
- expect(data.url).toContain("/public.php/dav/files/" + sharingToken + '/' + encodeURI(testFile.name));
- });
- }
- });
-});
diff --git a/apps/files_sharing/tests/js/publicAppSpec.js b/apps/files_sharing/tests/js/publicAppSpec.js
deleted file mode 100644
index 72a31088c6c..00000000000
--- a/apps/files_sharing/tests/js/publicAppSpec.js
+++ /dev/null
@@ -1,159 +0,0 @@
-/**
-* @copyright 2015 Vincent Petry <pvince81@owncloud.com>
- *
- * @author Christoph Wurst <christoph@winzerhof-wurst.at>
- * @author Jan-Christoph Borchardt <hey@jancborchardt.net>
- * @author Roeland Jago Douma <roeland@famdouma.nl>
- * @author Vincent Petry <vincent@nextcloud.com>
- *
- * @license AGPL-3.0-or-later
- *
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License as
- * published by the Free Software Foundation, either version 3 of the
- * License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU Affero General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- *
- */
-
-describe('OCA.Sharing.PublicApp tests', function() {
- var App = OCA.Sharing.PublicApp;
- var hostStub, protocolStub;
- var originalWebroot;
- var $preview;
-
- beforeEach(function() {
- originalWebroot = window._oc_webroot;
- window._oc_webroot = '/owncloud';
- protocolStub = sinon.stub(OC, 'getProtocol').returns('https');
- hostStub = sinon.stub(OC, 'getHost').returns('example.com:9876');
-
- $preview = $('<div id="preview"></div>');
- $('#testArea').append($preview);
- $preview.append(
- '<div id="mimetype"></div>' +
- '<div id="mimetypeIcon"></div>' +
- '<input type="hidden" id="sharingToken" value="sh4tok"></input>'
- );
- });
-
- afterEach(function() {
- window._oc_webroot = originalWebroot;
- protocolStub.restore();
- hostStub.restore();
- });
-
- describe('File list', function() {
- var parseUrlQueryStub
- // TODO: this should be moved to a separate file once the PublicFileList is extracted from public.js
- beforeEach(function() {
- $preview.append(
- '<div id="app-content-files">' +
- // init horrible parameters
- '<input type="hidden" id="permissions" value="31"/>' +
- // dummy controls
- '<div class="files-controls">' +
- ' <div class="actions creatable"></div>' +
- ' <div class="notCreatable"></div>' +
- '</div>' +
- // uploader
- '<input type="file" id="file_upload_start" name="files[]" multiple="multiple">' +
- // dummy table
- // TODO: at some point this will be rendered by the fileList class itself!
- '<table class="files-filestable list-container view-grid">' +
- '<thead><tr>' +
- '<th class="hidden column-name">' +
- '<input type="checkbox" id="select_all_files" class="select-all">' +
- '<a class="name columntitle" data-sort="name"><span>Name</span><span class="sort-indicator"></span></a>' +
- '<span class="selectedActions hidden">' +
- '<a href class="download">Download</a>' +
- '</span>' +
- '</th>' +
- '<th class="hidden column-size"><a class="columntitle" data-sort="size"><span class="sort-indicator"></span></a></th>' +
- '<th class="hidden column-mtime"><a class="columntitle" data-sort="mtime"><span class="sort-indicator"></span></a></th>' +
- '</tr></thead>' +
- '<tbody class="files-fileList"></tbody>' +
- '<tfoot></tfoot>' +
- '</table>' +
- // TODO: move to handlebars template
- '<div class="emptyfilelist emptycontent"><h2>Empty content message</h2><p class="uploadmessage">Upload message</p></div>' +
- '<div class="nofilterresults hidden"></div>' +
- '</div>'
- );
-
- parseUrlQueryStub = sinon.stub(OC.Util.History, 'parseUrlQuery');
- parseUrlQueryStub.returns({path: '/subdir'});
- App.initialize($('#preview'));
- });
- afterEach(function() {
- App._initialized = false;
- parseUrlQueryStub.restore();
- });
-
- it('Uses public webdav endpoint', function() {
- App._initialized = false;
- fakeServer.restore();
- window.fakeServer = sinon.fakeServer.create();
-
- // uploader function messes up with fakeServer
- var uploaderDetectStub = sinon.stub(OC.Uploader.prototype, '_supportAjaxUploadWithProgress');
- App.initialize($('#preview'));
- expect(fakeServer.requests.length).toEqual(1);
- expect(fakeServer.requests[0].method).toEqual('PROPFIND');
- expect(fakeServer.requests[0].url).toEqual('https://example.com:9876/owncloud/public.php/dav/files/sh4tok/subdir');
- uploaderDetectStub.restore();
- });
-
- describe('Download Url', function() {
- var fileList;
-
- beforeEach(function() {
- fileList = App.fileList;
- });
-
- it('returns correct download URL for single files', function() {
- expect(fileList.getDownloadUrl('some file.txt'))
- .toEqual(OC.getRootPath() + '/index.php/s/sh4tok/download?path=%2Fsubdir&files=some%20file.txt');
- expect(fileList.getDownloadUrl('some file.txt', '/anotherpath/abc'))
- .toEqual(OC.getRootPath() + '/index.php/s/sh4tok/download?path=%2Fanotherpath%2Fabc&files=some%20file.txt');
- fileList.changeDirectory('/');
- expect(fileList.getDownloadUrl('some file.txt'))
- .toEqual(OC.getRootPath() + '/index.php/s/sh4tok/download?path=%2F&files=some%20file.txt');
- });
- it('returns correct download URL for multiple files', function() {
- expect(fileList.getDownloadUrl(['a b c.txt', 'd e f.txt']))
- .toEqual(OC.getRootPath() + '/index.php/s/sh4tok/download?path=%2Fsubdir&files=%5B%22a%20b%20c.txt%22%2C%22d%20e%20f.txt%22%5D');
- });
- it('returns the correct ajax URL', function() {
- expect(fileList.getAjaxUrl('test', {a:1, b:'x y'}))
- .toEqual(OC.getRootPath() + '/index.php/apps/files_sharing/ajax/test.php?a=1&b=x%20y&t=sh4tok');
- });
- it('returns correct download URL for downloading everything', function() {
- expect(fileList.getDownloadUrl())
- .toEqual(OC.getRootPath() + '/index.php/s/sh4tok/download?path=%2Fsubdir');
- });
- });
- describe('Upload Url', function() {
- var fileList;
-
- beforeEach(function() {
- fileList = App.fileList;
- });
- it('returns correct upload URL', function() {
- expect(fileList.getUploadUrl('some file.txt'))
- .toEqual('/owncloud/public.php/dav/files/sh4tok/subdir/some%20file.txt');
- });
- it('returns correct upload URL with specified dir', function() {
- expect(fileList.getUploadUrl('some file.txt', 'sub'))
- .toEqual('/owncloud/public.php/dav/files/sh4tok/sub/some%20file.txt');
- });
- });
- });
-});
diff --git a/apps/files_sharing/tests/js/shareSpec.js b/apps/files_sharing/tests/js/shareSpec.js
deleted file mode 100644
index 8a48ce54f19..00000000000
--- a/apps/files_sharing/tests/js/shareSpec.js
+++ /dev/null
@@ -1,343 +0,0 @@
-/**
- * Copyright (c) 2014 Vincent Petry <pvince81@owncloud.com>
- *
- * @author Arthur Schiwon <blizzz@arthur-schiwon.de>
- * @author Daniel Calviño Sánchez <danxuliu@gmail.com>
- * @author Jan-Christoph Borchardt <hey@jancborchardt.net>
- * @author John Molakvoæ <skjnldsv@protonmail.com>
- * @author Morris Jobke <hey@morrisjobke.de>
- * @author Roeland Jago Douma <roeland@famdouma.nl>
- * @author Vincent Petry <vincent@nextcloud.com>
- *
- * @license AGPL-3.0-or-later
- *
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License as
- * published by the Free Software Foundation, either version 3 of the
- * License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU Affero General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- *
- */
-
-describe('OCA.Sharing.Util tests', function() {
- var fileList;
- var testFiles;
-
- function getImageUrl($el) {
- // might be slightly different cross-browser
- var url = $el.css('background-image');
- var r = url.match(/url\(['"]?([^'")]*)['"]?\)/);
- if (!r) {
- return url;
- }
- return r[1];
- }
-
- beforeEach(function() {
- var $content = $('<div id="app-content"></div>');
- $('#testArea').append($content);
- // dummy file list
- var $div = $(
- '<div id="listContainer">' +
- '<table class="files-filestable list-container view-grid">' +
- '<thead></thead>' +
- '<tbody class="files-fileList"></tbody>' +
- '</table>' +
- '</div>');
- $('#app-content').append($div);
-
- var fileActions = new OCA.Files.FileActions();
- fileList = new OCA.Files.FileList(
- $div, {
- fileActions : fileActions
- }
- );
- OCA.Sharing.Util.attach(fileList);
-
- testFiles = [{
- id: 1,
- type: 'file',
- name: 'One.txt',
- path: '/subdir',
- mimetype: 'text/plain',
- size: 12,
- permissions: OC.PERMISSION_ALL,
- etag: 'abc',
- shareOwner: 'User One',
- isShareMountPoint: false,
- shareTypes: [OC.Share.SHARE_TYPE_USER]
- }];
- });
- afterEach(function() {
- delete OCA.Sharing.sharesLoaded;
- delete OC.Share.droppedDown;
- fileList.destroy();
- fileList = null;
- });
-
- describe('Sharing data in table row', function() {
- // TODO: test data-permissions, data-share-owner, etc
- });
- describe('Share action icon', function() {
- it('do not shows share text when not shared', function() {
- var $action, $tr;
- OC.Share.statuses = {};
- fileList.setFiles([{
- id: 1,
- type: 'dir',
- name: 'One',
- path: '/subdir',
- mimetype: 'httpd/unix-directory',
- size: 12,
- permissions: OC.PERMISSION_ALL,
- etag: 'abc',
- shareTypes: []
- }]);
- $tr = fileList.$el.find('tbody tr:first');
- $action = $tr.find('.action-share');
- expect($action.find('.icon').hasClass('icon-shared')).toEqual(true);
- expect($action.find('.icon').hasClass('icon-public')).toEqual(false);
- expect(OC.basename(getImageUrl($tr.find('.filename .thumbnail')))).toEqual('folder.svg');
- });
- it('shows simple share text with share icon', function() {
- var $action, $tr;
- fileList.setFiles([{
- id: 1,
- type: 'dir',
- name: 'One',
- path: '/subdir',
- mimetype: 'text/plain',
- size: 12,
- permissions: OC.PERMISSION_ALL,
- etag: 'abc',
- shareTypes: [OC.Share.SHARE_TYPE_USER]
- }]);
- $tr = fileList.$el.find('tbody tr:first');
- $action = $tr.find('.action-share');
- expect($action.find('>span').text().trim()).toEqual('Shared');
- expect($action.find('.icon').hasClass('icon-shared')).toEqual(true);
- expect($action.find('.icon').hasClass('icon-public')).toEqual(false);
- expect(OC.basename(getImageUrl($tr.find('.filename .thumbnail')))).toEqual('folder-shared.svg');
- });
- it('shows simple share text with share icon when shared to a room', function() {
- var $action, $tr;
- fileList.setFiles([{
- id: 1,
- type: 'dir',
- name: 'One',
- path: '/subdir',
- mimetype: 'text/plain',
- size: 12,
- permissions: OC.PERMISSION_ALL,
- etag: 'abc',
- shareTypes: [OC.Share.SHARE_TYPE_ROOM]
- }]);
- $tr = fileList.$el.find('tbody tr:first');
- $action = $tr.find('.action-share');
- expect($action.find('>span').text().trim()).toEqual('Shared');
- expect($action.find('.icon').hasClass('icon-shared')).toEqual(true);
- expect($action.find('.icon').hasClass('icon-public')).toEqual(false);
- expect(OC.basename(getImageUrl($tr.find('.filename .thumbnail')))).toEqual('folder-shared.svg');
- });
- it('shows simple share text with public icon when shared with link', function() {
- var $action, $tr;
- OC.Share.statuses = {1: {link: true, path: '/subdir'}};
- fileList.setFiles([{
- id: 1,
- type: 'dir',
- name: 'One',
- path: '/subdir',
- mimetype: 'text/plain',
- size: 12,
- permissions: OC.PERMISSION_ALL,
- etag: 'abc',
- shareTypes: [OC.Share.SHARE_TYPE_LINK]
- }]);
- $tr = fileList.$el.find('tbody tr:first');
- $action = $tr.find('.action-share');
- expect($action.find('>span').text().trim()).toEqual('Shared');
- expect($action.find('.icon').hasClass('icon-shared')).toEqual(false);
- expect($action.find('.icon').hasClass('icon-public')).toEqual(true);
- expect(OC.basename(getImageUrl($tr.find('.filename .thumbnail')))).toEqual('folder-public.svg');
- });
- it('shows owner name when owner is available but no icons', function() {
- var $action, $tr;
- fileList.setFiles([{
- id: 1,
- type: 'dir',
- name: 'One.txt',
- path: '/subdir',
- mimetype: 'text/plain',
- size: 12,
- permissions: OC.PERMISSION_ALL,
- shareOwner: 'User One',
- shareOwnerId: 'User One',
- etag: 'abc',
- shareTypes: []
- }]);
- $tr = fileList.$el.find('tbody tr:first');
- $action = $tr.find('.action-share');
- expect($action.find('>span').text().trim()).toEqual('Shared by User One');
- expect($action.find('.icon').hasClass('icon-shared')).toEqual(false);
- expect($action.find('.icon').hasClass('icon-public')).toEqual(false);
- expect(OC.basename(getImageUrl($tr.find('.filename .thumbnail')))).toEqual('folder-shared.svg');
- });
- it('shows recipients when recipients are available', function() {
- var $action, $tr;
- fileList.setFiles([{
- id: 1,
- type: 'dir',
- name: 'One.txt',
- path: '/subdir',
- mimetype: 'text/plain',
- size: 12,
- permissions: OC.PERMISSION_ALL,
- recipientsDisplayName: 'User One, User Two',
- recipientData: {
- 0: {
- shareWith: 'User One',
- shareWithDisplayName: 'User One'
- },
- 1: {
- shareWith: 'User Two',
- shareWithDisplayName: 'User Two'
- }
- },
- etag: 'abc',
- shareTypes: [OC.Share.SHARE_TYPE_USER]
- }]);
- $tr = fileList.$el.find('tbody tr:first');
- $action = $tr.find('.action-share');
- expect($action.text().trim()).toEqual('Shared with User One Shared with User Two');
- expect($action.find('.icon').hasClass('icon-shared')).toEqual(true);
- expect($action.find('.icon').hasClass('icon-public')).toEqual(false);
- expect(OC.basename(getImageUrl($tr.find('.filename .thumbnail')))).toEqual('folder-shared.svg');
- });
- it('shows share action when shared with user who has no share permission', function() {
- var $action, $tr;
- fileList.setFiles([{
- id: 1,
- type: 'dir',
- name: 'One',
- path: '/subdir',
- mimetype: 'text/plain',
- size: 12,
- permissions: OC.PERMISSION_CREATE,
- etag: 'abc',
- shareOwner: 'User One'
- }]);
- $tr = fileList.$el.find('tbody tr:first');
- expect($tr.find('.action-share').length).toEqual(1);
- });
- it('do not show share action when share exists but neither permission nor owner is available', function() {
- var $action, $tr;
- fileList.setFiles([{
- id: 1,
- type: 'dir',
- name: 'One',
- path: '/subdir',
- mimetype: 'text/plain',
- size: 12,
- permissions: OC.PERMISSION_CREATE,
- etag: 'abc'
- }]);
- $tr = fileList.$el.find('tbody tr:first');
- expect($tr.find('.action-share').length).toEqual(0);
- });
- });
- describe('Excluded lists', function() {
- function createListThenAttach(listId) {
- var fileActions = new OCA.Files.FileActions();
- fileList.destroy();
- fileList = new OCA.Files.FileList(
- $('#listContainer'), {
- id: listId,
- fileActions: fileActions
- }
- );
- OCA.Sharing.Util.attach(fileList);
- fileList.setFiles(testFiles);
- return fileList;
- }
-
- it('does not attach to trashbin or public file lists', function() {
- createListThenAttach('trashbin');
- expect($('.action-share').length).toEqual(0);
- expect($('[data-share-recipient]').length).toEqual(0);
- createListThenAttach('files.public');
- expect($('.action-share').length).toEqual(0);
- expect($('[data-share-recipient]').length).toEqual(0);
- });
- });
-
- describe('ShareTabView interaction', function() {
- var shareTabSpy;
- var fileInfoModel;
- var configModel;
- var shareModel;
-
- beforeEach(function() {
- shareTabSpy = sinon.spy(OCA.Sharing, 'ShareTabView');
-
- var attributes = {
- itemType: 'file',
- itemSource: 123,
- possiblePermissions: 31,
- permissions: 31
- };
- fileInfoModel = new OCA.Files.FileInfoModel(testFiles[0]);
- configModel = new OC.Share.ShareConfigModel({
- enforcePasswordForPublicLink: false,
- isResharingAllowed: true,
- isDefaultExpireDateEnabled: false,
- isDefaultExpireDateEnforced: false,
- defaultExpireDate: 7
- });
- shareModel = new OC.Share.ShareItemModel(attributes, {
- configModel: configModel,
- fileInfoModel: fileInfoModel
- });
-
- /* jshint camelcase: false */
- shareModel.set({
- reshare: {},
- shares: [{
- id: 100,
- item_source: 1,
- permissions: 31,
- share_type: OC.Share.SHARE_TYPE_USER,
- share_with: 'user1',
- share_with_displayname: 'User One'
- }, {
- id: 102,
- item_source: 1,
- permissions: 31,
- share_type: OC.Share.SHARE_TYPE_REMOTE,
- share_with: 'foo@bar.com/baz',
- share_with_displayname: 'foo@bar.com/baz'
-
- }]
- }, {parse: true});
-
- fileList.destroy();
- fileList = new OCA.Files.FileList(
- $('#listContainer'), {
- id: 'files',
- fileActions: new OCA.Files.FileActions()
- }
- );
- OCA.Sharing.Util.attach(fileList);
- fileList.setFiles(testFiles);
- });
- afterEach(function() {
- shareTabSpy.restore();
- });
- });
-});