summaryrefslogtreecommitdiffstats
path: root/tests
diff options
context:
space:
mode:
Diffstat (limited to 'tests')
-rw-r--r--tests/Core/Command/Apps/AppsDisableTest.php18
-rw-r--r--tests/Core/Command/Apps/AppsEnableTest.php26
-rw-r--r--tests/Core/Controller/LostControllerTest.php304
-rw-r--r--tests/Core/Controller/SvgControllerTest.php2
-rw-r--r--tests/Core/Controller/TwoFactorChallengeControllerTest.php5
-rw-r--r--tests/Core/Middleware/TwoFactorMiddlewareTest.php27
-rw-r--r--tests/acceptance/features/bootstrap/AppSettingsContext.php4
-rw-r--r--tests/acceptance/features/bootstrap/FilesAppContext.php2
-rw-r--r--tests/lib/Accounts/AccountManagerTest.php36
-rw-r--r--tests/lib/AllConfigTest.php22
-rw-r--r--tests/lib/AppFramework/Middleware/Security/SecurityMiddlewareTest.php12
-rw-r--r--tests/lib/Contacts/ContactsMenu/EntryTest.php4
-rw-r--r--tests/lib/Files/Node/FolderTest.php98
-rw-r--r--tests/lib/Files/ObjectStore/ObjectStoreTest.php19
-rw-r--r--tests/lib/Files/ObjectStore/S3Test.php86
-rw-r--r--tests/lib/Security/CredentialsManagerTest.php81
-rw-r--r--tests/lib/Security/RateLimiting/Backend/MemoryCacheBackendTest.php (renamed from tests/lib/Security/RateLimiting/Backend/MemoryCacheTest.php)26
-rw-r--r--tests/lib/Security/RateLimiting/LimiterTest.php29
-rw-r--r--tests/lib/Security/VerificationToken/VerificationTokenTest.php309
-rw-r--r--tests/lib/Settings/ManagerTest.php31
-rw-r--r--tests/lib/UrlGeneratorTest.php6
-rw-r--r--tests/lib/User/UserTest.php5
22 files changed, 643 insertions, 509 deletions
diff --git a/tests/Core/Command/Apps/AppsDisableTest.php b/tests/Core/Command/Apps/AppsDisableTest.php
index 79dd9c59bbf..493dfc16f3e 100644
--- a/tests/Core/Command/Apps/AppsDisableTest.php
+++ b/tests/Core/Command/Apps/AppsDisableTest.php
@@ -55,31 +55,31 @@ class AppsDisableTest extends TestCase {
* @param $appId
* @param $groups
* @param $statusCode
- * @param $output
+ * @param $pattern
*/
- public function testCommandInput($appId, $statusCode, $output): void {
+ public function testCommandInput($appId, $statusCode, $pattern): void {
$input = ['app-id' => $appId];
$this->commandTester->execute($input);
- $this->assertStringContainsString($output, $this->commandTester->getDisplay());
+ $this->assertRegExp('/' . $pattern . '/', $this->commandTester->getDisplay());
$this->assertSame($statusCode, $this->commandTester->getStatusCode());
}
public function dataCommandInput(): array {
return [
- [['admin_audit'], 0, 'admin_audit 1.12.0 disabled'],
- [['comments'], 0, 'comments 1.12.0 disabled'],
+ [['admin_audit'], 0, 'admin_audit ([\d\.]*) disabled'],
+ [['comments'], 0, 'comments ([\d\.]*) disabled'],
[['invalid_app'], 0, 'No such app enabled: invalid_app'],
- [['admin_audit', 'comments'], 0, "admin_audit 1.12.0 disabled\ncomments 1.12.0 disabled"],
- [['admin_audit', 'comments', 'invalid_app'], 0, "admin_audit 1.12.0 disabled\ncomments 1.12.0 disabled\nNo such app enabled: invalid_app"],
+ [['admin_audit', 'comments'], 0, "admin_audit ([\d\.]*) disabled\ncomments ([\d\.]*) disabled"],
+ [['admin_audit', 'comments', 'invalid_app'], 0, "admin_audit ([\d\.]*) disabled\ncomments ([\d\.]*) disabled\nNo such app enabled: invalid_app"],
[['files'], 2, "files can't be disabled"],
[['provisioning_api'], 2, "provisioning_api can't be disabled"],
- [['files', 'admin_audit'], 2, "files can't be disabled.\nadmin_audit 1.12.0 disabled"],
- [['provisioning_api', 'comments'], 2, "provisioning_api can't be disabled.\ncomments 1.12.0 disabled"],
+ [['files', 'admin_audit'], 2, "files can't be disabled.\nadmin_audit ([\d\.]*) disabled"],
+ [['provisioning_api', 'comments'], 2, "provisioning_api can't be disabled.\ncomments ([\d\.]*) disabled"],
];
}
}
diff --git a/tests/Core/Command/Apps/AppsEnableTest.php b/tests/Core/Command/Apps/AppsEnableTest.php
index 0924edffc35..73a7d3f449f 100644
--- a/tests/Core/Command/Apps/AppsEnableTest.php
+++ b/tests/Core/Command/Apps/AppsEnableTest.php
@@ -56,9 +56,9 @@ class AppsEnableTest extends TestCase {
* @param $appId
* @param $groups
* @param $statusCode
- * @param $output
+ * @param $pattern
*/
- public function testCommandInput($appId, $groups, $statusCode, $output): void {
+ public function testCommandInput($appId, $groups, $statusCode, $pattern): void {
$input = ['app-id' => $appId];
if (is_array($groups)) {
@@ -67,29 +67,29 @@ class AppsEnableTest extends TestCase {
$this->commandTester->execute($input);
- $this->assertStringContainsString($output, $this->commandTester->getDisplay());
+ $this->assertRegExp('/' . $pattern . '/', $this->commandTester->getDisplay());
$this->assertSame($statusCode, $this->commandTester->getStatusCode());
}
public function dataCommandInput(): array {
return [
- [['admin_audit'], null, 0, 'admin_audit 1.12.0 enabled'],
- [['comments'], null, 0, 'comments 1.12.0 enabled'],
- [['comments', 'comments'], null, 0, "comments 1.12.0 enabled\ncomments already enabled"],
+ [['admin_audit'], null, 0, 'admin_audit ([\d\.]*) enabled'],
+ [['comments'], null, 0, 'comments ([\d\.]*) enabled'],
+ [['comments', 'comments'], null, 0, "comments ([\d\.]*) enabled\ncomments already enabled"],
[['invalid_app'], null, 1, 'Could not download app invalid_app'],
- [['admin_audit', 'comments'], null, 0, "admin_audit 1.12.0 enabled\ncomments 1.12.0 enabled"],
- [['admin_audit', 'comments', 'invalid_app'], null, 1, "admin_audit 1.12.0 enabled\ncomments 1.12.0 enabled\nCould not download app invalid_app"],
+ [['admin_audit', 'comments'], null, 0, "admin_audit ([\d\.]*) enabled\ncomments ([\d\.]*) enabled"],
+ [['admin_audit', 'comments', 'invalid_app'], null, 1, "admin_audit ([\d\.]*) enabled\ncomments ([\d\.]*) enabled\nCould not download app invalid_app"],
[['admin_audit'], ['admin'], 1, "admin_audit can't be enabled for groups"],
[['comments'], ['admin'], 1, "comments can't be enabled for groups"],
- [['updatenotification'], ['admin'], 0, 'updatenotification 1.12.0 enabled for groups: admin'],
- [['updatenotification', 'accessibility'], ['admin'], 0, "updatenotification 1.12.0 enabled for groups: admin\naccessibility 1.8.0 enabled for groups: admin"],
+ [['updatenotification'], ['admin'], 0, 'updatenotification ([\d\.]*) enabled for groups: admin'],
+ [['updatenotification', 'accessibility'], ['admin'], 0, "updatenotification ([\d\.]*) enabled for groups: admin\naccessibility ([\d\.]*) enabled for groups: admin"],
- [['updatenotification'], ['admin', 'invalid_group'], 0, 'updatenotification 1.12.0 enabled for groups: admin'],
- [['updatenotification', 'accessibility'], ['admin', 'invalid_group'], 0, "updatenotification 1.12.0 enabled for groups: admin\naccessibility 1.8.0 enabled for groups: admin"],
- [['updatenotification', 'accessibility', 'invalid_app'], ['admin', 'invalid_group'], 1, "updatenotification 1.12.0 enabled for groups: admin\naccessibility 1.8.0 enabled for groups: admin\nCould not download app invalid_app"],
+ [['updatenotification'], ['admin', 'invalid_group'], 0, 'updatenotification ([\d\.]*) enabled for groups: admin'],
+ [['updatenotification', 'accessibility'], ['admin', 'invalid_group'], 0, "updatenotification ([\d\.]*) enabled for groups: admin\naccessibility ([\d\.]*) enabled for groups: admin"],
+ [['updatenotification', 'accessibility', 'invalid_app'], ['admin', 'invalid_group'], 1, "updatenotification ([\d\.]*) enabled for groups: admin\naccessibility ([\d\.]*) enabled for groups: admin\nCould not download app invalid_app"],
];
}
}
diff --git a/tests/Core/Controller/LostControllerTest.php b/tests/Core/Controller/LostControllerTest.php
index fd4e27d47f1..e860c808014 100644
--- a/tests/Core/Controller/LostControllerTest.php
+++ b/tests/Core/Controller/LostControllerTest.php
@@ -26,7 +26,6 @@ use OC\Core\Controller\LostController;
use OC\Mail\Message;
use OCP\AppFramework\Http\JSONResponse;
use OCP\AppFramework\Http\TemplateResponse;
-use OCP\AppFramework\Utility\ITimeFactory;
use OCP\Defaults;
use OCP\Encryption\IEncryptionModule;
use OCP\Encryption\IManager;
@@ -40,8 +39,8 @@ use OCP\IUser;
use OCP\IUserManager;
use OCP\Mail\IEMailTemplate;
use OCP\Mail\IMailer;
-use OCP\Security\ICrypto;
-use OCP\Security\ISecureRandom;
+use OCP\Security\VerificationToken\InvalidTokenException;
+use OCP\Security\VerificationToken\IVerificationToken;
/**
* Class LostControllerTest
@@ -66,22 +65,18 @@ class LostControllerTest extends \Test\TestCase {
private $config;
/** @var IMailer | \PHPUnit\Framework\MockObject\MockObject */
private $mailer;
- /** @var ISecureRandom | \PHPUnit\Framework\MockObject\MockObject */
- private $secureRandom;
/** @var IManager|\PHPUnit\Framework\MockObject\MockObject */
private $encryptionManager;
- /** @var ITimeFactory | \PHPUnit\Framework\MockObject\MockObject */
- private $timeFactory;
/** @var IRequest|\PHPUnit\Framework\MockObject\MockObject */
private $request;
- /** @var ICrypto|\PHPUnit\Framework\MockObject\MockObject */
- private $crypto;
/** @var ILogger|\PHPUnit\Framework\MockObject\MockObject */
private $logger;
/** @var Manager|\PHPUnit\Framework\MockObject\MockObject */
private $twofactorManager;
/** @var IInitialStateService|\PHPUnit\Framework\MockObject\MockObject */
private $initialStateService;
+ /** @var IVerificationToken|\PHPUnit\Framework\MockObject\MockObject */
+ private $verificationToken;
protected function setUp(): void {
parent::setUp();
@@ -123,10 +118,6 @@ class LostControllerTest extends \Test\TestCase {
->disableOriginalConstructor()->getMock();
$this->mailer = $this->getMockBuilder('\OCP\Mail\IMailer')
->disableOriginalConstructor()->getMock();
- $this->secureRandom = $this->getMockBuilder('\OCP\Security\ISecureRandom')
- ->disableOriginalConstructor()->getMock();
- $this->timeFactory = $this->getMockBuilder('\OCP\AppFramework\Utility\ITimeFactory')
- ->disableOriginalConstructor()->getMock();
$this->request = $this->getMockBuilder(IRequest::class)
->disableOriginalConstructor()->getMock();
$this->encryptionManager = $this->getMockBuilder(IManager::class)
@@ -134,10 +125,10 @@ class LostControllerTest extends \Test\TestCase {
$this->encryptionManager->expects($this->any())
->method('isEnabled')
->willReturn(true);
- $this->crypto = $this->createMock(ICrypto::class);
$this->logger = $this->createMock(ILogger::class);
$this->twofactorManager = $this->createMock(Manager::class);
$this->initialStateService = $this->createMock(IInitialStateService::class);
+ $this->verificationToken = $this->createMock(IVerificationToken::class);
$this->lostController = new LostController(
'Core',
$this->request,
@@ -146,89 +137,31 @@ class LostControllerTest extends \Test\TestCase {
$this->defaults,
$this->l10n,
$this->config,
- $this->secureRandom,
'lostpassword-noreply@localhost',
$this->encryptionManager,
$this->mailer,
- $this->timeFactory,
- $this->crypto,
$this->logger,
$this->twofactorManager,
- $this->initialStateService
- );
- }
-
- public function testResetFormWithNotExistingUser() {
- $this->userManager->method('get')
- ->with('NotExistingUser')
- ->willReturn(null);
-
- $expectedResponse = new TemplateResponse(
- 'core',
- 'error',
- [
- 'errors' => [
- ['error' => 'Couldn\'t reset password because the token is invalid'],
- ]
- ],
- 'guest'
+ $this->initialStateService,
+ $this->verificationToken
);
- $this->assertEquals($expectedResponse, $this->lostController->resetform('MySecretToken', 'NotExistingUser'));
}
- public function testResetFormInvalidTokenMatch() {
- $this->config->method('getUserValue')
- ->with('ValidTokenUser', 'core', 'lostpassword', null)
- ->willReturn('encryptedToken');
- $this->existingUser->method('getLastLogin')
- ->willReturn(12344);
+ public function testResetFormTokenError() {
$this->userManager->method('get')
->with('ValidTokenUser')
->willReturn($this->existingUser);
- $this->crypto->method('decrypt')
- ->with(
- $this->equalTo('encryptedToken'),
- $this->equalTo('test@example.comSECRET')
- )->willReturn('12345:TheOnlyAndOnlyOneTokenToResetThePassword');
+ $this->verificationToken->expects($this->once())
+ ->method('check')
+ ->with('12345:MySecretToken', $this->existingUser, 'lostpassword', 'test@example.com')
+ ->willThrowException(new InvalidTokenException(InvalidTokenException::TOKEN_DECRYPTION_ERROR));
$response = $this->lostController->resetform('12345:MySecretToken', 'ValidTokenUser');
$expectedResponse = new TemplateResponse('core',
'error',
[
'errors' => [
- ['error' => 'Couldn\'t reset password because the token is invalid'],
- ]
- ],
- 'guest');
- $this->assertEquals($expectedResponse, $response);
- }
-
-
- public function testResetFormExpiredToken() {
- $this->userManager->method('get')
- ->with('ValidTokenUser')
- ->willReturn($this->existingUser);
- $this->config
- ->expects($this->once())
- ->method('getUserValue')
- ->with('ValidTokenUser', 'core', 'lostpassword', null)
- ->willReturn('encryptedToken');
- $this->crypto->method('decrypt')
- ->with(
- $this->equalTo('encryptedToken'),
- $this->equalTo('test@example.comSECRET')
- )->willReturn('12345:TheOnlyAndOnlyOneTokenToResetThePassword');
- $this->timeFactory
- ->expects($this->once())
- ->method('getTime')
- ->willReturn(999999);
-
- $response = $this->lostController->resetform('TheOnlyAndOnlyOneTokenToResetThePassword', 'ValidTokenUser');
- $expectedResponse = new TemplateResponse('core',
- 'error',
- [
- 'errors' => [
- ['error' => 'Couldn\'t reset password because the token is expired'],
+ ['error' => 'Could not reset password because the token is invalid'],
]
],
'guest');
@@ -236,39 +169,14 @@ class LostControllerTest extends \Test\TestCase {
}
public function testResetFormValidToken() {
- $this->existingUser->method('getLastLogin')
- ->willReturn(12344);
$this->userManager->method('get')
->with('ValidTokenUser')
->willReturn($this->existingUser);
- $this->timeFactory
- ->expects($this->once())
- ->method('getTime')
- ->willReturn(12348);
+ $this->verificationToken->expects($this->once())
+ ->method('check')
+ ->with('MySecretToken', $this->existingUser, 'lostpassword', 'test@example.com');
- $this->config->method('getUserValue')
- ->with('ValidTokenUser', 'core', 'lostpassword', null)
- ->willReturn('encryptedToken');
-
- $this->crypto->method('decrypt')
- ->with(
- $this->equalTo('encryptedToken'),
- $this->equalTo('test@example.comSECRET')
- )->willReturn('12345:TheOnlyAndOnlyOneTokenToResetThePassword');
- $this->urlGenerator
- ->expects($this->once())
- ->method('linkToRouteAbsolute')
- ->with('core.lost.setPassword', ['userId' => 'ValidTokenUser', 'token' => 'TheOnlyAndOnlyOneTokenToResetThePassword'])
- ->willReturn('https://example.tld/index.php/lostpassword/');
-
- $this->initialStateService->expects($this->at(0))
- ->method('provideInitialState')
- ->with('core', 'resetPasswordUser', 'ValidTokenUser');
- $this->initialStateService->expects($this->at(1))
- ->method('provideInitialState')
- ->with('core', 'resetPasswordTarget', 'https://example.tld/index.php/lostpassword/');
-
- $response = $this->lostController->resetform('TheOnlyAndOnlyOneTokenToResetThePassword', 'ValidTokenUser');
+ $response = $this->lostController->resetform('MySecretToken', 'ValidTokenUser');
$expectedResponse = new TemplateResponse('core',
'login',
[],
@@ -319,24 +227,14 @@ class LostControllerTest extends \Test\TestCase {
}
public function testEmailSuccessful() {
- $this->secureRandom
- ->expects($this->once())
- ->method('generate')
- ->with('21')
- ->willReturn('ThisIsMaybeANotSoSecretToken!');
$this->userManager
->expects($this->any())
->method('get')
->with('ExistingUser')
->willReturn($this->existingUser);
- $this->timeFactory
- ->expects($this->once())
- ->method('getTime')
- ->willReturn(12348);
- $this->config
- ->expects($this->once())
- ->method('setUserValue')
- ->with('ExistingUser', 'core', 'lostpassword', 'encryptedToken');
+ $this->verificationToken->expects($this->once())
+ ->method('create')
+ ->willReturn('ThisIsMaybeANotSoSecretToken!');
$this->urlGenerator
->expects($this->once())
->method('linkToRouteAbsolute')
@@ -379,12 +277,6 @@ class LostControllerTest extends \Test\TestCase {
->method('send')
->with($message);
- $this->crypto->method('encrypt')
- ->with(
- $this->equalTo('12348:ThisIsMaybeANotSoSecretToken!'),
- $this->equalTo('test@example.comSECRET')
- )->willReturn('encryptedToken');
-
$response = $this->lostController->email('ExistingUser');
$expectedResponse = new JSONResponse(['status' => 'success']);
$expectedResponse->throttle();
@@ -392,11 +284,6 @@ class LostControllerTest extends \Test\TestCase {
}
public function testEmailWithMailSuccessful() {
- $this->secureRandom
- ->expects($this->once())
- ->method('generate')
- ->with('21')
- ->willReturn('ThisIsMaybeANotSoSecretToken!');
$this->userManager
->expects($this->any())
->method('get')
@@ -407,14 +294,9 @@ class LostControllerTest extends \Test\TestCase {
->method('getByEmail')
->with('test@example.com')
->willReturn([$this->existingUser]);
- $this->timeFactory
- ->expects($this->once())
- ->method('getTime')
- ->willReturn(12348);
- $this->config
- ->expects($this->once())
- ->method('setUserValue')
- ->with('ExistingUser', 'core', 'lostpassword', 'encryptedToken');
+ $this->verificationToken->expects($this->once())
+ ->method('create')
+ ->willReturn('ThisIsMaybeANotSoSecretToken!');
$this->urlGenerator
->expects($this->once())
->method('linkToRouteAbsolute')
@@ -457,12 +339,6 @@ class LostControllerTest extends \Test\TestCase {
->method('send')
->with($message);
- $this->crypto->method('encrypt')
- ->with(
- $this->equalTo('12348:ThisIsMaybeANotSoSecretToken!'),
- $this->equalTo('test@example.comSECRET')
- )->willReturn('encryptedToken');
-
$response = $this->lostController->email('test@example.com');
$expectedResponse = new JSONResponse(['status' => 'success']);
$expectedResponse->throttle();
@@ -470,24 +346,14 @@ class LostControllerTest extends \Test\TestCase {
}
public function testEmailCantSendException() {
- $this->secureRandom
- ->expects($this->once())
- ->method('generate')
- ->with('21')
- ->willReturn('ThisIsMaybeANotSoSecretToken!');
$this->userManager
->expects($this->any())
->method('get')
->with('ExistingUser')
->willReturn($this->existingUser);
- $this->config
- ->expects($this->once())
- ->method('setUserValue')
- ->with('ExistingUser', 'core', 'lostpassword', 'encryptedToken');
- $this->timeFactory
- ->expects($this->once())
- ->method('getTime')
- ->willReturn(12348);
+ $this->verificationToken->expects($this->once())
+ ->method('create')
+ ->willReturn('ThisIsMaybeANotSoSecretToken!');
$this->urlGenerator
->expects($this->once())
->method('linkToRouteAbsolute')
@@ -530,12 +396,6 @@ class LostControllerTest extends \Test\TestCase {
->with($message)
->will($this->throwException(new \Exception()));
- $this->crypto->method('encrypt')
- ->with(
- $this->equalTo('12348:ThisIsMaybeANotSoSecretToken!'),
- $this->equalTo('test@example.comSECRET')
- )->willReturn('encryptedToken');
-
$this->logger->expects($this->exactly(1))
->method('logException');
@@ -560,14 +420,6 @@ class LostControllerTest extends \Test\TestCase {
->willReturn($this->existingUser);
$this->config->expects($this->never())
->method('deleteUserValue');
- $this->timeFactory->method('getTime')
- ->willReturn(12348);
-
- $this->crypto->method('decrypt')
- ->with(
- $this->equalTo('encryptedData'),
- $this->equalTo('test@example.comSECRET')
- )->willReturn('12345:TheOnlyAndOnlyOneTokenToResetThePassword');
$response = $this->lostController->setPassword('TheOnlyAndOnlyOneTokenToResetThePassword', 'ValidTokenUser', 'NewPassword', true);
$expectedResponse = ['status' => 'error', 'msg' => ''];
@@ -590,14 +442,6 @@ class LostControllerTest extends \Test\TestCase {
$this->config->expects($this->once())
->method('deleteUserValue')
->with('ValidTokenUser', 'core', 'lostpassword');
- $this->timeFactory->method('getTime')
- ->willReturn(12348);
-
- $this->crypto->method('decrypt')
- ->with(
- $this->equalTo('encryptedData'),
- $this->equalTo('test@example.comSECRET')
- )->willReturn('12345:TheOnlyAndOnlyOneTokenToResetThePassword');
$response = $this->lostController->setPassword('TheOnlyAndOnlyOneTokenToResetThePassword', 'ValidTokenUser', 'NewPassword', true);
$expectedResponse = ['user' => 'ValidTokenUser', 'status' => 'success'];
@@ -611,19 +455,14 @@ class LostControllerTest extends \Test\TestCase {
$this->userManager->method('get')
->with('ValidTokenUser')
->willReturn($this->existingUser);
- $this->timeFactory->method('getTime')
- ->willReturn(617146);
-
- $this->crypto->method('decrypt')
- ->with(
- $this->equalTo('encryptedData'),
- $this->equalTo('test@example.comSECRET')
- )->willReturn('12345:TheOnlyAndOnlyOneTokenToResetThePassword');
+ $this->verificationToken->expects($this->atLeastOnce())
+ ->method('check')
+ ->willThrowException(new InvalidTokenException(InvalidTokenException::TOKEN_EXPIRED));
$response = $this->lostController->setPassword('TheOnlyAndOnlyOneTokenToResetThePassword', 'ValidTokenUser', 'NewPassword', true);
$expectedResponse = [
'status' => 'error',
- 'msg' => 'Couldn\'t reset password because the token is expired',
+ 'msg' => 'Could not reset password because the token is expired',
];
$this->assertSame($expectedResponse, $response);
}
@@ -636,45 +475,14 @@ class LostControllerTest extends \Test\TestCase {
->method('get')
->with('ValidTokenUser')
->willReturn($this->existingUser);
-
- $this->crypto->method('decrypt')
- ->with(
- $this->equalTo('invalidEncryptedData'),
- $this->equalTo('test@example.comSECRET')
- )->willReturn('TheOnlyAndOnlyOneTokenToResetThePassword');
-
- $response = $this->lostController->setPassword('TheOnlyAndOnlyOneTokenToResetThePassword', 'ValidTokenUser', 'NewPassword', true);
- $expectedResponse = [
- 'status' => 'error',
- 'msg' => 'Couldn\'t reset password because the token is invalid',
- ];
- $this->assertSame($expectedResponse, $response);
- }
-
- public function testSetPasswordExpiredTokenDueToLogin() {
- $this->config->method('getUserValue')
- ->with('ValidTokenUser', 'core', 'lostpassword', null)
- ->willReturn('encryptedData');
- $this->existingUser->method('getLastLogin')
- ->willReturn(12346);
- $this->userManager
- ->method('get')
- ->with('ValidTokenUser')
- ->willReturn($this->existingUser);
- $this->timeFactory
- ->method('getTime')
- ->willReturn(12345);
-
- $this->crypto->method('decrypt')
- ->with(
- $this->equalTo('encryptedData'),
- $this->equalTo('test@example.comSECRET')
- )->willReturn('12345:TheOnlyAndOnlyOneTokenToResetThePassword');
+ $this->verificationToken->expects($this->atLeastOnce())
+ ->method('check')
+ ->willThrowException(new InvalidTokenException(InvalidTokenException::TOKEN_INVALID_FORMAT));
$response = $this->lostController->setPassword('TheOnlyAndOnlyOneTokenToResetThePassword', 'ValidTokenUser', 'NewPassword', true);
$expectedResponse = [
'status' => 'error',
- 'msg' => 'Couldn\'t reset password because the token is expired',
+ 'msg' => 'Could not reset password because the token is invalid',
];
$this->assertSame($expectedResponse, $response);
}
@@ -686,33 +494,14 @@ class LostControllerTest extends \Test\TestCase {
$this->userManager->method('get')
->with('ValidTokenUser')
->willReturn($this->existingUser);
-
- $this->crypto->method('decrypt')
- ->with(
- $this->equalTo('aValidtoken'),
- $this->equalTo('test@example.comSECRET')
- )->willThrowException(new \Exception());
+ $this->verificationToken->expects($this->atLeastOnce())
+ ->method('check')
+ ->willThrowException(new InvalidTokenException(InvalidTokenException::TOKEN_MISMATCH));
$response = $this->lostController->setPassword('', 'ValidTokenUser', 'NewPassword', true);
$expectedResponse = [
'status' => 'error',
- 'msg' => 'Couldn\'t reset password because the token is invalid'
- ];
- $this->assertSame($expectedResponse, $response);
- }
-
- public function testIsSetPasswordTokenNullFailing() {
- $this->config->method('getUserValue')
- ->with('ValidTokenUser', 'core', 'lostpassword', null)
- ->willReturn(null);
- $this->userManager->method('get')
- ->with('ValidTokenUser')
- ->willReturn($this->existingUser);
-
- $response = $this->lostController->setPassword('', 'ValidTokenUser', 'NewPassword', true);
- $expectedResponse = [
- 'status' => 'error',
- 'msg' => 'Couldn\'t reset password because the token is invalid'
+ 'msg' => 'Could not reset password because the token is invalid'
];
$this->assertSame($expectedResponse, $response);
}
@@ -724,6 +513,9 @@ class LostControllerTest extends \Test\TestCase {
->willReturn(false);
$user->expects($this->never())
->method('setPassword');
+ $user->expects($this->any())
+ ->method('getEMailAddress')
+ ->willReturn('random@example.org');
$this->config->method('getUserValue')
->with('ValidTokenUser', 'core', 'lostpassword', null)
@@ -732,10 +524,14 @@ class LostControllerTest extends \Test\TestCase {
->with('DisabledUser')
->willReturn($user);
+ $this->verificationToken->expects($this->atLeastOnce())
+ ->method('check')
+ ->willThrowException(new InvalidTokenException(InvalidTokenException::USER_UNKNOWN));
+
$response = $this->lostController->setPassword('TheOnlyAndOnlyOneTokenToResetThePassword', 'DisabledUser', 'NewPassword', true);
$expectedResponse = [
'status' => 'error',
- 'msg' => 'Couldn\'t reset password because the token is invalid'
+ 'msg' => 'Could not reset password because the token is invalid'
];
$this->assertSame($expectedResponse, $response);
}
@@ -798,14 +594,6 @@ class LostControllerTest extends \Test\TestCase {
$this->config->expects($this->once())
->method('deleteUserValue')
->with('ValidTokenUser', 'core', 'lostpassword');
- $this->timeFactory->method('getTime')
- ->willReturn(12348);
-
- $this->crypto->method('decrypt')
- ->with(
- $this->equalTo('encryptedData'),
- $this->equalTo('test@example.comSECRET')
- )->willReturn('12345:TheOnlyAndOnlyOneTokenToResetThePassword');
$response = $this->lostController->setPassword('TheOnlyAndOnlyOneTokenToResetThePassword', 'ValidTokenUser', 'NewPassword', false);
$expectedResponse = ['user' => 'ValidTokenUser', 'status' => 'success'];
diff --git a/tests/Core/Controller/SvgControllerTest.php b/tests/Core/Controller/SvgControllerTest.php
index c8d0ea5f503..f44440389ff 100644
--- a/tests/Core/Controller/SvgControllerTest.php
+++ b/tests/Core/Controller/SvgControllerTest.php
@@ -183,7 +183,7 @@ class SvgControllerTest extends TestCase {
$this->appManager->expects($this->once())
->method('getAppPath')
->with($appName)
- ->willReturn(__DIR__ . '/../../../apps/' . $appName);
+ ->willReturn(realpath(__DIR__ . '/../../../apps/') . '/' . $appName);
$response = $this->svgController->getSvgFromApp($appName, $name, $color);
diff --git a/tests/Core/Controller/TwoFactorChallengeControllerTest.php b/tests/Core/Controller/TwoFactorChallengeControllerTest.php
index 1b5042722e5..2cb8d4bd50f 100644
--- a/tests/Core/Controller/TwoFactorChallengeControllerTest.php
+++ b/tests/Core/Controller/TwoFactorChallengeControllerTest.php
@@ -56,6 +56,9 @@ class TwoFactorChallengeControllerTest extends TestCase {
/** @var IURLGenerator|\PHPUnit\Framework\MockObject\MockObject */
private $urlGenerator;
+ /** @var ILogger|\PHPUnit\Framework\MockObject\MockObject */
+ private $logger;
+
/** @var TwoFactorChallengeController|\PHPUnit\Framework\MockObject\MockObject */
private $controller;
@@ -67,6 +70,7 @@ class TwoFactorChallengeControllerTest extends TestCase {
$this->userSession = $this->createMock(IUserSession::class);
$this->session = $this->createMock(ISession::class);
$this->urlGenerator = $this->createMock(IURLGenerator::class);
+ $this->logger = $this->createMock(ILogger::class);
$this->controller = $this->getMockBuilder(TwoFactorChallengeController::class)
->setConstructorArgs([
@@ -76,6 +80,7 @@ class TwoFactorChallengeControllerTest extends TestCase {
$this->userSession,
$this->session,
$this->urlGenerator,
+ $this->logger,
])
->setMethods(['getLogoutUrl'])
->getMock();
diff --git a/tests/Core/Middleware/TwoFactorMiddlewareTest.php b/tests/Core/Middleware/TwoFactorMiddlewareTest.php
index 5ef2b75fde6..8cc4340ad98 100644
--- a/tests/Core/Middleware/TwoFactorMiddlewareTest.php
+++ b/tests/Core/Middleware/TwoFactorMiddlewareTest.php
@@ -97,10 +97,6 @@ class TwoFactorMiddlewareTest extends TestCase {
}
public function testBeforeControllerNotLoggedIn() {
- $this->reflector->expects($this->once())
- ->method('hasAnnotation')
- ->with('PublicPage')
- ->willReturn(false);
$this->userSession->expects($this->once())
->method('isLoggedIn')
->willReturn(false);
@@ -111,24 +107,9 @@ class TwoFactorMiddlewareTest extends TestCase {
$this->middleware->beforeController($this->controller, 'index');
}
- public function testBeforeControllerPublicPage() {
- $this->reflector->expects($this->once())
- ->method('hasAnnotation')
- ->with('PublicPage')
- ->willReturn(true);
- $this->userSession->expects($this->never())
- ->method('isLoggedIn');
-
- $this->middleware->beforeController($this->controller, 'create');
- }
-
public function testBeforeSetupController() {
$user = $this->createMock(IUser::class);
$controller = $this->createMock(ALoginSetupController::class);
- $this->reflector->expects($this->once())
- ->method('hasAnnotation')
- ->with('PublicPage')
- ->willReturn(false);
$this->userSession->expects($this->any())
->method('getUser')
->willReturn($user);
@@ -144,10 +125,6 @@ class TwoFactorMiddlewareTest extends TestCase {
public function testBeforeControllerNoTwoFactorCheckNeeded() {
$user = $this->createMock(IUser::class);
- $this->reflector->expects($this->once())
- ->method('hasAnnotation')
- ->with('PublicPage')
- ->willReturn(false);
$this->userSession->expects($this->once())
->method('isLoggedIn')
->willReturn(true);
@@ -168,10 +145,6 @@ class TwoFactorMiddlewareTest extends TestCase {
$user = $this->createMock(IUser::class);
- $this->reflector->expects($this->once())
- ->method('hasAnnotation')
- ->with('PublicPage')
- ->willReturn(false);
$this->userSession->expects($this->once())
->method('isLoggedIn')
->willReturn(true);
diff --git a/tests/acceptance/features/bootstrap/AppSettingsContext.php b/tests/acceptance/features/bootstrap/AppSettingsContext.php
index c7859edcb64..210e907a9bc 100644
--- a/tests/acceptance/features/bootstrap/AppSettingsContext.php
+++ b/tests/acceptance/features/bootstrap/AppSettingsContext.php
@@ -39,7 +39,7 @@ class AppSettingsContext implements Context, ActorAwareInterface {
* @return Locator
*/
public static function appSettingsContent() {
- return Locator::forThe()->id("app-settings-content")->
+ return Locator::forThe()->xpath("//div[@id = 'app-settings-content' or @id = 'app-settings__content']")->
descendantOf(self::appSettings())->
describedAs("App settings");
}
@@ -48,7 +48,7 @@ class AppSettingsContext implements Context, ActorAwareInterface {
* @return Locator
*/
public static function appSettingsOpenButton() {
- return Locator::forThe()->xpath("//div[@id = 'app-settings-header']/button")->
+ return Locator::forThe()->xpath("//div[@id = 'app-settings-header' or @id = 'app-settings__header']/button")->
descendantOf(self::appSettings())->
describedAs("The button to open the app settings");
}
diff --git a/tests/acceptance/features/bootstrap/FilesAppContext.php b/tests/acceptance/features/bootstrap/FilesAppContext.php
index fe93bf194a2..7c29aadb8d4 100644
--- a/tests/acceptance/features/bootstrap/FilesAppContext.php
+++ b/tests/acceptance/features/bootstrap/FilesAppContext.php
@@ -89,7 +89,7 @@ class FilesAppContext implements Context, ActorAwareInterface {
* @return Locator
*/
public static function closeDetailsViewButton() {
- return Locator::forThe()->css(".icon-close")->
+ return Locator::forThe()->css(".app-sidebar__close")->
descendantOf(self::detailsView())->
describedAs("Close details view in Files app");
}
diff --git a/tests/lib/Accounts/AccountManagerTest.php b/tests/lib/Accounts/AccountManagerTest.php
index 8ed0e29d7ce..bf79d233131 100644
--- a/tests/lib/Accounts/AccountManagerTest.php
+++ b/tests/lib/Accounts/AccountManagerTest.php
@@ -25,9 +25,15 @@ use OC\Accounts\Account;
use OC\Accounts\AccountManager;
use OCP\Accounts\IAccountManager;
use OCP\BackgroundJob\IJobList;
+use OCP\Defaults;
use OCP\IConfig;
use OCP\IDBConnection;
+use OCP\IURLGenerator;
use OCP\IUser;
+use OCP\L10N\IFactory;
+use OCP\Mail\IMailer;
+use OCP\Security\ICrypto;
+use OCP\Security\VerificationToken\IVerificationToken;
use PHPUnit\Framework\MockObject\MockObject;
use Psr\Log\LoggerInterface;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
@@ -41,6 +47,18 @@ use Test\TestCase;
* @package Test\Accounts
*/
class AccountManagerTest extends TestCase {
+ /** @var IVerificationToken|MockObject */
+ protected $verificationToken;
+ /** @var IMailer|MockObject */
+ protected $mailer;
+ /** @var ICrypto|MockObject */
+ protected $crypto;
+ /** @var IURLGenerator|MockObject */
+ protected $urlGenerator;
+ /** @var Defaults|MockObject */
+ protected $defaults;
+ /** @var IFactory|MockObject */
+ protected $l10nFactory;
/** @var \OCP\IDBConnection */
private $connection;
@@ -70,6 +88,12 @@ class AccountManagerTest extends TestCase {
$this->config = $this->createMock(IConfig::class);
$this->jobList = $this->createMock(IJobList::class);
$this->logger = $this->createMock(LoggerInterface::class);
+ $this->verificationToken = $this->createMock(IVerificationToken::class);
+ $this->mailer = $this->createMock(IMailer::class);
+ $this->defaults = $this->createMock(Defaults::class);
+ $this->l10nFactory = $this->createMock(IFactory::class);
+ $this->urlGenerator = $this->createMock(IURLGenerator::class);
+ $this->crypto = $this->createMock(ICrypto::class);
$this->accountManager = new AccountManager(
$this->connection,
@@ -77,6 +101,12 @@ class AccountManagerTest extends TestCase {
$this->eventDispatcher,
$this->jobList,
$this->logger,
+ $this->verificationToken,
+ $this->mailer,
+ $this->defaults,
+ $this->l10nFactory,
+ $this->urlGenerator,
+ $this->crypto
);
}
@@ -310,6 +340,12 @@ class AccountManagerTest extends TestCase {
$this->eventDispatcher,
$this->jobList,
$this->logger,
+ $this->verificationToken,
+ $this->mailer,
+ $this->defaults,
+ $this->l10nFactory,
+ $this->urlGenerator,
+ $this->crypto
])
->setMethods($mockedMethods)
->getMock();
diff --git a/tests/lib/AllConfigTest.php b/tests/lib/AllConfigTest.php
index 9daa7c9be9c..b0b0b7eff8b 100644
--- a/tests/lib/AllConfigTest.php
+++ b/tests/lib/AllConfigTest.php
@@ -15,6 +15,8 @@ namespace Test;
*
* @package Test
*/
+
+use OC\SystemConfig;
use OCP\IDBConnection;
class AllConfigTest extends \Test\TestCase {
@@ -145,7 +147,7 @@ class AllConfigTest extends \Test\TestCase {
$config->setUserValue('userSetBool', 'appSetBool', 'keySetBool', $value);
}
-
+
public function testSetUserValueWithPreConditionFailure() {
$this->expectException(\OCP\PreConditionNotMetException::class);
@@ -437,4 +439,22 @@ class AllConfigTest extends \Test\TestCase {
// cleanup
$this->connection->executeUpdate('DELETE FROM `*PREFIX*preferences`');
}
+
+ public function testGetUsersForUserValueCaseInsensitive() {
+ // mock the check for the database to run the correct SQL statements for each database type
+ $systemConfig = $this->createMock(SystemConfig::class);
+ $systemConfig->expects($this->once())
+ ->method('getValue')
+ ->with($this->equalTo('dbtype'), $this->equalTo('sqlite'))
+ ->willReturn(\OC::$server->getConfig()->getSystemValue('dbtype', 'sqlite'));
+ $config = $this->getConfig($systemConfig);
+
+ $config->setUserValue('user1', 'myApp', 'myKey', 'test123');
+ $config->setUserValue('user2', 'myApp', 'myKey', 'TEST123');
+ $config->setUserValue('user3', 'myApp', 'myKey', 'test12345');
+
+ $users = $config->getUsersForUserValueCaseInsensitive('myApp', 'myKey', 'test123');
+ $this->assertSame(2, count($users));
+ $this->assertSame(['user1', 'user2'], $users);
+ }
}
diff --git a/tests/lib/AppFramework/Middleware/Security/SecurityMiddlewareTest.php b/tests/lib/AppFramework/Middleware/Security/SecurityMiddlewareTest.php
index 8f55f90d377..bf84a631f74 100644
--- a/tests/lib/AppFramework/Middleware/Security/SecurityMiddlewareTest.php
+++ b/tests/lib/AppFramework/Middleware/Security/SecurityMiddlewareTest.php
@@ -32,6 +32,7 @@ use OC\AppFramework\Middleware\Security\Exceptions\SecurityException;
use OC\Appframework\Middleware\Security\Exceptions\StrictCookieMissingException;
use OC\AppFramework\Middleware\Security\SecurityMiddleware;
use OC\AppFramework\Utility\ControllerMethodReflector;
+use OC\Settings\AuthorizedGroupMapper;
use OCP\App\IAppManager;
use OCP\AppFramework\Controller;
use OCP\AppFramework\Http\JSONResponse;
@@ -42,6 +43,7 @@ use OCP\IL10N;
use OCP\INavigationManager;
use OCP\IRequest;
use OCP\IURLGenerator;
+use OCP\IUserSession;
use OCP\Security\ISecureRandom;
use Psr\Log\LoggerInterface;
@@ -69,10 +71,16 @@ class SecurityMiddlewareTest extends \Test\TestCase {
private $appManager;
/** @var IL10N|\PHPUnit\Framework\MockObject\MockObject */
private $l10n;
+ /** @var IUserSession|\PHPUnit\Framework\MockObject\MockObject */
+ private $userSession;
+ /** @var AuthorizedGroupMapper|\PHPUnit\Framework\MockObject\MockObject */
+ private $authorizedGroupMapper;
protected function setUp(): void {
parent::setUp();
+ $this->authorizedGroupMapper = $this->createMock(AuthorizedGroupMapper::class);
+ $this->userSession = $this->createMock(IUserSession::class);
$this->controller = $this->createMock(Controller::class);
$this->reader = new ControllerMethodReflector();
$this->logger = $this->createMock(LoggerInterface::class);
@@ -102,7 +110,9 @@ class SecurityMiddlewareTest extends \Test\TestCase {
$isAdminUser,
$isSubAdmin,
$this->appManager,
- $this->l10n
+ $this->l10n,
+ $this->authorizedGroupMapper,
+ $this->userSession
);
}
diff --git a/tests/lib/Contacts/ContactsMenu/EntryTest.php b/tests/lib/Contacts/ContactsMenu/EntryTest.php
index a8dd7fdc508..bce1865f94a 100644
--- a/tests/lib/Contacts/ContactsMenu/EntryTest.php
+++ b/tests/lib/Contacts/ContactsMenu/EntryTest.php
@@ -96,16 +96,18 @@ class EntryTest extends TestCase {
public function testJsonSerialize() {
$expectedJson = [
- 'id' => 123,
+ 'id' => '123',
'fullName' => 'Guadalupe Frisbey',
'topAction' => null,
'actions' => [],
'lastMessage' => '',
'avatar' => null,
+ 'emailAddresses' => ['user@example.com']
];
$this->entry->setId(123);
$this->entry->setFullName('Guadalupe Frisbey');
+ $this->entry->addEMailAddress('user@example.com');
$json = $this->entry->jsonSerialize();
$this->assertEquals($expectedJson, $json);
diff --git a/tests/lib/Files/Node/FolderTest.php b/tests/lib/Files/Node/FolderTest.php
index 72bf70a68b7..94bcac4aa00 100644
--- a/tests/lib/Files/Node/FolderTest.php
+++ b/tests/lib/Files/Node/FolderTest.php
@@ -99,8 +99,7 @@ class FolderTest extends NodeTest {
->method('getUser')
->willReturn($this->user);
- $root->expects($this->once())
- ->method('get')
+ $root->method('get')
->with('/bar/foo/asd');
$node = new Folder($root, $view, '/bar/foo');
@@ -122,8 +121,7 @@ class FolderTest extends NodeTest {
$child = new Folder($root, $view, '/bar/foo/asd');
- $root->expects($this->once())
- ->method('get')
+ $root->method('get')
->with('/bar/foo/asd')
->willReturn($child);
@@ -144,8 +142,7 @@ class FolderTest extends NodeTest {
->method('getUser')
->willReturn($this->user);
- $root->expects($this->once())
- ->method('get')
+ $root->method('get')
->with('/bar/foo/asd')
->will($this->throwException(new NotFoundException()));
@@ -166,13 +163,11 @@ class FolderTest extends NodeTest {
->method('getUser')
->willReturn($this->user);
- $view->expects($this->once())
- ->method('getFileInfo')
+ $view->method('getFileInfo')
->with('/bar/foo')
->willReturn($this->getFileInfo(['permissions' => \OCP\Constants::PERMISSION_ALL]));
- $view->expects($this->once())
- ->method('mkdir')
+ $view->method('mkdir')
->with('/bar/foo/asd')
->willReturn(true);
@@ -194,12 +189,10 @@ class FolderTest extends NodeTest {
$root = $this->getMockBuilder(Root::class)
->setConstructorArgs([$manager, $view, $this->user, $this->userMountCache, $this->logger, $this->userManager])
->getMock();
- $root->expects($this->any())
- ->method('getUser')
+ $root->method('getUser')
->willReturn($this->user);
- $view->expects($this->once())
- ->method('getFileInfo')
+ $view->method('getFileInfo')
->with('/bar/foo')
->willReturn($this->getFileInfo(['permissions' => \OCP\Constants::PERMISSION_READ]));
@@ -220,13 +213,11 @@ class FolderTest extends NodeTest {
->method('getUser')
->willReturn($this->user);
- $view->expects($this->once())
- ->method('getFileInfo')
+ $view->method('getFileInfo')
->with('/bar/foo')
->willReturn($this->getFileInfo(['permissions' => \OCP\Constants::PERMISSION_ALL]));
- $view->expects($this->once())
- ->method('touch')
+ $view->method('touch')
->with('/bar/foo/asd')
->willReturn(true);
@@ -248,12 +239,10 @@ class FolderTest extends NodeTest {
$root = $this->getMockBuilder(Root::class)
->setConstructorArgs([$manager, $view, $this->user, $this->userMountCache, $this->logger, $this->userManager])
->getMock();
- $root->expects($this->any())
- ->method('getUser')
+ $root->method('getUser')
->willReturn($this->user);
- $view->expects($this->once())
- ->method('getFileInfo')
+ $view->method('getFileInfo')
->with('/bar/foo')
->willReturn($this->getFileInfo(['permissions' => \OCP\Constants::PERMISSION_READ]));
@@ -270,12 +259,10 @@ class FolderTest extends NodeTest {
$root = $this->getMockBuilder(Root::class)
->setConstructorArgs([$manager, $view, $this->user, $this->userMountCache, $this->logger, $this->userManager])
->getMock();
- $root->expects($this->any())
- ->method('getUser')
+ $root->method('getUser')
->willReturn($this->user);
- $view->expects($this->once())
- ->method('free_space')
+ $view->method('free_space')
->with('/bar/foo')
->willReturn(100);
@@ -501,8 +488,7 @@ class FolderTest extends NodeTest {
$fileInfo = new CacheEntry(['path' => 'foo/qwerty', 'mimetype' => 'text/plain'], null);
- $storage->expects($this->once())
- ->method('getCache')
+ $storage->method('getCache')
->willReturn($cache);
$this->userMountCache->expects($this->any())
@@ -517,18 +503,15 @@ class FolderTest extends NodeTest {
''
)]);
- $cache->expects($this->once())
- ->method('get')
+ $cache->method('get')
->with(1)
->willReturn($fileInfo);
- $root->expects($this->once())
- ->method('getMountsIn')
+ $root->method('getMountsIn')
->with('/bar/foo')
->willReturn([]);
- $root->expects($this->once())
- ->method('getMount')
+ $root->method('getMount')
->with('/bar/foo')
->willReturn($mount);
@@ -555,8 +538,7 @@ class FolderTest extends NodeTest {
$fileInfo = new CacheEntry(['path' => '', 'mimetype' => 'text/plain'], null);
- $storage->expects($this->once())
- ->method('getCache')
+ $storage->method('getCache')
->willReturn($cache);
$this->userMountCache->expects($this->any())
@@ -571,13 +553,11 @@ class FolderTest extends NodeTest {
''
)]);
- $cache->expects($this->once())
- ->method('get')
+ $cache->method('get')
->with(1)
->willReturn($fileInfo);
- $root->expects($this->once())
- ->method('getMount')
+ $root->method('getMount')
->with('/bar')
->willReturn($mount);
@@ -604,8 +584,7 @@ class FolderTest extends NodeTest {
$fileInfo = new CacheEntry(['path' => 'foobar', 'mimetype' => 'text/plain'], null);
- $storage->expects($this->once())
- ->method('getCache')
+ $storage->method('getCache')
->willReturn($cache);
$this->userMountCache->expects($this->any())
@@ -620,18 +599,15 @@ class FolderTest extends NodeTest {
''
)]);
- $cache->expects($this->once())
- ->method('get')
+ $cache->method('get')
->with(1)
->willReturn($fileInfo);
- $root->expects($this->once())
- ->method('getMountsIn')
+ $root->method('getMountsIn')
->with('/bar/foo')
->willReturn([]);
- $root->expects($this->once())
- ->method('getMount')
+ $root->method('getMount')
->with('/bar/foo')
->willReturn($mount);
@@ -658,12 +634,10 @@ class FolderTest extends NodeTest {
$fileInfo = new CacheEntry(['path' => 'foo/qwerty', 'mimetype' => 'text/plain'], null);
- $storage->expects($this->exactly(2))
- ->method('getCache')
+ $storage->method('getCache')
->willReturn($cache);
- $this->userMountCache->expects($this->any())
- ->method('getMountsForFileId')
+ $this->userMountCache->method('getMountsForFileId')
->with(1)
->willReturn([
new CachedMountInfo(
@@ -674,32 +648,20 @@ class FolderTest extends NodeTest {
1,
''
),
- new CachedMountInfo(
- $this->user,
- 1,
- 0,
- '/bar/foo/asd/',
- 1,
- ''
- ),
]);
- $storage->expects($this->any())
- ->method('getCache')
+ $storage->method('getCache')
->willReturn($cache);
- $cache->expects($this->any())
- ->method('get')
+ $cache->method('get')
->with(1)
->willReturn($fileInfo);
- $root->expects($this->any())
- ->method('getMountsIn')
+ $root->method('getMountsIn')
->with('/bar/foo')
->willReturn([$mount2]);
- $root->expects($this->once())
- ->method('getMount')
+ $root->method('getMount')
->with('/bar/foo')
->willReturn($mount1);
diff --git a/tests/lib/Files/ObjectStore/ObjectStoreTest.php b/tests/lib/Files/ObjectStore/ObjectStoreTest.php
index 4ec44eb410d..a245f0ae366 100644
--- a/tests/lib/Files/ObjectStore/ObjectStoreTest.php
+++ b/tests/lib/Files/ObjectStore/ObjectStoreTest.php
@@ -26,11 +26,27 @@ use Test\TestCase;
abstract class ObjectStoreTest extends TestCase {
+ /** @var string[] */
+ private $cleanup = [];
+
/**
* @return \OCP\Files\ObjectStore\IObjectStore
*/
abstract protected function getInstance();
+ protected function cleanupAfter(string $urn) {
+ $this->cleanup[] = $urn;
+ }
+
+ public function tearDown(): void {
+ parent::tearDown();
+
+ $instance = $this->getInstance();
+ foreach ($this->cleanup as $urn) {
+ $instance->deleteObject($urn);
+ }
+ }
+
protected function stringToStream($data) {
$stream = fopen('php://temp', 'w+');
fwrite($stream, $data);
@@ -110,6 +126,9 @@ abstract class ObjectStoreTest extends TestCase {
}
public function testCopy() {
+ $this->cleanupAfter('source');
+ $this->cleanupAfter('target');
+
$stream = $this->stringToStream('foobar');
$instance = $this->getInstance();
diff --git a/tests/lib/Files/ObjectStore/S3Test.php b/tests/lib/Files/ObjectStore/S3Test.php
index 25bee9cbdd8..a7a95d53375 100644
--- a/tests/lib/Files/ObjectStore/S3Test.php
+++ b/tests/lib/Files/ObjectStore/S3Test.php
@@ -60,6 +60,12 @@ class NonSeekableStream extends Wrapper {
* @group PRIMARY-s3
*/
class S3Test extends ObjectStoreTest {
+ public function setUp(): void {
+ parent::setUp();
+ $s3 = $this->getInstance();
+ $s3->deleteObject('multiparttest');
+ }
+
protected function getInstance() {
$config = \OC::$server->getConfig()->getSystemValue('objectstore');
if (!is_array($config) || $config['class'] !== S3::class) {
@@ -70,6 +76,8 @@ class S3Test extends ObjectStoreTest {
}
public function testUploadNonSeekable() {
+ $this->cleanupAfter('multiparttest');
+
$s3 = $this->getInstance();
$s3->writeObject('multiparttest', NonSeekableStream::wrap(fopen(__FILE__, 'r')));
@@ -80,6 +88,8 @@ class S3Test extends ObjectStoreTest {
}
public function testSeek() {
+ $this->cleanupAfter('seek');
+
$data = file_get_contents(__FILE__);
$instance = $this->getInstance();
@@ -94,4 +104,80 @@ class S3Test extends ObjectStoreTest {
fseek($read, 100, SEEK_CUR);
$this->assertEquals(substr($data, 210, 100), fread($read, 100));
}
+
+ public function assertNoUpload($objectUrn) {
+ $s3 = $this->getInstance();
+ $s3client = $s3->getConnection();
+ $uploads = $s3client->listMultipartUploads([
+ 'Bucket' => $s3->getBucket(),
+ 'Prefix' => $objectUrn,
+ ]);
+ $this->assertArrayNotHasKey('Uploads', $uploads);
+ }
+
+ public function testEmptyUpload() {
+ $s3 = $this->getInstance();
+
+ $emptyStream = fopen("php://memory", "r");
+ fwrite($emptyStream, null);
+
+ $s3->writeObject('emptystream', $emptyStream);
+
+ $this->assertNoUpload('emptystream');
+ $this->assertTrue($s3->objectExists('emptystream'));
+
+ $thrown = false;
+ try {
+ self::assertFalse($s3->readObject('emptystream'));
+ } catch (\Exception $e) {
+ // An exception is expected here since 0 byte files are wrapped
+ // to be read from an empty memory stream in the ObjectStoreStorage
+ $thrown = true;
+ }
+ self::assertTrue($thrown, 'readObject with range requests are not expected to work on empty objects');
+
+ $s3->deleteObject('emptystream');
+ }
+
+ /** File size to upload in bytes */
+ public function dataFileSizes() {
+ return [
+ [1000000], [2000000], [5242879], [5242880], [5242881], [10000000]
+ ];
+ }
+
+ /** @dataProvider dataFileSizes */
+ public function testFileSizes($size) {
+ $this->cleanupAfter('testfilesizes');
+ $s3 = $this->getInstance();
+
+ $sourceStream = fopen('php://memory', 'wb+');
+ $writeChunkSize = 1024;
+ $chunkCount = $size / $writeChunkSize;
+ for ($i = 0; $i < $chunkCount; $i++) {
+ fwrite($sourceStream, str_repeat('A',
+ ($i < $chunkCount - 1) ? $writeChunkSize : $size - ($i * $writeChunkSize)
+ ));
+ }
+ rewind($sourceStream);
+ $s3->writeObject('testfilesizes', $sourceStream);
+
+ $this->assertNoUpload('testfilesizes');
+ self::assertTrue($s3->objectExists('testfilesizes'));
+
+ $result = $s3->readObject('testfilesizes');
+
+ // compare first 100 bytes
+ self::assertEquals(str_repeat('A', 100), fread($result, 100));
+
+ // compare 100 bytes
+ fseek($result, $size - 100);
+ self::assertEquals(str_repeat('A', 100), fread($result, 100));
+
+ // end of file reached
+ fseek($result, $size);
+ self:self::assertTrue(feof($result));
+
+ $this->assertNoUpload('testfilesizes');
+ }
}
diff --git a/tests/lib/Security/CredentialsManagerTest.php b/tests/lib/Security/CredentialsManagerTest.php
index 3335e18a8b1..f81db330640 100644
--- a/tests/lib/Security/CredentialsManagerTest.php
+++ b/tests/lib/Security/CredentialsManagerTest.php
@@ -24,92 +24,11 @@ declare(strict_types=1);
namespace Test\Security;
-use OC\Security\CredentialsManager;
-use OCP\DB\IResult;
-use OCP\DB\QueryBuilder\IExpressionBuilder;
-use OCP\DB\QueryBuilder\IQueryBuilder;
-use OCP\IDBConnection;
-use OCP\Security\ICrypto;
-
/**
* @group DB
*/
class CredentialsManagerTest extends \Test\TestCase {
- /** @var ICrypto */
- protected $crypto;
-
- /** @var IDBConnection */
- protected $dbConnection;
-
- /** @var CredentialsManager */
- protected $manager;
-
- protected function setUp(): void {
- parent::setUp();
- $this->crypto = $this->createMock(ICrypto::class);
- $this->dbConnection = $this->getMockBuilder(IDBConnection::class)
- ->disableOriginalConstructor()
- ->getMock();
- $this->manager = new CredentialsManager($this->crypto, $this->dbConnection);
- }
-
- private function getQueryResult($row) {
- $result = $this->createMock(IResult::class);
-
- $result->expects($this->any())
- ->method('fetch')
- ->willReturn($row);
-
- return $result;
- }
-
- public function testStore() {
- $userId = 'abc';
- $identifier = 'foo';
- $credentials = 'bar';
-
- $this->crypto->expects($this->once())
- ->method('encrypt')
- ->with(json_encode($credentials))
- ->willReturn('baz');
-
- $this->dbConnection->expects($this->once())
- ->method('setValues')
- ->with(CredentialsManager::DB_TABLE,
- ['user' => $userId, 'identifier' => $identifier],
- ['credentials' => 'baz']
- );
-
- $this->manager->store($userId, $identifier, $credentials);
- }
-
- public function testRetrieve() {
- $userId = 'abc';
- $identifier = 'foo';
-
- $this->crypto->expects($this->once())
- ->method('decrypt')
- ->with('baz')
- ->willReturn(json_encode('bar'));
-
- $eb = $this->createMock(IExpressionBuilder::class);
- $qb = $this->createMock(IQueryBuilder::class);
- $qb->method('select')->willReturnSelf();
- $qb->method('from')->willReturnSelf();
- $qb->method('where')->willReturnSelf();
- $qb->method('expr')->willReturn($eb);
- $qb->expects($this->once())
- ->method('execute')
- ->willReturn($this->getQueryResult(['credentials' => 'baz']));
-
- $this->dbConnection->expects($this->once())
- ->method('getQueryBuilder')
- ->willReturn($qb);
-
- $this->manager->retrieve($userId, $identifier);
- }
-
/**
* @dataProvider credentialsProvider
*/
diff --git a/tests/lib/Security/RateLimiting/Backend/MemoryCacheTest.php b/tests/lib/Security/RateLimiting/Backend/MemoryCacheBackendTest.php
index ff58bd5c09e..e7cb4a93a29 100644
--- a/tests/lib/Security/RateLimiting/Backend/MemoryCacheTest.php
+++ b/tests/lib/Security/RateLimiting/Backend/MemoryCacheBackendTest.php
@@ -24,20 +24,20 @@ declare(strict_types=1);
namespace Test\Security\RateLimiting\Backend;
-use OC\Security\RateLimiting\Backend\MemoryCache;
+use OC\Security\RateLimiting\Backend\MemoryCacheBackend;
use OCP\AppFramework\Utility\ITimeFactory;
use OCP\ICache;
use OCP\ICacheFactory;
use Test\TestCase;
-class MemoryCacheTest extends TestCase {
+class MemoryCacheBackendTest extends TestCase {
/** @var ICacheFactory|\PHPUnit\Framework\MockObject\MockObject */
private $cacheFactory;
/** @var ITimeFactory|\PHPUnit\Framework\MockObject\MockObject */
private $timeFactory;
/** @var ICache|\PHPUnit\Framework\MockObject\MockObject */
private $cache;
- /** @var MemoryCache */
+ /** @var MemoryCacheBackend */
private $memoryCache;
protected function setUp(): void {
@@ -50,10 +50,10 @@ class MemoryCacheTest extends TestCase {
$this->cacheFactory
->expects($this->once())
->method('createDistributed')
- ->with('OC\Security\RateLimiting\Backend\MemoryCache')
+ ->with('OC\Security\RateLimiting\Backend\MemoryCacheBackend')
->willReturn($this->cache);
- $this->memoryCache = new MemoryCache(
+ $this->memoryCache = new MemoryCacheBackend(
$this->cacheFactory,
$this->timeFactory
);
@@ -66,7 +66,7 @@ class MemoryCacheTest extends TestCase {
->with('eea460b8d756885099c7f0a4c083bf6a745069ee4a301984e726df58fd4510bffa2dac4b7fd5d835726a6753ffa8343ba31c7e902bbef78fc68c2e743667cb4b')
->willReturn(null);
- $this->assertSame(0, $this->memoryCache->getAttempts('Method', 'User', 123));
+ $this->assertSame(0, $this->memoryCache->getAttempts('Method', 'User'));
}
public function testGetAttempts() {
@@ -82,12 +82,12 @@ class MemoryCacheTest extends TestCase {
'1',
'2',
'87',
- '123',
- '123',
- '124',
+ '223',
+ '223',
+ '224',
]));
- $this->assertSame(3, $this->memoryCache->getAttempts('Method', 'User', 123));
+ $this->assertSame(3, $this->memoryCache->getAttempts('Method', 'User'));
}
public function testRegisterAttemptWithNoAttemptsBefore() {
@@ -106,7 +106,7 @@ class MemoryCacheTest extends TestCase {
->method('set')
->with(
'eea460b8d756885099c7f0a4c083bf6a745069ee4a301984e726df58fd4510bffa2dac4b7fd5d835726a6753ffa8343ba31c7e902bbef78fc68c2e743667cb4b',
- json_encode(['123'])
+ json_encode(['223'])
);
$this->memoryCache->registerAttempt('Method', 'User', 100);
@@ -116,7 +116,7 @@ class MemoryCacheTest extends TestCase {
$this->timeFactory
->expects($this->once())
->method('getTime')
- ->willReturn(129);
+ ->willReturn(86);
$this->cache
->expects($this->once())
@@ -140,7 +140,7 @@ class MemoryCacheTest extends TestCase {
'123',
'123',
'124',
- '129',
+ '186',
])
);
diff --git a/tests/lib/Security/RateLimiting/LimiterTest.php b/tests/lib/Security/RateLimiting/LimiterTest.php
index 8b3509a4790..a5b187fb546 100644
--- a/tests/lib/Security/RateLimiting/LimiterTest.php
+++ b/tests/lib/Security/RateLimiting/LimiterTest.php
@@ -26,13 +26,10 @@ namespace Test\Security\RateLimiting;
use OC\Security\RateLimiting\Backend\IBackend;
use OC\Security\RateLimiting\Limiter;
-use OCP\AppFramework\Utility\ITimeFactory;
use OCP\IUser;
use Test\TestCase;
class LimiterTest extends TestCase {
- /** @var ITimeFactory|\PHPUnit\Framework\MockObject\MockObject */
- private $timeFactory;
/** @var IBackend|\PHPUnit\Framework\MockObject\MockObject */
private $backend;
/** @var Limiter */
@@ -41,11 +38,9 @@ class LimiterTest extends TestCase {
protected function setUp(): void {
parent::setUp();
- $this->timeFactory = $this->createMock(ITimeFactory::class);
$this->backend = $this->createMock(IBackend::class);
$this->limiter = new Limiter(
- $this->timeFactory,
$this->backend
);
}
@@ -60,8 +55,7 @@ class LimiterTest extends TestCase {
->method('getAttempts')
->with(
'MyIdentifier',
- '4664f0d9c88dcb7552be47b37bb52ce35977b2e60e1ac13757cf625f31f87050a41f3da064887fa87d49fd042e4c8eb20de8f10464877d3959677ab011b73a47',
- 100
+ '4664f0d9c88dcb7552be47b37bb52ce35977b2e60e1ac13757cf625f31f87050a41f3da064887fa87d49fd042e4c8eb20de8f10464877d3959677ab011b73a47'
)
->willReturn(101);
@@ -69,17 +63,12 @@ class LimiterTest extends TestCase {
}
public function testRegisterAnonRequestSuccess() {
- $this->timeFactory
- ->expects($this->once())
- ->method('getTime')
- ->willReturn(2000);
$this->backend
->expects($this->once())
->method('getAttempts')
->with(
'MyIdentifier',
- '4664f0d9c88dcb7552be47b37bb52ce35977b2e60e1ac13757cf625f31f87050a41f3da064887fa87d49fd042e4c8eb20de8f10464877d3959677ab011b73a47',
- 100
+ '4664f0d9c88dcb7552be47b37bb52ce35977b2e60e1ac13757cf625f31f87050a41f3da064887fa87d49fd042e4c8eb20de8f10464877d3959677ab011b73a47'
)
->willReturn(99);
$this->backend
@@ -88,7 +77,7 @@ class LimiterTest extends TestCase {
->with(
'MyIdentifier',
'4664f0d9c88dcb7552be47b37bb52ce35977b2e60e1ac13757cf625f31f87050a41f3da064887fa87d49fd042e4c8eb20de8f10464877d3959677ab011b73a47',
- 2000
+ 100
);
$this->limiter->registerAnonRequest('MyIdentifier', 100, 100, '127.0.0.1');
@@ -110,8 +99,7 @@ class LimiterTest extends TestCase {
->method('getAttempts')
->with(
'MyIdentifier',
- 'ddb2ec50fa973fd49ecf3d816f677c8095143e944ad10485f30fb3dac85c13a346dace4dae2d0a15af91867320957bfd38a43d9eefbb74fe6919e15119b6d805',
- 100
+ 'ddb2ec50fa973fd49ecf3d816f677c8095143e944ad10485f30fb3dac85c13a346dace4dae2d0a15af91867320957bfd38a43d9eefbb74fe6919e15119b6d805'
)
->willReturn(101);
@@ -126,17 +114,12 @@ class LimiterTest extends TestCase {
->method('getUID')
->willReturn('MyUid');
- $this->timeFactory
- ->expects($this->once())
- ->method('getTime')
- ->willReturn(2000);
$this->backend
->expects($this->once())
->method('getAttempts')
->with(
'MyIdentifier',
- 'ddb2ec50fa973fd49ecf3d816f677c8095143e944ad10485f30fb3dac85c13a346dace4dae2d0a15af91867320957bfd38a43d9eefbb74fe6919e15119b6d805',
- 100
+ 'ddb2ec50fa973fd49ecf3d816f677c8095143e944ad10485f30fb3dac85c13a346dace4dae2d0a15af91867320957bfd38a43d9eefbb74fe6919e15119b6d805'
)
->willReturn(99);
$this->backend
@@ -145,7 +128,7 @@ class LimiterTest extends TestCase {
->with(
'MyIdentifier',
'ddb2ec50fa973fd49ecf3d816f677c8095143e944ad10485f30fb3dac85c13a346dace4dae2d0a15af91867320957bfd38a43d9eefbb74fe6919e15119b6d805',
- 2000
+ 100
);
$this->limiter->registerUserRequest('MyIdentifier', 100, 100, $user);
diff --git a/tests/lib/Security/VerificationToken/VerificationTokenTest.php b/tests/lib/Security/VerificationToken/VerificationTokenTest.php
new file mode 100644
index 00000000000..4d90e304ab7
--- /dev/null
+++ b/tests/lib/Security/VerificationToken/VerificationTokenTest.php
@@ -0,0 +1,309 @@
+<?php
+
+declare(strict_types=1);
+
+/**
+ * @copyright Copyright (c) 2021 Arthur Schiwon <blizzz@arthur-schiwon.de>
+ *
+ * @author Arthur Schiwon <blizzz@arthur-schiwon.de>
+ *
+ * @license GNU AGPL version 3 or any later version
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <https://www.gnu.org/licenses/>.
+ *
+ */
+
+namespace Test\Security\VerificationToken;
+
+use OC\Security\VerificationToken\VerificationToken;
+use OCP\AppFramework\Utility\ITimeFactory;
+use OCP\BackgroundJob\IJobList;
+use OCP\IConfig;
+use OCP\IUser;
+use OCP\Security\ICrypto;
+use OCP\Security\ISecureRandom;
+use OCP\Security\VerificationToken\InvalidTokenException;
+use Test\TestCase;
+
+class VerificationTokenTest extends TestCase {
+ /** @var VerificationToken */
+ protected $token;
+ /** @var IConfig|\PHPUnit\Framework\MockObject\MockObject */
+ protected $config;
+ /** @var ISecureRandom|\PHPUnit\Framework\MockObject\MockObject */
+ protected $secureRandom;
+ /** @var ICrypto|\PHPUnit\Framework\MockObject\MockObject */
+ protected $crypto;
+ /** @var ITimeFactory|\PHPUnit\Framework\MockObject\MockObject */
+ protected $timeFactory;
+
+ protected function setUp(): void {
+ parent::setUp();
+
+ $this->config = $this->createMock(IConfig::class);
+ $this->crypto = $this->createMock(ICrypto::class);
+ $this->timeFactory = $this->createMock(ITimeFactory::class);
+ $this->secureRandom = $this->createMock(ISecureRandom::class);
+ $this->jobList = $this->createMock(IJobList::class);
+
+ $this->token = new VerificationToken(
+ $this->config,
+ $this->crypto,
+ $this->timeFactory,
+ $this->secureRandom,
+ $this->jobList
+ );
+ }
+
+ public function testTokenUserUnknown() {
+ $this->expectException(InvalidTokenException::class);
+ $this->expectExceptionCode(InvalidTokenException::USER_UNKNOWN);
+ $this->token->check('encryptedToken', null, 'fingerprintToken', 'foobar');
+ }
+
+ public function testTokenUserUnknown2() {
+ $user = $this->createMock(IUser::class);
+ $user->expects($this->atLeastOnce())
+ ->method('isEnabled')
+ ->willReturn(false);
+
+ $this->expectException(InvalidTokenException::class);
+ $this->expectExceptionCode(InvalidTokenException::USER_UNKNOWN);
+ $this->token->check('encryptedToken', $user, 'fingerprintToken', 'foobar');
+ }
+
+ public function testTokenNotFound() {
+ $user = $this->createMock(IUser::class);
+ $user->expects($this->atLeastOnce())
+ ->method('isEnabled')
+ ->willReturn(true);
+ $user->expects($this->atLeastOnce())
+ ->method('getUID')
+ ->willReturn('alice');
+
+ // implicit: IConfig::getUserValue returns null by default
+
+ $this->expectException(InvalidTokenException::class);
+ $this->expectExceptionCode(InvalidTokenException::TOKEN_NOT_FOUND);
+ $this->token->check('encryptedToken', $user, 'fingerprintToken', 'foobar');
+ }
+
+ public function testTokenDecryptionError() {
+ $user = $this->createMock(IUser::class);
+ $user->expects($this->atLeastOnce())
+ ->method('isEnabled')
+ ->willReturn(true);
+ $user->expects($this->atLeastOnce())
+ ->method('getUID')
+ ->willReturn('alice');
+
+ $this->config->expects($this->atLeastOnce())
+ ->method('getUserValue')
+ ->with('alice', 'core', 'fingerprintToken', null)
+ ->willReturn('encryptedToken');
+ $this->config->expects($this->any())
+ ->method('getSystemValue')
+ ->with('secret')
+ ->willReturn('357111317');
+
+ $this->crypto->method('decrypt')
+ ->with('encryptedToken', 'foobar' . '357111317')
+ ->willThrowException(new \Exception('decryption failed'));
+
+ $this->expectException(InvalidTokenException::class);
+ $this->expectExceptionCode(InvalidTokenException::TOKEN_DECRYPTION_ERROR);
+ $this->token->check('encryptedToken', $user, 'fingerprintToken', 'foobar');
+ }
+
+ public function testTokenInvalidFormat() {
+ $user = $this->createMock(IUser::class);
+ $user->expects($this->atLeastOnce())
+ ->method('isEnabled')
+ ->willReturn(true);
+ $user->expects($this->atLeastOnce())
+ ->method('getUID')
+ ->willReturn('alice');
+
+ $this->config->expects($this->atLeastOnce())
+ ->method('getUserValue')
+ ->with('alice', 'core', 'fingerprintToken', null)
+ ->willReturn('encryptedToken');
+ $this->config->expects($this->any())
+ ->method('getSystemValue')
+ ->with('secret')
+ ->willReturn('357111317');
+
+ $this->crypto->method('decrypt')
+ ->with('encryptedToken', 'foobar' . '357111317')
+ ->willReturn('decrypted^nonsense');
+
+ $this->expectException(InvalidTokenException::class);
+ $this->expectExceptionCode(InvalidTokenException::TOKEN_INVALID_FORMAT);
+ $this->token->check('encryptedToken', $user, 'fingerprintToken', 'foobar');
+ }
+
+ public function testTokenExpired() {
+ $user = $this->createMock(IUser::class);
+ $user->expects($this->atLeastOnce())
+ ->method('isEnabled')
+ ->willReturn(true);
+ $user->expects($this->atLeastOnce())
+ ->method('getUID')
+ ->willReturn('alice');
+ $user->expects($this->any())
+ ->method('getLastLogin')
+ ->willReturn(604803);
+
+ $this->config->expects($this->atLeastOnce())
+ ->method('getUserValue')
+ ->with('alice', 'core', 'fingerprintToken', null)
+ ->willReturn('encryptedToken');
+ $this->config->expects($this->any())
+ ->method('getSystemValue')
+ ->with('secret')
+ ->willReturn('357111317');
+
+ $this->crypto->method('decrypt')
+ ->with('encryptedToken', 'foobar' . '357111317')
+ ->willReturn('604800:mY70K3n');
+
+ $this->timeFactory->expects($this->any())
+ ->method('getTime')
+ ->willReturn(604800 * 3);
+
+ $this->expectException(InvalidTokenException::class);
+ $this->expectExceptionCode(InvalidTokenException::TOKEN_EXPIRED);
+ $this->token->check('encryptedToken', $user, 'fingerprintToken', 'foobar');
+ }
+
+ public function testTokenExpiredByLogin() {
+ $user = $this->createMock(IUser::class);
+ $user->expects($this->atLeastOnce())
+ ->method('isEnabled')
+ ->willReturn(true);
+ $user->expects($this->atLeastOnce())
+ ->method('getUID')
+ ->willReturn('alice');
+ $user->expects($this->any())
+ ->method('getLastLogin')
+ ->willReturn(604803);
+
+ $this->config->expects($this->atLeastOnce())
+ ->method('getUserValue')
+ ->with('alice', 'core', 'fingerprintToken', null)
+ ->willReturn('encryptedToken');
+ $this->config->expects($this->any())
+ ->method('getSystemValue')
+ ->with('secret')
+ ->willReturn('357111317');
+
+ $this->crypto->method('decrypt')
+ ->with('encryptedToken', 'foobar' . '357111317')
+ ->willReturn('604800:mY70K3n');
+
+ $this->timeFactory->expects($this->any())
+ ->method('getTime')
+ ->willReturn(604801);
+
+ $this->expectException(InvalidTokenException::class);
+ $this->expectExceptionCode(InvalidTokenException::TOKEN_EXPIRED);
+ $this->token->check('encryptedToken', $user, 'fingerprintToken', 'foobar', true);
+ }
+
+ public function testTokenMismatch() {
+ $user = $this->createMock(IUser::class);
+ $user->expects($this->atLeastOnce())
+ ->method('isEnabled')
+ ->willReturn(true);
+ $user->expects($this->atLeastOnce())
+ ->method('getUID')
+ ->willReturn('alice');
+ $user->expects($this->any())
+ ->method('getLastLogin')
+ ->willReturn(604703);
+
+ $this->config->expects($this->atLeastOnce())
+ ->method('getUserValue')
+ ->with('alice', 'core', 'fingerprintToken', null)
+ ->willReturn('encryptedToken');
+ $this->config->expects($this->any())
+ ->method('getSystemValue')
+ ->with('secret')
+ ->willReturn('357111317');
+
+ $this->crypto->method('decrypt')
+ ->with('encryptedToken', 'foobar' . '357111317')
+ ->willReturn('604802:mY70K3n');
+
+ $this->timeFactory->expects($this->any())
+ ->method('getTime')
+ ->willReturn(604801);
+
+ $this->expectException(InvalidTokenException::class);
+ $this->expectExceptionCode(InvalidTokenException::TOKEN_MISMATCH);
+ $this->token->check('encryptedToken', $user, 'fingerprintToken', 'foobar');
+ }
+
+ public function testTokenSuccess() {
+ $user = $this->createMock(IUser::class);
+ $user->expects($this->atLeastOnce())
+ ->method('isEnabled')
+ ->willReturn(true);
+ $user->expects($this->atLeastOnce())
+ ->method('getUID')
+ ->willReturn('alice');
+ $user->expects($this->any())
+ ->method('getLastLogin')
+ ->willReturn(604703);
+
+ $this->config->expects($this->atLeastOnce())
+ ->method('getUserValue')
+ ->with('alice', 'core', 'fingerprintToken', null)
+ ->willReturn('encryptedToken');
+ $this->config->expects($this->any())
+ ->method('getSystemValue')
+ ->with('secret')
+ ->willReturn('357111317');
+
+ $this->crypto->method('decrypt')
+ ->with('encryptedToken', 'foobar' . '357111317')
+ ->willReturn('604802:barfoo');
+
+ $this->timeFactory->expects($this->any())
+ ->method('getTime')
+ ->willReturn(604801);
+
+ $this->token->check('barfoo', $user, 'fingerprintToken', 'foobar');
+ }
+
+ public function testCreate() {
+ $user = $this->createMock(IUser::class);
+ $user->expects($this->any())
+ ->method('getUID')
+ ->willReturn('alice');
+
+ $this->secureRandom->expects($this->atLeastOnce())
+ ->method('generate')
+ ->willReturn('barfoo');
+ $this->crypto->expects($this->atLeastOnce())
+ ->method('encrypt')
+ ->willReturn('encryptedToken');
+ $this->config->expects($this->atLeastOnce())
+ ->method('setUserValue')
+ ->with('alice', 'core', 'fingerprintToken', 'encryptedToken');
+
+ $vToken = $this->token->create($user, 'fingerprintToken', 'foobar');
+ $this->assertSame('barfoo', $vToken);
+ }
+}
diff --git a/tests/lib/Settings/ManagerTest.php b/tests/lib/Settings/ManagerTest.php
index 3d967b2ed21..96711e75cab 100644
--- a/tests/lib/Settings/ManagerTest.php
+++ b/tests/lib/Settings/ManagerTest.php
@@ -23,22 +23,25 @@
namespace OCA\Settings\Tests\AppInfo;
+use OC\Settings\AuthorizedGroupMapper;
use OC\Settings\Manager;
+use OCP\Group\ISubAdmin;
use OCP\IDBConnection;
+use OCP\IGroupManager;
use OCP\IL10N;
-use OCP\ILogger;
use OCP\IServerContainer;
use OCP\IURLGenerator;
use OCP\L10N\IFactory;
use OCP\Settings\ISettings;
use OCP\Settings\ISubAdminSettings;
+use Psr\Log\LoggerInterface;
use Test\TestCase;
class ManagerTest extends TestCase {
/** @var Manager|\PHPUnit\Framework\MockObject\MockObject */
private $manager;
- /** @var ILogger|\PHPUnit\Framework\MockObject\MockObject */
+ /** @var LoggerInterface|\PHPUnit\Framework\MockObject\MockObject */
private $logger;
/** @var IDBConnection|\PHPUnit\Framework\MockObject\MockObject */
private $l10n;
@@ -48,21 +51,31 @@ class ManagerTest extends TestCase {
private $url;
/** @var IServerContainer|\PHPUnit\Framework\MockObject\MockObject */
private $container;
+ /** @var IGroupManager|\PHPUnit\Framework\MockObject\MockObject */
+ private $groupManager;
+ /** @var ISubAdmin|\PHPUnit\Framework\MockObject\MockObject */
+ private $subAdmin;
protected function setUp(): void {
parent::setUp();
- $this->logger = $this->createMock(ILogger::class);
+ $this->logger = $this->createMock(LoggerInterface::class);
$this->l10n = $this->createMock(IL10N::class);
$this->l10nFactory = $this->createMock(IFactory::class);
$this->url = $this->createMock(IURLGenerator::class);
$this->container = $this->createMock(IServerContainer::class);
+ $this->mapper = $this->createMock(AuthorizedGroupMapper::class);
+ $this->groupManager = $this->createMock(IGroupManager::class);
+ $this->subAdmin = $this->createMock(ISubAdmin::class);
$this->manager = new Manager(
$this->logger,
$this->l10nFactory,
$this->url,
- $this->container
+ $this->container,
+ $this->mapper,
+ $this->groupManager,
+ $this->subAdmin,
);
}
@@ -106,7 +119,7 @@ class ManagerTest extends TestCase {
->willReturn(13);
$section->method('getSection')
->willReturn('sharing');
- $this->container->method('query')
+ $this->container->method('get')
->with('myAdminClass')
->willReturn($section);
@@ -124,7 +137,7 @@ class ManagerTest extends TestCase {
->willReturn(13);
$section->method('getSection')
->willReturn('sharing');
- $this->container->method('query')
+ $this->container->method('get')
->with('myAdminClass')
->willReturn($section);
@@ -141,7 +154,7 @@ class ManagerTest extends TestCase {
$section->method('getSection')
->willReturn('sharing');
$this->container->expects($this->once())
- ->method('query')
+ ->method('get')
->with('mySubAdminClass')
->willReturn($section);
@@ -169,11 +182,11 @@ class ManagerTest extends TestCase {
$this->manager->registerSetting('personal', 'section2');
$this->container->expects($this->at(0))
- ->method('query')
+ ->method('get')
->with('section1')
->willReturn($section);
$this->container->expects($this->at(1))
- ->method('query')
+ ->method('get')
->with('section2')
->willReturn($section2);
diff --git a/tests/lib/UrlGeneratorTest.php b/tests/lib/UrlGeneratorTest.php
index 259cf81164d..9e5795fc41e 100644
--- a/tests/lib/UrlGeneratorTest.php
+++ b/tests/lib/UrlGeneratorTest.php
@@ -185,6 +185,12 @@ class UrlGeneratorTest extends \Test\TestCase {
$this->assertEquals($expected, $actual);
}
+ public function testGetWebroot() {
+ \OC::$WEBROOT = '/nextcloud';
+ $actual = $this->urlGenerator->getWebroot();
+ $this->assertEquals(\OC::$WEBROOT, $actual);
+ }
+
/**
* @dataProvider provideOCSRoutes
*/
diff --git a/tests/lib/User/UserTest.php b/tests/lib/User/UserTest.php
index 2366bf45321..ad8b01555ea 100644
--- a/tests/lib/User/UserTest.php
+++ b/tests/lib/User/UserTest.php
@@ -676,11 +676,14 @@ class UserTest extends TestCase {
$emitter->expects($this->never())
->method('emit');
+ $this->dispatcher->expects($this->never())
+ ->method('dispatch');
+
$config = $this->createMock(IConfig::class);
$config->expects($this->any())
->method('getUserValue')
->willReturn('foo@bar.com');
- $config->expects($this->never())
+ $config->expects($this->any())
->method('setUserValue');
$user = new User('foo', $backend, $this->dispatcher, $emitter, $config);