diff options
author | Robin Appelman <icewind@owncloud.com> | 2014-02-07 13:42:18 +0100 |
---|---|---|
committer | Robin Appelman <icewind@owncloud.com> | 2014-02-07 13:45:59 +0100 |
commit | b537d90e58913be203fd96f31b624559be00abeb (patch) | |
tree | 9af6c432b3b503303f1315f82f602844664f837d /tests/lib | |
parent | b35b22977cfc9412278ae70b49c402a95efca19e (diff) | |
parent | b9e724d4ae7635435b3cc7793237c3ab9fe2a1c0 (diff) | |
download | nextcloud-server-b537d90e58913be203fd96f31b624559be00abeb.tar.gz nextcloud-server-b537d90e58913be203fd96f31b624559be00abeb.zip |
use the 'new' server container for appconfig
Diffstat (limited to 'tests/lib')
61 files changed, 2829 insertions, 401 deletions
diff --git a/tests/lib/api.php b/tests/lib/api.php new file mode 100644 index 00000000000..9c4324e63e0 --- /dev/null +++ b/tests/lib/api.php @@ -0,0 +1,141 @@ +<?php +/** + * Copyright (c) 2013 Tom Needham <tom@owncloud.com> + * This file is licensed under the Affero General Public License version 3 or + * later. + * See the COPYING-README file. + */ + +class Test_API extends PHPUnit_Framework_TestCase { + + // Helps build a response variable + function buildResponse($shipped, $data, $code, $message=null) { + return array( + 'shipped' => $shipped, + 'response' => new OC_OCS_Result($data, $code, $message), + 'app' => uniqid('testapp_', true), + ); + } + + // Validate details of the result + function checkResult($result, $success) { + // Check response is of correct type + $this->assertInstanceOf('OC_OCS_Result', $result); + // Check if it succeeded + /** @var $result OC_OCS_Result */ + $this->assertEquals($success, $result->succeeded()); + } + + function dataProviderTestOneResult() { + return array( + array(100, true), + array(101, true), + array(997, false), + ); + } + + /** + * @dataProvider dataProviderTestOneResult + * + * @param $statusCode + * @param $succeeded + */ + public function testOneResult($statusCode, $succeeded) { + // Setup some data arrays + $data1 = array( + 'users' => array( + 'tom' => array( + 'key' => 'value', + ), + 'frank' => array( + 'key' => 'value', + ), + )); + + // Test merging one success result + $response = $this->buildResponse(true, $data1, $statusCode); + $result = OC_API::mergeResponses(array($response)); + $this->assertEquals($response['response'], $result); + $this->checkResult($result, $succeeded); + } + + function dataProviderTestMergeResponses() { + return array( + // Two shipped success results + array(true, 100, true, 100, true), + // Two shipped results, one success and one failure + array(true, 100, true, 998, false), + // Two shipped results, both failure + array(true, 997, true, 998, false), + // Two third party success results + array(false, 100, false, 100, true), + // Two third party results, one success and one failure + array(false, 100, false, 998, false), + // Two third party results, both failure + array(false, 997, false, 998, false), + // One of each, both success + array(false, 100, true, 100, true), + array(true, 100, false, 100, true), + // One of each, both failure + array(false, 997, true, 998, false), + // One of each, shipped success + array(false, 997, true, 100, true), + // One of each, third party success + array(false, 100, true, 998, false), + ); + } + /** + * @dataProvider dataProviderTestMergeResponses + * + * Test the merging of multiple responses + * @param $statusCode1 + * @param $statusCode2 + * @param $succeeded + */ + public function testMultipleMergeResponses($shipped1, $statusCode1, $shipped2, $statusCode2, $succeeded){ + // Tests that app responses are merged correctly + // Setup some data arrays + $data1 = array( + 'users' => array( + 'tom' => array( + 'key' => 'value', + ), + 'frank' => array( + 'key' => 'value', + ), + )); + + $data2 = array( + 'users' => array( + 'tom' => array( + 'key' => 'newvalue', + ), + 'jan' => array( + 'key' => 'value', + ), + )); + + // Two shipped success results + $result = OC_API::mergeResponses(array( + $this->buildResponse($shipped1, $data1, $statusCode1, "message1"), + $this->buildResponse($shipped2, $data2, $statusCode2, "message2"), + )); + $this->checkResult($result, $succeeded); + $resultData = $result->getData(); + $resultMeta = $result->getMeta(); + $resultStatusCode = $result->getStatusCode(); + + $this->assertArrayHasKey('jan', $resultData['users']); + + // check if the returned status message matches the selected status code + if ($resultStatusCode === 997) { + $this->assertEquals('message1', $resultMeta['message']); + } elseif ($resultStatusCode === 998) { + $this->assertEquals('message2', $resultMeta['message']); + } elseif ($resultStatusCode === 100) { + $this->assertEquals(null, $resultMeta['message']); + } + + } + +} diff --git a/tests/lib/app.php b/tests/lib/app.php index 52eade90a6e..49f40f089bb 100644 --- a/tests/lib/app.php +++ b/tests/lib/app.php @@ -79,4 +79,17 @@ class Test_App extends PHPUnit_Framework_TestCase { $this->assertFalse(OC_App::isAppVersionCompatible($oc, $app)); } + /** + * Tests that the app order is correct + */ + public function testGetEnabledAppsIsSorted() { + $apps = \OC_App::getEnabledApps(true); + // copy array + $sortedApps = $apps; + sort($sortedApps); + // 'files' is always on top + unset($sortedApps[array_search('files', $sortedApps)]); + array_unshift($sortedApps, 'files'); + $this->assertEquals($sortedApps, $apps); + } } diff --git a/tests/lib/appconfig.php b/tests/lib/appconfig.php index 1f605263560..29b29778fd2 100644 --- a/tests/lib/appconfig.php +++ b/tests/lib/appconfig.php @@ -36,7 +36,7 @@ class Test_Appconfig extends PHPUnit_Framework_TestCase { } public function testGetApps() { - $query = \OC_DB::prepare('SELECT DISTINCT `appid` FROM `*PREFIX*appconfig`'); + $query = \OC_DB::prepare('SELECT DISTINCT `appid` FROM `*PREFIX*appconfig` ORDER BY `appid`'); $result = $query->execute(); $expected = array(); while ($row = $result->fetchRow()) { diff --git a/tests/lib/appframework/AppTest.php b/tests/lib/appframework/AppTest.php index 80abaefc43b..3628e4ceab2 100644 --- a/tests/lib/appframework/AppTest.php +++ b/tests/lib/appframework/AppTest.php @@ -38,9 +38,9 @@ class AppTest extends \PHPUnit_Framework_TestCase { private $controllerMethod; protected function setUp() { - $this->container = new \OC\AppFramework\DependencyInjection\DIContainer('test'); + $this->container = new \OC\AppFramework\DependencyInjection\DIContainer('test', array()); $this->controller = $this->getMockBuilder( - 'OC\AppFramework\Controller\Controller') + 'OCP\AppFramework\Controller') ->disableOriginalConstructor() ->getMock(); $this->dispatcher = $this->getMockBuilder( @@ -56,6 +56,7 @@ class AppTest extends \PHPUnit_Framework_TestCase { $this->container[$this->controllerName] = $this->controller; $this->container['Dispatcher'] = $this->dispatcher; + $this->container['urlParams'] = array(); } @@ -69,7 +70,7 @@ class AppTest extends \PHPUnit_Framework_TestCase { $this->expectOutputString(''); - App::main($this->controllerName, $this->controllerMethod, array(), + App::main($this->controllerName, $this->controllerMethod, $this->container); } diff --git a/tests/lib/appframework/controller/ControllerTest.php b/tests/lib/appframework/controller/ControllerTest.php index 4441bddfca9..f17d5f24aa5 100644 --- a/tests/lib/appframework/controller/ControllerTest.php +++ b/tests/lib/appframework/controller/ControllerTest.php @@ -25,13 +25,10 @@ namespace Test\AppFramework\Controller; use OC\AppFramework\Http\Request; -use OC\AppFramework\Controller\Controller; +use OCP\AppFramework\Controller; use OCP\AppFramework\Http\TemplateResponse; -//require_once __DIR__ . "/../classloader.php"; - - class ChildController extends Controller {}; class ControllerTest extends \PHPUnit_Framework_TestCase { @@ -40,7 +37,7 @@ class ControllerTest extends \PHPUnit_Framework_TestCase { * @var Controller */ private $controller; - private $api; + private $app; protected function setUp(){ $request = new Request( @@ -55,13 +52,13 @@ class ControllerTest extends \PHPUnit_Framework_TestCase { ) ); - $this->api = $this->getMock('OC\AppFramework\Core\API', + $this->app = $this->getMock('OC\AppFramework\DependencyInjection\DIContainer', array('getAppName'), array('test')); - $this->api->expects($this->any()) + $this->app->expects($this->any()) ->method('getAppName') ->will($this->returnValue('apptemplate_advanced')); - $this->controller = new ChildController($this->api, $request); + $this->controller = new ChildController($this->app, $request); } @@ -114,26 +111,6 @@ class ControllerTest extends \PHPUnit_Framework_TestCase { } - public function testRenderRenderAs(){ - $ocTpl = $this->getMock('Template', array('fetchPage')); - $ocTpl->expects($this->once()) - ->method('fetchPage'); - - $api = $this->getMock('OC\AppFramework\Core\API', - array('getAppName', 'getTemplate'), array('app')); - $api->expects($this->any()) - ->method('getAppName') - ->will($this->returnValue('app')); - $api->expects($this->once()) - ->method('getTemplate') - ->with($this->equalTo('home'), $this->equalTo('admin'), $this->equalTo('app')) - ->will($this->returnValue($ocTpl)); - - $this->controller = new ChildController($api, new Request()); - $this->controller->render('home', array(), 'admin')->render(); - } - - public function testRenderHeaders(){ $headers = array('one', 'two'); $response = $this->controller->render('', array(), '', $headers); diff --git a/tests/lib/appframework/dependencyinjection/DIContainerTest.php b/tests/lib/appframework/dependencyinjection/DIContainerTest.php index 25fdd202839..f3ebff0207f 100644 --- a/tests/lib/appframework/dependencyinjection/DIContainerTest.php +++ b/tests/lib/appframework/dependencyinjection/DIContainerTest.php @@ -29,23 +29,14 @@ namespace OC\AppFramework\DependencyInjection; use \OC\AppFramework\Http\Request; -//require_once(__DIR__ . "/../classloader.php"); - - class DIContainerTest extends \PHPUnit_Framework_TestCase { private $container; + private $api; protected function setUp(){ $this->container = new DIContainer('name'); - $this->api = $this->getMock('OC\AppFramework\Core\API', array('getTrans'), array('hi')); - } - - private function exchangeAPI(){ - $this->api->expects($this->any()) - ->method('getTrans') - ->will($this->returnValue('yo')); - $this->container['API'] = $this->api; + $this->api = $this->getMock('OC\AppFramework\Core\API', array(), array('hi')); } public function testProvidesAPI(){ @@ -87,12 +78,4 @@ class DIContainerTest extends \PHPUnit_Framework_TestCase { } - public function testMiddlewareDispatcherDoesNotIncludeTwigWhenTplDirectoryNotSet(){ - $this->container['Request'] = new Request(); - $this->exchangeAPI(); - $dispatcher = $this->container['MiddlewareDispatcher']; - - $this->assertEquals(1, count($dispatcher->getMiddlewares())); - } - } diff --git a/tests/lib/appframework/http/DispatcherTest.php b/tests/lib/appframework/http/DispatcherTest.php index 849b0ca97a6..6cf0da879ff 100644 --- a/tests/lib/appframework/http/DispatcherTest.php +++ b/tests/lib/appframework/http/DispatcherTest.php @@ -26,7 +26,7 @@ namespace OC\AppFramework\Http; use OC\AppFramework\Core\API; use OC\AppFramework\Middleware\MiddlewareDispatcher; - +use OCP\AppFramework\Http; //require_once(__DIR__ . "/../classloader.php"); @@ -44,8 +44,8 @@ class DispatcherTest extends \PHPUnit_Framework_TestCase { protected function setUp() { $this->controllerMethod = 'test'; - $api = $this->getMockBuilder( - '\OC\AppFramework\Core\API') + $app = $this->getMockBuilder( + 'OC\AppFramework\DependencyInjection\DIContainer') ->disableOriginalConstructor() ->getMock(); $request = $this->getMockBuilder( @@ -53,7 +53,7 @@ class DispatcherTest extends \PHPUnit_Framework_TestCase { ->disableOriginalConstructor() ->getMock(); $this->http = $this->getMockBuilder( - '\OC\AppFramework\Http\Http') + '\OC\AppFramework\Http') ->disableOriginalConstructor() ->getMock(); @@ -62,8 +62,8 @@ class DispatcherTest extends \PHPUnit_Framework_TestCase { ->disableOriginalConstructor() ->getMock(); $this->controller = $this->getMock( - '\OC\AppFramework\Controller\Controller', - array($this->controllerMethod), array($api, $request)); + '\OCP\AppFramework\Controller', + array($this->controllerMethod), array($app, $request)); $this->dispatcher = new Dispatcher( $this->http, $this->middlewareDispatcher); diff --git a/tests/lib/appframework/http/HttpTest.php b/tests/lib/appframework/http/HttpTest.php index 382d511b116..0bdcee24c99 100644 --- a/tests/lib/appframework/http/HttpTest.php +++ b/tests/lib/appframework/http/HttpTest.php @@ -24,6 +24,7 @@ namespace OC\AppFramework\Http; +use OC\AppFramework\Http; //require_once(__DIR__ . "/../classloader.php"); diff --git a/tests/lib/appframework/http/RedirectResponseTest.php b/tests/lib/appframework/http/RedirectResponseTest.php index 1946655b0fa..f82d0c3a675 100644 --- a/tests/lib/appframework/http/RedirectResponseTest.php +++ b/tests/lib/appframework/http/RedirectResponseTest.php @@ -24,6 +24,7 @@ namespace OC\AppFramework\Http; +use OCP\AppFramework\Http; //require_once(__DIR__ . "/../classloader.php"); diff --git a/tests/lib/appframework/http/RequestTest.php b/tests/lib/appframework/http/RequestTest.php index 0371c870cf2..00473a8c44f 100644 --- a/tests/lib/appframework/http/RequestTest.php +++ b/tests/lib/appframework/http/RequestTest.php @@ -8,12 +8,26 @@ namespace OC\AppFramework\Http; +global $data; class RequestTest extends \PHPUnit_Framework_TestCase { + public function setUp() { + require_once __DIR__ . '/requeststream.php'; + if (in_array('fakeinput', stream_get_wrappers())) { + stream_wrapper_unregister('fakeinput'); + } + stream_wrapper_register('fakeinput', 'RequestStream'); + } + + public function tearDown() { + stream_wrapper_unregister('fakeinput'); + } + public function testRequestAccessors() { $vars = array( 'get' => array('name' => 'John Q. Public', 'nickname' => 'Joey'), + 'method' => 'GET', ); $request = new Request($vars); @@ -31,6 +45,7 @@ class RequestTest extends \PHPUnit_Framework_TestCase { $this->assertEquals('Joey', $request->get['nickname']); // Always returns null if variable not set. $this->assertEquals(null, $request->{'flickname'}); + } // urlParams has precedence over POST which has precedence over GET @@ -73,4 +88,123 @@ class RequestTest extends \PHPUnit_Framework_TestCase { $request->{'nickname'} = 'Janey'; } + /** + * @expectedException LogicException + */ + public function testGetTheMethodRight() { + $vars = array( + 'get' => array('name' => 'John Q. Public', 'nickname' => 'Joey'), + 'method' => 'GET', + ); + + $request = new Request($vars); + $result = $request->post; + } + + public function testTheMethodIsRight() { + $vars = array( + 'get' => array('name' => 'John Q. Public', 'nickname' => 'Joey'), + 'method' => 'GET', + ); + + $request = new Request($vars); + $this->assertEquals('GET', $request->method); + $result = $request->get; + $this->assertEquals('John Q. Public', $result['name']); + $this->assertEquals('Joey', $result['nickname']); + } + + public function testJsonPost() { + global $data; + $data = '{"name": "John Q. Public", "nickname": "Joey"}'; + $vars = array( + 'method' => 'POST', + 'server' => array('CONTENT_TYPE' => 'application/json; utf-8'), + ); + + $request = new Request($vars); + $this->assertEquals('POST', $request->method); + $result = $request->post; + $this->assertEquals('John Q. Public', $result['name']); + $this->assertEquals('Joey', $result['nickname']); + $this->assertEquals('Joey', $request->params['nickname']); + $this->assertEquals('Joey', $request['nickname']); + } + + public function testPatch() { + global $data; + $data = http_build_query(array('name' => 'John Q. Public', 'nickname' => 'Joey'), '', '&'); + + $vars = array( + 'method' => 'PATCH', + 'server' => array('CONTENT_TYPE' => 'application/x-www-form-urlencoded'), + ); + + $request = new Request($vars); + + $this->assertEquals('PATCH', $request->method); + $result = $request->patch; + + $this->assertEquals('John Q. Public', $result['name']); + $this->assertEquals('Joey', $result['nickname']); + } + + public function testJsonPatchAndPut() { + global $data; + + // PUT content + $data = '{"name": "John Q. Public", "nickname": "Joey"}'; + $vars = array( + 'method' => 'PUT', + 'server' => array('CONTENT_TYPE' => 'application/json; utf-8'), + ); + + $request = new Request($vars); + + $this->assertEquals('PUT', $request->method); + $result = $request->put; + + $this->assertEquals('John Q. Public', $result['name']); + $this->assertEquals('Joey', $result['nickname']); + + // PATCH content + $data = '{"name": "John Q. Public", "nickname": null}'; + $vars = array( + 'method' => 'PATCH', + 'server' => array('CONTENT_TYPE' => 'application/json; utf-8'), + ); + + $request = new Request($vars); + + $this->assertEquals('PATCH', $request->method); + $result = $request->patch; + + $this->assertEquals('John Q. Public', $result['name']); + $this->assertEquals(null, $result['nickname']); + } + + public function testPutStream() { + global $data; + $data = file_get_contents(__DIR__ . '/../../../data/testimage.png'); + + $vars = array( + 'put' => $data, + 'method' => 'PUT', + 'server' => array('CONTENT_TYPE' => 'image/png'), + ); + + $request = new Request($vars); + $this->assertEquals('PUT', $request->method); + $resource = $request->put; + $contents = stream_get_contents($resource); + $this->assertEquals($data, $contents); + + try { + $resource = $request->put; + } catch(\LogicException $e) { + return; + } + $this->fail('Expected LogicException.'); + + } } diff --git a/tests/lib/appframework/http/ResponseTest.php b/tests/lib/appframework/http/ResponseTest.php index 7e09086f801..1a38c38c1e7 100644 --- a/tests/lib/appframework/http/ResponseTest.php +++ b/tests/lib/appframework/http/ResponseTest.php @@ -25,7 +25,8 @@ namespace OC\AppFramework\Http; -use OCP\AppFramework\Http\Response; +use OCP\AppFramework\Http\Response, + OCP\AppFramework\Http; class ResponseTest extends \PHPUnit_Framework_TestCase { diff --git a/tests/lib/appframework/http/TemplateResponseTest.php b/tests/lib/appframework/http/TemplateResponseTest.php index 3c6d29cd339..a583d9da14f 100644 --- a/tests/lib/appframework/http/TemplateResponseTest.php +++ b/tests/lib/appframework/http/TemplateResponseTest.php @@ -63,93 +63,33 @@ class TemplateResponseTest extends \PHPUnit_Framework_TestCase { } - public function testRender(){ - $ocTpl = $this->getMock('Template', array('fetchPage')); - $ocTpl->expects($this->once()) - ->method('fetchPage'); - - $api = $this->getMock('OC\AppFramework\Core\API', - array('getAppName', 'getTemplate'), array('app')); - $api->expects($this->any()) - ->method('getAppName') - ->will($this->returnValue('app')); - $api->expects($this->once()) - ->method('getTemplate') - ->with($this->equalTo('home'), $this->equalTo('user'), $this->equalTo('app')) - ->will($this->returnValue($ocTpl)); - - $tpl = new TemplateResponse($api, 'home'); - - $tpl->render(); - } - - - public function testRenderAssignsParams(){ - $params = array('john' => 'doe'); - - $ocTpl = $this->getMock('Template', array('assign', 'fetchPage')); - $ocTpl->expects($this->once()) - ->method('assign') - ->with($this->equalTo('john'), $this->equalTo('doe')); - - $api = $this->getMock('OC\AppFramework\Core\API', - array('getAppName', 'getTemplate'), array('app')); - $api->expects($this->any()) - ->method('getAppName') - ->will($this->returnValue('app')); - $api->expects($this->once()) - ->method('getTemplate') - ->with($this->equalTo('home'), $this->equalTo('user'), $this->equalTo('app')) - ->will($this->returnValue($ocTpl)); - - $tpl = new TemplateResponse($api, 'home'); - $tpl->setParams($params); - - $tpl->render(); - } - - - public function testRenderDifferentApp(){ - $ocTpl = $this->getMock('Template', array('fetchPage')); - $ocTpl->expects($this->once()) - ->method('fetchPage'); - - $api = $this->getMock('OC\AppFramework\Core\API', - array('getAppName', 'getTemplate'), array('app')); - $api->expects($this->any()) - ->method('getAppName') - ->will($this->returnValue('app')); - $api->expects($this->once()) - ->method('getTemplate') - ->with($this->equalTo('home'), $this->equalTo('user'), $this->equalTo('app2')) - ->will($this->returnValue($ocTpl)); - - $tpl = new TemplateResponse($api, 'home', 'app2'); - - $tpl->render(); - } - - - public function testRenderDifferentRenderAs(){ - $ocTpl = $this->getMock('Template', array('fetchPage')); - $ocTpl->expects($this->once()) - ->method('fetchPage'); - - $api = $this->getMock('OC\AppFramework\Core\API', - array('getAppName', 'getTemplate'), array('app')); - $api->expects($this->any()) - ->method('getAppName') - ->will($this->returnValue('app')); - $api->expects($this->once()) - ->method('getTemplate') - ->with($this->equalTo('home'), $this->equalTo('admin'), $this->equalTo('app')) - ->will($this->returnValue($ocTpl)); - - $tpl = new TemplateResponse($api, 'home'); - $tpl->renderAs('admin'); - - $tpl->render(); - } +// public function testRender(){ +// $ocTpl = $this->getMock('Template', array('fetchPage')); +// $ocTpl->expects($this->once()) +// ->method('fetchPage'); +// +// $tpl = new TemplateResponse('core', 'error'); +// +// $tpl->render(); +// } +// +// +// public function testRenderAssignsParams(){ +// $params = array('john' => 'doe'); +// +// $tpl = new TemplateResponse('app', 'home'); +// $tpl->setParams($params); +// +// $tpl->render(); +// } +// +// +// public function testRenderDifferentApp(){ +// +// $tpl = new TemplateResponse('app', 'home', 'app2'); +// +// $tpl->render(); +// } public function testGetRenderAs(){ diff --git a/tests/lib/appframework/http/requeststream.php b/tests/lib/appframework/http/requeststream.php new file mode 100644 index 00000000000..e1bf5c2c6bb --- /dev/null +++ b/tests/lib/appframework/http/requeststream.php @@ -0,0 +1,107 @@ +<?php +/** + * Copy of http://dk1.php.net/manual/en/stream.streamwrapper.example-1.php + * Used to simulate php://input for Request tests + */ +class RequestStream { + protected $position; + protected $varname; + + function stream_open($path, $mode, $options, &$opened_path) { + $url = parse_url($path); + $this->varname = $url["host"]; + $this->position = 0; + + return true; + } + + function stream_read($count) { + $ret = substr($GLOBALS[$this->varname], $this->position, $count); + $this->position += strlen($ret); + return $ret; + } + + function stream_write($data) { + $left = substr($GLOBALS[$this->varname], 0, $this->position); + $right = substr($GLOBALS[$this->varname], $this->position + strlen($data)); + $GLOBALS[$this->varname] = $left . $data . $right; + $this->position += strlen($data); + return strlen($data); + } + + function stream_tell() { + return $this->position; + } + + function stream_eof() { + return $this->position >= strlen($GLOBALS[$this->varname]); + } + + function stream_seek($offset, $whence) { + switch ($whence) { + case SEEK_SET: + if ($offset < strlen($GLOBALS[$this->varname]) && $offset >= 0) { + $this->position = $offset; + return true; + } else { + return false; + } + break; + + case SEEK_CUR: + if ($offset >= 0) { + $this->position += $offset; + return true; + } else { + return false; + } + break; + + case SEEK_END: + if (strlen($GLOBALS[$this->varname]) + $offset >= 0) { + $this->position = strlen($GLOBALS[$this->varname]) + $offset; + return true; + } else { + return false; + } + break; + + default: + return false; + } + } + + public function stream_stat() { + $size = strlen($GLOBALS[$this->varname]); + $time = time(); + $data = array( + 'dev' => 0, + 'ino' => 0, + 'mode' => 0777, + 'nlink' => 1, + 'uid' => 0, + 'gid' => 0, + 'rdev' => '', + 'size' => $size, + 'atime' => $time, + 'mtime' => $time, + 'ctime' => $time, + 'blksize' => -1, + 'blocks' => -1, + ); + return array_values($data) + $data; + //return false; + } + + function stream_metadata($path, $option, $var) { + if($option == STREAM_META_TOUCH) { + $url = parse_url($path); + $varname = $url["host"]; + if(!isset($GLOBALS[$varname])) { + $GLOBALS[$varname] = ''; + } + return true; + } + return false; + } +} diff --git a/tests/lib/appframework/middleware/MiddlewareDispatcherTest.php b/tests/lib/appframework/middleware/MiddlewareDispatcherTest.php index 43727846dcf..95d42e4eb8e 100644 --- a/tests/lib/appframework/middleware/MiddlewareDispatcherTest.php +++ b/tests/lib/appframework/middleware/MiddlewareDispatcherTest.php @@ -25,8 +25,8 @@ namespace OC\AppFramework; use OC\AppFramework\Http\Request; -use OC\AppFramework\Middleware\Middleware; use OC\AppFramework\Middleware\MiddlewareDispatcher; +use OCP\AppFramework\Middleware; use OCP\AppFramework\Http\Response; @@ -122,13 +122,13 @@ class MiddlewareDispatcherTest extends \PHPUnit_Framework_TestCase { private function getAPIMock(){ - return $this->getMock('OC\AppFramework\Core\API', + return $this->getMock('OC\AppFramework\DependencyInjection\DIContainer', array('getAppName'), array('app')); } private function getControllerMock(){ - return $this->getMock('OC\AppFramework\Controller\Controller', array('method'), + return $this->getMock('OCP\AppFramework\Controller', array('method'), array($this->getAPIMock(), new Request())); } @@ -142,12 +142,12 @@ class MiddlewareDispatcherTest extends \PHPUnit_Framework_TestCase { public function testAfterExceptionShouldReturnResponseOfMiddleware(){ $response = new Response(); - $m1 = $this->getMock('\OC\AppFramework\Middleware\Middleware', + $m1 = $this->getMock('\OCP\AppFramework\Middleware', array('afterException', 'beforeController')); $m1->expects($this->never()) ->method('afterException'); - $m2 = $this->getMock('OC\AppFramework\Middleware\Middleware', + $m2 = $this->getMock('OCP\AppFramework\Middleware', array('afterException', 'beforeController')); $m2->expects($this->once()) ->method('afterException') @@ -267,7 +267,7 @@ class MiddlewareDispatcherTest extends \PHPUnit_Framework_TestCase { public function testExceptionShouldRunAfterExceptionOfOnlyPreviouslyExecutedMiddlewares(){ $m1 = $this->getMiddleware(); $m2 = $this->getMiddleware(true); - $m3 = $this->getMock('\OC\AppFramework\Middleware\Middleware'); + $m3 = $this->getMock('\OCP\AppFramework\Middleware'); $m3->expects($this->never()) ->method('afterException'); $m3->expects($this->never()) diff --git a/tests/lib/appframework/middleware/MiddlewareTest.php b/tests/lib/appframework/middleware/MiddlewareTest.php index 5e2930ac6a3..7a93c0d4dda 100644 --- a/tests/lib/appframework/middleware/MiddlewareTest.php +++ b/tests/lib/appframework/middleware/MiddlewareTest.php @@ -25,7 +25,7 @@ namespace OC\AppFramework; use OC\AppFramework\Http\Request; -use OC\AppFramework\Middleware\Middleware; +use OCP\AppFramework\Middleware; class ChildMiddleware extends Middleware {}; @@ -44,10 +44,10 @@ class MiddlewareTest extends \PHPUnit_Framework_TestCase { protected function setUp(){ $this->middleware = new ChildMiddleware(); - $this->api = $this->getMock('OC\AppFramework\Core\API', + $this->api = $this->getMock('OC\AppFramework\DependencyInjection\DIContainer', array(), array('test')); - $this->controller = $this->getMock('OC\AppFramework\Controller\Controller', + $this->controller = $this->getMock('OCP\AppFramework\Controller', array(), array($this->api, new Request())); $this->exception = new \Exception(); $this->response = $this->getMock('OCP\AppFramework\Http\Response'); diff --git a/tests/lib/appframework/middleware/security/SecurityMiddlewareTest.php b/tests/lib/appframework/middleware/security/SecurityMiddlewareTest.php index 3ed44282a7b..dae6135dc54 100644 --- a/tests/lib/appframework/middleware/security/SecurityMiddlewareTest.php +++ b/tests/lib/appframework/middleware/security/SecurityMiddlewareTest.php @@ -24,7 +24,7 @@ namespace OC\AppFramework\Middleware\Security; -use OC\AppFramework\Http\Http; +use OC\AppFramework\Http; use OC\AppFramework\Http\Request; use OC\AppFramework\Http\RedirectResponse; use OCP\AppFramework\Http\JSONResponse; @@ -39,8 +39,8 @@ class SecurityMiddlewareTest extends \PHPUnit_Framework_TestCase { private $request; public function setUp() { - $api = $this->getMock('OC\AppFramework\Core\API', array(), array('test')); - $this->controller = $this->getMock('OC\AppFramework\Controller\Controller', + $api = $this->getMock('OC\AppFramework\DependencyInjection\DIContainer', array(), array('test')); + $this->controller = $this->getMock('OCP\AppFramework\Controller', array(), array($api, new Request())); $this->request = new Request(); @@ -51,24 +51,19 @@ class SecurityMiddlewareTest extends \PHPUnit_Framework_TestCase { private function getAPI(){ - return $this->getMock('OC\AppFramework\Core\API', + return $this->getMock('OC\AppFramework\DependencyInjection\DIContainer', array('isLoggedIn', 'passesCSRFCheck', 'isAdminUser', - 'isSubAdminUser', 'activateNavigationEntry', - 'getUserId'), + 'isSubAdminUser', 'getUserId'), array('app')); } - private function checkNavEntry($method, $shouldBeActivated=false){ + private function checkNavEntry($method){ $api = $this->getAPI(); - if($shouldBeActivated){ - $api->expects($this->once()) - ->method('activateNavigationEntry'); - } else { - $api->expects($this->never()) - ->method('activateNavigationEntry'); - } + $serverMock = $this->getMock('\OC\Server', array()); + $api->expects($this->any())->method('getServer') + ->will($this->returnValue($serverMock)); $sec = new SecurityMiddleware($api, $this->request); $sec->beforeController('\OC\AppFramework\Middleware\Security\SecurityMiddlewareTest', $method); @@ -80,7 +75,7 @@ class SecurityMiddlewareTest extends \PHPUnit_Framework_TestCase { * @NoCSRFRequired */ public function testSetNavigationEntry(){ - $this->checkNavEntry('testSetNavigationEntry', true); + $this->checkNavEntry('testSetNavigationEntry'); } @@ -215,9 +210,33 @@ class SecurityMiddlewareTest extends \PHPUnit_Framework_TestCase { /** * @PublicPage + * @expectedException \OC\AppFramework\Middleware\Security\SecurityException */ public function testCsrfCheck(){ - $this->securityCheck('testCsrfCheck', 'passesCSRFCheck'); + $api = $this->getAPI(); + $request = $this->getMock('OC\AppFramework\Http\Request', array('passesCSRFCheck')); + $request->expects($this->once()) + ->method('passesCSRFCheck') + ->will($this->returnValue(false)); + + $sec = new SecurityMiddleware($api, $request); + $sec->beforeController('\OC\AppFramework\Middleware\Security\SecurityMiddlewareTest', 'testCsrfCheck'); + } + + + /** + * @PublicPage + * @NoCSRFRequired + */ + public function testNoCsrfCheck(){ + $api = $this->getAPI(); + $request = $this->getMock('OC\AppFramework\Http\Request', array('passesCSRFCheck')); + $request->expects($this->never()) + ->method('passesCSRFCheck') + ->will($this->returnValue(false)); + + $sec = new SecurityMiddleware($api, $request); + $sec->beforeController('\OC\AppFramework\Middleware\Security\SecurityMiddlewareTest', 'testNoCsrfCheck'); } @@ -225,7 +244,14 @@ class SecurityMiddlewareTest extends \PHPUnit_Framework_TestCase { * @PublicPage */ public function testFailCsrfCheck(){ - $this->securityCheck('testFailCsrfCheck', 'passesCSRFCheck', true); + $api = $this->getAPI(); + $request = $this->getMock('OC\AppFramework\Http\Request', array('passesCSRFCheck')); + $request->expects($this->once()) + ->method('passesCSRFCheck') + ->will($this->returnValue(true)); + + $sec = new SecurityMiddleware($api, $request); + $sec->beforeController('\OC\AppFramework\Middleware\Security\SecurityMiddlewareTest', 'testFailCsrfCheck'); } @@ -271,8 +297,12 @@ class SecurityMiddlewareTest extends \PHPUnit_Framework_TestCase { public function testAfterExceptionReturnsRedirect(){ - $api = $this->getMock('OC\AppFramework\Core\API', array(), array('test')); - $this->controller = $this->getMock('OC\AppFramework\Controller\Controller', + $api = $this->getMock('OC\AppFramework\DependencyInjection\DIContainer', array(), array('test')); + $serverMock = $this->getMock('\OC\Server', array('getNavigationManager')); + $api->expects($this->once())->method('getServer') + ->will($this->returnValue($serverMock)); + + $this->controller = $this->getMock('OCP\AppFramework\Controller', array(), array($api, new Request())); $this->request = new Request( diff --git a/tests/lib/autoloader.php b/tests/lib/autoloader.php index b182dc87477..314a8ebee8d 100644 --- a/tests/lib/autoloader.php +++ b/tests/lib/autoloader.php @@ -19,11 +19,11 @@ class AutoLoader extends \PHPUnit_Framework_TestCase { } public function testLeadingSlashOnClassName() { - $this->assertEquals(array('private/files/storage/local.php'), $this->loader->findClass('\OC\Files\Storage\Local')); + $this->assertEquals(array('private/files/storage/local.php', 'files/storage/local.php'), $this->loader->findClass('\OC\Files\Storage\Local')); } public function testNoLeadingSlashOnClassName() { - $this->assertEquals(array('private/files/storage/local.php'), $this->loader->findClass('OC\Files\Storage\Local')); + $this->assertEquals(array('private/files/storage/local.php', 'files/storage/local.php'), $this->loader->findClass('OC\Files\Storage\Local')); } public function testLegacyPath() { @@ -54,7 +54,7 @@ class AutoLoader extends \PHPUnit_Framework_TestCase { } public function testLoadCoreNamespace() { - $this->assertEquals(array('private/foo/bar.php'), $this->loader->findClass('OC\Foo\Bar')); + $this->assertEquals(array('private/foo/bar.php', 'foo/bar.php'), $this->loader->findClass('OC\Foo\Bar')); } public function testLoadCore() { diff --git a/tests/lib/avatar.php b/tests/lib/avatar.php index 1c5195f8eb1..0334639afa8 100644 --- a/tests/lib/avatar.php +++ b/tests/lib/avatar.php @@ -1,23 +1,45 @@ <?php + /** * Copyright (c) 2013 Christopher Schäpers <christopher@schaepers.it> * This file is licensed under the Affero General Public License version 3 or * later. * See the COPYING-README file. */ - class Test_Avatar extends PHPUnit_Framework_TestCase { + private $user; + + public function setUp() { + $this->user = uniqid(); + $storage = new \OC\Files\Storage\Temporary(array()); + \OC\Files\Filesystem::mount($storage, array(), '/' . $this->user . '/'); + } + public function testAvatar() { - $this->markTestSkipped("Setting custom avatars with encryption doesn't work yet"); - $avatar = new \OC_Avatar(\OC_User::getUser()); + $avatar = new \OC_Avatar($this->user); $this->assertEquals(false, $avatar->get()); - $expected = new OC_Image(\OC::$SERVERROOT.'/tests/data/testavatar.png'); + $expected = new OC_Image(\OC::$SERVERROOT . '/tests/data/testavatar.png'); + $expected->resize(64); $avatar->set($expected->data()); + $this->assertEquals($expected->data(), $avatar->get()->data()); + + $avatar->remove(); + $this->assertEquals(false, $avatar->get()); + } + + public function testAvatarApi() { + $avatarManager = \OC::$server->getAvatarManager(); + $avatar = $avatarManager->getAvatar($this->user); + + $this->assertEquals(false, $avatar->get()); + + $expected = new OC_Image(\OC::$SERVERROOT . '/tests/data/testavatar.png'); $expected->resize(64); + $avatar->set($expected->data()); $this->assertEquals($expected->data(), $avatar->get()->data()); $avatar->remove(); diff --git a/tests/lib/backgroundjob/dummyjoblist.php b/tests/lib/backgroundjob/dummyjoblist.php index d91d6b344b5..e1579c273bb 100644 --- a/tests/lib/backgroundjob/dummyjoblist.php +++ b/tests/lib/backgroundjob/dummyjoblist.php @@ -8,9 +8,6 @@ namespace Test\BackgroundJob; -class JobRun extends \Exception { -} - /** * Class DummyJobList * diff --git a/tests/lib/backgroundjob/job.php b/tests/lib/backgroundjob/job.php new file mode 100644 index 00000000000..7d66fa772d2 --- /dev/null +++ b/tests/lib/backgroundjob/job.php @@ -0,0 +1,59 @@ +<?php +/** + * Copyright (c) 2013 Robin Appelman <icewind@owncloud.com> + * This file is licensed under the Affero General Public License version 3 or + * later. + * See the COPYING-README file. + */ + +namespace Test\BackgroundJob; + + +class TestJob extends \OC\BackgroundJob\Job { + private $testCase; + + /** + * @var callable $callback + */ + private $callback; + + /** + * @param Job $testCase + * @param callable $callback + */ + public function __construct($testCase, $callback) { + $this->testCase = $testCase; + $this->callback = $callback; + } + + public function run($argument) { + $this->testCase->markRun(); + $callback = $this->callback; + $callback($argument); + } +} + +class Job extends \PHPUnit_Framework_TestCase { + private $run = false; + + public function setUp() { + $this->run = false; + } + + public function testRemoveAfterException() { + $jobList = new DummyJobList(); + $job = new TestJob($this, function () { + throw new \Exception(); + }); + $jobList->add($job); + + $this->assertCount(1, $jobList->getAll()); + $job->execute($jobList); + $this->assertTrue($this->run); + $this->assertCount(0, $jobList->getAll()); + } + + public function markRun() { + $this->run = true; + } +} diff --git a/tests/lib/backgroundjob/queuedjob.php b/tests/lib/backgroundjob/queuedjob.php index 1d373473cd7..19c1b28a507 100644 --- a/tests/lib/backgroundjob/queuedjob.php +++ b/tests/lib/backgroundjob/queuedjob.php @@ -9,8 +9,17 @@ namespace Test\BackgroundJob; class TestQueuedJob extends \OC\BackgroundJob\QueuedJob { + private $testCase; + + /** + * @param QueuedJob $testCase + */ + public function __construct($testCase) { + $this->testCase = $testCase; + } + public function run($argument) { - throw new JobRun(); //throw an exception so we can detect if this function is called + $this->testCase->markRun(); } } @@ -24,19 +33,22 @@ class QueuedJob extends \PHPUnit_Framework_TestCase { */ private $job; + private $jobRun = false; + + public function markRun() { + $this->jobRun = true; + } + public function setup() { $this->jobList = new DummyJobList(); - $this->job = new TestQueuedJob(); + $this->job = new TestQueuedJob($this); $this->jobList->add($this->job); + $this->jobRun = false; } public function testJobShouldBeRemoved() { - try { - $this->assertTrue($this->jobList->has($this->job, null)); - $this->job->execute($this->jobList); - $this->fail("job should have been run"); - } catch (JobRun $e) { - $this->assertFalse($this->jobList->has($this->job, null)); - } + $this->assertTrue($this->jobList->has($this->job, null)); + $this->job->execute($this->jobList); + $this->assertTrue($this->jobRun); } } diff --git a/tests/lib/backgroundjob/timedjob.php b/tests/lib/backgroundjob/timedjob.php index f3c3eb4d0dd..646a2607ef3 100644 --- a/tests/lib/backgroundjob/timedjob.php +++ b/tests/lib/backgroundjob/timedjob.php @@ -9,12 +9,18 @@ namespace Test\BackgroundJob; class TestTimedJob extends \OC\BackgroundJob\TimedJob { - public function __construct() { + private $testCase; + + /** + * @param TimedJob $testCase + */ + public function __construct($testCase) { $this->setInterval(10); + $this->testCase = $testCase; } public function run($argument) { - throw new JobRun(); //throw an exception so we can detect if this function is called + $this->testCase->markRun(); } } @@ -28,44 +34,37 @@ class TimedJob extends \PHPUnit_Framework_TestCase { */ private $job; + private $jobRun = false; + + public function markRun() { + $this->jobRun = true; + } + public function setup() { $this->jobList = new DummyJobList(); - $this->job = new TestTimedJob(); + $this->job = new TestTimedJob($this); $this->jobList->add($this->job); + $this->jobRun = false; } public function testShouldRunAfterInterval() { $this->job->setLastRun(time() - 12); - try { - $this->job->execute($this->jobList); - $this->fail("job should have run"); - } catch (JobRun $e) { - } - $this->assertTrue(true); + $this->job->execute($this->jobList); + $this->assertTrue($this->jobRun); } public function testShouldNotRunWithinInterval() { $this->job->setLastRun(time() - 5); - try { - $this->job->execute($this->jobList); - } catch (JobRun $e) { - $this->fail("job should not have run"); - } - $this->assertTrue(true); + $this->job->execute($this->jobList); + $this->assertFalse($this->jobRun); } public function testShouldNotTwice() { $this->job->setLastRun(time() - 15); - try { - $this->job->execute($this->jobList); - $this->fail("job should have run the first time"); - } catch (JobRun $e) { - try { - $this->job->execute($this->jobList); - } catch (JobRun $e) { - $this->fail("job should not have run the second time"); - } - } - $this->assertTrue(true); + $this->job->execute($this->jobList); + $this->assertTrue($this->jobRun); + $this->jobRun = false; + $this->job->execute($this->jobList); + $this->assertFalse($this->jobRun); } } diff --git a/tests/lib/connector/sabre/aborteduploaddetectionplugin.php b/tests/lib/connector/sabre/aborteduploaddetectionplugin.php index bef0e4c4d7d..201f1263867 100644 --- a/tests/lib/connector/sabre/aborteduploaddetectionplugin.php +++ b/tests/lib/connector/sabre/aborteduploaddetectionplugin.php @@ -37,10 +37,11 @@ class Test_OC_Connector_Sabre_AbortedUploadDetectionPlugin extends PHPUnit_Frame /** * @dataProvider verifyContentLengthProvider */ - public function testVerifyContentLength($fileSize, $headers) + public function testVerifyContentLength($method, $fileSize, $headers) { $this->plugin->fileView = $this->buildFileViewMock($fileSize); + $headers['REQUEST_METHOD'] = $method; $this->server->httpRequest = new Sabre_HTTP_Request($headers); $this->plugin->verifyContentLength('foo.txt'); $this->assertTrue(true); @@ -50,30 +51,33 @@ class Test_OC_Connector_Sabre_AbortedUploadDetectionPlugin extends PHPUnit_Frame * @dataProvider verifyContentLengthFailedProvider * @expectedException Sabre_DAV_Exception_BadRequest */ - public function testVerifyContentLengthFailed($fileSize, $headers) + public function testVerifyContentLengthFailed($method, $fileSize, $headers) { $this->plugin->fileView = $this->buildFileViewMock($fileSize); // we expect unlink to be called $this->plugin->fileView->expects($this->once())->method('unlink'); - + $headers['REQUEST_METHOD'] = $method; $this->server->httpRequest = new Sabre_HTTP_Request($headers); $this->plugin->verifyContentLength('foo.txt'); } public function verifyContentLengthProvider() { return array( - array(1024, array()), - array(1024, array('HTTP_X_EXPECTED_ENTITY_LENGTH' => '1024')), - array(512, array('HTTP_CONTENT_LENGTH' => '512')), + array('PUT', 1024, array()), + array('PUT', 1024, array('HTTP_X_EXPECTED_ENTITY_LENGTH' => '1024')), + array('PUT', 512, array('HTTP_CONTENT_LENGTH' => '512')), + array('LOCK', 1024, array()), + array('LOCK', 1024, array('HTTP_X_EXPECTED_ENTITY_LENGTH' => '1024')), + array('LOCK', 512, array('HTTP_CONTENT_LENGTH' => '512')), ); } public function verifyContentLengthFailedProvider() { return array( - array(1025, array('HTTP_X_EXPECTED_ENTITY_LENGTH' => '1024')), - array(525, array('HTTP_CONTENT_LENGTH' => '512')), + array('PUT', 1025, array('HTTP_X_EXPECTED_ENTITY_LENGTH' => '1024')), + array('PUT', 525, array('HTTP_CONTENT_LENGTH' => '512')), ); } @@ -87,7 +91,7 @@ class Test_OC_Connector_Sabre_AbortedUploadDetectionPlugin extends PHPUnit_Frame } private function buildFileViewMock($fileSize) { - // mock filesysten + // mock filesystem $view = $this->getMock('\OC\Files\View', array('filesize', 'unlink'), array(), '', FALSE); $view->expects($this->any())->method('filesize')->withAnyParameters()->will($this->returnValue($fileSize)); diff --git a/tests/lib/connector/sabre/directory.php b/tests/lib/connector/sabre/directory.php new file mode 100644 index 00000000000..c501521b601 --- /dev/null +++ b/tests/lib/connector/sabre/directory.php @@ -0,0 +1,34 @@ +<?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 { + + /** + * @expectedException Sabre_DAV_Exception_Forbidden + */ + public function testCreateSharedFileFails() { + $dir = new OC_Connector_Sabre_Directory(''); + $dir->createFile('Shared'); + } + + /** + * @expectedException Sabre_DAV_Exception_Forbidden + */ + public function testCreateSharedFolderFails() { + $dir = new OC_Connector_Sabre_Directory(''); + $dir->createDirectory('Shared'); + } + + /** + * @expectedException Sabre_DAV_Exception_Forbidden + */ + public function testDeleteSharedFolderFails() { + $dir = new OC_Connector_Sabre_Directory('Shared'); + $dir->delete(); + } +} diff --git a/tests/lib/connector/sabre/file.php b/tests/lib/connector/sabre/file.php new file mode 100644 index 00000000000..e1fed0384c6 --- /dev/null +++ b/tests/lib/connector/sabre/file.php @@ -0,0 +1,45 @@ +<?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_File extends PHPUnit_Framework_TestCase { + + /** + * @expectedException Sabre_DAV_Exception + */ + 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)); + + // action + $etag = $file->put('test data'); + } + + /** + * @expectedException Sabre_DAV_Exception + */ + 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)); + + // action + $etag = $file->put('test data'); + } + + /** + * @expectedException Sabre_DAV_Exception_Forbidden + */ + public function testDeleteSharedFails() { + $file = new OC_Connector_Sabre_File('Shared'); + $file->delete(); + } +} diff --git a/tests/lib/connector/sabre/objecttree.php b/tests/lib/connector/sabre/objecttree.php index 1d76bb59676..e32f2365f95 100644 --- a/tests/lib/connector/sabre/objecttree.php +++ b/tests/lib/connector/sabre/objecttree.php @@ -15,8 +15,9 @@ use Sabre_DAV_Exception_Forbidden; class TestDoubleFileView extends \OC\Files\View{ - public function __construct($updatables, $canRename = true) { + public function __construct($updatables, $deletables, $canRename = true) { $this->updatables = $updatables; + $this->deletables = $deletables; $this->canRename = $canRename; } @@ -24,6 +25,10 @@ class TestDoubleFileView extends \OC\Files\View{ return $this->updatables[$path]; } + public function isDeletable($path) { + return $this->deletables[$path]; + } + public function rename($path1, $path2) { return $this->canRename; } @@ -35,31 +40,32 @@ class ObjectTree extends PHPUnit_Framework_TestCase { * @dataProvider moveFailedProvider * @expectedException Sabre_DAV_Exception_Forbidden */ - public function testMoveFailed($source, $dest, $updatables) { - $this->moveTest($source, $dest, $updatables); + public function testMoveFailed($source, $dest, $updatables, $deletables) { + $this->moveTest($source, $dest, $updatables, $deletables); } /** * @dataProvider moveSuccessProvider */ - public function testMoveSuccess($source, $dest, $updatables) { - $this->moveTest($source, $dest, $updatables); + public function testMoveSuccess($source, $dest, $updatables, $deletables) { + $this->moveTest($source, $dest, $updatables, $deletables); $this->assertTrue(true); } function moveFailedProvider() { return array( - array('a/b', 'a/c', array('a' => false, 'a/b' => false, 'a/c' => false)), - array('a/b', 'b/b', array('a' => false, 'a/b' => false, 'b' => false, 'b/b' => false)), - array('a/b', 'b/b', array('a' => false, 'a/b' => true, 'b' => false, 'b/b' => false)), - array('a/b', 'b/b', array('a' => true, 'a/b' => true, 'b' => false, 'b/b' => false)), + array('a/b', 'a/c', array('a' => false, 'a/b' => false, 'a/c' => false), array()), + array('a/b', 'b/b', array('a' => false, 'a/b' => false, 'b' => false, 'b/b' => false), array()), + array('a/b', 'b/b', array('a' => false, 'a/b' => true, 'b' => false, 'b/b' => false), array()), + array('a/b', 'b/b', array('a' => true, 'a/b' => true, 'b' => false, 'b/b' => false), array()), + array('a/b', 'b/b', array('a' => true, 'a/b' => true, 'b' => true, 'b/b' => false), array('a/b' => false)), ); } function moveSuccessProvider() { return array( - array('a/b', 'a/c', array('a' => false, 'a/b' => true, 'a/c' => false)), - array('a/b', 'b/b', array('a' => true, 'a/b' => true, 'b' => true, 'b/b' => false)), + array('a/b', 'a/c', array('a' => false, 'a/b' => true, 'a/c' => false), array()), + array('a/b', 'b/b', array('a' => true, 'a/b' => true, 'b' => true, 'b/b' => false), array('a/b' => true)), ); } @@ -68,7 +74,7 @@ class ObjectTree extends PHPUnit_Framework_TestCase { * @param $dest * @param $updatables */ - private function moveTest($source, $dest, $updatables) { + private function moveTest($source, $dest, $updatables, $deletables) { $rootDir = new OC_Connector_Sabre_Directory(''); $objectTree = $this->getMock('\OC\Connector\Sabre\ObjectTree', array('nodeExists', 'getNodeForPath'), @@ -80,7 +86,7 @@ class ObjectTree extends PHPUnit_Framework_TestCase { ->will($this->returnValue(false)); /** @var $objectTree \OC\Connector\Sabre\ObjectTree */ - $objectTree->fileView = new TestDoubleFileView($updatables); + $objectTree->fileView = new TestDoubleFileView($updatables, $deletables); $objectTree->move($source, $dest); } diff --git a/tests/lib/db.php b/tests/lib/db.php index c87bee4ab99..f0b271a36f1 100644 --- a/tests/lib/db.php +++ b/tests/lib/db.php @@ -12,6 +12,21 @@ class Test_DB extends PHPUnit_Framework_TestCase { protected static $schema_file = 'static://test_db_scheme'; protected $test_prefix; + /** + * @var string + */ + private $table1; + + /** + * @var string + */ + private $table2; + + /** + * @var string + */ + private $table3; + public function setUp() { $dbfile = OC::$SERVERROOT.'/tests/data/db_structure.xml'; @@ -25,6 +40,7 @@ class Test_DB extends PHPUnit_Framework_TestCase { $this->table1 = $this->test_prefix.'cntcts_addrsbks'; $this->table2 = $this->test_prefix.'cntcts_cards'; $this->table3 = $this->test_prefix.'vcategory'; + $this->table4 = $this->test_prefix.'decimal'; } public function tearDown() { @@ -121,10 +137,10 @@ class Test_DB extends PHPUnit_Framework_TestCase { $query = OC_DB::prepare('SELECT `fullname`, `uri`, `carddata` FROM `*PREFIX*'.$this->table2.'` WHERE `uri` = ?'); $result = $query->execute(array($uri)); $this->assertTrue((bool)$result); - $row = $result->fetchRow(); - $this->assertArrayHasKey('carddata', $row); - $this->assertEquals($carddata, $row['carddata']); - $this->assertEquals(1, $result->numRows()); + $rowset = $result->fetchAll(); + $this->assertEquals(1, count($rowset)); + $this->assertArrayHasKey('carddata', $rowset[0]); + $this->assertEquals($carddata, $rowset[0]['carddata']); // Try to insert a new row $result = OC_DB::insertIfNotExist('*PREFIX*'.$this->table2, @@ -137,50 +153,51 @@ class Test_DB extends PHPUnit_Framework_TestCase { $query = OC_DB::prepare('SELECT `fullname`, `uri`, `carddata` FROM `*PREFIX*'.$this->table2.'` WHERE `uri` = ?'); $result = $query->execute(array($uri)); $this->assertTrue((bool)$result); - $row = $result->fetchRow(); - $this->assertArrayHasKey('carddata', $row); // Test that previously inserted data isn't overwritten - $this->assertEquals($carddata, $row['carddata']); // And that a new row hasn't been inserted. - $this->assertEquals(1, $result->numRows()); - + $rowset = $result->fetchAll(); + $this->assertEquals(1, count($rowset)); + $this->assertArrayHasKey('carddata', $rowset[0]); + $this->assertEquals($carddata, $rowset[0]['carddata']); } - /** - * Tests whether the database is configured so it accepts and returns dates - * in the expected format. - */ - public function testTimestampDateFormat() { - $table = '*PREFIX*'.$this->test_prefix.'timestamp'; - $column = 'timestamptest'; - - $expectedFormat = 'Y-m-d H:i:s'; - $expected = new \DateTime; - - $query = OC_DB::prepare("INSERT INTO `$table` (`$column`) VALUES (?)"); - $result = $query->execute(array($expected->format($expectedFormat))); - $this->assertEquals( - 1, - $result, - "Database failed to accept dates in the format '$expectedFormat'." - ); - - $id = OC_DB::insertid($table); - $query = OC_DB::prepare("SELECT * FROM `$table` WHERE `id` = ?"); - $result = $query->execute(array($id)); - $row = $result->fetchRow(); + public function testUtf8Data() { + $table = "*PREFIX*{$this->table2}"; + $expected = "Ћö雙喜\xE2\x80\xA2"; + + $query = OC_DB::prepare("INSERT INTO `$table` (`fullname`, `uri`, `carddata`) VALUES (?, ?, ?)"); + $result = $query->execute(array($expected, 'uri_1', 'This is a vCard')); + $this->assertEquals(1, $result); - $actual = \DateTime::createFromFormat($expectedFormat, $row[$column]); - $this->assertInstanceOf( - '\DateTime', - $actual, - "Database failed to return dates in the format '$expectedFormat'." - ); - - $this->assertEquals( - $expected, - $actual, - 'Failed asserting that the returned date is the same as the inserted.' - ); + $actual = OC_DB::prepare("SELECT `fullname` FROM `$table`")->execute()->fetchOne(); + $this->assertSame($expected, $actual); } + + public function testDecimal() { + $table = "*PREFIX*" . $this->table4; + $rowname = 'decimaltest'; + + // Insert, select and delete decimal(12,2) values + $inserts = array('1337133713.37', '1234567890'); + $expects = array('1337133713.37', '1234567890.00'); + + for ($i = 0; $i < count($inserts); $i++) { + $insert = $inserts[$i]; + $expect = $expects[$i]; + + $query = OC_DB::prepare('INSERT INTO `' . $table . '` (`' . $rowname . '`) VALUES (?)'); + $result = $query->execute(array($insert)); + $this->assertEquals(1, $result); + $query = OC_DB::prepare('SELECT `' . $rowname . '` FROM `' . $table . '`'); + $result = $query->execute(); + $this->assertTrue((bool)$result); + $row = $result->fetchRow(); + $this->assertArrayHasKey($rowname, $row); + $this->assertEquals($expect, $row[$rowname]); + $query = OC_DB::prepare('DELETE FROM `' . $table . '`'); + $result = $query->execute(); + $this->assertTrue((bool)$result); + } + } + } diff --git a/tests/lib/db/mdb2schemareader.php b/tests/lib/db/mdb2schemareader.php index b9b241194fd..f08996cbeaf 100644 --- a/tests/lib/db/mdb2schemareader.php +++ b/tests/lib/db/mdb2schemareader.php @@ -39,7 +39,7 @@ class MDB2SchemaReader extends \PHPUnit_Framework_TestCase { $this->assertCount(1, $schema->getTables()); $table = $schema->getTable('test_table'); - $this->assertCount(7, $table->getColumns()); + $this->assertCount(8, $table->getColumns()); $this->assertEquals(4, $table->getColumn('integerfield')->getLength()); $this->assertTrue($table->getColumn('integerfield')->getAutoincrement()); @@ -57,18 +57,21 @@ class MDB2SchemaReader extends \PHPUnit_Framework_TestCase { $this->assertNull($table->getColumn('clobfield')->getLength()); $this->assertFalse($table->getColumn('clobfield')->getAutoincrement()); - $this->assertSame('', $table->getColumn('clobfield')->getDefault()); + $this->assertNull($table->getColumn('clobfield')->getDefault()); $this->assertTrue($table->getColumn('clobfield')->getNotnull()); $this->assertInstanceOf('Doctrine\DBAL\Types\TextType', $table->getColumn('clobfield')->getType()); $this->assertNull($table->getColumn('booleanfield')->getLength()); $this->assertFalse($table->getColumn('booleanfield')->getAutoincrement()); - $this->assertFalse($table->getColumn('booleanfield')->getDefault()); + $this->assertNull($table->getColumn('booleanfield')->getDefault()); $this->assertInstanceOf('Doctrine\DBAL\Types\BooleanType', $table->getColumn('booleanfield')->getType()); $this->assertTrue($table->getColumn('booleanfield_true')->getDefault()); $this->assertFalse($table->getColumn('booleanfield_false')->getDefault()); + $this->assertEquals(12, $table->getColumn('decimalfield_precision_scale')->getPrecision()); + $this->assertEquals(2, $table->getColumn('decimalfield_precision_scale')->getScale()); + $this->assertCount(2, $table->getIndexes()); $this->assertEquals(array('integerfield'), $table->getIndex('primary')->getUnquotedColumns()); $this->assertTrue($table->getIndex('primary')->isPrimary()); diff --git a/tests/lib/db/testschema.xml b/tests/lib/db/testschema.xml index 509b55ee81f..dfca920a0ef 100644 --- a/tests/lib/db/testschema.xml +++ b/tests/lib/db/testschema.xml @@ -53,6 +53,12 @@ <type>boolean</type> <default>false</default> </field> + <field> + <name>decimalfield_precision_scale</name> + <type>decimal</type> + <precision>12</precision> + <scale>2</scale> + </field> <index> <name>index_primary</name> diff --git a/tests/lib/dbschema.php b/tests/lib/dbschema.php index 7de90c047ca..4a7b7f7aac0 100644 --- a/tests/lib/dbschema.php +++ b/tests/lib/dbschema.php @@ -103,7 +103,7 @@ class Test_DBSchema extends PHPUnit_Framework_TestCase { break; } - $name = $result->fetchOne(); //FIXME checking with '$result->numRows() === 1' does not seem to work? + $name = $result->fetchOne(); if ($name === $table) { return true; } else { diff --git a/tests/lib/errorHandler.php b/tests/lib/errorHandler.php new file mode 100644 index 00000000000..68b87deccb6 --- /dev/null +++ b/tests/lib/errorHandler.php @@ -0,0 +1,62 @@ +<?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_ErrorHandler extends \PHPUnit_Framework_TestCase { + + /** + * @brief provide username, password combinations for testRemovePassword + * @return array + */ + function passwordProvider() { + return array( + array('user', 'password'), + array('user@owncloud.org', 'password'), + array('user', 'pass@word'), + array('us:er', 'password'), + array('user', 'pass:word'), + ); + + } + + /** + * @dataProvider passwordProvider + * @param string $username + * @param string $password + */ + function testRemovePassword($username, $password) { + $url = 'http://'.$username.':'.$password.'@owncloud.org'; + $expectedResult = 'http://xxx:xxx@owncloud.org'; + $result = TestableErrorHandler::testRemovePassword($url); + + $this->assertEquals($expectedResult, $result); + } + +} + +/** + * @brief dummy class to access protected methods of \OC\Log\ErrorHandler + */ +class TestableErrorHandler extends \OC\Log\ErrorHandler { + public static function testRemovePassword($msg) { + return self::removePassword($msg); + } +} diff --git a/tests/lib/files/cache/cache.php b/tests/lib/files/cache/cache.php index 247373a5cb9..5d876932479 100644 --- a/tests/lib/files/cache/cache.php +++ b/tests/lib/files/cache/cache.php @@ -18,11 +18,11 @@ class LongId extends \OC\Files\Storage\Temporary { class Cache extends \PHPUnit_Framework_TestCase { /** - * @var \OC\Files\Storage\Temporary $storage; + * @var \OC\Files\Storage\Temporary $storage ; */ private $storage; /** - * @var \OC\Files\Storage\Temporary $storage2; + * @var \OC\Files\Storage\Temporary $storage2 ; */ private $storage2; @@ -137,6 +137,79 @@ class Cache extends \PHPUnit_Framework_TestCase { $this->assertFalse($this->cache->inCache('folder/bar')); } + public function testEncryptedFolder() { + $file1 = 'folder'; + $file2 = 'folder/bar'; + $file3 = 'folder/foo'; + $data1 = array('size' => 100, 'mtime' => 50, 'mimetype' => 'httpd/unix-directory'); + $fileData = array(); + $fileData['bar'] = array('size' => 1000, 'unencrypted_size' => 900, 'encrypted' => 1, 'mtime' => 20, 'mimetype' => 'foo/file'); + $fileData['foo'] = array('size' => 20, 'unencrypted_size' => 16, 'encrypted' => 1, 'mtime' => 25, 'mimetype' => 'foo/file'); + + $this->cache->put($file1, $data1); + $this->cache->put($file2, $fileData['bar']); + $this->cache->put($file3, $fileData['foo']); + + $content = $this->cache->getFolderContents($file1); + $this->assertEquals(count($content), 2); + foreach ($content as $cachedData) { + $data = $fileData[$cachedData['name']]; + // indirect retrieval swaps unencrypted_size and size + $this->assertEquals($data['unencrypted_size'], $cachedData['size']); + } + + $file4 = 'folder/unkownSize'; + $fileData['unkownSize'] = array('size' => -1, 'mtime' => 25, 'mimetype' => 'foo/file'); + $this->cache->put($file4, $fileData['unkownSize']); + + $this->assertEquals(-1, $this->cache->calculateFolderSize($file1)); + + $fileData['unkownSize'] = array('size' => 5, 'mtime' => 25, 'mimetype' => 'foo/file'); + $this->cache->put($file4, $fileData['unkownSize']); + + $this->assertEquals(916, $this->cache->calculateFolderSize($file1)); + // direct cache entry retrieval returns the original values + $entry = $this->cache->get($file1); + $this->assertEquals(1025, $entry['size']); + $this->assertEquals(916, $entry['unencrypted_size']); + + $this->cache->remove($file2); + $this->cache->remove($file3); + $this->cache->remove($file4); + $this->assertEquals(0, $this->cache->calculateFolderSize($file1)); + + $this->cache->remove('folder'); + $this->assertFalse($this->cache->inCache('folder/foo')); + $this->assertFalse($this->cache->inCache('folder/bar')); + } + + public function testRootFolderSizeForNonHomeStorage() { + $dir1 = 'knownsize'; + $dir2 = 'unknownsize'; + $fileData = array(); + $fileData[''] = array('size' => -1, 'mtime' => 20, 'mimetype' => 'httpd/unix-directory'); + $fileData[$dir1] = array('size' => 1000, 'mtime' => 20, 'mimetype' => 'httpd/unix-directory'); + $fileData[$dir2] = array('size' => -1, 'mtime' => 25, 'mimetype' => 'httpd/unix-directory'); + + $this->cache->put('', $fileData['']); + $this->cache->put($dir1, $fileData[$dir1]); + $this->cache->put($dir2, $fileData[$dir2]); + + $this->assertTrue($this->cache->inCache($dir1)); + $this->assertTrue($this->cache->inCache($dir2)); + + // check that root size ignored the unknown sizes + $this->assertEquals(-1, $this->cache->calculateFolderSize('')); + + // clean up + $this->cache->remove(''); + $this->cache->remove($dir1); + $this->cache->remove($dir2); + + $this->assertFalse($this->cache->inCache($dir1)); + $this->assertFalse($this->cache->inCache($dir2)); + } + function testStatus() { $this->assertEquals(\OC\Files\Cache\Cache::NOT_FOUND, $this->cache->getStatus('foo')); $this->cache->put('foo', array('size' => -1)); @@ -247,14 +320,14 @@ class Cache extends \PHPUnit_Framework_TestCase { $data = array('size' => 1000, 'mtime' => 20, 'mimetype' => 'foo/file'); $this->cache->put('foo', $data); $cachedData = $this->cache->get('foo'); - $this->assertEquals($data['mtime'], $cachedData['storage_mtime']);//if no storage_mtime is saved, mtime should be used + $this->assertEquals($data['mtime'], $cachedData['storage_mtime']); //if no storage_mtime is saved, mtime should be used - $this->cache->put('foo', array('storage_mtime' => 30));//when setting storage_mtime, mtime is also set + $this->cache->put('foo', array('storage_mtime' => 30)); //when setting storage_mtime, mtime is also set $cachedData = $this->cache->get('foo'); $this->assertEquals(30, $cachedData['storage_mtime']); $this->assertEquals(30, $cachedData['mtime']); - $this->cache->put('foo', array('mtime' => 25));//setting mtime does not change storage_mtime + $this->cache->put('foo', array('mtime' => 25)); //setting mtime does not change storage_mtime $cachedData = $this->cache->get('foo'); $this->assertEquals(30, $cachedData['storage_mtime']); $this->assertEquals(25, $cachedData['mtime']); @@ -295,18 +368,18 @@ class Cache extends \PHPUnit_Framework_TestCase { $this->assertGreaterThan(0, $cacheMock->put('folder', $data)); // put un-normalized folder - $this->assertFalse($cacheMock->get('folder/' .$folderWith0308)); - $this->assertGreaterThan(0, $cacheMock->put('folder/' .$folderWith0308, $data)); + $this->assertFalse($cacheMock->get('folder/' . $folderWith0308)); + $this->assertGreaterThan(0, $cacheMock->put('folder/' . $folderWith0308, $data)); // get un-normalized folder by name - $unNormalizedFolderName = $cacheMock->get('folder/' .$folderWith0308); + $unNormalizedFolderName = $cacheMock->get('folder/' . $folderWith0308); // check if database layer normalized the folder name (this should not happen) $this->assertEquals($folderWith0308, $unNormalizedFolderName['name']); // put normalized folder $this->assertFalse($cacheMock->get('folder/' . $folderWith00F6)); - $this->assertGreaterThan(0, $cacheMock->put('folder/' .$folderWith00F6, $data)); + $this->assertGreaterThan(0, $cacheMock->put('folder/' . $folderWith00F6, $data)); // this is our bug, we have two different hashes with the same name (Schön) $this->assertEquals(2, count($cacheMock->getFolderContents('folder'))); @@ -317,7 +390,7 @@ class Cache extends \PHPUnit_Framework_TestCase { */ public function testWithNormalizer() { - if(!class_exists('Patchwork\PHP\Shim\Normalizer')) { + if (!class_exists('Patchwork\PHP\Shim\Normalizer')) { $this->markTestSkipped('The 3rdparty Normalizer extension is not available.'); return; } @@ -335,18 +408,18 @@ class Cache extends \PHPUnit_Framework_TestCase { $this->assertGreaterThan(0, $this->cache->put('folder', $data)); // put un-normalized folder - $this->assertFalse($this->cache->get('folder/' .$folderWith0308)); - $this->assertGreaterThan(0, $this->cache->put('folder/' .$folderWith0308, $data)); + $this->assertFalse($this->cache->get('folder/' . $folderWith0308)); + $this->assertGreaterThan(0, $this->cache->put('folder/' . $folderWith0308, $data)); // get un-normalized folder by name - $unNormalizedFolderName = $this->cache->get('folder/' .$folderWith0308); + $unNormalizedFolderName = $this->cache->get('folder/' . $folderWith0308); // check if folder name was normalized $this->assertEquals($folderWith00F6, $unNormalizedFolderName['name']); // put normalized folder $this->assertTrue(is_array($this->cache->get('folder/' . $folderWith00F6))); - $this->assertGreaterThan(0, $this->cache->put('folder/' .$folderWith00F6, $data)); + $this->assertGreaterThan(0, $this->cache->put('folder/' . $folderWith00F6, $data)); // at this point we should have only one folder named "Schön" $this->assertEquals(1, count($this->cache->getFolderContents('folder'))); diff --git a/tests/lib/files/cache/homecache.php b/tests/lib/files/cache/homecache.php new file mode 100644 index 00000000000..87fd0dba4c6 --- /dev/null +++ b/tests/lib/files/cache/homecache.php @@ -0,0 +1,127 @@ +<?php +/** + * Copyright (c) 2012 Robin Appelman <icewind@owncloud.com> + * This file is licensed under the Affero General Public License version 3 or + * later. + * See the COPYING-README file. + */ + +namespace Test\Files\Cache; + +class DummyUser extends \OC\User\User { + /** + * @var string $home + */ + private $home; + + /** + * @var string $uid + */ + private $uid; + + public function __construct($uid, $home) { + $this->home = $home; + $this->uid = $uid; + } + + /** + * @return string + */ + public function getHome() { + return $this->home; + } + + /** + * @return string + */ + public function getUID() { + return $this->uid; + } +} + +class HomeCache extends \PHPUnit_Framework_TestCase { + /** + * @var \OC\Files\Storage\Home $storage + */ + private $storage; + + /** + * @var \OC\Files\Cache\HomeCache $cache + */ + private $cache; + + /** + * @var \OC\User\User $user + */ + private $user; + + public function setUp() { + $this->user = new DummyUser('foo', \OC_Helper::tmpFolder()); + $this->storage = new \OC\Files\Storage\Home(array('user' => $this->user)); + $this->cache = $this->storage->getCache(); + } + + /** + * Tests that the root and files folder size calculation ignores the subdirs + * that have an unknown size. This makes sure that quota calculation still + * works as it's based on the "files" folder size. + */ + public function testRootFolderSizeIgnoresUnknownUpdate() { + $dir1 = 'files/knownsize'; + $dir2 = 'files/unknownsize'; + $fileData = array(); + $fileData[''] = array('size' => -1, 'mtime' => 20, 'mimetype' => 'httpd/unix-directory'); + $fileData['files'] = array('size' => -1, 'mtime' => 20, 'mimetype' => 'httpd/unix-directory'); + $fileData[$dir1] = array('size' => 1000, 'mtime' => 20, 'mimetype' => 'httpd/unix-directory'); + $fileData[$dir2] = array('size' => -1, 'mtime' => 25, 'mimetype' => 'httpd/unix-directory'); + + $this->cache->put('', $fileData['']); + $this->cache->put('files', $fileData['files']); + $this->cache->put($dir1, $fileData[$dir1]); + $this->cache->put($dir2, $fileData[$dir2]); + + $this->assertTrue($this->cache->inCache('files')); + $this->assertTrue($this->cache->inCache($dir1)); + $this->assertTrue($this->cache->inCache($dir2)); + + // 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(''); + $this->cache->remove('files'); + $this->cache->remove($dir1); + $this->cache->remove($dir2); + + $this->assertFalse($this->cache->inCache('files')); + $this->assertFalse($this->cache->inCache($dir1)); + $this->assertFalse($this->cache->inCache($dir2)); + } + + public function testRootFolderSizeIsFilesSize() { + $dir1 = 'files'; + $afile = 'test.txt'; + $fileData = array(); + $fileData[''] = array('size' => 1500, 'mtime' => 20, 'mimetype' => 'httpd/unix-directory'); + $fileData[$dir1] = array('size' => 1000, 'mtime' => 20, 'mimetype' => 'httpd/unix-directory'); + $fileData[$afile] = array('size' => 500, 'mtime' => 20); + + $this->cache->put('', $fileData['']); + $this->cache->put($dir1, $fileData[$dir1]); + + $this->assertTrue($this->cache->inCache($dir1)); + + // check that root size ignored the unknown sizes + $data = $this->cache->get('files'); + $this->assertEquals(1000, $data['size']); + $data = $this->cache->get(''); + $this->assertEquals(1000, $data['size']); + + // clean up + $this->cache->remove(''); + $this->cache->remove($dir1); + + $this->assertFalse($this->cache->inCache($dir1)); + } +} diff --git a/tests/lib/files/cache/scanner.php b/tests/lib/files/cache/scanner.php index 3f3a045377a..3f5604b4d45 100644 --- a/tests/lib/files/cache/scanner.php +++ b/tests/lib/files/cache/scanner.php @@ -147,7 +147,7 @@ class Scanner extends \PHPUnit_Framework_TestCase { $this->scanner->scan(''); $oldData = $this->cache->get(''); $this->storage->unlink('folder/bar.txt'); - $this->cache->put('folder', array('mtime' => $this->storage->filemtime('folder'))); + $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']); diff --git a/tests/lib/files/cache/updater.php b/tests/lib/files/cache/updater.php index 5d7997b0544..48986149a73 100644 --- a/tests/lib/files/cache/updater.php +++ b/tests/lib/files/cache/updater.php @@ -9,6 +9,7 @@ namespace Test\Files\Cache; use \OC\Files\Filesystem as Filesystem; +use OC\Files\Storage\Temporary; class Updater extends \PHPUnit_Framework_TestCase { /** @@ -21,6 +22,8 @@ class Updater extends \PHPUnit_Framework_TestCase { */ private $scanner; + private $stateFilesEncryption; + /** * @var \OC\Files\Cache\Cache $cache */ @@ -29,6 +32,12 @@ class Updater extends \PHPUnit_Framework_TestCase { private static $user; public function setUp() { + + // remember files_encryption state + $this->stateFilesEncryption = \OC_App::isEnabled('files_encryption'); + // we want to tests with the encryption app disabled + \OC_App::disable('files_encryption'); + $this->storage = new \OC\Files\Storage\Temporary(array()); $textData = "dummy file data\n"; $imgData = file_get_contents(\OC::$SERVERROOT . '/core/img/logo.png'); @@ -46,6 +55,10 @@ class Updater extends \PHPUnit_Framework_TestCase { if (!self::$user) { self::$user = uniqid(); } + + \OC_User::createUser(self::$user, 'password'); + \OC_User::setUserId(self::$user); + \OC\Files\Filesystem::init(self::$user, '/' . self::$user . '/files'); Filesystem::clearMounts(); @@ -63,13 +76,19 @@ class Updater extends \PHPUnit_Framework_TestCase { if ($this->cache) { $this->cache->clear(); } + $result = \OC_User::deleteUser(self::$user); + $this->assertTrue($result); Filesystem::tearDown(); + // reset app files_encryption + if ($this->stateFilesEncryption) { + \OC_App::enable('files_encryption'); + } } public function testWrite() { $textSize = strlen("dummy file data\n"); $imageSize = filesize(\OC::$SERVERROOT . '/core/img/logo.png'); - $this->cache->put('foo.txt', array('mtime' => 100)); + $this->cache->put('foo.txt', array('mtime' => 100, 'storage_mtime' => 150)); $rootCachedData = $this->cache->get(''); $this->assertEquals(3 * $textSize + $imageSize, $rootCachedData['size']); @@ -183,6 +202,14 @@ class Updater extends \PHPUnit_Framework_TestCase { $this->assertNotEquals($rootCachedData['etag'], $cachedData['etag']); } + public function testRenameExtension() { + $fooCachedData = $this->cache->get('foo.txt'); + $this->assertEquals('text/plain', $fooCachedData['mimetype']); + Filesystem::rename('foo.txt', 'foo.abcd'); + $fooCachedData = $this->cache->get('foo.abcd'); + $this->assertEquals('application/octet-stream', $fooCachedData['mimetype']); + } + public function testRenameWithMountPoints() { $storage2 = new \OC\Files\Storage\Temporary(array()); $cache2 = $storage2->getCache(); @@ -233,7 +260,6 @@ class Updater extends \PHPUnit_Framework_TestCase { $cachedData = $this->cache->get('folder'); $this->assertNotEquals($folderCachedData['etag'], $cachedData['etag']); - $this->assertEquals($time, $cachedData['mtime']); $cachedData = $this->cache->get(''); $this->assertNotEquals($rootCachedData['etag'], $cachedData['etag']); @@ -258,11 +284,41 @@ class Updater extends \PHPUnit_Framework_TestCase { $cachedData = $cache2->get(''); $this->assertNotEquals($substorageCachedData['etag'], $cachedData['etag']); - $this->assertEquals($time, $cachedData['mtime']); $cachedData = $this->cache->get('folder'); $this->assertNotEquals($folderCachedData['etag'], $cachedData['etag']); $this->assertEquals($time, $cachedData['mtime']); } + public function testUpdatePermissionsOnRescanOnlyForUpdatedFile() { + $permissionsCache = $this->storage->getPermissionsCache(); + $scanner = $this->storage->getScanner(); + $scanner->scan(''); + $cache = $this->storage->getCache(); + $loggedInUser = \OC_User::getUser(); + \OC_User::setUserId(self::$user); + FileSystem::getDirectoryContent('/'); + $past = time() - 600; + $cache->put('', array('storage_mtime' => $past)); + + $this->assertNotEquals(-1, $permissionsCache->get($cache->getId('foo.txt'), self::$user)); + $this->assertNotEquals(-1, $permissionsCache->get($cache->getId('foo.png'), self::$user)); + + $permissionsCache->set($cache->getId('foo.png'), self::$user, 15); + FileSystem::file_put_contents('/foo.txt', 'asd'); + + $this->assertEquals(-1, $permissionsCache->get($cache->getId('foo.txt'), self::$user)); + $this->assertEquals(15, $permissionsCache->get($cache->getId('foo.png'), self::$user)); + + FileSystem::getDirectoryContent('/'); + + $this->assertEquals(15, $permissionsCache->get($cache->getId('foo.png'), self::$user)); + + FileSystem::file_put_contents('/qwerty.txt', 'asd'); + FileSystem::getDirectoryContent('/'); + + $this->assertEquals(15, $permissionsCache->get($cache->getId('foo.png'), self::$user)); + + \OC_User::setUserId($loggedInUser); + } } diff --git a/tests/lib/files/cache/watcher.php b/tests/lib/files/cache/watcher.php index 749b1ab75a3..1920c276907 100644 --- a/tests/lib/files/cache/watcher.php +++ b/tests/lib/files/cache/watcher.php @@ -53,6 +53,9 @@ class Watcher extends \PHPUnit_Framework_TestCase { $cache->put('bar.test', array('storage_mtime' => 10)); $storage->file_put_contents('bar.test', 'test data'); + // make sure that PHP can read the new size correctly + clearstatcache(); + $updater->checkUpdate('bar.test'); $cachedData = $cache->get('bar.test'); $this->assertEquals(9, $cachedData['size']); diff --git a/tests/lib/files/etagtest.php b/tests/lib/files/etagtest.php new file mode 100644 index 00000000000..6c41413c4df --- /dev/null +++ b/tests/lib/files/etagtest.php @@ -0,0 +1,79 @@ +<?php +/** + * Copyright (c) 2012 Robin Appelman <icewind@owncloud.com> + * This file is licensed under the Affero General Public License version 3 or + * later. + * See the COPYING-README file. + */ + +namespace Test\Files; + +use OC\Files\Filesystem; +use OCP\Share; + +class EtagTest extends \PHPUnit_Framework_TestCase { + private $datadir; + + private $tmpDir; + + private $uid; + + /** + * @var \OC_User_Dummy $userBackend + */ + private $userBackend; + + public function setUp() { + \OC_Hook::clear('OC_Filesystem', 'setup'); + \OCP\Util::connectHook('OC_Filesystem', 'setup', '\OC\Files\Storage\Shared', 'setup'); + \OCP\Share::registerBackend('file', 'OC_Share_Backend_File'); + \OCP\Share::registerBackend('folder', 'OC_Share_Backend_Folder', 'file'); + + $this->datadir = \OC_Config::getValue('datadirectory'); + $this->tmpDir = \OC_Helper::tmpFolder(); + \OC_Config::setValue('datadirectory', $this->tmpDir); + $this->uid = \OC_User::getUser(); + \OC_User::setUserId(null); + + $this->userBackend = new \OC_User_Dummy(); + \OC_User::useBackend($this->userBackend); + \OC_Util::tearDownFS(); + } + + public function tearDown() { + \OC_Config::setValue('datadirectory', $this->datadir); + \OC_User::setUserId($this->uid); + \OC_Util::setupFS($this->uid); + } + + public function testNewUser() { + $user1 = uniqid('user_'); + $this->userBackend->createUser($user1, ''); + + \OC_Util::tearDownFS(); + \OC_User::setUserId($user1); + \OC_Util::setupFS($user1); + Filesystem::mkdir('/folder'); + Filesystem::mkdir('/folder/subfolder'); + Filesystem::file_put_contents('/foo.txt', 'asd'); + Filesystem::file_put_contents('/folder/bar.txt', 'fgh'); + Filesystem::file_put_contents('/folder/subfolder/qwerty.txt', 'jkl'); + + $files = array('/foo.txt', '/folder/bar.txt', '/folder/subfolder', '/folder/subfolder/qwerty.txt'); + $originalEtags = $this->getEtags($files); + + $scanner = new \OC\Files\Utils\Scanner($user1); + $scanner->backgroundScan('/'); + + $this->assertEquals($originalEtags, $this->getEtags($files)); + } + + private function getEtags($files) { + $etags = array(); + foreach ($files as $file) { + $info = Filesystem::getFileInfo($file); + $etags[$file] = $info['etag']; + } + return $etags; + } +} diff --git a/tests/lib/files/filesystem.php b/tests/lib/files/filesystem.php index bef70cc725b..90f1dfe581b 100644 --- a/tests/lib/files/filesystem.php +++ b/tests/lib/files/filesystem.php @@ -26,7 +26,7 @@ class Filesystem extends \PHPUnit_Framework_TestCase { /** * @var array tmpDirs */ - private $tmpDirs=array(); + private $tmpDirs = array(); /** * @return array @@ -41,57 +41,115 @@ class Filesystem extends \PHPUnit_Framework_TestCase { foreach ($this->tmpDirs as $dir) { \OC_Helper::rmdirr($dir); } + \OC\Files\Filesystem::clearMounts(); + \OC_User::setUserId(''); } public function setUp() { + \OC_User::setUserId(''); \OC\Files\Filesystem::clearMounts(); } public function testMount() { - \OC\Files\Filesystem::mount('\OC\Files\Storage\Local',self::getStorageData(),'/'); - $this->assertEquals('/',\OC\Files\Filesystem::getMountPoint('/')); - $this->assertEquals('/',\OC\Files\Filesystem::getMountPoint('/some/folder')); - list( , $internalPath)=\OC\Files\Filesystem::resolvePath('/'); - $this->assertEquals('',$internalPath); - list( , $internalPath)=\OC\Files\Filesystem::resolvePath('/some/folder'); - $this->assertEquals('some/folder',$internalPath); - - \OC\Files\Filesystem::mount('\OC\Files\Storage\Local',self::getStorageData(),'/some'); - $this->assertEquals('/',\OC\Files\Filesystem::getMountPoint('/')); - $this->assertEquals('/some/',\OC\Files\Filesystem::getMountPoint('/some/folder')); - $this->assertEquals('/some/',\OC\Files\Filesystem::getMountPoint('/some/')); - $this->assertEquals('/some/',\OC\Files\Filesystem::getMountPoint('/some')); - list( , $internalPath)=\OC\Files\Filesystem::resolvePath('/some/folder'); - $this->assertEquals('folder',$internalPath); + \OC\Files\Filesystem::mount('\OC\Files\Storage\Local', self::getStorageData(), '/'); + $this->assertEquals('/', \OC\Files\Filesystem::getMountPoint('/')); + $this->assertEquals('/', \OC\Files\Filesystem::getMountPoint('/some/folder')); + list(, $internalPath) = \OC\Files\Filesystem::resolvePath('/'); + $this->assertEquals('', $internalPath); + list(, $internalPath) = \OC\Files\Filesystem::resolvePath('/some/folder'); + $this->assertEquals('some/folder', $internalPath); + + \OC\Files\Filesystem::mount('\OC\Files\Storage\Local', self::getStorageData(), '/some'); + $this->assertEquals('/', \OC\Files\Filesystem::getMountPoint('/')); + $this->assertEquals('/some/', \OC\Files\Filesystem::getMountPoint('/some/folder')); + $this->assertEquals('/some/', \OC\Files\Filesystem::getMountPoint('/some/')); + $this->assertEquals('/some/', \OC\Files\Filesystem::getMountPoint('/some')); + list(, $internalPath) = \OC\Files\Filesystem::resolvePath('/some/folder'); + $this->assertEquals('folder', $internalPath); } public function testNormalize() { + $this->assertEquals('/', \OC\Files\Filesystem::normalizePath('')); + $this->assertEquals('/', \OC\Files\Filesystem::normalizePath('/')); + $this->assertEquals('/', \OC\Files\Filesystem::normalizePath('/', false)); + $this->assertEquals('/', \OC\Files\Filesystem::normalizePath('//')); + $this->assertEquals('/', \OC\Files\Filesystem::normalizePath('//', false)); $this->assertEquals('/path', \OC\Files\Filesystem::normalizePath('/path/')); $this->assertEquals('/path/', \OC\Files\Filesystem::normalizePath('/path/', false)); $this->assertEquals('/path', \OC\Files\Filesystem::normalizePath('path')); - $this->assertEquals('/path', \OC\Files\Filesystem::normalizePath('\path')); $this->assertEquals('/foo/bar', \OC\Files\Filesystem::normalizePath('/foo//bar/')); + $this->assertEquals('/foo/bar/', \OC\Files\Filesystem::normalizePath('/foo//bar/', false)); $this->assertEquals('/foo/bar', \OC\Files\Filesystem::normalizePath('/foo////bar')); + $this->assertEquals('/foo/bar', \OC\Files\Filesystem::normalizePath('/foo/////bar')); + $this->assertEquals('/foo/bar', \OC\Files\Filesystem::normalizePath('/foo/bar/.')); + $this->assertEquals('/foo/bar', \OC\Files\Filesystem::normalizePath('/foo/bar/./')); + $this->assertEquals('/foo/bar/', \OC\Files\Filesystem::normalizePath('/foo/bar/./', false)); + $this->assertEquals('/foo/bar', \OC\Files\Filesystem::normalizePath('/foo/bar/./.')); + $this->assertEquals('/foo/bar', \OC\Files\Filesystem::normalizePath('/foo/bar/././')); + $this->assertEquals('/foo/bar/', \OC\Files\Filesystem::normalizePath('/foo/bar/././', false)); + $this->assertEquals('/foo/bar', \OC\Files\Filesystem::normalizePath('/foo/./bar/')); + $this->assertEquals('/foo/bar/', \OC\Files\Filesystem::normalizePath('/foo/./bar/', false)); + $this->assertEquals('/foo/.bar', \OC\Files\Filesystem::normalizePath('/foo/.bar/')); + $this->assertEquals('/foo/.bar/', \OC\Files\Filesystem::normalizePath('/foo/.bar/', false)); + $this->assertEquals('/foo/.bar/tee', \OC\Files\Filesystem::normalizePath('/foo/.bar/tee')); + + // normalize does not resolve '..' (by design) + $this->assertEquals('/foo/..', \OC\Files\Filesystem::normalizePath('/foo/../')); + if (class_exists('Patchwork\PHP\Shim\Normalizer')) { $this->assertEquals("/foo/bar\xC3\xBC", \OC\Files\Filesystem::normalizePath("/foo/baru\xCC\x88")); } } + public function testNormalizeWindowsPaths() { + $this->assertEquals('/', \OC\Files\Filesystem::normalizePath('')); + $this->assertEquals('/', \OC\Files\Filesystem::normalizePath('\\')); + $this->assertEquals('/', \OC\Files\Filesystem::normalizePath('\\', false)); + $this->assertEquals('/', \OC\Files\Filesystem::normalizePath('\\\\')); + $this->assertEquals('/', \OC\Files\Filesystem::normalizePath('\\\\', false)); + $this->assertEquals('/path', \OC\Files\Filesystem::normalizePath('\\path')); + $this->assertEquals('/path', \OC\Files\Filesystem::normalizePath('\\path', false)); + $this->assertEquals('/path', \OC\Files\Filesystem::normalizePath('\\path\\')); + $this->assertEquals('/path/', \OC\Files\Filesystem::normalizePath('\\path\\', false)); + $this->assertEquals('/foo/bar', \OC\Files\Filesystem::normalizePath('\\foo\\\\bar\\')); + $this->assertEquals('/foo/bar/', \OC\Files\Filesystem::normalizePath('\\foo\\\\bar\\', false)); + $this->assertEquals('/foo/bar', \OC\Files\Filesystem::normalizePath('\\foo\\\\\\\\bar')); + $this->assertEquals('/foo/bar', \OC\Files\Filesystem::normalizePath('\\foo\\\\\\\\\\bar')); + $this->assertEquals('/foo/bar', \OC\Files\Filesystem::normalizePath('\\foo\\bar\\.')); + $this->assertEquals('/foo/bar', \OC\Files\Filesystem::normalizePath('\\foo\\bar\\.\\')); + $this->assertEquals('/foo/bar/', \OC\Files\Filesystem::normalizePath('\\foo\\bar\\.\\', false)); + $this->assertEquals('/foo/bar', \OC\Files\Filesystem::normalizePath('\\foo\\bar\\.\\.')); + $this->assertEquals('/foo/bar', \OC\Files\Filesystem::normalizePath('\\foo\\bar\\.\\.\\')); + $this->assertEquals('/foo/bar/', \OC\Files\Filesystem::normalizePath('\\foo\\bar\\.\\.\\', false)); + $this->assertEquals('/foo/bar', \OC\Files\Filesystem::normalizePath('\\foo\\.\\bar\\')); + $this->assertEquals('/foo/bar/', \OC\Files\Filesystem::normalizePath('\\foo\\.\\bar\\', false)); + $this->assertEquals('/foo/.bar', \OC\Files\Filesystem::normalizePath('\\foo\\.bar\\')); + $this->assertEquals('/foo/.bar/', \OC\Files\Filesystem::normalizePath('\\foo\\.bar\\', false)); + $this->assertEquals('/foo/.bar/tee', \OC\Files\Filesystem::normalizePath('\\foo\\.bar\\tee')); + + // normalize does not resolve '..' (by design) + $this->assertEquals('/foo/..', \OC\Files\Filesystem::normalizePath('\\foo\\..\\')); + + if (class_exists('Patchwork\PHP\Shim\Normalizer')) { + $this->assertEquals("/foo/bar\xC3\xBC", \OC\Files\Filesystem::normalizePath("\\foo\\baru\xCC\x88")); + } + } + public function testHooks() { - if(\OC\Files\Filesystem::getView()){ + if (\OC\Files\Filesystem::getView()) { $user = \OC_User::getUser(); - }else{ - $user=uniqid(); - \OC\Files\Filesystem::init($user, '/'.$user.'/files'); + } else { + $user = uniqid(); + \OC\Files\Filesystem::init($user, '/' . $user . '/files'); } \OC_Hook::clear('OC_Filesystem'); \OC_Hook::connect('OC_Filesystem', 'post_write', $this, 'dummyHook'); \OC\Files\Filesystem::mount('OC\Files\Storage\Temporary', array(), '/'); - $rootView=new \OC\Files\View(''); - $rootView->mkdir('/'.$user); - $rootView->mkdir('/'.$user.'/files'); + $rootView = new \OC\Files\View(''); + $rootView->mkdir('/' . $user); + $rootView->mkdir('/' . $user . '/files'); // \OC\Files\Filesystem::file_put_contents('/foo', 'foo'); \OC\Files\Filesystem::mkdir('/bar'); @@ -103,6 +161,67 @@ class Filesystem extends \PHPUnit_Framework_TestCase { // \OC\Files\Filesystem::file_put_contents('/bar//foo', $fh); } + /** + * Tests that a local storage mount is used when passed user + * does not exist. + */ + public function testLocalMountWhenUserDoesNotExist() { + $datadir = \OC_Config::getValue("datadirectory", \OC::$SERVERROOT . "/data"); + $userId = uniqid('user_'); + + \OC\Files\Filesystem::initMountPoints($userId); + + $homeMount = \OC\Files\Filesystem::getStorage('/' . $userId . '/'); + + $this->assertInstanceOf('\OC\Files\Storage\Local', $homeMount); + $this->assertEquals('local::' . $datadir . '/' . $userId . '/', $homeMount->getId()); + } + + /** + * Tests that the home storage is used for the user's mount point + */ + public function testHomeMount() { + $userId = uniqid('user_'); + + \OC_User::createUser($userId, $userId); + + \OC\Files\Filesystem::initMountPoints($userId); + + $homeMount = \OC\Files\Filesystem::getStorage('/' . $userId . '/'); + + $this->assertInstanceOf('\OC\Files\Storage\Home', $homeMount); + $this->assertEquals('home::' . $userId, $homeMount->getId()); + + \OC_User::deleteUser($userId); + } + + /** + * Tests that the home storage is used in legacy mode + * for the user's mount point + */ + public function testLegacyHomeMount() { + $datadir = \OC_Config::getValue("datadirectory", \OC::$SERVERROOT . "/data"); + $userId = uniqid('user_'); + + // insert storage into DB by constructing it + // to make initMountsPoint find its existence + $localStorage = new \OC\Files\Storage\Local(array('datadir' => $datadir . '/' . $userId . '/')); + // this will trigger the insert + $cache = $localStorage->getCache(); + + \OC_User::createUser($userId, $userId); + \OC\Files\Filesystem::initMountPoints($userId); + + $homeMount = \OC\Files\Filesystem::getStorage('/' . $userId . '/'); + + $this->assertInstanceOf('\OC\Files\Storage\Home', $homeMount); + $this->assertEquals('local::' . $datadir . '/' . $userId . '/', $homeMount->getId()); + + \OC_User::deleteUser($userId); + // delete storage entry + $cache->clear(); + } + public function dummyHook($arguments) { $path = $arguments['path']; $this->assertEquals($path, \OC\Files\Filesystem::normalizePath($path)); //the path passed to the hook should already be normalized diff --git a/tests/lib/files/storage/home.php b/tests/lib/files/storage/home.php new file mode 100644 index 00000000000..885291e4404 --- /dev/null +++ b/tests/lib/files/storage/home.php @@ -0,0 +1,96 @@ +<?php +/** + * ownCloud + * + * @author Robin Appelman + * @copyright 2012 Robin Appelman icewind@owncloud.com + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE + * License as published by the Free Software Foundation; either + * version 3 of the License, or any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU AFFERO GENERAL PUBLIC LICENSE for more details. + * + * You should have received a copy of the GNU Affero General Public + * License along with this library. If not, see <http://www.gnu.org/licenses/>. + * + */ + +namespace Test\Files\Storage; + +use OC\User\User; + +class DummyUser extends User { + private $home; + + private $uid; + + public function __construct($uid, $home) { + $this->uid = $uid; + $this->home = $home; + } + + public function getHome() { + return $this->home; + } + + public function getUID() { + return $this->uid; + } +} + +class Home extends Storage { + /** + * @var string tmpDir + */ + private $tmpDir; + + /** + * @var \OC\User\User $user + */ + private $user; + + public function setUp() { + $this->tmpDir = \OC_Helper::tmpFolder(); + $this->userId = uniqid('user_'); + $this->user = new DummyUser($this->userId, $this->tmpDir); + $this->instance = new \OC\Files\Storage\Home(array('user' => $this->user)); + } + + public function tearDown() { + \OC_Helper::rmdirr($this->tmpDir); + } + + /** + * Tests that the root path matches the data dir + */ + public function testRoot() { + $this->assertEquals($this->tmpDir, $this->instance->getLocalFolder('')); + } + + /** + * Tests that the home id is in the format home::user1 + */ + public function testId() { + $this->assertEquals('home::' . $this->userId, $this->instance->getId()); + } + + /** + * Tests that the legacy home id is in the format local::/path/to/datadir/user1/ + */ + public function testLegacyId() { + $this->instance = new \OC\Files\Storage\Home(array('user' => $this->user, 'legacy' => true)); + $this->assertEquals('local::' . $this->tmpDir . '/', $this->instance->getId()); + } + + /** + * Tests that getCache() returns an instance of HomeCache + */ + public function testGetCacheReturnsHomeCache() { + $this->assertInstanceOf('\OC\Files\Cache\HomeCache', $this->instance->getCache()); + } +} diff --git a/tests/lib/files/storage/storage.php b/tests/lib/files/storage/storage.php index 3f339a10016..182c014d999 100644 --- a/tests/lib/files/storage/storage.php +++ b/tests/lib/files/storage/storage.php @@ -42,18 +42,28 @@ abstract class Storage extends \PHPUnit_Framework_TestCase { $this->assertTrue($this->instance->isUpdatable('/'), 'Root folder is not writable'); } - public function testDirectories() { - $this->assertFalse($this->instance->file_exists('/folder')); + /** + * Check that the test() function works + */ + public function testTestFunction() { + $this->assertTrue($this->instance->test()); + } + + /** + * @dataProvider directoryProvider + */ + public function testDirectories($directory) { + $this->assertFalse($this->instance->file_exists('/'.$directory)); - $this->assertTrue($this->instance->mkdir('/folder')); + $this->assertTrue($this->instance->mkdir('/'.$directory)); - $this->assertTrue($this->instance->file_exists('/folder')); - $this->assertTrue($this->instance->is_dir('/folder')); - $this->assertFalse($this->instance->is_file('/folder')); - $this->assertEquals('dir', $this->instance->filetype('/folder')); - $this->assertEquals(0, $this->instance->filesize('/folder')); - $this->assertTrue($this->instance->isReadable('/folder')); - $this->assertTrue($this->instance->isUpdatable('/folder')); + $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(); @@ -62,14 +72,14 @@ abstract class Storage extends \PHPUnit_Framework_TestCase { $content[] = $file; } } - $this->assertEquals(array('folder'), $content); + $this->assertEquals(array($directory), $content); - $this->assertFalse($this->instance->mkdir('/folder')); //cant create existing folders - $this->assertTrue($this->instance->rmdir('/folder')); + $this->assertFalse($this->instance->mkdir('/'.$directory)); //cant create existing folders + $this->assertTrue($this->instance->rmdir('/'.$directory)); - $this->assertFalse($this->instance->file_exists('/folder')); + $this->assertFalse($this->instance->file_exists('/'.$directory)); - $this->assertFalse($this->instance->rmdir('/folder')); //cant remove non existing folders + $this->assertFalse($this->instance->rmdir('/'.$directory)); //cant remove non existing folders $dh = $this->instance->opendir('/'); $content = array(); @@ -81,6 +91,14 @@ abstract class Storage extends \PHPUnit_Framework_TestCase { $this->assertEquals(array(), $content); } + public function directoryProvider() + { + return array( + array('folder'), + array(' folder'), + array('folder '), + ); + } /** * test the various uses of file_get_contents and file_put_contents */ @@ -128,7 +146,15 @@ abstract class Storage extends \PHPUnit_Framework_TestCase { $this->instance->rename('/source.txt', '/target2.txt'); $this->assertTrue($this->instance->file_exists('/target2.txt')); $this->assertFalse($this->instance->file_exists('/source.txt')); - $this->assertEquals(file_get_contents($textFile), $this->instance->file_get_contents('/target.txt')); + $this->assertEquals(file_get_contents($textFile), $this->instance->file_get_contents('/target2.txt')); + + // move to overwrite + $testContents = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; + $this->instance->file_put_contents('/target3.txt', $testContents); + $this->instance->rename('/target2.txt', '/target3.txt'); + $this->assertTrue($this->instance->file_exists('/target3.txt')); + $this->assertFalse($this->instance->file_exists('/target2.txt')); + $this->assertEquals(file_get_contents($textFile), $this->instance->file_get_contents('/target3.txt')); } public function testLocal() { @@ -171,8 +197,9 @@ abstract class Storage extends \PHPUnit_Framework_TestCase { $this->assertTrue($this->instance->hasUpdated('/lorem.txt', $ctimeStart - 5)); $this->assertTrue($this->instance->hasUpdated('/', $ctimeStart - 5)); - $this->assertTrue(($ctimeStart - 5) <= $mTime); - $this->assertTrue($mTime <= ($ctimeEnd + 1)); + // check that ($ctimeStart - 5) <= $mTime <= ($ctimeEnd + 1) + $this->assertGreaterThanOrEqual(($ctimeStart - 5), $mTime); + $this->assertLessThanOrEqual(($ctimeEnd + 1), $mTime); $this->assertEquals(filesize($textFile), $this->instance->filesize('/lorem.txt')); $stat = $this->instance->stat('/lorem.txt'); @@ -191,6 +218,17 @@ abstract class Storage extends \PHPUnit_Framework_TestCase { $this->assertTrue($this->instance->hasUpdated('/', $mtimeStart - 5)); } + public function testUnlink() { + $textFile = \OC::$SERVERROOT . '/tests/data/lorem.txt'; + $this->instance->file_put_contents('/lorem.txt', file_get_contents($textFile)); + + $this->assertTrue($this->instance->file_exists('/lorem.txt')); + + $this->assertTrue($this->instance->unlink('/lorem.txt')); + + $this->assertFalse($this->instance->file_exists('/lorem.txt')); + } + public function testFOpen() { $textFile = \OC::$SERVERROOT . '/tests/data/lorem.txt'; @@ -213,7 +251,8 @@ abstract class Storage extends \PHPUnit_Framework_TestCase { public function testTouchCreateFile() { $this->assertFalse($this->instance->file_exists('foo')); - $this->instance->touch('foo'); + // returns true on success + $this->assertTrue($this->instance->touch('foo')); $this->assertTrue($this->instance->file_exists('foo')); } @@ -222,7 +261,19 @@ abstract class Storage extends \PHPUnit_Framework_TestCase { $this->instance->mkdir('folder/bar'); $this->instance->file_put_contents('folder/asd.txt', 'foobar'); $this->instance->file_put_contents('folder/bar/foo.txt', 'asd'); - $this->instance->rmdir('folder'); + $this->assertTrue($this->instance->rmdir('folder')); + $this->assertFalse($this->instance->file_exists('folder/asd.txt')); + $this->assertFalse($this->instance->file_exists('folder/bar/foo.txt')); + $this->assertFalse($this->instance->file_exists('folder/bar')); + $this->assertFalse($this->instance->file_exists('folder')); + } + + public function testRecursiveUnlink() { + $this->instance->mkdir('folder'); + $this->instance->mkdir('folder/bar'); + $this->instance->file_put_contents('folder/asd.txt', 'foobar'); + $this->instance->file_put_contents('folder/bar/foo.txt', 'asd'); + $this->assertTrue($this->instance->unlink('folder')); $this->assertFalse($this->instance->file_exists('folder/asd.txt')); $this->assertFalse($this->instance->file_exists('folder/bar/foo.txt')); $this->assertFalse($this->instance->file_exists('folder/bar')); diff --git a/tests/lib/files/storage/wrapper/quota.php b/tests/lib/files/storage/wrapper/quota.php index 3702f8154f5..87bafb64d41 100644 --- a/tests/lib/files/storage/wrapper/quota.php +++ b/tests/lib/files/storage/wrapper/quota.php @@ -58,4 +58,45 @@ class Quota extends \Test\Files\Storage\Storage { fclose($stream); $this->assertEquals('foobarqwe', $instance->file_get_contents('foo')); } + + public function testReturnFalseWhenFopenFailed(){ + $failStorage = $this->getMock( + '\OC\Files\Storage\Local', + array('fopen'), + array(array('datadir' => $this->tmpDir))); + $failStorage->expects($this->any()) + ->method('fopen') + ->will($this->returnValue(false)); + + $instance = new \OC\Files\Storage\Wrapper\Quota(array('storage' => $failStorage, 'quota' => 1000)); + + $this->assertFalse($instance->fopen('failedfopen', 'r')); + } + + public function testReturnRegularStreamOnRead(){ + $instance = $this->getLimitedStorage(9); + + // create test file first + $stream = $instance->fopen('foo', 'w+'); + fwrite($stream, 'blablacontent'); + fclose($stream); + + $stream = $instance->fopen('foo', 'r'); + $meta = stream_get_meta_data($stream); + $this->assertEquals('plainfile', $meta['wrapper_type']); + fclose($stream); + + $stream = $instance->fopen('foo', 'rb'); + $meta = stream_get_meta_data($stream); + $this->assertEquals('plainfile', $meta['wrapper_type']); + fclose($stream); + } + + public function testReturnQuotaStreamOnWrite(){ + $instance = $this->getLimitedStorage(9); + $stream = $instance->fopen('foo', 'w+'); + $meta = stream_get_meta_data($stream); + $this->assertEquals('user-space', $meta['wrapper_type']); + fclose($stream); + } } diff --git a/tests/lib/files/stream/quota.php b/tests/lib/files/stream/quota.php index 22d3e93592c..b11f0ac74c0 100644 --- a/tests/lib/files/stream/quota.php +++ b/tests/lib/files/stream/quota.php @@ -75,4 +75,76 @@ class Quota extends \PHPUnit_Framework_TestCase { rewind($stream); $this->assertEquals('qwerty', fread($stream, 100)); } + + public function testFseekReturnsSuccess() { + $stream = $this->getStream('w+', 100); + fwrite($stream, '0123456789'); + $this->assertEquals(0, fseek($stream, 3, SEEK_SET)); + $this->assertEquals(0, fseek($stream, -1, SEEK_CUR)); + $this->assertEquals(0, fseek($stream, -4, SEEK_END)); + } + + public function testWriteAfterSeekEndWithEnoughSpace() { + $stream = $this->getStream('w+', 100); + fwrite($stream, '0123456789'); + fseek($stream, -3, SEEK_END); + $this->assertEquals(11, fwrite($stream, 'abcdefghijk')); + rewind($stream); + $this->assertEquals('0123456abcdefghijk', fread($stream, 100)); + } + + public function testWriteAfterSeekEndWithNotEnoughSpace() { + $stream = $this->getStream('w+', 13); + fwrite($stream, '0123456789'); + // seek forward first to potentially week out + // potential limit calculation errors + fseek($stream, 4, SEEK_SET); + // seek to the end + fseek($stream, -3, SEEK_END); + $this->assertEquals(6, fwrite($stream, 'abcdefghijk')); + rewind($stream); + $this->assertEquals('0123456abcdef', fread($stream, 100)); + } + + public function testWriteAfterSeekSetWithEnoughSpace() { + $stream = $this->getStream('w+', 100); + fwrite($stream, '0123456789'); + fseek($stream, 7, SEEK_SET); + $this->assertEquals(11, fwrite($stream, 'abcdefghijk')); + rewind($stream); + $this->assertEquals('0123456abcdefghijk', fread($stream, 100)); + } + + public function testWriteAfterSeekSetWithNotEnoughSpace() { + $stream = $this->getStream('w+', 13); + fwrite($stream, '0123456789'); + fseek($stream, 7, SEEK_SET); + $this->assertEquals(6, fwrite($stream, 'abcdefghijk')); + rewind($stream); + $this->assertEquals('0123456abcdef', fread($stream, 100)); + } + + public function testWriteAfterSeekCurWithEnoughSpace() { + $stream = $this->getStream('w+', 100); + fwrite($stream, '0123456789'); + rewind($stream); + fseek($stream, 3, SEEK_CUR); + fseek($stream, 5, SEEK_CUR); + fseek($stream, -1, SEEK_CUR); + $this->assertEquals(11, fwrite($stream, 'abcdefghijk')); + rewind($stream); + $this->assertEquals('0123456abcdefghijk', fread($stream, 100)); + } + + public function testWriteAfterSeekCurWithNotEnoughSpace() { + $stream = $this->getStream('w+', 13); + fwrite($stream, '0123456789'); + rewind($stream); + fseek($stream, 3, SEEK_CUR); + fseek($stream, 5, SEEK_CUR); + fseek($stream, -1, SEEK_CUR); + $this->assertEquals(6, fwrite($stream, 'abcdefghijk')); + rewind($stream); + $this->assertEquals('0123456abcdef', fread($stream, 100)); + } } diff --git a/tests/lib/files/view.php b/tests/lib/files/view.php index 3043f132b73..72a2f854cb2 100644 --- a/tests/lib/files/view.php +++ b/tests/lib/files/view.php @@ -15,7 +15,7 @@ class TemporaryNoTouch extends \OC\Files\Storage\Temporary { class View extends \PHPUnit_Framework_TestCase { /** - * @var \OC\Files\Storage\Storage[] $storages; + * @var \OC\Files\Storage\Storage[] $storages */ private $storages = array(); @@ -67,6 +67,11 @@ class View extends \PHPUnit_Framework_TestCase { $this->assertEquals($storageSize * 3, $cachedData['size']); $this->assertEquals('httpd/unix-directory', $cachedData['mimetype']); + // get cached data excluding mount points + $cachedData = $rootView->getFileInfo('/', false); + $this->assertEquals($storageSize, $cachedData['size']); + $this->assertEquals('httpd/unix-directory', $cachedData['mimetype']); + $cachedData = $rootView->getFileInfo('/folder'); $this->assertEquals($storageSize + $textSize, $cachedData['size']); $this->assertEquals('httpd/unix-directory', $cachedData['mimetype']); @@ -304,6 +309,48 @@ class View extends \PHPUnit_Framework_TestCase { /** * @medium */ + function testUnlink() { + $storage1 = $this->getTestStorage(); + $storage2 = $this->getTestStorage(); + \OC\Files\Filesystem::mount($storage1, array(), '/'); + \OC\Files\Filesystem::mount($storage2, array(), '/substorage'); + + $rootView = new \OC\Files\View(''); + $rootView->file_put_contents('/foo.txt', 'asd'); + $rootView->file_put_contents('/substorage/bar.txt', 'asd'); + + $this->assertTrue($rootView->file_exists('foo.txt')); + $this->assertTrue($rootView->file_exists('substorage/bar.txt')); + + $this->assertTrue($rootView->unlink('foo.txt')); + $this->assertTrue($rootView->unlink('substorage/bar.txt')); + + $this->assertFalse($rootView->file_exists('foo.txt')); + $this->assertFalse($rootView->file_exists('substorage/bar.txt')); + } + + /** + * @medium + */ + function testUnlinkRootMustFail() { + $storage1 = $this->getTestStorage(); + $storage2 = $this->getTestStorage(); + \OC\Files\Filesystem::mount($storage1, array(), '/'); + \OC\Files\Filesystem::mount($storage2, array(), '/substorage'); + + $rootView = new \OC\Files\View(''); + $rootView->file_put_contents('/foo.txt', 'asd'); + $rootView->file_put_contents('/substorage/bar.txt', 'asd'); + + $this->assertFalse($rootView->unlink('')); + $this->assertFalse($rootView->unlink('/')); + $this->assertFalse($rootView->unlink('substorage')); + $this->assertFalse($rootView->unlink('/substorage')); + } + + /** + * @medium + */ function testTouch() { $storage = $this->getTestStorage(true, '\Test\Files\TemporaryNoTouch'); @@ -391,4 +438,128 @@ class View extends \PHPUnit_Framework_TestCase { $this->storages[] = $storage; return $storage; } + + private $createHookPath; + + function dummyCreateHook($params) { + $this->createHookPath = $params['path']; + } + + /** + * @medium + */ + function testViewHooksIfRootStartsTheSame() { + $storage1 = $this->getTestStorage(); + $storage2 = $this->getTestStorage(); + $defaultRoot = \OC\Files\Filesystem::getRoot(); + \OC\Files\Filesystem::mount($storage1, array(), '/'); + \OC\Files\Filesystem::mount($storage2, array(), $defaultRoot . '_substorage'); + \OC_Hook::connect('OC_Filesystem', 'post_write', $this, 'dummyHook'); + + $subView = new \OC\Files\View($defaultRoot . '_substorage'); + $this->hookPath = null; + + $subView->file_put_contents('/foo.txt', 'asd'); + $this->assertNull($this->hookPath); + } + + 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'); + + $view = new \OC\Files\View($defaultRoot); + $this->hookPath = null; + + $view->file_put_contents('/asd.txt', 'foo'); + $this->assertEquals('/asd.txt', $this->createHookPath); + $this->createHookPath = null; + + $view->file_put_contents('/asd.txt', 'foo'); + $this->assertNull($this->createHookPath); + } + + /** + * @dataProvider resolvePathTestProvider + */ + public function testResolvePath($expected, $pathToTest) { + $storage1 = $this->getTestStorage(); + \OC\Files\Filesystem::mount($storage1, array(), '/'); + + $view = new \OC\Files\View(''); + + $result = $view->resolvePath($pathToTest); + $this->assertEquals($expected, $result[1]); + + $exists = $view->file_exists($pathToTest); + $this->assertTrue($exists); + + $exists = $view->file_exists($result[1]); + $this->assertTrue($exists); + } + + function resolvePathTestProvider() { + return array( + array('foo.txt', 'foo.txt'), + array('foo.txt', '/foo.txt'), + array('folder', 'folder'), + array('folder', '/folder'), + array('folder', 'folder/'), + array('folder', '/folder/'), + array('folder/bar.txt', 'folder/bar.txt'), + array('folder/bar.txt', '/folder/bar.txt'), + array('', ''), + array('', '/'), + ); + } + + public function testUTF8Names() { + $names = array('虚', '和知しゃ和で', 'regular ascii', 'sɨˈrɪlɪk', 'ѨѬ', 'أنا أحب القراءة كثيرا'); + + $storage = new \OC\Files\Storage\Temporary(array()); + \OC\Files\Filesystem::mount($storage, array(), '/'); + + $rootView = new \OC\Files\View(''); + foreach ($names as $name) { + $rootView->file_put_contents('/' . $name, 'dummy content'); + } + + $list = $rootView->getDirectoryContent('/'); + + $this->assertCount(count($names), $list); + foreach ($list as $item) { + $this->assertContains($item['name'], $names); + } + + $cache = $storage->getCache(); + $scanner = $storage->getScanner(); + $scanner->scan(''); + + $list = $cache->getFolderContents(''); + + $this->assertCount(count($names), $list); + foreach ($list as $item) { + $this->assertContains($item['name'], $names); + } + } + + public function testTouchNotSupported() { + $storage = new TemporaryNoTouch(array()); + $scanner = $storage->getScanner(); + \OC\Files\Filesystem::mount($storage, array(), '/test/'); + $past = time() - 100; + $storage->file_put_contents('test', 'foobar'); + $scanner->scan(''); + $view = new \OC\Files\View(''); + $info = $view->getFileInfo('/test/test'); + + $view->touch('/test/test', $past); + $scanner->scanFile('test', \OC\Files\Cache\Scanner::REUSE_ETAG); + + $info2 = $view->getFileInfo('/test/test'); + $this->assertEquals($info['etag'], $info2['etag']); + } } diff --git a/tests/lib/group.php b/tests/lib/group.php index d2c9ce46148..8de8d033e19 100644 --- a/tests/lib/group.php +++ b/tests/lib/group.php @@ -109,6 +109,24 @@ 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()); diff --git a/tests/lib/helper.php b/tests/lib/helper.php index b4d896e5196..4311215795c 100644 --- a/tests/lib/helper.php +++ b/tests/lib/helper.php @@ -208,4 +208,39 @@ class Test_Helper extends PHPUnit_Framework_TestCase { ->will($this->returnValue(true)); // filename(1) (2) (3).ext exists $this->assertEquals('dir/filename(1) (2) (4).ext', OC_Helper::buildNotExistingFileNameForView('dir', 'filename(1) (2) (3).ext', $viewMock)); } + + /** + * @dataProvider streamCopyDataProvider + */ + public function testStreamCopy($expectedCount, $expectedResult, $source, $target) { + + if (is_string($source)) { + $source = fopen($source, 'r'); + } + if (is_string($target)) { + $target = fopen($target, 'w'); + } + + list($count, $result) = \OC_Helper::streamCopy($source, $target); + + if (is_resource($source)) { + fclose($source); + } + if (is_resource($target)) { + fclose($target); + } + + $this->assertSame($expectedCount, $count); + $this->assertSame($expectedResult, $result); + } + + + function streamCopyDataProvider() { + return array( + array(0, false, false, false), + array(0, false, \OC::$SERVERROOT . '/tests/data/lorem.txt', false), + array(filesize(\OC::$SERVERROOT . '/tests/data/lorem.txt'), true, \OC::$SERVERROOT . '/tests/data/lorem.txt', \OC::$SERVERROOT . '/tests/data/lorem-copy.txt'), + array(3670, true, \OC::$SERVERROOT . '/tests/data/testimage.png', \OC::$SERVERROOT . '/tests/data/testimage-copy.png'), + ); + } } diff --git a/tests/lib/l10n.php b/tests/lib/l10n.php index 12eac818f84..5ddf2290c35 100644 --- a/tests/lib/l10n.php +++ b/tests/lib/l10n.php @@ -64,4 +64,45 @@ class Test_L10n extends PHPUnit_Framework_TestCase { $l = new OC_L10N('test'); $this->assertSame('February 13, 2009 23:31', $l->l('datetime', 1234567890)); } + + /** + * @dataProvider findLanguageData + */ + public function testFindLanguage($default, $preference, $expected) { + OC_User::setUserId(null); + if (is_null($default)) { + OC_Config::deleteKey('default_language'); + } else { + OC_Config::setValue('default_language', $default); + } + $_SERVER['HTTP_ACCEPT_LANGUAGE'] = $preference; + + $reflection = new \ReflectionClass('OC_L10N'); + $prop = $reflection->getProperty('language'); + $prop->setAccessible(1); + $prop->setValue(''); + $prop->setAccessible(0); + + $this->assertSame($expected, OC_L10N::findLanguage()); + } + + public function findLanguageData() { + return array( + // Exact match + array(null, 'de-DE,en;q=0.5', 'de_DE'), + array(null, 'de-DE,en-US;q=0.8,en;q=0.6', 'de_DE'), + + // Best match + array(null, 'de-US,en;q=0.5', 'de'), + array(null, 'de-US,en-US;q=0.8,en;q=0.6', 'de'), + + // The default_language config setting overrides browser preferences. + array('es_AR', 'de-DE,en;q=0.5', 'es_AR'), + array('es_AR', 'de-DE,en-US;q=0.8,en;q=0.6', 'es_AR'), + + // Worst case default to english + array(null, '', 'en'), + array(null, null, 'en'), + ); + } } diff --git a/tests/lib/memcache/memcached.php b/tests/lib/memcache/memcached.php index 4b38ae8ef3c..fdab32693ff 100644 --- a/tests/lib/memcache/memcached.php +++ b/tests/lib/memcache/memcached.php @@ -10,11 +10,17 @@ namespace Test\Memcache; class Memcached extends Cache { - public function setUp() { + static public function setUpBeforeClass() { if (!\OC\Memcache\Memcached::isAvailable()) { - $this->markTestSkipped('The memcached extension is not available.'); - return; + self::markTestSkipped('The memcached extension is not available.'); + } + $instance = new \OC\Memcache\Memcached(uniqid()); + if ($instance->set(uniqid(), uniqid()) === false) { + self::markTestSkipped('memcached server seems to be down.'); } + } + + public function setUp() { $this->instance = new \OC\Memcache\Memcached(uniqid()); } } diff --git a/tests/lib/ocs/privatedata.php b/tests/lib/ocs/privatedata.php new file mode 100644 index 00000000000..ea8413734f1 --- /dev/null +++ b/tests/lib/ocs/privatedata.php @@ -0,0 +1,141 @@ +<?php + /** + * ownCloud + * + * @author Thomas Müller + * @copyright 2013 Thomas Müller deepdiver@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_OC_OCS_Privatedata extends PHPUnit_Framework_TestCase +{ + + private $appKey; + + public function setUp() { + \OC::$session->set('user_id', 'user1'); + $this->appKey = uniqid('app'); + } + + public function tearDown() { + } + + public function testGetEmptyOne() { + $params = array('app' => $this->appKey, 'key' => '123'); + $result = OC_OCS_Privatedata::get($params); + $this->assertOcsResult(0, $result); + } + + public function testGetEmptyAll() { + $params = array('app' => $this->appKey); + $result = OC_OCS_Privatedata::get($params); + $this->assertOcsResult(0, $result); + } + + public function testSetOne() { + $_POST = array('value' => 123456789); + $params = array('app' => $this->appKey, 'key' => 'k-1'); + $result = OC_OCS_Privatedata::set($params); + $this->assertEquals(100, $result->getStatusCode()); + + $result = OC_OCS_Privatedata::get($params); + $this->assertOcsResult(1, $result); + } + + public function testSetExisting() { + $_POST = array('value' => 123456789); + $params = array('app' => $this->appKey, 'key' => 'k-10'); + $result = OC_OCS_Privatedata::set($params); + $this->assertEquals(100, $result->getStatusCode()); + + $result = OC_OCS_Privatedata::get($params); + $this->assertOcsResult(1, $result); + $data = $result->getData(); + $data = $data[0]; + $this->assertEquals('123456789', $data['value']); + + $_POST = array('value' => 'updated'); + $params = array('app' => $this->appKey, 'key' => 'k-10'); + $result = OC_OCS_Privatedata::set($params); + $this->assertEquals(100, $result->getStatusCode()); + + $result = OC_OCS_Privatedata::get($params); + $this->assertOcsResult(1, $result); + $data = $result->getData(); + $data = $data[0]; + $this->assertEquals('updated', $data['value']); + } + + public function testSetMany() { + $_POST = array('value' => 123456789); + + // set key 'k-1' + $params = array('app' => $this->appKey, 'key' => 'k-1'); + $result = OC_OCS_Privatedata::set($params); + $this->assertEquals(100, $result->getStatusCode()); + + // set key 'k-2' + $params = array('app' => $this->appKey, 'key' => 'k-2'); + $result = OC_OCS_Privatedata::set($params); + $this->assertEquals(100, $result->getStatusCode()); + + // query for all + $params = array('app' => $this->appKey); + $result = OC_OCS_Privatedata::get($params); + $this->assertOcsResult(2, $result); + } + + public function testDelete() { + $_POST = array('value' => 123456789); + + // set key 'k-1' + $params = array('app' => $this->appKey, 'key' => 'k-3'); + $result = OC_OCS_Privatedata::set($params); + $this->assertEquals(100, $result->getStatusCode()); + + $result = OC_OCS_Privatedata::delete($params); + $this->assertEquals(100, $result->getStatusCode()); + + $result = OC_OCS_Privatedata::get($params); + $this->assertOcsResult(0, $result); + } + + /** + * @dataProvider deleteWithEmptyKeysProvider + */ + public function testDeleteWithEmptyKeys($params) { + $result = OC_OCS_Privatedata::delete($params); + $this->assertEquals(101, $result->getStatusCode()); + } + + public function deleteWithEmptyKeysProvider() { + return array( + array(array()), + array(array('app' => '123')), + array(array('key' => '123')), + ); + } + + /** + * @param \OC_OCS_Result $result + */ + public function assertOcsResult($expectedArraySize, $result) { + $this->assertEquals(100, $result->getStatusCode()); + $data = $result->getData(); + $this->assertTrue(is_array($data)); + $this->assertEquals($expectedArraySize, sizeof($data)); + } +} diff --git a/tests/lib/preferences.php b/tests/lib/preferences.php index 68b794e9ea9..a8236909ded 100644 --- a/tests/lib/preferences.php +++ b/tests/lib/preferences.php @@ -101,28 +101,28 @@ class Test_Preferences extends PHPUnit_Framework_TestCase { $this->assertTrue(\OC_Preferences::deleteKey('Deleteuser', 'deleteapp', 'deletekey')); $query = \OC_DB::prepare('SELECT `configvalue` FROM `*PREFIX*preferences` WHERE `userid` = ? AND `appid` = ? AND `configkey` = ?'); $result = $query->execute(array('Deleteuser', 'deleteapp', 'deletekey')); - $this->assertEquals(0, $result->numRows()); + $this->assertEquals(0, count($result->fetchAll())); } public function testDeleteApp() { $this->assertTrue(\OC_Preferences::deleteApp('Deleteuser', 'deleteapp')); $query = \OC_DB::prepare('SELECT `configvalue` FROM `*PREFIX*preferences` WHERE `userid` = ? AND `appid` = ?'); $result = $query->execute(array('Deleteuser', 'deleteapp')); - $this->assertEquals(0, $result->numRows()); + $this->assertEquals(0, count($result->fetchAll())); } public function testDeleteUser() { $this->assertTrue(\OC_Preferences::deleteUser('Deleteuser')); $query = \OC_DB::prepare('SELECT `configvalue` FROM `*PREFIX*preferences` WHERE `userid` = ?'); $result = $query->execute(array('Deleteuser')); - $this->assertEquals(0, $result->numRows()); + $this->assertEquals(0, count($result->fetchAll())); } public function testDeleteAppFromAllUsers() { $this->assertTrue(\OC_Preferences::deleteAppFromAllUsers('someapp')); $query = \OC_DB::prepare('SELECT `configvalue` FROM `*PREFIX*preferences` WHERE `appid` = ?'); $result = $query->execute(array('someapp')); - $this->assertEquals(0, $result->numRows()); + $this->assertEquals(0, count($result->fetchAll())); } } diff --git a/tests/lib/preview.php b/tests/lib/preview.php index d0cdd2c44fb..353b66fd6d6 100644 --- a/tests/lib/preview.php +++ b/tests/lib/preview.php @@ -134,13 +134,11 @@ class Preview extends \PHPUnit_Framework_TestCase { } private function initFS() { - if(\OC\Files\Filesystem::getView()){ - $user = \OC_User::getUser(); - }else{ - $user=uniqid(); - \OC_User::setUserId($user); - \OC\Files\Filesystem::init($user, '/'.$user.'/files'); - } + // create a new user with his own filesystem view + // this gets called by each test in this test class + $user=uniqid(); + \OC_User::setUserId($user); + \OC\Files\Filesystem::init($user, '/'.$user.'/files'); \OC\Files\Filesystem::mount('OC\Files\Storage\Temporary', array(), '/'); diff --git a/tests/lib/request.php b/tests/lib/request.php new file mode 100644 index 00000000000..1d77acc70ae --- /dev/null +++ b/tests/lib/request.php @@ -0,0 +1,138 @@ +<?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_Request extends PHPUnit_Framework_TestCase { + + public function setUp() { + OC_Config::setValue('overwritewebroot', '/domain.tld/ownCloud'); + } + + public function tearDown() { + OC_Config::setValue('overwritewebroot', ''); + } + + public function testScriptNameOverWrite() { + $_SERVER['REMOTE_ADDR'] = '10.0.0.1'; + $_SERVER["SCRIPT_FILENAME"] = __FILE__; + + $scriptName = OC_Request::scriptName(); + $this->assertEquals('/domain.tld/ownCloud/tests/lib/request.php', $scriptName); + } + + /** + * @dataProvider rawPathInfoProvider + * @param $expected + * @param $requestUri + * @param $scriptName + */ + public function testRawPathInfo($expected, $requestUri, $scriptName) { + $_SERVER['REQUEST_URI'] = $requestUri; + $_SERVER['SCRIPT_NAME'] = $scriptName; + $rawPathInfo = OC_Request::getRawPathInfo(); + $this->assertEquals($expected, $rawPathInfo); + } + + function rawPathInfoProvider() { + return array( + array('/core/ajax/translations.php', 'index.php/core/ajax/translations.php', 'index.php'), + array('/core/ajax/translations.php', '/index.php/core/ajax/translations.php', '/index.php'), + array('/core/ajax/translations.php', '//index.php/core/ajax/translations.php', '/index.php'), + array('', '/oc/core', '/oc/core/index.php'), + array('', '/oc/core/', '/oc/core/index.php'), + array('', '/oc/core/index.php', '/oc/core/index.php'), + array('/core/ajax/translations.php', '/core/ajax/translations.php', 'index.php'), + array('/core/ajax/translations.php', '//core/ajax/translations.php', '/index.php'), + array('/core/ajax/translations.php', '/oc/core/ajax/translations.php', '/oc/index.php'), + array('/1', '/oc/core/1', '/oc/core/index.php'), + ); + } + + /** + * @dataProvider rawPathInfoThrowsExceptionProvider + * @expectedException Exception + * + * @param $requestUri + * @param $scriptName + */ + public function testRawPathInfoThrowsException($requestUri, $scriptName) { + $_SERVER['REQUEST_URI'] = $requestUri; + $_SERVER['SCRIPT_NAME'] = $scriptName; + OC_Request::getRawPathInfo(); + } + + function rawPathInfoThrowsExceptionProvider() { + return array( + array('/oc/core1', '/oc/core/index.php'), + ); + } + + /** + * @dataProvider userAgentProvider + */ + public function testUserAgent($testAgent, $userAgent, $matches) { + $_SERVER['HTTP_USER_AGENT'] = $testAgent; + $this->assertEquals($matches, OC_Request::isUserAgent($userAgent)); + } + + function userAgentProvider() { + return array( + array( + 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0)', + OC_Request::USER_AGENT_IE, + true + ), + array( + 'Mozilla/5.0 (X11; Linux i686; rv:24.0) Gecko/20100101 Firefox/24.0', + OC_Request::USER_AGENT_IE, + false + ), + array( + 'Mozilla/5.0 (Linux; Android 4.4; Nexus 4 Build/KRT16S) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.59 Mobile Safari/537.36', + OC_Request::USER_AGENT_ANDROID_MOBILE_CHROME, + true + ), + array( + 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0)', + OC_Request::USER_AGENT_ANDROID_MOBILE_CHROME, + false + ), + // test two values + array( + 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0)', + array( + OC_Request::USER_AGENT_IE, + OC_Request::USER_AGENT_ANDROID_MOBILE_CHROME, + ), + true + ), + array( + 'Mozilla/5.0 (Linux; Android 4.4; Nexus 4 Build/KRT16S) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.59 Mobile Safari/537.36', + array( + OC_Request::USER_AGENT_IE, + OC_Request::USER_AGENT_ANDROID_MOBILE_CHROME, + ), + true + ), + array( + 'Mozilla/5.0 (X11; Linux i686; rv:24.0) Gecko/20100101 Firefox/24.0', + OC_Request::USER_AGENT_FREEBOX, + false + ), + array( + 'Mozilla/5.0', + OC_Request::USER_AGENT_FREEBOX, + true + ), + array( + 'Fake Mozilla/5.0', + OC_Request::USER_AGENT_FREEBOX, + false + ), + ); + } +} diff --git a/tests/lib/share/share.php b/tests/lib/share/share.php index 8e9eef65d32..d6acee6c924 100644 --- a/tests/lib/share/share.php +++ b/tests/lib/share/share.php @@ -25,6 +25,8 @@ class Test_Share extends PHPUnit_Framework_TestCase { protected $userBackend; protected $user1; protected $user2; + protected $user3; + protected $user4; protected $groupBackend; protected $group1; protected $group2; @@ -135,20 +137,40 @@ class Test_Share extends PHPUnit_Framework_TestCase { OCP\Share::shareItem('test', 'test.txt', OCP\Share::SHARE_TYPE_USER, $this->user2, OCP\PERMISSION_READ), 'Failed asserting that user 1 successfully shared text.txt with user 2.' ); - $this->assertEquals( - array('test.txt'), + $this->assertContains( + 'test.txt', OCP\Share::getItemShared('test', 'test.txt', Test_Share_Backend::FORMAT_SOURCE), 'Failed asserting that test.txt is a shared file of user 1.' ); OC_User::setUserId($this->user2); - $this->assertEquals( - array('test.txt'), + $this->assertContains( + 'test.txt', OCP\Share::getItemSharedWith('test', 'test.txt', Test_Share_Backend::FORMAT_SOURCE), 'Failed asserting that user 2 has access to test.txt after initial sharing.' ); } + protected function shareUserTestFileWithUser($sharer, $receiver) { + OC_User::setUserId($sharer); + $this->assertTrue( + OCP\Share::shareItem('test', 'test.txt', OCP\Share::SHARE_TYPE_USER, $receiver, OCP\PERMISSION_READ | OCP\PERMISSION_SHARE), + 'Failed asserting that ' . $sharer . ' successfully shared text.txt with ' . $receiver . '.' + ); + $this->assertContains( + 'test.txt', + OCP\Share::getItemShared('test', 'test.txt', Test_Share_Backend::FORMAT_SOURCE), + 'Failed asserting that test.txt is a shared file of ' . $sharer . '.' + ); + + OC_User::setUserId($receiver); + $this->assertContains( + 'test.txt', + OCP\Share::getItemSharedWith('test', 'test.txt', Test_Share_Backend::FORMAT_SOURCE), + 'Failed asserting that ' . $receiver . ' has access to test.txt after initial sharing.' + ); + } + public function testShareWithUser() { // Invalid shares $message = 'Sharing test.txt failed, because the user '.$this->user1.' is the item owner'; @@ -328,22 +350,22 @@ class Test_Share extends PHPUnit_Framework_TestCase { OCP\Share::shareItem('test', 'test.txt', OCP\Share::SHARE_TYPE_GROUP, $this->group1, OCP\PERMISSION_READ), 'Failed asserting that user 1 successfully shared text.txt with group 1.' ); - $this->assertEquals( - array('test.txt'), + $this->assertContains( + 'test.txt', OCP\Share::getItemShared('test', 'test.txt', Test_Share_Backend::FORMAT_SOURCE), 'Failed asserting that test.txt is a shared file of user 1.' ); OC_User::setUserId($this->user2); - $this->assertEquals( - array('test.txt'), + $this->assertContains( + 'test.txt', OCP\Share::getItemSharedWith('test', 'test.txt', Test_Share_Backend::FORMAT_SOURCE), 'Failed asserting that user 2 has access to test.txt after initial sharing.' ); OC_User::setUserId($this->user3); - $this->assertEquals( - array('test.txt'), + $this->assertContains( + 'test.txt', OCP\Share::getItemSharedWith('test', 'test.txt', Test_Share_Backend::FORMAT_SOURCE), 'Failed asserting that user 3 has access to test.txt after initial sharing.' ); @@ -583,4 +605,97 @@ class Test_Share extends PHPUnit_Framework_TestCase { 'Failed asserting that an expired share could not be found.' ); } + + public function testUnshareAll() { + $this->shareUserTestFileWithUser($this->user1, $this->user2); + $this->shareUserTestFileWithUser($this->user2, $this->user3); + $this->shareUserTestFileWithUser($this->user3, $this->user4); + $this->shareUserOneTestFileWithGroupOne(); + + OC_User::setUserId($this->user1); + $this->assertEquals( + array('test.txt', 'test.txt'), + OCP\Share::getItemsShared('test', 'test.txt'), + 'Failed asserting that the test.txt file is shared exactly two times by user1.' + ); + + OC_User::setUserId($this->user2); + $this->assertEquals( + array('test.txt'), + OCP\Share::getItemsShared('test', 'test.txt'), + 'Failed asserting that the test.txt file is shared exactly once by user2.' + ); + + OC_User::setUserId($this->user3); + $this->assertEquals( + array('test.txt'), + OCP\Share::getItemsShared('test', 'test.txt'), + 'Failed asserting that the test.txt file is shared exactly once by user3.' + ); + + $this->assertTrue( + OCP\Share::unshareAll('test', 'test.txt'), + 'Failed asserting that user 3 successfully unshared all shares of the test.txt share.' + ); + + $this->assertEquals( + array(), + OCP\Share::getItemsShared('test'), + 'Failed asserting that the share of the test.txt file by user 3 has been removed.' + ); + + OC_User::setUserId($this->user1); + $this->assertEquals( + array(), + OCP\Share::getItemsShared('test'), + 'Failed asserting that both shares of the test.txt file by user 1 have been removed.' + ); + + OC_User::setUserId($this->user2); + $this->assertEquals( + array(), + OCP\Share::getItemsShared('test'), + 'Failed asserting that the share of the test.txt file by user 2 has been removed.' + ); + } + + /** + * @dataProvider checkPasswordProtectedShareDataProvider + * @param $expected + * @param $item + */ + public function testCheckPasswordProtectedShare($expected, $item) { + \OC::$session->set('public_link_authenticated', 100); + $result = \OCP\Share::checkPasswordProtectedShare($item); + $this->assertEquals($expected, $result); + } + + function checkPasswordProtectedShareDataProvider() { + return array( + array(true, array()), + array(true, array('share_with' => null)), + array(true, array('share_with' => '')), + array(true, array('share_with' => '1234567890', 'share_type' => '1')), + array(true, array('share_with' => '1234567890', 'share_type' => 1)), + array(true, array('share_with' => '1234567890', 'share_type' => '3', 'id' => 100)), + array(true, array('share_with' => '1234567890', 'share_type' => 3, 'id' => 100)), + array(false, array('share_with' => '1234567890', 'share_type' => '3', 'id' => 101)), + array(false, array('share_with' => '1234567890', 'share_type' => 3, 'id' => 101)), + ); + + /* + if (!isset($linkItem['share_with'])) { + return true; + } + + if ($linkItem['share_type'] != \OCP\Share::SHARE_TYPE_LINK) { + return true; + } + + if ( \OC::$session->exists('public_link_authenticated') + && \OC::$session->get('public_link_authenticated') === $linkItem['id'] ) { + return true; + } + * */ + } } diff --git a/tests/lib/template.php b/tests/lib/template.php index fd12119da58..b4f1a4c4053 100644 --- a/tests/lib/template.php +++ b/tests/lib/template.php @@ -46,7 +46,6 @@ class Test_TemplateFunctions extends PHPUnit_Framework_TestCase { $this->assertEquals("This is a good string!", $result); } - public function testPrintUnescaped() { $htmlString = "<script>alert('xss');</script>"; @@ -66,5 +65,194 @@ class Test_TemplateFunctions extends PHPUnit_Framework_TestCase { $this->assertEquals("This is a good string!", $result); } + // --------------------------------------------------------------------------- + // Test relative_modified_date with dates only + // --------------------------------------------------------------------------- + public function testRelativeDateToday(){ + $currentTime = 1380703592; + $elementTime = $currentTime; + $result = (string)relative_modified_date($elementTime, $currentTime, true); + + $this->assertEquals('today', $result); + + // 2 hours ago is still today + $elementTime = $currentTime - 2 * 3600; + $result = (string)relative_modified_date($elementTime, $currentTime, true); + + $this->assertEquals('today', $result); + } + + public function testRelativeDateYesterday(){ + $currentTime = 1380703592; + $elementTime = $currentTime - 24 * 3600; + $result = (string)relative_modified_date($elementTime, $currentTime, true); + + $this->assertEquals('yesterday', $result); + + // yesterday - 2 hours is still yesterday + $elementTime = $currentTime - 26 * 3600; + $result = (string)relative_modified_date($elementTime, $currentTime, true); + + $this->assertEquals('yesterday', $result); + } + + public function testRelativeDate2DaysAgo(){ + $currentTime = 1380703592; + $elementTime = $currentTime - 48 * 3600; + $result = (string)relative_modified_date($elementTime, $currentTime, true); + + $this->assertEquals('2 days ago', $result); + + // 2 days ago minus 4 hours is still 2 days ago + $elementTime = $currentTime - 52 * 3600; + $result = (string)relative_modified_date($elementTime, $currentTime, true); + + $this->assertEquals('2 days ago', $result); + } + + public function testRelativeDateLastMonth(){ + $currentTime = 1380703592; + $elementTime = $currentTime - 86400 * 31; + $result = (string)relative_modified_date($elementTime, $currentTime, true); + + $this->assertEquals('last month', $result); + + $elementTime = $currentTime - 86400 * 35; + $result = (string)relative_modified_date($elementTime, $currentTime, true); + + $this->assertEquals('last month', $result); + } + + public function testRelativeDateMonthsAgo(){ + $currentTime = 1380703592; + $elementTime = $currentTime - 86400 * 60; + $result = (string)relative_modified_date($elementTime, $currentTime, true); + + $this->assertEquals('2 months ago', $result); + + $elementTime = $currentTime - 86400 * 65; + $result = (string)relative_modified_date($elementTime, $currentTime, true); + + $this->assertEquals('2 months ago', $result); + } + + public function testRelativeDateLastYear(){ + $currentTime = 1380703592; + $elementTime = $currentTime - 86400 * 365; + $result = (string)relative_modified_date($elementTime, $currentTime, true); + + $this->assertEquals('last year', $result); + + $elementTime = $currentTime - 86400 * 450; + $result = (string)relative_modified_date($elementTime, $currentTime, true); + + $this->assertEquals('last year', $result); + } + + public function testRelativeDateYearsAgo(){ + $currentTime = 1380703592; + $elementTime = $currentTime - 86400 * 365.25 * 2; + $result = (string)relative_modified_date($elementTime, $currentTime, true); + + $this->assertEquals('years ago', $result); + + $elementTime = $currentTime - 86400 * 365.25 * 3; + $result = (string)relative_modified_date($elementTime, $currentTime, true); + + $this->assertEquals('years ago', $result); + } + // --------------------------------------------------------------------------- + // Test relative_modified_date with timestamps only (date + time value) + // --------------------------------------------------------------------------- + + public function testRelativeTimeSecondsAgo(){ + $currentTime = 1380703592; + $elementTime = $currentTime - 5; + $result = (string)relative_modified_date($elementTime, $currentTime, false); + + $this->assertEquals('seconds ago', $result); + } + + public function testRelativeTimeMinutesAgo(){ + $currentTime = 1380703592; + $elementTime = $currentTime - 190; + $result = (string)relative_modified_date($elementTime, $currentTime, false); + + $this->assertEquals('3 minutes ago', $result); + } + + public function testRelativeTimeHoursAgo(){ + $currentTime = 1380703592; + $elementTime = $currentTime - 7500; + $result = (string)relative_modified_date($elementTime, $currentTime, false); + + $this->assertEquals('2 hours ago', $result); + } + + public function testRelativeTime2DaysAgo(){ + $currentTime = 1380703592; + $elementTime = $currentTime - 48 * 3600; + $result = (string)relative_modified_date($elementTime, $currentTime, false); + + $this->assertEquals('2 days ago', $result); + + // 2 days ago minus 4 hours is still 2 days ago + $elementTime = $currentTime - 52 * 3600; + $result = (string)relative_modified_date($elementTime, $currentTime, false); + + $this->assertEquals('2 days ago', $result); + } + + public function testRelativeTimeLastMonth(){ + $currentTime = 1380703592; + $elementTime = $currentTime - 86400 * 31; + $result = (string)relative_modified_date($elementTime, $currentTime, false); + + $this->assertEquals('last month', $result); + + $elementTime = $currentTime - 86400 * 35; + $result = (string)relative_modified_date($elementTime, $currentTime, false); + + $this->assertEquals('last month', $result); + } + + public function testRelativeTimeMonthsAgo(){ + $currentTime = 1380703592; + $elementTime = $currentTime - 86400 * 60; + $result = (string)relative_modified_date($elementTime, $currentTime, false); + + $this->assertEquals('2 months ago', $result); + + $elementTime = $currentTime - 86400 * 65; + $result = (string)relative_modified_date($elementTime, $currentTime, false); + + $this->assertEquals('2 months ago', $result); + } + + public function testRelativeTimeLastYear(){ + $currentTime = 1380703592; + $elementTime = $currentTime - 86400 * 365; + $result = (string)relative_modified_date($elementTime, $currentTime, false); + + $this->assertEquals('last year', $result); + + $elementTime = $currentTime - 86400 * 450; + $result = (string)relative_modified_date($elementTime, $currentTime, false); + + $this->assertEquals('last year', $result); + } + + public function testRelativeTimeYearsAgo(){ + $currentTime = 1380703592; + $elementTime = $currentTime - 86400 * 365.25 * 2; + $result = (string)relative_modified_date($elementTime, $currentTime, false); + + $this->assertEquals('years ago', $result); + + $elementTime = $currentTime - 86400 * 365.25 * 3; + $result = (string)relative_modified_date($elementTime, $currentTime, false); + + $this->assertEquals('years ago', $result); + } } diff --git a/tests/lib/user.php b/tests/lib/user.php index 66c7f3f0d74..fdf9e7a08e0 100644 --- a/tests/lib/user.php +++ b/tests/lib/user.php @@ -12,18 +12,26 @@ namespace Test; use OC\Hooks\PublicEmitter; class User extends \PHPUnit_Framework_TestCase { - + /** + * @var \OC_User_Backend | \PHPUnit_Framework_MockObject_MockObject $backend + */ + private $backend; + + protected function setUp(){ + $this->backend = $this->getMock('\OC_User_Dummy'); + $manager = \OC_User::getManager(); + $manager->registerBackend($this->backend); + } + public function testCheckPassword() { - /** - * @var \OC_User_Backend | \PHPUnit_Framework_MockObject_MockObject $backend - */ - $backend = $this->getMock('\OC_User_Dummy'); - $backend->expects($this->once()) + + $this->backend->expects($this->once()) ->method('checkPassword') ->with($this->equalTo('foo'), $this->equalTo('bar')) - ->will($this->returnValue('foo')); + ->will($this->returnValue('foo')) + ; - $backend->expects($this->any()) + $this->backend->expects($this->any()) ->method('implementsActions') ->will($this->returnCallback(function ($actions) { if ($actions === \OC_USER_BACKEND_CHECK_PASSWORD) { @@ -33,11 +41,33 @@ class User extends \PHPUnit_Framework_TestCase { } })); - $manager = \OC_User::getManager(); - $manager->registerBackend($backend); - $uid = \OC_User::checkPassword('foo', 'bar'); $this->assertEquals($uid, 'foo'); } + + public function testDeleteUser() { + $fail = \OC_User::deleteUser('victim'); + $this->assertFalse($fail); + + $success = \OC_User::createUser('victim', 'password'); + + $success = \OC_User::deleteUser('victim'); + $this->assertTrue($success); + } + + public function testCreateUser(){ + $this->backend->expects($this->any()) + ->method('implementsActions') + ->will($this->returnCallback(function ($actions) { + if ($actions === \OC_USER_BACKEND_CREATE_USER) { + return true; + } else { + return false; + } + })); + + $user = \OC_User::createUser('newuser', 'newpassword'); + $this->assertEquals('newuser', $user->getUid()); + } }
\ No newline at end of file diff --git a/tests/lib/user/avataruserdummy.php b/tests/lib/user/avataruserdummy.php new file mode 100644 index 00000000000..738b10492ea --- /dev/null +++ b/tests/lib/user/avataruserdummy.php @@ -0,0 +1,27 @@ +<?php +/** +* ownCloud +* +* @author Arthur Schiwon +* @copyright 2013 Arthur Schiwon blizzz@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 Avatar_User_Dummy extends \OC_User_Dummy { + public function canChangeAvatar($uid) { + return true; + } +}
\ No newline at end of file diff --git a/tests/lib/user/backend.php b/tests/lib/user/backend.php index 40674424c96..1384c54a921 100644 --- a/tests/lib/user/backend.php +++ b/tests/lib/user/backend.php @@ -39,7 +39,7 @@ abstract class Test_User_Backend extends PHPUnit_Framework_TestCase { /** * get a new unique user name * test cases can override this in order to clean up created user - * @return array + * @return string */ public function getUser() { return uniqid('test_'); @@ -82,8 +82,8 @@ abstract class Test_User_Backend extends PHPUnit_Framework_TestCase { $this->assertTrue($this->backend->userExists($name1)); $this->assertTrue($this->backend->userExists($name2)); - $this->assertTrue($this->backend->checkPassword($name1, 'pass1')); - $this->assertTrue($this->backend->checkPassword($name2, 'pass2')); + $this->assertSame($name1, $this->backend->checkPassword($name1, 'pass1')); + $this->assertSame($name2, $this->backend->checkPassword($name2, 'pass2')); $this->assertFalse($this->backend->checkPassword($name1, 'pass2')); $this->assertFalse($this->backend->checkPassword($name2, 'pass1')); @@ -93,7 +93,7 @@ abstract class Test_User_Backend extends PHPUnit_Framework_TestCase { $this->backend->setPassword($name1, 'newpass1'); $this->assertFalse($this->backend->checkPassword($name1, 'pass1')); - $this->assertTrue($this->backend->checkPassword($name1, 'newpass1')); + $this->assertSame($name1, $this->backend->checkPassword($name1, 'newpass1')); $this->assertFalse($this->backend->checkPassword($name2, 'newpass1')); } } diff --git a/tests/lib/user/database.php b/tests/lib/user/database.php index fe7d87c44de..d7cc39ae387 100644 --- a/tests/lib/user/database.php +++ b/tests/lib/user/database.php @@ -21,19 +21,14 @@ */ class Test_User_Database extends Test_User_Backend { - /** - * get a new unique user name - * test cases can override this in order to clean up created user - * @return array - */ public function getUser() { - $user=uniqid('test_'); + $user = parent::getUser(); $this->users[]=$user; return $user; } public function setUp() { - $this->backend=new OC_User_Dummy(); + $this->backend=new OC_User_Database(); } public function tearDown() { diff --git a/tests/lib/user/manager.php b/tests/lib/user/manager.php index 00901dd4115..ad1ac9e12f2 100644 --- a/tests/lib/user/manager.php +++ b/tests/lib/user/manager.php @@ -346,4 +346,76 @@ class Manager extends \PHPUnit_Framework_TestCase { $manager->createUser('foo', 'bar'); } + + public function testCountUsersNoBackend() { + $manager = new \OC\User\Manager(); + + $result = $manager->countUsers(); + $this->assertTrue(is_array($result)); + $this->assertTrue(empty($result)); + } + + public function testCountUsersOneBackend() { + /** + * @var \OC_User_Dummy | \PHPUnit_Framework_MockObject_MockObject $backend + */ + $backend = $this->getMock('\OC_User_Dummy'); + $backend->expects($this->once()) + ->method('countUsers') + ->will($this->returnValue(7)); + + $backend->expects($this->once()) + ->method('implementsActions') + ->with(\OC_USER_BACKEND_COUNT_USERS) + ->will($this->returnValue(true)); + + $manager = new \OC\User\Manager(); + $manager->registerBackend($backend); + + $result = $manager->countUsers(); + $keys = array_keys($result); + $this->assertTrue(strpos($keys[0], 'Mock_OC_User_Dummy') !== false); + + $users = array_shift($result); + $this->assertEquals(7, $users); + } + + public function testCountUsersTwoBackends() { + /** + * @var \OC_User_Dummy | \PHPUnit_Framework_MockObject_MockObject $backend + */ + $backend1 = $this->getMock('\OC_User_Dummy'); + $backend1->expects($this->once()) + ->method('countUsers') + ->will($this->returnValue(7)); + + $backend1->expects($this->once()) + ->method('implementsActions') + ->with(\OC_USER_BACKEND_COUNT_USERS) + ->will($this->returnValue(true)); + + $backend2 = $this->getMock('\OC_User_Dummy'); + $backend2->expects($this->once()) + ->method('countUsers') + ->will($this->returnValue(16)); + + $backend2->expects($this->once()) + ->method('implementsActions') + ->with(\OC_USER_BACKEND_COUNT_USERS) + ->will($this->returnValue(true)); + + $manager = new \OC\User\Manager(); + $manager->registerBackend($backend1); + $manager->registerBackend($backend2); + + $result = $manager->countUsers(); + //because the backends have the same class name, only one value expected + $this->assertEquals(1, count($result)); + $keys = array_keys($result); + $this->assertTrue(strpos($keys[0], 'Mock_OC_User_Dummy') !== false); + + $users = array_shift($result); + //users from backends shall be summed up + $this->assertEquals(7+16, $users); + } } diff --git a/tests/lib/user/session.php b/tests/lib/user/session.php index e457a7bda30..46b268b3624 100644 --- a/tests/lib/user/session.php +++ b/tests/lib/user/session.php @@ -52,9 +52,20 @@ class Session extends \PHPUnit_Framework_TestCase { public function testLoginValidPasswordEnabled() { $session = $this->getMock('\OC\Session\Memory', array(), array('')); - $session->expects($this->once()) + $session->expects($this->exactly(2)) ->method('set') - ->with('user_id', 'foo'); + ->with($this->callback(function($key) { + switch($key) { + case 'user_id': + case 'loginname': + return true; + break; + default: + return false; + break; + } + }, + 'foo')); $manager = $this->getMock('\OC\User\Manager'); diff --git a/tests/lib/user/user.php b/tests/lib/user/user.php index de5ccbf38c1..3f90432c6b0 100644 --- a/tests/lib/user/user.php +++ b/tests/lib/user/user.php @@ -9,6 +9,7 @@ namespace Test\User; +use OC\AllConfig; use OC\Hooks\PublicEmitter; class User extends \PHPUnit_Framework_TestCase { @@ -87,6 +88,75 @@ class User extends \PHPUnit_Framework_TestCase { $this->assertFalse($user->setPassword('bar','')); } + public function testChangeAvatarSupportedYes() { + /** + * @var \OC_User_Backend | \PHPUnit_Framework_MockObject_MockObject $backend + */ + require_once 'avataruserdummy.php'; + $backend = $this->getMock('Avatar_User_Dummy'); + $backend->expects($this->once()) + ->method('canChangeAvatar') + ->with($this->equalTo('foo')) + ->will($this->returnValue(true)); + + $backend->expects($this->any()) + ->method('implementsActions') + ->will($this->returnCallback(function ($actions) { + if ($actions === \OC_USER_BACKEND_PROVIDE_AVATAR) { + return true; + } else { + return false; + } + })); + + $user = new \OC\User\User('foo', $backend); + $this->assertTrue($user->canChangeAvatar()); + } + + public function testChangeAvatarSupportedNo() { + /** + * @var \OC_User_Backend | \PHPUnit_Framework_MockObject_MockObject $backend + */ + require_once 'avataruserdummy.php'; + $backend = $this->getMock('Avatar_User_Dummy'); + $backend->expects($this->once()) + ->method('canChangeAvatar') + ->with($this->equalTo('foo')) + ->will($this->returnValue(false)); + + $backend->expects($this->any()) + ->method('implementsActions') + ->will($this->returnCallback(function ($actions) { + if ($actions === \OC_USER_BACKEND_PROVIDE_AVATAR) { + return true; + } else { + return false; + } + })); + + $user = new \OC\User\User('foo', $backend); + $this->assertFalse($user->canChangeAvatar()); + } + + public function testChangeAvatarNotSupported() { + /** + * @var \OC_User_Backend | \PHPUnit_Framework_MockObject_MockObject $backend + */ + require_once 'avataruserdummy.php'; + $backend = $this->getMock('Avatar_User_Dummy'); + $backend->expects($this->never()) + ->method('canChangeAvatar'); + + $backend->expects($this->any()) + ->method('implementsActions') + ->will($this->returnCallback(function ($actions) { + return false; + })); + + $user = new \OC\User\User('foo', $backend); + $this->assertTrue($user->canChangeAvatar()); + } + public function testDelete() { /** * @var \OC_User_Backend | \PHPUnit_Framework_MockObject_MockObject $backend @@ -136,7 +206,9 @@ class User extends \PHPUnit_Framework_TestCase { ->method('implementsActions') ->will($this->returnValue(false)); - $user = new \OC\User\User('foo', $backend); + $allConfig = new AllConfig(); + + $user = new \OC\User\User('foo', $backend, null, $allConfig); $this->assertEquals(\OC_Config::getValue("datadirectory", \OC::$SERVERROOT . "/data") . '/foo', $user->getHome()); } diff --git a/tests/lib/util.php b/tests/lib/util.php index d607a3e7725..bfe68f5f680 100644 --- a/tests/lib/util.php +++ b/tests/lib/util.php @@ -88,12 +88,70 @@ class Test_Util extends PHPUnit_Framework_TestCase { OC_Config::deleteKey('mail_domain'); } + function testGetConfiguredEmailAddressFromConfig() { + OC_Config::setValue('mail_domain', 'example.com'); + OC_Config::setValue('mail_from_address', 'owncloud'); + $email = \OCP\Util::getDefaultEmailAddress("no-reply"); + $this->assertEquals('owncloud@example.com', $email); + OC_Config::deleteKey('mail_domain'); + OC_Config::deleteKey('mail_from_address'); + } + function testGetInstanceIdGeneratesValidId() { OC_Config::deleteKey('instanceid'); $this->assertStringStartsWith('oc', OC_Util::getInstanceId()); } /** + * Tests that the home storage is not wrapped when no quota exists. + */ + function testHomeStorageWrapperWithoutQuota() { + $user1 = uniqid(); + \OC_User::createUser($user1, 'test'); + OC_Preferences::setValue($user1, 'files', 'quota', 'none'); + \OC_User::setUserId($user1); + + \OC_Util::setupFS($user1); + + $userMount = \OC\Files\Filesystem::getMountManager()->find('/' . $user1 . '/'); + $this->assertNotNull($userMount); + $this->assertNotInstanceOf('\OC\Files\Storage\Wrapper\Quota', $userMount->getStorage()); + + // clean up + \OC_User::setUserId(''); + \OC_User::deleteUser($user1); + OC_Preferences::deleteUser($user1); + \OC_Util::tearDownFS(); + } + + /** + * Tests that the home storage is not wrapped when no quota exists. + */ + function testHomeStorageWrapperWithQuota() { + $user1 = uniqid(); + \OC_User::createUser($user1, 'test'); + OC_Preferences::setValue($user1, 'files', 'quota', '1024'); + \OC_User::setUserId($user1); + + \OC_Util::setupFS($user1); + + $userMount = \OC\Files\Filesystem::getMountManager()->find('/' . $user1 . '/'); + $this->assertNotNull($userMount); + $this->assertInstanceOf('\OC\Files\Storage\Wrapper\Quota', $userMount->getStorage()); + + // ensure that root wasn't wrapped + $rootMount = \OC\Files\Filesystem::getMountManager()->find('/'); + $this->assertNotNull($rootMount); + $this->assertNotInstanceOf('\OC\Files\Storage\Wrapper\Quota', $rootMount->getStorage()); + + // clean up + \OC_User::setUserId(''); + \OC_User::deleteUser($user1); + OC_Preferences::deleteUser($user1); + \OC_Util::tearDownFS(); + } + + /** * @dataProvider baseNameProvider */ public function testBaseName($expected, $file) |