From 9489104cb3880f22d52bcf7b439a67dd3db60ccf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20M=C3=BCller?= Date: Wed, 15 Feb 2017 16:34:05 +0100 Subject: [PATCH] Central user account table arriving ..... --- apps/federatedfilesharing/tests/TestCase.php | 12 +- apps/files/tests/Service/TagServiceTest.php | 14 +- apps/files_sharing/tests/CacheTest.php | 32 +- .../tests/EncryptedSizePropagationTest.php | 6 +- .../tests/External/ManagerTest.php | 2 +- apps/files_sharing/tests/LockingTest.php | 18 +- .../tests/SizePropagationTest.php | 4 +- apps/files_sharing/tests/TestCase.php | 32 +- apps/files_versions/tests/VersioningTest.php | 7 +- apps/provisioning_api/appinfo/routes.php | 1 - apps/provisioning_api/lib/Users.php | 8 +- apps/provisioning_api/tests/UsersTest.php | 23 +- core/Migrations/Version20170214112458.php | 61 ++ lib/base.php | 1 + lib/private/Log.php | 2 +- lib/private/Server.php | 6 +- lib/private/Setup.php | 3 + lib/private/User/Account.php | 89 +++ lib/private/User/AccountMapper.php | 140 +++++ lib/private/User/Database.php | 2 + lib/private/User/Manager.php | 266 +++------ lib/private/User/Session.php | 9 +- lib/private/User/User.php | 221 ++++---- lib/private/legacy/app.php | 7 + lib/public/AppFramework/Db/Mapper.php | 12 +- lib/public/IUserManager.php | 1 - lib/public/User/IChangePasswordBackend.php | 44 ++ .../Controller/UsersControllerTest.php | 4 +- tests/lib/App/ManagerTest.php | 25 +- tests/lib/AppTest.php | 9 +- tests/lib/Cache/FileCacheTest.php | 7 +- tests/lib/Encryption/Keys/StorageTest.php | 1 + tests/lib/Files/Cache/CacheTest.php | 2 +- tests/lib/Files/Config/UserMountCacheTest.php | 40 +- tests/lib/Files/EtagTest.php | 18 +- .../Service/UserGlobalStoragesServiceTest.php | 2 +- tests/lib/Files/FilesystemTest.php | 125 ++-- tests/lib/Files/Node/IntegrationTest.php | 16 +- tests/lib/Files/Node/NodeTest.php | 33 +- tests/lib/Files/Node/RootTest.php | 46 +- .../Files/Storage/HomeStorageQuotaTest.php | 4 +- .../Files/Storage/Wrapper/EncryptionTest.php | 11 +- tests/lib/Files/Stream/EncryptionTest.php | 5 +- tests/lib/Files/Utils/ScannerTest.php | 11 +- tests/lib/Files/ViewTest.php | 7 +- tests/lib/Group/GroupTest.php | 52 +- tests/lib/HelperStorageTest.php | 7 +- tests/lib/Preview/Provider.php | 7 +- tests/lib/Repair/RemoveRootSharesTest.php | 8 +- tests/lib/Security/CertificateManagerTest.php | 2 +- tests/lib/Share/ShareTest.php | 20 +- tests/lib/SubAdminTest.php | 4 +- tests/lib/TagsTest.php | 30 +- tests/lib/Traits/UserTrait.php | 28 +- tests/lib/User/BackendTestCase.php | 17 +- tests/lib/User/DatabaseTest.php | 8 +- tests/lib/User/ManagerTest.php | 511 ++++------------- tests/lib/User/SessionTest.php | 447 +++++++-------- tests/lib/User/UserTest.php | 533 +++++------------- tests/lib/UserTest.php | 56 -- 60 files changed, 1405 insertions(+), 1714 deletions(-) create mode 100644 core/Migrations/Version20170214112458.php create mode 100644 lib/private/User/Account.php create mode 100644 lib/private/User/AccountMapper.php create mode 100644 lib/public/User/IChangePasswordBackend.php delete mode 100644 tests/lib/UserTest.php diff --git a/apps/federatedfilesharing/tests/TestCase.php b/apps/federatedfilesharing/tests/TestCase.php index 3549ac8c9a0d..ec0ec8b55119 100644 --- a/apps/federatedfilesharing/tests/TestCase.php +++ b/apps/federatedfilesharing/tests/TestCase.php @@ -24,6 +24,7 @@ use OC\Files\Filesystem; use OCA\Files\Share; +use Test\Traits\UserTrait; /** * Class Test_Files_Sharing_Base @@ -34,6 +35,8 @@ */ abstract class TestCase extends \Test\TestCase { + use UserTrait; + const TEST_FILES_SHARING_API_USER1 = "test-share-user1"; const TEST_FILES_SHARING_API_USER2 = "test-share-user2"; @@ -43,17 +46,14 @@ public static function setUpBeforeClass() { // reset backend \OC_User::clearBackends(); \OC::$server->getGroupManager()->clearBackends(); - - // create users - $backend = new \Test\Util\User\Dummy(); - \OC_User::useBackend($backend); - $backend->createUser(self::TEST_FILES_SHARING_API_USER1, self::TEST_FILES_SHARING_API_USER1); - $backend->createUser(self::TEST_FILES_SHARING_API_USER2, self::TEST_FILES_SHARING_API_USER2); } protected function setUp() { parent::setUp(); + $this->createUser(self::TEST_FILES_SHARING_API_USER1, self::TEST_FILES_SHARING_API_USER1); + $this->createUser(self::TEST_FILES_SHARING_API_USER2, self::TEST_FILES_SHARING_API_USER2); + //login as user1 self::loginHelper(self::TEST_FILES_SHARING_API_USER1); } diff --git a/apps/files/tests/Service/TagServiceTest.php b/apps/files/tests/Service/TagServiceTest.php index 7bbb5beb3a2c..210b75f2403f 100644 --- a/apps/files/tests/Service/TagServiceTest.php +++ b/apps/files/tests/Service/TagServiceTest.php @@ -24,6 +24,8 @@ namespace OCA\Files\Tests\Service; use OCA\Files\Service\TagService; +use OCP\IUserSession; +use Test\Traits\UserTrait; /** * Class TagServiceTest @@ -34,6 +36,8 @@ */ class TagServiceTest extends \Test\TestCase { + use UserTrait; + /** * @var string */ @@ -57,14 +61,10 @@ class TagServiceTest extends \Test\TestCase { protected function setUp() { parent::setUp(); $this->user = $this->getUniqueID('user'); - \OC::$server->getUserManager()->createUser($this->user, 'test'); + $user = $this->createUser($this->user, 'test'); \OC_User::setUserId($this->user); \OC_Util::setupFS($this->user); - /** @var \OCP\IUser */ - $user = new \OC\User\User($this->user, null); - /** - * @var \OCP\IUserSession - */ + /** @var IUserSession | \PHPUnit_Framework_MockObject_MockObject $userSession */ $userSession = $this->createMock('\OCP\IUserSession'); $userSession->expects($this->any()) ->method('getUser') @@ -83,8 +83,6 @@ protected function setUp() { protected function tearDown() { \OC_User::setUserId(''); - $user = \OC::$server->getUserManager()->get($this->user); - if ($user !== null) { $user->delete(); } } public function testUpdateFileTags() { diff --git a/apps/files_sharing/tests/CacheTest.php b/apps/files_sharing/tests/CacheTest.php index 8cf0ba7465bc..bd4984b4d032 100644 --- a/apps/files_sharing/tests/CacheTest.php +++ b/apps/files_sharing/tests/CacheTest.php @@ -28,16 +28,19 @@ namespace OCA\Files_Sharing\Tests; +use OC\Files\View; +use OCP\Constants; +use Test\Traits\UserTrait; + /** * Class CacheTest * * @group DB */ class CacheTest extends TestCase { + use UserTrait; - /** - * @var \OC\Files\View - */ + /** @var View */ public $user2View; /** @var \OC\Files\Cache\Cache */ @@ -60,12 +63,17 @@ protected function setUp() { $this->shareManager = \OC::$server->getShareManager(); + $this->createUser(self::TEST_FILES_SHARING_API_USER1, self::TEST_FILES_SHARING_API_USER1); + $this->createUser(self::TEST_FILES_SHARING_API_USER2, self::TEST_FILES_SHARING_API_USER2); + \OC_User::setDisplayName(self::TEST_FILES_SHARING_API_USER1, 'User One'); \OC_User::setDisplayName(self::TEST_FILES_SHARING_API_USER2, 'User Two'); - self::loginHelper(self::TEST_FILES_SHARING_API_USER1); + self::loginHelper(self::TEST_FILES_SHARING_API_USER2); - $this->user2View = new \OC\Files\View('/'. self::TEST_FILES_SHARING_API_USER2 . '/files'); + $this->user2View = new View('/'. self::TEST_FILES_SHARING_API_USER2 . '/files'); + + self::loginHelper(self::TEST_FILES_SHARING_API_USER1); // prepare user1's dir structure $this->view->mkdir('container'); @@ -94,7 +102,7 @@ protected function setUp() { ->setShareType(\OCP\Share::SHARE_TYPE_USER) ->setSharedWith(self::TEST_FILES_SHARING_API_USER2) ->setSharedBy(self::TEST_FILES_SHARING_API_USER1) - ->setPermissions(\OCP\Constants::PERMISSION_ALL); + ->setPermissions(Constants::PERMISSION_ALL); $this->shareManager->createShare($share); $node = $rootFolder->get('container/shared single file.txt'); @@ -103,14 +111,14 @@ protected function setUp() { ->setShareType(\OCP\Share::SHARE_TYPE_USER) ->setSharedWith(self::TEST_FILES_SHARING_API_USER2) ->setSharedBy(self::TEST_FILES_SHARING_API_USER1) - ->setPermissions(\OCP\Constants::PERMISSION_ALL & ~(\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_DELETE)); + ->setPermissions(Constants::PERMISSION_ALL & ~(Constants::PERMISSION_CREATE | Constants::PERMISSION_DELETE)); $this->shareManager->createShare($share); // login as user2 self::loginHelper(self::TEST_FILES_SHARING_API_USER2); // retrieve the shared storage - $secondView = new \OC\Files\View('/' . self::TEST_FILES_SHARING_API_USER2); + $secondView = new View('/' . self::TEST_FILES_SHARING_API_USER2); list($this->sharedStorage,) = $secondView->resolvePath('files/shareddir'); $this->sharedCache = $this->sharedStorage->getCache(); } @@ -393,12 +401,12 @@ function testGetFolderContentsWhenSubSubdirShared() { ->setShareType(\OCP\Share::SHARE_TYPE_USER) ->setSharedWith(self::TEST_FILES_SHARING_API_USER3) ->setSharedBy(self::TEST_FILES_SHARING_API_USER1) - ->setPermissions(\OCP\Constants::PERMISSION_ALL); + ->setPermissions(Constants::PERMISSION_ALL); $share = $this->shareManager->createShare($share); self::loginHelper(self::TEST_FILES_SHARING_API_USER3); - $thirdView = new \OC\Files\View('/' . self::TEST_FILES_SHARING_API_USER3 . '/files'); + $thirdView = new View('/' . self::TEST_FILES_SHARING_API_USER3 . '/files'); $results = $thirdView->getDirectoryContent('/subdir'); $this->verifyFiles( @@ -477,7 +485,7 @@ public function testGetPathByIdDirectShare() { ->setShareType(\OCP\Share::SHARE_TYPE_USER) ->setSharedWith(self::TEST_FILES_SHARING_API_USER2) ->setSharedBy(self::TEST_FILES_SHARING_API_USER1) - ->setPermissions(\OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_SHARE); + ->setPermissions(Constants::PERMISSION_READ | Constants::PERMISSION_UPDATE | Constants::PERMISSION_SHARE); $this->shareManager->createShare($share); \OC_Util::tearDownFS(); @@ -508,7 +516,7 @@ public function testGetPathByIdShareSubFolder() { ->setShareType(\OCP\Share::SHARE_TYPE_USER) ->setSharedWith(self::TEST_FILES_SHARING_API_USER2) ->setSharedBy(self::TEST_FILES_SHARING_API_USER1) - ->setPermissions(\OCP\Constants::PERMISSION_ALL); + ->setPermissions(Constants::PERMISSION_ALL); $this->shareManager->createShare($share); \OC_Util::tearDownFS(); diff --git a/apps/files_sharing/tests/EncryptedSizePropagationTest.php b/apps/files_sharing/tests/EncryptedSizePropagationTest.php index 555bba21830d..e2a24c3e7873 100644 --- a/apps/files_sharing/tests/EncryptedSizePropagationTest.php +++ b/apps/files_sharing/tests/EncryptedSizePropagationTest.php @@ -31,11 +31,11 @@ class EncryptedSizePropagationTest extends SizePropagationTest { use EncryptionTrait; - protected function setupUser($name, $password = '') { - $this->createUser($name, $password); + protected function setupUser($name) { + $this->createUser($name); $tmpFolder = \OC::$server->getTempManager()->getTemporaryFolder(); $this->registerMount($name, '\OC\Files\Storage\Local', '/' . $name, ['datadir' => $tmpFolder]); - $this->setupForUser($name, $password); + $this->setupForUser($name, $name); $this->loginWithEncryption($name); return new View('/' . $name . '/files'); } diff --git a/apps/files_sharing/tests/External/ManagerTest.php b/apps/files_sharing/tests/External/ManagerTest.php index 6a9287c4460b..3db303d41c3b 100644 --- a/apps/files_sharing/tests/External/ManagerTest.php +++ b/apps/files_sharing/tests/External/ManagerTest.php @@ -62,7 +62,7 @@ protected function setUp() { parent::setUp(); $this->uid = $this->getUniqueID('user'); - $this->createUser($this->uid, ''); + $this->createUser($this->uid); $this->user = \OC::$server->getUserManager()->get($this->uid); $this->mountManager = new \OC\Files\Mount\Manager(); $this->httpHelper = $httpHelper = $this->getMockBuilder('\OC\HTTPHelper')->disableOriginalConstructor()->getMock(); diff --git a/apps/files_sharing/tests/LockingTest.php b/apps/files_sharing/tests/LockingTest.php index 9b1f8be26517..f89e0d0a008c 100644 --- a/apps/files_sharing/tests/LockingTest.php +++ b/apps/files_sharing/tests/LockingTest.php @@ -28,6 +28,7 @@ use OC\Files\Filesystem; use OC\Files\View; use OCP\Lock\ILockingProvider; +use Test\Traits\UserTrait; /** * Class LockingTest @@ -37,10 +38,7 @@ * @package OCA\Files_Sharing\Tests */ class LockingTest extends TestCase { - /** - * @var \Test\Util\User\Dummy - */ - private $userBackend; + use UserTrait; private $ownerUid; private $recipientUid; @@ -48,13 +46,10 @@ class LockingTest extends TestCase { public function setUp() { parent::setUp(); - $this->userBackend = new \Test\Util\User\Dummy(); - \OC::$server->getUserManager()->registerBackend($this->userBackend); - $this->ownerUid = $this->getUniqueID('owner_'); $this->recipientUid = $this->getUniqueID('recipient_'); - $this->userBackend->createUser($this->ownerUid, ''); - $this->userBackend->createUser($this->recipientUid, ''); + $this->createUser($this->ownerUid); + $this->createUser($this->recipientUid); $this->loginAsUser($this->ownerUid); Filesystem::mkdir('/foo'); @@ -73,11 +68,6 @@ public function setUp() { $this->assertTrue(Filesystem::file_exists('bar.txt')); } - public function tearDown() { - \OC::$server->getUserManager()->removeBackend($this->userBackend); - parent::tearDown(); - } - /** * @expectedException \OCP\Lock\LockedException */ diff --git a/apps/files_sharing/tests/SizePropagationTest.php b/apps/files_sharing/tests/SizePropagationTest.php index 6a998f75b107..98ee88196cc3 100644 --- a/apps/files_sharing/tests/SizePropagationTest.php +++ b/apps/files_sharing/tests/SizePropagationTest.php @@ -39,8 +39,8 @@ class SizePropagationTest extends TestCase { use UserTrait; use MountProviderTrait; - protected function setupUser($name, $password = '') { - $this->createUser($name, $password); + protected function setupUser($name) { + $this->createUser($name); $tmpFolder = \OC::$server->getTempManager()->getTemporaryFolder(); $this->registerMount($name, '\OC\Files\Storage\Local', '/' . $name, ['datadir' => $tmpFolder]); $this->loginAsUser($name); diff --git a/apps/files_sharing/tests/TestCase.php b/apps/files_sharing/tests/TestCase.php index 5f3310239f1c..4bc1f95d3b3a 100644 --- a/apps/files_sharing/tests/TestCase.php +++ b/apps/files_sharing/tests/TestCase.php @@ -36,6 +36,7 @@ use OCA\Files_Sharing\AppInfo\Application; use OCA\Files_Sharing\SharedStorage; use OCP\ICache; +use Test\Traits\UserTrait; /** * Class TestCase @@ -46,6 +47,8 @@ */ abstract class TestCase extends \Test\TestCase { + use UserTrait; + const TEST_FILES_SHARING_API_USER1 = "test-share-user1"; const TEST_FILES_SHARING_API_USER2 = "test-share-user2"; const TEST_FILES_SHARING_API_USER3 = "test-share-user3"; @@ -74,20 +77,21 @@ public static function setUpBeforeClass() { $application->registerMountProviders(); // reset backend - \OC_User::clearBackends(); \OC::$server->getGroupManager()->clearBackends(); // clear share hooks \OC_Hook::clear('OCP\\Share'); \OC::registerShareHooks(); + } + + protected function setUp() { + parent::setUp(); // create users - $backend = new \Test\Util\User\Dummy(); - \OC_User::useBackend($backend); - $backend->createUser(self::TEST_FILES_SHARING_API_USER1, self::TEST_FILES_SHARING_API_USER1); - $backend->createUser(self::TEST_FILES_SHARING_API_USER2, self::TEST_FILES_SHARING_API_USER2); - $backend->createUser(self::TEST_FILES_SHARING_API_USER3, self::TEST_FILES_SHARING_API_USER3); - $backend->createUser(self::TEST_FILES_SHARING_API_USER4, self::TEST_FILES_SHARING_API_USER4); + $this->createUser(self::TEST_FILES_SHARING_API_USER1, self::TEST_FILES_SHARING_API_USER1); + $this->createUser(self::TEST_FILES_SHARING_API_USER2, self::TEST_FILES_SHARING_API_USER2); + $this->createUser(self::TEST_FILES_SHARING_API_USER3, self::TEST_FILES_SHARING_API_USER3); + $this->createUser(self::TEST_FILES_SHARING_API_USER4, self::TEST_FILES_SHARING_API_USER4); // create group $groupBackend = new \Test\Util\Group\Dummy(); @@ -104,10 +108,6 @@ public static function setUpBeforeClass() { $groupBackend->addToGroup(self::TEST_FILES_SHARING_API_USER4, 'group3'); $groupBackend->addToGroup(self::TEST_FILES_SHARING_API_USER2, self::TEST_FILES_SHARING_API_GROUP1); \OC::$server->getGroupManager()->addBackend($groupBackend); - } - - protected function setUp() { - parent::setUp(); //login as user1 self::loginHelper(self::TEST_FILES_SHARING_API_USER1); @@ -127,14 +127,6 @@ protected function tearDown() { } public static function tearDownAfterClass() { - // cleanup users - $user = \OC::$server->getUserManager()->get(self::TEST_FILES_SHARING_API_USER1); - if ($user !== null) { $user->delete(); } - $user = \OC::$server->getUserManager()->get(self::TEST_FILES_SHARING_API_USER2); - if ($user !== null) { $user->delete(); } - $user = \OC::$server->getUserManager()->get(self::TEST_FILES_SHARING_API_USER3); - if ($user !== null) { $user->delete(); } - // delete group $group = \OC::$server->getGroupManager()->get(self::TEST_FILES_SHARING_API_GROUP1); if ($group !== null) { $group->delete(); } @@ -144,8 +136,6 @@ public static function tearDownAfterClass() { Filesystem::tearDown(); // reset backend - \OC_User::clearBackends(); - \OC_User::useBackend('database'); \OC::$server->getGroupManager()->clearBackends(); \OC::$server->getGroupManager()->addBackend(new \OC\Group\Database()); diff --git a/apps/files_versions/tests/VersioningTest.php b/apps/files_versions/tests/VersioningTest.php index 7d9cd6e59a68..e9b22e31455e 100644 --- a/apps/files_versions/tests/VersioningTest.php +++ b/apps/files_versions/tests/VersioningTest.php @@ -35,6 +35,7 @@ require_once __DIR__ . '/../appinfo/app.php'; use OC\Files\Storage\Temporary; +use Test\TestCase; /** * Class Test_Files_versions @@ -42,7 +43,7 @@ * * @group DB */ -class VersioningTest extends \Test\TestCase { +class VersioningTest extends TestCase { const TEST_VERSIONS_USER = 'test-versions-user'; const TEST_VERSIONS_USER2 = 'test-versions-user2'; @@ -887,9 +888,7 @@ private function createAndCheckVersions(\OC\Files\View $view, $path) { public static function loginHelper($user, $create = false) { if ($create) { - $backend = new \Test\Util\User\Dummy(); - $backend->createUser($user, $user); - \OC::$server->getUserManager()->registerBackend($backend); + \OC::$server->getUserManager()->createUser($user, $user); } $storage = new \ReflectionClass('\OCA\Files_Sharing\SharedStorage'); diff --git a/apps/provisioning_api/appinfo/routes.php b/apps/provisioning_api/appinfo/routes.php index 80fd891de85b..dc588e951a56 100644 --- a/apps/provisioning_api/appinfo/routes.php +++ b/apps/provisioning_api/appinfo/routes.php @@ -35,7 +35,6 @@ // Users $users = new Users( \OC::$server->getUserManager(), - \OC::$server->getConfig(), \OC::$server->getGroupManager(), \OC::$server->getUserSession(), \OC::$server->getLogger(), diff --git a/apps/provisioning_api/lib/Users.php b/apps/provisioning_api/lib/Users.php index a57f1fc2079d..37be466df095 100644 --- a/apps/provisioning_api/lib/Users.php +++ b/apps/provisioning_api/lib/Users.php @@ -33,7 +33,6 @@ use \OC_Helper; use OCP\API; use OCP\Files\NotFoundException; -use OCP\IConfig; use OCP\IGroup; use OCP\IGroupManager; use OCP\ILogger; @@ -46,8 +45,6 @@ class Users { /** @var IUserManager */ private $userManager; - /** @var IConfig */ - private $config; /** @var IGroupManager|\OC\Group\Manager */ // FIXME Requires a method that is not on the interface private $groupManager; /** @var IUserSession */ @@ -59,19 +56,16 @@ class Users { /** * @param IUserManager $userManager - * @param IConfig $config * @param IGroupManager $groupManager * @param IUserSession $userSession * @param ILogger $logger */ public function __construct(IUserManager $userManager, - IConfig $config, IGroupManager $groupManager, IUserSession $userSession, ILogger $logger, \OC\Authentication\TwoFactorAuth\Manager $twoFactorAuthManager ) { $this->userManager = $userManager; - $this->config = $config; $this->groupManager = $groupManager; $this->userSession = $userSession; $this->logger = $logger; @@ -203,7 +197,7 @@ public function getUser($parameters) { // Admin? Or SubAdmin? if($this->groupManager->isAdmin($currentLoggedInUser->getUID()) || $this->groupManager->getSubAdmin()->isUserAccessible($currentLoggedInUser, $targetUserObject)) { - $data['enabled'] = $this->config->getUserValue($userId, 'core', 'enabled', 'true'); + $data['enabled'] = $targetUserObject->isEnabled() ? 'true' : 'false'; } else { // Check they are looking up themselves if($currentLoggedInUser->getUID() !== $userId) { diff --git a/apps/provisioning_api/tests/UsersTest.php b/apps/provisioning_api/tests/UsersTest.php index fbfce3b6a3ff..1ee0abb7a58e 100644 --- a/apps/provisioning_api/tests/UsersTest.php +++ b/apps/provisioning_api/tests/UsersTest.php @@ -33,7 +33,6 @@ use OCA\Provisioning_API\Users; use OCP\API; use OCP\IUserManager; -use OCP\IConfig; use OCP\IUserSession; use PHPUnit_Framework_MockObject_MockObject; use Test\TestCase as OriginalTest; @@ -43,8 +42,6 @@ class UsersTest extends OriginalTest { /** @var IUserManager | PHPUnit_Framework_MockObject_MockObject */ protected $userManager; - /** @var IConfig | PHPUnit_Framework_MockObject_MockObject */ - protected $config; /** @var \OC\Group\Manager | PHPUnit_Framework_MockObject_MockObject */ protected $groupManager; /** @var IUserSession | PHPUnit_Framework_MockObject_MockObject */ @@ -66,7 +63,6 @@ protected function setUp() { parent::setUp(); $this->userManager = $this->createMock('OCP\IUserManager'); - $this->config = $this->createMock('OCP\IConfig'); $this->groupManager = $this->getMockBuilder('OC\Group\Manager') ->disableOriginalConstructor() ->getMock(); @@ -82,7 +78,6 @@ protected function setUp() { $this->api = $this->getMockBuilder('OCA\Provisioning_API\Users') ->setConstructorArgs([ $this->userManager, - $this->config, $this->groupManager, $this->userSession, $this->logger, @@ -715,11 +710,6 @@ public function testGetUserAsAdmin() { ->method('isAdmin') ->with('admin') ->will($this->returnValue(true)); - $this->config - ->expects($this->at(0)) - ->method('getUserValue') - ->with('UserToGet', 'core', 'enabled', 'true') - ->will($this->returnValue('true')); $this->api ->expects($this->once()) ->method('fillStorageInfo') @@ -729,6 +719,10 @@ public function testGetUserAsAdmin() { ->expects($this->once()) ->method('getDisplayName') ->will($this->returnValue('Demo User')); + $targetUser + ->expects($this->once()) + ->method('isEnabled') + ->willReturn('true'); $expected = new Result( [ @@ -783,11 +777,6 @@ public function testGetUserAsSubAdminAndUserIsAccessible() { ->expects($this->once()) ->method('getSubAdmin') ->will($this->returnValue($subAdminManager)); - $this->config - ->expects($this->at(0)) - ->method('getUserValue') - ->with('UserToGet', 'core', 'enabled', 'true') - ->will($this->returnValue('true')); $this->api ->expects($this->once()) ->method('fillStorageInfo') @@ -797,6 +786,10 @@ public function testGetUserAsSubAdminAndUserIsAccessible() { ->expects($this->once()) ->method('getDisplayName') ->will($this->returnValue('Demo User')); + $targetUser + ->expects($this->once()) + ->method('isEnabled') + ->willReturn('true'); $expected = new Result( [ diff --git a/core/Migrations/Version20170214112458.php b/core/Migrations/Version20170214112458.php new file mode 100644 index 000000000000..bb1d3d20b587 --- /dev/null +++ b/core/Migrations/Version20170214112458.php @@ -0,0 +1,61 @@ +createTable("{$prefix}accounts"); + $table->addColumn('id', Type::BIGINT, [ + 'autoincrement' => true, + 'unsigned' => true, + 'notnull' => true, + ]); + $table->addColumn('email', Type::STRING, [ + 'notnull' => false, + 'length' => 255, + ]); + $table->addColumn('user_id', Type::STRING, [ + 'notnull' => true, + 'length' => 255, + ]); + $table->addColumn('lower_user_id', Type::STRING, [ + 'notnull' => true, + 'length' => 255, + ]); + $table->addColumn('display_name', Type::STRING, [ + 'notnull' => false, + 'length' => 255, + ]); + $table->addColumn('quota', Type::STRING, [ + 'notnull' => false, + 'length' => 32, + ]); + $table->addColumn('last_login', Type::INTEGER, [ + 'notnull' => true, + 'length' => 32, + 'default' => 0, + ]); + $table->addColumn('backend', Type::STRING, [ + 'notnull' => true, + 'length' => 64, + ]); + $table->addColumn('home', Type::STRING, [ + 'notnull' => true, + 'length' => 1024, + ]); + $table->addColumn('state', Type::SMALLINT, [ + 'notnull' => true, + 'default' => 0, + 'comment' => '0: initial, 1: enabled, 2: disabled, 3: deleted' + ]); + + $table->setPrimaryKey(['id']); + $table->addUniqueIndex(['email']); + $table->addUniqueIndex(['user_id']); + } +} diff --git a/lib/base.php b/lib/base.php index 0cc2a6756acc..7138745ba04d 100644 --- a/lib/base.php +++ b/lib/base.php @@ -842,6 +842,7 @@ public static function handleRequest() { $isOccControllerRequested = preg_match('|/index\.php$|', $request->getScriptName()) === 1 && strpos($request->getPathInfo(), '/occ/') === 0; + $needUpgrade = false; $requestPath = $request->getRawPathInfo(); if (substr($requestPath, -3) !== '.js') { // we need these files during the upgrade self::checkMaintenanceMode($request); diff --git a/lib/private/Log.php b/lib/private/Log.php index 455992fd97c1..068a9064f415 100644 --- a/lib/private/Log.php +++ b/lib/private/Log.php @@ -319,7 +319,7 @@ public function logException($exception, array $context = []) { 'Line' => $exception->getLine(), ]; $exception['Trace'] = preg_replace('!(' . implode('|', $this->methodsWithSensitiveParameters) . ')\(.*\)!', '$1(*** sensitive parameters replaced ***)', $exception['Trace']); - if (\OC::$server->getUserSession()->isLoggedIn()) { + if (\OC::$server->getUserSession() && \OC::$server->getUserSession()->isLoggedIn()) { $context['userid'] = \OC::$server->getUserSession()->getUser()->getUID(); } $msg = isset($context['message']) ? $context['message'] : 'Exception'; diff --git a/lib/private/Server.php b/lib/private/Server.php index 74e7978656d4..5e1a063d1a8e 100644 --- a/lib/private/Server.php +++ b/lib/private/Server.php @@ -83,9 +83,8 @@ use OC\Settings\Panels\Helper; use OC\Settings\SettingsManager; use OC\Tagging\TagMapper; -use OC\URLGenerator; use OC\Theme\ThemeService; -use OCP\IDateTimeFormatter; +use OC\User\AccountMapper; use OCP\IL10N; use OCP\IServerContainer; use OCP\Security\IContentSecurityPolicyManager; @@ -221,7 +220,8 @@ public function __construct($webRoot, \OC\Config $config) { }); $this->registerService('UserManager', function (Server $c) { $config = $c->getConfig(); - return new \OC\User\Manager($config); + $accountMapper = new AccountMapper($c->getDatabaseConnection()); + return new \OC\User\Manager($config, $accountMapper); }); $this->registerService('GroupManager', function (Server $c) { $groupManager = new \OC\Group\Manager($this->getUserManager()); diff --git a/lib/private/Setup.php b/lib/private/Setup.php index 2dabe99290e4..5db2044b9d41 100644 --- a/lib/private/Setup.php +++ b/lib/private/Setup.php @@ -348,6 +348,7 @@ public function install($options) { //create the user and group $user = null; try { + \OC::$server->getUserManager()->registerBackend(new \OC\User\Database()); $user = \OC::$server->getUserManager()->createUser($username, $password); if (!$user) { $error[] = "User <$username> could not be created."; @@ -361,6 +362,8 @@ public function install($options) { $config->setAppValue('core', 'installedat', microtime(true)); $config->setAppValue('core', 'lastupdatedat', microtime(true)); + \OC::$server->getGroupManager()->addBackend(new \OC\Group\Database()); + $group =\OC::$server->getGroupManager()->createGroup('admin'); $group->addUser($user); diff --git a/lib/private/User/Account.php b/lib/private/User/Account.php new file mode 100644 index 000000000000..4b927573b058 --- /dev/null +++ b/lib/private/User/Account.php @@ -0,0 +1,89 @@ + + * + * @copyright Copyright (c) 2017, ownCloud GmbH + * @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 + * + */ + + +namespace OC\User; + + +use OCP\AppFramework\Db\Entity; +use OCP\AppFramework\QueryException; +use OCP\UserInterface; + +/** + * Class Account + * + * @method int getUserId() + * @method string getDisplayName() + * @method void setDisplayName(string $displayName) + * @method string getEmail() + * @method void setEmail(string $email) + * @method int getLastLogin() + * @method void setLastLogin(int $lastLogin) + * @method string getBackend() + * @method void setBackend(string $backEnd) + * @method int getState() + * @method void setState(integer $state) + * @method string getQuota() + * @method void setQuota(string $quota) + * @method string getHome() + * @method void setHome(string $home) + * + * @package OC\User + */ +class Account extends Entity { + + const STATE_INITIAL = 0; + const STATE_ENABLED = 1; + const STATE_DISABLED = 2; + const STATE_DELETED = 3; + + protected $email; + protected $userId; + protected $lowerUserId; + protected $displayName; + protected $quota; + protected $lastLogin; + protected $backend; + protected $state; + protected $home; + + public function __construct() { + $this->addType('state', 'integer'); + $this->addType('lastLogin', 'integer'); + } + + public function setUserId($uid) { + parent::setter('lowerUserId', [strtolower($uid)]); + parent::setter('userId', [$uid]); + } + + /** + * @return UserInterface + */ + public function getBackendInstance() { + $backendClass = $this->getBackend(); + if (empty($backendClass)) { + return null; + } + // actually stupid + return \OC::$server->getUserManager()->getBackend($backendClass); + } +} diff --git a/lib/private/User/AccountMapper.php b/lib/private/User/AccountMapper.php new file mode 100644 index 000000000000..c174b0e9b64b --- /dev/null +++ b/lib/private/User/AccountMapper.php @@ -0,0 +1,140 @@ + + * + * @copyright Copyright (c) 2017, ownCloud GmbH + * @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 + * + */ + + +namespace OC\User; + + +use OC\DB\QueryBuilder\Literal; +use OCP\AppFramework\Db\Mapper; +use OCP\IDBConnection; + +class AccountMapper extends Mapper { + + public function __construct(IDBConnection $db) { + parent::__construct($db, 'accounts', Account::class); + } + + /** + * @param string $email + * @return Account[] + */ + public function getByEmail($email) { + $qb = $this->db->getQueryBuilder(); + $qb->select('*') + ->from($this->getTableName()) + ->where($qb->expr()->eq('email', $qb->createNamedParameter($email))); + + return $this->findEntities($qb->getSQL(), $qb->getParameters()); + } + + /** + * @param string $uid + * @return Account + */ + public function getByUid($uid) { + $qb = $this->db->getQueryBuilder(); + $qb->select('*') + ->from($this->getTableName()) + ->where($qb->expr()->eq('lower_user_id', $qb->createNamedParameter(strtolower($uid)))); + + return $this->findEntity($qb->getSQL(), $qb->getParameters()); + } + + /** + * @param string $fieldName + * @param string $pattern + * @param integer $limit + * @param integer $offset + * @return Account[] + */ + public function search($fieldName, $pattern, $limit, $offset) { + $qb = $this->db->getQueryBuilder(); + $qb->select('*') + ->from($this->getTableName()) + ->where($qb->expr()->iLike($fieldName, $qb->createNamedParameter('%' . $this->db->escapeLikeParameter($pattern) . '%'))) + ->orderBy($fieldName); + + return $this->findEntities($qb->getSQL(), $qb->getParameters(), $limit, $offset); + } + + public function getUserCountPerBackend($hasLoggedIn) { + $qb = $this->db->getQueryBuilder(); + $qb->select(['backend', $qb->createFunction('count(*) as `count`')]) + ->from($this->getTableName()) + ->groupBy('backend'); + + if ($hasLoggedIn) { + $qb->where($qb->expr()->gt('last_login', new Literal(0))); + } + + $result = $qb->execute(); + $data = $result->fetchAll(); + $result->closeCursor(); + + $return = []; + foreach ($data as $d) { + $return[$d['backend']] = $d['count']; + } + + return $return; + } + + public function getUserCount($hasLoggedIn) { + $qb = $this->db->getQueryBuilder(); + $qb->select([$qb->createFunction('count(*) as `count`')]) + ->from($this->getTableName()); + + if ($hasLoggedIn) { + $qb->where($qb->expr()->gt('last_login', new Literal(0))); + } + + $result = $qb->execute(); + $data = $result->fetch(); + $result->closeCursor(); + + return (int) $data['count']; + } + + public function callForAllUsers($callback, $search, $onlySeen) { + $qb = $this->db->getQueryBuilder(); + $qb->select(['*']) + ->from($this->getTableName()); + + if ($search) { + $qb->where($qb->expr()->iLike('user_id', + $qb->createNamedParameter('%' . $this->db->escapeLikeParameter($search) . '%'))); + } + if ($onlySeen) { + $qb->where($qb->expr()->gt('last_login', new Literal(0))); + } + $stmt = $qb->execute(); + while ($row = $stmt->fetch()) { + $return =$callback($this->mapRowToEntity($row)); + if ($return === false) { + break; + } + } + + $stmt->closeCursor(); + } + +} diff --git a/lib/private/User/Database.php b/lib/private/User/Database.php index d0b280e6937a..1ed89148a56b 100644 --- a/lib/private/User/Database.php +++ b/lib/private/User/Database.php @@ -173,6 +173,7 @@ public function getDisplayNames($search = '', $limit = null, $offset = null) { $parameters = []; $searchLike = ''; if ($search !== '') { + $search = \OC::$server->getDatabaseConnection()->escapeLikeParameter($search); $parameters[] = '%' . $search . '%'; $parameters[] = '%' . $search . '%'; $searchLike = ' WHERE LOWER(`displayname`) LIKE LOWER(?) OR ' @@ -262,6 +263,7 @@ public function getUsers($search = '', $limit = null, $offset = null) { $parameters = []; $searchLike = ''; if ($search !== '') { + $search = \OC::$server->getDatabaseConnection()->escapeLikeParameter($search); $parameters[] = '%' . $search . '%'; $searchLike = ' WHERE LOWER(`uid`) LIKE LOWER(?)'; } diff --git a/lib/private/User/Manager.php b/lib/private/User/Manager.php index aaabb810ef13..54e527ebc8d8 100644 --- a/lib/private/User/Manager.php +++ b/lib/private/User/Manager.php @@ -33,10 +33,12 @@ namespace OC\User; use OC\Hooks\PublicEmitter; +use OCP\AppFramework\Db\DoesNotExistException; +use OCP\IDBConnection; use OCP\IUser; -use OCP\IUserBackend; use OCP\IUserManager; use OCP\IConfig; +use OCP\UserInterface; /** * Class Manager @@ -68,11 +70,16 @@ class Manager extends PublicEmitter implements IUserManager { */ private $config; + /** @var AccountMapper */ + private $accountMapper; + /** * @param \OCP\IConfig $config + * @param IDBConnection $connection */ - public function __construct(IConfig $config = null) { + public function __construct(IConfig $config, AccountMapper $accountMapper) { $this->config = $config; + $this->accountMapper = $accountMapper; $cachedUsers = &$this->cachedUsers; $this->listen('\OC\User', 'postDelete', function ($user) use (&$cachedUsers) { /** @var \OC\User\User $user */ @@ -85,7 +92,7 @@ public function __construct(IConfig $config = null) { * @return \OCP\UserInterface[] */ public function getBackends() { - return $this->backends; + return array_values($this->backends); } /** @@ -94,7 +101,7 @@ public function getBackends() { * @param \OCP\UserInterface $backend */ public function registerBackend($backend) { - $this->backends[] = $backend; + $this->backends[get_class($backend)] = $backend; } /** @@ -104,9 +111,7 @@ public function registerBackend($backend) { */ public function removeBackend($backend) { $this->cachedUsers = []; - if (($i = array_search($backend, $this->backends)) !== false) { - unset($this->backends[$i]); - } + unset($this->backends[get_class($backend)]); } /** @@ -127,40 +132,32 @@ public function get($uid) { if (isset($this->cachedUsers[$uid])) { //check the cache first to prevent having to loop over the backends return $this->cachedUsers[$uid]; } - foreach ($this->backends as $backend) { - if ($backend->userExists($uid)) { - return $this->getUserObject($uid, $backend); + try { + $account = $this->accountMapper->getByUid($uid); + if (is_null($account)) { + return null; } + return $this->getUserObject($account); + } catch (DoesNotExistException $ex) { + return null; } - return null; } /** * get or construct the user object * - * @param string $uid - * @param \OCP\UserInterface $backend + * @param Account $account * @param bool $cacheUser If false the newly created user object will not be cached * @return \OC\User\User */ - protected function getUserObject($uid, $backend, $cacheUser = true) { - if (isset($this->cachedUsers[$uid])) { - return $this->cachedUsers[$uid]; - } - - if (method_exists($backend, 'loginName2UserName')) { - $loginName = $backend->loginName2UserName($uid); - if ($loginName !== false) { - $uid = $loginName; - } - if (isset($this->cachedUsers[$uid])) { - return $this->cachedUsers[$uid]; - } + protected function getUserObject(Account $account, $cacheUser = true) { + if (isset($this->cachedUsers[$account->getUserId()])) { + return $this->cachedUsers[$account->getUserId()]; } - $user = new User($uid, $backend, $this, $this->config, null, \OC::$server->getEventDispatcher() ); + $user = new User($account, $this->accountMapper, $this, $this->config, null, \OC::$server->getEventDispatcher() ); if ($cacheUser) { - $this->cachedUsers[$uid] = $user; + $this->cachedUsers[$account->getUserId()] = $user; } return $user; } @@ -186,12 +183,21 @@ public function userExists($uid) { public function checkPassword($loginName, $password) { $loginName = str_replace("\0", '', $loginName); $password = str_replace("\0", '', $password); - + + if (empty($this->backends)) { + $this->registerBackend(new Database()); + } + foreach ($this->backends as $backend) { if ($backend->implementsActions(Backend::CHECK_PASSWORD)) { $uid = $backend->checkPassword($loginName, $password); if ($uid !== false) { - return $this->getUserObject($uid, $backend); + try { + $account = $this->accountMapper->getByUid($uid); + } catch(DoesNotExistException $ex) { + $account = $this->newAccount($uid, $backend); + } + return $this->getUserObject($account); } } } @@ -209,23 +215,13 @@ public function checkPassword($loginName, $password) { * @return \OC\User\User[] */ public function search($pattern, $limit = null, $offset = null) { + $accounts = $this->accountMapper->search('user_id', $pattern, $limit, $offset); $users = []; - foreach ($this->backends as $backend) { - $backendUsers = $backend->getUsers($pattern, $limit, $offset); - if (is_array($backendUsers)) { - foreach ($backendUsers as $uid) { - $users[$uid] = $this->getUserObject($uid, $backend); - } - } + foreach ($accounts as $account) { + $user = $this->getUserObject($account); + $users[$user->getUID()] = $user; } - uasort($users, function ($a, $b) { - /** - * @var \OC\User\User $a - * @var \OC\User\User $b - */ - return strcmp($a->getUID(), $b->getUID()); - }); return $users; } @@ -238,24 +234,10 @@ public function search($pattern, $limit = null, $offset = null) { * @return \OC\User\User[] */ public function searchDisplayName($pattern, $limit = null, $offset = null) { - $users = []; - foreach ($this->backends as $backend) { - $backendUsers = $backend->getDisplayNames($pattern, $limit, $offset); - if (is_array($backendUsers)) { - foreach ($backendUsers as $uid => $displayName) { - $users[] = $this->getUserObject($uid, $backend); - } - } - } - - usort($users, function ($a, $b) { - /** - * @var \OC\User\User $a - * @var \OC\User\User $b - */ - return strcmp($a->getDisplayName(), $b->getDisplayName()); - }); - return $users; + $accounts = $this->accountMapper->search('user_id', $pattern, $limit, $offset); + return array_map(function(Account $account) { + return $this->getUserObject($account); + }, $accounts); } /** @@ -291,10 +273,14 @@ public function createUser($uid, $password) { } $this->emit('\OC\User', 'preCreateUser', [$uid, $password]); + if (empty($this->backends)) { + $this->registerBackend(new Database()); + } foreach ($this->backends as $backend) { if ($backend->implementsActions(Backend::CREATE_USER)) { $backend->createUser($uid, $password); - $user = $this->getUserObject($uid, $backend); + $account = $this->newAccount($uid, $backend); + $user = $this->getUserObject($account); $this->emit('\OC\User', 'postCreateUser', [$user, $password]); return $user; } @@ -312,27 +298,9 @@ public function createUser($uid, $password) { */ public function countUsers($hasLoggedIn = false) { if ($hasLoggedIn) { - return $this->countSeenUsers(); + return $this->accountMapper->getUserCount($hasLoggedIn); } - $userCountStatistics = []; - foreach ($this->backends as $backend) { - if ($backend->implementsActions(Backend::COUNT_USERS)) { - $backendUsers = $backend->countUsers(); - if($backendUsers !== false) { - if($backend instanceof IUserBackend) { - $name = $backend->getBackendName(); - } else { - $name = get_class($backend); - } - if(isset($userCountStatistics[$name])) { - $userCountStatistics[$name] += $backendUsers; - } else { - $userCountStatistics[$name] = $backendUsers; - } - } - } - } - return $userCountStatistics; + return $this->accountMapper->getUserCountPerBackend($hasLoggedIn); } /** @@ -346,28 +314,10 @@ public function countUsers($hasLoggedIn = false) { * @since 9.0.0 */ public function callForAllUsers(\Closure $callback, $search = '', $onlySeen = false) { - if ($onlySeen) { - $this->callForSeenUsers($callback); - } else { - foreach ($this->getBackends() as $backend) { - $limit = 500; - $offset = 0; - do { - $users = $backend->getUsers($search, $limit, $offset); - foreach ($users as $uid) { - if (!$backend->userExists($uid)) { - continue; - } - $user = $this->getUserObject($uid, $backend, false); - $return = $callback($user); - if ($return === false) { - break; - } - } - $offset += $limit; - } while (count($users) >= $limit); - } - } + $this->accountMapper->callForAllUsers(function (Account $account) use ($callback) { + $user = $this->getUserObject($account); + return $callback($user); + }, $search, $onlySeen); } /** @@ -377,94 +327,54 @@ public function callForAllUsers(\Closure $callback, $search = '', $onlySeen = fa * @since 10.0 */ public function countSeenUsers() { - $queryBuilder = \OC::$server->getDatabaseConnection()->getQueryBuilder(); - $queryBuilder->select($queryBuilder->createFunction('COUNT(*)')) - ->from('preferences') - ->where($queryBuilder->expr()->eq( - 'appid', $queryBuilder->createNamedParameter('login')) - ) - ->andWhere($queryBuilder->expr()->eq( - 'configkey', $queryBuilder->createNamedParameter('lastLogin')) - ) - ->andWhere($queryBuilder->expr()->isNotNull('configvalue') - ); - - $query = $queryBuilder->execute(); - return (int)$query->fetchColumn(); + return $this->accountMapper->getUserCount(true); } /** * @param \Closure $callback - * @param string $search * @since 10.0 */ public function callForSeenUsers (\Closure $callback) { - $limit = 1000; - $offset = 0; - do { - $userIds = $this->getSeenUserIds($limit, $offset); - $offset += $limit; - foreach ($userIds as $userId) { - foreach ($this->backends as $backend) { - if ($backend->userExists($userId)) { - $user = $this->getUserObject($userId, $backend, false); - $return = $callback($user); - if ($return === false) { - return; - } - } - } - } - } while (count($userIds) >= $limit); + $this->callForAllUsers($callback, '', true); } - /** - * Getting all userIds that have a listLogin value requires checking the - * value in php because on oracle you cannot use a clob in a where clause, - * preventing us from doing a not null or length(value) > 0 check. - * - * @param int $limit - * @param int $offset - * @return string[] with user ids - */ - private function getSeenUserIds($limit = null, $offset = null) { - $queryBuilder = \OC::$server->getDatabaseConnection()->getQueryBuilder(); - $queryBuilder->select(['userid']) - ->from('preferences') - ->where($queryBuilder->expr()->eq( - 'appid', $queryBuilder->createNamedParameter('login')) - ) - ->andWhere($queryBuilder->expr()->eq( - 'configkey', $queryBuilder->createNamedParameter('lastLogin')) - ) - ->andWhere($queryBuilder->expr()->isNotNull('configvalue') - ); - - if ($limit !== null) { - $queryBuilder->setMaxResults($limit); - } - if ($offset !== null) { - $queryBuilder->setFirstResult($offset); - } - $query = $queryBuilder->execute(); - $result = []; - - while ($row = $query->fetch()) { - $result[] = $row['userid']; - } - - return $result; - } /** * @param string $email * @return IUser[] * @since 9.1.0 */ public function getByEmail($email) { - $userIds = $this->config->getUsersForUserValue('settings', 'email', $email); + $accounts = $this->accountMapper->getByEmail($email); + return array_map(function(Account $account) { + return $this->getUserObject($account); + }, $accounts); + } - return array_map(function($uid) { - return $this->get($uid); - }, $userIds); + /** + * @param string $uid + * @param UserInterface $backend + * @return Account|\OCP\AppFramework\Db\Entity + */ + private function newAccount($uid, $backend) { + $account = new Account(); + $account->setUserId($uid); + $account->setBackend(get_class($backend)); + $account->setState(Account::STATE_ENABLED); + $account->setLastLogin(0); + if ($backend->implementsActions(Backend::GET_DISPLAYNAME)) { + $account->setDisplayName($backend->getDisplayName($uid)); + } + if ($backend->implementsActions(Backend::GET_HOME)) { + $account->setHome($backend->getHome($uid)); + } + $account = $this->accountMapper->insert($account); + return $account; + } + + public function getBackend($backendClass) { + if (isset($this->backends[$backendClass])) { + return $this->backends[$backendClass]; + } + return null; } } diff --git a/lib/private/User/Session.php b/lib/private/User/Session.php index 7a0a0f2776ef..8159dff57ef3 100644 --- a/lib/private/User/Session.php +++ b/lib/private/User/Session.php @@ -201,7 +201,6 @@ public function getUser() { if (is_null($this->activeUser)) { return null; } - $this->validateSession(); } return $this->activeUser; } @@ -212,7 +211,11 @@ public function getUser() { * - For token-authenticated clients, the token validity is checked * - For browsers, the session token validity is checked */ - protected function validateSession() { + public function validateSession() { + if (!$this->getUser()) { + return; + } + $token = null; $appPassword = $this->session->get('app_password'); @@ -382,7 +385,7 @@ public function isTokenPassword($password) { } } - protected function prepareUserLogin($firstTimeLogin) { + protected function prepareUserLogin($firstTimeLogin = false) { // TODO: mock/inject/use non-static // Refresh the token \OC::$server->getCsrfTokenManager()->refreshToken(); diff --git a/lib/private/User/User.php b/lib/private/User/User.php index 960f70d82b09..40b9272cffdf 100644 --- a/lib/private/User/User.php +++ b/lib/private/User/User.php @@ -38,33 +38,19 @@ use OCP\IURLGenerator; use OCP\IUser; use OCP\IConfig; -use OCP\UserInterface; -use \OCP\IUserBackend; +use OCP\IUserBackend; +use OCP\User\IChangePasswordBackend; use Symfony\Component\EventDispatcher\EventDispatcher; use Symfony\Component\EventDispatcher\GenericEvent; class User implements IUser { - /** @var string $uid */ - private $uid; - /** @var string $displayName */ - private $displayName; - - /** @var UserInterface $backend */ - private $backend; - - /** @var bool $enabled */ - private $enabled; + /** @var Account */ + private $account; /** @var Emitter|Manager $emitter */ private $emitter; - /** @var string $home */ - private $home; - - /** @var int $lastLogin */ - private $lastLogin; - /** @var \OCP\IConfig $config */ private $config; @@ -77,19 +63,24 @@ class User implements IUser { /** @var EventDispatcher */ private $eventDispatcher; + /** @var AccountMapper */ + private $mapper; + /** - * @param string $uid - * @param UserInterface $backend - * @param \OC\Hooks\Emitter $emitter + * User constructor. + * + * @param Account $account + * @param AccountMapper $mapper + * @param null $emitter * @param IConfig|null $config - * @param IURLGenerator $urlGenerator - * @param EventDispatcher $eventDispatcher + * @param null $urlGenerator + * @param EventDispatcher|null $eventDispatcher */ - public function __construct($uid, $backend, $emitter = null, IConfig $config = null, + public function __construct(Account $account, AccountMapper $mapper, $emitter = null, IConfig $config = null, $urlGenerator = null, EventDispatcher $eventDispatcher = null ) { - $this->uid = $uid; - $this->backend = $backend; + $this->account = $account; + $this->mapper = $mapper; $this->emitter = $emitter; $this->eventDispatcher = $eventDispatcher; if(is_null($config)) { @@ -97,9 +88,6 @@ public function __construct($uid, $backend, $emitter = null, IConfig $config = n } $this->config = $config; $this->urlGenerator = $urlGenerator; - $enabled = $this->config->getUserValue($uid, 'core', 'enabled', 'true'); - $this->enabled = ($enabled === 'true'); - $this->lastLogin = $this->config->getUserValue($uid, 'login', 'lastLogin', 0); if (is_null($this->urlGenerator)) { $this->urlGenerator = \OC::$server->getURLGenerator(); } @@ -111,7 +99,7 @@ public function __construct($uid, $backend, $emitter = null, IConfig $config = n * @return string */ public function getUID() { - return $this->uid; + return $this->account->getUserId(); } /** @@ -120,23 +108,11 @@ public function getUID() { * @return string */ public function getDisplayName() { - if (!isset($this->displayName)) { - $displayName = ''; - if ($this->backend and $this->backend->implementsActions(Backend::GET_DISPLAYNAME)) { - // get display name and strip whitespace from the beginning and end of it - $backendDisplayName = $this->backend->getDisplayName($this->uid); - if (is_string($backendDisplayName)) { - $displayName = trim($backendDisplayName); - } - } - - if (!empty($displayName)) { - $this->displayName = $displayName; - } else { - $this->displayName = $this->uid; - } + $displayName = $this->account->getDisplayName(); + if (empty($displayName)) { + $displayName = $this->getUID(); } - return $this->displayName; + return $displayName; } /** @@ -146,17 +122,18 @@ public function getDisplayName() { * @return bool */ public function setDisplayName($displayName) { + if (!$this->canChangeDisplayName()) { + return false; + } $displayName = trim($displayName); - if ($this->backend->implementsActions(Backend::SET_DISPLAYNAME) && !empty($displayName)) { - $result = $this->backend->setDisplayName($this->uid, $displayName); - if ($result) { - $this->displayName = $displayName; - $this->triggerChange('displayName', $displayName); - } - return $result !== false; - } else { + if ($displayName === $this->account->getDisplayName()) { return false; } + $this->account->setDisplayName($displayName); + $this->mapper->update($this->account); + $this->triggerChange('displayName', $displayName); + + return true; } /** @@ -167,12 +144,12 @@ public function setDisplayName($displayName) { * @since 9.0.0 */ public function setEMailAddress($mailAddress) { - if(is_null($mailAddress) || $mailAddress === '') { - $this->config->deleteUserValue($this->uid, 'settings', 'email'); - } else { - $this->config->setUserValue($this->uid, 'settings', 'email', $mailAddress); + $mailAddress = trim($mailAddress); + if ($mailAddress === $this->account->getEmail()) { + return; } - $this->config->deleteUserValue($this->getUID(), 'owncloud', 'lostpassword'); + $this->account->setEmail($mailAddress); + $this->mapper->update($this->account); $this->triggerChange('eMailAddress', $mailAddress); } @@ -183,18 +160,16 @@ public function setEMailAddress($mailAddress) { * @return int */ public function getLastLogin() { - return $this->lastLogin; + return (int)$this->account->getLastLogin(); } /** * updates the timestamp of the most recent login of this user */ public function updateLastLoginTimestamp() { - $firstTimeLogin = ($this->lastLogin === 0); - $this->lastLogin = time(); - $this->config->setUserValue( - $this->uid, 'login', 'lastLogin', $this->lastLogin); - + $firstTimeLogin = ($this->getLastLogin() === 0); + $this->account->setLastLogin(time()); + $this->mapper->update($this->account); return $firstTimeLogin; } @@ -209,36 +184,38 @@ public function delete() { } // get the home now because it won't return it after user deletion $homePath = $this->getHome(); - $result = $this->backend->deleteUser($this->uid); - if ($result) { + $this->mapper->delete($this->account); + $bi = $this->account->getBackendInstance(); + if (!is_null($bi)) { + $bi->deleteUser($this->account->getUserId()); + } - // FIXME: Feels like an hack - suggestions? + // FIXME: Feels like an hack - suggestions? - // We have to delete the user from all groups - foreach (\OC::$server->getGroupManager()->getUserGroups($this) as $group) { - $group->removeUser($this); - } - // Delete the user's keys in preferences - \OC::$server->getConfig()->deleteAllUserValues($this->uid); - - // Delete user files in /data/ - if ($homePath !== false) { - // FIXME: this operates directly on FS, should use View instead... - // also this is not testable/mockable... - \OC_Helper::rmdirr($homePath); - } + // We have to delete the user from all groups + foreach (\OC::$server->getGroupManager()->getUserGroups($this) as $group) { + $group->removeUser($this); + } + // Delete the user's keys in preferences + \OC::$server->getConfig()->deleteAllUserValues($this->getUID()); + + // Delete user files in /data/ + if ($homePath !== false) { + // FIXME: this operates directly on FS, should use View instead... + // also this is not testable/mockable... + \OC_Helper::rmdirr($homePath); + } - // Delete the users entry in the storage table - Storage::remove('home::' . $this->uid); + // Delete the users entry in the storage table + Storage::remove('home::' . $this->getUID()); - \OC::$server->getCommentsManager()->deleteReferencesOfActor('users', $this->uid); - \OC::$server->getCommentsManager()->deleteReadMarksFromUser($this); - } + \OC::$server->getCommentsManager()->deleteReferencesOfActor('users', $this->getUID()); + \OC::$server->getCommentsManager()->deleteReadMarksFromUser($this); if ($this->emitter) { $this->emitter->emit('\OC\User', 'postDelete', [$this]); } - return !($result === false); + return true; } /** @@ -252,8 +229,10 @@ public function setPassword($password, $recoveryPassword = null) { if ($this->emitter) { $this->emitter->emit('\OC\User', 'preSetPassword', [$this, $password, $recoveryPassword]); } - if ($this->backend->implementsActions(Backend::SET_PASSWORD)) { - $result = $this->backend->setPassword($this->uid, $password); + if ($this->canChangePassword()) { + /** @var IChangePasswordBackend $backend */ + $backend = $this->account->getBackendInstance(); + $result = $backend->setPassword($this->getUID(), $password); if ($result) { if ($this->emitter) { $this->emitter->emit('\OC\User', 'postSetPassword', [$this, $password, $recoveryPassword]); @@ -272,16 +251,15 @@ public function setPassword($password, $recoveryPassword = null) { * @return string */ public function getHome() { - if (!$this->home) { - if ($this->backend->implementsActions(Backend::GET_HOME) and $home = $this->backend->getHome($this->uid)) { - $this->home = $home; - } elseif ($this->config) { - $this->home = $this->config->getSystemValue('datadirectory') . '/' . $this->uid; + $home = $this->account->getHome(); + if (!$home) { + if ($this->config) { + $home = $this->config->getSystemValue('datadirectory') . '/' . $this->getUID(); } else { - $this->home = \OC::$SERVERROOT . '/data/' . $this->uid; + $home = \OC::$SERVERROOT . '/data/' . $this->getUID(); } } - return $this->home; + return $home; } /** @@ -290,10 +268,11 @@ public function getHome() { * @return string */ public function getBackendClassName() { - if($this->backend instanceof IUserBackend) { - return $this->backend->getBackendName(); + $b = $this->account->getBackendInstance(); + if($b instanceof IUserBackend) { + return $b->getBackendName(); } - return get_class($this->backend); + return $this->account->getBackend(); } /** @@ -302,10 +281,14 @@ public function getBackendClassName() { * @return bool */ public function canChangeAvatar() { - if ($this->backend->implementsActions(Backend::PROVIDE_AVATAR)) { - return $this->backend->canChangeAvatar($this->uid); + $backend = $this->account->getBackendInstance(); + if (is_null($backend)) { + return false; } - return true; + if ($backend->implementsActions(Backend::PROVIDE_AVATAR)) { + return $backend->canChangeAvatar($this->getUID()); + } + return true; } /** @@ -314,7 +297,11 @@ public function canChangeAvatar() { * @return bool */ public function canChangePassword() { - return $this->backend->implementsActions(Backend::SET_PASSWORD); + $backend = $this->account->getBackendInstance(); + if (is_null($backend)) { + return false; + } + return $backend instanceof IChangePasswordBackend || $backend->implementsActions(Backend::SET_PASSWORD); } /** @@ -326,7 +313,11 @@ public function canChangeDisplayName() { if ($this->config->getSystemValue('allow_user_to_change_display_name') === false) { return false; } - return $this->backend->implementsActions(Backend::SET_DISPLAYNAME); + $backend = $this->account->getBackendInstance(); + if (is_null($backend)) { + return false; + } + return $backend->implementsActions(Backend::SET_DISPLAYNAME); } /** @@ -335,7 +326,7 @@ public function canChangeDisplayName() { * @return bool */ public function isEnabled() { - return $this->enabled; + return $this->account->getState() === Account::STATE_ENABLED; } /** @@ -344,9 +335,12 @@ public function isEnabled() { * @param bool $enabled */ public function setEnabled($enabled) { - $this->enabled = $enabled; - $enabled = ($enabled) ? 'true' : 'false'; - $this->config->setUserValue($this->uid, 'core', 'enabled', $enabled); + if ($enabled === true) { + $this->account->setState(Account::STATE_ENABLED); + } else { + $this->account->setState(Account::STATE_DISABLED); + } + $this->mapper->update($this->account); if ($this->eventDispatcher){ $this->eventDispatcher->dispatch(self::class . '::postSetEnabled', new GenericEvent($this)); @@ -360,7 +354,7 @@ public function setEnabled($enabled) { * @since 9.0.0 */ public function getEMailAddress() { - return $this->config->getUserValue($this->uid, 'settings', 'email', null); + return $this->account->getEmail(); } /** @@ -370,8 +364,8 @@ public function getEMailAddress() { * @since 9.0.0 */ public function getQuota() { - $quota = $this->config->getUserValue($this->uid, 'files', 'quota', 'default'); - if($quota === 'default') { + $quota = $this->account->getQuota(); + if(is_null($quota)) { $quota = $this->config->getAppValue('files', 'default_quota', 'none'); } return $quota; @@ -389,7 +383,8 @@ public function setQuota($quota) { $quota = OC_Helper::computerFileSize($quota); $quota = OC_Helper::humanFileSize($quota); } - $this->config->setUserValue($this->uid, 'files', 'quota', $quota); + $this->account->setQuota($quota); + $this->mapper->update($this->account); $this->triggerChange('quota', $quota); } @@ -406,7 +401,7 @@ public function getAvatarImage($size) { $this->avatarManager = \OC::$server->getAvatarManager(); } - $avatar = $this->avatarManager->getAvatar($this->uid); + $avatar = $this->avatarManager->getAvatar($this->getUID()); $image = $avatar->get($size); if ($image) { return $image; diff --git a/lib/private/legacy/app.php b/lib/private/legacy/app.php index 1d5be391ff5f..7455f47c5d7e 100644 --- a/lib/private/legacy/app.php +++ b/lib/private/legacy/app.php @@ -121,6 +121,13 @@ public static function loadApps($types = null) { } ob_end_clean(); + // once all authentication apps are loaded we can validate the session + if (is_null($types) || in_array('authentication', $types)) { + if (\OC::$server->getUserSession()) { + \OC::$server->getUserSession()->validateSession(); + } + } + return true; } diff --git a/lib/public/AppFramework/Db/Mapper.php b/lib/public/AppFramework/Db/Mapper.php index 8e178c10e483..8510df3212df 100644 --- a/lib/public/AppFramework/Db/Mapper.php +++ b/lib/public/AppFramework/Db/Mapper.php @@ -26,6 +26,7 @@ namespace OCP\AppFramework\Db; +use OCP\DB\QueryBuilder\IQueryBuilder; use OCP\IDBConnection; use OCP\IDb; @@ -227,7 +228,7 @@ private function getPDOType($value) { * @return \PDOStatement the database query result * @since 7.0.0 */ - protected function execute($sql, array $params=[], $limit=null, $offset=null){ + protected function execute($sql, array $params=[], $limit=null, $offset=null) { if ($this->db instanceof IDb) { $query = $this->db->prepareQuery($sql, $limit, $offset); } else { @@ -276,8 +277,13 @@ protected function execute($sql, array $params=[], $limit=null, $offset=null){ * @return array the result as row * @since 7.0.0 */ - protected function findOneQuery($sql, array $params=[], $limit=null, $offset=null){ - $stmt = $this->execute($sql, $params, $limit, $offset); + protected function findOneQuery($sql, array $params=[], $limit=null, $offset=null) { + + if ($sql instanceof IQueryBuilder) { + $stmt = $sql->execute(); + } else { + $stmt = $this->execute($sql, $params, $limit, $offset); + } $row = $stmt->fetch(); if($row === false || $row === null){ diff --git a/lib/public/IUserManager.php b/lib/public/IUserManager.php index 055893be844b..10b3f903346e 100644 --- a/lib/public/IUserManager.php +++ b/lib/public/IUserManager.php @@ -155,7 +155,6 @@ public function countSeenUsers(); /** * @param \Closure $callback - * @param string $search * @since 10.0 */ public function callForSeenUsers (\Closure $callback); diff --git a/lib/public/User/IChangePasswordBackend.php b/lib/public/User/IChangePasswordBackend.php new file mode 100644 index 000000000000..e2bff47e601a --- /dev/null +++ b/lib/public/User/IChangePasswordBackend.php @@ -0,0 +1,44 @@ + + * + * @copyright Copyright (c) 2017, ownCloud GmbH + * @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 + * + */ + + +// use OCP namespace for all classes that are considered public. +// This means that they should be used by apps instead of the internal ownCloud classes +namespace OCP\User; + +/** + * Interface IChangePasswordBackend + * + * @package OCP\User + * @since 10.0 + */ +interface IChangePasswordBackend { + + /** + * Set password + * @param string $uid The username + * @param string $password The new password + * @return bool + * @since 10.0 + */ + public function setPassword($uid, $password); +} + diff --git a/tests/Settings/Controller/UsersControllerTest.php b/tests/Settings/Controller/UsersControllerTest.php index 2bfe0be98167..80b10d46e0e5 100644 --- a/tests/Settings/Controller/UsersControllerTest.php +++ b/tests/Settings/Controller/UsersControllerTest.php @@ -727,7 +727,7 @@ public function testIndexWithBackend() { $this->container['UserManager'] ->expects($this->once()) ->method('getBackends') - ->will($this->returnValue([new \Test\Util\User\Dummy(), new \OC\User\Database()])); + ->will($this->returnValue([new \OC\User\Database()])); $this->container['UserManager'] ->expects($this->once()) ->method('clearBackends'); @@ -776,7 +776,7 @@ public function testIndexWithBackendNoUser() { $this->container['UserManager'] ->expects($this->once()) ->method('getBackends') - ->will($this->returnValue([new \Test\Util\User\Dummy(), new \OC\User\Database()])); + ->will($this->returnValue([new \OC\User\Database()])); $this->container['UserManager'] ->expects($this->once()) ->method('search') diff --git a/tests/lib/App/ManagerTest.php b/tests/lib/App/ManagerTest.php index 53fc4075dd75..2c10ba38bb7a 100644 --- a/tests/lib/App/ManagerTest.php +++ b/tests/lib/App/ManagerTest.php @@ -10,7 +10,8 @@ namespace Test\App; use OC\Group\Group; -use OC\User\User; +use OCP\IUser; +use Symfony\Component\EventDispatcher\EventDispatcherInterface; use Test\TestCase; /** @@ -61,25 +62,25 @@ protected function getAppConfig() { return $config; } - /** @var \OCP\IUserSession */ + /** @var \OCP\IUserSession | \PHPUnit_Framework_MockObject_MockObject */ protected $userSession; - /** @var \OCP\IGroupManager */ + /** @var \OCP\IGroupManager | \PHPUnit_Framework_MockObject_MockObject */ protected $groupManager; /** @var \OCP\IAppConfig */ protected $appConfig; - /** @var \OCP\ICache */ + /** @var \OCP\ICache | \PHPUnit_Framework_MockObject_MockObject */ protected $cache; - /** @var \OCP\ICacheFactory */ + /** @var \OCP\ICacheFactory | \PHPUnit_Framework_MockObject_MockObject */ protected $cacheFactory; /** @var \OCP\App\IAppManager */ protected $manager; - /** @var \Symfony\Component\EventDispatcher\EventDispatcherInterface */ + /** @var EventDispatcherInterface | \PHPUnit_Framework_MockObject_MockObject */ protected $eventDispatcher; protected function setUp() { @@ -243,18 +244,18 @@ public function testIsInstalledEnabledForGroups() { public function testIsEnabledForUserEnabled() { $this->appConfig->setValue('test', 'enabled', 'yes'); - $user = new User('user1', null); + $user = $this->createMock(IUser::class); $this->assertTrue($this->manager->isEnabledForUser('test', $user)); } public function testIsEnabledForUserDisabled() { $this->appConfig->setValue('test', 'enabled', 'no'); - $user = new User('user1', null); + $user = $this->createMock(IUser::class); $this->assertFalse($this->manager->isEnabledForUser('test', $user)); } public function testIsEnabledForUserEnabledForGroup() { - $user = new User('user1', null); + $user = $this->createMock(IUser::class); $this->groupManager->expects($this->once()) ->method('getUserGroupIds') ->with($user) @@ -265,7 +266,7 @@ public function testIsEnabledForUserEnabledForGroup() { } public function testIsEnabledForUserDisabledForGroup() { - $user = new User('user1', null); + $user = $this->createMock(IUser::class); $this->groupManager->expects($this->once()) ->method('getUserGroupIds') ->with($user) @@ -281,7 +282,7 @@ public function testIsEnabledForUserLoggedOut() { } public function testIsEnabledForUserLoggedIn() { - $user = new User('user1', null); + $user = $this->createMock(IUser::class); $this->userSession->expects($this->once()) ->method('getUser') @@ -310,7 +311,7 @@ public function testGetInstalledApps() { } public function testGetAppsForUser() { - $user = new User('user1', null); + $user = $this->createMock(IUser::class); $this->groupManager->expects($this->any()) ->method('getUserGroupIds') ->with($user) diff --git a/tests/lib/AppTest.php b/tests/lib/AppTest.php index 309d266df0f0..6c7d70d4a1cc 100644 --- a/tests/lib/AppTest.php +++ b/tests/lib/AppTest.php @@ -9,6 +9,7 @@ namespace Test; use OCP\IAppConfig; +use Test\Traits\UserTrait; /** * Class AppTest @@ -16,6 +17,7 @@ * @group DB */ class AppTest extends \Test\TestCase { + use UserTrait; const TEST_USER1 = 'user1'; const TEST_USER2 = 'user2'; @@ -392,11 +394,10 @@ function appConfigValuesProvider() { * @dataProvider appConfigValuesProvider */ public function testEnabledApps($user, $expectedApps, $forceAll) { - $userManager = \OC::$server->getUserManager(); $groupManager = \OC::$server->getGroupManager(); - $user1 = $userManager->createUser(self::TEST_USER1, self::TEST_USER1); - $user2 = $userManager->createUser(self::TEST_USER2, self::TEST_USER2); - $user3 = $userManager->createUser(self::TEST_USER3, self::TEST_USER3); + $user1 = $this->createUser(self::TEST_USER1, self::TEST_USER1); + $user2 = $this->createUser(self::TEST_USER2, self::TEST_USER2); + $user3 = $this->createUser(self::TEST_USER3, self::TEST_USER3); $group1 = $groupManager->createGroup(self::TEST_GROUP1); $group1->addUser($user1); diff --git a/tests/lib/Cache/FileCacheTest.php b/tests/lib/Cache/FileCacheTest.php index 19571fc26488..bc2fc5396f01 100644 --- a/tests/lib/Cache/FileCacheTest.php +++ b/tests/lib/Cache/FileCacheTest.php @@ -67,10 +67,11 @@ protected function setUp() { $this->datadir = $config->getSystemValue('cachedirectory', \OC::$SERVERROOT.'/data/cache'); $config->setSystemValue('cachedirectory', $datadir); - \OC_User::clearBackends(); - \OC_User::useBackend(new \Test\Util\User\Dummy()); - //login + if (\OC::$server->getUserManager()->userExists('test')) { + $user = \OC::$server->getUserManager()->get('test'); + $user->delete(); + } \OC::$server->getUserManager()->createUser('test', 'test'); $this->user = \OC_User::getUser(); diff --git a/tests/lib/Encryption/Keys/StorageTest.php b/tests/lib/Encryption/Keys/StorageTest.php index 3943e4f98bd5..274f477d9650 100644 --- a/tests/lib/Encryption/Keys/StorageTest.php +++ b/tests/lib/Encryption/Keys/StorageTest.php @@ -73,6 +73,7 @@ public function setUp() { $user = $this->createMock(IUser::class); $user->method('getUID')->willReturn('user1'); + /** @var IUserSession | \PHPUnit_Framework_MockObject_MockObject $userSession */ $userSession = $this->createMock(IUserSession::class); $userSession->method('getUser')->willReturn($user); diff --git a/tests/lib/Files/Cache/CacheTest.php b/tests/lib/Files/Cache/CacheTest.php index 9b5cc8ece48a..568d139141b4 100644 --- a/tests/lib/Files/Cache/CacheTest.php +++ b/tests/lib/Files/Cache/CacheTest.php @@ -322,7 +322,7 @@ function testSearchByTag() { $userId = $this->getUniqueId('user'); \OC::$server->getUserManager()->createUser($userId, $userId); $this->loginAsUser($userId); - $user = new \OC\User\User($userId, null); +// $user = new \OC\User\User($userId, null); $file1 = 'folder'; $file2 = 'folder/foobar'; diff --git a/tests/lib/Files/Config/UserMountCacheTest.php b/tests/lib/Files/Config/UserMountCacheTest.php index f262b3d3f196..a267ad98a858 100644 --- a/tests/lib/Files/Config/UserMountCacheTest.php +++ b/tests/lib/Files/Config/UserMountCacheTest.php @@ -9,14 +9,17 @@ namespace Test\Files\Config; use OC\DB\QueryBuilder\Literal; +use OC\Files\Config\UserMountCache; use OC\Files\Mount\MountPoint; use OC\Log; +use OC\User\Account; +use OC\User\AccountMapper; use OC\User\Manager; use OCP\Files\Config\ICachedMountInfo; +use OCP\IConfig; use OCP\IDBConnection; use OCP\IUserManager; use Test\TestCase; -use Test\Util\User\Dummy; /** * @group DB @@ -33,7 +36,7 @@ class UserMountCacheTest extends TestCase { private $userManager; /** - * @var \OC\Files\Config\UserMountCache + * @var UserMountCache */ private $cache; @@ -42,13 +45,32 @@ class UserMountCacheTest extends TestCase { public function setUp() { $this->fileIds = []; $this->connection = \OC::$server->getDatabaseConnection(); - $this->userManager = new Manager(null); - $userBackend = new Dummy(); - $userBackend->createUser('u1', ''); - $userBackend->createUser('u2', ''); - $userBackend->createUser('u3', ''); - $this->userManager->registerBackend($userBackend); - $this->cache = new \OC\Files\Config\UserMountCache($this->connection, $this->userManager, $this->createMock('\OC\Log')); + /** @var IConfig $config */ + $config = $this->createMock(IConfig::class); + /** @var AccountMapper | \PHPUnit_Framework_MockObject_MockObject $accountMapper */ + $accountMapper = $this->createMock(AccountMapper::class); + $a1 = new Account(); + $a1->setId(1); + $a1->setUserId('u1'); + $a2 = new Account(); + $a2->setId(2); + $a2->setUserId('u2'); + $a3 = new Account(); + $a3->setId(3); + $a3->setUserId('u3'); + + $accountMapper->expects($this->any())->method('getByUid')->willReturnMap([ + ['u1', $a1], + ['u2', $a2], + ['u3', $a3], + ]); + $this->userManager = new Manager($config, $accountMapper); + /** @var Log $log */ + $log = $this->createMock(Log::class); + $this->cache = new UserMountCache($this->connection, $this->userManager, $log); + + // hookup listener + $this->userManager->listen('\OC\User', 'postDelete', [$this->cache, 'removeUserMounts']); } public function tearDown() { diff --git a/tests/lib/Files/EtagTest.php b/tests/lib/Files/EtagTest.php index 7bcf3098665c..b482822c55f3 100644 --- a/tests/lib/Files/EtagTest.php +++ b/tests/lib/Files/EtagTest.php @@ -9,7 +9,9 @@ namespace Test\Files; use OC\Files\Filesystem; +use OC\Files\Utils\Scanner; use OCP\Share; +use Test\Traits\UserTrait; /** * Class EtagTest @@ -19,15 +21,13 @@ * @package Test\Files */ class EtagTest extends \Test\TestCase { + + use UserTrait; + private $datadir; private $tmpDir; - /** - * @var \Test\Util\User\Dummy $userBackend - */ - private $userBackend; - protected function setUp() { parent::setUp(); @@ -41,9 +41,6 @@ protected function setUp() { $this->datadir = $config->getSystemValue('datadirectory'); $this->tmpDir = \OC::$server->getTempManager()->getTemporaryFolder(); $config->setSystemValue('datadirectory', $this->tmpDir); - - $this->userBackend = new \Test\Util\User\Dummy(); - \OC_User::useBackend($this->userBackend); } protected function tearDown() { @@ -55,7 +52,7 @@ protected function tearDown() { public function testNewUser() { $user1 = $this->getUniqueID('user_'); - $this->userBackend->createUser($user1, ''); + $this->createUser($user1, $user1); $this->loginAsUser($user1); Filesystem::mkdir('/folder'); @@ -67,7 +64,7 @@ public function testNewUser() { $files = ['/foo.txt', '/folder/bar.txt', '/folder/subfolder', '/folder/subfolder/qwerty.txt']; $originalEtags = $this->getEtags($files); - $scanner = new \OC\Files\Utils\Scanner($user1, \OC::$server->getDatabaseConnection(), \OC::$server->getLogger()); + $scanner = new Scanner($user1, \OC::$server->getDatabaseConnection(), \OC::$server->getLogger()); $scanner->backgroundScan('/'); $newEtags = $this->getEtags($files); @@ -79,6 +76,7 @@ public function testNewUser() { /** * @param string[] $files + * @return array */ private function getEtags($files) { $etags = []; diff --git a/tests/lib/Files/External/Service/UserGlobalStoragesServiceTest.php b/tests/lib/Files/External/Service/UserGlobalStoragesServiceTest.php index 2f4d3f475db1..85a8435e13d9 100644 --- a/tests/lib/Files/External/Service/UserGlobalStoragesServiceTest.php +++ b/tests/lib/Files/External/Service/UserGlobalStoragesServiceTest.php @@ -64,7 +64,7 @@ public function setUp() { $this->globalStoragesService = $this->service; - $this->user = new \OC\User\User(self::USER_ID, null); + $this->user = $this->createUser(self::USER_ID, self::USER_ID); /** @var \OCP\IUserSession|\PHPUnit_Framework_MockObject_MockObject $userSession */ $userSession = $this->createMock('\OCP\IUserSession'); $userSession diff --git a/tests/lib/Files/FilesystemTest.php b/tests/lib/Files/FilesystemTest.php index 48963543a75b..cb853e17781e 100644 --- a/tests/lib/Files/FilesystemTest.php +++ b/tests/lib/Files/FilesystemTest.php @@ -22,14 +22,19 @@ namespace Test\Files; +use OC\Files\Filesystem; use OC\Files\Mount\MountPoint; use OC\Files\Storage\Temporary; +use OC\Files\View; use OC\User\NoUserException; use OCP\Files\Config\IMountProvider; use OCP\Files\Storage\IStorageFactory; use OCP\IUser; +use Test\TestCase; +use Test\Traits\UserTrait; class DummyMountProvider implements IMountProvider { + private $mounts = []; /** @@ -58,7 +63,9 @@ public function getMountsForUser(IUser $user, IStorageFactory $loader) { * * @package Test\Files */ -class FilesystemTest extends \Test\TestCase { +class FilesystemTest extends TestCase { + + use UserTrait; const TEST_FILESYSTEM_USER1 = "test-filesystem-user1"; const TEST_FILESYSTEM_USER2 = "test-filesystem-user1"; @@ -79,11 +86,8 @@ private function getStorageData() { protected function setUp() { parent::setUp(); - \OC_User::clearBackends(); - $userBackend = new \Test\Util\User\Dummy(); - $userBackend->createUser(self::TEST_FILESYSTEM_USER1, self::TEST_FILESYSTEM_USER1); - $userBackend->createUser(self::TEST_FILESYSTEM_USER2, self::TEST_FILESYSTEM_USER2); - \OC::$server->getUserManager()->registerBackend($userBackend); + $this->createUser(self::TEST_FILESYSTEM_USER1, self::TEST_FILESYSTEM_USER1); + $this->createUser(self::TEST_FILESYSTEM_USER2, self::TEST_FILESYSTEM_USER2); $this->loginAsUser(); } @@ -99,20 +103,20 @@ protected function tearDown() { } public function testMount() { - \OC\Files\Filesystem::mount('\OC\Files\Storage\Local', self::getStorageData(), '/'); - $this->assertEquals('/', \OC\Files\Filesystem::getMountPoint('/')); - $this->assertEquals('/', \OC\Files\Filesystem::getMountPoint('/some/folder')); - list(, $internalPath) = \OC\Files\Filesystem::resolvePath('/'); + Filesystem::mount('\OC\Files\Storage\Local', self::getStorageData(), '/'); + $this->assertEquals('/', Filesystem::getMountPoint('/')); + $this->assertEquals('/', Filesystem::getMountPoint('/some/folder')); + list(, $internalPath) = Filesystem::resolvePath('/'); $this->assertEquals('', $internalPath); - list(, $internalPath) = \OC\Files\Filesystem::resolvePath('/some/folder'); + list(, $internalPath) = Filesystem::resolvePath('/some/folder'); $this->assertEquals('some/folder', $internalPath); - \OC\Files\Filesystem::mount('\OC\Files\Storage\Local', self::getStorageData(), '/some'); - $this->assertEquals('/', \OC\Files\Filesystem::getMountPoint('/')); - $this->assertEquals('/some/', \OC\Files\Filesystem::getMountPoint('/some/folder')); - $this->assertEquals('/some/', \OC\Files\Filesystem::getMountPoint('/some/')); - $this->assertEquals('/some/', \OC\Files\Filesystem::getMountPoint('/some')); - list(, $internalPath) = \OC\Files\Filesystem::resolvePath('/some/folder'); + Filesystem::mount('\OC\Files\Storage\Local', self::getStorageData(), '/some'); + $this->assertEquals('/', Filesystem::getMountPoint('/')); + $this->assertEquals('/some/', Filesystem::getMountPoint('/some/folder')); + $this->assertEquals('/some/', Filesystem::getMountPoint('/some/')); + $this->assertEquals('/some/', Filesystem::getMountPoint('/some')); + list(, $internalPath) = Filesystem::resolvePath('/some/folder'); $this->assertEquals('folder', $internalPath); } @@ -190,7 +194,7 @@ public function normalizePathData() { * @dataProvider normalizePathData */ public function testNormalizePath($expected, $path, $stripTrailingSlash = true) { - $this->assertEquals($expected, \OC\Files\Filesystem::normalizePath($path, $stripTrailingSlash)); + $this->assertEquals($expected, Filesystem::normalizePath($path, $stripTrailingSlash)); } public function normalizePathKeepUnicodeData() { @@ -208,15 +212,15 @@ public function normalizePathKeepUnicodeData() { * @dataProvider normalizePathKeepUnicodeData */ public function testNormalizePathKeepUnicode($expected, $path, $keepUnicode = false) { - $this->assertEquals($expected, \OC\Files\Filesystem::normalizePath($path, true, false, $keepUnicode)); + $this->assertEquals($expected, Filesystem::normalizePath($path, true, false, $keepUnicode)); } public function testNormalizePathKeepUnicodeCache() { $nfdName = 'ümlaut'; $nfcName = 'ümlaut'; // call in succession due to cache - $this->assertEquals('/' . $nfcName, \OC\Files\Filesystem::normalizePath($nfdName, true, false, false)); - $this->assertEquals('/' . $nfdName, \OC\Files\Filesystem::normalizePath($nfdName, true, false, true)); + $this->assertEquals('/' . $nfcName, Filesystem::normalizePath($nfdName, true, false, false)); + $this->assertEquals('/' . $nfdName, Filesystem::normalizePath($nfdName, true, false, true)); } public function isValidPathData() { @@ -249,7 +253,7 @@ public function isValidPathData() { * @dataProvider isValidPathData */ public function testIsValidPath($path, $expected) { - $this->assertSame($expected, \OC\Files\Filesystem::isValidPath($path)); + $this->assertSame($expected, Filesystem::isValidPath($path)); } public function isFileBlacklistedData() { @@ -271,7 +275,7 @@ public function isFileBlacklistedData() { * @dataProvider isFileBlacklistedData */ public function testIsFileBlacklisted($path, $expected) { - $this->assertSame($expected, \OC\Files\Filesystem::isForbiddenFileOrDir($path)); + $this->assertSame($expected, Filesystem::isForbiddenFileOrDir($path)); } public function isExcludedData() { @@ -294,7 +298,7 @@ public function isExcludedData() { * @dataProvider isExcludedData */ public function testIsExcluded($path, $expected) { - $this->assertSame($expected, \OC\Files\Filesystem::isForbiddenFileOrDir($path, ['.snapshot'])); + $this->assertSame($expected, Filesystem::isForbiddenFileOrDir($path, ['.snapshot'])); } public function testNormalizePathUTF8() { @@ -302,34 +306,32 @@ public function testNormalizePathUTF8() { $this->markTestSkipped('UTF8 normalizer Patchwork was not found'); } - $this->assertEquals("/foo/bar\xC3\xBC", \OC\Files\Filesystem::normalizePath("/foo/baru\xCC\x88")); - $this->assertEquals("/foo/bar\xC3\xBC", \OC\Files\Filesystem::normalizePath("\\foo\\baru\xCC\x88")); + $this->assertEquals("/foo/bar\xC3\xBC", Filesystem::normalizePath("/foo/baru\xCC\x88")); + $this->assertEquals("/foo/bar\xC3\xBC", Filesystem::normalizePath("\\foo\\baru\xCC\x88")); } public function testHooks() { - if (\OC\Files\Filesystem::getView()) { + if (Filesystem::getView()) { $user = \OC_User::getUser(); } else { $user = self::TEST_FILESYSTEM_USER1; - $backend = new \Test\Util\User\Dummy(); - \OC_User::useBackend($backend); - $backend->createUser($user, $user); + $this->createUser($user, $user); $userObj = \OC::$server->getUserManager()->get($user); \OC::$server->getUserSession()->setUser($userObj); - \OC\Files\Filesystem::init($user, '/' . $user . '/files'); + Filesystem::init($user, '/' . $user . '/files'); } \OC_Hook::clear('OC_Filesystem'); \OC_Hook::connect('OC_Filesystem', 'post_write', $this, 'dummyHook'); - \OC\Files\Filesystem::mount('OC\Files\Storage\Temporary', [], '/'); + Filesystem::mount('OC\Files\Storage\Temporary', [], '/'); - $rootView = new \OC\Files\View(''); + $rootView = new View(''); $rootView->mkdir('/' . $user); $rootView->mkdir('/' . $user . '/files'); // \OC\Files\Filesystem::file_put_contents('/foo', 'foo'); - \OC\Files\Filesystem::mkdir('/bar'); + Filesystem::mkdir('/bar'); // \OC\Files\Filesystem::file_put_contents('/bar//foo', 'foo'); $tmpFile = \OC::$server->getTempManager()->getTemporaryFile(); @@ -346,25 +348,25 @@ public function testHooks() { public function testLocalMountWhenUserDoesNotExist() { $userId = $this->getUniqueID('user_'); - \OC\Files\Filesystem::initMountPoints($userId); + Filesystem::initMountPoints($userId); } /** * @expectedException \OC\User\NoUserException */ public function testNullUserThrows() { - \OC\Files\Filesystem::initMountPoints(null); + Filesystem::initMountPoints(null); } public function testNullUserThrowsTwice() { $thrown = 0; try { - \OC\Files\Filesystem::initMountPoints(null); + Filesystem::initMountPoints(null); } catch (NoUserException $e) { $thrown++; } try { - \OC\Files\Filesystem::initMountPoints(null); + Filesystem::initMountPoints(null); } catch (NoUserException $e) { $thrown++; } @@ -379,13 +381,13 @@ public function testLocalMountWhenUserDoesNotExistTwice() { $userId = $this->getUniqueID('user_'); try { - \OC\Files\Filesystem::initMountPoints($userId); + Filesystem::initMountPoints($userId); } catch (NoUserException $e) { $thrown++; } try { - \OC\Files\Filesystem::initMountPoints($userId); + Filesystem::initMountPoints($userId); } catch (NoUserException $e) { $thrown++; } @@ -396,25 +398,12 @@ public function testLocalMountWhenUserDoesNotExistTwice() { public function testUserNameCasing() { $this->logout(); $userId = $this->getUniqueID('user_'); + $this->createUser($userId); - \OC_User::clearBackends(); - // needed for loginName2UserName mapping - $userBackend = $this->createMock(\OC\User\Database::class); - \OC::$server->getUserManager()->registerBackend($userBackend); - - $userBackend->expects($this->once()) - ->method('userExists') - ->with(strtoupper($userId)) - ->will($this->returnValue(true)); - $userBackend->expects($this->once()) - ->method('loginName2UserName') - ->with(strtoupper($userId)) - ->will($this->returnValue($userId)); - - $view = new \OC\Files\View(); + $view = new View(); $this->assertFalse($view->file_exists('/' . $userId)); - \OC\Files\Filesystem::initMountPoints(strtoupper($userId)); + Filesystem::initMountPoints(strtoupper($userId)); list($storage1, $path1) = $view->resolvePath('/' . $userId); list($storage2, $path2) = $view->resolvePath('/' . strtoupper($userId)); @@ -434,9 +423,9 @@ public function testHomeMount() { \OC::$server->getUserManager()->createUser($userId, $userId); - \OC\Files\Filesystem::initMountPoints($userId); + Filesystem::initMountPoints($userId); - $homeMount = \OC\Files\Filesystem::getStorage('/' . $userId . '/'); + $homeMount = Filesystem::getStorage('/' . $userId . '/'); $this->assertTrue($homeMount->instanceOfStorage('\OCP\Files\IHomeStorage')); if (getenv('RUN_OBJECTSTORE_TESTS')) { @@ -453,7 +442,7 @@ public function testHomeMount() { public function dummyHook($arguments) { $path = $arguments['path']; - $this->assertEquals($path, \OC\Files\Filesystem::normalizePath($path)); //the path passed to the hook should already be normalized + $this->assertEquals($path, Filesystem::normalizePath($path)); //the path passed to the hook should already be normalized } /** @@ -467,13 +456,13 @@ public function testMountDefaultCacheDir() { $config->setSystemValue('cache_path', ''); \OC::$server->getUserManager()->createUser($userId, $userId); - \OC\Files\Filesystem::initMountPoints($userId); + Filesystem::initMountPoints($userId); $this->assertEquals( '/' . $userId . '/', - \OC\Files\Filesystem::getMountPoint('/' . $userId . '/cache') + Filesystem::getMountPoint('/' . $userId . '/cache') ); - list($storage, $internalPath) = \OC\Files\Filesystem::resolvePath('/' . $userId . '/cache'); + list($storage, $internalPath) = Filesystem::resolvePath('/' . $userId . '/cache'); $this->assertTrue($storage->instanceOfStorage('\OCP\Files\IHomeStorage')); $this->assertEquals('cache', $internalPath); $user = \OC::$server->getUserManager()->get($userId); @@ -496,13 +485,13 @@ public function testMountExternalCacheDir() { $config->setSystemValue('cache_path', $cachePath); \OC::$server->getUserManager()->createUser($userId, $userId); - \OC\Files\Filesystem::initMountPoints($userId); + Filesystem::initMountPoints($userId); $this->assertEquals( '/' . $userId . '/cache/', - \OC\Files\Filesystem::getMountPoint('/' . $userId . '/cache') + Filesystem::getMountPoint('/' . $userId . '/cache') ); - list($storage, $internalPath) = \OC\Files\Filesystem::resolvePath('/' . $userId . '/cache'); + list($storage, $internalPath) = Filesystem::resolvePath('/' . $userId . '/cache'); $this->assertTrue($storage->instanceOfStorage('\OC\Files\Storage\Local')); $this->assertEquals('', $internalPath); $user = \OC::$server->getUserManager()->get($userId); @@ -512,11 +501,11 @@ public function testMountExternalCacheDir() { } public function testRegisterMountProviderAfterSetup() { - \OC\Files\Filesystem::initMountPoints(self::TEST_FILESYSTEM_USER2); - $this->assertEquals('/', \OC\Files\Filesystem::getMountPoint('/foo/bar')); + Filesystem::initMountPoints(self::TEST_FILESYSTEM_USER2); + $this->assertEquals('/', Filesystem::getMountPoint('/foo/bar')); $mount = new MountPoint(new Temporary([]), '/foo/bar'); $mountProvider = new DummyMountProvider([self::TEST_FILESYSTEM_USER2 => [$mount]]); \OC::$server->getMountProviderCollection()->registerProvider($mountProvider); - $this->assertEquals('/foo/bar/', \OC\Files\Filesystem::getMountPoint('/foo/bar')); + $this->assertEquals('/foo/bar/', Filesystem::getMountPoint('/foo/bar')); } } diff --git a/tests/lib/Files/Node/IntegrationTest.php b/tests/lib/Files/Node/IntegrationTest.php index 13a5cf058afc..31aacf1c2348 100644 --- a/tests/lib/Files/Node/IntegrationTest.php +++ b/tests/lib/Files/Node/IntegrationTest.php @@ -8,10 +8,12 @@ namespace Test\Files\Node; +use OC\Files\Filesystem; use OC\Files\Node\Root; use OC\Files\Storage\Temporary; use OC\Files\View; -use OC\User\User; +use Test\TestCase; +use Test\Traits\UserTrait; /** * Class IntegrationTest @@ -20,7 +22,9 @@ * * @package Test\Files\Node */ -class IntegrationTest extends \Test\TestCase { +class IntegrationTest extends TestCase { + use UserTrait; + /** * @var \OC\Files\Node\Root $root */ @@ -39,11 +43,11 @@ class IntegrationTest extends \Test\TestCase { protected function setUp() { parent::setUp(); - $manager = \OC\Files\Filesystem::getMountManager(); + $manager = Filesystem::getMountManager(); \OC_Hook::clear('OC_Filesystem'); - $user = new User($this->getUniqueID('user'), new \Test\Util\User\Dummy); + $user = $this->createUser($this->getUniqueID('user')); $this->loginAsUser($user->getUID()); $this->view = new View(); @@ -67,7 +71,7 @@ protected function tearDown() { public function testBasicFile() { $file = $this->root->newFile('/foo.txt'); - $this->assertCount(2, $this->root->getDirectoryListing()); + $this->assertCount(3, $this->root->getDirectoryListing()); $this->assertTrue($this->root->nodeExists('/foo.txt')); $id = $file->getId(); $this->assertInstanceOf('\OC\Files\Node\File', $file); @@ -102,7 +106,7 @@ public function testBasicFolder() { $rootListing = $this->root->getDirectoryListing(); - $this->assertEquals(2, count($rootListing)); + $this->assertEquals(3, count($rootListing)); $folder->move('/asd'); /** diff --git a/tests/lib/Files/Node/NodeTest.php b/tests/lib/Files/Node/NodeTest.php index edc1e6ad8caa..8a6f175ca183 100644 --- a/tests/lib/Files/Node/NodeTest.php +++ b/tests/lib/Files/Node/NodeTest.php @@ -9,20 +9,23 @@ namespace Test\Files\Node; use OC\Files\FileInfo; +use OCP\Constants; use OCP\Files\NotFoundException; +use OCP\IUser; +use Test\TestCase; /** * Class NodeTest * * @package Test\Files\Node */ -abstract class NodeTest extends \Test\TestCase { +abstract class NodeTest extends TestCase { protected $viewDeleteMethod = 'unlink'; protected $user; protected function setUp() { parent::setUp(); - $this->user = new \OC\User\User('', new \Test\Util\User\Dummy); + $this->user = $this->createMock(IUser::class); } protected abstract function createTestNode($root, $view, $path); @@ -56,7 +59,7 @@ public function testDelete() { $view->expects($this->once()) ->method('getFileInfo') ->with('/bar/foo') - ->will($this->returnValue($this->getFileInfo(['permissions' => \OCP\Constants::PERMISSION_ALL]))); + ->will($this->returnValue($this->getFileInfo(['permissions' => Constants::PERMISSION_ALL]))); $view->expects($this->once()) ->method($this->viewDeleteMethod) @@ -108,7 +111,7 @@ public function testDeleteHooks() { $view->expects($this->any()) ->method('getFileInfo') ->with('/bar/foo') - ->will($this->returnValue($this->getFileInfo(['permissions' => \OCP\Constants::PERMISSION_ALL, 'fileid' => 1, 'mimetype' => 'text/plain']))); + ->will($this->returnValue($this->getFileInfo(['permissions' => Constants::PERMISSION_ALL, 'fileid' => 1, 'mimetype' => 'text/plain']))); $view->expects($this->once()) ->method($this->viewDeleteMethod) @@ -142,7 +145,7 @@ public function testDeleteNotPermitted() { $view->expects($this->once()) ->method('getFileInfo') ->with('/bar/foo') - ->will($this->returnValue($this->getFileInfo(['permissions' => \OCP\Constants::PERMISSION_READ]))); + ->will($this->returnValue($this->getFileInfo(['permissions' => Constants::PERMISSION_READ]))); $node = $this->createTestNode($root, $view, '/bar/foo'); $node->delete(); @@ -375,7 +378,7 @@ public function testTouchSetMTime() { $view->expects($this->once()) ->method('getFileInfo') ->with('/bar/foo') - ->will($this->returnValue($this->getFileInfo(['permissions' => \OCP\Constants::PERMISSION_ALL]))); + ->will($this->returnValue($this->getFileInfo(['permissions' => Constants::PERMISSION_ALL]))); $node = $this->createTestNode($root, $view, '/bar/foo'); $node->touch(100); @@ -428,7 +431,7 @@ public function testTouchHooks() { $view->expects($this->any()) ->method('getFileInfo') ->with('/bar/foo') - ->will($this->returnValue($this->getFileInfo(['permissions' => \OCP\Constants::PERMISSION_ALL]))); + ->will($this->returnValue($this->getFileInfo(['permissions' => Constants::PERMISSION_ALL]))); $node = $this->createTestNode($root, $view, '/bar/foo'); $node->touch(100); @@ -451,7 +454,7 @@ public function testTouchNotPermitted() { $view->expects($this->any()) ->method('getFileInfo') ->with('/bar/foo') - ->will($this->returnValue($this->getFileInfo(['permissions' => \OCP\Constants::PERMISSION_READ]))); + ->will($this->returnValue($this->getFileInfo(['permissions' => Constants::PERMISSION_READ]))); $node = $this->createTestNode($root, $view, '/bar/foo'); $node->touch(100); @@ -485,7 +488,7 @@ public function testCopySameStorage() { $view->expects($this->any()) ->method('getFileInfo') - ->will($this->returnValue($this->getFileInfo(['permissions' => \OCP\Constants::PERMISSION_ALL, 'fileid' => 3]))); + ->will($this->returnValue($this->getFileInfo(['permissions' => Constants::PERMISSION_ALL, 'fileid' => 3]))); $node = $this->createTestNode($root, $view, '/bar/foo'); $parentNode = new \OC\Files\Node\Folder($root, $view, '/bar'); @@ -525,7 +528,7 @@ public function testCopyNotPermitted() { $view->expects($this->any()) ->method('getFileInfo') - ->will($this->returnValue($this->getFileInfo(['permissions' => \OCP\Constants::PERMISSION_READ, 'fileid' => 3]))); + ->will($this->returnValue($this->getFileInfo(['permissions' => Constants::PERMISSION_READ, 'fileid' => 3]))); $node = $this->createTestNode($root, $view, '/bar/foo'); $parentNode = new \OC\Files\Node\Folder($root, $view, '/bar'); @@ -601,7 +604,7 @@ public function testMoveSameStorage() { $view->expects($this->any()) ->method('getFileInfo') - ->will($this->returnValue($this->getFileInfo(['permissions' => \OCP\Constants::PERMISSION_ALL, 'fileid' => 1]))); + ->will($this->returnValue($this->getFileInfo(['permissions' => Constants::PERMISSION_ALL, 'fileid' => 1]))); $node = $this->createTestNode($root, $view, '/bar/foo'); $parentNode = new \OC\Files\Node\Folder($root, $view, '/bar'); @@ -649,7 +652,7 @@ public function testMoveCopyHooks($operationMethod, $viewMethod, $preHookName, $ $view->expects($this->any()) ->method('getFileInfo') - ->will($this->returnValue($this->getFileInfo(['permissions' => \OCP\Constants::PERMISSION_ALL, 'fileid' => 1]))); + ->will($this->returnValue($this->getFileInfo(['permissions' => Constants::PERMISSION_ALL, 'fileid' => 1]))); $node = $this->createTestNode($root, $view, '/bar/foo'); $parentNode = new \OC\Files\Node\Folder($root, $view, '/bar'); @@ -722,7 +725,7 @@ public function testMoveNotPermitted() { $view->expects($this->any()) ->method('getFileInfo') - ->will($this->returnValue($this->getFileInfo(['permissions' => \OCP\Constants::PERMISSION_READ]))); + ->will($this->returnValue($this->getFileInfo(['permissions' => Constants::PERMISSION_READ]))); $view->expects($this->never()) ->method('rename'); @@ -807,7 +810,7 @@ public function testMoveFailed() { $view->expects($this->any()) ->method('getFileInfo') - ->will($this->returnValue($this->getFileInfo(['permissions' => \OCP\Constants::PERMISSION_ALL, 'fileid' => 1]))); + ->will($this->returnValue($this->getFileInfo(['permissions' => Constants::PERMISSION_ALL, 'fileid' => 1]))); $node = $this->createTestNode($root, $view, '/bar/foo'); $parentNode = new \OC\Files\Node\Folder($root, $view, '/bar'); @@ -836,7 +839,7 @@ public function testCopyFailed() { $view->expects($this->any()) ->method('getFileInfo') - ->will($this->returnValue($this->getFileInfo(['permissions' => \OCP\Constants::PERMISSION_ALL, 'fileid' => 1]))); + ->will($this->returnValue($this->getFileInfo(['permissions' => Constants::PERMISSION_ALL, 'fileid' => 1]))); $node = $this->createTestNode($root, $view, '/bar/foo'); $parentNode = new \OC\Files\Node\Folder($root, $view, '/bar'); diff --git a/tests/lib/Files/Node/RootTest.php b/tests/lib/Files/Node/RootTest.php index 69f1aaaead46..016d8db3b347 100644 --- a/tests/lib/Files/Node/RootTest.php +++ b/tests/lib/Files/Node/RootTest.php @@ -9,19 +9,22 @@ namespace Test\Files\Node; use OC\Files\FileInfo; -use OCP\Files\NotPermittedException; use OC\Files\Mount\Manager; -use OC\User\NoUserException; +use OCP\IUser; +use Test\TestCase; +use Test\Traits\UserTrait; /** * @group DB */ -class RootTest extends \Test\TestCase { +class RootTest extends TestCase { + use UserTrait; + private $user; protected function setUp() { parent::setUp(); - $this->user = new \OC\User\User('', new \Test\Util\User\Dummy); + $this->user = $this->createMock(IUser::class); } protected function getFileInfo($data) { @@ -103,6 +106,9 @@ public function testGetNoStorages() { $root->get('/bar/foo'); } + /** + * @expectedException \OC\User\NoUserException + */ public function testGetUserFolder() { $this->logout(); $manager = new Manager(); @@ -113,28 +119,8 @@ public function testGetUserFolder() { $user1 = $this->getUniqueID('user1_'); $user2 = $this->getUniqueID('user2_'); - - \OC_User::clearBackends(); - // needed for loginName2UserName mapping - $userBackend = $this->createMock(\OC\User\Database::class); - \OC::$server->getUserManager()->registerBackend($userBackend); - - $userBackend->expects($this->any()) - ->method('userExists') - ->will($this->returnValueMap([ - [$user1, true], - [$user2, true], - [strtoupper($user1), true], - [strtoupper($user2), true], - ])); - $userBackend->expects($this->any()) - ->method('loginName2UserName') - ->will($this->returnValueMap([ - [strtoupper($user1), $user1], - [$user1, $user1], - [strtoupper($user2), $user2], - [$user2, $user2], - ])); + $this->createUser($user1); + $this->createUser($user2); $this->loginAsUser($user1); $root = new \OC\Files\Node\Root($manager, $view, null); @@ -149,12 +135,6 @@ public function testGetUserFolder() { $folder = $root->getUserFolder(strtoupper($user2)); $this->assertEquals('/' . $user2 . '/files', $folder->getPath()); - $thrown = false; - try { - $folder = $root->getUserFolder($this->getUniqueID('unexist')); - } catch (NoUserException $e) { - $thrown = true; - } - $this->assertTrue($thrown); + $root->getUserFolder($this->getUniqueID('unexist')); } } diff --git a/tests/lib/Files/Storage/HomeStorageQuotaTest.php b/tests/lib/Files/Storage/HomeStorageQuotaTest.php index 68fa4bb0bbbf..8daf4a86b293 100644 --- a/tests/lib/Files/Storage/HomeStorageQuotaTest.php +++ b/tests/lib/Files/Storage/HomeStorageQuotaTest.php @@ -55,8 +55,8 @@ function testHomeStorageWrapperWithoutQuota() { */ function testHomeStorageWrapperWithQuota() { $user1 = $this->getUniqueID(); - \OC::$server->getUserManager()->createUser($user1, 'test'); - \OC::$server->getConfig()->setUserValue($user1, 'files', 'quota', '1024'); + $userObj = \OC::$server->getUserManager()->createUser($user1, 'test'); + $userObj->setQuota('1024'); \OC_User::setUserId($user1); \OC_Util::setupFS($user1); diff --git a/tests/lib/Files/Storage/Wrapper/EncryptionTest.php b/tests/lib/Files/Storage/Wrapper/EncryptionTest.php index 4a1daf4db1f5..a94908e2b5ea 100644 --- a/tests/lib/Files/Storage/Wrapper/EncryptionTest.php +++ b/tests/lib/Files/Storage/Wrapper/EncryptionTest.php @@ -6,6 +6,7 @@ use OC\Files\Storage\Temporary; use OC\Files\View; use OC\User\Manager; +use OCP\IUserManager; use Test\Files\Storage\Storage; class EncryptionTest extends Storage { @@ -116,9 +117,11 @@ protected function setUp() { ->disableOriginalConstructor() ->getMock(); + $userManager = $this->createMock(Manager::class); + $this->util = $this->getMockBuilder('\OC\Encryption\Util') ->setMethods(['getUidAndFilename', 'isFile', 'isExcluded']) - ->setConstructorArgs([new View(), new Manager(), $this->groupManager, $this->config, $this->arrayCache]) + ->setConstructorArgs([new View(), $userManager, $this->groupManager, $this->config, $this->arrayCache]) ->getMock(); $this->util->expects($this->any()) ->method('getUidAndFilename') @@ -540,11 +543,12 @@ public function testGetHeader($path, $strippedPathExists, $strippedPath) { $sourceStorage = $this->getMockBuilder('\OC\Files\Storage\Storage') ->disableOriginalConstructor()->getMock(); + $userManager = $this->createMock(Manager::class); $util = $this->getMockBuilder('\OC\Encryption\Util') ->setConstructorArgs( [ new View(), - new Manager(), + $userManager, $this->groupManager, $this->config, $this->arrayCache @@ -608,8 +612,9 @@ public function testGetHeaderAddLegacyModule($header, $isEncrypted, $expected) { $sourceStorage = $this->getMockBuilder('\OC\Files\Storage\Storage') ->disableOriginalConstructor()->getMock(); + $userManager = $this->createMock(Manager::class); $util = $this->getMockBuilder('\OC\Encryption\Util') - ->setConstructorArgs([new View(), new Manager(), $this->groupManager, $this->config, $this->arrayCache]) + ->setConstructorArgs([new View(), $userManager, $this->groupManager, $this->config, $this->arrayCache]) ->getMock(); $cache = $this->getMockBuilder('\OC\Files\Cache\Cache') diff --git a/tests/lib/Files/Stream/EncryptionTest.php b/tests/lib/Files/Stream/EncryptionTest.php index dd5e7c902508..bd5a333c4d8d 100644 --- a/tests/lib/Files/Stream/EncryptionTest.php +++ b/tests/lib/Files/Stream/EncryptionTest.php @@ -3,6 +3,7 @@ namespace Test\Files\Stream; use OC\Files\View; +use OC\User\Manager; use Test\TestCase; class EncryptionTest extends TestCase { @@ -41,9 +42,11 @@ protected function getStream($fileName, $mode, $unencryptedSize, $wrapper = '\OC ->setMethods(['getAccessList']) ->getMock(); $file->expects($this->any())->method('getAccessList')->willReturn([]); + + $userManager = $this->createMock(Manager::class); $util = $this->getMockBuilder('\OC\Encryption\Util') ->setMethods(['getUidAndFilename']) - ->setConstructorArgs([new View(), new \OC\User\Manager(), $groupManager, $config, $arrayCache]) + ->setConstructorArgs([new View(), $userManager, $groupManager, $config, $arrayCache]) ->getMock(); $util->expects($this->any()) ->method('getUidAndFilename') diff --git a/tests/lib/Files/Utils/ScannerTest.php b/tests/lib/Files/Utils/ScannerTest.php index 8d784dd7aaaa..9d0fca4c3563 100644 --- a/tests/lib/Files/Utils/ScannerTest.php +++ b/tests/lib/Files/Utils/ScannerTest.php @@ -13,6 +13,7 @@ use OC\Files\Storage\Temporary; use OCP\Files\Storage\IStorageFactory; use OCP\IUser; +use Test\Traits\UserTrait; class TestScanner extends \OC\Files\Utils\Scanner { /** @@ -40,22 +41,16 @@ protected function getMounts($dir) { * @package Test\Files\Utils */ class ScannerTest extends \Test\TestCase { - /** - * @var \Test\Util\User\Dummy - */ - private $userBackend; + use UserTrait; protected function setUp() { parent::setUp(); - $this->userBackend = new \Test\Util\User\Dummy(); - \OC::$server->getUserManager()->registerBackend($this->userBackend); $this->loginAsUser(); } protected function tearDown() { $this->logout(); - \OC::$server->getUserManager()->removeBackend($this->userBackend); parent::tearDown(); } @@ -105,7 +100,7 @@ public function testReuseExistingFile() { public function testScanSubMount() { $uid = $this->getUniqueID(); - $this->userBackend->createUser($uid, 'test'); + $this->createUser($uid); $mountProvider = $this->createMock('\OCP\Files\Config\IMountProvider'); diff --git a/tests/lib/Files/ViewTest.php b/tests/lib/Files/ViewTest.php index fb09b37c8cfd..9a93627ef374 100644 --- a/tests/lib/Files/ViewTest.php +++ b/tests/lib/Files/ViewTest.php @@ -80,13 +80,14 @@ protected function setUp() { parent::setUp(); \OC_Hook::clear(); - \OC_User::clearBackends(); - \OC_User::useBackend(new \Test\Util\User\Dummy()); - //login $userManager = \OC::$server->getUserManager(); $groupManager = \OC::$server->getGroupManager(); $this->user = 'test'; + if ($userManager->userExists('test')) { + $this->userObject = $userManager->get('test'); + $this->userObject->delete(); + } $this->userObject = $userManager->createUser('test', 'test'); $this->groupObject = $groupManager->createGroup('group1'); diff --git a/tests/lib/Group/GroupTest.php b/tests/lib/Group/GroupTest.php index 16d7a529e525..d234d3555ed4 100644 --- a/tests/lib/Group/GroupTest.php +++ b/tests/lib/Group/GroupTest.php @@ -10,17 +10,20 @@ namespace Test\Group; use OC\User\User; +use OCP\IUser; class GroupTest extends \Test\TestCase { /** * @return \OC\User\Manager | \OC\User\Manager */ protected function getUserManager() { + $user1 = $this->createMock(IUser::class); + $user1->expects($this->any())->method('getUID')->willReturn('user1'); + $user2 = $this->createMock(IUser::class); + $user2->expects($this->any())->method('getUID')->willReturn('user2'); + $user3 = $this->createMock(IUser::class); + $user3->expects($this->any())->method('getUID')->willReturn('user3'); $userManager = $this->createMock('\OC\User\Manager'); - $backend = $this->createMock('\OC_User_Backend'); - $user1 = new User('user1', $backend); - $user2 = new User('user2', $backend); - $user3 = new User('user3', $backend); $userManager->expects($this->any()) ->method('get') ->will($this->returnValueMap([ @@ -80,7 +83,6 @@ public function testGetUsersMultipleBackends() { public function testInGroupSingleBackend() { $backend = $this->createMock('OC\Group\Database'); $userManager = $this->getUserManager(); - $userBackend = $this->createMock('\OC_User_Backend'); $group = new \OC\Group\Group('group1', [$backend], $userManager); $backend->expects($this->once()) @@ -88,14 +90,16 @@ public function testInGroupSingleBackend() { ->with('user1', 'group1') ->will($this->returnValue(true)); - $this->assertTrue($group->inGroup(new User('user1', $userBackend))); + $user1 = $this->createMock(IUser::class); + $user1->expects($this->any())->method('getUID')->willReturn('user1'); + + $this->assertTrue($group->inGroup($user1)); } public function testInGroupMultipleBackends() { $backend1 = $this->createMock('OC\Group\Database'); $backend2 = $this->createMock('OC\Group\Database'); $userManager = $this->getUserManager(); - $userBackend = $this->createMock('\OC_User_Backend'); $group = new \OC\Group\Group('group1', [$backend1, $backend2], $userManager); $backend1->expects($this->once()) @@ -108,13 +112,15 @@ public function testInGroupMultipleBackends() { ->with('user1', 'group1') ->will($this->returnValue(true)); - $this->assertTrue($group->inGroup(new User('user1', $userBackend))); + $user1 = $this->createMock(IUser::class); + $user1->expects($this->any())->method('getUID')->willReturn('user1'); + + $this->assertTrue($group->inGroup($user1)); } public function testAddUser() { $backend = $this->createMock('OC\Group\Database'); $userManager = $this->getUserManager(); - $userBackend = $this->createMock('\OC_User_Backend'); $group = new \OC\Group\Group('group1', [$backend], $userManager); $backend->expects($this->once()) @@ -129,13 +135,15 @@ public function testAddUser() { ->method('addToGroup') ->with('user1', 'group1'); - $group->addUser(new User('user1', $userBackend)); + $user1 = $this->createMock(IUser::class); + $user1->expects($this->any())->method('getUID')->willReturn('user1'); + + $group->addUser($user1); } public function testAddUserAlreadyInGroup() { $backend = $this->createMock('OC\Group\Database'); $userManager = $this->getUserManager(); - $userBackend = $this->createMock('\OC_User_Backend'); $group = new \OC\Group\Group('group1', [$backend], $userManager); $backend->expects($this->once()) @@ -149,13 +157,15 @@ public function testAddUserAlreadyInGroup() { $backend->expects($this->never()) ->method('addToGroup'); - $group->addUser(new User('user1', $userBackend)); + $user1 = $this->createMock(IUser::class); + $user1->expects($this->any())->method('getUID')->willReturn('user1'); + + $group->addUser($user1); } public function testRemoveUser() { $backend = $this->createMock('OC\Group\Database'); $userManager = $this->getUserManager(); - $userBackend = $this->createMock('\OC_User_Backend'); $group = new \OC\Group\Group('group1', [$backend], $userManager); $backend->expects($this->once()) @@ -170,13 +180,15 @@ public function testRemoveUser() { ->method('removeFromGroup') ->with('user1', 'group1'); - $group->removeUser(new User('user1', $userBackend)); + $user1 = $this->createMock(IUser::class); + $user1->expects($this->any())->method('getUID')->willReturn('user1'); + + $group->removeUser($user1); } public function testRemoveUserNotInGroup() { $backend = $this->createMock('OC\Group\Database'); $userManager = $this->getUserManager(); - $userBackend = $this->createMock('\OC_User_Backend'); $group = new \OC\Group\Group('group1', [$backend], $userManager); $backend->expects($this->once()) @@ -189,15 +201,16 @@ public function testRemoveUserNotInGroup() { $backend->expects($this->never()) ->method('removeFromGroup'); + $user1 = $this->createMock(IUser::class); + $user1->expects($this->any())->method('getUID')->willReturn('user1'); - $group->removeUser(new User('user1', $userBackend)); + $group->removeUser($user1); } public function testRemoveUserMultipleBackends() { $backend1 = $this->createMock('OC\Group\Database'); $backend2 = $this->createMock('OC\Group\Database'); $userManager = $this->getUserManager(); - $userBackend = $this->createMock('\OC_User_Backend'); $group = new \OC\Group\Group('group1', [$backend1, $backend2], $userManager); $backend1->expects($this->once()) @@ -224,7 +237,10 @@ public function testRemoveUserMultipleBackends() { ->method('removeFromGroup') ->with('user1', 'group1'); - $group->removeUser(new User('user1', $userBackend)); + $user1 = $this->createMock(IUser::class); + $user1->expects($this->any())->method('getUID')->willReturn('user1'); + + $group->removeUser($user1); } public function testSearchUsers() { diff --git a/tests/lib/HelperStorageTest.php b/tests/lib/HelperStorageTest.php index bce3f773dca7..60b279661d16 100644 --- a/tests/lib/HelperStorageTest.php +++ b/tests/lib/HelperStorageTest.php @@ -9,6 +9,7 @@ namespace Test; use OC\Files\Filesystem; use OC\Files\Storage\Temporary; +use OCP\IUser; /** * Test the storage functions of OC_Helper @@ -22,12 +23,14 @@ class HelperStorageTest extends TestCase { private $storageMock; /** @var \OC\Files\Storage\Storage */ private $storage; + /** @var IUser */ + private $userObj; protected function setUp() { parent::setUp(); $this->user = $this->getUniqueID('user_'); - \OC::$server->getUserManager()->createUser($this->user, $this->user); + $this->userObj = \OC::$server->getUserManager()->createUser($this->user, $this->user); $this->storage = Filesystem::getStorage('/'); Filesystem::tearDown(); @@ -127,7 +130,7 @@ function testGetStorageInfoIncludingExtStorage() { $oldConfig = $config->getSystemValue('quota_include_external_storage', false); $config->setSystemValue('quota_include_external_storage', 'true'); - $config->setUserValue($this->user, 'files', 'quota', '25'); + $this->userObj->setQuota('25'); $storageInfo = \OC_Helper::getStorageInfo(''); $this->assertEquals(3, $storageInfo['free']); diff --git a/tests/lib/Preview/Provider.php b/tests/lib/Preview/Provider.php index 5377f30df820..14297904fc88 100644 --- a/tests/lib/Preview/Provider.php +++ b/tests/lib/Preview/Provider.php @@ -21,7 +21,10 @@ namespace Test\Preview; +use Test\Traits\UserTrait; + abstract class Provider extends \Test\TestCase { + use UserTrait; /** @var string */ protected $imgPath; @@ -49,11 +52,9 @@ protected function setUp() { $userManager = \OC::$server->getUserManager(); $userManager->clearBackends(); - $backend = new \Test\Util\User\Dummy(); - $userManager->registerBackend($backend); $userId = $this->getUniqueID(); - $backend->createUser($userId, $userId); + $this->createUser($userId, $userId); $this->loginAsUser($userId); $this->storage = new \OC\Files\Storage\Temporary([]); diff --git a/tests/lib/Repair/RemoveRootSharesTest.php b/tests/lib/Repair/RemoveRootSharesTest.php index cfb81cb1ecca..3eee85a1a2c4 100644 --- a/tests/lib/Repair/RemoveRootSharesTest.php +++ b/tests/lib/Repair/RemoveRootSharesTest.php @@ -75,7 +75,7 @@ protected function tearDown() { public function testRootSharesExist() { //Add test user - $user = $this->userManager->createUser('test', 'test'); + $user = $this->createUser('test', 'test'); $userFolder = $this->rootFolder->getUserFolder('test'); $fileId = $userFolder->getId(); @@ -103,7 +103,7 @@ public function testRootSharesExist() { public function testRootSharesDontExist() { //Add test user - $user = $this->userManager->createUser('test', 'test'); + $user = $this->createUser('test', 'test'); $userFolder = $this->rootFolder->getUserFolder('test'); $fileId = $userFolder->getId(); $user->updateLastLoginTimestamp(); @@ -132,7 +132,7 @@ public function testRootSharesDontExist() { public function testRun() { //Add test user - $user1 = $this->userManager->createUser('test1', 'test1'); + $user1 = $this->createUser('test1', 'test1'); $userFolder = $this->rootFolder->getUserFolder('test1'); $fileId = $userFolder->getId(); $user1->updateLastLoginTimestamp(); @@ -154,7 +154,7 @@ public function testRun() { $qb->execute(); //Add test user - $user2 = $this->userManager->createUser('test2', 'test2'); + $user2 = $this->createUser('test2', 'test2'); $userFolder = $this->rootFolder->getUserFolder('test2'); $folder = $userFolder->newFolder('foo'); $fileId = $folder->getId(); diff --git a/tests/lib/Security/CertificateManagerTest.php b/tests/lib/Security/CertificateManagerTest.php index ca4b30b58bec..25ec4095e107 100644 --- a/tests/lib/Security/CertificateManagerTest.php +++ b/tests/lib/Security/CertificateManagerTest.php @@ -28,7 +28,7 @@ protected function setUp() { parent::setUp(); $this->username = $this->getUniqueID('', 20); - $this->createUser($this->username, ''); + $this->createUser($this->username); $storage = new \OC\Files\Storage\Temporary(); $this->registerMount($this->username, $storage, '/' . $this->username . '/'); diff --git a/tests/lib/Share/ShareTest.php b/tests/lib/Share/ShareTest.php index 805242360f6c..410dae603ab1 100644 --- a/tests/lib/Share/ShareTest.php +++ b/tests/lib/Share/ShareTest.php @@ -21,6 +21,8 @@ namespace Test\Share; +use Test\Traits\UserTrait; + /** * Class Test_Share * @@ -28,6 +30,8 @@ */ class ShareTest extends \Test\TestCase { + use UserTrait; + protected $itemType; protected $userBackend; protected $user1; @@ -47,8 +51,6 @@ class ShareTest extends \Test\TestCase { protected function setUp() { parent::setUp(); - \OC_User::clearBackends(); - \OC_User::useBackend('dummy'); $this->user1 = $this->getUniqueID('user1_'); $this->user2 = $this->getUniqueID('user2_'); $this->user3 = $this->getUniqueID('user3_'); @@ -56,13 +58,13 @@ protected function setUp() { $this->user5 = $this->getUniqueID('user5_'); $this->user6 = $this->getUniqueID('user6_'); $this->groupAndUser = $this->getUniqueID('groupAndUser_'); - $u1 = \OC::$server->getUserManager()->createUser($this->user1, 'pass'); - $u2 = \OC::$server->getUserManager()->createUser($this->user2, 'pass'); - $u3 = \OC::$server->getUserManager()->createUser($this->user3, 'pass'); - $u4 = \OC::$server->getUserManager()->createUser($this->user4, 'pass'); - $u5 = \OC::$server->getUserManager()->createUser($this->user5, 'pass'); - $u6 = \OC::$server->getUserManager()->createUser($this->user6, 'pass'); // no group - $uug = \OC::$server->getUserManager()->createUser($this->groupAndUser, 'pass'); + $u1 = $this->createUser($this->user1, 'pass'); + $u2 = $this->createUser($this->user2, 'pass'); + $u3 = $this->createUser($this->user3, 'pass'); + $u4 = $this->createUser($this->user4, 'pass'); + $u5 = $this->createUser($this->user5, 'pass'); + $u6 = $this->createUser($this->user6, 'pass'); // no group + $uug = $this->createUser($this->groupAndUser, 'pass'); \OC_User::setUserId($this->user1); \OC::$server->getGroupManager()->clearBackends(); \OC::$server->getGroupManager()->addBackend(new \Test\Util\Group\Dummy()); diff --git a/tests/lib/SubAdminTest.php b/tests/lib/SubAdminTest.php index c1159132a50f..88eb13c57d7a 100644 --- a/tests/lib/SubAdminTest.php +++ b/tests/lib/SubAdminTest.php @@ -20,7 +20,7 @@ */ namespace Test; -class SubAdminTest extends \Test\TestCase { +class SubAdminTest extends TestCase { /** @var \OCP\IUserManager */ private $userManager; @@ -47,7 +47,7 @@ public function setup() { // Create 3 users and 3 groups for ($i = 0; $i < 3; $i++) { - $this->users[] = $this->userManager->createUser('user'.$i, 'user'); + $this->users[] = $this->userManager->createUser($this->getUniqueID('user'), 'user'); $this->groups[] = $this->groupManager->createGroup('group'.$i); } diff --git a/tests/lib/TagsTest.php b/tests/lib/TagsTest.php index e421664be6bb..c755ab0ba381 100644 --- a/tests/lib/TagsTest.php +++ b/tests/lib/TagsTest.php @@ -21,13 +21,19 @@ */ namespace Test; +use OC\Tagging\TagMapper; +use OC\TagManager; +use OCP\IUserSession; +use Test\Traits\UserTrait; /** * Class TagsTest * * @group DB */ -class TagsTest extends \Test\TestCase { +class TagsTest extends TestCase { + + use UserTrait; protected $objectType; /** @var \OCP\IUser */ @@ -35,7 +41,7 @@ class TagsTest extends \Test\TestCase { /** @var \OCP\IUserSession */ protected $userSession; protected $backupGlobals = FALSE; - /** @var \OC\Tagging\TagMapper */ + /** @var TagMapper */ protected $tagMapper; /** @var \OCP\ITagManager */ protected $tagMgr; @@ -43,12 +49,9 @@ class TagsTest extends \Test\TestCase { protected function setUp() { parent::setUp(); - \OC_User::clearBackends(); - \OC_User::useBackend('dummy'); $userId = $this->getUniqueID('user_'); - \OC::$server->getUserManager()->createUser($userId, 'pass'); + $this->user = $this->createUser($userId, 'pass'); \OC_User::setUserId($userId); - $this->user = new \OC\User\User($userId, null); $this->userSession = $this->createMock('\OCP\IUserSession'); $this->userSession ->expects($this->any()) @@ -56,8 +59,8 @@ protected function setUp() { ->will($this->returnValue($this->user)); $this->objectType = $this->getUniqueID('type_'); - $this->tagMapper = new \OC\Tagging\TagMapper(\OC::$server->getDatabaseConnection()); - $this->tagMgr = new \OC\TagManager($this->tagMapper, $this->userSession); + $this->tagMapper = new TagMapper(\OC::$server->getDatabaseConnection()); + $this->tagMgr = new TagManager($this->tagMapper, $this->userSession); } @@ -75,7 +78,7 @@ public function testTagManagerWithoutUserReturnsNull() { ->expects($this->any()) ->method('getUser') ->will($this->returnValue(null)); - $this->tagMgr = new \OC\TagManager($this->tagMapper, $this->userSession); + $this->tagMgr = new TagManager($this->tagMapper, $this->userSession); $this->assertNull($this->tagMgr->load($this->objectType)); } @@ -292,15 +295,16 @@ public function testShareTags() { $tagger->tagAs(1, $testTag); $otherUserId = $this->getUniqueID('user2_'); - \OC::$server->getUserManager()->createUser($otherUserId, 'pass'); + $otherUser = \OC::$server->getUserManager()->createUser($otherUserId, 'pass'); \OC_User::setUserId($otherUserId); - $otherUserSession = $this->createMock('\OCP\IUserSession'); + /** @var IUserSession | \PHPUnit_Framework_MockObject_MockObject $otherUserSession */ + $otherUserSession = $this->createMock(IUserSession::class); $otherUserSession ->expects($this->any()) ->method('getUser') - ->will($this->returnValue(new \OC\User\User($otherUserId, null))); + ->will($this->returnValue($otherUser)); - $otherTagMgr = new \OC\TagManager($this->tagMapper, $otherUserSession); + $otherTagMgr = new TagManager($this->tagMapper, $otherUserSession); $otherTagger = $otherTagMgr->load('test'); $this->assertFalse($otherTagger->hasTag($testTag)); diff --git a/tests/lib/Traits/UserTrait.php b/tests/lib/Traits/UserTrait.php index 229087a5200e..64377875b23d 100644 --- a/tests/lib/Traits/UserTrait.php +++ b/tests/lib/Traits/UserTrait.php @@ -8,25 +8,35 @@ namespace Test\Traits; +use OC\User\User; + /** * Allow creating users in a temporary backend */ trait UserTrait { - /** - * @var \Test\Util\User\Dummy|\OCP\UserInterface - */ - protected $userBackend; - protected function createUser($name, $password) { - $this->userBackend->createUser($name, $password); + /** @var User[] */ + private $users = []; + + protected function createUser($name, $password = null) { + if (is_null($password)) { + $password = $name; + } + $userManager = \OC::$server->getUserManager(); + if ($userManager->userExists($name)) { + $userManager->get($name)->delete(); + } + $user = \OC::$server->getUserManager()->createUser($name, $password); + $this->users[] = $user; + return $user; } protected function setUpUserTrait() { - $this->userBackend = new \Test\Util\User\Dummy(); - \OC::$server->getUserManager()->registerBackend($this->userBackend); } protected function tearDownUserTrait() { - \OC::$server->getUserManager()->removeBackend($this->userBackend); + foreach($this->users as $user) { + $user->delete(); + } } } diff --git a/tests/lib/User/BackendTestCase.php b/tests/lib/User/BackendTestCase.php index bc5b2498612a..d0fa901f4625 100644 --- a/tests/lib/User/BackendTestCase.php +++ b/tests/lib/User/BackendTestCase.php @@ -43,8 +43,8 @@ abstract class BackendTestCase extends \Test\TestCase { * test cases can override this in order to clean up created user * @return string */ - public function getUser() { - return $this->getUniqueID('test_'); + public function getUser($prefix = 'test_') { + return $this->getUniqueID($prefix); } public function testAddRemove() { @@ -100,18 +100,19 @@ public function testLogin() { } public function testSearch() { - $name1 = 'foobarbaz'; - $name2 = 'bazbarfoo'; - $name3 = 'notme'; + $prefix = str_replace('\\', '#', get_class($this->backend)); + $name1 = $this->getUser('foo' . $prefix . 'baz'); + $name2 = $this->getUser('baz' . $prefix . 'foo'); + $name3 = $this->getUser('notme'); $this->backend->createUser($name1, 'pass1'); $this->backend->createUser($name2, 'pass2'); $this->backend->createUser($name3, 'pass3'); - $result = $this->backend->getUsers('bar'); - $this->assertSame(2, count($result)); + $result = $this->backend->getUsers($prefix); + $this->assertSame(2, count($result), json_encode($result)); - $result = $this->backend->getDisplayNames('bar'); + $result = $this->backend->getDisplayNames($prefix); $this->assertSame(2, count($result)); } } diff --git a/tests/lib/User/DatabaseTest.php b/tests/lib/User/DatabaseTest.php index 29d74e9df5f4..49161e5ae34e 100644 --- a/tests/lib/User/DatabaseTest.php +++ b/tests/lib/User/DatabaseTest.php @@ -31,8 +31,8 @@ class DatabaseTest extends BackendTestCase { /** @var array */ private $users; - public function getUser() { - $user = parent::getUser(); + public function getUser($prefix = 'test_') { + $user = parent::getUser($prefix); $this->users[]=$user; return $user; } @@ -53,14 +53,14 @@ protected function tearDown() { } public function testCreateUserInvalidatesCache() { - $user1 = $this->getUniqueID('test_'); + $user1 = $this->getUser(); $this->assertFalse($this->backend->userExists($user1)); $this->backend->createUser($user1, 'pw'); $this->assertTrue($this->backend->userExists($user1)); } public function testDeleteUserInvalidatesCache() { - $user1 = $this->getUniqueID('test_'); + $user1 = $this->getUser(); $this->backend->createUser($user1, 'pw'); $this->assertTrue($this->backend->userExists($user1)); $this->backend->deleteUser($user1); diff --git a/tests/lib/User/ManagerTest.php b/tests/lib/User/ManagerTest.php index c1d380f093bc..bafc294c1c27 100644 --- a/tests/lib/User/ManagerTest.php +++ b/tests/lib/User/ManagerTest.php @@ -8,7 +8,13 @@ */ namespace Test\User; +use OC\User\Account; +use OC\User\AccountMapper; +use OC\User\Backend; use OC\User\Database; +use OC\User\Manager; +use OCP\AppFramework\Db\DoesNotExistException; +use OCP\IConfig; use OCP\IUser; use Test\TestCase; @@ -20,129 +26,75 @@ * @package Test\User */ class ManagerTest extends TestCase { - public function testGetBackends() { - $userDummyBackend = $this->createMock('\Test\Util\User\Dummy'); - $manager = new \OC\User\Manager(); - $manager->registerBackend($userDummyBackend); - $this->assertEquals([$userDummyBackend], $manager->getBackends()); - $dummyDatabaseBackend = $this->createMock(Database::class); - $manager->registerBackend($dummyDatabaseBackend); - $this->assertEquals([$userDummyBackend, $dummyDatabaseBackend], $manager->getBackends()); - } + /** @var Manager */ + private $manager; + /** @var AccountMapper | \PHPUnit_Framework_MockObject_MockObject */ + private $accountMapper; - public function testUserExistsSingleBackendExists() { - /** - * @var \Test\Util\User\Dummy | \PHPUnit_Framework_MockObject_MockObject $backend - */ - $backend = $this->createMock('\Test\Util\User\Dummy'); - $backend->expects($this->once()) - ->method('userExists') - ->with($this->equalTo('foo')) - ->will($this->returnValue(true)); + public function setUp() { + parent::setUp(); - $manager = new \OC\User\Manager(); - $manager->registerBackend($backend); - - $this->assertTrue($manager->userExists('foo')); + /** @var IConfig | \PHPUnit_Framework_MockObject_MockObject $config */ + $config = $this->createMock(IConfig::class); + $this->accountMapper = $this->createMock(AccountMapper::class); + $this->manager = new \OC\User\Manager($config, $this->accountMapper); } - public function testUserExistsSingleBackendNotExists() { - /** - * @var \Test\Util\User\Dummy | \PHPUnit_Framework_MockObject_MockObject $backend - */ - $backend = $this->createMock('\Test\Util\User\Dummy'); - $backend->expects($this->once()) - ->method('userExists') - ->with($this->equalTo('foo')) - ->will($this->returnValue(false)); - - $manager = new \OC\User\Manager(); - $manager->registerBackend($backend); + public function testGetBackends() { + /** @var Backend | \PHPUnit_Framework_MockObject_MockObject $backend */ + $backend = $this->createMock(Backend::class); + $this->manager->registerBackend($backend); + $this->assertEquals([$backend], $this->manager->getBackends()); - $this->assertFalse($manager->userExists('foo')); + /** @var Backend | \PHPUnit_Framework_MockObject_MockObject $dummyDatabaseBackend */ + $dummyDatabaseBackend = $this->createMock(Database::class); + $this->manager->registerBackend($dummyDatabaseBackend); + $this->assertEquals([$backend, $dummyDatabaseBackend], $this->manager->getBackends()); } - public function testUserExistsNoBackends() { - $manager = new \OC\User\Manager(); - $this->assertFalse($manager->userExists('foo')); + public function testUserExistsSingleBackendExists() { + $account = $this->createMock(Account::class); + $this->accountMapper->expects($this->once())->method('getByUid')->with('foo')->willReturn($account); + $this->assertTrue($this->manager->userExists('foo')); } - public function testUserExistsTwoBackendsSecondExists() { - /** - * @var \Test\Util\User\Dummy | \PHPUnit_Framework_MockObject_MockObject $backend1 - */ - $backend1 = $this->createMock('\Test\Util\User\Dummy'); - $backend1->expects($this->once()) - ->method('userExists') - ->with($this->equalTo('foo')) - ->will($this->returnValue(false)); - - /** - * @var \Test\Util\User\Dummy | \PHPUnit_Framework_MockObject_MockObject $backend2 - */ - $backend2 = $this->createMock('\Test\Util\User\Dummy'); - $backend2->expects($this->once()) - ->method('userExists') - ->with($this->equalTo('foo')) - ->will($this->returnValue(true)); - - $manager = new \OC\User\Manager(); - $manager->registerBackend($backend1); - $manager->registerBackend($backend2); - - $this->assertTrue($manager->userExists('foo')); + public function testUserExistsSingleBackendNotExists() { + $this->accountMapper->expects($this->once())->method('getByUid')->with('foo')->willThrowException(new DoesNotExistException('')); + $this->assertFalse($this->manager->userExists('foo')); } - public function testUserExistsTwoBackendsFirstExists() { - /** - * @var \Test\Util\User\Dummy | \PHPUnit_Framework_MockObject_MockObject $backend1 - */ - $backend1 = $this->createMock('\Test\Util\User\Dummy'); - $backend1->expects($this->once()) - ->method('userExists') - ->with($this->equalTo('foo')) - ->will($this->returnValue(true)); - - /** - * @var \Test\Util\User\Dummy | \PHPUnit_Framework_MockObject_MockObject $backend2 - */ - $backend2 = $this->createMock('\Test\Util\User\Dummy'); - $backend2->expects($this->never()) - ->method('userExists'); - - $manager = new \OC\User\Manager(); - $manager->registerBackend($backend1); - $manager->registerBackend($backend2); - - $this->assertTrue($manager->userExists('foo')); + public function testUserExistsNoBackends() { + $this->assertFalse($this->manager->userExists('foo')); } public function testCheckPassword() { /** * @var \OC\User\Backend | \PHPUnit_Framework_MockObject_MockObject $backend */ - $backend = $this->createMock('\Test\Util\User\Dummy'); + $backend = $this->createMock(Database::class); $backend->expects($this->once()) ->method('checkPassword') ->with($this->equalTo('foo'), $this->equalTo('bar')) - ->will($this->returnValue(true)); + ->willReturn('foo'); $backend->expects($this->any()) ->method('implementsActions') ->will($this->returnCallback(function ($actions) { - if ($actions === \OC_USER_BACKEND_CHECK_PASSWORD) { + if ($actions === \OC_User_Backend::CHECK_PASSWORD) { return true; } else { return false; } })); - $manager = new \OC\User\Manager(); - $manager->registerBackend($backend); + $this->manager->registerBackend($backend); - $user = $manager->checkPassword('foo', 'bar'); + $account = $this->createMock(Account::class); + $this->accountMapper->expects($this->once())->method('getByUid')->with('foo')->willReturn($account); + + $user = $this->manager->checkPassword('foo', 'bar'); $this->assertTrue($user instanceof \OC\User\User); } @@ -150,7 +102,7 @@ public function testCheckPasswordNotSupported() { /** * @var \OC\User\Backend | \PHPUnit_Framework_MockObject_MockObject $backend */ - $backend = $this->createMock('\Test\Util\User\Dummy'); + $backend = $this->createMock(Database::class); $backend->expects($this->never()) ->method('checkPassword'); @@ -158,316 +110,97 @@ public function testCheckPasswordNotSupported() { ->method('implementsActions') ->will($this->returnValue(false)); - $manager = new \OC\User\Manager(); - $manager->registerBackend($backend); + $this->manager->registerBackend($backend); - $this->assertFalse($manager->checkPassword('foo', 'bar')); + $this->assertFalse($this->manager->checkPassword('foo', 'bar')); } public function testGetOneBackendExists() { - /** - * @var \Test\Util\User\Dummy | \PHPUnit_Framework_MockObject_MockObject $backend - */ - $backend = $this->createMock('\Test\Util\User\Dummy'); - $backend->expects($this->once()) - ->method('userExists') - ->with($this->equalTo('foo')) - ->will($this->returnValue(true)); - - $manager = new \OC\User\Manager(); - $manager->registerBackend($backend); - - $this->assertEquals('foo', $manager->get('foo')->getUID()); + $account = new Account(); + $account->setUserId('foo'); + $this->accountMapper->expects($this->once())->method('getByUid')->with('foo')->willReturn($account); + $this->assertEquals('foo', $this->manager->get('foo')->getUID()); } public function testGetOneBackendNotExists() { - /** - * @var \Test\Util\User\Dummy | \PHPUnit_Framework_MockObject_MockObject $backend - */ - $backend = $this->createMock('\Test\Util\User\Dummy'); - $backend->expects($this->once()) - ->method('userExists') - ->with($this->equalTo('foo')) - ->will($this->returnValue(false)); - - $manager = new \OC\User\Manager(); - $manager->registerBackend($backend); - - $this->assertEquals(null, $manager->get('foo')); + $this->assertEquals(null, $this->manager->get('foo')); } - public function testSearchOneBackend() { - /** - * @var \Test\Util\User\Dummy | \PHPUnit_Framework_MockObject_MockObject $backend - */ - $backend = $this->createMock('\Test\Util\User\Dummy'); - $backend->expects($this->once()) - ->method('getUsers') - ->with($this->equalTo('fo')) - ->will($this->returnValue(['foo', 'afoo'])); - - $manager = new \OC\User\Manager(); - $manager->registerBackend($backend); - - $result = $manager->search('fo'); + public function testSearch() { + $a0 = new Account(); + $a0->setUserId('afoo'); + $a1 = new Account(); + $a1->setUserId('foo'); + $this->accountMapper->expects($this->once())->method('search') + ->with('user_id', 'fo')->willReturn([$a0, $a1]); + $result = $this->manager->search('fo'); $this->assertEquals(2, count($result)); $this->assertEquals('afoo', array_shift($result)->getUID()); $this->assertEquals('foo', array_shift($result)->getUID()); } - public function testSearchTwoBackendLimitOffset() { - /** - * @var \Test\Util\User\Dummy | \PHPUnit_Framework_MockObject_MockObject $backend1 - */ - $backend1 = $this->createMock('\Test\Util\User\Dummy'); - $backend1->expects($this->once()) - ->method('getUsers') - ->with($this->equalTo('fo'), $this->equalTo(3), $this->equalTo(1)) - ->will($this->returnValue(['foo1', 'foo2'])); - - /** - * @var \Test\Util\User\Dummy | \PHPUnit_Framework_MockObject_MockObject $backend2 - */ - $backend2 = $this->createMock('\Test\Util\User\Dummy'); - $backend2->expects($this->once()) - ->method('getUsers') - ->with($this->equalTo('fo'), $this->equalTo(3), $this->equalTo(1)) - ->will($this->returnValue(['foo3'])); - - $manager = new \OC\User\Manager(); - $manager->registerBackend($backend1); - $manager->registerBackend($backend2); - - $result = $manager->search('fo', 3, 1); + public function testSearchLimitOffset() { + $a0 = new Account(); + $a0->setUserId('foo1'); + $a1 = new Account(); + $a1->setUserId('foo2'); + $a2 = new Account(); + $a2->setUserId('foo3'); + $this->accountMapper->expects($this->once())->method('search') + ->with('user_id', 'fo', 3, 1)->willReturn([$a0, $a1, $a2]); + $result = $this->manager->search('fo', 3, 1); $this->assertEquals(3, count($result)); $this->assertEquals('foo1', array_shift($result)->getUID()); $this->assertEquals('foo2', array_shift($result)->getUID()); $this->assertEquals('foo3', array_shift($result)->getUID()); } - public function testCreateUserSingleBackendNotExists() { - /** - * @var \Test\Util\User\Dummy | \PHPUnit_Framework_MockObject_MockObject $backend - */ - $backend = $this->createMock('\Test\Util\User\Dummy'); - $backend->expects($this->any()) - ->method('implementsActions') - ->will($this->returnValue(true)); - - $backend->expects($this->once()) - ->method('createUser') - ->with($this->equalTo('foo'), $this->equalTo('bar')); - - $backend->expects($this->once()) - ->method('userExists') - ->with($this->equalTo('foo')) - ->will($this->returnValue(false)); - - $manager = new \OC\User\Manager(); - $manager->registerBackend($backend); - - $user = $manager->createUser('foo', 'bar'); - $this->assertEquals('foo', $user->getUID()); - } - - /** - * @expectedException \Exception - */ - public function testCreateUserSingleBackendExists() { - /** - * @var \Test\Util\User\Dummy | \PHPUnit_Framework_MockObject_MockObject $backend - */ - $backend = $this->createMock('\Test\Util\User\Dummy'); - $backend->expects($this->any()) - ->method('implementsActions') - ->will($this->returnValue(true)); - - $backend->expects($this->never()) - ->method('createUser'); - - $backend->expects($this->once()) - ->method('userExists') - ->with($this->equalTo('foo')) - ->will($this->returnValue(true)); - - $manager = new \OC\User\Manager(); - $manager->registerBackend($backend); - - $manager->createUser('foo', 'bar'); - } - - public function testCreateUserSingleBackendNotSupported() { - /** - * @var \Test\Util\User\Dummy | \PHPUnit_Framework_MockObject_MockObject $backend - */ - $backend = $this->createMock('\Test\Util\User\Dummy'); - $backend->expects($this->any()) - ->method('implementsActions') - ->will($this->returnValue(false)); - - $backend->expects($this->never()) - ->method('createUser'); - - $backend->expects($this->once()) - ->method('userExists') - ->with($this->equalTo('foo')) - ->will($this->returnValue(false)); - - $manager = new \OC\User\Manager(); - $manager->registerBackend($backend); - - $this->assertFalse($manager->createUser('foo', 'bar')); - } - - public function testCreateUserNoBackends() { - $manager = new \OC\User\Manager(); - - $this->assertFalse($manager->createUser('foo', 'bar')); - } - - /** - * @expectedException \Exception - */ - public function testCreateUserTwoBackendExists() { - /** - * @var \Test\Util\User\Dummy | \PHPUnit_Framework_MockObject_MockObject $backend1 - */ - $backend1 = $this->createMock('\Test\Util\User\Dummy'); - $backend1->expects($this->any()) - ->method('implementsActions') - ->will($this->returnValue(true)); - - $backend1->expects($this->never()) - ->method('createUser'); - - $backend1->expects($this->once()) - ->method('userExists') - ->with($this->equalTo('foo')) - ->will($this->returnValue(false)); - - /** - * @var \Test\Util\User\Dummy | \PHPUnit_Framework_MockObject_MockObject $backend2 - */ - $backend2 = $this->createMock('\Test\Util\User\Dummy'); - $backend2->expects($this->any()) - ->method('implementsActions') - ->will($this->returnValue(true)); - - $backend2->expects($this->never()) - ->method('createUser'); - - $backend2->expects($this->once()) - ->method('userExists') - ->with($this->equalTo('foo')) - ->will($this->returnValue(true)); - - $manager = new \OC\User\Manager(); - $manager->registerBackend($backend1); - $manager->registerBackend($backend2); - - $manager->createUser('foo', 'bar'); - } - public function testCountUsersNoBackend() { - $manager = new \OC\User\Manager(); - - $result = $manager->countUsers(); - $this->assertTrue(is_array($result)); - $this->assertTrue(empty($result)); + $this->accountMapper->expects($this->once())->method('getUserCountPerBackend')->willReturn([]); + $result = $this->manager->countUsers(); + $this->assertEquals([], $result); } public function testCountUsersOneBackend() { - /** - * @var \Test\Util\User\Dummy | \PHPUnit_Framework_MockObject_MockObject $backend - */ - $backend = $this->createMock('\Test\Util\User\Dummy'); - $backend->expects($this->once()) - ->method('countUsers') - ->will($this->returnValue(7)); - - $backend->expects($this->once()) - ->method('implementsActions') - ->with(\OC_USER_BACKEND_COUNT_USERS) - ->will($this->returnValue(true)); - - $backend->expects($this->once()) - ->method('getBackendName') - ->will($this->returnValue('Mock_Test_Util_User_Dummy')); - - $manager = new \OC\User\Manager(); - $manager->registerBackend($backend); + $this->accountMapper->expects($this->once())->method('getUserCountPerBackend')->willReturn([ + 'dummy' => 7 + ]); - $result = $manager->countUsers(); - $keys = array_keys($result); - $this->assertTrue(strpos($keys[0], 'Mock_Test_Util_User_Dummy') !== false); - - $users = array_shift($result); - $this->assertEquals(7, $users); - } - - public function testCountUsersTwoBackends() { - /** - * @var \Test\Util\User\Dummy | \PHPUnit_Framework_MockObject_MockObject $backend - */ - $backend1 = $this->createMock('\Test\Util\User\Dummy'); - $backend1->expects($this->once()) - ->method('countUsers') - ->will($this->returnValue(7)); - - $backend1->expects($this->once()) - ->method('implementsActions') - ->with(\OC_USER_BACKEND_COUNT_USERS) - ->will($this->returnValue(true)); - $backend1->expects($this->once()) - ->method('getBackendName') - ->will($this->returnValue('Mock_Test_Util_User_Dummy')); - - $backend2 = $this->createMock('\Test\Util\User\Dummy'); - $backend2->expects($this->once()) - ->method('countUsers') - ->will($this->returnValue(16)); - - $backend2->expects($this->once()) - ->method('implementsActions') - ->with(\OC_USER_BACKEND_COUNT_USERS) - ->will($this->returnValue(true)); - $backend2->expects($this->once()) - ->method('getBackendName') - ->will($this->returnValue('Mock_Test_Util_User_Dummy')); - - $manager = new \OC\User\Manager(); - $manager->registerBackend($backend1); - $manager->registerBackend($backend2); - - $result = $manager->countUsers(); - //because the backends have the same class name, only one value expected - $this->assertEquals(1, count($result)); - $keys = array_keys($result); - $this->assertTrue(strpos($keys[0], 'Mock_Test_Util_User_Dummy') !== false); - - $users = array_shift($result); - //users from backends shall be summed up - $this->assertEquals(7 + 16, $users); + $result = $this->manager->countUsers(); + $this->assertEquals(['dummy' => 7], $result); } public function testCountUsersOnlySeen() { - $manager = \OC::$server->getUserManager(); + $this->manager = \OC::$server->getUserManager(); + if ($this->manager->userExists('testseencount1')) { + $this->manager->get('testseencount1')->delete(); + } + if ($this->manager->userExists('testseencount2')) { + $this->manager->get('testseencount2')->delete(); + } + if ($this->manager->userExists('testseencount3')) { + $this->manager->get('testseencount3')->delete(); + } + if ($this->manager->userExists('testseencount4')) { + $this->manager->get('testseencount4')->delete(); + } + // count other users in the db before adding our own - $countBefore = $manager->countUsers(true); + $countBefore = $this->manager->countUsers(true); //Add test users - $user1 = $manager->createUser('testseencount1', 'testseencount1'); + $user1 = $this->manager->createUser('testseencount1', 'testseencount1'); $user1->updateLastLoginTimestamp(); - $user2 = $manager->createUser('testseencount2', 'testseencount2'); + $user2 = $this->manager->createUser('testseencount2', 'testseencount2'); $user2->updateLastLoginTimestamp(); - $user3 = $manager->createUser('testseencount3', 'testseencount3'); + $user3 = $this->manager->createUser('testseencount3', 'testseencount3'); - $user4 = $manager->createUser('testseencount4', 'testseencount4'); + $user4 = $this->manager->createUser('testseencount4', 'testseencount4'); $user4->updateLastLoginTimestamp(); - $this->assertEquals($countBefore + 3, $manager->countUsers(true)); + $this->assertEquals($countBefore + 3, $this->manager->countUsers(true)); //cleanup $user1->delete(); @@ -477,29 +210,42 @@ public function testCountUsersOnlySeen() { } public function testCallForSeenUsers() { - $manager = \OC::$server->getUserManager(); + $this->manager = \OC::$server->getUserManager(); + if ($this->manager->userExists('testseen1')) { + $this->manager->get('testseen1')->delete(); + } + if ($this->manager->userExists('testseen2')) { + $this->manager->get('testseen2')->delete(); + } + if ($this->manager->userExists('testseen3')) { + $this->manager->get('testseen3')->delete(); + } + if ($this->manager->userExists('testseen4')) { + $this->manager->get('testseen4')->delete(); + } + // count other users in the db before adding our own $count = 0; $function = function (IUser $user) use (&$count) { $count++; }; - $manager->callForAllUsers($function, '', true); + $this->manager->callForAllUsers($function, '', true); $countBefore = $count; //Add test users - $user1 = $manager->createUser('testseen1', 'testseen1'); + $user1 = $this->manager->createUser('testseen1', 'testseen1'); $user1->updateLastLoginTimestamp(); - $user2 = $manager->createUser('testseen2', 'testseen2'); + $user2 = $this->manager->createUser('testseen2', 'testseen2'); $user2->updateLastLoginTimestamp(); - $user3 = $manager->createUser('testseen3', 'testseen3'); + $user3 = $this->manager->createUser('testseen3', 'testseen3'); - $user4 = $manager->createUser('testseen4', 'testseen4'); + $user4 = $this->manager->createUser('testseen4', 'testseen4'); $user4->updateLastLoginTimestamp(); $count = 0; - $manager->callForAllUsers($function, '', true); + $this->manager->callForAllUsers($function, '', true); $this->assertEquals($countBefore + 3, $count); @@ -509,29 +255,4 @@ public function testCallForSeenUsers() { $user3->delete(); $user4->delete(); } - - public function testDeleteUser() { - $config = $this->getMockBuilder('OCP\IConfig') - ->disableOriginalConstructor() - ->getMock(); - $config - ->expects($this->at(0)) - ->method('getUserValue') - ->with('foo', 'core', 'enabled') - ->will($this->returnValue(true)); - $config - ->expects($this->at(1)) - ->method('getUserValue') - ->with('foo', 'login', 'lastLogin') - ->will($this->returnValue(0)); - - $manager = new \OC\User\Manager($config); - $backend = new \Test\Util\User\Dummy(); - - $manager->registerBackend($backend); - $backend->createUser('foo', 'bar'); - $this->assertTrue($manager->userExists('foo')); - $manager->get('foo')->delete(); - $this->assertFalse($manager->userExists('foo')); - } } diff --git a/tests/lib/User/SessionTest.php b/tests/lib/User/SessionTest.php index 68087f9fd015..17b998828ff0 100644 --- a/tests/lib/User/SessionTest.php +++ b/tests/lib/User/SessionTest.php @@ -9,19 +9,31 @@ namespace Test\User; +use OC\AppFramework\Http\Request; +use OC\Authentication\Exceptions\InvalidTokenException; +use OC\Authentication\Exceptions\PasswordlessTokenException; use OC\Authentication\Token\DefaultToken; use OC\Authentication\Token\IProvider; +use OC\Authentication\Token\IToken; +use OC\Security\CSRF\CsrfTokenManager; use OC\Session\Memory; +use OC\User\Manager; use OC\User\Session; -use OC\User\User; use OCP\AppFramework\Utility\ITimeFactory; use OCP\IConfig; +use OCP\IRequest; +use OCP\ISession; +use OCP\IUser; +use OCP\IUserManager; +use OCP\Security\ISecureRandom; +use OCP\Session\Exceptions\SessionNotAvailableException; +use Test\TestCase; /** * @group DB * @package Test\User */ -class SessionTest extends \Test\TestCase { +class SessionTest extends TestCase { /** @var \OCP\AppFramework\Utility\ITimeFactory | \PHPUnit_Framework_MockObject_MockObject */ private $timeFactory; @@ -48,18 +60,21 @@ public function testGetUser() { $token->setLoginName('User123'); $token->setLastCheck(200); - $expectedUser = $this->createMock('\OCP\IUser'); + /** @var IUser | \PHPUnit_Framework_MockObject_MockObject $expectedUser */ + $expectedUser = $this->createMock(IUser::class); $expectedUser->expects($this->any()) ->method('getUID') ->will($this->returnValue('user123')); - $session = $this->createMock('\OC\Session\Memory'); + /** @var Memory | \PHPUnit_Framework_MockObject_MockObject $session */ + $session = $this->createMock(Memory::class); $session->expects($this->at(0)) ->method('get') ->with('user_id') ->will($this->returnValue($expectedUser->getUID())); $sessionId = 'abcdef12345'; - $manager = $this->getMockBuilder('\OC\User\Manager') + /** @var Manager | \PHPUnit_Framework_MockObject_MockObject $manager */ + $manager = $this->getMockBuilder(Manager::class) ->disableOriginalConstructor() ->getMock(); $session->expects($this->at(1)) @@ -94,16 +109,17 @@ public function testGetUser() { ->with($expectedUser->getUID()) ->will($this->returnValue($expectedUser)); - $userSession = new \OC\User\Session($manager, $session, $this->timeFactory, $this->tokenProvider, $this->config); + $userSession = new Session($manager, $session, $this->timeFactory, $this->tokenProvider, $this->config); $user = $userSession->getUser(); $this->assertSame($expectedUser, $user); + $userSession->validateSession(); $this->assertSame(10000, $token->getLastCheck()); } public function isLoggedInData() { return [ - [true], - [false], + 'User is logged in' => [true], + 'User is not logged in' => [false], ]; } @@ -111,19 +127,21 @@ public function isLoggedInData() { * @dataProvider isLoggedInData */ public function testIsLoggedIn($isLoggedIn) { - $session = $this->createMock('\OC\Session\Memory'); + $session = $this->createMock(Memory::class); - $manager = $this->getMockBuilder('\OC\User\Manager') + $manager = $this->getMockBuilder(Manager::class) ->disableOriginalConstructor() ->getMock(); - $userSession = $this->getMockBuilder('\OC\User\Session') + /** @var \PHPUnit_Framework_MockObject_MockObject | Session $userSession */ + $userSession = $this->getMockBuilder(Session::class) ->setConstructorArgs([$manager, $session, $this->timeFactory, $this->tokenProvider, $this->config]) ->setMethods([ 'getUser' ]) ->getMock(); - $user = new User('sepp', null); + $user = $this->createMock(IUser::class); + $user->expects($this->any())->method('isEnabled')->willReturn(true); $userSession->expects($this->once()) ->method('getUser') ->will($this->returnValue($isLoggedIn ? $user : null)); @@ -131,34 +149,33 @@ public function testIsLoggedIn($isLoggedIn) { } public function testSetUser() { - $session = $this->createMock('\OC\Session\Memory'); + /** @var ISession | \PHPUnit_Framework_MockObject_MockObject $session */ + $session = $this->createMock(Memory::class); $session->expects($this->once()) ->method('set') ->with('user_id', 'foo'); - $manager = $this->createMock('\OC\User\Manager'); - - $backend = $this->createMock('\Test\Util\User\Dummy'); + /** @var Manager $manager */ + $manager = $this->createMock(Manager::class); - $user = $this->getMockBuilder('\OC\User\User') - ->setConstructorArgs(['foo', $backend]) - ->getMock(); + /** @var IUser | \PHPUnit_Framework_MockObject_MockObject $user */ + $user = $this->createMock(IUser::class); $user->expects($this->once()) ->method('getUID') ->will($this->returnValue('foo')); - $userSession = new \OC\User\Session($manager, $session, $this->timeFactory, $this->tokenProvider, $this->config); + $userSession = new Session($manager, $session, $this->timeFactory, $this->tokenProvider, $this->config); $userSession->setUser($user); } public function testLoginValidPasswordEnabled() { - $session = $this->createMock('\OC\Session\Memory'); + $session = $this->createMock(Memory::class); $session->expects($this->once()) ->method('regenerateId'); $this->tokenProvider->expects($this->once()) ->method('getToken') ->with('bar') - ->will($this->throwException(new \OC\Authentication\Exceptions\InvalidTokenException())); + ->will($this->throwException(new InvalidTokenException())); $session->expects($this->exactly(2)) ->method('set') ->with($this->callback(function ($key) { @@ -173,7 +190,7 @@ public function testLoginValidPasswordEnabled() { } }, 'foo')); - $managerMethods = get_class_methods('\OC\User\Manager'); + $managerMethods = get_class_methods(Manager::class); //keep following methods intact in order to ensure hooks are //working $doNotMock = ['__construct', 'emit', 'listen']; @@ -183,15 +200,12 @@ public function testLoginValidPasswordEnabled() { unset($managerMethods[$i]); } } - $manager = $this->getMockBuilder('\OC\User\Manager') - ->setMethods($managerMethods) - ->getMock(); - - $backend = $this->createMock('\Test\Util\User\Dummy'); +// $manager = $this->getMockBuilder(Manager::class) +// ->setMethods($managerMethods) +// ->getMock(); - $user = $this->getMockBuilder('\OC\User\User') - ->setConstructorArgs(['foo', $backend]) - ->getMock(); + $manager = $this->createMock(Manager::class); + $user = $this->createMock(IUser::class); $user->expects($this->any()) ->method('isEnabled') ->will($this->returnValue(true)); @@ -206,7 +220,8 @@ public function testLoginValidPasswordEnabled() { ->with('foo', 'bar') ->will($this->returnValue($user)); - $userSession = $this->getMockBuilder('\OC\User\Session') + /** @var Session | \PHPUnit_Framework_MockObject_MockObject $userSession */ + $userSession = $this->getMockBuilder(Session::class) ->setConstructorArgs([$manager, $session, $this->timeFactory, $this->tokenProvider, $this->config]) ->setMethods([ 'prepareUserLogin' @@ -222,7 +237,8 @@ public function testLoginValidPasswordEnabled() { * @expectedException \OC\User\LoginException */ public function testLoginValidPasswordDisabled() { - $session = $this->createMock('\OC\Session\Memory', [], ['']); + /** @var ISession | \PHPUnit_Framework_MockObject_MockObject $session */ + $session = $this->createMock(Memory::class); $session->expects($this->never()) ->method('set'); $session->expects($this->once()) @@ -230,23 +246,12 @@ public function testLoginValidPasswordDisabled() { $this->tokenProvider->expects($this->once()) ->method('getToken') ->with('bar') - ->will($this->throwException(new \OC\Authentication\Exceptions\InvalidTokenException())); - - $managerMethods = get_class_methods('\OC\User\Manager'); - //keep following methods intact in order to ensure hooks are - //working - $doNotMock = ['__construct', 'emit', 'listen']; - foreach ($doNotMock as $methodName) { - $i = array_search($methodName, $managerMethods, true); - if ($i !== false) { - unset($managerMethods[$i]); - } - } - $manager = $this->createMock('\OC\User\Manager', $managerMethods, []); + ->will($this->throwException(new InvalidTokenException())); - $backend = $this->createMock('\Test\Util\User\Dummy'); + /** @var Manager | \PHPUnit_Framework_MockObject_MockObject $manager */ + $manager = $this->createMock(Manager::class); - $user = $this->createMock('\OC\User\User', [], ['foo', $backend]); + $user = $this->createMock(IUser::class); $user->expects($this->any()) ->method('isEnabled') ->will($this->returnValue(false)); @@ -258,27 +263,18 @@ public function testLoginValidPasswordDisabled() { ->with('foo', 'bar') ->will($this->returnValue($user)); - $userSession = new \OC\User\Session($manager, $session, $this->timeFactory, $this->tokenProvider, $this->config); + $userSession = new Session($manager, $session, $this->timeFactory, $this->tokenProvider, $this->config); $userSession->login('foo', 'bar'); } public function testLoginInvalidPassword() { - $session = $this->createMock('\OC\Session\Memory', [], ['']); - $managerMethods = get_class_methods('\OC\User\Manager'); - //keep following methods intact in order to ensure hooks are - //working - $doNotMock = ['__construct', 'emit', 'listen']; - foreach ($doNotMock as $methodName) { - $i = array_search($methodName, $managerMethods, true); - if ($i !== false) { - unset($managerMethods[$i]); - } - } - $manager = $this->createMock('\OC\User\Manager', $managerMethods, []); - $backend = $this->createMock('\Test\Util\User\Dummy'); - $userSession = new \OC\User\Session($manager, $session, $this->timeFactory, $this->tokenProvider, $this->config); + /** @var ISession | \PHPUnit_Framework_MockObject_MockObject $session */ + $session = $this->createMock(Memory::class); + /** @var Manager | \PHPUnit_Framework_MockObject_MockObject $manager */ + $manager = $this->createMock(Manager::class); + $userSession = new Session($manager, $session, $this->timeFactory, $this->tokenProvider, $this->config); - $user = $this->createMock('\OC\User\User', [], ['foo', $backend]); + $user = $this->createMock(IUser::class); $session->expects($this->never()) ->method('set'); @@ -287,7 +283,7 @@ public function testLoginInvalidPassword() { $this->tokenProvider->expects($this->once()) ->method('getToken') ->with('bar') - ->will($this->throwException(new \OC\Authentication\Exceptions\InvalidTokenException())); + ->will($this->throwException(new InvalidTokenException())); $user->expects($this->never()) ->method('isEnabled'); @@ -303,10 +299,11 @@ public function testLoginInvalidPassword() { } public function testLoginNonExisting() { - $session = $this->createMock('\OC\Session\Memory', [], ['']); - $manager = $this->createMock('\OC\User\Manager'); - $backend = $this->createMock('\Test\Util\User\Dummy'); - $userSession = new \OC\User\Session($manager, $session, $this->timeFactory, $this->tokenProvider, $this->config); + /** @var ISession | \PHPUnit_Framework_MockObject_MockObject $session */ + $session = $this->createMock(Memory::class); + /** @var Manager | \PHPUnit_Framework_MockObject_MockObject $manager */ + $manager = $this->createMock(Manager::class); + $userSession = new Session($manager, $session, $this->timeFactory, $this->tokenProvider, $this->config); $session->expects($this->never()) ->method('set'); @@ -315,7 +312,7 @@ public function testLoginNonExisting() { $this->tokenProvider->expects($this->once()) ->method('getToken') ->with('bar') - ->will($this->throwException(new \OC\Authentication\Exceptions\InvalidTokenException())); + ->will($this->throwException(new InvalidTokenException())); $manager->expects($this->once()) ->method('checkPassword') @@ -330,10 +327,11 @@ public function testLoginNonExisting() { * when generating the token on the browser. */ public function testLoginWithDifferentTokenLoginName() { - $session = $this->createMock('\OC\Session\Memory', [], ['']); - $manager = $this->createMock('\OC\User\Manager'); - $backend = $this->createMock('\Test\Util\User\Dummy'); - $userSession = new \OC\User\Session($manager, $session, $this->timeFactory, $this->tokenProvider, $this->config); + /** @var ISession | \PHPUnit_Framework_MockObject_MockObject $session */ + $session = $this->createMock(Memory::class); + /** @var Manager | \PHPUnit_Framework_MockObject_MockObject $manager */ + $manager = $this->createMock(Manager::class); + $userSession = new Session($manager, $session, $this->timeFactory, $this->tokenProvider, $this->config); $username = 'user123'; $token = new DefaultToken(); $token->setLoginName($username); @@ -359,15 +357,15 @@ public function testLoginWithDifferentTokenLoginName() { * @expectedException \OC\Authentication\Exceptions\PasswordLoginForbiddenException */ public function testLogClientInNoTokenPasswordWith2fa() { - $manager = $this->getMockBuilder('\OC\User\Manager') + $manager = $this->getMockBuilder(Manager::class) ->disableOriginalConstructor() ->getMock(); - $session = $this->createMock('\OCP\ISession'); - $request = $this->createMock('\OCP\IRequest'); - $user = $this->createMock('\OCP\IUser'); + $session = $this->createMock(ISession::class); + /** @var IRequest | \PHPUnit_Framework_MockObject_MockObject $request */ + $request = $this->createMock(IRequest::class); - /** @var \OC\User\Session $userSession */ - $userSession = $this->getMockBuilder('\OC\User\Session') + /** @var Session $userSession */ + $userSession = $this->getMockBuilder(Session::class) ->setConstructorArgs([$manager, $session, $this->timeFactory, $this->tokenProvider, $this->config]) ->setMethods(['login', 'supportsCookies', 'createSessionToken', 'getUser']) ->getMock(); @@ -375,7 +373,7 @@ public function testLogClientInNoTokenPasswordWith2fa() { $this->tokenProvider->expects($this->once()) ->method('getToken') ->with('doe') - ->will($this->throwException(new \OC\Authentication\Exceptions\InvalidTokenException())); + ->will($this->throwException(new InvalidTokenException())); $this->config->expects($this->once()) ->method('getSystemValue') ->with('token_auth_enforced', false) @@ -385,15 +383,15 @@ public function testLogClientInNoTokenPasswordWith2fa() { } public function testLogClientInUnexist() { - $manager = $this->getMockBuilder('\OC\User\Manager') + $manager = $this->getMockBuilder(Manager::class) ->disableOriginalConstructor() ->getMock(); - $session = $this->createMock('\OCP\ISession'); - $request = $this->createMock('\OCP\IRequest'); - $user = $this->createMock('\OCP\IUser'); + $session = $this->createMock(ISession::class); + /** @var IRequest | \PHPUnit_Framework_MockObject_MockObject $request */ + $request = $this->createMock(IRequest::class); - /** @var \OC\User\Session $userSession */ - $userSession = $this->getMockBuilder('\OC\User\Session') + /** @var Session $userSession */ + $userSession = $this->getMockBuilder(Session::class) ->setConstructorArgs([$manager, $session, $this->timeFactory, $this->tokenProvider, $this->config]) ->setMethods(['login', 'supportsCookies', 'createSessionToken', 'getUser']) ->getMock(); @@ -401,7 +399,7 @@ public function testLogClientInUnexist() { $this->tokenProvider->expects($this->once()) ->method('getToken') ->with('doe') - ->will($this->throwException(new \OC\Authentication\Exceptions\InvalidTokenException())); + ->will($this->throwException(new InvalidTokenException())); $this->config->expects($this->once()) ->method('getSystemValue') ->with('token_auth_enforced', false) @@ -411,15 +409,15 @@ public function testLogClientInUnexist() { } public function testLogClientInWithTokenPassword() { - $manager = $this->getMockBuilder('\OC\User\Manager') + $manager = $this->getMockBuilder(Manager::class) ->disableOriginalConstructor() ->getMock(); - $session = $this->createMock('\OCP\ISession'); - $request = $this->createMock('\OCP\IRequest'); - $user = $this->createMock('\OCP\IUser'); + $session = $this->createMock(ISession::class); + /** @var IRequest | \PHPUnit_Framework_MockObject_MockObject $request */ + $request = $this->createMock(IRequest::class); - /** @var \OC\User\Session $userSession */ - $userSession = $this->getMockBuilder('\OC\User\Session') + /** @var Session | \PHPUnit_Framework_MockObject_MockObject $userSession */ + $userSession = $this->getMockBuilder(Session::class) ->setConstructorArgs([$manager, $session, $this->timeFactory, $this->tokenProvider, $this->config]) ->setMethods(['isTokenPassword', 'login', 'supportsCookies', 'createSessionToken', 'getUser']) ->getMock(); @@ -443,15 +441,15 @@ public function testLogClientInWithTokenPassword() { * @expectedException \OC\Authentication\Exceptions\PasswordLoginForbiddenException */ public function testLogClientInNoTokenPasswordNo2fa() { - $manager = $this->getMockBuilder('\OC\User\Manager') + $manager = $this->getMockBuilder(Manager::class) ->disableOriginalConstructor() ->getMock(); - $session = $this->createMock('\OCP\ISession'); - $user = $this->createMock('\OCP\IUser'); - $request = $this->createMock('\OCP\IRequest'); + $session = $this->createMock(ISession::class); + /** @var IRequest | \PHPUnit_Framework_MockObject_MockObject $request */ + $request = $this->createMock(IRequest::class); - /** @var \OC\User\Session $userSession */ - $userSession = $this->getMockBuilder('\OC\User\Session') + /** @var Session | \PHPUnit_Framework_MockObject_MockObject $userSession */ + $userSession = $this->getMockBuilder(Session::class) ->setConstructorArgs([$manager, $session, $this->timeFactory, $this->tokenProvider, $this->config]) ->setMethods(['login', 'isTwoFactorEnforced']) ->getMock(); @@ -459,7 +457,7 @@ public function testLogClientInNoTokenPasswordNo2fa() { $this->tokenProvider->expects($this->once()) ->method('getToken') ->with('doe') - ->will($this->throwException(new \OC\Authentication\Exceptions\InvalidTokenException())); + ->will($this->throwException(new InvalidTokenException())); $this->config->expects($this->once()) ->method('getSystemValue') ->with('token_auth_enforced', false) @@ -474,7 +472,7 @@ public function testLogClientInNoTokenPasswordNo2fa() { } public function testRememberLoginValidToken() { - $session = $this->createMock('\OC\Session\Memory'); + $session = $this->createMock(Memory::class); $session->expects($this->exactly(1)) ->method('set') ->with($this->callback(function ($key) { @@ -488,26 +486,8 @@ public function testRememberLoginValidToken() { $session->expects($this->once()) ->method('regenerateId'); - $managerMethods = get_class_methods('\OC\User\Manager'); - //keep following methods intact in order to ensure hooks are - //working - $doNotMock = ['__construct', 'emit', 'listen']; - foreach ($doNotMock as $methodName) { - $i = array_search($methodName, $managerMethods, true); - if ($i !== false) { - unset($managerMethods[$i]); - } - } - $manager = $this->getMockBuilder('\OC\User\Manager') - ->setMethods($managerMethods) - ->getMock(); - - $backend = $this->createMock('\Test\Util\User\Dummy'); - - $user = $this->getMockBuilder('\OC\User\User') - ->setConstructorArgs(['foo', $backend]) - ->getMock(); - + $manager = $this->createMock(Manager::class); + $user = $this->createMock(IUser::class); $user->expects($this->any()) ->method('getUID') ->will($this->returnValue('foo')); @@ -537,33 +517,16 @@ public function testRememberLoginValidToken() { } public function testRememberLoginInvalidToken() { - $session = $this->createMock('\OC\Session\Memory'); + /** @var ISession | \PHPUnit_Framework_MockObject_MockObject $session */ + $session = $this->createMock(Memory::class); $session->expects($this->never()) ->method('set'); $session->expects($this->once()) ->method('regenerateId'); - $managerMethods = get_class_methods('\OC\User\Manager'); - //keep following methods intact in order to ensure hooks are - //working - $doNotMock = ['__construct', 'emit', 'listen']; - foreach ($doNotMock as $methodName) { - $i = array_search($methodName, $managerMethods, true); - if ($i !== false) { - unset($managerMethods[$i]); - } - } - $manager = $this->getMockBuilder('\OC\User\Manager') - ->setMethods($managerMethods) - ->setConstructorArgs([]) - ->getMock(); - - $backend = $this->createMock('\Test\Util\User\Dummy'); - - $user = $this->getMockBuilder('\OC\User\User') - ->setConstructorArgs(['foo', $backend]) - ->getMock(); - + /** @var Manager | \PHPUnit_Framework_MockObject_MockObject $manager */ + $manager = $this->createMock(Manager::class); + $user = $this->createMock(IUser::class); $user->expects($this->any()) ->method('getUID') ->will($this->returnValue('foo')); @@ -579,41 +542,23 @@ public function testRememberLoginInvalidToken() { $token = 'goodToken'; \OC::$server->getConfig()->setUserValue('foo', 'login_token', $token, time()); - $userSession = new \OC\User\Session($manager, $session, $this->timeFactory, $this->tokenProvider, $this->config); + $userSession = new Session($manager, $session, $this->timeFactory, $this->tokenProvider, $this->config); $granted = $userSession->loginWithCookie('foo', 'badToken'); $this->assertSame($granted, false); } public function testRememberLoginInvalidUser() { -// $session = $this->createMock('\OC\Session\Memory', array(), array('')); - $session = $this->createMock('\OC\Session\Memory'); + /** @var ISession | \PHPUnit_Framework_MockObject_MockObject $session */ + $session = $this->createMock(Memory::class); $session->expects($this->never()) ->method('set'); $session->expects($this->once()) ->method('regenerateId'); - $managerMethods = get_class_methods('\OC\User\Manager'); - //keep following methods intact in order to ensure hooks are - //working - $doNotMock = ['__construct', 'emit', 'listen']; - foreach ($doNotMock as $methodName) { - $i = array_search($methodName, $managerMethods, true); - if ($i !== false) { - unset($managerMethods[$i]); - } - } - $manager = $this->getMockBuilder('\OC\User\Manager') - ->setMethods($managerMethods) - ->setConstructorArgs([]) - ->getMock(); - - $backend = $this->createMock('\Test\Util\User\Dummy'); - - $user = $this->getMockBuilder('\OC\User\User') - ->setMethods([]) - ->setConstructorArgs(['foo', $backend]) - ->getMock(); + /** @var Manager | \PHPUnit_Framework_MockObject_MockObject $manager */ + $manager = $this->createMock(Manager::class); + $user = $this->createMock(IUser::class); $user->expects($this->never()) ->method('getUID'); @@ -629,19 +574,21 @@ public function testRememberLoginInvalidUser() { $token = 'goodToken'; \OC::$server->getConfig()->setUserValue('foo', 'login_token', $token, time()); - $userSession = new \OC\User\Session($manager, $session, $this->timeFactory, $this->tokenProvider, $this->config); + $userSession = new Session($manager, $session, $this->timeFactory, $this->tokenProvider, $this->config); $granted = $userSession->loginWithCookie('foo', $token); $this->assertSame($granted, false); } public function testActiveUserAfterSetSession() { + $user1 = $this->createMock(IUser::class); + $user2 = $this->createMock(IUser::class); $users = [ - 'foo' => new User('foo', null), - 'bar' => new User('bar', null) + 'foo' => $user1, + 'bar' => $user2 ]; - $manager = $this->getMockBuilder('\OC\User\Manager') + $manager = $this->getMockBuilder(Manager::class) ->disableOriginalConstructor() ->getMock(); @@ -654,7 +601,7 @@ public function testActiveUserAfterSetSession() { $session = new Memory(''); $session->set('user_id', 'foo'); /** @var Session | \PHPUnit_Framework_MockObject_MockObject $userSession */ - $userSession = $this->getMockBuilder('\OC\User\Session') + $userSession = $this->getMockBuilder(Session::class) ->setConstructorArgs([$manager, $session, $this->timeFactory, $this->tokenProvider, $this->config]) ->setMethods([ 'validateSession' @@ -672,20 +619,19 @@ public function testActiveUserAfterSetSession() { } public function testCreateSessionToken() { - $manager = $this->getMockBuilder('\OC\User\Manager') - ->disableOriginalConstructor() - ->getMock(); - $session = $this->createMock('\OCP\ISession'); - $token = $this->createMock('\OC\Authentication\Token\IToken'); - $user = $this->createMock('\OCP\IUser'); - $userSession = new \OC\User\Session($manager, $session, $this->timeFactory, $this->tokenProvider, $this->config); - - $random = $this->createMock('\OCP\Security\ISecureRandom'); - $config = $this->createMock('\OCP\IConfig'); - $csrf = $this->getMockBuilder('\OC\Security\CSRF\CsrfTokenManager') + /** @var Manager | \PHPUnit_Framework_MockObject_MockObject $manager */ + $manager = $this->createMock(Manager::class); + /** @var ISession | \PHPUnit_Framework_MockObject_MockObject $session */ + $session = $this->createMock(ISession::class); + $user = $this->createMock(IUser::class); + $userSession = new Session($manager, $session, $this->timeFactory, $this->tokenProvider, $this->config); + + $random = $this->createMock(ISecureRandom::class); + $config = $this->createMock(IConfig::class); + $csrf = $this->getMockBuilder(CsrfTokenManager::class) ->disableOriginalConstructor() ->getMock(); - $request = new \OC\AppFramework\Http\Request([ + $request = new Request([ 'server' => [ 'HTTP_USER_AGENT' => 'Firefox', ] @@ -706,7 +652,7 @@ public function testCreateSessionToken() { $this->tokenProvider->expects($this->once()) ->method('getToken') ->with($password) - ->will($this->throwException(new \OC\Authentication\Exceptions\InvalidTokenException())); + ->will($this->throwException(new InvalidTokenException())); $this->tokenProvider->expects($this->once()) ->method('generateToken') @@ -716,20 +662,23 @@ public function testCreateSessionToken() { } public function testCreateSessionTokenWithTokenPassword() { - $manager = $this->getMockBuilder('\OC\User\Manager') + /** @var Manager | \PHPUnit_Framework_MockObject_MockObject $manager */ + $manager = $this->getMockBuilder(Manager::class) ->disableOriginalConstructor() ->getMock(); - $session = $this->createMock('\OCP\ISession'); - $token = $this->createMock('\OC\Authentication\Token\IToken'); - $user = $this->createMock('\OCP\IUser'); - $userSession = new \OC\User\Session($manager, $session, $this->timeFactory, $this->tokenProvider, $this->config); - - $random = $this->createMock('\OCP\Security\ISecureRandom'); - $config = $this->createMock('\OCP\IConfig'); - $csrf = $this->getMockBuilder('\OC\Security\CSRF\CsrfTokenManager') + /** @var ISession | \PHPUnit_Framework_MockObject_MockObject $session */ + $session = $this->createMock(ISession::class); + /** @var IToken | \PHPUnit_Framework_MockObject_MockObject $token */ + $token = $this->createMock(IToken::class); + $user = $this->createMock(IUser::class); + $userSession = new Session($manager, $session, $this->timeFactory, $this->tokenProvider, $this->config); + + $random = $this->createMock(ISecureRandom::class); + $config = $this->createMock(IConfig::class); + $csrf = $this->getMockBuilder(CsrfTokenManager::class) ->disableOriginalConstructor() ->getMock(); - $request = new \OC\AppFramework\Http\Request([ + $request = new Request([ 'server' => [ 'HTTP_USER_AGENT' => 'Firefox', ] @@ -765,12 +714,15 @@ public function testCreateSessionTokenWithTokenPassword() { } public function testCreateSessionTokenWithNonExistentUser() { - $manager = $this->getMockBuilder('\OC\User\Manager') + /** @var Manager | \PHPUnit_Framework_MockObject_MockObject $manager */ + $manager = $this->getMockBuilder(Manager::class) ->disableOriginalConstructor() ->getMock(); - $session = $this->createMock('\OCP\ISession'); - $userSession = new \OC\User\Session($manager, $session, $this->timeFactory, $this->tokenProvider, $this->config); - $request = $this->createMock('\OCP\IRequest'); + /** @var ISession | \PHPUnit_Framework_MockObject_MockObject $session */ + $session = $this->createMock(ISession::class); + $userSession = new Session($manager, $session, $this->timeFactory, $this->tokenProvider, $this->config); + /** @var IRequest $request */ + $request = $this->createMock(IRequest::class); $uid = 'user123'; $loginName = 'User123'; @@ -788,7 +740,7 @@ public function testCreateSessionTokenWithNonExistentUser() { * @expectedException \OC\User\LoginException */ public function testTryTokenLoginWithDisabledUser() { - $manager = $this->getMockBuilder('\OC\User\Manager') + $manager = $this->getMockBuilder(Manager::class) ->disableOriginalConstructor() ->getMock(); $session = new Memory(''); @@ -796,12 +748,14 @@ public function testTryTokenLoginWithDisabledUser() { $token->setLoginName('fritz'); $token->setUid('fritz0'); $token->setLastCheck(100); // Needs check - $user = $this->createMock('\OCP\IUser'); - $userSession = $this->getMockBuilder('\OC\User\Session') + $user = $this->createMock(IUser::class); + /** @var Session | \PHPUnit_Framework_MockObject_MockObject $userSession */ + $userSession = $this->getMockBuilder(Session::class) ->setMethods(['logout']) ->setConstructorArgs([$manager, $session, $this->timeFactory, $this->tokenProvider, $this->config]) ->getMock(); - $request = $this->createMock('\OCP\IRequest'); + /** @var IRequest | \PHPUnit_Framework_MockObject_MockObject $request */ + $request = $this->createMock(IRequest::class); $request->expects($this->once()) ->method('getHeader') @@ -823,16 +777,19 @@ public function testTryTokenLoginWithDisabledUser() { } public function testValidateSessionDisabledUser() { - $userManager = $this->createMock('\OCP\IUserManager'); - $session = $this->createMock('\OCP\ISession'); - $timeFactory = $this->createMock('\OCP\AppFramework\Utility\ITimeFactory'); - $tokenProvider = $this->createMock('\OC\Authentication\Token\IProvider'); - $userSession = $this->getMockBuilder('\OC\User\Session') + $userManager = $this->createMock(IUserManager::class); + $session = $this->createMock(ISession::class); + $timeFactory = $this->createMock(ITimeFactory::class); + $tokenProvider = $this->createMock(IProvider::class); + + /** @var Session | \PHPUnit_Framework_MockObject_MockObject $userSession */ + $userSession = $this->getMockBuilder(Session::class) ->setConstructorArgs([$userManager, $session, $timeFactory, $tokenProvider, $this->config]) ->setMethods(['logout']) ->getMock(); - $user = $this->createMock('\OCP\IUser'); + /** @var IUser | \PHPUnit_Framework_MockObject_MockObject $user */ + $user = $this->createMock(IUser::class); $token = new DefaultToken(); $token->setLoginName('susan'); $token->setLastCheck(20); @@ -866,20 +823,25 @@ public function testValidateSessionDisabledUser() { ->method('logout'); $userSession->setUser($user); - $this->invokePrivate($userSession, 'validateSession'); + $userSession->validateSession(); } public function testValidateSessionNoPassword() { - $userManager = $this->createMock('\OCP\IUserManager'); - $session = $this->createMock('\OCP\ISession'); - $timeFactory = $this->createMock('\OCP\AppFramework\Utility\ITimeFactory'); - $tokenProvider = $this->createMock('\OC\Authentication\Token\IProvider'); - $userSession = $this->getMockBuilder('\OC\User\Session') + $userManager = $this->createMock(IUserManager::class); + $session = $this->createMock(ISession::class); + $timeFactory = $this->createMock(ITimeFactory::class); + $tokenProvider = $this->createMock(IProvider::class); + /** @var Session | \PHPUnit_Framework_MockObject_MockObject $userSession */ + $userSession = $this->getMockBuilder(Session::class) ->setConstructorArgs([$userManager, $session, $timeFactory, $tokenProvider, $this->config]) ->setMethods(['logout']) ->getMock(); - $user = $this->createMock('\OCP\IUser'); + /** @var IUser | \PHPUnit_Framework_MockObject_MockObject $user */ + $user = $this->createMock(IUser::class); + $user->expects($this->once()) + ->method('isEnabled') + ->willReturn(true); $token = new DefaultToken(); $token->setLastCheck(20); @@ -897,22 +859,27 @@ public function testValidateSessionNoPassword() { $tokenProvider->expects($this->once()) ->method('getPassword') ->with($token, 'APP-PASSWORD') - ->will($this->throwException(new \OC\Authentication\Exceptions\PasswordlessTokenException())); + ->will($this->throwException(new PasswordlessTokenException())); $tokenProvider->expects($this->once()) ->method('updateToken') ->with($token); - $this->invokePrivate($userSession, 'validateSession', [$user]); + $userSession->setUser($user); + $userSession->validateSession(); $this->assertEquals(1000, $token->getLastCheck()); } public function testUpdateSessionTokenPassword() { - $userManager = $this->createMock('\OCP\IUserManager'); - $session = $this->createMock('\OCP\ISession'); - $timeFactory = $this->createMock('\OCP\AppFramework\Utility\ITimeFactory'); - $tokenProvider = $this->createMock('\OC\Authentication\Token\IProvider'); - $userSession = new \OC\User\Session($userManager, $session, $timeFactory, $tokenProvider, $this->config); + /** @var IUserManager | \PHPUnit_Framework_MockObject_MockObject $userManager */ + $userManager = $this->createMock(IUserManager::class); + /** @var ISession | \PHPUnit_Framework_MockObject_MockObject $session */ + $session = $this->createMock(ISession::class); + /** @var ITimeFactory | \PHPUnit_Framework_MockObject_MockObject $timeFactory */ + $timeFactory = $this->createMock(ITimeFactory::class); + /** @var IProvider | \PHPUnit_Framework_MockObject_MockObject $tokenProvider */ + $tokenProvider = $this->createMock(IProvider::class); + $userSession = new Session($userManager, $session, $timeFactory, $tokenProvider, $this->config); $password = '123456'; $sessionId ='session1234'; @@ -933,25 +900,33 @@ public function testUpdateSessionTokenPassword() { } public function testUpdateSessionTokenPasswordNoSessionAvailable() { - $userManager = $this->createMock('\OCP\IUserManager'); - $session = $this->createMock('\OCP\ISession'); - $timeFactory = $this->createMock('\OCP\AppFramework\Utility\ITimeFactory'); - $tokenProvider = $this->createMock('\OC\Authentication\Token\IProvider'); - $userSession = new \OC\User\Session($userManager, $session, $timeFactory, $tokenProvider, $this->config); + /** @var IUserManager | \PHPUnit_Framework_MockObject_MockObject $userManager */ + $userManager = $this->createMock(IUserManager::class); + /** @var ISession | \PHPUnit_Framework_MockObject_MockObject $session */ + $session = $this->createMock(ISession::class); + /** @var ITimeFactory | \PHPUnit_Framework_MockObject_MockObject $timeFactory */ + $timeFactory = $this->createMock(ITimeFactory::class); + /** @var IProvider | \PHPUnit_Framework_MockObject_MockObject $tokenProvider */ + $tokenProvider = $this->createMock(IProvider::class); + $userSession = new Session($userManager, $session, $timeFactory, $tokenProvider, $this->config); $session->expects($this->once()) ->method('getId') - ->will($this->throwException(new \OCP\Session\Exceptions\SessionNotAvailableException())); + ->will($this->throwException(new SessionNotAvailableException())); $userSession->updateSessionTokenPassword('1234'); } public function testUpdateSessionTokenPasswordInvalidTokenException() { - $userManager = $this->createMock('\OCP\IUserManager'); - $session = $this->createMock('\OCP\ISession'); - $timeFactory = $this->createMock('\OCP\AppFramework\Utility\ITimeFactory'); - $tokenProvider = $this->createMock('\OC\Authentication\Token\IProvider'); - $userSession = new \OC\User\Session($userManager, $session, $timeFactory, $tokenProvider, $this->config); + /** @var IUserManager | \PHPUnit_Framework_MockObject_MockObject $userManager */ + $userManager = $this->createMock(IUserManager::class); + /** @var ISession | \PHPUnit_Framework_MockObject_MockObject $session */ + $session = $this->createMock(ISession::class); + /** @var ITimeFactory | \PHPUnit_Framework_MockObject_MockObject $timeFactory */ + $timeFactory = $this->createMock(ITimeFactory::class); + /** @var IProvider | \PHPUnit_Framework_MockObject_MockObject $tokenProvider */ + $tokenProvider = $this->createMock(IProvider::class); + $userSession = new Session($userManager, $session, $timeFactory, $tokenProvider, $this->config); $password = '123456'; $sessionId ='session1234'; @@ -967,7 +942,7 @@ public function testUpdateSessionTokenPasswordInvalidTokenException() { $tokenProvider->expects($this->once()) ->method('setPassword') ->with($token, $sessionId, $password) - ->will($this->throwException(new \OC\Authentication\Exceptions\InvalidTokenException())); + ->will($this->throwException(new InvalidTokenException())); $userSession->updateSessionTokenPassword($password); } diff --git a/tests/lib/User/UserTest.php b/tests/lib/User/UserTest.php index 341bb56c9515..3066b6e7e20d 100644 --- a/tests/lib/User/UserTest.php +++ b/tests/lib/User/UserTest.php @@ -10,14 +10,16 @@ namespace Test\User; use OC\Hooks\PublicEmitter; +use OC\User\Account; +use OC\User\AccountMapper; use OC\User\Backend; use OC\User\Database; use OC\User\User; use OCP\IConfig; +use OCP\IURLGenerator; +use OCP\User\IChangePasswordBackend; use Symfony\Component\EventDispatcher\EventDispatcher; -use Symfony\Component\EventDispatcher\GenericEvent; use Test\TestCase; -use Test\Util\User\Dummy; /** * Class UserTest @@ -27,409 +29,222 @@ * @package Test\User */ class UserTest extends TestCase { - public function testDisplayName() { - /** - * @var Backend | \PHPUnit_Framework_MockObject_MockObject $backend - */ - $backend = $this->createMock('\OC\User\Backend'); - $backend->expects($this->once()) - ->method('getDisplayName') - ->with($this->equalTo('foo')) - ->will($this->returnValue('Foo')); - $backend->expects($this->any()) - ->method('implementsActions') - ->with($this->equalTo(Backend::GET_DISPLAYNAME)) - ->will($this->returnValue(true)); + /** @var AccountMapper | \PHPUnit_Framework_MockObject_MockObject */ + private $accountMapper; + /** @var Account */ + private $account; + /** @var User */ + private $user; + /** @var IConfig | \PHPUnit_Framework_MockObject_MockObject */ + private $config; + /** @var PublicEmitter */ + private $emitter; + /** @var EventDispatcher | \PHPUnit_Framework_MockObject_MockObject */ + private $eventDispatcher; + /** @var IURLGenerator | \PHPUnit_Framework_MockObject_MockObject */ + private $urlGenerator; + + public function setUp() { + parent::setUp(); + $this->accountMapper = $this->createMock(AccountMapper::class); + $this->config = $this->createMock(IConfig::class); + $this->account = new Account(); + $this->account->setUserId('foo'); + $this->emitter = new PublicEmitter(); + $this->eventDispatcher = $this->createMock(EventDispatcher::class); + $this->urlGenerator = $this->getMockBuilder('\OC\URLGenerator') + ->setMethods(['getAbsoluteURL']) + ->disableOriginalConstructor() + ->getMock(); + + $this->user = new User($this->account, $this->accountMapper, $this->emitter, $this->config, $this->urlGenerator, $this->eventDispatcher); + } - $user = new User('foo', $backend); - $this->assertEquals('Foo', $user->getDisplayName()); + public function testDisplayName() { + $this->account->setDisplayName('Foo'); + $this->assertEquals('Foo', $this->user->getDisplayName()); } /** * if the display name contain whitespaces only, we expect the uid as result */ public function testDisplayNameEmpty() { - /** - * @var Backend | \PHPUnit_Framework_MockObject_MockObject $backend - */ - $backend = $this->createMock('\OC\User\Backend'); - $backend->expects($this->once()) - ->method('getDisplayName') - ->with($this->equalTo('foo')) - ->will($this->returnValue(' ')); - - $backend->expects($this->any()) - ->method('implementsActions') - ->with($this->equalTo(Backend::GET_DISPLAYNAME)) - ->will($this->returnValue(true)); - - $user = new User('foo', $backend); - $this->assertEquals('foo', $user->getDisplayName()); - } - - public function testDisplayNameNotSupported() { - /** - * @var Backend | \PHPUnit_Framework_MockObject_MockObject $backend - */ - $backend = $this->createMock('\OC\User\Backend'); - $backend->expects($this->never()) - ->method('getDisplayName'); - - $backend->expects($this->any()) - ->method('implementsActions') - ->with($this->equalTo(Backend::GET_DISPLAYNAME)) - ->will($this->returnValue(false)); - - $user = new User('foo', $backend); - $this->assertEquals('foo', $user->getDisplayName()); + $this->assertEquals('foo', $this->user->getDisplayName()); } public function testSetPassword() { - /** @var Backend | \PHPUnit_Framework_MockObject_MockObject $backend */ - $backend = $this->createMock(Dummy::class); - $backend->expects($this->once()) - ->method('setPassword') - ->with($this->equalTo('foo'), $this->equalTo('bar')) - ->willReturn(true); - - $backend->expects($this->any()) - ->method('implementsActions') - ->will($this->returnCallback(function ($actions) { - if ($actions === Backend::SET_PASSWORD) { - return true; - } else { - return false; - } - })); - $config = $this->createMock(IConfig::class); - $config->expects($this->once()) + $this->config->expects($this->once()) ->method('deleteUserValue') ->with('foo', 'owncloud', 'lostpassword'); - $user = new User('foo', $backend, null, $config); - $this->assertTrue($user->setPassword('bar','')); - } + $backend = $this->createMock(IChangePasswordBackend::class); + /** @var Account | \PHPUnit_Framework_MockObject_MockObject $account */ + $account = $this->createMock(Account::class); + $account->expects($this->any())->method('getBackendInstance')->willReturn($backend); + $account->expects($this->any())->method('__call')->with('getUserId')->willReturn('foo'); + $backend->expects($this->once())->method('setPassword')->with('foo', 'bar')->willReturn(true); + + $this->user = new User($account, $this->accountMapper, null, $this->config); + $this->assertTrue($this->user->setPassword('bar','')); + $this->assertTrue($this->user->canChangePassword()); + } public function testSetPasswordNotSupported() { - /** - * @var Backend | \PHPUnit_Framework_MockObject_MockObject $backend - */ - $backend = $this->createMock(Dummy::class); - $backend->expects($this->never()) - ->method('setPassword'); + $this->config->expects($this->never()) + ->method('deleteUserValue') + ->with('foo', 'owncloud', 'lostpassword'); - $backend->expects($this->any()) - ->method('implementsActions') - ->will($this->returnValue(false)); + $backend = $this->createMock(IChangePasswordBackend::class); + /** @var Account | \PHPUnit_Framework_MockObject_MockObject $account */ + $account = $this->createMock(Account::class); + $account->expects($this->any())->method('getBackendInstance')->willReturn($backend); + $account->expects($this->any())->method('__call')->with('getUserId')->willReturn('foo'); + $backend->expects($this->once())->method('setPassword')->with('foo', 'bar')->willReturn(false); - $user = new User('foo', $backend); - $this->assertFalse($user->setPassword('bar','')); + $this->user = new User($account, $this->accountMapper, null, $this->config); + $this->assertFalse($this->user->setPassword('bar','')); + $this->assertTrue($this->user->canChangePassword()); } - public function testChangeAvatarSupportedYes() { - /** - * @var Backend | \PHPUnit_Framework_MockObject_MockObject $backend - */ - $backend = $this->createMock('Test\User\AvatarUserDummy'); - $backend->expects($this->once()) - ->method('canChangeAvatar') - ->with($this->equalTo('foo')) - ->will($this->returnValue(true)); - - $backend->expects($this->any()) - ->method('implementsActions') - ->will($this->returnCallback(function ($actions) { - if ($actions === Backend::PROVIDE_AVATAR) { - return true; - } else { - return false; - } - })); + public function testSetPasswordNoBackend() { + $this->assertFalse($this->user->setPassword('bar','')); + $this->assertFalse($this->user->canChangePassword()); + } - $user = new User('foo', $backend); - $this->assertTrue($user->canChangeAvatar()); + public function providesChangeAvatarSupported() { + return [ + [true, true, true], + [false, true, false], + [true, false, null] + ]; } - public function testChangeAvatarSupportedNo() { - /** - * @var Backend | \PHPUnit_Framework_MockObject_MockObject $backend - */ - $backend = $this->createMock('Test\User\AvatarUserDummy'); - $backend->expects($this->once()) - ->method('canChangeAvatar') - ->with($this->equalTo('foo')) - ->will($this->returnValue(false)); + /** + * @dataProvider providesChangeAvatarSupported + */ + public function testChangeAvatarSupported($expected, $implements, $canChange) { + $backend = $this->getMockBuilder(Database::class) + ->setMethods(['canChangeAvatar', 'implementsActions']) + ->getMock(); + $backend->expects($this->any())->method('canChangeAvatar')->willReturn($canChange); + + /** @var Account | \PHPUnit_Framework_MockObject_MockObject $account */ + $account = $this->createMock(Account::class); + $account->expects($this->any())->method('getBackendInstance')->willReturn($backend); + $account->expects($this->any())->method('__call')->with('getUserId')->willReturn('foo'); $backend->expects($this->any()) ->method('implementsActions') - ->will($this->returnCallback(function ($actions) { + ->will($this->returnCallback(function ($actions) use ($implements) { if ($actions === Backend::PROVIDE_AVATAR) { - return true; + return $implements; } else { return false; } })); - $user = new User('foo', $backend); - $this->assertFalse($user->canChangeAvatar()); - } - - public function testChangeAvatarNotSupported() { - /** - * @var Backend | \PHPUnit_Framework_MockObject_MockObject $backend - */ - $backend = $this->createMock('Test\User\AvatarUserDummy'); - $backend->expects($this->never()) - ->method('canChangeAvatar'); - - $backend->expects($this->any()) - ->method('implementsActions') - ->will($this->returnCallback(function ($actions) { - return false; - })); - - $user = new User('foo', $backend); - $this->assertTrue($user->canChangeAvatar()); + $user = new User($account, $this->accountMapper, null, $this->config); + $this->assertEquals($expected, $user->canChangeAvatar()); } public function testDelete() { - /** - * @var Backend | \PHPUnit_Framework_MockObject_MockObject $backend - */ - $backend = $this->createMock(Dummy::class); - $backend->expects($this->once()) - ->method('deleteUser') - ->with($this->equalTo('foo')); - - $user = new User('foo', $backend); - $this->assertTrue($user->delete()); - } - - public function testDeleteWithDifferentHome() { - /** - * @var Backend | \PHPUnit_Framework_MockObject_MockObject $backend - */ - $backend = $this->createMock(Dummy::class); - - $backend->expects($this->at(0)) - ->method('implementsActions') - ->will($this->returnCallback(function ($actions) { - if ($actions === Backend::GET_HOME) { - return true; - } else { - return false; - } - })); - - // important: getHome MUST be called before deleteUser because - // once the user is deleted, getHome implementations might not - // return anything - $backend->expects($this->at(1)) - ->method('getHome') - ->with($this->equalTo('foo')) - ->will($this->returnValue('/home/foo')); - - $backend->expects($this->at(2)) - ->method('deleteUser') - ->with($this->equalTo('foo')); - - $user = new User('foo', $backend); - $this->assertTrue($user->delete()); + $this->accountMapper->expects($this->once())->method('delete')->willReturn($this->account); + $this->assertTrue($this->user->delete()); } public function testGetHome() { - /** - * @var Backend | \PHPUnit_Framework_MockObject_MockObject $backend - */ - $backend = $this->createMock(Dummy::class); - $backend->expects($this->once()) - ->method('getHome') - ->with($this->equalTo('foo')) - ->will($this->returnValue('/home/foo')); - - $backend->expects($this->any()) - ->method('implementsActions') - ->will($this->returnCallback(function ($actions) { - if ($actions === Backend::GET_HOME) { - return true; - } else { - return false; - } - })); - - $user = new User('foo', $backend); - $this->assertEquals('/home/foo', $user->getHome()); + $this->account->setHome('/home/foo'); + $this->assertEquals('/home/foo', $this->user->getHome()); } public function testGetBackendClassName() { - $user = new User('foo', new Dummy()); - $this->assertEquals('Dummy', $user->getBackendClassName()); - $user = new User('foo', new Database()); - $this->assertEquals('Database', $user->getBackendClassName()); + \OC::$server->getUserManager()->registerBackend(new Database()); + $this->account->setBackend(Database::class); + $this->assertEquals('Database', $this->user->getBackendClassName()); } public function testGetHomeNotSupported() { - /** - * @var Backend | \PHPUnit_Framework_MockObject_MockObject $backend - */ - $backend = $this->createMock(Dummy::class); - $backend->expects($this->never()) - ->method('getHome'); - - $backend->expects($this->any()) - ->method('implementsActions') - ->will($this->returnValue(false)); - - $allConfig = $this->getMockBuilder('\OCP\IConfig') - ->disableOriginalConstructor() - ->getMock(); - $allConfig->expects($this->any()) + $this->config->expects($this->any()) ->method('getUserValue') ->will($this->returnValue(true)); - $allConfig->expects($this->any()) + $this->config->expects($this->any()) ->method('getSystemValue') ->with($this->equalTo('datadirectory')) ->will($this->returnValue('arbitrary/path')); - $user = new User('foo', $backend, null, $allConfig); - $this->assertEquals('arbitrary/path/foo', $user->getHome()); + $this->assertEquals('arbitrary/path/foo', $this->user->getHome()); } - public function testCanChangePassword() { - /** - * @var Backend | \PHPUnit_Framework_MockObject_MockObject $backend - */ - $backend = $this->createMock(Dummy::class); - - $backend->expects($this->any()) - ->method('implementsActions') - ->will($this->returnCallback(function ($actions) { - if ($actions === Backend::SET_PASSWORD) { - return true; - } else { - return false; - } - })); - - $user = new User('foo', $backend); - $this->assertTrue($user->canChangePassword()); - } - - public function testCanChangePasswordNotSupported() { - /** - * @var Backend | \PHPUnit_Framework_MockObject_MockObject $backend - */ - $backend = $this->createMock(Dummy::class); - - $backend->expects($this->any()) - ->method('implementsActions') - ->will($this->returnValue(false)); - - $user = new User('foo', $backend); - $this->assertFalse($user->canChangePassword()); + public function providesChangeDisplayName() { + return [ + [true, true], + [false, false] + ]; } + /** + * @dataProvider providesChangeDisplayName + */ + public function testCanChangeDisplayName($expected, $implements) { + $backend = $this->getMockBuilder(Database::class) + ->setMethods(['implementsActions']) + ->getMock(); - public function testCanChangeDisplayName() { - /** - * @var Backend | \PHPUnit_Framework_MockObject_MockObject $backend - */ - $backend = $this->createMock(Dummy::class); + /** @var Account | \PHPUnit_Framework_MockObject_MockObject $account */ + $account = $this->getMockBuilder(Account::class) + ->setMethods(['getBackendInstance', 'getDisplayName', 'setDisplayName']) + ->getMock(); + $account->expects($this->any())->method('getBackendInstance')->willReturn($backend); + $account->expects($this->any())->method('getDisplayName')->willReturn('foo'); + $account->expects($this->any())->method('setDisplayName')->willReturn($implements); $backend->expects($this->any()) ->method('implementsActions') - ->will($this->returnCallback(function ($actions) { + ->will($this->returnCallback(function ($actions) use ($implements) { if ($actions === Backend::SET_DISPLAYNAME) { - return true; + return $implements; } else { return false; } })); - $user = new User('foo', $backend); - $this->assertTrue($user->canChangeDisplayName()); - } - - public function testCanChangeDisplayNameNotSupported() { - /** - * @var Backend | \PHPUnit_Framework_MockObject_MockObject $backend - */ - $backend = $this->createMock(Dummy::class); + $user = new User($account, $this->accountMapper, null, $this->config); + $this->assertEquals($expected, $user->canChangeDisplayName()); - $backend->expects($this->any()) - ->method('implementsActions') - ->will($this->returnValue(false)); + if ($expected) { + $this->accountMapper->expects($this->once()) + ->method('update'); + } - $user = new User('foo', $backend); - $this->assertFalse($user->canChangeDisplayName()); - } - - public function testSetDisplayNameSupported() { - /** - * @var Backend | \PHPUnit_Framework_MockObject_MockObject $backend - */ - $backend = $this->createMock('\OC\User\Database'); - - $backend->expects($this->any()) - ->method('implementsActions') - ->will($this->returnCallback(function ($actions) { - if ($actions === Backend::SET_DISPLAYNAME) { - return true; - } else { - return false; - } - })); - - $backend->expects($this->once()) - ->method('setDisplayName') - ->with('foo','Foo') - ->willReturn(true); - - $user = new User('foo', $backend); - $this->assertTrue($user->setDisplayName('Foo')); - $this->assertEquals('Foo',$user->getDisplayName()); + $this->assertEquals($expected, $user->setDisplayName('Foo')); } /** * don't allow display names containing whitespaces only */ public function testSetDisplayNameEmpty() { - /** - * @var Backend | \PHPUnit_Framework_MockObject_MockObject $backend - */ - $backend = $this->createMock('\OC\User\Database'); - - $backend->expects($this->any()) - ->method('implementsActions') - ->will($this->returnCallback(function ($actions) { - if ($actions === Backend::SET_DISPLAYNAME) { - return true; - } else { - return false; - } - })); - - $user = new User('foo', $backend); - $this->assertFalse($user->setDisplayName(' ')); - $this->assertEquals('foo',$user->getDisplayName()); + $this->account->setDisplayName(''); + $this->assertFalse($this->user->setDisplayName(' ')); + $this->assertEquals('foo', $this->user->getDisplayName()); } public function testSetDisplayNameNotSupported() { - /** - * @var Backend | \PHPUnit_Framework_MockObject_MockObject $backend - */ - $backend = $this->createMock('\OC\User\Database'); + $backend = $this->getMockBuilder(Database::class) + ->setMethods(['implementsActions']) + ->getMock(); + + /** @var Account | \PHPUnit_Framework_MockObject_MockObject $account */ + $account = $this->createMock(Account::class); + $account->expects($this->any())->method('getBackendInstance')->willReturn($backend); + $account->expects($this->any())->method('__call')->with('getDisplayName')->willReturn('foo'); $backend->expects($this->any()) ->method('implementsActions') ->will($this->returnCallback(function ($actions) { - return false; + return false; })); - $backend->expects($this->never()) - ->method('setDisplayName'); - - $user = new User('foo', $backend); + $user = new User($account, $this->accountMapper, null, $this->config); $this->assertFalse($user->setDisplayName('Foo')); $this->assertEquals('foo',$user->getDisplayName()); } @@ -438,14 +253,6 @@ public function testSetPasswordHooks() { $hooksCalled = 0; $test = $this; - /** - * @var Backend | \PHPUnit_Framework_MockObject_MockObject $backend - */ - $backend = $this->createMock(Dummy::class); - $backend->expects($this->once()) - ->method('setPassword') - ->willReturn(true); - /** * @param User $user * @param string $password @@ -460,19 +267,16 @@ public function testSetPasswordHooks() { $emitter->listen('\OC\User', 'preSetPassword', $hook); $emitter->listen('\OC\User', 'postSetPassword', $hook); - $backend->expects($this->any()) - ->method('implementsActions') - ->will($this->returnCallback(function ($actions) { - if ($actions === Backend::SET_PASSWORD) { - return true; - } else { - return false; - } - })); + $backend = $this->createMock(IChangePasswordBackend::class); + /** @var Account | \PHPUnit_Framework_MockObject_MockObject $account */ + $account = $this->createMock(Account::class); + $account->expects($this->any())->method('getBackendInstance')->willReturn($backend); + $account->expects($this->any())->method('__call')->with('getUserId')->willReturn('foo'); + $backend->expects($this->once())->method('setPassword')->with('foo', 'bar')->willReturn(true); - $user = new User('foo', $backend, $emitter); + $this->user = new User($account, $this->accountMapper, $emitter, $this->config); - $user->setPassword('bar',''); + $this->user->setPassword('bar',''); $this->assertEquals(2, $hooksCalled); } @@ -480,13 +284,6 @@ public function testDeleteHooks() { $hooksCalled = 0; $test = $this; - /** - * @var Backend | \PHPUnit_Framework_MockObject_MockObject $backend - */ - $backend = $this->createMock(Dummy::class); - $backend->expects($this->once()) - ->method('deleteUser'); - /** * @param User $user */ @@ -495,24 +292,15 @@ public function testDeleteHooks() { $test->assertEquals('foo', $user->getUID()); }; - $emitter = new PublicEmitter(); - $emitter->listen('\OC\User', 'preDelete', $hook); - $emitter->listen('\OC\User', 'postDelete', $hook); + $this->emitter->listen('\OC\User', 'preDelete', $hook); + $this->emitter->listen('\OC\User', 'postDelete', $hook); - $user = new User('foo', $backend, $emitter); - $this->assertTrue($user->delete()); + $this->assertTrue($this->user->delete()); $this->assertEquals(2, $hooksCalled); } public function testSetEnabledHook(){ - /** - * @var Backend | \PHPUnit_Framework_MockObject_MockObject $backend - */ - $backend = $this->createMock(Dummy::class); - $eventDispatcherMock = $this->createMock(EventDispatcher::class); - - $expectations = [true, false]; - $eventDispatcherMock->expects($this->exactly(2)) + $this->eventDispatcher->expects($this->exactly(2)) ->method('dispatch') ->with( $this->callback( @@ -527,25 +315,16 @@ function($eventName){ ) ; - $user = new User('foo', $backend, null, null, null, $eventDispatcherMock); - $user->setEnabled(false); - $user->setEnabled(true); + $this->user->setEnabled(false); + $this->user->setEnabled(true); } public function testGetCloudId() { - /** - * @var Backend | \PHPUnit_Framework_MockObject_MockObject $backend - */ - $backend = $this->createMock(Dummy::class); - $urlGenerator = $this->getMockBuilder('\OC\URLGenerator') - ->setMethods(['getAbsoluteURL']) - ->disableOriginalConstructor()->getMock(); - $urlGenerator + $this->urlGenerator ->expects($this->any()) ->method('getAbsoluteURL') ->withAnyParameters() ->willReturn('http://localhost:8888/owncloud'); - $user = new User('foo', $backend, null, null, $urlGenerator); - $this->assertEquals("foo@localhost:8888/owncloud", $user->getCloudId()); + $this->assertEquals("foo@localhost:8888/owncloud", $this->user->getCloudId()); } } diff --git a/tests/lib/UserTest.php b/tests/lib/UserTest.php deleted file mode 100644 index c9b0c6e122ae..000000000000 --- a/tests/lib/UserTest.php +++ /dev/null @@ -1,56 +0,0 @@ - - * This file is licensed under the Affero General Public License version 3 or - * later. - * See the COPYING-README file. - */ - -namespace Test; -use OC_User_Backend; - -/** - * Class User - * - * @group DB - * - * @package Test - */ -class UserTest extends TestCase { - /** - * @var \OC\User\Backend | \PHPUnit_Framework_MockObject_MockObject $backend - */ - private $backend; - - protected function setUp(){ - parent::setUp(); - - $this->backend = $this->createMock('\Test\Util\User\Dummy'); - $manager = \OC::$server->getUserManager(); - $manager->registerBackend($this->backend); - } - - public function testCheckPassword() { - - $this->backend->expects($this->once()) - ->method('checkPassword') - ->with($this->equalTo('foo'), $this->equalTo('bar')) - ->will($this->returnValue('foo')) - ; - - $this->backend->expects($this->any()) - ->method('implementsActions') - ->will($this->returnCallback(function ($actions) { - if ($actions === OC_User_Backend::CHECK_PASSWORD) { - return true; - } else { - return false; - } - })); - - $uid = \OC_User::checkPassword('foo', 'bar'); - $this->assertEquals($uid, 'foo'); - } - -}