diff options
author | Bart Visscher <bartv@thisnet.nl> | 2014-05-07 17:54:38 +0200 |
---|---|---|
committer | Bart Visscher <bartv@thisnet.nl> | 2014-05-07 17:54:38 +0200 |
commit | f569c721a64486d0e7c7e307ed77ac0caed2dc2d (patch) | |
tree | df7b3399a858ffdae6bd6e66616746efbcee24bc /tests/lib | |
parent | 47d70da2f5cb55ad47023b061b68062dd8b8d8e2 (diff) | |
parent | 254fa5eb22efa5ba572702064377a6ad9eec9a53 (diff) | |
download | nextcloud-server-f569c721a64486d0e7c7e307ed77ac0caed2dc2d.tar.gz nextcloud-server-f569c721a64486d0e7c7e307ed77ac0caed2dc2d.zip |
Merge branch 'master' into optimize-startup-queries
Conflicts:
apps/files_sharing/lib/sharedstorage.php
tests/lib/group/manager.php
removed hasFilesSharedWith from lib/public/share.php and
sharedstorage.php to fix merge
Diffstat (limited to 'tests/lib')
42 files changed, 1525 insertions, 266 deletions
diff --git a/tests/lib/api.php b/tests/lib/api.php index 233beebd68a..0f7d08543ea 100644 --- a/tests/lib/api.php +++ b/tests/lib/api.php @@ -37,7 +37,7 @@ class Test_API extends PHPUnit_Framework_TestCase { function dataProviderTestOneResult() { return array( array(100, true), - array(101, true), + array(101, false), array(997, false), ); } diff --git a/tests/lib/appframework/dependencyinjection/DIContainerTest.php b/tests/lib/appframework/dependencyinjection/DIContainerTest.php index f3ebff0207f..d1bc900fb28 100644 --- a/tests/lib/appframework/dependencyinjection/DIContainerTest.php +++ b/tests/lib/appframework/dependencyinjection/DIContainerTest.php @@ -70,7 +70,7 @@ class DIContainerTest extends \PHPUnit_Framework_TestCase { public function testMiddlewareDispatcherIncludesSecurityMiddleware(){ - $this->container['Request'] = new Request(); + $this->container['Request'] = new Request(array('method' => 'GET')); $security = $this->container['SecurityMiddleware']; $dispatcher = $this->container['MiddlewareDispatcher']; diff --git a/tests/lib/appframework/http/DownloadResponseTest.php b/tests/lib/appframework/http/DownloadResponseTest.php index 64fe7992b6a..b305c63ad4d 100644 --- a/tests/lib/appframework/http/DownloadResponseTest.php +++ b/tests/lib/appframework/http/DownloadResponseTest.php @@ -22,7 +22,7 @@ */ -namespace OC\AppFramework\Http; +namespace OCP\AppFramework\Http; //require_once(__DIR__ . "/../classloader.php"); diff --git a/tests/lib/appframework/http/JSONResponseTest.php b/tests/lib/appframework/http/JSONResponseTest.php index 534c54cbcee..fbaae1b9227 100644 --- a/tests/lib/appframework/http/JSONResponseTest.php +++ b/tests/lib/appframework/http/JSONResponseTest.php @@ -28,6 +28,7 @@ namespace OC\AppFramework\Http; use OCP\AppFramework\Http\JSONResponse; +use OCP\AppFramework\Http; //require_once(__DIR__ . "/../classloader.php"); @@ -78,13 +79,6 @@ class JSONResponseTest extends \PHPUnit_Framework_TestCase { $this->assertEquals($expected, $this->json->render()); } - - public function testShouldHaveXContentHeaderByDefault() { - $headers = $this->json->getHeaders(); - $this->assertEquals('nosniff', $headers['X-Content-Type-Options']); - } - - public function testConstructorAllowsToSetData() { $data = array('hi'); $code = 300; @@ -95,4 +89,13 @@ class JSONResponseTest extends \PHPUnit_Framework_TestCase { $this->assertEquals($code, $response->getStatus()); } + public function testChainability() { + $params = array('hi', 'yo'); + $this->json->setData($params) + ->setStatus(Http::STATUS_NOT_FOUND); + + $this->assertEquals(Http::STATUS_NOT_FOUND, $this->json->getStatus()); + $this->assertEquals(array('hi', 'yo'), $this->json->getData()); + } + } diff --git a/tests/lib/appframework/http/RedirectResponseTest.php b/tests/lib/appframework/http/RedirectResponseTest.php index f82d0c3a675..f62b420f4ee 100644 --- a/tests/lib/appframework/http/RedirectResponseTest.php +++ b/tests/lib/appframework/http/RedirectResponseTest.php @@ -22,7 +22,7 @@ */ -namespace OC\AppFramework\Http; +namespace OCP\AppFramework\Http; use OCP\AppFramework\Http; diff --git a/tests/lib/appframework/http/RequestTest.php b/tests/lib/appframework/http/RequestTest.php index 00473a8c44f..58828d17bb2 100644 --- a/tests/lib/appframework/http/RequestTest.php +++ b/tests/lib/appframework/http/RequestTest.php @@ -18,6 +18,7 @@ class RequestTest extends \PHPUnit_Framework_TestCase { stream_wrapper_unregister('fakeinput'); } stream_wrapper_register('fakeinput', 'RequestStream'); + $this->stream = 'fakeinput://data'; } public function tearDown() { @@ -30,7 +31,7 @@ class RequestTest extends \PHPUnit_Framework_TestCase { 'method' => 'GET', ); - $request = new Request($vars); + $request = new Request($vars, $this->stream); // Countable $this->assertEquals(2, count($request)); @@ -54,9 +55,10 @@ class RequestTest extends \PHPUnit_Framework_TestCase { 'get' => array('name' => 'John Q. Public', 'nickname' => 'Joey'), 'post' => array('name' => 'Jane Doe', 'nickname' => 'Janey'), 'urlParams' => array('user' => 'jw', 'name' => 'Johnny Weissmüller'), + 'method' => 'GET' ); - $request = new Request($vars); + $request = new Request($vars, $this->stream); $this->assertEquals(3, count($request)); $this->assertEquals('Janey', $request->{'nickname'}); @@ -70,9 +72,10 @@ class RequestTest extends \PHPUnit_Framework_TestCase { public function testImmutableArrayAccess() { $vars = array( 'get' => array('name' => 'John Q. Public', 'nickname' => 'Joey'), + 'method' => 'GET' ); - $request = new Request($vars); + $request = new Request($vars, $this->stream); $request['nickname'] = 'Janey'; } @@ -82,9 +85,10 @@ class RequestTest extends \PHPUnit_Framework_TestCase { public function testImmutableMagicAccess() { $vars = array( 'get' => array('name' => 'John Q. Public', 'nickname' => 'Joey'), + 'method' => 'GET' ); - $request = new Request($vars); + $request = new Request($vars, $this->stream); $request->{'nickname'} = 'Janey'; } @@ -97,7 +101,7 @@ class RequestTest extends \PHPUnit_Framework_TestCase { 'method' => 'GET', ); - $request = new Request($vars); + $request = new Request($vars, $this->stream); $result = $request->post; } @@ -107,7 +111,7 @@ class RequestTest extends \PHPUnit_Framework_TestCase { 'method' => 'GET', ); - $request = new Request($vars); + $request = new Request($vars, $this->stream); $this->assertEquals('GET', $request->method); $result = $request->get; $this->assertEquals('John Q. Public', $result['name']); @@ -119,10 +123,10 @@ class RequestTest extends \PHPUnit_Framework_TestCase { $data = '{"name": "John Q. Public", "nickname": "Joey"}'; $vars = array( 'method' => 'POST', - 'server' => array('CONTENT_TYPE' => 'application/json; utf-8'), + 'server' => array('CONTENT_TYPE' => 'application/json; utf-8') ); - $request = new Request($vars); + $request = new Request($vars, $this->stream); $this->assertEquals('POST', $request->method); $result = $request->post; $this->assertEquals('John Q. Public', $result['name']); @@ -140,7 +144,7 @@ class RequestTest extends \PHPUnit_Framework_TestCase { 'server' => array('CONTENT_TYPE' => 'application/x-www-form-urlencoded'), ); - $request = new Request($vars); + $request = new Request($vars, $this->stream); $this->assertEquals('PATCH', $request->method); $result = $request->patch; @@ -159,7 +163,7 @@ class RequestTest extends \PHPUnit_Framework_TestCase { 'server' => array('CONTENT_TYPE' => 'application/json; utf-8'), ); - $request = new Request($vars); + $request = new Request($vars, $this->stream); $this->assertEquals('PUT', $request->method); $result = $request->put; @@ -174,7 +178,7 @@ class RequestTest extends \PHPUnit_Framework_TestCase { 'server' => array('CONTENT_TYPE' => 'application/json; utf-8'), ); - $request = new Request($vars); + $request = new Request($vars, $this->stream); $this->assertEquals('PATCH', $request->method); $result = $request->patch; @@ -193,7 +197,7 @@ class RequestTest extends \PHPUnit_Framework_TestCase { 'server' => array('CONTENT_TYPE' => 'image/png'), ); - $request = new Request($vars); + $request = new Request($vars, $this->stream); $this->assertEquals('PUT', $request->method); $resource = $request->put; $contents = stream_get_contents($resource); diff --git a/tests/lib/appframework/http/ResponseTest.php b/tests/lib/appframework/http/ResponseTest.php index 4f21d77a170..27350725d79 100644 --- a/tests/lib/appframework/http/ResponseTest.php +++ b/tests/lib/appframework/http/ResponseTest.php @@ -78,7 +78,7 @@ class ResponseTest extends \PHPUnit_Framework_TestCase { public function testGetEtag() { $this->childResponse->setEtag('hi'); - $this->assertEquals('hi', $this->childResponse->getEtag()); + $this->assertSame('hi', $this->childResponse->getEtag()); } @@ -117,5 +117,25 @@ class ResponseTest extends \PHPUnit_Framework_TestCase { $this->assertEquals('Thu, 01 Jan 1970 00:00:01 +0000', $headers['Last-Modified']); } + public function testChainability() { + $lastModified = new \DateTime(null, new \DateTimeZone('GMT')); + $lastModified->setTimestamp(1); + + $this->childResponse->setEtag('hi') + ->setStatus(Http::STATUS_NOT_FOUND) + ->setLastModified($lastModified) + ->cacheFor(33) + ->addHeader('hello', 'world'); + + $headers = $this->childResponse->getHeaders(); + + $this->assertEquals('world', $headers['hello']); + $this->assertEquals(Http::STATUS_NOT_FOUND, $this->childResponse->getStatus()); + $this->assertEquals('hi', $this->childResponse->getEtag()); + $this->assertEquals('Thu, 01 Jan 1970 00:00:01 +0000', $headers['Last-Modified']); + $this->assertEquals('max-age=33, must-revalidate', + $headers['Cache-Control']); + + } } diff --git a/tests/lib/appframework/http/TemplateResponseTest.php b/tests/lib/appframework/http/TemplateResponseTest.php index a583d9da14f..0b158edff6f 100644 --- a/tests/lib/appframework/http/TemplateResponseTest.php +++ b/tests/lib/appframework/http/TemplateResponseTest.php @@ -25,6 +25,7 @@ namespace OC\AppFramework\Http; use OCP\AppFramework\Http\TemplateResponse; +use OCP\AppFramework\Http; class TemplateResponseTest extends \PHPUnit_Framework_TestCase { @@ -98,4 +99,13 @@ class TemplateResponseTest extends \PHPUnit_Framework_TestCase { $this->assertEquals($render, $this->tpl->getRenderAs()); } + public function testChainability() { + $params = array('hi' => 'yo'); + $this->tpl->setParams($params) + ->setStatus(Http::STATUS_NOT_FOUND); + + $this->assertEquals(Http::STATUS_NOT_FOUND, $this->tpl->getStatus()); + $this->assertEquals(array('hi' => 'yo'), $this->tpl->getParams()); + } + } diff --git a/tests/lib/appframework/middleware/MiddlewareDispatcherTest.php b/tests/lib/appframework/middleware/MiddlewareDispatcherTest.php index f16b14150c3..935f97d2a6f 100644 --- a/tests/lib/appframework/middleware/MiddlewareDispatcherTest.php +++ b/tests/lib/appframework/middleware/MiddlewareDispatcherTest.php @@ -132,7 +132,7 @@ class MiddlewareDispatcherTest extends \PHPUnit_Framework_TestCase { private function getControllerMock(){ return $this->getMock('OCP\AppFramework\Controller', array('method'), - array($this->getAPIMock(), new Request())); + array($this->getAPIMock(), new Request(array('method' => 'GET')))); } diff --git a/tests/lib/appframework/middleware/security/SecurityMiddlewareTest.php b/tests/lib/appframework/middleware/security/SecurityMiddlewareTest.php index 63c48a62829..19e8a68c388 100644 --- a/tests/lib/appframework/middleware/security/SecurityMiddlewareTest.php +++ b/tests/lib/appframework/middleware/security/SecurityMiddlewareTest.php @@ -26,7 +26,7 @@ namespace OC\AppFramework\Middleware\Security; use OC\AppFramework\Http; use OC\AppFramework\Http\Request; -use OC\AppFramework\Http\RedirectResponse; +use OCP\AppFramework\Http\RedirectResponse; use OCP\AppFramework\Http\JSONResponse; diff --git a/tests/lib/appframework/routing/RoutingTest.php b/tests/lib/appframework/routing/RoutingTest.php index d0244cf2511..261ab0b26af 100644 --- a/tests/lib/appframework/routing/RoutingTest.php +++ b/tests/lib/appframework/routing/RoutingTest.php @@ -36,6 +36,16 @@ class RouteConfigTest extends \PHPUnit_Framework_TestCase $this->assertSimpleRoute($routes, 'folders.open', 'DELETE', '/folders/{folderId}/open', 'FoldersController', 'open'); } + public function testSimpleRouteWithRequirements() + { + $routes = array('routes' => array( + array('name' => 'folders#open', 'url' => '/folders/{folderId}/open', 'verb' => 'delete', 'requirements' => array('something')) + )); + + $this->assertSimpleRoute($routes, 'folders.open', 'DELETE', '/folders/{folderId}/open', 'FoldersController', 'open', array('something')); + } + + /** * @expectedException \UnexpectedValueException */ @@ -46,7 +56,7 @@ class RouteConfigTest extends \PHPUnit_Framework_TestCase )); // router mock - $router = $this->getMock("\OC_Router", array('create')); + $router = $this->getMock("\OC\Route\Router", array('create')); // load route configuration $container = new DIContainer('app1'); @@ -85,13 +95,13 @@ class RouteConfigTest extends \PHPUnit_Framework_TestCase * @param string $controllerName * @param string $actionName */ - private function assertSimpleRoute($routes, $name, $verb, $url, $controllerName, $actionName) + private function assertSimpleRoute($routes, $name, $verb, $url, $controllerName, $actionName, array $requirements=array()) { // route mocks - $route = $this->mockRoute($verb, $controllerName, $actionName); + $route = $this->mockRoute($verb, $controllerName, $actionName, $requirements); // router mock - $router = $this->getMock("\OC_Router", array('create')); + $router = $this->getMock("\OC\Route\Router", array('create')); // we expect create to be called once: $router @@ -116,7 +126,7 @@ class RouteConfigTest extends \PHPUnit_Framework_TestCase private function assertResource($yaml, $resourceName, $url, $controllerName, $paramName) { // router mock - $router = $this->getMock("\OC_Router", array('create')); + $router = $this->getMock("\OC\Route\Router", array('create')); // route mocks $indexRoute = $this->mockRoute('GET', $controllerName, 'index'); @@ -166,15 +176,15 @@ class RouteConfigTest extends \PHPUnit_Framework_TestCase } /** - * @param $verb - * @param $controllerName - * @param $actionName + * @param string $verb + * @param string $controllerName + * @param string $actionName * @return \PHPUnit_Framework_MockObject_MockObject */ - private function mockRoute($verb, $controllerName, $actionName) + private function mockRoute($verb, $controllerName, $actionName, array $requirements=array()) { $container = new DIContainer('app1'); - $route = $this->getMock("\OC_Route", array('method', 'action'), array(), '', false); + $route = $this->getMock("\OC\Route\Route", array('method', 'action', 'requirements'), array(), '', false); $route ->expects($this->exactly(1)) ->method('method') @@ -186,6 +196,14 @@ class RouteConfigTest extends \PHPUnit_Framework_TestCase ->method('action') ->with($this->equalTo(new RouteActionHandler($container, $controllerName, $actionName))) ->will($this->returnValue($route)); + + if(count($requirements) > 0) { + $route + ->expects($this->exactly(1)) + ->method('requirements') + ->with($this->equalTo($requirements)) + ->will($this->returnValue($route)); + } return $route; } diff --git a/tests/lib/connector/sabre/aborteduploaddetectionplugin.php b/tests/lib/connector/sabre/aborteduploaddetectionplugin.php index 201f1263867..60d141e72bc 100644 --- a/tests/lib/connector/sabre/aborteduploaddetectionplugin.php +++ b/tests/lib/connector/sabre/aborteduploaddetectionplugin.php @@ -1,11 +1,11 @@ <?php + /** * Copyright (c) 2013 Thomas Müller <thomas.mueller@tmit.eu> * This file is licensed under the Affero General Public License version 3 or * later. * See the COPYING-README file. */ - class Test_OC_Connector_Sabre_AbortedUploadDetectionPlugin extends PHPUnit_Framework_TestCase { /** @@ -18,17 +18,18 @@ class Test_OC_Connector_Sabre_AbortedUploadDetectionPlugin extends PHPUnit_Frame */ private $plugin; - public function setUp() { + private function init($view) { $this->server = new Sabre_DAV_Server(); - $this->plugin = new OC_Connector_Sabre_AbortedUploadDetectionPlugin(); + $this->plugin = new OC_Connector_Sabre_AbortedUploadDetectionPlugin($view); $this->plugin->initialize($this->server); } /** * @dataProvider lengthProvider */ - public function testLength($expected, $headers) - { + public function testLength($expected, $headers) { + $this->init(null); + $this->server->httpRequest = new Sabre_HTTP_Request($headers); $length = $this->plugin->getLength(); $this->assertEquals($expected, $length); @@ -37,9 +38,8 @@ class Test_OC_Connector_Sabre_AbortedUploadDetectionPlugin extends PHPUnit_Frame /** * @dataProvider verifyContentLengthProvider */ - public function testVerifyContentLength($method, $fileSize, $headers) - { - $this->plugin->fileView = $this->buildFileViewMock($fileSize); + public function testVerifyContentLength($method, $fileSize, $headers) { + $this->init($this->buildFileViewMock($fileSize)); $headers['REQUEST_METHOD'] = $method; $this->server->httpRequest = new Sabre_HTTP_Request($headers); @@ -51,12 +51,11 @@ class Test_OC_Connector_Sabre_AbortedUploadDetectionPlugin extends PHPUnit_Frame * @dataProvider verifyContentLengthFailedProvider * @expectedException Sabre_DAV_Exception_BadRequest */ - public function testVerifyContentLengthFailed($method, $fileSize, $headers) - { - $this->plugin->fileView = $this->buildFileViewMock($fileSize); - + public function testVerifyContentLengthFailed($method, $fileSize, $headers) { + $view = $this->buildFileViewMock($fileSize); + $this->init($view); // we expect unlink to be called - $this->plugin->fileView->expects($this->once())->method('unlink'); + $view->expects($this->once())->method('unlink'); $headers['REQUEST_METHOD'] = $method; $this->server->httpRequest = new Sabre_HTTP_Request($headers); @@ -92,7 +91,7 @@ class Test_OC_Connector_Sabre_AbortedUploadDetectionPlugin extends PHPUnit_Frame private function buildFileViewMock($fileSize) { // mock filesystem - $view = $this->getMock('\OC\Files\View', array('filesize', 'unlink'), array(), '', FALSE); + $view = $this->getMock('\OC\Files\View', array('filesize', 'unlink'), array(), '', false); $view->expects($this->any())->method('filesize')->withAnyParameters()->will($this->returnValue($fileSize)); return $view; diff --git a/tests/lib/connector/sabre/directory.php b/tests/lib/connector/sabre/directory.php index c501521b601..b2bf0d4a6d2 100644 --- a/tests/lib/connector/sabre/directory.php +++ b/tests/lib/connector/sabre/directory.php @@ -1,18 +1,32 @@ <?php + /** * Copyright (c) 2013 Thomas Müller <thomas.mueller@tmit.eu> * This file is licensed under the Affero General Public License version 3 or * later. * See the COPYING-README file. */ - class Test_OC_Connector_Sabre_Directory extends PHPUnit_Framework_TestCase { + private function getRootDir() { + $view = $this->getMock('OC\Files\View', array(), array(), '', false); + $view->expects($this->once()) + ->method('getRelativePath') + ->will($this->returnValue('')); + + $info = $this->getMock('OC\Files\FileInfo', array(), array(), '', false); + $info->expects($this->once()) + ->method('getPath') + ->will($this->returnValue('')); + + return new OC_Connector_Sabre_Directory($view, $info); + } + /** * @expectedException Sabre_DAV_Exception_Forbidden */ public function testCreateSharedFileFails() { - $dir = new OC_Connector_Sabre_Directory(''); + $dir = $this->getRootDir(); $dir->createFile('Shared'); } @@ -20,7 +34,7 @@ class Test_OC_Connector_Sabre_Directory extends PHPUnit_Framework_TestCase { * @expectedException Sabre_DAV_Exception_Forbidden */ public function testCreateSharedFolderFails() { - $dir = new OC_Connector_Sabre_Directory(''); + $dir = $this->getRootDir(); $dir->createDirectory('Shared'); } @@ -28,7 +42,7 @@ class Test_OC_Connector_Sabre_Directory extends PHPUnit_Framework_TestCase { * @expectedException Sabre_DAV_Exception_Forbidden */ public function testDeleteSharedFolderFails() { - $dir = new OC_Connector_Sabre_Directory('Shared'); + $dir = $this->getRootDir(); $dir->delete(); } } diff --git a/tests/lib/connector/sabre/file.php b/tests/lib/connector/sabre/file.php index c2f0ffa12d4..a9056460a5c 100644 --- a/tests/lib/connector/sabre/file.php +++ b/tests/lib/connector/sabre/file.php @@ -13,9 +13,20 @@ class Test_OC_Connector_Sabre_File extends PHPUnit_Framework_TestCase { */ public function testSimplePutFails() { // setup - $file = new OC_Connector_Sabre_File('/test.txt'); - $file->fileView = $this->getMock('\OC\Files\View', array('file_put_contents'), array(), '', FALSE); - $file->fileView->expects($this->any())->method('file_put_contents')->withAnyParameters()->will($this->returnValue(false)); + $view = $this->getMock('\OC\Files\View', array('file_put_contents', 'getRelativePath'), array(), '', false); + $view->expects($this->any()) + ->method('file_put_contents') + ->will($this->returnValue(false)); + + $view->expects($this->any()) + ->method('getRelativePath') + ->will($this->returnValue('/test.txt')); + + $info = new \OC\Files\FileInfo('/test.txt', null, null, array( + 'permissions'=>\OCP\PERMISSION_ALL + )); + + $file = new OC_Connector_Sabre_File($view, $info); // action $etag = $file->put('test data'); @@ -26,10 +37,25 @@ class Test_OC_Connector_Sabre_File extends PHPUnit_Framework_TestCase { */ public function testSimplePutFailsOnRename() { // setup - $file = new OC_Connector_Sabre_File('/test.txt'); - $file->fileView = $this->getMock('\OC\Files\View', array('file_put_contents', 'rename'), array(), '', FALSE); - $file->fileView->expects($this->any())->method('file_put_contents')->withAnyParameters()->will($this->returnValue(true)); - $file->fileView->expects($this->any())->method('rename')->withAnyParameters()->will($this->returnValue(false)); + $view = $this->getMock('\OC\Files\View', array('file_put_contents', 'rename', 'getRelativePath'), array(), '', false); + $view->expects($this->any()) + ->method('file_put_contents') + ->withAnyParameters() + ->will($this->returnValue(true)); + $view->expects($this->any()) + ->method('rename') + ->withAnyParameters() + ->will($this->returnValue(false)); + + $view->expects($this->any()) + ->method('getRelativePath') + ->will($this->returnValue('/test.txt')); + + $info = new \OC\Files\FileInfo('/test.txt', null, null, array( + 'permissions' => \OCP\PERMISSION_ALL + )); + + $file = new OC_Connector_Sabre_File($view, $info); // action $etag = $file->put('test data'); @@ -40,9 +66,19 @@ class Test_OC_Connector_Sabre_File extends PHPUnit_Framework_TestCase { */ public function testSimplePutInvalidChars() { // setup - $file = new OC_Connector_Sabre_File('/super*star.txt'); - $file->fileView = $this->getMock('\OC\Files\View', array('file_put_contents'), array(), '', FALSE); - $file->fileView->expects($this->any())->method('file_put_contents')->withAnyParameters()->will($this->returnValue(false)); + $view = $this->getMock('\OC\Files\View', array('file_put_contents', 'getRelativePath'), array(), '', false); + $view->expects($this->any()) + ->method('file_put_contents') + ->will($this->returnValue(false)); + + $view->expects($this->any()) + ->method('getRelativePath') + ->will($this->returnValue('/super*star.txt')); + + $info = new \OC\Files\FileInfo('/super*star.txt', null, null, array( + 'permissions' => \OCP\PERMISSION_ALL + )); + $file = new OC_Connector_Sabre_File($view, $info); // action $etag = $file->put('test data'); @@ -54,17 +90,16 @@ class Test_OC_Connector_Sabre_File extends PHPUnit_Framework_TestCase { */ public function testSetNameInvalidChars() { // setup - $file = new OC_Connector_Sabre_File('/test.txt'); - $file->fileView = $this->getMock('\OC\Files\View', array('isUpdatable'), array(), '', FALSE); - $file->fileView->expects($this->any())->method('isUpdatable')->withAnyParameters()->will($this->returnValue(true)); - $file->setName('/super*star.txt'); - } + $view = $this->getMock('\OC\Files\View', array('getRelativePath'), array(), '', false); - /** - * @expectedException Sabre_DAV_Exception_Forbidden - */ - public function testDeleteSharedFails() { - $file = new OC_Connector_Sabre_File('Shared'); - $file->delete(); + $view->expects($this->any()) + ->method('getRelativePath') + ->will($this->returnValue('/super*star.txt')); + + $info = new \OC\Files\FileInfo('/super*star.txt', null, null, array( + 'permissions' => \OCP\PERMISSION_ALL + )); + $file = new OC_Connector_Sabre_File($view, $info); + $file->setName('/super*star.txt'); } } diff --git a/tests/lib/connector/sabre/objecttree.php b/tests/lib/connector/sabre/objecttree.php index fb50c736edd..bc8ec98faee 100644 --- a/tests/lib/connector/sabre/objecttree.php +++ b/tests/lib/connector/sabre/objecttree.php @@ -9,6 +9,7 @@ namespace Test\OC\Connector\Sabre; +use OC\Files\FileInfo; use OC_Connector_Sabre_Directory; use PHPUnit_Framework_TestCase; use Sabre_DAV_Exception_Forbidden; @@ -32,6 +33,10 @@ class TestDoubleFileView extends \OC\Files\View{ public function rename($path1, $path2) { return $this->canRename; } + + public function getRelativePath($path){ + return $path; + } } class ObjectTree extends PHPUnit_Framework_TestCase { @@ -91,10 +96,14 @@ class ObjectTree extends PHPUnit_Framework_TestCase { * @param $updatables */ private function moveTest($source, $dest, $updatables, $deletables) { - $rootDir = new OC_Connector_Sabre_Directory(''); + $view = new TestDoubleFileView($updatables, $deletables); + + $info = new FileInfo('', null, null, array()); + + $rootDir = new OC_Connector_Sabre_Directory($view, $info); $objectTree = $this->getMock('\OC\Connector\Sabre\ObjectTree', array('nodeExists', 'getNodeForPath'), - array($rootDir)); + array($rootDir, $view)); $objectTree->expects($this->once()) ->method('getNodeForPath') @@ -102,7 +111,7 @@ class ObjectTree extends PHPUnit_Framework_TestCase { ->will($this->returnValue(false)); /** @var $objectTree \OC\Connector\Sabre\ObjectTree */ - $objectTree->fileView = new TestDoubleFileView($updatables, $deletables); + $objectTree->init($rootDir, $view); $objectTree->move($source, $dest); } diff --git a/tests/lib/connector/sabre/quotaplugin.php b/tests/lib/connector/sabre/quotaplugin.php index 1186de28742..6781b970a4f 100644 --- a/tests/lib/connector/sabre/quotaplugin.php +++ b/tests/lib/connector/sabre/quotaplugin.php @@ -1,11 +1,11 @@ <?php + /** * Copyright (c) 2013 Thomas Müller <thomas.mueller@tmit.eu> * This file is licensed under the Affero General Public License version 3 or * later. * See the COPYING-README file. */ - class Test_OC_Connector_Sabre_QuotaPlugin extends PHPUnit_Framework_TestCase { /** @@ -18,17 +18,18 @@ class Test_OC_Connector_Sabre_QuotaPlugin extends PHPUnit_Framework_TestCase { */ private $plugin; - public function setUp() { + private function init($quota) { + $view = $this->buildFileViewMock($quota); $this->server = new Sabre_DAV_Server(); - $this->plugin = new OC_Connector_Sabre_QuotaPlugin(); + $this->plugin = new OC_Connector_Sabre_QuotaPlugin($view); $this->plugin->initialize($this->server); } /** * @dataProvider lengthProvider */ - public function testLength($expected, $headers) - { + public function testLength($expected, $headers) { + $this->init(0); $this->server->httpRequest = new Sabre_HTTP_Request($headers); $length = $this->plugin->getLength(); $this->assertEquals($expected, $length); @@ -37,9 +38,8 @@ class Test_OC_Connector_Sabre_QuotaPlugin extends PHPUnit_Framework_TestCase { /** * @dataProvider quotaOkayProvider */ - public function testCheckQuota($quota, $headers) - { - $this->plugin->fileView = $this->buildFileViewMock($quota); + public function testCheckQuota($quota, $headers) { + $this->init($quota); $this->server->httpRequest = new Sabre_HTTP_Request($headers); $result = $this->plugin->checkQuota(''); @@ -50,9 +50,8 @@ class Test_OC_Connector_Sabre_QuotaPlugin extends PHPUnit_Framework_TestCase { * @expectedException Sabre_DAV_Exception_InsufficientStorage * @dataProvider quotaExceededProvider */ - public function testCheckExceededQuota($quota, $headers) - { - $this->plugin->fileView = $this->buildFileViewMock($quota); + public function testCheckExceededQuota($quota, $headers) { + $this->init($quota); $this->server->httpRequest = new Sabre_HTTP_Request($headers); $this->plugin->checkQuota(''); @@ -92,7 +91,7 @@ class Test_OC_Connector_Sabre_QuotaPlugin extends PHPUnit_Framework_TestCase { private function buildFileViewMock($quota) { // mock filesysten - $view = $this->getMock('\OC\Files\View', array('free_space'), array(), '', FALSE); + $view = $this->getMock('\OC\Files\View', array('free_space'), array(), '', false); $view->expects($this->any())->method('free_space')->withAnyParameters()->will($this->returnValue($quota)); return $view; diff --git a/tests/lib/dbschema.php b/tests/lib/dbschema.php index 11e9fcdf4fa..cfa2d6fd9aa 100644 --- a/tests/lib/dbschema.php +++ b/tests/lib/dbschema.php @@ -71,6 +71,9 @@ class Test_DBSchema extends PHPUnit_Framework_TestCase { $this->assertTableNotExist($this->table2); } + /** + * @param string $table + */ public function tableExist($table) { switch (OC_Config::getValue( 'dbtype', 'sqlite' )) { diff --git a/tests/lib/files/cache/homecache.php b/tests/lib/files/cache/homecache.php index dbcf6e9caa0..80dc54c9d19 100644 --- a/tests/lib/files/cache/homecache.php +++ b/tests/lib/files/cache/homecache.php @@ -90,7 +90,6 @@ class HomeCache extends \PHPUnit_Framework_TestCase { // check that files and root size ignored the unknown sizes $this->assertEquals(1000, $this->cache->calculateFolderSize('files')); - $this->assertEquals(1000, $this->cache->calculateFolderSize('')); // clean up $this->cache->remove(''); diff --git a/tests/lib/files/cache/scanner.php b/tests/lib/files/cache/scanner.php index 3f5604b4d45..5182fac8b10 100644 --- a/tests/lib/files/cache/scanner.php +++ b/tests/lib/files/cache/scanner.php @@ -150,13 +150,15 @@ class Scanner extends \PHPUnit_Framework_TestCase { $this->cache->put('folder', array('mtime' => $this->storage->filemtime('folder'), 'storage_mtime' => $this->storage->filemtime('folder'))); $this->scanner->scan('', \OC\Files\Cache\Scanner::SCAN_SHALLOW, \OC\Files\Cache\Scanner::REUSE_SIZE); $newData = $this->cache->get(''); - $this->assertNotEquals($oldData['etag'], $newData['etag']); + $this->assertInternalType('string', $oldData['etag']); + $this->assertInternalType('string', $newData['etag']); + $this->assertNotSame($oldData['etag'], $newData['etag']); $this->assertEquals($oldData['size'], $newData['size']); $oldData = $newData; $this->scanner->scan('', \OC\Files\Cache\Scanner::SCAN_SHALLOW, \OC\Files\Cache\Scanner::REUSE_ETAG); $newData = $this->cache->get(''); - $this->assertEquals($oldData['etag'], $newData['etag']); + $this->assertSame($oldData['etag'], $newData['etag']); $this->assertEquals(-1, $newData['size']); $this->scanner->scan('', \OC\Files\Cache\Scanner::SCAN_RECURSIVE); @@ -164,17 +166,17 @@ class Scanner extends \PHPUnit_Framework_TestCase { $this->assertNotEquals(-1, $oldData['size']); $this->scanner->scanFile('', \OC\Files\Cache\Scanner::REUSE_ETAG + \OC\Files\Cache\Scanner::REUSE_SIZE); $newData = $this->cache->get(''); - $this->assertEquals($oldData['etag'], $newData['etag']); + $this->assertSame($oldData['etag'], $newData['etag']); $this->assertEquals($oldData['size'], $newData['size']); $this->scanner->scan('', \OC\Files\Cache\Scanner::SCAN_RECURSIVE, \OC\Files\Cache\Scanner::REUSE_ETAG + \OC\Files\Cache\Scanner::REUSE_SIZE); $newData = $this->cache->get(''); - $this->assertEquals($oldData['etag'], $newData['etag']); + $this->assertSame($oldData['etag'], $newData['etag']); $this->assertEquals($oldData['size'], $newData['size']); $this->scanner->scan('', \OC\Files\Cache\Scanner::SCAN_SHALLOW, \OC\Files\Cache\Scanner::REUSE_ETAG + \OC\Files\Cache\Scanner::REUSE_SIZE); $newData = $this->cache->get(''); - $this->assertEquals($oldData['etag'], $newData['etag']); + $this->assertSame($oldData['etag'], $newData['etag']); $this->assertEquals($oldData['size'], $newData['size']); } @@ -217,8 +219,11 @@ class Scanner extends \PHPUnit_Framework_TestCase { // manipulate etag to simulate an empty etag $this->scanner->scan('', \OC\Files\Cache\Scanner::SCAN_SHALLOW, \OC\Files\Cache\Scanner::REUSE_ETAG); $data0 = $this->cache->get('folder/bar.txt'); + $this->assertInternalType('string', $data0['etag']); $data1 = $this->cache->get('folder'); + $this->assertInternalType('string', $data1['etag']); $data2 = $this->cache->get(''); + $this->assertInternalType('string', $data2['etag']); $data0['etag'] = ''; $this->cache->put('folder/bar.txt', $data0); @@ -227,10 +232,15 @@ class Scanner extends \PHPUnit_Framework_TestCase { // verify cache content $newData0 = $this->cache->get('folder/bar.txt'); + $this->assertInternalType('string', $newData0['etag']); + $this->assertNotEmpty($newData0['etag']); + $newData1 = $this->cache->get('folder'); + $this->assertInternalType('string', $newData1['etag']); + $this->assertNotSame($data1['etag'], $newData1['etag']); + $newData2 = $this->cache->get(''); - $this->assertNotEmpty($newData0['etag']); - $this->assertNotEquals($data1['etag'], $newData1['etag']); - $this->assertNotEquals($data2['etag'], $newData2['etag']); + $this->assertInternalType('string', $newData2['etag']); + $this->assertNotSame($data2['etag'], $newData2['etag']); } } diff --git a/tests/lib/files/cache/updater.php b/tests/lib/files/cache/updater.php index 48986149a73..e2fae0ae57f 100644 --- a/tests/lib/files/cache/updater.php +++ b/tests/lib/files/cache/updater.php @@ -65,11 +65,6 @@ class Updater extends \PHPUnit_Framework_TestCase { Filesystem::mount($this->storage, array(), '/' . self::$user . '/files'); \OC_Hook::clear('OC_Filesystem'); - - \OC_Hook::connect('OC_Filesystem', 'post_write', '\OC\Files\Cache\Updater', 'writeHook'); - \OC_Hook::connect('OC_Filesystem', 'post_delete', '\OC\Files\Cache\Updater', 'deleteHook'); - \OC_Hook::connect('OC_Filesystem', 'post_rename', '\OC\Files\Cache\Updater', 'renameHook'); - \OC_Hook::connect('OC_Filesystem', 'post_touch', '\OC\Files\Cache\Updater', 'touchHook'); } public function tearDown() { @@ -96,10 +91,14 @@ class Updater extends \PHPUnit_Framework_TestCase { Filesystem::file_put_contents('foo.txt', 'asd'); $cachedData = $this->cache->get('foo.txt'); $this->assertEquals(3, $cachedData['size']); - $this->assertNotEquals($fooCachedData['etag'], $cachedData['etag']); + $this->assertInternalType('string', $fooCachedData['etag']); + $this->assertInternalType('string', $cachedData['etag']); + $this->assertNotSame($fooCachedData['etag'], $cachedData['etag']); $cachedData = $this->cache->get(''); $this->assertEquals(2 * $textSize + $imageSize + 3, $cachedData['size']); - $this->assertNotEquals($rootCachedData['etag'], $cachedData['etag']); + $this->assertInternalType('string', $rootCachedData['etag']); + $this->assertInternalType('string', $cachedData['etag']); + $this->assertNotSame($rootCachedData['etag'], $cachedData['etag']); $rootCachedData = $cachedData; $this->assertFalse($this->cache->inCache('bar.txt')); @@ -110,12 +109,15 @@ class Updater extends \PHPUnit_Framework_TestCase { $mtime = $cachedData['mtime']; $cachedData = $this->cache->get(''); $this->assertEquals(2 * $textSize + $imageSize + 2 * 3, $cachedData['size']); - $this->assertNotEquals($rootCachedData['etag'], $cachedData['etag']); + $this->assertInternalType('string', $rootCachedData['etag']); + $this->assertInternalType('string', $cachedData['etag']); + $this->assertNotSame($rootCachedData['etag'], $cachedData['etag']); $this->assertGreaterThanOrEqual($rootCachedData['mtime'], $mtime); } public function testWriteWithMountPoints() { $storage2 = new \OC\Files\Storage\Temporary(array()); + $storage2->getScanner()->scan(''); //initialize etags $cache2 = $storage2->getCache(); Filesystem::mount($storage2, array(), '/' . self::$user . '/files/folder/substorage'); $folderCachedData = $this->cache->get('folder'); @@ -127,11 +129,15 @@ class Updater extends \PHPUnit_Framework_TestCase { $mtime = $cachedData['mtime']; $cachedData = $cache2->get(''); - $this->assertNotEquals($substorageCachedData['etag'], $cachedData['etag']); + $this->assertInternalType('string', $substorageCachedData['etag']); + $this->assertInternalType('string', $cachedData['etag']); + $this->assertNotSame($substorageCachedData['etag'], $cachedData['etag']); $this->assertEquals($mtime, $cachedData['mtime']); $cachedData = $this->cache->get('folder'); - $this->assertNotEquals($folderCachedData['etag'], $cachedData['etag']); + $this->assertInternalType('string', $folderCachedData['etag']); + $this->assertInternalType('string', $cachedData['etag']); + $this->assertNotSame($folderCachedData['etag'], $cachedData['etag']); $this->assertEquals($mtime, $cachedData['mtime']); } @@ -146,19 +152,25 @@ class Updater extends \PHPUnit_Framework_TestCase { $this->assertFalse($this->cache->inCache('foo.txt')); $cachedData = $this->cache->get(''); $this->assertEquals(2 * $textSize + $imageSize, $cachedData['size']); - $this->assertNotEquals($rootCachedData['etag'], $cachedData['etag']); + $this->assertInternalType('string', $rootCachedData['etag']); + $this->assertInternalType('string', $cachedData['etag']); + $this->assertNotSame($rootCachedData['etag'], $cachedData['etag']); $this->assertGreaterThanOrEqual($rootCachedData['mtime'], $cachedData['mtime']); $rootCachedData = $cachedData; Filesystem::mkdir('bar_folder'); $this->assertTrue($this->cache->inCache('bar_folder')); $cachedData = $this->cache->get(''); - $this->assertNotEquals($rootCachedData['etag'], $cachedData['etag']); + $this->assertInternalType('string', $rootCachedData['etag']); + $this->assertInternalType('string', $cachedData['etag']); + $this->assertNotSame($rootCachedData['etag'], $cachedData['etag']); $rootCachedData = $cachedData; Filesystem::rmdir('bar_folder'); $this->assertFalse($this->cache->inCache('bar_folder')); $cachedData = $this->cache->get(''); - $this->assertNotEquals($rootCachedData['etag'], $cachedData['etag']); + $this->assertInternalType('string', $rootCachedData['etag']); + $this->assertInternalType('string', $cachedData['etag']); + $this->assertNotSame($rootCachedData['etag'], $cachedData['etag']); $this->assertGreaterThanOrEqual($rootCachedData['mtime'], $cachedData['mtime']); } @@ -174,11 +186,15 @@ class Updater extends \PHPUnit_Framework_TestCase { $this->assertFalse($cache2->inCache('foo.txt')); $cachedData = $cache2->get(''); - $this->assertNotEquals($substorageCachedData['etag'], $cachedData['etag']); + $this->assertInternalType('string', $substorageCachedData['etag']); + $this->assertInternalType('string', $cachedData['etag']); + $this->assertNotSame($substorageCachedData['etag'], $cachedData['etag']); $this->assertGreaterThanOrEqual($substorageCachedData['mtime'], $cachedData['mtime']); $cachedData = $this->cache->get('folder'); - $this->assertNotEquals($folderCachedData['etag'], $cachedData['etag']); + $this->assertInternalType('string', $folderCachedData['etag']); + $this->assertInternalType('string', $cachedData['etag']); + $this->assertNotSame($folderCachedData['etag'], $cachedData['etag']); $this->assertGreaterThanOrEqual($folderCachedData['mtime'], $cachedData['mtime']); } @@ -199,7 +215,9 @@ class Updater extends \PHPUnit_Framework_TestCase { $mtime = $cachedData['mtime']; $cachedData = $this->cache->get(''); $this->assertEquals(3 * $textSize + $imageSize, $cachedData['size']); - $this->assertNotEquals($rootCachedData['etag'], $cachedData['etag']); + $this->assertInternalType('string', $rootCachedData['etag']); + $this->assertInternalType('string', $cachedData['etag']); + $this->assertNotSame($rootCachedData['etag'], $cachedData['etag']); } public function testRenameExtension() { @@ -227,12 +245,16 @@ class Updater extends \PHPUnit_Framework_TestCase { $mtime = $cachedData['mtime']; $cachedData = $cache2->get(''); - $this->assertNotEquals($substorageCachedData['etag'], $cachedData['etag']); + $this->assertInternalType('string', $substorageCachedData['etag']); + $this->assertInternalType('string', $cachedData['etag']); + $this->assertNotSame($substorageCachedData['etag'], $cachedData['etag']); // rename can cause mtime change - invalid assert // $this->assertEquals($mtime, $cachedData['mtime']); $cachedData = $this->cache->get('folder'); - $this->assertNotEquals($folderCachedData['etag'], $cachedData['etag']); + $this->assertInternalType('string', $folderCachedData['etag']); + $this->assertInternalType('string', $cachedData['etag']); + $this->assertNotSame($folderCachedData['etag'], $cachedData['etag']); // rename can cause mtime change - invalid assert // $this->assertEquals($mtime, $cachedData['mtime']); } @@ -242,11 +264,15 @@ class Updater extends \PHPUnit_Framework_TestCase { $fooCachedData = $this->cache->get('foo.txt'); Filesystem::touch('foo.txt'); $cachedData = $this->cache->get('foo.txt'); - $this->assertNotEquals($fooCachedData['etag'], $cachedData['etag']); + $this->assertInternalType('string', $fooCachedData['etag']); + $this->assertInternalType('string', $cachedData['etag']); + $this->assertNotSame($fooCachedData['etag'], $cachedData['etag']); $this->assertGreaterThanOrEqual($fooCachedData['mtime'], $cachedData['mtime']); $cachedData = $this->cache->get(''); - $this->assertNotEquals($rootCachedData['etag'], $cachedData['etag']); + $this->assertInternalType('string', $rootCachedData['etag']); + $this->assertInternalType('string', $cachedData['etag']); + $this->assertNotSame($rootCachedData['etag'], $cachedData['etag']); $this->assertGreaterThanOrEqual($rootCachedData['mtime'], $cachedData['mtime']); $rootCachedData = $cachedData; @@ -255,14 +281,20 @@ class Updater extends \PHPUnit_Framework_TestCase { $folderCachedData = $this->cache->get('folder'); Filesystem::touch('folder/bar.txt', $time); $cachedData = $this->cache->get('folder/bar.txt'); - $this->assertNotEquals($barCachedData['etag'], $cachedData['etag']); + $this->assertInternalType('string', $barCachedData['etag']); + $this->assertInternalType('string', $cachedData['etag']); + $this->assertNotSame($barCachedData['etag'], $cachedData['etag']); $this->assertEquals($time, $cachedData['mtime']); $cachedData = $this->cache->get('folder'); - $this->assertNotEquals($folderCachedData['etag'], $cachedData['etag']); + $this->assertInternalType('string', $folderCachedData['etag']); + $this->assertInternalType('string', $cachedData['etag']); + $this->assertNotSame($folderCachedData['etag'], $cachedData['etag']); $cachedData = $this->cache->get(''); - $this->assertNotEquals($rootCachedData['etag'], $cachedData['etag']); + $this->assertInternalType('string', $rootCachedData['etag']); + $this->assertInternalType('string', $cachedData['etag']); + $this->assertNotSame($rootCachedData['etag'], $cachedData['etag']); $this->assertEquals($time, $cachedData['mtime']); } @@ -279,14 +311,20 @@ class Updater extends \PHPUnit_Framework_TestCase { $time = 1371006070; Filesystem::touch('folder/substorage/foo.txt', $time); $cachedData = $cache2->get('foo.txt'); - $this->assertNotEquals($fooCachedData['etag'], $cachedData['etag']); + $this->assertInternalType('string', $fooCachedData['etag']); + $this->assertInternalType('string', $cachedData['etag']); + $this->assertNotSame($fooCachedData['etag'], $cachedData['etag']); $this->assertEquals($time, $cachedData['mtime']); $cachedData = $cache2->get(''); - $this->assertNotEquals($substorageCachedData['etag'], $cachedData['etag']); + $this->assertInternalType('string', $substorageCachedData['etag']); + $this->assertInternalType('string', $cachedData['etag']); + $this->assertNotSame($substorageCachedData['etag'], $cachedData['etag']); $cachedData = $this->cache->get('folder'); - $this->assertNotEquals($folderCachedData['etag'], $cachedData['etag']); + $this->assertInternalType('string', $folderCachedData['etag']); + $this->assertInternalType('string', $cachedData['etag']); + $this->assertNotSame($folderCachedData['etag'], $cachedData['etag']); $this->assertEquals($time, $cachedData['mtime']); } diff --git a/tests/lib/files/etagtest.php b/tests/lib/files/etagtest.php index ce05adb188a..af9f66835f0 100644 --- a/tests/lib/files/etagtest.php +++ b/tests/lib/files/etagtest.php @@ -65,7 +65,11 @@ class EtagTest extends \PHPUnit_Framework_TestCase { $scanner = new \OC\Files\Utils\Scanner($user1); $scanner->backgroundScan('/'); - $this->assertEquals($originalEtags, $this->getEtags($files)); + $newEtags = $this->getEtags($files); + // loop over array and use assertSame over assertEquals to prevent false positives + foreach ($originalEtags as $file => $originalEtag) { + $this->assertSame($originalEtag, $newEtags[$file]); + } } /** diff --git a/tests/lib/files/filesystem.php b/tests/lib/files/filesystem.php index 90f1dfe581b..53f528af793 100644 --- a/tests/lib/files/filesystem.php +++ b/tests/lib/files/filesystem.php @@ -226,4 +226,55 @@ class Filesystem extends \PHPUnit_Framework_TestCase { $path = $arguments['path']; $this->assertEquals($path, \OC\Files\Filesystem::normalizePath($path)); //the path passed to the hook should already be normalized } + + /** + * Test that the default cache dir is part of the user's home + */ + public function testMountDefaultCacheDir() { + $userId = uniqid('user_'); + $oldCachePath = \OC_Config::getValue('cache_path', ''); + // no cache path configured + \OC_Config::setValue('cache_path', ''); + + \OC_User::createUser($userId, $userId); + \OC\Files\Filesystem::initMountPoints($userId); + + $this->assertEquals( + '/' . $userId . '/', + \OC\Files\Filesystem::getMountPoint('/' . $userId . '/cache') + ); + list($storage, $internalPath) = \OC\Files\Filesystem::resolvePath('/' . $userId . '/cache'); + $this->assertInstanceOf('\OC\Files\Storage\Home', $storage); + $this->assertEquals('cache', $internalPath); + \OC_User::deleteUser($userId); + + \OC_Config::setValue('cache_path', $oldCachePath); + } + + /** + * Test that an external cache is mounted into + * the user's home + */ + public function testMountExternalCacheDir() { + $userId = uniqid('user_'); + + $oldCachePath = \OC_Config::getValue('cache_path', ''); + // set cache path to temp dir + $cachePath = \OC_Helper::tmpFolder() . '/extcache'; + \OC_Config::setValue('cache_path', $cachePath); + + \OC_User::createUser($userId, $userId); + \OC\Files\Filesystem::initMountPoints($userId); + + $this->assertEquals( + '/' . $userId . '/cache/', + \OC\Files\Filesystem::getMountPoint('/' . $userId . '/cache') + ); + list($storage, $internalPath) = \OC\Files\Filesystem::resolvePath('/' . $userId . '/cache'); + $this->assertInstanceOf('\OC\Files\Storage\Local', $storage); + $this->assertEquals('', $internalPath); + \OC_User::deleteUser($userId); + + \OC_Config::setValue('cache_path', $oldCachePath); + } } diff --git a/tests/lib/files/storage/storage.php b/tests/lib/files/storage/storage.php index f9291758606..38cd17ac8c9 100644 --- a/tests/lib/files/storage/storage.php +++ b/tests/lib/files/storage/storage.php @@ -64,17 +64,17 @@ abstract class Storage extends \PHPUnit_Framework_TestCase { * @dataProvider directoryProvider */ public function testDirectories($directory) { - $this->assertFalse($this->instance->file_exists('/'.$directory)); + $this->assertFalse($this->instance->file_exists('/' . $directory)); - $this->assertTrue($this->instance->mkdir('/'.$directory)); + $this->assertTrue($this->instance->mkdir('/' . $directory)); - $this->assertTrue($this->instance->file_exists('/'.$directory)); - $this->assertTrue($this->instance->is_dir('/'.$directory)); - $this->assertFalse($this->instance->is_file('/'.$directory)); - $this->assertEquals('dir', $this->instance->filetype('/'.$directory)); - $this->assertEquals(0, $this->instance->filesize('/'.$directory)); - $this->assertTrue($this->instance->isReadable('/'.$directory)); - $this->assertTrue($this->instance->isUpdatable('/'.$directory)); + $this->assertTrue($this->instance->file_exists('/' . $directory)); + $this->assertTrue($this->instance->is_dir('/' . $directory)); + $this->assertFalse($this->instance->is_file('/' . $directory)); + $this->assertEquals('dir', $this->instance->filetype('/' . $directory)); + $this->assertEquals(0, $this->instance->filesize('/' . $directory)); + $this->assertTrue($this->instance->isReadable('/' . $directory)); + $this->assertTrue($this->instance->isUpdatable('/' . $directory)); $dh = $this->instance->opendir('/'); $content = array(); @@ -85,13 +85,13 @@ abstract class Storage extends \PHPUnit_Framework_TestCase { } $this->assertEquals(array($directory), $content); - $this->assertFalse($this->instance->mkdir('/'.$directory)); //cant create existing folders - $this->assertTrue($this->instance->rmdir('/'.$directory)); + $this->assertFalse($this->instance->mkdir('/' . $directory)); //cant create existing folders + $this->assertTrue($this->instance->rmdir('/' . $directory)); $this->wait(); - $this->assertFalse($this->instance->file_exists('/'.$directory)); + $this->assertFalse($this->instance->file_exists('/' . $directory)); - $this->assertFalse($this->instance->rmdir('/'.$directory)); //cant remove non existing folders + $this->assertFalse($this->instance->rmdir('/' . $directory)); //cant remove non existing folders $dh = $this->instance->opendir('/'); $content = array(); @@ -103,8 +103,7 @@ abstract class Storage extends \PHPUnit_Framework_TestCase { $this->assertEquals(array(), $content); } - public function directoryProvider() - { + public function directoryProvider() { return array( array('folder'), array(' folder'), @@ -113,11 +112,23 @@ abstract class Storage extends \PHPUnit_Framework_TestCase { array('spéciäl földer'), ); } + + function loremFileProvider() { + $root = \OC::$SERVERROOT . '/tests/data/'; + return array( + // small file + array($root . 'lorem.txt'), + // bigger file (> 8 KB which is the standard PHP block size) + array($root . 'lorem-big.txt') + ); + } + /** * test the various uses of file_get_contents and file_put_contents + * + * @dataProvider loremFileProvider */ - public function testGetPutContents() { - $sourceFile = \OC::$SERVERROOT . '/tests/data/lorem.txt'; + public function testGetPutContents($sourceFile) { $sourceText = file_get_contents($sourceFile); //fill a file with string data @@ -298,4 +309,40 @@ abstract class Storage extends \PHPUnit_Framework_TestCase { $this->assertFalse($this->instance->file_exists('folder/bar')); $this->assertFalse($this->instance->file_exists('folder')); } + + public function hashProvider() { + return array( + array('Foobar', 'md5'), + array('Foobar', 'sha1'), + array('Foobar', 'sha256'), + ); + } + + /** + * @dataProvider hashProvider + */ + public function testHash($data, $type) { + $this->instance->file_put_contents('hash.txt', $data); + $this->assertEquals(hash($type, $data), $this->instance->hash($type, 'hash.txt')); + $this->assertEquals(hash($type, $data, true), $this->instance->hash($type, 'hash.txt', true)); + } + + public function testHashInFileName() { + $this->instance->file_put_contents('#test.txt', 'data'); + $this->assertEquals('data', $this->instance->file_get_contents('#test.txt')); + + $this->instance->mkdir('#foo'); + $this->instance->file_put_contents('#foo/test.txt', 'data'); + $this->assertEquals('data', $this->instance->file_get_contents('#foo/test.txt')); + + $dh = $this->instance->opendir('#foo'); + $content = array(); + while ($file = readdir($dh)) { + if ($file != '.' and $file != '..') { + $content[] = $file; + } + } + + $this->assertEquals(array('test.txt'), $content); + } } diff --git a/tests/lib/files/storage/wrapper/quota.php b/tests/lib/files/storage/wrapper/quota.php index 43eae78415d..777529fd85e 100644 --- a/tests/lib/files/storage/wrapper/quota.php +++ b/tests/lib/files/storage/wrapper/quota.php @@ -53,6 +53,40 @@ class Quota extends \Test\Files\Storage\Storage { $this->assertEquals(9, $instance->free_space('')); } + public function testFreeSpaceWithUsedSpace() { + $instance = $this->getLimitedStorage(9); + $instance->getCache()->put( + '', array('size' => 3, 'unencrypted_size' => 0) + ); + $this->assertEquals(6, $instance->free_space('')); + } + + public function testFreeSpaceWithUnknownDiskSpace() { + $storage = $this->getMock( + '\OC\Files\Storage\Local', + array('free_space'), + array(array('datadir' => $this->tmpDir)) + ); + $storage->expects($this->any()) + ->method('free_space') + ->will($this->returnValue(-2)); + $storage->getScanner()->scan(''); + + $instance = new \OC\Files\Storage\Wrapper\Quota(array('storage' => $storage, 'quota' => 9)); + $instance->getCache()->put( + '', array('size' => 3, 'unencrypted_size' => 0) + ); + $this->assertEquals(6, $instance->free_space('')); + } + + public function testFreeSpaceWithUsedSpaceAndEncryption() { + $instance = $this->getLimitedStorage(9); + $instance->getCache()->put( + '', array('size' => 7, 'unencrypted_size' => 3) + ); + $this->assertEquals(6, $instance->free_space('')); + } + public function testFWriteNotEnoughSpace() { $instance = $this->getLimitedStorage(9); $stream = $instance->fopen('foo', 'w+'); diff --git a/tests/lib/files/view.php b/tests/lib/files/view.php index 371d1ed1798..f80dd06e1cb 100644 --- a/tests/lib/files/view.php +++ b/tests/lib/files/view.php @@ -394,13 +394,12 @@ class View extends \PHPUnit_Framework_TestCase { $this->assertNull($this->hookPath); $subView->file_put_contents('/foo.txt', 'asd'); - $this->assertNotNull($this->hookPath); $this->assertEquals('/substorage/foo.txt', $this->hookPath); } private $hookPath; - function dummyHook($params) { + public function dummyHook($params) { $this->hookPath = $params['path']; } @@ -442,12 +441,6 @@ class View extends \PHPUnit_Framework_TestCase { return $storage; } - private $createHookPath; - - function dummyCreateHook($params) { - $this->createHookPath = $params['path']; - } - /** * @medium */ @@ -466,23 +459,50 @@ class View extends \PHPUnit_Framework_TestCase { $this->assertNull($this->hookPath); } + private $hookWritePath; + private $hookCreatePath; + private $hookUpdatePath; + + public function dummyHookWrite($params) { + $this->hookWritePath = $params['path']; + } + + public function dummyHookUpdate($params) { + $this->hookUpdatePath = $params['path']; + } + + public function dummyHookCreate($params) { + $this->hookCreatePath = $params['path']; + } + public function testEditNoCreateHook() { $storage1 = $this->getTestStorage(); $storage2 = $this->getTestStorage(); $defaultRoot = \OC\Files\Filesystem::getRoot(); \OC\Files\Filesystem::mount($storage1, array(), '/'); \OC\Files\Filesystem::mount($storage2, array(), $defaultRoot); - \OC_Hook::connect('OC_Filesystem', 'post_create', $this, 'dummyCreateHook'); + \OC_Hook::connect('OC_Filesystem', 'post_create', $this, 'dummyHookCreate'); + \OC_Hook::connect('OC_Filesystem', 'post_update', $this, 'dummyHookUpdate'); + \OC_Hook::connect('OC_Filesystem', 'post_write', $this, 'dummyHookWrite'); $view = new \OC\Files\View($defaultRoot); - $this->hookPath = null; + $this->hookWritePath = $this->hookUpdatePath = $this->hookCreatePath = null; $view->file_put_contents('/asd.txt', 'foo'); - $this->assertEquals('/asd.txt', $this->createHookPath); - $this->createHookPath = null; + $this->assertEquals('/asd.txt', $this->hookCreatePath); + $this->assertNull($this->hookUpdatePath); + $this->assertEquals('/asd.txt', $this->hookWritePath); + + $this->hookWritePath = $this->hookUpdatePath = $this->hookCreatePath = null; $view->file_put_contents('/asd.txt', 'foo'); - $this->assertNull($this->createHookPath); + $this->assertNull($this->hookCreatePath); + $this->assertEquals('/asd.txt', $this->hookUpdatePath); + $this->assertEquals('/asd.txt', $this->hookWritePath); + + \OC_Hook::clear('OC_Filesystem', 'post_create'); + \OC_Hook::clear('OC_Filesystem', 'post_update'); + \OC_Hook::clear('OC_Filesystem', 'post_write'); } /** @@ -563,6 +583,6 @@ class View extends \PHPUnit_Framework_TestCase { $scanner->scanFile('test', \OC\Files\Cache\Scanner::REUSE_ETAG); $info2 = $view->getFileInfo('/test/test'); - $this->assertEquals($info['etag'], $info2['etag']); + $this->assertSame($info['etag'], $info2['etag']); } } diff --git a/tests/lib/group.php b/tests/lib/group.php index 8de8d033e19..26232187c36 100644 --- a/tests/lib/group.php +++ b/tests/lib/group.php @@ -109,25 +109,6 @@ class Test_Group extends PHPUnit_Framework_TestCase { $this->assertEquals(array(), OC_Group::getGroups()); } - public function testDisplayNamesInGroup() { - OC_Group::useBackend(new OC_Group_Dummy()); - $userBackend = new \OC_User_Dummy(); - \OC_User::getManager()->registerBackend($userBackend); - - $group1 = uniqid(); - $user1 = 'uid1'; - $user2 = 'uid2'; - OC_Group::createGroup($group1); - $userBackend->createUser($user1, ''); - $userBackend->createUser($user2, ''); - OC_Group::addToGroup($user1, $group1); - OC_Group::addToGroup($user2, $group1); - //Dummy backend does not support setting displaynames, uid will always - //be returned. This checks primarily, that the return format is okay. - $expected = array($user1 => $user1, $user2 => $user2); - $this->assertEquals($expected, OC_Group::displayNamesInGroup($group1)); - } - public function testUsersInGroup() { OC_Group::useBackend(new OC_Group_Dummy()); $userBackend = new \OC_User_Dummy(); diff --git a/tests/lib/group/group.php b/tests/lib/group/group.php index 3982c00e45f..990f8ecc1d5 100644 --- a/tests/lib/group/group.php +++ b/tests/lib/group/group.php @@ -287,7 +287,7 @@ class Group extends \PHPUnit_Framework_TestCase { ->will($this->returnValue(array('user2'))); $backend2->expects($this->once()) ->method('usersInGroup') - ->with('group1', 'user', 1, 0) + ->with('group1', 'user', 2, 1) ->will($this->returnValue(array('user1'))); $users = $group->searchUsers('user', 2, 1); @@ -299,6 +299,68 @@ class Group extends \PHPUnit_Framework_TestCase { $this->assertEquals('user1', $user1->getUID()); } + public function testCountUsers() { + $backend1 = $this->getMock('OC_Group_Database'); + $userManager = $this->getUserManager(); + $group = new \OC\Group\Group('group1', array($backend1), $userManager); + + $backend1->expects($this->once()) + ->method('countUsersInGroup') + ->with('group1', '2') + ->will($this->returnValue(3)); + + $backend1->expects($this->any()) + ->method('implementsActions') + ->will($this->returnValue(true)); + + $users = $group->count('2'); + + $this->assertSame(3, $users); + } + + public function testCountUsersMultipleBackends() { + $backend1 = $this->getMock('OC_Group_Database'); + $backend2 = $this->getMock('OC_Group_Database'); + $userManager = $this->getUserManager(); + $group = new \OC\Group\Group('group1', array($backend1, $backend2), $userManager); + + $backend1->expects($this->once()) + ->method('countUsersInGroup') + ->with('group1', '2') + ->will($this->returnValue(3)); + $backend1->expects($this->any()) + ->method('implementsActions') + ->will($this->returnValue(true)); + + $backend2->expects($this->once()) + ->method('countUsersInGroup') + ->with('group1', '2') + ->will($this->returnValue(4)); + $backend2->expects($this->any()) + ->method('implementsActions') + ->will($this->returnValue(true)); + + $users = $group->count('2'); + + $this->assertSame(7, $users); + } + + public function testCountUsersNoMethod() { + $backend1 = $this->getMock('OC_Group_Database'); + $userManager = $this->getUserManager(); + $group = new \OC\Group\Group('group1', array($backend1), $userManager); + + $backend1->expects($this->never()) + ->method('countUsersInGroup'); + $backend1->expects($this->any()) + ->method('implementsActions') + ->will($this->returnValue(false)); + + $users = $group->count('2'); + + $this->assertSame(false, $users); + } + public function testDelete() { $backend = $this->getMock('OC_Group_Database'); $userManager = $this->getUserManager(); diff --git a/tests/lib/group/manager.php b/tests/lib/group/manager.php index c39a7d6f33a..bab9621e39d 100644 --- a/tests/lib/group/manager.php +++ b/tests/lib/group/manager.php @@ -254,7 +254,7 @@ class Manager extends \PHPUnit_Framework_TestCase { $backend2 = $this->getMock('\OC_Group_Database'); $backend2->expects($this->once()) ->method('getGroups') - ->with('1', 1, 0) + ->with('1', 2, 1) ->will($this->returnValue(array('group12'))); $backend2->expects($this->any()) ->method('groupExists') @@ -344,6 +344,56 @@ class Manager extends \PHPUnit_Framework_TestCase { $this->assertEquals('group2', $group2->getGID()); } + public function testDisplayNamesInGroupMultipleUserBackends() { + $user1 = new User('user1', null); + $user2 = new User('user2', null); + $user3 = new User('user3', null); + $user4 = new User('user33', null); + + /** + * @var \PHPUnit_Framework_MockObject_MockObject | \OC_Group_Backend $backend1 + */ + $backend = $this->getMock('\OC_Group_Database'); + $backend->expects($this->exactly(1)) + ->method('groupExists') + ->with('testgroup') + ->will($this->returnValue(true)); + + $backend->expects($this->once()) + ->method('usersInGroup') + ->with('testgroup', '', -1, 0) + ->will($this->returnValue(array('user2', 'user33'))); + + /** + * @var \OC\User\Manager $userManager + */ + $userManager = $this->getMock('\OC\User\Manager'); + $userManager->expects($this->once()) + ->method('search') + ->with('user3') + ->will($this->returnValue(array('user3' => $user3, 'user33' => $user4))); + + $userManager->expects($this->any()) + ->method('get') + ->will($this->returnCallback(function($uid) { + switch($uid) { + case 'user1' : return new User('user1', null); + case 'user2' : return new User('user2', null); + case 'user3' : return new User('user3', null); + case 'user33': return new User('user33', null); + default: + return null; + } + })); + + $manager = new \OC\Group\Manager($userManager); + $manager->addBackend($backend); + + $users = $manager->displayNamesInGroup('testgroup', 'user3'); + $this->assertEquals(1, count($users)); + $this->assertTrue(isset($users['user33'])); + } + public function testGetUserGroupsWithAddUser() { /** * @var \PHPUnit_Framework_MockObject_MockObject | \OC_Group_Backend $backend diff --git a/tests/lib/helper.php b/tests/lib/helper.php index 4311215795c..5663df7c9ae 100644 --- a/tests/lib/helper.php +++ b/tests/lib/helper.php @@ -23,6 +23,7 @@ class Test_Helper extends PHPUnit_Framework_TestCase { array('0 B', 0), array('1 kB', 1024), array('9.5 MB', 10000000), + array('1.3 GB', 1395864371), array('465.7 GB', 500000000000), array('454.7 TB', 500000000000000), array('444.1 PB', 500000000000000000), @@ -30,6 +31,28 @@ class Test_Helper extends PHPUnit_Framework_TestCase { } /** + * @dataProvider phpFileSizeProvider + */ + public function testPhpFileSize($expected, $input) + { + $result = OC_Helper::phpFileSize($input); + $this->assertEquals($expected, $result); + } + + public function phpFileSizeProvider() + { + return array( + array('0B', 0), + array('1K', 1024), + array('9.5M', 10000000), + array('1.3G', 1395864371), + array('465.7G', 500000000000), + array('465661.3G', 500000000000000), + array('465661287.3G', 500000000000000000), + ); + } + + /** * @dataProvider computerFileSizeProvider */ function testComputerFileSize($expected, $input) { @@ -41,8 +64,9 @@ class Test_Helper extends PHPUnit_Framework_TestCase { return array( array(0.0, "0 B"), array(1024.0, "1 kB"), + array(1395864371.0, '1.3 GB'), array(9961472.0, "9.5 MB"), - array(500041567436.8, "465.7 GB"), + array(500041567437.0, "465.7 GB"), ); } @@ -69,6 +93,18 @@ class Test_Helper extends PHPUnit_Framework_TestCase { $this->assertEquals($result, $expected); } + function testGetSecureMimeType() { + $dir=OC::$SERVERROOT.'/tests/data'; + + $result = OC_Helper::getSecureMimeType('image/svg+xml'); + $expected = 'text/plain'; + $this->assertEquals($result, $expected); + + $result = OC_Helper::getSecureMimeType('image/png'); + $expected = 'image/png'; + $this->assertEquals($result, $expected); + } + function testGetFileNameMimeType() { $this->assertEquals('text/plain', OC_Helper::getFileNameMimeType('foo.txt')); $this->assertEquals('image/png', OC_Helper::getFileNameMimeType('foo.png')); @@ -243,4 +279,179 @@ class Test_Helper extends PHPUnit_Framework_TestCase { array(3670, true, \OC::$SERVERROOT . '/tests/data/testimage.png', \OC::$SERVERROOT . '/tests/data/testimage-copy.png'), ); } + + // Url generator methods + + /** + * @small + * @brief test absolute URL construction + * @dataProvider provideDocRootURLs + */ + function testMakeAbsoluteURLDocRoot($url, $expectedResult) { + \OC::$WEBROOT = ''; + $result = \OC_Helper::makeURLAbsolute($url); + + $this->assertEquals($expectedResult, $result); + } + + /** + * @small + * @brief test absolute URL construction + * @dataProvider provideSubDirURLs + */ + function testMakeAbsoluteURLSubDir($url, $expectedResult) { + \OC::$WEBROOT = '/owncloud'; + $result = \OC_Helper::makeURLAbsolute($url); + + $this->assertEquals($expectedResult, $result); + } + + public function provideDocRootURLs() { + return array( + array('index.php', 'http://localhost/index.php'), + array('/index.php', 'http://localhost/index.php'), + array('/apps/index.php', 'http://localhost/apps/index.php'), + array('apps/index.php', 'http://localhost/apps/index.php'), + ); + } + + public function provideSubDirURLs() { + return array( + array('index.php', 'http://localhost/owncloud/index.php'), + array('/index.php', 'http://localhost/owncloud/index.php'), + array('/apps/index.php', 'http://localhost/owncloud/apps/index.php'), + array('apps/index.php', 'http://localhost/owncloud/apps/index.php'), + ); + } + + /** + * @small + * @brief test linkTo URL construction + * @dataProvider provideDocRootAppUrlParts + */ + public function testLinkToDocRoot($app, $file, $args, $expectedResult) { + \OC::$WEBROOT = ''; + $result = \OC_Helper::linkTo($app, $file, $args); + + $this->assertEquals($expectedResult, $result); + } + + /** + * @small + * @brief test linkTo URL construction in sub directory + * @dataProvider provideSubDirAppUrlParts + */ + public function testLinkToSubDir($app, $file, $args, $expectedResult) { + \OC::$WEBROOT = '/owncloud'; + $result = \OC_Helper::linkTo($app, $file, $args); + + $this->assertEquals($expectedResult, $result); + } + + public function provideDocRootAppUrlParts() { + return array( + array('files', 'index.php', array(), '/index.php/apps/files'), + array('files', 'index.php', array('trut' => 'trat', 'dut' => 'dat'), '/index.php/apps/files?trut=trat&dut=dat'), + array('', 'index.php', array('trut' => 'trat', 'dut' => 'dat'), '/index.php?trut=trat&dut=dat'), + ); + } + + public function provideSubDirAppUrlParts() { + return array( + array('files', 'index.php', array(), '/owncloud/index.php/apps/files'), + array('files', 'index.php', array('trut' => 'trat', 'dut' => 'dat'), '/owncloud/index.php/apps/files?trut=trat&dut=dat'), + array('', 'index.php', array('trut' => 'trat', 'dut' => 'dat'), '/owncloud/index.php?trut=trat&dut=dat'), + ); + } + + /** + * @small + * @brief test linkToAbsolute URL construction + * @dataProvider provideDocRootAppAbsoluteUrlParts + */ + public function testLinkToAbsoluteDocRoot($app, $file, $args, $expectedResult) { + \OC::$WEBROOT = ''; + $result = \OC_Helper::linkToAbsolute($app, $file, $args); + + $this->assertEquals($expectedResult, $result); + } + + /** + * @small + * @brief test linkToAbsolute URL construction in sub directory + * @dataProvider provideSubDirAppAbsoluteUrlParts + */ + public function testLinkToAbsoluteSubDir($app, $file, $args, $expectedResult) { + \OC::$WEBROOT = '/owncloud'; + $result = \OC_Helper::linkToAbsolute($app, $file, $args); + + $this->assertEquals($expectedResult, $result); + } + + public function provideDocRootAppAbsoluteUrlParts() { + return array( + array('files', 'index.php', array(), 'http://localhost/index.php/apps/files'), + array('files', 'index.php', array('trut' => 'trat', 'dut' => 'dat'), 'http://localhost/index.php/apps/files?trut=trat&dut=dat'), + array('', 'index.php', array('trut' => 'trat', 'dut' => 'dat'), 'http://localhost/index.php?trut=trat&dut=dat'), + ); + } + + public function provideSubDirAppAbsoluteUrlParts() { + return array( + array('files', 'index.php', array(), 'http://localhost/owncloud/index.php/apps/files'), + array('files', 'index.php', array('trut' => 'trat', 'dut' => 'dat'), 'http://localhost/owncloud/index.php/apps/files?trut=trat&dut=dat'), + array('', 'index.php', array('trut' => 'trat', 'dut' => 'dat'), 'http://localhost/owncloud/index.php?trut=trat&dut=dat'), + ); + } + + /** + * @small + * @brief test linkToRemoteBase URL construction + */ + public function testLinkToRemoteBase() { + \OC::$WEBROOT = ''; + $result = \OC_Helper::linkToRemoteBase('webdav'); + $this->assertEquals('/remote.php/webdav', $result); + + \OC::$WEBROOT = '/owncloud'; + $result = \OC_Helper::linkToRemoteBase('webdav'); + $this->assertEquals('/owncloud/remote.php/webdav', $result); + } + + /** + * @small + * @brief test linkToRemote URL construction + */ + public function testLinkToRemote() { + \OC::$WEBROOT = ''; + $result = \OC_Helper::linkToRemote('webdav'); + $this->assertEquals('http://localhost/remote.php/webdav/', $result); + $result = \OC_Helper::linkToRemote('webdav', false); + $this->assertEquals('http://localhost/remote.php/webdav', $result); + + \OC::$WEBROOT = '/owncloud'; + $result = \OC_Helper::linkToRemote('webdav'); + $this->assertEquals('http://localhost/owncloud/remote.php/webdav/', $result); + $result = \OC_Helper::linkToRemote('webdav', false); + $this->assertEquals('http://localhost/owncloud/remote.php/webdav', $result); + } + + /** + * @small + * @brief test linkToPublic URL construction + */ + public function testLinkToPublic() { + \OC::$WEBROOT = ''; + $result = \OC_Helper::linkToPublic('files'); + $this->assertEquals('http://localhost/public.php?service=files', $result); + $result = \OC_Helper::linkToPublic('files', false); + $this->assertEquals('http://localhost/public.php?service=files', $result); + + \OC::$WEBROOT = '/owncloud'; + $result = \OC_Helper::linkToPublic('files'); + $this->assertEquals('http://localhost/owncloud/public.php?service=files', $result); + $result = \OC_Helper::linkToPublic('files', false); + $this->assertEquals('http://localhost/owncloud/public.php?service=files', $result); + } + } diff --git a/tests/lib/helperstorage.php b/tests/lib/helperstorage.php new file mode 100644 index 00000000000..010a54e3bb0 --- /dev/null +++ b/tests/lib/helperstorage.php @@ -0,0 +1,113 @@ +<?php +/** + * Copyright (c) 2014 Vincent Petry <pvince81@owncloud.com> + * This file is licensed under the Affero General Public License version 3 or + * later. + * See the COPYING-README file. + */ + +/** + * Test the storage functions of OC_Helper + */ +class Test_Helper_Storage extends PHPUnit_Framework_TestCase { + private $user; + private $storageMock; + + public function setUp() { + $this->user = 'user_' . uniqid(); + \OC\Files\Filesystem::tearDown(); + \OC\Files\Filesystem::init($this->user, '/' . $this->user . '/files'); + + $this->storageMock = $this->getMock( + '\OC\Files\Storage\Temporary', + array('free_space'), + array('') + ); + + \OC\Files\Filesystem::clearMounts(); + + $this->storageMock->expects($this->once()) + ->method('free_space') + ->will($this->returnValue(12)); + } + + public function tearDown() { + $this->user = null; + + $this->storageMock->getCache()->clear(); + \OC\Files\Filesystem::tearDown(); + } + + /** + * Test getting the storage info + */ + function testGetStorageInfo() { + \OC\Files\Filesystem::mount($this->storageMock, array(), '/' . $this->user . '/files'); + $this->storageMock->file_put_contents('test.txt', '01234'); + + $storageInfo = \OC_Helper::getStorageInfo(''); + $this->assertEquals(12, $storageInfo['free']); + $this->assertEquals(5, $storageInfo['used']); + $this->assertEquals(17, $storageInfo['total']); + } + + /** + * Test getting the storage info with quota enabled + */ + function testGetStorageInfoWithQuota() { + $this->storageMock->file_put_contents('test.txt', '01234'); + $this->storageMock = new \OC\Files\Storage\Wrapper\Quota( + array( + 'storage' => $this->storageMock, + 'quota' => 7 + ) + ); + \OC\Files\Filesystem::mount($this->storageMock, array(), '/' . $this->user . '/files'); + + $storageInfo = \OC_Helper::getStorageInfo(''); + $this->assertEquals(2, $storageInfo['free']); + $this->assertEquals(5, $storageInfo['used']); + $this->assertEquals(7, $storageInfo['total']); + } + + /** + * Test getting the storage info when data exceeds quota + */ + function testGetStorageInfoWhenSizeExceedsQuota() { + $this->storageMock->file_put_contents('test.txt', '0123456789'); + $this->storageMock = new \OC\Files\Storage\Wrapper\Quota( + array( + 'storage' => $this->storageMock, + 'quota' => 7 + ) + ); + \OC\Files\Filesystem::mount($this->storageMock, array(), '/' . $this->user . '/files'); + + $storageInfo = \OC_Helper::getStorageInfo(''); + $this->assertEquals(0, $storageInfo['free']); + $this->assertEquals(10, $storageInfo['used']); + // total = quota + $this->assertEquals(7, $storageInfo['total']); + } + + /** + * Test getting the storage info when the remaining + * free storage space is less than the quota + */ + function testGetStorageInfoWhenFreeSpaceLessThanQuota() { + $this->storageMock->file_put_contents('test.txt', '01234'); + $this->storageMock = new \OC\Files\Storage\Wrapper\Quota( + array( + 'storage' => $this->storageMock, + 'quota' => 18 + ) + ); + \OC\Files\Filesystem::mount($this->storageMock, array(), '/' . $this->user . '/files'); + + $storageInfo = \OC_Helper::getStorageInfo(''); + $this->assertEquals(12, $storageInfo['free']); + $this->assertEquals(5, $storageInfo['used']); + // total = free + used (because quota > total) + $this->assertEquals(17, $storageInfo['total']); + } +} diff --git a/tests/lib/image.php b/tests/lib/image.php index 4aba1b0bc61..131a9d86f3e 100644 --- a/tests/lib/image.php +++ b/tests/lib/image.php @@ -8,8 +8,8 @@ class Test_Image extends PHPUnit_Framework_TestCase { public static function tearDownAfterClass() { - unlink(OC::$SERVERROOT.'/tests/data/testimage2.png'); - unlink(OC::$SERVERROOT.'/tests/data/testimage2.jpg'); + @unlink(OC::$SERVERROOT.'/tests/data/testimage2.png'); + @unlink(OC::$SERVERROOT.'/tests/data/testimage2.jpg'); } public function testGetMimeTypeForFile() { @@ -236,4 +236,24 @@ class Test_Image extends PHPUnit_Framework_TestCase { $this->assertEquals(200, $img->width()); $this->assertEquals(200, $img->height()); } + + function convertDataProvider() { + return array( + array( 'image/gif'), + array( 'image/jpeg'), + array( 'image/png'), + ); + } + + /** + * @dataProvider convertDataProvider + */ + public function testConvert($mimeType) { + $img = new \OC_Image(OC::$SERVERROOT.'/tests/data/testimage.png'); + $tempFile = tempnam(sys_get_temp_dir(), 'img-test'); + + $img->save($tempFile, $mimeType); + $actualMimeType = \OC_Image::getMimeTypeForFile($tempFile); + $this->assertEquals($mimeType, $actualMimeType); + } } diff --git a/tests/lib/mail.php b/tests/lib/mail.php new file mode 100644 index 00000000000..3cc9868e25e --- /dev/null +++ b/tests/lib/mail.php @@ -0,0 +1,39 @@ +<?php +/** + * Copyright (c) 2014 Thomas Müller <deepdiver@owncloud.com> + * This file is licensed under the Affero General Public License version 3 or + * later. + * See the COPYING-README file. + */ + +class Test_Mail extends PHPUnit_Framework_TestCase { + + protected function setUp() + { + if (!function_exists('idn_to_ascii')) { + $this->markTestSkipped( + 'The intl extension is not available.' + ); + } + } + + /** + * @dataProvider buildAsciiEmailProvider + * @param $expected + * @param $address + */ + public function testBuildAsciiEmail($expected, $address) { + $actual = \OC_Mail::buildAsciiEmail($address); + $this->assertEquals($expected, $actual); + } + + function buildAsciiEmailProvider() { + return array( + array('info@example.com', 'info@example.com'), + array('info@xn--cjr6vy5ejyai80u.com', 'info@國際化域名.com'), + array('info@xn--mller-kva.de', 'info@müller.de'), + array('info@xn--mller-kva.xn--mller-kva.de', 'info@müller.müller.de'), + ); + } + +} diff --git a/tests/lib/preview.php b/tests/lib/preview.php index 353b66fd6d6..4ef61fb8257 100644 --- a/tests/lib/preview.php +++ b/tests/lib/preview.php @@ -10,66 +10,73 @@ namespace Test; class Preview extends \PHPUnit_Framework_TestCase { - public function testIsPreviewDeleted() { - $user = $this->initFS(); + /** + * @var string + */ + private $user; + + /** + * @var \OC\Files\View + */ + private $rootView; + + public function setUp() { + $this->user = $this->initFS(); - $rootView = new \OC\Files\View(''); - $rootView->mkdir('/'.$user); - $rootView->mkdir('/'.$user.'/files'); + $this->rootView = new \OC\Files\View(''); + $this->rootView->mkdir('/'.$this->user); + $this->rootView->mkdir('/'.$this->user.'/files'); + } + + public function testIsPreviewDeleted() { - $samplefile = '/'.$user.'/files/test.txt'; + $sampleFile = '/'.$this->user.'/files/test.txt'; - $rootView->file_put_contents($samplefile, 'dummy file data'); + $this->rootView->file_put_contents($sampleFile, 'dummy file data'); $x = 50; $y = 50; - $preview = new \OC\Preview($user, 'files/', 'test.txt', $x, $y); + $preview = new \OC\Preview($this->user, 'files/', 'test.txt', $x, $y); $preview->getPreview(); - $fileinfo = $rootView->getFileInfo($samplefile); - $fileid = $fileinfo['fileid']; + $fileInfo = $this->rootView->getFileInfo($sampleFile); + $fileId = $fileInfo['fileid']; - $thumbcachefile = '/' . $user . '/' . \OC\Preview::THUMBNAILS_FOLDER . '/' . $fileid . '/' . $x . '-' . $y . '.png'; + $thumbCacheFile = '/' . $this->user . '/' . \OC\Preview::THUMBNAILS_FOLDER . '/' . $fileId . '/' . $x . '-' . $y . '.png'; - $this->assertEquals($rootView->file_exists($thumbcachefile), true); + $this->assertEquals($this->rootView->file_exists($thumbCacheFile), true); $preview->deletePreview(); - $this->assertEquals($rootView->file_exists($thumbcachefile), false); + $this->assertEquals($this->rootView->file_exists($thumbCacheFile), false); } public function testAreAllPreviewsDeleted() { - $user = $this->initFS(); - $rootView = new \OC\Files\View(''); - $rootView->mkdir('/'.$user); - $rootView->mkdir('/'.$user.'/files'); + $sampleFile = '/'.$this->user.'/files/test.txt'; - $samplefile = '/'.$user.'/files/test.txt'; - - $rootView->file_put_contents($samplefile, 'dummy file data'); + $this->rootView->file_put_contents($sampleFile, 'dummy file data'); $x = 50; $y = 50; - $preview = new \OC\Preview($user, 'files/', 'test.txt', $x, $y); + $preview = new \OC\Preview($this->user, 'files/', 'test.txt', $x, $y); $preview->getPreview(); - $fileinfo = $rootView->getFileInfo($samplefile); - $fileid = $fileinfo['fileid']; + $fileInfo = $this->rootView->getFileInfo($sampleFile); + $fileId = $fileInfo['fileid']; - $thumbcachefolder = '/' . $user . '/' . \OC\Preview::THUMBNAILS_FOLDER . '/' . $fileid . '/'; + $thumbCacheFolder = '/' . $this->user . '/' . \OC\Preview::THUMBNAILS_FOLDER . '/' . $fileId . '/'; - $this->assertEquals($rootView->is_dir($thumbcachefolder), true); + $this->assertEquals($this->rootView->is_dir($thumbCacheFolder), true); $preview->deleteAllPreviews(); - $this->assertEquals($rootView->is_dir($thumbcachefolder), false); + $this->assertEquals($this->rootView->is_dir($thumbCacheFolder), false); } public function testIsMaxSizeWorking() { - $user = $this->initFS(); $maxX = 250; $maxY = 250; @@ -77,15 +84,11 @@ class Preview extends \PHPUnit_Framework_TestCase { \OC_Config::setValue('preview_max_x', $maxX); \OC_Config::setValue('preview_max_y', $maxY); - $rootView = new \OC\Files\View(''); - $rootView->mkdir('/'.$user); - $rootView->mkdir('/'.$user.'/files'); - - $samplefile = '/'.$user.'/files/test.txt'; + $sampleFile = '/'.$this->user.'/files/test.txt'; - $rootView->file_put_contents($samplefile, 'dummy file data'); + $this->rootView->file_put_contents($sampleFile, 'dummy file data'); - $preview = new \OC\Preview($user, 'files/', 'test.txt', 1000, 1000); + $preview = new \OC\Preview($this->user, 'files/', 'test.txt', 1000, 1000); $image = $preview->getPreview(); $this->assertEquals($image->width(), $maxX); @@ -108,18 +111,13 @@ class Preview extends \PHPUnit_Framework_TestCase { * @dataProvider txtBlacklist */ public function testIsTransparent($extension, $data, $expectedResult) { - $user = $this->initFS(); - - $rootView = new \OC\Files\View(''); - $rootView->mkdir('/'.$user); - $rootView->mkdir('/'.$user.'/files'); $x = 32; $y = 32; - $sample = '/'.$user.'/files/test.'.$extension; - $rootView->file_put_contents($sample, $data); - $preview = new \OC\Preview($user, 'files/', 'test.'.$extension, $x, $y); + $sample = '/'.$this->user.'/files/test.'.$extension; + $this->rootView->file_put_contents($sample, $data); + $preview = new \OC\Preview($this->user, 'files/', 'test.'.$extension, $x, $y); $image = $preview->getPreview(); $resource = $image->resource(); @@ -133,6 +131,64 @@ class Preview extends \PHPUnit_Framework_TestCase { ); } + public function testCreationFromCached() { + + $sampleFile = '/'.$this->user.'/files/test.txt'; + + $this->rootView->file_put_contents($sampleFile, 'dummy file data'); + + // create base preview + $x = 150; + $y = 150; + + $preview = new \OC\Preview($this->user, 'files/', 'test.txt', $x, $y); + $preview->getPreview(); + + $fileInfo = $this->rootView->getFileInfo($sampleFile); + $fileId = $fileInfo['fileid']; + + $thumbCacheFile = '/' . $this->user . '/' . \OC\Preview::THUMBNAILS_FOLDER . '/' . $fileId . '/' . $x . '-' . $y . '.png'; + + $this->assertEquals($this->rootView->file_exists($thumbCacheFile), true); + + + // create smaller previews + $preview = new \OC\Preview($this->user, 'files/', 'test.txt', 50, 50); + $isCached = $preview->isCached($fileId); + + $this->assertEquals($this->user . '/' . \OC\Preview::THUMBNAILS_FOLDER . '/' . $fileId . '/150-150.png', $isCached); + } + + /* + public function testScalingUp() { + + $sampleFile = '/'.$this->user.'/files/test.txt'; + + $this->rootView->file_put_contents($sampleFile, 'dummy file data'); + + // create base preview + $x = 150; + $y = 150; + + $preview = new \OC\Preview($this->user, 'files/', 'test.txt', $x, $y); + $preview->getPreview(); + + $fileInfo = $this->rootView->getFileInfo($sampleFile); + $fileId = $fileInfo['fileid']; + + $thumbCacheFile = '/' . $this->user . '/' . \OC\Preview::THUMBNAILS_FOLDER . '/' . $fileId . '/' . $x . '-' . $y . '.png'; + + $this->assertEquals($this->rootView->file_exists($thumbCacheFile), true); + + + // create bigger previews - with scale up + $preview = new \OC\Preview($this->user, 'files/', 'test.txt', 250, 250); + $isCached = $preview->isCached($fileId); + + $this->assertEquals($this->user . '/' . \OC\Preview::THUMBNAILS_FOLDER . '/' . $fileId . '/150-150.png', $isCached); + } + */ + private function initFS() { // create a new user with his own filesystem view // this gets called by each test in this test class diff --git a/tests/lib/public/ocpconfig.php b/tests/lib/public/ocpconfig.php new file mode 100644 index 00000000000..43a9ca625ee --- /dev/null +++ b/tests/lib/public/ocpconfig.php @@ -0,0 +1,37 @@ +<?php +/** + * ownCloud + * + * @author Thomas Müller + * @copyright 2014 Thomas Müller thomas.mueller@tmit.eu + * + * 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_OCPConfig extends PHPUnit_Framework_TestCase +{ + + public function testSetAppValueIfSetToNull() { + + $key = uniqid("key-"); + + $result = \OCP\Config::setAppValue('unit-test', $key, null); + $this->assertTrue($result); + + $result = \OCP\Config::setAppValue('unit-test', $key, '12'); + $this->assertTrue($result); + + } + +} diff --git a/tests/lib/request.php b/tests/lib/request.php index 1d77acc70ae..bff84e1b03f 100644 --- a/tests/lib/request.php +++ b/tests/lib/request.php @@ -135,4 +135,141 @@ class Test_Request extends PHPUnit_Framework_TestCase { ), ); } + + public function testInsecureServerHost() { + unset($_SERVER['HTTP_X_FORWARDED_HOST']); + unset($_SERVER['HTTP_HOST']); + unset($_SERVER['SERVER_NAME']); + $_SERVER['SERVER_NAME'] = 'from.server.name:8080'; + $host = OC_Request::insecureServerHost(); + $this->assertEquals('from.server.name:8080', $host); + + $_SERVER['HTTP_HOST'] = 'from.host.header:8080'; + $host = OC_Request::insecureServerHost(); + $this->assertEquals('from.host.header:8080', $host); + + $_SERVER['HTTP_X_FORWARDED_HOST'] = 'from.forwarded.host:8080'; + $host = OC_Request::insecureServerHost(); + $this->assertEquals('from.forwarded.host:8080', $host); + + $_SERVER['HTTP_X_FORWARDED_HOST'] = 'from.forwarded.host2:8080,another.one:9000'; + $host = OC_Request::insecureServerHost(); + $this->assertEquals('from.forwarded.host2:8080', $host); + + // clean up + unset($_SERVER['HTTP_X_FORWARDED_HOST']); + unset($_SERVER['HTTP_HOST']); + unset($_SERVER['SERVER_NAME']); + } + + public function testGetOverwriteHost() { + unset($_SERVER['REMOTE_ADDR']); + OC_Config::deleteKey('overwritecondaddr'); + OC_Config::deleteKey('overwritehost'); + $host = OC_Request::getOverwriteHost(); + $this->assertNull($host); + + OC_Config::setValue('overwritehost', ''); + $host = OC_Request::getOverwriteHost(); + $this->assertNull($host); + + OC_Config::setValue('overwritehost', 'host.one.test:8080'); + $host = OC_Request::getOverwriteHost(); + $this->assertEquals('host.one.test:8080', $host); + + $_SERVER['REMOTE_ADDR'] = 'somehost.test:8080'; + OC_Config::setValue('overwritecondaddr', '^somehost\..*$'); + $host = OC_Request::getOverwriteHost(); + $this->assertEquals('host.one.test:8080', $host); + + OC_Config::setValue('overwritecondaddr', '^somethingelse.*$'); + $host = OC_Request::getOverwriteHost(); + $this->assertNull($host); + + // clean up + unset($_SERVER['REMOTE_ADDR']); + OC_Config::deleteKey('overwritecondaddr'); + OC_Config::deleteKey('overwritehost'); + } + + /** + * @dataProvider trustedDomainDataProvider + */ + public function testIsTrustedDomain($trustedDomains, $testDomain, $result) { + OC_Config::deleteKey('trusted_domains'); + if ($trustedDomains !== null) { + OC_Config::setValue('trusted_domains', $trustedDomains); + } + + $this->assertEquals($result, OC_Request::isTrustedDomain($testDomain)); + + // clean up + OC_Config::deleteKey('trusted_domains'); + } + + public function trustedDomainDataProvider() { + $trustedHostTestList = array('host.one.test:8080', 'host.two.test:8080'); + return array( + // empty defaults to true + array(null, 'host.one.test:8080', true), + array('', 'host.one.test:8080', true), + array(array(), 'host.one.test:8080', true), + + // trust list when defined + array($trustedHostTestList, 'host.two.test:8080', true), + array($trustedHostTestList, 'host.two.test:9999', false), + array($trustedHostTestList, 'host.three.test:8080', false), + + // trust localhost regardless of trust list + array($trustedHostTestList, 'localhost', true), + array($trustedHostTestList, 'localhost:8080', true), + array($trustedHostTestList, '127.0.0.1', true), + array($trustedHostTestList, '127.0.0.1:8080', true), + + // do not trust invalid localhosts + array($trustedHostTestList, 'localhost:1:2', false), + array($trustedHostTestList, 'localhost: evil.host', false), + ); + } + + public function testServerHost() { + OC_Config::deleteKey('overwritecondaddr'); + OC_Config::setValue('overwritehost', 'overwritten.host:8080'); + OC_Config::setValue( + 'trusted_domains', + array( + 'trusted.host:8080', + 'second.trusted.host:8080' + ) + ); + $_SERVER['HTTP_HOST'] = 'trusted.host:8080'; + + // CLI always gives localhost + $oldCLI = OC::$CLI; + OC::$CLI = true; + $host = OC_Request::serverHost(); + $this->assertEquals('localhost', $host); + OC::$CLI = false; + + // overwritehost overrides trusted domain + $host = OC_Request::serverHost(); + $this->assertEquals('overwritten.host:8080', $host); + + // trusted domain returned when used + OC_Config::deleteKey('overwritehost'); + $host = OC_Request::serverHost(); + $this->assertEquals('trusted.host:8080', $host); + + // trusted domain returned when untrusted one in header + $_SERVER['HTTP_HOST'] = 'untrusted.host:8080'; + OC_Config::deleteKey('overwritehost'); + $host = OC_Request::serverHost(); + $this->assertEquals('trusted.host:8080', $host); + + // clean up + OC_Config::deleteKey('overwritecondaddr'); + OC_Config::deleteKey('overwritehost'); + unset($_SERVER['HTTP_HOST']); + OC::$CLI = $oldCLI; + } } diff --git a/tests/lib/share/helper.php b/tests/lib/share/helper.php new file mode 100644 index 00000000000..367507417a0 --- /dev/null +++ b/tests/lib/share/helper.php @@ -0,0 +1,54 @@ +<?php +/** +* ownCloud +* +* @author Bjoern Schiessle +* @copyright 2014 Bjoern Schiessle <schiessle@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_Share_Helper extends PHPUnit_Framework_TestCase { + + public function expireDateProvider() { + return array( + // no default expire date, we take the users expire date + array(array('defaultExpireDateSet' => false), 2000000000, 2000010000, 2000010000), + // no default expire date and no user defined expire date, return false + array(array('defaultExpireDateSet' => false), 2000000000, null, false), + // unenforced expire data and no user defined expire date, take default expire date + array(array('defaultExpireDateSet' => true, 'expireAfterDays' => 1, 'enforceExpireDate' => false), 2000000000, null, 2000086400), + // enforced expire date and no user defined expire date, take default expire date + array(array('defaultExpireDateSet' => true, 'expireAfterDays' => 1, 'enforceExpireDate' => true), 2000000000, null, 2000086400), + // unenforced expire date and user defined date > default expire date, take users expire date + array(array('defaultExpireDateSet' => true, 'expireAfterDays' => 1, 'enforceExpireDate' => false), 2000000000, 2000100000, 2000100000), + // unenforced expire date and user expire date < default expire date, take users expire date + array(array('defaultExpireDateSet' => true, 'expireAfterDays' => 1, 'enforceExpireDate' => false), 2000000000, 2000010000, 2000010000), + // enforced expire date and user expire date < default expire date, take users expire date + array(array('defaultExpireDateSet' => true, 'expireAfterDays' => 1, 'enforceExpireDate' => true), 2000000000, 2000010000, 2000010000), + // enforced expire date and users expire date > default expire date, take default expire date + array(array('defaultExpireDateSet' => true, 'expireAfterDays' => 1, 'enforceExpireDate' => true), 2000000000, 2000100000, 2000086400), + ); + } + + /** + * @dataProvider expireDateProvider + */ + public function testCalculateExpireDate($defaultExpireSettings, $creationTime, $userExpireDate, $expected) { + $result = \OC\Share\Helper::calculateExpireDate($defaultExpireSettings, $creationTime, $userExpireDate); + $this->assertSame($expected, $result); + } + + +} diff --git a/tests/lib/share/share.php b/tests/lib/share/share.php index b5cba9430aa..aae91fa1087 100644 --- a/tests/lib/share/share.php +++ b/tests/lib/share/share.php @@ -282,7 +282,7 @@ class Test_Share extends PHPUnit_Framework_TestCase { OC_User::setUserId($this->user2); $this->assertEquals(array(OCP\PERMISSION_READ), OCP\Share::getItemSharedWith('test', 'test.txt', Test_Share_Backend::FORMAT_PERMISSIONS)); OC_User::setUserId($this->user3); - $this->assertFalse(OCP\Share::getItemSharedWith('test', 'test.txt')); + $this->assertSame(array(), OCP\Share::getItemSharedWith('test', 'test.txt')); // Reshare again, and then have owner unshare OC_User::setUserId($this->user1); @@ -292,9 +292,9 @@ class Test_Share extends PHPUnit_Framework_TestCase { OC_User::setUserId($this->user1); $this->assertTrue(OCP\Share::unshare('test', 'test.txt', OCP\Share::SHARE_TYPE_USER, $this->user2)); OC_User::setUserId($this->user2); - $this->assertFalse(OCP\Share::getItemSharedWith('test', 'test.txt')); + $this->assertSame(array(), OCP\Share::getItemSharedWith('test', 'test.txt')); OC_User::setUserId($this->user3); - $this->assertFalse(OCP\Share::getItemSharedWith('test', 'test.txt')); + $this->assertSame(array(), OCP\Share::getItemSharedWith('test', 'test.txt')); // Attempt target conflict OC_User::setUserId($this->user1); @@ -325,7 +325,7 @@ class Test_Share extends PHPUnit_Framework_TestCase { ); OC_User::setUserId($this->user2); - $this->assertFalse( + $this->assertSame(array(), OCP\Share::getItemSharedWith('test', 'test.txt', Test_Share_Backend::FORMAT_SOURCE), 'Failed asserting that user 2 no longer has access to test.txt after expiration.' ); @@ -526,13 +526,13 @@ class Test_Share extends PHPUnit_Framework_TestCase { ); OC_User::setUserId($this->user2); - $this->assertFalse( + $this->assertSame(array(), OCP\Share::getItemSharedWith('test', 'test.txt', Test_Share_Backend::FORMAT_SOURCE), 'Failed asserting that user 2 no longer has access to test.txt after expiration.' ); OC_User::setUserId($this->user3); - $this->assertFalse( + $this->assertSame(array(), OCP\Share::getItemSharedWith('test', 'test.txt', Test_Share_Backend::FORMAT_SOURCE), 'Failed asserting that user 3 no longer has access to test.txt after expiration.' ); diff --git a/tests/lib/template.php b/tests/lib/template.php index b4f1a4c4053..eedf688721d 100644 --- a/tests/lib/template.php +++ b/tests/lib/template.php @@ -27,42 +27,32 @@ class Test_TemplateFunctions extends PHPUnit_Framework_TestCase { $loader->load('OC_Template'); } - public function testP() { - // FIXME: do we need more testcases? - $htmlString = "<script>alert('xss');</script>"; - ob_start(); - p($htmlString); - $result = ob_get_clean(); + public function testPJavaScript() { + $this->expectOutputString('<img onload="alert(1)" />'); + p('<img onload="alert(1)" />'); + } - $this->assertEquals("<script>alert('xss');</script>", $result); + public function testPJavaScriptWithScriptTags() { + $this->expectOutputString('<script>alert('Hacked!');</script>'); + p("<script>alert('Hacked!');</script>"); } public function testPNormalString() { - $normalString = "This is a good string!"; - ob_start(); - p($normalString); - $result = ob_get_clean(); - - $this->assertEquals("This is a good string!", $result); + $string = 'This is a good string without HTML.'; + $this->expectOutputString($string); + p($string); } public function testPrintUnescaped() { $htmlString = "<script>alert('xss');</script>"; - - ob_start(); + $this->expectOutputString($htmlString); print_unescaped($htmlString); - $result = ob_get_clean(); - - $this->assertEquals($htmlString, $result); } public function testPrintUnescapedNormalString() { - $normalString = "This is a good string!"; - ob_start(); - print_unescaped($normalString); - $result = ob_get_clean(); - - $this->assertEquals("This is a good string!", $result); + $string = 'This is a good string!'; + $this->expectOutputString($string); + print_unescaped($string); } // --------------------------------------------------------------------------- diff --git a/tests/lib/urlgenerator.php b/tests/lib/urlgenerator.php index 875a7f06580..65c7fb56943 100644 --- a/tests/lib/urlgenerator.php +++ b/tests/lib/urlgenerator.php @@ -8,21 +8,79 @@ class Test_Urlgenerator extends PHPUnit_Framework_TestCase { + /** + * @small + * @brief test linkTo URL construction + * @dataProvider provideDocRootAppUrlParts + */ + public function testLinkToDocRoot($app, $file, $args, $expectedResult) { + \OC::$WEBROOT = ''; + $config = $this->getMock('\OCP\IConfig'); + $urlGenerator = new \OC\URLGenerator($config); + $result = $urlGenerator->linkTo($app, $file, $args); + + $this->assertEquals($expectedResult, $result); + } + + /** + * @small + * @brief test linkTo URL construction in sub directory + * @dataProvider provideSubDirAppUrlParts + */ + public function testLinkToSubDir($app, $file, $args, $expectedResult) { + \OC::$WEBROOT = '/owncloud'; + $config = $this->getMock('\OCP\IConfig'); + $urlGenerator = new \OC\URLGenerator($config); + $result = $urlGenerator->linkTo($app, $file, $args); + + $this->assertEquals($expectedResult, $result); + } + + public function provideDocRootAppUrlParts() { + return array( + array('files', 'index.php', array(), '/index.php/apps/files'), + array('files', 'index.php', array('trut' => 'trat', 'dut' => 'dat'), '/index.php/apps/files?trut=trat&dut=dat'), + array('', 'index.php', array('trut' => 'trat', 'dut' => 'dat'), '/index.php?trut=trat&dut=dat'), + ); + } + + public function provideSubDirAppUrlParts() { + return array( + array('files', 'index.php', array(), '/owncloud/index.php/apps/files'), + array('files', 'index.php', array('trut' => 'trat', 'dut' => 'dat'), '/owncloud/index.php/apps/files?trut=trat&dut=dat'), + array('', 'index.php', array('trut' => 'trat', 'dut' => 'dat'), '/owncloud/index.php?trut=trat&dut=dat'), + ); + } /** * @small * @brief test absolute URL construction - * @dataProvider provideURLs + * @dataProvider provideDocRootURLs */ - function testGetAbsoluteURL($url, $expectedResult) { + function testGetAbsoluteURLDocRoot($url, $expectedResult) { + \OC::$WEBROOT = ''; $urlGenerator = new \OC\URLGenerator(null); $result = $urlGenerator->getAbsoluteURL($url); $this->assertEquals($expectedResult, $result); } - public function provideURLs() { + /** + * @small + * @brief test absolute URL construction + * @dataProvider provideSubDirURLs + */ + function testGetAbsoluteURLSubDir($url, $expectedResult) { + + \OC::$WEBROOT = '/owncloud'; + $urlGenerator = new \OC\URLGenerator(null); + $result = $urlGenerator->getAbsoluteURL($url); + + $this->assertEquals($expectedResult, $result); + } + + public function provideDocRootURLs() { return array( array("index.php", "http://localhost/index.php"), array("/index.php", "http://localhost/index.php"), @@ -30,5 +88,14 @@ class Test_Urlgenerator extends PHPUnit_Framework_TestCase { array("apps/index.php", "http://localhost/apps/index.php"), ); } + + public function provideSubDirURLs() { + return array( + array("index.php", "http://localhost/owncloud/index.php"), + array("/index.php", "http://localhost/owncloud/index.php"), + array("/apps/index.php", "http://localhost/owncloud/apps/index.php"), + array("apps/index.php", "http://localhost/owncloud/apps/index.php"), + ); + } } diff --git a/tests/lib/user/manager.php b/tests/lib/user/manager.php index ad1ac9e12f2..fd0931af7e4 100644 --- a/tests/lib/user/manager.php +++ b/tests/lib/user/manager.php @@ -190,8 +190,8 @@ class Manager extends \PHPUnit_Framework_TestCase { $result = $manager->search('fo'); $this->assertEquals(2, count($result)); - $this->assertEquals('afoo', $result[0]->getUID()); - $this->assertEquals('foo', $result[1]->getUID()); + $this->assertEquals('afoo', array_shift($result)->getUID()); + $this->assertEquals('foo', array_shift($result)->getUID()); } public function testSearchTwoBackendLimitOffset() { @@ -210,7 +210,7 @@ class Manager extends \PHPUnit_Framework_TestCase { $backend2 = $this->getMock('\OC_User_Dummy'); $backend2->expects($this->once()) ->method('getUsers') - ->with($this->equalTo('fo'), $this->equalTo(1), $this->equalTo(0)) + ->with($this->equalTo('fo'), $this->equalTo(3), $this->equalTo(1)) ->will($this->returnValue(array('foo3'))); $manager = new \OC\User\Manager(); @@ -219,9 +219,9 @@ class Manager extends \PHPUnit_Framework_TestCase { $result = $manager->search('fo', 3, 1); $this->assertEquals(3, count($result)); - $this->assertEquals('foo1', $result[0]->getUID()); - $this->assertEquals('foo2', $result[1]->getUID()); - $this->assertEquals('foo3', $result[2]->getUID()); + $this->assertEquals('foo1', array_shift($result)->getUID()); + $this->assertEquals('foo2', array_shift($result)->getUID()); + $this->assertEquals('foo3', array_shift($result)->getUID()); } public function testCreateUserSingleBackendNotExists() { diff --git a/tests/lib/util.php b/tests/lib/util.php index ee336aa1118..c4780cc5f48 100644 --- a/tests/lib/util.php +++ b/tests/lib/util.php @@ -43,15 +43,32 @@ class Test_Util extends PHPUnit_Framework_TestCase { } function testSanitizeHTML() { + $badArray = array( + 'While it is unusual to pass an array', + 'this function actually <blink>supports</blink> it.', + 'And therefore there needs to be a <script>alert("Unit"+\'test\')</script> for it!' + ); + $goodArray = array( + 'While it is unusual to pass an array', + 'this function actually <blink>supports</blink> it.', + 'And therefore there needs to be a <script>alert("Unit"+'test')</script> for it!' + ); + $result = OC_Util::sanitizeHTML($badArray); + $this->assertEquals($goodArray, $result); + + $badString = '<img onload="alert(1)" />'; + $result = OC_Util::sanitizeHTML($badString); + $this->assertEquals('<img onload="alert(1)" />', $result); + $badString = "<script>alert('Hacked!');</script>"; $result = OC_Util::sanitizeHTML($badString); - $this->assertEquals("<script>alert('Hacked!');</script>", $result); + $this->assertEquals('<script>alert('Hacked!');</script>', $result); - $goodString = "This is an harmless string."; + $goodString = 'This is a good string without HTML.'; $result = OC_Util::sanitizeHTML($goodString); - $this->assertEquals("This is an harmless string.", $result); + $this->assertEquals('This is a good string without HTML.', $result); } - + function testEncodePath(){ $component = '/§#@test%&^ä/-child'; $result = OC_Util::encodePath($component); diff --git a/tests/lib/utilcheckserver.php b/tests/lib/utilcheckserver.php new file mode 100644 index 00000000000..155d617c4ad --- /dev/null +++ b/tests/lib/utilcheckserver.php @@ -0,0 +1,108 @@ +<?php +/** + * Copyright (c) 2014 Vincent Petry <pvince81@owncloud.com> + * This file is licensed under the Affero General Public License version 3 or + * later. + * See the COPYING-README file. + */ + +/** + * Tests for server check functions + */ +class Test_Util_CheckServer extends PHPUnit_Framework_TestCase { + + private $datadir; + + public function setUp() { + $this->datadir = \OC_Config::getValue('datadirectory', \OC::$SERVERROOT . '/data'); + + file_put_contents($this->datadir . '/.ocdata', ''); + } + + public function tearDown() { + // clean up + @unlink($this->datadir . '/.ocdata'); + } + + /** + * Test that checkServer() returns no errors in the regular case. + */ + public function testCheckServer() { + $result = \OC_Util::checkServer(); + $this->assertEmpty($result); + } + + /** + * Test that checkServer() does not check the data dir validity + * when the server is not installed yet (else the setup cannot + * be run...) + */ + public function testCheckServerSkipDataDirValidityOnSetup() { + // simulate old version that didn't have it + unlink($this->datadir . '/.ocdata'); + + $session = \OC::$server->getSession(); + $oldInstalled = \OC_Config::getValue('installed', false); + + // simulate that the server isn't setup yet + \OC_Config::setValue('installed', false); + + // even though ".ocdata" is missing, the error isn't + // triggered to allow setup to run + $result = \OC_Util::checkServer(); + $this->assertEmpty($result); + + // restore config + \OC_Config::setValue('installed', $oldInstalled); + } + + /** + * Test that checkServer() does not check the data dir validity + * when an upgrade is required (else the upgrade cannot be + * performed...) + */ + public function testCheckServerSkipDataDirValidityOnUpgrade() { + // simulate old version that didn't have it + unlink($this->datadir . '/.ocdata'); + + $session = \OC::$server->getSession(); + $oldCurrentVersion = $session->get('OC_Version'); + $oldInstallVersion = \OC_Config::getValue('version', '0.0.0'); + + // upgrade condition to simulate needUpgrade() === true + $session->set('OC_Version', array(6, 0, 0, 2)); + \OC_Config::setValue('version', '6.0.0.1'); + + // even though ".ocdata" is missing, the error isn't + // triggered to allow for upgrade + $result = \OC_Util::checkServer(); + $this->assertEmpty($result); + + // restore versions + $session->set('OC_Version', $oldCurrentVersion); + \OC_Config::setValue('version', $oldInstallVersion); + } + + /** + * Test that checkDataDirectoryValidity returns no error + * when ".ocdata" is present. + */ + public function testCheckDataDirValidity() { + $result = \OC_Util::checkDataDirectoryValidity($this->datadir); + $this->assertEmpty($result); + } + + /** + * Test that checkDataDirectoryValidity and checkServer + * both return an error when ".ocdata" is missing. + */ + public function testCheckDataDirValidityWhenFileMissing() { + unlink($this->datadir . '/.ocdata'); + $result = \OC_Util::checkDataDirectoryValidity($this->datadir); + $this->assertEquals(1, count($result)); + + $result = \OC_Util::checkServer(); + $this->assertEquals(1, count($result)); + } + +} |