diff options
Diffstat (limited to 'tests')
97 files changed, 3480 insertions, 1052 deletions
diff --git a/tests/Core/Command/Apps/AppsDisableTest.php b/tests/Core/Command/Apps/AppsDisableTest.php new file mode 100644 index 00000000000..d9c43a79c26 --- /dev/null +++ b/tests/Core/Command/Apps/AppsDisableTest.php @@ -0,0 +1,85 @@ +<?php +declare(strict_types=1); +/** + * @copyright Copyright (c) 2019, Daniel Kesselberg (mail@danielkesselberg.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 <http://www.gnu.org/licenses/>. + * + */ + +namespace Tests\Core\Command\Config; + +use OC\Core\Command\App\Disable; +use Symfony\Component\Console\Tester\CommandTester; +use Test\TestCase; + +/** + * Class AppsDisableTest + * + * @group DB + */ +class AppsDisableTest extends TestCase { + + /** @var CommandTester */ + private $commandTester; + + public function setUp() { + parent::setUp(); + + $command = new Disable( + \OC::$server->getAppManager() + ); + + $this->commandTester = new CommandTester($command); + + \OC::$server->getAppManager()->enableApp('admin_audit'); + \OC::$server->getAppManager()->enableApp('comments'); + } + + /** + * @dataProvider dataCommandInput + * @param $appId + * @param $groups + * @param $statusCode + * @param $output + */ + public function testCommandInput($appId, $statusCode, $output): void { + $input = ['app-id' => $appId]; + + $this->commandTester->execute($input); + + $this->assertContains($output, $this->commandTester->getDisplay()); + $this->assertSame($statusCode, $this->commandTester->getStatusCode()); + } + + public function dataCommandInput(): array { + return [ + [['admin_audit'], 0, 'admin_audit disabled'], + [['comments'], 0, 'comments disabled'], + [['invalid_app'], 0, 'No such app enabled: invalid_app'], + + [['admin_audit', 'comments'], 0, "admin_audit disabled\ncomments disabled"], + [['admin_audit', 'comments', 'invalid_app'], 0, "admin_audit disabled\ncomments 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 disabled"], + [['provisioning_api', 'comments'], 2, "provisioning_api can't be disabled.\ncomments disabled"], + + ]; + } +} diff --git a/tests/Core/Command/Apps/AppsEnableTest.php b/tests/Core/Command/Apps/AppsEnableTest.php new file mode 100644 index 00000000000..bfec710f1bc --- /dev/null +++ b/tests/Core/Command/Apps/AppsEnableTest.php @@ -0,0 +1,93 @@ +<?php +declare(strict_types=1); +/** + * @copyright Copyright (c) 2019, Daniel Kesselberg (mail@danielkesselberg.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 <http://www.gnu.org/licenses/>. + * + */ + +namespace Tests\Core\Command\Config; + +use OC\Core\Command\App\Enable; +use Symfony\Component\Console\Tester\CommandTester; +use Test\TestCase; + +/** + * Class AppsEnableTest + * + * @group DB + */ +class AppsEnableTest extends TestCase { + + /** @var CommandTester */ + private $commandTester; + + public function setUp() { + parent::setUp(); + + $command = new Enable( + \OC::$server->getAppManager(), + \OC::$server->getGroupManager() + ); + + $this->commandTester = new CommandTester($command); + + \OC::$server->getAppManager()->disableApp('admin_audit'); + \OC::$server->getAppManager()->disableApp('comments'); + } + + /** + * @dataProvider dataCommandInput + * @param $appId + * @param $groups + * @param $statusCode + * @param $output + */ + public function testCommandInput($appId, $groups, $statusCode, $output): void { + $input = ['app-id' => $appId]; + + if (is_array($groups)) { + $input['--groups'] = $groups; + } + + $this->commandTester->execute($input); + + $this->assertContains($output, $this->commandTester->getDisplay()); + $this->assertSame($statusCode, $this->commandTester->getStatusCode()); + } + + public function dataCommandInput(): array { + return [ + [['admin_audit'], null, 0, 'admin_audit enabled'], + [['comments'], null, 0, 'comments enabled'], + [['invalid_app'], null, 1, 'Could not download app invalid_app'], + + [['admin_audit', 'comments'], null, 0, "admin_audit enabled\ncomments enabled"], + [['admin_audit', 'comments', 'invalid_app'], null, 1, "admin_audit enabled\ncomments 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 enabled for groups: admin'], + [['updatenotification', 'contacts'], ['admin'], 0, "updatenotification enabled for groups: admin\ncontacts enabled for groups: admin"], + + [['updatenotification'], ['admin', 'invalid_group'], 0, 'updatenotification enabled for groups: admin'], + [['updatenotification', 'contacts'], ['admin', 'invalid_group'], 0, "updatenotification enabled for groups: admin\ncontacts enabled for groups: admin"], + [['updatenotification', 'contacts', 'invalid_app'], ['admin', 'invalid_group'], 1, "updatenotification enabled for groups: admin\ncontacts enabled for groups: admin\nCould not download app invalid_app"], + ]; + } +} diff --git a/tests/Core/Command/Encryption/EncryptAllTest.php b/tests/Core/Command/Encryption/EncryptAllTest.php index ca7b264c98f..c6af7e38722 100644 --- a/tests/Core/Command/Encryption/EncryptAllTest.php +++ b/tests/Core/Command/Encryption/EncryptAllTest.php @@ -91,7 +91,7 @@ class EncryptAllTest extends TestCase { $this->appManager->expects($this->once())->method('disableApp')->with('files_trashbin'); // enable single user mode to avoid that other user login during encryption // destructor should disable the single user mode again - $this->config->expects($this->once())->method('getSystemValue')->with('maintenance', false)->willReturn(false); + $this->config->expects($this->once())->method('getSystemValueBool')->with('maintenance', false)->willReturn(false); $this->config->expects($this->at(1))->method('setSystemValue')->with('maintenance', true); $this->config->expects($this->at(2))->method('setSystemValue')->with('maintenance', false); diff --git a/tests/Core/Command/Maintenance/ModeTest.php b/tests/Core/Command/Maintenance/ModeTest.php index da5e95998e9..895a06bbec1 100644 --- a/tests/Core/Command/Maintenance/ModeTest.php +++ b/tests/Core/Command/Maintenance/ModeTest.php @@ -123,7 +123,7 @@ class ModeTest extends TestCase { string $expectedOutput ) { $this->config->expects($this->any()) - ->method('getSystemValue') + ->method('getSystemValueBool') ->willReturn($currentMaintenanceState); if ($expectedMaintenanceState !== null) { diff --git a/tests/Core/Controller/AppPasswordControllerTest.php b/tests/Core/Controller/AppPasswordControllerTest.php index f0c223ccc1d..a66bcb3fc26 100644 --- a/tests/Core/Controller/AppPasswordControllerTest.php +++ b/tests/Core/Controller/AppPasswordControllerTest.php @@ -36,6 +36,7 @@ use OCP\IRequest; use OCP\ISession; use OCP\Security\ISecureRandom; use PHPUnit\Framework\MockObject\MockObject; +use Symfony\Component\EventDispatcher\EventDispatcherInterface; use Test\TestCase; class AppPasswordControllerTest extends TestCase { @@ -55,6 +56,9 @@ class AppPasswordControllerTest extends TestCase { /** @var IRequest|MockObject */ private $request; + /** @var EventDispatcherInterface|\PHPUnit_Framework_MockObject_MockObject */ + private $eventDispatcher; + /** @var AppPasswordController */ private $controller; @@ -66,6 +70,7 @@ class AppPasswordControllerTest extends TestCase { $this->tokenProvider = $this->createMock(IProvider::class); $this->credentialStore = $this->createMock(IStore::class); $this->request = $this->createMock(IRequest::class); + $this->eventDispatcher = $this->createMock(EventDispatcherInterface::class); $this->controller = new AppPasswordController( 'core', @@ -73,7 +78,8 @@ class AppPasswordControllerTest extends TestCase { $this->session, $this->random, $this->tokenProvider, - $this->credentialStore + $this->credentialStore, + $this->eventDispatcher ); } @@ -134,6 +140,9 @@ class AppPasswordControllerTest extends TestCase { IToken::DO_NOT_REMEMBER ); + $this->eventDispatcher->expects($this->once()) + ->method('dispatch'); + $this->controller->getAppPassword(); } @@ -172,6 +181,9 @@ class AppPasswordControllerTest extends TestCase { IToken::DO_NOT_REMEMBER ); + $this->eventDispatcher->expects($this->once()) + ->method('dispatch'); + $this->controller->getAppPassword(); } diff --git a/tests/Core/Controller/AutoCompleteControllerTest.php b/tests/Core/Controller/AutoCompleteControllerTest.php index b1e9e6ba304..8ff0542cb0b 100644 --- a/tests/Core/Controller/AutoCompleteControllerTest.php +++ b/tests/Core/Controller/AutoCompleteControllerTest.php @@ -27,13 +27,17 @@ use OC\Core\Controller\AutoCompleteController; use OCP\Collaboration\AutoComplete\IManager; use OCP\Collaboration\Collaborators\ISearch; use OCP\IRequest; +use PHPUnit\Framework\MockObject\MockObject; +use Symfony\Component\EventDispatcher\EventDispatcherInterface; use Test\TestCase; class AutoCompleteControllerTest extends TestCase { - /** @var ISearch|\PHPUnit_Framework_MockObject_MockObject */ + /** @var ISearch|MockObject */ protected $collaboratorSearch; - /** @var IManager|\PHPUnit_Framework_MockObject_MockObject */ + /** @var IManager|MockObject */ protected $autoCompleteManager; + /** @var EventDispatcherInterface|MockObject */ + protected $dispatcher; /** @var AutoCompleteController */ protected $controller; @@ -44,12 +48,14 @@ class AutoCompleteControllerTest extends TestCase { $request = $this->createMock(IRequest::class); $this->collaboratorSearch = $this->createMock(ISearch::class); $this->autoCompleteManager = $this->createMock(IManager::class); + $this->dispatcher = $this->createMock(EventDispatcherInterface::class); $this->controller = new AutoCompleteController( 'core', $request, $this->collaboratorSearch, - $this->autoCompleteManager + $this->autoCompleteManager, + $this->dispatcher ); } diff --git a/tests/Core/Controller/AvatarControllerTest.php b/tests/Core/Controller/AvatarControllerTest.php index 3369fa882c8..5fce8fc6359 100644 --- a/tests/Core/Controller/AvatarControllerTest.php +++ b/tests/Core/Controller/AvatarControllerTest.php @@ -53,7 +53,7 @@ use OCP\IUserManager; * @package OC\Core\Controller */ class AvatarControllerTest extends \Test\TestCase { - /** @var \OC\Core\Controller\AvatarController */ + /** @var AvatarController */ private $avatarController; /** @var IAvatar|\PHPUnit_Framework_MockObject_MockObject */ private $avatarMock; @@ -78,7 +78,7 @@ class AvatarControllerTest extends \Test\TestCase { private $request; /** @var TimeFactory|\PHPUnit_Framework_MockObject_MockObject */ private $timeFactory; - + protected function setUp() { parent::setUp(); diff --git a/tests/Core/Controller/ClientFlowLoginControllerTest.php b/tests/Core/Controller/ClientFlowLoginControllerTest.php index ba9caabd0b0..73b8118a876 100644 --- a/tests/Core/Controller/ClientFlowLoginControllerTest.php +++ b/tests/Core/Controller/ClientFlowLoginControllerTest.php @@ -30,7 +30,7 @@ use OCA\OAuth2\Db\AccessTokenMapper; use OCA\OAuth2\Db\Client; use OCA\OAuth2\Db\ClientMapper; use OCP\AppFramework\Http; -use OCP\AppFramework\Http\TemplateResponse; +use OCP\AppFramework\Http\StandaloneTemplateResponse; use OCP\Defaults; use OCP\IL10N; use OCP\IRequest; @@ -41,6 +41,7 @@ use OCP\IUserSession; use OCP\Security\ICrypto; use OCP\Security\ISecureRandom; use OCP\Session\Exceptions\SessionNotAvailableException; +use Symfony\Component\EventDispatcher\EventDispatcherInterface; use Test\TestCase; class ClientFlowLoginControllerTest extends TestCase { @@ -66,6 +67,9 @@ class ClientFlowLoginControllerTest extends TestCase { private $accessTokenMapper; /** @var ICrypto|\PHPUnit_Framework_MockObject_MockObject */ private $crypto; + /** @var EventDispatcherInterface|\PHPUnit_Framework_MockObject_MockObject */ + private $eventDispatcher; + /** @var ClientFlowLoginController */ private $clientFlowLoginController; @@ -90,6 +94,7 @@ class ClientFlowLoginControllerTest extends TestCase { $this->clientMapper = $this->createMock(ClientMapper::class); $this->accessTokenMapper = $this->createMock(AccessTokenMapper::class); $this->crypto = $this->createMock(ICrypto::class); + $this->eventDispatcher = $this->createMock(EventDispatcherInterface::class); $this->clientFlowLoginController = new ClientFlowLoginController( 'core', @@ -103,12 +108,13 @@ class ClientFlowLoginControllerTest extends TestCase { $this->urlGenerator, $this->clientMapper, $this->accessTokenMapper, - $this->crypto + $this->crypto, + $this->eventDispatcher ); } public function testShowAuthPickerPageNoClientOrOauthRequest() { - $expected = new TemplateResponse( + $expected = new StandaloneTemplateResponse( 'core', 'error', [ @@ -166,7 +172,7 @@ class ClientFlowLoginControllerTest extends TestCase { ->method('getServerProtocol') ->willReturn('https'); - $expected = new TemplateResponse( + $expected = new StandaloneTemplateResponse( 'core', 'loginflow/authpicker', [ @@ -225,7 +231,7 @@ class ClientFlowLoginControllerTest extends TestCase { ->method('getServerProtocol') ->willReturn('https'); - $expected = new TemplateResponse( + $expected = new StandaloneTemplateResponse( 'core', 'loginflow/authpicker', [ @@ -253,11 +259,11 @@ class ClientFlowLoginControllerTest extends TestCase { ->method('remove') ->with('client.flow.state.token'); - $expected = new TemplateResponse( + $expected = new StandaloneTemplateResponse( 'core', '403', [ - 'file' => 'State token does not match', + 'message' => 'State token does not match', ], 'guest' ); @@ -378,6 +384,9 @@ class ClientFlowLoginControllerTest extends TestCase { ->method('getHeader') ->willReturn(''); + $this->eventDispatcher->expects($this->once()) + ->method('dispatch'); + $expected = new Http\RedirectResponse('nc://login/server:http://example.com&user:MyLoginName&password:MyGeneratedToken'); $this->assertEquals($expected, $this->clientFlowLoginController->generateAppPassword('MyStateToken')); } @@ -462,6 +471,9 @@ class ClientFlowLoginControllerTest extends TestCase { ->with('MyClientIdentifier') ->willReturn($client); + $this->eventDispatcher->expects($this->once()) + ->method('dispatch'); + $expected = new Http\RedirectResponse('https://example.com/redirect.php?state=MyOauthState&code=MyAccessCode'); $this->assertEquals($expected, $this->clientFlowLoginController->generateAppPassword('MyStateToken', 'MyClientIdentifier')); } @@ -534,6 +546,9 @@ class ClientFlowLoginControllerTest extends TestCase { ->method('getHeader') ->willReturn(''); + $this->eventDispatcher->expects($this->once()) + ->method('dispatch'); + $expected = new Http\RedirectResponse('nc://login/server:http://example.com&user:MyLoginName&password:MyGeneratedToken'); $this->assertEquals($expected, $this->clientFlowLoginController->generateAppPassword('MyStateToken')); } @@ -662,6 +677,9 @@ class ClientFlowLoginControllerTest extends TestCase { ->method('getHeader') ->willReturnMap($headers); + $this->eventDispatcher->expects($this->once()) + ->method('dispatch'); + $expected = new Http\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 new file mode 100644 index 00000000000..911a4923675 --- /dev/null +++ b/tests/Core/Controller/ClientFlowLoginV2ControllerTest.php @@ -0,0 +1,321 @@ +<?php +declare(strict_types=1); +/** + * @copyright Copyright (c) 2019, Roeland Jago Douma <roeland@famdouma.nl> + * + * @author Roeland Jago Douma <roeland@famdouma.nl> + * + * @license GNU AGPL version 3 or any later version + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + * + */ + +namespace Test\Core\Controller; + +use OC\Core\Controller\ClientFlowLoginV2Controller; +use OC\Core\Data\LoginFlowV2Credentials; +use OC\Core\Db\LoginFlowV2; +use OC\Core\Exception\LoginFlowV2NotFoundException; +use OC\Core\Service\LoginFlowV2Service; +use OCP\AppFramework\Http; +use OCP\Defaults; +use OCP\IL10N; +use OCP\IRequest; +use OCP\ISession; +use OCP\IURLGenerator; +use OCP\Security\ISecureRandom; +use PHPUnit\Framework\MockObject\MockObject; +use Test\TestCase; + +class ClientFlowLoginV2ControllerTest extends TestCase { + + /** @var IRequest|MockObject */ + private $request; + /** @var LoginFlowV2Service|MockObject */ + private $loginFlowV2Service; + /** @var IURLGenerator|MockObject */ + private $urlGenerator; + /** @var ISession|MockObject */ + private $session; + /** @var ISecureRandom|MockObject */ + private $random; + /** @var Defaults|MockObject */ + private $defaults; + /** @var IL10N|MockObject */ + private $l; + /** @var ClientFlowLoginV2Controller */ + private $controller; + + public function setUp() { + parent::setUp(); + + $this->request = $this->createMock(IRequest::class); + $this->loginFlowV2Service = $this->createMock(LoginFlowV2Service::class); + $this->urlGenerator = $this->createMock(IURLGenerator::class); + $this->session = $this->createMock(ISession::class); + $this->random = $this->createMock(ISecureRandom::class); + $this->defaults = $this->createMock(Defaults::class); + $this->l = $this->createMock(IL10N::class); + $this->controller = new ClientFlowLoginV2Controller( + 'core', + $this->request, + $this->loginFlowV2Service, + $this->urlGenerator, + $this->session, + $this->random, + $this->defaults, + 'user', + $this->l + ); + } + + public function testPollInvalid() { + $this->loginFlowV2Service->method('poll') + ->with('token') + ->willThrowException(new LoginFlowV2NotFoundException()); + + $result = $this->controller->poll('token'); + + $this->assertSame([], $result->getData()); + $this->assertSame(Http::STATUS_NOT_FOUND, $result->getStatus()); + } + + public function testPollValid() { + $creds = new LoginFlowV2Credentials('server', 'login', 'pass'); + $this->loginFlowV2Service->method('poll') + ->with('token') + ->willReturn($creds); + + $result = $this->controller->poll('token'); + + $this->assertSame($creds, $result->getData()); + $this->assertSame(Http::STATUS_OK, $result->getStatus()); + } + + public function testLandingInvalid() { + $this->session->expects($this->never()) + ->method($this->anything()); + + $this->loginFlowV2Service->method('startLoginFlow') + ->with('token') + ->willReturn(false); + + $result = $this->controller->landing('token'); + + $this->assertSame(Http::STATUS_FORBIDDEN, $result->getStatus()); + $this->assertInstanceOf(Http\StandaloneTemplateResponse::class, $result); + } + + public function testLandingValid() { + $this->session->expects($this->once()) + ->method('set') + ->with('client.flow.v2.login.token', 'token'); + + $this->loginFlowV2Service->method('startLoginFlow') + ->with('token') + ->willReturn(true); + + $this->urlGenerator->method('linkToRouteAbsolute') + ->with('core.ClientFlowLoginV2.showAuthPickerPage') + ->willReturn('https://server/path'); + + $result = $this->controller->landing('token'); + + $this->assertInstanceOf(Http\RedirectResponse::class, $result); + $this->assertSame(Http::STATUS_SEE_OTHER, $result->getStatus()); + $this->assertSame('https://server/path', $result->getRedirectURL()); + } + + public function testShowAuthPickerNoLoginToken() { + $this->session->method('get') + ->willReturn(null); + + $result = $this->controller->showAuthPickerPage(); + + $this->assertSame(Http::STATUS_FORBIDDEN, $result->getStatus()); + } + + public function testShowAuthPickerInvalidLoginToken() { + $this->session->method('get') + ->with('client.flow.v2.login.token') + ->willReturn('loginToken'); + + $this->loginFlowV2Service->method('getByLoginToken') + ->with('loginToken') + ->willThrowException(new LoginFlowV2NotFoundException()); + + $result = $this->controller->showAuthPickerPage(); + + $this->assertSame(Http::STATUS_FORBIDDEN, $result->getStatus()); + } + + public function testShowAuthPickerValidLoginToken() { + $this->session->method('get') + ->with('client.flow.v2.login.token') + ->willReturn('loginToken'); + + $flow = new LoginFlowV2(); + $this->loginFlowV2Service->method('getByLoginToken') + ->with('loginToken') + ->willReturn($flow); + + $this->random->method('generate') + ->with(64, ISecureRandom::CHAR_LOWER.ISecureRandom::CHAR_UPPER.ISecureRandom::CHAR_DIGITS) + ->willReturn('random'); + $this->session->expects($this->once()) + ->method('set') + ->with('client.flow.v2.state.token', 'random'); + + $this->controller->showAuthPickerPage(); + } + + public function testGrantPageInvalidStateToken() { + $this->session->method('get') + ->will($this->returnCallback(function($name) { + return null; + })); + + $result = $this->controller->grantPage('stateToken'); + $this->assertSame(Http::STATUS_FORBIDDEN, $result->getStatus()); + } + + public function testGrantPageInvalidLoginToken() { + $this->session->method('get') + ->will($this->returnCallback(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 LoginFlowV2NotFoundException()); + + $result = $this->controller->grantPage('stateToken'); + $this->assertSame(Http::STATUS_FORBIDDEN, $result->getStatus()); + } + + public function testGrantPageValid() { + $this->session->method('get') + ->will($this->returnCallback(function($name) { + if ($name === 'client.flow.v2.state.token') { + return 'stateToken'; + } + if ($name === 'client.flow.v2.login.token') { + return 'loginToken'; + } + return null; + })); + + $flow = new LoginFlowV2(); + $this->loginFlowV2Service->method('getByLoginToken') + ->with('loginToken') + ->willReturn($flow); + + $result = $this->controller->grantPage('stateToken'); + $this->assertSame(Http::STATUS_OK, $result->getStatus()); + } + + + public function testGenerateAppPasswordInvalidStateToken() { + $this->session->method('get') + ->will($this->returnCallback(function($name) { + return null; + })); + + $result = $this->controller->generateAppPassword('stateToken'); + $this->assertSame(Http::STATUS_FORBIDDEN, $result->getStatus()); + } + + public function testGenerateAppPassworInvalidLoginToken() { + $this->session->method('get') + ->will($this->returnCallback(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 LoginFlowV2NotFoundException()); + + $result = $this->controller->generateAppPassword('stateToken'); + $this->assertSame(Http::STATUS_FORBIDDEN, $result->getStatus()); + } + + public function testGenerateAppPassworValid() { + $this->session->method('get') + ->will($this->returnCallback(function($name) { + if ($name === 'client.flow.v2.state.token') { + return 'stateToken'; + } + if ($name === 'client.flow.v2.login.token') { + return 'loginToken'; + } + return null; + })); + + $flow = new LoginFlowV2(); + $this->loginFlowV2Service->method('getByLoginToken') + ->with('loginToken') + ->willReturn($flow); + + $clearedState = false; + $clearedLogin = false; + $this->session->method('remove') + ->will($this->returnCallback(function ($name) use (&$clearedLogin, &$clearedState) { + if ($name === 'client.flow.v2.state.token') { + $clearedState = true; + } + if ($name === 'client.flow.v2.login.token') { + $clearedLogin = true; + } + })); + + $this->session->method('getId') + ->willReturn('sessionId'); + + $this->loginFlowV2Service->expects($this->once()) + ->method('flowDone') + ->with( + 'loginToken', + 'sessionId', + 'https://server', + 'user' + )->willReturn(true); + + $this->request->method('getServerProtocol') + ->willReturn('https'); + $this->request->method('getRequestUri') + ->willReturn('/login/v2'); + $this->request->method('getServerHost') + ->willReturn('server'); + + $result = $this->controller->generateAppPassword('stateToken'); + $this->assertSame(Http::STATUS_OK, $result->getStatus()); + + $this->assertTrue($clearedLogin); + $this->assertTrue($clearedState); + } +} + diff --git a/tests/Core/Controller/GuestAvatarControllerTest.php b/tests/Core/Controller/GuestAvatarControllerTest.php new file mode 100644 index 00000000000..f720478e499 --- /dev/null +++ b/tests/Core/Controller/GuestAvatarControllerTest.php @@ -0,0 +1,89 @@ +<?php + +namespace Core\Controller; + +use OC\Core\Controller\GuestAvatarController; +use OCP\AppFramework\Http\FileDisplayResponse; +use OCP\Files\SimpleFS\ISimpleFile; +use OCP\IAvatar; +use OCP\IAvatarManager; +use OCP\ILogger; +use OCP\IRequest; + +/** + * This class provides tests for the guest avatar controller. + */ +class GuestAvatarControllerTest extends \Test\TestCase { + + /** + * @var GuestAvatarController + */ + private $guestAvatarController; + + /** + * @var IRequest|\PHPUnit_Framework_MockObject_MockObject + */ + private $request; + + /** + * @var IAvatarManager|\PHPUnit_Framework_MockObject_MockObject + */ + private $avatarManager; + + /** + * @var IAvatar|\PHPUnit_Framework_MockObject_MockObject + */ + private $avatar; + + /** + * @var \OCP\Files\File|\PHPUnit_Framework_MockObject_MockObject + */ + private $file; + + /** + * @var ILogger|\PHPUnit_Framework_MockObject_MockObject + */ + private $logger; + + /** + * Sets up the test environment. + */ + protected function setUp() { + parent::setUp(); + + $this->logger = $this->getMockBuilder(ILogger::class)->getMock(); + $this->request = $this->getMockBuilder(IRequest::class)->getMock(); + $this->avatar = $this->getMockBuilder(IAvatar::class)->getMock(); + $this->avatarManager = $this->getMockBuilder(IAvatarManager::class)->getMock(); + $this->file = $this->getMockBuilder(ISimpleFile::class)->getMock(); + $this->guestAvatarController = new GuestAvatarController( + 'core', + $this->request, + $this->avatarManager, + $this->logger + ); + } + + /** + * Tests getAvatar returns the guest avatar. + */ + public function testGetAvatar() { + $this->avatarManager->expects($this->once()) + ->method('getGuestAvatar') + ->with('Peter') + ->willReturn($this->avatar); + + $this->avatar->expects($this->once()) + ->method('getFile') + ->with(128) + ->willReturn($this->file); + + $this->file->method('getMimeType') + ->willReturn('image/svg+xml'); + + $response = $this->guestAvatarController->getAvatar('Peter', 128); + + $this->assertGreaterThanOrEqual(201, $response->getStatus()); + $this->assertInstanceOf(FileDisplayResponse::class, $response); + } +} diff --git a/tests/Core/Controller/LoginControllerTest.php b/tests/Core/Controller/LoginControllerTest.php index efe85d81e1c..bb21903b653 100644 --- a/tests/Core/Controller/LoginControllerTest.php +++ b/tests/Core/Controller/LoginControllerTest.php @@ -449,6 +449,10 @@ class LoginControllerTest extends TestCase { $this->config->expects($this->once()) ->method('setUserValue') ->with('uid', 'core', 'timezone', 'Europe/Berlin'); + $this->config + ->method('getSystemValue') + ->with('remember_login_cookie_lifetime') + ->willReturn(1234); $this->userSession->expects($this->never()) ->method('createRememberMeToken'); @@ -493,6 +497,10 @@ class LoginControllerTest extends TestCase { $this->config->expects($this->once()) ->method('deleteUserValue') ->with('uid', 'core', 'lostpassword'); + $this->config + ->method('getSystemValue') + ->with('remember_login_cookie_lifetime') + ->willReturn(1234); $this->userSession->expects($this->once()) ->method('createRememberMeToken') ->with($user); @@ -553,6 +561,10 @@ class LoginControllerTest extends TestCase { ->method('deleteUserValue'); $this->userSession->expects($this->never()) ->method('createRememberMeToken'); + $this->config + ->method('getSystemValue') + ->with('remember_login_cookie_lifetime') + ->willReturn(1234); $expected = new \OCP\AppFramework\Http\RedirectResponse($redirectUrl); $this->assertEquals($expected, $this->loginController->tryLogin('Jane', $password, $originalUrl)); @@ -590,6 +602,10 @@ class LoginControllerTest extends TestCase { $this->config->expects($this->once()) ->method('deleteUserValue') ->with('jane', 'core', 'lostpassword'); + $this->config + ->method('getSystemValue') + ->with('remember_login_cookie_lifetime') + ->willReturn(1234); $expected = new \OCP\AppFramework\Http\RedirectResponse(urldecode($redirectUrl)); $this->assertEquals($expected, $this->loginController->tryLogin('Jane', $password, $originalUrl)); @@ -642,6 +658,10 @@ class LoginControllerTest extends TestCase { $this->config->expects($this->once()) ->method('deleteUserValue') ->with('john', 'core', 'lostpassword'); + $this->config + ->method('getSystemValue') + ->with('remember_login_cookie_lifetime') + ->willReturn(1234); $this->userSession->expects($this->never()) ->method('createRememberMeToken'); @@ -694,6 +714,10 @@ class LoginControllerTest extends TestCase { $this->config->expects($this->once()) ->method('deleteUserValue') ->with('john', 'core', 'lostpassword'); + $this->config + ->method('getSystemValue') + ->with('remember_login_cookie_lifetime') + ->willReturn(1234); $this->userSession->expects($this->never()) ->method('createRememberMeToken'); diff --git a/tests/Core/Controller/LostControllerTest.php b/tests/Core/Controller/LostControllerTest.php index 91b52fc8efa..8635616a9d5 100644 --- a/tests/Core/Controller/LostControllerTest.php +++ b/tests/Core/Controller/LostControllerTest.php @@ -21,6 +21,7 @@ namespace Tests\Core\Controller; +use OC\Authentication\TwoFactorAuth\Manager; use OC\Core\Controller\LostController; use OC\Mail\Message; use OCP\AppFramework\Http\JSONResponse; @@ -31,6 +32,7 @@ use OCP\Encryption\IEncryptionModule; use OCP\Encryption\IManager; use OCP\IConfig; use OCP\IL10N; +use OCP\ILogger; use OCP\IRequest; use OCP\IURLGenerator; use OCP\IUser; @@ -74,6 +76,10 @@ class LostControllerTest extends \Test\TestCase { 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; protected function setUp() { parent::setUp(); @@ -124,6 +130,8 @@ class LostControllerTest extends \Test\TestCase { ->method('isEnabled') ->willReturn(true); $this->crypto = $this->createMock(ICrypto::class); + $this->logger = $this->createMock(ILogger::class); + $this->twofactorManager = $this->createMock(Manager::class); $this->lostController = new LostController( 'Core', $this->request, @@ -137,7 +145,9 @@ class LostControllerTest extends \Test\TestCase { $this->encryptionManager, $this->mailer, $this->timeFactory, - $this->crypto + $this->crypto, + $this->logger, + $this->twofactorManager ); } @@ -265,6 +275,9 @@ class LostControllerTest extends \Test\TestCase { array(false, $nonExistingUser) ))); + $this->logger->expects($this->exactly(2)) + ->method('logException'); + $this->userManager ->method('getByEmail') ->willReturn([]); @@ -272,8 +285,7 @@ class LostControllerTest extends \Test\TestCase { // With a non existing user $response = $this->lostController->email($nonExistingUser); $expectedResponse = new JSONResponse([ - 'status' => 'error', - 'msg' => 'Couldn\'t send reset email. Please make sure your username is correct.' + 'status' => 'success', ]); $expectedResponse->throttle(); $this->assertEquals($expectedResponse, $response); @@ -286,8 +298,7 @@ class LostControllerTest extends \Test\TestCase { ->will($this->returnValue(null)); $response = $this->lostController->email($existingUser); $expectedResponse = new JSONResponse([ - 'status' => 'error', - 'msg' => 'Couldn\'t send reset email. Please make sure your username is correct.' + 'status' => 'success', ]); $expectedResponse->throttle(); $this->assertEquals($expectedResponse, $response); @@ -511,8 +522,11 @@ class LostControllerTest extends \Test\TestCase { $this->equalTo('test@example.comSECRET') )->willReturn('encryptedToken'); + $this->logger->expects($this->exactly(1)) + ->method('logException'); + $response = $this->lostController->email('ExistingUser'); - $expectedResponse = new JSONResponse(['status' => 'error', 'msg' => 'Couldn\'t send reset email. Please contact your administrator.']); + $expectedResponse = new JSONResponse(['status' => 'success']); $expectedResponse->throttle(); $this->assertEquals($expectedResponse, $response); } @@ -708,8 +722,11 @@ class LostControllerTest extends \Test\TestCase { ->with('ExistingUser') ->willReturn($user); + $this->logger->expects($this->exactly(1)) + ->method('logException'); + $response = $this->lostController->email('ExistingUser'); - $expectedResponse = new JSONResponse(['status' => 'error', 'msg' => 'Could not send reset email because there is no email address for this username. Please contact your administrator.']); + $expectedResponse = new JSONResponse(['status' => 'success']); $expectedResponse->throttle(); $this->assertEquals($expectedResponse, $response); } @@ -790,12 +807,14 @@ class LostControllerTest extends \Test\TestCase { ->method('getByEmail') ->willReturn([$user1, $user2]); + $this->logger->expects($this->exactly(1)) + ->method('logException'); + // request password reset for test@example.com $response = $this->lostController->email('test@example.com'); $expectedResponse = new JSONResponse([ - 'status' => 'error', - 'msg' => 'Couldn\'t send reset email. Please make sure your username is correct.' + 'status' => 'success' ]); $expectedResponse->throttle(); diff --git a/tests/Core/Controller/TwoFactorChallengeControllerTest.php b/tests/Core/Controller/TwoFactorChallengeControllerTest.php index 6a01c510ed2..a405914cc47 100644 --- a/tests/Core/Controller/TwoFactorChallengeControllerTest.php +++ b/tests/Core/Controller/TwoFactorChallengeControllerTest.php @@ -27,7 +27,7 @@ use OC\Authentication\TwoFactorAuth\ProviderSet; use OC\Core\Controller\TwoFactorChallengeController; use OC_Util; use OCP\AppFramework\Http\RedirectResponse; -use OCP\AppFramework\Http\TemplateResponse; +use OCP\AppFramework\Http\StandaloneTemplateResponse; use OCP\Authentication\TwoFactorAuth\IProvider; use OCP\Authentication\TwoFactorAuth\TwoFactorException; use OCP\IRequest; @@ -100,7 +100,7 @@ class TwoFactorChallengeControllerTest extends TestCase { ->with($user) ->will($this->returnValue($providerSet)); - $expected = new TemplateResponse('core', 'twofactorselectchallenge', [ + $expected = new StandaloneTemplateResponse('core', 'twofactorselectchallenge', [ 'providers' => [ $p1, ], @@ -151,7 +151,7 @@ class TwoFactorChallengeControllerTest extends TestCase { ->method('fetchPage') ->will($this->returnValue('<html/>')); - $expected = new TemplateResponse('core', 'twofactorshowchallenge', [ + $expected = new StandaloneTemplateResponse('core', 'twofactorshowchallenge', [ 'error' => true, 'provider' => $provider, 'backupProvider' => $backupProvider, diff --git a/tests/Settings/Controller/AppSettingsControllerTest.php b/tests/Settings/Controller/AppSettingsControllerTest.php index 14e537437ff..7ae815cc4fa 100644 --- a/tests/Settings/Controller/AppSettingsControllerTest.php +++ b/tests/Settings/Controller/AppSettingsControllerTest.php @@ -44,6 +44,8 @@ use OCP\App\IAppManager; * Class AppSettingsControllerTest * * @package Tests\Settings\Controller + * + * @group DB */ class AppSettingsControllerTest extends TestCase { /** @var AppSettingsController */ diff --git a/tests/Settings/Controller/AuthSettingsControllerTest.php b/tests/Settings/Controller/AuthSettingsControllerTest.php index 1c957299e39..198b3a72c33 100644 --- a/tests/Settings/Controller/AuthSettingsControllerTest.php +++ b/tests/Settings/Controller/AuthSettingsControllerTest.php @@ -1,5 +1,4 @@ <?php - /** * @author Christoph Wurst <christoph@owncloud.com> * @@ -28,11 +27,12 @@ use OC\Authentication\Token\DefaultToken; use OC\Authentication\Token\IProvider; use OC\Authentication\Token\IToken; use OC\Settings\Controller\AuthSettingsController; +use OCP\Activity\IEvent; +use OCP\Activity\IManager; use OCP\AppFramework\Http\JSONResponse; +use OCP\ILogger; use OCP\IRequest; use OCP\ISession; -use OCP\IUser; -use OCP\IUserManager; use OCP\Security\ISecureRandom; use OCP\Session\Exceptions\SessionNotAvailableException; use Test\TestCase; @@ -41,71 +41,39 @@ class AuthSettingsControllerTest extends TestCase { /** @var AuthSettingsController */ private $controller; + /** @var IRequest|\PHPUnit_Framework_MockObject_MockObject */ private $request; /** @var IProvider|\PHPUnit_Framework_MockObject_MockObject */ private $tokenProvider; - private $userManager; + /** @var ISession|\PHPUnit_Framework_MockObject_MockObject */ private $session; + /** @var ISecureRandom|\PHPUnit_Framework_MockObject_MockObject */ private $secureRandom; - private $uid; + /** @var IManager|\PHPUnit_Framework_MockObject_MockObject */ + private $activityManager; + private $uid = 'jane'; protected function setUp() { parent::setUp(); $this->request = $this->createMock(IRequest::class); $this->tokenProvider = $this->createMock(IProvider::class); - $this->userManager = $this->createMock(IUserManager::class); $this->session = $this->createMock(ISession::class); $this->secureRandom = $this->createMock(ISecureRandom::class); - $this->uid = 'jane'; - $this->user = $this->createMock(IUser::class); - - $this->controller = new AuthSettingsController('core', $this->request, $this->tokenProvider, $this->userManager, $this->session, $this->secureRandom, $this->uid); - } - - public function testIndex() { - $token1 = new DefaultToken(); - $token1->setId(100); - $token2 = new DefaultToken(); - $token2->setId(200); - $tokens = [ - $token1, - $token2, - ]; - $sessionToken = new DefaultToken(); - $sessionToken->setId(100); - - $this->tokenProvider->expects($this->once()) - ->method('getTokenByUser') - ->with($this->uid) - ->will($this->returnValue($tokens)); - $this->session->expects($this->once()) - ->method('getId') - ->will($this->returnValue('session123')); - $this->tokenProvider->expects($this->once()) - ->method('getToken') - ->with('session123') - ->will($this->returnValue($sessionToken)); - - $this->assertEquals([ - [ - 'id' => 100, - 'name' => null, - 'lastActivity' => 0, - 'type' => 0, - 'canDelete' => false, - 'current' => true, - 'scope' => ['filesystem' => true] - ], - [ - 'id' => 200, - 'name' => null, - 'lastActivity' => 0, - 'type' => 0, - 'canDelete' => true, - 'scope' => ['filesystem' => true] - ] - ], $this->controller->index()); + $this->activityManager = $this->createMock(IManager::class); + /** @var ILogger|\PHPUnit_Framework_MockObject_MockObject $logger */ + $logger = $this->createMock(ILogger::class); + + $this->controller = new AuthSettingsController( + 'core', + $this->request, + $this->tokenProvider, + $this->session, + $this->secureRandom, + $this->uid, + $this->activityManager, + $logger + ); } public function testCreate() { @@ -116,39 +84,42 @@ class AuthSettingsControllerTest extends TestCase { $this->session->expects($this->once()) ->method('getId') - ->will($this->returnValue('sessionid')); + ->willReturn('sessionid'); $this->tokenProvider->expects($this->once()) ->method('getToken') ->with('sessionid') - ->will($this->returnValue($sessionToken)); + ->willReturn($sessionToken); $this->tokenProvider->expects($this->once()) ->method('getPassword') ->with($sessionToken, 'sessionid') - ->will($this->returnValue($password)); + ->willReturn($password); $sessionToken->expects($this->once()) ->method('getLoginName') - ->will($this->returnValue('User13')); + ->willReturn('User13'); $this->secureRandom->expects($this->exactly(5)) ->method('generate') ->with(5, ISecureRandom::CHAR_HUMAN_READABLE) - ->will($this->returnValue('XXXXX')); + ->willReturn('XXXXX'); $newToken = 'XXXXX-XXXXX-XXXXX-XXXXX-XXXXX'; $this->tokenProvider->expects($this->once()) ->method('generateToken') ->with($newToken, $this->uid, 'User13', $password, $name, IToken::PERMANENT_TOKEN) - ->will($this->returnValue($deviceToken)); + ->willReturn($deviceToken); $deviceToken->expects($this->once()) ->method('jsonSerialize') - ->will($this->returnValue(['dummy' => 'dummy', 'canDelete' => true])); + ->willReturn(['dummy' => 'dummy', 'canDelete' => true]); + + $this->mockActivityManager(); $expected = [ 'token' => $newToken, - 'deviceToken' => ['dummy' => 'dummy', 'canDelete' => true], + 'deviceToken' => ['dummy' => 'dummy', 'canDelete' => true, 'canRename' => true], 'loginName' => 'User13', ]; + $response = $this->controller->create($name); $this->assertInstanceOf(JSONResponse::class, $response); $this->assertEquals($expected, $response->getData()); @@ -172,7 +143,7 @@ class AuthSettingsControllerTest extends TestCase { $this->session->expects($this->once()) ->method('getId') - ->will($this->returnValue('sessionid')); + ->willReturn('sessionid'); $this->tokenProvider->expects($this->once()) ->method('getToken') ->with('sessionid') @@ -185,48 +156,162 @@ class AuthSettingsControllerTest extends TestCase { } public function testDestroy() { - $id = 123; - $user = $this->createMock(IUser::class); + $tokenId = 124; + $token = $this->createMock(DefaultToken::class); + + $this->mockGetTokenById($tokenId, $token); + $this->mockActivityManager(); + + $token->expects($this->exactly(2)) + ->method('getId') + ->willReturn($tokenId); + + $token->expects($this->once()) + ->method('getUID') + ->willReturn('jane'); $this->tokenProvider->expects($this->once()) ->method('invalidateTokenById') - ->with($this->uid, $id); + ->with($this->uid, $tokenId); + + $this->assertEquals([], $this->controller->destroy($tokenId)); + } + + public function testDestroyWrongUser() { + $tokenId = 124; + $token = $this->createMock(DefaultToken::class); + + $this->mockGetTokenById($tokenId, $token); + + $token->expects($this->once()) + ->method('getUID') + ->willReturn('foobar'); - $this->assertEquals([], $this->controller->destroy($id)); + $response = $this->controller->destroy($tokenId); + $this->assertSame([], $response->getData()); + $this->assertSame(\OCP\AppFramework\Http::STATUS_NOT_FOUND, $response->getStatus()); + } + + public function dataRenameToken(): array { + return [ + 'App password => Other token name' => ['App password', 'Other token name'], + 'Other token name => App password' => ['Other token name', 'App password'], + ]; } - public function testUpdateToken() { + /** + * @dataProvider dataRenameToken + * @param string $name + * @param string $newName + */ + public function testUpdateRename(string $name, string $newName): void { + $tokenId = 42; $token = $this->createMock(DefaultToken::class); + $this->mockGetTokenById($tokenId, $token); + $this->mockActivityManager(); + + $token->expects($this->once()) + ->method('getUID') + ->willReturn('jane'); + + $token->expects($this->once()) + ->method('getName') + ->willReturn($name); + + $token->expects($this->once()) + ->method('getScopeAsArray') + ->willReturn(['filesystem' => true]); + + $token->expects($this->once()) + ->method('setName') + ->with($this->equalTo($newName)); + $this->tokenProvider->expects($this->once()) - ->method('getTokenById') - ->with($this->equalTo(42)) - ->willReturn($token); + ->method('updateToken') + ->with($this->equalTo($token)); + + $this->assertSame([], $this->controller->update($tokenId, ['filesystem' => true], $newName)); + } + + public function dataUpdateFilesystemScope(): array { + return [ + 'Grant filesystem access' => [false, true], + 'Revoke filesystem access' => [true, false], + ]; + } + + /** + * @dataProvider dataUpdateFilesystemScope + * @param bool $filesystem + * @param bool $newFilesystem + */ + public function testUpdateFilesystemScope(bool $filesystem, bool $newFilesystem): void { + $tokenId = 42; + $token = $this->createMock(DefaultToken::class); + + $this->mockGetTokenById($tokenId, $token); + $this->mockActivityManager(); $token->expects($this->once()) ->method('getUID') ->willReturn('jane'); $token->expects($this->once()) + ->method('getName') + ->willReturn('App password'); + + $token->expects($this->once()) + ->method('getScopeAsArray') + ->willReturn(['filesystem' => $filesystem]); + + $token->expects($this->once()) ->method('setScope') - ->with($this->equalTo([ - 'filesystem' => true - ])); + ->with($this->equalTo(['filesystem' => $newFilesystem])); $this->tokenProvider->expects($this->once()) ->method('updateToken') ->with($this->equalTo($token)); - $this->assertSame([], $this->controller->update(42, ['filesystem' => true])); + $this->assertSame([], $this->controller->update($tokenId, ['filesystem' => $newFilesystem], 'App password')); } - public function testUpdateTokenWrongUser() { + public function testUpdateNoChange(): void { + $tokenId = 42; $token = $this->createMock(DefaultToken::class); + $this->mockGetTokenById($tokenId, $token); + + $token->expects($this->once()) + ->method('getUID') + ->willReturn('jane'); + + $token->expects($this->once()) + ->method('getName') + ->willReturn('App password'); + + $token->expects($this->once()) + ->method('getScopeAsArray') + ->willReturn(['filesystem' => true]); + + $token->expects($this->never()) + ->method('setName'); + + $token->expects($this->never()) + ->method('setScope'); + $this->tokenProvider->expects($this->once()) - ->method('getTokenById') - ->with($this->equalTo(42)) - ->willReturn($token); + ->method('updateToken') + ->with($this->equalTo($token)); + + $this->assertSame([], $this->controller->update($tokenId, ['filesystem' => true], 'App password')); + } + + public function testUpdateTokenWrongUser() { + $tokenId = 42; + $token = $this->createMock(DefaultToken::class); + + $this->mockGetTokenById($tokenId, $token); $token->expects($this->once()) ->method('getUID') @@ -237,7 +322,7 @@ class AuthSettingsControllerTest extends TestCase { $this->tokenProvider->expects($this->never()) ->method('updateToken'); - $response = $this->controller->update(42, ['filesystem' => true]); + $response = $this->controller->update($tokenId, ['filesystem' => true], 'App password'); $this->assertSame([], $response->getData()); $this->assertSame(\OCP\AppFramework\Http::STATUS_NOT_FOUND, $response->getStatus()); } @@ -251,9 +336,27 @@ class AuthSettingsControllerTest extends TestCase { $this->tokenProvider->expects($this->never()) ->method('updateToken'); - $response = $this->controller->update(42, ['filesystem' => true]); + $response = $this->controller->update(42, ['filesystem' => true], 'App password'); $this->assertSame([], $response->getData()); $this->assertSame(\OCP\AppFramework\Http::STATUS_NOT_FOUND, $response->getStatus()); } + private function mockActivityManager(): void { + $this->activityManager->expects($this->once()) + ->method('generateEvent') + ->willReturn($this->createMock(IEvent::class)); + $this->activityManager->expects($this->once()) + ->method('publish'); + } + + /** + * @param int $tokenId + * @param $token + */ + private function mockGetTokenById(int $tokenId, $token): void { + $this->tokenProvider->expects($this->once()) + ->method('getTokenById') + ->with($this->equalTo($tokenId)) + ->willReturn($token); + } } diff --git a/tests/Settings/Controller/CheckSetupControllerTest.php b/tests/Settings/Controller/CheckSetupControllerTest.php index 01d2178fd7f..dd13b29697d 100644 --- a/tests/Settings/Controller/CheckSetupControllerTest.php +++ b/tests/Settings/Controller/CheckSetupControllerTest.php @@ -148,7 +148,6 @@ class CheckSetupControllerTest extends TestCase { 'hasWorkingFileLocking', 'getLastCronInfo', 'getSuggestedOverwriteCliURL', - 'getOutdatedCaches', 'getCurlVersion', 'isPhpOutdated', 'isOpcacheProperlySetup', @@ -160,6 +159,7 @@ class CheckSetupControllerTest extends TestCase { 'getAppDirsWithDifferentOwner', 'hasRecommendedPHPModules', 'hasBigIntConversionPendingColumns', + 'isMysqlUsedWithoutUTF8MB4', ])->getMock(); } @@ -311,19 +311,21 @@ class CheckSetupControllerTest extends TestCase { * @dataProvider dataForwardedForHeadersWorking * * @param array $trustedProxies - * @param string $remoteAddrNoForwarded + * @param string $remoteAddrNotForwarded * @param string $remoteAddr * @param bool $result */ - public function testForwardedForHeadersWorking(array $trustedProxies, string $remoteAddrNoForwarded, string $remoteAddr, bool $result) { + public function testForwardedForHeadersWorking(array $trustedProxies, string $remoteAddrNotForwarded, string $remoteAddr, bool $result) { $this->config->expects($this->once()) ->method('getSystemValue') ->with('trusted_proxies', []) ->willReturn($trustedProxies); - $this->request->expects($this->once()) + $this->request->expects($this->atLeastOnce()) ->method('getHeader') - ->with('REMOTE_ADDR') - ->willReturn($remoteAddrNoForwarded); + ->willReturnMap([ + ['REMOTE_ADDR', $remoteAddrNotForwarded], + ['X-Forwarded-Host', ''] + ]); $this->request->expects($this->any()) ->method('getRemoteAddress') ->willReturn($remoteAddr); @@ -344,6 +346,27 @@ class CheckSetupControllerTest extends TestCase { ]; } + public function testForwardedHostPresentButTrustedProxiesEmpty() { + $this->config->expects($this->once()) + ->method('getSystemValue') + ->with('trusted_proxies', []) + ->willReturn([]); + $this->request->expects($this->atLeastOnce()) + ->method('getHeader') + ->willReturnMap([ + ['REMOTE_ADDR', '1.1.1.1'], + ['X-Forwarded-Host', 'nextcloud.test'] + ]); + $this->request->expects($this->any()) + ->method('getRemoteAddress') + ->willReturn('1.1.1.1'); + + $this->assertEquals( + false, + self::invokePrivate($this->checkSetupController, 'forwardedForHeadersWorking') + ); + } + public function testCheck() { $this->config->expects($this->at(0)) ->method('getAppValue') @@ -366,10 +389,12 @@ class CheckSetupControllerTest extends TestCase { ->with('appstoreenabled', true) ->will($this->returnValue(false)); - $this->request->expects($this->once()) + $this->request->expects($this->atLeastOnce()) ->method('getHeader') - ->with('REMOTE_ADDR') - ->willReturn('4.3.2.1'); + ->willReturnMap([ + ['REMOTE_ADDR', '4.3.2.1'], + ['X-Forwarded-Host', ''] + ]); $client = $this->getMockBuilder('\OCP\Http\Client\IClient') ->disableOriginalConstructor()->getMock(); @@ -435,9 +460,6 @@ class CheckSetupControllerTest extends TestCase { ->method('hasMissingIndexes') ->willReturn([]); $this->checkSetupController - ->method('getOutdatedCaches') - ->willReturn([]); - $this->checkSetupController ->method('isSqliteUsed') ->willReturn(false); $this->checkSetupController @@ -499,12 +521,16 @@ class CheckSetupControllerTest extends TestCase { ->method('hasBigIntConversionPendingColumns') ->willReturn([]); + $this->checkSetupController + ->expects($this->once()) + ->method('isMysqlUsedWithoutUTF8MB4') + ->willReturn(false); + $expected = new DataResponse( [ 'isGetenvServerWorking' => true, 'isReadOnlyConfig' => false, 'hasValidTransactionIsolationLevel' => true, - 'outdatedCaches' => [], 'hasFileinfoInstalled' => true, 'hasWorkingFileLocking' => true, 'suggestedOverwriteCliURL' => '', @@ -543,6 +569,7 @@ class CheckSetupControllerTest extends TestCase { 'appDirsWithDifferentOwner' => [], 'recommendedPHPModules' => [], 'pendingBigIntConversionColumns' => [], + 'isMysqlUsedWithoutUTF8MB4' => false, ] ); $this->assertEquals($expected, $this->checkSetupController->check()); @@ -1324,4 +1351,53 @@ Array ); $this->assertEquals($expected, $this->checkSetupController->getFailedIntegrityCheckFiles()); } + + public function dataForIsMysqlUsedWithoutUTF8MB4() { + return [ + ['sqlite', false, false], + ['sqlite', true, false], + ['postgres', false, false], + ['postgres', true, false], + ['oci', false, false], + ['oci', true, false], + ['mysql', false, true], + ['mysql', true, false], + ]; + } + + /** + * @dataProvider dataForIsMysqlUsedWithoutUTF8MB4 + */ + public function testIsMysqlUsedWithoutUTF8MB4(string $db, bool $useUTF8MB4, bool $expected) { + $this->config->method('getSystemValue') + ->will($this->returnCallback(function($key, $default) use ($db, $useUTF8MB4) { + if ($key === 'dbtype') { + return $db; + } + if ($key === 'mysql.utf8mb4') { + return $useUTF8MB4; + } + return $default; + })); + + $checkSetupController = new CheckSetupController( + 'settings', + $this->request, + $this->config, + $this->clientService, + $this->urlGenerator, + $this->util, + $this->l10n, + $this->checker, + $this->logger, + $this->dispatcher, + $this->db, + $this->lockingProvider, + $this->dateTimeFormatter, + $this->memoryInfo, + $this->secureRandom + ); + + $this->assertSame($expected, $this->invokePrivate($checkSetupController, 'isMysqlUsedWithoutUTF8MB4')); + } } diff --git a/tests/Settings/Controller/ServerInfoSettingsControllerTest.php b/tests/Settings/Controller/ServerInfoSettingsControllerTest.php new file mode 100644 index 00000000000..8d2083d0acb --- /dev/null +++ b/tests/Settings/Controller/ServerInfoSettingsControllerTest.php @@ -0,0 +1,94 @@ +<?php +/** + * @copyright Copyright (c) 2018 Michael Weimann <mail@michael-weimann.eu> + * + * @author Michael Weimann <mail@michael-weimann.eu> + * + * @license GNU AGPL version 3 or any later version + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +namespace Settings\Controller; + +use OC\Settings\Theming\ServerInfo; +use OC\Settings\Controller\ServerInfoSettingsController; +use OCP\IConfig; +use OCP\IRequest; +use PHPUnit\Framework\MockObject\MockObject; +use Test\TestCase; + +/** + * This class provides tests for the server info settings controller. + */ +class ServerInfoSettingsControllerTest extends TestCase { + + /** + * @var IConfig|MockObject + */ + private $config; + + /** + * @var ServerInfoSettingsController + */ + private $controller; + + /** + * Does the test setup. + */ + protected function setUp() { + parent::setUp(); + + $request = $this->getMockBuilder(IRequest::class)->getMock(); + /* @var IRequest|MockObject $request */ + $this->config = $this->getMockBuilder(IConfig::class)->getMock(); + $this->controller = new ServerInfoSettingsController( + 'settings', + $request, + $this->config + ); + } + + /** + * Tests that the handler passes the params to the config. + */ + public function testStoreServerInfo() { + + $location = 'test-location'; + $provider = 'test-provider'; + $providerWebsite = 'https://example.com/'; + $providerPrivacyLink = 'https://example.com/privacy'; + $adminContact = 'testuser'; + + $this->config->expects($this->once()) + ->method('setSystemValues') + ->with([ + ServerInfo::SETTING_LOCATION => $location, + ServerInfo::SETTING_PROVIDER => $provider, + ServerInfo::SETTING_PROVIDER_WEBSITE => $providerWebsite, + ServerInfo::SETTING_PROVIDER_PRIVACY_LINK => $providerPrivacyLink, + ServerInfo::SETTING_PROVIDER_ADMIN_CONTACT => $adminContact, + ]); + + $this->controller->storeServerInfo( + $location, + $provider, + $providerWebsite, + $providerPrivacyLink, + $adminContact + ); + + } + +} diff --git a/tests/Settings/Controller/UsersControllerTest.php b/tests/Settings/Controller/UsersControllerTest.php index 74ac990be92..8294514fa50 100644 --- a/tests/Settings/Controller/UsersControllerTest.php +++ b/tests/Settings/Controller/UsersControllerTest.php @@ -11,6 +11,7 @@ namespace Tests\Settings\Controller; use OC\Accounts\AccountManager; +use OC\Encryption\Exceptions\ModuleDoesNotExistsException; use OC\Group\Group; use OC\Group\Manager; use OC\Settings\Controller\UsersController; @@ -98,7 +99,7 @@ class UsersControllerTest extends \Test\TestCase { $this->securityManager = $this->getMockBuilder(\OC\Security\IdentityProof\Manager::class)->disableOriginalConstructor()->getMock(); $this->jobList = $this->createMock(IJobList::class); $this->encryptionManager = $this->createMock(IManager::class); - + $this->l->method('t') ->will($this->returnCallback(function ($text, $parameters = []) { return vsprintf($text, $parameters); @@ -513,4 +514,49 @@ class UsersControllerTest extends \Test\TestCase { $this->assertSame(Http::STATUS_BAD_REQUEST, $result->getStatus()); } + /** + * @dataProvider dataTestCanAdminChangeUserPasswords + * + * @param bool $encryptionEnabled + * @param bool $encryptionModuleLoaded + * @param bool $masterKeyEnabled + * @param bool $expected + */ + public function testCanAdminChangeUserPasswords($encryptionEnabled, + $encryptionModuleLoaded, + $masterKeyEnabled, + $expected) { + $controller = $this->getController(); + + $this->encryptionManager->expects($this->any()) + ->method('isEnabled') + ->willReturn($encryptionEnabled); + $this->encryptionManager->expects($this->any()) + ->method('getEncryptionModule') + ->willReturnCallback(function() use ($encryptionModuleLoaded) { + if ($encryptionModuleLoaded) return $this->encryptionModule; + else throw new ModuleDoesNotExistsException(); + }); + $this->encryptionModule->expects($this->any()) + ->method('needDetailedAccessList') + ->willReturn(!$masterKeyEnabled); + + $result = $this->invokePrivate($controller, 'canAdminChangeUserPasswords', []); + $this->assertSame($expected, $result); + } + + public function dataTestCanAdminChangeUserPasswords() { + return [ + // encryptionEnabled, encryptionModuleLoaded, masterKeyEnabled, expectedResult + [true, true, true, true], + [false, true, true, true], + [true, false, true, false], + [false, false, true, true], + [true, true, false, false], + [false, true, false, false], + [true, false, false, false], + [false, false, false, true], + ]; + } + } diff --git a/tests/acceptance/config/behat.yml b/tests/acceptance/config/behat.yml index acb404aae26..182629701e8 100644 --- a/tests/acceptance/config/behat.yml +++ b/tests/acceptance/config/behat.yml @@ -15,6 +15,7 @@ default: - DialogContext - FeatureContext - FileListContext + - FilePickerContext - FilesAppContext - FilesAppSharingContext - LoginPageContext @@ -43,6 +44,7 @@ default: - DialogContext - FeatureContext - FileListContext + - FilePickerContext - FilesAppContext - FilesAppSharingContext - LoginPageContext diff --git a/tests/acceptance/features/app-comments.feature b/tests/acceptance/features/app-comments.feature index ee60ece1cec..2980d63ccd1 100644 --- a/tests/acceptance/features/app-comments.feature +++ b/tests/acceptance/features/app-comments.feature @@ -16,7 +16,7 @@ Feature: app-comments And I see a comment with "Hello world" as message When I open the details view for "Folder" # The "Comments" tab should already be opened - Then I see that there are no comments +# Then I see that there are no comments Scenario: write a comment in a file right after writing a comment in another file Given I am logged in diff --git a/tests/acceptance/features/app-files-tags.feature b/tests/acceptance/features/app-files-tags.feature index d606c7a88a4..89599d5f51c 100644 --- a/tests/acceptance/features/app-files-tags.feature +++ b/tests/acceptance/features/app-files-tags.feature @@ -31,7 +31,7 @@ Feature: app-files-tags Scenario: create tags using the Administration settings Given I am logged in as the admin And I visit the settings page - And I open the "Workflow" section + And I open the "Tag management" section # The "create" button does nothing before JavaScript was initialized, and # the only way to detect that is waiting for the button to select tags to be # shown. @@ -42,7 +42,7 @@ Feature: app-files-tags Scenario: add tags using the dropdown in the details view Given I am logged in as the admin And I visit the settings page - And I open the "Workflow" section + And I open the "Tag management" section # The "create" button does nothing before JavaScript was initialized, and # the only way to detect that is waiting for the button to select tags to be # shown. @@ -70,7 +70,7 @@ Feature: app-files-tags Scenario: remove tags using the dropdown in the details view Given I am logged in as the admin And I visit the settings page - And I open the "Workflow" section + And I open the "Tag management" section # The "create" button does nothing before JavaScript was initialized, and # the only way to detect that is waiting for the button to select tags to be # shown. diff --git a/tests/acceptance/features/app-files.feature b/tests/acceptance/features/app-files.feature index 7d216ffc1f4..c6d879dc6ef 100644 --- a/tests/acceptance/features/app-files.feature +++ b/tests/acceptance/features/app-files.feature @@ -1,3 +1,4 @@ +@apache Feature: app-files Scenario: open and close the details view @@ -140,6 +141,101 @@ Feature: app-files Then I see that the current section is "Deleted files" Then I see that the file list contains a file named "welcome.txt" + Scenario: move a file to another folder + Given I am logged in + And I create a new folder named "Destination" + When I start the move or copy operation for "welcome.txt" + And I select "Destination" in the file picker + And I move to the last selected folder in the file picker + Then I see that the file list does not contain a file named "welcome.txt" + And I enter in the folder named "Destination" + And I see that the file list contains a file named "welcome.txt" + + Scenario: move a selection to another folder + Given I am logged in + And I create a new folder named "Folder" + And I create a new folder named "Not selected folder" + And I create a new folder named "Destination" + When I select "welcome.txt" + And I select "Folder" + And I start the move or copy operation for the selected files + And I select "Destination" in the file picker + And I move to the last selected folder in the file picker + Then I see that the file list does not contain a file named "welcome.txt" + And I see that the file list does not contain a file named "Folder" + And I see that the file list contains a file named "Not selected folder" + And I enter in the folder named "Destination" + And I see that the file list contains a file named "welcome.txt" + And I see that the file list contains a file named "Folder" + And I see that the file list does not contain a file named "Not selected folder" + + Scenario: copy a file to another folder + Given I am logged in + And I create a new folder named "Destination" + When I start the move or copy operation for "welcome.txt" + And I select "Destination" in the file picker + And I copy to the last selected folder in the file picker + Then I enter in the folder named "Destination" + # The file will appear in the destination once the copy operation finishes + And I see that the file list contains a file named "welcome.txt" + # The Files app is open again to reload the file list in the root folder + And I open the Files app + And I see that the file list contains a file named "welcome.txt" + + Scenario: copy a selection to another folder + Given I am logged in + And I create a new folder named "Folder" + And I create a new folder named "Not selected folder" + And I create a new folder named "Destination" + When I select "welcome.txt" + And I select "Folder" + And I start the move or copy operation for the selected files + And I select "Destination" in the file picker + And I copy to the last selected folder in the file picker + Then I enter in the folder named "Destination" + # The files will appear in the destination once the copy operation finishes + And I see that the file list contains a file named "welcome.txt" + And I see that the file list contains a file named "Folder" + And I see that the file list does not contain a file named "Not selected folder" + # The Files app is open again to reload the file list in the root folder + And I open the Files app + And I see that the file list contains a file named "welcome.txt" + And I see that the file list contains a file named "Folder" + And I see that the file list contains a file named "Not selected folder" + + Scenario: copy a file in its same folder + Given I am logged in + When I start the move or copy operation for "welcome.txt" + # No folder was explicitly selected, so the last selected folder is the + # current folder. + And I copy to the last selected folder in the file picker + Then I see that the file list contains a file named "welcome.txt" + And I see that the file list contains a file named "welcome (copy).txt" + + Scenario: copy a file twice in its same folder + Given I am logged in + And I start the move or copy operation for "welcome.txt" + # No folder was explicitly selected, so the last selected folder is the + # current folder. + And I copy to the last selected folder in the file picker + When I start the move or copy operation for "welcome.txt" + And I copy to the last selected folder in the file picker + Then I see that the file list contains a file named "welcome.txt" + And I see that the file list contains a file named "welcome (copy).txt" + And I see that the file list contains a file named "welcome (copy 2).txt" + + Scenario: copy a copy of a file in its same folder + Given I am logged in + And I start the move or copy operation for "welcome.txt" + # No folder was explicitly selected, so the last selected folder is the + # current folder. + And I copy to the last selected folder in the file picker + When I start the move or copy operation for "welcome (copy).txt" + And I copy to the last selected folder in the file picker + Then I see that the file list contains a file named "welcome.txt" + And I see that the file list contains a file named "welcome (copy).txt" + And I see that the file list contains a file named "welcome (copy 2).txt" + Scenario: rename a file with the details view open Given I am logged in And I open the details view for "welcome.txt" diff --git a/tests/acceptance/features/apps.feature b/tests/acceptance/features/apps.feature index 33e9e15dad2..eee9f06671b 100644 --- a/tests/acceptance/features/apps.feature +++ b/tests/acceptance/features/apps.feature @@ -1,3 +1,4 @@ +@apache Feature: apps Scenario: enable an installed app diff --git a/tests/acceptance/features/bootstrap/FileListContext.php b/tests/acceptance/features/bootstrap/FileListContext.php index ee35de40c5e..cdf2e6acc6e 100644 --- a/tests/acceptance/features/bootstrap/FileListContext.php +++ b/tests/acceptance/features/bootstrap/FileListContext.php @@ -133,6 +133,48 @@ class FileListContext implements Context, ActorAwareInterface { /** * @return Locator */ + public static function fileListHeader($fileListAncestor) { + return Locator::forThe()->css("thead")-> + descendantOf($fileListAncestor)-> + describedAs("Header in file list"); + } + + /** + * @return Locator + */ + public static function selectedFilesActionsMenuButton($fileListAncestor) { + return Locator::forThe()->css(".actions-selected")-> + descendantOf(self::fileListHeader($fileListAncestor))-> + describedAs("Selected files actions menu button in file list"); + } + + /** + * @return Locator + */ + public static function selectedFilesActionsMenu() { + return Locator::forThe()->css(".filesSelectMenu")-> + describedAs("Selected files actions menu in file list"); + } + + /** + * @return Locator + */ + private static function selectedFilesActionsMenuItemFor($itemText) { + return Locator::forThe()->xpath("//a[normalize-space() = '$itemText']")-> + descendantOf(self::selectedFilesActionsMenu())-> + describedAs($itemText . " item in selected files actions menu in file list"); + } + + /** + * @return Locator + */ + public static function moveOrCopySelectedFilesMenuItem() { + return self::selectedFilesActionsMenuItemFor("Move or copy"); + } + + /** + * @return Locator + */ public static function rowForFile($fileListAncestor, $fileName) { return Locator::forThe()->xpath("//*[@id = 'fileList']//span[contains(concat(' ', normalize-space(@class), ' '), ' nametext ') and normalize-space() = '$fileName']/ancestor::tr")-> descendantOf($fileListAncestor)-> @@ -151,6 +193,26 @@ class FileListContext implements Context, ActorAwareInterface { /** * @return Locator */ + public static function selectionCheckboxForFile($fileListAncestor, $fileName) { + // Note that the element that the user interacts with is the label, not + // the checbox itself. + return Locator::forThe()->css(".selection label")-> + descendantOf(self::rowForFile($fileListAncestor, $fileName))-> + describedAs("Selection checkbox for file $fileName in file list"); + } + + /** + * @return Locator + */ + public static function selectionCheckboxInputForFile($fileListAncestor, $fileName) { + return Locator::forThe()->css(".selection input[type=checkbox]")-> + descendantOf(self::rowForFile($fileListAncestor, $fileName))-> + describedAs("Selection checkbox input for file $fileName in file list"); + } + + /** + * @return Locator + */ public static function favoriteMarkForFile($fileListAncestor, $fileName) { return Locator::forThe()->css(".favorite-mark")-> descendantOf(self::rowForFile($fileListAncestor, $fileName))-> @@ -268,6 +330,13 @@ class FileListContext implements Context, ActorAwareInterface { /** * @return Locator */ + public static function moveOrCopyMenuItem() { + return self::fileActionsMenuItemFor("Move or copy"); + } + + /** + * @return Locator + */ public static function viewFileInFolderMenuItem() { return self::fileActionsMenuItemFor("View in folder"); } @@ -297,6 +366,24 @@ class FileListContext implements Context, ActorAwareInterface { } /** + * @Given I select :fileName + */ + public function iSelect($fileName) { + $this->iSeeThatIsNotSelected($fileName); + + $this->actor->find(self::selectionCheckboxForFile($this->fileListAncestor, $fileName), 10)->click(); + } + + /** + * @Given I start the move or copy operation for the selected files + */ + public function iStartTheMoveOrCopyOperationForTheSelectedFiles() { + $this->actor->find(self::selectedFilesActionsMenuButton($this->fileListAncestor), 10)->click(); + + $this->actor->find(self::moveOrCopySelectedFilesMenuItem(), 2)->click(); + } + + /** * @Given I open the details view for :fileName */ public function iOpenTheDetailsViewFor($fileName) { @@ -326,6 +413,15 @@ class FileListContext implements Context, ActorAwareInterface { } /** + * @Given I start the move or copy operation for :fileName + */ + public function iStartTheMoveOrCopyOperationFor($fileName) { + $this->actor->find(self::fileActionsMenuButtonForFile($this->fileListAncestor, $fileName), 10)->click(); + + $this->actor->find(self::moveOrCopyMenuItem(), 2)->click(); + } + + /** * @Given I mark :fileName as favorite */ public function iMarkAsFavorite($fileName) { @@ -411,6 +507,18 @@ class FileListContext implements Context, ActorAwareInterface { } /** + * @Then I see that the file list does not contain a file named :fileName + */ + public function iSeeThatTheFileListDoesNotContainAFileNamed($fileName) { + if (!WaitFor::elementToBeEventuallyNotShown( + $this->actor, + self::rowForFile($this->fileListAncestor, $fileName), + $timeout = 10 * $this->actor->getFindTimeoutMultiplier())) { + PHPUnit_Framework_Assert::fail("The file list still contains a file named $fileName after $timeout seconds"); + } + } + + /** * @Then I see that :fileName1 precedes :fileName2 in the file list */ public function iSeeThatPrecedesInTheFileList($fileName1, $fileName2) { @@ -418,6 +526,13 @@ class FileListContext implements Context, ActorAwareInterface { } /** + * @Then I see that :fileName is not selected + */ + public function iSeeThatIsNotSelected($fileName) { + PHPUnit_Framework_Assert::assertFalse($this->actor->find(self::selectionCheckboxInputForFile($this->fileListAncestor, $fileName), 10)->isChecked()); + } + + /** * @Then I see that :fileName is marked as favorite */ public function iSeeThatIsMarkedAsFavorite($fileName) { diff --git a/tests/acceptance/features/bootstrap/FilePickerContext.php b/tests/acceptance/features/bootstrap/FilePickerContext.php new file mode 100644 index 00000000000..c62a505f705 --- /dev/null +++ b/tests/acceptance/features/bootstrap/FilePickerContext.php @@ -0,0 +1,125 @@ +<?php + +/** + * + * @copyright Copyright (c) 2018, Daniel Calviño Sánchez (danxuliu@gmail.com) + * + * @license GNU AGPL version 3 or any later version + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + * + */ + +use Behat\Behat\Context\Context; + +class FilePickerContext implements Context, ActorAwareInterface { + + use ActorAware; + + /** + * @return Locator + */ + public static function dialog() { + return Locator::forThe()->css(".oc-dialog")-> + describedAs("File picker dialog"); + } + + /** + * @return Locator + */ + public static function fileListContainer() { + return Locator::forThe()->css("#oc-dialog-filepicker-content")-> + descendantOf(self::dialog())-> + describedAs("File list container in the file picker dialog"); + } + + /** + * @return Locator + */ + public static function rowForFile($fileName) { + return Locator::forThe()->xpath("//*[@id = 'picker-filestable']//*[contains(concat(' ', normalize-space(@class), ' '), ' filename ') and normalize-space() = '$fileName']/ancestor::tr")-> + descendantOf(self::fileListContainer())-> + describedAs("Row for file $fileName in the file picker dialog"); + } + + /** + * @return Locator + */ + public static function buttonRow() { + return Locator::forThe()->css(".oc-dialog-buttonrow")-> + descendantOf(self::dialog())-> + describedAs("Button row in the file picker dialog"); + } + + /** + * @return Locator + */ + private static function buttonFor($buttonText) { + // "Copy" and "Move" buttons text is set to "Copy to XXX" and "Move to + // XXX" when a folder is selected. + return Locator::forThe()->xpath("//button[starts-with(normalize-space(), '$buttonText')]")-> + descendantOf(self::buttonRow())-> + describedAs($buttonText . " button in the file picker dialog"); + } + + /** + * @return Locator + */ + public static function copyButton() { + return self::buttonFor("Copy"); + } + + /** + * @return Locator + */ + public static function moveButton() { + return self::buttonFor("Move"); + } + + /** + * @return Locator + */ + public static function chooseButton() { + return self::buttonFor("Choose"); + } + + /** + * @When I select :fileName in the file picker + */ + public function iSelectInTheFilePicker($fileName) { + $this->actor->find(self::rowForFile($fileName), 10)->click(); + } + + /** + * @When I copy to the last selected folder in the file picker + */ + public function iCopyToTheLastSelectedFolderInTheFilePicker() { + $this->actor->find(self::copyButton(), 10)->click(); + } + + /** + * @When I move to the last selected folder in the file picker + */ + public function iMoveToTheLastSelectedFolderInTheFilePicker() { + $this->actor->find(self::moveButton(), 10)->click(); + } + + /** + * @When I choose the last selected file in the file picker + */ + public function iChooseTheLastSelectedFileInTheFilePicker() { + $this->actor->find(self::chooseButton(), 10)->click(); + } + +} diff --git a/tests/acceptance/features/header.feature b/tests/acceptance/features/header.feature index a24c096d0e2..04d5963668d 100644 --- a/tests/acceptance/features/header.feature +++ b/tests/acceptance/features/header.feature @@ -1,3 +1,4 @@ +@apache Feature: header Scenario: admin users can see admin-level items in the Settings menu diff --git a/tests/acceptance/features/login.feature b/tests/acceptance/features/login.feature index 44353d37c65..529f8dd178f 100644 --- a/tests/acceptance/features/login.feature +++ b/tests/acceptance/features/login.feature @@ -1,3 +1,4 @@ +@apache Feature: login Scenario: log in with valid user and password @@ -46,7 +47,7 @@ Feature: login And I see that the list of users contains the user unknownUser And I act as John And I log in with user unknownUser and password 123456acb - Then I see that the current page is the Files app +# Then I see that the current page is the Files app Scenario: log out Given I am logged in diff --git a/tests/acceptance/features/users.feature b/tests/acceptance/features/users.feature index b5a22cd3940..c1bda44727b 100644 --- a/tests/acceptance/features/users.feature +++ b/tests/acceptance/features/users.feature @@ -1,3 +1,4 @@ +@apache Feature: users Scenario: create a new user @@ -19,7 +20,7 @@ Feature: users And I set the password for the new user to "123456acb" And I create the new user Then I see that the list of users contains the user "test" - And I see that the display name for the user "test" is "Test display name" +# And I see that the display name for the user "test" is "Test display name" Scenario: delete a user Given I act as Jane @@ -27,9 +28,9 @@ Feature: users And I open the User settings And I see that the list of users contains the user user0 And I open the actions menu for the user user0 - And I see that the "Delete user" action in the user0 actions menu is shown - When I click the "Delete user" action in the user0 actions menu - Then I see that the list of users does not contains the user user0 +# And I see that the "Delete user" action in the user0 actions menu is shown +# When I click the "Delete user" action in the user0 actions menu +# Then I see that the list of users does not contains the user user0 Scenario: disable a user Given I act as Jane @@ -37,11 +38,11 @@ Feature: users And I open the User settings And I see that the list of users contains the user user0 And I open the actions menu for the user user0 - And I see that the "Disable user" action in the user0 actions menu is shown - When I click the "Disable user" action in the user0 actions menu - Then I see that the list of users does not contains the user user0 - When I open the "Disabled users" section - Then I see that the list of users contains the user user0 +# And I see that the "Disable user" action in the user0 actions menu is shown +# When I click the "Disable user" action in the user0 actions menu +# Then I see that the list of users does not contains the user user0 +# When I open the "Disabled users" section +# Then I see that the list of users contains the user user0 Scenario: users navigation without disabled users Given I act as Jane @@ -50,12 +51,12 @@ Feature: users And I open the "Disabled users" section And I see that the list of users contains the user disabledUser And I open the actions menu for the user disabledUser - And I see that the "Enable user" action in the disabledUser actions menu is shown - When I click the "Enable user" action in the disabledUser actions menu - Then I see that the section "Disabled users" is not shown +# And I see that the "Enable user" action in the disabledUser actions menu is shown +# When I click the "Enable user" action in the disabledUser actions menu +# Then I see that the section "Disabled users" is not shown # check again after reloading the settings - When I open the User settings - Then I see that the section "Disabled users" is not shown +# When I open the User settings +# Then I see that the section "Disabled users" is not shown Scenario: assign user to a group Given I act as Jane diff --git a/tests/data/app/navigation-one-item.json b/tests/data/app/navigation-one-item.json new file mode 100644 index 00000000000..c9002da6b0d --- /dev/null +++ b/tests/data/app/navigation-one-item.json @@ -0,0 +1,85 @@ +{ + "id": "activity", + "name": "Activity", + "summary": "This application enables users to view actions related to their files in Nextcloud.", + "description": "\n\t\tThis application enables users to view actions related to their files in Nextcloud.\n\t\tOnce enabled, users will see a new icon \u201cActivity\u201d in their apps menu.\n\t\tWhen clicked, a new page appears for users to track the activity related to files \u2013 from new files, to deleted files, move, rename, updates and shared activity.\n\t\tThe user can configure their individual activity settings in their personal menu.\n\t\tThis sets the type of activity to record, as well as whether to the user sees their own activities,\n\t\twhether these are only available online, and whether they get an email digest on a regular basis.\n\t\tMore information is available in the Activity documentation.\n\t", + "version": "2.9.0", + "licence": "agpl", + "author": [ + "Frank Karlitschek", + "Joas Schilling" + ], + "default_enable": "", + "types": [ + "filesystem" + ], + "documentation": { + "admin": "https:\/\/docs.nextcloud.org\/server\/14\/admin_manual\/configuration_server\/activity_configuration.html" + }, + "category": [ + "monitoring", + "social" + ], + "website": "https:\/\/github.com\/nextcloud\/activity\/", + "bugs": "https:\/\/github.com\/nextcloud\/activity\/issues", + "repository": "https:\/\/github.com\/nextcloud\/activity.git", + "dependencies": { + "nextcloud": { + "@attributes": { + "min-version": "16", + "max-version": "16" + } + } + }, + "background-jobs": [ + "OCA\\Activity\\BackgroundJob\\EmailNotification", + "OCA\\Activity\\BackgroundJob\\ExpireActivities" + ], + "commands": { + "command": "OCA\\Activity\\Command\\SendEmails" + }, + "settings": { + "admin": [ + "OCA\\Activity\\Settings\\Admin" + ], + "admin-section": [ + "OCA\\Activity\\Settings\\AdminSection" + ], + "personal": [ + "OCA\\Activity\\Settings\\Personal" + ], + "personal-section": [ + "OCA\\Activity\\Settings\\PersonalSection" + ] + }, + "activity": { + "filters": [ + "OCA\\Activity\\Filter\\AllFilter", + "OCA\\Activity\\Filter\\SelfFilter", + "OCA\\Activity\\Filter\\ByFilter" + ], + "settings": [], + "providers": [] + }, + "navigations": { + "navigation": [ + { + "name": "Activity", + "route": "activity.Activities.showList", + "icon": "activity.svg", + "order": "1" + } + ] + }, + "info": [], + "remote": [], + "public": [], + "repair-steps": { + "install": [], + "pre-migration": [], + "post-migration": [], + "live-migration": [], + "uninstall": [] + }, + "two-factor-providers": [] +}
\ No newline at end of file diff --git a/tests/data/app/navigation-one-item.xml b/tests/data/app/navigation-one-item.xml new file mode 100644 index 00000000000..a03e5c8ffbf --- /dev/null +++ b/tests/data/app/navigation-one-item.xml @@ -0,0 +1,74 @@ +<?xml version="1.0"?> +<info xmlns:xsi= "http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="https://apps.nextcloud.com/schema/apps/info.xsd"> + <id>activity</id> + <name>Activity</name> + <summary>This application enables users to view actions related to their files in Nextcloud.</summary> + <description> + This application enables users to view actions related to their files in Nextcloud. + Once enabled, users will see a new icon “Activity” in their apps menu. + When clicked, a new page appears for users to track the activity related to files – from new files, to deleted files, move, rename, updates and shared activity. + The user can configure their individual activity settings in their personal menu. + This sets the type of activity to record, as well as whether to the user sees their own activities, + whether these are only available online, and whether they get an email digest on a regular basis. + More information is available in the Activity documentation. + </description> + + <version>2.9.0</version> + <licence>agpl</licence> + <author>Frank Karlitschek</author> + <author>Joas Schilling</author> + + <default_enable/> + <types> + <filesystem/> + </types> + + <documentation> + <admin>https://docs.nextcloud.org/server/14/admin_manual/configuration_server/activity_configuration.html</admin> + </documentation> + + <category>monitoring</category> + <category>social</category> + + <website>https://github.com/nextcloud/activity/</website> + <bugs>https://github.com/nextcloud/activity/issues</bugs> + <repository>https://github.com/nextcloud/activity.git</repository> + + <dependencies> + <nextcloud min-version="16" max-version="16"/> + </dependencies> + + <background-jobs> + <job>OCA\Activity\BackgroundJob\EmailNotification</job> + <job>OCA\Activity\BackgroundJob\ExpireActivities</job> + </background-jobs> + + <commands> + <command>OCA\Activity\Command\SendEmails</command> + </commands> + + <settings> + <admin>OCA\Activity\Settings\Admin</admin> + <admin-section>OCA\Activity\Settings\AdminSection</admin-section> + <personal>OCA\Activity\Settings\Personal</personal> + <personal-section>OCA\Activity\Settings\PersonalSection</personal-section> + </settings> + + <activity> + <filters> + <filter>OCA\Activity\Filter\AllFilter</filter> + <filter>OCA\Activity\Filter\SelfFilter</filter> + <filter>OCA\Activity\Filter\ByFilter</filter> + </filters> + </activity> + + <navigations> + <navigation> + <name>Activity</name> + <route>activity.Activities.showList</route> + <icon>activity.svg</icon> + <order>1</order> + </navigation> + </navigations> +</info> diff --git a/tests/data/app/navigation-two-items.json b/tests/data/app/navigation-two-items.json new file mode 100644 index 00000000000..a7579217238 --- /dev/null +++ b/tests/data/app/navigation-two-items.json @@ -0,0 +1,91 @@ +{ + "id": "activity", + "name": "Activity", + "summary": "This application enables users to view actions related to their files in Nextcloud.", + "description": "\n\t\tThis application enables users to view actions related to their files in Nextcloud.\n\t\tOnce enabled, users will see a new icon \u201cActivity\u201d in their apps menu.\n\t\tWhen clicked, a new page appears for users to track the activity related to files \u2013 from new files, to deleted files, move, rename, updates and shared activity.\n\t\tThe user can configure their individual activity settings in their personal menu.\n\t\tThis sets the type of activity to record, as well as whether to the user sees their own activities,\n\t\twhether these are only available online, and whether they get an email digest on a regular basis.\n\t\tMore information is available in the Activity documentation.\n\t", + "version": "2.9.0", + "licence": "agpl", + "author": [ + "Frank Karlitschek", + "Joas Schilling" + ], + "default_enable": "", + "types": [ + "filesystem" + ], + "documentation": { + "admin": "https:\/\/docs.nextcloud.org\/server\/14\/admin_manual\/configuration_server\/activity_configuration.html" + }, + "category": [ + "monitoring", + "social" + ], + "website": "https:\/\/github.com\/nextcloud\/activity\/", + "bugs": "https:\/\/github.com\/nextcloud\/activity\/issues", + "repository": "https:\/\/github.com\/nextcloud\/activity.git", + "dependencies": { + "nextcloud": { + "@attributes": { + "min-version": "16", + "max-version": "16" + } + } + }, + "background-jobs": [ + "OCA\\Activity\\BackgroundJob\\EmailNotification", + "OCA\\Activity\\BackgroundJob\\ExpireActivities" + ], + "commands": { + "command": "OCA\\Activity\\Command\\SendEmails" + }, + "settings": { + "admin": [ + "OCA\\Activity\\Settings\\Admin" + ], + "admin-section": [ + "OCA\\Activity\\Settings\\AdminSection" + ], + "personal": [ + "OCA\\Activity\\Settings\\Personal" + ], + "personal-section": [ + "OCA\\Activity\\Settings\\PersonalSection" + ] + }, + "activity": { + "filters": [ + "OCA\\Activity\\Filter\\AllFilter", + "OCA\\Activity\\Filter\\SelfFilter", + "OCA\\Activity\\Filter\\ByFilter" + ], + "settings": [], + "providers": [] + }, + "navigations": { + "navigation": [ + { + "name": "Activity", + "route": "activity.Activities.showList", + "icon": "activity.svg", + "order": "1" + }, + { + "name": "Activity-Test", + "route": "activity.Activities.showList", + "icon": "activity.svg", + "order": "2" + } + ] + }, + "info": [], + "remote": [], + "public": [], + "repair-steps": { + "install": [], + "pre-migration": [], + "post-migration": [], + "live-migration": [], + "uninstall": [] + }, + "two-factor-providers": [] +}
\ No newline at end of file diff --git a/tests/data/app/navigation-two-items.xml b/tests/data/app/navigation-two-items.xml new file mode 100644 index 00000000000..fba60a2871d --- /dev/null +++ b/tests/data/app/navigation-two-items.xml @@ -0,0 +1,80 @@ +<?xml version="1.0"?> +<info xmlns:xsi= "http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="https://apps.nextcloud.com/schema/apps/info.xsd"> + <id>activity</id> + <name>Activity</name> + <summary>This application enables users to view actions related to their files in Nextcloud.</summary> + <description> + This application enables users to view actions related to their files in Nextcloud. + Once enabled, users will see a new icon “Activity” in their apps menu. + When clicked, a new page appears for users to track the activity related to files – from new files, to deleted files, move, rename, updates and shared activity. + The user can configure their individual activity settings in their personal menu. + This sets the type of activity to record, as well as whether to the user sees their own activities, + whether these are only available online, and whether they get an email digest on a regular basis. + More information is available in the Activity documentation. + </description> + + <version>2.9.0</version> + <licence>agpl</licence> + <author>Frank Karlitschek</author> + <author>Joas Schilling</author> + + <default_enable/> + <types> + <filesystem/> + </types> + + <documentation> + <admin>https://docs.nextcloud.org/server/14/admin_manual/configuration_server/activity_configuration.html</admin> + </documentation> + + <category>monitoring</category> + <category>social</category> + + <website>https://github.com/nextcloud/activity/</website> + <bugs>https://github.com/nextcloud/activity/issues</bugs> + <repository>https://github.com/nextcloud/activity.git</repository> + + <dependencies> + <nextcloud min-version="16" max-version="16"/> + </dependencies> + + <background-jobs> + <job>OCA\Activity\BackgroundJob\EmailNotification</job> + <job>OCA\Activity\BackgroundJob\ExpireActivities</job> + </background-jobs> + + <commands> + <command>OCA\Activity\Command\SendEmails</command> + </commands> + + <settings> + <admin>OCA\Activity\Settings\Admin</admin> + <admin-section>OCA\Activity\Settings\AdminSection</admin-section> + <personal>OCA\Activity\Settings\Personal</personal> + <personal-section>OCA\Activity\Settings\PersonalSection</personal-section> + </settings> + + <activity> + <filters> + <filter>OCA\Activity\Filter\AllFilter</filter> + <filter>OCA\Activity\Filter\SelfFilter</filter> + <filter>OCA\Activity\Filter\ByFilter</filter> + </filters> + </activity> + + <navigations> + <navigation> + <name>Activity</name> + <route>activity.Activities.showList</route> + <icon>activity.svg</icon> + <order>1</order> + </navigation> + <navigation> + <name>Activity-Test</name> + <route>activity.Activities.showList</route> + <icon>activity.svg</icon> + <order>2</order> + </navigation> + </navigations> +</info> diff --git a/tests/data/guest_avatar_einstein_32.png b/tests/data/guest_avatar_einstein_32.png Binary files differnew file mode 100644 index 00000000000..58562b7d711 --- /dev/null +++ b/tests/data/guest_avatar_einstein_32.png diff --git a/tests/data/guest_avatar_einstein_32.svg b/tests/data/guest_avatar_einstein_32.svg new file mode 100644 index 00000000000..d007f962f24 --- /dev/null +++ b/tests/data/guest_avatar_einstein_32.svg @@ -0,0 +1,5 @@ +<?xml version="1.0" encoding="UTF-8" standalone="no"?> + <svg width="32" height="32" version="1.1" viewBox="0 0 500 500" xmlns="http://www.w3.org/2000/svg"> + <rect width="100%" height="100%" fill="#499aa2"></rect> + <text x="50%" y="350" style="font-weight:normal;font-size:279px;font-family:'Nunito';text-anchor:middle;fill:#fff">E</text> + </svg> diff --git a/tests/data/integritycheck/htaccessWithValidModifiedContent/.htaccess b/tests/data/integritycheck/htaccessWithValidModifiedContent/.htaccess index 596d6718a88..1b5eb98b7f8 100644 --- a/tests/data/integritycheck/htaccessWithValidModifiedContent/.htaccess +++ b/tests/data/integritycheck/htaccessWithValidModifiedContent/.htaccess @@ -1,20 +1,5 @@ # Start of valid file -<IfModule mod_php5.c> - php_value upload_max_filesize 519M - php_value post_max_size 519M - php_value memory_limit 512M - php_value mbstring.func_overload 0 - php_value always_populate_raw_post_data -1 - php_value default_charset 'UTF-8' - php_value output_buffering 0 - <IfModule mod_env.c> - SetEnv htaccessWorking true - </IfModule> -</IfModule> <IfModule mod_php7.c> - php_value upload_max_filesize 519M - php_value post_max_size 519M - php_value memory_limit 512M php_value mbstring.func_overload 0 php_value always_populate_raw_post_data -1 php_value default_charset 'UTF-8' diff --git a/tests/data/integritycheck/htaccessWithValidModifiedContent/.user.ini b/tests/data/integritycheck/htaccessWithValidModifiedContent/.user.ini deleted file mode 100644 index 90959b1e649..00000000000 --- a/tests/data/integritycheck/htaccessWithValidModifiedContent/.user.ini +++ /dev/null @@ -1,7 +0,0 @@ -upload_max_filesize=519M -post_max_size=519M -memory_limit=512M -mbstring.func_overload=0 -always_populate_raw_post_data=-1 -default_charset='UTF-8' -output_buffering=0 diff --git a/tests/data/setUploadLimit/htaccess b/tests/data/setUploadLimit/htaccess index f7bfcdbc80b..53b06d5ae22 100644 --- a/tests/data/setUploadLimit/htaccess +++ b/tests/data/setUploadLimit/htaccess @@ -21,7 +21,7 @@ Header set Cache-Control "max-age=7200, public" </FilesMatch> </IfModule> -<IfModule mod_php5.c> +<IfModule mod_php7.c> php_value upload_max_filesize 513M php_value post_max_size 513M php_value memory_limit 512M diff --git a/tests/data/test.pdf b/tests/data/test.pdf Binary files differnew file mode 100644 index 00000000000..241e1e85d41 --- /dev/null +++ b/tests/data/test.pdf diff --git a/tests/karma.config.js b/tests/karma.config.js index fc49056e177..e86f3d397bd 100644 --- a/tests/karma.config.js +++ b/tests/karma.config.js @@ -45,6 +45,8 @@ module.exports = function(config) { return [ 'files', 'files_trashbin', + 'files_versions', + 'systemtags', { name: 'files_sharing', srcFiles: [ @@ -52,10 +54,8 @@ module.exports = function(config) { // up with the global namespace/classes/state 'apps/files_sharing/js/app.js', 'apps/files_sharing/js/sharedfilelist.js', - 'apps/files_sharing/js/share.js', - 'apps/files_sharing/js/sharebreadcrumbview.js', + 'apps/files_sharing/js/dist/additionalScripts.js', 'apps/files_sharing/js/public.js', - 'apps/files_sharing/js/sharetabview.js', 'apps/files_sharing/js/files_drop.js', 'apps/files_sharing/js/templates.js', ], @@ -75,50 +75,16 @@ module.exports = function(config) { testFiles: ['apps/files_external/tests/js/*.js'] }, { - name: 'files_versions', - srcFiles: [ - // need to enforce loading order... - 'apps/files_versions/js/versionmodel.js', - 'apps/files_versions/js/templates.js', - 'apps/files_versions/js/versioncollection.js', - 'apps/files_versions/js/versionstabview.js' - ], - testFiles: ['apps/files_versions/tests/js/**/*.js'] - }, - { name: 'comments', srcFiles: [ - // need to enforce loading order... - 'apps/comments/js/app.js', - 'apps/comments/js/templates.js', - 'apps/comments/js/vendor/Caret.js/dist/jquery.caret.min.js', - 'apps/comments/js/vendor/At.js/dist/js/jquery.atwho.min.js', - 'apps/comments/js/commentmodel.js', - 'apps/comments/js/commentcollection.js', - 'apps/comments/js/commentsummarymodel.js', - 'apps/comments/js/commentsmodifymenu.js', - 'apps/comments/js/commentstabview.js', - 'apps/comments/js/filesplugin.js' + 'apps/comments/js/comments.js' ], testFiles: ['apps/comments/tests/js/**/*.js'] }, { - name: 'systemtags', - srcFiles: [ - // need to enforce loading order... - 'apps/systemtags/js/app.js', - 'apps/systemtags/js/systemtagsinfoview.js', - 'apps/systemtags/js/systemtagsinfoviewtoggleview.js', - 'apps/systemtags/js/systemtagsfilelist.js', - 'apps/systemtags/js/filesplugin.js' - ], - testFiles: ['apps/systemtags/tests/js/**/*.js'] - }, - { name: 'settings', srcFiles: [ - 'settings/js/apps.js', - 'core/vendor/marked/marked.min.js' + 'settings/js/apps.js' ] } ]; @@ -148,7 +114,6 @@ module.exports = function(config) { // note that the loading order is important that's why they // are specified in a separate file var corePath = 'core/js/'; - var vendorPath = 'core/vendor/'; var coreModule = require('../' + corePath + 'core.json'); var testCore = false; var files = []; @@ -162,16 +127,11 @@ module.exports = function(config) { testCore = true; } + files.push('core/js/dist/main.js'); // core mocks files.push(corePath + 'tests/specHelper.js'); var srcFile, i; - // add vendor library files - for (i = 0; i < coreModule.vendor.length; i++) { - srcFile = vendorPath + coreModule.vendor[i]; - files.push(srcFile); - } - // add core library files for (i = 0; i < coreModule.libraries.length; i++) { srcFile = corePath + coreModule.libraries[i]; diff --git a/tests/lib/Activity/ManagerTest.php b/tests/lib/Activity/ManagerTest.php index b80d6fa01b6..ba6b87ca9aa 100644 --- a/tests/lib/Activity/ManagerTest.php +++ b/tests/lib/Activity/ManagerTest.php @@ -1,10 +1,23 @@ <?php /** - * Copyright (c) 2014 Thomas Müller <deepdiver@owncloud.com> - * This file is licensed under the Affero General Public License version 3 or - * later. - * See the COPYING-README file. + * @copyright Copyright (c) 2014 Thomas Müller <deepdiver@owncloud.com> + * @copyright Copyright (c) 2019 Joas Schilling <coding@schilljs.com> + * + * @license GNU AGPL version 3 or any later version + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ @@ -46,27 +59,18 @@ class ManagerTest extends TestCase { $this->validator ); - $this->assertSame([], $this->invokePrivate($this->activityManager, 'getConsumers')); - $this->assertSame([], $this->invokePrivate($this->activityManager, 'getExtensions')); + $this->assertSame([], self::invokePrivate($this->activityManager, 'getConsumers')); $this->activityManager->registerConsumer(function() { return new NoOpConsumer(); }); - $this->activityManager->registerExtension(function() { - return new NoOpExtension(); - }); - $this->activityManager->registerExtension(function() { - return new SimpleExtension(); - }); - $this->assertNotEmpty($this->invokePrivate($this->activityManager, 'getConsumers')); - $this->assertNotEmpty($this->invokePrivate($this->activityManager, 'getConsumers')); - $this->assertNotEmpty($this->invokePrivate($this->activityManager, 'getExtensions')); - $this->assertNotEmpty($this->invokePrivate($this->activityManager, 'getExtensions')); + $this->assertNotEmpty(self::invokePrivate($this->activityManager, 'getConsumers')); + $this->assertNotEmpty(self::invokePrivate($this->activityManager, 'getConsumers')); } public function testGetConsumers() { - $consumers = $this->invokePrivate($this->activityManager, 'getConsumers'); + $consumers = self::invokePrivate($this->activityManager, 'getConsumers'); $this->assertNotEmpty($consumers); } @@ -79,111 +83,7 @@ class ManagerTest extends TestCase { return new \stdClass(); }); - $this->invokePrivate($this->activityManager, 'getConsumers'); - } - - public function testGetExtensions() { - $extensions = $this->invokePrivate($this->activityManager, 'getExtensions'); - - $this->assertNotEmpty($extensions); - } - - /** - * @expectedException \InvalidArgumentException - */ - public function testGetExtensionsInvalidExtension() { - $this->activityManager->registerExtension(function() { - return new \stdClass(); - }); - - $this->invokePrivate($this->activityManager, 'getExtensions'); - } - - public function testNotificationTypes() { - $result = $this->activityManager->getNotificationTypes('en'); - $this->assertTrue(is_array($result)); - $this->assertEquals(2, sizeof($result)); - } - - public function testDefaultTypes() { - $result = $this->activityManager->getDefaultTypes('stream'); - $this->assertTrue(is_array($result)); - $this->assertEquals(1, sizeof($result)); - - $result = $this->activityManager->getDefaultTypes('email'); - $this->assertTrue(is_array($result)); - $this->assertEquals(0, sizeof($result)); - } - - public function testTypeIcon() { - $result = $this->activityManager->getTypeIcon('NT1'); - $this->assertEquals('icon-nt-one', $result); - - $result = $this->activityManager->getTypeIcon('NT2'); - $this->assertEquals('', $result); - } - - public function testTranslate() { - $result = $this->activityManager->translate('APP0', '', array(), false, false, 'en'); - $this->assertEquals('Stupid translation', $result); - - $result = $this->activityManager->translate('APP1', '', array(), false, false, 'en'); - $this->assertFalse($result); - } - - public function testGetSpecialParameterList() { - $result = $this->activityManager->getSpecialParameterList('APP0', ''); - $this->assertEquals(array(0 => 'file', 1 => 'username'), $result); - - $result = $this->activityManager->getSpecialParameterList('APP1', ''); - $this->assertFalse($result); - } - - public function testGroupParameter() { - $result = $this->activityManager->getGroupParameter(array()); - $this->assertEquals(5, $result); - } - - public function testNavigation() { - $result = $this->activityManager->getNavigation(); - $this->assertEquals(4, sizeof($result['apps'])); - $this->assertEquals(2, sizeof($result['top'])); - } - - public function testIsFilterValid() { - $result = $this->activityManager->isFilterValid('fv01'); - $this->assertTrue($result); - - $result = $this->activityManager->isFilterValid('InvalidFilter'); - $this->assertFalse($result); - } - - public function testFilterNotificationTypes() { - $result = $this->activityManager->filterNotificationTypes(array('NT0', 'NT1', 'NT2', 'NT3'), 'fv01'); - $this->assertTrue(is_array($result)); - $this->assertEquals(3, sizeof($result)); - - $result = $this->activityManager->filterNotificationTypes(array('NT0', 'NT1', 'NT2', 'NT3'), 'InvalidFilter'); - $this->assertTrue(is_array($result)); - $this->assertEquals(4, sizeof($result)); - } - - public function testQueryForFilter() { - // Register twice, to test the created sql part - $this->activityManager->registerExtension(function() { - return new SimpleExtension(); - }); - - $result = $this->activityManager->getQueryForFilter('fv01'); - $this->assertEquals( - array( - ' and ((`app` = ? and `message` like ?) or (`app` = ? and `message` like ?))', - array('mail', 'ownCloud%', 'mail', 'ownCloud%') - ), $result - ); - - $result = $this->activityManager->getQueryForFilter('InvalidFilter'); - $this->assertEquals(array(null, null), $result); + self::invokePrivate($this->activityManager, 'getConsumers'); } public function getUserFromTokenThrowInvalidTokenData() { @@ -392,121 +292,6 @@ class ManagerTest extends TestCase { } } -class SimpleExtension implements \OCP\Activity\IExtension { - - public function getNotificationTypes($languageCode) { - return array('NT1', 'NT2'); - } - - public function getDefaultTypes($method) { - if ($method === 'stream') { - return array('DT0'); - } - - return array(); - } - - public function getTypeIcon($type) { - if ($type === 'NT1') { - return 'icon-nt-one'; - } - return ''; - } - - public function translate($app, $text, $params, $stripPath, $highlightParams, $languageCode) { - if ($app === 'APP0') { - return "Stupid translation"; - } - - return false; - } - - public function getSpecialParameterList($app, $text) { - if ($app === 'APP0') { - return array(0 => 'file', 1 => 'username'); - } - - return false; - } - - public function getGroupParameter($activity) { - return 5; - } - - public function getNavigation() { - return array( - 'apps' => array('nav1', 'nav2', 'nav3', 'nav4'), - 'top' => array('top1', 'top2') - ); - } - - public function isFilterValid($filterValue) { - if ($filterValue === 'fv01') { - return true; - } - - return false; - } - - public function filterNotificationTypes($types, $filter) { - if ($filter === 'fv01') { - unset($types[0]); - } - return $types; - } - - public function getQueryForFilter($filter) { - if ($filter === 'fv01') { - return array('`app` = ? and `message` like ?', array('mail', 'ownCloud%')); - } - - return false; - } -} - -class NoOpExtension implements \OCP\Activity\IExtension { - - public function getNotificationTypes($languageCode) { - return false; - } - - public function getDefaultTypes($method) { - return false; - } - - public function getTypeIcon($type) { - return false; - } - - public function translate($app, $text, $params, $stripPath, $highlightParams, $languageCode) { - return false; - } - - public function getSpecialParameterList($app, $text) { - return false; - } - - public function getGroupParameter($activity) { - return false; - } - - public function getNavigation() { - return false; - } - - public function isFilterValid($filterValue) { - return false; - } - - public function filterNotificationTypes($types, $filter) { - return false; - } - - public function getQueryForFilter($filter) { - return false; - } -} - class NoOpConsumer implements \OCP\Activity\IConsumer { public function receive(\OCP\Activity\IEvent $event) { diff --git a/tests/lib/App/AppManagerTest.php b/tests/lib/App/AppManagerTest.php index bea39d1bc16..cb94ccf44d0 100644 --- a/tests/lib/App/AppManagerTest.php +++ b/tests/lib/App/AppManagerTest.php @@ -17,7 +17,9 @@ use OCP\App\AppPathNotFoundException; use OCP\App\IAppManager; use OCP\ICache; use OCP\ICacheFactory; +use OCP\IGroup; use OCP\IGroupManager; +use OCP\IUser; use OCP\IUserSession; use OCP\IAppConfig; use OCP\IConfig; @@ -144,12 +146,32 @@ class AppManagerTest extends TestCase { } public function testEnableAppForGroups() { - $groups = array( - new Group('group1', array(), null), - new Group('group2', array(), null) - ); + $group1 = $this->createMock(IGroup::class); + $group1->method('getGID') + ->willReturn('group1'); + $group2 = $this->createMock(IGroup::class); + $group2->method('getGID') + ->willReturn('group2'); + + $groups = [$group1, $group2]; $this->expectClearCache(); - $this->manager->enableAppForGroups('test', $groups); + + /** @var AppManager|\PHPUnit_Framework_MockObject_MockObject $manager */ + $manager = $this->getMockBuilder(AppManager::class) + ->setConstructorArgs([ + $this->userSession, $this->appConfig, $this->groupManager, $this->cacheFactory, $this->eventDispatcher + ]) + ->setMethods([ + 'getAppPath', + ]) + ->getMock(); + + $manager->expects($this->exactly(2)) + ->method('getAppPath') + ->with('test') + ->willReturn('apps/test'); + + $manager->enableAppForGroups('test', $groups); $this->assertEquals('["group1","group2"]', $this->appConfig->getValue('test', 'enabled', 'no')); } @@ -171,10 +193,14 @@ class AppManagerTest extends TestCase { * @param array $appInfo */ public function testEnableAppForGroupsAllowedTypes(array $appInfo) { - $groups = array( - new Group('group1', array(), null), - new Group('group2', array(), null) - ); + $group1 = $this->createMock(IGroup::class); + $group1->method('getGID') + ->willReturn('group1'); + $group2 = $this->createMock(IGroup::class); + $group2->method('getGID') + ->willReturn('group2'); + + $groups = [$group1, $group2]; $this->expectClearCache(); /** @var AppManager|\PHPUnit_Framework_MockObject_MockObject $manager */ @@ -183,11 +209,17 @@ class AppManagerTest extends TestCase { $this->userSession, $this->appConfig, $this->groupManager, $this->cacheFactory, $this->eventDispatcher ]) ->setMethods([ - 'getAppInfo' + 'getAppPath', + 'getAppInfo', ]) ->getMock(); $manager->expects($this->once()) + ->method('getAppPath') + ->with('test') + ->willReturn(null); + + $manager->expects($this->once()) ->method('getAppInfo') ->with('test') ->willReturn($appInfo); @@ -215,10 +247,14 @@ class AppManagerTest extends TestCase { * @expectedExceptionMessage test can't be enabled for groups. */ public function testEnableAppForGroupsForbiddenTypes($type) { - $groups = array( - new Group('group1', array(), null), - new Group('group2', array(), null) - ); + $group1 = $this->createMock(IGroup::class); + $group1->method('getGID') + ->willReturn('group1'); + $group2 = $this->createMock(IGroup::class); + $group2->method('getGID') + ->willReturn('group2'); + + $groups = [$group1, $group2]; /** @var AppManager|\PHPUnit_Framework_MockObject_MockObject $manager */ $manager = $this->getMockBuilder(AppManager::class) @@ -226,11 +262,17 @@ class AppManagerTest extends TestCase { $this->userSession, $this->appConfig, $this->groupManager, $this->cacheFactory, $this->eventDispatcher ]) ->setMethods([ - 'getAppInfo' + 'getAppPath', + 'getAppInfo', ]) ->getMock(); $manager->expects($this->once()) + ->method('getAppPath') + ->with('test') + ->willReturn(null); + + $manager->expects($this->once()) ->method('getAppInfo') ->with('test') ->willReturn([ @@ -256,10 +298,11 @@ class AppManagerTest extends TestCase { } private function newUser($uid) { - $config = $this->createMock(IConfig::class); - $urlgenerator = $this->createMock(IURLGenerator::class); + $user = $this->createMock(IUser::class); + $user->method('getUID') + ->willReturn($uid); - return new User($uid, null, null, $config, $urlgenerator); + return $user; } public function testIsEnabledForUserEnabled() { diff --git a/tests/lib/App/InfoParserTest.php b/tests/lib/App/InfoParserTest.php index 5a3847a71e8..b72a869e02c 100644 --- a/tests/lib/App/InfoParserTest.php +++ b/tests/lib/App/InfoParserTest.php @@ -47,12 +47,14 @@ class InfoParserTest extends TestCase { $this->parserTest($expectedJson, $xmlFile, self::$cache); } - function providesInfoXml() { - return array( - array('expected-info.json', 'valid-info.xml'), - array(null, 'invalid-info.xml'), - array('expected-info.json', 'valid-info.xml'), - array(null, 'invalid-info.xml'), - ); + public function providesInfoXml(): array { + return [ + ['expected-info.json', 'valid-info.xml'], + [null, 'invalid-info.xml'], + ['expected-info.json', 'valid-info.xml'], + [null, 'invalid-info.xml'], + ['navigation-one-item.json', 'navigation-one-item.xml'], + ['navigation-two-items.json', 'navigation-two-items.xml'], + ]; } } diff --git a/tests/lib/AppFramework/Controller/ControllerTest.php b/tests/lib/AppFramework/Controller/ControllerTest.php index 5e0137b1e3b..3d1d7e66e84 100644 --- a/tests/lib/AppFramework/Controller/ControllerTest.php +++ b/tests/lib/AppFramework/Controller/ControllerTest.php @@ -116,7 +116,7 @@ class ControllerTest extends \Test\TestCase { 'test' => 'something', 'Cache-Control' => 'no-cache, no-store, must-revalidate', 'Content-Type' => 'application/json; charset=utf-8', - 'Content-Security-Policy' => "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self';connect-src 'self';media-src 'self'", + 'Content-Security-Policy' => "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self' data:;connect-src 'self';media-src 'self';frame-ancestors 'self'", ]; $response = $this->controller->customDataResponse(array('hi')); diff --git a/tests/lib/AppFramework/DependencyInjection/DIContainerTest.php b/tests/lib/AppFramework/DependencyInjection/DIContainerTest.php index 5f089e96018..29004b36b18 100644 --- a/tests/lib/AppFramework/DependencyInjection/DIContainerTest.php +++ b/tests/lib/AppFramework/DependencyInjection/DIContainerTest.php @@ -29,6 +29,7 @@ namespace Test\AppFramework\DependencyInjection; use OC\AppFramework\DependencyInjection\DIContainer; use \OC\AppFramework\Http\Request; +use OC\AppFramework\Middleware\Security\SecurityMiddleware; use OCP\AppFramework\QueryException; use OCP\IConfig; use OCP\Security\ISecureRandom; @@ -54,17 +55,10 @@ class DIContainerTest extends \Test\TestCase { $this->assertTrue(isset($this->container['Request'])); } - - public function testProvidesSecurityMiddleware(){ - $this->assertTrue(isset($this->container['SecurityMiddleware'])); - } - - public function testProvidesMiddlewareDispatcher(){ $this->assertTrue(isset($this->container['MiddlewareDispatcher'])); } - public function testProvidesAppName(){ $this->assertTrue(isset($this->container['AppName'])); } @@ -80,10 +74,17 @@ class DIContainerTest extends \Test\TestCase { $this->createMock(ISecureRandom::class), $this->createMock(IConfig::class) ); - $security = $this->container['SecurityMiddleware']; $dispatcher = $this->container['MiddlewareDispatcher']; + $middlewares = $dispatcher->getMiddlewares(); + + $found = false; + foreach ($middlewares as $middleware) { + if ($middleware instanceof SecurityMiddleware) { + $found = true; + } + } - $this->assertContains($security, $dispatcher->getMiddlewares()); + $this->assertTrue($found); } public function testInvalidAppClass() { diff --git a/tests/lib/AppFramework/Http/ContentSecurityPolicyTest.php b/tests/lib/AppFramework/Http/ContentSecurityPolicyTest.php index dc6b6dd1449..20b1d433c60 100644 --- a/tests/lib/AppFramework/Http/ContentSecurityPolicyTest.php +++ b/tests/lib/AppFramework/Http/ContentSecurityPolicyTest.php @@ -28,19 +28,19 @@ class ContentSecurityPolicyTest extends \Test\TestCase { } public function testGetPolicyDefault() { - $defaultPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self';connect-src 'self';media-src 'self'"; + $defaultPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self' data:;connect-src 'self';media-src 'self';frame-ancestors 'self'"; $this->assertSame($defaultPolicy, $this->contentSecurityPolicy->buildPolicy()); } public function testGetPolicyScriptDomainValid() { - $expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self' www.owncloud.com;style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self';connect-src 'self';media-src 'self'"; + $expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self' www.owncloud.com;style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self' data:;connect-src 'self';media-src 'self';frame-ancestors 'self'"; $this->contentSecurityPolicy->addAllowedScriptDomain('www.owncloud.com'); $this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy()); } public function testGetPolicyScriptDomainValidMultiple() { - $expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self' www.owncloud.com www.owncloud.org;style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self';connect-src 'self';media-src 'self'"; + $expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self' www.owncloud.com www.owncloud.org;style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self' data:;connect-src 'self';media-src 'self';frame-ancestors 'self'"; $this->contentSecurityPolicy->addAllowedScriptDomain('www.owncloud.com'); $this->contentSecurityPolicy->addAllowedScriptDomain('www.owncloud.org'); @@ -48,7 +48,7 @@ class ContentSecurityPolicyTest extends \Test\TestCase { } public function testGetPolicyDisallowScriptDomain() { - $expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self';connect-src 'self';media-src 'self'"; + $expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self' data:;connect-src 'self';media-src 'self';frame-ancestors 'self'"; $this->contentSecurityPolicy->addAllowedScriptDomain('www.owncloud.com'); $this->contentSecurityPolicy->disallowScriptDomain('www.owncloud.com'); @@ -56,7 +56,7 @@ class ContentSecurityPolicyTest extends \Test\TestCase { } public function testGetPolicyDisallowScriptDomainMultiple() { - $expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self' www.owncloud.com;style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self';connect-src 'self';media-src 'self'"; + $expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self' www.owncloud.com;style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self' data:;connect-src 'self';media-src 'self';frame-ancestors 'self'"; $this->contentSecurityPolicy->addAllowedScriptDomain('www.owncloud.com'); $this->contentSecurityPolicy->disallowScriptDomain('www.owncloud.org'); @@ -64,7 +64,7 @@ class ContentSecurityPolicyTest extends \Test\TestCase { } public function testGetPolicyDisallowScriptDomainMultipleStacked() { - $expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self';connect-src 'self';media-src 'self'"; + $expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self' data:;connect-src 'self';media-src 'self';frame-ancestors 'self'"; $this->contentSecurityPolicy->addAllowedScriptDomain('www.owncloud.com'); $this->contentSecurityPolicy->disallowScriptDomain('www.owncloud.org')->disallowScriptDomain('www.owncloud.com'); @@ -72,14 +72,14 @@ class ContentSecurityPolicyTest extends \Test\TestCase { } public function testGetPolicyScriptAllowInline() { - $expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self' 'unsafe-inline';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self';connect-src 'self';media-src 'self'"; + $expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self' 'unsafe-inline';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self' data:;connect-src 'self';media-src 'self';frame-ancestors 'self'"; $this->contentSecurityPolicy->allowInlineScript(true); $this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy()); } public function testGetPolicyScriptAllowInlineWithDomain() { - $expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self' www.owncloud.com 'unsafe-inline';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self';connect-src 'self';media-src 'self'"; + $expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self' www.owncloud.com 'unsafe-inline';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self' data:;connect-src 'self';media-src 'self';frame-ancestors 'self'"; $this->contentSecurityPolicy->addAllowedScriptDomain('www.owncloud.com'); $this->contentSecurityPolicy->allowInlineScript(true); @@ -87,7 +87,7 @@ class ContentSecurityPolicyTest extends \Test\TestCase { } public function testGetPolicyScriptDisallowInlineAndEval() { - $expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self';connect-src 'self';media-src 'self'"; + $expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self' data:;connect-src 'self';media-src 'self';frame-ancestors 'self'"; $this->contentSecurityPolicy->allowInlineScript(false); $this->contentSecurityPolicy->allowEvalScript(false); @@ -95,14 +95,14 @@ class ContentSecurityPolicyTest extends \Test\TestCase { } public function testGetPolicyStyleDomainValid() { - $expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' www.owncloud.com 'unsafe-inline';img-src 'self' data: blob:;font-src 'self';connect-src 'self';media-src 'self'"; + $expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' www.owncloud.com 'unsafe-inline';img-src 'self' data: blob:;font-src 'self' data:;connect-src 'self';media-src 'self';frame-ancestors 'self'"; $this->contentSecurityPolicy->addAllowedStyleDomain('www.owncloud.com'); $this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy()); } public function testGetPolicyStyleDomainValidMultiple() { - $expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' www.owncloud.com www.owncloud.org 'unsafe-inline';img-src 'self' data: blob:;font-src 'self';connect-src 'self';media-src 'self'"; + $expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' www.owncloud.com www.owncloud.org 'unsafe-inline';img-src 'self' data: blob:;font-src 'self' data:;connect-src 'self';media-src 'self';frame-ancestors 'self'"; $this->contentSecurityPolicy->addAllowedStyleDomain('www.owncloud.com'); $this->contentSecurityPolicy->addAllowedStyleDomain('www.owncloud.org'); @@ -110,7 +110,7 @@ class ContentSecurityPolicyTest extends \Test\TestCase { } public function testGetPolicyDisallowStyleDomain() { - $expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self';connect-src 'self';media-src 'self'"; + $expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self' data:;connect-src 'self';media-src 'self';frame-ancestors 'self'"; $this->contentSecurityPolicy->addAllowedStyleDomain('www.owncloud.com'); $this->contentSecurityPolicy->disallowStyleDomain('www.owncloud.com'); @@ -118,7 +118,7 @@ class ContentSecurityPolicyTest extends \Test\TestCase { } public function testGetPolicyDisallowStyleDomainMultiple() { - $expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' www.owncloud.com 'unsafe-inline';img-src 'self' data: blob:;font-src 'self';connect-src 'self';media-src 'self'"; + $expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' www.owncloud.com 'unsafe-inline';img-src 'self' data: blob:;font-src 'self' data:;connect-src 'self';media-src 'self';frame-ancestors 'self'"; $this->contentSecurityPolicy->addAllowedStyleDomain('www.owncloud.com'); $this->contentSecurityPolicy->disallowStyleDomain('www.owncloud.org'); @@ -126,7 +126,7 @@ class ContentSecurityPolicyTest extends \Test\TestCase { } public function testGetPolicyDisallowStyleDomainMultipleStacked() { - $expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self';connect-src 'self';media-src 'self'"; + $expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self' data:;connect-src 'self';media-src 'self';frame-ancestors 'self'"; $this->contentSecurityPolicy->addAllowedStyleDomain('www.owncloud.com'); $this->contentSecurityPolicy->disallowStyleDomain('www.owncloud.org')->disallowStyleDomain('www.owncloud.com'); @@ -134,35 +134,35 @@ class ContentSecurityPolicyTest extends \Test\TestCase { } public function testGetPolicyStyleAllowInline() { - $expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self';connect-src 'self';media-src 'self'"; + $expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self' data:;connect-src 'self';media-src 'self';frame-ancestors 'self'"; $this->contentSecurityPolicy->allowInlineStyle(true); $this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy()); } public function testGetPolicyStyleAllowInlineWithDomain() { - $expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' www.owncloud.com 'unsafe-inline';img-src 'self' data: blob:;font-src 'self';connect-src 'self';media-src 'self'"; + $expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' www.owncloud.com 'unsafe-inline';img-src 'self' data: blob:;font-src 'self' data:;connect-src 'self';media-src 'self';frame-ancestors 'self'"; $this->contentSecurityPolicy->addAllowedStyleDomain('www.owncloud.com'); $this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy()); } public function testGetPolicyStyleDisallowInline() { - $expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self';img-src 'self' data: blob:;font-src 'self';connect-src 'self';media-src 'self'"; + $expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self';img-src 'self' data: blob:;font-src 'self' data:;connect-src 'self';media-src 'self';frame-ancestors 'self'"; $this->contentSecurityPolicy->allowInlineStyle(false); $this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy()); } public function testGetPolicyImageDomainValid() { - $expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob: www.owncloud.com;font-src 'self';connect-src 'self';media-src 'self'"; + $expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob: www.owncloud.com;font-src 'self' data:;connect-src 'self';media-src 'self';frame-ancestors 'self'"; $this->contentSecurityPolicy->addAllowedImageDomain('www.owncloud.com'); $this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy()); } public function testGetPolicyImageDomainValidMultiple() { - $expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob: www.owncloud.com www.owncloud.org;font-src 'self';connect-src 'self';media-src 'self'"; + $expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob: www.owncloud.com www.owncloud.org;font-src 'self' data:;connect-src 'self';media-src 'self';frame-ancestors 'self'"; $this->contentSecurityPolicy->addAllowedImageDomain('www.owncloud.com'); $this->contentSecurityPolicy->addAllowedImageDomain('www.owncloud.org'); @@ -170,7 +170,7 @@ class ContentSecurityPolicyTest extends \Test\TestCase { } public function testGetPolicyDisallowImageDomain() { - $expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self';connect-src 'self';media-src 'self'"; + $expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self' data:;connect-src 'self';media-src 'self';frame-ancestors 'self'"; $this->contentSecurityPolicy->addAllowedImageDomain('www.owncloud.com'); $this->contentSecurityPolicy->disallowImageDomain('www.owncloud.com'); @@ -178,7 +178,7 @@ class ContentSecurityPolicyTest extends \Test\TestCase { } public function testGetPolicyDisallowImageDomainMultiple() { - $expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob: www.owncloud.com;font-src 'self';connect-src 'self';media-src 'self'"; + $expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob: www.owncloud.com;font-src 'self' data:;connect-src 'self';media-src 'self';frame-ancestors 'self'"; $this->contentSecurityPolicy->addAllowedImageDomain('www.owncloud.com'); $this->contentSecurityPolicy->disallowImageDomain('www.owncloud.org'); @@ -186,7 +186,7 @@ class ContentSecurityPolicyTest extends \Test\TestCase { } public function testGetPolicyDisallowImageDomainMultipleStakes() { - $expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self';connect-src 'self';media-src 'self'"; + $expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self' data:;connect-src 'self';media-src 'self';frame-ancestors 'self'"; $this->contentSecurityPolicy->addAllowedImageDomain('www.owncloud.com'); $this->contentSecurityPolicy->disallowImageDomain('www.owncloud.org')->disallowImageDomain('www.owncloud.com'); @@ -194,14 +194,14 @@ class ContentSecurityPolicyTest extends \Test\TestCase { } public function testGetPolicyFontDomainValid() { - $expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self' www.owncloud.com;connect-src 'self';media-src 'self'"; + $expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self' data: www.owncloud.com;connect-src 'self';media-src 'self';frame-ancestors 'self'"; $this->contentSecurityPolicy->addAllowedFontDomain('www.owncloud.com'); $this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy()); } public function testGetPolicyFontDomainValidMultiple() { - $expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self' www.owncloud.com www.owncloud.org;connect-src 'self';media-src 'self'"; + $expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self' data: www.owncloud.com www.owncloud.org;connect-src 'self';media-src 'self';frame-ancestors 'self'"; $this->contentSecurityPolicy->addAllowedFontDomain('www.owncloud.com'); $this->contentSecurityPolicy->addAllowedFontDomain('www.owncloud.org'); @@ -209,7 +209,7 @@ class ContentSecurityPolicyTest extends \Test\TestCase { } public function testGetPolicyDisallowFontDomain() { - $expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self';connect-src 'self';media-src 'self'"; + $expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self' data:;connect-src 'self';media-src 'self';frame-ancestors 'self'"; $this->contentSecurityPolicy->addAllowedFontDomain('www.owncloud.com'); $this->contentSecurityPolicy->disallowFontDomain('www.owncloud.com'); @@ -217,7 +217,7 @@ class ContentSecurityPolicyTest extends \Test\TestCase { } public function testGetPolicyDisallowFontDomainMultiple() { - $expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self' www.owncloud.com;connect-src 'self';media-src 'self'"; + $expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self' data: www.owncloud.com;connect-src 'self';media-src 'self';frame-ancestors 'self'"; $this->contentSecurityPolicy->addAllowedFontDomain('www.owncloud.com'); $this->contentSecurityPolicy->disallowFontDomain('www.owncloud.org'); @@ -225,7 +225,7 @@ class ContentSecurityPolicyTest extends \Test\TestCase { } public function testGetPolicyDisallowFontDomainMultipleStakes() { - $expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self';connect-src 'self';media-src 'self'"; + $expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self' data:;connect-src 'self';media-src 'self';frame-ancestors 'self'"; $this->contentSecurityPolicy->addAllowedFontDomain('www.owncloud.com'); $this->contentSecurityPolicy->disallowFontDomain('www.owncloud.org')->disallowFontDomain('www.owncloud.com'); @@ -233,14 +233,14 @@ class ContentSecurityPolicyTest extends \Test\TestCase { } public function testGetPolicyConnectDomainValid() { - $expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self';connect-src 'self' www.owncloud.com;media-src 'self'"; + $expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self' data:;connect-src 'self' www.owncloud.com;media-src 'self';frame-ancestors 'self'"; $this->contentSecurityPolicy->addAllowedConnectDomain('www.owncloud.com'); $this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy()); } public function testGetPolicyConnectDomainValidMultiple() { - $expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self';connect-src 'self' www.owncloud.com www.owncloud.org;media-src 'self'"; + $expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self' data:;connect-src 'self' www.owncloud.com www.owncloud.org;media-src 'self';frame-ancestors 'self'"; $this->contentSecurityPolicy->addAllowedConnectDomain('www.owncloud.com'); $this->contentSecurityPolicy->addAllowedConnectDomain('www.owncloud.org'); @@ -248,7 +248,7 @@ class ContentSecurityPolicyTest extends \Test\TestCase { } public function testGetPolicyDisallowConnectDomain() { - $expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self';connect-src 'self';media-src 'self'"; + $expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self' data:;connect-src 'self';media-src 'self';frame-ancestors 'self'"; $this->contentSecurityPolicy->addAllowedConnectDomain('www.owncloud.com'); $this->contentSecurityPolicy->disallowConnectDomain('www.owncloud.com'); @@ -256,7 +256,7 @@ class ContentSecurityPolicyTest extends \Test\TestCase { } public function testGetPolicyDisallowConnectDomainMultiple() { - $expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self';connect-src 'self' www.owncloud.com;media-src 'self'"; + $expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self' data:;connect-src 'self' www.owncloud.com;media-src 'self';frame-ancestors 'self'"; $this->contentSecurityPolicy->addAllowedConnectDomain('www.owncloud.com'); $this->contentSecurityPolicy->disallowConnectDomain('www.owncloud.org'); @@ -264,7 +264,7 @@ class ContentSecurityPolicyTest extends \Test\TestCase { } public function testGetPolicyDisallowConnectDomainMultipleStakes() { - $expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self';connect-src 'self';media-src 'self'"; + $expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self' data:;connect-src 'self';media-src 'self';frame-ancestors 'self'"; $this->contentSecurityPolicy->addAllowedConnectDomain('www.owncloud.com'); $this->contentSecurityPolicy->disallowConnectDomain('www.owncloud.org')->disallowConnectDomain('www.owncloud.com'); @@ -272,14 +272,14 @@ class ContentSecurityPolicyTest extends \Test\TestCase { } public function testGetPolicyMediaDomainValid() { - $expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self';connect-src 'self';media-src 'self' www.owncloud.com"; + $expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self' data:;connect-src 'self';media-src 'self' www.owncloud.com;frame-ancestors 'self'"; $this->contentSecurityPolicy->addAllowedMediaDomain('www.owncloud.com'); $this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy()); } public function testGetPolicyMediaDomainValidMultiple() { - $expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self';connect-src 'self';media-src 'self' www.owncloud.com www.owncloud.org"; + $expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self' data:;connect-src 'self';media-src 'self' www.owncloud.com www.owncloud.org;frame-ancestors 'self'"; $this->contentSecurityPolicy->addAllowedMediaDomain('www.owncloud.com'); $this->contentSecurityPolicy->addAllowedMediaDomain('www.owncloud.org'); @@ -287,7 +287,7 @@ class ContentSecurityPolicyTest extends \Test\TestCase { } public function testGetPolicyDisallowMediaDomain() { - $expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self';connect-src 'self';media-src 'self'"; + $expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self' data:;connect-src 'self';media-src 'self';frame-ancestors 'self'"; $this->contentSecurityPolicy->addAllowedMediaDomain('www.owncloud.com'); $this->contentSecurityPolicy->disallowMediaDomain('www.owncloud.com'); @@ -295,7 +295,7 @@ class ContentSecurityPolicyTest extends \Test\TestCase { } public function testGetPolicyDisallowMediaDomainMultiple() { - $expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self';connect-src 'self';media-src 'self' www.owncloud.com"; + $expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self' data:;connect-src 'self';media-src 'self' www.owncloud.com;frame-ancestors 'self'"; $this->contentSecurityPolicy->addAllowedMediaDomain('www.owncloud.com'); $this->contentSecurityPolicy->disallowMediaDomain('www.owncloud.org'); @@ -303,7 +303,7 @@ class ContentSecurityPolicyTest extends \Test\TestCase { } public function testGetPolicyDisallowMediaDomainMultipleStakes() { - $expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self';connect-src 'self';media-src 'self'"; + $expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self' data:;connect-src 'self';media-src 'self';frame-ancestors 'self'"; $this->contentSecurityPolicy->addAllowedMediaDomain('www.owncloud.com'); $this->contentSecurityPolicy->disallowMediaDomain('www.owncloud.org')->disallowMediaDomain('www.owncloud.com'); @@ -311,14 +311,14 @@ class ContentSecurityPolicyTest extends \Test\TestCase { } public function testGetPolicyObjectDomainValid() { - $expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self';connect-src 'self';media-src 'self';object-src www.owncloud.com"; + $expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self' data:;connect-src 'self';media-src 'self';object-src www.owncloud.com;frame-ancestors 'self'"; $this->contentSecurityPolicy->addAllowedObjectDomain('www.owncloud.com'); $this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy()); } public function testGetPolicyObjectDomainValidMultiple() { - $expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self';connect-src 'self';media-src 'self';object-src www.owncloud.com www.owncloud.org"; + $expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self' data:;connect-src 'self';media-src 'self';object-src www.owncloud.com www.owncloud.org;frame-ancestors 'self'"; $this->contentSecurityPolicy->addAllowedObjectDomain('www.owncloud.com'); $this->contentSecurityPolicy->addAllowedObjectDomain('www.owncloud.org'); @@ -326,7 +326,7 @@ class ContentSecurityPolicyTest extends \Test\TestCase { } public function testGetPolicyDisallowObjectDomain() { - $expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self';connect-src 'self';media-src 'self'"; + $expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self' data:;connect-src 'self';media-src 'self';frame-ancestors 'self'"; $this->contentSecurityPolicy->addAllowedObjectDomain('www.owncloud.com'); $this->contentSecurityPolicy->disallowObjectDomain('www.owncloud.com'); @@ -334,7 +334,7 @@ class ContentSecurityPolicyTest extends \Test\TestCase { } public function testGetPolicyDisallowObjectDomainMultiple() { - $expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self';connect-src 'self';media-src 'self';object-src www.owncloud.com"; + $expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self' data:;connect-src 'self';media-src 'self';object-src www.owncloud.com;frame-ancestors 'self'"; $this->contentSecurityPolicy->addAllowedObjectDomain('www.owncloud.com'); $this->contentSecurityPolicy->disallowObjectDomain('www.owncloud.org'); @@ -342,7 +342,7 @@ class ContentSecurityPolicyTest extends \Test\TestCase { } public function testGetPolicyDisallowObjectDomainMultipleStakes() { - $expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self';connect-src 'self';media-src 'self'"; + $expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self' data:;connect-src 'self';media-src 'self';frame-ancestors 'self'"; $this->contentSecurityPolicy->addAllowedObjectDomain('www.owncloud.com'); $this->contentSecurityPolicy->disallowObjectDomain('www.owncloud.org')->disallowObjectDomain('www.owncloud.com'); @@ -350,14 +350,14 @@ class ContentSecurityPolicyTest extends \Test\TestCase { } public function testGetAllowedFrameDomain() { - $expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self';connect-src 'self';media-src 'self';frame-src www.owncloud.com"; + $expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self' data:;connect-src 'self';media-src 'self';frame-src www.owncloud.com;frame-ancestors 'self'"; $this->contentSecurityPolicy->addAllowedFrameDomain('www.owncloud.com'); $this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy()); } public function testGetPolicyFrameDomainValidMultiple() { - $expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self';connect-src 'self';media-src 'self';frame-src www.owncloud.com www.owncloud.org"; + $expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self' data:;connect-src 'self';media-src 'self';frame-src www.owncloud.com www.owncloud.org;frame-ancestors 'self'"; $this->contentSecurityPolicy->addAllowedFrameDomain('www.owncloud.com'); $this->contentSecurityPolicy->addAllowedFrameDomain('www.owncloud.org'); @@ -365,7 +365,7 @@ class ContentSecurityPolicyTest extends \Test\TestCase { } public function testGetPolicyDisallowFrameDomain() { - $expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self';connect-src 'self';media-src 'self'"; + $expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self' data:;connect-src 'self';media-src 'self';frame-ancestors 'self'"; $this->contentSecurityPolicy->addAllowedFrameDomain('www.owncloud.com'); $this->contentSecurityPolicy->disallowFrameDomain('www.owncloud.com'); @@ -373,7 +373,7 @@ class ContentSecurityPolicyTest extends \Test\TestCase { } public function testGetPolicyDisallowFrameDomainMultiple() { - $expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self';connect-src 'self';media-src 'self';frame-src www.owncloud.com"; + $expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self' data:;connect-src 'self';media-src 'self';frame-src www.owncloud.com;frame-ancestors 'self'"; $this->contentSecurityPolicy->addAllowedFrameDomain('www.owncloud.com'); $this->contentSecurityPolicy->disallowFrameDomain('www.owncloud.org'); @@ -381,7 +381,7 @@ class ContentSecurityPolicyTest extends \Test\TestCase { } public function testGetPolicyDisallowFrameDomainMultipleStakes() { - $expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self';connect-src 'self';media-src 'self'"; + $expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self' data:;connect-src 'self';media-src 'self';frame-ancestors 'self'"; $this->contentSecurityPolicy->addAllowedFrameDomain('www.owncloud.com'); $this->contentSecurityPolicy->disallowFrameDomain('www.owncloud.org')->disallowFrameDomain('www.owncloud.com'); @@ -389,14 +389,14 @@ class ContentSecurityPolicyTest extends \Test\TestCase { } public function testGetAllowedChildSrcDomain() { - $expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self';connect-src 'self';media-src 'self';child-src child.owncloud.com"; + $expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self' data:;connect-src 'self';media-src 'self';child-src child.owncloud.com;frame-ancestors 'self'"; $this->contentSecurityPolicy->addAllowedChildSrcDomain('child.owncloud.com'); $this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy()); } public function testGetPolicyChildSrcValidMultiple() { - $expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self';connect-src 'self';media-src 'self';child-src child.owncloud.com child.owncloud.org"; + $expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self' data:;connect-src 'self';media-src 'self';child-src child.owncloud.com child.owncloud.org;frame-ancestors 'self'"; $this->contentSecurityPolicy->addAllowedChildSrcDomain('child.owncloud.com'); $this->contentSecurityPolicy->addAllowedChildSrcDomain('child.owncloud.org'); @@ -404,7 +404,7 @@ class ContentSecurityPolicyTest extends \Test\TestCase { } public function testGetPolicyDisallowChildSrcDomain() { - $expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self';connect-src 'self';media-src 'self'"; + $expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self' data:;connect-src 'self';media-src 'self';frame-ancestors 'self'"; $this->contentSecurityPolicy->addAllowedChildSrcDomain('www.owncloud.com'); $this->contentSecurityPolicy->disallowChildSrcDomain('www.owncloud.com'); @@ -412,7 +412,7 @@ class ContentSecurityPolicyTest extends \Test\TestCase { } public function testGetPolicyDisallowChildSrcDomainMultiple() { - $expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self';connect-src 'self';media-src 'self';child-src www.owncloud.com"; + $expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self' data:;connect-src 'self';media-src 'self';child-src www.owncloud.com;frame-ancestors 'self'"; $this->contentSecurityPolicy->addAllowedChildSrcDomain('www.owncloud.com'); $this->contentSecurityPolicy->disallowChildSrcDomain('www.owncloud.org'); @@ -420,7 +420,7 @@ class ContentSecurityPolicyTest extends \Test\TestCase { } public function testGetPolicyDisallowChildSrcDomainMultipleStakes() { - $expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self';connect-src 'self';media-src 'self'"; + $expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self' data:;connect-src 'self';media-src 'self';frame-ancestors 'self'"; $this->contentSecurityPolicy->addAllowedChildSrcDomain('www.owncloud.com'); $this->contentSecurityPolicy->disallowChildSrcDomain('www.owncloud.org')->disallowChildSrcDomain('www.owncloud.com'); @@ -430,14 +430,14 @@ class ContentSecurityPolicyTest extends \Test\TestCase { public function testGetAllowedFrameAncestorDomain() { - $expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self';connect-src 'self';media-src 'self';frame-ancestors sub.nextcloud.com"; + $expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self' data:;connect-src 'self';media-src 'self';frame-ancestors 'self' sub.nextcloud.com"; $this->contentSecurityPolicy->addAllowedFrameAncestorDomain('sub.nextcloud.com'); $this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy()); } public function testGetPolicyFrameAncestorValidMultiple() { - $expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self';connect-src 'self';media-src 'self';frame-ancestors sub.nextcloud.com foo.nextcloud.com"; + $expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self' data:;connect-src 'self';media-src 'self';frame-ancestors 'self' sub.nextcloud.com foo.nextcloud.com"; $this->contentSecurityPolicy->addAllowedFrameAncestorDomain('sub.nextcloud.com'); $this->contentSecurityPolicy->addAllowedFrameAncestorDomain('foo.nextcloud.com'); @@ -445,7 +445,7 @@ class ContentSecurityPolicyTest extends \Test\TestCase { } public function testGetPolicyDisallowFrameAncestorDomain() { - $expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self';connect-src 'self';media-src 'self'"; + $expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self' data:;connect-src 'self';media-src 'self';frame-ancestors 'self'"; $this->contentSecurityPolicy->addAllowedFrameAncestorDomain('www.nextcloud.com'); $this->contentSecurityPolicy->disallowFrameAncestorDomain('www.nextcloud.com'); @@ -453,7 +453,7 @@ class ContentSecurityPolicyTest extends \Test\TestCase { } public function testGetPolicyDisallowFrameAncestorDomainMultiple() { - $expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self';connect-src 'self';media-src 'self';frame-ancestors www.nextcloud.com"; + $expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self' data:;connect-src 'self';media-src 'self';frame-ancestors 'self' www.nextcloud.com"; $this->contentSecurityPolicy->addAllowedFrameAncestorDomain('www.nextcloud.com'); $this->contentSecurityPolicy->disallowFrameAncestorDomain('www.nextcloud.org'); @@ -461,7 +461,7 @@ class ContentSecurityPolicyTest extends \Test\TestCase { } public function testGetPolicyDisallowFrameAncestorDomainMultipleStakes() { - $expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self';connect-src 'self';media-src 'self'"; + $expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self' data:;connect-src 'self';media-src 'self';frame-ancestors 'self'"; $this->contentSecurityPolicy->addAllowedChildSrcDomain('www.owncloud.com'); $this->contentSecurityPolicy->disallowChildSrcDomain('www.owncloud.org')->disallowChildSrcDomain('www.owncloud.com'); @@ -469,7 +469,7 @@ class ContentSecurityPolicyTest extends \Test\TestCase { } public function testGetPolicyUnsafeEval() { - $expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self' 'unsafe-eval';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self';connect-src 'self';media-src 'self'"; + $expectedPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self' 'unsafe-eval';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self' data:;connect-src 'self';media-src 'self';frame-ancestors 'self'"; $this->contentSecurityPolicy->allowEvalScript(true); $this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy()); diff --git a/tests/lib/AppFramework/Http/DataResponseTest.php b/tests/lib/AppFramework/Http/DataResponseTest.php index 28364d6aa77..67ffdde8669 100644 --- a/tests/lib/AppFramework/Http/DataResponseTest.php +++ b/tests/lib/AppFramework/Http/DataResponseTest.php @@ -68,7 +68,7 @@ class DataResponseTest extends \Test\TestCase { $expectedHeaders = [ 'Cache-Control' => 'no-cache, no-store, must-revalidate', - 'Content-Security-Policy' => "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self';connect-src 'self';media-src 'self'", + 'Content-Security-Policy' => "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self' data:;connect-src 'self';media-src 'self';frame-ancestors 'self'", ]; $expectedHeaders = array_merge($expectedHeaders, $headers); diff --git a/tests/lib/AppFramework/Http/ResponseTest.php b/tests/lib/AppFramework/Http/ResponseTest.php index 61cfe2cabdc..18a9a398f72 100644 --- a/tests/lib/AppFramework/Http/ResponseTest.php +++ b/tests/lib/AppFramework/Http/ResponseTest.php @@ -59,14 +59,14 @@ class ResponseTest extends \Test\TestCase { $this->childResponse->setHeaders($expected); $headers = $this->childResponse->getHeaders(); - $expected['Content-Security-Policy'] = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self';connect-src 'self';media-src 'self'"; + $expected['Content-Security-Policy'] = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self' data:;connect-src 'self';media-src 'self';frame-ancestors 'self'"; $this->assertEquals($expected, $headers); } public function testOverwriteCsp() { $expected = [ - 'Content-Security-Policy' => "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self' 'unsafe-inline';style-src 'self' 'unsafe-inline';img-src 'self';font-src 'self';connect-src 'self';media-src 'self'", + 'Content-Security-Policy' => "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self' 'unsafe-inline';style-src 'self' 'unsafe-inline';img-src 'self';font-src 'self' data:;connect-src 'self';media-src 'self'", ]; $policy = new Http\ContentSecurityPolicy(); $policy->allowInlineScript(true); diff --git a/tests/lib/AppFramework/Middleware/AdditionalScriptsMiddlewareTest.php b/tests/lib/AppFramework/Middleware/AdditionalScriptsMiddlewareTest.php new file mode 100644 index 00000000000..7f817e03c1e --- /dev/null +++ b/tests/lib/AppFramework/Middleware/AdditionalScriptsMiddlewareTest.php @@ -0,0 +1,135 @@ +<?php +declare(strict_types=1); +/** + * @copyright Copyright (c) 2019, Roeland Jago Douma <roeland@famdouma.nl> + * + * @author Roeland Jago Douma <roeland@famdouma.nl> + * + * @license GNU AGPL version 3 or any later version + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + * + */ + +namespace Test\AppFramework\Middleware; + +use OC\AppFramework\Middleware\AdditionalScriptsMiddleware; +use OCP\AppFramework\Controller; +use OCP\AppFramework\Http\Response; +use OCP\AppFramework\Http\StandaloneTemplateResponse; +use OCP\AppFramework\Http\TemplateResponse; +use OCP\AppFramework\PublicShareController; +use OCP\IUserSession; +use PHPUnit\Framework\MockObject\MockObject; +use Symfony\Component\EventDispatcher\EventDispatcherInterface; + +class AdditionalScriptsMiddlewareTest extends \Test\TestCase { + + /** @var EventDispatcherInterface|MockObject */ + private $dispatcher; + /** @var IUserSession|MockObject */ + private $userSession; + + /** @var Controller */ + private $controller; + + /** @var AdditionalScriptsMiddleware */ + private $middleWare; + + public function setUp() { + parent::setUp(); + + $this->dispatcher = $this->createMock(EventDispatcherInterface::class); + $this->userSession = $this->createMock(IUserSession::class); + $this->middleWare = new AdditionalScriptsMiddleware( + $this->dispatcher, + $this->userSession + ); + + $this->controller = $this->createMock(Controller::class); + } + + public function testNoTemplateResponse() { + $this->dispatcher->expects($this->never()) + ->method($this->anything()); + $this->userSession->expects($this->never()) + ->method($this->anything()); + + $this->middleWare->afterController($this->controller, 'myMethod', $this->createMock(Response::class)); + } + + public function testPublicShareController() { + $this->dispatcher->expects($this->never()) + ->method($this->anything()); + $this->userSession->expects($this->never()) + ->method($this->anything()); + + $this->middleWare->afterController($this->createMock(PublicShareController::class), 'myMethod', $this->createMock(Response::class)); + } + + public function testStandaloneTemplateResponse() { + $this->dispatcher->expects($this->once()) + ->method('dispatch') + ->willReturnCallback(function($eventName) { + if ($eventName === TemplateResponse::EVENT_LOAD_ADDITIONAL_SCRIPTS) { + return; + } + + $this->fail('Wrong event dispatched'); + }); + $this->userSession->expects($this->never()) + ->method($this->anything()); + + $this->middleWare->afterController($this->controller, 'myMethod', $this->createMock(StandaloneTemplateResponse::class)); + } + + public function testTemplateResponseNotLoggedIn() { + $this->dispatcher->expects($this->once()) + ->method('dispatch') + ->willReturnCallback(function($eventName) { + if ($eventName === TemplateResponse::EVENT_LOAD_ADDITIONAL_SCRIPTS) { + return; + } + + $this->fail('Wrong event dispatched'); + }); + $this->userSession->method('isLoggedIn') + ->willReturn(false); + + $this->middleWare->afterController($this->controller, 'myMethod', $this->createMock(TemplateResponse::class)); + } + + public function testTemplateResponseLoggedIn() { + $events = []; + + $this->dispatcher->expects($this->exactly(2)) + ->method('dispatch') + ->willReturnCallback(function($eventName) use (&$events) { + if ($eventName === TemplateResponse::EVENT_LOAD_ADDITIONAL_SCRIPTS || + $eventName === TemplateResponse::EVENT_LOAD_ADDITIONAL_SCRIPTS_LOGGEDIN) { + $events[] = $eventName; + return; + } + + $this->fail('Wrong event dispatched'); + }); + $this->userSession->method('isLoggedIn') + ->willReturn(true); + + $this->middleWare->afterController($this->controller, 'myMethod', $this->createMock(TemplateResponse::class)); + + $this->assertContains(TemplateResponse::EVENT_LOAD_ADDITIONAL_SCRIPTS, $events); + $this->assertContains(TemplateResponse::EVENT_LOAD_ADDITIONAL_SCRIPTS_LOGGEDIN, $events); + } +} diff --git a/tests/lib/AppFramework/Routing/RoutingTest.php b/tests/lib/AppFramework/Routing/RoutingTest.php index 76533fff014..fccece481ce 100644 --- a/tests/lib/AppFramework/Routing/RoutingTest.php +++ b/tests/lib/AppFramework/Routing/RoutingTest.php @@ -6,6 +6,9 @@ use OC\AppFramework\DependencyInjection\DIContainer; use OC\AppFramework\Routing\RouteActionHandler; use OC\AppFramework\Routing\RouteConfig; use OCP\ILogger; +use OCP\Route\IRouter; +use PHPUnit\Framework\MockObject\MockObject; +use OC\Route\Router; class RoutingTest extends \Test\TestCase { @@ -179,6 +182,27 @@ class RoutingTest extends \Test\TestCase $this->assertSimpleOCSRoute($routes, 'admin_folders.open_current', 'DELETE', '/apps/app1/folders/{folderId}/open', 'AdminFoldersController', 'openCurrent'); } + public function testOCSResource() + { + $routes = ['ocs-resources' => ['account' => ['url' => '/accounts']]]; + + $this->assertOCSResource($routes, 'account', '/apps/app1/accounts', 'AccountController', 'id'); + } + + public function testOCSResourceWithUnderScoreName() + { + $routes = ['ocs-resources' => ['admin_accounts' => ['url' => '/admin/accounts']]]; + + $this->assertOCSResource($routes, 'admin_accounts', '/apps/app1/admin/accounts', 'AdminAccountsController', 'id'); + } + + public function testOCSResourceWithRoot() + { + $routes = ['ocs-resources' => ['admin_accounts' => ['url' => '/admin/accounts', 'root' => '/core/endpoint']]]; + + $this->assertOCSResource($routes, 'admin_accounts', '/core/endpoint/admin/accounts', 'AdminAccountsController', 'id'); + } + public function testResource() { $routes = array('resources' => array('account' => array('url' => '/accounts'))); @@ -278,6 +302,67 @@ class RoutingTest extends \Test\TestCase } /** + * @param array $yaml + * @param string $resourceName + * @param string $url + * @param string $controllerName + * @param string $paramName + */ + private function assertOCSResource($yaml, $resourceName, $url, $controllerName, $paramName): void { + /** @var IRouter|MockObject $router */ + $router = $this->getMockBuilder(Router::class) + ->setMethods(['create']) + ->setConstructorArgs([$this->getMockBuilder(ILogger::class)->getMock()]) + ->getMock(); + + // route mocks + $container = new DIContainer('app1'); + $indexRoute = $this->mockRoute($container, 'GET', $controllerName, 'index'); + $showRoute = $this->mockRoute($container, 'GET', $controllerName, 'show'); + $createRoute = $this->mockRoute($container, 'POST', $controllerName, 'create'); + $updateRoute = $this->mockRoute($container, 'PUT', $controllerName, 'update'); + $destroyRoute = $this->mockRoute($container, 'DELETE', $controllerName, 'destroy'); + + $urlWithParam = $url . '/{' . $paramName . '}'; + + // we expect create to be called once: + $router + ->expects($this->at(0)) + ->method('create') + ->with($this->equalTo('ocs.app1.' . $resourceName . '.index'), $this->equalTo($url)) + ->willReturn($indexRoute); + + $router + ->expects($this->at(1)) + ->method('create') + ->with($this->equalTo('ocs.app1.' . $resourceName . '.show'), $this->equalTo($urlWithParam)) + ->willReturn($showRoute); + + $router + ->expects($this->at(2)) + ->method('create') + ->with($this->equalTo('ocs.app1.' . $resourceName . '.create'), $this->equalTo($url)) + ->willReturn($createRoute); + + $router + ->expects($this->at(3)) + ->method('create') + ->with($this->equalTo('ocs.app1.' . $resourceName . '.update'), $this->equalTo($urlWithParam)) + ->willReturn($updateRoute); + + $router + ->expects($this->at(4)) + ->method('create') + ->with($this->equalTo('ocs.app1.' . $resourceName . '.destroy'), $this->equalTo($urlWithParam)) + ->willReturn($destroyRoute); + + // load route configuration + $config = new RouteConfig($container, $router, $yaml); + + $config->register(); + } + + /** * @param string $resourceName * @param string $url * @param string $controllerName diff --git a/tests/lib/AvatarManagerTest.php b/tests/lib/Avatar/AvatarManagerTest.php index 9f2a4f4f337..7466f664eb5 100644 --- a/tests/lib/AvatarManagerTest.php +++ b/tests/lib/Avatar/AvatarManagerTest.php @@ -22,11 +22,10 @@ * */ -namespace Test; +namespace Test\Avatar; -use OC\Avatar; -use OC\AvatarManager; -use OC\Files\AppData\AppData; +use OC\Avatar\UserAvatar; +use OC\Avatar\AvatarManager; use OC\User\Manager; use OCP\Files\IAppData; use OCP\Files\SimpleFS\ISimpleFolder; @@ -34,7 +33,6 @@ use OCP\IConfig; use OCP\IL10N; use OCP\ILogger; use OCP\IUser; -use OCP\IUserManager; /** * Class AvatarManagerTest @@ -103,7 +101,7 @@ class AvatarManagerTest extends \Test\TestCase { ->with('valid-user') ->willReturn($folder); - $expected = new Avatar($folder, $this->l10n, $user, $this->logger, $this->config); + $expected = new UserAvatar($folder, $this->l10n, $user, $this->logger, $this->config); $this->assertEquals($expected, $this->avatarManager->getAvatar('valid-user')); } @@ -125,7 +123,7 @@ class AvatarManagerTest extends \Test\TestCase { ->with('valid-user') ->willReturn($folder); - $expected = new Avatar($folder, $this->l10n, $user, $this->logger, $this->config); + $expected = new UserAvatar($folder, $this->l10n, $user, $this->logger, $this->config); $this->assertEquals($expected, $this->avatarManager->getAvatar('vaLid-USER')); } } diff --git a/tests/lib/Avatar/GuestAvatarTest.php b/tests/lib/Avatar/GuestAvatarTest.php new file mode 100644 index 00000000000..0d13655133b --- /dev/null +++ b/tests/lib/Avatar/GuestAvatarTest.php @@ -0,0 +1,80 @@ +<?php +declare(strict_types=1); + +/** + * @copyright Copyright (c) 2018, Michael Weimann <mail@michael-weimann.eu> + * + * @author Michael Weimann <mail@michael-weimann.eu> + * + * @license AGPL-3.0 + * + * This code is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License, version 3, + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License, version 3, + * along with this program. If not, see <http://www.gnu.org/licenses/> + */ + +namespace Test\Avatar; + +use OC\Avatar\GuestAvatar; +use OCP\Files\SimpleFS\InMemoryFile; +use OCP\ILogger; +use PHPUnit\Framework\MockObject\MockObject; +use Test\TestCase; + +/** + * This class provides test cases for the GuestAvatar class. + * + * @package Test\Avatar + */ +class GuestAvatarTest extends TestCase { + /** + * @var GuestAvatar + */ + private $guestAvatar; + + /** + * Setups a guest avatar instance for tests. + * + * @before + * @return void + */ + public function setupGuestAvatar() { + /* @var MockObject|ILogger $logger */ + $logger = $this->getMockBuilder(ILogger::class)->getMock(); + $this->guestAvatar = new GuestAvatar('einstein', $logger); + } + + /** + * Asserts that testGet() returns the expected avatar. + * + * For the test a static name "einstein" is used and + * the generated image is compared with an expected one. + * + * @return void + */ + public function testGet() { + $avatar = $this->guestAvatar->getFile(32); + self::assertInstanceOf(InMemoryFile::class, $avatar); + $expectedFile = file_get_contents( + __DIR__ . '/../../data/guest_avatar_einstein_32.png' + ); + self::assertEquals(trim($expectedFile), trim($avatar->getContent())); + } + + /** + * Asserts that "testIsCustomAvatar" returns false for guests. + * + * @return void + */ + public function testIsCustomAvatar() { + self::assertFalse($this->guestAvatar->isCustomAvatar()); + } +} diff --git a/tests/lib/AvatarTest.php b/tests/lib/Avatar/UserAvatarTest.php index c8c9d3b8317..049725c78c9 100644 --- a/tests/lib/AvatarTest.php +++ b/tests/lib/Avatar/UserAvatarTest.php @@ -6,7 +6,7 @@ * See the COPYING-README file. */ -namespace Test; +namespace Test\Avatar; use OC\Files\SimpleFS\SimpleFolder; use OC\User\User; @@ -18,11 +18,11 @@ use OCP\IConfig; use OCP\IL10N; use OCP\ILogger; -class AvatarTest extends \Test\TestCase { +class UserAvatarTest extends \Test\TestCase { /** @var Folder | \PHPUnit_Framework_MockObject_MockObject */ private $folder; - /** @var \OC\Avatar */ + /** @var \OC\Avatar\UserAvatar */ private $avatar; /** @var \OC\User\User | \PHPUnit_Framework_MockObject_MockObject $user */ @@ -41,7 +41,7 @@ class AvatarTest extends \Test\TestCase { $this->user = $this->createMock(User::class); $this->config = $this->createMock(IConfig::class); - $this->avatar = new \OC\Avatar( + $this->avatar = new \OC\Avatar\UserAvatar( $this->folder, $l, $this->user, diff --git a/tests/lib/Collaboration/Collaborators/GroupPluginTest.php b/tests/lib/Collaboration/Collaborators/GroupPluginTest.php index 9849bdb874a..36d98ee302f 100644 --- a/tests/lib/Collaboration/Collaborators/GroupPluginTest.php +++ b/tests/lib/Collaboration/Collaborators/GroupPluginTest.php @@ -101,9 +101,10 @@ class GroupPluginTest extends TestCase { /** * @param string $gid * @param null $displayName + * @param bool $hide * @return IGroup|\PHPUnit_Framework_MockObject_MockObject */ - protected function getGroupMock($gid, $displayName = null) { + protected function getGroupMock($gid, $displayName = null, $hide = false) { $group = $this->createMock(IGroup::class); $group->expects($this->any()) @@ -119,6 +120,9 @@ class GroupPluginTest extends TestCase { ->method('getDisplayName') ->willReturn($displayName); + $group->method('hideFromCollaboration') + ->willReturn($hide); + return $group; } @@ -413,7 +417,20 @@ class GroupPluginTest extends TestCase { true, $this->getGroupMock('test'), ], + [ + 'test', false, false, + [ + $this->getGroupMock('test', null, true), + $this->getGroupMock('test1'), + ], + [], + [], + [], + true, + false, + ], ]; + } /** diff --git a/tests/lib/Collaboration/Collaborators/LookupPluginTest.php b/tests/lib/Collaboration/Collaborators/LookupPluginTest.php index 98e4adf2a7c..e4be6a73ee1 100644 --- a/tests/lib/Collaboration/Collaborators/LookupPluginTest.php +++ b/tests/lib/Collaboration/Collaborators/LookupPluginTest.php @@ -90,7 +90,7 @@ class LookupPluginTest extends TestCase { public function testSearchNoLookupServerURI() { $this->config->expects($this->once()) ->method('getAppValue') - ->with('files_sharing', 'lookupServerEnabled', 'no') + ->with('files_sharing', 'lookupServerEnabled', 'yes') ->willReturn('yes'); $this->config->expects($this->at(0)) ->method('getSystemValue') @@ -118,7 +118,7 @@ class LookupPluginTest extends TestCase { public function testSearchNoInternet() { $this->config->expects($this->once()) ->method('getAppValue') - ->with('files_sharing', 'lookupServerEnabled', 'no') + ->with('files_sharing', 'lookupServerEnabled', 'yes') ->willReturn('yes'); $this->config->expects($this->at(0)) ->method('getSystemValue') @@ -154,7 +154,7 @@ class LookupPluginTest extends TestCase { $this->config->expects($this->once()) ->method('getAppValue') - ->with('files_sharing', 'lookupServerEnabled', 'no') + ->with('files_sharing', 'lookupServerEnabled', 'yes') ->willReturn('yes'); $this->config->expects($this->at(0)) ->method('getSystemValue') @@ -213,7 +213,7 @@ class LookupPluginTest extends TestCase { $this->config->expects($this->once()) ->method('getAppValue') - ->with('files_sharing', 'lookupServerEnabled', 'no') + ->with('files_sharing', 'lookupServerEnabled', 'yes') ->willReturn($LookupEnabled ? 'yes' : 'no'); $this->config->expects($this->at(0)) ->method('getSystemValue') @@ -267,7 +267,7 @@ class LookupPluginTest extends TestCase { public function testSearchLookupServerDisabled() { $this->config->expects($this->once()) ->method('getAppValue') - ->with('files_sharing', 'lookupServerEnabled', 'no') + ->with('files_sharing', 'lookupServerEnabled', 'yes') ->willReturn('no'); /** @var ISearchResult|\PHPUnit_Framework_MockObject_MockObject $searchResult */ diff --git a/tests/lib/Command/AsyncBusTest.php b/tests/lib/Command/AsyncBusTest.php index da168d66e6d..8f07738bec6 100644 --- a/tests/lib/Command/AsyncBusTest.php +++ b/tests/lib/Command/AsyncBusTest.php @@ -136,7 +136,7 @@ abstract class AsyncBusTest extends TestCase { public function testClosureSelf() { $this->getBus()->push(function () { - self::$lastCommand = 'closure-self'; + AsyncBusTest::$lastCommand = 'closure-self'; }); $this->runJobs(); $this->assertEquals('closure-self', self::$lastCommand); @@ -154,7 +154,7 @@ abstract class AsyncBusTest extends TestCase { public function testClosureBind() { $state = 'bar'; $this->getBus()->push(function () use ($state) { - self::$lastCommand = 'closure-' . $state; + AsyncBusTest::$lastCommand = 'closure-' . $state; }); $this->runJobs(); $this->assertEquals('closure-bar', self::$lastCommand); diff --git a/tests/lib/DB/MigrationsTest.php b/tests/lib/DB/MigrationsTest.php index 7e201191087..8654c83a545 100644 --- a/tests/lib/DB/MigrationsTest.php +++ b/tests/lib/DB/MigrationsTest.php @@ -16,6 +16,7 @@ use Doctrine\DBAL\Schema\Column; use Doctrine\DBAL\Schema\ForeignKeyConstraint; use Doctrine\DBAL\Schema\Index; use Doctrine\DBAL\Schema\Schema; +use Doctrine\DBAL\Schema\SchemaException; use Doctrine\DBAL\Schema\Sequence; use Doctrine\DBAL\Schema\Table; use OC\DB\Connection; @@ -102,13 +103,12 @@ class MigrationsTest extends \Test\TestCase { ->method('migrateToSchema'); $wrappedSchema = $this->createMock(Schema::class); - // TODO re-enable once stable14 is branched of: https://github.com/nextcloud/server/issues/10518 - /*$wrappedSchema->expects($this->once()) + $wrappedSchema->expects($this->once()) ->method('getTables') ->willReturn([]); $wrappedSchema->expects($this->once()) ->method('getSequences') - ->willReturn([]);*/ + ->willReturn([]); $schemaResult = $this->createMock(SchemaWrapper::class); $schemaResult->expects($this->once()) @@ -239,12 +239,12 @@ class MigrationsTest extends \Test\TestCase { ->willReturn(\str_repeat('a', 30)); $table = $this->createMock(Table::class); - $table->expects($this->once()) + $table->expects($this->atLeastOnce()) ->method('getName') ->willReturn(\str_repeat('a', 30)); $sequence = $this->createMock(Sequence::class); - $sequence->expects($this->once()) + $sequence->expects($this->atLeastOnce()) ->method('getName') ->willReturn(\str_repeat('a', 30)); @@ -269,7 +269,15 @@ class MigrationsTest extends \Test\TestCase { ->method('getSequences') ->willReturn([$sequence]); - self::invokePrivate($this->migrationService, 'ensureOracleIdentifierLengthLimit', [$schema, 3]); + $sourceSchema = $this->createMock(Schema::class); + $sourceSchema->expects($this->any()) + ->method('getTable') + ->willThrowException(new SchemaException()); + $sourceSchema->expects($this->any()) + ->method('hasSequence') + ->willReturn(false); + + self::invokePrivate($this->migrationService, 'ensureOracleIdentifierLengthLimit', [$sourceSchema, $schema, 3]); } public function testEnsureOracleIdentifierLengthLimitValidWithPrimaryKey() { @@ -304,7 +312,15 @@ class MigrationsTest extends \Test\TestCase { ->method('getSequences') ->willReturn([]); - self::invokePrivate($this->migrationService, 'ensureOracleIdentifierLengthLimit', [$schema, 3]); + $sourceSchema = $this->createMock(Schema::class); + $sourceSchema->expects($this->any()) + ->method('getTable') + ->willThrowException(new SchemaException()); + $sourceSchema->expects($this->any()) + ->method('hasSequence') + ->willReturn(false); + + self::invokePrivate($this->migrationService, 'ensureOracleIdentifierLengthLimit', [$sourceSchema, $schema, 3]); } public function testEnsureOracleIdentifierLengthLimitValidWithPrimaryKeyDefault() { @@ -349,7 +365,15 @@ class MigrationsTest extends \Test\TestCase { ->method('getSequences') ->willReturn([]); - self::invokePrivate($this->migrationService, 'ensureOracleIdentifierLengthLimit', [$schema, 3]); + $sourceSchema = $this->createMock(Schema::class); + $sourceSchema->expects($this->any()) + ->method('getTable') + ->willThrowException(new SchemaException()); + $sourceSchema->expects($this->any()) + ->method('hasSequence') + ->willReturn(false); + + self::invokePrivate($this->migrationService, 'ensureOracleIdentifierLengthLimit', [$sourceSchema, $schema, 3]); } /** @@ -366,7 +390,15 @@ class MigrationsTest extends \Test\TestCase { ->method('getTables') ->willReturn([$table]); - self::invokePrivate($this->migrationService, 'ensureOracleIdentifierLengthLimit', [$schema, 3]); + $sourceSchema = $this->createMock(Schema::class); + $sourceSchema->expects($this->any()) + ->method('getTable') + ->willThrowException(new SchemaException()); + $sourceSchema->expects($this->any()) + ->method('hasSequence') + ->willReturn(false); + + self::invokePrivate($this->migrationService, 'ensureOracleIdentifierLengthLimit', [$sourceSchema, $schema, 3]); } /** @@ -411,7 +443,15 @@ class MigrationsTest extends \Test\TestCase { ->method('getTables') ->willReturn([$table]); - self::invokePrivate($this->migrationService, 'ensureOracleIdentifierLengthLimit', [$schema, 3]); + $sourceSchema = $this->createMock(Schema::class); + $sourceSchema->expects($this->any()) + ->method('getTable') + ->willThrowException(new SchemaException()); + $sourceSchema->expects($this->any()) + ->method('hasSequence') + ->willReturn(false); + + self::invokePrivate($this->migrationService, 'ensureOracleIdentifierLengthLimit', [$sourceSchema, $schema, 3]); } /** @@ -446,7 +486,15 @@ class MigrationsTest extends \Test\TestCase { ->method('getTables') ->willReturn([$table]); - self::invokePrivate($this->migrationService, 'ensureOracleIdentifierLengthLimit', [$schema, 3]); + $sourceSchema = $this->createMock(Schema::class); + $sourceSchema->expects($this->any()) + ->method('getTable') + ->willThrowException(new SchemaException()); + $sourceSchema->expects($this->any()) + ->method('hasSequence') + ->willReturn(false); + + self::invokePrivate($this->migrationService, 'ensureOracleIdentifierLengthLimit', [$sourceSchema, $schema, 3]); } /** @@ -472,7 +520,15 @@ class MigrationsTest extends \Test\TestCase { ->method('getTables') ->willReturn([$table]); - self::invokePrivate($this->migrationService, 'ensureOracleIdentifierLengthLimit', [$schema, 3]); + $sourceSchema = $this->createMock(Schema::class); + $sourceSchema->expects($this->any()) + ->method('getTable') + ->willThrowException(new SchemaException()); + $sourceSchema->expects($this->any()) + ->method('hasSequence') + ->willReturn(false); + + self::invokePrivate($this->migrationService, 'ensureOracleIdentifierLengthLimit', [$sourceSchema, $schema, 3]); } /** @@ -501,7 +557,15 @@ class MigrationsTest extends \Test\TestCase { ->method('getTables') ->willReturn([$table]); - self::invokePrivate($this->migrationService, 'ensureOracleIdentifierLengthLimit', [$schema, 3]); + $sourceSchema = $this->createMock(Schema::class); + $sourceSchema->expects($this->any()) + ->method('getTable') + ->willThrowException(new SchemaException()); + $sourceSchema->expects($this->any()) + ->method('hasSequence') + ->willReturn(false); + + self::invokePrivate($this->migrationService, 'ensureOracleIdentifierLengthLimit', [$sourceSchema, $schema, 3]); } /** @@ -533,7 +597,15 @@ class MigrationsTest extends \Test\TestCase { ->method('getTables') ->willReturn([$table]); - self::invokePrivate($this->migrationService, 'ensureOracleIdentifierLengthLimit', [$schema, 3]); + $sourceSchema = $this->createMock(Schema::class); + $sourceSchema->expects($this->any()) + ->method('getTable') + ->willThrowException(new SchemaException()); + $sourceSchema->expects($this->any()) + ->method('hasSequence') + ->willReturn(false); + + self::invokePrivate($this->migrationService, 'ensureOracleIdentifierLengthLimit', [$sourceSchema, $schema, 3]); } /** @@ -553,6 +625,14 @@ class MigrationsTest extends \Test\TestCase { ->method('getSequences') ->willReturn([$sequence]); - self::invokePrivate($this->migrationService, 'ensureOracleIdentifierLengthLimit', [$schema, 3]); + $sourceSchema = $this->createMock(Schema::class); + $sourceSchema->expects($this->any()) + ->method('getTable') + ->willThrowException(new SchemaException()); + $sourceSchema->expects($this->any()) + ->method('hasSequence') + ->willReturn(false); + + self::invokePrivate($this->migrationService, 'ensureOracleIdentifierLengthLimit', [$sourceSchema, $schema, 3]); } } diff --git a/tests/lib/Files/Cache/CacheTest.php b/tests/lib/Files/Cache/CacheTest.php index d984964ca9f..f94b4f57078 100644 --- a/tests/lib/Files/Cache/CacheTest.php +++ b/tests/lib/Files/Cache/CacheTest.php @@ -332,7 +332,7 @@ class CacheTest extends \Test\TestCase { $userId = $this->getUniqueId('user'); \OC::$server->getUserManager()->createUser($userId, $userId); $this->loginAsUser($userId); - $user = new \OC\User\User($userId, null); + $user = new \OC\User\User($userId, null, \OC::$server->getEventDispatcher()); $file1 = 'folder'; $file2 = 'folder/foobar'; @@ -402,7 +402,7 @@ class CacheTest extends \Test\TestCase { $userId = static::getUniqueID('user'); \OC::$server->getUserManager()->createUser($userId, $userId); static::loginAsUser($userId); - $user = new \OC\User\User($userId, null); + $user = new \OC\User\User($userId, null, \OC::$server->getEventDispatcher()); $file1 = 'folder'; $file2 = 'folder/foobar'; diff --git a/tests/lib/Files/Config/UserMountCacheTest.php b/tests/lib/Files/Config/UserMountCacheTest.php index ddf40a2b5e5..299ec1a4378 100644 --- a/tests/lib/Files/Config/UserMountCacheTest.php +++ b/tests/lib/Files/Config/UserMountCacheTest.php @@ -17,6 +17,7 @@ use OC\Files\Storage\Storage; use OCP\IConfig; use OCP\IDBConnection; use OCP\IUserManager; +use Symfony\Component\EventDispatcher\EventDispatcherInterface; use Test\TestCase; use Test\Util\User\Dummy; @@ -44,7 +45,7 @@ class UserMountCacheTest extends TestCase { public function setUp() { $this->fileIds = []; $this->connection = \OC::$server->getDatabaseConnection(); - $this->userManager = new Manager($this->createMock(IConfig::class)); + $this->userManager = new Manager($this->createMock(IConfig::class), $this->createMock(EventDispatcherInterface::class)); $userBackend = new Dummy(); $userBackend->createUser('u1', ''); $userBackend->createUser('u2', ''); diff --git a/tests/lib/Files/FileInfoTest.php b/tests/lib/Files/FileInfoTest.php index ee7a10ccec4..b1ab880ad70 100644 --- a/tests/lib/Files/FileInfoTest.php +++ b/tests/lib/Files/FileInfoTest.php @@ -14,6 +14,7 @@ use OC\Files\Storage\Home; use OC\Files\Storage\Temporary; use OC\User\User; use OCP\IConfig; +use OCP\IUser; use Test\TestCase; use Test\Traits\UserTrait; @@ -29,9 +30,15 @@ class FileInfoTest extends TestCase { } public function testIsMountedHomeStorage() { + $user = $this->createMock(IUser::class); + $user->method('getUID') + ->willReturn('foo'); + $user->method('getHome') + ->willReturn('foo'); + $fileInfo = new FileInfo( '', - new Home(['user' => new User('foo', $this->userBackend, null, $this->config)]), + new Home(['user' => $user]), '', [], null); $this->assertFalse($fileInfo->isMounted()); } diff --git a/tests/lib/Files/Node/FolderTest.php b/tests/lib/Files/Node/FolderTest.php index 2c87b645dd9..e1ee96c37ec 100644 --- a/tests/lib/Files/Node/FolderTest.php +++ b/tests/lib/Files/Node/FolderTest.php @@ -290,7 +290,8 @@ class FolderTest extends NodeTest { ->method('getUser') ->will($this->returnValue($this->user)); $storage = $this->createMock(Storage::class); - $cache = $this->getMockBuilder(Cache::class)->setConstructorArgs([''])->getMock(); + $storage->method('getId')->willReturn(''); + $cache = $this->getMockBuilder(Cache::class)->setConstructorArgs([$storage])->getMock(); $storage->expects($this->once()) ->method('getCache') @@ -340,8 +341,10 @@ class FolderTest extends NodeTest { $root->expects($this->any()) ->method('getUser') ->will($this->returnValue($this->user)); + /** @var \PHPUnit_Framework_MockObject_MockObject|Storage $storage */ $storage = $this->createMock(Storage::class); - $cache = $this->getMockBuilder(Cache::class)->setConstructorArgs([''])->getMock(); + $storage->method('getId')->willReturn(''); + $cache = $this->getMockBuilder(Cache::class)->setConstructorArgs([$storage])->getMock(); $mount = $this->createMock(IMountPoint::class); $mount->expects($this->once()) @@ -391,7 +394,8 @@ class FolderTest extends NodeTest { ->method('getUser') ->will($this->returnValue($this->user)); $storage = $this->createMock(Storage::class); - $cache = $this->getMockBuilder(Cache::class)->setConstructorArgs([''])->getMock(); + $storage->method('getId')->willReturn(''); + $cache = $this->getMockBuilder(Cache::class)->setConstructorArgs([$storage])->getMock(); $mount = $this->createMock(IMountPoint::class); $mount->expects($this->once()) @@ -441,7 +445,8 @@ class FolderTest extends NodeTest { ->method('getUser') ->will($this->returnValue($this->user)); $storage = $this->createMock(Storage::class); - $cache = $this->getMockBuilder(Cache::class)->setConstructorArgs([''])->getMock(); + $storage->method('getId')->willReturn(''); + $cache = $this->getMockBuilder(Cache::class)->setConstructorArgs([$storage])->getMock(); $mount = $this->createMock(IMountPoint::class); $mount->expects($this->once()) @@ -491,8 +496,9 @@ class FolderTest extends NodeTest { ->method('getUser') ->will($this->returnValue($this->user)); $storage = $this->createMock(Storage::class); - $cache = $this->getMockBuilder(Cache::class)->setConstructorArgs([''])->getMock(); - $subCache = $this->getMockBuilder(Cache::class)->setConstructorArgs([''])->getMock(); + $storage->method('getId')->willReturn(''); + $cache = $this->getMockBuilder(Cache::class)->setConstructorArgs([$storage])->getMock(); + $subCache = $this->getMockBuilder(Cache::class)->setConstructorArgs([$storage])->getMock(); $subStorage = $this->createMock(Storage::class); $subMount = $this->getMockBuilder(MountPoint::class)->setConstructorArgs([null, ''])->getMock(); @@ -572,7 +578,8 @@ class FolderTest extends NodeTest { ->getMock(); $storage = $this->createMock(\OC\Files\Storage\Storage::class); $mount = new MountPoint($storage, '/bar'); - $cache = $this->getMockBuilder(Cache::class)->setConstructorArgs([''])->getMock(); + $storage->method('getId')->willReturn(''); + $cache = $this->getMockBuilder(Cache::class)->setConstructorArgs([$storage])->getMock(); $fileInfo = new CacheEntry(['path' => 'foo/qwerty', 'mimetype' => 'text/plain'], null); @@ -625,7 +632,8 @@ class FolderTest extends NodeTest { ->getMock(); $storage = $this->createMock(\OC\Files\Storage\Storage::class); $mount = new MountPoint($storage, '/bar'); - $cache = $this->getMockBuilder(Cache::class)->setConstructorArgs([''])->getMock(); + $storage->method('getId')->willReturn(''); + $cache = $this->getMockBuilder(Cache::class)->setConstructorArgs([$storage])->getMock(); $fileInfo = new CacheEntry(['path' => '', 'mimetype' => 'text/plain'], null); @@ -673,7 +681,8 @@ class FolderTest extends NodeTest { ->getMock(); $storage = $this->createMock(\OC\Files\Storage\Storage::class); $mount = new MountPoint($storage, '/bar'); - $cache = $this->getMockBuilder(Cache::class)->setConstructorArgs([''])->getMock(); + $storage->method('getId')->willReturn(''); + $cache = $this->getMockBuilder(Cache::class)->setConstructorArgs([$storage])->getMock(); $fileInfo = new CacheEntry(['path' => 'foobar', 'mimetype' => 'text/plain'], null); @@ -726,7 +735,8 @@ class FolderTest extends NodeTest { $storage = $this->createMock(\OC\Files\Storage\Storage::class); $mount1 = new MountPoint($storage, '/bar'); $mount2 = new MountPoint($storage, '/bar/foo/asd'); - $cache = $this->getMockBuilder(Cache::class)->setConstructorArgs([''])->getMock(); + $storage->method('getId')->willReturn(''); + $cache = $this->getMockBuilder(Cache::class)->setConstructorArgs([$storage])->getMock(); $fileInfo = new CacheEntry(['path' => 'foo/qwerty', 'mimetype' => 'text/plain'], null); diff --git a/tests/lib/Files/Node/IntegrationTest.php b/tests/lib/Files/Node/IntegrationTest.php index b5cd832d1dd..6d9b0ce20b9 100644 --- a/tests/lib/Files/Node/IntegrationTest.php +++ b/tests/lib/Files/Node/IntegrationTest.php @@ -45,7 +45,7 @@ class IntegrationTest extends \Test\TestCase { \OC_Hook::clear('OC_Filesystem'); - $user = new User($this->getUniqueID('user'), new \Test\Util\User\Dummy); + $user = new User($this->getUniqueID('user'), new \Test\Util\User\Dummy, \OC::$server->getEventDispatcher()); $this->loginAsUser($user->getUID()); $this->view = new View(); diff --git a/tests/lib/Files/Node/NodeTest.php b/tests/lib/Files/Node/NodeTest.php index 9200ae69f75..dee5a0211c5 100644 --- a/tests/lib/Files/Node/NodeTest.php +++ b/tests/lib/Files/Node/NodeTest.php @@ -18,6 +18,7 @@ use OCP\Files\Storage; use OCP\IConfig; use OCP\ILogger; use OCP\IURLGenerator; +use OCP\IUser; use OCP\IUserManager; use OCP\Files\NotFoundException; @@ -45,14 +46,7 @@ abstract class NodeTest extends \Test\TestCase { protected function setUp() { parent::setUp(); - $config = $this->getMockBuilder(IConfig::class) - ->disableOriginalConstructor() - ->getMock(); - $urlGenerator = $this->getMockBuilder(IURLGenerator - ::class) - ->disableOriginalConstructor() - ->getMock(); - $this->user = new \OC\User\User('', new \Test\Util\User\Dummy, null, $config, $urlGenerator); + $this->user = $this->createMock(IUser::class); $this->manager = $this->getMockBuilder(Manager::class) ->disableOriginalConstructor() ->getMock(); diff --git a/tests/lib/Files/Node/RootTest.php b/tests/lib/Files/Node/RootTest.php index fd050c8d90c..8a6e5411f26 100644 --- a/tests/lib/Files/Node/RootTest.php +++ b/tests/lib/Files/Node/RootTest.php @@ -39,14 +39,7 @@ class RootTest extends \Test\TestCase { protected function setUp() { parent::setUp(); - $config = $this->getMockBuilder(IConfig::class) - ->disableOriginalConstructor() - ->getMock(); - $urlgenerator = $this->getMockBuilder(IURLGenerator::class) - ->disableOriginalConstructor() - ->getMock(); - - $this->user = new \OC\User\User('', new \Test\Util\User\Dummy, null, $config, $urlgenerator); + $this->user = $this->createMock(IUser::class); $this->manager = $this->getMockBuilder(Manager::class) ->disableOriginalConstructor() ->getMock(); diff --git a/tests/lib/Files/ObjectStore/FailWriteObjectStore.php b/tests/lib/Files/ObjectStore/FailWriteObjectStore.php new file mode 100644 index 00000000000..4310d8ba27c --- /dev/null +++ b/tests/lib/Files/ObjectStore/FailWriteObjectStore.php @@ -0,0 +1,53 @@ +<?php declare(strict_types=1); +/** + * @copyright Copyright (c) 2018 Robin Appelman <robin@icewind.nl> + * + * @license GNU AGPL version 3 or any later version + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + * + */ + +namespace Test\Files\ObjectStore; + +use OCP\Files\ObjectStore\IObjectStore; + +class FailWriteObjectStore implements IObjectStore { + private $objectStore; + + public function __construct(IObjectStore $objectStore) { + $this->objectStore = $objectStore; + } + + public function getStorageId() { + return $this->objectStore->getStorageId(); + } + + public function readObject($urn) { + return $this->objectStore->readObject($urn); + } + + public function writeObject($urn, $stream) { + // emulate a failed write that didn't throw an error + return true; + } + + public function deleteObject($urn) { + $this->objectStore->deleteObject($urn); + } + + public function objectExists($urn) { + return $this->objectStore->objectExists($urn); + } +} diff --git a/tests/lib/Files/Stream/CountReadStreamTest.php b/tests/lib/Files/ObjectStore/ObjectStoreStorageOverwrite.php index 99291d1644f..5e8faed3347 100644 --- a/tests/lib/Files/Stream/CountReadStreamTest.php +++ b/tests/lib/Files/ObjectStore/ObjectStoreStorageOverwrite.php @@ -19,31 +19,20 @@ * */ -namespace Test\Files\Stream; +namespace Test\Files\ObjectStore; -use OC\Files\Stream\CountReadStream; -use Test\TestCase; +use OC\Files\ObjectStore\ObjectStoreStorage; +use OCP\Files\ObjectStore\IObjectStore; -class CountReadStreamTest extends TestCase { - private function getStream($data) { - $handle = fopen('php://temp', 'w+'); - fwrite($handle, $data); - rewind($handle); - return $handle; - } - - public function testBasicCount() { - $source = $this->getStream('foo'); - $stream = CountReadStream::wrap($source, function ($size) { - $this->assertEquals(3, $size); - }); - stream_get_contents($stream); +/** + * Allow overwriting the object store instance for test purposes + */ +class ObjectStoreStorageOverwrite extends ObjectStoreStorage { + public function setObjectStore(IObjectStore $objectStore) { + $this->objectStore = $objectStore; } - public function testLarger() { - $stream = CountReadStream::wrap(fopen(__DIR__ . '/../../../data/testimage.mp4', 'r'), function ($size) { - $this->assertEquals(383631, $size); - }); - stream_get_contents($stream); + public function getObjectStore(): IObjectStore { + return $this->objectStore; } } diff --git a/tests/lib/Files/ObjectStore/ObjectStoreStorageTest.php b/tests/lib/Files/ObjectStore/ObjectStoreStorageTest.php index c9d6c1bd922..3b3827f460a 100644 --- a/tests/lib/Files/ObjectStore/ObjectStoreStorageTest.php +++ b/tests/lib/Files/ObjectStore/ObjectStoreStorageTest.php @@ -30,6 +30,8 @@ use Test\Files\Storage\Storage; * @group DB */ class ObjectStoreStorageTest extends Storage { + /** @var ObjectStoreStorageOverwrite */ + protected $instance; /** * @var IObjectStore @@ -42,7 +44,7 @@ class ObjectStoreStorageTest extends Storage { $baseStorage = new Temporary(); $this->objectStorage = new StorageObjectStore($baseStorage); $config['objectstore'] = $this->objectStorage; - $this->instance = new ObjectStoreStorage($config); + $this->instance = new ObjectStoreStorageOverwrite($config); } protected function tearDown() { @@ -166,4 +168,17 @@ class ObjectStoreStorageTest extends Storage { $targetId = $this->instance->getCache()->getId('target'); $this->assertSame($sourceId, $targetId, 'fileid must be stable on move or shares will break'); } + + public function testWriteObjectSilentFailure() { + $objectStore = $this->instance->getObjectStore(); + $this->instance->setObjectStore(new FailWriteObjectStore($objectStore)); + + try { + $this->instance->file_put_contents('test.txt', 'foo'); + $this->fail('expected exception'); + } catch (\Exception $e) { + $this->assertStringStartsWith('Object not found after writing', $e->getMessage()); + } + $this->assertFalse($this->instance->file_exists('test.txt')); + } } diff --git a/tests/lib/Files/ObjectStore/ObjectStoreTest.php b/tests/lib/Files/ObjectStore/ObjectStoreTest.php index 2116306053e..1383c0149a2 100644 --- a/tests/lib/Files/ObjectStore/ObjectStoreTest.php +++ b/tests/lib/Files/ObjectStore/ObjectStoreTest.php @@ -94,4 +94,19 @@ abstract class ObjectStoreTest extends TestCase { $this->assertEquals(1, 1); } } + + public function testExists() { + $stream = $this->stringToStream('foobar'); + + $instance = $this->getInstance(); + $this->assertFalse($instance->objectExists('2')); + + $instance->writeObject('2', $stream); + + $this->assertTrue($instance->objectExists('2')); + + $instance->deleteObject('2'); + + $this->assertFalse($instance->objectExists('2')); + } } diff --git a/tests/lib/Files/ObjectStore/S3Test.php b/tests/lib/Files/ObjectStore/S3Test.php index a54ade8fd08..91b24d8b615 100644 --- a/tests/lib/Files/ObjectStore/S3Test.php +++ b/tests/lib/Files/ObjectStore/S3Test.php @@ -21,6 +21,7 @@ namespace Test\Files\ObjectStore; +use Icewind\Streams\Wrapper; use OC\Files\ObjectStore\S3; class MultiPartUploadS3 extends S3 { @@ -31,6 +32,30 @@ class MultiPartUploadS3 extends S3 { } } +class NonSeekableStream extends Wrapper { + public static function wrap($source) { + $context = stream_context_create(array( + 'nonseek' => array( + 'source' => $source + ) + )); + return Wrapper::wrapSource($source, $context, 'nonseek', self::class); + } + + public function dir_opendir($path, $options) { + return false; + } + + public function stream_open($path, $mode, $options, &$opened_path) { + $this->loadContext('nonseek'); + return true; + } + + public function stream_seek($offset, $whence = SEEK_SET) { + return false; + } +} + /** * @group PRIMARY-s3 */ @@ -44,15 +69,15 @@ class S3Test extends ObjectStoreTest { return new S3($config['arguments']); } - public function testMultiPartUploader() { + public function testUploadNonSeekable() { $config = \OC::$server->getConfig()->getSystemValue('objectstore'); if (!is_array($config) || $config['class'] !== 'OC\\Files\\ObjectStore\\S3') { $this->markTestSkipped('objectstore not configured for s3'); } - $s3 = new MultiPartUploadS3($config['arguments']); + $s3 = $this->getInstance(); - $s3->writeObject('multiparttest', fopen(__FILE__, 'r')); + $s3->writeObject('multiparttest', NonSeekableStream::wrap(fopen(__FILE__, 'r'))); $result = $s3->readObject('multiparttest'); diff --git a/tests/lib/Files/SimpleFS/InMemoryFileTest.php b/tests/lib/Files/SimpleFS/InMemoryFileTest.php new file mode 100644 index 00000000000..195a5d04a8f --- /dev/null +++ b/tests/lib/Files/SimpleFS/InMemoryFileTest.php @@ -0,0 +1,145 @@ +<?php +declare(strict_types=1); + +/** + * @copyright Copyright (c) 2018, Michael Weimann <mail@michael-weimann.eu> + * + * @author Michael Weimann <mail@michael-weimann.eu> + * + * @license AGPL-3.0 + * + * This code is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License, version 3, + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License, version 3, + * along with this program. If not, see <http://www.gnu.org/licenses/> + */ + +namespace Test\File\SimpleFS; + +use OCP\Files\NotPermittedException; +use OCP\Files\SimpleFS\InMemoryFile; +use Test\TestCase; + +/** + * This class provide test casesf or the InMemoryFile. + * + * @package Test\File\SimpleFS + */ +class InMemoryFileTest extends TestCase { + /** + * Holds a pdf file with know attributes for tests. + * + * @var InMemoryFile + */ + private $testPdf; + + /** + * Sets the test file from "./resources/test.pdf". + * + * @before + * @return void + */ + public function setupTestPdf() { + $fileContents = file_get_contents( + __DIR__ . '/../../../data/test.pdf' + ); + $this->testPdf = new InMemoryFile('test.pdf', $fileContents); + } + + /** + * Asserts that putContent replaces the file contents. + * + * @return void + */ + public function testPutContent() { + $this->testPdf->putContent('test'); + self::assertEquals('test', $this->testPdf->getContent()); + } + + /** + * Asserts that delete() doesn't rise an exception. + * + * @return void + */ + public function testDelete() { + $this->testPdf->delete(); + // assert true, otherwise phpunit complains about not doing any assert + self::assertTrue(true); + } + + /** + * Asserts that getName returns the name passed on file creation. + * + * @return void + */ + public function testGetName() { + self::assertEquals('test.pdf', $this->testPdf->getName()); + } + + /** + * Asserts that the file size is the size of the test file. + * + * @return void + */ + public function testGetSize() { + self::assertEquals(7083, $this->testPdf->getSize()); + } + + /** + * Asserts the file contents are the same than the original file contents. + * + * @return void + */ + public function testGetContent() { + self::assertEquals( + file_get_contents(__DIR__ . '/../../../data/test.pdf'), + $this->testPdf->getContent() + ); + } + + /** + * Asserts the test file modification time is an integer. + * + * @return void + */ + public function testGetMTime() { + self::assertTrue(is_int($this->testPdf->getMTime())); + } + + /** + * Asserts the test file mime type is "application/json". + * + * @return void + */ + public function testGetMimeType() { + self::assertEquals('application/pdf', $this->testPdf->getMimeType()); + } + + + /** + * Asserts that read() raises an NotPermittedException. + * + * @return void + */ + public function testRead() { + self::expectException(NotPermittedException::class); + $this->testPdf->read(); + } + + /** + * Asserts that write() raises an NotPermittedException. + * + * @return void + */ + public function testWrite() { + self::expectException(NotPermittedException::class); + $this->testPdf->write(); + } +} diff --git a/tests/lib/Files/Storage/Wrapper/EncryptionTest.php b/tests/lib/Files/Storage/Wrapper/EncryptionTest.php index 22c93ee0a91..70d94ab16e6 100644 --- a/tests/lib/Files/Storage/Wrapper/EncryptionTest.php +++ b/tests/lib/Files/Storage/Wrapper/EncryptionTest.php @@ -18,6 +18,7 @@ use OCP\Files\Cache\ICache; use OCP\Files\Mount\IMountPoint; use OCP\IConfig; use OCP\ILogger; +use Symfony\Component\EventDispatcher\EventDispatcherInterface; use Test\Files\Storage\Storage; class EncryptionTest extends Storage { @@ -130,7 +131,7 @@ class EncryptionTest extends Storage { $this->util = $this->getMockBuilder('\OC\Encryption\Util') ->setMethods(['getUidAndFilename', 'isFile', 'isExcluded']) - ->setConstructorArgs([new View(), new Manager($this->config), $this->groupManager, $this->config, $this->arrayCache]) + ->setConstructorArgs([new View(), new Manager($this->config, $this->createMock(EventDispatcherInterface::class)), $this->groupManager, $this->config, $this->arrayCache]) ->getMock(); $this->util->expects($this->any()) ->method('getUidAndFilename') @@ -558,7 +559,7 @@ class EncryptionTest extends Storage { ->setConstructorArgs( [ new View(), - new Manager($this->config), + new Manager($this->config, $this->createMock(EventDispatcherInterface::class)), $this->groupManager, $this->config, $this->arrayCache @@ -627,7 +628,7 @@ class EncryptionTest extends Storage { ->willReturn($exists); $util = $this->getMockBuilder('\OC\Encryption\Util') - ->setConstructorArgs([new View(), new Manager($this->config), $this->groupManager, $this->config, $this->arrayCache]) + ->setConstructorArgs([new View(), new Manager($this->config, $this->createMock(EventDispatcherInterface::class)), $this->groupManager, $this->config, $this->arrayCache]) ->getMock(); $cache = $this->getMockBuilder('\OC\Files\Cache\Cache') diff --git a/tests/lib/Files/Stream/EncryptionTest.php b/tests/lib/Files/Stream/EncryptionTest.php index d7a5554acfd..3ded6ef91d6 100644 --- a/tests/lib/Files/Stream/EncryptionTest.php +++ b/tests/lib/Files/Stream/EncryptionTest.php @@ -7,6 +7,7 @@ use OC\Files\View; use OC\Memcache\ArrayCache; use OCP\Files\Cache\ICache; use OCP\IConfig; +use Symfony\Component\EventDispatcher\EventDispatcherInterface; class EncryptionTest extends \Test\TestCase { @@ -47,7 +48,7 @@ class EncryptionTest extends \Test\TestCase { $file->expects($this->any())->method('getAccessList')->willReturn([]); $util = $this->getMockBuilder('\OC\Encryption\Util') ->setMethods(['getUidAndFilename']) - ->setConstructorArgs([new View(), new \OC\User\Manager($config), $groupManager, $config, $arrayCache]) + ->setConstructorArgs([new View(), new \OC\User\Manager($config, $this->createMock(EventDispatcherInterface::class)), $groupManager, $config, $arrayCache]) ->getMock(); $util->expects($this->any()) ->method('getUidAndFilename') diff --git a/tests/lib/Files/ViewTest.php b/tests/lib/Files/ViewTest.php index 97e3d42684f..7a32736adb3 100644 --- a/tests/lib/Files/ViewTest.php +++ b/tests/lib/Files/ViewTest.php @@ -1997,6 +1997,37 @@ class ViewTest extends \Test\TestCase { $this->assertNull($this->getFileLockType($view, $path), 'File got unlocked after exception'); } + public function testLockBasicOperationUnlocksAfterLockException() { + $view = new View('/' . $this->user . '/files/'); + + $storage = new Temporary([]); + + Filesystem::mount($storage, array(), $this->user . '/'); + + $storage->mkdir('files'); + $storage->mkdir('files/dir'); + $storage->file_put_contents('files/test.txt', 'blah'); + $storage->getScanner()->scan('files'); + + // get a shared lock + $handle = $view->fopen('test.txt', 'r'); + + $thrown = false; + try { + // try (and fail) to get a write lock + $view->unlink('test.txt'); + } catch (\Exception $e) { + $thrown = true; + $this->assertInstanceOf(LockedException::class, $e); + } + $this->assertTrue($thrown, 'Exception was rethrown'); + + // clean shared lock + fclose($handle); + + $this->assertNull($this->getFileLockType($view, 'test.txt'), 'File got unlocked'); + } + /** * Test locks for fopen with fclose at the end * diff --git a/tests/lib/FilesTest.php b/tests/lib/FilesTest.php deleted file mode 100644 index 1d26984ee72..00000000000 --- a/tests/lib/FilesTest.php +++ /dev/null @@ -1,137 +0,0 @@ -<?php -/** - * @author Robin McCorkell <rmccorkell@karoshi.org.uk> - * - * @copyright Copyright (c) 2015, ownCloud, Inc. - * @license AGPL-3.0 - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE - * License as published by the Free Software Foundation; either - * version 3 of the License, or any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU AFFERO GENERAL PUBLIC LICENSE for more details. - * - * You should have received a copy of the GNU Affero General Public - * License along with this library. If not, see <http://www.gnu.org/licenses/>. - * - */ - -namespace Test; - -class FilesTest extends \Test\TestCase { - - const UPLOAD_LIMIT_DEFAULT_STR = '511M'; - const UPLOAD_LIMIT_SETTING_STR = '2M'; - const UPLOAD_LIMIT_SETTING_BYTES = 2097152; - - /** @var array $tmpDirs */ - private $tmpDirs = []; - - /** - * @return array - */ - private function getUploadLimitTestFiles() { - $dir = \OC::$server->getTempManager()->getTemporaryFolder(); - $this->tmpDirs[] = $dir; - $result = [ - '.htaccess' => $dir . '/htaccess', - '.user.ini' => $dir . '/user.ini' - ]; - copy(\OC::$SERVERROOT . '/tests/data/setUploadLimit/htaccess', $result['.htaccess']); - copy(\OC::$SERVERROOT . '/tests/data/setUploadLimit/user.ini', $result['.user.ini']); - return $result; - } - - protected function tearDown() { - foreach ($this->tmpDirs as $dir) { - \OC_Helper::rmdirr($dir); - } - parent::tearDown(); - } - - public function testSetUploadLimitSizeSanity() { - $this->assertFalse(\OC_Files::setUploadLimit(PHP_INT_MAX + 10)); - $this->assertFalse(\OC_Files::setUploadLimit(\OC_Files::UPLOAD_MIN_LIMIT_BYTES - 10)); - $this->assertFalse(\OC_Files::setUploadLimit('foobar')); - } - - public function setUploadLimitWriteProvider() { - return [ - [ - // both files writable - true, true, - self::UPLOAD_LIMIT_SETTING_BYTES, self::UPLOAD_LIMIT_SETTING_BYTES, - self::UPLOAD_LIMIT_SETTING_STR, self::UPLOAD_LIMIT_SETTING_STR - ], - [ - // neither file writable - false, false, - self::UPLOAD_LIMIT_SETTING_BYTES, false, - self::UPLOAD_LIMIT_DEFAULT_STR, self::UPLOAD_LIMIT_DEFAULT_STR - ], - [ - // only .htaccess writable - true, false, - self::UPLOAD_LIMIT_SETTING_BYTES, false, - self::UPLOAD_LIMIT_SETTING_STR, self::UPLOAD_LIMIT_DEFAULT_STR - ], - [ - // only .user.ini writable - false, true, - self::UPLOAD_LIMIT_SETTING_BYTES, false, - self::UPLOAD_LIMIT_DEFAULT_STR, self::UPLOAD_LIMIT_SETTING_STR - ], - [ - // test rounding of values - true, true, - self::UPLOAD_LIMIT_SETTING_BYTES + 20, self::UPLOAD_LIMIT_SETTING_BYTES, - self::UPLOAD_LIMIT_SETTING_STR, self::UPLOAD_LIMIT_SETTING_STR - ] - ]; - } - - /** - * @dataProvider setUploadLimitWriteProvider - */ - public function testSetUploadLimitWrite( - $htaccessWritable, $userIniWritable, - $setSize, $expectedSize, - $htaccessStr, $userIniStr - ) { - $this->markTestSkipped('TODO: Disable because fails on drone'); - - $files = $this->getUploadLimitTestFiles(); - chmod($files['.htaccess'], ($htaccessWritable ? 0644 : 0444)); - chmod($files['.user.ini'], ($userIniWritable ? 0644 : 0444)); - - $htaccessSize = filesize($files['.htaccess']); - $userIniSize = filesize($files['.user.ini']); - $htaccessSizeMod = 2*(strlen($htaccessStr) - strlen(self::UPLOAD_LIMIT_DEFAULT_STR)); - $userIniSizeMod = 2*(strlen($userIniStr) - strlen(self::UPLOAD_LIMIT_DEFAULT_STR)); - - $this->assertEquals($expectedSize, \OC_Files::setUploadLimit($setSize, $files)); - - // check file contents - $htaccess = file_get_contents($files['.htaccess']); - $this->assertEquals(1, - preg_match('/php_value upload_max_filesize '.$htaccessStr.'/', $htaccess) - ); - $this->assertEquals(1, - preg_match('/php_value post_max_size '.$htaccessStr.'/', $htaccess) - ); - $this->assertEquals($htaccessSize + $htaccessSizeMod, filesize($files['.htaccess'])); - - $userIni = file_get_contents($files['.user.ini']); - $this->assertEquals(1, - preg_match('/upload_max_filesize='.$userIniStr.'/', $userIni) - ); - $this->assertEquals(1, - preg_match('/post_max_size='.$userIniStr.'/', $userIni) - ); - $this->assertEquals($userIniSize + $userIniSizeMod, filesize($files['.user.ini'])); - } -} diff --git a/tests/lib/Group/GroupTest.php b/tests/lib/Group/GroupTest.php index a0b77bbe4d7..5ab7a645081 100644 --- a/tests/lib/Group/GroupTest.php +++ b/tests/lib/Group/GroupTest.php @@ -12,8 +12,19 @@ namespace Test\Group; use OC\User\User; use OCP\IConfig; use OCP\IURLGenerator; +use OCP\IUser; +use PHPUnit\Framework\MockObject\MockObject; +use Symfony\Component\EventDispatcher\EventDispatcherInterface; class GroupTest extends \Test\TestCase { + + /** @var EventDispatcherInterface|MockObject */ + protected $dispatcher; + + public function setUp() { + parent::setUp(); + $this->dispatcher = $this->createMock(EventDispatcherInterface::class); + } /** * @param string $uid @@ -21,14 +32,13 @@ class GroupTest extends \Test\TestCase { * @return User */ private function newUser($uid, \OC\User\Backend $backend) { - $config = $this->getMockBuilder(IConfig::class) - ->disableOriginalConstructor() - ->getMock(); - $urlgenerator = $this->getMockBuilder(IURLGenerator::class) - ->disableOriginalConstructor() - ->getMock(); + $user = $this->createMock(IUser::class); + $user->method('getUID') + ->willReturn($uid); + $user->method('getBackend') + ->willReturn($backend); - return new User($uid, $backend, null, $config, $urlgenerator); + return $user; } /** @@ -59,7 +69,7 @@ class GroupTest extends \Test\TestCase { ->disableOriginalConstructor() ->getMock(); $userManager = $this->getUserManager(); - $group = new \OC\Group\Group('group1', array($backend), $userManager); + $group = new \OC\Group\Group('group1', array($backend), $this->dispatcher, $userManager); $backend->expects($this->once()) ->method('usersInGroup') @@ -83,7 +93,7 @@ class GroupTest extends \Test\TestCase { ->disableOriginalConstructor() ->getMock(); $userManager = $this->getUserManager(); - $group = new \OC\Group\Group('group1', array($backend1, $backend2), $userManager); + $group = new \OC\Group\Group('group1', array($backend1, $backend2), $this->dispatcher, $userManager); $backend1->expects($this->once()) ->method('usersInGroup') @@ -114,7 +124,7 @@ class GroupTest extends \Test\TestCase { $userBackend = $this->getMockBuilder('\OC\User\Backend') ->disableOriginalConstructor() ->getMock(); - $group = new \OC\Group\Group('group1', array($backend), $userManager); + $group = new \OC\Group\Group('group1', array($backend), $this->dispatcher, $userManager); $backend->expects($this->once()) ->method('inGroup') @@ -135,7 +145,7 @@ class GroupTest extends \Test\TestCase { $userBackend = $this->getMockBuilder(\OC\User\Backend::class) ->disableOriginalConstructor() ->getMock(); - $group = new \OC\Group\Group('group1', array($backend1, $backend2), $userManager); + $group = new \OC\Group\Group('group1', array($backend1, $backend2), $this->dispatcher, $userManager); $backend1->expects($this->once()) ->method('inGroup') @@ -158,7 +168,7 @@ class GroupTest extends \Test\TestCase { $userBackend = $this->getMockBuilder('\OC\User\Backend') ->disableOriginalConstructor() ->getMock(); - $group = new \OC\Group\Group('group1', array($backend), $userManager); + $group = new \OC\Group\Group('group1', array($backend), $this->dispatcher, $userManager); $backend->expects($this->once()) ->method('inGroup') @@ -183,7 +193,7 @@ class GroupTest extends \Test\TestCase { $userBackend = $this->getMockBuilder('\OC\User\Backend') ->disableOriginalConstructor() ->getMock(); - $group = new \OC\Group\Group('group1', array($backend), $userManager); + $group = new \OC\Group\Group('group1', array($backend), $this->dispatcher, $userManager); $backend->expects($this->once()) ->method('inGroup') @@ -207,7 +217,7 @@ class GroupTest extends \Test\TestCase { $userBackend = $this->getMockBuilder('\OC\User\Backend') ->disableOriginalConstructor() ->getMock(); - $group = new \OC\Group\Group('group1', array($backend), $userManager); + $group = new \OC\Group\Group('group1', array($backend), $this->dispatcher, $userManager); $backend->expects($this->once()) ->method('inGroup') @@ -232,7 +242,7 @@ class GroupTest extends \Test\TestCase { $userBackend = $this->getMockBuilder(\OC\User\Backend::class) ->disableOriginalConstructor() ->getMock(); - $group = new \OC\Group\Group('group1', array($backend), $userManager); + $group = new \OC\Group\Group('group1', array($backend), $this->dispatcher, $userManager); $backend->expects($this->once()) ->method('inGroup') @@ -259,7 +269,7 @@ class GroupTest extends \Test\TestCase { $userBackend = $this->getMockBuilder('\OC\User\Backend') ->disableOriginalConstructor() ->getMock(); - $group = new \OC\Group\Group('group1', array($backend1, $backend2), $userManager); + $group = new \OC\Group\Group('group1', array($backend1, $backend2), $this->dispatcher, $userManager); $backend1->expects($this->once()) ->method('inGroup') @@ -293,7 +303,7 @@ class GroupTest extends \Test\TestCase { ->disableOriginalConstructor() ->getMock(); $userManager = $this->getUserManager(); - $group = new \OC\Group\Group('group1', array($backend), $userManager); + $group = new \OC\Group\Group('group1', array($backend), $this->dispatcher, $userManager); $backend->expects($this->once()) ->method('usersInGroup') @@ -315,7 +325,7 @@ class GroupTest extends \Test\TestCase { ->disableOriginalConstructor() ->getMock(); $userManager = $this->getUserManager(); - $group = new \OC\Group\Group('group1', array($backend1, $backend2), $userManager); + $group = new \OC\Group\Group('group1', array($backend1, $backend2), $this->dispatcher, $userManager); $backend1->expects($this->once()) ->method('usersInGroup') @@ -338,7 +348,7 @@ class GroupTest extends \Test\TestCase { ->disableOriginalConstructor() ->getMock(); $userManager = $this->getUserManager(); - $group = new \OC\Group\Group('group1', array($backend), $userManager); + $group = new \OC\Group\Group('group1', array($backend), $this->dispatcher, $userManager); $backend->expects($this->once()) ->method('usersInGroup') @@ -360,7 +370,7 @@ class GroupTest extends \Test\TestCase { ->disableOriginalConstructor() ->getMock(); $userManager = $this->getUserManager(); - $group = new \OC\Group\Group('group1', array($backend1, $backend2), $userManager); + $group = new \OC\Group\Group('group1', array($backend1, $backend2), $this->dispatcher, $userManager); $backend1->expects($this->once()) ->method('usersInGroup') @@ -385,7 +395,7 @@ class GroupTest extends \Test\TestCase { ->disableOriginalConstructor() ->getMock(); $userManager = $this->getUserManager(); - $group = new \OC\Group\Group('group1', array($backend1), $userManager); + $group = new \OC\Group\Group('group1', array($backend1), $this->dispatcher, $userManager); $backend1->expects($this->once()) ->method('countUsersInGroup') @@ -409,7 +419,7 @@ class GroupTest extends \Test\TestCase { ->disableOriginalConstructor() ->getMock(); $userManager = $this->getUserManager(); - $group = new \OC\Group\Group('group1', array($backend1, $backend2), $userManager); + $group = new \OC\Group\Group('group1', array($backend1, $backend2), $this->dispatcher, $userManager); $backend1->expects($this->once()) ->method('countUsersInGroup') @@ -437,7 +447,7 @@ class GroupTest extends \Test\TestCase { ->disableOriginalConstructor() ->getMock(); $userManager = $this->getUserManager(); - $group = new \OC\Group\Group('group1', array($backend1), $userManager); + $group = new \OC\Group\Group('group1', array($backend1), $this->dispatcher, $userManager); $backend1->expects($this->never()) ->method('countUsersInGroup'); @@ -455,7 +465,7 @@ class GroupTest extends \Test\TestCase { ->disableOriginalConstructor() ->getMock(); $userManager = $this->getUserManager(); - $group = new \OC\Group\Group('group1', array($backend), $userManager); + $group = new \OC\Group\Group('group1', array($backend), $this->dispatcher, $userManager); $backend->expects($this->once()) ->method('deleteGroup') diff --git a/tests/lib/Group/ManagerTest.php b/tests/lib/Group/ManagerTest.php index 23a35024e0a..32e30217759 100644 --- a/tests/lib/Group/ManagerTest.php +++ b/tests/lib/Group/ManagerTest.php @@ -27,18 +27,23 @@ use OC\User\Manager; use OCP\ILogger; use OCP\IUser; use OCP\GroupInterface; +use PHPUnit\Framework\MockObject\MockObject; +use Symfony\Component\EventDispatcher\EventDispatcherInterface; use Test\TestCase; class ManagerTest extends TestCase { - /** @var Manager|\PHPUnit_Framework_MockObject_MockObject $userManager */ + /** @var Manager|MockObject */ protected $userManager; - /** @var ILogger|\PHPUnit_Framework_MockObject_MockObject $userManager */ + /** @var EventDispatcherInterface|MockObject */ + protected $dispatcher; + /** @var ILogger|MockObject */ protected $logger; protected function setUp() { parent::setUp(); $this->userManager = $this->createMock(Manager::class); + $this->dispatcher = $this->createMock(EventDispatcherInterface::class); $this->logger = $this->createMock(ILogger::class); } @@ -101,7 +106,7 @@ class ManagerTest extends TestCase { ->with('group1') ->will($this->returnValue(true)); - $manager = new \OC\Group\Manager($this->userManager, $this->logger); + $manager = new \OC\Group\Manager($this->userManager, $this->dispatcher, $this->logger); $manager->addBackend($backend); $group = $manager->get('group1'); @@ -110,7 +115,7 @@ class ManagerTest extends TestCase { } public function testGetNoBackend() { - $manager = new \OC\Group\Manager($this->userManager, $this->logger); + $manager = new \OC\Group\Manager($this->userManager, $this->dispatcher, $this->logger); $this->assertNull($manager->get('group1')); } @@ -125,7 +130,7 @@ class ManagerTest extends TestCase { ->with('group1') ->will($this->returnValue(false)); - $manager = new \OC\Group\Manager($this->userManager, $this->logger); + $manager = new \OC\Group\Manager($this->userManager, $this->dispatcher, $this->logger); $manager->addBackend($backend); $this->assertNull($manager->get('group1')); @@ -135,7 +140,7 @@ class ManagerTest extends TestCase { $backend = new \Test\Util\Group\Dummy(); $backend->createGroup('group1'); - $manager = new \OC\Group\Manager($this->userManager, $this->logger); + $manager = new \OC\Group\Manager($this->userManager, $this->dispatcher, $this->logger); $manager->addBackend($backend); $group = $manager->get('group1'); @@ -162,7 +167,7 @@ class ManagerTest extends TestCase { ->with('group1') ->will($this->returnValue(true)); - $manager = new \OC\Group\Manager($this->userManager, $this->logger); + $manager = new \OC\Group\Manager($this->userManager, $this->dispatcher, $this->logger); $manager->addBackend($backend1); $manager->addBackend($backend2); @@ -187,7 +192,7 @@ class ManagerTest extends TestCase { $backendGroupCreated = true; })); - $manager = new \OC\Group\Manager($this->userManager, $this->logger); + $manager = new \OC\Group\Manager($this->userManager, $this->dispatcher, $this->logger); $manager->addBackend($backend); $group = $manager->createGroup('group1'); @@ -204,7 +209,7 @@ class ManagerTest extends TestCase { $backend->expects($this->never()) ->method('createGroup'); - $manager = new \OC\Group\Manager($this->userManager, $this->logger); + $manager = new \OC\Group\Manager($this->userManager, $this->dispatcher, $this->logger); $manager->addBackend($backend); $group = $manager->createGroup('group1'); @@ -225,7 +230,7 @@ class ManagerTest extends TestCase { ->with('group1') ->will($this->returnValue(true)); - $manager = new \OC\Group\Manager($this->userManager, $this->logger); + $manager = new \OC\Group\Manager($this->userManager, $this->dispatcher, $this->logger); $manager->addBackend($backend); $groups = $manager->search('1'); @@ -259,7 +264,7 @@ class ManagerTest extends TestCase { ->method('groupExists') ->will($this->returnValue(true)); - $manager = new \OC\Group\Manager($this->userManager, $this->logger); + $manager = new \OC\Group\Manager($this->userManager, $this->dispatcher, $this->logger); $manager->addBackend($backend1); $manager->addBackend($backend2); @@ -296,7 +301,7 @@ class ManagerTest extends TestCase { ->method('groupExists') ->will($this->returnValue(true)); - $manager = new \OC\Group\Manager($this->userManager, $this->logger); + $manager = new \OC\Group\Manager($this->userManager, $this->dispatcher, $this->logger); $manager->addBackend($backend1); $manager->addBackend($backend2); @@ -323,7 +328,7 @@ class ManagerTest extends TestCase { /** @var \OC\User\Manager $userManager */ $userManager = $this->createMock(Manager::class); - $manager = new \OC\Group\Manager($userManager, $this->logger); + $manager = new \OC\Group\Manager($userManager, $this->dispatcher, $this->logger); $manager->addBackend($backend); $groups = $manager->search('1'); @@ -344,7 +349,7 @@ class ManagerTest extends TestCase { ->with('group1') ->will($this->returnValue(true)); - $manager = new \OC\Group\Manager($this->userManager, $this->logger); + $manager = new \OC\Group\Manager($this->userManager, $this->dispatcher, $this->logger); $manager->addBackend($backend); $groups = $manager->getUserGroups($this->getTestUser('user1')); @@ -391,7 +396,7 @@ class ManagerTest extends TestCase { ->with('group1') ->will($this->returnValue(false)); - $manager = new \OC\Group\Manager($this->userManager, $this->logger); + $manager = new \OC\Group\Manager($this->userManager, $this->dispatcher, $this->logger); $manager->addBackend($backend); /** @var \OC\User\User|\PHPUnit_Framework_MockObject_MockObject $user */ @@ -417,7 +422,7 @@ class ManagerTest extends TestCase { ->method('groupExists') ->will($this->returnValue(true)); - $manager = new \OC\Group\Manager($this->userManager, $this->logger); + $manager = new \OC\Group\Manager($this->userManager, $this->dispatcher, $this->logger); $manager->addBackend($backend); $this->assertTrue($manager->isInGroup('user1', 'group1')); @@ -436,7 +441,7 @@ class ManagerTest extends TestCase { ->method('groupExists') ->will($this->returnValue(true)); - $manager = new \OC\Group\Manager($this->userManager, $this->logger); + $manager = new \OC\Group\Manager($this->userManager, $this->dispatcher, $this->logger); $manager->addBackend($backend); $this->assertTrue($manager->isAdmin('user1')); @@ -455,7 +460,7 @@ class ManagerTest extends TestCase { ->method('groupExists') ->will($this->returnValue(true)); - $manager = new \OC\Group\Manager($this->userManager, $this->logger); + $manager = new \OC\Group\Manager($this->userManager, $this->dispatcher, $this->logger); $manager->addBackend($backend); $this->assertFalse($manager->isAdmin('user1')); @@ -486,7 +491,7 @@ class ManagerTest extends TestCase { ->method('groupExists') ->will($this->returnValue(true)); - $manager = new \OC\Group\Manager($this->userManager, $this->logger); + $manager = new \OC\Group\Manager($this->userManager, $this->dispatcher, $this->logger); $manager->addBackend($backend1); $manager->addBackend($backend2); @@ -545,7 +550,7 @@ class ManagerTest extends TestCase { } })); - $manager = new \OC\Group\Manager($this->userManager, $this->logger); + $manager = new \OC\Group\Manager($this->userManager, $this->dispatcher, $this->logger); $manager->addBackend($backend); $users = $manager->displayNamesInGroup('testgroup', 'user3'); @@ -605,7 +610,7 @@ class ManagerTest extends TestCase { } })); - $manager = new \OC\Group\Manager($this->userManager, $this->logger); + $manager = new \OC\Group\Manager($this->userManager, $this->dispatcher, $this->logger); $manager->addBackend($backend); $users = $manager->displayNamesInGroup('testgroup', 'user3', 1); @@ -669,7 +674,7 @@ class ManagerTest extends TestCase { } })); - $manager = new \OC\Group\Manager($this->userManager, $this->logger); + $manager = new \OC\Group\Manager($this->userManager, $this->dispatcher, $this->logger); $manager->addBackend($backend); $users = $manager->displayNamesInGroup('testgroup', 'user3', 1, 1); @@ -709,7 +714,7 @@ class ManagerTest extends TestCase { } })); - $manager = new \OC\Group\Manager($this->userManager, $this->logger); + $manager = new \OC\Group\Manager($this->userManager, $this->dispatcher, $this->logger); $manager->addBackend($backend); $users = $manager->displayNamesInGroup('testgroup', ''); @@ -748,7 +753,7 @@ class ManagerTest extends TestCase { } })); - $manager = new \OC\Group\Manager($this->userManager, $this->logger); + $manager = new \OC\Group\Manager($this->userManager, $this->dispatcher, $this->logger); $manager->addBackend($backend); $users = $manager->displayNamesInGroup('testgroup', '', 1); @@ -787,7 +792,7 @@ class ManagerTest extends TestCase { } })); - $manager = new \OC\Group\Manager($this->userManager, $this->logger); + $manager = new \OC\Group\Manager($this->userManager, $this->dispatcher, $this->logger); $manager->addBackend($backend); $users = $manager->displayNamesInGroup('testgroup', '', 1, 1); @@ -815,7 +820,7 @@ class ManagerTest extends TestCase { ->with('group1') ->will($this->returnValue(true)); - $manager = new \OC\Group\Manager($this->userManager, $this->logger); + $manager = new \OC\Group\Manager($this->userManager, $this->dispatcher, $this->logger); $manager->addBackend($backend); // prime cache @@ -858,7 +863,7 @@ class ManagerTest extends TestCase { ->method('removeFromGroup') ->will($this->returnValue(true)); - $manager = new \OC\Group\Manager($this->userManager, $this->logger); + $manager = new \OC\Group\Manager($this->userManager, $this->dispatcher, $this->logger); $manager->addBackend($backend); // prime cache @@ -888,7 +893,7 @@ class ManagerTest extends TestCase { ->with('user1') ->will($this->returnValue(null)); - $manager = new \OC\Group\Manager($this->userManager, $this->logger); + $manager = new \OC\Group\Manager($this->userManager, $this->dispatcher, $this->logger); $manager->addBackend($backend); $groups = $manager->getUserIdGroups('user1'); @@ -914,7 +919,7 @@ class ManagerTest extends TestCase { ['group2', ['gid' => 'group2']], ])); - $manager = new \OC\Group\Manager($this->userManager, $this->logger); + $manager = new \OC\Group\Manager($this->userManager, $this->dispatcher, $this->logger); $manager->addBackend($backend); // group with display name diff --git a/tests/lib/InitialStateServiceTest.php b/tests/lib/InitialStateServiceTest.php new file mode 100644 index 00000000000..08bff615e3e --- /dev/null +++ b/tests/lib/InitialStateServiceTest.php @@ -0,0 +1,98 @@ +<?php + +declare(strict_types=1); + +/** + * @copyright 2019 Christoph Wurst <christoph@winzerhof-wurst.at> + * + * @author 2019 Christoph Wurst <christoph@winzerhof-wurst.at> + * + * @license GNU AGPL version 3 or any later version + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +namespace Test; + +use function json_encode; +use JsonSerializable; +use OC\InitialStateService; +use OCP\ILogger; +use stdClass; + +class InitialStateServiceTest extends TestCase { + + /** @var InitialStateService */ + private $service; + + protected function setUp() { + parent::setUp(); + + $this->service = new InitialStateService( + $this->createMock(ILogger::class) + ); + } + + public function staticData() { + return [ + ['string'], + [23], + [2.3], + [new class implements JsonSerializable { + public function jsonSerialize() { + return 3; + } + }], + ]; + } + + /** + * @dataProvider staticData + */ + public function testStaticData($value) { + $this->service->provideInitialState('test', 'key', $value); + $data = $this->service->getInitialStates(); + + $this->assertEquals( + ['test-key' => json_encode($value)], + $data + ); + } + + public function testStaticButInvalidData() { + $this->service->provideInitialState('test', 'key', new stdClass()); + $data = $this->service->getInitialStates(); + + $this->assertEquals( + [], + $data + ); + } + + /** + * @dataProvider staticData + */ + public function testLazyData($value) { + $this->service->provideLazyInitialState('test', 'key', function() use ($value) { + return $value; + }); + $data = $this->service->getInitialStates(); + + $this->assertEquals( + ['test-key' => json_encode($value)], + $data + ); + } + +} diff --git a/tests/lib/InstallerTest.php b/tests/lib/InstallerTest.php index 824682740e2..9fb813aaac6 100644 --- a/tests/lib/InstallerTest.php +++ b/tests/lib/InstallerTest.php @@ -255,28 +255,28 @@ YSu356M= [ 'id' => 'news', 'certificate' => '-----BEGIN CERTIFICATE----- -MIIEAjCCAuoCAhAYMA0GCSqGSIb3DQEBCwUAMHsxCzAJBgNVBAYTAkRFMRswGQYD +MIIEAjCCAuoCAhDUMA0GCSqGSIb3DQEBCwUAMHsxCzAJBgNVBAYTAkRFMRswGQYD VQQIDBJCYWRlbi1XdWVydHRlbWJlcmcxFzAVBgNVBAoMDk5leHRjbG91ZCBHbWJI MTYwNAYDVQQDDC1OZXh0Y2xvdWQgQ29kZSBTaWduaW5nIEludGVybWVkaWF0ZSBB -dXRob3JpdHkwHhcNMTYxMDE5MTkzNTEyWhcNMjcwMTI1MTkzNTEyWjASMRAwDgYD -VQQDDAdwYXNzbWFuMIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEA1Jw1 -8F0DefogaLaBudGbhK2zcFIBSzxhh7dRWguZKHGE+rG00BOvFLIAo37Bfmy9WKLc -3BFYvuFBowaVdaFOLxQJod0sOTmVMXhwoY5e3Xx+P+nsAw1/0gI10/LD1Vgl6i1u -gMocmnbEYhKwr0NbdiQiMI9UB9Ge/51wt4WtAxwK7yJFl3+5qzvJgfX75Wt+8L1e -Wk0LpVW23tUueJovjYZJXyAtohNaV3gwiST+QmKljCd4gwGX9abqfc76/lWtS+hI -rKptuICc55ffH30rqVhAgCMouF/Ml5Qru8tDen5dSNtmAXz89OlDNisP+9HL4WDZ -wvgps0mm/OYAUAQln24uXPDmAX/H2P5xIDHAa8avsqdgmHiqnLr4GYD8JYeb8GmB -zZ38hEMjCr2F1k1h9T1+SyfRiDPDqqv1mBtcvNVc1JmZvSikMxhtQbU0C4/o2SBG -RPCirknfPeKu8wBi6gvH4/SK0XTyuM8H58b9AKxzoo/wLbQ668+faLYyMSzCvsZD -eeZkiO85y87Ax57WRY93arccCMaUeks/cTriNw3JrvdDyb2SeQOX9JUp0orUlC64 -AzK2xhXCpmkprVBGizT5g3brrknX6VDX1gXFAmH/daCRJAIHPX0S/ol0z9w/hCEl -CpbiJPEphGtxqz4SfMv6IrIfneuDDKbF+w5MV/sCAwEAATANBgkqhkiG9w0BAQsF -AAOCAQEAUKj+/GpnMn+0/u9SPHTNmX3U3Y/ldmud0CsU5ELzMf/3YPbC/qWziRik -ewM2WyG8cwT9ayt9DxWGfu/zLv+ddyl8Wje1e/FIkRKXK0WW6OMz3e8Y45ONzpmu -8ME75IpnMuZEqE/WayRg27dQT5QNnEe/uNLd4m9BfsQcHIx3OfHCu5Of6/BclgsJ -VWp31zY8kcT0QN1GQxfB3eXnMyELneKCP3OH9DBhr4FUFb0vRHc8/1rdADFvSsdX -hNm8iRq+s2n0F6OGBofYT8ZyCnDUSQAoKMTIHcz+dDGyP4BfPY5w0ZGUfuaYATvm -cR92p/PYCFXkAKP3OO0RPlf6dXNKTw== +dXRob3JpdHkwHhcNMTkwMTMwMTMwMjA5WhcNMjkwNTA3MTMwMjA5WjASMRAwDgYD +VQQDDAdwYXNzbWFuMIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAwT1/ +hO/RSUkj0T9a879LPjy4c5V7FBDffEh6H/n1aiOEzofr8vqP3wJ4ZLwIvpZIZNFC +CY4HjBTIgk+QOlAv2oV2w/8XxkSQ708H3m99GFNRQg9EztjiIeKn7y1HhFOeiVaF +Eq6R1Tnre8cjzv6/yf1f1EFpPY3ptCefUjdLfpU/YrPhFxGLS+n5hyr8b6EszqKm +6NhGI09sd1Wb1y8o+dtQIQr24gWeo3l3QGLxjcJQqHCxE38rGdTNd04qDEm69BMD +Kjk4/JmUBBOn0svg9IAks+4nDnpr3IABfcnKYlmAucVEMNMYfA6kXXWEALsE2yo9 +8Y7GeV8En5Ztn4w3Pt2HMNpJV2m7MWWocSbF+ocp8oJ0cIEcthBubiE2kJhdPi5a +Yo5Bwh54hx53an+XfiDn+bfidvNz5TsJtmZykB84gLcdBQyMHrZcDcD6g74KdW3X +du/AnNUlJujhIU0fsw3UUPB845Q8XjbsIK5WhgaQeXJum8HXnXWkEfh6mE4j9l2Z +6FJVe8fQlF5lspn6z3qYsWlYRalD3N9Qxy3vpRgCAYTPc3D+fbVP9KJw1cWux1+O +0X/hNWMDOTenhgyQS+mqhRvdWq71mFjP/RXjOSfED3ipFamPofCz9QC7EERtvZPE +Pr8tBnbxnyTbAOQrN9N2mA9UJbOhk2l5kCSkDpMCAwEAATANBgkqhkiG9w0BAQsF +AAOCAQEAdVaizjIBQLGFo3uzOVAjh5IoFt/DBiSjVYOOt4HacWDDkRKOmQp3AJaA +Zecbd+tF7OsIqrBzbbfK7wp1+y1pLrPNFQghhk7gVxBP9LscLQ1JmDK2vHv9rLAg +d/gv90gf3HVeRQWntAhGTqtiSZkafcXJIRCM4GygoPy2zxeWeCTt85yEbQnuGZ4Z +qtWS/yyJR5ZQEwYG7jFWRxaZicuUdWBhlUMafRUxzjxBhsQplGKSI66eFQ5VtB7L +u/spPSSVhaun5BA1FlphB2TkgnzlCmxJa63nFY045e/Jq+IKMcqqZl/092gbI2EQ +5EpZaQ1l6H5DBXwrz58a8WTPC2Mu8g== -----END CERTIFICATE-----', ], ]; @@ -298,28 +298,28 @@ cR92p/PYCFXkAKP3OO0RPlf6dXNKTw== [ 'id' => 'passman', 'certificate' => '-----BEGIN CERTIFICATE----- -MIIEAjCCAuoCAhAYMA0GCSqGSIb3DQEBCwUAMHsxCzAJBgNVBAYTAkRFMRswGQYD +MIIEAjCCAuoCAhDUMA0GCSqGSIb3DQEBCwUAMHsxCzAJBgNVBAYTAkRFMRswGQYD VQQIDBJCYWRlbi1XdWVydHRlbWJlcmcxFzAVBgNVBAoMDk5leHRjbG91ZCBHbWJI MTYwNAYDVQQDDC1OZXh0Y2xvdWQgQ29kZSBTaWduaW5nIEludGVybWVkaWF0ZSBB -dXRob3JpdHkwHhcNMTYxMDE5MTkzNTEyWhcNMjcwMTI1MTkzNTEyWjASMRAwDgYD -VQQDDAdwYXNzbWFuMIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEA1Jw1 -8F0DefogaLaBudGbhK2zcFIBSzxhh7dRWguZKHGE+rG00BOvFLIAo37Bfmy9WKLc -3BFYvuFBowaVdaFOLxQJod0sOTmVMXhwoY5e3Xx+P+nsAw1/0gI10/LD1Vgl6i1u -gMocmnbEYhKwr0NbdiQiMI9UB9Ge/51wt4WtAxwK7yJFl3+5qzvJgfX75Wt+8L1e -Wk0LpVW23tUueJovjYZJXyAtohNaV3gwiST+QmKljCd4gwGX9abqfc76/lWtS+hI -rKptuICc55ffH30rqVhAgCMouF/Ml5Qru8tDen5dSNtmAXz89OlDNisP+9HL4WDZ -wvgps0mm/OYAUAQln24uXPDmAX/H2P5xIDHAa8avsqdgmHiqnLr4GYD8JYeb8GmB -zZ38hEMjCr2F1k1h9T1+SyfRiDPDqqv1mBtcvNVc1JmZvSikMxhtQbU0C4/o2SBG -RPCirknfPeKu8wBi6gvH4/SK0XTyuM8H58b9AKxzoo/wLbQ668+faLYyMSzCvsZD -eeZkiO85y87Ax57WRY93arccCMaUeks/cTriNw3JrvdDyb2SeQOX9JUp0orUlC64 -AzK2xhXCpmkprVBGizT5g3brrknX6VDX1gXFAmH/daCRJAIHPX0S/ol0z9w/hCEl -CpbiJPEphGtxqz4SfMv6IrIfneuDDKbF+w5MV/sCAwEAATANBgkqhkiG9w0BAQsF -AAOCAQEAUKj+/GpnMn+0/u9SPHTNmX3U3Y/ldmud0CsU5ELzMf/3YPbC/qWziRik -ewM2WyG8cwT9ayt9DxWGfu/zLv+ddyl8Wje1e/FIkRKXK0WW6OMz3e8Y45ONzpmu -8ME75IpnMuZEqE/WayRg27dQT5QNnEe/uNLd4m9BfsQcHIx3OfHCu5Of6/BclgsJ -VWp31zY8kcT0QN1GQxfB3eXnMyELneKCP3OH9DBhr4FUFb0vRHc8/1rdADFvSsdX -hNm8iRq+s2n0F6OGBofYT8ZyCnDUSQAoKMTIHcz+dDGyP4BfPY5w0ZGUfuaYATvm -cR92p/PYCFXkAKP3OO0RPlf6dXNKTw== +dXRob3JpdHkwHhcNMTkwMTMwMTMwMjA5WhcNMjkwNTA3MTMwMjA5WjASMRAwDgYD +VQQDDAdwYXNzbWFuMIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAwT1/ +hO/RSUkj0T9a879LPjy4c5V7FBDffEh6H/n1aiOEzofr8vqP3wJ4ZLwIvpZIZNFC +CY4HjBTIgk+QOlAv2oV2w/8XxkSQ708H3m99GFNRQg9EztjiIeKn7y1HhFOeiVaF +Eq6R1Tnre8cjzv6/yf1f1EFpPY3ptCefUjdLfpU/YrPhFxGLS+n5hyr8b6EszqKm +6NhGI09sd1Wb1y8o+dtQIQr24gWeo3l3QGLxjcJQqHCxE38rGdTNd04qDEm69BMD +Kjk4/JmUBBOn0svg9IAks+4nDnpr3IABfcnKYlmAucVEMNMYfA6kXXWEALsE2yo9 +8Y7GeV8En5Ztn4w3Pt2HMNpJV2m7MWWocSbF+ocp8oJ0cIEcthBubiE2kJhdPi5a +Yo5Bwh54hx53an+XfiDn+bfidvNz5TsJtmZykB84gLcdBQyMHrZcDcD6g74KdW3X +du/AnNUlJujhIU0fsw3UUPB845Q8XjbsIK5WhgaQeXJum8HXnXWkEfh6mE4j9l2Z +6FJVe8fQlF5lspn6z3qYsWlYRalD3N9Qxy3vpRgCAYTPc3D+fbVP9KJw1cWux1+O +0X/hNWMDOTenhgyQS+mqhRvdWq71mFjP/RXjOSfED3ipFamPofCz9QC7EERtvZPE +Pr8tBnbxnyTbAOQrN9N2mA9UJbOhk2l5kCSkDpMCAwEAATANBgkqhkiG9w0BAQsF +AAOCAQEAdVaizjIBQLGFo3uzOVAjh5IoFt/DBiSjVYOOt4HacWDDkRKOmQp3AJaA +Zecbd+tF7OsIqrBzbbfK7wp1+y1pLrPNFQghhk7gVxBP9LscLQ1JmDK2vHv9rLAg +d/gv90gf3HVeRQWntAhGTqtiSZkafcXJIRCM4GygoPy2zxeWeCTt85yEbQnuGZ4Z +qtWS/yyJR5ZQEwYG7jFWRxaZicuUdWBhlUMafRUxzjxBhsQplGKSI66eFQ5VtB7L +u/spPSSVhaun5BA1FlphB2TkgnzlCmxJa63nFY045e/Jq+IKMcqqZl/092gbI2EQ +5EpZaQ1l6H5DBXwrz58a8WTPC2Mu8g== -----END CERTIFICATE-----', 'releases' => [ [ diff --git a/tests/lib/IntegrityCheck/CheckerTest.php b/tests/lib/IntegrityCheck/CheckerTest.php index 71a9935008b..91d1fa36758 100644 --- a/tests/lib/IntegrityCheck/CheckerTest.php +++ b/tests/lib/IntegrityCheck/CheckerTest.php @@ -624,14 +624,13 @@ class CheckerTest extends TestCase { $this->checker->writeCoreSignature($x509, $rsa, \OC::$SERVERROOT . '/tests/data/integritycheck/htaccessWithInvalidModifiedContent/'); } - public function testWriteCoreSignatureWithValidModifiedHtaccessAndUserIni() { + public function testWriteCoreSignatureWithValidModifiedHtaccess() { $expectedSignatureFileData = '{ "hashes": { - ".htaccess": "9a37a508ad4cc3a7ff668e3cd63177891e5601143fa18bb605346020d5f3cd7979748beab956554aca43ae59ff146755cfe83de0f93a3a7bb328b1395b2ccf2f", - ".user.ini": "467d4f028c447895716a2b7859ed6e569f8ee34b87b51d73dab2e6a9ca4fbe63172c7be3e365ae864a60408286afcce852dd38ee544b61685ed4ee5e021fecb0", + ".htaccess": "7e6a7a4d8ee4f3fbc45dd579407c643471575a9d127d1c75f6d0a49e80766c3c587104b2139ef76d2a4bffce3f45777900605aaa49519c9532909b71e5030227", "subfolder\/.htaccess": "2c57b1e25050e11dc3ae975832f378c452159f7b69f818e47eeeafadd6ba568517461dcb4d843b90b906cd7c89d161bc1b89dff8e3ae0eb6f5088508c47befd1" }, - "signature": "HBUFy5NYoAX7nmHInD5N3RXTjzx6Ks5x3AJ4nPMLn5JyxEz5DGKA/kuUpcR2witPfeuLykFVAgv81e0BWXWW98iNHyNq/Gz707WC2qlAk9CME9xl0wayBI00LJ4FElEhxY505OpUz9KDpGDVz0egKNeiB7EAD7dvH4Aw5ffPwU03m2i/Qn5ixnSOW9Z+QRGr7a9qSxIdJa6tykJGwb9BPrmQamLgw3EJebD0rDpHEQID+RBgX+TPArn4zQoYaWooBoTH44JAjw0IpC/6rl29CfczIsNlQo+GJY6dkHQRQSDqSLV4t/qU70I7jUmq+ZWyGBPJXZ6u+SiNOuJl79jOeLKgoNSRrBL0/XuxSMsmszLEwD+RbLRG71/O7DcOQIdIo5jJ/fWm/ljnxIi61TZTBVZoHUM3Jc5MGHaT36yn8TUo0Zic9zFDE7INHuAs6qIOyRS6xkJAaiFMbFSgl3N3UgIGCRvh9l1Vcw5811jbaXnAxOpwJMPHv0ieviwhwO3QZbHfasxCJ4E70Y80N8VQhrruL+qy9I7NrqD19ObkC29MYmWrT+bl48/6IEbzhVXU3o/RMEPIRhgW5rc9OidnfJg4lPZVd1ZHKNWpVLAO0FgpsAl4dLblOIDwscOdQvgDDYyF+0stWxLiPC/MXBf546y7C/HlBYDxsW60EpO0cyw=", + "signature": "YVwQvl9Dh8UebCumfgzFxfz3NiZJLmYG8oJVTfEBhulI4KXBnTG1jZTprf4XxG2XIriEYAZXsoXpu9xWsUFe9QfdncwoEpqJtGq7l6aVDTofX5Be5b03MQFJr4cflgllqW77QZ84D9O9qWF\/vNDAofXcwrzT04CxLDhyQgTCgYUnRjG9pnuP\/gtbDKbTjRvxhTyfg3T0Phv1+XAvpTPnH2q5A+1+LmiqziUJ1sMipsKo+jQP614eCi9qjmqhHIgLRgcuOBvsi4g5WUcdcAIZ6qLt5gm2Y3r6rKNVchosU9ZydMUTfjuejDbVwE2fNH5UUnV57fQBxwg9CfX7iFHqKv1bfv5Zviu12paShgWCB12uR3iH\/3lmTJn8K5Xqit3G4eymFaJ5IChdUThBp\/jhQSI2r8sPcZDYSJ\/UZKuFnezFdKhEBd5hMXe8aKAd6ijGDjLARksFuqpi1sS8llC5K1Q+DzktSL\/o64TY4Vuvykiwe\/BAk2SkL9voOtrvU7vfDBcuCPbDJnSBBC0ESpcXeClTBIn6xZ9WaxqoS7sinE\/kUwtWsRd04I7d79\/ouotyNb+mBhTuRsZT12p\/gn4JHXXNUAIpTwchYzGxbfNJ4kxnYBFZWVmvsSqOLFZu1yi5BP3ktA9yhFyWIa5659azRFEKRdXpVHtQVa4IgdhxEqA=", "certificate": "-----BEGIN CERTIFICATE-----\r\nMIIEvjCCAqagAwIBAgIUc\/0FxYrsgSs9rDxp03EJmbjN0NwwDQYJKoZIhvcNAQEF\r\nBQAwIzEhMB8GA1UECgwYb3duQ2xvdWQgQ29kZSBTaWduaW5nIENBMB4XDTE1MTEw\r\nMzIxMDMzM1oXDTE2MTEwMzIxMDMzM1owDzENMAsGA1UEAwwEY29yZTCCAiIwDQYJ\r\nKoZIhvcNAQEBBQADggIPADCCAgoCggIBALb6EgHpkAqZbO5vRO8XSh7G7XGWHw5s\r\niOf4RwPXR6SE9bWZEm\/b72SfWk\/\/J6AbrD8WiOzBuT\/ODy6k5T1arEdHO+Pux0W1\r\nMxYJJI4kH74KKgMpC0SB0Rt+8WrMqV1r3hhJ46df6Xr\/xolP3oD+eLbShPcblhdS\r\nVtkZEkoev8Sh6L2wDCeHDyPxzvj1w2dTdGVO9Kztn0xIlyfEBakqvBWtcxyi3Ln0\r\nklnxlMx3tPDUE4kqvpia9qNiB1AN2PV93eNr5\/2riAzIssMFSCarWCx0AKYb54+d\r\nxLpcYFyqPJ0ydBCkF78DD45RCZet6PNYkdzgbqlUWEGGomkuDoJbBg4wzgzO0D77\r\nH87KFhYW8tKFFvF1V3AHl\/sFQ9tDHaxM9Y0pZ2jPp\/ccdiqnmdkBxBDqsiRvHvVB\r\nCn6qpb4vWGFC7vHOBfYspmEL1zLlKXZv3ezMZEZw7O9ZvUP3VO\/wAtd2vUW8UFiq\r\ns2v1QnNLN6jNh51obcwmrBvWhJy9vQIdtIjQbDxqWTHh1zUSrw9wrlklCBZ\/zrM0\r\ni8nfCFwTxWRxp3H9KoECzO\/zS5R5KIS7s3\/wq\/w9T2Ie4rcecgXwDizwnn0C\/aKc\r\nbDIjujpL1s9HO05pcD\/V3wKcPZ1izymBkmMyIbL52iRVN5FTVHeZdXPpFuq+CTQJ\r\nQ238lC+A\/KOVAgMBAAEwDQYJKoZIhvcNAQEFBQADggIBAGoKTnh8RfJV4sQItVC2\r\nAvfJagkrIqZ3iiQTUBQGTKBsTnAqE1H7QgUSV9vSd+8rgvHkyZsRjmtyR1e3A6Ji\r\noNCXUbExC\/0iCPUqdHZIVb+Lc\/vWuv4ByFMybGPydgtLoEUX2ZrKFWmcgZFDUSRd\r\n9Uj26vtUhCC4bU4jgu6hIrR9IuxOBLQUxGTRZyAcXvj7obqRAEZwFAKQgFpfpqTb\r\nH+kjcbZSaAlLVSF7vBc1syyI8RGYbqpwvtREqJtl5IEIwe6huEqJ3zPnlP2th\/55\r\ncf3Fovj6JJgbb9XFxrdnsOsDOu\/tpnaRWlvv5ib4+SzG5wWFT5UUEo4Wg2STQiiX\r\nuVSRQxK1LE1yg84bs3NZk9FSQh4B8vZVuRr5FaJsZZkwlFlhRO\/\/+TJtXRbyNgsf\r\noMRZGi8DLGU2SGEAHcRH\/QZHq\/XDUWVzdxrSBYcy7GSpT7UDVzGv1rEJUrn5veP1\r\n0KmauAqtiIaYRm4f6YBsn0INcZxzIPZ0p8qFtVZBPeHhvQtvOt0iXI\/XUxEWOa2F\r\nK2EqhErgMK\/N07U1JJJay5tYZRtvkGq46oP\/5kQG8hYST0MDK6VihJoPpvCmAm4E\r\npEYKQ96x6A4EH9Y9mZlYozH\/eqmxPbTK8n89\/p7Ydun4rI+B2iiLnY8REWWy6+UQ\r\nV204fGUkJqW5CrKy3P3XvY9X\r\n-----END CERTIFICATE-----" }'; $this->environmentHelper @@ -721,7 +720,7 @@ class CheckerTest extends TestCase { $this->assertSame([], $this->checker->verifyCoreSignature()); } - public function testVerifyCoreSignatureWithValidModifiedHtaccessAndUserIniSignatureData() { + public function testVerifyCoreSignatureWithValidModifiedHtaccessSignatureData() { $this->environmentHelper ->expects($this->once()) ->method('getChannel') @@ -738,11 +737,10 @@ class CheckerTest extends TestCase { ->will($this->returnValue(\OC::$SERVERROOT . '/tests/data/integritycheck/htaccessWithValidModifiedContent')); $signatureDataFile = '{ "hashes": { - ".htaccess": "9a37a508ad4cc3a7ff668e3cd63177891e5601143fa18bb605346020d5f3cd7979748beab956554aca43ae59ff146755cfe83de0f93a3a7bb328b1395b2ccf2f", - ".user.ini": "467d4f028c447895716a2b7859ed6e569f8ee34b87b51d73dab2e6a9ca4fbe63172c7be3e365ae864a60408286afcce852dd38ee544b61685ed4ee5e021fecb0", + ".htaccess": "7e6a7a4d8ee4f3fbc45dd579407c643471575a9d127d1c75f6d0a49e80766c3c587104b2139ef76d2a4bffce3f45777900605aaa49519c9532909b71e5030227", "subfolder\/.htaccess": "2c57b1e25050e11dc3ae975832f378c452159f7b69f818e47eeeafadd6ba568517461dcb4d843b90b906cd7c89d161bc1b89dff8e3ae0eb6f5088508c47befd1" }, - "signature": "HBUFy5NYoAX7nmHInD5N3RXTjzx6Ks5x3AJ4nPMLn5JyxEz5DGKA/kuUpcR2witPfeuLykFVAgv81e0BWXWW98iNHyNq/Gz707WC2qlAk9CME9xl0wayBI00LJ4FElEhxY505OpUz9KDpGDVz0egKNeiB7EAD7dvH4Aw5ffPwU03m2i/Qn5ixnSOW9Z+QRGr7a9qSxIdJa6tykJGwb9BPrmQamLgw3EJebD0rDpHEQID+RBgX+TPArn4zQoYaWooBoTH44JAjw0IpC/6rl29CfczIsNlQo+GJY6dkHQRQSDqSLV4t/qU70I7jUmq+ZWyGBPJXZ6u+SiNOuJl79jOeLKgoNSRrBL0/XuxSMsmszLEwD+RbLRG71/O7DcOQIdIo5jJ/fWm/ljnxIi61TZTBVZoHUM3Jc5MGHaT36yn8TUo0Zic9zFDE7INHuAs6qIOyRS6xkJAaiFMbFSgl3N3UgIGCRvh9l1Vcw5811jbaXnAxOpwJMPHv0ieviwhwO3QZbHfasxCJ4E70Y80N8VQhrruL+qy9I7NrqD19ObkC29MYmWrT+bl48/6IEbzhVXU3o/RMEPIRhgW5rc9OidnfJg4lPZVd1ZHKNWpVLAO0FgpsAl4dLblOIDwscOdQvgDDYyF+0stWxLiPC/MXBf546y7C/HlBYDxsW60EpO0cyw=", + "signature": "YVwQvl9Dh8UebCumfgzFxfz3NiZJLmYG8oJVTfEBhulI4KXBnTG1jZTprf4XxG2XIriEYAZXsoXpu9xWsUFe9QfdncwoEpqJtGq7l6aVDTofX5Be5b03MQFJr4cflgllqW77QZ84D9O9qWF\/vNDAofXcwrzT04CxLDhyQgTCgYUnRjG9pnuP\/gtbDKbTjRvxhTyfg3T0Phv1+XAvpTPnH2q5A+1+LmiqziUJ1sMipsKo+jQP614eCi9qjmqhHIgLRgcuOBvsi4g5WUcdcAIZ6qLt5gm2Y3r6rKNVchosU9ZydMUTfjuejDbVwE2fNH5UUnV57fQBxwg9CfX7iFHqKv1bfv5Zviu12paShgWCB12uR3iH\/3lmTJn8K5Xqit3G4eymFaJ5IChdUThBp\/jhQSI2r8sPcZDYSJ\/UZKuFnezFdKhEBd5hMXe8aKAd6ijGDjLARksFuqpi1sS8llC5K1Q+DzktSL\/o64TY4Vuvykiwe\/BAk2SkL9voOtrvU7vfDBcuCPbDJnSBBC0ESpcXeClTBIn6xZ9WaxqoS7sinE\/kUwtWsRd04I7d79\/ouotyNb+mBhTuRsZT12p\/gn4JHXXNUAIpTwchYzGxbfNJ4kxnYBFZWVmvsSqOLFZu1yi5BP3ktA9yhFyWIa5659azRFEKRdXpVHtQVa4IgdhxEqA=", "certificate": "-----BEGIN CERTIFICATE-----\r\nMIIEvjCCAqagAwIBAgIUc\/0FxYrsgSs9rDxp03EJmbjN0NwwDQYJKoZIhvcNAQEF\r\nBQAwIzEhMB8GA1UECgwYb3duQ2xvdWQgQ29kZSBTaWduaW5nIENBMB4XDTE1MTEw\r\nMzIxMDMzM1oXDTE2MTEwMzIxMDMzM1owDzENMAsGA1UEAwwEY29yZTCCAiIwDQYJ\r\nKoZIhvcNAQEBBQADggIPADCCAgoCggIBALb6EgHpkAqZbO5vRO8XSh7G7XGWHw5s\r\niOf4RwPXR6SE9bWZEm\/b72SfWk\/\/J6AbrD8WiOzBuT\/ODy6k5T1arEdHO+Pux0W1\r\nMxYJJI4kH74KKgMpC0SB0Rt+8WrMqV1r3hhJ46df6Xr\/xolP3oD+eLbShPcblhdS\r\nVtkZEkoev8Sh6L2wDCeHDyPxzvj1w2dTdGVO9Kztn0xIlyfEBakqvBWtcxyi3Ln0\r\nklnxlMx3tPDUE4kqvpia9qNiB1AN2PV93eNr5\/2riAzIssMFSCarWCx0AKYb54+d\r\nxLpcYFyqPJ0ydBCkF78DD45RCZet6PNYkdzgbqlUWEGGomkuDoJbBg4wzgzO0D77\r\nH87KFhYW8tKFFvF1V3AHl\/sFQ9tDHaxM9Y0pZ2jPp\/ccdiqnmdkBxBDqsiRvHvVB\r\nCn6qpb4vWGFC7vHOBfYspmEL1zLlKXZv3ezMZEZw7O9ZvUP3VO\/wAtd2vUW8UFiq\r\ns2v1QnNLN6jNh51obcwmrBvWhJy9vQIdtIjQbDxqWTHh1zUSrw9wrlklCBZ\/zrM0\r\ni8nfCFwTxWRxp3H9KoECzO\/zS5R5KIS7s3\/wq\/w9T2Ie4rcecgXwDizwnn0C\/aKc\r\nbDIjujpL1s9HO05pcD\/V3wKcPZ1izymBkmMyIbL52iRVN5FTVHeZdXPpFuq+CTQJ\r\nQ238lC+A\/KOVAgMBAAEwDQYJKoZIhvcNAQEFBQADggIBAGoKTnh8RfJV4sQItVC2\r\nAvfJagkrIqZ3iiQTUBQGTKBsTnAqE1H7QgUSV9vSd+8rgvHkyZsRjmtyR1e3A6Ji\r\noNCXUbExC\/0iCPUqdHZIVb+Lc\/vWuv4ByFMybGPydgtLoEUX2ZrKFWmcgZFDUSRd\r\n9Uj26vtUhCC4bU4jgu6hIrR9IuxOBLQUxGTRZyAcXvj7obqRAEZwFAKQgFpfpqTb\r\nH+kjcbZSaAlLVSF7vBc1syyI8RGYbqpwvtREqJtl5IEIwe6huEqJ3zPnlP2th\/55\r\ncf3Fovj6JJgbb9XFxrdnsOsDOu\/tpnaRWlvv5ib4+SzG5wWFT5UUEo4Wg2STQiiX\r\nuVSRQxK1LE1yg84bs3NZk9FSQh4B8vZVuRr5FaJsZZkwlFlhRO\/\/+TJtXRbyNgsf\r\noMRZGi8DLGU2SGEAHcRH\/QZHq\/XDUWVzdxrSBYcy7GSpT7UDVzGv1rEJUrn5veP1\r\n0KmauAqtiIaYRm4f6YBsn0INcZxzIPZ0p8qFtVZBPeHhvQtvOt0iXI\/XUxEWOa2F\r\nK2EqhErgMK\/N07U1JJJay5tYZRtvkGq46oP\/5kQG8hYST0MDK6VihJoPpvCmAm4E\r\npEYKQ96x6A4EH9Y9mZlYozH\/eqmxPbTK8n89\/p7Ydun4rI+B2iiLnY8REWWy6+UQ\r\nV204fGUkJqW5CrKy3P3XvY9X\r\n-----END CERTIFICATE-----" }'; $this->fileAccessHelper diff --git a/tests/lib/IntegrityCheck/Iterator/ExcludeFileByNameFilterIteratorTest.php b/tests/lib/IntegrityCheck/Iterator/ExcludeFileByNameFilterIteratorTest.php new file mode 100644 index 00000000000..124618eb538 --- /dev/null +++ b/tests/lib/IntegrityCheck/Iterator/ExcludeFileByNameFilterIteratorTest.php @@ -0,0 +1,94 @@ +<?php +/** + * @author Victor Dubiniuk <dubiniuk@owncloud.com> + * + * @copyright Copyright (c) 2015, ownCloud, Inc. + * @license AGPL-3.0 + * + * This code is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License, version 3, + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License, version 3, + * along with this program. If not, see <http://www.gnu.org/licenses/> + * + */ + +namespace Test\IntegrityCheck\Iterator; + +use \OC\IntegrityCheck\Iterator\ExcludeFileByNameFilterIterator; +use Test\TestCase; + +class ExcludeFileByNameFilterIteratorTest extends TestCase { + /** @var ExcludeFileByNameFilterIterator|\PHPUnit\Framework\MockObject\MockObject */ + protected $filter; + + public function setUp() { + parent::setUp(); + $this->filter = $this->getMockBuilder(ExcludeFileByNameFilterIterator::class) + ->disableOriginalConstructor() + ->setMethods(['current']) + ->getMock(); + } + + public function fileNameProvider(): array { + return [ + ['a file', true], + ['Thumbs.db', false], + ['another file', true], + ['.directory', false], + ['.webapp-nextcloud-15.0.2', false], + ['.webapp-nextcloud-14.0.5-r3', false], + ['wx.webapp-nextcloud-obee', true], + ]; + } + + /** + * @dataProvider fileNameProvider + * @param string $fileName + * @param bool $expectedResult + */ + public function testAcceptForFiles($fileName, $expectedResult): void { + $iteratorMock = $this->getMockBuilder(\RecursiveDirectoryIterator::class) + ->disableOriginalConstructor() + ->setMethods(['getFilename', 'isDir']) + ->getMock(); + + $iteratorMock->method('getFilename') + ->willReturn($fileName); + $iteratorMock->method('isDir') + ->willReturn(false); + $this->filter->method('current') + ->willReturn($iteratorMock); + + $actualResult = $this->filter->accept(); + $this->assertEquals($expectedResult, $actualResult); + } + + /** + * @dataProvider fileNameProvider + * @param string $fileName + * @param bool $expectedResult + */ + public function testAcceptForDirs($fileName, $expectedResult): void { + $iteratorMock = $this->getMockBuilder(\RecursiveDirectoryIterator::class) + ->disableOriginalConstructor() + ->setMethods(['getFilename', 'isDir']) + ->getMock(); + + $iteratorMock->method('getFilename') + ->willReturn($fileName); + $iteratorMock->method('isDir') + ->willReturn(true); + $this->filter->method('current') + ->willReturn($iteratorMock); + + $actualResult = $this->filter->accept(); + $this->assertTrue($actualResult); + } +} diff --git a/tests/lib/LegacyHelperTest.php b/tests/lib/LegacyHelperTest.php index 76f38706b4c..96cd190fd62 100644 --- a/tests/lib/LegacyHelperTest.php +++ b/tests/lib/LegacyHelperTest.php @@ -47,28 +47,6 @@ class LegacyHelperTest extends \Test\TestCase { } /** - * @dataProvider phpFileSizeProvider - */ - public function testPhpFileSize($expected, $input) - { - $result = OC_Helper::phpFileSize($input); - $this->assertEquals($expected, $result); - } - - public function phpFileSizeProvider() - { - return array( - array('0B', 0), - array('1K', 1024), - array('9.5M', 10000000), - array('1.3G', 1395864371), - array('465.7G', 500000000000), - array('465661.3G', 500000000000000), - array('465661287.3G', 500000000000000000), - ); - } - - /** * @dataProvider providesComputerFileSize */ function testComputerFileSize($expected, $input) { diff --git a/tests/lib/Migration/BackgroundRepairTest.php b/tests/lib/Migration/BackgroundRepairTest.php index 7a3a960074f..180ce72d315 100644 --- a/tests/lib/Migration/BackgroundRepairTest.php +++ b/tests/lib/Migration/BackgroundRepairTest.php @@ -21,13 +21,12 @@ namespace Test\Migration; - use OC\Migration\BackgroundRepair; use OC\NeedsUpdateException; use OCP\ILogger; use OCP\Migration\IOutput; use OCP\Migration\IRepairStep; -use Symfony\Component\EventDispatcher\EventDispatcher; +use Symfony\Component\EventDispatcher\EventDispatcherInterface; use Symfony\Component\EventDispatcher\GenericEvent; use Test\TestCase; @@ -57,15 +56,18 @@ class TestRepairStep implements IRepairStep { class BackgroundRepairTest extends TestCase { - /** @var \OC\BackgroundJob\JobList | \PHPUnit_Framework_MockObject_MockObject */ + /** @var \OC\BackgroundJob\JobList|\PHPUnit_Framework_MockObject_MockObject */ private $jobList; - /** @var BackgroundRepair | \PHPUnit_Framework_MockObject_MockObject */ + /** @var BackgroundRepair|\PHPUnit_Framework_MockObject_MockObject */ private $job; - /** @var ILogger | \PHPUnit_Framework_MockObject_MockObject */ + /** @var ILogger|\PHPUnit_Framework_MockObject_MockObject */ private $logger; + /** @var EventDispatcherInterface|\PHPUnit_Framework_MockObject_MockObject $dispatcher */ + private $dispatcher; + public function setUp() { parent::setUp(); @@ -78,6 +80,9 @@ class BackgroundRepairTest extends TestCase { $this->job = $this->getMockBuilder(BackgroundRepair::class) ->setMethods(['loadApp']) ->getMock(); + + $this->dispatcher = $this->createMock(EventDispatcherInterface::class); + $this->job->setDispatcher($this->dispatcher); } public function testNoArguments() { @@ -96,8 +101,11 @@ class BackgroundRepairTest extends TestCase { } public function testUnknownStep() { + $this->dispatcher->expects($this->never())->method('dispatch'); + $this->jobList->expects($this->once())->method('remove'); $this->logger->expects($this->once())->method('logException'); + $this->job->setArgument([ 'app' => 'test', 'step' => 'j' @@ -106,13 +114,11 @@ class BackgroundRepairTest extends TestCase { } public function testWorkingStep() { - /** @var EventDispatcher | \PHPUnit_Framework_MockObject_MockObject $dispatcher */ - $dispatcher = $this->createMock(EventDispatcher::class); - $dispatcher->expects($this->once())->method('dispatch') + $this->dispatcher->expects($this->once())->method('dispatch') ->with('\OC\Repair::step', new GenericEvent('\OC\Repair::step', ['A test repair step'])); $this->jobList->expects($this->once())->method('remove'); - $this->job->setDispatcher($dispatcher); + $this->job->setArgument([ 'app' => 'test', 'step' => '\Test\Migration\TestRepairStep' diff --git a/tests/lib/NavigationManagerTest.php b/tests/lib/NavigationManagerTest.php index 8bc1c372ac8..31efbce929c 100644 --- a/tests/lib/NavigationManagerTest.php +++ b/tests/lib/NavigationManagerTest.php @@ -221,15 +221,10 @@ class NavigationManagerTest extends TestCase { return '/apps/test/'; }); $this->urlGenerator - ->expects($this->once()) - ->method('linkToRouteAbsolute') - ->with( - 'core.login.logout', - [ - 'requesttoken' => \OCP\Util::callRegister() - ] - ) - ->willReturn('https://example.com/logout'); + ->expects($this->once()) + ->method('linkToRouteAbsolute') + ->with('core.login.logout') + ->willReturn('https://example.com/logout'); $user = $this->createMock(IUser::class); $user->expects($this->any())->method('getUID')->willReturn('user001'); $this->userSession->expects($this->any())->method('getUser')->willReturn($user); @@ -275,7 +270,7 @@ class NavigationManagerTest extends TestCase { 'logout' => [ 'id' => 'logout', 'order' => 99999, - 'href' => 'https://example.com/logout', + 'href' => 'https://example.com/logout?requesttoken='. urlencode(\OCP\Util::callRegister()), 'icon' => '/apps/core/img/actions/logout.svg', 'name' => 'Log out', 'active' => false, @@ -301,7 +296,9 @@ class NavigationManagerTest extends TestCase { ['logout' => $defaults['logout']] ), ['navigations' => [ - ['route' => 'test.page.index', 'name' => 'Test'] + 'navigation' => [ + ['route' => 'test.page.index', 'name' => 'Test'] + ] ]] ], 'minimalistic-settings' => [ @@ -320,9 +317,11 @@ class NavigationManagerTest extends TestCase { ['logout' => $defaults['logout']] ), ['navigations' => [ - ['route' => 'test.page.index', 'name' => 'Test', 'type' => 'settings'] - ] - ]], + 'navigation' => [ + ['route' => 'test.page.index', 'name' => 'Test', 'type' => 'settings'] + ], + ]] + ], 'admin' => [ array_merge( ['settings' => $defaults['settings']], @@ -340,7 +339,9 @@ class NavigationManagerTest extends TestCase { ['logout' => $defaults['logout']] ), ['navigations' => [ - ['@attributes' => ['role' => 'admin'], 'route' => 'test.page.index', 'name' => 'Test'] + 'navigation' => [ + ['@attributes' => ['role' => 'admin'], 'route' => 'test.page.index', 'name' => 'Test'] + ], ]], true ], @@ -351,7 +352,9 @@ class NavigationManagerTest extends TestCase { ['logout' => $defaults['logout']] ), ['navigations' => [ - ['@attributes' => ['role' => 'admin'], 'route' => 'test.page.index'] + 'navigation' => [ + ['@attributes' => ['role' => 'admin'], 'route' => 'test.page.index'] + ], ]], true ], diff --git a/tests/lib/Repair/ClearGeneratedAvatarCacheTest.php b/tests/lib/Repair/ClearGeneratedAvatarCacheTest.php index ec107d300d6..dd98307993f 100644 --- a/tests/lib/Repair/ClearGeneratedAvatarCacheTest.php +++ b/tests/lib/Repair/ClearGeneratedAvatarCacheTest.php @@ -25,7 +25,7 @@ namespace Test\Repair; use OCP\IConfig; use OCP\Migration\IOutput; -use OC\AvatarManager; +use OC\Avatar\AvatarManager; use OC\Repair\ClearGeneratedAvatarCache; class ClearGeneratedAvatarCacheTest extends \Test\TestCase { diff --git a/tests/lib/Security/Bruteforce/ThrottlerTest.php b/tests/lib/Security/Bruteforce/ThrottlerTest.php index dac12a00dcd..da386db9d2d 100644 --- a/tests/lib/Security/Bruteforce/ThrottlerTest.php +++ b/tests/lib/Security/Bruteforce/ThrottlerTest.php @@ -101,6 +101,27 @@ class ThrottlerTest extends TestCase { true, ], [ + '10.10.10.10', + [ + 'whitelist_0' => '10.10.10.11/31', + ], + true, + ], + [ + '10.10.10.10', + [ + 'whitelist_0' => '10.10.10.9/31', + ], + false, + ], + [ + '10.10.10.10', + [ + 'whitelist_0' => '10.10.10.15/29', + ], + true, + ], + [ 'dead:beef:cafe::1', [ 'whitelist_0' => '192.168.0.0/16', @@ -128,6 +149,14 @@ class ThrottlerTest extends TestCase { true, ], [ + 'dead:beef:cafe::1111', + [ + 'whitelist_0' => 'dead:beef:cafe::1100/123', + + ], + true, + ], + [ 'invalid', [], false, diff --git a/tests/lib/Security/CSP/ContentSecurityPolicyManagerTest.php b/tests/lib/Security/CSP/ContentSecurityPolicyManagerTest.php index 2a82e9c4878..8f8be5cba9f 100644 --- a/tests/lib/Security/CSP/ContentSecurityPolicyManagerTest.php +++ b/tests/lib/Security/CSP/ContentSecurityPolicyManagerTest.php @@ -63,7 +63,7 @@ class ContentSecurityPolicyManagerTest extends \Test\TestCase { $expected->addAllowedImageDomain('anotherdomain.de'); $expected->addAllowedImageDomain('example.org'); $expected->addAllowedChildSrcDomain('childdomain'); - $expectedStringPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self' 'unsafe-inline' 'unsafe-eval';style-src 'self' 'unsafe-inline';img-src 'self' data: blob: anotherdomain.de example.org;font-src 'self' mydomain.com example.com anotherFontDomain;connect-src 'self';media-src 'self';child-src childdomain"; + $expectedStringPolicy = "default-src 'none';base-uri 'none';manifest-src 'self';script-src 'self' 'unsafe-inline' 'unsafe-eval';style-src 'self' 'unsafe-inline';img-src 'self' data: blob: anotherdomain.de example.org;font-src 'self' data: mydomain.com example.com anotherFontDomain;connect-src 'self';media-src 'self';child-src childdomain;frame-ancestors 'self'"; $this->assertEquals($expected, $this->contentSecurityPolicyManager->getDefaultPolicy()); $this->assertSame($expectedStringPolicy, $this->contentSecurityPolicyManager->getDefaultPolicy()->buildPolicy()); diff --git a/tests/lib/ServerTest.php b/tests/lib/ServerTest.php index e76b2b96db7..604e11ec11e 100644 --- a/tests/lib/ServerTest.php +++ b/tests/lib/ServerTest.php @@ -57,7 +57,7 @@ class ServerTest extends \Test\TestCase { ['AppManager', '\OCP\App\IAppManager'], ['AsyncCommandBus', '\OC\Command\AsyncBus'], ['AsyncCommandBus', '\OCP\Command\IBus'], - ['AvatarManager', '\OC\AvatarManager'], + ['AvatarManager', '\OC\Avatar\AvatarManager'], ['AvatarManager', '\OCP\IAvatarManager'], ['CategoryFetcher', CategoryFetcher::class], diff --git a/tests/lib/Settings/Admin/SecurityTest.php b/tests/lib/Settings/Admin/SecurityTest.php index a7c56f697b0..6a9d84bd40d 100644 --- a/tests/lib/Settings/Admin/SecurityTest.php +++ b/tests/lib/Settings/Admin/SecurityTest.php @@ -23,10 +23,13 @@ namespace Test\Settings\Admin; +use OC\Authentication\TwoFactorAuth\MandatoryTwoFactor; use OC\Encryption\Manager; use OC\Settings\Admin\Security; use OCP\AppFramework\Http\TemplateResponse; +use OCP\IInitialStateService; use OCP\IUserManager; +use PHPUnit\Framework\MockObject\MockObject; use Test\TestCase; class SecurityTest extends TestCase { @@ -36,15 +39,23 @@ class SecurityTest extends TestCase { private $manager; /** @var IUserManager */ private $userManager; + /** @var MandatoryTwoFactor|MockObject */ + private $mandatoryTwoFactor; + /** @var IInitialStateService|MockObject */ + private $initialState; public function setUp() { parent::setUp(); $this->manager = $this->getMockBuilder('\OC\Encryption\Manager')->disableOriginalConstructor()->getMock(); $this->userManager = $this->getMockBuilder(IUserManager::class)->getMock(); + $this->mandatoryTwoFactor = $this->createMock(MandatoryTwoFactor::class); + $this->initialState = $this->createMock(IInitialStateService::class); $this->admin = new Security( $this->manager, - $this->userManager + $this->userManager, + $this->mandatoryTwoFactor, + $this->initialState ); } diff --git a/tests/lib/Settings/ManagerTest.php b/tests/lib/Settings/ManagerTest.php index b82fb5bc3ca..8323452934f 100644 --- a/tests/lib/Settings/ManagerTest.php +++ b/tests/lib/Settings/ManagerTest.php @@ -72,13 +72,14 @@ class ManagerTest extends TestCase { $this->manager->registerSection('admin', \OCA\WorkflowEngine\Settings\Section::class); - $this->url->expects($this->exactly(6)) + $this->url->expects($this->exactly(7)) ->method('imagePath') ->willReturnMap([ ['settings', 'admin.svg', '0'], ['core', 'actions/settings-dark.svg', '1'], ['core', 'actions/share.svg', '2'], ['core', 'actions/password.svg', '3'], + ['settings', 'theming-dark.svg', '6'], ['core', 'places/contacts.svg', '5'], ['settings', 'help.svg', '4'], ]); @@ -88,6 +89,7 @@ class ManagerTest extends TestCase { 1 => [new Section('server', 'Basic settings', 0, '1')], 5 => [new Section('sharing', 'Sharing', 0, '2')], 10 => [new Section('security', 'Security', 0, '3')], + 30 => [new Section('theming', 'Theming', 0, '6')], 50 => [new Section('groupware', 'Groupware', 0, '5')], 55 => [\OC::$server->query(\OCA\WorkflowEngine\Settings\Section::class)], 98 => [new Section('additional', 'Additional settings', 0, '1')], @@ -124,13 +126,14 @@ class ManagerTest extends TestCase { ->method('t') ->will($this->returnArgument(0)); - $this->url->expects($this->exactly(6)) + $this->url->expects($this->exactly(7)) ->method('imagePath') ->willReturnMap([ ['settings', 'admin.svg', '0'], ['core', 'actions/settings-dark.svg', '1'], ['core', 'actions/share.svg', '2'], ['core', 'actions/password.svg', '3'], + ['settings', 'theming-dark.svg', '6'], ['core', 'places/contacts.svg', '5'], ['settings', 'help.svg', '4'], ]); @@ -140,6 +143,7 @@ class ManagerTest extends TestCase { 1 => [new Section('server', 'Basic settings', 0, '1')], 5 => [new Section('sharing', 'Sharing', 0, '2')], 10 => [new Section('security', 'Security', 0, '3')], + 30 => [new Section('theming', 'Theming', 0, '6')], 50 => [new Section('groupware', 'Groupware', 0, '5')], 98 => [new Section('additional', 'Additional settings', 0, '1')], ], $this->manager->getAdminSections()); @@ -209,7 +213,7 @@ class ManagerTest extends TestCase { $this->manager->registerSection('personal', \OCA\WorkflowEngine\Settings\Section::class); $this->manager->registerSection('admin', \OCA\WorkflowEngine\Settings\Section::class); - $this->url->expects($this->exactly(9)) + $this->url->expects($this->exactly(10)) ->method('imagePath') ->willReturnMap([ ['core', 'actions/info.svg', '1'], @@ -219,6 +223,7 @@ class ManagerTest extends TestCase { ['core', 'actions/settings-dark.svg', '1'], ['core', 'actions/share.svg', '2'], ['core', 'actions/password.svg', '3'], + ['settings', 'theming-dark.svg', '6'], ['core', 'places/contacts.svg', '5'], ['settings', 'help.svg', '4'], ]); @@ -235,6 +240,7 @@ class ManagerTest extends TestCase { 1 => [new Section('server', 'Basic settings', 0, '1')], 5 => [new Section('sharing', 'Sharing', 0, '2')], 10 => [new Section('security', 'Security', 0, '3')], + 30 => [new Section('theming', 'Theming', 0, '6')], 50 => [new Section('groupware', 'Groupware', 0, '5')], 55 => [\OC::$server->query(\OCA\WorkflowEngine\Settings\Section::class)], 98 => [new Section('additional', 'Additional settings', 0, '1')], diff --git a/tests/lib/Settings/Personal/SecurityTest.php b/tests/lib/Settings/Personal/SecurityTest.php new file mode 100644 index 00000000000..dcef9ab0d7d --- /dev/null +++ b/tests/lib/Settings/Personal/SecurityTest.php @@ -0,0 +1,167 @@ +<?php + +declare(strict_types=1); + +/** + * @copyright 2019 Christoph Wurst <christoph@winzerhof-wurst.at> + * + * @author 2019 Christoph Wurst <christoph@winzerhof-wurst.at> + * + * @license GNU AGPL version 3 or any later version + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +namespace Test\Settings\Personal; + +use OC\Authentication\Token\DefaultToken; +use OC\Authentication\Token\IProvider as IAuthTokenProvider; +use OC\Authentication\TwoFactorAuth\Manager as TwoFactorManager; +use OC\Authentication\TwoFactorAuth\ProviderLoader; +use OC\Settings\Personal\Security; +use OCP\AppFramework\Http\TemplateResponse; +use OCP\IInitialStateService; +use OCP\ISession; +use OCP\IUser; +use OCP\IUserManager; +use OCP\IUserSession; +use PHPUnit\Framework\MockObject\MockObject; +use Test\TestCase; + +class SecurityTest extends TestCase { + + /** @var IUserManager|MockObject */ + private $userManager; + + /** @var TwoFactorManager|MockObject */ + private $twoFactorManager; + + /** @var IAuthTokenProvider|MockObject */ + private $authTokenProvider; + + /** @var ProviderLoader|MockObject */ + private $providerLoader; + + /** @var IUserSession|MockObject */ + private $userSession; + + /** @var ISession|MockObject */ + private $session; + + /** @var IInitialStateService|MockObject */ + private $initialStateService; + + /** @var string */ + private $uid; + + /** @var Security */ + private $section; + + public function setUp() { + parent::setUp(); + + $this->userManager = $this->createMock(IUserManager::class); + $this->twoFactorManager = $this->createMock(TwoFactorManager::class); + $this->authTokenProvider = $this->createMock(IAuthTokenProvider::class); + $this->providerLoader = $this->createMock(ProviderLoader::class); + $this->userSession = $this->createMock(IUserSession::class); + $this->session = $this->createMock(ISession::class); + $this->initialStateService = $this->createMock(IInitialStateService::class); + $this->uid = 'test123'; + + $this->section = new Security( + $this->userManager, + $this->twoFactorManager, + $this->authTokenProvider, + $this->providerLoader, + $this->userSession, + $this->session, + $this->initialStateService, + $this->uid + ); + } + + public function testGetForm() { + $token1 = new DefaultToken(); + $token1->setId(100); + $token2 = new DefaultToken(); + $token2->setId(200); + $tokens = [ + $token1, + $token2, + ]; + $sessionToken = new DefaultToken(); + $sessionToken->setId(100); + $user = $this->createMock(IUser::class); + $this->userManager->expects($this->once()) + ->method('get') + ->with($this->uid) + ->willReturn($user); + $user->expects($this->once()) + ->method('canChangePassword') + ->willReturn(true); + $this->authTokenProvider->expects($this->once()) + ->method('getTokenByUser') + ->with($this->uid) + ->willReturn($tokens); + $this->session->expects($this->once()) + ->method('getId') + ->willReturn('session123'); + $this->authTokenProvider->expects($this->once()) + ->method('getToken') + ->with('session123') + ->willReturn($sessionToken); + $this->initialStateService->expects($this->once()) + ->method('provideInitialState') + ->with('settings', 'app_tokens', [ + [ + 'id' => 100, + 'name' => null, + 'lastActivity' => 0, + 'type' => 0, + 'canDelete' => false, + 'current' => true, + 'scope' => ['filesystem' => true], + 'canRename' => false, + ], + [ + 'id' => 200, + 'name' => null, + 'lastActivity' => 0, + 'type' => 0, + 'canDelete' => true, + 'scope' => ['filesystem' => true], + 'canRename' => true, + ], + ]); + $this->userSession->expects($this->once()) + ->method('getUser') + ->willReturn($user); + $this->providerLoader->expects($this->once()) + ->method('getProviders') + ->with($user) + ->willReturn([]); + + $form = $this->section->getForm(); + + $expected = new TemplateResponse('settings', 'settings/personal/security', [ + 'passwordChangeSupported' => true, + 'twoFactorProviderData' => [ + 'providers' => [], + ], + ]); + $this->assertEquals($expected, $form); + } + +} diff --git a/tests/lib/Share20/ManagerTest.php b/tests/lib/Share20/ManagerTest.php index 80747e1a157..ddbfe857222 100644 --- a/tests/lib/Share20/ManagerTest.php +++ b/tests/lib/Share20/ManagerTest.php @@ -3427,15 +3427,15 @@ class ManagerTest extends \Test\TestCase { $extraProvider = $this->createMock(IShareProvider::class); $factory->setSecondProvider($extraProvider); - $owner = $this->createMock(IUser::class); - $owner->expects($this->once()) + $nodeOwner = $this->createMock(IUser::class); + $nodeOwner->expects($this->once()) ->method('getUID') - ->willReturn('owner'); + ->willReturn('user1'); $node = $this->createMock(Node::class); $node->expects($this->once()) ->method('getOwner') - ->willReturn($owner); + ->willReturn($nodeOwner); $node->method('getId') ->willReturn(42); @@ -3443,10 +3443,17 @@ class ManagerTest extends \Test\TestCase { $file = $this->createMock(File::class); $folder = $this->createMock(Folder::class); + $owner = $this->createMock(IUser::class); + $owner->expects($this->once()) + ->method('getUID') + ->willReturn('owner'); + $file->method('getParent') ->willReturn($folder); $file->method('getPath') ->willReturn('/owner/files/folder/file'); + $file->method('getOwner') + ->willReturn($owner); $file->method('getId') ->willReturn(23); $folder->method('getParent') @@ -3455,12 +3462,12 @@ class ManagerTest extends \Test\TestCase { ->willReturn('/owner/files/folder'); $userFolder->method('getById') ->with($this->equalTo(42)) - ->willReturn([$file]); + ->willReturn([12 => $file]); $userFolder->method('getPath') - ->willReturn('/owner/files'); + ->willReturn('/user1/files'); $this->userManager->method('userExists') - ->with($this->equalTo('owner')) + ->with($this->equalTo('user1')) ->willReturn(true); $this->defaultProvider->method('getAccessList') @@ -3494,7 +3501,7 @@ class ManagerTest extends \Test\TestCase { ]); $this->rootFolder->method('getUserFolder') - ->with($this->equalTo('owner')) + ->with($this->equalTo('user1')) ->willReturn($userFolder); $expected = [ @@ -3536,26 +3543,33 @@ class ManagerTest extends \Test\TestCase { $extraProvider = $this->createMock(IShareProvider::class); $factory->setSecondProvider($extraProvider); - $owner = $this->createMock(IUser::class); - $owner->expects($this->once()) + $nodeOwner = $this->createMock(IUser::class); + $nodeOwner->expects($this->once()) ->method('getUID') - ->willReturn('owner'); + ->willReturn('user1'); $node = $this->createMock(Node::class); $node->expects($this->once()) ->method('getOwner') - ->willReturn($owner); + ->willReturn($nodeOwner); $node->method('getId') ->willReturn(42); $userFolder = $this->createMock(Folder::class); $file = $this->createMock(File::class); + + $owner = $this->createMock(IUser::class); + $owner->expects($this->once()) + ->method('getUID') + ->willReturn('owner'); $folder = $this->createMock(Folder::class); $file->method('getParent') ->willReturn($folder); $file->method('getPath') ->willReturn('/owner/files/folder/file'); + $file->method('getOwner') + ->willReturn($owner); $file->method('getId') ->willReturn(23); $folder->method('getParent') @@ -3564,12 +3578,12 @@ class ManagerTest extends \Test\TestCase { ->willReturn('/owner/files/folder'); $userFolder->method('getById') ->with($this->equalTo(42)) - ->willReturn([$file]); + ->willReturn([42 => $file]); $userFolder->method('getPath') - ->willReturn('/owner/files'); + ->willReturn('/user1/files'); $this->userManager->method('userExists') - ->with($this->equalTo('owner')) + ->with($this->equalTo('user1')) ->willReturn(true); $this->defaultProvider->method('getAccessList') @@ -3605,7 +3619,7 @@ class ManagerTest extends \Test\TestCase { ]); $this->rootFolder->method('getUserFolder') - ->with($this->equalTo('owner')) + ->with($this->equalTo('user1')) ->willReturn($userFolder); $expected = [ diff --git a/tests/lib/SubAdminTest.php b/tests/lib/SubAdminTest.php index c1159132a50..4c0b030c44b 100644 --- a/tests/lib/SubAdminTest.php +++ b/tests/lib/SubAdminTest.php @@ -20,6 +20,9 @@ */ namespace Test; +/** + * @group DB + */ class SubAdminTest extends \Test\TestCase { /** @var \OCP\IUserManager */ @@ -97,7 +100,7 @@ class SubAdminTest extends \Test\TestCase { public function testCreateSubAdmin() { $subAdmin = new \OC\SubAdmin($this->userManager, $this->groupManager, $this->dbConn); - $this->assertTrue($subAdmin->createSubAdmin($this->users[0], $this->groups[0])); + $subAdmin->createSubAdmin($this->users[0], $this->groups[0]); // Look for subadmin in the database $qb = $this->dbConn->getQueryBuilder(); @@ -122,8 +125,8 @@ class SubAdminTest extends \Test\TestCase { public function testDeleteSubAdmin() { $subAdmin = new \OC\SubAdmin($this->userManager, $this->groupManager, $this->dbConn); - $this->assertTrue($subAdmin->createSubAdmin($this->users[0], $this->groups[0])); - $this->assertTrue($subAdmin->deleteSubAdmin($this->users[0], $this->groups[0])); + $subAdmin->createSubAdmin($this->users[0], $this->groups[0]); + $subAdmin->deleteSubAdmin($this->users[0], $this->groups[0]); // DB query should be empty $qb = $this->dbConn->getQueryBuilder(); @@ -138,8 +141,8 @@ class SubAdminTest extends \Test\TestCase { public function testGetSubAdminsGroups() { $subAdmin = new \OC\SubAdmin($this->userManager, $this->groupManager, $this->dbConn); - $this->assertTrue($subAdmin->createSubAdmin($this->users[0], $this->groups[0])); - $this->assertTrue($subAdmin->createSubAdmin($this->users[0], $this->groups[1])); + $subAdmin->createSubAdmin($this->users[0], $this->groups[0]); + $subAdmin->createSubAdmin($this->users[0], $this->groups[1]); $result = $subAdmin->getSubAdminsGroups($this->users[0]); @@ -148,14 +151,14 @@ class SubAdminTest extends \Test\TestCase { $this->assertNotContains($this->groups[2], $result); $this->assertNotContains(null, $result); - $this->assertTrue($subAdmin->deleteSubAdmin($this->users[0], $this->groups[0])); - $this->assertTrue($subAdmin->deleteSubAdmin($this->users[0], $this->groups[1])); + $subAdmin->deleteSubAdmin($this->users[0], $this->groups[0]); + $subAdmin->deleteSubAdmin($this->users[0], $this->groups[1]); } public function testGetGroupsSubAdmins() { $subAdmin = new \OC\SubAdmin($this->userManager, $this->groupManager, $this->dbConn); - $this->assertTrue($subAdmin->createSubAdmin($this->users[0], $this->groups[0])); - $this->assertTrue($subAdmin->createSubAdmin($this->users[1], $this->groups[0])); + $subAdmin->createSubAdmin($this->users[0], $this->groups[0]); + $subAdmin->createSubAdmin($this->users[1], $this->groups[0]); $result = $subAdmin->getGroupsSubAdmins($this->groups[0]); @@ -164,16 +167,16 @@ class SubAdminTest extends \Test\TestCase { $this->assertNotContains($this->users[2], $result); $this->assertNotContains(null, $result); - $this->assertTrue($subAdmin->deleteSubAdmin($this->users[0], $this->groups[0])); - $this->assertTrue($subAdmin->deleteSubAdmin($this->users[1], $this->groups[0])); + $subAdmin->deleteSubAdmin($this->users[0], $this->groups[0]); + $subAdmin->deleteSubAdmin($this->users[1], $this->groups[0]); } public function testGetAllSubAdmin() { $subAdmin = new \OC\SubAdmin($this->userManager, $this->groupManager, $this->dbConn); - $this->assertTrue($subAdmin->createSubAdmin($this->users[0], $this->groups[0])); - $this->assertTrue($subAdmin->createSubAdmin($this->users[1], $this->groups[1])); - $this->assertTrue($subAdmin->createSubAdmin($this->users[2], $this->groups[1])); + $subAdmin->createSubAdmin($this->users[0], $this->groups[0]); + $subAdmin->createSubAdmin($this->users[1], $this->groups[1]); + $subAdmin->createSubAdmin($this->users[2], $this->groups[1]); $result = $subAdmin->getAllSubAdmins(); @@ -185,23 +188,23 @@ class SubAdminTest extends \Test\TestCase { public function testIsSubAdminofGroup() { $subAdmin = new \OC\SubAdmin($this->userManager, $this->groupManager, $this->dbConn); - $this->assertTrue($subAdmin->createSubAdmin($this->users[0], $this->groups[0])); + $subAdmin->createSubAdmin($this->users[0], $this->groups[0]); $this->assertTrue($subAdmin->isSubAdminOfGroup($this->users[0], $this->groups[0])); $this->assertFalse($subAdmin->isSubAdminOfGroup($this->users[0], $this->groups[1])); $this->assertFalse($subAdmin->isSubAdminOfGroup($this->users[1], $this->groups[0])); - $this->assertTrue($subAdmin->deleteSubAdmin($this->users[0], $this->groups[0])); + $subAdmin->deleteSubAdmin($this->users[0], $this->groups[0]); } public function testIsSubAdmin() { $subAdmin = new \OC\SubAdmin($this->userManager, $this->groupManager, $this->dbConn); - $this->assertTrue($subAdmin->createSubAdmin($this->users[0], $this->groups[0])); + $subAdmin->createSubAdmin($this->users[0], $this->groups[0]); $this->assertTrue($subAdmin->isSubAdmin($this->users[0])); $this->assertFalse($subAdmin->isSubAdmin($this->users[1])); - $this->assertTrue($subAdmin->deleteSubAdmin($this->users[0], $this->groups[0])); + $subAdmin->deleteSubAdmin($this->users[0], $this->groups[0]); } public function testIsSubAdminAsAdmin() { @@ -216,15 +219,15 @@ class SubAdminTest extends \Test\TestCase { $this->groups[0]->addUser($this->users[1]); $this->groups[1]->addUser($this->users[1]); $this->groups[1]->addUser($this->users[2]); - $this->assertTrue($subAdmin->createSubAdmin($this->users[0], $this->groups[0])); - $this->assertTrue($subAdmin->createSubAdmin($this->users[2], $this->groups[2])); + $subAdmin->createSubAdmin($this->users[0], $this->groups[0]); + $subAdmin->createSubAdmin($this->users[2], $this->groups[2]); $this->assertTrue($subAdmin->isUserAccessible($this->users[0], $this->users[1])); $this->assertFalse($subAdmin->isUserAccessible($this->users[0], $this->users[2])); $this->assertFalse($subAdmin->isUserAccessible($this->users[2], $this->users[0])); - $this->assertTrue($subAdmin->deleteSubAdmin($this->users[0], $this->groups[0])); - $this->assertTrue($subAdmin->deleteSubAdmin($this->users[2], $this->groups[2])); + $subAdmin->deleteSubAdmin($this->users[0], $this->groups[0]); + $subAdmin->deleteSubAdmin($this->users[2], $this->groups[2]); } public function testIsUserAccessibleAsUser() { @@ -234,7 +237,7 @@ class SubAdminTest extends \Test\TestCase { public function testIsUserAccessibleAdmin() { $subAdmin = new \OC\SubAdmin($this->userManager, $this->groupManager, $this->dbConn); - $this->assertTrue($subAdmin->createSubAdmin($this->users[0], $this->groups[0])); + $subAdmin->createSubAdmin($this->users[0], $this->groups[0]); $this->groupManager->get('admin')->addUser($this->users[1]); $this->assertFalse($subAdmin->isUserAccessible($this->users[0], $this->users[1])); @@ -246,7 +249,7 @@ class SubAdminTest extends \Test\TestCase { $user = array_shift($this->users); foreach($this->groups as $group) { - $this->assertTrue($subAdmin->createSubAdmin($user, $group)); + $subAdmin->createSubAdmin($user, $group); } $user->delete(); @@ -258,7 +261,7 @@ class SubAdminTest extends \Test\TestCase { $group = array_shift($this->groups); foreach($this->users as $user) { - $this->assertTrue($subAdmin->createSubAdmin($user, $group)); + $subAdmin->createSubAdmin($user, $group); } $group->delete(); @@ -285,10 +288,10 @@ class SubAdminTest extends \Test\TestCase { $count++; }); - $this->assertTrue($subAdmin->createSubAdmin($u, $g)); + $subAdmin->createSubAdmin($u, $g); $this->assertEquals(1, $count); - $this->assertTrue($subAdmin->deleteSubAdmin($u, $g)); + $subAdmin->deleteSubAdmin($u, $g); $this->assertEquals(2, $count); } diff --git a/tests/lib/TagsTest.php b/tests/lib/TagsTest.php index ce26f6b4807..268521bed51 100644 --- a/tests/lib/TagsTest.php +++ b/tests/lib/TagsTest.php @@ -21,6 +21,7 @@ */ namespace Test; +use OCP\IUser; use OCP\IUserSession; /** @@ -49,7 +50,9 @@ class TagsTest extends \Test\TestCase { $userId = $this->getUniqueID('user_'); \OC::$server->getUserManager()->createUser($userId, 'pass'); \OC_User::setUserId($userId); - $this->user = new \OC\User\User($userId, null); + $this->user = $this->createMock(IUser::class); + $this->user->method('getUID') + ->willReturn($userId); $this->userSession = $this->createMock(IUserSession::class); $this->userSession ->expects($this->any()) @@ -292,14 +295,19 @@ class TagsTest extends \Test\TestCase { $tagger = $this->tagMgr->load('test'); $tagger->tagAs(1, $testTag); + $otherUserId = $this->getUniqueID('user2_'); + $otherUser = $this->createMock(IUser::class); + $otherUser->method('getUID') + ->willReturn($otherUserId); + \OC::$server->getUserManager()->createUser($otherUserId, 'pass'); \OC_User::setUserId($otherUserId); $otherUserSession = $this->createMock(IUserSession::class); $otherUserSession ->expects($this->any()) ->method('getUser') - ->will($this->returnValue(new \OC\User\User($otherUserId, null))); + ->willReturn($otherUser); $otherTagMgr = new \OC\TagManager($this->tagMapper, $otherUserSession); $otherTagger = $otherTagMgr->load('test'); diff --git a/tests/lib/User/DatabaseTest.php b/tests/lib/User/DatabaseTest.php index a6fb8047a98..666833ec44c 100644 --- a/tests/lib/User/DatabaseTest.php +++ b/tests/lib/User/DatabaseTest.php @@ -22,7 +22,7 @@ namespace Test\User; use OC\HintException; -use Symfony\Component\EventDispatcher\EventDispatcher; +use Symfony\Component\EventDispatcher\EventDispatcherInterface; use Symfony\Component\EventDispatcher\GenericEvent; use OC\User\User; @@ -34,7 +34,7 @@ use OC\User\User; class DatabaseTest extends Backend { /** @var array */ private $users; - /** @var EventDispatcher | \PHPUnit_Framework_MockObject_MockObject */ + /** @var EventDispatcherInterface|\PHPUnit_Framework_MockObject_MockObject */ private $eventDispatcher; public function getUser() { @@ -46,7 +46,7 @@ class DatabaseTest extends Backend { protected function setUp() { parent::setUp(); - $this->eventDispatcher = $this->createMock(EventDispatcher::class); + $this->eventDispatcher = $this->createMock(EventDispatcherInterface::class); $this->backend=new \OC\User\Database($this->eventDispatcher); } @@ -124,8 +124,8 @@ class DatabaseTest extends Backend { $user2 = $this->getUser(); $this->backend->createUser($user2, 'pass1'); - $user1Obj = new User($user1, $this->backend); - $user2Obj = new User($user2, $this->backend); + $user1Obj = new User($user1, $this->backend, $this->eventDispatcher); + $user2Obj = new User($user2, $this->backend, $this->eventDispatcher); $emailAddr1 = "$user1@nextcloud.com"; $emailAddr2 = "$user2@nextcloud.com"; diff --git a/tests/lib/User/ManagerTest.php b/tests/lib/User/ManagerTest.php index 284f7b173bc..b99d499b2a8 100644 --- a/tests/lib/User/ManagerTest.php +++ b/tests/lib/User/ManagerTest.php @@ -13,6 +13,7 @@ use OC\User\Database; use OC\User\Manager; use OCP\IConfig; use OCP\IUser; +use Symfony\Component\EventDispatcher\EventDispatcherInterface; use Test\TestCase; /** @@ -26,16 +27,19 @@ class ManagerTest extends TestCase { /** @var IConfig */ private $config; + /** @var EventDispatcherInterface */ + private $dispatcher; public function setUp() { parent::setUp(); $this->config = $this->createMock(IConfig::class); + $this->dispatcher = $this->createMock(EventDispatcherInterface::class); } public function testGetBackends() { $userDummyBackend = $this->createMock(\Test\Util\User\Dummy::class); - $manager = new \OC\User\Manager($this->config); + $manager = new \OC\User\Manager($this->config, $this->dispatcher); $manager->registerBackend($userDummyBackend); $this->assertEquals([$userDummyBackend], $manager->getBackends()); $dummyDatabaseBackend = $this->createMock(Database::class); @@ -54,7 +58,7 @@ class ManagerTest extends TestCase { ->with($this->equalTo('foo')) ->will($this->returnValue(true)); - $manager = new \OC\User\Manager($this->config); + $manager = new \OC\User\Manager($this->config, $this->dispatcher); $manager->registerBackend($backend); $this->assertTrue($manager->userExists('foo')); @@ -70,14 +74,14 @@ class ManagerTest extends TestCase { ->with($this->equalTo('foo')) ->will($this->returnValue(false)); - $manager = new \OC\User\Manager($this->config); + $manager = new \OC\User\Manager($this->config, $this->dispatcher); $manager->registerBackend($backend); $this->assertFalse($manager->userExists('foo')); } public function testUserExistsNoBackends() { - $manager = new \OC\User\Manager($this->config); + $manager = new \OC\User\Manager($this->config, $this->dispatcher); $this->assertFalse($manager->userExists('foo')); } @@ -101,7 +105,7 @@ class ManagerTest extends TestCase { ->with($this->equalTo('foo')) ->will($this->returnValue(true)); - $manager = new \OC\User\Manager($this->config); + $manager = new \OC\User\Manager($this->config, $this->dispatcher); $manager->registerBackend($backend1); $manager->registerBackend($backend2); @@ -125,7 +129,7 @@ class ManagerTest extends TestCase { $backend2->expects($this->never()) ->method('userExists'); - $manager = new \OC\User\Manager($this->config); + $manager = new \OC\User\Manager($this->config, $this->dispatcher); $manager->registerBackend($backend1); $manager->registerBackend($backend2); @@ -152,7 +156,7 @@ class ManagerTest extends TestCase { } })); - $manager = new \OC\User\Manager($this->config); + $manager = new \OC\User\Manager($this->config, $this->dispatcher); $manager->registerBackend($backend); $user = $manager->checkPassword('foo', 'bar'); @@ -171,7 +175,7 @@ class ManagerTest extends TestCase { ->method('implementsActions') ->will($this->returnValue(false)); - $manager = new \OC\User\Manager($this->config); + $manager = new \OC\User\Manager($this->config, $this->dispatcher); $manager->registerBackend($backend); $this->assertFalse($manager->checkPassword('foo', 'bar')); @@ -189,7 +193,7 @@ class ManagerTest extends TestCase { $backend->expects($this->never()) ->method('loginName2UserName'); - $manager = new \OC\User\Manager($this->config); + $manager = new \OC\User\Manager($this->config, $this->dispatcher); $manager->registerBackend($backend); $this->assertEquals('foo', $manager->get('foo')->getUID()); @@ -205,7 +209,7 @@ class ManagerTest extends TestCase { ->with($this->equalTo('foo')) ->will($this->returnValue(false)); - $manager = new \OC\User\Manager($this->config); + $manager = new \OC\User\Manager($this->config, $this->dispatcher); $manager->registerBackend($backend); $this->assertEquals(null, $manager->get('foo')); @@ -223,7 +227,7 @@ class ManagerTest extends TestCase { $backend->expects($this->never()) ->method('loginName2UserName'); - $manager = new \OC\User\Manager($this->config); + $manager = new \OC\User\Manager($this->config, $this->dispatcher); $manager->registerBackend($backend); $this->assertEquals('bLeNdEr', $manager->get('bLeNdEr')->getUID()); @@ -241,7 +245,7 @@ class ManagerTest extends TestCase { $backend->expects($this->never()) ->method('loginName2UserName'); - $manager = new \OC\User\Manager($this->config); + $manager = new \OC\User\Manager($this->config, $this->dispatcher); $manager->registerBackend($backend); $result = $manager->search('fo'); @@ -275,7 +279,7 @@ class ManagerTest extends TestCase { $backend2->expects($this->never()) ->method('loginName2UserName'); - $manager = new \OC\User\Manager($this->config); + $manager = new \OC\User\Manager($this->config, $this->dispatcher); $manager->registerBackend($backend1); $manager->registerBackend($backend2); @@ -329,7 +333,7 @@ class ManagerTest extends TestCase { ->willReturn(true); - $manager = new \OC\User\Manager($this->config); + $manager = new \OC\User\Manager($this->config, $this->dispatcher); $manager->registerBackend($backend); $this->expectException(\InvalidArgumentException::class, $exception); @@ -356,7 +360,7 @@ class ManagerTest extends TestCase { $backend->expects($this->never()) ->method('loginName2UserName'); - $manager = new \OC\User\Manager($this->config); + $manager = new \OC\User\Manager($this->config, $this->dispatcher); $manager->registerBackend($backend); $user = $manager->createUser('foo', 'bar'); @@ -383,7 +387,7 @@ class ManagerTest extends TestCase { ->with($this->equalTo('foo')) ->will($this->returnValue(true)); - $manager = new \OC\User\Manager($this->config); + $manager = new \OC\User\Manager($this->config, $this->dispatcher); $manager->registerBackend($backend); $manager->createUser('foo', 'bar'); @@ -404,14 +408,14 @@ class ManagerTest extends TestCase { $backend->expects($this->never()) ->method('userExists'); - $manager = new \OC\User\Manager($this->config); + $manager = new \OC\User\Manager($this->config, $this->dispatcher); $manager->registerBackend($backend); $this->assertFalse($manager->createUser('foo', 'bar')); } public function testCreateUserNoBackends() { - $manager = new \OC\User\Manager($this->config); + $manager = new \OC\User\Manager($this->config, $this->dispatcher); $this->assertFalse($manager->createUser('foo', 'bar')); } @@ -431,7 +435,7 @@ class ManagerTest extends TestCase { ->with('MyUid', 'MyPassword') ->willReturn(false); - $manager = new Manager($config); + $manager = new Manager($config, $this->dispatcher); $manager->createUserFromBackend('MyUid', 'MyPassword', $backend); } @@ -471,7 +475,7 @@ class ManagerTest extends TestCase { ->with($this->equalTo('foo')) ->will($this->returnValue(true)); - $manager = new \OC\User\Manager($this->config); + $manager = new \OC\User\Manager($this->config, $this->dispatcher); $manager->registerBackend($backend1); $manager->registerBackend($backend2); @@ -479,7 +483,7 @@ class ManagerTest extends TestCase { } public function testCountUsersNoBackend() { - $manager = new \OC\User\Manager($this->config); + $manager = new \OC\User\Manager($this->config, $this->dispatcher); $result = $manager->countUsers(); $this->assertTrue(is_array($result)); @@ -504,7 +508,7 @@ class ManagerTest extends TestCase { ->method('getBackendName') ->will($this->returnValue('Mock_Test_Util_User_Dummy')); - $manager = new \OC\User\Manager($this->config); + $manager = new \OC\User\Manager($this->config, $this->dispatcher); $manager->registerBackend($backend); $result = $manager->countUsers(); @@ -545,7 +549,7 @@ class ManagerTest extends TestCase { ->method('getBackendName') ->will($this->returnValue('Mock_Test_Util_User_Dummy')); - $manager = new \OC\User\Manager($this->config); + $manager = new \OC\User\Manager($this->config, $this->dispatcher); $manager->registerBackend($backend1); $manager->registerBackend($backend2); @@ -660,7 +664,7 @@ class ManagerTest extends TestCase { ->with('foo', 'login', 'lastLogin') ->will($this->returnValue(0)); - $manager = new \OC\User\Manager($config); + $manager = new \OC\User\Manager($config, $this->dispatcher); $backend = new \Test\Util\User\Dummy(); $manager->registerBackend($backend); @@ -694,7 +698,7 @@ class ManagerTest extends TestCase { ->with($this->equalTo('uid2')) ->will($this->returnValue(true)); - $manager = new \OC\User\Manager($config); + $manager = new \OC\User\Manager($config, $this->dispatcher); $manager->registerBackend($backend); $users = $manager->getByEmail('test@example.com'); diff --git a/tests/lib/User/SessionTest.php b/tests/lib/User/SessionTest.php index 114b2eb5597..f6d86de7291 100644 --- a/tests/lib/User/SessionTest.php +++ b/tests/lib/User/SessionTest.php @@ -28,6 +28,7 @@ use OCP\IUser; use OCP\Lockdown\ILockdownManager; use OCP\Security\ICrypto; use OCP\Security\ISecureRandom; +use Symfony\Component\EventDispatcher\EventDispatcherInterface; /** * @group DB @@ -167,7 +168,7 @@ class SessionTest extends \Test\TestCase { 'getUser' ]) ->getMock(); - $user = new User('sepp', null); + $user = new User('sepp', null, $this->createMock(EventDispatcherInterface::class)); $userSession->expects($this->once()) ->method('getUser') ->will($this->returnValue($isLoggedIn ? $user : null)); @@ -184,7 +185,7 @@ class SessionTest extends \Test\TestCase { $backend = $this->createMock(\Test\Util\User\Dummy::class); - $user = $this->getMockBuilder(User::class)->setConstructorArgs(['foo', $backend])->getMock(); + $user = $this->createMock(IUser::class); $user->expects($this->once()) ->method('getUID') ->will($this->returnValue('foo')); @@ -220,12 +221,12 @@ class SessionTest extends \Test\TestCase { $mockedManagerMethods = array_diff($managerMethods, ['__construct', 'emit', 'listen']); $manager = $this->getMockBuilder(Manager::class) ->setMethods($mockedManagerMethods) - ->setConstructorArgs([$this->config]) + ->setConstructorArgs([$this->config, $this->createMock(EventDispatcherInterface::class)]) ->getMock(); $backend = $this->createMock(\Test\Util\User\Dummy::class); - $user = $this->getMockBuilder(User::class)->setConstructorArgs(['foo', $backend])->getMock(); + $user = $this->createMock(IUser::class); $user->expects($this->any()) ->method('isEnabled') ->will($this->returnValue(true)); @@ -271,12 +272,12 @@ class SessionTest extends \Test\TestCase { $mockedManagerMethods = array_diff($managerMethods, ['__construct', 'emit', 'listen']); $manager = $this->getMockBuilder(Manager::class) ->setMethods($mockedManagerMethods) - ->setConstructorArgs([$this->config]) + ->setConstructorArgs([$this->config, $this->createMock(EventDispatcherInterface::class)]) ->getMock(); $backend = $this->createMock(\Test\Util\User\Dummy::class); - $user = $this->getMockBuilder(User::class)->setConstructorArgs(['foo', $backend])->getMock(); + $user = $this->createMock(IUser::class); $user->expects($this->any()) ->method('isEnabled') ->will($this->returnValue(false)); @@ -299,12 +300,12 @@ class SessionTest extends \Test\TestCase { $mockedManagerMethods = array_diff($managerMethods, ['__construct', 'emit', 'listen']); $manager = $this->getMockBuilder(Manager::class) ->setMethods($mockedManagerMethods) - ->setConstructorArgs([$this->config]) + ->setConstructorArgs([$this->config, $this->createMock(EventDispatcherInterface::class)]) ->getMock(); $backend = $this->createMock(\Test\Util\User\Dummy::class); $userSession = new \OC\User\Session($manager, $session, $this->timeFactory, $this->tokenProvider, $this->config, $this->random, $this->lockdownManager, $this->logger); - $user = $this->getMockBuilder(User::class)->setConstructorArgs(['foo', $backend])->getMock(); + $user = $this->createMock(IUser::class); $session->expects($this->never()) ->method('set'); @@ -535,7 +536,7 @@ class SessionTest extends \Test\TestCase { $mockedManagerMethods = array_diff($managerMethods, ['__construct', 'emit', 'listen']); $manager = $this->getMockBuilder(Manager::class) ->setMethods($mockedManagerMethods) - ->setConstructorArgs([$this->config]) + ->setConstructorArgs([$this->config, $this->createMock(EventDispatcherInterface::class)]) ->getMock(); $userSession = $this->getMockBuilder(Session::class) //override, otherwise tests will fail because of setcookie() @@ -621,7 +622,7 @@ class SessionTest extends \Test\TestCase { $mockedManagerMethods = array_diff($managerMethods, ['__construct', 'emit', 'listen']); $manager = $this->getMockBuilder(Manager::class) ->setMethods($mockedManagerMethods) - ->setConstructorArgs([$this->config]) + ->setConstructorArgs([$this->config, $this->createMock(EventDispatcherInterface::class)]) ->getMock(); $userSession = $this->getMockBuilder(Session::class) //override, otherwise tests will fail because of setcookie() @@ -681,7 +682,7 @@ class SessionTest extends \Test\TestCase { $mockedManagerMethods = array_diff($managerMethods, ['__construct', 'emit', 'listen']); $manager = $this->getMockBuilder(Manager::class) ->setMethods($mockedManagerMethods) - ->setConstructorArgs([$this->config]) + ->setConstructorArgs([$this->config, $this->createMock(EventDispatcherInterface::class)]) ->getMock(); $userSession = $this->getMockBuilder(Session::class) //override, otherwise tests will fail because of setcookie() @@ -729,7 +730,7 @@ class SessionTest extends \Test\TestCase { $mockedManagerMethods = array_diff($managerMethods, ['__construct', 'emit', 'listen']); $manager = $this->getMockBuilder(Manager::class) ->setMethods($mockedManagerMethods) - ->setConstructorArgs([$this->config]) + ->setConstructorArgs([$this->config, $this->createMock(EventDispatcherInterface::class)]) ->getMock(); $userSession = $this->getMockBuilder(Session::class) //override, otherwise tests will fail because of setcookie() @@ -765,8 +766,8 @@ class SessionTest extends \Test\TestCase { public function testActiveUserAfterSetSession() { $users = array( - 'foo' => new User('foo', null), - 'bar' => new User('bar', null) + 'foo' => new User('foo', null, $this->createMock(EventDispatcherInterface::class)), + 'bar' => new User('bar', null, $this->createMock(EventDispatcherInterface::class)) ); $manager = $this->getMockBuilder('\OC\User\Manager') diff --git a/tests/lib/User/UserTest.php b/tests/lib/User/UserTest.php index 2a99e725ec7..16fde814b85 100644 --- a/tests/lib/User/UserTest.php +++ b/tests/lib/User/UserTest.php @@ -17,6 +17,8 @@ use OCP\IUser; use OCP\Notification\IManager as INotificationManager; use OCP\Notification\INotification; use OCP\UserInterface; +use PHPUnit\Framework\MockObject\MockObject; +use Symfony\Component\EventDispatcher\EventDispatcherInterface; use Test\TestCase; /** @@ -27,6 +29,15 @@ use Test\TestCase; * @package Test\User */ class UserTest extends TestCase { + + /** @var EventDispatcherInterface|MockObject */ + protected $dispatcher; + + public function setUp() { + parent::setUp(); + $this->dispatcher = $this->createMock(EventDispatcherInterface::class); + } + public function testDisplayName() { /** * @var \OC\User\Backend | \PHPUnit_Framework_MockObject_MockObject $backend @@ -42,7 +53,7 @@ class UserTest extends TestCase { ->with($this->equalTo(\OC\User\Backend::GET_DISPLAYNAME)) ->will($this->returnValue(true)); - $user = new User('foo', $backend); + $user = new User('foo', $backend, $this->dispatcher); $this->assertEquals('Foo', $user->getDisplayName()); } @@ -64,7 +75,7 @@ class UserTest extends TestCase { ->with($this->equalTo(\OC\User\Backend::GET_DISPLAYNAME)) ->will($this->returnValue(true)); - $user = new User('foo', $backend); + $user = new User('foo', $backend, $this->dispatcher); $this->assertEquals('foo', $user->getDisplayName()); } @@ -81,7 +92,7 @@ class UserTest extends TestCase { ->with($this->equalTo(\OC\User\Backend::GET_DISPLAYNAME)) ->will($this->returnValue(false)); - $user = new User('foo', $backend); + $user = new User('foo', $backend, $this->dispatcher); $this->assertEquals('foo', $user->getDisplayName()); } @@ -104,7 +115,7 @@ class UserTest extends TestCase { } })); - $user = new User('foo', $backend); + $user = new User('foo', $backend, $this->dispatcher); $this->assertTrue($user->setPassword('bar','')); } @@ -120,7 +131,7 @@ class UserTest extends TestCase { ->method('implementsActions') ->will($this->returnValue(false)); - $user = new User('foo', $backend); + $user = new User('foo', $backend, $this->dispatcher); $this->assertFalse($user->setPassword('bar','')); } @@ -144,7 +155,7 @@ class UserTest extends TestCase { } })); - $user = new User('foo', $backend); + $user = new User('foo', $backend, $this->dispatcher); $this->assertTrue($user->canChangeAvatar()); } @@ -168,7 +179,7 @@ class UserTest extends TestCase { } })); - $user = new User('foo', $backend); + $user = new User('foo', $backend, $this->dispatcher); $this->assertFalse($user->canChangeAvatar()); } @@ -184,7 +195,7 @@ class UserTest extends TestCase { ->method('implementsActions') ->willReturn(false); - $user = new User('foo', $backend); + $user = new User('foo', $backend, $this->dispatcher); $this->assertTrue($user->canChangeAvatar()); } @@ -197,7 +208,7 @@ class UserTest extends TestCase { ->method('deleteUser') ->with($this->equalTo('foo')); - $user = new User('foo', $backend); + $user = new User('foo', $backend, $this->dispatcher); $this->assertTrue($user->delete()); } @@ -229,7 +240,7 @@ class UserTest extends TestCase { ->method('deleteUser') ->with($this->equalTo('foo')); - $user = new User('foo', $backend); + $user = new User('foo', $backend, $this->dispatcher); $this->assertTrue($user->delete()); } @@ -253,14 +264,14 @@ class UserTest extends TestCase { } })); - $user = new User('foo', $backend); + $user = new User('foo', $backend, $this->dispatcher); $this->assertEquals('/home/foo', $user->getHome()); } public function testGetBackendClassName() { - $user = new User('foo', new \Test\Util\User\Dummy()); + $user = new User('foo', new \Test\Util\User\Dummy(), $this->dispatcher); $this->assertEquals('Dummy', $user->getBackendClassName()); - $user = new User('foo', new \OC\User\Database()); + $user = new User('foo', new \OC\User\Database(), $this->dispatcher); $this->assertEquals('Database', $user->getBackendClassName()); } @@ -287,7 +298,7 @@ class UserTest extends TestCase { ->with($this->equalTo('datadirectory')) ->will($this->returnValue('arbitrary/path')); - $user = new User('foo', $backend, null, $allConfig); + $user = new User('foo', $backend, $this->dispatcher, null, $allConfig); $this->assertEquals('arbitrary/path/foo', $user->getHome()); } @@ -307,7 +318,7 @@ class UserTest extends TestCase { } })); - $user = new User('foo', $backend); + $user = new User('foo', $backend, $this->dispatcher); $this->assertTrue($user->canChangePassword()); } @@ -321,7 +332,7 @@ class UserTest extends TestCase { ->method('implementsActions') ->will($this->returnValue(false)); - $user = new User('foo', $backend); + $user = new User('foo', $backend, $this->dispatcher); $this->assertFalse($user->canChangePassword()); } @@ -341,7 +352,7 @@ class UserTest extends TestCase { } })); - $user = new User('foo', $backend); + $user = new User('foo', $backend, $this->dispatcher); $this->assertTrue($user->canChangeDisplayName()); } @@ -355,7 +366,7 @@ class UserTest extends TestCase { ->method('implementsActions') ->will($this->returnValue(false)); - $user = new User('foo', $backend); + $user = new User('foo', $backend, $this->dispatcher); $this->assertFalse($user->canChangeDisplayName()); } @@ -380,7 +391,7 @@ class UserTest extends TestCase { ->with('foo','Foo') ->willReturn(true); - $user = new User('foo', $backend); + $user = new User('foo', $backend, $this->dispatcher); $this->assertTrue($user->setDisplayName('Foo')); $this->assertEquals('Foo',$user->getDisplayName()); } @@ -404,7 +415,7 @@ class UserTest extends TestCase { } })); - $user = new User('foo', $backend); + $user = new User('foo', $backend, $this->dispatcher); $this->assertFalse($user->setDisplayName(' ')); $this->assertEquals('foo',$user->getDisplayName()); } @@ -422,7 +433,7 @@ class UserTest extends TestCase { $backend->expects($this->never()) ->method('setDisplayName'); - $user = new User('foo', $backend); + $user = new User('foo', $backend, $this->dispatcher); $this->assertFalse($user->setDisplayName('Foo')); $this->assertEquals('foo',$user->getDisplayName()); } @@ -462,7 +473,7 @@ class UserTest extends TestCase { } })); - $user = new User('foo', $backend, $emitter); + $user = new User('foo', $backend, $this->dispatcher, $emitter); $user->setPassword('bar',''); $this->assertEquals(2, $hooksCalled); @@ -492,7 +503,7 @@ class UserTest extends TestCase { ->method('deleteUser') ->willReturn($result); $emitter = new PublicEmitter(); - $user = new User('foo', $backend, $emitter); + $user = new User('foo', $backend, $this->dispatcher, $emitter); /** * @param User $user @@ -573,7 +584,7 @@ class UserTest extends TestCase { ->method('getAbsoluteURL') ->withAnyParameters() ->willReturn('http://localhost:8888/owncloud'); - $user = new User('foo', $backend, null, null, $urlGenerator); + $user = new User('foo', $backend, $this->dispatcher, null, null, $urlGenerator); $this->assertEquals('foo@localhost:8888/owncloud', $user->getCloudId()); } @@ -609,7 +620,7 @@ class UserTest extends TestCase { 'email' ); - $user = new User('foo', $backend, $emitter, $config); + $user = new User('foo', $backend, $this->dispatcher, $emitter, $config); $user->setEMailAddress(''); } @@ -646,7 +657,7 @@ class UserTest extends TestCase { 'foo@bar.com' ); - $user = new User('foo', $backend, $emitter, $config); + $user = new User('foo', $backend, $this->dispatcher, $emitter, $config); $user->setEMailAddress('foo@bar.com'); } @@ -674,7 +685,7 @@ class UserTest extends TestCase { 'foo@bar.com' ); - $user = new User('foo', $backend, $emitter, $config); + $user = new User('foo', $backend, $this->dispatcher, $emitter, $config); $user->setEMailAddress('foo@bar.com'); } @@ -711,7 +722,7 @@ class UserTest extends TestCase { '23 TB' ); - $user = new User('foo', $backend, $emitter, $config); + $user = new User('foo', $backend, $this->dispatcher, $emitter, $config); $user->setQuota('23 TB'); } @@ -739,7 +750,7 @@ class UserTest extends TestCase { '23 TB' ); - $user = new User('foo', $backend, $emitter, $config); + $user = new User('foo', $backend, $this->dispatcher, $emitter, $config); $user->setQuota('23 TB'); } @@ -759,7 +770,7 @@ class UserTest extends TestCase { } })); - $user = new User('foo', $backend, null, $config); + $user = new User('foo', $backend, $this->dispatcher, null, $config); $this->assertSame(42, $user->getLastLogin()); } @@ -779,7 +790,7 @@ class UserTest extends TestCase { 'true' ); - $user = new User('foo', $backend, null, $config); + $user = new User('foo', $backend, $this->dispatcher, null, $config); $user->setEnabled(true); } @@ -803,6 +814,7 @@ class UserTest extends TestCase { ->setConstructorArgs([ 'foo', $backend, + $this->dispatcher, null, $config, ]) @@ -836,6 +848,7 @@ class UserTest extends TestCase { ->setConstructorArgs([ 'foo', $backend, + $this->dispatcher, null, $config, ]) @@ -867,7 +880,7 @@ class UserTest extends TestCase { } })); - $user = new User('foo', $backend, null, $config); + $user = new User('foo', $backend, $this->dispatcher, null, $config); $this->assertSame('foo@bar.com', $user->getEMailAddress()); } } diff --git a/tests/preseed-config.php b/tests/preseed-config.php index 70cf272faef..2d88d939157 100644 --- a/tests/preseed-config.php +++ b/tests/preseed-config.php @@ -63,6 +63,14 @@ if (getenv('OBJECT_STORE') === 'swift') { 'name' => 'default', ] ], + 'scope' => [ + 'project' => [ + 'name' => 'service', + 'domain' => [ + 'name' => 'default', + ], + ], + ], 'tenantName' => 'service', 'serviceName' => 'swift', 'region' => 'regionOne', |