diff options
Diffstat (limited to 'tests')
44 files changed, 2722 insertions, 362 deletions
diff --git a/tests/Core/Controller/AvatarControllerTest.php b/tests/Core/Controller/AvatarControllerTest.php index 937d8aaf17b..fe1a44b28ab 100644 --- a/tests/Core/Controller/AvatarControllerTest.php +++ b/tests/Core/Controller/AvatarControllerTest.php @@ -19,86 +19,103 @@ * */ -namespace Tests\Core\Controller; - -use OC\Core\Application; -use OCP\AppFramework\IAppContainer; -use OCP\AppFramework\Http; -use OCP\Files\File; -use OCP\Files\NotFoundException; -use OCP\IUser; -use OCP\IAvatar; -use Punic\Exception; -use Test\Traits\UserTrait; +namespace OC\Core\Controller; /** - * Overwrite is_uploaded_file in this namespace to allow proper unit testing of - * the postAvatar call. + * Overwrite is_uploaded_file in the OC\Core\Controller namespace to allow + * proper unit testing of the postAvatar call. */ function is_uploaded_file($filename) { return file_exists($filename); } +namespace Tests\Core\Controller; + +use OC\Core\Controller\AvatarController; +use OCP\AppFramework\Http; +use OCP\Files\Cache\ICache; +use OCP\Files\File; +use OCP\Files\IRootFolder; +use OCP\Files\NotFoundException; +use OCP\IAvatar; +use OCP\IAvatarManager; +use OCP\IL10N; +use OCP\ILogger; +use OCP\IRequest; +use OCP\IUser; +use OCP\IUserManager; + /** * Class AvatarControllerTest * - * @group DB - * * @package OC\Core\Controller */ class AvatarControllerTest extends \Test\TestCase { - use UserTrait; - - /** @var IAppContainer */ - private $container; /** @var \OC\Core\Controller\AvatarController */ private $avatarController; - /** @var IAvatar */ + /** @var IAvatar|\PHPUnit_Framework_MockObject_MockObject */ private $avatarMock; - /** @var IUser */ + /** @var IUser|\PHPUnit_Framework_MockObject_MockObject */ private $userMock; - /** @var File */ + /** @var File|\PHPUnit_Framework_MockObject_MockObject */ private $avatarFile; + + /** @var IAvatarManager|\PHPUnit_Framework_MockObject_MockObject */ + private $avatarManager; + /** @var ICache|\PHPUnit_Framework_MockObject_MockObject */ + private $cache; + /** @var IL10N|\PHPUnit_Framework_MockObject_MockObject */ + private $l; + /** @var IUserManager|\PHPUnit_Framework_MockObject_MockObject */ + private $userManager; + /** @var IRootFolder|\PHPUnit_Framework_MockObject_MockObject */ + private $rootFolder; + /** @var ILogger|\PHPUnit_Framework_MockObject_MockObject */ + private $logger; + /** @var IRequest|\PHPUnit_Framework_MockObject_MockObject */ + private $request; protected function setUp() { parent::setUp(); - $this->createUser('userid', 'pass'); - $this->loginAsUser('userid'); - - $app = new Application; - $this->container = $app->getContainer(); - $this->container['AppName'] = 'core'; - $this->container['AvatarManager'] = $this->getMock('OCP\IAvatarManager'); - $this->container['Cache'] = $this->getMockBuilder('OC\Cache\File') - ->disableOriginalConstructor()->getMock(); - $this->container['L10N'] = $this->getMock('OCP\IL10N'); - $this->container['L10N']->method('t')->will($this->returnArgument(0)); - $this->container['UserManager'] = $this->getMock('OCP\IUserManager'); - $this->container['UserSession'] = $this->getMock('OCP\IUserSession'); - $this->container['Request'] = $this->getMock('OCP\IRequest'); - $this->container['UserFolder'] = $this->getMock('OCP\Files\Folder'); - $this->container['Logger'] = $this->getMock('OCP\ILogger'); - $this->avatarMock = $this->getMock('OCP\IAvatar'); - $this->userMock = $this->getMock('OCP\IUser'); - - $this->avatarController = $this->container['AvatarController']; + $this->avatarManager = $this->getMockBuilder('OCP\IAvatarManager')->getMock(); + $this->cache = $this->getMockBuilder('OCP\ICache') + ->disableOriginalConstructor()->getMock(); + $this->l = $this->getMockBuilder('OCP\IL10N')->getMock(); + $this->l->method('t')->will($this->returnArgument(0)); + $this->userManager = $this->getMockBuilder('OCP\IUserManager')->getMock(); + $this->request = $this->getMockBuilder('OCP\IRequest')->getMock(); + $this->rootFolder = $this->getMockBuilder('OCP\Files\IRootFolder')->getMock(); + $this->logger = $this->getMockBuilder('OCP\ILogger')->getMock(); + + $this->avatarMock = $this->getMockBuilder('OCP\IAvatar')->getMock(); + $this->userMock = $this->getMockBuilder('OCP\IUser')->getMock(); + + $this->avatarController = new AvatarController( + 'core', + $this->request, + $this->avatarManager, + $this->cache, + $this->l, + $this->userManager, + $this->rootFolder, + $this->logger, + 'userid' + ); // Configure userMock $this->userMock->method('getDisplayName')->willReturn('displayName'); $this->userMock->method('getUID')->willReturn('userId'); - $this->container['UserManager']->method('get') + $this->userManager->method('get') ->willReturnMap([['userId', $this->userMock]]); - $this->container['UserSession']->method('getUser')->willReturn($this->userMock); - $this->avatarFile = $this->getMock('OCP\Files\File'); + $this->avatarFile = $this->getMockBuilder('OCP\Files\File')->getMock(); $this->avatarFile->method('getContent')->willReturn('image data'); $this->avatarFile->method('getMimeType')->willReturn('image type'); $this->avatarFile->method('getEtag')->willReturn('my etag'); } public function tearDown() { - $this->logout(); parent::tearDown(); } @@ -106,7 +123,7 @@ class AvatarControllerTest extends \Test\TestCase { * Fetch an avatar if a user has no avatar */ public function testGetAvatarNoAvatar() { - $this->container['AvatarManager']->method('getAvatar')->willReturn($this->avatarMock); + $this->avatarManager->method('getAvatar')->willReturn($this->avatarMock); $this->avatarMock->method('getFile')->will($this->throwException(new NotFoundException())); $response = $this->avatarController->getAvatar('userId', 32); @@ -121,7 +138,7 @@ class AvatarControllerTest extends \Test\TestCase { */ public function testGetAvatar() { $this->avatarMock->method('getFile')->willReturn($this->avatarFile); - $this->container['AvatarManager']->method('getAvatar')->with('userId')->willReturn($this->avatarMock); + $this->avatarManager->method('getAvatar')->with('userId')->willReturn($this->avatarMock); $response = $this->avatarController->getAvatar('userId', 32); @@ -129,14 +146,14 @@ class AvatarControllerTest extends \Test\TestCase { $this->assertArrayHasKey('Content-Type', $response->getHeaders()); $this->assertEquals('image type', $response->getHeaders()['Content-Type']); - $this->assertEquals('my etag', $response->getEtag()); + $this->assertEquals('my etag', $response->getETag()); } /** * Fetch the avatar of a non-existing user */ public function testGetAvatarNoUser() { - $this->container['AvatarManager'] + $this->avatarManager ->method('getAvatar') ->with('userDoesNotExist') ->will($this->throwException(new \Exception('user does not exist'))); @@ -158,7 +175,7 @@ class AvatarControllerTest extends \Test\TestCase { ->with($this->equalTo(32)) ->willReturn($this->avatarFile); - $this->container['AvatarManager']->method('getAvatar')->willReturn($this->avatarMock); + $this->avatarManager->method('getAvatar')->willReturn($this->avatarMock); $this->avatarController->getAvatar('userId', 32); } @@ -172,7 +189,7 @@ class AvatarControllerTest extends \Test\TestCase { ->with($this->equalTo(64)) ->willReturn($this->avatarFile); - $this->container['AvatarManager']->method('getAvatar')->willReturn($this->avatarMock); + $this->avatarManager->method('getAvatar')->willReturn($this->avatarMock); $this->avatarController->getAvatar('userId', 0); } @@ -186,7 +203,7 @@ class AvatarControllerTest extends \Test\TestCase { ->with($this->equalTo(2048)) ->willReturn($this->avatarFile); - $this->container['AvatarManager']->method('getAvatar')->willReturn($this->avatarMock); + $this->avatarManager->method('getAvatar')->willReturn($this->avatarMock); $this->avatarController->getAvatar('userId', 2049); } @@ -195,7 +212,7 @@ class AvatarControllerTest extends \Test\TestCase { * Remove an avatar */ public function testDeleteAvatar() { - $this->container['AvatarManager']->method('getAvatar')->willReturn($this->avatarMock); + $this->avatarManager->method('getAvatar')->willReturn($this->avatarMock); $response = $this->avatarController->deleteAvatar(); $this->assertEquals(Http::STATUS_OK, $response->getStatus()); @@ -206,12 +223,12 @@ class AvatarControllerTest extends \Test\TestCase { */ public function testDeleteAvatarException() { $this->avatarMock->method('remove')->will($this->throwException(new \Exception("foo"))); - $this->container['AvatarManager']->method('getAvatar')->willReturn($this->avatarMock); + $this->avatarManager->method('getAvatar')->willReturn($this->avatarMock); - $this->container['Logger']->expects($this->once()) + $this->logger->expects($this->once()) ->method('logException') ->with(new \Exception("foo")); - $expectedResponse = new Http\DataResponse(['data' => ['message' => 'An error occurred. Please contact your admin.']], Http::STATUS_BAD_REQUEST); + $expectedResponse = new Http\JSONResponse(['data' => ['message' => 'An error occurred. Please contact your admin.']], Http::STATUS_BAD_REQUEST); $this->assertEquals($expectedResponse, $this->avatarController->deleteAvatar()); } @@ -227,7 +244,7 @@ class AvatarControllerTest extends \Test\TestCase { * Fetch tmp avatar */ public function testTmpAvatarValid() { - $this->container['Cache']->method('get')->willReturn(file_get_contents(\OC::$SERVERROOT.'/tests/data/testimage.jpg')); + $this->cache->method('get')->willReturn(file_get_contents(\OC::$SERVERROOT.'/tests/data/testimage.jpg')); $response = $this->avatarController->getTmpAvatar(); $this->assertEquals(Http::STATUS_OK, $response->getStatus()); @@ -253,11 +270,11 @@ class AvatarControllerTest extends \Test\TestCase { $this->assertTrue($copyRes); //Create file in cache - $this->container['Cache']->method('get')->willReturn(file_get_contents(\OC::$SERVERROOT.'/tests/data/testimage.jpg')); + $this->cache->method('get')->willReturn(file_get_contents(\OC::$SERVERROOT.'/tests/data/testimage.jpg')); //Create request return $reqRet = ['error' => [0], 'tmp_name' => [$fileName], 'size' => [filesize(\OC::$SERVERROOT.'/tests/data/testimage.jpg')]]; - $this->container['Request']->method('getUploadedFile')->willReturn($reqRet); + $this->request->method('getUploadedFile')->willReturn($reqRet); $response = $this->avatarController->postAvatar(null); @@ -274,7 +291,7 @@ class AvatarControllerTest extends \Test\TestCase { public function testPostAvatarInvalidFile() { //Create request return $reqRet = ['error' => [1], 'tmp_name' => ['foo']]; - $this->container['Request']->method('getUploadedFile')->willReturn($reqRet); + $this->request->method('getUploadedFile')->willReturn($reqRet); $response = $this->avatarController->postAvatar(null); @@ -291,11 +308,11 @@ class AvatarControllerTest extends \Test\TestCase { $this->assertTrue($copyRes); //Create file in cache - $this->container['Cache']->method('get')->willReturn(file_get_contents(\OC::$SERVERROOT.'/tests/data/testimage.gif')); + $this->cache->method('get')->willReturn(file_get_contents(\OC::$SERVERROOT.'/tests/data/testimage.gif')); //Create request return $reqRet = ['error' => [0], 'tmp_name' => [$fileName], 'size' => filesize(\OC::$SERVERROOT.'/tests/data/testimage.gif')]; - $this->container['Request']->method('getUploadedFile')->willReturn($reqRet); + $this->request->method('getUploadedFile')->willReturn($reqRet); $response = $this->avatarController->postAvatar(null); @@ -313,7 +330,9 @@ class AvatarControllerTest extends \Test\TestCase { $file = $this->getMockBuilder('OCP\Files\File') ->disableOriginalConstructor()->getMock(); $file->method('getContent')->willReturn(file_get_contents(\OC::$SERVERROOT.'/tests/data/testimage.jpg')); - $this->container['UserFolder']->method('get')->willReturn($file); + $userFolder = $this->getMockBuilder('OCP\Files\Folder')->getMock(); + $this->rootFolder->method('getUserFolder')->with('userid')->willReturn($userFolder); + $userFolder->method('get')->willReturn($file); //Create request return $response = $this->avatarController->postAvatar('avatar.jpg'); @@ -326,8 +345,10 @@ class AvatarControllerTest extends \Test\TestCase { * Test posting avatar from existing folder */ public function testPostAvatarFromNoFile() { - $file = $this->getMock('OCP\Files\Node'); - $this->container['UserFolder'] + $file = $this->getMockBuilder('OCP\Files\Node')->getMock(); + $userFolder = $this->getMockBuilder('OCP\Files\Folder')->getMock(); + $this->rootFolder->method('getUserFolder')->with('userid')->willReturn($userFolder); + $userFolder ->method('get') ->with('folder') ->willReturn($file); @@ -343,18 +364,20 @@ class AvatarControllerTest extends \Test\TestCase { * Test what happens if the upload of the avatar fails */ public function testPostAvatarException() { - $this->container['Cache']->expects($this->once()) + $this->cache->expects($this->once()) ->method('set') ->will($this->throwException(new \Exception("foo"))); $file = $this->getMockBuilder('OCP\Files\File') ->disableOriginalConstructor()->getMock(); $file->method('getContent')->willReturn(file_get_contents(\OC::$SERVERROOT.'/tests/data/testimage.jpg')); - $this->container['UserFolder']->method('get')->willReturn($file); + $userFolder = $this->getMockBuilder('OCP\Files\Folder')->getMock(); + $this->rootFolder->method('getUserFolder')->with('userid')->willReturn($userFolder); + $userFolder->method('get')->willReturn($file); - $this->container['Logger']->expects($this->once()) + $this->logger->expects($this->once()) ->method('logException') ->with(new \Exception("foo")); - $expectedResponse = new Http\DataResponse(['data' => ['message' => 'An error occurred. Please contact your admin.']], Http::STATUS_OK); + $expectedResponse = new Http\JSONResponse(['data' => ['message' => 'An error occurred. Please contact your admin.']], Http::STATUS_OK); $this->assertEquals($expectedResponse, $this->avatarController->postAvatar('avatar.jpg')); } @@ -381,10 +404,10 @@ class AvatarControllerTest extends \Test\TestCase { * Test with non square crop */ public function testPostCroppedAvatarNoSquareCrop() { - $this->container['Cache']->method('get')->willReturn(file_get_contents(\OC::$SERVERROOT.'/tests/data/testimage.jpg')); + $this->cache->method('get')->willReturn(file_get_contents(\OC::$SERVERROOT.'/tests/data/testimage.jpg')); $this->avatarMock->method('set')->will($this->throwException(new \OC\NotSquareException)); - $this->container['AvatarManager']->method('getAvatar')->willReturn($this->avatarMock); + $this->avatarManager->method('getAvatar')->willReturn($this->avatarMock); $response = $this->avatarController->postCroppedAvatar(['x' => 0, 'y' => 0, 'w' => 10, 'h' => 11]); $this->assertEquals(Http::STATUS_BAD_REQUEST, $response->getStatus()); @@ -394,8 +417,8 @@ class AvatarControllerTest extends \Test\TestCase { * Check for proper reply on proper crop argument */ public function testPostCroppedAvatarValidCrop() { - $this->container['Cache']->method('get')->willReturn(file_get_contents(\OC::$SERVERROOT.'/tests/data/testimage.jpg')); - $this->container['AvatarManager']->method('getAvatar')->willReturn($this->avatarMock); + $this->cache->method('get')->willReturn(file_get_contents(\OC::$SERVERROOT.'/tests/data/testimage.jpg')); + $this->avatarManager->method('getAvatar')->willReturn($this->avatarMock); $response = $this->avatarController->postCroppedAvatar(['x' => 0, 'y' => 0, 'w' => 10, 'h' => 10]); $this->assertEquals(Http::STATUS_OK, $response->getStatus()); @@ -406,15 +429,15 @@ class AvatarControllerTest extends \Test\TestCase { * Test what happens if the cropping of the avatar fails */ public function testPostCroppedAvatarException() { - $this->container['Cache']->method('get')->willReturn(file_get_contents(\OC::$SERVERROOT.'/tests/data/testimage.jpg')); + $this->cache->method('get')->willReturn(file_get_contents(\OC::$SERVERROOT.'/tests/data/testimage.jpg')); $this->avatarMock->method('set')->will($this->throwException(new \Exception('foo'))); - $this->container['AvatarManager']->method('getAvatar')->willReturn($this->avatarMock); + $this->avatarManager->method('getAvatar')->willReturn($this->avatarMock); - $this->container['Logger']->expects($this->once()) + $this->logger->expects($this->once()) ->method('logException') ->with(new \Exception('foo')); - $expectedResponse = new Http\DataResponse(['data' => ['message' => 'An error occurred. Please contact your admin.']], Http::STATUS_BAD_REQUEST); + $expectedResponse = new Http\JSONResponse(['data' => ['message' => 'An error occurred. Please contact your admin.']], Http::STATUS_BAD_REQUEST); $this->assertEquals($expectedResponse, $this->avatarController->postCroppedAvatar(['x' => 0, 'y' => 0, 'w' => 10, 'h' => 11])); } @@ -426,7 +449,7 @@ class AvatarControllerTest extends \Test\TestCase { $fileName = \OC::$SERVERROOT.'/tests/data/testimage.jpg'; //Create request return $reqRet = ['error' => [0], 'tmp_name' => [$fileName], 'size' => [21*1024*1024]]; - $this->container['Request']->method('getUploadedFile')->willReturn($reqRet); + $this->request->method('getUploadedFile')->willReturn($reqRet); $response = $this->avatarController->postAvatar(null); diff --git a/tests/Core/Controller/ChangePasswordControllerTest.php b/tests/Core/Controller/ChangePasswordControllerTest.php new file mode 100644 index 00000000000..8dd4ca8db95 --- /dev/null +++ b/tests/Core/Controller/ChangePasswordControllerTest.php @@ -0,0 +1,161 @@ +<?php +/** + * + * @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 Tests\Core\Controller; + +use OC\Settings\Controller\ChangePasswordController; +use OC\User\Session; +use OCP\App\IAppManager; +use OCP\IGroupManager; +use OCP\IL10N; +use OCP\IUserManager; + +class ChangePasswordControllerTest extends \Test\TestCase { + + /** @var string */ + private $userId = 'currentUser'; + + /** @var IUserManager */ + private $userManager; + + /** @var Session */ + private $userSession; + + /** @var IGroupManager */ + private $groupManager; + + /** @var IAppManager */ + private $appManager; + + /** @var IL10N */ + private $l; + + /** @var ChangePasswordController */ + private $controller; + + public function setUp() { + parent::setUp(); + + $this->userManager = $this->getMockBuilder('OCP\IUserManager')->getMock(); + $this->userSession = $this->getMockBuilder('OC\User\Session')->disableOriginalConstructor()->getMock(); + $this->groupManager = $this->getMockBuilder('OCP\IGroupManager')->getMock(); + $this->appManager = $this->getMockBuilder('OCP\App\IAppManager')->getMock(); + $this->l = $this->getMockBuilder('OCP\IL10N')->getMock(); + + $this->l->method('t')->will($this->returnArgument(0)); + + $request = $this->getMockBuilder('OCP\IRequest')->getMock(); + + $this->controller = new ChangePasswordController( + 'core', + $request, + $this->userId, + $this->userManager, + $this->userSession, + $this->groupManager, + $this->appManager, + $this->l + ); + } + + public function testChangePersonalPasswordWrongPassword() { + $this->userManager->expects($this->once()) + ->method('checkPassword') + ->with($this->userId, 'old') + ->willReturn(false); + + $expects = [ + 'status' => 'error', + 'data' => [ + 'message' => 'Wrong password', + ], + ]; + + $res = $this->controller->changePersonalPassword('old', 'new'); + + $this->assertEquals($expects, $res->getData()); + } + + public function testChangePersonalPasswordNoNewPassword() { + $user = $this->getMockBuilder('OCP\IUser')->getMock(); + $this->userManager->expects($this->once()) + ->method('checkPassword') + ->with($this->userId, 'old') + ->willReturn($user); + + $expects = [ + 'status' => 'error', + ]; + + $res = $this->controller->changePersonalPassword('old'); + + $this->assertEquals($expects, $res->getData()); + } + + public function testChangePersonalPasswordCantSetPassword() { + $user = $this->getMockBuilder('OCP\IUser')->getMock(); + $this->userManager->expects($this->once()) + ->method('checkPassword') + ->with($this->userId, 'old') + ->willReturn($user); + + $user->expects($this->once()) + ->method('setPassword') + ->with('new') + ->willReturn(false); + + $expects = [ + 'status' => 'error', + ]; + + $res = $this->controller->changePersonalPassword('old', 'new'); + + $this->assertEquals($expects, $res->getData()); + } + + public function testChangePersonalPassword() { + $user = $this->getMockBuilder('OCP\IUser')->getMock(); + $this->userManager->expects($this->once()) + ->method('checkPassword') + ->with($this->userId, 'old') + ->willReturn($user); + + $user->expects($this->once()) + ->method('setPassword') + ->with('new') + ->willReturn(true); + + $this->userSession->expects($this->once()) + ->method('updateSessionTokenPassword') + ->with('new'); + + $expects = [ + 'status' => 'success', + 'data' => [ + 'message' => 'Saved', + ], + ]; + + $res = $this->controller->changePersonalPassword('old', 'new'); + + $this->assertEquals($expects, $res->getData()); + } +} diff --git a/tests/Core/Controller/LoginControllerTest.php b/tests/Core/Controller/LoginControllerTest.php index f09f3c98118..ff50ac98fbd 100644 --- a/tests/Core/Controller/LoginControllerTest.php +++ b/tests/Core/Controller/LoginControllerTest.php @@ -57,14 +57,14 @@ class LoginControllerTest extends TestCase { public function setUp() { parent::setUp(); - $this->request = $this->getMock('\\OCP\\IRequest'); - $this->userManager = $this->getMock('\\OCP\\IUserManager'); - $this->config = $this->getMock('\\OCP\\IConfig'); - $this->session = $this->getMock('\\OCP\\ISession'); + $this->request = $this->getMockBuilder('\\OCP\\IRequest')->getMock(); + $this->userManager = $this->getMockBuilder('\\OCP\\IUserManager')->getMock(); + $this->config = $this->getMockBuilder('\\OCP\\IConfig')->getMock(); + $this->session = $this->getMockBuilder('\\OCP\\ISession')->getMock(); $this->userSession = $this->getMockBuilder('\\OC\\User\\Session') ->disableOriginalConstructor() ->getMock(); - $this->urlGenerator = $this->getMock('\\OCP\\IURLGenerator'); + $this->urlGenerator = $this->getMockBuilder('\\OCP\\IURLGenerator')->getMock(); $this->twoFactorManager = $this->getMockBuilder('\OC\Authentication\TwoFactorAuth\Manager') ->disableOriginalConstructor() ->getMock(); @@ -110,7 +110,7 @@ class LoginControllerTest extends TestCase { ->method('getCookie') ->with('oc_token') ->willReturn('MyLoginToken'); - $user = $this->getMock('\\OCP\\IUser'); + $user = $this->getMockBuilder('\\OCP\\IUser')->getMock(); $user ->expects($this->once()) ->method('getUID') @@ -181,6 +181,7 @@ class LoginControllerTest extends TestCase { 'alt_login' => [], 'rememberLoginAllowed' => \OC_Util::rememberLoginAllowed(), 'rememberLoginState' => 0, + 'resetPasswordLink' => null, ], 'guest' ); @@ -217,7 +218,7 @@ class LoginControllerTest extends TestCase { ->method('getSystemValue') ->with('lost_password_link') ->willReturn(false); - $user = $this->getMock('\\OCP\\IUser'); + $user = $this->getMockBuilder('\\OCP\\IUser')->getMock(); $user ->expects($this->once()) ->method('canChangePassword') @@ -239,6 +240,7 @@ class LoginControllerTest extends TestCase { 'alt_login' => [], 'rememberLoginAllowed' => \OC_Util::rememberLoginAllowed(), 'rememberLoginState' => 0, + 'resetPasswordLink' => false, ], 'guest' ); @@ -255,7 +257,7 @@ class LoginControllerTest extends TestCase { ->method('getSystemValue') ->with('lost_password_link') ->willReturn(false); - $user = $this->getMock('\\OCP\\IUser'); + $user = $this->getMockBuilder('\\OCP\\IUser')->getMock(); $user ->expects($this->once()) ->method('canChangePassword') @@ -277,6 +279,7 @@ class LoginControllerTest extends TestCase { 'alt_login' => [], 'rememberLoginAllowed' => \OC_Util::rememberLoginAllowed(), 'rememberLoginState' => 0, + 'resetPasswordLink' => false, ], 'guest' ); @@ -292,6 +295,10 @@ class LoginControllerTest extends TestCase { ->expects($this->exactly(4)) ->method('getRemoteAddress') ->willReturn('192.168.0.1'); + $this->request + ->expects($this->once()) + ->method('passesCSRFCheck') + ->willReturn(true); $this->throttler ->expects($this->exactly(2)) ->method('sleepDelay') @@ -315,6 +322,8 @@ class LoginControllerTest extends TestCase { $this->userSession->expects($this->never()) ->method('createSessionToken'); + $this->config->expects($this->never()) + ->method('deleteUserValue'); $expected = new \OCP\AppFramework\Http\RedirectResponse($loginPageUrl); $this->assertEquals($expected, $this->loginController->tryLogin($user, $password, '')); @@ -322,14 +331,21 @@ class LoginControllerTest extends TestCase { public function testLoginWithValidCredentials() { /** @var IUser | \PHPUnit_Framework_MockObject_MockObject $user */ - $user = $this->getMock('\OCP\IUser'); + $user = $this->getMockBuilder('\OCP\IUser')->getMock(); + $user->expects($this->any()) + ->method('getUID') + ->will($this->returnValue('uid')); $password = 'secret'; - $indexPageUrl = 'some url'; + $indexPageUrl = \OC_Util::getDefaultPageUrl(); $this->request ->expects($this->exactly(2)) ->method('getRemoteAddress') ->willReturn('192.168.0.1'); + $this->request + ->expects($this->once()) + ->method('passesCSRFCheck') + ->willReturn(true); $this->throttler ->expects($this->once()) ->method('sleepDelay') @@ -352,18 +368,96 @@ class LoginControllerTest extends TestCase { ->method('isTwoFactorAuthenticated') ->with($user) ->will($this->returnValue(false)); - $this->urlGenerator->expects($this->once()) - ->method('linkToRoute') - ->with('files.view.index') - ->will($this->returnValue($indexPageUrl)); + $this->config->expects($this->once()) + ->method('deleteUserValue') + ->with('uid', 'core', 'lostpassword'); $expected = new \OCP\AppFramework\Http\RedirectResponse($indexPageUrl); $this->assertEquals($expected, $this->loginController->tryLogin($user, $password, null)); } + public function testLoginWithoutPassedCsrfCheckAndNotLoggedIn() { + /** @var IUser | \PHPUnit_Framework_MockObject_MockObject $user */ + $user = $this->getMockBuilder('\OCP\IUser')->getMock(); + $user->expects($this->any()) + ->method('getUID') + ->will($this->returnValue('jane')); + $password = 'secret'; + $originalUrl = 'another%20url'; + + $this->request + ->expects($this->exactly(2)) + ->method('getRemoteAddress') + ->willReturn('192.168.0.1'); + $this->request + ->expects($this->once()) + ->method('passesCSRFCheck') + ->willReturn(false); + $this->throttler + ->expects($this->once()) + ->method('sleepDelay') + ->with('192.168.0.1'); + $this->throttler + ->expects($this->once()) + ->method('getDelay') + ->with('192.168.0.1') + ->willReturn(200); + $this->userSession->expects($this->once()) + ->method('isLoggedIn') + ->with() + ->will($this->returnValue(false)); + $this->config->expects($this->never()) + ->method('deleteUserValue'); + + $expected = new \OCP\AppFramework\Http\RedirectResponse(\OC_Util::getDefaultPageUrl()); + $this->assertEquals($expected, $this->loginController->tryLogin('Jane', $password, $originalUrl)); + } + + public function testLoginWithoutPassedCsrfCheckAndLoggedIn() { + /** @var IUser | \PHPUnit_Framework_MockObject_MockObject $user */ + $user = $this->getMockBuilder('\OCP\IUser')->getMock(); + $user->expects($this->any()) + ->method('getUID') + ->will($this->returnValue('jane')); + $password = 'secret'; + $originalUrl = 'another%20url'; + $redirectUrl = 'http://localhost/another url'; + + $this->request + ->expects($this->exactly(2)) + ->method('getRemoteAddress') + ->willReturn('192.168.0.1'); + $this->request + ->expects($this->once()) + ->method('passesCSRFCheck') + ->willReturn(false); + $this->throttler + ->expects($this->once()) + ->method('sleepDelay') + ->with('192.168.0.1'); + $this->throttler + ->expects($this->once()) + ->method('getDelay') + ->with('192.168.0.1') + ->willReturn(200); + $this->userSession->expects($this->once()) + ->method('isLoggedIn') + ->with() + ->will($this->returnValue(true)); + $this->urlGenerator->expects($this->once()) + ->method('getAbsoluteURL') + ->with(urldecode($originalUrl)) + ->will($this->returnValue($redirectUrl)); + $this->config->expects($this->never()) + ->method('deleteUserValue'); + + $expected = new \OCP\AppFramework\Http\RedirectResponse($redirectUrl); + $this->assertEquals($expected, $this->loginController->tryLogin('Jane', $password, $originalUrl)); + } + public function testLoginWithValidCredentialsAndRedirectUrl() { /** @var IUser | \PHPUnit_Framework_MockObject_MockObject $user */ - $user = $this->getMock('\OCP\IUser'); + $user = $this->getMockBuilder('\OCP\IUser')->getMock(); $user->expects($this->any()) ->method('getUID') ->will($this->returnValue('jane')); @@ -375,6 +469,10 @@ class LoginControllerTest extends TestCase { ->expects($this->exactly(2)) ->method('getRemoteAddress') ->willReturn('192.168.0.1'); + $this->request + ->expects($this->once()) + ->method('passesCSRFCheck') + ->willReturn(true); $this->throttler ->expects($this->once()) ->method('sleepDelay') @@ -399,24 +497,97 @@ class LoginControllerTest extends TestCase { ->method('getAbsoluteURL') ->with(urldecode($originalUrl)) ->will($this->returnValue($redirectUrl)); + $this->config->expects($this->once()) + ->method('deleteUserValue') + ->with('jane', 'core', 'lostpassword'); $expected = new \OCP\AppFramework\Http\RedirectResponse(urldecode($redirectUrl)); $this->assertEquals($expected, $this->loginController->tryLogin('Jane', $password, $originalUrl)); } - public function testLoginWithTwoFactorEnforced() { + public function testLoginWithOneTwoFactorProvider() { + /** @var IUser | \PHPUnit_Framework_MockObject_MockObject $user */ + $user = $this->getMockBuilder('\OCP\IUser')->getMock(); + $user->expects($this->any()) + ->method('getUID') + ->will($this->returnValue('john')); + $password = 'secret'; + $challengeUrl = 'challenge/url'; + $provider = $this->getMockBuilder('\OCP\Authentication\TwoFactorAuth\IProvider')->getMock(); + + $this->request + ->expects($this->exactly(2)) + ->method('getRemoteAddress') + ->willReturn('192.168.0.1'); + $this->request + ->expects($this->once()) + ->method('passesCSRFCheck') + ->willReturn(true); + $this->throttler + ->expects($this->once()) + ->method('sleepDelay') + ->with('192.168.0.1'); + $this->throttler + ->expects($this->once()) + ->method('getDelay') + ->with('192.168.0.1') + ->willReturn(200); + $this->userManager->expects($this->once()) + ->method('checkPassword') + ->will($this->returnValue($user)); + $this->userSession->expects($this->once()) + ->method('login') + ->with('john@doe.com', $password); + $this->userSession->expects($this->once()) + ->method('createSessionToken') + ->with($this->request, $user->getUID(), 'john@doe.com', $password); + $this->twoFactorManager->expects($this->once()) + ->method('isTwoFactorAuthenticated') + ->with($user) + ->will($this->returnValue(true)); + $this->twoFactorManager->expects($this->once()) + ->method('prepareTwoFactorLogin') + ->with($user); + $this->twoFactorManager->expects($this->once()) + ->method('getProviders') + ->with($user) + ->will($this->returnValue([$provider])); + $provider->expects($this->once()) + ->method('getId') + ->will($this->returnValue('u2f')); + $this->urlGenerator->expects($this->once()) + ->method('linkToRoute') + ->with('core.TwoFactorChallenge.showChallenge', [ + 'challengeProviderId' => 'u2f', + ]) + ->will($this->returnValue($challengeUrl)); + $this->config->expects($this->once()) + ->method('deleteUserValue') + ->with('john', 'core', 'lostpassword'); + + $expected = new RedirectResponse($challengeUrl); + $this->assertEquals($expected, $this->loginController->tryLogin('john@doe.com', $password, null)); + } + + public function testLoginWithMultpleTwoFactorProviders() { /** @var IUser | \PHPUnit_Framework_MockObject_MockObject $user */ - $user = $this->getMock('\OCP\IUser'); + $user = $this->getMockBuilder('\OCP\IUser')->getMock(); $user->expects($this->any()) ->method('getUID') ->will($this->returnValue('john')); $password = 'secret'; $challengeUrl = 'challenge/url'; + $provider1 = $this->getMockBuilder('\OCP\Authentication\TwoFactorAuth\IProvider')->getMock(); + $provider2 = $this->getMockBuilder('\OCP\Authentication\TwoFactorAuth\IProvider')->getMock(); $this->request ->expects($this->exactly(2)) ->method('getRemoteAddress') ->willReturn('192.168.0.1'); + $this->request + ->expects($this->once()) + ->method('passesCSRFCheck') + ->willReturn(true); $this->throttler ->expects($this->once()) ->method('sleepDelay') @@ -442,10 +613,21 @@ class LoginControllerTest extends TestCase { $this->twoFactorManager->expects($this->once()) ->method('prepareTwoFactorLogin') ->with($user); + $this->twoFactorManager->expects($this->once()) + ->method('getProviders') + ->with($user) + ->will($this->returnValue([$provider1, $provider2])); + $provider1->expects($this->never()) + ->method('getId'); + $provider2->expects($this->never()) + ->method('getId'); $this->urlGenerator->expects($this->once()) ->method('linkToRoute') ->with('core.TwoFactorChallenge.selectChallenge') ->will($this->returnValue($challengeUrl)); + $this->config->expects($this->once()) + ->method('deleteUserValue') + ->with('john', 'core', 'lostpassword'); $expected = new RedirectResponse($challengeUrl); $this->assertEquals($expected, $this->loginController->tryLogin('john@doe.com', $password, null)); @@ -453,7 +635,7 @@ class LoginControllerTest extends TestCase { public function testToNotLeakLoginName() { /** @var IUser | \PHPUnit_Framework_MockObject_MockObject $user */ - $user = $this->getMock('\OCP\IUser'); + $user = $this->getMockBuilder('\OCP\IUser')->getMock(); $user->expects($this->any()) ->method('getUID') ->will($this->returnValue('john')); @@ -479,6 +661,10 @@ class LoginControllerTest extends TestCase { ->expects($this->exactly(3)) ->method('getRemoteAddress') ->willReturn('192.168.0.1'); + $this->request + ->expects($this->once()) + ->method('passesCSRFCheck') + ->willReturn(true); $this->throttler ->expects($this->once()) ->method('getDelay') @@ -492,6 +678,8 @@ class LoginControllerTest extends TestCase { ->expects($this->once()) ->method('registerAttempt') ->with('login', '192.168.0.1', ['user' => 'john@doe.com']); + $this->config->expects($this->never()) + ->method('deleteUserValue'); $expected = new RedirectResponse(''); $this->assertEquals($expected, $this->loginController->tryLogin('john@doe.com', 'just wrong', null)); diff --git a/tests/Core/Controller/LostControllerTest.php b/tests/Core/Controller/LostControllerTest.php index 492a04bcfde..2e7d6721d56 100644 --- a/tests/Core/Controller/LostControllerTest.php +++ b/tests/Core/Controller/LostControllerTest.php @@ -133,7 +133,7 @@ class LostControllerTest extends \PHPUnit_Framework_TestCase { $this->config ->expects($this->once()) ->method('getUserValue') - ->with('ValidTokenUser', 'owncloud', 'lostpassword', null) + ->with('ValidTokenUser', 'core', 'lostpassword', null) ->will($this->returnValue('12345:TheOnlyAndOnlyOneTokenToResetThePassword')); $user = $this->getMockBuilder('\OCP\IUser') ->disableOriginalConstructor()->getMock(); @@ -180,7 +180,7 @@ class LostControllerTest extends \PHPUnit_Framework_TestCase { $this->config ->expects($this->once()) ->method('getUserValue') - ->with('ValidTokenUser', 'owncloud', 'lostpassword', null) + ->with('ValidTokenUser', 'core', 'lostpassword', null) ->will($this->returnValue('12345:TheOnlyAndOnlyOneTokenToResetThePassword')); $response = $this->lostController->resetform($token, $userId); $expectedResponse = new TemplateResponse('core', @@ -217,19 +217,19 @@ class LostControllerTest extends \PHPUnit_Framework_TestCase { $this->config ->expects($this->once()) ->method('getUserValue') - ->with('ValidTokenUser', 'owncloud', 'lostpassword', null) + ->with('ValidTokenUser', 'core', 'lostpassword', null) ->will($this->returnValue('12345:TheOnlyAndOnlyOneTokenToResetThePassword')); $this->urlGenerator ->expects($this->once()) ->method('linkToRouteAbsolute') ->with('core.lost.setPassword', array('userId' => 'ValidTokenUser', 'token' => 'TheOnlyAndOnlyOneTokenToResetThePassword')) - ->will($this->returnValue('https://ownCloud.com/index.php/lostpassword/')); + ->will($this->returnValue('https://example.tld/index.php/lostpassword/')); $response = $this->lostController->resetform($token, $userId); $expectedResponse = new TemplateResponse('core', 'lostpassword/resetpassword', array( - 'link' => 'https://ownCloud.com/index.php/lostpassword/', + 'link' => 'https://example.tld/index.php/lostpassword/', ), 'guest'); $this->assertEquals($expectedResponse, $response); @@ -291,12 +291,12 @@ class LostControllerTest extends \PHPUnit_Framework_TestCase { $this->config ->expects($this->once()) ->method('setUserValue') - ->with('ExistingUser', 'owncloud', 'lostpassword', '12348:ThisIsMaybeANotSoSecretToken!'); + ->with('ExistingUser', 'core', 'lostpassword', '12348:ThisIsMaybeANotSoSecretToken!'); $this->urlGenerator ->expects($this->once()) ->method('linkToRouteAbsolute') ->with('core.lost.resetform', array('userId' => 'ExistingUser', 'token' => 'ThisIsMaybeANotSoSecretToken!')) - ->will($this->returnValue('https://ownCloud.com/index.php/lostpassword/')); + ->will($this->returnValue('https://example.tld/index.php/lostpassword/')); $message = $this->getMockBuilder('\OC\Mail\Message') ->disableOriginalConstructor()->getMock(); $message @@ -310,7 +310,7 @@ class LostControllerTest extends \PHPUnit_Framework_TestCase { $message ->expects($this->at(2)) ->method('setPlainBody') - ->with('Use the following link to reset your password: https://ownCloud.com/index.php/lostpassword/'); + ->with('Use the following link to reset your password: https://example.tld/index.php/lostpassword/'); $message ->expects($this->at(3)) ->method('setFrom') @@ -348,7 +348,7 @@ class LostControllerTest extends \PHPUnit_Framework_TestCase { $this->config ->expects($this->once()) ->method('setUserValue') - ->with('ExistingUser', 'owncloud', 'lostpassword', '12348:ThisIsMaybeANotSoSecretToken!'); + ->with('ExistingUser', 'core', 'lostpassword', '12348:ThisIsMaybeANotSoSecretToken!'); $this->timeFactory ->expects($this->once()) ->method('getTime') @@ -357,7 +357,7 @@ class LostControllerTest extends \PHPUnit_Framework_TestCase { ->expects($this->once()) ->method('linkToRouteAbsolute') ->with('core.lost.resetform', array('userId' => 'ExistingUser', 'token' => 'ThisIsMaybeANotSoSecretToken!')) - ->will($this->returnValue('https://ownCloud.com/index.php/lostpassword/')); + ->will($this->returnValue('https://example.tld/index.php/lostpassword/')); $message = $this->getMockBuilder('\OC\Mail\Message') ->disableOriginalConstructor()->getMock(); $message @@ -371,7 +371,7 @@ class LostControllerTest extends \PHPUnit_Framework_TestCase { $message ->expects($this->at(2)) ->method('setPlainBody') - ->with('Use the following link to reset your password: https://ownCloud.com/index.php/lostpassword/'); + ->with('Use the following link to reset your password: https://example.tld/index.php/lostpassword/'); $message ->expects($this->at(3)) ->method('setFrom') @@ -395,7 +395,7 @@ class LostControllerTest extends \PHPUnit_Framework_TestCase { $this->config ->expects($this->once()) ->method('getUserValue') - ->with('InvalidTokenUser', 'owncloud', 'lostpassword', null) + ->with('InvalidTokenUser', 'core', 'lostpassword', null) ->will($this->returnValue('TheOnlyAndOnlyOneTokenToResetThePassword')); // With an invalid token @@ -417,7 +417,7 @@ class LostControllerTest extends \PHPUnit_Framework_TestCase { $this->config ->expects($this->once()) ->method('getUserValue') - ->with('ValidTokenUser', 'owncloud', 'lostpassword', null) + ->with('ValidTokenUser', 'core', 'lostpassword', null) ->will($this->returnValue('12345:TheOnlyAndOnlyOneTokenToResetThePassword')); $user = $this->getMockBuilder('\OCP\IUser') ->disableOriginalConstructor()->getMock(); @@ -437,7 +437,7 @@ class LostControllerTest extends \PHPUnit_Framework_TestCase { $this->config ->expects($this->once()) ->method('deleteUserValue') - ->with('ValidTokenUser', 'owncloud', 'lostpassword'); + ->with('ValidTokenUser', 'core', 'lostpassword'); $this->timeFactory ->expects($this->once()) ->method('getTime') @@ -452,7 +452,7 @@ class LostControllerTest extends \PHPUnit_Framework_TestCase { $this->config ->expects($this->once()) ->method('getUserValue') - ->with('ValidTokenUser', 'owncloud', 'lostpassword', null) + ->with('ValidTokenUser', 'core', 'lostpassword', null) ->will($this->returnValue('12345:TheOnlyAndOnlyOneTokenToResetThePassword')); $user = $this->getMockBuilder('\OCP\IUser') ->disableOriginalConstructor()->getMock(); @@ -478,7 +478,7 @@ class LostControllerTest extends \PHPUnit_Framework_TestCase { $this->config ->expects($this->once()) ->method('getUserValue') - ->with('ValidTokenUser', 'owncloud', 'lostpassword', null) + ->with('ValidTokenUser', 'core', 'lostpassword', null) ->will($this->returnValue('TheOnlyAndOnlyOneTokenToResetThePassword')); $user = $this->getMockBuilder('\OCP\IUser') ->disableOriginalConstructor()->getMock(); @@ -500,7 +500,7 @@ class LostControllerTest extends \PHPUnit_Framework_TestCase { $this->config ->expects($this->once()) ->method('getUserValue') - ->with('ValidTokenUser', 'owncloud', 'lostpassword', null) + ->with('ValidTokenUser', 'core', 'lostpassword', null) ->will($this->returnValue('12345:TheOnlyAndOnlyOneTokenToResetThePassword')); $user = $this->getMockBuilder('\OCP\IUser') ->disableOriginalConstructor()->getMock(); @@ -530,7 +530,7 @@ class LostControllerTest extends \PHPUnit_Framework_TestCase { $this->config ->expects($this->once()) ->method('getUserValue') - ->with('ValidTokenUser', 'owncloud', 'lostpassword', null) + ->with('ValidTokenUser', 'core', 'lostpassword', null) ->will($this->returnValue(null)); $response = $this->lostController->setPassword('', 'ValidTokenUser', 'NewPassword', true); diff --git a/tests/Core/Controller/TokenControllerTest.php b/tests/Core/Controller/TokenControllerTest.php index b6b54b14fad..0e965aac2e5 100644 --- a/tests/Core/Controller/TokenControllerTest.php +++ b/tests/Core/Controller/TokenControllerTest.php @@ -41,15 +41,17 @@ class TokenControllerTest extends TestCase { protected function setUp() { parent::setUp(); - $this->request = $this->getMock('\OCP\IRequest'); + $this->request = $this->getMockBuilder('\OCP\IRequest')->getMock(); $this->userManager = $this->getMockBuilder('\OC\User\Manager') ->disableOriginalConstructor() ->getMock(); - $this->tokenProvider = $this->getMock('\OC\Authentication\Token\IProvider'); + $this->tokenProvider = $this->getMockBuilder('\OC\Authentication\Token\IProvider') + ->getMock(); $this->twoFactorAuthManager = $this->getMockBuilder('\OC\Authentication\TwoFactorAuth\Manager') ->disableOriginalConstructor() ->getMock(); - $this->secureRandom = $this->getMock('\OCP\Security\ISecureRandom'); + $this->secureRandom = $this->getMockBuilder('\OCP\Security\ISecureRandom') + ->getMock(); $this->tokenController = new TokenController('core', $this->request, $this->userManager, $this->tokenProvider, $this->twoFactorAuthManager, $this->secureRandom); } @@ -77,7 +79,7 @@ class TokenControllerTest extends TestCase { } public function testWithValidCredentials() { - $user = $this->getMock('\OCP\IUser'); + $user = $this->getMockBuilder('\OCP\IUser')->getMock(); $this->userManager->expects($this->once()) ->method('checkPassword') ->with('john', '123456') @@ -96,9 +98,9 @@ class TokenControllerTest extends TestCase { $this->tokenProvider->expects($this->once()) ->method('generateToken') ->with('verysecurerandomtoken', 'john', 'john', '123456', 'unknown client', IToken::PERMANENT_TOKEN); - $expected = [ + $expected = new JSONResponse([ 'token' => 'verysecurerandomtoken' - ]; + ]); $actual = $this->tokenController->generateToken('john', '123456'); @@ -106,7 +108,7 @@ class TokenControllerTest extends TestCase { } public function testWithValidCredentialsBut2faEnabled() { - $user = $this->getMock('\OCP\IUser'); + $user = $this->getMockBuilder('\OCP\IUser')->getMock(); $this->userManager->expects($this->once()) ->method('checkPassword') ->with('john', '123456') diff --git a/tests/Core/Middleware/TwoFactorMiddlewareTest.php b/tests/Core/Middleware/TwoFactorMiddlewareTest.php index 6b8f4928928..8247efa1b82 100644 --- a/tests/Core/Middleware/TwoFactorMiddlewareTest.php +++ b/tests/Core/Middleware/TwoFactorMiddlewareTest.php @@ -132,6 +132,7 @@ class TwoFactorMiddlewareTest extends TestCase { ->will($this->returnValue(true)); $this->twoFactorManager->expects($this->once()) ->method('needsSecondFactor') + ->with($user) ->will($this->returnValue(true)); $this->middleware->beforeController(null, 'index'); @@ -159,6 +160,7 @@ class TwoFactorMiddlewareTest extends TestCase { ->will($this->returnValue(true)); $this->twoFactorManager->expects($this->once()) ->method('needsSecondFactor') + ->with($user) ->will($this->returnValue(false)); $twoFactorChallengeController = $this->getMockBuilder('\OC\Core\Controller\TwoFactorChallengeController') diff --git a/tests/Core/Templates/TemplatesTest.php b/tests/Core/Templates/TemplatesTest.php index 03565411a13..cd1502fd22c 100644 --- a/tests/Core/Templates/TemplatesTest.php +++ b/tests/Core/Templates/TemplatesTest.php @@ -13,7 +13,7 @@ class TemplatesTest extends \Test\TestCase { public function test404() { $template = \OC::$SERVERROOT . '/core/templates/404.php'; $href = \OC::$server->getURLGenerator()->linkTo('', 'index.php'); - $expectedHtml = "<ul><li class='error'>\n\t\t\tFile not found<br><p class='hint'>The specified document has not been found on the server.</p>\n<p class='hint'><a href='$href'>You can click here to return to ownCloud.</a></p>\n\t\t</li></ul>"; + $expectedHtml = "<ul><li class='error'>\n\t\t\tFile not found<br><p class='hint'>The specified document has not been found on the server.</p>\n<p class='hint'><a href='$href'>You can click here to return to Nextcloud.</a></p>\n\t\t</li></ul>"; $this->assertTemplate($expectedHtml, $template); } diff --git a/tests/Settings/Controller/AdminSettingsControllerTest.php b/tests/Settings/Controller/AdminSettingsControllerTest.php new file mode 100644 index 00000000000..6c93bca0d68 --- /dev/null +++ b/tests/Settings/Controller/AdminSettingsControllerTest.php @@ -0,0 +1,72 @@ +<?php +/** + * @copyright Copyright (c) 2016 Lukas Reschke <lukas@statuscode.ch> + * + * @author Lukas Reschke <lukas@statuscode.ch> + * + * @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\Settings\Controller; + + +use OC\Settings\Admin\TipsTricks; +use OC\Settings\Controller\AdminSettingsController; +use OCP\AppFramework\Http\TemplateResponse; +use OCP\INavigationManager; +use OCP\IRequest; +use OCP\Settings\IManager; +use Test\TestCase; + +class AdminSettingsControllerTest extends TestCase { + /** @var AdminSettingsController */ + private $adminSettingsController; + /** @var IRequest */ + private $request; + /** @var INavigationManager */ + private $navigationManager; + /** @var IManager */ + private $settingsManager; + + public function setUp() { + parent::setUp(); + + $this->request = $this->getMockBuilder('\OCP\IRequest')->getMock(); + $this->navigationManager = $this->getMockBuilder('\OCP\INavigationManager')->getMock(); + $this->settingsManager = $this->getMockBuilder('\OCP\Settings\IManager')->getMock(); + + $this->adminSettingsController = new AdminSettingsController( + 'settings', + $this->request, + $this->navigationManager, + $this->settingsManager + ); + } + + public function testIndex() { + $this->settingsManager + ->expects($this->once()) + ->method('getAdminSections') + ->willReturn([]); + $this->settingsManager + ->expects($this->once()) + ->method('getAdminSettings') + ->with('test') + ->willReturn([5 => new TipsTricks($this->getMockBuilder('\OCP\IConfig')->getMock())]); + $expected = new TemplateResponse('settings', 'admin/frame', ['forms' => [], 'content' => '']); + $this->assertEquals($expected, $this->adminSettingsController->index('test')); + } +} diff --git a/tests/Settings/Controller/AuthSettingsControllerTest.php b/tests/Settings/Controller/AuthSettingsControllerTest.php index 1705cb5ddf1..b57aea0930c 100644 --- a/tests/Settings/Controller/AuthSettingsControllerTest.php +++ b/tests/Settings/Controller/AuthSettingsControllerTest.php @@ -91,6 +91,7 @@ class AuthSettingsControllerTest extends TestCase { 'lastActivity' => null, 'type' => null, 'canDelete' => false, + 'current' => true, ], [ 'id' => 200, diff --git a/tests/Settings/Controller/CertificateControllerTest.php b/tests/Settings/Controller/CertificateControllerTest.php index c9ea2a4024f..36b5715e734 100644 --- a/tests/Settings/Controller/CertificateControllerTest.php +++ b/tests/Settings/Controller/CertificateControllerTest.php @@ -51,11 +51,11 @@ class CertificateControllerTest extends \Test\TestCase { public function setUp() { parent::setUp(); - $this->request = $this->getMock('\OCP\IRequest'); - $this->certificateManager = $this->getMock('\OCP\ICertificateManager'); - $this->systemCertificateManager = $this->getMock('\OCP\ICertificateManager'); - $this->l10n = $this->getMock('\OCP\IL10N'); - $this->appManager = $this->getMock('OCP\App\IAppManager'); + $this->request = $this->getMockBuilder('\OCP\IRequest')->getMock(); + $this->certificateManager = $this->getMockBuilder('\OCP\ICertificateManager')->getMock(); + $this->systemCertificateManager = $this->getMockBuilder('\OCP\ICertificateManager')->getMock(); + $this->l10n = $this->getMockBuilder('\OCP\IL10N')->getMock(); + $this->appManager = $this->getMockBuilder('OCP\App\IAppManager')->getMock(); $this->certificateController = $this->getMockBuilder('OC\Settings\Controller\CertificateController') ->setConstructorArgs( @@ -90,7 +90,7 @@ class CertificateControllerTest extends \Test\TestCase { 'name' => 'goodCertificate.crt', ]; - $certificate = $this->getMock('\OCP\ICertificate'); + $certificate = $this->getMockBuilder('\OCP\ICertificate')->getMock(); $certificate ->expects($this->once()) ->method('getName') diff --git a/tests/Settings/Controller/CheckSetupControllerTest.php b/tests/Settings/Controller/CheckSetupControllerTest.php index f48e9c04f3d..e4f66b5d879 100644 --- a/tests/Settings/Controller/CheckSetupControllerTest.php +++ b/tests/Settings/Controller/CheckSetupControllerTest.php @@ -29,6 +29,7 @@ use OCP\AppFramework\Http\RedirectResponse; use OCP\Http\Client\IClientService; use OCP\IConfig; use OCP\IL10N; +use OCP\ILogger; use OCP\IRequest; use OCP\IURLGenerator; use OC_Util; @@ -36,24 +37,11 @@ use Test\TestCase; use OC\IntegrityCheck\Checker; /** - * Mock version_compare - * @param string $version1 - * @param string $version2 - * @return int - */ -function version_compare($version1, $version2) { - return CheckSetupControllerTest::$version_compare; -} - -/** * Class CheckSetupControllerTest * * @package Tests\Settings\Controller */ class CheckSetupControllerTest extends TestCase { - /** @var int */ - public static $version_compare; - /** @var CheckSetupController */ private $checkSetupController; /** @var IRequest */ @@ -68,6 +56,8 @@ class CheckSetupControllerTest extends TestCase { private $util; /** @var IL10N */ private $l10n; + /** @var ILogger */ + private $logger; /** @var Checker */ private $checker; @@ -95,6 +85,7 @@ class CheckSetupControllerTest extends TestCase { })); $this->checker = $this->getMockBuilder('\OC\IntegrityCheck\Checker') ->disableOriginalConstructor()->getMock(); + $this->logger = $this->getMockBuilder('\OCP\ILogger')->getMock(); $this->checkSetupController = $this->getMockBuilder('\OC\Settings\Controller\CheckSetupController') ->setConstructorArgs([ 'settings', @@ -105,8 +96,9 @@ class CheckSetupControllerTest extends TestCase { $this->util, $this->l10n, $this->checker, + $this->logger ]) - ->setMethods(['getCurlVersion'])->getMock(); + ->setMethods(['getCurlVersion', 'isPhpOutdated'])->getMock(); } public function testIsInternetConnectionWorkingDisabledViaConfig() { @@ -131,12 +123,8 @@ class CheckSetupControllerTest extends TestCase { $client = $this->getMockBuilder('\OCP\Http\Client\IClient') ->disableOriginalConstructor()->getMock(); - $client->expects($this->at(0)) - ->method('get') - ->with('https://www.owncloud.org/', []); - $client->expects($this->at(1)) - ->method('get') - ->with('http://www.owncloud.org/', []); + $client->expects($this->any()) + ->method('get'); $this->clientService->expects($this->once()) ->method('newClient') @@ -151,7 +139,7 @@ class CheckSetupControllerTest extends TestCase { ); } - public function testIsInternetConnectionHttpsFail() { + public function testIsInternetConnectionFail() { $this->config->expects($this->once()) ->method('getSystemValue') ->with('has_internet_connection', true) @@ -159,12 +147,11 @@ class CheckSetupControllerTest extends TestCase { $client = $this->getMockBuilder('\OCP\Http\Client\IClient') ->disableOriginalConstructor()->getMock(); - $client->expects($this->at(0)) + $client->expects($this->any()) ->method('get') - ->with('https://www.owncloud.org/', []) ->will($this->throwException(new \Exception())); - $this->clientService->expects($this->once()) + $this->clientService->expects($this->exactly(3)) ->method('newClient') ->will($this->returnValue($client)); @@ -176,33 +163,6 @@ class CheckSetupControllerTest extends TestCase { ); } - public function testIsInternetConnectionHttpFail() { - $this->config->expects($this->once()) - ->method('getSystemValue') - ->with('has_internet_connection', true) - ->will($this->returnValue(true)); - - $client = $this->getMockBuilder('\OCP\Http\Client\IClient') - ->disableOriginalConstructor()->getMock(); - $client->expects($this->at(0)) - ->method('get') - ->with('https://www.owncloud.org/', []); - $client->expects($this->at(1)) - ->method('get') - ->with('http://www.owncloud.org/', []) - ->will($this->throwException(new \Exception())); - - $this->clientService->expects($this->once()) - ->method('newClient') - ->will($this->returnValue($client)); - - $this->assertFalse( - self::invokePrivate( - $this->checkSetupController, - 'isInternetConnectionWorking' - ) - ); - } public function testIsMemcacheConfiguredFalse() { $this->config->expects($this->once()) @@ -233,7 +193,10 @@ class CheckSetupControllerTest extends TestCase { } public function testIsPhpSupportedFalse() { - self::$version_compare = -1; + $this->checkSetupController + ->expects($this->once()) + ->method('isPhpOutdated') + ->willReturn(true); $this->assertEquals( ['eol' => true, 'version' => PHP_VERSION], @@ -242,7 +205,10 @@ class CheckSetupControllerTest extends TestCase { } public function testIsPhpSupportedTrue() { - self::$version_compare = 0; + $this->checkSetupController + ->expects($this->exactly(2)) + ->method('isPhpOutdated') + ->willReturn(false); $this->assertEquals( ['eol' => false, 'version' => PHP_VERSION], @@ -250,8 +216,6 @@ class CheckSetupControllerTest extends TestCase { ); - self::$version_compare = 1; - $this->assertEquals( ['eol' => false, 'version' => PHP_VERSION], self::invokePrivate($this->checkSetupController, 'isPhpSupported') @@ -318,13 +282,17 @@ class CheckSetupControllerTest extends TestCase { ->disableOriginalConstructor()->getMock(); $client->expects($this->at(0)) ->method('get') - ->with('https://www.owncloud.org/', []); + ->with('http://www.nextcloud.com/', []) + ->will($this->throwException(new \Exception())); $client->expects($this->at(1)) ->method('get') - ->with('http://www.owncloud.org/', []) + ->with('http://www.google.com/', []) ->will($this->throwException(new \Exception())); - - $this->clientService->expects($this->once()) + $client->expects($this->at(2)) + ->method('get') + ->with('http://www.github.com/', []) + ->will($this->throwException(new \Exception())); + $this->clientService->expects($this->exactly(3)) ->method('newClient') ->will($this->returnValue($client)); $this->urlGenerator->expects($this->at(0)) @@ -335,7 +303,10 @@ class CheckSetupControllerTest extends TestCase { ->method('linkToDocs') ->with('admin-security') ->willReturn('https://doc.owncloud.org/server/8.1/admin_manual/configuration_server/hardening.html'); - self::$version_compare = -1; + $this->checkSetupController + ->expects($this->once()) + ->method('isPhpOutdated') + ->willReturn(true); $this->urlGenerator->expects($this->at(2)) ->method('linkToDocs') ->with('admin-reverse-proxy') @@ -373,7 +344,8 @@ class CheckSetupControllerTest extends TestCase { $this->urlGenerator, $this->util, $this->l10n, - $this->checker + $this->checker, + $this->logger ]) ->setMethods(null)->getMock(); @@ -612,7 +584,7 @@ class CheckSetupControllerTest extends TestCase { $this->urlGenerator ->expects($this->once()) ->method('linkToRoute') - ->with('settings_admin') + ->with('settings.AdminSettings.index') ->will($this->returnValue('/admin')); $expected = new RedirectResponse('/admin'); diff --git a/tests/lib/App/DependencyAnalyzerTest.php b/tests/lib/App/DependencyAnalyzerTest.php index 3f410444f47..684a1b52259 100644 --- a/tests/lib/App/DependencyAnalyzerTest.php +++ b/tests/lib/App/DependencyAnalyzerTest.php @@ -16,7 +16,7 @@ use Test\TestCase; class DependencyAnalyzerTest extends TestCase { - /** @var Platform */ + /** @var Platform|\PHPUnit_Framework_MockObject_MockObject */ private $platformMock; /** @var IL10N */ @@ -206,6 +206,8 @@ class DependencyAnalyzerTest extends TestCase { array(array(), array('@attributes' => array('min-version' => '8.0.2', 'max-version' => '8.0.2'))), array(array('Server version 8.0.3 or higher is required.'), array('@attributes' => array('min-version' => '8.0.3'))), array(array('Server version 9 or higher is required.'), array('@attributes' => array('min-version' => '9'))), + array(array('Server version 10 or higher is required.'), array('@attributes' => array('min-version' => '9.1'))), + array(array('Server version 11 or higher is required.'), array('@attributes' => array('min-version' => '9.2'))), [['Server version 8.0.1 or lower is required.'], ['@attributes' => ['max-version' => '8.0.1']]], ); } diff --git a/tests/lib/AppFramework/AppTest.php b/tests/lib/AppFramework/AppTest.php index 7288e686d52..92ebd1f81e7 100644 --- a/tests/lib/AppFramework/AppTest.php +++ b/tests/lib/AppFramework/AppTest.php @@ -162,4 +162,55 @@ class AppTest extends \Test\TestCase { App::main($this->controllerName, $this->controllerMethod, $this->container, []); } + public function testCoreApp() { + $this->container['AppName'] = 'core'; + $this->container['OC\Core\Controller\Foo'] = $this->controller; + + $return = array(null, array(), array(), null, new Response()); + $this->dispatcher->expects($this->once()) + ->method('dispatch') + ->with($this->equalTo($this->controller), + $this->equalTo($this->controllerMethod)) + ->will($this->returnValue($return)); + + $this->io->expects($this->never()) + ->method('setOutput'); + + App::main('Foo', $this->controllerMethod, $this->container); + } + + public function testSettingsApp() { + $this->container['AppName'] = 'settings'; + $this->container['OC\Settings\Controller\Foo'] = $this->controller; + + $return = array(null, array(), array(), null, new Response()); + $this->dispatcher->expects($this->once()) + ->method('dispatch') + ->with($this->equalTo($this->controller), + $this->equalTo($this->controllerMethod)) + ->will($this->returnValue($return)); + + $this->io->expects($this->never()) + ->method('setOutput'); + + App::main('Foo', $this->controllerMethod, $this->container); + } + + public function testApp() { + $this->container['AppName'] = 'bar'; + $this->container['OCA\Bar\Controller\Foo'] = $this->controller; + + $return = array(null, array(), array(), null, new Response()); + $this->dispatcher->expects($this->once()) + ->method('dispatch') + ->with($this->equalTo($this->controller), + $this->equalTo($this->controllerMethod)) + ->will($this->returnValue($return)); + + $this->io->expects($this->never()) + ->method('setOutput'); + + App::main('Foo', $this->controllerMethod, $this->container); + } + } diff --git a/tests/lib/AppFramework/Controller/OCSControllerTest.php b/tests/lib/AppFramework/Controller/OCSControllerTest.php index 7dcbd189cd5..9c9214181a4 100644 --- a/tests/lib/AppFramework/Controller/OCSControllerTest.php +++ b/tests/lib/AppFramework/Controller/OCSControllerTest.php @@ -75,8 +75,8 @@ class OCSControllerTest extends \Test\TestCase { $expected = "<?xml version=\"1.0\"?>\n" . "<ocs>\n" . " <meta>\n" . - " <status>failure</status>\n" . - " <statuscode>400</statuscode>\n" . + " <status>ok</status>\n" . + " <statuscode>100</statuscode>\n" . " <message>OK</message>\n" . " <totalitems></totalitems>\n" . " <itemsperpage></itemsperpage>\n" . @@ -86,54 +86,12 @@ class OCSControllerTest extends \Test\TestCase { " </data>\n" . "</ocs>\n"; - $params = [ - 'data' => [ - 'test' => 'hi' - ], - 'statuscode' => 400 - ]; + $params = new DataResponse(['test' => 'hi']); $out = $controller->buildResponse($params, 'xml')->render(); $this->assertEquals($expected, $out); } - - public function testXMLDataResponse() { - $controller = new ChildOCSController('app', new Request( - [], - $this->getMockBuilder('\OCP\Security\ISecureRandom') - ->disableOriginalConstructor() - ->getMock(), - $this->getMockBuilder('\OCP\IConfig') - ->disableOriginalConstructor() - ->getMock() - )); - $expected = "<?xml version=\"1.0\"?>\n" . - "<ocs>\n" . - " <meta>\n" . - " <status>failure</status>\n" . - " <statuscode>400</statuscode>\n" . - " <message>OK</message>\n" . - " <totalitems></totalitems>\n" . - " <itemsperpage></itemsperpage>\n" . - " </meta>\n" . - " <data>\n" . - " <test>hi</test>\n" . - " </data>\n" . - "</ocs>\n"; - - $params = new DataResponse([ - 'data' => [ - 'test' => 'hi' - ], - 'statuscode' => 400 - ]); - - $out = $controller->buildResponse($params, 'xml')->render(); - $this->assertEquals($expected, $out); - } - - public function testJSON() { $controller = new ChildOCSController('app', new Request( [], @@ -144,14 +102,9 @@ class OCSControllerTest extends \Test\TestCase { ->disableOriginalConstructor() ->getMock() )); - $expected = '{"ocs":{"meta":{"status":"failure","statuscode":400,"message":"OK",' . + $expected = '{"ocs":{"meta":{"status":"ok","statuscode":100,"message":"OK",' . '"totalitems":"","itemsperpage":""},"data":{"test":"hi"}}}'; - $params = [ - 'data' => [ - 'test' => 'hi' - ], - 'statuscode' => 400 - ]; + $params = new DataResponse(['test' => 'hi']); $out = $controller->buildResponse($params, 'json')->render(); $this->assertEquals($expected, $out); diff --git a/tests/lib/AppFramework/Http/RequestTest.php b/tests/lib/AppFramework/Http/RequestTest.php index 8df81afeb3b..a3433e558d8 100644 --- a/tests/lib/AppFramework/Http/RequestTest.php +++ b/tests/lib/AppFramework/Http/RequestTest.php @@ -1063,22 +1063,6 @@ class RequestTest extends \Test\TestCase { $this->assertSame('www.owncloud.org', self::invokePrivate($request, 'getOverwriteHost')); } - public function testGetPathInfoWithSetEnv() { - $request = new Request( - [ - 'server' => [ - 'PATH_INFO' => 'apps/files/', - ] - ], - $this->secureRandom, - $this->config, - $this->csrfTokenManager, - $this->stream - ); - - $this->assertSame('apps/files/', $request->getPathInfo()); - } - /** * @expectedException \Exception * @expectedExceptionMessage The requested uri(/foo.php) cannot be processed by the script '/var/www/index.php') diff --git a/tests/lib/AppFramework/Middleware/OCSMiddlewareTest.php b/tests/lib/AppFramework/Middleware/OCSMiddlewareTest.php index 5eff056eebc..b2295fdc26d 100644 --- a/tests/lib/AppFramework/Middleware/OCSMiddlewareTest.php +++ b/tests/lib/AppFramework/Middleware/OCSMiddlewareTest.php @@ -27,14 +27,14 @@ use OCP\AppFramework\OCS\OCSBadRequestException; use OCP\AppFramework\OCS\OCSException; use OCP\AppFramework\OCS\OCSForbiddenException; use OCP\AppFramework\OCS\OCSNotFoundException; -use OC\AppFramework\Http\Request; +use OCP\IRequest; use OC\AppFramework\Middleware\OCSMiddleware; class OCSMiddlewareTest extends \Test\TestCase { /** - * @var Request + * @var IRequest */ private $request; @@ -101,8 +101,18 @@ class OCSMiddlewareTest extends \Test\TestCase { $this->assertInstanceOf('OCP\AppFramework\Http\OCSResponse', $result); $this->assertSame($message, $this->invokePrivate($result, 'message')); - $this->assertSame($code, $this->invokePrivate($result, 'statuscode')); - $this->assertSame(200, $result->getStatus()); + + if ($exception->getCode() === 0) { + $this->assertSame(\OCP\API::RESPOND_UNKNOWN_ERROR, $this->invokePrivate($result, 'statuscode')); + } else { + $this->assertSame($code, $this->invokePrivate($result, 'statuscode')); + } + + if ($exception instanceof OCSForbiddenException) { + $this->assertSame(Http::STATUS_UNAUTHORIZED, $result->getStatus()); + } else { + $this->assertSame(200, $result->getStatus()); + } } catch (\Exception $e) { $this->assertTrue($forward); $this->assertEquals($exception, $e); @@ -131,7 +141,45 @@ class OCSMiddlewareTest extends \Test\TestCase { $this->assertInstanceOf('OCP\AppFramework\Http\OCSResponse', $result); $this->assertSame($message, $this->invokePrivate($result, 'message')); - $this->assertSame($code, $this->invokePrivate($result, 'statuscode')); + if ($exception->getCode() === 0) { + $this->assertSame(\OCP\API::RESPOND_UNKNOWN_ERROR, $this->invokePrivate($result, 'statuscode')); + } else { + $this->assertSame($code, $this->invokePrivate($result, 'statuscode')); + } + $this->assertSame($code, $result->getStatus()); + } catch (\Exception $e) { + $this->assertTrue($forward); + $this->assertEquals($exception, $e); + } + } + + /** + * @dataProvider dataAfterException + * + * @param Controller $controller + * @param \Exception $exception + * @param bool $forward + * @param string $message + * @param int $code + */ + public function testAfterExceptionOCSv2SubFolder($controller, $exception, $forward, $message = '', $code = 0) { + $this->request + ->method('getScriptName') + ->willReturn('/mysubfolder/ocs/v2.php'); + $OCSMiddleware = new OCSMiddleware($this->request); + + try { + $result = $OCSMiddleware->afterException($controller, 'method', $exception); + $this->assertFalse($forward); + + $this->assertInstanceOf('OCP\AppFramework\Http\OCSResponse', $result); + + $this->assertSame($message, $this->invokePrivate($result, 'message')); + if ($exception->getCode() === 0) { + $this->assertSame(\OCP\API::RESPOND_UNKNOWN_ERROR, $this->invokePrivate($result, 'statuscode')); + } else { + $this->assertSame($code, $this->invokePrivate($result, 'statuscode')); + } $this->assertSame($code, $result->getStatus()); } catch (\Exception $e) { $this->assertTrue($forward); @@ -139,4 +187,50 @@ class OCSMiddlewareTest extends \Test\TestCase { } } + public function dataAfterController() { + $OCSController = $this->getMockBuilder('OCP\AppFramework\OCSController') + ->disableOriginalConstructor() + ->getMock(); + $controller = $this->getMockBuilder('OCP\AppFramework\Controller') + ->disableOriginalConstructor() + ->getMock(); + + return [ + [$OCSController, new Http\Response(), false], + [$OCSController, new Http\JSONResponse(), false], + [$OCSController, new Http\JSONResponse(['message' => 'foo']), false], + [$OCSController, new Http\JSONResponse(['message' => 'foo'], Http::STATUS_UNAUTHORIZED), true], + [$OCSController, new Http\JSONResponse(['message' => 'foo'], Http::STATUS_FORBIDDEN), true], + + [$controller, new Http\Response(), false], + [$controller, new Http\JSONResponse(), false], + [$controller, new Http\JSONResponse(['message' => 'foo']), false], + [$controller, new Http\JSONResponse(['message' => 'foo'], Http::STATUS_UNAUTHORIZED), false], + [$controller, new Http\JSONResponse(['message' => 'foo'], Http::STATUS_FORBIDDEN), false], + + ]; + } + + /** + * @dataProvider dataAfterController + * + * @param Controller $controller + * @param Http\Response $response + * @param bool $converted + */ + public function testAfterController($controller, $response, $converted) { + $OCSMiddleware = new OCSMiddleware($this->request); + $newResponse = $OCSMiddleware->afterController($controller, 'foo', $response); + + if ($converted === false) { + $this->assertSame($response, $newResponse); + } else { + $this->assertInstanceOf('\OCP\AppFramework\Http\OCSResponse', $newResponse); + /** @var Http\OCSResponse $newResponse */ + $this->assertSame($response->getData()['message'], $this->invokePrivate($newResponse, 'message')); + $this->assertSame(\OCP\API::RESPOND_UNAUTHORISED, $this->invokePrivate($newResponse, 'statuscode')); + $this->assertSame(Http::STATUS_UNAUTHORIZED, $newResponse->getStatus()); + } + } + } diff --git a/tests/lib/AppFramework/Middleware/Security/SecurityMiddlewareTest.php b/tests/lib/AppFramework/Middleware/Security/SecurityMiddlewareTest.php index 487b83c0bef..bfd810bc6b9 100644 --- a/tests/lib/AppFramework/Middleware/Security/SecurityMiddlewareTest.php +++ b/tests/lib/AppFramework/Middleware/Security/SecurityMiddlewareTest.php @@ -35,22 +35,38 @@ use OC\Appframework\Middleware\Security\Exceptions\StrictCookieMissingException; use OC\AppFramework\Middleware\Security\SecurityMiddleware; use OC\AppFramework\Utility\ControllerMethodReflector; use OC\Security\CSP\ContentSecurityPolicy; +use OC\Security\CSP\ContentSecurityPolicyManager; +use OCP\AppFramework\Controller; use OCP\AppFramework\Http\RedirectResponse; use OCP\AppFramework\Http\JSONResponse; use OCP\AppFramework\Http\TemplateResponse; +use OCP\ILogger; +use OCP\INavigationManager; +use OCP\IRequest; +use OCP\IURLGenerator; class SecurityMiddlewareTest extends \Test\TestCase { + /** @var SecurityMiddleware|\PHPUnit_Framework_MockObject_MockObject */ private $middleware; + /** @var Controller|\PHPUnit_Framework_MockObject_MockObject */ private $controller; + /** @var SecurityException */ private $secException; + /** @var SecurityException */ private $secAjaxException; + /** @var IRequest|\PHPUnit_Framework_MockObject_MockObject */ private $request; + /** @var ControllerMethodReflector */ private $reader; + /** @var ILogger|\PHPUnit_Framework_MockObject_MockObject */ private $logger; + /** @var INavigationManager|\PHPUnit_Framework_MockObject_MockObject */ private $navigationManager; + /** @var IURLGenerator|\PHPUnit_Framework_MockObject_MockObject */ private $urlGenerator; + /** @var ContentSecurityPolicyManager|\PHPUnit_Framework_MockObject_MockObject */ private $contentSecurityPolicyManager; protected function setUp() { @@ -354,6 +370,46 @@ class SecurityMiddlewareTest extends \Test\TestCase { $this->middleware->beforeController(__CLASS__, __FUNCTION__); } + public function dataCsrfOcsController() { + $controller = $this->getMockBuilder('OCP\AppFramework\Controller') + ->disableOriginalConstructor() + ->getMock(); + $ocsController = $this->getMockBuilder('OCP\AppFramework\OCSController') + ->disableOriginalConstructor() + ->getMock(); + + return [ + [$controller, false, true], + [$controller, true, true], + + [$ocsController, false, true], + [$ocsController, true, false], + ]; + } + + /** + * @dataProvider dataCsrfOcsController + * @param Controller $controller + * @param bool $hasOcsApiHeader + * @param bool $exception + */ + public function testCsrfOcsController(Controller $controller, $hasOcsApiHeader, $exception) { + $this->request + ->method('getHeader') + ->with('OCS-APIREQUEST') + ->willReturn($hasOcsApiHeader ? 'true' : null); + $this->request->expects($this->once()) + ->method('passesStrictCookieCheck') + ->willReturn(true); + + try { + $this->middleware->beforeController($controller, 'foo'); + $this->assertFalse($exception); + } catch (CrossSiteRequestForgeryException $e) { + $this->assertTrue($exception); + } + } + /** * @NoCSRFRequired * @NoAdminRequired diff --git a/tests/lib/AppFramework/Routing/RoutingTest.php b/tests/lib/AppFramework/Routing/RoutingTest.php index 6c8b0f40133..d395584d011 100644 --- a/tests/lib/AppFramework/Routing/RoutingTest.php +++ b/tests/lib/AppFramework/Routing/RoutingTest.php @@ -24,7 +24,7 @@ class RoutingTest extends \Test\TestCase ] ]; - $this->assertSimpleOCSRoute($routes, 'folders.open', 'GET', '/folders/{folderId}/open', 'FoldersController', 'open'); + $this->assertSimpleOCSRoute($routes, 'folders.open', 'GET', '/apps/app1/folders/{folderId}/open', 'FoldersController', 'open'); } public function testSimpleRouteWithMissingVerb() @@ -42,7 +42,7 @@ class RoutingTest extends \Test\TestCase ] ]; - $this->assertSimpleOCSRoute($routes, 'folders.open', 'GET', '/folders/{folderId}/open', 'FoldersController', 'open'); + $this->assertSimpleOCSRoute($routes, 'folders.open', 'GET', '/apps/app1/folders/{folderId}/open', 'FoldersController', 'open'); } public function testSimpleRouteWithLowercaseVerb() @@ -60,7 +60,7 @@ class RoutingTest extends \Test\TestCase ] ]; - $this->assertSimpleOCSRoute($routes, 'folders.open', 'DELETE', '/folders/{folderId}/open', 'FoldersController', 'open'); + $this->assertSimpleOCSRoute($routes, 'folders.open', 'DELETE', '/apps/app1/folders/{folderId}/open', 'FoldersController', 'open'); } public function testSimpleRouteWithRequirements() @@ -78,7 +78,7 @@ class RoutingTest extends \Test\TestCase ] ]; - $this->assertSimpleOCSRoute($routes, 'folders.open', 'DELETE', '/folders/{folderId}/open', 'FoldersController', 'open', ['something']); + $this->assertSimpleOCSRoute($routes, 'folders.open', 'DELETE', '/apps/app1/folders/{folderId}/open', 'FoldersController', 'open', ['something']); } public function testSimpleRouteWithDefaults() @@ -97,7 +97,7 @@ class RoutingTest extends \Test\TestCase ] ]; - $this->assertSimpleOCSRoute($routes, 'folders.open', 'DELETE', '/folders/{folderId}/open', 'FoldersController', 'open', [], ['param' => 'foobar']); + $this->assertSimpleOCSRoute($routes, 'folders.open', 'DELETE', '/apps/app1/folders/{folderId}/open', 'FoldersController', 'open', [], ['param' => 'foobar']); } public function testSimpleRouteWithPostfix() @@ -115,7 +115,7 @@ class RoutingTest extends \Test\TestCase ] ]; - $this->assertSimpleOCSRoute($routes, 'folders.open', 'DELETE', '/folders/{folderId}/open', 'FoldersController', 'open', [], [], '_something'); + $this->assertSimpleOCSRoute($routes, 'folders.open', 'DELETE', '/apps/app1/folders/{folderId}/open', 'FoldersController', 'open', [], [], '_something'); } /** @@ -175,7 +175,7 @@ class RoutingTest extends \Test\TestCase ['name' => 'admin_folders#open_current', 'url' => '/folders/{folderId}/open', 'verb' => 'delete'] ]]; - $this->assertSimpleOCSRoute($routes, 'admin_folders.open_current', 'DELETE', '/folders/{folderId}/open', 'AdminFoldersController', 'openCurrent'); + $this->assertSimpleOCSRoute($routes, 'admin_folders.open_current', 'DELETE', '/apps/app1/folders/{folderId}/open', 'AdminFoldersController', 'openCurrent'); } public function testResource() diff --git a/tests/lib/Authentication/TwoFactorAuth/ManagerTest.php b/tests/lib/Authentication/TwoFactorAuth/ManagerTest.php index 586fd3aaa2e..f9489150e21 100644 --- a/tests/lib/Authentication/TwoFactorAuth/ManagerTest.php +++ b/tests/lib/Authentication/TwoFactorAuth/ManagerTest.php @@ -72,6 +72,19 @@ class ManagerTest extends TestCase { }); } + private function prepareNoProviders() { + $this->appManager->expects($this->any()) + ->method('getEnabledAppsForUser') + ->with($this->user) + ->will($this->returnValue([])); + + $this->appManager->expects($this->never()) + ->method('getAppInfo'); + + $this->manager->expects($this->never()) + ->method('loadTwoFactorApp'); + } + private function prepareProviders() { $this->appManager->expects($this->any()) ->method('getEnabledAppsForUser') @@ -164,7 +177,7 @@ class ManagerTest extends TestCase { ->method('remove') ->with('two_factor_auth_uid'); - $this->assertEquals(true, $this->manager->verifyChallenge('email', $this->user, $challenge)); + $this->assertTrue($this->manager->verifyChallenge('email', $this->user, $challenge)); } public function testVerifyChallengeInvalidProviderId() { @@ -177,7 +190,7 @@ class ManagerTest extends TestCase { $this->session->expects($this->never()) ->method('remove'); - $this->assertEquals(false, $this->manager->verifyChallenge('dontexist', $this->user, $challenge)); + $this->assertFalse($this->manager->verifyChallenge('dontexist', $this->user, $challenge)); } public function testVerifyInvalidChallenge() { @@ -191,16 +204,40 @@ class ManagerTest extends TestCase { $this->session->expects($this->never()) ->method('remove'); - $this->assertEquals(false, $this->manager->verifyChallenge('email', $this->user, $challenge)); + $this->assertFalse($this->manager->verifyChallenge('email', $this->user, $challenge)); } public function testNeedsSecondFactor() { + $user = $this->getMock('\OCP\IUser'); $this->session->expects($this->once()) ->method('exists') ->with('two_factor_auth_uid') ->will($this->returnValue(false)); - $this->assertEquals(false, $this->manager->needsSecondFactor()); + $this->assertFalse($this->manager->needsSecondFactor($user)); + } + + public function testNeedsSecondFactorUserIsNull() { + $user = null; + $this->session->expects($this->never()) + ->method('exists'); + + $this->assertFalse($this->manager->needsSecondFactor($user)); + } + + public function testNeedsSecondFactorWithNoProviderAvailableAnymore() { + $this->prepareNoProviders(); + + $user = null; + $this->session->expects($this->never()) + ->method('exists') + ->with('two_factor_auth_uid') + ->will($this->returnValue(true)); + $this->session->expects($this->never()) + ->method('remove') + ->with('two_factor_auth_uid'); + + $this->assertFalse($this->manager->needsSecondFactor($user)); } public function testPrepareTwoFactorLogin() { diff --git a/tests/lib/Cache/CappedMemoryCacheTest.php b/tests/lib/Cache/CappedMemoryCacheTest.php index 27e5df4e265..243a1ad74f1 100644 --- a/tests/lib/Cache/CappedMemoryCacheTest.php +++ b/tests/lib/Cache/CappedMemoryCacheTest.php @@ -25,8 +25,6 @@ namespace Test\Cache; /** * Class CappedMemoryCacheTest * - * @group DB - * * @package Test\Cache */ class CappedMemoryCacheTest extends TestCache { diff --git a/tests/lib/CapabilitiesManagerTest.php b/tests/lib/CapabilitiesManagerTest.php index d4dd52d07f1..75fbdb8d89f 100644 --- a/tests/lib/CapabilitiesManagerTest.php +++ b/tests/lib/CapabilitiesManagerTest.php @@ -21,14 +21,29 @@ namespace Test; +use OC\CapabilitiesManager; +use OCP\AppFramework\QueryException; +use OCP\Capabilities\ICapability; +use OCP\ILogger; + class CapabilitiesManagerTest extends TestCase { + /** @var CapabilitiesManager */ + private $manager; + + /** @var ILogger */ + private $logger; + + public function setUp() { + $this->logger = $this->getMockBuilder('OCP\ILogger')->getMock(); + $this->manager = new CapabilitiesManager($this->logger); + } + /** * Test no capabilities */ public function testNoCapabilities() { - $manager = new \OC\CapabilitiesManager(); - $res = $manager->getCapabilities(); + $res = $this->manager->getCapabilities(); $this->assertEmpty($res); } @@ -36,13 +51,11 @@ class CapabilitiesManagerTest extends TestCase { * Test a valid capabilitie */ public function testValidCapability() { - $manager = new \OC\CapabilitiesManager(); - - $manager->registerCapability(function() { + $this->manager->registerCapability(function() { return new SimpleCapability(); }); - $res = $manager->getCapabilities(); + $res = $this->manager->getCapabilities(); $this->assertEquals(['foo' => 1], $res); } @@ -52,13 +65,11 @@ class CapabilitiesManagerTest extends TestCase { * @expectedExceptionMessage The given Capability (Test\NoCapability) does not implement the ICapability interface */ public function testNoICapability() { - $manager = new \OC\CapabilitiesManager(); - - $manager->registerCapability(function() { + $this->manager->registerCapability(function() { return new NoCapability(); }); - $res = $manager->getCapabilities(); + $res = $this->manager->getCapabilities(); $this->assertEquals([], $res); } @@ -66,19 +77,17 @@ class CapabilitiesManagerTest extends TestCase { * Test a bunch of merged Capabilities */ public function testMergedCapabilities() { - $manager = new \OC\CapabilitiesManager(); - - $manager->registerCapability(function() { + $this->manager->registerCapability(function() { return new SimpleCapability(); }); - $manager->registerCapability(function() { + $this->manager->registerCapability(function() { return new SimpleCapability2(); }); - $manager->registerCapability(function() { + $this->manager->registerCapability(function() { return new SimpleCapability3(); }); - $res = $manager->getCapabilities(); + $res = $this->manager->getCapabilities(); $expected = [ 'foo' => 1, 'bar' => [ @@ -94,16 +103,14 @@ class CapabilitiesManagerTest extends TestCase { * Test deep identical capabilities */ public function testDeepIdenticalCapabilities() { - $manager = new \OC\CapabilitiesManager(); - - $manager->registerCapability(function() { + $this->manager->registerCapability(function() { return new DeepCapability(); }); - $manager->registerCapability(function() { + $this->manager->registerCapability(function() { return new DeepCapability(); }); - $res = $manager->getCapabilities(); + $res = $this->manager->getCapabilities(); $expected = [ 'foo' => [ 'bar' => [ @@ -114,9 +121,22 @@ class CapabilitiesManagerTest extends TestCase { $this->assertEquals($expected, $res); } + + public function testInvalidCapability() { + $this->manager->registerCapability(function () { + throw new QueryException(); + }); + + $this->logger->expects($this->once()) + ->method('error'); + + $res = $this->manager->getCapabilities(); + + $this->assertEquals([], $res); + } } -class SimpleCapability implements \OCP\Capabilities\ICapability { +class SimpleCapability implements ICapability { public function getCapabilities() { return [ 'foo' => 1 @@ -124,7 +144,7 @@ class SimpleCapability implements \OCP\Capabilities\ICapability { } } -class SimpleCapability2 implements \OCP\Capabilities\ICapability { +class SimpleCapability2 implements ICapability { public function getCapabilities() { return [ 'bar' => ['x' => 1] @@ -132,7 +152,7 @@ class SimpleCapability2 implements \OCP\Capabilities\ICapability { } } -class SimpleCapability3 implements \OCP\Capabilities\ICapability { +class SimpleCapability3 implements ICapability { public function getCapabilities() { return [ 'bar' => ['y' => 2] @@ -148,7 +168,7 @@ class NoCapability { } } -class DeepCapability implements \OCP\Capabilities\ICapability { +class DeepCapability implements ICapability { public function getCapabilities() { return [ 'foo' => [ @@ -159,4 +179,3 @@ class DeepCapability implements \OCP\Capabilities\ICapability { ]; } } - diff --git a/tests/lib/Files/Cache/Wrapper/CacheJailTest.php b/tests/lib/Files/Cache/Wrapper/CacheJailTest.php index 6ef6716f721..e3043c50d57 100644 --- a/tests/lib/Files/Cache/Wrapper/CacheJailTest.php +++ b/tests/lib/Files/Cache/Wrapper/CacheJailTest.php @@ -63,8 +63,17 @@ class CacheJailTest extends CacheTest { } function testGetById() { - //not supported - $this->assertTrue(true); + $data1 = array('size' => 100, 'mtime' => 50, 'mimetype' => 'httpd/unix-directory'); + $id = $this->sourceCache->put('foo/bar', $data1); + + // path from jailed foo of foo/bar is bar + $path = $this->cache->getPathById($id); + $this->assertEquals('bar', $path); + + // path from jailed '' of foo/bar is foo/bar + $this->cache = new \OC\Files\Cache\Wrapper\CacheJail($this->sourceCache, ''); + $path = $this->cache->getPathById($id); + $this->assertEquals('foo/bar', $path); } function testGetIncomplete() { diff --git a/tests/lib/Files/EtagTest.php b/tests/lib/Files/EtagTest.php index d8e44000f9c..67ddd6ca514 100644 --- a/tests/lib/Files/EtagTest.php +++ b/tests/lib/Files/EtagTest.php @@ -34,8 +34,8 @@ class EtagTest extends \Test\TestCase { \OC_Hook::clear('OC_Filesystem', 'setup'); $application = new \OCA\Files_Sharing\AppInfo\Application(); $application->registerMountProviders(); - \OCP\Share::registerBackend('file', 'OC_Share_Backend_File'); - \OCP\Share::registerBackend('folder', 'OC_Share_Backend_Folder', 'file'); + \OCP\Share::registerBackend('file', 'OCA\Files_Sharing\ShareBackend\File'); + \OCP\Share::registerBackend('folder', 'OCA\Files_Sharing\ShareBackend\Folder', 'file'); $config = \OC::$server->getConfig(); $this->datadir = $config->getSystemValue('datadirectory'); diff --git a/tests/lib/Files/Mount/MountPointTest.php b/tests/lib/Files/Mount/MountPointTest.php index 392f10c7170..799f441a1ab 100644 --- a/tests/lib/Files/Mount/MountPointTest.php +++ b/tests/lib/Files/Mount/MountPointTest.php @@ -16,9 +16,9 @@ class MountPointTest extends \Test\TestCase { ->method('getId') ->will($this->returnValue(123)); - $loader = $this->getMock('\OCP\Files\Storage\IStorageFactory'); + $loader = $this->getMock('\OC\Files\Storage\StorageFactory'); $loader->expects($this->once()) - ->method('getInstance') + ->method('wrap') ->will($this->returnValue($storage)); $mountPoint = new \OC\Files\Mount\MountPoint( @@ -38,9 +38,9 @@ class MountPointTest extends \Test\TestCase { } public function testInvalidStorage() { - $loader = $this->getMock('\OCP\Files\Storage\IStorageFactory'); + $loader = $this->getMock('\OC\Files\Storage\StorageFactory'); $loader->expects($this->once()) - ->method('getInstance') + ->method('wrap') ->will($this->throwException(new \Exception('Test storage init exception'))); $called = false; diff --git a/tests/lib/L10N/FactoryTest.php b/tests/lib/L10N/FactoryTest.php index 98bb5ec13c9..bb72d84941c 100644 --- a/tests/lib/L10N/FactoryTest.php +++ b/tests/lib/L10N/FactoryTest.php @@ -15,7 +15,6 @@ use Test\TestCase; * Class FactoryTest * * @package Test\L10N - * @group DB */ class FactoryTest extends TestCase { @@ -44,7 +43,9 @@ class FactoryTest extends TestCase { ->disableOriginalConstructor() ->getMock(); - $this->userSession = $this->getMock('\OCP\IUserSession'); + $this->userSession = $this->getMockBuilder('\OCP\IUserSession') + ->disableOriginalConstructor() + ->getMock(); $this->serverRoot = \OC::$SERVERROOT; } @@ -110,7 +111,8 @@ class FactoryTest extends TestCase { ->method('getSystemValue') ->with('installed', false) ->willReturn(true); - $user = $this->getMock('\OCP\IUser'); + $user = $this->getMockBuilder('\OCP\IUser') + ->getMock(); $user->expects($this->once()) ->method('getUID') ->willReturn('MyUserUid'); @@ -143,7 +145,8 @@ class FactoryTest extends TestCase { ->method('getSystemValue') ->with('installed', false) ->willReturn(true); - $user = $this->getMock('\OCP\IUser'); + $user = $this->getMockBuilder('\OCP\IUser') + ->getMock(); $user->expects($this->once()) ->method('getUID') ->willReturn('MyUserUid'); @@ -185,7 +188,8 @@ class FactoryTest extends TestCase { ->method('getSystemValue') ->with('installed', false) ->willReturn(true); - $user = $this->getMock('\OCP\IUser'); + $user = $this->getMockBuilder('\OCP\IUser') + ->getMock(); $user->expects($this->once()) ->method('getUID') ->willReturn('MyUserUid'); @@ -230,7 +234,8 @@ class FactoryTest extends TestCase { ->method('getSystemValue') ->with('installed', false) ->willReturn(true); - $user = $this->getMock('\OCP\IUser'); + $user = $this->getMockBuilder('\OCP\IUser') + ->getMock(); $user->expects($this->once()) ->method('getUID') ->willReturn('MyUserUid'); diff --git a/tests/lib/L10N/L10nLegacyTest.php b/tests/lib/L10N/L10nLegacyTest.php index 1df22ba36bd..71b4e21f1a1 100644 --- a/tests/lib/L10N/L10nLegacyTest.php +++ b/tests/lib/L10N/L10nLegacyTest.php @@ -14,7 +14,6 @@ use DateTime; /** * Class Test_L10n - * @group DB */ class L10nLegacyTest extends \Test\TestCase { @@ -124,7 +123,11 @@ class L10nLegacyTest extends \Test\TestCase { } public function testFactoryGetLanguageCode() { - $factory = new \OC\L10N\Factory($this->getMock('OCP\IConfig'), $this->getMock('OCP\IRequest'), $this->getMock('OCP\IUserSession'), \OC::$SERVERROOT); + $factory = new \OC\L10N\Factory( + $this->getMockBuilder('OCP\IConfig')->getMock(), + $this->getMockBuilder('OCP\IRequest')->getMock(), + $this->getMockBuilder('OCP\IUserSession')->getMock(), + \OC::$SERVERROOT); $l = $factory->get('lib', 'de'); $this->assertEquals('de', $l->getLanguageCode()); } diff --git a/tests/lib/LoggerTest.php b/tests/lib/LoggerTest.php index 4b80c01f343..abb9deebd55 100644 --- a/tests/lib/LoggerTest.php +++ b/tests/lib/LoggerTest.php @@ -122,4 +122,20 @@ class LoggerTest extends TestCase { $this->assertContains('validateUserPass(*** sensitive parameters replaced ***)', $logLine); } } + + /** + * @dataProvider userAndPasswordData + */ + public function testDetecttryLogin($user, $password) { + $e = new \Exception('test'); + $this->logger->logException($e); + $logLines = $this->getLogs(); + + foreach($logLines as $logLine) { + $this->assertNotContains($user, $logLine); + $this->assertNotContains($password, $logLine); + $this->assertContains('tryLogin(*** sensitive parameters replaced ***)', $logLine); + } + } + } diff --git a/tests/lib/Notification/NotificationTest.php b/tests/lib/Notification/NotificationTest.php index c6ededf0142..93d48dfd604 100644 --- a/tests/lib/Notification/NotificationTest.php +++ b/tests/lib/Notification/NotificationTest.php @@ -495,6 +495,35 @@ class NotificationTest extends TestCase { $this->notification->addParsedAction($action); } + public function testAddActionParsedPrimaryEnd() { + /** @var \OCP\Notification\IAction|\PHPUnit_Framework_MockObject_MockObject $action */ + $action1 = $this->getMockBuilder('OCP\Notification\IAction') + ->disableOriginalConstructor() + ->getMock(); + $action1->expects($this->exactly(2)) + ->method('isValidParsed') + ->willReturn(true); + $action1->expects($this->exactly(2)) + ->method('isPrimary') + ->willReturn(false); + /** @var \OCP\Notification\IAction|\PHPUnit_Framework_MockObject_MockObject $action */ + $action2 = $this->getMockBuilder('OCP\Notification\IAction') + ->disableOriginalConstructor() + ->getMock(); + $action2->expects($this->once()) + ->method('isValidParsed') + ->willReturn(true); + $action2->expects($this->once()) + ->method('isPrimary') + ->willReturn(true); + + $this->assertSame($this->notification, $this->notification->addParsedAction($action1)); + $this->assertSame($this->notification, $this->notification->addParsedAction($action2)); + $this->assertSame($this->notification, $this->notification->addParsedAction($action1)); + + $this->assertEquals([$action2, $action1, $action1], $this->notification->getParsedActions()); + } + public function dataIsValid() { return [ [false, '', false], diff --git a/tests/lib/Repair/RepairLegacyStoragesTest.php b/tests/lib/Repair/RepairLegacyStoragesTest.php index aa51fe06a35..8d8366dde06 100644 --- a/tests/lib/Repair/RepairLegacyStoragesTest.php +++ b/tests/lib/Repair/RepairLegacyStoragesTest.php @@ -98,23 +98,9 @@ class RepairLegacyStoragesTest extends TestCase { $storageId = Storage::adjustStorageId($storageId); $numRows = $this->connection->executeUpdate($sql, array($storageId)); - $this->assertEquals(1, $numRows); + $this->assertSame(1, $numRows); - return \OC::$server->getDatabaseConnection()->lastInsertId('*PREFIX*storages'); - } - - /** - * Returns the storage id based on the numeric id - * - * @param int $storageId numeric id of the storage - * @return string storage id or null if not found - */ - private function getStorageId($storageId) { - $numericId = Storage::getNumericStorageId($storageId); - if (!is_null($numericId)) { - return (int)$numericId; - } - return null; + return (int)\OC::$server->getDatabaseConnection()->lastInsertId('*PREFIX*storages'); } /** @@ -144,8 +130,8 @@ class RepairLegacyStoragesTest extends TestCase { $this->repair->run($this->outputMock); - $this->assertNull($this->getStorageId($this->legacyStorageId)); - $this->assertEquals($newStorageNumId, $this->getStorageId($this->newStorageId)); + $this->assertNull(Storage::getNumericStorageId($this->legacyStorageId)); + $this->assertSame($newStorageNumId, Storage::getNumericStorageId($this->newStorageId)); } /** @@ -163,8 +149,8 @@ class RepairLegacyStoragesTest extends TestCase { $this->repair->run($this->outputMock); - $this->assertNull($this->getStorageId($this->legacyStorageId)); - $this->assertEquals($legacyStorageNumId, $this->getStorageId($this->newStorageId)); + $this->assertNull(Storage::getNumericStorageId($this->legacyStorageId)); + $this->assertSame($legacyStorageNumId, Storage::getNumericStorageId($this->newStorageId)); } /** @@ -185,8 +171,8 @@ class RepairLegacyStoragesTest extends TestCase { $this->repair->run($this->outputMock); - $this->assertNull($this->getStorageId($this->legacyStorageId)); - $this->assertEquals($legacyStorageNumId, $this->getStorageId($this->newStorageId)); + $this->assertNull(Storage::getNumericStorageId($this->legacyStorageId)); + $this->assertSame($legacyStorageNumId, Storage::getNumericStorageId($this->newStorageId)); } /** @@ -208,8 +194,8 @@ class RepairLegacyStoragesTest extends TestCase { $this->repair->run($this->outputMock); - $this->assertNull($this->getStorageId($this->legacyStorageId)); - $this->assertEquals($newStorageNumId, $this->getStorageId($this->newStorageId)); + $this->assertNull(Storage::getNumericStorageId($this->legacyStorageId)); + $this->assertSame($newStorageNumId, Storage::getNumericStorageId($this->newStorageId)); } /** @@ -233,8 +219,8 @@ class RepairLegacyStoragesTest extends TestCase { $this->repair->run($this->outputMock); // storages left alone - $this->assertEquals($legacyStorageNumId, $this->getStorageId($this->legacyStorageId)); - $this->assertEquals($newStorageNumId, $this->getStorageId($this->newStorageId)); + $this->assertSame($legacyStorageNumId, Storage::getNumericStorageId($this->legacyStorageId)); + $this->assertSame($newStorageNumId, Storage::getNumericStorageId($this->newStorageId)); // do not set the done flag $this->assertNotEquals('yes', $this->config->getAppValue('core', 'repairlegacystoragesdone')); @@ -255,7 +241,7 @@ class RepairLegacyStoragesTest extends TestCase { $this->repair->run($this->outputMock); - $this->assertEquals($numId, $this->getStorageId($storageId)); + $this->assertSame($numId, Storage::getNumericStorageId($storageId)); } /** @@ -273,7 +259,7 @@ class RepairLegacyStoragesTest extends TestCase { $this->repair->run($this->outputMock); - $this->assertEquals($numId, $this->getStorageId($storageId)); + $this->assertSame($numId, Storage::getNumericStorageId($storageId)); } /** @@ -291,7 +277,7 @@ class RepairLegacyStoragesTest extends TestCase { $this->repair->run($this->outputMock); - $this->assertEquals($numId, $this->getStorageId($storageId)); + $this->assertSame($numId, Storage::getNumericStorageId($storageId)); } /** diff --git a/tests/lib/Repair/RepairUnmergedSharesTest.php b/tests/lib/Repair/RepairUnmergedSharesTest.php new file mode 100644 index 00000000000..7b9d2579389 --- /dev/null +++ b/tests/lib/Repair/RepairUnmergedSharesTest.php @@ -0,0 +1,574 @@ +<?php +/** + * @author Vincent Petry <pvince81@owncloud.com> + * + * @copyright Copyright (c) 2016, 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\Repair; + + +use OC\Repair\RepairUnmergedShares; +use OC\Share\Constants; +use OCP\Migration\IOutput; +use OCP\Migration\IRepairStep; +use Test\TestCase; +use OC\Share20\DefaultShareProvider; +use OCP\IUserManager; +use OCP\IGroupManager; + +/** + * Tests for repairing invalid shares + * + * @group DB + * + * @see \OC\Repair\RepairUnmergedShares + */ +class RepairUnmergedSharesTest extends TestCase { + + /** @var IRepairStep */ + private $repair; + + /** @var \OCP\IDBConnection */ + private $connection; + + /** @var int */ + private $lastShareTime; + + /** @var IUserManager */ + private $userManager; + + /** @var IGroupManager */ + private $groupManager; + + protected function setUp() { + parent::setUp(); + + $config = $this->getMockBuilder('OCP\IConfig') + ->disableOriginalConstructor() + ->getMock(); + $config->expects($this->any()) + ->method('getSystemValue') + ->with('version') + ->will($this->returnValue('9.0.3.0')); + + $this->connection = \OC::$server->getDatabaseConnection(); + $this->deleteAllShares(); + + $this->userManager = $this->getMock('\OCP\IUserManager'); + $this->groupManager = $this->getMock('\OCP\IGroupManager'); + + // used to generate incremental stimes + $this->lastShareTime = time(); + + /** @var \OCP\IConfig $config */ + $this->repair = new RepairUnmergedShares($config, $this->connection, $this->userManager, $this->groupManager); + } + + protected function tearDown() { + $this->deleteAllShares(); + + parent::tearDown(); + } + + protected function deleteAllShares() { + $qb = $this->connection->getQueryBuilder(); + $qb->delete('share')->execute(); + } + + private function createShare($type, $sourceId, $recipient, $targetName, $permissions, $parentId = null) { + $this->lastShareTime += 100; + $qb = $this->connection->getQueryBuilder(); + $values = [ + 'share_type' => $qb->expr()->literal($type), + 'share_with' => $qb->expr()->literal($recipient), + 'uid_owner' => $qb->expr()->literal('user1'), + 'item_type' => $qb->expr()->literal('folder'), + 'item_source' => $qb->expr()->literal($sourceId), + 'item_target' => $qb->expr()->literal('/' . $sourceId), + 'file_source' => $qb->expr()->literal($sourceId), + 'file_target' => $qb->expr()->literal($targetName), + 'permissions' => $qb->expr()->literal($permissions), + 'stime' => $qb->expr()->literal($this->lastShareTime), + ]; + if ($parentId !== null) { + $values['parent'] = $qb->expr()->literal($parentId); + } + $qb->insert('share') + ->values($values) + ->execute(); + + return $this->connection->lastInsertId('*PREFIX*share'); + } + + private function getShareById($id) { + $query = $this->connection->getQueryBuilder(); + $results = $query + ->select('*') + ->from('share') + ->where($query->expr()->eq('id', $query->expr()->literal($id))) + ->execute() + ->fetchAll(); + + if (!empty($results)) { + return $results[0]; + } + return null; + } + + public function sharesDataProvider() { + /** + * For all these test cases we have the following situation: + * + * - "user1" is the share owner + * - "user2" is the recipient, and member of "recipientgroup1" and "recipientgroup2" + * - "user1" is member of "samegroup1", "samegroup2" for same group tests + */ + return [ + [ + // #0 legitimate share: + // - outsider shares with group1, group2 + // - recipient renamed, resulting in subshares + // - one subshare for each group share + // - targets of subshare all match + [ + [Constants::SHARE_TYPE_GROUP, 123, 'recipientgroup1', '/test', 31], + [Constants::SHARE_TYPE_GROUP, 123, 'recipientgroup2', '/test', 31], + // child of the previous ones + [DefaultShareProvider::SHARE_TYPE_USERGROUP, 123, 'user2', '/test renamed', 31, 0], + // child of the previous ones + [DefaultShareProvider::SHARE_TYPE_USERGROUP, 123, 'user2', '/test renamed', 31, 1], + // different unrelated share + [Constants::SHARE_TYPE_GROUP, 456, 'recipientgroup1', '/test (4)', 31], + ], + [ + ['/test', 31], + ['/test', 31], + // leave them alone + ['/test renamed', 31], + ['/test renamed', 31], + // leave unrelated alone + ['/test (4)', 31], + ] + ], + [ + // #1 broken share: + // - outsider shares with group1, group2 + // - only one subshare for two group shares + [ + [Constants::SHARE_TYPE_GROUP, 123, 'recipientgroup1', '/test', 31], + [Constants::SHARE_TYPE_GROUP, 123, 'recipientgroup2', '/test', 31], + // child of the previous one + [DefaultShareProvider::SHARE_TYPE_USERGROUP, 123, 'user2', '/test (2)', 31, 1], + // different unrelated share + [Constants::SHARE_TYPE_GROUP, 456, 'recipientgroup1', '/test (4)', 31], + ], + [ + ['/test', 31], + ['/test', 31], + ['/test', 31], + // leave unrelated alone + ['/test (4)', 31], + ] + ], + [ + // #2 bogus share + // - outsider shares with group1, group2 + // - one subshare for each group share, both with parenthesis + // - but the targets do not match when grouped + [ + [Constants::SHARE_TYPE_GROUP, 123, 'recipientgroup1', '/test', 31], + [Constants::SHARE_TYPE_GROUP, 123, 'recipientgroup2', '/test', 31], + // child of the previous ones + [DefaultShareProvider::SHARE_TYPE_USERGROUP, 123, 'user2', '/test (2)', 31, 0], + [DefaultShareProvider::SHARE_TYPE_USERGROUP, 123, 'user2', '/test (3)', 31, 1], + // different unrelated share + [Constants::SHARE_TYPE_GROUP, 456, 'recipientgroup1', '/test (4)', 31], + ], + [ + ['/test', 31], + ['/test', 31], + // reset to original name as the sub-names have parenthesis + ['/test', 31], + ['/test', 31], + // leave unrelated alone + ['/test (4)', 31], + ] + ], + [ + // #3 bogus share + // - outsider shares with group1, group2 + // - one subshare for each group share, both renamed manually + // - but the targets do not match when grouped + [ + [Constants::SHARE_TYPE_GROUP, 123, 'recipientgroup1', '/test', 31], + [Constants::SHARE_TYPE_GROUP, 123, 'recipientgroup2', '/test', 31], + // child of the previous ones + [DefaultShareProvider::SHARE_TYPE_USERGROUP, 123, 'user2', '/test_renamed (1 legit paren)', 31, 0], + [DefaultShareProvider::SHARE_TYPE_USERGROUP, 123, 'user2', '/test_renamed (2 legit paren)', 31, 1], + // different unrelated share + [Constants::SHARE_TYPE_GROUP, 456, 'recipientgroup1', '/test (4)', 31], + ], + [ + ['/test', 31], + ['/test', 31], + // reset to less recent subshare name + ['/test_renamed (2 legit paren)', 31], + ['/test_renamed (2 legit paren)', 31], + // leave unrelated alone + ['/test (4)', 31], + ] + ], + [ + // #4 bogus share + // - outsider shares with group1, group2 + // - one subshare for each group share, one with parenthesis + // - but the targets do not match when grouped + [ + [Constants::SHARE_TYPE_GROUP, 123, 'recipientgroup1', '/test', 31], + [Constants::SHARE_TYPE_GROUP, 123, 'recipientgroup2', '/test', 31], + // child of the previous ones + [DefaultShareProvider::SHARE_TYPE_USERGROUP, 123, 'user2', '/test (2)', 31, 0], + [DefaultShareProvider::SHARE_TYPE_USERGROUP, 123, 'user2', '/test_renamed', 31, 1], + // different unrelated share + [Constants::SHARE_TYPE_GROUP, 456, 'recipientgroup1', '/test (4)', 31], + ], + [ + ['/test', 31], + ['/test', 31], + // reset to less recent subshare name but without parenthesis + ['/test_renamed', 31], + ['/test_renamed', 31], + // leave unrelated alone + ['/test (4)', 31], + ] + ], + [ + // #5 bogus share + // - outsider shares with group1, group2 + // - one subshare for each group share + // - first subshare not renamed (as in real world scenario) + // - but the targets do not match when grouped + [ + [Constants::SHARE_TYPE_GROUP, 123, 'recipientgroup1', '/test', 31], + [Constants::SHARE_TYPE_GROUP, 123, 'recipientgroup2', '/test', 31], + // child of the previous ones + [DefaultShareProvider::SHARE_TYPE_USERGROUP, 123, 'user2', '/test', 31, 0], + [DefaultShareProvider::SHARE_TYPE_USERGROUP, 123, 'user2', '/test (2)', 31, 1], + // different unrelated share + [Constants::SHARE_TYPE_GROUP, 456, 'recipientgroup1', '/test (4)', 31], + ], + [ + ['/test', 31], + ['/test', 31], + // reset to original name + ['/test', 31], + ['/test', 31], + // leave unrelated alone + ['/test (4)', 31], + ] + ], + [ + // #6 bogus share: + // - outsider shares with group1, group2 + // - one subshare for each group share + // - non-matching targets + // - recipient deletes one duplicate (unshare from self, permissions 0) + [ + [Constants::SHARE_TYPE_GROUP, 123, 'recipientgroup1', '/test', 31], + [Constants::SHARE_TYPE_GROUP, 123, 'recipientgroup2', '/test', 15], + // child of the previous ones + [DefaultShareProvider::SHARE_TYPE_USERGROUP, 123, 'user2', '/test (2)', 0, 0], + [DefaultShareProvider::SHARE_TYPE_USERGROUP, 123, 'user2', '/test (3)', 15, 1], + // different unrelated share + [Constants::SHARE_TYPE_GROUP, 456, 'recipientgroup1', '/test (4)', 31], + ], + [ + ['/test', 31], + ['/test', 15], + // subshares repaired and permissions restored to the max allowed + ['/test', 31], + ['/test', 15], + // leave unrelated alone + ['/test (4)', 31], + ] + ], + [ + // #7 bogus share: + // - outsider shares with group1, group2 + // - one subshare for each group share + // - non-matching targets + // - recipient deletes ALL duplicates (unshare from self, permissions 0) + [ + [Constants::SHARE_TYPE_GROUP, 123, 'recipientgroup1', '/test', 31], + [Constants::SHARE_TYPE_GROUP, 123, 'recipientgroup2', '/test', 15], + // child of the previous ones + [DefaultShareProvider::SHARE_TYPE_USERGROUP, 123, 'user2', '/test (2)', 0, 0], + [DefaultShareProvider::SHARE_TYPE_USERGROUP, 123, 'user2', '/test (3)', 0, 1], + // different unrelated share + [Constants::SHARE_TYPE_GROUP, 456, 'recipientgroup1', '/test (4)', 31], + ], + [ + ['/test', 31], + ['/test', 15], + // subshares target repaired but left "deleted" as it was the user's choice + ['/test', 0], + ['/test', 0], + // leave unrelated alone + ['/test (4)', 31], + ] + ], + [ + // #8 bogus share: + // - outsider shares with group1, group2 and also user2 + // - one subshare for each group share + // - one extra share entry for direct share to user2 + // - non-matching targets + // - user share has more permissions + [ + [Constants::SHARE_TYPE_GROUP, 123, 'recipientgroup1', '/test', 1], + [Constants::SHARE_TYPE_GROUP, 123, 'recipientgroup2', '/test', 15], + // child of the previous ones + [DefaultShareProvider::SHARE_TYPE_USERGROUP, 123, 'user2', '/test (2)', 1, 0], + [DefaultShareProvider::SHARE_TYPE_USERGROUP, 123, 'user2', '/test (3)', 15, 1], + [Constants::SHARE_TYPE_USER, 123, 'user2', '/test (4)', 31], + // different unrelated share + [Constants::SHARE_TYPE_GROUP, 456, 'recipientgroup1', '/test (5)', 31], + ], + [ + ['/test', 1], + ['/test', 15], + // subshares repaired + ['/test', 1], + ['/test', 15], + ['/test', 31], + // leave unrelated alone + ['/test (5)', 31], + ] + ], + [ + // #9 bogus share: + // - outsider shares with group1 and also user2 + // - no subshare at all + // - one extra share entry for direct share to user2 + // - non-matching targets + // - user share has more permissions + [ + [Constants::SHARE_TYPE_GROUP, 123, 'recipientgroup1', '/test', 1], + [Constants::SHARE_TYPE_USER, 123, 'user2', '/test (2)', 31], + // different unrelated share + [Constants::SHARE_TYPE_GROUP, 456, 'recipientgroup1', '/test (5)', 31], + ], + [ + ['/test', 1], + // user share repaired + ['/test', 31], + // leave unrelated alone + ['/test (5)', 31], + ] + ], + [ + // #10 legitimate share with own group: + // - insider shares with both groups the user is already in + // - no subshares in this case + [ + [Constants::SHARE_TYPE_GROUP, 123, 'samegroup1', '/test', 31], + [Constants::SHARE_TYPE_GROUP, 123, 'samegroup2', '/test', 31], + // different unrelated share + [Constants::SHARE_TYPE_GROUP, 456, 'recipientgroup1', '/test (4)', 31], + ], + [ + // leave all alone + ['/test', 31], + ['/test', 31], + // leave unrelated alone + ['/test (4)', 31], + ] + ], + [ + // #11 legitimate shares: + // - group share with same group + // - group share with other group + // - user share where recipient renamed + // - user share where recipient did not rename + [ + [Constants::SHARE_TYPE_GROUP, 123, 'samegroup1', '/test', 31], + [Constants::SHARE_TYPE_GROUP, 123, 'recipientgroup1', '/test', 31], + [Constants::SHARE_TYPE_USER, 123, 'user3', '/test legit rename', 31], + [Constants::SHARE_TYPE_USER, 123, 'user4', '/test', 31], + // different unrelated share + [Constants::SHARE_TYPE_GROUP, 456, 'recipientgroup1', '/test (4)', 31], + ], + [ + // leave all alone + ['/test', 31], + ['/test', 31], + ['/test legit rename', 31], + ['/test', 31], + // leave unrelated alone + ['/test (4)', 31], + ] + ], + [ + // #12 legitimate share: + // - outsider shares with group and user directly with different permissions + // - no subshares + // - same targets + [ + [Constants::SHARE_TYPE_GROUP, 123, 'samegroup1', '/test', 1], + [Constants::SHARE_TYPE_USER, 123, 'user3', '/test', 31], + // different unrelated share + [Constants::SHARE_TYPE_GROUP, 456, 'recipientgroup1', '/test (4)', 31], + ], + [ + // leave all alone + ['/test', 1], + ['/test', 31], + // leave unrelated alone + ['/test (4)', 31], + ] + ], + [ + // #13 bogus share: + // - outsider shares with group1, user2 and then group2 + // - user renamed share as soon as it arrived before the next share (order) + // - one subshare for each group share + // - one extra share entry for direct share to user2 + // - non-matching targets + [ + // first share with group + [Constants::SHARE_TYPE_GROUP, 123, 'recipientgroup1', '/test', 31], + // recipient renames + [DefaultShareProvider::SHARE_TYPE_USERGROUP, 123, 'user2', '/first', 31, 0], + // then direct share, user renames too + [Constants::SHARE_TYPE_USER, 123, 'user2', '/second', 31], + // another share with the second group + [Constants::SHARE_TYPE_GROUP, 123, 'recipientgroup2', '/test', 31], + // use renames it + [DefaultShareProvider::SHARE_TYPE_USERGROUP, 123, 'user2', '/third', 31, 1], + // different unrelated share + [Constants::SHARE_TYPE_GROUP, 456, 'recipientgroup1', '/test (5)', 31], + ], + [ + // group share with group1 left alone + ['/test', 31], + // first subshare repaired + ['/third', 31], + // direct user share repaired + ['/third', 31], + // group share with group2 left alone + ['/test', 31], + // second subshare repaired + ['/third', 31], + // leave unrelated alone + ['/test (5)', 31], + ] + ], + ]; + } + + /** + * Test merge shares from group shares + * + * @dataProvider sharesDataProvider + */ + public function testMergeGroupShares($shares, $expectedShares) { + $user1 = $this->getMock('\OCP\IUser'); + $user1->expects($this->any()) + ->method('getUID') + ->will($this->returnValue('user1')); + + $user2 = $this->getMock('\OCP\IUser'); + $user2->expects($this->any()) + ->method('getUID') + ->will($this->returnValue('user2')); + + $users = [$user1, $user2]; + + $this->groupManager->expects($this->any()) + ->method('getUserGroupIds') + ->will($this->returnValueMap([ + // owner + [$user1, ['samegroup1', 'samegroup2']], + // recipient + [$user2, ['recipientgroup1', 'recipientgroup2']], + ])); + + $this->userManager->expects($this->once()) + ->method('countUsers') + ->will($this->returnValue([2])); + $this->userManager->expects($this->once()) + ->method('callForAllUsers') + ->will($this->returnCallback(function(\Closure $closure) use ($users) { + foreach ($users as $user) { + $closure($user); + } + })); + + $shareIds = []; + + foreach ($shares as $share) { + // if parent + if (isset($share[5])) { + // adjust to real id + $share[5] = $shareIds[$share[5]]; + } else { + $share[5] = null; + } + $shareIds[] = $this->createShare($share[0], $share[1], $share[2], $share[3], $share[4], $share[5]); + } + + /** @var IOutput | \PHPUnit_Framework_MockObject_MockObject $outputMock */ + $outputMock = $this->getMockBuilder('\OCP\Migration\IOutput') + ->disableOriginalConstructor() + ->getMock(); + + $this->repair->run($outputMock); + + foreach ($expectedShares as $index => $expectedShare) { + $share = $this->getShareById($shareIds[$index]); + $this->assertEquals($expectedShare[0], $share['file_target']); + $this->assertEquals($expectedShare[1], $share['permissions']); + } + } + + public function duplicateNamesProvider() { + return [ + // matching + ['filename (1).txt', true], + ['folder (2)', true], + ['filename (1)(2).txt', true], + // non-matching + ['filename ().txt', false], + ['folder ()', false], + ['folder (1x)', false], + ['folder (x1)', false], + ['filename (a)', false], + ['filename (1).', false], + ['filename (1).txt.txt', false], + ['filename (1)..txt', false], + ]; + } + + /** + * @dataProvider duplicateNamesProvider + */ + public function testIsPotentialDuplicateName($name, $expectedResult) { + $this->assertEquals($expectedResult, $this->invokePrivate($this->repair, 'isPotentialDuplicateName', [$name])); + } +} + diff --git a/tests/lib/ServerTest.php b/tests/lib/ServerTest.php index 534f3f8cfd5..2e5900c4ce5 100644 --- a/tests/lib/ServerTest.php +++ b/tests/lib/ServerTest.php @@ -158,6 +158,7 @@ class ServerTest extends \Test\TestCase { ['TagManager', '\OCP\ITagManager'], ['TempManager', '\OC\TempManager'], ['TempManager', '\OCP\ITempManager'], + ['ThemingDefaults', '\OCA\Theming\ThemingDefaults'], ['TrustedDomainHelper', '\OC\Security\TrustedDomainHelper'], ['SystemTagManager', '\OCP\SystemTag\ISystemTagManager'], diff --git a/tests/lib/Settings/Admin/AdditionalTest.php b/tests/lib/Settings/Admin/AdditionalTest.php new file mode 100644 index 00000000000..3a99893cf7c --- /dev/null +++ b/tests/lib/Settings/Admin/AdditionalTest.php @@ -0,0 +1,127 @@ +<?php +/** + * @copyright Copyright (c) 2016 Lukas Reschke <lukas@statuscode.ch> + * + * @author Lukas Reschke <lukas@statuscode.ch> + * + * @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\Admin; + +use OC\Settings\Admin\Additional; +use OCP\AppFramework\Http\TemplateResponse; +use OCP\IConfig; +use Test\TestCase; + +class AdditionalTest extends TestCase { + /** @var Additional */ + private $admin; + /** @var IConfig */ + private $config; + + public function setUp() { + parent::setUp(); + $this->config = $this->getMockBuilder('\OCP\IConfig')->getMock(); + + $this->admin = new Additional( + $this->config + ); + } + + public function testGetForm() { + $this->config + ->expects($this->at(0)) + ->method('getSystemValue') + ->with('mail_domain', '') + ->willReturn('mx.nextcloud.com'); + $this->config + ->expects($this->at(1)) + ->method('getSystemValue') + ->with('mail_from_address', '') + ->willReturn('no-reply@nextcloud.com'); + $this->config + ->expects($this->at(2)) + ->method('getSystemValue') + ->with('mail_smtpmode', '') + ->willReturn('php'); + $this->config + ->expects($this->at(3)) + ->method('getSystemValue') + ->with('mail_smtpsecure', '') + ->willReturn(true); + $this->config + ->expects($this->at(4)) + ->method('getSystemValue') + ->with('mail_smtphost', '') + ->willReturn('smtp.nextcloud.com'); + $this->config + ->expects($this->at(5)) + ->method('getSystemValue') + ->with('mail_smtpport', '') + ->willReturn(25); + $this->config + ->expects($this->at(6)) + ->method('getSystemValue') + ->with('mail_smtpauthtype', '') + ->willReturn('login'); + $this->config + ->expects($this->at(7)) + ->method('getSystemValue') + ->with('mail_smtpauth', false) + ->willReturn(true); + $this->config + ->expects($this->at(8)) + ->method('getSystemValue') + ->with('mail_smtpname', '') + ->willReturn('smtp.sender.com'); + $this->config + ->expects($this->at(9)) + ->method('getSystemValue') + ->with('mail_smtppassword', '') + ->willReturn('mypassword'); + + $expected = new TemplateResponse( + 'settings', + 'admin/additional-mail', + [ + 'sendmail_is_available' => (bool) \OC_Helper::findBinaryPath('sendmail'), + 'mail_domain' => 'mx.nextcloud.com', + 'mail_from_address' => 'no-reply@nextcloud.com', + 'mail_smtpmode' => 'php', + 'mail_smtpsecure' => true, + 'mail_smtphost' => 'smtp.nextcloud.com', + 'mail_smtpport' => 25, + 'mail_smtpauthtype' => 'login', + 'mail_smtpauth' => true, + 'mail_smtpname' => 'smtp.sender.com', + 'mail_smtppassword' => 'mypassword', + ], + '' + ); + + $this->assertEquals($expected, $this->admin->getForm()); + } + + public function testGetSection() { + $this->assertSame('additional', $this->admin->getSection()); + } + + public function testGetPriority() { + $this->assertSame(0, $this->admin->getPriority()); + } +} diff --git a/tests/lib/Settings/Admin/EncryptionTest.php b/tests/lib/Settings/Admin/EncryptionTest.php new file mode 100644 index 00000000000..a282b059c92 --- /dev/null +++ b/tests/lib/Settings/Admin/EncryptionTest.php @@ -0,0 +1,138 @@ +<?php +/** + * @copyright Copyright (c) 2016 Lukas Reschke <lukas@statuscode.ch> + * + * @author Lukas Reschke <lukas@statuscode.ch> + * + * @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\Admin; + +use OC\Encryption\Manager; +use OC\Settings\Admin\Encryption; +use OCP\AppFramework\Http\TemplateResponse; +use OCP\IUserManager; +use Test\TestCase; + +class EncryptionTest extends TestCase { + /** @var Encryption */ + private $admin; + /** @var Manager */ + private $manager; + /** @var IUserManager */ + private $userManager; + + public function setUp() { + parent::setUp(); + $this->manager = $this->getMockBuilder('\OC\Encryption\Manager')->disableOriginalConstructor()->getMock(); + $this->userManager = $this->getMockBuilder('\OCP\IUserManager')->getMock(); + + $this->admin = new Encryption( + $this->manager, + $this->userManager + ); + } + + /** + * @return array + */ + public function encryptionSettingsProvider() { + return [ + [true], + [false], + ]; + } + + /** + * @dataProvider encryptionSettingsProvider + * @param bool $enabled + */ + public function testGetFormWithOnlyOneBackend($enabled) { + $this->manager + ->expects($this->once()) + ->method('isEnabled') + ->willReturn($enabled); + $this->manager + ->expects($this->once()) + ->method('isReady') + ->willReturn($enabled); + $this->manager + ->expects($this->once()) + ->method('getEncryptionModules') + ->willReturn([]); + $this->userManager + ->expects($this->once()) + ->method('getBackends') + ->willReturn(['entry']); + $expected = new TemplateResponse( + 'settings', + 'admin/encryption', + [ + 'encryptionEnabled' => $enabled, + 'encryptionReady' => $enabled, + 'externalBackendsEnabled' => false, + 'encryptionModules' => [] + ], + '' + ); + $this->assertEquals($expected, $this->admin->getForm()); + } + + /** + * @dataProvider encryptionSettingsProvider + * @param bool $enabled + */ + public function testGetFormWithMultipleBackends($enabled) { + $this->manager + ->expects($this->once()) + ->method('isEnabled') + ->willReturn($enabled); + $this->manager + ->expects($this->once()) + ->method('isReady') + ->willReturn($enabled); + $this->manager + ->expects($this->once()) + ->method('getEncryptionModules') + ->willReturn([]); + $this->userManager + ->expects($this->once()) + ->method('getBackends') + ->willReturn(['entry', 'entry']); + $expected = new TemplateResponse( + 'settings', + 'admin/encryption', + [ + 'encryptionEnabled' => $enabled, + 'encryptionReady' => $enabled, + 'externalBackendsEnabled' => true, + 'encryptionModules' => [] + ], + '' + ); + $this->assertEquals($expected, $this->admin->getForm()); + } + + public function testGetSection() { + $this->assertSame('encryption', $this->admin->getSection()); + } + + public function testGetPriority() { + $this->assertSame(0, $this->admin->getPriority()); + } +} diff --git a/tests/lib/Settings/Admin/LoggingTest.php b/tests/lib/Settings/Admin/LoggingTest.php new file mode 100644 index 00000000000..181553d3894 --- /dev/null +++ b/tests/lib/Settings/Admin/LoggingTest.php @@ -0,0 +1,91 @@ +<?php +/** + * @copyright Copyright (c) 2016 Lukas Reschke <lukas@statuscode.ch> + * + * @author Lukas Reschke <lukas@statuscode.ch> + * + * @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\Admin; + +use OC\Settings\Admin\Logging; +use OCP\AppFramework\Http\TemplateResponse; +use OCP\IConfig; +use Test\TestCase; +use OC\Log\File as LogFile; + +class LoggingTest extends TestCase { + /** @var Logging */ + private $admin; + /** @var IConfig */ + private $config; + + public function setUp() { + parent::setUp(); + $this->config = $this->getMockBuilder('\OCP\IConfig')->getMock(); + + $this->admin = new Logging( + $this->config + ); + } + + public function testGetForm() { + $this->config + ->expects($this->at(0)) + ->method('getSystemValue') + ->with('log_type', 'file') + ->willReturn('owncloud'); + $this->config + ->expects($this->at(1)) + ->method('getSystemValue') + ->with('loglevel', 2) + ->willReturn(3); + + $numEntriesToLoad = 5; + $entries = LogFile::getEntries($numEntriesToLoad + 1); + $entriesRemaining = count($entries) > $numEntriesToLoad; + $entries = array_slice($entries, 0, $numEntriesToLoad); + + $logFileExists = file_exists(LogFile::getLogFilePath()) ; + $logFileSize = $logFileExists ? filesize(LogFile::getLogFilePath()) : 0; + + $expected = new TemplateResponse( + 'settings', + 'admin/logging', + [ + 'loglevel' => 3, + 'entries' => $entries, + 'entriesremain' => $entriesRemaining, + 'doesLogFileExist' => $logFileExists, + 'logFileSize' => $logFileSize, + 'showLog' => true, + ], + '' + ); + + $this->assertEquals($expected, $this->admin->getForm()); + } + + public function testGetSection() { + $this->assertSame('logging', $this->admin->getSection()); + } + + public function testGetPriority() { + $this->assertSame(0, $this->admin->getPriority()); + } +} diff --git a/tests/lib/Settings/Admin/ServerTest.php b/tests/lib/Settings/Admin/ServerTest.php new file mode 100644 index 00000000000..874422307e0 --- /dev/null +++ b/tests/lib/Settings/Admin/ServerTest.php @@ -0,0 +1,154 @@ +<?php +/** + * @copyright Copyright (c) 2016 Lukas Reschke <lukas@statuscode.ch> + * + * @author Lukas Reschke <lukas@statuscode.ch> + * + * @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\Admin; + +use Doctrine\DBAL\Platforms\SqlitePlatform; +use OC\Settings\Admin\Server; +use OCP\AppFramework\Http\TemplateResponse; +use OCP\IConfig; +use OCP\IDBConnection; +use OCP\IL10N; +use OCP\Lock\ILockingProvider; +use Test\TestCase; + +class ServerTest extends TestCase { + /** @var Server */ + private $admin; + /** @var IDBConnection */ + private $dbConnection; + /** @var IConfig */ + private $config; + /** @var ILockingProvider */ + private $lockingProvider; + /** @var IL10N */ + private $l10n; + + public function setUp() { + parent::setUp(); + $this->config = $this->getMockBuilder('\OCP\IConfig')->getMock(); + $this->dbConnection = $this->getMockBuilder('\OCP\IDBConnection')->getMock(); + $this->lockingProvider = $this->getMockBuilder('\OCP\Lock\ILockingProvider')->getMock(); + $this->l10n = $this->getMockBuilder('\OCP\IL10N')->getMock(); + + $this->admin = new Server( + $this->dbConnection, + $this->config, + $this->lockingProvider, + $this->l10n + ); + } + + public function testGetForm() { + $this->dbConnection + ->expects($this->once()) + ->method('getDatabasePlatform') + ->willReturn(new SqlitePlatform()); + $this->config + ->expects($this->at(0)) + ->method('getAppValue') + ->with('core', 'backgroundjobs_mode', 'ajax') + ->willReturn('ajax'); + $this->config + ->expects($this->at(2)) + ->method('getAppValue') + ->with('core', 'backgroundjobs_mode', 'ajax') + ->willReturn('ajax'); + $this->config + ->expects($this->at(4)) + ->method('getAppValue') + ->with('core', 'lastcron', false) + ->willReturn(false); + $this->config + ->expects($this->at(5)) + ->method('getAppValue') + ->with('core', 'cronErrors') + ->willReturn(''); + $this->config + ->expects($this->at(1)) + ->method('getSystemValue') + ->with('check_for_working_wellknown_setup', true) + ->willReturn(true); + $this->config + ->expects($this->at(3)) + ->method('getSystemValue') + ->with('cron_log', true) + ->willReturn(true); + $this->l10n + ->expects($this->at(0)) + ->method('t') + ->with('APCu') + ->willReturn('APCu'); + $this->l10n + ->expects($this->at(1)) + ->method('t') + ->with('Redis') + ->willReturn('Redis'); + $outdatedCaches = []; + $caches = [ + 'apcu' => ['name' => 'APCu', 'version' => '4.0.6'], + 'redis' => ['name' => 'Redis', 'version' => '2.2.5'], + ]; + foreach ($caches as $php_module => $data) { + $isOutdated = extension_loaded($php_module) && version_compare(phpversion($php_module), $data['version'], '<'); + if ($isOutdated) { + $outdatedCaches[$php_module] = $data; + } + } + $envPath = getenv('PATH'); + $expected = new TemplateResponse( + 'settings', + 'admin/server', + [ + // Diagnosis + 'readOnlyConfigEnabled' => \OC_Helper::isReadOnlyConfigEnabled(), + 'isLocaleWorking' => \OC_Util::isSetLocaleWorking(), + 'isAnnotationsWorking' => \OC_Util::isAnnotationsWorking(), + 'checkForWorkingWellKnownSetup' => true, + 'has_fileinfo' => \OC_Util::fileInfoLoaded(), + 'invalidTransactionIsolationLevel' => false, + 'getenvServerNotWorking' => empty($envPath), + 'OutdatedCacheWarning' => $outdatedCaches, + 'fileLockingType' => 'cache', + 'suggestedOverwriteCliUrl' => '', + + // Background jobs + 'backgroundjobs_mode' => 'ajax', + 'cron_log' => true, + 'lastcron' => false, + 'cronErrors' => '' + ], + '' + ); + + $this->assertEquals($expected, $this->admin->getForm()); + } + + public function testGetSection() { + $this->assertSame('server', $this->admin->getSection()); + } + + public function testGetPriority() { + $this->assertSame(0, $this->admin->getPriority()); + } +} diff --git a/tests/lib/Settings/Admin/SharingTest.php b/tests/lib/Settings/Admin/SharingTest.php new file mode 100644 index 00000000000..38ab7614d1c --- /dev/null +++ b/tests/lib/Settings/Admin/SharingTest.php @@ -0,0 +1,239 @@ +<?php +/** + * @copyright Copyright (c) 2016 Lukas Reschke <lukas@statuscode.ch> + * + * @author Lukas Reschke <lukas@statuscode.ch> + * + * @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\Admin; + +use OC\Settings\Admin\Sharing; +use OCP\AppFramework\Http\TemplateResponse; +use OCP\IConfig; +use Test\TestCase; + +class SharingTest extends TestCase { + /** @var Sharing */ + private $admin; + /** @var IConfig */ + private $config; + + public function setUp() { + parent::setUp(); + $this->config = $this->getMockBuilder('\OCP\IConfig')->getMock(); + + $this->admin = new Sharing( + $this->config + ); + } + + public function testGetFormWithoutExcludedGroups() { + $this->config + ->expects($this->at(0)) + ->method('getAppValue') + ->with('core', 'shareapi_exclude_groups_list', '') + ->willReturn(''); + $this->config + ->expects($this->at(1)) + ->method('getAppValue') + ->with('core', 'shareapi_allow_group_sharing', 'yes') + ->willReturn('yes'); + $this->config + ->expects($this->at(2)) + ->method('getAppValue') + ->with('core', 'shareapi_allow_links', 'yes') + ->willReturn('yes'); + $this->config + ->expects($this->at(3)) + ->method('getAppValue') + ->with('core', 'shareapi_allow_mail_notification', 'no') + ->willReturn('no'); + $this->config + ->expects($this->at(4)) + ->method('getAppValue') + ->with('core', 'shareapi_allow_public_notification', 'no') + ->willReturn('no'); + $this->config + ->expects($this->at(5)) + ->method('getAppValue') + ->with('core', 'shareapi_allow_public_upload', 'yes') + ->willReturn('yes'); + $this->config + ->expects($this->at(6)) + ->method('getAppValue') + ->with('core', 'shareapi_allow_resharing', 'yes') + ->willReturn('yes'); + $this->config + ->expects($this->at(7)) + ->method('getAppValue') + ->with('core', 'shareapi_allow_share_dialog_user_enumeration', 'yes') + ->willReturn('yes'); + $this->config + ->expects($this->at(8)) + ->method('getAppValue') + ->with('core', 'shareapi_enabled', 'yes') + ->willReturn('yes'); + $this->config + ->expects($this->at(9)) + ->method('getAppValue') + ->with('core', 'shareapi_default_expire_date', 'no') + ->willReturn('no'); + $this->config + ->expects($this->at(10)) + ->method('getAppValue') + ->with('core', 'shareapi_expire_after_n_days', '7') + ->willReturn('7'); + $this->config + ->expects($this->at(11)) + ->method('getAppValue') + ->with('core', 'shareapi_enforce_expire_date', 'no') + ->willReturn('no'); + $this->config + ->expects($this->at(12)) + ->method('getAppValue') + ->with('core', 'shareapi_exclude_groups', 'no') + ->willReturn('no'); + + $expected = new TemplateResponse( + 'settings', + 'admin/sharing', + [ + 'allowGroupSharing' => 'yes', + 'allowLinks' => 'yes', + 'allowMailNotification' => 'no', + 'allowPublicMailNotification' => 'no', + 'allowPublicUpload' => 'yes', + 'allowResharing' => 'yes', + 'allowShareDialogUserEnumeration' => 'yes', + 'enforceLinkPassword' => false, + 'onlyShareWithGroupMembers' => false, + 'shareAPIEnabled' => 'yes', + 'shareDefaultExpireDateSet' => 'no', + 'shareExpireAfterNDays' => '7', + 'shareEnforceExpireDate' => 'no', + 'shareExcludeGroups' => false, + 'shareExcludedGroupsList' => '', + ], + '' + ); + + $this->assertEquals($expected, $this->admin->getForm()); + } + + public function testGetFormWithExcludedGroups() { + $this->config + ->expects($this->at(0)) + ->method('getAppValue') + ->with('core', 'shareapi_exclude_groups_list', '') + ->willReturn('["NoSharers","OtherNoSharers"]'); + $this->config + ->expects($this->at(1)) + ->method('getAppValue') + ->with('core', 'shareapi_allow_group_sharing', 'yes') + ->willReturn('yes'); + $this->config + ->expects($this->at(2)) + ->method('getAppValue') + ->with('core', 'shareapi_allow_links', 'yes') + ->willReturn('yes'); + $this->config + ->expects($this->at(3)) + ->method('getAppValue') + ->with('core', 'shareapi_allow_mail_notification', 'no') + ->willReturn('no'); + $this->config + ->expects($this->at(4)) + ->method('getAppValue') + ->with('core', 'shareapi_allow_public_notification', 'no') + ->willReturn('no'); + $this->config + ->expects($this->at(5)) + ->method('getAppValue') + ->with('core', 'shareapi_allow_public_upload', 'yes') + ->willReturn('yes'); + $this->config + ->expects($this->at(6)) + ->method('getAppValue') + ->with('core', 'shareapi_allow_resharing', 'yes') + ->willReturn('yes'); + $this->config + ->expects($this->at(7)) + ->method('getAppValue') + ->with('core', 'shareapi_allow_share_dialog_user_enumeration', 'yes') + ->willReturn('yes'); + $this->config + ->expects($this->at(8)) + ->method('getAppValue') + ->with('core', 'shareapi_enabled', 'yes') + ->willReturn('yes'); + $this->config + ->expects($this->at(9)) + ->method('getAppValue') + ->with('core', 'shareapi_default_expire_date', 'no') + ->willReturn('no'); + $this->config + ->expects($this->at(10)) + ->method('getAppValue') + ->with('core', 'shareapi_expire_after_n_days', '7') + ->willReturn('7'); + $this->config + ->expects($this->at(11)) + ->method('getAppValue') + ->with('core', 'shareapi_enforce_expire_date', 'no') + ->willReturn('no'); + $this->config + ->expects($this->at(12)) + ->method('getAppValue') + ->with('core', 'shareapi_exclude_groups', 'no') + ->willReturn('yes'); + + $expected = new TemplateResponse( + 'settings', + 'admin/sharing', + [ + 'allowGroupSharing' => 'yes', + 'allowLinks' => 'yes', + 'allowMailNotification' => 'no', + 'allowPublicMailNotification' => 'no', + 'allowPublicUpload' => 'yes', + 'allowResharing' => 'yes', + 'allowShareDialogUserEnumeration' => 'yes', + 'enforceLinkPassword' => false, + 'onlyShareWithGroupMembers' => false, + 'shareAPIEnabled' => 'yes', + 'shareDefaultExpireDateSet' => 'no', + 'shareExpireAfterNDays' => '7', + 'shareEnforceExpireDate' => 'no', + 'shareExcludeGroups' => true, + 'shareExcludedGroupsList' => 'NoSharers|OtherNoSharers', + ], + '' + ); + + $this->assertEquals($expected, $this->admin->getForm()); + } + + public function testGetSection() { + $this->assertSame('sharing', $this->admin->getSection()); + } + + public function testGetPriority() { + $this->assertSame(0, $this->admin->getPriority()); + } +} diff --git a/tests/lib/Settings/Admin/TipsTricksTest.php b/tests/lib/Settings/Admin/TipsTricksTest.php new file mode 100644 index 00000000000..0e8857b56d0 --- /dev/null +++ b/tests/lib/Settings/Admin/TipsTricksTest.php @@ -0,0 +1,91 @@ +<?php +/** + * @copyright Copyright (c) 2016 Lukas Reschke <lukas@statuscode.ch> + * + * @author Lukas Reschke <lukas@statuscode.ch> + * + * @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\Admin; + +use OC\Settings\Admin\TipsTricks; +use OCP\AppFramework\Http\TemplateResponse; +use OCP\IConfig; +use Test\TestCase; + +class TipsTrickTest extends TestCase { + /** @var TipsTricks */ + private $admin; + /** @var IConfig */ + private $config; + + public function setUp() { + parent::setUp(); + $this->config = $this->getMockBuilder('\OCP\IConfig')->getMock(); + + $this->admin = new TipsTricks( + $this->config + ); + } + + public function testGetFormWithExcludedGroupsWithSQLite() { + $this->config + ->expects($this->once()) + ->method('getSystemValue') + ->with('dbtype') + ->willReturn('sqlite'); + + $expected = new TemplateResponse( + 'settings', + 'admin/tipstricks', + [ + 'databaseOverload' => true, + ], + '' + ); + + $this->assertEquals($expected, $this->admin->getForm()); + } + + public function testGetFormWithExcludedGroupsWithoutSQLite() { + $this->config + ->expects($this->once()) + ->method('getSystemValue') + ->with('dbtype') + ->willReturn('mysql'); + + $expected = new TemplateResponse( + 'settings', + 'admin/tipstricks', + [ + 'databaseOverload' => false, + ], + '' + ); + + $this->assertEquals($expected, $this->admin->getForm()); + } + + public function testGetSection() { + $this->assertSame('tips-tricks', $this->admin->getSection()); + } + + public function testGetPriority() { + $this->assertSame(0, $this->admin->getPriority()); + } +} diff --git a/tests/lib/Settings/ManagerTest.php b/tests/lib/Settings/ManagerTest.php new file mode 100644 index 00000000000..942a2bb63e7 --- /dev/null +++ b/tests/lib/Settings/ManagerTest.php @@ -0,0 +1,233 @@ +<?php +/** + * @copyright Copyright (c) 2016 Lukas Reschke <lukas@statuscode.ch> + * + * @author Lukas Reschke <lukas@statuscode.ch> + * + * @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\Settings; + +use OC\Settings\Admin\Sharing; +use OC\Settings\Manager; +use OC\Settings\Section; +use OCP\Encryption\IManager; +use OCP\IConfig; +use OCP\IDBConnection; +use OCP\IL10N; +use OCP\ILogger; +use OCP\IUserManager; +use OCP\Lock\ILockingProvider; +use Test\TestCase; + +class ManagerTest extends TestCase { + /** @var Manager */ + private $manager; + /** @var ILogger */ + private $logger; + /** @var IDBConnection */ + private $dbConnection; + /** @var IL10N */ + private $l10n; + /** @var IConfig */ + private $config; + /** @var IManager */ + private $encryptionManager; + /** @var IUserManager */ + private $userManager; + /** @var ILockingProvider */ + private $lockingProvider; + + public function setUp() { + parent::setUp(); + + $this->logger = $this->getMockBuilder('\OCP\ILogger')->getMock(); + $this->dbConnection = $this->getMockBuilder('\OCP\IDBConnection')->getMock(); + $this->l10n = $this->getMockBuilder('\OCP\IL10N')->getMock(); + $this->config = $this->getMockBuilder('\OCP\IConfig')->getMock(); + $this->encryptionManager = $this->getMockBuilder('\OCP\Encryption\IManager')->getMock(); + $this->userManager = $this->getMockBuilder('\OCP\IUserManager')->getMock(); + $this->lockingProvider = $this->getMockBuilder('\OCP\Lock\ILockingProvider')->getMock(); + + $this->manager = new Manager( + $this->logger, + $this->dbConnection, + $this->l10n, + $this->config, + $this->encryptionManager, + $this->userManager, + $this->lockingProvider + ); + } + + public function testSetupSettings() { + $qb = $this->getMockBuilder('\OCP\DB\QueryBuilder\IQueryBuilder')->getMock(); + $qb + ->expects($this->once()) + ->method('select') + ->with('class') + ->willReturn($qb); + $this->dbConnection + ->expects($this->at(0)) + ->method('getQueryBuilder') + ->willReturn($qb); + $qb + ->expects($this->once()) + ->method('from') + ->with('admin_settings') + ->willReturn($qb); + $expressionBuilder = $this->getMockBuilder('\OCP\DB\QueryBuilder\IExpressionBuilder')->getMock(); + $qb + ->expects($this->once()) + ->method('expr') + ->willReturn($expressionBuilder); + $param = $this->getMockBuilder('\OCP\DB\QueryBuilder\IParameter')->getMock(); + $qb + ->expects($this->once()) + ->method('createNamedParameter') + ->with('OCA\Files\Settings\Admin') + ->willReturn($param); + $expressionBuilder + ->expects($this->once()) + ->method('eq') + ->with('class', $param) + ->willReturn('myString'); + $qb + ->expects($this->once()) + ->method('where') + ->with('myString') + ->willReturn($qb); + $stmt = $this->getMockBuilder('\Doctrine\DBAL\Driver\Statement')->getMock(); + $qb + ->expects($this->once()) + ->method('execute') + ->willReturn($stmt); + + $qb1 = $this->getMockBuilder('\OCP\DB\QueryBuilder\IQueryBuilder')->getMock(); + $qb1 + ->expects($this->once()) + ->method('insert') + ->with('admin_settings') + ->willReturn($qb1); + $this->dbConnection + ->expects($this->at(1)) + ->method('getQueryBuilder') + ->willReturn($qb1); + + $this->manager->setupSettings([ + 'admin' => 'OCA\Files\Settings\Admin', + ]); + } + + public function testGetAdminSections() { + $qb = $this->getMockBuilder('\OCP\DB\QueryBuilder\IQueryBuilder')->getMock(); + $expr = $this->getMockBuilder('OCP\DB\QueryBuilder\IExpressionBuilder')->getMock(); + $qb + ->expects($this->once()) + ->method('selectDistinct') + ->with('s.class') + ->willReturn($qb); + $qb + ->expects($this->once()) + ->method('addSelect') + ->with('s.priority') + ->willReturn($qb); + $qb + ->expects($this->exactly(2)) + ->method('from') + ->willReturn($qb); + $qb + ->expects($this->once()) + ->method('expr') + ->willReturn($expr); + $qb + ->expects($this->once()) + ->method('where') + ->willReturn($qb); + $stmt = $this->getMockBuilder('\Doctrine\DBAL\Driver\Statement')->getMock(); + $qb + ->expects($this->once()) + ->method('execute') + ->willReturn($stmt); + $this->dbConnection + ->expects($this->once()) + ->method('getQueryBuilder') + ->willReturn($qb); + $this->l10n + ->expects($this->any()) + ->method('t') + ->will($this->returnArgument(0)); + + $this->assertEquals([ + 0 => [new Section('server', 'Server settings', 0)], + 5 => [new Section('sharing', 'Sharing', 0)], + 45 => [new Section('encryption', 'Encryption', 0)], + 90 => [new Section('logging', 'Logging', 0)], + 98 => [new Section('additional', 'Additional settings', 0)], + 99 => [new Section('tips-tricks', 'Tips & tricks', 0)], + ], $this->manager->getAdminSections()); + } + + public function testGetAdminSettings() { + $qb = $this->getMockBuilder('\OCP\DB\QueryBuilder\IQueryBuilder')->getMock(); + $qb + ->expects($this->once()) + ->method('select') + ->with(['class', 'priority']) + ->willReturn($qb); + $qb + ->expects($this->once()) + ->method('from') + ->with('admin_settings') + ->willReturn($qb); + $expressionBuilder = $this->getMockBuilder('\OCP\DB\QueryBuilder\IExpressionBuilder')->getMock(); + $qb + ->expects($this->once()) + ->method('expr') + ->willReturn($expressionBuilder); + $param = $this->getMockBuilder('\OCP\DB\QueryBuilder\IParameter')->getMock(); + $qb + ->expects($this->once()) + ->method('createParameter') + ->with('section') + ->willReturn($param); + $expressionBuilder + ->expects($this->once()) + ->method('eq') + ->with('section', $param) + ->willReturn('myString'); + $qb + ->expects($this->once()) + ->method('where') + ->with('myString') + ->willReturn($qb); + $stmt = $this->getMockBuilder('\Doctrine\DBAL\Driver\Statement')->getMock(); + $qb + ->expects($this->once()) + ->method('execute') + ->willReturn($stmt); + $this->dbConnection + ->expects($this->exactly(2)) + ->method('getQueryBuilder') + ->willReturn($qb); + + $this->assertEquals([ + 0 => [new Sharing($this->config)], + ], $this->manager->getAdminSettings('sharing')); + } +} diff --git a/tests/lib/Settings/SectionTest.php b/tests/lib/Settings/SectionTest.php new file mode 100644 index 00000000000..422b931bb4b --- /dev/null +++ b/tests/lib/Settings/SectionTest.php @@ -0,0 +1,39 @@ +<?php +/** + * @copyright Copyright (c) 2016 Lukas Reschke <lukas@statuscode.ch> + * + * @author Lukas Reschke <lukas@statuscode.ch> + * + * @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\Settings; + +use OC\Settings\Section; +use Test\TestCase; + +class SectionTest extends TestCase { + public function testGetID() { + $this->assertSame('ldap', (new Section('ldap', 'name', 1))->getID()); + } + public function testGetName() { + $this->assertSame('name', (new Section('ldap', 'name', 1))->getName()); + } + public function testGetPriority() { + $this->assertSame(1, (new Section('ldap', 'name', 1))->getPriority()); + } +} diff --git a/tests/lib/TestCase.php b/tests/lib/TestCase.php index 514cb6ea3a5..b9b18c644fd 100644 --- a/tests/lib/TestCase.php +++ b/tests/lib/TestCase.php @@ -24,6 +24,7 @@ namespace Test; use DOMDocument; use DOMNode; +use OC\Cache\CappedMemoryCache; use OC\Command\QueueBus; use OC\Files\Filesystem; use OC\Template\Base; diff --git a/tests/lib/UpdaterTest.php b/tests/lib/UpdaterTest.php index 643a18cc714..e45a9f08243 100644 --- a/tests/lib/UpdaterTest.php +++ b/tests/lib/UpdaterTest.php @@ -137,6 +137,12 @@ class UpdaterTest extends \Test\TestCase { ['8.1.0.0', '8.2.0.0', '8.1', true, true], ['8.2.0.1', '8.2.0.1', '8.1', true, true], ['8.3.0.0', '8.2.0.0', '8.1', true, true], + + // Downgrade of maintenance + ['9.0.53.0', '9.0.4.0', '8.1', false, false, 'nextcloud'], + // with vendor switch + ['9.0.53.0', '9.0.4.0', '8.1', true, false, ''], + ['9.0.53.0', '9.0.4.0', '8.1', true, false, 'owncloud'], ]; } @@ -148,12 +154,17 @@ class UpdaterTest extends \Test\TestCase { * @param string $allowedVersion * @param bool $result * @param bool $debug + * @param string $vendor */ - public function testIsUpgradePossible($oldVersion, $newVersion, $allowedVersion, $result, $debug = false) { + public function testIsUpgradePossible($oldVersion, $newVersion, $allowedVersion, $result, $debug = false, $vendor = 'nextcloud') { $this->config->expects($this->any()) ->method('getSystemValue') ->with('debug', false) ->willReturn($debug); + $this->config->expects($this->any()) + ->method('getAppValue') + ->with('core', 'vendor', '') + ->willReturn($vendor); $this->assertSame($result, $this->updater->isUpgradePossible($oldVersion, $newVersion, $allowedVersion)); } diff --git a/tests/lib/User/SessionTest.php b/tests/lib/User/SessionTest.php index 379c7e39442..4b8067117b1 100644 --- a/tests/lib/User/SessionTest.php +++ b/tests/lib/User/SessionTest.php @@ -371,7 +371,7 @@ class SessionTest extends \Test\TestCase { ->with('token_auth_enforced', false) ->will($this->returnValue(true)); $request - ->expects($this->exactly(2)) + ->expects($this->any()) ->method('getRemoteAddress') ->willReturn('192.168.0.1'); $this->throttler @@ -379,7 +379,7 @@ class SessionTest extends \Test\TestCase { ->method('sleepDelay') ->with('192.168.0.1'); $this->throttler - ->expects($this->once()) + ->expects($this->any()) ->method('getDelay') ->with('192.168.0.1') ->willReturn(0); @@ -412,7 +412,7 @@ class SessionTest extends \Test\TestCase { ->method('set') ->with('app_password', 'I-AM-AN-APP-PASSWORD'); $request - ->expects($this->exactly(2)) + ->expects($this->any()) ->method('getRemoteAddress') ->willReturn('192.168.0.1'); $this->throttler @@ -420,7 +420,7 @@ class SessionTest extends \Test\TestCase { ->method('sleepDelay') ->with('192.168.0.1'); $this->throttler - ->expects($this->once()) + ->expects($this->any()) ->method('getDelay') ->with('192.168.0.1') ->willReturn(0); @@ -459,7 +459,7 @@ class SessionTest extends \Test\TestCase { ->will($this->returnValue(true)); $request - ->expects($this->exactly(2)) + ->expects($this->any()) ->method('getRemoteAddress') ->willReturn('192.168.0.1'); $this->throttler @@ -467,7 +467,7 @@ class SessionTest extends \Test\TestCase { ->method('sleepDelay') ->with('192.168.0.1'); $this->throttler - ->expects($this->once()) + ->expects($this->any()) ->method('getDelay') ->with('192.168.0.1') ->willReturn(0); diff --git a/tests/phpunit-autotest.xml b/tests/phpunit-autotest.xml index 07de887c8cb..301f63a375d 100644 --- a/tests/phpunit-autotest.xml +++ b/tests/phpunit-autotest.xml @@ -8,9 +8,8 @@ > <testsuite name='ownCloud'> <directory suffix='.php'>lib/</directory> - <directory suffix='.php'>settings/</directory> - <directory suffix='.php'>core/</directory> - <directory suffix='.php'>ocs-provider/</directory> + <directory suffix='.php'>Settings/</directory> + <directory suffix='.php'>Core/</directory> <file>apps.php</file> </testsuite> <!-- filters for code coverage --> diff --git a/tests/phpunit.xml.dist b/tests/phpunit.xml.dist index 19fa38209a9..d3a5897dfaf 100644 --- a/tests/phpunit.xml.dist +++ b/tests/phpunit.xml.dist @@ -2,9 +2,8 @@ <phpunit bootstrap="bootstrap.php"> <testsuite name='ownCloud'> <directory suffix='.php'>lib/</directory> - <directory suffix='.php'>settings/</directory> - <directory suffix='.php'>core/</directory> - <directory suffix='.php'>ocs-provider/</directory> + <directory suffix='.php'>Settings/</directory> + <directory suffix='.php'>Core/</directory> <file>apps.php</file> </testsuite> <!-- filters for code coverage --> |