aboutsummaryrefslogtreecommitdiffstats
path: root/tests/Core/Controller
diff options
context:
space:
mode:
Diffstat (limited to 'tests/Core/Controller')
-rw-r--r--tests/Core/Controller/AppPasswordControllerTest.php22
-rw-r--r--tests/Core/Controller/AutoCompleteControllerTest.php17
-rw-r--r--tests/Core/Controller/AvatarControllerTest.php95
-rw-r--r--tests/Core/Controller/ChangePasswordControllerTest.php13
-rw-r--r--tests/Core/Controller/ClientFlowLoginControllerTest.php157
-rw-r--r--tests/Core/Controller/ClientFlowLoginV2ControllerTest.php105
-rw-r--r--tests/Core/Controller/ContactsMenuControllerTest.php6
-rw-r--r--tests/Core/Controller/CssControllerTest.php11
-rw-r--r--tests/Core/Controller/GuestAvatarControllerTest.php6
-rw-r--r--tests/Core/Controller/JsControllerTest.php11
-rw-r--r--tests/Core/Controller/LoginControllerTest.php155
-rw-r--r--tests/Core/Controller/LostControllerTest.php121
-rw-r--r--tests/Core/Controller/NavigationControllerTest.php88
-rw-r--r--tests/Core/Controller/OCSControllerTest.php44
-rw-r--r--tests/Core/Controller/PreviewControllerTest.php195
-rw-r--r--tests/Core/Controller/ProfilePageControllerTest.php78
-rw-r--r--tests/Core/Controller/TwoFactorChallengeControllerTest.php42
-rw-r--r--tests/Core/Controller/UserControllerTest.php3
-rw-r--r--tests/Core/Controller/WellKnownControllerTest.php6
-rw-r--r--tests/Core/Controller/WipeControllerTest.php12
20 files changed, 699 insertions, 488 deletions
diff --git a/tests/Core/Controller/AppPasswordControllerTest.php b/tests/Core/Controller/AppPasswordControllerTest.php
index 6b7b023ab2e..eb1566eca8b 100644
--- a/tests/Core/Controller/AppPasswordControllerTest.php
+++ b/tests/Core/Controller/AppPasswordControllerTest.php
@@ -86,7 +86,7 @@ class AppPasswordControllerTest extends TestCase {
);
}
- public function testGetAppPasswordWithAppPassword() {
+ public function testGetAppPasswordWithAppPassword(): void {
$this->session->method('exists')
->with('app_password')
->willReturn(true);
@@ -96,7 +96,7 @@ class AppPasswordControllerTest extends TestCase {
$this->controller->getAppPassword();
}
- public function testGetAppPasswordNoLoginCreds() {
+ public function testGetAppPasswordNoLoginCreds(): void {
$this->session->method('exists')
->with('app_password')
->willReturn(false);
@@ -108,7 +108,7 @@ class AppPasswordControllerTest extends TestCase {
$this->controller->getAppPassword();
}
- public function testGetAppPassword() {
+ public function testGetAppPassword(): void {
$credentials = $this->createMock(ICredentials::class);
$this->session->method('exists')
@@ -123,12 +123,12 @@ class AppPasswordControllerTest extends TestCase {
$credentials->method('getLoginName')
->willReturn('myLoginName');
$this->request->method('getHeader')
- ->with('USER_AGENT')
+ ->with('user-agent')
->willReturn('myUA');
$this->random->method('generate')
->with(
72,
- ISecureRandom::CHAR_UPPER.ISecureRandom::CHAR_LOWER.ISecureRandom::CHAR_DIGITS
+ ISecureRandom::CHAR_UPPER . ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_DIGITS
)->willReturn('myToken');
$this->tokenProvider->expects($this->once())
@@ -149,7 +149,7 @@ class AppPasswordControllerTest extends TestCase {
$this->controller->getAppPassword();
}
- public function testGetAppPasswordNoPassword() {
+ public function testGetAppPasswordNoPassword(): void {
$credentials = $this->createMock(ICredentials::class);
$this->session->method('exists')
@@ -164,12 +164,12 @@ class AppPasswordControllerTest extends TestCase {
$credentials->method('getLoginName')
->willReturn('myLoginName');
$this->request->method('getHeader')
- ->with('USER_AGENT')
+ ->with('user-agent')
->willReturn('myUA');
$this->random->method('generate')
->with(
72,
- ISecureRandom::CHAR_UPPER.ISecureRandom::CHAR_LOWER.ISecureRandom::CHAR_DIGITS
+ ISecureRandom::CHAR_UPPER . ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_DIGITS
)->willReturn('myToken');
$this->tokenProvider->expects($this->once())
@@ -190,7 +190,7 @@ class AppPasswordControllerTest extends TestCase {
$this->controller->getAppPassword();
}
- public function testDeleteAppPasswordNoAppPassword() {
+ public function testDeleteAppPasswordNoAppPassword(): void {
$this->session->method('exists')
->with('app_password')
->willReturn(false);
@@ -200,7 +200,7 @@ class AppPasswordControllerTest extends TestCase {
$this->controller->deleteAppPassword();
}
- public function testDeleteAppPasswordFails() {
+ public function testDeleteAppPasswordFails(): void {
$this->session->method('exists')
->with('app_password')
->willReturn(true);
@@ -217,7 +217,7 @@ class AppPasswordControllerTest extends TestCase {
$this->controller->deleteAppPassword();
}
- public function testDeleteAppPasswordSuccess() {
+ public function testDeleteAppPasswordSuccess(): void {
$this->session->method('exists')
->with('app_password')
->willReturn(true);
diff --git a/tests/Core/Controller/AutoCompleteControllerTest.php b/tests/Core/Controller/AutoCompleteControllerTest.php
index e2797181097..c5574f78fc1 100644
--- a/tests/Core/Controller/AutoCompleteControllerTest.php
+++ b/tests/Core/Controller/AutoCompleteControllerTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2017 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
@@ -15,13 +16,13 @@ use PHPUnit\Framework\MockObject\MockObject;
use Test\TestCase;
class AutoCompleteControllerTest extends TestCase {
- /** @var ISearch|MockObject */
+ /** @var ISearch|MockObject */
protected $collaboratorSearch;
- /** @var IManager|MockObject */
+ /** @var IManager|MockObject */
protected $autoCompleteManager;
- /** @var IEventDispatcher|MockObject */
+ /** @var IEventDispatcher|MockObject */
protected $dispatcher;
- /** @var AutoCompleteController */
+ /** @var AutoCompleteController */
protected $controller;
protected function setUp(): void {
@@ -42,7 +43,7 @@ class AutoCompleteControllerTest extends TestCase {
);
}
- public function searchDataProvider() {
+ public static function searchDataProvider(): array {
return [
[ #0 – regular search
// searchResults
@@ -153,10 +154,8 @@ class AutoCompleteControllerTest extends TestCase {
];
}
- /**
- * @dataProvider searchDataProvider
- */
- public function testGet(array $searchResults, array $expected, string $searchTerm, ?string $itemType, ?string $itemId, ?string $sorter) {
+ #[\PHPUnit\Framework\Attributes\DataProvider('searchDataProvider')]
+ public function testGet(array $searchResults, array $expected, string $searchTerm, ?string $itemType, ?string $itemId, ?string $sorter): void {
$this->collaboratorSearch->expects($this->once())
->method('search')
->willReturn([$searchResults, false]);
diff --git a/tests/Core/Controller/AvatarControllerTest.php b/tests/Core/Controller/AvatarControllerTest.php
index b000482e29a..a78e2c1bb5c 100644
--- a/tests/Core/Controller/AvatarControllerTest.php
+++ b/tests/Core/Controller/AvatarControllerTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -128,9 +129,9 @@ class AvatarControllerTest extends \Test\TestCase {
/**
* Fetch an avatar if a user has no avatar
*/
- public function testGetAvatarNoAvatar() {
+ public function testGetAvatarNoAvatar(): void {
$this->avatarManager->method('getAvatar')->willReturn($this->avatarMock);
- $this->avatarMock->method('getFile')->will($this->throwException(new NotFoundException()));
+ $this->avatarMock->method('getFile')->willThrowException(new NotFoundException());
$response = $this->avatarController->getAvatar('userId', 32);
//Comment out until JS is fixed
@@ -140,7 +141,7 @@ class AvatarControllerTest extends \Test\TestCase {
/**
* Fetch the user's avatar
*/
- public function testGetAvatar() {
+ public function testGetAvatar(): void {
$this->avatarMock->method('getFile')->willReturn($this->avatarFile);
$this->avatarManager->method('getAvatar')->with('userId')->willReturn($this->avatarMock);
$this->avatarMock->expects($this->once())
@@ -161,7 +162,7 @@ class AvatarControllerTest extends \Test\TestCase {
/**
* Fetch the user's avatar
*/
- public function testGetGeneratedAvatar() {
+ public function testGetGeneratedAvatar(): void {
$this->avatarMock->method('getFile')->willReturn($this->avatarFile);
$this->avatarManager->method('getAvatar')->with('userId')->willReturn($this->avatarMock);
@@ -179,11 +180,11 @@ class AvatarControllerTest extends \Test\TestCase {
/**
* Fetch the avatar of a non-existing user
*/
- public function testGetAvatarNoUser() {
+ public function testGetAvatarNoUser(): void {
$this->avatarManager
->method('getAvatar')
->with('userDoesNotExist')
- ->will($this->throwException(new \Exception('user does not exist')));
+ ->willThrowException(new \Exception('user does not exist'));
$response = $this->avatarController->getAvatar('userDoesNotExist', 32);
@@ -276,7 +277,7 @@ class AvatarControllerTest extends \Test\TestCase {
/**
* Remove an avatar
*/
- public function testDeleteAvatar() {
+ public function testDeleteAvatar(): void {
$this->avatarManager->method('getAvatar')->willReturn($this->avatarMock);
$response = $this->avatarController->deleteAvatar();
@@ -286,13 +287,13 @@ class AvatarControllerTest extends \Test\TestCase {
/**
* Test what happens if the removing of the avatar fails
*/
- public function testDeleteAvatarException() {
- $this->avatarMock->method('remove')->will($this->throwException(new \Exception("foo")));
+ public function testDeleteAvatarException(): void {
+ $this->avatarMock->method('remove')->willThrowException(new \Exception('foo'));
$this->avatarManager->method('getAvatar')->willReturn($this->avatarMock);
$this->logger->expects($this->once())
->method('error')
- ->with('foo', ['exception' => new \Exception("foo"), 'app' => 'core']);
+ ->with('foo', ['exception' => new \Exception('foo'), 'app' => 'core']);
$expectedResponse = new Http\JSONResponse(['data' => ['message' => 'An error occurred. Please contact your admin.']], Http::STATUS_BAD_REQUEST);
$this->assertEquals($expectedResponse, $this->avatarController->deleteAvatar());
}
@@ -300,7 +301,7 @@ class AvatarControllerTest extends \Test\TestCase {
/**
* Trying to get a tmp avatar when it is not available. 404
*/
- public function testTmpAvatarNoTmp() {
+ public function testTmpAvatarNoTmp(): void {
$response = $this->avatarController->getTmpAvatar();
$this->assertEquals(Http::STATUS_NOT_FOUND, $response->getStatus());
}
@@ -308,8 +309,8 @@ class AvatarControllerTest extends \Test\TestCase {
/**
* Fetch tmp avatar
*/
- public function testTmpAvatarValid() {
- $this->cache->method('get')->willReturn(file_get_contents(\OC::$SERVERROOT.'/tests/data/testimage.jpg'));
+ public function testTmpAvatarValid(): void {
+ $this->cache->method('get')->willReturn(file_get_contents(\OC::$SERVERROOT . '/tests/data/testimage.jpg'));
$response = $this->avatarController->getTmpAvatar();
$this->assertEquals(Http::STATUS_OK, $response->getStatus());
@@ -319,7 +320,7 @@ class AvatarControllerTest extends \Test\TestCase {
/**
* When trying to post a new avatar a path or image should be posted.
*/
- public function testPostAvatarNoPathOrImage() {
+ public function testPostAvatarNoPathOrImage(): void {
$response = $this->avatarController->postAvatar(null);
$this->assertEquals(Http::STATUS_BAD_REQUEST, $response->getStatus());
@@ -328,17 +329,17 @@ class AvatarControllerTest extends \Test\TestCase {
/**
* Test a correct post of an avatar using POST
*/
- public function testPostAvatarFile() {
+ public function testPostAvatarFile(): void {
//Create temp file
- $fileName = tempnam('', "avatarTest");
- $copyRes = copy(\OC::$SERVERROOT.'/tests/data/testimage.jpg', $fileName);
+ $fileName = tempnam('', 'avatarTest');
+ $copyRes = copy(\OC::$SERVERROOT . '/tests/data/testimage.jpg', $fileName);
$this->assertTrue($copyRes);
//Create file in cache
- $this->cache->method('get')->willReturn(file_get_contents(\OC::$SERVERROOT.'/tests/data/testimage.jpg'));
+ $this->cache->method('get')->willReturn(file_get_contents(\OC::$SERVERROOT . '/tests/data/testimage.jpg'));
//Create request return
- $reqRet = ['error' => [0], 'tmp_name' => [$fileName], 'size' => [filesize(\OC::$SERVERROOT.'/tests/data/testimage.jpg')]];
+ $reqRet = ['error' => [0], 'tmp_name' => [$fileName], 'size' => [filesize(\OC::$SERVERROOT . '/tests/data/testimage.jpg')]];
$this->request->method('getUploadedFile')->willReturn($reqRet);
$response = $this->avatarController->postAvatar(null);
@@ -353,7 +354,7 @@ class AvatarControllerTest extends \Test\TestCase {
/**
* Test invalid post os an avatar using POST
*/
- public function testPostAvatarInvalidFile() {
+ public function testPostAvatarInvalidFile(): void {
//Create request return
$reqRet = ['error' => [1], 'tmp_name' => ['foo']];
$this->request->method('getUploadedFile')->willReturn($reqRet);
@@ -366,17 +367,17 @@ class AvatarControllerTest extends \Test\TestCase {
/**
* Check what happens when we upload a GIF
*/
- public function testPostAvatarFileGif() {
+ public function testPostAvatarFileGif(): void {
//Create temp file
- $fileName = tempnam('', "avatarTest");
- $copyRes = copy(\OC::$SERVERROOT.'/tests/data/testimage.gif', $fileName);
+ $fileName = tempnam('', 'avatarTest');
+ $copyRes = copy(\OC::$SERVERROOT . '/tests/data/testimage.gif', $fileName);
$this->assertTrue($copyRes);
//Create file in cache
- $this->cache->method('get')->willReturn(file_get_contents(\OC::$SERVERROOT.'/tests/data/testimage.gif'));
+ $this->cache->method('get')->willReturn(file_get_contents(\OC::$SERVERROOT . '/tests/data/testimage.gif'));
//Create request return
- $reqRet = ['error' => [0], 'tmp_name' => [$fileName], 'size' => [filesize(\OC::$SERVERROOT.'/tests/data/testimage.gif')]];
+ $reqRet = ['error' => [0], 'tmp_name' => [$fileName], 'size' => [filesize(\OC::$SERVERROOT . '/tests/data/testimage.gif')]];
$this->request->method('getUploadedFile')->willReturn($reqRet);
$response = $this->avatarController->postAvatar(null);
@@ -390,13 +391,13 @@ class AvatarControllerTest extends \Test\TestCase {
/**
* Test posting avatar from existing file
*/
- public function testPostAvatarFromFile() {
+ public function testPostAvatarFromFile(): void {
//Mock node API call
$file = $this->getMockBuilder('OCP\Files\File')
->disableOriginalConstructor()->getMock();
$file->expects($this->once())
->method('getContent')
- ->willReturn(file_get_contents(\OC::$SERVERROOT.'/tests/data/testimage.jpg'));
+ ->willReturn(file_get_contents(\OC::$SERVERROOT . '/tests/data/testimage.jpg'));
$file->expects($this->once())
->method('getMimeType')
->willReturn('image/jpeg');
@@ -414,7 +415,7 @@ class AvatarControllerTest extends \Test\TestCase {
/**
* Test posting avatar from existing folder
*/
- public function testPostAvatarFromNoFile() {
+ public function testPostAvatarFromNoFile(): void {
$file = $this->getMockBuilder('OCP\Files\Node')->getMock();
$userFolder = $this->getMockBuilder('OCP\Files\Folder')->getMock();
$this->rootFolder->method('getUserFolder')->with('userid')->willReturn($userFolder);
@@ -430,7 +431,7 @@ class AvatarControllerTest extends \Test\TestCase {
$this->assertEquals(['data' => ['message' => 'Please select a file.']], $response->getData());
}
- public function testPostAvatarInvalidType() {
+ public function testPostAvatarInvalidType(): void {
$file = $this->getMockBuilder('OCP\Files\File')
->disableOriginalConstructor()->getMock();
$file->expects($this->never())
@@ -446,7 +447,7 @@ class AvatarControllerTest extends \Test\TestCase {
$this->assertEquals($expectedResponse, $this->avatarController->postAvatar('avatar.jpg'));
}
- public function testPostAvatarNotPermittedException() {
+ public function testPostAvatarNotPermittedException(): void {
$file = $this->getMockBuilder('OCP\Files\File')
->disableOriginalConstructor()->getMock();
$file->expects($this->once())
@@ -466,15 +467,15 @@ class AvatarControllerTest extends \Test\TestCase {
/**
* Test what happens if the upload of the avatar fails
*/
- public function testPostAvatarException() {
+ public function testPostAvatarException(): void {
$this->cache->expects($this->once())
->method('set')
- ->will($this->throwException(new \Exception("foo")));
+ ->willThrowException(new \Exception('foo'));
$file = $this->getMockBuilder('OCP\Files\File')
->disableOriginalConstructor()->getMock();
$file->expects($this->once())
->method('getContent')
- ->willReturn(file_get_contents(\OC::$SERVERROOT.'/tests/data/testimage.jpg'));
+ ->willReturn(file_get_contents(\OC::$SERVERROOT . '/tests/data/testimage.jpg'));
$file->expects($this->once())
->method('getMimeType')
->willReturn('image/jpeg');
@@ -484,7 +485,7 @@ class AvatarControllerTest extends \Test\TestCase {
$this->logger->expects($this->once())
->method('error')
- ->with('foo', ['exception' => new \Exception("foo"), 'app' => 'core']);
+ ->with('foo', ['exception' => new \Exception('foo'), 'app' => 'core']);
$expectedResponse = new Http\JSONResponse(['data' => ['message' => 'An error occurred. Please contact your admin.']], Http::STATUS_OK);
$this->assertEquals($expectedResponse, $this->avatarController->postAvatar('avatar.jpg'));
}
@@ -493,7 +494,7 @@ class AvatarControllerTest extends \Test\TestCase {
/**
* Test invalid crop argument
*/
- public function testPostCroppedAvatarInvalidCrop() {
+ public function testPostCroppedAvatarInvalidCrop(): void {
$response = $this->avatarController->postCroppedAvatar([]);
$this->assertEquals(Http::STATUS_BAD_REQUEST, $response->getStatus());
@@ -502,7 +503,7 @@ class AvatarControllerTest extends \Test\TestCase {
/**
* Test no tmp avatar to crop
*/
- public function testPostCroppedAvatarNoTmpAvatar() {
+ public function testPostCroppedAvatarNoTmpAvatar(): void {
$response = $this->avatarController->postCroppedAvatar(['x' => 0, 'y' => 0, 'w' => 10, 'h' => 10]);
$this->assertEquals(Http::STATUS_BAD_REQUEST, $response->getStatus());
@@ -511,10 +512,10 @@ class AvatarControllerTest extends \Test\TestCase {
/**
* Test with non square crop
*/
- public function testPostCroppedAvatarNoSquareCrop() {
- $this->cache->method('get')->willReturn(file_get_contents(\OC::$SERVERROOT.'/tests/data/testimage.jpg'));
+ public function testPostCroppedAvatarNoSquareCrop(): void {
+ $this->cache->method('get')->willReturn(file_get_contents(\OC::$SERVERROOT . '/tests/data/testimage.jpg'));
- $this->avatarMock->method('set')->will($this->throwException(new \OC\NotSquareException));
+ $this->avatarMock->method('set')->willThrowException(new \OC\NotSquareException);
$this->avatarManager->method('getAvatar')->willReturn($this->avatarMock);
$response = $this->avatarController->postCroppedAvatar(['x' => 0, 'y' => 0, 'w' => 10, 'h' => 11]);
@@ -524,8 +525,8 @@ class AvatarControllerTest extends \Test\TestCase {
/**
* Check for proper reply on proper crop argument
*/
- public function testPostCroppedAvatarValidCrop() {
- $this->cache->method('get')->willReturn(file_get_contents(\OC::$SERVERROOT.'/tests/data/testimage.jpg'));
+ public function testPostCroppedAvatarValidCrop(): void {
+ $this->cache->method('get')->willReturn(file_get_contents(\OC::$SERVERROOT . '/tests/data/testimage.jpg'));
$this->avatarManager->method('getAvatar')->willReturn($this->avatarMock);
$response = $this->avatarController->postCroppedAvatar(['x' => 0, 'y' => 0, 'w' => 10, 'h' => 10]);
@@ -536,15 +537,15 @@ class AvatarControllerTest extends \Test\TestCase {
/**
* Test what happens if the cropping of the avatar fails
*/
- public function testPostCroppedAvatarException() {
- $this->cache->method('get')->willReturn(file_get_contents(\OC::$SERVERROOT.'/tests/data/testimage.jpg'));
+ public function testPostCroppedAvatarException(): void {
+ $this->cache->method('get')->willReturn(file_get_contents(\OC::$SERVERROOT . '/tests/data/testimage.jpg'));
- $this->avatarMock->method('set')->will($this->throwException(new \Exception('foo')));
+ $this->avatarMock->method('set')->willThrowException(new \Exception('foo'));
$this->avatarManager->method('getAvatar')->willReturn($this->avatarMock);
$this->logger->expects($this->once())
->method('error')
- ->with('foo', ['exception' => new \Exception("foo"), 'app' => 'core']);
+ ->with('foo', ['exception' => new \Exception('foo'), 'app' => 'core']);
$expectedResponse = new Http\JSONResponse(['data' => ['message' => 'An error occurred. Please contact your admin.']], Http::STATUS_BAD_REQUEST);
$this->assertEquals($expectedResponse, $this->avatarController->postCroppedAvatar(['x' => 0, 'y' => 0, 'w' => 10, 'h' => 11]));
}
@@ -553,8 +554,8 @@ class AvatarControllerTest extends \Test\TestCase {
/**
* Check for proper reply on proper crop argument
*/
- public function testFileTooBig() {
- $fileName = \OC::$SERVERROOT.'/tests/data/testimage.jpg';
+ public function testFileTooBig(): void {
+ $fileName = \OC::$SERVERROOT . '/tests/data/testimage.jpg';
//Create request return
$reqRet = ['error' => [0], 'tmp_name' => [$fileName], 'size' => [21 * 1024 * 1024]];
$this->request->method('getUploadedFile')->willReturn($reqRet);
diff --git a/tests/Core/Controller/ChangePasswordControllerTest.php b/tests/Core/Controller/ChangePasswordControllerTest.php
index 93fb4196d35..aae36fb52b8 100644
--- a/tests/Core/Controller/ChangePasswordControllerTest.php
+++ b/tests/Core/Controller/ChangePasswordControllerTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
@@ -60,7 +61,7 @@ class ChangePasswordControllerTest extends \Test\TestCase {
);
}
- public function testChangePersonalPasswordWrongPassword() {
+ public function testChangePersonalPasswordWrongPassword(): void {
$this->userSession->expects($this->once())
->method('getLoginName')
->willReturn($this->loginName);
@@ -82,7 +83,7 @@ class ChangePasswordControllerTest extends \Test\TestCase {
$this->assertEquals($expects, $actual);
}
- public function testChangePersonalPasswordCommonPassword() {
+ public function testChangePersonalPasswordCommonPassword(): void {
$this->userSession->expects($this->once())
->method('getLoginName')
->willReturn($this->loginName);
@@ -96,7 +97,7 @@ class ChangePasswordControllerTest extends \Test\TestCase {
$user->expects($this->once())
->method('setPassword')
->with('new')
- ->will($this->throwException(new HintException('Common password')));
+ ->willThrowException(new HintException('Common password'));
$expects = new JSONResponse([
'status' => 'error',
@@ -109,7 +110,7 @@ class ChangePasswordControllerTest extends \Test\TestCase {
$this->assertEquals($expects, $actual);
}
- public function testChangePersonalPasswordNoNewPassword() {
+ public function testChangePersonalPasswordNoNewPassword(): void {
$this->userSession->expects($this->once())
->method('getLoginName')
->willReturn($this->loginName);
@@ -132,7 +133,7 @@ class ChangePasswordControllerTest extends \Test\TestCase {
$this->assertEquals($expects, $res->getData());
}
- public function testChangePersonalPasswordCantSetPassword() {
+ public function testChangePersonalPasswordCantSetPassword(): void {
$this->userSession->expects($this->once())
->method('getLoginName')
->willReturn($this->loginName);
@@ -159,7 +160,7 @@ class ChangePasswordControllerTest extends \Test\TestCase {
$this->assertEquals($expects, $actual);
}
- public function testChangePersonalPassword() {
+ public function testChangePersonalPassword(): void {
$this->userSession->expects($this->once())
->method('getLoginName')
->willReturn($this->loginName);
diff --git a/tests/Core/Controller/ClientFlowLoginControllerTest.php b/tests/Core/Controller/ClientFlowLoginControllerTest.php
index 98f09f0f18c..b182bb1bb39 100644
--- a/tests/Core/Controller/ClientFlowLoginControllerTest.php
+++ b/tests/Core/Controller/ClientFlowLoginControllerTest.php
@@ -1,4 +1,7 @@
<?php
+
+declare(strict_types=1);
+
/**
* SPDX-FileCopyrightText: 2017 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
@@ -15,10 +18,14 @@ use OCA\OAuth2\Db\AccessTokenMapper;
use OCA\OAuth2\Db\Client;
use OCA\OAuth2\Db\ClientMapper;
use OCP\AppFramework\Http;
+use OCP\AppFramework\Http\ContentSecurityPolicy;
+use OCP\AppFramework\Http\RedirectResponse;
+use OCP\AppFramework\Http\Response;
use OCP\AppFramework\Http\StandaloneTemplateResponse;
use OCP\AppFramework\Utility\ITimeFactory;
use OCP\Defaults;
use OCP\EventDispatcher\IEventDispatcher;
+use OCP\IConfig;
use OCP\IL10N;
use OCP\IRequest;
use OCP\ISession;
@@ -28,38 +35,26 @@ use OCP\IUserSession;
use OCP\Security\ICrypto;
use OCP\Security\ISecureRandom;
use OCP\Session\Exceptions\SessionNotAvailableException;
+use PHPUnit\Framework\MockObject\MockObject;
use Test\TestCase;
class ClientFlowLoginControllerTest extends TestCase {
- /** @var IRequest|\PHPUnit\Framework\MockObject\MockObject */
- private $request;
- /** @var IUserSession|\PHPUnit\Framework\MockObject\MockObject */
- private $userSession;
- /** @var IL10N|\PHPUnit\Framework\MockObject\MockObject */
- private $l10n;
- /** @var Defaults|\PHPUnit\Framework\MockObject\MockObject */
- private $defaults;
- /** @var ISession|\PHPUnit\Framework\MockObject\MockObject */
- private $session;
- /** @var IProvider|\PHPUnit\Framework\MockObject\MockObject */
- private $tokenProvider;
- /** @var ISecureRandom|\PHPUnit\Framework\MockObject\MockObject */
- private $random;
- /** @var IURLGenerator|\PHPUnit\Framework\MockObject\MockObject */
- private $urlGenerator;
- /** @var ClientMapper|\PHPUnit\Framework\MockObject\MockObject */
- private $clientMapper;
- /** @var AccessTokenMapper|\PHPUnit\Framework\MockObject\MockObject */
- private $accessTokenMapper;
- /** @var ICrypto|\PHPUnit\Framework\MockObject\MockObject */
- private $crypto;
- /** @var IEventDispatcher|\PHPUnit\Framework\MockObject\MockObject */
- private $eventDispatcher;
- /** @var ITimeFactory|\PHPUnit\Framework\MockObject\MockObject */
- private $timeFactory;
-
- /** @var ClientFlowLoginController */
- private $clientFlowLoginController;
+ private IRequest&MockObject $request;
+ private IUserSession&MockObject $userSession;
+ private IL10N&MockObject $l10n;
+ private Defaults&MockObject $defaults;
+ private ISession&MockObject $session;
+ private IProvider&MockObject $tokenProvider;
+ private ISecureRandom&MockObject $random;
+ private IURLGenerator&MockObject $urlGenerator;
+ private ClientMapper&MockObject $clientMapper;
+ private AccessTokenMapper&MockObject $accessTokenMapper;
+ private ICrypto&MockObject $crypto;
+ private IEventDispatcher&MockObject $eventDispatcher;
+ private ITimeFactory&MockObject $timeFactory;
+ private IConfig&MockObject $config;
+
+ private ClientFlowLoginController $clientFlowLoginController;
protected function setUp(): void {
parent::setUp();
@@ -83,6 +78,7 @@ class ClientFlowLoginControllerTest extends TestCase {
$this->crypto = $this->createMock(ICrypto::class);
$this->eventDispatcher = $this->createMock(IEventDispatcher::class);
$this->timeFactory = $this->createMock(ITimeFactory::class);
+ $this->config = $this->createMock(IConfig::class);
$this->clientFlowLoginController = new ClientFlowLoginController(
'core',
@@ -98,17 +94,18 @@ class ClientFlowLoginControllerTest extends TestCase {
$this->accessTokenMapper,
$this->crypto,
$this->eventDispatcher,
- $this->timeFactory
+ $this->timeFactory,
+ $this->config,
);
}
- public function testShowAuthPickerPageNoClientOrOauthRequest() {
+ public function testShowAuthPickerPageNoClientOrOauthRequest(): void {
$expected = new StandaloneTemplateResponse(
'core',
'error',
[
- 'errors' =>
- [
+ 'errors'
+ => [
[
'error' => 'Access Forbidden',
'hint' => 'Invalid request',
@@ -121,15 +118,11 @@ class ClientFlowLoginControllerTest extends TestCase {
$this->assertEquals($expected, $this->clientFlowLoginController->showAuthPickerPage());
}
- public function testShowAuthPickerPageWithOcsHeader() {
+ public function testShowAuthPickerPageWithOcsHeader(): void {
$this->request
->method('getHeader')
- ->withConsecutive(
- ['USER_AGENT'],
- ['OCS-APIREQUEST']
- )
->willReturnMap([
- ['USER_AGENT', 'Mac OS X Sync Client'],
+ ['user-agent', 'Mac OS X Sync Client'],
['OCS-APIREQUEST', 'true'],
]);
$this->random
@@ -137,7 +130,7 @@ class ClientFlowLoginControllerTest extends TestCase {
->method('generate')
->with(
64,
- ISecureRandom::CHAR_LOWER.ISecureRandom::CHAR_UPPER.ISecureRandom::CHAR_DIGITS
+ ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_UPPER . ISecureRandom::CHAR_DIGITS
)
->willReturn('StateToken');
$this->session
@@ -173,25 +166,22 @@ class ClientFlowLoginControllerTest extends TestCase {
'serverHost' => 'https://example.com',
'oauthState' => 'OauthStateToken',
'user' => '',
- 'direct' => 0
+ 'direct' => 0,
+ 'providedRedirectUri' => '',
],
'guest'
);
- $csp = new Http\ContentSecurityPolicy();
+ $csp = new ContentSecurityPolicy();
$csp->addAllowedFormActionDomain('nc://*');
$expected->setContentSecurityPolicy($csp);
$this->assertEquals($expected, $this->clientFlowLoginController->showAuthPickerPage());
}
- public function testShowAuthPickerPageWithOauth() {
+ public function testShowAuthPickerPageWithOauth(): void {
$this->request
->method('getHeader')
- ->withConsecutive(
- ['USER_AGENT'],
- ['OCS-APIREQUEST']
- )
->willReturnMap([
- ['USER_AGENT', 'Mac OS X Sync Client'],
+ ['user-agent', 'Mac OS X Sync Client'],
['OCS-APIREQUEST', 'false'],
]);
$client = new Client();
@@ -207,7 +197,7 @@ class ClientFlowLoginControllerTest extends TestCase {
->method('generate')
->with(
64,
- ISecureRandom::CHAR_LOWER.ISecureRandom::CHAR_UPPER.ISecureRandom::CHAR_DIGITS
+ ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_UPPER . ISecureRandom::CHAR_DIGITS
)
->willReturn('StateToken');
$this->session
@@ -243,17 +233,18 @@ class ClientFlowLoginControllerTest extends TestCase {
'serverHost' => 'https://example.com',
'oauthState' => 'OauthStateToken',
'user' => '',
- 'direct' => 0
+ 'direct' => 0,
+ 'providedRedirectUri' => '',
],
'guest'
);
- $csp = new Http\ContentSecurityPolicy();
+ $csp = new ContentSecurityPolicy();
$csp->addAllowedFormActionDomain('https://example.com/redirect.php');
$expected->setContentSecurityPolicy($csp);
$this->assertEquals($expected, $this->clientFlowLoginController->showAuthPickerPage('MyClientIdentifier'));
}
- public function testGenerateAppPasswordWithInvalidToken() {
+ public function testGenerateAppPasswordWithInvalidToken(): void {
$this->session
->expects($this->once())
->method('get')
@@ -276,7 +267,7 @@ class ClientFlowLoginControllerTest extends TestCase {
$this->assertEquals($expected, $this->clientFlowLoginController->generateAppPassword('MyStateToken'));
}
- public function testGenerateAppPasswordWithSessionNotAvailableException() {
+ public function testGenerateAppPasswordWithSessionNotAvailableException(): void {
$this->session
->expects($this->once())
->method('get')
@@ -291,12 +282,12 @@ class ClientFlowLoginControllerTest extends TestCase {
->method('getId')
->willThrowException(new SessionNotAvailableException());
- $expected = new Http\Response();
+ $expected = new Response();
$expected->setStatus(Http::STATUS_FORBIDDEN);
$this->assertEquals($expected, $this->clientFlowLoginController->generateAppPassword('MyStateToken'));
}
- public function testGenerateAppPasswordWithInvalidTokenException() {
+ public function testGenerateAppPasswordWithInvalidTokenException(): void {
$this->session
->expects($this->once())
->method('get')
@@ -316,12 +307,12 @@ class ClientFlowLoginControllerTest extends TestCase {
->with('SessionId')
->willThrowException(new InvalidTokenException());
- $expected = new Http\Response();
+ $expected = new Response();
$expected->setStatus(Http::STATUS_FORBIDDEN);
$this->assertEquals($expected, $this->clientFlowLoginController->generateAppPassword('MyStateToken'));
}
- public function testGeneratePasswordWithPassword() {
+ public function testGeneratePasswordWithPassword(): void {
$this->session
->expects($this->once())
->method('get')
@@ -392,7 +383,7 @@ class ClientFlowLoginControllerTest extends TestCase {
$this->eventDispatcher->expects($this->once())
->method('dispatchTyped');
- $expected = new Http\RedirectResponse('nc://login/server:http://example.com&user:MyLoginName&password:MyGeneratedToken');
+ $expected = new RedirectResponse('nc://login/server:http://example.com&user:MyLoginName&password:MyGeneratedToken');
$this->assertEquals($expected, $this->clientFlowLoginController->generateAppPassword('MyStateToken'));
}
@@ -405,23 +396,23 @@ class ClientFlowLoginControllerTest extends TestCase {
* ["https://example.com/redirect.php?hello=world", "https://example.com/redirect.php?hello=world&state=MyOauthState&code=MyAccessCode"]
*
*/
- public function testGeneratePasswordWithPasswordForOauthClient($redirectUri, $redirectUrl) {
+ public function testGeneratePasswordWithPasswordForOauthClient($redirectUri, $redirectUrl): void {
$this->session
->method('get')
- ->withConsecutive(
- ['client.flow.state.token'],
- ['oauth.state']
- )
->willReturnMap([
['client.flow.state.token', 'MyStateToken'],
['oauth.state', 'MyOauthState'],
]);
+ $calls = [
+ 'client.flow.state.token',
+ 'oauth.state',
+ ];
$this->session
->method('remove')
- ->withConsecutive(
- ['client.flow.state.token'],
- ['oauth.state']
- );
+ ->willReturnCallback(function ($key) use (&$calls): void {
+ $expected = array_shift($calls);
+ $this->assertEquals($expected, $key);
+ });
$this->session
->expects($this->once())
->method('getId')
@@ -443,13 +434,9 @@ class ClientFlowLoginControllerTest extends TestCase {
->willReturn('MyPassword');
$this->random
->method('generate')
- ->withConsecutive(
- [72],
- [128]
- )
->willReturnMap([
- [72, ISecureRandom::CHAR_UPPER.ISecureRandom::CHAR_LOWER.ISecureRandom::CHAR_DIGITS, 'MyGeneratedToken'],
- [128, ISecureRandom::CHAR_UPPER.ISecureRandom::CHAR_LOWER.ISecureRandom::CHAR_DIGITS, 'MyAccessCode'],
+ [72, ISecureRandom::CHAR_UPPER . ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_DIGITS, 'MyGeneratedToken'],
+ [128, ISecureRandom::CHAR_UPPER . ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_DIGITS, 'MyAccessCode'],
]);
$user = $this->createMock(IUser::class);
$user
@@ -486,11 +473,11 @@ class ClientFlowLoginControllerTest extends TestCase {
$this->eventDispatcher->expects($this->once())
->method('dispatchTyped');
- $expected = new Http\RedirectResponse($redirectUrl);
+ $expected = new RedirectResponse($redirectUrl);
$this->assertEquals($expected, $this->clientFlowLoginController->generateAppPassword('MyStateToken', 'MyClientIdentifier'));
}
- public function testGeneratePasswordWithoutPassword() {
+ public function testGeneratePasswordWithoutPassword(): void {
$this->session
->expects($this->once())
->method('get')
@@ -561,17 +548,17 @@ class ClientFlowLoginControllerTest extends TestCase {
$this->eventDispatcher->expects($this->once())
->method('dispatchTyped');
- $expected = new Http\RedirectResponse('nc://login/server:http://example.com&user:MyLoginName&password:MyGeneratedToken');
+ $expected = new RedirectResponse('nc://login/server:http://example.com&user:MyLoginName&password:MyGeneratedToken');
$this->assertEquals($expected, $this->clientFlowLoginController->generateAppPassword('MyStateToken'));
}
- public function dataGeneratePasswordWithHttpsProxy() {
+ public static function dataGeneratePasswordWithHttpsProxy(): array {
return [
[
[
['X-Forwarded-Proto', 'http'],
['X-Forwarded-Ssl', 'off'],
- ['USER_AGENT', ''],
+ ['user-agent', ''],
],
'http',
'http',
@@ -580,7 +567,7 @@ class ClientFlowLoginControllerTest extends TestCase {
[
['X-Forwarded-Proto', 'http'],
['X-Forwarded-Ssl', 'off'],
- ['USER_AGENT', ''],
+ ['user-agent', ''],
],
'https',
'https',
@@ -589,7 +576,7 @@ class ClientFlowLoginControllerTest extends TestCase {
[
['X-Forwarded-Proto', 'https'],
['X-Forwarded-Ssl', 'off'],
- ['USER_AGENT', ''],
+ ['user-agent', ''],
],
'http',
'https',
@@ -598,7 +585,7 @@ class ClientFlowLoginControllerTest extends TestCase {
[
['X-Forwarded-Proto', 'https'],
['X-Forwarded-Ssl', 'on'],
- ['USER_AGENT', ''],
+ ['user-agent', ''],
],
'http',
'https',
@@ -607,7 +594,7 @@ class ClientFlowLoginControllerTest extends TestCase {
[
['X-Forwarded-Proto', 'http'],
['X-Forwarded-Ssl', 'on'],
- ['USER_AGENT', ''],
+ ['user-agent', ''],
],
'http',
'https',
@@ -616,12 +603,12 @@ class ClientFlowLoginControllerTest extends TestCase {
}
/**
- * @dataProvider dataGeneratePasswordWithHttpsProxy
* @param array $headers
* @param string $protocol
* @param string $expected
*/
- public function testGeneratePasswordWithHttpsProxy(array $headers, $protocol, $expected) {
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataGeneratePasswordWithHttpsProxy')]
+ public function testGeneratePasswordWithHttpsProxy(array $headers, $protocol, $expected): void {
$this->session
->expects($this->once())
->method('get')
@@ -692,7 +679,7 @@ class ClientFlowLoginControllerTest extends TestCase {
$this->eventDispatcher->expects($this->once())
->method('dispatchTyped');
- $expected = new Http\RedirectResponse('nc://login/server:' . $expected . '://example.com&user:MyLoginName&password:MyGeneratedToken');
+ $expected = new RedirectResponse('nc://login/server:' . $expected . '://example.com&user:MyLoginName&password:MyGeneratedToken');
$this->assertEquals($expected, $this->clientFlowLoginController->generateAppPassword('MyStateToken'));
}
}
diff --git a/tests/Core/Controller/ClientFlowLoginV2ControllerTest.php b/tests/Core/Controller/ClientFlowLoginV2ControllerTest.php
index eefa2982c74..d130eb75c1a 100644
--- a/tests/Core/Controller/ClientFlowLoginV2ControllerTest.php
+++ b/tests/Core/Controller/ClientFlowLoginV2ControllerTest.php
@@ -11,9 +11,12 @@ namespace Test\Core\Controller;
use OC\Core\Controller\ClientFlowLoginV2Controller;
use OC\Core\Data\LoginFlowV2Credentials;
use OC\Core\Db\LoginFlowV2;
+use OC\Core\Exception\LoginFlowV2ClientForbiddenException;
use OC\Core\Exception\LoginFlowV2NotFoundException;
use OC\Core\Service\LoginFlowV2Service;
use OCP\AppFramework\Http;
+use OCP\AppFramework\Http\RedirectResponse;
+use OCP\AppFramework\Http\StandaloneTemplateResponse;
use OCP\Defaults;
use OCP\IL10N;
use OCP\IRequest;
@@ -56,6 +59,12 @@ class ClientFlowLoginV2ControllerTest extends TestCase {
$this->random = $this->createMock(ISecureRandom::class);
$this->defaults = $this->createMock(Defaults::class);
$this->l = $this->createMock(IL10N::class);
+ $this->l
+ ->expects($this->any())
+ ->method('t')
+ ->willReturnCallback(function ($text, $parameters = []) {
+ return vsprintf($text, $parameters);
+ });
$this->controller = new ClientFlowLoginV2Controller(
'core',
$this->request,
@@ -70,7 +79,7 @@ class ClientFlowLoginV2ControllerTest extends TestCase {
);
}
- public function testPollInvalid() {
+ public function testPollInvalid(): void {
$this->loginFlowV2Service->method('poll')
->with('token')
->willThrowException(new LoginFlowV2NotFoundException());
@@ -81,7 +90,7 @@ class ClientFlowLoginV2ControllerTest extends TestCase {
$this->assertSame(Http::STATUS_NOT_FOUND, $result->getStatus());
}
- public function testPollValid() {
+ public function testPollValid(): void {
$creds = new LoginFlowV2Credentials('server', 'login', 'pass');
$this->loginFlowV2Service->method('poll')
->with('token')
@@ -93,7 +102,7 @@ class ClientFlowLoginV2ControllerTest extends TestCase {
$this->assertSame(Http::STATUS_OK, $result->getStatus());
}
- public function testLandingInvalid() {
+ public function testLandingInvalid(): void {
$this->session->expects($this->never())
->method($this->anything());
@@ -104,10 +113,10 @@ class ClientFlowLoginV2ControllerTest extends TestCase {
$result = $this->controller->landing('token');
$this->assertSame(Http::STATUS_FORBIDDEN, $result->getStatus());
- $this->assertInstanceOf(Http\StandaloneTemplateResponse::class, $result);
+ $this->assertInstanceOf(StandaloneTemplateResponse::class, $result);
}
- public function testLandingValid() {
+ public function testLandingValid(): void {
$this->session->expects($this->once())
->method('set')
->with('client.flow.v2.login.token', 'token');
@@ -122,12 +131,12 @@ class ClientFlowLoginV2ControllerTest extends TestCase {
$result = $this->controller->landing('token');
- $this->assertInstanceOf(Http\RedirectResponse::class, $result);
+ $this->assertInstanceOf(RedirectResponse::class, $result);
$this->assertSame(Http::STATUS_SEE_OTHER, $result->getStatus());
$this->assertSame('https://server/path', $result->getRedirectURL());
}
- public function testShowAuthPickerNoLoginToken() {
+ public function testShowAuthPickerNoLoginToken(): void {
$this->session->method('get')
->willReturn(null);
@@ -136,7 +145,7 @@ class ClientFlowLoginV2ControllerTest extends TestCase {
$this->assertSame(Http::STATUS_FORBIDDEN, $result->getStatus());
}
- public function testShowAuthPickerInvalidLoginToken() {
+ public function testShowAuthPickerInvalidLoginToken(): void {
$this->session->method('get')
->with('client.flow.v2.login.token')
->willReturn('loginToken');
@@ -150,7 +159,23 @@ class ClientFlowLoginV2ControllerTest extends TestCase {
$this->assertSame(Http::STATUS_FORBIDDEN, $result->getStatus());
}
- public function testShowAuthPickerValidLoginToken() {
+ public function testShowAuthPickerForbiddenUserClient() {
+ $this->session->method('get')
+ ->with('client.flow.v2.login.token')
+ ->willReturn('loginToken');
+
+ $this->loginFlowV2Service->method('getByLoginToken')
+ ->with('loginToken')
+ ->willThrowException(new LoginFlowV2ClientForbiddenException());
+
+ $result = $this->controller->showAuthPickerPage();
+
+ $this->assertInstanceOf(StandaloneTemplateResponse::class, $result);
+ $this->assertSame(Http::STATUS_FORBIDDEN, $result->getStatus());
+ $this->assertSame('Please use original client', $result->getParams()['message']);
+ }
+
+ public function testShowAuthPickerValidLoginToken(): void {
$this->session->method('get')
->with('client.flow.v2.login.token')
->willReturn('loginToken');
@@ -161,7 +186,7 @@ class ClientFlowLoginV2ControllerTest extends TestCase {
->willReturn($flow);
$this->random->method('generate')
- ->with(64, ISecureRandom::CHAR_LOWER.ISecureRandom::CHAR_UPPER.ISecureRandom::CHAR_DIGITS)
+ ->with(64, ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_UPPER . ISecureRandom::CHAR_DIGITS)
->willReturn('random');
$this->session->expects($this->once())
->method('set')
@@ -176,7 +201,7 @@ class ClientFlowLoginV2ControllerTest extends TestCase {
$this->assertSame(Http::STATUS_FORBIDDEN, $result->getStatus());
}
- public function testGrantPageInvalidStateToken() {
+ public function testGrantPageInvalidStateToken(): void {
$this->session->method('get')
->willReturnCallback(function ($name) {
return null;
@@ -186,7 +211,7 @@ class ClientFlowLoginV2ControllerTest extends TestCase {
$this->assertSame(Http::STATUS_FORBIDDEN, $result->getStatus());
}
- public function testGrantPageInvalidLoginToken() {
+ public function testGrantPageInvalidLoginToken(): void {
$this->session->method('get')
->willReturnCallback(function ($name) {
if ($name === 'client.flow.v2.state.token') {
@@ -206,7 +231,30 @@ class ClientFlowLoginV2ControllerTest extends TestCase {
$this->assertSame(Http::STATUS_FORBIDDEN, $result->getStatus());
}
- public function testGrantPageValid() {
+ public function testGrantPageForbiddenUserClient() {
+ $this->session->method('get')
+ ->willReturnCallback(function ($name) {
+ if ($name === 'client.flow.v2.state.token') {
+ return 'stateToken';
+ }
+ if ($name === 'client.flow.v2.login.token') {
+ return 'loginToken';
+ }
+ return null;
+ });
+
+ $this->loginFlowV2Service->method('getByLoginToken')
+ ->with('loginToken')
+ ->willThrowException(new LoginFlowV2ClientForbiddenException());
+
+ $result = $this->controller->grantPage('stateToken');
+
+ $this->assertInstanceOf(StandaloneTemplateResponse::class, $result);
+ $this->assertSame(Http::STATUS_FORBIDDEN, $result->getStatus());
+ $this->assertSame('Please use original client', $result->getParams()['message']);
+ }
+
+ public function testGrantPageValid(): void {
$this->session->method('get')
->willReturnCallback(function ($name) {
if ($name === 'client.flow.v2.state.token') {
@@ -236,7 +284,7 @@ class ClientFlowLoginV2ControllerTest extends TestCase {
}
- public function testGenerateAppPasswordInvalidStateToken() {
+ public function testGenerateAppPasswordInvalidStateToken(): void {
$this->session->method('get')
->willReturnCallback(function ($name) {
return null;
@@ -246,7 +294,7 @@ class ClientFlowLoginV2ControllerTest extends TestCase {
$this->assertSame(Http::STATUS_FORBIDDEN, $result->getStatus());
}
- public function testGenerateAppPassworInvalidLoginToken() {
+ public function testGenerateAppPassworInvalidLoginToken(): void {
$this->session->method('get')
->willReturnCallback(function ($name) {
if ($name === 'client.flow.v2.state.token') {
@@ -266,7 +314,30 @@ class ClientFlowLoginV2ControllerTest extends TestCase {
$this->assertSame(Http::STATUS_FORBIDDEN, $result->getStatus());
}
- public function testGenerateAppPassworValid() {
+ public function testGenerateAppPasswordForbiddenUserClient() {
+ $this->session->method('get')
+ ->willReturnCallback(function ($name) {
+ if ($name === 'client.flow.v2.state.token') {
+ return 'stateToken';
+ }
+ if ($name === 'client.flow.v2.login.token') {
+ return 'loginToken';
+ }
+ return null;
+ });
+
+ $this->loginFlowV2Service->method('getByLoginToken')
+ ->with('loginToken')
+ ->willThrowException(new LoginFlowV2ClientForbiddenException());
+
+ $result = $this->controller->generateAppPassword('stateToken');
+
+ $this->assertInstanceOf(StandaloneTemplateResponse::class, $result);
+ $this->assertSame(Http::STATUS_FORBIDDEN, $result->getStatus());
+ $this->assertSame('Please use original client', $result->getParams()['message']);
+ }
+
+ public function testGenerateAppPassworValid(): void {
$this->session->method('get')
->willReturnCallback(function ($name) {
if ($name === 'client.flow.v2.state.token') {
@@ -286,7 +357,7 @@ class ClientFlowLoginV2ControllerTest extends TestCase {
$clearedState = false;
$clearedLogin = false;
$this->session->method('remove')
- ->willReturnCallback(function ($name) use (&$clearedLogin, &$clearedState) {
+ ->willReturnCallback(function ($name) use (&$clearedLogin, &$clearedState): void {
if ($name === 'client.flow.v2.state.token') {
$clearedState = true;
}
diff --git a/tests/Core/Controller/ContactsMenuControllerTest.php b/tests/Core/Controller/ContactsMenuControllerTest.php
index d688ea6682f..aa20e6726e2 100644
--- a/tests/Core/Controller/ContactsMenuControllerTest.php
+++ b/tests/Core/Controller/ContactsMenuControllerTest.php
@@ -35,7 +35,7 @@ class ContactsMenuControllerTest extends TestCase {
$this->controller = new ContactsMenuController($request, $this->userSession, $this->contactsManager);
}
- public function testIndex() {
+ public function testIndex(): void {
$user = $this->createMock(IUser::class);
$entries = [
$this->createMock(IEntry::class),
@@ -54,7 +54,7 @@ class ContactsMenuControllerTest extends TestCase {
$this->assertEquals($entries, $response);
}
- public function testFindOne() {
+ public function testFindOne(): void {
$user = $this->createMock(IUser::class);
$entry = $this->createMock(IEntry::class);
$this->userSession->expects($this->once())
@@ -70,7 +70,7 @@ class ContactsMenuControllerTest extends TestCase {
$this->assertEquals($entry, $response);
}
- public function testFindOne404() {
+ public function testFindOne404(): void {
$user = $this->createMock(IUser::class);
$this->userSession->expects($this->once())
->method('getUser')
diff --git a/tests/Core/Controller/CssControllerTest.php b/tests/Core/Controller/CssControllerTest.php
index 8064f36cddb..b4764d6ea3a 100644
--- a/tests/Core/Controller/CssControllerTest.php
+++ b/tests/Core/Controller/CssControllerTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2017 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
@@ -56,7 +57,7 @@ class CssControllerTest extends TestCase {
);
}
- public function testNoCssFolderForApp() {
+ public function testNoCssFolderForApp(): void {
$this->appData->method('getFolder')
->with('myapp')
->willThrowException(new NotFoundException());
@@ -67,7 +68,7 @@ class CssControllerTest extends TestCase {
}
- public function testNoCssFile() {
+ public function testNoCssFile(): void {
$folder = $this->createMock(ISimpleFolder::class);
$this->appData->method('getFolder')
->with('myapp')
@@ -81,7 +82,7 @@ class CssControllerTest extends TestCase {
$this->assertInstanceOf(NotFoundResponse::class, $result);
}
- public function testGetFile() {
+ public function testGetFile(): void {
$folder = $this->createMock(ISimpleFolder::class);
$file = $this->createMock(ISimpleFile::class);
$file->method('getName')->willReturn('my name');
@@ -105,7 +106,7 @@ class CssControllerTest extends TestCase {
$this->assertEquals($expected, $result);
}
- public function testGetGzipFile() {
+ public function testGetGzipFile(): void {
$folder = $this->createMock(ISimpleFolder::class);
$gzipFile = $this->createMock(ISimpleFile::class);
$gzipFile->method('getName')->willReturn('my name');
@@ -134,7 +135,7 @@ class CssControllerTest extends TestCase {
$this->assertEquals($expected, $result);
}
- public function testGetGzipFileNotFound() {
+ public function testGetGzipFileNotFound(): void {
$folder = $this->createMock(ISimpleFolder::class);
$file = $this->createMock(ISimpleFile::class);
$file->method('getName')->willReturn('my name');
diff --git a/tests/Core/Controller/GuestAvatarControllerTest.php b/tests/Core/Controller/GuestAvatarControllerTest.php
index b2f60665948..66a83098130 100644
--- a/tests/Core/Controller/GuestAvatarControllerTest.php
+++ b/tests/Core/Controller/GuestAvatarControllerTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2019 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
@@ -7,6 +8,7 @@ namespace Core\Controller;
use OC\Core\Controller\GuestAvatarController;
use OCP\AppFramework\Http\FileDisplayResponse;
+use OCP\Files\File;
use OCP\Files\SimpleFS\ISimpleFile;
use OCP\IAvatar;
use OCP\IAvatarManager;
@@ -38,7 +40,7 @@ class GuestAvatarControllerTest extends \Test\TestCase {
private $avatar;
/**
- * @var \OCP\Files\File|\PHPUnit\Framework\MockObject\MockObject
+ * @var File|\PHPUnit\Framework\MockObject\MockObject
*/
private $file;
@@ -71,7 +73,7 @@ class GuestAvatarControllerTest extends \Test\TestCase {
/**
* Tests getAvatar returns the guest avatar.
*/
- public function testGetAvatar() {
+ public function testGetAvatar(): void {
$this->avatarManager->expects($this->once())
->method('getGuestAvatar')
->with('Peter')
diff --git a/tests/Core/Controller/JsControllerTest.php b/tests/Core/Controller/JsControllerTest.php
index 5aa853e4ed0..30bc02e8625 100644
--- a/tests/Core/Controller/JsControllerTest.php
+++ b/tests/Core/Controller/JsControllerTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2017 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
@@ -56,7 +57,7 @@ class JsControllerTest extends TestCase {
);
}
- public function testNoCssFolderForApp() {
+ public function testNoCssFolderForApp(): void {
$this->appData->method('getFolder')
->with('myapp')
->willThrowException(new NotFoundException());
@@ -67,7 +68,7 @@ class JsControllerTest extends TestCase {
}
- public function testNoCssFile() {
+ public function testNoCssFile(): void {
$folder = $this->createMock(ISimpleFolder::class);
$this->appData->method('getFolder')
->with('myapp')
@@ -81,7 +82,7 @@ class JsControllerTest extends TestCase {
$this->assertInstanceOf(NotFoundResponse::class, $result);
}
- public function testGetFile() {
+ public function testGetFile(): void {
$folder = $this->createMock(ISimpleFolder::class);
$file = $this->createMock(ISimpleFile::class);
$file->method('getName')->willReturn('my name');
@@ -105,7 +106,7 @@ class JsControllerTest extends TestCase {
$this->assertEquals($expected, $result);
}
- public function testGetGzipFile() {
+ public function testGetGzipFile(): void {
$folder = $this->createMock(ISimpleFolder::class);
$gzipFile = $this->createMock(ISimpleFile::class);
$gzipFile->method('getName')->willReturn('my name');
@@ -134,7 +135,7 @@ class JsControllerTest extends TestCase {
$this->assertEquals($expected, $result);
}
- public function testGetGzipFileNotFound() {
+ public function testGetGzipFileNotFound(): void {
$folder = $this->createMock(ISimpleFolder::class);
$file = $this->createMock(ISimpleFile::class);
$file->method('getName')->willReturn('my name');
diff --git a/tests/Core/Controller/LoginControllerTest.php b/tests/Core/Controller/LoginControllerTest.php
index 8fe24f156f6..18baaf5b08c 100644
--- a/tests/Core/Controller/LoginControllerTest.php
+++ b/tests/Core/Controller/LoginControllerTest.php
@@ -30,6 +30,7 @@ use OCP\IUser;
use OCP\IUserManager;
use OCP\Notification\IManager;
use OCP\Security\Bruteforce\IThrottler;
+use OCP\Security\ITrustedDomainHelper;
use PHPUnit\Framework\MockObject\MockObject;
use Test\TestCase;
@@ -105,6 +106,9 @@ class LoginControllerTest extends TestCase {
$this->request->method('getRemoteAddress')
->willReturn('1.2.3.4');
+ $this->request->method('getHeader')
+ ->with('Origin')
+ ->willReturn('domain.example.com');
$this->throttler->method('getDelay')
->with(
$this->equalTo('1.2.3.4'),
@@ -129,7 +133,7 @@ class LoginControllerTest extends TestCase {
);
}
- public function testLogoutWithoutToken() {
+ public function testLogoutWithoutToken(): void {
$this->request
->expects($this->once())
->method('getCookie')
@@ -156,7 +160,7 @@ class LoginControllerTest extends TestCase {
$this->assertEquals($expected, $this->loginController->logout());
}
- public function testLogoutNoClearSiteData() {
+ public function testLogoutNoClearSiteData(): void {
$this->request
->expects($this->once())
->method('getCookie')
@@ -179,7 +183,7 @@ class LoginControllerTest extends TestCase {
$this->assertEquals($expected, $this->loginController->logout());
}
- public function testLogoutWithToken() {
+ public function testLogoutWithToken(): void {
$this->request
->expects($this->once())
->method('getCookie')
@@ -216,7 +220,7 @@ class LoginControllerTest extends TestCase {
$this->assertEquals($expected, $this->loginController->logout());
}
- public function testShowLoginFormForLoggedInUsers() {
+ public function testShowLoginFormForLoggedInUsers(): void {
$this->userSession
->expects($this->once())
->method('isLoggedIn')
@@ -230,7 +234,7 @@ class LoginControllerTest extends TestCase {
$this->assertEquals($expectedResponse, $this->loginController->showLoginForm('', ''));
}
- public function testShowLoginFormWithErrorsInSession() {
+ public function testShowLoginFormWithErrorsInSession(): void {
$this->userSession
->expects($this->once())
->method('isLoggedIn')
@@ -251,9 +255,9 @@ class LoginControllerTest extends TestCase {
],
]
);
- $this->initialState->expects($this->exactly(13))
- ->method('provideInitialState')
- ->withConsecutive([
+
+ $calls = [
+ [
'loginMessages',
[
'MessageArray1',
@@ -261,17 +265,26 @@ class LoginControllerTest extends TestCase {
'This community release of Nextcloud is unsupported and push notifications are limited.',
],
],
+ [
+ 'loginErrors',
[
- 'loginErrors',
- [
- 'ErrorArray1',
- 'ErrorArray2',
- ],
+ 'ErrorArray1',
+ 'ErrorArray2',
],
- [
- 'loginUsername',
- '',
- ]);
+ ],
+ [
+ 'loginUsername',
+ '',
+ ]
+ ];
+ $this->initialState->expects($this->exactly(13))
+ ->method('provideInitialState')
+ ->willReturnCallback(function () use (&$calls): void {
+ $expected = array_shift($calls);
+ if (!empty($expected)) {
+ $this->assertEquals($expected, func_get_args());
+ }
+ });
$expectedResponse = new TemplateResponse(
'core',
@@ -285,20 +298,30 @@ class LoginControllerTest extends TestCase {
$this->assertEquals($expectedResponse, $this->loginController->showLoginForm('', ''));
}
- public function testShowLoginFormForFlowAuth() {
+ public function testShowLoginFormForFlowAuth(): void {
$this->userSession
->expects($this->once())
->method('isLoggedIn')
->willReturn(false);
- $this->initialState->expects($this->exactly(14))
- ->method('provideInitialState')
- ->withConsecutive([], [], [], [
+ $calls = [
+ [], [], [],
+ [
'loginAutocomplete',
false
- ], [
+ ],
+ [
'loginRedirectUrl',
'login/flow'
- ]);
+ ],
+ ];
+ $this->initialState->expects($this->exactly(14))
+ ->method('provideInitialState')
+ ->willReturnCallback(function () use (&$calls): void {
+ $expected = array_shift($calls);
+ if (!empty($expected)) {
+ $this->assertEquals($expected, func_get_args());
+ }
+ });
$expectedResponse = new TemplateResponse(
'core',
@@ -315,7 +338,7 @@ class LoginControllerTest extends TestCase {
/**
* @return array
*/
- public function passwordResetDataProvider(): array {
+ public static function passwordResetDataProvider(): array {
return [
[
true,
@@ -328,11 +351,9 @@ class LoginControllerTest extends TestCase {
];
}
- /**
- * @dataProvider passwordResetDataProvider
- */
+ #[\PHPUnit\Framework\Attributes\DataProvider('passwordResetDataProvider')]
public function testShowLoginFormWithPasswordResetOption($canChangePassword,
- $expectedResult) {
+ $expectedResult): void {
$this->userSession
->expects($this->once())
->method('isLoggedIn')
@@ -359,15 +380,26 @@ class LoginControllerTest extends TestCase {
->method('get')
->with('LdapUser')
->willReturn($user);
- $this->initialState->expects($this->exactly(13))
- ->method('provideInitialState')
- ->withConsecutive([], [], [
+ $calls = [
+ [], [],
+ [
'loginUsername',
'LdapUser'
- ], [], [], [], [
+ ],
+ [], [], [],
+ [
'loginCanResetPassword',
$expectedResult
- ]);
+ ],
+ ];
+ $this->initialState->expects($this->exactly(13))
+ ->method('provideInitialState')
+ ->willReturnCallback(function () use (&$calls): void {
+ $expected = array_shift($calls);
+ if (!empty($expected)) {
+ $this->assertEquals($expected, func_get_args());
+ }
+ });
$expectedResponse = new TemplateResponse(
'core',
@@ -381,7 +413,7 @@ class LoginControllerTest extends TestCase {
$this->assertEquals($expectedResponse, $this->loginController->showLoginForm('LdapUser', ''));
}
- public function testShowLoginFormForUserNamed0() {
+ public function testShowLoginFormForUserNamed0(): void {
$this->userSession
->expects($this->once())
->method('isLoggedIn')
@@ -407,18 +439,30 @@ class LoginControllerTest extends TestCase {
->method('get')
->with('0')
->willReturn($user);
- $this->initialState->expects($this->exactly(13))
- ->method('provideInitialState')
- ->withConsecutive([], [], [], [
+ $calls = [
+ [], [], [],
+ [
'loginAutocomplete',
true
- ], [], [
+ ],
+ [],
+ [
'loginResetPasswordLink',
false
- ], [
+ ],
+ [
'loginCanResetPassword',
false
- ]);
+ ],
+ ];
+ $this->initialState->expects($this->exactly(13))
+ ->method('provideInitialState')
+ ->willReturnCallback(function () use (&$calls): void {
+ $expected = array_shift($calls);
+ if (!empty($expected)) {
+ $this->assertEquals($expected, func_get_args());
+ }
+ });
$expectedResponse = new TemplateResponse(
'core',
@@ -437,6 +481,8 @@ class LoginControllerTest extends TestCase {
$password = 'secret';
$loginPageUrl = '/login?redirect_url=/apps/files';
$loginChain = $this->createMock(LoginChain::class);
+ $trustedDomainHelper = $this->createMock(ITrustedDomainHelper::class);
+ $trustedDomainHelper->method('isTrustedUrl')->willReturn(true);
$this->request
->expects($this->once())
->method('passesCSRFCheck')
@@ -463,15 +509,17 @@ class LoginControllerTest extends TestCase {
$expected = new RedirectResponse($loginPageUrl);
$expected->throttle(['user' => 'MyUserName']);
- $response = $this->loginController->tryLogin($loginChain, $user, $password, '/apps/files');
+ $response = $this->loginController->tryLogin($loginChain, $trustedDomainHelper, $user, $password, '/apps/files');
$this->assertEquals($expected, $response);
}
- public function testLoginWithValidCredentials() {
+ public function testLoginWithValidCredentials(): void {
$user = 'MyUserName';
$password = 'secret';
$loginChain = $this->createMock(LoginChain::class);
+ $trustedDomainHelper = $this->createMock(ITrustedDomainHelper::class);
+ $trustedDomainHelper->method('isTrustedUrl')->willReturn(true);
$this->request
->expects($this->once())
->method('passesCSRFCheck')
@@ -492,7 +540,7 @@ class LoginControllerTest extends TestCase {
->willReturn('/default/foo');
$expected = new RedirectResponse('/default/foo');
- $this->assertEquals($expected, $this->loginController->tryLogin($loginChain, $user, $password));
+ $this->assertEquals($expected, $this->loginController->tryLogin($loginChain, $trustedDomainHelper, $user, $password));
}
public function testLoginWithoutPassedCsrfCheckAndNotLoggedIn(): void {
@@ -504,6 +552,8 @@ class LoginControllerTest extends TestCase {
$password = 'secret';
$originalUrl = 'another%20url';
$loginChain = $this->createMock(LoginChain::class);
+ $trustedDomainHelper = $this->createMock(ITrustedDomainHelper::class);
+ $trustedDomainHelper->method('isTrustedUrl')->willReturn(true);
$this->request
->expects($this->once())
->method('passesCSRFCheck')
@@ -517,14 +567,14 @@ class LoginControllerTest extends TestCase {
$this->userSession->expects($this->never())
->method('createRememberMeToken');
- $response = $this->loginController->tryLogin($loginChain, 'Jane', $password, $originalUrl);
+ $response = $this->loginController->tryLogin($loginChain, $trustedDomainHelper, 'Jane', $password, $originalUrl);
$expected = new RedirectResponse('');
$expected->throttle(['user' => 'Jane']);
$this->assertEquals($expected, $response);
}
- public function testLoginWithoutPassedCsrfCheckAndLoggedIn() {
+ public function testLoginWithoutPassedCsrfCheckAndLoggedIn(): void {
/** @var IUser|MockObject $user */
$user = $this->createMock(IUser::class);
$user->expects($this->any())
@@ -534,6 +584,8 @@ class LoginControllerTest extends TestCase {
$originalUrl = 'another url';
$redirectUrl = 'http://localhost/another url';
$loginChain = $this->createMock(LoginChain::class);
+ $trustedDomainHelper = $this->createMock(ITrustedDomainHelper::class);
+ $trustedDomainHelper->method('isTrustedUrl')->willReturn(true);
$this->request
->expects($this->once())
->method('passesCSRFCheck')
@@ -555,17 +607,19 @@ class LoginControllerTest extends TestCase {
->with('remember_login_cookie_lifetime')
->willReturn(1234);
- $response = $this->loginController->tryLogin($loginChain, 'Jane', $password, $originalUrl);
+ $response = $this->loginController->tryLogin($loginChain, $trustedDomainHelper, 'Jane', $password, $originalUrl);
$expected = new RedirectResponse($redirectUrl);
$this->assertEquals($expected, $response);
}
- public function testLoginWithValidCredentialsAndRedirectUrl() {
+ public function testLoginWithValidCredentialsAndRedirectUrl(): void {
$user = 'MyUserName';
$password = 'secret';
$redirectUrl = 'https://next.cloud/apps/mail';
$loginChain = $this->createMock(LoginChain::class);
+ $trustedDomainHelper = $this->createMock(ITrustedDomainHelper::class);
+ $trustedDomainHelper->method('isTrustedUrl')->willReturn(true);
$this->request
->expects($this->once())
->method('passesCSRFCheck')
@@ -590,13 +644,15 @@ class LoginControllerTest extends TestCase {
->willReturn($redirectUrl);
$expected = new RedirectResponse($redirectUrl);
- $response = $this->loginController->tryLogin($loginChain, $user, $password, '/apps/mail');
+ $response = $this->loginController->tryLogin($loginChain, $trustedDomainHelper, $user, $password, '/apps/mail');
$this->assertEquals($expected, $response);
}
- public function testToNotLeakLoginName() {
+ public function testToNotLeakLoginName(): void {
$loginChain = $this->createMock(LoginChain::class);
+ $trustedDomainHelper = $this->createMock(ITrustedDomainHelper::class);
+ $trustedDomainHelper->method('isTrustedUrl')->willReturn(true);
$this->request
->expects($this->once())
->method('passesCSRFCheck')
@@ -629,6 +685,7 @@ class LoginControllerTest extends TestCase {
$response = $this->loginController->tryLogin(
$loginChain,
+ $trustedDomainHelper,
'john@doe.com',
'just wrong',
'/apps/files'
diff --git a/tests/Core/Controller/LostControllerTest.php b/tests/Core/Controller/LostControllerTest.php
index 1e1771f7a15..bbb5f2c2e54 100644
--- a/tests/Core/Controller/LostControllerTest.php
+++ b/tests/Core/Controller/LostControllerTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2023 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-only
@@ -138,7 +139,7 @@ class LostControllerTest extends TestCase {
);
}
- public function testResetFormTokenError() {
+ public function testResetFormTokenError(): void {
$this->userManager->method('get')
->with('ValidTokenUser')
->willReturn($this->existingUser);
@@ -160,7 +161,7 @@ class LostControllerTest extends TestCase {
$this->assertEquals($expectedResponse, $response);
}
- public function testResetFormValidToken() {
+ public function testResetFormValidToken(): void {
$this->userManager->method('get')
->with('ValidTokenUser')
->willReturn($this->existingUser);
@@ -172,13 +173,18 @@ class LostControllerTest extends TestCase {
->method('linkToRouteAbsolute')
->with('core.lost.setPassword', ['userId' => 'ValidTokenUser', 'token' => 'MySecretToken'])
->willReturn('https://example.tld/index.php/lostpassword/set/sometoken/someuser');
+
+ $calls = [
+ ['resetPasswordUser', 'ValidTokenUser'],
+ ['resetPasswordTarget', 'https://example.tld/index.php/lostpassword/set/sometoken/someuser'],
+ ];
$this->initialState
->expects($this->exactly(2))
->method('provideInitialState')
- ->withConsecutive(
- ['resetPasswordUser', 'ValidTokenUser'],
- ['resetPasswordTarget', 'https://example.tld/index.php/lostpassword/set/sometoken/someuser']
- );
+ ->willReturnCallback(function () use (&$calls): void {
+ $expected = array_shift($calls);
+ $this->assertEquals($expected, func_get_args());
+ });
$response = $this->lostController->resetform('MySecretToken', 'ValidTokenUser');
$expectedResponse = new TemplateResponse('core',
@@ -188,7 +194,7 @@ class LostControllerTest extends TestCase {
$this->assertEquals($expectedResponse, $response);
}
- public function testEmailUnsuccessful() {
+ public function testEmailUnsuccessful(): void {
$existingUser = 'ExistingUser';
$nonExistingUser = 'NonExistingUser';
$this->userManager
@@ -230,12 +236,12 @@ class LostControllerTest extends TestCase {
$this->assertEquals($expectedResponse, $response);
}
- public function testEmailSuccessful() {
+ public function testEmailSuccessful(): void {
$this->userManager
- ->expects($this->any())
- ->method('get')
- ->with('ExistingUser')
- ->willReturn($this->existingUser);
+ ->expects($this->any())
+ ->method('get')
+ ->with('ExistingUser')
+ ->willReturn($this->existingUser);
$this->verificationToken->expects($this->once())
->method('create')
->willReturn('ThisIsMaybeANotSoSecretToken!');
@@ -287,17 +293,17 @@ class LostControllerTest extends TestCase {
$this->assertEquals($expectedResponse, $response);
}
- public function testEmailWithMailSuccessful() {
+ public function testEmailWithMailSuccessful(): void {
$this->userManager
- ->expects($this->any())
- ->method('get')
- ->with('test@example.com')
- ->willReturn(null);
+ ->expects($this->any())
+ ->method('get')
+ ->with('test@example.com')
+ ->willReturn(null);
$this->userManager
- ->expects($this->any())
- ->method('getByEmail')
- ->with('test@example.com')
- ->willReturn([$this->existingUser]);
+ ->expects($this->any())
+ ->method('getByEmail')
+ ->with('test@example.com')
+ ->willReturn([$this->existingUser]);
$this->verificationToken->expects($this->once())
->method('create')
->willReturn('ThisIsMaybeANotSoSecretToken!');
@@ -349,12 +355,12 @@ class LostControllerTest extends TestCase {
$this->assertEquals($expectedResponse, $response);
}
- public function testEmailCantSendException() {
+ public function testEmailCantSendException(): void {
$this->userManager
- ->expects($this->any())
- ->method('get')
- ->with('ExistingUser')
- ->willReturn($this->existingUser);
+ ->expects($this->any())
+ ->method('get')
+ ->with('ExistingUser')
+ ->willReturn($this->existingUser);
$this->verificationToken->expects($this->once())
->method('create')
->willReturn('ThisIsMaybeANotSoSecretToken!');
@@ -398,7 +404,7 @@ class LostControllerTest extends TestCase {
->expects($this->once())
->method('send')
->with($message)
- ->will($this->throwException(new \Exception()));
+ ->willThrowException(new \Exception());
$this->logger->expects($this->exactly(1))
->method('error');
@@ -409,7 +415,7 @@ class LostControllerTest extends TestCase {
$this->assertEquals($expectedResponse, $response);
}
- public function testSetPasswordUnsuccessful() {
+ public function testSetPasswordUnsuccessful(): void {
$this->config->method('getUserValue')
->with('ValidTokenUser', 'core', 'lostpassword', null)
->willReturn('encryptedData');
@@ -435,7 +441,7 @@ class LostControllerTest extends TestCase {
$this->assertSame($expectedResponse, $response->getData());
}
- public function testSetPasswordSuccessful() {
+ public function testSetPasswordSuccessful(): void {
$this->config->method('getUserValue')
->with('ValidTokenUser', 'core', 'lostpassword', null)
->willReturn('encryptedData');
@@ -448,12 +454,19 @@ class LostControllerTest extends TestCase {
$this->userManager->method('get')
->with('ValidTokenUser')
->willReturn($this->existingUser);
- $beforePasswordResetEvent = new BeforePasswordResetEvent($this->existingUser, 'NewPassword');
- $passwordResetEvent = new PasswordResetEvent($this->existingUser, 'NewPassword');
+
+ $calls = [
+ [new BeforePasswordResetEvent($this->existingUser, 'NewPassword')],
+ [new PasswordResetEvent($this->existingUser, 'NewPassword')],
+ ];
$this->eventDispatcher
->expects($this->exactly(2))
->method('dispatchTyped')
- ->withConsecutive([$beforePasswordResetEvent], [$passwordResetEvent]);
+ ->willReturnCallback(function () use (&$calls): void {
+ $expected = array_shift($calls);
+ $this->assertEquals($expected, func_get_args());
+ });
+
$this->config->expects($this->once())
->method('deleteUserValue')
->with('ValidTokenUser', 'core', 'lostpassword');
@@ -463,7 +476,7 @@ class LostControllerTest extends TestCase {
$this->assertSame($expectedResponse, $response->getData());
}
- public function testSetPasswordExpiredToken() {
+ public function testSetPasswordExpiredToken(): void {
$this->config->method('getUserValue')
->with('ValidTokenUser', 'core', 'lostpassword', null)
->willReturn('encryptedData');
@@ -482,7 +495,7 @@ class LostControllerTest extends TestCase {
$this->assertSame($expectedResponse, $response->getData());
}
- public function testSetPasswordInvalidDataInDb() {
+ public function testSetPasswordInvalidDataInDb(): void {
$this->config->method('getUserValue')
->with('ValidTokenUser', 'core', 'lostpassword', null)
->willReturn('invalidEncryptedData');
@@ -502,7 +515,7 @@ class LostControllerTest extends TestCase {
$this->assertSame($expectedResponse, $response->getData());
}
- public function testIsSetPasswordWithoutTokenFailing() {
+ public function testIsSetPasswordWithoutTokenFailing(): void {
$this->config->method('getUserValue')
->with('ValidTokenUser', 'core', 'lostpassword', null)
->willReturn('aValidtoken');
@@ -521,7 +534,7 @@ class LostControllerTest extends TestCase {
$this->assertSame($expectedResponse, $response->getData());
}
- public function testSetPasswordForDisabledUser() {
+ public function testSetPasswordForDisabledUser(): void {
$user = $this->createMock(IUser::class);
$user->expects($this->any())
->method('isEnabled')
@@ -551,7 +564,7 @@ class LostControllerTest extends TestCase {
$this->assertSame($expectedResponse, $response->getData());
}
- public function testSendEmailNoEmail() {
+ public function testSendEmailNoEmail(): void {
$user = $this->createMock(IUser::class);
$user->expects($this->any())
->method('isEnabled')
@@ -574,7 +587,7 @@ class LostControllerTest extends TestCase {
$this->assertEquals($expectedResponse, $response);
}
- public function testSetPasswordEncryptionDontProceedPerUserKey() {
+ public function testSetPasswordEncryptionDontProceedPerUserKey(): void {
/** @var IEncryptionModule|MockObject $encryptionModule */
$encryptionModule = $this->createMock(IEncryptionModule::class);
$encryptionModule->expects($this->once())->method('needDetailedAccessList')->willReturn(true);
@@ -587,7 +600,7 @@ class LostControllerTest extends TestCase {
$this->assertSame($expectedResponse, $response->getData());
}
- public function testSetPasswordDontProceedMasterKey() {
+ public function testSetPasswordDontProceedMasterKey(): void {
$encryptionModule = $this->createMock(IEncryptionModule::class);
$encryptionModule->expects($this->once())->method('needDetailedAccessList')->willReturn(false);
$this->encryptionManager->expects($this->once())->method('getEncryptionModules')
@@ -615,7 +628,7 @@ class LostControllerTest extends TestCase {
$this->assertSame($expectedResponse, $response->getData());
}
- public function testTwoUsersWithSameEmail() {
+ public function testTwoUsersWithSameEmail(): void {
$user1 = $this->createMock(IUser::class);
$user1->expects($this->any())
->method('getEMailAddress')
@@ -666,18 +679,18 @@ class LostControllerTest extends TestCase {
/**
* @return array
*/
- public function dataTwoUserswithSameEmailOneDisabled(): array {
+ public static function dataTwoUsersWithSameEmailOneDisabled(): array {
return [
- ['user1' => true, 'user2' => false],
- ['user1' => false, 'user2' => true]
+ ['userEnabled1' => true, 'userEnabled2' => false],
+ ['userEnabled1' => false, 'userEnabled2' => true]
];
}
/**
- * @dataProvider dataTwoUserswithSameEmailOneDisabled
* @param bool $userEnabled1
* @param bool $userEnabled2
*/
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataTwoUsersWithSameEmailOneDisabled')]
public function testTwoUsersWithSameEmailOneDisabled(bool $userEnabled1, bool $userEnabled2): void {
$user1 = $this->createMock(IUser::class);
$user1->method('getEMailAddress')
@@ -707,12 +720,12 @@ class LostControllerTest extends TestCase {
$this->assertInstanceOf(IUser::class, $result);
}
- public function testTrimEmailInput() {
+ public function testTrimEmailInput(): void {
$this->userManager
- ->expects($this->once())
- ->method('getByEmail')
- ->with('test@example.com')
- ->willReturn([$this->existingUser]);
+ ->expects($this->once())
+ ->method('getByEmail')
+ ->with('test@example.com')
+ ->willReturn([$this->existingUser]);
$this->mailer
->expects($this->once())
@@ -724,12 +737,12 @@ class LostControllerTest extends TestCase {
$this->assertEquals($expectedResponse, $response);
}
- public function testUsernameInput() {
+ public function testUsernameInput(): void {
$this->userManager
- ->expects($this->once())
- ->method('get')
- ->with('ExistingUser')
- ->willReturn($this->existingUser);
+ ->expects($this->once())
+ ->method('get')
+ ->with('ExistingUser')
+ ->willReturn($this->existingUser);
$this->mailer
->expects($this->once())
diff --git a/tests/Core/Controller/NavigationControllerTest.php b/tests/Core/Controller/NavigationControllerTest.php
index 0d7c91d3034..d00976f18ec 100644
--- a/tests/Core/Controller/NavigationControllerTest.php
+++ b/tests/Core/Controller/NavigationControllerTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2018 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
@@ -7,7 +8,6 @@
namespace Tests\Core\Controller;
use OC\Core\Controller\NavigationController;
-use OCP\AppFramework\Http;
use OCP\AppFramework\Http\DataResponse;
use OCP\INavigationManager;
use OCP\IRequest;
@@ -42,13 +42,14 @@ class NavigationControllerTest extends TestCase {
);
}
- public function dataGetNavigation() {
+ public static function dataGetNavigation(): array {
return [
- [false], [true]
+ [false],
+ [true],
];
}
- /** @dataProvider dataGetNavigation */
- public function testGetAppNavigation($absolute) {
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataGetNavigation')]
+ public function testGetAppNavigation(bool $absolute): void {
$this->navigationManager->expects($this->once())
->method('getAll')
->with('link')
@@ -59,11 +60,10 @@ class NavigationControllerTest extends TestCase {
->willReturn('http://localhost/');
$this->urlGenerator->expects($this->exactly(2))
->method('getAbsoluteURL')
- ->withConsecutive(['/index.php/apps/files'], ['icon'])
- ->willReturnOnConsecutiveCalls(
- 'http://localhost/index.php/apps/files',
- 'http://localhost/icon'
- );
+ ->willReturnMap([
+ ['/index.php/apps/files', 'http://localhost/index.php/apps/files'],
+ ['icon', 'http://localhost/icon'],
+ ]);
$actual = $this->controller->getAppsNavigation($absolute);
$this->assertInstanceOf(DataResponse::class, $actual);
$this->assertEquals('http://localhost/index.php/apps/files', $actual->getData()[0]['href']);
@@ -76,8 +76,8 @@ class NavigationControllerTest extends TestCase {
}
}
- /** @dataProvider dataGetNavigation */
- public function testGetSettingsNavigation($absolute) {
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataGetNavigation')]
+ public function testGetSettingsNavigation(bool $absolute): void {
$this->navigationManager->expects($this->once())
->method('getAll')
->with('settings')
@@ -88,14 +88,10 @@ class NavigationControllerTest extends TestCase {
->willReturn('http://localhost/');
$this->urlGenerator->expects($this->exactly(2))
->method('getAbsoluteURL')
- ->withConsecutive(
- ['/index.php/settings/user'],
- ['/core/img/settings.svg']
- )
- ->willReturnOnConsecutiveCalls(
- 'http://localhost/index.php/settings/user',
- 'http://localhost/core/img/settings.svg'
- );
+ ->willReturnMap([
+ ['/index.php/settings/user', 'http://localhost/index.php/settings/user'],
+ ['/core/img/settings.svg', 'http://localhost/core/img/settings.svg']
+ ]);
$actual = $this->controller->getSettingsNavigation($absolute);
$this->assertInstanceOf(DataResponse::class, $actual);
$this->assertEquals('http://localhost/index.php/settings/user', $actual->getData()[0]['href']);
@@ -108,33 +104,35 @@ class NavigationControllerTest extends TestCase {
}
}
- public function testGetAppNavigationEtagMatch() {
- $navigation = [ ['id' => 'files', 'href' => '/index.php/apps/files', 'icon' => 'icon' ] ];
- $this->request->expects($this->once())
- ->method('getHeader')
- ->with('If-None-Match')
- ->willReturn(md5(json_encode($navigation)));
- $this->navigationManager->expects($this->once())
+ public function testEtagIgnoresLogout(): void {
+ $navigation1 = [
+ ['id' => 'files', 'href' => '/index.php/apps/files', 'icon' => 'icon' ],
+ ['id' => 'logout', 'href' => '/index.php/logout?requesttoken=abcd', 'icon' => 'icon' ],
+ ];
+ $navigation2 = [
+ ['id' => 'files', 'href' => '/index.php/apps/files', 'icon' => 'icon' ],
+ ['id' => 'logout', 'href' => '/index.php/logout?requesttoken=1234', 'icon' => 'icon' ],
+ ];
+ $navigation3 = [
+ ['id' => 'files', 'href' => '/index.php/apps/files/test', 'icon' => 'icon' ],
+ ['id' => 'logout', 'href' => '/index.php/logout?requesttoken=1234', 'icon' => 'icon' ],
+ ];
+ $this->navigationManager->expects($this->exactly(3))
->method('getAll')
->with('link')
- ->willReturn($navigation);
- $actual = $this->controller->getAppsNavigation();
- $this->assertInstanceOf(DataResponse::class, $actual);
- $this->assertEquals(Http::STATUS_NOT_MODIFIED, $actual->getStatus());
- }
+ ->willReturnOnConsecutiveCalls(
+ $navigation1,
+ $navigation2,
+ $navigation3,
+ );
- public function testGetSettingsNavigationEtagMatch() {
- $navigation = [ ['id' => 'logout', 'href' => '/index.php/apps/files', 'icon' => 'icon' ] ];
- $this->request->expects($this->once())
- ->method('getHeader')
- ->with('If-None-Match')
- ->willReturn(md5(json_encode([ ['id' => 'logout', 'href' => 'logout', 'icon' => 'icon' ] ])));
- $this->navigationManager->expects($this->once())
- ->method('getAll')
- ->with('settings')
- ->willReturn($navigation);
- $actual = $this->controller->getSettingsNavigation();
- $this->assertInstanceOf(DataResponse::class, $actual);
- $this->assertEquals(Http::STATUS_NOT_MODIFIED, $actual->getStatus());
+ // Changes in the logout url should not change the ETag
+ $request1 = $this->controller->getAppsNavigation();
+ $request2 = $this->controller->getAppsNavigation();
+ $this->assertEquals($request1->getETag(), $request2->getETag());
+
+ // Changes in non-logout urls should result in a different ETag
+ $request3 = $this->controller->getAppsNavigation();
+ $this->assertNotEquals($request2->getETag(), $request3->getETag());
}
}
diff --git a/tests/Core/Controller/OCSControllerTest.php b/tests/Core/Controller/OCSControllerTest.php
index 19b87a97359..bd7e26d5e8f 100644
--- a/tests/Core/Controller/OCSControllerTest.php
+++ b/tests/Core/Controller/OCSControllerTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@@ -15,6 +16,8 @@ use OCP\IRequest;
use OCP\IUser;
use OCP\IUserManager;
use OCP\IUserSession;
+use OCP\Server;
+use OCP\ServerVersion;
use Test\TestCase;
class OCSControllerTest extends TestCase {
@@ -28,6 +31,8 @@ class OCSControllerTest extends TestCase {
private $userManager;
/** @var Manager|\PHPUnit\Framework\MockObject\MockObject */
private $keyManager;
+ /** @var ServerVersion|\PHPUnit\Framework\MockObject\MockObject */
+ private $serverVersion;
/** @var OCSController */
private $controller;
@@ -39,6 +44,7 @@ class OCSControllerTest extends TestCase {
$this->userSession = $this->createMock(IUserSession::class);
$this->userManager = $this->createMock(IUserManager::class);
$this->keyManager = $this->createMock(Manager::class);
+ $serverVersion = Server::get(ServerVersion::class);
$this->controller = new OCSController(
'core',
@@ -46,7 +52,8 @@ class OCSControllerTest extends TestCase {
$this->capabilitiesManager,
$this->userSession,
$this->userManager,
- $this->keyManager
+ $this->keyManager,
+ $serverVersion
);
}
@@ -68,18 +75,19 @@ class OCSControllerTest extends TestCase {
return new DataResponse($data);
}
- public function testGetCapabilities() {
+ public function testGetCapabilities(): void {
$this->userSession->expects($this->once())
->method('isLoggedIn')
->willReturn(true);
- [$major, $minor, $micro] = \OCP\Util::getVersion();
+
+ $serverVersion = Server::get(ServerVersion::class);
$result = [];
$result['version'] = [
- 'major' => $major,
- 'minor' => $minor,
- 'micro' => $micro,
- 'string' => \OC_Util::getVersionString(),
+ 'major' => $serverVersion->getMajorVersion(),
+ 'minor' => $serverVersion->getMinorVersion(),
+ 'micro' => $serverVersion->getPatchVersion(),
+ 'string' => $serverVersion->getVersionString(),
'edition' => '',
'extendedSupport' => false
];
@@ -101,18 +109,18 @@ class OCSControllerTest extends TestCase {
$this->assertEquals($expected, $this->controller->getCapabilities());
}
- public function testGetCapabilitiesPublic() {
+ public function testGetCapabilitiesPublic(): void {
$this->userSession->expects($this->once())
->method('isLoggedIn')
->willReturn(false);
- [$major, $minor, $micro] = \OCP\Util::getVersion();
+ $serverVersion = Server::get(ServerVersion::class);
$result = [];
$result['version'] = [
- 'major' => $major,
- 'minor' => $minor,
- 'micro' => $micro,
- 'string' => \OC_Util::getVersionString(),
+ 'major' => $serverVersion->getMajorVersion(),
+ 'minor' => $serverVersion->getMinorVersion(),
+ 'micro' => $serverVersion->getPatchVersion(),
+ 'string' => $serverVersion->getVersionString(),
'edition' => '',
'extendedSupport' => false
];
@@ -135,7 +143,7 @@ class OCSControllerTest extends TestCase {
$this->assertEquals($expected, $this->controller->getCapabilities());
}
- public function testPersonCheckValid() {
+ public function testPersonCheckValid(): void {
$this->userManager->method('checkPassword')
->with(
$this->equalTo('user'),
@@ -150,7 +158,7 @@ class OCSControllerTest extends TestCase {
$this->assertEquals($expected, $this->controller->personCheck('user', 'pass'));
}
- public function testPersonInvalid() {
+ public function testPersonInvalid(): void {
$this->userManager->method('checkPassword')
->with(
$this->equalTo('user'),
@@ -162,7 +170,7 @@ class OCSControllerTest extends TestCase {
$this->assertEquals($expected, $this->controller->personCheck('user', 'wrongpass'));
}
- public function testPersonNoLogin() {
+ public function testPersonNoLogin(): void {
$this->userManager->method('checkPassword')
->with(
$this->equalTo('user'),
@@ -173,7 +181,7 @@ class OCSControllerTest extends TestCase {
$this->assertEquals($expected, $this->controller->personCheck('', ''));
}
- public function testGetIdentityProofWithNotExistingUser() {
+ public function testGetIdentityProofWithNotExistingUser(): void {
$this->userManager
->expects($this->once())
->method('get')
@@ -184,7 +192,7 @@ class OCSControllerTest extends TestCase {
$this->assertEquals($expected, $this->controller->getIdentityProof('NotExistingUser'));
}
- public function testGetIdentityProof() {
+ public function testGetIdentityProof(): void {
$user = $this->createMock(IUser::class);
$key = $this->createMock(Key::class);
$this->userManager
diff --git a/tests/Core/Controller/PreviewControllerTest.php b/tests/Core/Controller/PreviewControllerTest.php
index d330c1d5209..5a6cd1fba0a 100644
--- a/tests/Core/Controller/PreviewControllerTest.php
+++ b/tests/Core/Controller/PreviewControllerTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
@@ -14,34 +15,34 @@ use OCP\Files\Folder;
use OCP\Files\IRootFolder;
use OCP\Files\NotFoundException;
use OCP\Files\SimpleFS\ISimpleFile;
+use OCP\Files\Storage\ISharedStorage;
use OCP\Files\Storage\IStorage;
use OCP\IPreview;
use OCP\IRequest;
use OCP\Preview\IMimeIconProvider;
+use OCP\Share\IShare;
+use PHPUnit\Framework\MockObject\MockObject;
class PreviewControllerTest extends \Test\TestCase {
- /** @var IRootFolder|\PHPUnit\Framework\MockObject\MockObject */
- private $rootFolder;
-
- /** @var string */
- private $userId;
- /** @var IPreview|\PHPUnit\Framework\MockObject\MockObject */
- private $previewManager;
+ private string $userId;
+ private PreviewController $controller;
- /** @var PreviewController|\PHPUnit\Framework\MockObject\MockObject */
- private $controller;
+ private IRootFolder&MockObject $rootFolder;
+ private IPreview&MockObject $previewManager;
+ private IRequest&MockObject $request;
protected function setUp(): void {
parent::setUp();
- $this->rootFolder = $this->createMock(IRootFolder::class);
$this->userId = 'user';
+ $this->rootFolder = $this->createMock(IRootFolder::class);
$this->previewManager = $this->createMock(IPreview::class);
+ $this->request = $this->createMock(IRequest::class);
$this->controller = new PreviewController(
'core',
- $this->createMock(IRequest::class),
+ $this->request,
$this->previewManager,
$this->rootFolder,
$this->userId,
@@ -49,28 +50,28 @@ class PreviewControllerTest extends \Test\TestCase {
);
}
- public function testInvalidFile() {
+ public function testInvalidFile(): void {
$res = $this->controller->getPreview('');
$expected = new DataResponse([], Http::STATUS_BAD_REQUEST);
$this->assertEquals($expected, $res);
}
- public function testInvalidWidth() {
+ public function testInvalidWidth(): void {
$res = $this->controller->getPreview('file', 0);
$expected = new DataResponse([], Http::STATUS_BAD_REQUEST);
$this->assertEquals($expected, $res);
}
- public function testInvalidHeight() {
+ public function testInvalidHeight(): void {
$res = $this->controller->getPreview('file', 10, 0);
$expected = new DataResponse([], Http::STATUS_BAD_REQUEST);
$this->assertEquals($expected, $res);
}
- public function testFileNotFound() {
+ public function testFileNotFound(): void {
$userFolder = $this->createMock(Folder::class);
$this->rootFolder->method('getUserFolder')
->with($this->equalTo($this->userId))
@@ -86,7 +87,7 @@ class PreviewControllerTest extends \Test\TestCase {
$this->assertEquals($expected, $res);
}
- public function testNotAFile() {
+ public function testNotAFile(): void {
$userFolder = $this->createMock(Folder::class);
$this->rootFolder->method('getUserFolder')
->with($this->equalTo($this->userId))
@@ -103,7 +104,7 @@ class PreviewControllerTest extends \Test\TestCase {
$this->assertEquals($expected, $res);
}
- public function testNoPreviewAndNoIcon() {
+ public function testNoPreviewAndNoIcon(): void {
$userFolder = $this->createMock(Folder::class);
$this->rootFolder->method('getUserFolder')
->with($this->equalTo($this->userId))
@@ -124,7 +125,38 @@ class PreviewControllerTest extends \Test\TestCase {
$this->assertEquals($expected, $res);
}
- public function testForbiddenFile() {
+ public function testNoPreview() {
+ $userFolder = $this->createMock(Folder::class);
+ $this->rootFolder->method('getUserFolder')
+ ->with($this->equalTo($this->userId))
+ ->willReturn($userFolder);
+
+ $file = $this->createMock(File::class);
+ $userFolder->method('get')
+ ->with($this->equalTo('file'))
+ ->willReturn($file);
+
+ $storage = $this->createMock(IStorage::class);
+ $file->method('getStorage')
+ ->willReturn($storage);
+
+ $this->previewManager->method('isAvailable')
+ ->with($this->equalTo($file))
+ ->willReturn(true);
+
+ $file->method('isReadable')
+ ->willReturn(true);
+
+ $this->previewManager->method('getPreview')
+ ->with($this->equalTo($file), 10, 10, false, $this->equalTo('myMode'))
+ ->willThrowException(new NotFoundException());
+
+ $res = $this->controller->getPreview('file', 10, 10, true, true, 'myMode');
+ $expected = new DataResponse([], Http::STATUS_NOT_FOUND);
+
+ $this->assertEquals($expected, $res);
+ }
+ public function testFileWithoutReadPermission() {
$userFolder = $this->createMock(Folder::class);
$this->rootFolder->method('getUserFolder')
->with($this->equalTo($this->userId))
@@ -148,45 +180,107 @@ class PreviewControllerTest extends \Test\TestCase {
$this->assertEquals($expected, $res);
}
- public function testNoPreview() {
+ public function testFileWithoutDownloadPermission() {
$userFolder = $this->createMock(Folder::class);
$this->rootFolder->method('getUserFolder')
->with($this->equalTo($this->userId))
->willReturn($userFolder);
$file = $this->createMock(File::class);
+ $file->method('getId')->willReturn(123);
$userFolder->method('get')
->with($this->equalTo('file'))
->willReturn($file);
- $storage = $this->createMock(IStorage::class);
+ $this->previewManager->method('isAvailable')
+ ->with($this->equalTo($file))
+ ->willReturn(true);
+
+ $share = $this->createMock(IShare::class);
+ $share->method('canSeeContent')
+ ->willReturn(false);
+
+ $storage = $this->createMock(ISharedStorage::class);
+ $storage->method('instanceOfStorage')
+ ->with(ISharedStorage::class)
+ ->willReturn(true);
+ $storage->method('getShare')
+ ->willReturn($share);
+
$file->method('getStorage')
->willReturn($storage);
+ $file->method('isReadable')
+ ->willReturn(true);
+
+ $this->request->method('getHeader')->willReturn('');
+
+ $res = $this->controller->getPreview('file', 10, 10, true, true);
+ $expected = new DataResponse([], Http::STATUS_FORBIDDEN);
+
+ $this->assertEquals($expected, $res);
+ }
+
+ public function testFileWithoutDownloadPermissionButHeader() {
+ $userFolder = $this->createMock(Folder::class);
+ $this->rootFolder->method('getUserFolder')
+ ->with($this->equalTo($this->userId))
+ ->willReturn($userFolder);
+
+ $file = $this->createMock(File::class);
+ $file->method('getId')->willReturn(123);
+ $userFolder->method('get')
+ ->with($this->equalTo('file'))
+ ->willReturn($file);
$this->previewManager->method('isAvailable')
->with($this->equalTo($file))
->willReturn(true);
+ $share = $this->createMock(IShare::class);
+ $share->method('canSeeContent')
+ ->willReturn(false);
+
+ $storage = $this->createMock(ISharedStorage::class);
+ $storage->method('instanceOfStorage')
+ ->with(ISharedStorage::class)
+ ->willReturn(true);
+ $storage->method('getShare')
+ ->willReturn($share);
+
+ $file->method('getStorage')
+ ->willReturn($storage);
$file->method('isReadable')
->willReturn(true);
+ $this->request
+ ->method('getHeader')
+ ->with('x-nc-preview')
+ ->willReturn('true');
+
+ $preview = $this->createMock(ISimpleFile::class);
+ $preview->method('getName')->willReturn('my name');
+ $preview->method('getMTime')->willReturn(42);
$this->previewManager->method('getPreview')
->with($this->equalTo($file), 10, 10, false, $this->equalTo('myMode'))
- ->willThrowException(new NotFoundException());
+ ->willReturn($preview);
+ $preview->method('getMimeType')
+ ->willReturn('myMime');
$res = $this->controller->getPreview('file', 10, 10, true, true, 'myMode');
- $expected = new DataResponse([], Http::STATUS_NOT_FOUND);
- $this->assertEquals($expected, $res);
+ $this->assertEquals('myMime', $res->getHeaders()['Content-Type']);
+ $this->assertEquals(Http::STATUS_OK, $res->getStatus());
+ $this->assertEquals($preview, $this->invokePrivate($res, 'file'));
}
- public function testValidPreview() {
+ public function testValidPreview(): void {
$userFolder = $this->createMock(Folder::class);
$this->rootFolder->method('getUserFolder')
->with($this->equalTo($this->userId))
->willReturn($userFolder);
$file = $this->createMock(File::class);
+ $file->method('getId')->willReturn(123);
$userFolder->method('get')
->with($this->equalTo('file'))
->willReturn($file);
@@ -217,4 +311,57 @@ class PreviewControllerTest extends \Test\TestCase {
$this->assertEquals(Http::STATUS_OK, $res->getStatus());
$this->assertEquals($preview, $this->invokePrivate($res, 'file'));
}
+
+ public function testValidPreviewOfShare() {
+ $userFolder = $this->createMock(Folder::class);
+ $this->rootFolder->method('getUserFolder')
+ ->with($this->equalTo($this->userId))
+ ->willReturn($userFolder);
+
+ $file = $this->createMock(File::class);
+ $file->method('getId')->willReturn(123);
+ $userFolder->method('get')
+ ->with($this->equalTo('file'))
+ ->willReturn($file);
+
+ $this->previewManager->method('isAvailable')
+ ->with($this->equalTo($file))
+ ->willReturn(true);
+
+ // No attributes set -> download permitted
+ $share = $this->createMock(IShare::class);
+ $share->method('canSeeContent')
+ ->willReturn(true);
+
+ $storage = $this->createMock(ISharedStorage::class);
+ $storage->method('instanceOfStorage')
+ ->with(ISharedStorage::class)
+ ->willReturn(true);
+ $storage->method('getShare')
+ ->willReturn($share);
+
+ $file->method('getStorage')
+ ->willReturn($storage);
+ $file->method('isReadable')
+ ->willReturn(true);
+
+ $this->request
+ ->method('getHeader')
+ ->willReturn('');
+
+ $preview = $this->createMock(ISimpleFile::class);
+ $preview->method('getName')->willReturn('my name');
+ $preview->method('getMTime')->willReturn(42);
+ $this->previewManager->method('getPreview')
+ ->with($this->equalTo($file), 10, 10, false, $this->equalTo('myMode'))
+ ->willReturn($preview);
+ $preview->method('getMimeType')
+ ->willReturn('myMime');
+
+ $res = $this->controller->getPreview('file', 10, 10, true, true, 'myMode');
+
+ $this->assertEquals('myMime', $res->getHeaders()['Content-Type']);
+ $this->assertEquals(Http::STATUS_OK, $res->getStatus());
+ $this->assertEquals($preview, $this->invokePrivate($res, 'file'));
+ }
}
diff --git a/tests/Core/Controller/ProfilePageControllerTest.php b/tests/Core/Controller/ProfilePageControllerTest.php
deleted file mode 100644
index 361f93ff409..00000000000
--- a/tests/Core/Controller/ProfilePageControllerTest.php
+++ /dev/null
@@ -1,78 +0,0 @@
-<?php
-
-declare(strict_types=1);
-
-/**
- * SPDX-FileCopyrightText: 2024 Nextcloud GmbH and Nextcloud contributors
- * SPDX-License-Identifier: AGPL-3.0-or-later
- */
-
-namespace Core\Controller;
-
-use OC\Core\Controller\ProfilePageController;
-use OC\Profile\ProfileManager;
-use OC\UserStatus\Manager;
-use OCP\AppFramework\Services\IInitialState;
-use OCP\EventDispatcher\IEventDispatcher;
-use OCP\INavigationManager;
-use OCP\IRequest;
-use OCP\IUser;
-use OCP\IUserManager;
-use OCP\IUserSession;
-use OCP\Share\IManager;
-use Test\TestCase;
-
-class ProfilePageControllerTest extends TestCase {
-
- private IUserManager $userManager;
- private ProfilePageController $controller;
-
- protected function setUp(): void {
- parent::setUp();
-
- $request = $this->createMock(IRequest::class);
- $initialStateService = $this->createMock(IInitialState::class);
- $profileManager = $this->createMock(ProfileManager::class);
- $shareManager = $this->createMock(IManager::class);
- $this->userManager = $this->createMock(IUserManager::class);
- $userSession = $this->createMock(IUserSession::class);
- $userStatusManager = $this->createMock(Manager::class);
- $navigationManager = $this->createMock(INavigationManager::class);
- $eventDispatcher = $this->createMock(IEventDispatcher::class);
-
- $this->controller = new ProfilePageController(
- 'core',
- $request,
- $initialStateService,
- $profileManager,
- $shareManager,
- $this->userManager,
- $userSession,
- $userStatusManager,
- $navigationManager,
- $eventDispatcher,
- );
- }
-
- public function testUserNotFound(): void {
- $this->userManager->method('get')
- ->willReturn(null);
-
- $response = $this->controller->index('bob');
-
- $this->assertTrue($response->isThrottled());
- }
-
- public function testUserDisabled(): void {
- $user = $this->createMock(IUser::class);
- $user->method('isEnabled')
- ->willReturn(false);
-
- $this->userManager->method('get')
- ->willReturn($user);
-
- $response = $this->controller->index('bob');
-
- $this->assertFalse($response->isThrottled());
- }
-}
diff --git a/tests/Core/Controller/TwoFactorChallengeControllerTest.php b/tests/Core/Controller/TwoFactorChallengeControllerTest.php
index f003975b359..d9ea1ca263f 100644
--- a/tests/Core/Controller/TwoFactorChallengeControllerTest.php
+++ b/tests/Core/Controller/TwoFactorChallengeControllerTest.php
@@ -22,7 +22,7 @@ use OCP\ISession;
use OCP\IURLGenerator;
use OCP\IUser;
use OCP\IUserSession;
-use OCP\Template;
+use OCP\Template\ITemplate;
use Psr\Log\LoggerInterface;
use Test\TestCase;
@@ -68,14 +68,14 @@ class TwoFactorChallengeControllerTest extends TestCase {
$this->urlGenerator,
$this->logger,
])
- ->setMethods(['getLogoutUrl'])
+ ->onlyMethods(['getLogoutUrl'])
->getMock();
$this->controller->expects($this->any())
->method('getLogoutUrl')
->willReturn('logoutAttribute');
}
- public function testSelectChallenge() {
+ public function testSelectChallenge(): void {
$user = $this->getMockBuilder(IUser::class)->getMock();
$p1 = $this->createMock(IActivatableAtLogin::class);
$p1->method('getId')->willReturn('p1');
@@ -109,13 +109,13 @@ class TwoFactorChallengeControllerTest extends TestCase {
$this->assertEquals($expected, $this->controller->selectChallenge('/some/url'));
}
- public function testShowChallenge() {
+ public function testShowChallenge(): void {
$user = $this->createMock(IUser::class);
$provider = $this->createMock(IProvider::class);
$provider->method('getId')->willReturn('myprovider');
$backupProvider = $this->createMock(IProvider::class);
$backupProvider->method('getId')->willReturn('backup_codes');
- $tmpl = $this->createMock(Template::class);
+ $tmpl = $this->createMock(ITemplate::class);
$providerSet = new ProviderSet([$provider, $backupProvider], true);
$this->userSession->expects($this->once())
@@ -160,7 +160,7 @@ class TwoFactorChallengeControllerTest extends TestCase {
$this->assertEquals($expected, $this->controller->showChallenge('myprovider', '/re/dir/ect/url'));
}
- public function testShowInvalidChallenge() {
+ public function testShowInvalidChallenge(): void {
$user = $this->createMock(IUser::class);
$providerSet = new ProviderSet([], false);
@@ -181,7 +181,7 @@ class TwoFactorChallengeControllerTest extends TestCase {
$this->assertEquals($expected, $this->controller->showChallenge('myprovider', 'redirect/url'));
}
- public function testSolveChallenge() {
+ public function testSolveChallenge(): void {
$user = $this->createMock(IUser::class);
$provider = $this->createMock(IProvider::class);
@@ -206,7 +206,7 @@ class TwoFactorChallengeControllerTest extends TestCase {
$this->assertEquals($expected, $this->controller->solveChallenge('myprovider', 'token'));
}
- public function testSolveValidChallengeAndRedirect() {
+ public function testSolveValidChallengeAndRedirect(): void {
$user = $this->createMock(IUser::class);
$provider = $this->createMock(IProvider::class);
@@ -231,7 +231,7 @@ class TwoFactorChallengeControllerTest extends TestCase {
$this->assertEquals($expected, $this->controller->solveChallenge('myprovider', 'token', 'redirect%20url'));
}
- public function testSolveChallengeInvalidProvider() {
+ public function testSolveChallengeInvalidProvider(): void {
$user = $this->getMockBuilder(IUser::class)->getMock();
$this->userSession->expects($this->once())
@@ -251,7 +251,7 @@ class TwoFactorChallengeControllerTest extends TestCase {
$this->assertEquals($expected, $this->controller->solveChallenge('myprovider', 'token'));
}
- public function testSolveInvalidChallenge() {
+ public function testSolveInvalidChallenge(): void {
$user = $this->createMock(IUser::class);
$provider = $this->createMock(IProvider::class);
@@ -285,10 +285,10 @@ class TwoFactorChallengeControllerTest extends TestCase {
$this->assertEquals($expected, $this->controller->solveChallenge('myprovider', 'token', '/url'));
}
- public function testSolveChallengeTwoFactorException() {
+ public function testSolveChallengeTwoFactorException(): void {
$user = $this->createMock(IUser::class);
$provider = $this->createMock(IProvider::class);
- $exception = new TwoFactorException("2FA failed");
+ $exception = new TwoFactorException('2FA failed');
$this->userSession->expects($this->once())
->method('getUser')
@@ -301,13 +301,17 @@ class TwoFactorChallengeControllerTest extends TestCase {
$this->twoFactorManager->expects($this->once())
->method('verifyChallenge')
->with('myprovider', $user, 'token')
- ->will($this->throwException($exception));
+ ->willThrowException($exception);
+ $calls = [
+ ['two_factor_auth_error_message', '2FA failed'],
+ ['two_factor_auth_error', true],
+ ];
$this->session->expects($this->exactly(2))
->method('set')
- ->withConsecutive(
- ['two_factor_auth_error_message', '2FA failed'],
- ['two_factor_auth_error', true]
- );
+ ->willReturnCallback(function () use (&$calls): void {
+ $expected = array_shift($calls);
+ $this->assertEquals($expected, func_get_args());
+ });
$this->urlGenerator->expects($this->once())
->method('linkToRoute')
->with('core.TwoFactorChallenge.showChallenge', [
@@ -353,7 +357,7 @@ class TwoFactorChallengeControllerTest extends TestCase {
$this->assertEquals($expected, $response);
}
- public function testSetUpInvalidProvider() {
+ public function testSetUpInvalidProvider(): void {
$user = $this->createMock(IUser::class);
$this->userSession->expects($this->once())
->method('getUser')
@@ -399,7 +403,7 @@ class TwoFactorChallengeControllerTest extends TestCase {
->method('getLoginSetup')
->with($user)
->willReturn($loginSetup);
- $tmpl = $this->createMock(Template::class);
+ $tmpl = $this->createMock(ITemplate::class);
$loginSetup->expects($this->once())
->method('getBody')
->willReturn($tmpl);
diff --git a/tests/Core/Controller/UserControllerTest.php b/tests/Core/Controller/UserControllerTest.php
index 09a22913fdc..2473f280580 100644
--- a/tests/Core/Controller/UserControllerTest.php
+++ b/tests/Core/Controller/UserControllerTest.php
@@ -1,4 +1,5 @@
<?php
+
/**
* SPDX-FileCopyrightText: 2016 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
@@ -31,7 +32,7 @@ class UserControllerTest extends TestCase {
);
}
- public function testGetDisplayNames() {
+ public function testGetDisplayNames(): void {
$user = $this->createMock(IUser::class);
$user->method('getDisplayName')
->willReturn('FooDisplay Name');
diff --git a/tests/Core/Controller/WellKnownControllerTest.php b/tests/Core/Controller/WellKnownControllerTest.php
index 99c693c78b7..35606dc6384 100644
--- a/tests/Core/Controller/WellKnownControllerTest.php
+++ b/tests/Core/Controller/WellKnownControllerTest.php
@@ -40,7 +40,7 @@ class WellKnownControllerTest extends TestCase {
}
public function testHandleNotProcessed(): void {
- $httpResponse = $this->controller->handle("nodeinfo");
+ $httpResponse = $this->controller->handle('nodeinfo');
self::assertInstanceOf(JSONResponse::class, $httpResponse);
self::assertArrayHasKey('X-NEXTCLOUD-WELL-KNOWN', $httpResponse->getHeaders());
@@ -55,14 +55,14 @@ class WellKnownControllerTest extends TestCase {
$this->manager->expects(self::once())
->method('process')
->with(
- "nodeinfo",
+ 'nodeinfo',
$this->request
)->willReturn($response);
$jsonResponse->expects(self::once())
->method('addHeader')
->willReturnSelf();
- $httpResponse = $this->controller->handle("nodeinfo");
+ $httpResponse = $this->controller->handle('nodeinfo');
self::assertInstanceOf(JSONResponse::class, $httpResponse);
}
diff --git a/tests/Core/Controller/WipeControllerTest.php b/tests/Core/Controller/WipeControllerTest.php
index f07fe4c9282..5330eb599e6 100644
--- a/tests/Core/Controller/WipeControllerTest.php
+++ b/tests/Core/Controller/WipeControllerTest.php
@@ -33,7 +33,7 @@ class WipeControllerTest extends TestCase {
$this->remoteWipe);
}
- public function dataTest() {
+ public static function dataTest(): array {
return [
// valid token, could perform operation, valid result
[ true, true, true],
@@ -47,10 +47,9 @@ class WipeControllerTest extends TestCase {
* @param bool $valid
* @param bool $couldPerform
* @param bool $result
- *
- * @dataProvider dataTest
*/
- public function testCheckWipe(bool $valid, bool $couldPerform, bool $result) {
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataTest')]
+ public function testCheckWipe(bool $valid, bool $couldPerform, bool $result): void {
if (!$valid) {
$this->remoteWipe->method('start')
->with('mytoken')
@@ -76,10 +75,9 @@ class WipeControllerTest extends TestCase {
* @param bool $valid
* @param bool $couldPerform
* @param bool $result
- *
- * @dataProvider dataTest
*/
- public function testWipeDone(bool $valid, bool $couldPerform, bool $result) {
+ #[\PHPUnit\Framework\Attributes\DataProvider('dataTest')]
+ public function testWipeDone(bool $valid, bool $couldPerform, bool $result): void {
if (!$valid) {
$this->remoteWipe->method('finish')
->with('mytoken')