diff options
Diffstat (limited to 'tests/lib')
38 files changed, 1281 insertions, 376 deletions
diff --git a/tests/lib/activitymanager.php b/tests/lib/activitymanager.php index d3263fa2ede..a35daeaf494 100644 --- a/tests/lib/activitymanager.php +++ b/tests/lib/activitymanager.php @@ -156,7 +156,7 @@ class Test_ActivityManager extends \Test\TestCase { */ public function testGetUserFromTokenThrowInvalidToken($token, $users) { $this->mockRSSToken($token, $token, $users); - \Test_Helper::invokePrivate($this->activityManager, 'getUserFromToken'); + self::invokePrivate($this->activityManager, 'getUserFromToken'); } public function getUserFromTokenData() { diff --git a/tests/lib/appframework/http/ContentSecurityPolicyTest.php b/tests/lib/appframework/http/ContentSecurityPolicyTest.php index f79c23ae644..18d71df483f 100644 --- a/tests/lib/appframework/http/ContentSecurityPolicyTest.php +++ b/tests/lib/appframework/http/ContentSecurityPolicyTest.php @@ -47,6 +47,30 @@ class ContentSecurityPolicyTest extends \Test\TestCase { $this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy()); } + public function testGetPolicyDisallowScriptDomain() { + $expectedPolicy = "default-src 'none';script-src 'self' 'unsafe-eval';style-src 'self' 'unsafe-inline';img-src 'self';font-src 'self';connect-src 'self';media-src 'self'"; + + $this->contentSecurityPolicy->addAllowedScriptDomain('www.owncloud.com'); + $this->contentSecurityPolicy->disallowScriptDomain('www.owncloud.com'); + $this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy()); + } + + public function testGetPolicyDisallowScriptDomainMultiple() { + $expectedPolicy = "default-src 'none';script-src 'self' www.owncloud.com 'unsafe-eval';style-src 'self' 'unsafe-inline';img-src 'self';font-src 'self';connect-src 'self';media-src 'self'"; + + $this->contentSecurityPolicy->addAllowedScriptDomain('www.owncloud.com'); + $this->contentSecurityPolicy->disallowScriptDomain('www.owncloud.org'); + $this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy()); + } + + public function testGetPolicyDisallowScriptDomainMultipleStacked() { + $expectedPolicy = "default-src 'none';script-src 'self' 'unsafe-eval';style-src 'self' 'unsafe-inline';img-src 'self';font-src 'self';connect-src 'self';media-src 'self'"; + + $this->contentSecurityPolicy->addAllowedScriptDomain('www.owncloud.com'); + $this->contentSecurityPolicy->disallowScriptDomain('www.owncloud.org')->disallowScriptDomain('www.owncloud.com'); + $this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy()); + } + public function testGetPolicyScriptAllowInline() { $expectedPolicy = "default-src 'none';script-src 'self' 'unsafe-inline' 'unsafe-eval';style-src 'self' 'unsafe-inline';img-src 'self';font-src 'self';connect-src 'self';media-src 'self'"; @@ -85,6 +109,30 @@ class ContentSecurityPolicyTest extends \Test\TestCase { $this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy()); } + public function testGetPolicyDisallowStyleDomain() { + $expectedPolicy = "default-src 'none';script-src 'self' 'unsafe-eval';style-src 'self' 'unsafe-inline';img-src 'self';font-src 'self';connect-src 'self';media-src 'self'"; + + $this->contentSecurityPolicy->addAllowedStyleDomain('www.owncloud.com'); + $this->contentSecurityPolicy->disallowStyleDomain('www.owncloud.com'); + $this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy()); + } + + public function testGetPolicyDisallowStyleDomainMultiple() { + $expectedPolicy = "default-src 'none';script-src 'self' 'unsafe-eval';style-src 'self' www.owncloud.com 'unsafe-inline';img-src 'self';font-src 'self';connect-src 'self';media-src 'self'"; + + $this->contentSecurityPolicy->addAllowedStyleDomain('www.owncloud.com'); + $this->contentSecurityPolicy->disallowStyleDomain('www.owncloud.org'); + $this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy()); + } + + public function testGetPolicyDisallowStyleDomainMultipleStacked() { + $expectedPolicy = "default-src 'none';script-src 'self' 'unsafe-eval';style-src 'self' 'unsafe-inline';img-src 'self';font-src 'self';connect-src 'self';media-src 'self'"; + + $this->contentSecurityPolicy->addAllowedStyleDomain('www.owncloud.com'); + $this->contentSecurityPolicy->disallowStyleDomain('www.owncloud.org')->disallowStyleDomain('www.owncloud.com'); + $this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy()); + } + public function testGetPolicyStyleAllowInline() { $expectedPolicy = "default-src 'none';script-src 'self' 'unsafe-eval';style-src 'self' 'unsafe-inline';img-src 'self';font-src 'self';connect-src 'self';media-src 'self'"; @@ -121,6 +169,30 @@ class ContentSecurityPolicyTest extends \Test\TestCase { $this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy()); } + public function testGetPolicyDisallowImageDomain() { + $expectedPolicy = "default-src 'none';script-src 'self' 'unsafe-eval';style-src 'self' 'unsafe-inline';img-src 'self';font-src 'self';connect-src 'self';media-src 'self'"; + + $this->contentSecurityPolicy->addAllowedImageDomain('www.owncloud.com'); + $this->contentSecurityPolicy->disallowImageDomain('www.owncloud.com'); + $this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy()); + } + + public function testGetPolicyDisallowImageDomainMultiple() { + $expectedPolicy = "default-src 'none';script-src 'self' 'unsafe-eval';style-src 'self' 'unsafe-inline';img-src 'self' www.owncloud.com;font-src 'self';connect-src 'self';media-src 'self'"; + + $this->contentSecurityPolicy->addAllowedImageDomain('www.owncloud.com'); + $this->contentSecurityPolicy->disallowImageDomain('www.owncloud.org'); + $this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy()); + } + + public function testGetPolicyDisallowImageDomainMultipleStakes() { + $expectedPolicy = "default-src 'none';script-src 'self' 'unsafe-eval';style-src 'self' 'unsafe-inline';img-src 'self';font-src 'self';connect-src 'self';media-src 'self'"; + + $this->contentSecurityPolicy->addAllowedImageDomain('www.owncloud.com'); + $this->contentSecurityPolicy->disallowImageDomain('www.owncloud.org')->disallowImageDomain('www.owncloud.com'); + $this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy()); + } + public function testGetPolicyFontDomainValid() { $expectedPolicy = "default-src 'none';script-src 'self' 'unsafe-eval';style-src 'self' 'unsafe-inline';img-src 'self';font-src 'self' www.owncloud.com;connect-src 'self';media-src 'self'"; @@ -136,6 +208,30 @@ class ContentSecurityPolicyTest extends \Test\TestCase { $this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy()); } + public function testGetPolicyDisallowFontDomain() { + $expectedPolicy = "default-src 'none';script-src 'self' 'unsafe-eval';style-src 'self' 'unsafe-inline';img-src 'self';font-src 'self';connect-src 'self';media-src 'self'"; + + $this->contentSecurityPolicy->addAllowedFontDomain('www.owncloud.com'); + $this->contentSecurityPolicy->disallowFontDomain('www.owncloud.com'); + $this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy()); + } + + public function testGetPolicyDisallowFontDomainMultiple() { + $expectedPolicy = "default-src 'none';script-src 'self' 'unsafe-eval';style-src 'self' 'unsafe-inline';img-src 'self';font-src 'self' www.owncloud.com;connect-src 'self';media-src 'self'"; + + $this->contentSecurityPolicy->addAllowedFontDomain('www.owncloud.com'); + $this->contentSecurityPolicy->disallowFontDomain('www.owncloud.org'); + $this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy()); + } + + public function testGetPolicyDisallowFontDomainMultipleStakes() { + $expectedPolicy = "default-src 'none';script-src 'self' 'unsafe-eval';style-src 'self' 'unsafe-inline';img-src 'self';font-src 'self';connect-src 'self';media-src 'self'"; + + $this->contentSecurityPolicy->addAllowedFontDomain('www.owncloud.com'); + $this->contentSecurityPolicy->disallowFontDomain('www.owncloud.org')->disallowFontDomain('www.owncloud.com'); + $this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy()); + } + public function testGetPolicyConnectDomainValid() { $expectedPolicy = "default-src 'none';script-src 'self' 'unsafe-eval';style-src 'self' 'unsafe-inline';img-src 'self';font-src 'self';connect-src 'self' www.owncloud.com;media-src 'self'"; @@ -151,6 +247,30 @@ class ContentSecurityPolicyTest extends \Test\TestCase { $this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy()); } + public function testGetPolicyDisallowConnectDomain() { + $expectedPolicy = "default-src 'none';script-src 'self' 'unsafe-eval';style-src 'self' 'unsafe-inline';img-src 'self';font-src 'self';connect-src 'self';media-src 'self'"; + + $this->contentSecurityPolicy->addAllowedConnectDomain('www.owncloud.com'); + $this->contentSecurityPolicy->disallowConnectDomain('www.owncloud.com'); + $this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy()); + } + + public function testGetPolicyDisallowConnectDomainMultiple() { + $expectedPolicy = "default-src 'none';script-src 'self' 'unsafe-eval';style-src 'self' 'unsafe-inline';img-src 'self';font-src 'self';connect-src 'self' www.owncloud.com;media-src 'self'"; + + $this->contentSecurityPolicy->addAllowedConnectDomain('www.owncloud.com'); + $this->contentSecurityPolicy->disallowConnectDomain('www.owncloud.org'); + $this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy()); + } + + public function testGetPolicyDisallowConnectDomainMultipleStakes() { + $expectedPolicy = "default-src 'none';script-src 'self' 'unsafe-eval';style-src 'self' 'unsafe-inline';img-src 'self';font-src 'self';connect-src 'self';media-src 'self'"; + + $this->contentSecurityPolicy->addAllowedConnectDomain('www.owncloud.com'); + $this->contentSecurityPolicy->disallowConnectDomain('www.owncloud.org')->disallowConnectDomain('www.owncloud.com'); + $this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy()); + } + public function testGetPolicyMediaDomainValid() { $expectedPolicy = "default-src 'none';script-src 'self' 'unsafe-eval';style-src 'self' 'unsafe-inline';img-src 'self';font-src 'self';connect-src 'self';media-src 'self' www.owncloud.com"; @@ -166,6 +286,30 @@ class ContentSecurityPolicyTest extends \Test\TestCase { $this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy()); } + public function testGetPolicyDisallowMediaDomain() { + $expectedPolicy = "default-src 'none';script-src 'self' 'unsafe-eval';style-src 'self' 'unsafe-inline';img-src 'self';font-src 'self';connect-src 'self';media-src 'self'"; + + $this->contentSecurityPolicy->addAllowedMediaDomain('www.owncloud.com'); + $this->contentSecurityPolicy->disallowMediaDomain('www.owncloud.com'); + $this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy()); + } + + public function testGetPolicyDisallowMediaDomainMultiple() { + $expectedPolicy = "default-src 'none';script-src 'self' 'unsafe-eval';style-src 'self' 'unsafe-inline';img-src 'self';font-src 'self';connect-src 'self';media-src 'self' www.owncloud.com"; + + $this->contentSecurityPolicy->addAllowedMediaDomain('www.owncloud.com'); + $this->contentSecurityPolicy->disallowMediaDomain('www.owncloud.org'); + $this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy()); + } + + public function testGetPolicyDisallowMediaDomainMultipleStakes() { + $expectedPolicy = "default-src 'none';script-src 'self' 'unsafe-eval';style-src 'self' 'unsafe-inline';img-src 'self';font-src 'self';connect-src 'self';media-src 'self'"; + + $this->contentSecurityPolicy->addAllowedMediaDomain('www.owncloud.com'); + $this->contentSecurityPolicy->disallowMediaDomain('www.owncloud.org')->disallowMediaDomain('www.owncloud.com'); + $this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy()); + } + public function testGetPolicyObjectDomainValid() { $expectedPolicy = "default-src 'none';script-src 'self' 'unsafe-eval';style-src 'self' 'unsafe-inline';img-src 'self';font-src 'self';connect-src 'self';media-src 'self';object-src www.owncloud.com"; @@ -181,6 +325,30 @@ class ContentSecurityPolicyTest extends \Test\TestCase { $this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy()); } + public function testGetPolicyDisallowObjectDomain() { + $expectedPolicy = "default-src 'none';script-src 'self' 'unsafe-eval';style-src 'self' 'unsafe-inline';img-src 'self';font-src 'self';connect-src 'self';media-src 'self'"; + + $this->contentSecurityPolicy->addAllowedObjectDomain('www.owncloud.com'); + $this->contentSecurityPolicy->disallowObjectDomain('www.owncloud.com'); + $this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy()); + } + + public function testGetPolicyDisallowObjectDomainMultiple() { + $expectedPolicy = "default-src 'none';script-src 'self' 'unsafe-eval';style-src 'self' 'unsafe-inline';img-src 'self';font-src 'self';connect-src 'self';media-src 'self';object-src www.owncloud.com"; + + $this->contentSecurityPolicy->addAllowedObjectDomain('www.owncloud.com'); + $this->contentSecurityPolicy->disallowObjectDomain('www.owncloud.org'); + $this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy()); + } + + public function testGetPolicyDisallowObjectDomainMultipleStakes() { + $expectedPolicy = "default-src 'none';script-src 'self' 'unsafe-eval';style-src 'self' 'unsafe-inline';img-src 'self';font-src 'self';connect-src 'self';media-src 'self'"; + + $this->contentSecurityPolicy->addAllowedObjectDomain('www.owncloud.com'); + $this->contentSecurityPolicy->disallowObjectDomain('www.owncloud.org')->disallowObjectDomain('www.owncloud.com'); + $this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy()); + } + public function testGetAllowedFrameDomain() { $expectedPolicy = "default-src 'none';script-src 'self' 'unsafe-eval';style-src 'self' 'unsafe-inline';img-src 'self';font-src 'self';connect-src 'self';media-src 'self';frame-src www.owncloud.com"; @@ -196,6 +364,30 @@ class ContentSecurityPolicyTest extends \Test\TestCase { $this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy()); } + public function testGetPolicyDisallowFrameDomain() { + $expectedPolicy = "default-src 'none';script-src 'self' 'unsafe-eval';style-src 'self' 'unsafe-inline';img-src 'self';font-src 'self';connect-src 'self';media-src 'self'"; + + $this->contentSecurityPolicy->addAllowedFrameDomain('www.owncloud.com'); + $this->contentSecurityPolicy->disallowFrameDomain('www.owncloud.com'); + $this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy()); + } + + public function testGetPolicyDisallowFrameDomainMultiple() { + $expectedPolicy = "default-src 'none';script-src 'self' 'unsafe-eval';style-src 'self' 'unsafe-inline';img-src 'self';font-src 'self';connect-src 'self';media-src 'self';frame-src www.owncloud.com"; + + $this->contentSecurityPolicy->addAllowedFrameDomain('www.owncloud.com'); + $this->contentSecurityPolicy->disallowFrameDomain('www.owncloud.org'); + $this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy()); + } + + public function testGetPolicyDisallowFrameDomainMultipleStakes() { + $expectedPolicy = "default-src 'none';script-src 'self' 'unsafe-eval';style-src 'self' 'unsafe-inline';img-src 'self';font-src 'self';connect-src 'self';media-src 'self'"; + + $this->contentSecurityPolicy->addAllowedFrameDomain('www.owncloud.com'); + $this->contentSecurityPolicy->disallowFrameDomain('www.owncloud.org')->disallowFrameDomain('www.owncloud.com'); + $this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy()); + } + public function testGetAllowedChildSrcDomain() { $expectedPolicy = "default-src 'none';script-src 'self' 'unsafe-eval';style-src 'self' 'unsafe-inline';img-src 'self';font-src 'self';connect-src 'self';media-src 'self';child-src child.owncloud.com"; @@ -211,6 +403,30 @@ class ContentSecurityPolicyTest extends \Test\TestCase { $this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy()); } + public function testGetPolicyDisallowChildSrcDomain() { + $expectedPolicy = "default-src 'none';script-src 'self' 'unsafe-eval';style-src 'self' 'unsafe-inline';img-src 'self';font-src 'self';connect-src 'self';media-src 'self'"; + + $this->contentSecurityPolicy->addAllowedChildSrcDomain('www.owncloud.com'); + $this->contentSecurityPolicy->disallowChildSrcDomain('www.owncloud.com'); + $this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy()); + } + + public function testGetPolicyDisallowChildSrcDomainMultiple() { + $expectedPolicy = "default-src 'none';script-src 'self' 'unsafe-eval';style-src 'self' 'unsafe-inline';img-src 'self';font-src 'self';connect-src 'self';media-src 'self';child-src www.owncloud.com"; + + $this->contentSecurityPolicy->addAllowedChildSrcDomain('www.owncloud.com'); + $this->contentSecurityPolicy->disallowChildSrcDomain('www.owncloud.org'); + $this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy()); + } + + public function testGetPolicyDisallowChildSrcDomainMultipleStakes() { + $expectedPolicy = "default-src 'none';script-src 'self' 'unsafe-eval';style-src 'self' 'unsafe-inline';img-src 'self';font-src 'self';connect-src 'self';media-src 'self'"; + + $this->contentSecurityPolicy->addAllowedChildSrcDomain('www.owncloud.com'); + $this->contentSecurityPolicy->disallowChildSrcDomain('www.owncloud.org')->disallowChildSrcDomain('www.owncloud.com'); + $this->assertSame($expectedPolicy, $this->contentSecurityPolicy->buildPolicy()); + } + public function testConfigureStacked() { $expectedPolicy = "default-src 'none';script-src 'self' script.owncloud.org;style-src 'self' style.owncloud.org;img-src 'self' img.owncloud.org;font-src 'self' font.owncloud.org;connect-src 'self' connect.owncloud.org;media-src 'self' media.owncloud.org;object-src objects.owncloud.org;frame-src frame.owncloud.org;child-src child.owncloud.org"; diff --git a/tests/lib/appframework/http/RequestTest.php b/tests/lib/appframework/http/RequestTest.php index 282d13a3397..a4bf3519bfc 100644 --- a/tests/lib/appframework/http/RequestTest.php +++ b/tests/lib/appframework/http/RequestTest.php @@ -797,7 +797,7 @@ class RequestTest extends \Test\TestCase { $this->stream ); - $this->assertNull(\Test_Helper::invokePrivate($request, 'getOverwriteHost')); + $this->assertNull(self::invokePrivate($request, 'getOverwriteHost')); } public function testGetOverwriteHostWithOverwrite() { @@ -824,7 +824,7 @@ class RequestTest extends \Test\TestCase { $this->stream ); - $this->assertSame('www.owncloud.org', \Test_Helper::invokePrivate($request, 'getOverwriteHost')); + $this->assertSame('www.owncloud.org', self::invokePrivate($request, 'getOverwriteHost')); } public function testGetPathInfoWithSetEnv() { diff --git a/tests/lib/appframework/middleware/security/CORSMiddlewareTest.php b/tests/lib/appframework/middleware/security/CORSMiddlewareTest.php index a4f3137cb11..5c93c95e188 100644 --- a/tests/lib/appframework/middleware/security/CORSMiddlewareTest.php +++ b/tests/lib/appframework/middleware/security/CORSMiddlewareTest.php @@ -21,10 +21,12 @@ use OCP\AppFramework\Http\Response; class CORSMiddlewareTest extends \Test\TestCase { private $reflector; + private $session; protected function setUp() { parent::setUp(); $this->reflector = new ControllerMethodReflector(); + $this->session = $this->getMock('\OCP\IUserSession'); } /** @@ -41,7 +43,7 @@ class CORSMiddlewareTest extends \Test\TestCase { $this->getMock('\OCP\IConfig') ); $this->reflector->reflect($this, __FUNCTION__); - $middleware = new CORSMiddleware($request, $this->reflector); + $middleware = new CORSMiddleware($request, $this->reflector, $this->session); $response = $middleware->afterController($this, __FUNCTION__, new Response()); $headers = $response->getHeaders(); @@ -59,7 +61,7 @@ class CORSMiddlewareTest extends \Test\TestCase { $this->getMock('\OCP\Security\ISecureRandom'), $this->getMock('\OCP\IConfig') ); - $middleware = new CORSMiddleware($request, $this->reflector); + $middleware = new CORSMiddleware($request, $this->reflector, $this->session); $response = $middleware->afterController($this, __FUNCTION__, new Response()); $headers = $response->getHeaders(); @@ -77,7 +79,7 @@ class CORSMiddlewareTest extends \Test\TestCase { $this->getMock('\OCP\IConfig') ); $this->reflector->reflect($this, __FUNCTION__); - $middleware = new CORSMiddleware($request, $this->reflector); + $middleware = new CORSMiddleware($request, $this->reflector, $this->session); $response = $middleware->afterController($this, __FUNCTION__, new Response()); $headers = $response->getHeaders(); @@ -100,11 +102,83 @@ class CORSMiddlewareTest extends \Test\TestCase { $this->getMock('\OCP\IConfig') ); $this->reflector->reflect($this, __FUNCTION__); - $middleware = new CORSMiddleware($request, $this->reflector); + $middleware = new CORSMiddleware($request, $this->reflector, $this->session); $response = new Response(); $response->addHeader('AcCess-control-Allow-Credentials ', 'TRUE'); $middleware->afterController($this, __FUNCTION__, $response); } + /** + * @CORS + * @PublicPage + */ + public function testNoCORSShouldAllowCookieAuth() { + $request = new Request( + [], + $this->getMock('\OCP\Security\ISecureRandom'), + $this->getMock('\OCP\IConfig') + ); + $this->reflector->reflect($this, __FUNCTION__); + $middleware = new CORSMiddleware($request, $this->reflector, $this->session); + $this->session->expects($this->never()) + ->method('logout'); + $this->session->expects($this->never()) + ->method('login') + ->with($this->equalTo('user'), $this->equalTo('pass')) + ->will($this->returnValue(true)); + $this->reflector->reflect($this, __FUNCTION__); + + $middleware->beforeController($this, __FUNCTION__, new Response()); + } + + /** + * @CORS + */ + public function testCORSShouldRelogin() { + $request = new Request( + ['server' => [ + 'PHP_AUTH_USER' => 'user', + 'PHP_AUTH_PW' => 'pass' + ]], + $this->getMock('\OCP\Security\ISecureRandom'), + $this->getMock('\OCP\IConfig') + ); + $this->session->expects($this->once()) + ->method('logout'); + $this->session->expects($this->once()) + ->method('login') + ->with($this->equalTo('user'), $this->equalTo('pass')) + ->will($this->returnValue(true)); + $this->reflector->reflect($this, __FUNCTION__); + $middleware = new CORSMiddleware($request, $this->reflector, $this->session); + + $middleware->beforeController($this, __FUNCTION__, new Response()); + } + + /** + * @CORS + * @expectedException \OC\AppFramework\Middleware\Security\SecurityException + */ + public function testCORSShouldNotAllowCookieAuth() { + $request = new Request( + ['server' => [ + 'PHP_AUTH_USER' => 'user', + 'PHP_AUTH_PW' => 'pass' + ]], + $this->getMock('\OCP\Security\ISecureRandom'), + $this->getMock('\OCP\IConfig') + ); + $this->session->expects($this->once()) + ->method('logout'); + $this->session->expects($this->once()) + ->method('login') + ->with($this->equalTo('user'), $this->equalTo('pass')) + ->will($this->returnValue(false)); + $this->reflector->reflect($this, __FUNCTION__); + $middleware = new CORSMiddleware($request, $this->reflector, $this->session); + + $middleware->beforeController($this, __FUNCTION__, new Response()); + } + } diff --git a/tests/lib/cache/file.php b/tests/lib/cache/file.php index 153cb198f13..e31f84ee6f1 100644 --- a/tests/lib/cache/file.php +++ b/tests/lib/cache/file.php @@ -1,24 +1,24 @@ <?php /** -* ownCloud -* -* @author Robin Appelman -* @copyright 2012 Robin Appelman icewind@owncloud.com -* -* This library is free software; you can redistribute it and/or -* modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE -* License as published by the Free Software Foundation; either -* version 3 of the License, or any later version. -* -* This library is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU AFFERO GENERAL PUBLIC LICENSE for more details. -* -* You should have received a copy of the GNU Affero General Public -* License along with this library. If not, see <http://www.gnu.org/licenses/>. -* -*/ + * ownCloud + * + * @author Robin Appelman + * @copyright 2012 Robin Appelman icewind@owncloud.com + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE + * License as published by the Free Software Foundation; either + * version 3 of the License, or any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU AFFERO GENERAL PUBLIC LICENSE for more details. + * + * You should have received a copy of the GNU Affero General Public + * License along with this library. If not, see <http://www.gnu.org/licenses/>. + * + */ namespace Test\Cache; @@ -51,17 +51,17 @@ class FileCache extends \Test_Cache { \OC_User::clearBackends(); \OC_User::useBackend(new \OC_User_Dummy()); - + //login \OC_User::createUser('test', 'test'); - + $this->user = \OC_User::getUser(); \OC_User::setUserId('test'); //set up the users dir $rootView = new \OC\Files\View(''); $rootView->mkdir('/test'); - + $this->instance=new \OC\Cache\File(); } diff --git a/tests/lib/cache/fileglobalgc.php b/tests/lib/cache/fileglobalgc.php deleted file mode 100644 index 4f032538e7d..00000000000 --- a/tests/lib/cache/fileglobalgc.php +++ /dev/null @@ -1,107 +0,0 @@ -<?php -/** - * ownCloud - * - * @author Robin Appelman - * @copyright 2012 Robin Appelman icewind@owncloud.com - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE - * License as published by the Free Software Foundation; either - * version 3 of the License, or any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU AFFERO GENERAL PUBLIC LICENSE for more details. - * - * You should have received a copy of the GNU Affero General Public - * License along with this library. If not, see <http://www.gnu.org/licenses/>. - * - */ - -namespace Test\Cache; - -use Test\TestCase; - -class FileGlobalGC extends TestCase { - /** - * @var string - */ - private $cacheDir; - - /** - * @var \OC\Cache\FileGlobalGC - */ - private $gc; - - public function setUp() { - $this->cacheDir = \OC::$server->getTempManager()->getTemporaryFolder(); - $this->gc = new \OC\Cache\FileGlobalGC(); - } - - private function addCacheFile($name, $expire) { - file_put_contents($this->cacheDir . $name, 'foo'); - touch($this->cacheDir . $name, $expire); - } - - public function testGetExpiredEmpty() { - $this->assertEquals([], $this->gc->getExpiredPaths($this->cacheDir, time())); - } - - public function testGetExpiredNone() { - $time = time(); - $this->addCacheFile('foo', $time + 10); - $this->assertEquals([], $this->gc->getExpiredPaths($this->cacheDir, $time)); - } - - public function testGetExpired() { - $time = time(); - $this->addCacheFile('foo', $time + 10); - $this->addCacheFile('bar', $time); - $this->addCacheFile('bar2', $time - 10); - $this->addCacheFile('asd', $time - 100); - $this->assertEquals([$this->cacheDir . 'asd', $this->cacheDir . 'bar2'], $this->gc->getExpiredPaths($this->cacheDir, $time)); - } - - public function testGetExpiredDirectory() { - $time = time(); - $this->addCacheFile('foo', $time - 10); - mkdir($this->cacheDir . 'asd'); - $this->assertEquals([$this->cacheDir . 'foo'], $this->gc->getExpiredPaths($this->cacheDir, $time)); - } - - public function testGcUnlink() { - $time = time(); - $this->addCacheFile('foo', $time - 10); - $this->addCacheFile('bar', $time - 10); - $this->addCacheFile('asd', $time + 10); - - $config = $this->getMock('\OCP\IConfig'); - $config->expects($this->once()) - ->method('getAppValue') - ->with('core', 'global_cache_gc_lastrun', 0) - ->willReturn($time - \OC\Cache\FileGlobalGC::CLEANUP_TTL_SEC - 1); - $config->expects($this->once()) - ->method('setAppValue'); - - $this->gc->gc($config, $this->cacheDir); - $this->assertFileNotExists($this->cacheDir . 'foo'); - $this->assertFileNotExists($this->cacheDir . 'bar'); - $this->assertFileExists($this->cacheDir . 'asd'); - } - - public function testGcLastRun() { - $time = time(); - - $config = $this->getMock('\OCP\IConfig'); - $config->expects($this->once()) - ->method('getAppValue') - ->with('core', 'global_cache_gc_lastrun', 0) - ->willReturn($time); - $config->expects($this->never()) - ->method('setAppValue'); - - $this->gc->gc($config, $this->cacheDir); - } -} diff --git a/tests/lib/cache/usercache.php b/tests/lib/cache/usercache.php deleted file mode 100644 index 26a9158ab3a..00000000000 --- a/tests/lib/cache/usercache.php +++ /dev/null @@ -1,74 +0,0 @@ -<?php -/** -* ownCloud -* -* @author Robin Appelman -* @copyright 2012 Robin Appelman icewind@owncloud.com -* -* This library is free software; you can redistribute it and/or -* modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE -* License as published by the Free Software Foundation; either -* version 3 of the License, or any later version. -* -* This library is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU AFFERO GENERAL PUBLIC LICENSE for more details. -* -* You should have received a copy of the GNU Affero General Public -* License along with this library. If not, see <http://www.gnu.org/licenses/>. -* -*/ - -namespace Test\Cache; - -class UserCache extends \Test_Cache { - /** @var string */ - private $user; - /** @var string */ - private $datadir; - /** @var \OC\Files\Storage\Storage */ - private $storage; - - protected function setUp() { - parent::setUp(); - - //clear all proxies and hooks so we can do clean testing - \OC_Hook::clear('OC_Filesystem'); - - //set up temporary storage - $this->storage = \OC\Files\Filesystem::getStorage('/'); - \OC\Files\Filesystem::clearMounts(); - $storage = new \OC\Files\Storage\Temporary(array()); - \OC\Files\Filesystem::mount($storage,array(),'/'); - $datadir = str_replace('local::', '', $storage->getId()); - $this->datadir = \OC_Config::getValue('cachedirectory', \OC::$SERVERROOT.'/data/cache'); - \OC_Config::setValue('cachedirectory', $datadir); - - \OC_User::clearBackends(); - \OC_User::useBackend(new \OC_User_Dummy()); - - //login - \OC_User::createUser('test', 'test'); - - $this->user = \OC_User::getUser(); - \OC_User::setUserId('test'); - - //set up the users dir - $rootView=new \OC\Files\View(''); - $rootView->mkdir('/test'); - - $this->instance=new \OC\Cache\UserCache(); - } - - protected function tearDown() { - \OC_User::setUserId($this->user); - \OC_Config::setValue('cachedirectory', $this->datadir); - - // Restore the original mount point - \OC\Files\Filesystem::clearMounts(); - \OC\Files\Filesystem::mount($this->storage, array(), '/'); - - parent::tearDown(); - } -} diff --git a/tests/lib/connector/sabre/DummyGetResponsePluginTest.php b/tests/lib/connector/sabre/DummyGetResponsePluginTest.php new file mode 100644 index 00000000000..fa8f0694625 --- /dev/null +++ b/tests/lib/connector/sabre/DummyGetResponsePluginTest.php @@ -0,0 +1,65 @@ +<?php +/** + * @author Lukas Reschke <lukas@owncloud.com> + * + * @copyright Copyright (c) 2015, ownCloud, Inc. + * @license AGPL-3.0 + * + * This code is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License, version 3, + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License, version 3, + * along with this program. If not, see <http://www.gnu.org/licenses/> + * + */ + +namespace Test\Connector\Sabre; + +use OC\Connector\Sabre\DummyGetResponsePlugin; +use Test\TestCase; + +/** + * Class DummyGetResponsePluginTest + * + * @package Test\Connector\Sabre + */ +class DummyGetResponsePluginTest extends TestCase { + /** @var DummyGetResponsePlugin */ + private $dummyGetResponsePlugin; + + public function setUp() { + parent::setUp(); + + $this->dummyGetResponsePlugin = new DummyGetResponsePlugin(); + } + + public function testInitialize() { + /** @var \Sabre\DAV\Server $server */ + $server = $this->getMock('\Sabre\DAV\Server'); + $server + ->expects($this->once()) + ->method('on') + ->with('method:GET', [$this->dummyGetResponsePlugin, 'httpGet'], 200); + + $this->dummyGetResponsePlugin->initialize($server); + } + + + public function testHttpGet() { + /** @var \Sabre\HTTP\RequestInterface $request */ + $request = $this->getMock('\Sabre\HTTP\RequestInterface'); + /** @var \Sabre\HTTP\ResponseInterface $response */ + $response = $server = $this->getMock('\Sabre\HTTP\ResponseInterface'); + $response + ->expects($this->once()) + ->method('setBody'); + + $this->assertSame(false, $this->dummyGetResponsePlugin->httpGet($request, $response)); + } +} diff --git a/tests/lib/connector/sabre/directory.php b/tests/lib/connector/sabre/directory.php index 2550f2bcef1..c846f109d87 100644 --- a/tests/lib/connector/sabre/directory.php +++ b/tests/lib/connector/sabre/directory.php @@ -20,14 +20,14 @@ class Test_OC_Connector_Sabre_Directory extends \Test\TestCase { $this->info = $this->getMock('OC\Files\FileInfo', array(), array(), '', false); } - private function getRootDir() { + private function getDir($path = '/') { $this->view->expects($this->once()) ->method('getRelativePath') - ->will($this->returnValue('')); + ->will($this->returnValue($path)); $this->info->expects($this->once()) ->method('getPath') - ->will($this->returnValue('')); + ->will($this->returnValue($path)); return new \OC\Connector\Sabre\Directory($this->view, $this->info); } @@ -35,24 +35,13 @@ class Test_OC_Connector_Sabre_Directory extends \Test\TestCase { /** * @expectedException \Sabre\DAV\Exception\Forbidden */ - public function testCreateSharedFileFails() { - $dir = $this->getRootDir(); - $dir->createFile('Shared'); - } - - /** - * @expectedException \Sabre\DAV\Exception\Forbidden - */ - public function testCreateSharedFolderFails() { - $dir = $this->getRootDir(); - $dir->createDirectory('Shared'); - } - - /** - * @expectedException \Sabre\DAV\Exception\Forbidden - */ - public function testDeleteSharedFolderFails() { - $dir = $this->getRootDir(); + public function testDeleteRootFolderFails() { + $this->info->expects($this->any()) + ->method('isDeletable') + ->will($this->returnValue(true)); + $this->view->expects($this->never()) + ->method('rmdir'); + $dir = $this->getDir(); $dir->delete(); } @@ -68,9 +57,10 @@ class Test_OC_Connector_Sabre_Directory extends \Test\TestCase { // but fails $this->view->expects($this->once()) ->method('rmdir') + ->with('sub') ->will($this->returnValue(true)); - $dir = $this->getRootDir(); + $dir = $this->getDir('sub'); $dir->delete(); } @@ -82,7 +72,7 @@ class Test_OC_Connector_Sabre_Directory extends \Test\TestCase { ->method('isDeletable') ->will($this->returnValue(false)); - $dir = $this->getRootDir(); + $dir = $this->getDir('sub'); $dir->delete(); } @@ -98,9 +88,10 @@ class Test_OC_Connector_Sabre_Directory extends \Test\TestCase { // but fails $this->view->expects($this->once()) ->method('rmdir') + ->with('sub') ->will($this->returnValue(false)); - $dir = $this->getRootDir(); + $dir = $this->getDir('sub'); $dir->delete(); } @@ -140,7 +131,33 @@ class Test_OC_Connector_Sabre_Directory extends \Test\TestCase { // calling a second time just returns the cached values, // does not call getDirectoryContents again - $nodes = $dir->getChildren(); + $dir->getChildren(); + } + + /** + * @expectedException \Sabre\DAV\Exception\ServiceUnavailable + */ + public function testGetChildThrowStorageNotAvailableException() { + $this->view->expects($this->once()) + ->method('getFileInfo') + ->willThrowException(new \OCP\Files\StorageNotAvailableException()); + + $dir = new \OC\Connector\Sabre\Directory($this->view, $this->info); + $dir->getChild('.'); + } + + /** + * @expectedException \OC\Connector\Sabre\Exception\InvalidPath + */ + public function testGetChildThrowInvalidPath() { + $this->view->expects($this->once()) + ->method('verifyPath') + ->willThrowException(new \OCP\Files\InvalidPathException()); + $this->view->expects($this->never()) + ->method('getFileInfo'); + + $dir = new \OC\Connector\Sabre\Directory($this->view, $this->info); + $dir->getChild('.'); } public function testGetQuotaInfo() { diff --git a/tests/lib/db/migrator.php b/tests/lib/db/migrator.php index 54267740480..6bde68c2d20 100644 --- a/tests/lib/db/migrator.php +++ b/tests/lib/db/migrator.php @@ -26,11 +26,17 @@ class Migrator extends \Test\TestCase { */ private $manager; + /** + * @var IConfig + **/ + private $config; + private $tableName; protected function setUp() { parent::setUp(); + $this->config = \OC::$server->getConfig(); $this->connection = \OC_DB::getConnection(); if ($this->connection->getDatabasePlatform() instanceof OraclePlatform) { $this->markTestSkipped('DB migration tests are not supported on OCI'); @@ -39,7 +45,7 @@ class Migrator extends \Test\TestCase { $this->markTestSkipped('DB migration tests are not supported on MSSQL'); } $this->manager = new \OC\DB\MDB2SchemaManager($this->connection); - $this->tableName = strtolower($this->getUniqueID('oc_test_')); + $this->tableName = strtolower($this->getUniqueID($this->config->getSystemValue('dbtableprefix', 'oc_') . 'test_')); } protected function tearDown() { @@ -109,6 +115,27 @@ class Migrator extends \Test\TestCase { $this->assertTrue(true); } + public function testUpgradeDifferentPrefix() { + $oldTablePrefix = $this->config->getSystemValue('dbtableprefix', 'oc_'); + + $this->config->setSystemValue('dbtableprefix', 'ownc_'); + $this->tableName = strtolower($this->getUniqueID($this->config->getSystemValue('dbtableprefix') . 'test_')); + + list($startSchema, $endSchema) = $this->getDuplicateKeySchemas(); + $migrator = $this->manager->getMigrator(); + $migrator->migrate($startSchema); + + $this->connection->insert($this->tableName, array('id' => 1, 'name' => 'foo')); + $this->connection->insert($this->tableName, array('id' => 2, 'name' => 'bar')); + $this->connection->insert($this->tableName, array('id' => 3, 'name' => 'qwerty')); + + $migrator->checkMigrate($endSchema); + $migrator->migrate($endSchema); + $this->assertTrue(true); + + $this->config->setSystemValue('dbtableprefix', $oldTablePrefix); + } + public function testInsertAfterUpgrade() { list($startSchema, $endSchema) = $this->getDuplicateKeySchemas(); $migrator = $this->manager->getMigrator(); diff --git a/tests/lib/encryption/keys/storage.php b/tests/lib/encryption/keys/storage.php index e67103fb6aa..8af3821dc93 100644 --- a/tests/lib/encryption/keys/storage.php +++ b/tests/lib/encryption/keys/storage.php @@ -76,7 +76,9 @@ class StorageTest extends TestCase { $this->util->expects($this->any()) ->method('getUidAndFilename') ->willReturn(array('user1', '/files/foo.txt')); - $this->util->expects($this->any()) + // we need to strip away the part file extension in order to reuse a + // existing key if it exists, otherwise versions will break + $this->util->expects($this->once()) ->method('stripPartialFileExtension') ->willReturnArgument(0); $this->util->expects($this->any()) @@ -276,7 +278,7 @@ class StorageTest extends TestCase { /** * @dataProvider dataProviderCopyRename */ - public function testRenameKeys($source, $target, $systemWideMount, $expectedSource, $expectedTarget) { + public function testRenameKeys($source, $target, $systemWideMountSource, $systemWideMountTarget, $expectedSource, $expectedTarget) { $this->view->expects($this->any()) ->method('file_exists') ->willReturn(true); @@ -294,7 +296,12 @@ class StorageTest extends TestCase { ->will($this->returnCallback(array($this, 'getUidAndFilenameCallback'))); $this->util->expects($this->any()) ->method('isSystemWideMountPoint') - ->willReturn($systemWideMount); + ->willReturnCallback(function($path, $owner) use ($systemWideMountSource, $systemWideMountTarget) { + if(strpos($path, 'source.txt') !== false) { + return $systemWideMountSource; + } + return $systemWideMountTarget; + }); $this->storage->renameKeys($source, $target); } @@ -302,7 +309,7 @@ class StorageTest extends TestCase { /** * @dataProvider dataProviderCopyRename */ - public function testCopyKeys($source, $target, $systemWideMount, $expectedSource, $expectedTarget) { + public function testCopyKeys($source, $target, $systemWideMountSource, $systemWideMountTarget , $expectedSource, $expectedTarget) { $this->view->expects($this->any()) ->method('file_exists') ->willReturn(true); @@ -320,7 +327,12 @@ class StorageTest extends TestCase { ->will($this->returnCallback(array($this, 'getUidAndFilenameCallback'))); $this->util->expects($this->any()) ->method('isSystemWideMountPoint') - ->willReturn($systemWideMount); + ->willReturnCallback(function($path, $owner) use ($systemWideMountSource, $systemWideMountTarget) { + if(strpos($path, 'source.txt') !== false) { + return $systemWideMountSource; + } + return $systemWideMountTarget; + }); $this->storage->copyKeys($source, $target); } @@ -336,14 +348,59 @@ class StorageTest extends TestCase { public function dataProviderCopyRename() { return array( - array('/user1/files/foo.txt', '/user1/files/bar.txt', false, - '/user1/files_encryption/keys/files/foo.txt/', '/user1/files_encryption/keys/files/bar.txt/'), - array('/user1/files/foo/foo.txt', '/user1/files/bar.txt', false, - '/user1/files_encryption/keys/files/foo/foo.txt/', '/user1/files_encryption/keys/files/bar.txt/'), - array('/user1/files/foo.txt', '/user1/files/foo/bar.txt', false, - '/user1/files_encryption/keys/files/foo.txt/', '/user1/files_encryption/keys/files/foo/bar.txt/'), - array('/user1/files/foo.txt', '/user1/files/foo/bar.txt', true, - '/files_encryption/keys/files/foo.txt/', '/files_encryption/keys/files/foo/bar.txt/'), + array('/user1/files/source.txt', '/user1/files/target.txt', false, false, + '/user1/files_encryption/keys/files/source.txt/', '/user1/files_encryption/keys/files/target.txt/'), + array('/user1/files/foo/source.txt', '/user1/files/target.txt', false, false, + '/user1/files_encryption/keys/files/foo/source.txt/', '/user1/files_encryption/keys/files/target.txt/'), + array('/user1/files/source.txt', '/user1/files/foo/target.txt', false, false, + '/user1/files_encryption/keys/files/source.txt/', '/user1/files_encryption/keys/files/foo/target.txt/'), + array('/user1/files/source.txt', '/user1/files/foo/target.txt', true, true, + '/files_encryption/keys/files/source.txt/', '/files_encryption/keys/files/foo/target.txt/'), + array('/user1/files/source.txt', '/user1/files/target.txt', false, true, + '/user1/files_encryption/keys/files/source.txt/', '/files_encryption/keys/files/target.txt/'), + array('/user1/files/source.txt', '/user1/files/target.txt', true, false, + '/files_encryption/keys/files/source.txt/', '/user1/files_encryption/keys/files/target.txt/'), + + array('/user2/files/source.txt', '/user1/files/target.txt', false, false, + '/user2/files_encryption/keys/files/source.txt/', '/user1/files_encryption/keys/files/target.txt/'), + array('/user2/files/foo/source.txt', '/user1/files/target.txt', false, false, + '/user2/files_encryption/keys/files/foo/source.txt/', '/user1/files_encryption/keys/files/target.txt/'), + array('/user2/files/source.txt', '/user1/files/foo/target.txt', false, false, + '/user2/files_encryption/keys/files/source.txt/', '/user1/files_encryption/keys/files/foo/target.txt/'), + array('/user2/files/source.txt', '/user1/files/foo/target.txt', true, true, + '/files_encryption/keys/files/source.txt/', '/files_encryption/keys/files/foo/target.txt/'), + array('/user2/files/source.txt', '/user1/files/target.txt', false, true, + '/user2/files_encryption/keys/files/source.txt/', '/files_encryption/keys/files/target.txt/'), + array('/user2/files/source.txt', '/user1/files/target.txt', true, false, + '/files_encryption/keys/files/source.txt/', '/user1/files_encryption/keys/files/target.txt/'), + ); + } + + /** + * @dataProvider dataTestGetPathToKeys + * + * @param string $path + * @param boolean $systemWideMountPoint + * @param string $expected + */ + public function testGetPathToKeys($path, $systemWideMountPoint, $expected) { + + $this->util->expects($this->any()) + ->method('getUidAndFilename') + ->will($this->returnCallback(array($this, 'getUidAndFilenameCallback'))); + $this->util->expects($this->any()) + ->method('isSystemWideMountPoint') + ->willReturn($systemWideMountPoint); + + $this->assertSame($expected, + self::invokePrivate($this->storage, 'getPathToKeys', [$path]) + ); + } + + public function dataTestGetPathToKeys() { + return array( + array('/user1/files/source.txt', false, '/user1/files_encryption/keys/files/source.txt/'), + array('/user1/files/source.txt', true, '/files_encryption/keys/files/source.txt/') ); } @@ -364,7 +421,7 @@ class StorageTest extends TestCase { '/user1/files_encryption', '/user1'); - \Test_Helper::invokePrivate($this->storage, 'keySetPreparation', array('/user1/files_encryption/keys/foo')); + self::invokePrivate($this->storage, 'keySetPreparation', array('/user1/files_encryption/keys/foo')); } public function mkdirCallback() { diff --git a/tests/lib/encryption/managertest.php b/tests/lib/encryption/managertest.php index faca6474504..9af7bc2c134 100644 --- a/tests/lib/encryption/managertest.php +++ b/tests/lib/encryption/managertest.php @@ -16,11 +16,15 @@ class ManagerTest extends TestCase { /** @var \PHPUnit_Framework_MockObject_MockObject */ private $logger; + /** @var \PHPUnit_Framework_MockObject_MockObject */ + private $l10n; + public function setUp() { parent::setUp(); $this->config = $this->getMock('\OCP\IConfig'); $this->logger = $this->getMock('\OCP\ILogger'); - $this->manager = new Manager($this->config, $this->logger); + $this->l10n = $this->getMock('\OCP\Il10n'); + $this->manager = new Manager($this->config, $this->logger, $this->l10n); } public function testManagerIsDisabled() { @@ -77,7 +81,7 @@ class ManagerTest extends TestCase { /** * @expectedException \OC\Encryption\Exceptions\ModuleDoesNotExistsException - * @expectedExceptionMessage Module with id: unknown does not exists. + * @expectedExceptionMessage Module with id: unknown does not exist. */ public function testGetEncryptionModuleUnknown() { $this->config->expects($this->any())->method('getAppValue')->willReturn(true); @@ -123,7 +127,7 @@ class ManagerTest extends TestCase { $en0 = $this->manager->getEncryptionModule('ID0'); $this->assertEquals('ID0', $en0->getId()); - $en0 = \Test_Helper::invokePrivate($this->manager, 'getDefaultEncryptionModule'); + $en0 = self::invokePrivate($this->manager, 'getDefaultEncryptionModule'); $this->assertEquals('ID0', $en0->getId()); $this->assertEquals('ID0', $this->manager->getDefaultEncryptionModuleId()); @@ -191,7 +195,7 @@ class ManagerTest extends TestCase { // // /** // * @expectedException \OC\Encryption\Exceptions\ModuleDoesNotExistsException -// * @expectedExceptionMessage Module with id: unknown does not exists. +// * @expectedExceptionMessage Module with id: unknown does not exist. // */ // public function testGetEncryptionModuleUnknown() { // $config = $this->getMock('\OCP\IConfig'); diff --git a/tests/lib/encryption/utiltest.php b/tests/lib/encryption/utiltest.php index 0154fa30f7d..d5f5ce4c2e9 100644 --- a/tests/lib/encryption/utiltest.php +++ b/tests/lib/encryption/utiltest.php @@ -174,4 +174,69 @@ class UtilTest extends TestCase { ); } + /** + * @dataProvider dataTestStripPartialFileExtension + * + * @param string $path + * @param string $expected + */ + public function testStripPartialFileExtension($path, $expected) { + $this->assertSame($expected, + $this->util->stripPartialFileExtension($path)); + } + + public function dataTestStripPartialFileExtension() { + return array( + array('/foo/test.txt', '/foo/test.txt'), + array('/foo/test.txt.part', '/foo/test.txt'), + array('/foo/test.txt.ocTransferId7567846853.part', '/foo/test.txt'), + array('/foo/test.txt.ocTransferId7567.part', '/foo/test.txt'), + ); + } + + /** + * @dataProvider provideWrapStorage + */ + public function testWrapStorage($expectedWrapped, $wrappedStorages) { + $storage = $this->getMockBuilder('OC\Files\Storage\Storage') + ->disableOriginalConstructor() + ->getMock(); + + foreach ($wrappedStorages as $wrapper) { + $storage->expects($this->any()) + ->method('instanceOfStorage') + ->willReturnMap([ + [$wrapper, true], + ]); + } + + $mount = $this->getMockBuilder('OCP\Files\Mount\IMountPoint') + ->disableOriginalConstructor() + ->getMock(); + + $returnedStorage = $this->util->wrapStorage('mountPoint', $storage, $mount); + + $this->assertEquals( + $expectedWrapped, + $returnedStorage->instanceOfStorage('OC\Files\Storage\Wrapper\Encryption'), + 'Asserted that the storage is (not) wrapped with encryption' + ); + } + + public function provideWrapStorage() { + return [ + // Wrap when not wrapped or not wrapped with storage + [true, []], + [true, ['OCA\Files_Trashbin\Storage']], + + // Do not wrap shared storages + [false, ['OC\Files\Storage\Shared']], + [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\External\Storage', 'OC\Files\Storage\OwnCloud']], + [false, ['OC\Files\Storage\Shared', 'OCA\Files_Sharing\External\Storage', 'OC\Files\Storage\OwnCloud']], + ]; + } } diff --git a/tests/lib/files/cache/updater.php b/tests/lib/files/cache/updater.php index 726ee360479..ea75c8dcd72 100644 --- a/tests/lib/files/cache/updater.php +++ b/tests/lib/files/cache/updater.php @@ -216,27 +216,38 @@ class Updater extends \Test\TestCase { $this->storage->getScanner()->scan(''); + $this->assertTrue($this->cache->inCache('foo')); $this->assertTrue($this->cache->inCache('foo/foo.txt')); $this->assertTrue($this->cache->inCache('foo/bar.txt')); + $this->assertTrue($this->cache->inCache('foo/bar')); $this->assertTrue($this->cache->inCache('foo/bar/bar.txt')); $cached = []; + $cached[] = $this->cache->get('foo'); $cached[] = $this->cache->get('foo/foo.txt'); $cached[] = $this->cache->get('foo/bar.txt'); + $cached[] = $this->cache->get('foo/bar'); $cached[] = $this->cache->get('foo/bar/bar.txt'); - $this->view->rename('/foo', '/bar/foo'); + // add extension to trigger the possible mimetype change + $this->view->rename('/foo', '/bar/foo.b'); + $this->assertFalse($this->cache->inCache('foo')); $this->assertFalse($this->cache->inCache('foo/foo.txt')); $this->assertFalse($this->cache->inCache('foo/bar.txt')); + $this->assertFalse($this->cache->inCache('foo/bar')); $this->assertFalse($this->cache->inCache('foo/bar/bar.txt')); - $this->assertTrue($cache2->inCache('foo/foo.txt')); - $this->assertTrue($cache2->inCache('foo/bar.txt')); - $this->assertTrue($cache2->inCache('foo/bar/bar.txt')); + $this->assertTrue($cache2->inCache('foo.b')); + $this->assertTrue($cache2->inCache('foo.b/foo.txt')); + $this->assertTrue($cache2->inCache('foo.b/bar.txt')); + $this->assertTrue($cache2->inCache('foo.b/bar')); + $this->assertTrue($cache2->inCache('foo.b/bar/bar.txt')); $cachedTarget = []; - $cachedTarget[] = $cache2->get('foo/foo.txt'); - $cachedTarget[] = $cache2->get('foo/bar.txt'); - $cachedTarget[] = $cache2->get('foo/bar/bar.txt'); + $cachedTarget[] = $cache2->get('foo.b'); + $cachedTarget[] = $cache2->get('foo.b/foo.txt'); + $cachedTarget[] = $cache2->get('foo.b/bar.txt'); + $cachedTarget[] = $cache2->get('foo.b/bar'); + $cachedTarget[] = $cache2->get('foo.b/bar/bar.txt'); foreach ($cached as $i => $old) { $new = $cachedTarget[$i]; @@ -244,6 +255,7 @@ class Updater extends \Test\TestCase { $this->assertEquals($old['size'], $new['size']); $this->assertEquals($old['etag'], $new['etag']); $this->assertEquals($old['fileid'], $new['fileid']); + $this->assertEquals($old['mimetype'], $new['mimetype']); } } } diff --git a/tests/lib/files/node/integration.php b/tests/lib/files/node/integration.php index 545793be54a..2d5ccd1fb85 100644 --- a/tests/lib/files/node/integration.php +++ b/tests/lib/files/node/integration.php @@ -8,7 +8,6 @@ namespace Test\Files\Node; -use OC\Files\Cache\Cache; use OC\Files\Node\Root; use OC\Files\Storage\Temporary; use OC\Files\View; diff --git a/tests/lib/files/pathverificationtest.php b/tests/lib/files/pathverificationtest.php index 65342c7799e..b59aceba7b1 100644 --- a/tests/lib/files/pathverificationtest.php +++ b/tests/lib/files/pathverificationtest.php @@ -94,7 +94,7 @@ class PathVerification extends \Test\TestCase { $storage = new Local(['datadir' => '']); $fileName = " 123{$fileName}456 "; - \Test_Helper::invokePrivate($storage, 'verifyWindowsPath', [$fileName]); + self::invokePrivate($storage, 'verifyWindowsPath', [$fileName]); } public function providesInvalidCharsWindows() { @@ -151,7 +151,7 @@ class PathVerification extends \Test\TestCase { $storage = new Local(['datadir' => '']); $fileName = " 123{$fileName}456 "; - \Test_Helper::invokePrivate($storage, 'verifyWindowsPath', [$fileName]); + self::invokePrivate($storage, 'verifyWindowsPath', [$fileName]); } public function providesInvalidCharsPosix() { @@ -200,7 +200,7 @@ class PathVerification extends \Test\TestCase { public function testPathVerificationReservedNamesWindows($fileName) { $storage = new Local(['datadir' => '']); - \Test_Helper::invokePrivate($storage, 'verifyWindowsPath', [$fileName]); + self::invokePrivate($storage, 'verifyWindowsPath', [$fileName]); } public function providesReservedNamesWindows() { @@ -236,8 +236,8 @@ class PathVerification extends \Test\TestCase { public function testPathVerificationValidPaths($fileName) { $storage = new Local(['datadir' => '']); - \Test_Helper::invokePrivate($storage, 'verifyPosixPath', [$fileName]); - \Test_Helper::invokePrivate($storage, 'verifyWindowsPath', [$fileName]); + self::invokePrivate($storage, 'verifyPosixPath', [$fileName]); + self::invokePrivate($storage, 'verifyWindowsPath', [$fileName]); // nothing thrown $this->assertTrue(true); } diff --git a/tests/lib/files/storage/storage.php b/tests/lib/files/storage/storage.php index 938fecb5bf3..2355009c9bf 100644 --- a/tests/lib/files/storage/storage.php +++ b/tests/lib/files/storage/storage.php @@ -22,6 +22,8 @@ namespace Test\Files\Storage; +use OC\Files\Cache\Watcher; + abstract class Storage extends \Test\TestCase { /** * @var \OC\Files\Storage\Storage instance @@ -153,13 +155,13 @@ abstract class Storage extends \Test\TestCase { $this->instance->file_put_contents('/lorem.txt', file_get_contents($textFile, 'r')); $this->assertEquals('text/plain', $this->instance->getMimeType('/lorem.txt')); - $pngFile = \OC::$SERVERROOT . '/tests/data/logo-wide.png'; - $this->instance->file_put_contents('/logo-wide.png', file_get_contents($pngFile, 'r')); - $this->assertEquals('image/png', $this->instance->getMimeType('/logo-wide.png')); + $pngFile = \OC::$SERVERROOT . '/tests/data/desktopapp.png'; + $this->instance->file_put_contents('/desktopapp.png', file_get_contents($pngFile, 'r')); + $this->assertEquals('image/png', $this->instance->getMimeType('/desktopapp.png')); - $svgFile = \OC::$SERVERROOT . '/tests/data/logo-wide.svg'; - $this->instance->file_put_contents('/logo-wide.svg', file_get_contents($svgFile, 'r')); - $this->assertEquals('image/svg+xml', $this->instance->getMimeType('/logo-wide.svg')); + $svgFile = \OC::$SERVERROOT . '/tests/data/desktopapp.svg'; + $this->instance->file_put_contents('/desktopapp.svg', file_get_contents($svgFile, 'r')); + $this->assertEquals('image/svg+xml', $this->instance->getMimeType('/desktopapp.svg')); } @@ -176,7 +178,7 @@ abstract class Storage extends \Test\TestCase { ]; } - public function initSourceAndTarget ($source, $target = null) { + public function initSourceAndTarget($source, $target = null) { $textFile = \OC::$SERVERROOT . '/tests/data/lorem.txt'; $this->instance->file_put_contents($source, file_get_contents($textFile)); if ($target) { @@ -185,12 +187,12 @@ abstract class Storage extends \Test\TestCase { } } - public function assertSameAsLorem ($file) { + public function assertSameAsLorem($file) { $textFile = \OC::$SERVERROOT . '/tests/data/lorem.txt'; $this->assertEquals( file_get_contents($textFile), $this->instance->file_get_contents($file), - 'Expected '.$file.' to be a copy of '.$textFile + 'Expected ' . $file . ' to be a copy of ' . $textFile ); } @@ -202,9 +204,9 @@ abstract class Storage extends \Test\TestCase { $this->instance->copy($source, $target); - $this->assertTrue($this->instance->file_exists($target), $target.' was not created'); + $this->assertTrue($this->instance->file_exists($target), $target . ' was not created'); $this->assertSameAsLorem($target); - $this->assertTrue($this->instance->file_exists($source), $source.' was deleted'); + $this->assertTrue($this->instance->file_exists($source), $source . ' was deleted'); } /** @@ -216,8 +218,8 @@ abstract class Storage extends \Test\TestCase { $this->instance->rename($source, $target); $this->wait(); - $this->assertTrue($this->instance->file_exists($target), $target.' was not created'); - $this->assertFalse($this->instance->file_exists($source), $source.' still exists'); + $this->assertTrue($this->instance->file_exists($target), $target . ' was not created'); + $this->assertFalse($this->instance->file_exists($source), $source . ' still exists'); $this->assertSameAsLorem($target); } @@ -225,12 +227,12 @@ abstract class Storage extends \Test\TestCase { * @dataProvider copyAndMoveProvider */ public function testCopyOverwrite($source, $target) { - $this->initSourceAndTarget($source,$target); + $this->initSourceAndTarget($source, $target); $this->instance->copy($source, $target); - $this->assertTrue($this->instance->file_exists($target), $target.' was not created'); - $this->assertTrue($this->instance->file_exists($source), $source.' was deleted'); + $this->assertTrue($this->instance->file_exists($target), $target . ' was not created'); + $this->assertTrue($this->instance->file_exists($source), $source . ' was deleted'); $this->assertSameAsLorem($target); $this->assertSameAsLorem($source); } @@ -243,8 +245,8 @@ abstract class Storage extends \Test\TestCase { $this->instance->rename($source, $target); - $this->assertTrue($this->instance->file_exists($target), $target.' was not created'); - $this->assertFalse($this->instance->file_exists($source), $source.' still exists'); + $this->assertTrue($this->instance->file_exists($target), $target . ' was not created'); + $this->assertFalse($this->instance->file_exists($source), $source . ' still exists'); $this->assertSameAsLorem($target); } @@ -309,6 +311,22 @@ abstract class Storage extends \Test\TestCase { $this->assertTrue($this->instance->hasUpdated('/', $mtimeStart - 5)); } + /** + * Test whether checkUpdate properly returns false when there was + * no change. + */ + public function testCheckUpdate() { + if ($this->instance instanceof \OC\Files\Storage\Wrapper\Wrapper) { + $this->markTestSkipped('Cannot test update check on wrappers'); + } + $textFile = \OC::$SERVERROOT . '/tests/data/lorem.txt'; + $watcher = $this->instance->getWatcher(); + $watcher->setPolicy(Watcher::CHECK_ALWAYS); + $this->instance->file_put_contents('/lorem.txt', file_get_contents($textFile)); + $this->assertTrue($watcher->checkUpdate('/lorem.txt'), 'Update detected'); + $this->assertFalse($watcher->checkUpdate('/lorem.txt'), 'No update'); + } + public function testUnlink() { $textFile = \OC::$SERVERROOT . '/tests/data/lorem.txt'; $this->instance->file_put_contents('/lorem.txt', file_get_contents($textFile)); @@ -535,4 +553,17 @@ abstract class Storage extends \Test\TestCase { $this->assertTrue($this->instance->instanceOfStorage(get_class($this->instance))); $this->assertFalse($this->instance->instanceOfStorage('\OC')); } + + /** + * @dataProvider copyAndMoveProvider + */ + public function testCopyFromSameStorage($source, $target) { + $this->initSourceAndTarget($source); + + $this->instance->copyFromStorage($this->instance, $source, $target); + + $this->assertTrue($this->instance->file_exists($target), $target . ' was not created'); + $this->assertSameAsLorem($target); + $this->assertTrue($this->instance->file_exists($source), $source . ' was deleted'); + } } diff --git a/tests/lib/files/storage/wrapper/encryption.php b/tests/lib/files/storage/wrapper/encryption.php index 97810c9c5dd..520091df42d 100644 --- a/tests/lib/files/storage/wrapper/encryption.php +++ b/tests/lib/files/storage/wrapper/encryption.php @@ -47,6 +47,27 @@ class Encryption extends \Test\Files\Storage\Storage { */ private $cache; + /** + * @var \OC\Log | \PHPUnit_Framework_MockObject_MockObject + */ + private $logger; + + /** + * @var \OC\Encryption\File | \PHPUnit_Framework_MockObject_MockObject + */ + private $file; + + + /** + * @var \OC\Files\Mount\MountPoint | \PHPUnit_Framework_MockObject_MockObject + */ + private $mount; + + /** + * @var \OC\Files\Mount\Manager | \PHPUnit_Framework_MockObject_MockObject + */ + private $mountManager; + /** @var integer dummy unencrypted size */ private $dummySize = -1; @@ -70,20 +91,20 @@ class Encryption extends \Test\Files\Storage\Storage { ->disableOriginalConstructor() ->getMock(); - $this->util = $this->getMock('\OC\Encryption\Util', ['getUidAndFilename', 'isFile'], [new View(), new \OC\User\Manager(), $groupManager, $config]); + $this->util = $this->getMock('\OC\Encryption\Util', ['getUidAndFilename', 'isFile', 'isExcluded'], [new View(), new \OC\User\Manager(), $groupManager, $config]); $this->util->expects($this->any()) ->method('getUidAndFilename') ->willReturnCallback(function ($path) { return ['user1', $path]; }); - $file = $this->getMockBuilder('\OC\Encryption\File') + $this->file = $this->getMockBuilder('\OC\Encryption\File') ->disableOriginalConstructor() ->setMethods(['getAccessList']) ->getMock(); - $file->expects($this->any())->method('getAccessList')->willReturn([]); + $this->file->expects($this->any())->method('getAccessList')->willReturn([]); - $logger = $this->getMock('\OC\Log'); + $this->logger = $this->getMock('\OC\Log'); $this->sourceStorage = new Temporary(array()); @@ -93,17 +114,20 @@ class Encryption extends \Test\Files\Storage\Storage { $this->update = $this->getMockBuilder('\OC\Encryption\Update') ->disableOriginalConstructor()->getMock(); - $mount = $this->getMockBuilder('\OC\Files\Mount\MountPoint') + $this->mount = $this->getMockBuilder('\OC\Files\Mount\MountPoint') ->disableOriginalConstructor() ->setMethods(['getOption']) ->getMock(); - $mount->expects($this->any())->method('getOption')->willReturn(true); + $this->mount->expects($this->any())->method('getOption')->willReturn(true); $this->cache = $this->getMockBuilder('\OC\Files\Cache\Cache') ->disableOriginalConstructor()->getMock(); $this->cache->expects($this->any()) ->method('get') - ->willReturn(['encrypted' => false]); + ->willReturnCallback(function($path) {return ['encrypted' => false, 'path' => $path];}); + + $this->mountManager = $this->getMockBuilder('\OC\Files\Mount\Manager') + ->disableOriginalConstructor()->getMock(); $this->instance = $this->getMockBuilder('\OC\Files\Storage\Wrapper\Encryption') ->setConstructorArgs( @@ -112,21 +136,27 @@ class Encryption extends \Test\Files\Storage\Storage { 'storage' => $this->sourceStorage, 'root' => 'foo', 'mountPoint' => '/', - 'mount' => $mount + 'mount' => $this->mount ], - $this->encryptionManager, $this->util, $logger, $file, null, $this->keyStore, $this->update + $this->encryptionManager, $this->util, $this->logger, $this->file, null, $this->keyStore, $this->update, $this->mountManager ] ) - ->setMethods(['getMetaData', 'getCache']) + ->setMethods(['getMetaData', 'getCache', 'getEncryptionModule']) ->getMock(); $this->instance->expects($this->any()) ->method('getMetaData') - ->willReturn(['encrypted' => true, 'size' => $this->dummySize]); + ->willReturnCallback(function ($path) { + return ['encrypted' => true, 'size' => $this->dummySize, 'path' => $path]; + }); $this->instance->expects($this->any()) ->method('getCache') ->willReturn($this->cache); + + $this->instance->expects($this->any()) + ->method('getEncryptionModule') + ->willReturn($mockModule); } /** @@ -135,7 +165,7 @@ class Encryption extends \Test\Files\Storage\Storage { protected function buildMockModule() { $this->encryptionModule = $this->getMockBuilder('\OCP\Encryption\IEncryptionModule') ->disableOriginalConstructor() - ->setMethods(['getId', 'getDisplayName', 'begin', 'end', 'encrypt', 'decrypt', 'update', 'shouldEncrypt', 'getUnencryptedBlockSize']) + ->setMethods(['getId', 'getDisplayName', 'begin', 'end', 'encrypt', 'decrypt', 'update', 'shouldEncrypt', 'getUnencryptedBlockSize', 'isReadable']) ->getMock(); $this->encryptionModule->expects($this->any())->method('getId')->willReturn('UNIT_TEST_MODULE'); @@ -147,6 +177,7 @@ class Encryption extends \Test\Files\Storage\Storage { $this->encryptionModule->expects($this->any())->method('update')->willReturn(true); $this->encryptionModule->expects($this->any())->method('shouldEncrypt')->willReturn(true); $this->encryptionModule->expects($this->any())->method('getUnencryptedBlockSize')->willReturn(8192); + $this->encryptionModule->expects($this->any())->method('isReadable')->willReturn(true); return $this->encryptionModule; } @@ -211,6 +242,8 @@ class Encryption extends \Test\Files\Storage\Storage { } $this->util->expects($this->any()) ->method('isFile')->willReturn(true); + $this->util->expects($this->any()) + ->method('isExcluded')->willReturn(false); $this->encryptionManager->expects($this->once()) ->method('isEnabled')->willReturn($encryptionEnabled); if ($shouldUpdate) { @@ -252,4 +285,84 @@ class Encryption extends \Test\Files\Storage\Storage { ->method('isEnabled')->willReturn(true); $this->assertFalse($this->instance->isLocal()); } + + /** + * @dataProvider dataTestRmdir + * + * @param string $path + * @param boolean $rmdirResult + * @param boolean $isExcluded + * @param boolean $encryptionEnabled + */ + public function testRmdir($path, $rmdirResult, $isExcluded, $encryptionEnabled) { + $sourceStorage = $this->getMockBuilder('\OC\Files\Storage\Storage') + ->disableOriginalConstructor()->getMock(); + + $util = $this->getMockBuilder('\OC\Encryption\Util')->disableOriginalConstructor()->getMock(); + + $sourceStorage->expects($this->once())->method('rmdir')->willReturn($rmdirResult); + $util->expects($this->any())->method('isExcluded')-> willReturn($isExcluded); + $this->encryptionManager->expects($this->any())->method('isEnabled')->willReturn($encryptionEnabled); + + $encryptionStorage = new \OC\Files\Storage\Wrapper\Encryption( + [ + 'storage' => $sourceStorage, + 'root' => 'foo', + 'mountPoint' => '/mountPoint', + 'mount' => $this->mount + ], + $this->encryptionManager, $util, $this->logger, $this->file, null, $this->keyStore, $this->update + ); + + + if ($rmdirResult === true && $isExcluded === false && $encryptionEnabled === true) { + $this->keyStore->expects($this->once())->method('deleteAllFileKeys')->with('/mountPoint' . $path); + } else { + $this->keyStore->expects($this->never())->method('deleteAllFileKeys'); + } + + $encryptionStorage->rmdir($path); + } + + public function dataTestRmdir() { + return array( + array('/file.txt', true, true, true), + array('/file.txt', false, true, true), + array('/file.txt', true, false, true), + array('/file.txt', false, false, true), + array('/file.txt', true, true, false), + array('/file.txt', false, true, false), + array('/file.txt', true, false, false), + array('/file.txt', false, false, false), + ); + } + + /** + * @dataProvider dataTestCopyKeys + * + * @param boolean $excluded + * @param boolean $expected + */ + public function testCopyKeys($excluded, $expected) { + $this->util->expects($this->once()) + ->method('isExcluded') + ->willReturn($excluded); + + if ($excluded) { + $this->keyStore->expects($this->never())->method('copyKeys'); + } else { + $this->keyStore->expects($this->once())->method('copyKeys')->willReturn(true); + } + + $this->assertSame($expected, + self::invokePrivate($this->instance, 'copyKeys', ['/source', '/target']) + ); + } + + public function dataTestCopyKeys() { + return array( + array(true, false), + array(false, true), + ); + } } diff --git a/tests/lib/files/storage/wrapper/quota.php b/tests/lib/files/storage/wrapper/quota.php index a5828296be9..441f3a39d32 100644 --- a/tests/lib/files/storage/wrapper/quota.php +++ b/tests/lib/files/storage/wrapper/quota.php @@ -35,20 +35,21 @@ class Quota extends \Test\Files\Storage\Storage { */ protected function getLimitedStorage($limit) { $storage = new \OC\Files\Storage\Local(array('datadir' => $this->tmpDir)); + $storage->mkdir('files'); $storage->getScanner()->scan(''); return new \OC\Files\Storage\Wrapper\Quota(array('storage' => $storage, 'quota' => $limit)); } public function testFilePutContentsNotEnoughSpace() { $instance = $this->getLimitedStorage(3); - $this->assertFalse($instance->file_put_contents('foo', 'foobar')); + $this->assertFalse($instance->file_put_contents('files/foo', 'foobar')); } public function testCopyNotEnoughSpace() { $instance = $this->getLimitedStorage(9); - $this->assertEquals(6, $instance->file_put_contents('foo', 'foobar')); + $this->assertEquals(6, $instance->file_put_contents('files/foo', 'foobar')); $instance->getScanner()->scan(''); - $this->assertFalse($instance->copy('foo', 'bar')); + $this->assertFalse($instance->copy('files/foo', 'files/bar')); } public function testFreeSpace() { @@ -92,17 +93,17 @@ class Quota extends \Test\Files\Storage\Storage { public function testFWriteNotEnoughSpace() { $instance = $this->getLimitedStorage(9); - $stream = $instance->fopen('foo', 'w+'); + $stream = $instance->fopen('files/foo', 'w+'); $this->assertEquals(6, fwrite($stream, 'foobar')); $this->assertEquals(3, fwrite($stream, 'qwerty')); fclose($stream); - $this->assertEquals('foobarqwe', $instance->file_get_contents('foo')); + $this->assertEquals('foobarqwe', $instance->file_get_contents('files/foo')); } public function testStreamCopyWithEnoughSpace() { $instance = $this->getLimitedStorage(16); $inputStream = fopen('data://text/plain,foobarqwerty', 'r'); - $outputStream = $instance->fopen('foo', 'w+'); + $outputStream = $instance->fopen('files/foo', 'w+'); list($count, $result) = \OC_Helper::streamCopy($inputStream, $outputStream); $this->assertEquals(12, $count); $this->assertTrue($result); @@ -113,7 +114,7 @@ class Quota extends \Test\Files\Storage\Storage { public function testStreamCopyNotEnoughSpace() { $instance = $this->getLimitedStorage(9); $inputStream = fopen('data://text/plain,foobarqwerty', 'r'); - $outputStream = $instance->fopen('foo', 'w+'); + $outputStream = $instance->fopen('files/foo', 'w+'); list($count, $result) = \OC_Helper::streamCopy($inputStream, $outputStream); $this->assertEquals(9, $count); $this->assertFalse($result); @@ -139,16 +140,27 @@ class Quota extends \Test\Files\Storage\Storage { $instance = $this->getLimitedStorage(9); // create test file first - $stream = $instance->fopen('foo', 'w+'); + $stream = $instance->fopen('files/foo', 'w+'); fwrite($stream, 'blablacontent'); fclose($stream); - $stream = $instance->fopen('foo', 'r'); + $stream = $instance->fopen('files/foo', 'r'); $meta = stream_get_meta_data($stream); $this->assertEquals('plainfile', $meta['wrapper_type']); fclose($stream); - $stream = $instance->fopen('foo', 'rb'); + $stream = $instance->fopen('files/foo', 'rb'); + $meta = stream_get_meta_data($stream); + $this->assertEquals('plainfile', $meta['wrapper_type']); + fclose($stream); + } + + public function testReturnRegularStreamWhenOutsideFiles() { + $instance = $this->getLimitedStorage(9); + $instance->mkdir('files_other'); + + // create test file first + $stream = $instance->fopen('files_other/foo', 'w+'); $meta = stream_get_meta_data($stream); $this->assertEquals('plainfile', $meta['wrapper_type']); fclose($stream); @@ -156,7 +168,7 @@ class Quota extends \Test\Files\Storage\Storage { public function testReturnQuotaStreamOnWrite() { $instance = $this->getLimitedStorage(9); - $stream = $instance->fopen('foo', 'w+'); + $stream = $instance->fopen('files/foo', 'w+'); $meta = stream_get_meta_data($stream); $expected_type = defined('HHVM_VERSION') ? 'File' : 'user-space'; $this->assertEquals($expected_type, $meta['wrapper_type']); diff --git a/tests/lib/files/stream/dummyencryptionwrapper.php b/tests/lib/files/stream/dummyencryptionwrapper.php new file mode 100644 index 00000000000..bb512d99c66 --- /dev/null +++ b/tests/lib/files/stream/dummyencryptionwrapper.php @@ -0,0 +1,37 @@ +<?php +/** + * @author Björn Schießle <schiessle@owncloud.com> + * + * @copyright Copyright (c) 2015, ownCloud, Inc. + * @license AGPL-3.0 + * + * This code is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License, version 3, + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License, version 3, + * along with this program. If not, see <http://www.gnu.org/licenses/> + * + */ + + +namespace Test\Files\Stream; + +class DummyEncryptionWrapper extends \OC\Files\Stream\Encryption { + + /** + * simulate a non-seekable stream wrapper by always return false + * + * @param int $position + * @return bool + */ + protected function parentStreamSeek($position) { + return false; + } + +} diff --git a/tests/lib/files/stream/encryption.php b/tests/lib/files/stream/encryption.php index 892491cbc32..281ec0a14a0 100644 --- a/tests/lib/files/stream/encryption.php +++ b/tests/lib/files/stream/encryption.php @@ -3,17 +3,19 @@ namespace Test\Files\Stream; use OC\Files\View; -use OCA\Encryption_Dummy\DummyModule; class Encryption extends \Test\TestCase { + /** @var \OCP\Encryption\IEncryptionModule | \PHPUnit_Framework_MockObject_MockObject */ + private $encryptionModule; + /** * @param string $fileName * @param string $mode * @param integer $unencryptedSize * @return resource */ - protected function getStream($fileName, $mode, $unencryptedSize) { + protected function getStream($fileName, $mode, $unencryptedSize, $wrapper = '\OC\Files\Stream\Encryption') { clearstatcache(); $size = filesize($fileName); $source = fopen($fileName, $mode); @@ -21,7 +23,7 @@ class Encryption extends \Test\TestCase { $fullPath = $fileName; $header = []; $uid = ''; - $encryptionModule = $this->buildMockModule(); + $this->encryptionModule = $this->buildMockModule(); $storage = $this->getMockBuilder('\OC\Files\Storage\Storage') ->disableOriginalConstructor()->getMock(); $encStorage = $this->getMockBuilder('\OC\Files\Storage\Wrapper\Encryption') @@ -42,9 +44,10 @@ class Encryption extends \Test\TestCase { ->method('getUidAndFilename') ->willReturn(['user1', $internalPath]); - return \OC\Files\Stream\Encryption::wrap($source, $internalPath, - $fullPath, $header, $uid, $encryptionModule, $storage, $encStorage, - $util, $file, $mode, $size, $unencryptedSize, 8192); + + return $wrapper::wrap($source, $internalPath, + $fullPath, $header, $uid, $this->encryptionModule, $storage, $encStorage, + $util, $file, $mode, $size, $unencryptedSize, 8192, $wrapper); } /** @@ -160,15 +163,6 @@ class Encryption extends \Test\TestCase { $this->assertEquals('foobar', fread($stream, 100)); fclose($stream); - unlink($fileName); - } - - public function testWriteWriteRead() { - $fileName = tempnam("/tmp", "FOO"); - $stream = $this->getStream($fileName, 'w+', 0); - $this->assertEquals(6, fwrite($stream, 'foobar')); - fclose($stream); - $stream = $this->getStream($fileName, 'r+', 6); $this->assertEquals(3, fwrite($stream, 'bar')); fclose($stream); @@ -176,6 +170,8 @@ class Encryption extends \Test\TestCase { $stream = $this->getStream($fileName, 'r', 6); $this->assertEquals('barbar', fread($stream, 100)); fclose($stream); + + unlink($fileName); } public function testRewind() { @@ -191,7 +187,9 @@ class Encryption extends \Test\TestCase { $stream = $this->getStream($fileName, 'r', 6); $this->assertEquals('barbar', fread($stream, 100)); fclose($stream); - } + + unlink($fileName); +} public function testSeek() { $fileName = tempnam("/tmp", "FOO"); @@ -203,6 +201,12 @@ class Encryption extends \Test\TestCase { $stream = $this->getStream($fileName, 'r', 9); $this->assertEquals('foofoobar', fread($stream, 100)); + $this->assertEquals(-1, fseek($stream, 10)); + $this->assertEquals(0, fseek($stream, 9)); + $this->assertEquals(-1, fseek($stream, -10, SEEK_CUR)); + $this->assertEquals(0, fseek($stream, -9, SEEK_CUR)); + $this->assertEquals(-1, fseek($stream, -10, SEEK_END)); + $this->assertEquals(0, fseek($stream, -9, SEEK_END)); fclose($stream); unlink($fileName); @@ -220,10 +224,15 @@ class Encryption extends \Test\TestCase { * @dataProvider dataFilesProvider */ public function testWriteReadBigFile($testFile) { + $expectedData = file_get_contents(\OC::$SERVERROOT . '/tests/data/' . $testFile); // write it $fileName = tempnam("/tmp", "FOO"); $stream = $this->getStream($fileName, 'w+', 0); + // while writing the file from the beginning to the end we should never try + // to read parts of the file. This should only happen for write operations + // in the middle of a file + $this->encryptionModule->expects($this->never())->method('decrypt'); fwrite($stream, $expectedData); fclose($stream); @@ -248,18 +257,62 @@ class Encryption extends \Test\TestCase { } /** + * simulate a non-seekable storage + * + * @dataProvider dataFilesProvider + */ + public function testWriteToNonSeekableStorage($testFile) { + + $wrapper = $this->getMockBuilder('\OC\Files\Stream\Encryption') + ->setMethods(['parentSeekStream'])->getMock(); + $wrapper->expects($this->any())->method('parentSeekStream')->willReturn(false); + + $expectedData = file_get_contents(\OC::$SERVERROOT . '/tests/data/' . $testFile); + // write it + $fileName = tempnam("/tmp", "FOO"); + $stream = $this->getStream($fileName, 'w+', 0, '\Test\Files\Stream\DummyEncryptionWrapper'); + // while writing the file from the beginning to the end we should never try + // to read parts of the file. This should only happen for write operations + // in the middle of a file + $this->encryptionModule->expects($this->never())->method('decrypt'); + fwrite($stream, $expectedData); + fclose($stream); + + // read it all + $stream = $this->getStream($fileName, 'r', strlen($expectedData), '\Test\Files\Stream\DummyEncryptionWrapper'); + $data = stream_get_contents($stream); + fclose($stream); + + $this->assertEquals($expectedData, $data); + + // another read test with a loop like we do in several places: + $stream = $this->getStream($fileName, 'r', strlen($expectedData)); + $data = ''; + while (!feof($stream)) { + $data .= fread($stream, 8192); + } + fclose($stream); + + $this->assertEquals($expectedData, $data); + + unlink($fileName); + + } + + /** * @return \PHPUnit_Framework_MockObject_MockObject */ protected function buildMockModule() { $encryptionModule = $this->getMockBuilder('\OCP\Encryption\IEncryptionModule') ->disableOriginalConstructor() - ->setMethods(['getId', 'getDisplayName', 'begin', 'end', 'encrypt', 'decrypt', 'update', 'shouldEncrypt', 'getUnencryptedBlockSize']) + ->setMethods(['getId', 'getDisplayName', 'begin', 'end', 'encrypt', 'decrypt', 'update', 'shouldEncrypt', 'getUnencryptedBlockSize', 'isReadable']) ->getMock(); $encryptionModule->expects($this->any())->method('getId')->willReturn('UNIT_TEST_MODULE'); $encryptionModule->expects($this->any())->method('getDisplayName')->willReturn('Unit test module'); $encryptionModule->expects($this->any())->method('begin')->willReturn([]); $encryptionModule->expects($this->any())->method('end')->willReturn(''); + $encryptionModule->expects($this->any())->method('isReadable')->willReturn(true); $encryptionModule->expects($this->any())->method('encrypt')->willReturnCallback(function($data) { // simulate different block size by adding some padding to the data if (isset($data[6125])) { diff --git a/tests/lib/files/view.php b/tests/lib/files/view.php index 6bc63557138..06a42d63431 100644 --- a/tests/lib/files/view.php +++ b/tests/lib/files/view.php @@ -11,6 +11,7 @@ use OC\Files\Cache\Watcher; use OC\Files\Storage\Common; use OC\Files\Mount\MountPoint; use OC\Files\Storage\Temporary; +use OCP\Lock\ILockingProvider; class TemporaryNoTouch extends \OC\Files\Storage\Temporary { public function touch($path, $mtime = null) { @@ -1080,4 +1081,30 @@ class View extends \Test\TestCase { public function testNullAsRoot() { new \OC\Files\View(null); } + + /** + * e.g. reading from a folder that's being renamed + * + * @expectedException \OCP\Lock\LockedException + */ + public function testReadFromWriteLockedPath() { + $view = new \OC\Files\View(); + $storage = new Temporary(array()); + \OC\Files\Filesystem::mount($storage, [], '/'); + $view->lockFile('/foo/bar', ILockingProvider::LOCK_EXCLUSIVE); + $view->lockFile('/foo/bar/asd', ILockingProvider::LOCK_SHARED); + } + + /** + * e.g. writing a file that's being downloaded + * + * @expectedException \OCP\Lock\LockedException + */ + public function testWriteToReadLockedFile() { + $view = new \OC\Files\View(); + $storage = new Temporary(array()); + \OC\Files\Filesystem::mount($storage, [], '/'); + $view->lockFile('/foo/bar', ILockingProvider::LOCK_SHARED); + $view->lockFile('/foo/bar', ILockingProvider::LOCK_EXCLUSIVE); + } } diff --git a/tests/lib/helper.php b/tests/lib/helper.php index b7aa185f4e3..bd527de160d 100644 --- a/tests/lib/helper.php +++ b/tests/lib/helper.php @@ -85,11 +85,11 @@ class Test_Helper extends \Test\TestCase { $expected = 'application/zip'; $this->assertEquals($result, $expected); - $result = OC_Helper::getMimeType($dir."/logo-wide.svg"); + $result = OC_Helper::getMimeType($dir."/desktopapp.svg"); $expected = 'image/svg+xml'; $this->assertEquals($result, $expected); - $result = OC_Helper::getMimeType($dir."/logo-wide.png"); + $result = OC_Helper::getMimeType($dir."/desktopapp.png"); $expected = 'image/png'; $this->assertEquals($result, $expected); } @@ -509,28 +509,9 @@ class Test_Helper extends \Test\TestCase { * @param $methodName * @param array $parameters * @return mixed + * @deprecated Please extend \Test\TestCase and use self::invokePrivate() then */ public static function invokePrivate($object, $methodName, array $parameters = array()) { - $reflection = new ReflectionClass(get_class($object)); - - if ($reflection->hasMethod($methodName)) { - $method = $reflection->getMethod($methodName); - - $method->setAccessible(true); - - return $method->invokeArgs($object, $parameters); - } elseif ($reflection->hasProperty($methodName)) { - $property = $reflection->getProperty($methodName); - - $property->setAccessible(true); - - if (!empty($parameters)) { - $property->setValue($object, array_pop($parameters)); - } - - return $property->getValue($object); - } - - return false; + return parent::invokePrivate($object, $methodName, $parameters); } } diff --git a/tests/lib/http/client/clienttest.php b/tests/lib/http/client/clienttest.php index bd909769b09..c76fe0532a7 100644 --- a/tests/lib/http/client/clienttest.php +++ b/tests/lib/http/client/clienttest.php @@ -47,7 +47,7 @@ class ClientTest extends \Test\TestCase { ->method('getSystemValue') ->with('proxyuserpwd', null) ->willReturn(null); - $this->assertSame('', \Test_Helper::invokePrivate($this->client, 'getProxyUri')); + $this->assertSame('', self::invokePrivate($this->client, 'getProxyUri')); } public function testGetProxyUriProxyHostEmptyPassword() { @@ -61,7 +61,7 @@ class ClientTest extends \Test\TestCase { ->method('getSystemValue') ->with('proxyuserpwd', null) ->willReturn(null); - $this->assertSame('foo', \Test_Helper::invokePrivate($this->client, 'getProxyUri')); + $this->assertSame('foo', self::invokePrivate($this->client, 'getProxyUri')); } public function testGetProxyUriProxyHostWithPassword() { @@ -75,7 +75,7 @@ class ClientTest extends \Test\TestCase { ->method('getSystemValue') ->with('proxyuserpwd', null) ->willReturn('username:password'); - $this->assertSame('username:password@foo', \Test_Helper::invokePrivate($this->client, 'getProxyUri')); + $this->assertSame('username:password@foo', self::invokePrivate($this->client, 'getProxyUri')); } public function testGet() { diff --git a/tests/lib/httphelper.php b/tests/lib/httphelper.php index e8472ab553a..1d0981ba51b 100644 --- a/tests/lib/httphelper.php +++ b/tests/lib/httphelper.php @@ -12,15 +12,17 @@ class TestHTTPHelper extends \Test\TestCase { private $config; /** @var \OC\HTTPHelper */ private $httpHelperMock; + /** @var \OCP\Http\Client\IClientService */ + private $clientService; protected function setUp() { parent::setUp(); $this->config = $this->getMockBuilder('\OCP\IConfig') ->disableOriginalConstructor()->getMock(); - $clientService = $this->getMock('\OCP\Http\Client\IClientService'); + $this->clientService = $this->getMock('\OCP\Http\Client\IClientService'); $this->httpHelperMock = $this->getMockBuilder('\OC\HTTPHelper') - ->setConstructorArgs(array($this->config, $clientService)) + ->setConstructorArgs(array($this->config, $this->clientService)) ->setMethods(array('getHeaders')) ->getMock(); } @@ -44,4 +46,73 @@ class TestHTTPHelper extends \Test\TestCase { public function testIsHTTP($url, $expected) { $this->assertSame($expected, $this->httpHelperMock->isHTTPURL($url)); } + + public function testPostSuccess() { + $client = $this->getMockBuilder('\OCP\Http\Client\IClient') + ->disableOriginalConstructor()->getMock(); + $this->clientService + ->expects($this->once()) + ->method('newClient') + ->will($this->returnValue($client)); + $response = $this->getMockBuilder('\OCP\Http\Client\IResponse') + ->disableOriginalConstructor()->getMock(); + $client + ->expects($this->once()) + ->method('post') + ->with( + 'https://owncloud.org', + [ + 'body' => [ + 'Foo' => 'Bar', + ], + 'connect_timeout' => 10, + + ] + ) + ->will($this->returnValue($response)); + $response + ->expects($this->once()) + ->method('getBody') + ->will($this->returnValue('Body of the requested page')); + + + $response = $this->httpHelperMock->post('https://owncloud.org', ['Foo' => 'Bar']); + $expected = [ + 'success' => true, + 'result' => 'Body of the requested page' + ]; + $this->assertSame($expected, $response); + } + + public function testPostException() { + $client = $this->getMockBuilder('\OCP\Http\Client\IClient') + ->disableOriginalConstructor()->getMock(); + $this->clientService + ->expects($this->once()) + ->method('newClient') + ->will($this->returnValue($client)); + $client + ->expects($this->once()) + ->method('post') + ->with( + 'https://owncloud.org', + [ + 'body' => [ + 'Foo' => 'Bar', + ], + 'connect_timeout' => 10, + + ] + ) + ->will($this->throwException(new \Exception('Something failed'))); + + + $response = $this->httpHelperMock->post('https://owncloud.org', ['Foo' => 'Bar']); + $expected = [ + 'success' => false, + 'result' => 'Something failed' + ]; + $this->assertSame($expected, $response); + } + } diff --git a/tests/lib/lock/lockingprovider.php b/tests/lib/lock/lockingprovider.php index 08d879da8bb..efd6e1939f2 100644 --- a/tests/lib/lock/lockingprovider.php +++ b/tests/lib/lock/lockingprovider.php @@ -107,6 +107,30 @@ abstract class LockingProvider extends TestCase { $this->assertTrue($this->instance->isLocked('foo', ILockingProvider::LOCK_EXCLUSIVE)); } + public function testReleaseAll() { + $this->instance->acquireLock('foo', ILockingProvider::LOCK_SHARED); + $this->instance->acquireLock('foo', ILockingProvider::LOCK_SHARED); + $this->instance->acquireLock('bar', ILockingProvider::LOCK_SHARED); + $this->instance->acquireLock('asd', ILockingProvider::LOCK_EXCLUSIVE); + + $this->instance->releaseAll(); + + $this->assertFalse($this->instance->isLocked('foo', ILockingProvider::LOCK_SHARED)); + $this->assertFalse($this->instance->isLocked('bar', ILockingProvider::LOCK_SHARED)); + $this->assertFalse($this->instance->isLocked('asd', ILockingProvider::LOCK_EXCLUSIVE)); + } + + public function testReleaseAfterReleaseAll() { + $this->instance->acquireLock('foo', ILockingProvider::LOCK_SHARED); + $this->instance->acquireLock('foo', ILockingProvider::LOCK_SHARED); + + $this->instance->releaseAll(); + + $this->assertFalse($this->instance->isLocked('foo', ILockingProvider::LOCK_SHARED)); + + $this->instance->releaseLock('foo', ILockingProvider::LOCK_SHARED); + } + /** * @expectedException \OCP\Lock\LockedException @@ -134,4 +158,57 @@ abstract class LockingProvider extends TestCase { $this->assertEquals('foo', $e->getPath()); } } + + public function testChangeLockToExclusive() { + $this->instance->acquireLock('foo', ILockingProvider::LOCK_SHARED); + $this->instance->changeLock('foo', ILockingProvider::LOCK_EXCLUSIVE); + $this->assertFalse($this->instance->isLocked('foo', ILockingProvider::LOCK_SHARED)); + $this->assertTrue($this->instance->isLocked('foo', ILockingProvider::LOCK_EXCLUSIVE)); + } + + public function testChangeLockToShared() { + $this->instance->acquireLock('foo', ILockingProvider::LOCK_EXCLUSIVE); + $this->instance->changeLock('foo', ILockingProvider::LOCK_SHARED); + $this->assertFalse($this->instance->isLocked('foo', ILockingProvider::LOCK_EXCLUSIVE)); + $this->assertTrue($this->instance->isLocked('foo', ILockingProvider::LOCK_SHARED)); + } + + /** + * @expectedException \OCP\Lock\LockedException + */ + public function testChangeLockToExclusiveDoubleShared() { + $this->instance->acquireLock('foo', ILockingProvider::LOCK_SHARED); + $this->instance->acquireLock('foo', ILockingProvider::LOCK_SHARED); + $this->instance->changeLock('foo', ILockingProvider::LOCK_EXCLUSIVE); + } + + /** + * @expectedException \OCP\Lock\LockedException + */ + public function testChangeLockToExclusiveNoShared() { + $this->instance->changeLock('foo', ILockingProvider::LOCK_EXCLUSIVE); + } + + /** + * @expectedException \OCP\Lock\LockedException + */ + public function testChangeLockToExclusiveFromExclusive() { + $this->instance->acquireLock('foo', ILockingProvider::LOCK_EXCLUSIVE); + $this->instance->changeLock('foo', ILockingProvider::LOCK_EXCLUSIVE); + } + + /** + * @expectedException \OCP\Lock\LockedException + */ + public function testChangeLockToSharedNoExclusive() { + $this->instance->changeLock('foo', ILockingProvider::LOCK_SHARED); + } + + /** + * @expectedException \OCP\Lock\LockedException + */ + public function testChangeLockToSharedFromShared() { + $this->instance->acquireLock('foo', ILockingProvider::LOCK_SHARED); + $this->instance->changeLock('foo', ILockingProvider::LOCK_SHARED); + } } diff --git a/tests/lib/logger.php b/tests/lib/logger.php index 700a847917b..9a9f5be12fc 100644 --- a/tests/lib/logger.php +++ b/tests/lib/logger.php @@ -21,14 +21,38 @@ class Logger extends TestCase { parent::setUp(); self::$logs = array(); - $this->logger = new Log('Test\Logger'); + $this->config = $this->getMockBuilder( + '\OC\SystemConfig') + ->disableOriginalConstructor() + ->getMock(); + $this->logger = new Log('Test\Logger', $this->config); } public function testInterpolation() { $logger = $this->logger; - $logger->info('{Message {nothing} {user} {foo.bar} a}', array('user' => 'Bob', 'foo.bar' => 'Bar')); + $logger->warning('{Message {nothing} {user} {foo.bar} a}', array('user' => 'Bob', 'foo.bar' => 'Bar')); - $expected = array('1 {Message {nothing} Bob Bar a}'); + $expected = array('2 {Message {nothing} Bob Bar a}'); + $this->assertEquals($expected, $this->getLogs()); + } + + public function testAppCondition() { + $this->config->expects($this->any()) + ->method('getValue') + ->will(($this->returnValueMap([ + ['loglevel', \OC_Log::WARN, \OC_Log::WARN], + ['log.condition', [], ['apps' => ['files']]] + ]))); + $logger = $this->logger; + + $logger->info('Don\'t display info messages'); + $logger->info('Show info messages of files app', ['app' => 'files']); + $logger->warning('Show warning messages of other apps'); + + $expected = [ + '1 Show info messages of files app', + '2 Show warning messages of other apps', + ]; $this->assertEquals($expected, $this->getLogs()); } diff --git a/tests/lib/mail/mailer.php b/tests/lib/mail/mailer.php index 7e5e689741a..21565f9ffb5 100644 --- a/tests/lib/mail/mailer.php +++ b/tests/lib/mail/mailer.php @@ -35,7 +35,7 @@ class MailerTest extends TestCase { } public function testGetMailInstance() { - $this->assertEquals(\Swift_MailTransport::newInstance(), \Test_Helper::invokePrivate($this->mailer, 'getMailinstance')); + $this->assertEquals(\Swift_MailTransport::newInstance(), self::invokePrivate($this->mailer, 'getMailinstance')); } public function testGetSendMailInstanceSendMail() { @@ -45,7 +45,7 @@ class MailerTest extends TestCase { ->with('mail_smtpmode', 'sendmail') ->will($this->returnValue('sendmail')); - $this->assertEquals(\Swift_SendmailTransport::newInstance('/usr/sbin/sendmail -bs'), \Test_Helper::invokePrivate($this->mailer, 'getSendMailInstance')); + $this->assertEquals(\Swift_SendmailTransport::newInstance('/usr/sbin/sendmail -bs'), self::invokePrivate($this->mailer, 'getSendMailInstance')); } public function testGetSendMailInstanceSendMailQmail() { @@ -55,11 +55,11 @@ class MailerTest extends TestCase { ->with('mail_smtpmode', 'sendmail') ->will($this->returnValue('qmail')); - $this->assertEquals(\Swift_SendmailTransport::newInstance('/var/qmail/bin/sendmail -bs'), \Test_Helper::invokePrivate($this->mailer, 'getSendMailInstance')); + $this->assertEquals(\Swift_SendmailTransport::newInstance('/var/qmail/bin/sendmail -bs'), self::invokePrivate($this->mailer, 'getSendMailInstance')); } public function testGetInstanceDefault() { - $this->assertInstanceOf('\Swift_MailTransport', \Test_Helper::invokePrivate($this->mailer, 'getInstance')); + $this->assertInstanceOf('\Swift_MailTransport', self::invokePrivate($this->mailer, 'getInstance')); } public function testGetInstancePhp() { @@ -68,7 +68,7 @@ class MailerTest extends TestCase { ->method('getSystemValue') ->will($this->returnValue('php')); - $this->assertInstanceOf('\Swift_MailTransport', \Test_Helper::invokePrivate($this->mailer, 'getInstance')); + $this->assertInstanceOf('\Swift_MailTransport', self::invokePrivate($this->mailer, 'getInstance')); } public function testGetInstanceSendmail() { @@ -77,7 +77,7 @@ class MailerTest extends TestCase { ->method('getSystemValue') ->will($this->returnValue('sendmail')); - $this->assertInstanceOf('\Swift_SendmailTransport', \Test_Helper::invokePrivate($this->mailer, 'getInstance')); + $this->assertInstanceOf('\Swift_SendmailTransport', self::invokePrivate($this->mailer, 'getInstance')); } public function testCreateMessage() { diff --git a/tests/lib/mail/message.php b/tests/lib/mail/message.php index c75cc18b650..8ee3c33627c 100644 --- a/tests/lib/mail/message.php +++ b/tests/lib/mail/message.php @@ -42,7 +42,7 @@ class MessageTest extends TestCase { * @dataProvider mailAddressProvider */ public function testConvertAddresses($unconverted, $expected) { - $this->assertSame($expected, \Test_Helper::invokePrivate($this->message, 'convertAddresses', array($unconverted))); + $this->assertSame($expected, self::invokePrivate($this->message, 'convertAddresses', array($unconverted))); } public function testSetFrom() { diff --git a/tests/lib/ocsclienttest.php b/tests/lib/ocsclienttest.php index f4bf1536291..ca8a2a2a2e8 100644 --- a/tests/lib/ocsclienttest.php +++ b/tests/lib/ocsclienttest.php @@ -76,7 +76,7 @@ class OCSClientTest extends \Test\TestCase { ->method('getSystemValue') ->with('appstoreurl', 'https://api.owncloud.com/v1') ->will($this->returnValue('https://api.owncloud.com/v1')); - $this->assertSame('https://api.owncloud.com/v1', Test_Helper::invokePrivate($this->ocsClient, 'getAppStoreUrl')); + $this->assertSame('https://api.owncloud.com/v1', self::invokePrivate($this->ocsClient, 'getAppStoreUrl')); } public function testGetCategoriesDisabledAppStore() { diff --git a/tests/lib/public/util.php b/tests/lib/public/util.php new file mode 100644 index 00000000000..ebc4f70079b --- /dev/null +++ b/tests/lib/public/util.php @@ -0,0 +1,47 @@ +<?php +/** + * ownCloud + * + * @author Victor Dubiniuk + * @copyright 2015 Victor Dubiniuk victor.dubiniuk@owncloud.com + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE + * License as published by the Free Software Foundation; either + * version 3 of the License, or any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU AFFERO GENERAL PUBLIC LICENSE for more details. + * + * You should have received a copy of the GNU Affero General Public + * License along with this library. If not, see <http://www.gnu.org/licenses/>. + */ + +class Test_Public_Util extends \Test\TestCase { + protected function setUp() { + parent::setUp(); + OCP\Contacts::clear(); + } + + /** + * @dataProvider channelProvider + * + * @param string $channel + */ + public function testOverrideChannel($channel) { + \OCP\Util::setChannel($channel); + $actual = \OCP\Util::getChannel($channel); + $this->assertEquals($channel, $actual); + } + + public function channelProvider() { + return [ + ['daily'], + ['beta'], + ['stable'], + ['production'] + ]; + } +} diff --git a/tests/lib/repair/cleantags.php b/tests/lib/repair/cleantags.php index 75bbbd07503..b455aa870fb 100644 --- a/tests/lib/repair/cleantags.php +++ b/tests/lib/repair/cleantags.php @@ -64,15 +64,15 @@ class CleanTags extends \Test\TestCase { $this->assertEntryCount('*PREFIX*vcategory_to_object', 4, 'Assert tag entries count before repair step'); $this->assertEntryCount('*PREFIX*vcategory', 4, 'Assert tag categories count before repair step'); - \Test_Helper::invokePrivate($this->repair, 'deleteOrphanFileEntries'); + self::invokePrivate($this->repair, 'deleteOrphanFileEntries'); $this->assertEntryCount('*PREFIX*vcategory_to_object', 3, 'Assert tag entries count after cleaning file entries'); $this->assertEntryCount('*PREFIX*vcategory', 4, 'Assert tag categories count after cleaning file entries'); - \Test_Helper::invokePrivate($this->repair, 'deleteOrphanTagEntries'); + self::invokePrivate($this->repair, 'deleteOrphanTagEntries'); $this->assertEntryCount('*PREFIX*vcategory_to_object', 2, 'Assert tag entries count after cleaning tag entries'); $this->assertEntryCount('*PREFIX*vcategory', 4, 'Assert tag categories count after cleaning tag entries'); - \Test_Helper::invokePrivate($this->repair, 'deleteOrphanCategoryEntries'); + self::invokePrivate($this->repair, 'deleteOrphanCategoryEntries'); $this->assertEntryCount('*PREFIX*vcategory_to_object', 2, 'Assert tag entries count after cleaning category entries'); $this->assertEntryCount('*PREFIX*vcategory', 2, 'Assert tag categories count after cleaning category entries'); } diff --git a/tests/lib/repair/dropoldjobs.php b/tests/lib/repair/dropoldjobs.php new file mode 100644 index 00000000000..27d7860c63d --- /dev/null +++ b/tests/lib/repair/dropoldjobs.php @@ -0,0 +1,40 @@ +<?php +/** + * Copyright (c) 2015 Arthur Schiwon <blizzz@owncloud.com> + * This file is licensed under the Affero General Public License version 3 or + * later. + * See the COPYING-README file. + */ + +namespace Test\Repair; + +use OCP\BackgroundJob\IJobList; + +/** + * Tests for the dropping old tables + * + * @see \OC\Repair\DropOldTables + */ +class DropOldJobs extends \Test\TestCase { + /** @var IJobList */ + protected $jobList; + + protected function setUp() { + parent::setUp(); + + $this->jobList = \OC::$server->getJobList(); + $this->jobList->add('OC\Cache\FileGlobalGC'); + $this->jobList->add('OC_Cache_FileGlobalGC'); + } + + public function testRun() { + $this->assertTrue($this->jobList->has('OC\Cache\FileGlobalGC', null), 'Asserting that the job OC\Cache\FileGlobalGC exists before repairing'); + $this->assertTrue($this->jobList->has('OC_Cache_FileGlobalGC', null), 'Asserting that the job OC_Cache_FileGlobalGC exists before repairing'); + + $repair = new \OC\Repair\DropOldJobs($this->jobList); + $repair->run(); + + $this->assertFalse($this->jobList->has('OC\Cache\FileGlobalGC', null), 'Asserting that the job OC\Cache\FileGlobalGC does not exist after repairing'); + $this->assertFalse($this->jobList->has('OC_Cache_FileGlobalGC', null), 'Asserting that the job OC_Cache_FileGlobalGC does not exist after repairing'); + } +} diff --git a/tests/lib/security/hasher.php b/tests/lib/security/hasher.php index 330789c67a0..a6f7df5b79f 100644 --- a/tests/lib/security/hasher.php +++ b/tests/lib/security/hasher.php @@ -11,7 +11,7 @@ use OC\Security\Hasher; /** * Class HasherTest */ -class HasherTest extends \PHPUnit_Framework_TestCase { +class HasherTest extends \Test\TestCase { /** * @return array @@ -70,14 +70,15 @@ class HasherTest extends \PHPUnit_Framework_TestCase { ); } - - /** @var Hasher */ protected $hasher; + /** @var \OCP\IConfig */ protected $config; protected function setUp() { + parent::setUp(); + $this->config = $this->getMockBuilder('\OCP\IConfig') ->disableOriginalConstructor()->getMock(); @@ -93,7 +94,7 @@ class HasherTest extends \PHPUnit_Framework_TestCase { * @dataProvider versionHashProvider */ function testSplitHash($hash, $expected) { - $relativePath = \Test_Helper::invokePrivate($this->hasher, 'splitHash', array($hash)); + $relativePath = self::invokePrivate($this->hasher, 'splitHash', array($hash)); $this->assertSame($expected, $relativePath); } diff --git a/tests/lib/setup.php b/tests/lib/setup.php index caaeec08fb3..79ca0c0be90 100644 --- a/tests/lib/setup.php +++ b/tests/lib/setup.php @@ -120,7 +120,7 @@ class Test_OC_Setup extends \Test\TestCase { * If it hasn't this test will fail. */ public function testHtaccessIsCurrent() { - $result = Test_Helper::invokePrivate( + $result = self::invokePrivate( $this->setupClass, 'isCurrentHtaccess' ); diff --git a/tests/lib/share/share.php b/tests/lib/share/share.php index 5909102f797..f03ed43e7fc 100644 --- a/tests/lib/share/share.php +++ b/tests/lib/share/share.php @@ -1051,7 +1051,7 @@ class Test_Share extends \Test\TestCase { */ function testRemoveProtocolFromUrl($url, $expectedResult) { $share = new \OC\Share\Share(); - $result = \Test_Helper::invokePrivate($share, 'removeProtocolFromUrl', array($url)); + $result = self::invokePrivate($share, 'removeProtocolFromUrl', array($url)); $this->assertSame($expectedResult, $result); } diff --git a/tests/lib/tempmanager.php b/tests/lib/tempmanager.php index 72741d0dec6..0fa025d44c8 100644 --- a/tests/lib/tempmanager.php +++ b/tests/lib/tempmanager.php @@ -154,7 +154,7 @@ class TempManager extends \Test\TestCase { public function testBuildFileNameWithPostfix() { $logger = $this->getMock('\Test\NullLogger'); - $tmpManager = \Test_Helper::invokePrivate( + $tmpManager = self::invokePrivate( $this->getManager($logger), 'buildFileNameWithSuffix', ['/tmp/myTemporaryFile', 'postfix'] @@ -165,7 +165,7 @@ class TempManager extends \Test\TestCase { public function testBuildFileNameWithoutPostfix() { $logger = $this->getMock('\Test\NullLogger'); - $tmpManager = \Test_Helper::invokePrivate( + $tmpManager = self::invokePrivate( $this->getManager($logger), 'buildFileNameWithSuffix', ['/tmp/myTemporaryFile', ''] @@ -176,7 +176,7 @@ class TempManager extends \Test\TestCase { public function testBuildFileNameWithSuffixPathTraversal() { $logger = $this->getMock('\Test\NullLogger'); - $tmpManager = \Test_Helper::invokePrivate( + $tmpManager = self::invokePrivate( $this->getManager($logger), 'buildFileNameWithSuffix', ['foo', '../Traversal\\../FileName'] diff --git a/tests/lib/testcase.php b/tests/lib/testcase.php index 76d5662da9d..8551edab71f 100644 --- a/tests/lib/testcase.php +++ b/tests/lib/testcase.php @@ -43,12 +43,45 @@ abstract class TestCase extends \PHPUnit_Framework_TestCase { protected function tearDown() { $hookExceptions = \OC_Hook::$thrownExceptions; \OC_Hook::$thrownExceptions = []; + \OC::$server->getLockingProvider()->releaseAll(); if(!empty($hookExceptions)) { throw $hookExceptions[0]; } } /** + * Allows us to test private methods/properties + * + * @param $object + * @param $methodName + * @param array $parameters + * @return mixed + */ + protected static function invokePrivate($object, $methodName, array $parameters = array()) { + $reflection = new \ReflectionClass(get_class($object)); + + if ($reflection->hasMethod($methodName)) { + $method = $reflection->getMethod($methodName); + + $method->setAccessible(true); + + return $method->invokeArgs($object, $parameters); + } elseif ($reflection->hasProperty($methodName)) { + $property = $reflection->getProperty($methodName); + + $property->setAccessible(true); + + if (!empty($parameters)) { + $property->setValue($object, array_pop($parameters)); + } + + return $property->getValue($object); + } + + return false; + } + + /** * Returns a unique identifier as uniqid() is not reliable sometimes * * @param string $prefix @@ -174,6 +207,9 @@ abstract class TestCase extends \PHPUnit_Framework_TestCase { \OC\Files\Filesystem::tearDown(); \OC_User::setUserId($user); \OC_Util::setupFS($user); + if (\OC_User::userExists($user)) { + \OC::$server->getUserFolder($user); + } } /** |