diff options
Diffstat (limited to 'tests')
25 files changed, 483 insertions, 231 deletions
diff --git a/tests/Settings/Controller/CheckSetupControllerTest.php b/tests/Settings/Controller/CheckSetupControllerTest.php index c465ee79ed1..f087fec2105 100644 --- a/tests/Settings/Controller/CheckSetupControllerTest.php +++ b/tests/Settings/Controller/CheckSetupControllerTest.php @@ -42,23 +42,23 @@ use OC\IntegrityCheck\Checker; * @package Tests\Settings\Controller */ class CheckSetupControllerTest extends TestCase { - /** @var CheckSetupController */ + /** @var CheckSetupController | \PHPUnit_Framework_MockObject_MockObject */ private $checkSetupController; - /** @var IRequest */ + /** @var IRequest | \PHPUnit_Framework_MockObject_MockObject */ private $request; - /** @var IConfig */ + /** @var IConfig | \PHPUnit_Framework_MockObject_MockObject */ private $config; - /** @var IClientService */ + /** @var IClientService | \PHPUnit_Framework_MockObject_MockObject*/ private $clientService; - /** @var IURLGenerator */ + /** @var IURLGenerator | \PHPUnit_Framework_MockObject_MockObject */ private $urlGenerator; /** @var OC_Util */ private $util; - /** @var IL10N */ + /** @var IL10N | \PHPUnit_Framework_MockObject_MockObject */ private $l10n; /** @var ILogger */ private $logger; - /** @var Checker */ + /** @var Checker | \PHPUnit_Framework_MockObject_MockObject */ private $checker; public function setUp() { diff --git a/tests/lib/App/DependencyAnalyzerTest.php b/tests/lib/App/DependencyAnalyzerTest.php index 684a1b52259..c41829b796b 100644 --- a/tests/lib/App/DependencyAnalyzerTest.php +++ b/tests/lib/App/DependencyAnalyzerTest.php @@ -9,7 +9,7 @@ namespace Test\App; -use OC; +use OC\App\DependencyAnalyzer; use OC\App\Platform; use OCP\IL10N; use Test\TestCase; @@ -22,11 +22,11 @@ class DependencyAnalyzerTest extends TestCase { /** @var IL10N */ private $l10nMock; - /** @var \OC\App\DependencyAnalyzer */ + /** @var DependencyAnalyzer */ private $analyser; public function setUp() { - $this->platformMock = $this->getMockBuilder('\OC\App\Platform') + $this->platformMock = $this->getMockBuilder(Platform::class) ->disableOriginalConstructor() ->getMock(); $this->platformMock->expects($this->any()) @@ -67,7 +67,7 @@ class DependencyAnalyzerTest extends TestCase { return vsprintf($text, $parameters); })); - $this->analyser = new \OC\App\DependencyAnalyzer($this->platformMock, $this->l10nMock); + $this->analyser = new DependencyAnalyzer($this->platformMock, $this->l10nMock); } /** @@ -101,12 +101,14 @@ class DependencyAnalyzerTest extends TestCase { /** * @dataProvider providesDatabases + * @param $expectedMissing + * @param $databases */ public function testDatabases($expectedMissing, $databases) { - $app = array( - 'dependencies' => array( - ) - ); + $app = [ + 'dependencies' => [ + ] + ]; if (!is_null($databases)) { $app['dependencies']['database'] = $databases; } @@ -228,45 +230,48 @@ class DependencyAnalyzerTest extends TestCase { * @return array */ function providesLibs() { - return array( + return [ // we expect curl to exist - array(array(), 'curl'), + [[], 'curl'], // we expect abcde to exist - array(array('The library abcde is not available.'), array('abcde')), + [['The library abcde is not available.'], ['abcde']], // curl in version 100.0 does not exist - array(array('Library curl with a version higher than 100.0 is required - available version 2.3.4.'), - array(array('@attributes' => array('min-version' => '100.0'), '@value' => 'curl'))), + [['Library curl with a version higher than 100.0 is required - available version 2.3.4.'], + [['@attributes' => ['min-version' => '100.0'], '@value' => 'curl']]], // curl in version 100.0 does not exist - array(array('Library curl with a version lower than 1.0.0 is required - available version 2.3.4.'), - array(array('@attributes' => array('max-version' => '1.0.0'), '@value' => 'curl'))), - array(array('Library curl with a version lower than 2.3.3 is required - available version 2.3.4.'), - array(array('@attributes' => array('max-version' => '2.3.3'), '@value' => 'curl'))), - array(array('Library curl with a version higher than 2.3.5 is required - available version 2.3.4.'), - array(array('@attributes' => array('min-version' => '2.3.5'), '@value' => 'curl'))), - array(array(), - array(array('@attributes' => array('min-version' => '2.3.4', 'max-version' => '2.3.4'), '@value' => 'curl'))), - array(array(), - array(array('@attributes' => array('min-version' => '2.3', 'max-version' => '2.3'), '@value' => 'curl'))), - array(array(), - array(array('@attributes' => array('min-version' => '2', 'max-version' => '2'), '@value' => 'curl'))), - ); + [['Library curl with a version lower than 1.0.0 is required - available version 2.3.4.'], + [['@attributes' => ['max-version' => '1.0.0'], '@value' => 'curl']]], + [['Library curl with a version lower than 2.3.3 is required - available version 2.3.4.'], + [['@attributes' => ['max-version' => '2.3.3'], '@value' => 'curl']]], + [['Library curl with a version higher than 2.3.5 is required - available version 2.3.4.'], + [['@attributes' => ['min-version' => '2.3.5'], '@value' => 'curl']]], + [[], + [['@attributes' => ['min-version' => '2.3.4', 'max-version' => '2.3.4'], '@value' => 'curl']]], + [[], + [['@attributes' => ['min-version' => '2.3', 'max-version' => '2.3'], '@value' => 'curl']]], + [[], + [['@attributes' => ['min-version' => '2', 'max-version' => '2'], '@value' => 'curl']]], + [[], + ['@attributes' => ['min-version' => '2', 'max-version' => '2'], '@value' => 'curl']], + ]; } /** * @return array */ function providesCommands() { - return array( - array(array(), null), + return [ + [[], null], // grep is known on linux - array(array(), array(array('@attributes' => array('os' => 'Linux'), '@value' => 'grep'))), + [[], [['@attributes' => ['os' => 'Linux'], '@value' => 'grep']]], // grepp is not known on linux - array(array('The command line tool grepp could not be found'), array(array('@attributes' => array('os' => 'Linux'), '@value' => 'grepp'))), + [['The command line tool grepp could not be found'], [['@attributes' => ['os' => 'Linux'], '@value' => 'grepp']]], // we don't care about tools on Windows - we are on Linux - array(array(), array(array('@attributes' => array('os' => 'Windows'), '@value' => 'grepp'))), + [[], [['@attributes' => ['os' => 'Windows'], '@value' => 'grepp']]], // grep is known on all systems - array(array(), 'grep'), - ); + [[], 'grep'], + [[], ['@attributes' => ['os' => 'Linux'], '@value' => 'grep']], + ]; } /** diff --git a/tests/lib/App/ManagerTest.php b/tests/lib/App/ManagerTest.php index f3a91d4f5f4..e04f7c82375 100644 --- a/tests/lib/App/ManagerTest.php +++ b/tests/lib/App/ManagerTest.php @@ -306,7 +306,16 @@ class ManagerTest extends TestCase { $this->appConfig->setValue('test1', 'enabled', 'yes'); $this->appConfig->setValue('test2', 'enabled', 'no'); $this->appConfig->setValue('test3', 'enabled', '["foo"]'); - $apps = ['dav', 'federatedfilesharing', 'files', 'test1', 'test3', 'twofactor_backupcodes', 'workflowengine']; + $apps = [ + 'dav', + 'federatedfilesharing', + 'files', + 'provisioning_api', + 'test1', + 'test3', + 'twofactor_backupcodes', + 'workflowengine', + ]; $this->assertEquals($apps, $this->manager->getInstalledApps()); } @@ -325,6 +334,7 @@ class ManagerTest extends TestCase { 'dav', 'federatedfilesharing', 'files', + 'provisioning_api', 'test1', 'test3', 'twofactor_backupcodes', @@ -343,6 +353,7 @@ class ManagerTest extends TestCase { 'dav' => ['id' => 'dav'], 'files' => ['id' => 'files'], 'federatedfilesharing' => ['id' => 'federatedfilesharing'], + 'provisioning_api' => ['id' => 'provisioning_api'], 'test1' => ['id' => 'test1', 'version' => '1.0.1', 'requiremax' => '9.0.0'], 'test2' => ['id' => 'test2', 'version' => '1.0.0', 'requiremin' => '8.2.0'], 'test3' => ['id' => 'test3', 'version' => '1.2.4', 'requiremin' => '9.0.0'], @@ -386,6 +397,7 @@ class ManagerTest extends TestCase { 'dav' => ['id' => 'dav'], 'files' => ['id' => 'files'], 'federatedfilesharing' => ['id' => 'federatedfilesharing'], + 'provisioning_api' => ['id' => 'provisioning_api'], 'test1' => ['id' => 'test1', 'version' => '1.0.1', 'requiremax' => '8.0.0'], 'test2' => ['id' => 'test2', 'version' => '1.0.0', 'requiremin' => '8.2.0'], 'test3' => ['id' => 'test3', 'version' => '1.2.4', 'requiremin' => '9.0.0'], diff --git a/tests/lib/AppConfigTest.php b/tests/lib/AppConfigTest.php index 520dbf66d36..c4da7507752 100644 --- a/tests/lib/AppConfigTest.php +++ b/tests/lib/AppConfigTest.php @@ -40,7 +40,7 @@ class AppConfigTest extends TestCase { $sql->delete('appconfig'); $sql->execute(); - $this->registerAppConfig(new \OC\AppConfig($this->connection)); + $this->overwriteService('AppConfig', new \OC\AppConfig($this->connection)); $sql = $this->connection->getQueryBuilder(); $sql->insert('appconfig') @@ -130,21 +130,10 @@ class AppConfigTest extends TestCase { $sql->execute(); } - $this->registerAppConfig(new \OC\AppConfig(\OC::$server->getDatabaseConnection())); + $this->restoreService('AppConfig'); parent::tearDown(); } - /** - * Register an app config object for testing purposes. - * - * @param \OCP\IAppConfig $appConfig - */ - protected function registerAppConfig($appConfig) { - \OC::$server->registerService('AppConfig', function () use ($appConfig) { - return $appConfig; - }); - } - public function testGetApps() { $config = new \OC\AppConfig(\OC::$server->getDatabaseConnection()); diff --git a/tests/lib/AppFramework/Http/EmptyContentSecurityPolicyTest.php b/tests/lib/AppFramework/Http/EmptyContentSecurityPolicyTest.php index 248c3d808d2..33e2315ed89 100644 --- a/tests/lib/AppFramework/Http/EmptyContentSecurityPolicyTest.php +++ b/tests/lib/AppFramework/Http/EmptyContentSecurityPolicyTest.php @@ -427,4 +427,28 @@ class EmptyContentSecurityPolicyTest extends \Test\TestCase { $this->contentSecurityPolicy->disallowChildSrcDomain('www.owncloud.org')->disallowChildSrcDomain('www.owncloud.com'); $this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy()); } + + public function testGetPolicyWithJsNonceAndScriptDomains() { + $expectedPolicy = "default-src 'none';script-src 'nonce-TXlKc05vbmNl' www.nextcloud.com www.nextcloud.org"; + + $this->contentSecurityPolicy->addAllowedScriptDomain('www.nextcloud.com'); + $this->contentSecurityPolicy->useJsNonce('MyJsNonce'); + $this->contentSecurityPolicy->addAllowedScriptDomain('www.nextcloud.org'); + $this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy()); + } + + public function testGetPolicyWithJsNonceAndSelfScriptDomain() { + $expectedPolicy = "default-src 'none';script-src 'nonce-TXlKc05vbmNl'"; + + $this->contentSecurityPolicy->useJsNonce('MyJsNonce'); + $this->contentSecurityPolicy->addAllowedScriptDomain("'self'"); + $this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy()); + } + + public function testGetPolicyWithoutJsNonceAndSelfScriptDomain() { + $expectedPolicy = "default-src 'none';script-src 'self'"; + + $this->contentSecurityPolicy->addAllowedScriptDomain("'self'"); + $this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy()); + } } diff --git a/tests/lib/AppFramework/Http/RequestTest.php b/tests/lib/AppFramework/Http/RequestTest.php index 420b73a22d9..1ba20869439 100644 --- a/tests/lib/AppFramework/Http/RequestTest.php +++ b/tests/lib/AppFramework/Http/RequestTest.php @@ -792,6 +792,20 @@ class RequestTest extends \Test\TestCase { false, ], [ + 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36', + [ + Request::USER_AGENT_CHROME + ], + true, + ], + [ + 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/53.0.2785.143 Chrome/53.0.2785.143 Safari/537.36', + [ + Request::USER_AGENT_CHROME + ], + true, + ], + [ 'Mozilla/5.0 (Linux; Android 4.4; Nexus 4 Build/KRT16S) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.59 Mobile Safari/537.36', [ Request::USER_AGENT_ANDROID_MOBILE_CHROME diff --git a/tests/lib/AppFramework/Middleware/Security/SecurityMiddlewareTest.php b/tests/lib/AppFramework/Middleware/Security/SecurityMiddlewareTest.php index 55bf3e46e07..1fdcf485c28 100644 --- a/tests/lib/AppFramework/Middleware/Security/SecurityMiddlewareTest.php +++ b/tests/lib/AppFramework/Middleware/Security/SecurityMiddlewareTest.php @@ -36,6 +36,9 @@ use OC\AppFramework\Middleware\Security\SecurityMiddleware; use OC\AppFramework\Utility\ControllerMethodReflector; use OC\Security\CSP\ContentSecurityPolicy; use OC\Security\CSP\ContentSecurityPolicyManager; +use OC\Security\CSP\ContentSecurityPolicyNonceManager; +use OC\Security\CSRF\CsrfToken; +use OC\Security\CSRF\CsrfTokenManager; use OCP\AppFramework\Controller; use OCP\AppFramework\Http\EmptyContentSecurityPolicy; use OCP\AppFramework\Http\RedirectResponse; @@ -72,6 +75,10 @@ class SecurityMiddlewareTest extends \Test\TestCase { private $urlGenerator; /** @var ContentSecurityPolicyManager|\PHPUnit_Framework_MockObject_MockObject */ private $contentSecurityPolicyManager; + /** @var CsrfTokenManager|\PHPUnit_Framework_MockObject_MockObject */ + private $csrfTokenManager; + /** @var ContentSecurityPolicyNonceManager|\PHPUnit_Framework_MockObject_MockObject */ + private $cspNonceManager; protected function setUp() { parent::setUp(); @@ -83,6 +90,8 @@ class SecurityMiddlewareTest extends \Test\TestCase { $this->urlGenerator = $this->createMock(IURLGenerator::class); $this->request = $this->createMock(IRequest::class); $this->contentSecurityPolicyManager = $this->createMock(ContentSecurityPolicyManager::class); + $this->csrfTokenManager = $this->createMock(CsrfTokenManager::class); + $this->cspNonceManager = $this->createMock(ContentSecurityPolicyNonceManager::class); $this->middleware = $this->getMiddleware(true, true); $this->secException = new SecurityException('hey', false); $this->secAjaxException = new SecurityException('hey', true); @@ -103,7 +112,9 @@ class SecurityMiddlewareTest extends \Test\TestCase { 'files', $isLoggedIn, $isAdminUser, - $this->contentSecurityPolicyManager + $this->contentSecurityPolicyManager, + $this->csrfTokenManager, + $this->cspNonceManager ); } @@ -553,6 +564,10 @@ class SecurityMiddlewareTest extends \Test\TestCase { } public function testAfterController() { + $this->cspNonceManager + ->expects($this->once()) + ->method('browserSupportsCspV3') + ->willReturn(false); $response = $this->createMock(Response::class); $defaultPolicy = new ContentSecurityPolicy(); $defaultPolicy->addAllowedImageDomain('defaultpolicy'); @@ -591,4 +606,45 @@ class SecurityMiddlewareTest extends \Test\TestCase { $this->middleware->afterController($this->controller, 'test', $response); } + + public function testAfterControllerWithContentSecurityPolicy3Support() { + $this->cspNonceManager + ->expects($this->once()) + ->method('browserSupportsCspV3') + ->willReturn(true); + $token = $this->createMock(CsrfToken::class); + $token + ->expects($this->once()) + ->method('getEncryptedValue') + ->willReturn('MyEncryptedToken'); + $this->csrfTokenManager + ->expects($this->once()) + ->method('getToken') + ->willReturn($token); + $response = $this->createMock(Response::class); + $defaultPolicy = new ContentSecurityPolicy(); + $defaultPolicy->addAllowedImageDomain('defaultpolicy'); + $currentPolicy = new ContentSecurityPolicy(); + $currentPolicy->addAllowedConnectDomain('currentPolicy'); + $mergedPolicy = new ContentSecurityPolicy(); + $mergedPolicy->addAllowedMediaDomain('mergedPolicy'); + $response + ->expects($this->exactly(2)) + ->method('getContentSecurityPolicy') + ->willReturn($currentPolicy); + $this->contentSecurityPolicyManager + ->expects($this->once()) + ->method('getDefaultPolicy') + ->willReturn($defaultPolicy); + $this->contentSecurityPolicyManager + ->expects($this->once()) + ->method('mergePolicies') + ->with($defaultPolicy, $currentPolicy) + ->willReturn($mergedPolicy); + $response->expects($this->once()) + ->method('setContentSecurityPolicy') + ->with($mergedPolicy); + + $this->assertEquals($response, $this->middleware->afterController($this->controller, 'test', $response)); + } } diff --git a/tests/lib/AppTest.php b/tests/lib/AppTest.php index ac4fb913beb..b7263adb78b 100644 --- a/tests/lib/AppTest.php +++ b/tests/lib/AppTest.php @@ -317,6 +317,7 @@ class AppTest extends \Test\TestCase { 'appforgroup12', 'dav', 'federatedfilesharing', + 'provisioning_api', 'twofactor_backupcodes', 'workflowengine', ), @@ -333,6 +334,7 @@ class AppTest extends \Test\TestCase { 'appforgroup2', 'dav', 'federatedfilesharing', + 'provisioning_api', 'twofactor_backupcodes', 'workflowengine', ), @@ -350,6 +352,7 @@ class AppTest extends \Test\TestCase { 'appforgroup2', 'dav', 'federatedfilesharing', + 'provisioning_api', 'twofactor_backupcodes', 'workflowengine', ), @@ -367,6 +370,7 @@ class AppTest extends \Test\TestCase { 'appforgroup2', 'dav', 'federatedfilesharing', + 'provisioning_api', 'twofactor_backupcodes', 'workflowengine', ), @@ -384,6 +388,7 @@ class AppTest extends \Test\TestCase { 'appforgroup2', 'dav', 'federatedfilesharing', + 'provisioning_api', 'twofactor_backupcodes', 'workflowengine', ), @@ -463,11 +468,11 @@ class AppTest extends \Test\TestCase { ); $apps = \OC_App::getEnabledApps(); - $this->assertEquals(array('files', 'app3', 'dav', 'federatedfilesharing', 'twofactor_backupcodes', 'workflowengine'), $apps); + $this->assertEquals(array('files', 'app3', 'dav', 'federatedfilesharing', 'provisioning_api', 'twofactor_backupcodes', 'workflowengine'), $apps); // mock should not be called again here $apps = \OC_App::getEnabledApps(); - $this->assertEquals(array('files', 'app3', 'dav', 'federatedfilesharing', 'twofactor_backupcodes', 'workflowengine'), $apps); + $this->assertEquals(array('files', 'app3', 'dav', 'federatedfilesharing', 'provisioning_api', 'twofactor_backupcodes', 'workflowengine'), $apps); $this->restoreAppConfig(); \OC_User::setUserId(null); @@ -493,24 +498,22 @@ class AppTest extends \Test\TestCase { * @param IAppConfig $appConfig app config mock */ private function registerAppConfig(IAppConfig $appConfig) { - \OC::$server->registerService('AppConfig', function ($c) use ($appConfig) { - return $appConfig; - }); - \OC::$server->registerService('AppManager', function (\OC\Server $c) use ($appConfig) { - return new \OC\App\AppManager($c->getUserSession(), $appConfig, $c->getGroupManager(), $c->getMemCacheFactory(), $c->getEventDispatcher()); - }); + $this->overwriteService('AppConfig', $appConfig); + $this->overwriteService('AppManager', new \OC\App\AppManager( + \OC::$server->getUserSession(), + $appConfig, + \OC::$server->getGroupManager(), + \OC::$server->getMemCacheFactory(), + \OC::$server->getEventDispatcher() + )); } /** * Restore the original app config service. */ private function restoreAppConfig() { - \OC::$server->registerService('AppConfig', function (\OC\Server $c) { - return new \OC\AppConfig($c->getDatabaseConnection()); - }); - \OC::$server->registerService('AppManager', function (\OC\Server $c) { - return new \OC\App\AppManager($c->getUserSession(), $c->getAppConfig(), $c->getGroupManager(), $c->getMemCacheFactory(), $c->getEventDispatcher()); - }); + $this->restoreService('AppConfig'); + $this->restoreService('AppManager'); // Remove the cache of the mocked apps list with a forceRefresh \OC_App::getEnabledApps(); diff --git a/tests/lib/Comments/CommentTest.php b/tests/lib/Comments/CommentTest.php index ea10c52ae17..10ec4bae7d5 100644 --- a/tests/lib/Comments/CommentTest.php +++ b/tests/lib/Comments/CommentTest.php @@ -2,13 +2,14 @@ namespace Test\Comments; +use OC\Comments\Comment; use OCP\Comments\IComment; use Test\TestCase; class CommentTest extends TestCase { public function testSettersValidInput() { - $comment = new \OC\Comments\Comment(); + $comment = new Comment(); $id = 'comment23'; $parentId = 'comment11.5'; @@ -51,14 +52,14 @@ class CommentTest extends TestCase { * @expectedException \OCP\Comments\IllegalIDChangeException */ public function testSetIdIllegalInput() { - $comment = new \OC\Comments\Comment(); + $comment = new Comment(); $comment->setId('c23'); $comment->setId('c17'); } public function testResetId() { - $comment = new \OC\Comments\Comment(); + $comment = new Comment(); $comment->setId('c23'); $comment->setId(''); @@ -82,7 +83,7 @@ class CommentTest extends TestCase { * @expectedException \InvalidArgumentException */ public function testSimpleSetterInvalidInput($field, $input) { - $comment = new \OC\Comments\Comment(); + $comment = new Comment(); $setter = 'set' . $field; $comment->$setter($input); @@ -106,7 +107,7 @@ class CommentTest extends TestCase { * @expectedException \InvalidArgumentException */ public function testSetRoleInvalidInput($role, $type, $id){ - $comment = new \OC\Comments\Comment(); + $comment = new Comment(); $setter = 'set' . $role; $comment->$setter($type, $id); } @@ -115,11 +116,55 @@ class CommentTest extends TestCase { * @expectedException \OCP\Comments\MessageTooLongException */ public function testSetUberlongMessage() { - $comment = new \OC\Comments\Comment(); + $comment = new Comment(); $msg = str_pad('', IComment::MAX_MESSAGE_LENGTH + 1, 'x'); $comment->setMessage($msg); } + public function mentionsProvider() { + return [ + [ + '@alice @bob look look, a cook!', ['alice', 'bob'] + ], + [ + 'no mentions in this message', [] + ], + [ + '@alice @bob look look, a duplication @alice test @bob!', ['alice', 'bob'] + ], + [ + '@alice is the author, but notify @bob!', ['bob'], 'alice' + ], + [ + '@foobar and @barfoo you should know, @foo@bar.com is valid' . + ' and so is @bar@foo.org@foobar.io I hope that clarifies everything.' . + ' cc @23452-4333-54353-2342 @yolo!', + ['foobar', 'barfoo', 'foo@bar.com', 'bar@foo.org@foobar.io', '23452-4333-54353-2342', 'yolo'] + ] + + ]; + } + + /** + * @dataProvider mentionsProvider + */ + public function testMentions($message, $expectedUids, $author = null) { + $comment = new Comment(); + $comment->setMessage($message); + if(!is_null($author)) { + $comment->setActor('user', $author); + } + $mentions = $comment->getMentions(); + while($mention = array_shift($mentions)) { + $uid = array_shift($expectedUids); + $this->assertSame('user', $mention['type']); + $this->assertSame($uid, $mention['id']); + $this->assertNotSame($author, $mention['id']); + } + $this->assertEmpty($mentions); + $this->assertEmpty($expectedUids); + } + } diff --git a/tests/lib/Comments/FakeManager.php b/tests/lib/Comments/FakeManager.php index 7cd146e7cb2..dfb8f21b64b 100644 --- a/tests/lib/Comments/FakeManager.php +++ b/tests/lib/Comments/FakeManager.php @@ -40,4 +40,8 @@ class FakeManager implements \OCP\Comments\ICommentsManager { public function deleteReadMarksOnObject($objectType, $objectId) {} public function registerEventHandler(\Closure $closure) {} + + public function registerDisplayNameResolver($type, \Closure $closure) {} + + public function resolveDisplayName($type, $id) {} } diff --git a/tests/lib/Comments/ManagerTest.php b/tests/lib/Comments/ManagerTest.php index 71c918af6c7..a320366f29e 100644 --- a/tests/lib/Comments/ManagerTest.php +++ b/tests/lib/Comments/ManagerTest.php @@ -111,7 +111,7 @@ class ManagerTest extends TestCase { $this->assertSame($comment->getVerb(), 'comment'); $this->assertSame($comment->getObjectType(), 'files'); $this->assertSame($comment->getObjectId(), 'file64'); - $this->assertEquals($comment->getCreationDateTime(), $creationDT); + $this->assertEquals($comment->getCreationDateTime()->getTimestamp(), $creationDT->getTimestamp()); $this->assertEquals($comment->getLatestChildDateTime(), $latestChildDT); } @@ -373,7 +373,7 @@ class ManagerTest extends TestCase { $loadedComment = $manager->get($comment->getId()); $this->assertSame($comment->getMessage(), $loadedComment->getMessage()); - $this->assertEquals($comment->getCreationDateTime(), $loadedComment->getCreationDateTime()); + $this->assertEquals($comment->getCreationDateTime()->getTimestamp(), $loadedComment->getCreationDateTime()->getTimestamp()); } public function testSaveUpdate() { @@ -444,7 +444,7 @@ class ManagerTest extends TestCase { $this->assertSame($comment->getTopmostParentId(), strval($id)); $parentComment = $manager->get(strval($id)); $this->assertSame($parentComment->getChildrenCount(), $i + 1); - $this->assertEquals($parentComment->getLatestChildDateTime(), $comment->getCreationDateTime()); + $this->assertEquals($parentComment->getLatestChildDateTime()->getTimestamp(), $comment->getCreationDateTime()->getTimestamp()); } } @@ -577,7 +577,7 @@ class ManagerTest extends TestCase { $dateTimeGet = $manager->getReadMark('robot', '36', $user); - $this->assertEquals($dateTimeGet, $dateTimeSet); + $this->assertEquals($dateTimeGet->getTimestamp(), $dateTimeSet->getTimestamp()); } public function testSetMarkReadUpdate() { @@ -664,4 +664,82 @@ class ManagerTest extends TestCase { $manager->delete($comment->getId()); } + public function testResolveDisplayName() { + $manager = $this->getManager(); + + $planetClosure = function($name) { + return ucfirst($name); + }; + + $galaxyClosure = function($name) { + return strtoupper($name); + }; + + $manager->registerDisplayNameResolver('planet', $planetClosure); + $manager->registerDisplayNameResolver('galaxy', $galaxyClosure); + + $this->assertSame('Neptune', $manager->resolveDisplayName('planet', 'neptune')); + $this->assertSame('SOMBRERO', $manager->resolveDisplayName('galaxy', 'sombrero')); + } + + /** + * @expectedException \OutOfBoundsException + */ + public function testRegisterResolverDuplicate() { + $manager = $this->getManager(); + + $planetClosure = function($name) { + return ucfirst($name); + }; + $manager->registerDisplayNameResolver('planet', $planetClosure); + $manager->registerDisplayNameResolver('planet', $planetClosure); + } + + /** + * @expectedException \InvalidArgumentException + */ + public function testRegisterResolverInvalidType() { + $manager = $this->getManager(); + + $planetClosure = function($name) { + return ucfirst($name); + }; + $manager->registerDisplayNameResolver(1337, $planetClosure); + } + + /** + * @expectedException \OutOfBoundsException + */ + public function testResolveDisplayNameUnregisteredType() { + $manager = $this->getManager(); + + $planetClosure = function($name) { + return ucfirst($name); + }; + + $manager->registerDisplayNameResolver('planet', $planetClosure); + $manager->resolveDisplayName('galaxy', 'sombrero'); + } + + public function testResolveDisplayNameDirtyResolver() { + $manager = $this->getManager(); + + $planetClosure = function() { return null; }; + + $manager->registerDisplayNameResolver('planet', $planetClosure); + $this->assertTrue(is_string($manager->resolveDisplayName('planet', 'neptune'))); + } + + /** + * @expectedException \InvalidArgumentException + */ + public function testResolveDisplayNameInvalidType() { + $manager = $this->getManager(); + + $planetClosure = function() { return null; }; + + $manager->registerDisplayNameResolver('planet', $planetClosure); + $this->assertTrue(is_string($manager->resolveDisplayName(1337, 'neptune'))); + } + } diff --git a/tests/lib/Encryption/DecryptAllTest.php b/tests/lib/Encryption/DecryptAllTest.php index 7859a65ff6d..289e7de27ab 100644 --- a/tests/lib/Encryption/DecryptAllTest.php +++ b/tests/lib/Encryption/DecryptAllTest.php @@ -260,7 +260,7 @@ class DecryptAllTest extends TestCase { ->disableOriginalConstructor()->getMock(); $sharedStorage->expects($this->once())->method('instanceOfStorage') - ->with('OC\Files\Storage\Shared')->willReturn(true); + ->with('OCA\Files_Sharing\SharedStorage')->willReturn(true); $this->view->expects($this->at(0))->method('getDirectoryContent') ->with('/user1/files')->willReturn( diff --git a/tests/lib/Encryption/EncryptionWrapperTest.php b/tests/lib/Encryption/EncryptionWrapperTest.php index 6599428b364..6a6a3db2f68 100644 --- a/tests/lib/Encryption/EncryptionWrapperTest.php +++ b/tests/lib/Encryption/EncryptionWrapperTest.php @@ -91,13 +91,13 @@ class EncryptionWrapperTest extends TestCase { [true, ['OCA\Files_Trashbin\Storage']], // Do not wrap shared storages - [false, ['OC\Files\Storage\Shared']], + [false, ['OCA\Files_Sharing\SharedStorage']], [false, ['OCA\Files_Sharing\External\Storage']], [false, ['OC\Files\Storage\OwnCloud']], - [false, ['OC\Files\Storage\Shared', 'OCA\Files_Sharing\External\Storage']], - [false, ['OC\Files\Storage\Shared', 'OC\Files\Storage\OwnCloud']], + [false, ['OCA\Files_Sharing\SharedStorage', 'OCA\Files_Sharing\External\Storage']], + [false, ['OCA\Files_Sharing\SharedStorage', 'OC\Files\Storage\OwnCloud']], [false, ['OCA\Files_Sharing\External\Storage', 'OC\Files\Storage\OwnCloud']], - [false, ['OC\Files\Storage\Shared', 'OCA\Files_Sharing\External\Storage', 'OC\Files\Storage\OwnCloud']], + [false, ['OCA\Files_Sharing\SharedStorage', 'OCA\Files_Sharing\External\Storage', 'OC\Files\Storage\OwnCloud']], ]; } diff --git a/tests/lib/Files/PathVerificationTest.php b/tests/lib/Files/PathVerificationTest.php index 992734bdece..12285bb7acd 100644 --- a/tests/lib/Files/PathVerificationTest.php +++ b/tests/lib/Files/PathVerificationTest.php @@ -9,6 +9,7 @@ namespace Test\Files; use OC\Files\Storage\Local; use OC\Files\View; +use OCP\Files\InvalidPathException; /** * Class PathVerificationTest @@ -79,10 +80,15 @@ class PathVerificationTest extends \Test\TestCase { /** * @dataProvider providesAstralPlane - * @expectedException \OCP\Files\InvalidPathException - * @expectedExceptionMessage 4-byte characters are not supported in file names */ public function testPathVerificationAstralPlane($fileName) { + $connection = \OC::$server->getDatabaseConnection(); + + if (!$connection->supports4ByteText()) { + $this->expectException(InvalidPathException::class); + $this->expectExceptionMessage('4-byte characters are not supported in file names'); + } + $this->view->verifyPath('', $fileName); } diff --git a/tests/lib/Security/CSP/ContentSecurityPolicyNonceManagerTest.php b/tests/lib/Security/CSP/ContentSecurityPolicyNonceManagerTest.php new file mode 100644 index 00000000000..3211a5284f8 --- /dev/null +++ b/tests/lib/Security/CSP/ContentSecurityPolicyNonceManagerTest.php @@ -0,0 +1,59 @@ +<?php +/** + * @copyright Copyright (c) 2016 Lukas Reschke <lukas@statuscode.ch> + * + * @license GNU AGPL version 3 or any later version + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + * + */ + +namespace Test\Security\CSP; + +use OC\Security\CSP\ContentSecurityPolicyNonceManager; +use OC\Security\CSRF\CsrfToken; +use OC\Security\CSRF\CsrfTokenManager; +use OCP\IRequest; +use Test\TestCase; + +class ContentSecurityPolicyNonceManagerTest extends TestCase { + /** @var CsrfTokenManager */ + private $csrfTokenManager; + /** @var ContentSecurityPolicyNonceManager */ + private $nonceManager; + + public function setUp() { + $this->csrfTokenManager = $this->createMock(CsrfTokenManager::class); + $this->nonceManager = new ContentSecurityPolicyNonceManager( + $this->csrfTokenManager, + $this->createMock(IRequest::class) + ); + } + + public function testGetNonce() { + $token = $this->createMock(CsrfToken::class); + $token + ->expects($this->once()) + ->method('getEncryptedValue') + ->willReturn('MyToken'); + + $this->csrfTokenManager + ->expects($this->once()) + ->method('getToken') + ->willReturn($token); + + $this->assertSame('TXlUb2tlbg==', $this->nonceManager->getNonce()); + $this->assertSame('TXlUb2tlbg==', $this->nonceManager->getNonce()); + } +} diff --git a/tests/lib/Security/CSRF/CsrfTokenManagerTest.php b/tests/lib/Security/CSRF/CsrfTokenManagerTest.php index ab19a43e91e..6f7842fdfd9 100644 --- a/tests/lib/Security/CSRF/CsrfTokenManagerTest.php +++ b/tests/lib/Security/CSRF/CsrfTokenManagerTest.php @@ -56,6 +56,22 @@ class CsrfTokenManagerTest extends \Test\TestCase { $this->assertEquals($expected, $this->csrfTokenManager->getToken()); } + public function testGetTokenWithExistingTokenKeepsOnSecondRequest() { + $this->storageInterface + ->expects($this->once()) + ->method('hasToken') + ->willReturn(true); + $this->storageInterface + ->expects($this->once()) + ->method('getToken') + ->willReturn('MyExistingToken'); + + $expected = new \OC\Security\CSRF\CsrfToken('MyExistingToken'); + $token = $this->csrfTokenManager->getToken(); + $this->assertSame($token, $this->csrfTokenManager->getToken()); + $this->assertSame($token, $this->csrfTokenManager->getToken()); + } + public function testGetTokenWithoutExistingToken() { $this->storageInterface ->expects($this->once()) diff --git a/tests/lib/Security/CSRF/CsrfTokenTest.php b/tests/lib/Security/CSRF/CsrfTokenTest.php index da640ce5052..d19d1de916c 100644 --- a/tests/lib/Security/CSRF/CsrfTokenTest.php +++ b/tests/lib/Security/CSRF/CsrfTokenTest.php @@ -28,6 +28,13 @@ class CsrfTokenTest extends \Test\TestCase { $this->assertSame(':', $csrfToken->getEncryptedValue()[16]); } + public function testGetEncryptedValueStaysSameOnSecondRequest() { + $csrfToken = new \OC\Security\CSRF\CsrfToken('MyCsrfToken'); + $tokenValue = $csrfToken->getEncryptedValue(); + $this->assertSame($tokenValue, $csrfToken->getEncryptedValue()); + $this->assertSame($tokenValue, $csrfToken->getEncryptedValue()); + } + public function testGetDecryptedValue() { $csrfToken = new \OC\Security\CSRF\CsrfToken('XlQhHjgWCgBXAEI0Khl+IQEiCXN2LUcDHAQTQAc1HQs=:qgkUlg8l3m8WnkOG4XM9Az33pAt1vSVMx4hcJFsxdqc='); $this->assertSame('/3JKTq2ldmzcDr1f5zDJ7Wt0lEgqqfKF', $csrfToken->getDecryptedValue()); diff --git a/tests/lib/Share/MailNotificationsTest.php b/tests/lib/Share/MailNotificationsTest.php index d56efe57c9d..6fae8eb72fd 100644 --- a/tests/lib/Share/MailNotificationsTest.php +++ b/tests/lib/Share/MailNotificationsTest.php @@ -208,54 +208,6 @@ class MailNotificationsTest extends \Test\TestCase { $this->assertSame(['lukas@owncloud.com'], $mailNotifications->sendLinkShareMail('lukas@owncloud.com', 'MyFile', 'https://owncloud.com/file/?foo=bar', 3600)); } - public function testSendInternalShareMail() { - $this->setupMailerMock('TestUser shared »welcome.txt« with you', ['recipient@owncloud.com' => 'Recipient'], false); - - /** @var MailNotifications | \PHPUnit_Framework_MockObject_MockObject $mailNotifications */ - $mailNotifications = $this->getMockBuilder(MailNotifications::class) - ->setMethods(['getItemSharedWithUser']) - ->setConstructorArgs([ - $this->user, - $this->l10n, - $this->mailer, - $this->logger, - $this->defaults, - $this->urlGenerator - ]) - ->getMock(); - - $mailNotifications->method('getItemSharedWithUser') - ->withAnyParameters() - ->willReturn([ - ['file_target' => '/welcome.txt', 'item_source' => 123], - ]); - - $recipient = $this->getMockBuilder('\OCP\IUser') - ->disableOriginalConstructor()->getMock(); - $recipient - ->expects($this->once()) - ->method('getEMailAddress') - ->willReturn('recipient@owncloud.com'); - $recipient - ->expects($this->once()) - ->method('getDisplayName') - ->willReturn('Recipient'); - - $this->urlGenerator->expects($this->once()) - ->method('linkToRouteAbsolute') - ->with( - $this->equalTo('files.viewcontroller.showFile'), - $this->equalTo([ - 'fileId' => 123, - ]) - ); - - $recipientList = [$recipient]; - $result = $mailNotifications->sendInternalShareMail($recipientList, '3', 'file'); - $this->assertSame([], $result); - - } - /** * @param string $subject */ diff --git a/tests/lib/Share/ShareTest.php b/tests/lib/Share/ShareTest.php index 42adee21d0c..63289529843 100644 --- a/tests/lib/Share/ShareTest.php +++ b/tests/lib/Share/ShareTest.php @@ -119,12 +119,6 @@ class ShareTest extends \Test\TestCase { parent::tearDown(); } - protected function setHttpHelper($httpHelper) { - \OC::$server->registerService('HTTPHelper', function () use ($httpHelper) { - return $httpHelper; - }); - } - public function testShareInvalidShareType() { $message = 'Share type foobar is not valid for test.txt'; try { @@ -1046,11 +1040,10 @@ class ShareTest extends \Test\TestCase { * @param string $urlHost */ public function testRemoteShareUrlCalls($shareWith, $urlHost) { - $oldHttpHelper = \OC::$server->query('HTTPHelper'); - $httpHelperMock = $this->getMockBuilder('OC\HttpHelper') + $httpHelperMock = $this->getMockBuilder('OC\HTTPHelper') ->disableOriginalConstructor() ->getMock(); - $this->setHttpHelper($httpHelperMock); + $this->overwriteService('HTTPHelper', $httpHelperMock); $httpHelperMock->expects($this->at(0)) ->method('post') @@ -1075,7 +1068,7 @@ class ShareTest extends \Test\TestCase { ->willReturn(['success' => true, 'result' => json_encode(['ocs' => ['meta' => ['statuscode' => 100]]])]); \OCP\Share::unshare('test', 'test.txt', \OCP\Share::SHARE_TYPE_REMOTE, $shareWith); - $this->setHttpHelper($oldHttpHelper); + $this->restoreService('HTTPHelper'); } /** @@ -1473,11 +1466,10 @@ class ShareTest extends \Test\TestCase { * Make sure that a user cannot have multiple identical shares to remote users */ public function testOnlyOneRemoteShare() { - $oldHttpHelper = \OC::$server->query('HTTPHelper'); - $httpHelperMock = $this->getMockBuilder('OC\HttpHelper') + $httpHelperMock = $this->getMockBuilder('OC\HTTPHelper') ->disableOriginalConstructor() ->getMock(); - $this->setHttpHelper($httpHelperMock); + $this->overwriteService('HTTPHelper', $httpHelperMock); $httpHelperMock->expects($this->at(0)) ->method('post') @@ -1502,7 +1494,7 @@ class ShareTest extends \Test\TestCase { ->willReturn(['success' => true, 'result' => json_encode(['ocs' => ['meta' => ['statuscode' => 100]]])]); \OCP\Share::unshare('test', 'test.txt', \OCP\Share::SHARE_TYPE_REMOTE, 'foo@localhost'); - $this->setHttpHelper($oldHttpHelper); + $this->restoreService('HTTPHelper'); } /** diff --git a/tests/lib/Share20/DefaultShareProviderTest.php b/tests/lib/Share20/DefaultShareProviderTest.php index 0ae2ef922fc..778c1cb5722 100644 --- a/tests/lib/Share20/DefaultShareProviderTest.php +++ b/tests/lib/Share20/DefaultShareProviderTest.php @@ -743,7 +743,7 @@ class DefaultShareProviderTest extends \Test\TestCase { $this->assertSame($path, $share2->getNode()); $this->assertSame('password', $share2->getPassword()); $this->assertSame('token', $share2->getToken()); - $this->assertEquals($expireDate, $share2->getExpirationDate()); + $this->assertEquals($expireDate->getTimestamp(), $share2->getExpirationDate()->getTimestamp()); } public function testGetShareByToken() { diff --git a/tests/lib/StreamWrappersTest.php b/tests/lib/StreamWrappersTest.php index a378f975fde..c0ecb5e738b 100644 --- a/tests/lib/StreamWrappersTest.php +++ b/tests/lib/StreamWrappersTest.php @@ -77,40 +77,4 @@ class StreamWrappersTest extends \Test\TestCase { fclose($fh); $this->assertSame($tmpFile, $actual); } - - public function testOC() { - // FIXME: use proper tearDown with $this->loginAsUser() and $this->logout() - // (would currently break the tests for some reason) - $originalStorage = \OC\Files\Filesystem::getStorage('/'); - \OC\Files\Filesystem::clearMounts(); - - $storage = new \OC\Files\Storage\Temporary(array()); - $storage->file_put_contents('foo.txt', 'asd'); - \OC\Files\Filesystem::mount($storage, array(), '/'); - - $this->assertTrue(file_exists('oc:///foo.txt')); - $this->assertEquals('asd', file_get_contents('oc:///foo.txt')); - $this->assertEquals(array('.', '..', 'foo.txt'), scandir('oc:///')); - - file_put_contents('oc:///bar.txt', 'qwerty'); - $this->assertEquals('qwerty', $storage->file_get_contents('bar.txt')); - $this->assertEquals(array('.', '..', 'bar.txt', 'foo.txt'), scandir('oc:///')); - $this->assertEquals('qwerty', file_get_contents('oc:///bar.txt')); - - $fh = fopen('oc:///bar.txt', 'rb'); - $this->assertSame(0, ftell($fh)); - $content = fread($fh, 4); - $this->assertSame(4, ftell($fh)); - $this->assertSame('qwer', $content); - $content = fread($fh, 1); - $this->assertSame(5, ftell($fh)); - $this->assertSame(0, fseek($fh, 0)); - $this->assertSame(0, ftell($fh)); - - unlink('oc:///foo.txt'); - $this->assertEquals(array('.', '..', 'bar.txt'), scandir('oc:///')); - - \OC\Files\Filesystem::clearMounts(); - \OC\Files\Filesystem::mount($originalStorage, array(), '/'); - } } diff --git a/tests/lib/TestCase.php b/tests/lib/TestCase.php index 7ccff382357..61372d4ae90 100644 --- a/tests/lib/TestCase.php +++ b/tests/lib/TestCase.php @@ -102,6 +102,16 @@ abstract class TestCase extends \PHPUnit_Framework_TestCase { return false; } + public function restoreAllServices() { + if (!empty($this->services)) { + if (!empty($this->services)) { + foreach ($this->services as $name => $service) { + $this->restoreService($name); + } + } + } + } + protected function getTestTraits() { $traits = []; $class = $this; @@ -132,9 +142,7 @@ abstract class TestCase extends \PHPUnit_Framework_TestCase { // overwrite the command bus with one we can run ourselves $this->commandBus = new QueueBus(); - \OC::$server->registerService('AsyncCommandBus', function () { - return $this->commandBus; - }); + $this->overwriteService('AsyncCommandBus', $this->commandBus); $traits = $this->getTestTraits(); foreach ($traits as $trait) { @@ -145,7 +153,22 @@ abstract class TestCase extends \PHPUnit_Framework_TestCase { } } + protected function onNotSuccessfulTest($e) { + $this->restoreAllServices(); + + // restore database connection + if (!$this->IsDatabaseAccessAllowed()) { + \OC::$server->registerService('DatabaseConnection', function () { + return self::$realDatabase; + }); + } + + parent::onNotSuccessfulTest($e); + } + protected function tearDown() { + $this->restoreAllServices(); + // restore database connection if (!$this->IsDatabaseAccessAllowed()) { \OC::$server->registerService('DatabaseConnection', function () { diff --git a/tests/lib/User/SessionTest.php b/tests/lib/User/SessionTest.php index 21ac1b655b9..1b3d5cc4601 100644 --- a/tests/lib/User/SessionTest.php +++ b/tests/lib/User/SessionTest.php @@ -33,11 +33,11 @@ use OCP\Security\ISecureRandom; * @package Test\User */ class SessionTest extends \Test\TestCase { - /** @var \OCP\AppFramework\Utility\ITimeFactory */ + /** @var ITimeFactory|\PHPUnit_Framework_MockObject_MockObject */ private $timeFactory; - /** @var \OC\Authentication\Token\DefaultTokenProvider */ + /** @var DefaultTokenProvider|\PHPUnit_Framework_MockObject_MockObject */ protected $tokenProvider; - /** @var \OCP\IConfig */ + /** @var IConfig|\PHPUnit_Framework_MockObject_MockObject */ private $config; /** @var Throttler */ private $throttler; @@ -124,11 +124,9 @@ class SessionTest extends \Test\TestCase { public function testIsLoggedIn($isLoggedIn) { $session = $this->getMockBuilder(Memory::class)->setConstructorArgs([''])->getMock(); - $manager = $this->getMockBuilder('\OC\User\Manager') - ->disableOriginalConstructor() - ->getMock(); + $manager = $this->createMock(Manager::class); - $userSession = $this->getMockBuilder('\OC\User\Session') + $userSession = $this->getMockBuilder(Session::class) ->setConstructorArgs([$manager, $session, $this->timeFactory, $this->tokenProvider, $this->config]) ->setMethods([ 'getUser' @@ -182,7 +180,7 @@ class SessionTest extends \Test\TestCase { } }, '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 = array('__construct', 'emit', 'listen'); @@ -211,7 +209,7 @@ class SessionTest extends \Test\TestCase { ->with('foo', 'bar') ->will($this->returnValue($user)); - $userSession = $this->getMockBuilder('\OC\User\Session') + $userSession = $this->getMockBuilder(Session::class) ->setConstructorArgs([$manager, $session, $this->timeFactory, $this->tokenProvider, $this->config]) ->setMethods([ 'prepareUserLogin' @@ -310,7 +308,6 @@ class SessionTest extends \Test\TestCase { public function testLoginNonExisting() { $session = $this->getMockBuilder(Memory::class)->setConstructorArgs([''])->getMock(); $manager = $this->createMock(Manager::class); - $backend = $this->createMock(\Test\Util\User\Dummy::class); $userSession = new \OC\User\Session($manager, $session, $this->timeFactory, $this->tokenProvider, $this->config); $session->expects($this->never()) @@ -337,7 +334,6 @@ class SessionTest extends \Test\TestCase { public function testLoginWithDifferentTokenLoginName() { $session = $this->getMockBuilder(Memory::class)->setConstructorArgs([''])->getMock(); $manager = $this->createMock(Manager::class); - $backend = $this->createMock(\Test\Util\User\Dummy::class); $userSession = new \OC\User\Session($manager, $session, $this->timeFactory, $this->tokenProvider, $this->config); $username = 'user123'; $token = new \OC\Authentication\Token\DefaultToken(); @@ -364,14 +360,12 @@ class SessionTest extends \Test\TestCase { * @expectedException \OC\Authentication\Exceptions\PasswordLoginForbiddenException */ public function testLogClientInNoTokenPasswordWith2fa() { - $manager = $this->getMockBuilder('\OC\User\Manager') - ->disableOriginalConstructor() - ->getMock(); + $manager = $this->createMock(Manager::class); $session = $this->createMock(ISession::class); $request = $this->createMock(IRequest::class); /** @var \OC\User\Session $userSession */ - $userSession = $this->getMockBuilder('\OC\User\Session') + $userSession = $this->getMockBuilder(Session::class) ->setConstructorArgs([$manager, $session, $this->timeFactory, $this->tokenProvider, $this->config]) ->setMethods(['login', 'supportsCookies', 'createSessionToken', 'getUser']) ->getMock(); @@ -401,15 +395,36 @@ class SessionTest extends \Test\TestCase { $userSession->logClientIn('john', 'doe', $request, $this->throttler); } - public function testLogClientInWithTokenPassword() { - $manager = $this->getMockBuilder('\OC\User\Manager') - ->disableOriginalConstructor() + public function testLogClientInUnexist() { + $manager = $this->createMock(Manager::class); + $session = $this->createMock(ISession::class); + $request = $this->createMock(IRequest::class); + + /** @var Session $userSession */ + $userSession = $this->getMockBuilder(Session::class) + ->setConstructorArgs([$manager, $session, $this->timeFactory, $this->tokenProvider, $this->config]) + ->setMethods(['login', 'supportsCookies', 'createSessionToken', 'getUser']) ->getMock(); + + $this->tokenProvider->expects($this->once()) + ->method('getToken') + ->with('doe') + ->will($this->throwException(new \OC\Authentication\Exceptions\InvalidTokenException())); + $this->config->expects($this->once()) + ->method('getSystemValue') + ->with('token_auth_enforced', false) + ->will($this->returnValue(false)); + + $this->assertFalse($userSession->logClientIn('unexist', 'doe', $request, $this->throttler)); + } + + public function testLogClientInWithTokenPassword() { + $manager = $this->createMock(Manager::class); $session = $this->createMock(ISession::class); $request = $this->createMock(IRequest::class); /** @var \OC\User\Session $userSession */ - $userSession = $this->getMockBuilder('\OC\User\Session') + $userSession = $this->getMockBuilder(Session::class) ->setConstructorArgs([$manager, $session, $this->timeFactory, $this->tokenProvider, $this->config]) ->setMethods(['isTokenPassword', 'login', 'supportsCookies', 'createSessionToken', 'getUser']) ->getMock(); @@ -446,14 +461,12 @@ class SessionTest extends \Test\TestCase { * @expectedException \OC\Authentication\Exceptions\PasswordLoginForbiddenException */ public function testLogClientInNoTokenPasswordNo2fa() { - $manager = $this->getMockBuilder('\OC\User\Manager') - ->disableOriginalConstructor() - ->getMock(); + $manager = $this->createMock(Manager::class); $session = $this->createMock(ISession::class); $request = $this->createMock(IRequest::class); /** @var \OC\User\Session $userSession */ - $userSession = $this->getMockBuilder('\OC\User\Session') + $userSession = $this->getMockBuilder(Session::class) ->setConstructorArgs([$manager, $session, $this->timeFactory, $this->tokenProvider, $this->config]) ->setMethods(['login', 'isTwoFactorEnforced']) ->getMock(); @@ -504,7 +517,7 @@ class SessionTest extends \Test\TestCase { $session->expects($this->once()) ->method('regenerateId'); - $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 = array('__construct', 'emit', 'listen'); @@ -966,9 +979,7 @@ class SessionTest extends \Test\TestCase { } public function testUpdateAuthTokenLastCheck() { - $manager = $this->getMockBuilder('\OC\User\Manager') - ->disableOriginalConstructor() - ->getMock(); + $manager = $this->createMock(Manager::class); $session = $this->createMock(ISession::class); $request = $this->createMock(IRequest::class); @@ -981,8 +992,8 @@ class SessionTest extends \Test\TestCase { $mapper = $this->getMockBuilder(DefaultTokenMapper::class) ->disableOriginalConstructor() ->getMock(); - $crypto = $this->getMock(ICrypto::class); - $logger = $this->getMock(ILogger::class); + $crypto = $this->createMock(ICrypto::class); + $logger = $this->createMock(ILogger::class); $tokenProvider = new DefaultTokenProvider($mapper, $crypto, $this->config, $logger, $this->timeFactory); /** @var \OC\User\Session $userSession */ @@ -1018,9 +1029,7 @@ class SessionTest extends \Test\TestCase { } public function testNoUpdateAuthTokenLastCheckRecent() { - $manager = $this->getMockBuilder('\OC\User\Manager') - ->disableOriginalConstructor() - ->getMock(); + $manager = $this->createMock(Manager::class); $session = $this->createMock(ISession::class); $request = $this->createMock(IRequest::class); @@ -1033,8 +1042,8 @@ class SessionTest extends \Test\TestCase { $mapper = $this->getMockBuilder(DefaultTokenMapper::class) ->disableOriginalConstructor() ->getMock(); - $crypto = $this->getMock(ICrypto::class); - $logger = $this->getMock(ILogger::class); + $crypto = $this->createMock(ICrypto::class); + $logger = $this->createMock(ILogger::class); $tokenProvider = new DefaultTokenProvider($mapper, $crypto, $this->config, $logger, $this->timeFactory); /** @var \OC\User\Session $userSession */ diff --git a/tests/lib/UtilTest.php b/tests/lib/UtilTest.php index 619963a2abf..a1671191ab8 100644 --- a/tests/lib/UtilTest.php +++ b/tests/lib/UtilTest.php @@ -87,24 +87,17 @@ class UtilTest extends \Test\TestCase { function testFormatDateWithTZFromSession($offset, $expected, $expectedTimeZone) { date_default_timezone_set("UTC"); - $oldDateTimeFormatter = \OC::$server->query('DateTimeFormatter'); \OC::$server->getSession()->set('timezone', $offset); $selectedTimeZone = \OC::$server->getDateTimeZone()->getTimeZone(1350129205); $this->assertEquals($expectedTimeZone, $selectedTimeZone->getName()); $newDateTimeFormatter = new \OC\DateTimeFormatter($selectedTimeZone, new \OC_L10N('lib', 'en')); - $this->setDateFormatter($newDateTimeFormatter); + $this->overwriteService('DateTimeFormatter', $newDateTimeFormatter); $result = OC_Util::formatDate(1350129205, false); $this->assertEquals($expected, $result); - $this->setDateFormatter($oldDateTimeFormatter); - } - - protected function setDateFormatter($formatter) { - \OC::$server->registerService('DateTimeFormatter', function ($c) use ($formatter) { - return $formatter; - }); + $this->restoreService('DateTimeFormatter'); } function testSanitizeHTML() { diff --git a/tests/phpunit-autotest.xml b/tests/phpunit-autotest.xml index 3a82a56ebbf..ba16bbdbaac 100644 --- a/tests/phpunit-autotest.xml +++ b/tests/phpunit-autotest.xml @@ -10,6 +10,7 @@ <directory suffix='.php'>lib/</directory> <directory suffix='.php'>Settings/</directory> <directory suffix='.php'>Core/</directory> + <directory suffix='.php'>ocs-provider/</directory> <file>apps.php</file> </testsuite> <!-- filters for code coverage --> |