From b1458d590dbd4bfbaf64c3429ec441a82c074f40 Mon Sep 17 00:00:00 2001 From: Joas Schilling Date: Thu, 19 May 2016 08:41:01 +0200 Subject: Fix namespaces and class names in tests/lib/files/ --- tests/lib/files/cache/cache.php | 3 +- tests/lib/files/node/IntegrationTest.php | 125 ++++++++++ tests/lib/files/node/integration.php | 125 ---------- tests/lib/files/objectstore/SwiftTest.php | 198 ++++++++++++++++ tests/lib/files/objectstore/noopscanner.php | 2 +- tests/lib/files/objectstore/swift.php | 198 ---------------- tests/lib/files/pathverificationtest.php | 2 +- tests/lib/files/storage/wrapper/availability.php | 1 + tests/lib/files/type/DetectionTest.php | 287 +++++++++++++++++++++++ tests/lib/files/type/detection.php | 287 ----------------------- tests/lib/files/type/loadertest.php | 2 +- 11 files changed, 615 insertions(+), 615 deletions(-) create mode 100644 tests/lib/files/node/IntegrationTest.php delete mode 100644 tests/lib/files/node/integration.php create mode 100644 tests/lib/files/objectstore/SwiftTest.php delete mode 100644 tests/lib/files/objectstore/swift.php create mode 100644 tests/lib/files/type/DetectionTest.php delete mode 100644 tests/lib/files/type/detection.php (limited to 'tests') diff --git a/tests/lib/files/cache/cache.php b/tests/lib/files/cache/cache.php index 54aa7ad789a..3201e2d03fe 100644 --- a/tests/lib/files/cache/cache.php +++ b/tests/lib/files/cache/cache.php @@ -8,7 +8,6 @@ namespace Test\Files\Cache; -use PHPUnit_Framework_MockObject_MockObject; class LongId extends \OC\Files\Storage\Temporary { public function getId() { @@ -491,7 +490,7 @@ class Cache extends \Test\TestCase { $folderWith0308 = "\x53\x63\x68\x6f\xcc\x88\x6e"; /** - * @var \OC\Files\Cache\Cache | PHPUnit_Framework_MockObject_MockObject $cacheMock + * @var \OC\Files\Cache\Cache | \PHPUnit_Framework_MockObject_MockObject $cacheMock */ $cacheMock = $this->getMock('\OC\Files\Cache\Cache', array('normalize'), array($this->storage), '', true); diff --git a/tests/lib/files/node/IntegrationTest.php b/tests/lib/files/node/IntegrationTest.php new file mode 100644 index 00000000000..e11f9bca4ea --- /dev/null +++ b/tests/lib/files/node/IntegrationTest.php @@ -0,0 +1,125 @@ + + * This file is licensed under the Affero General Public License version 3 or + * later. + * See the COPYING-README file. + */ + +namespace Test\Files\Node; + +use OC\Files\Node\Root; +use OC\Files\Storage\Temporary; +use OC\Files\View; +use OC\User\User; + +/** + * Class IntegrationTests + * + * @group DB + * + * @package Test\Files\Node + */ +class IntegrationTest extends \Test\TestCase { + /** + * @var \OC\Files\Node\Root $root + */ + private $root; + + /** + * @var \OC\Files\Storage\Storage[] + */ + private $storages; + + /** + * @var \OC\Files\View $view + */ + private $view; + + protected function setUp() { + parent::setUp(); + + $manager = \OC\Files\Filesystem::getMountManager(); + + \OC_Hook::clear('OC_Filesystem'); + + $user = new User($this->getUniqueID('user'), new \Test\Util\User\Dummy); + $this->loginAsUser($user->getUID()); + + $this->view = new View(); + $this->root = new Root($manager, $this->view, $user); + $storage = new Temporary(array()); + $subStorage = new Temporary(array()); + $this->storages[] = $storage; + $this->storages[] = $subStorage; + $this->root->mount($storage, '/'); + $this->root->mount($subStorage, '/substorage/'); + } + + protected function tearDown() { + foreach ($this->storages as $storage) { + $storage->getCache()->clear(); + } + + $this->logout(); + parent::tearDown(); + } + + public function testBasicFile() { + $file = $this->root->newFile('/foo.txt'); + $this->assertCount(2, $this->root->getDirectoryListing()); + $this->assertTrue($this->root->nodeExists('/foo.txt')); + $id = $file->getId(); + $this->assertInstanceOf('\OC\Files\Node\File', $file); + $file->putContent('qwerty'); + $this->assertEquals('text/plain', $file->getMimeType()); + $this->assertEquals('qwerty', $file->getContent()); + $this->assertFalse($this->root->nodeExists('/bar.txt')); + $target = $file->move('/bar.txt'); + $this->assertEquals($id, $target->getId()); + $this->assertEquals($id, $file->getId()); + $this->assertFalse($this->root->nodeExists('/foo.txt')); + $this->assertTrue($this->root->nodeExists('/bar.txt')); + $this->assertEquals('bar.txt', $file->getName()); + $this->assertEquals('bar.txt', $file->getInternalPath()); + + $file->move('/substorage/bar.txt'); + $this->assertEquals($id, $file->getId()); + $this->assertEquals('qwerty', $file->getContent()); + } + + public function testBasicFolder() { + $folder = $this->root->newFolder('/foo'); + $this->assertTrue($this->root->nodeExists('/foo')); + $file = $folder->newFile('/bar'); + $this->assertTrue($this->root->nodeExists('/foo/bar')); + $file->putContent('qwerty'); + + $listing = $folder->getDirectoryListing(); + $this->assertEquals(1, count($listing)); + $this->assertEquals($file->getId(), $listing[0]->getId()); + $this->assertEquals($file->getStorage(), $listing[0]->getStorage()); + + + $rootListing = $this->root->getDirectoryListing(); + $this->assertEquals(2, count($rootListing)); + + $folder->move('/asd'); + /** + * @var \OC\Files\Node\File $file + */ + $file = $folder->get('/bar'); + $this->assertInstanceOf('\OC\Files\Node\File', $file); + $this->assertFalse($this->root->nodeExists('/foo/bar')); + $this->assertTrue($this->root->nodeExists('/asd/bar')); + $this->assertEquals('qwerty', $file->getContent()); + $folder->move('/substorage/foo'); + /** + * @var \OC\Files\Node\File $file + */ + $file = $folder->get('/bar'); + $this->assertInstanceOf('\OC\Files\Node\File', $file); + $this->assertTrue($this->root->nodeExists('/substorage/foo/bar')); + $this->assertEquals('qwerty', $file->getContent()); + } +} diff --git a/tests/lib/files/node/integration.php b/tests/lib/files/node/integration.php deleted file mode 100644 index addc7e98f48..00000000000 --- a/tests/lib/files/node/integration.php +++ /dev/null @@ -1,125 +0,0 @@ - - * This file is licensed under the Affero General Public License version 3 or - * later. - * See the COPYING-README file. - */ - -namespace Test\Files\Node; - -use OC\Files\Node\Root; -use OC\Files\Storage\Temporary; -use OC\Files\View; -use OC\User\User; - -/** - * Class IntegrationTests - * - * @group DB - * - * @package Test\Files\Node - */ -class IntegrationTests extends \Test\TestCase { - /** - * @var \OC\Files\Node\Root $root - */ - private $root; - - /** - * @var \OC\Files\Storage\Storage[] - */ - private $storages; - - /** - * @var \OC\Files\View $view - */ - private $view; - - protected function setUp() { - parent::setUp(); - - $manager = \OC\Files\Filesystem::getMountManager(); - - \OC_Hook::clear('OC_Filesystem'); - - $user = new User($this->getUniqueID('user'), new \Test\Util\User\Dummy); - $this->loginAsUser($user->getUID()); - - $this->view = new View(); - $this->root = new Root($manager, $this->view, $user); - $storage = new Temporary(array()); - $subStorage = new Temporary(array()); - $this->storages[] = $storage; - $this->storages[] = $subStorage; - $this->root->mount($storage, '/'); - $this->root->mount($subStorage, '/substorage/'); - } - - protected function tearDown() { - foreach ($this->storages as $storage) { - $storage->getCache()->clear(); - } - - $this->logout(); - parent::tearDown(); - } - - public function testBasicFile() { - $file = $this->root->newFile('/foo.txt'); - $this->assertCount(2, $this->root->getDirectoryListing()); - $this->assertTrue($this->root->nodeExists('/foo.txt')); - $id = $file->getId(); - $this->assertInstanceOf('\OC\Files\Node\File', $file); - $file->putContent('qwerty'); - $this->assertEquals('text/plain', $file->getMimeType()); - $this->assertEquals('qwerty', $file->getContent()); - $this->assertFalse($this->root->nodeExists('/bar.txt')); - $target = $file->move('/bar.txt'); - $this->assertEquals($id, $target->getId()); - $this->assertEquals($id, $file->getId()); - $this->assertFalse($this->root->nodeExists('/foo.txt')); - $this->assertTrue($this->root->nodeExists('/bar.txt')); - $this->assertEquals('bar.txt', $file->getName()); - $this->assertEquals('bar.txt', $file->getInternalPath()); - - $file->move('/substorage/bar.txt'); - $this->assertEquals($id, $file->getId()); - $this->assertEquals('qwerty', $file->getContent()); - } - - public function testBasicFolder() { - $folder = $this->root->newFolder('/foo'); - $this->assertTrue($this->root->nodeExists('/foo')); - $file = $folder->newFile('/bar'); - $this->assertTrue($this->root->nodeExists('/foo/bar')); - $file->putContent('qwerty'); - - $listing = $folder->getDirectoryListing(); - $this->assertEquals(1, count($listing)); - $this->assertEquals($file->getId(), $listing[0]->getId()); - $this->assertEquals($file->getStorage(), $listing[0]->getStorage()); - - - $rootListing = $this->root->getDirectoryListing(); - $this->assertEquals(2, count($rootListing)); - - $folder->move('/asd'); - /** - * @var \OC\Files\Node\File $file - */ - $file = $folder->get('/bar'); - $this->assertInstanceOf('\OC\Files\Node\File', $file); - $this->assertFalse($this->root->nodeExists('/foo/bar')); - $this->assertTrue($this->root->nodeExists('/asd/bar')); - $this->assertEquals('qwerty', $file->getContent()); - $folder->move('/substorage/foo'); - /** - * @var \OC\Files\Node\File $file - */ - $file = $folder->get('/bar'); - $this->assertInstanceOf('\OC\Files\Node\File', $file); - $this->assertTrue($this->root->nodeExists('/substorage/foo/bar')); - $this->assertEquals('qwerty', $file->getContent()); - } -} diff --git a/tests/lib/files/objectstore/SwiftTest.php b/tests/lib/files/objectstore/SwiftTest.php new file mode 100644 index 00000000000..4731936627d --- /dev/null +++ b/tests/lib/files/objectstore/SwiftTest.php @@ -0,0 +1,198 @@ + + * + * 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 . + * + */ + +namespace Test\Files\Cache\ObjectStore; + +use OC\Files\ObjectStore\ObjectStoreStorage; +use OC\Files\ObjectStore\Swift; + +/** + * Class SwiftTest + * + * @group DB + * + * @package Test\Files\Cache\ObjectStore + */ +class SwiftTest extends \Test\Files\Storage\Storage { + + /** + * @var Swift + */ + private $objectStorage; + + protected function setUp() { + parent::setUp(); + + if (!getenv('RUN_OBJECTSTORE_TESTS')) { + $this->markTestSkipped('objectstore tests are unreliable in some environments'); + } + + // reset backend + \OC_User::clearBackends(); + \OC_User::useBackend('database'); + + // create users + $users = array('test'); + foreach($users as $userName) { + $user = \OC::$server->getUserManager()->get($userName); + if ($user !== null) { $user->delete(); } + \OC::$server->getUserManager()->createUser($userName, $userName); + } + + // main test user + \OC_Util::tearDownFS(); + \OC_User::setUserId(''); + \OC\Files\Filesystem::tearDown(); + \OC_User::setUserId('test'); + + $config = \OC::$server->getConfig()->getSystemValue('objectstore'); + $this->objectStorage = new Swift($config['arguments']); + $config['objectstore'] = $this->objectStorage; + $this->instance = new ObjectStoreStorage($config); + } + + protected function tearDown() { + if (is_null($this->instance)) { + return; + } + $this->objectStorage->deleteContainer(true); + $this->instance->getCache()->clear(); + + $users = array('test'); + foreach($users as $userName) { + $user = \OC::$server->getUserManager()->get($userName); + if ($user !== null) { $user->delete(); } + } + parent::tearDown(); + } + + public function testStat() { + + $textFile = \OC::$SERVERROOT . '/tests/data/lorem.txt'; + $ctimeStart = time(); + $this->instance->file_put_contents('/lorem.txt', file_get_contents($textFile)); + $this->assertTrue($this->instance->isReadable('/lorem.txt')); + $ctimeEnd = time(); + $mTime = $this->instance->filemtime('/lorem.txt'); + + // 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'); + //only size and mtime are required in the result + $this->assertEquals($stat['size'], $this->instance->filesize('/lorem.txt')); + $this->assertEquals($stat['mtime'], $mTime); + + if ($this->instance->touch('/lorem.txt', 100) !== false) { + $mTime = $this->instance->filemtime('/lorem.txt'); + $this->assertEquals($mTime, 100); + } + } + + public function testCheckUpdate() { + $this->markTestSkipped('Detecting external changes is not supported on object storages'); + } + + /** + * @dataProvider copyAndMoveProvider + */ + public function testMove($source, $target) { + $this->initSourceAndTarget($source); + $sourceId = $this->instance->getCache()->getId(ltrim('/',$source)); + $this->assertNotEquals(-1, $sourceId); + + $this->instance->rename($source, $target); + + $this->assertTrue($this->instance->file_exists($target), $target.' was not created'); + $this->assertFalse($this->instance->file_exists($source), $source.' still exists'); + $this->assertSameAsLorem($target); + + $targetId = $this->instance->getCache()->getId(ltrim('/',$target)); + $this->assertSame($sourceId, $targetId, 'fileid must be stable on move or shares will break'); + } + + public function testRenameDirectory() { + $this->instance->mkdir('source'); + $this->instance->file_put_contents('source/test1.txt', 'foo'); + $this->instance->file_put_contents('source/test2.txt', 'qwerty'); + $this->instance->mkdir('source/subfolder'); + $this->instance->file_put_contents('source/subfolder/test.txt', 'bar'); + $sourceId = $this->instance->getCache()->getId('source'); + $this->assertNotEquals(-1, $sourceId); + $this->instance->rename('source', 'target'); + + $this->assertFalse($this->instance->file_exists('source')); + $this->assertFalse($this->instance->file_exists('source/test1.txt')); + $this->assertFalse($this->instance->file_exists('source/test2.txt')); + $this->assertFalse($this->instance->file_exists('source/subfolder')); + $this->assertFalse($this->instance->file_exists('source/subfolder/test.txt')); + + $this->assertTrue($this->instance->file_exists('target')); + $this->assertTrue($this->instance->file_exists('target/test1.txt')); + $this->assertTrue($this->instance->file_exists('target/test2.txt')); + $this->assertTrue($this->instance->file_exists('target/subfolder')); + $this->assertTrue($this->instance->file_exists('target/subfolder/test.txt')); + + $this->assertEquals('foo', $this->instance->file_get_contents('target/test1.txt')); + $this->assertEquals('qwerty', $this->instance->file_get_contents('target/test2.txt')); + $this->assertEquals('bar', $this->instance->file_get_contents('target/subfolder/test.txt')); + $targetId = $this->instance->getCache()->getId('target'); + $this->assertSame($sourceId, $targetId, 'fileid must be stable on move or shares will break'); + } + + public function testRenameOverWriteDirectory() { + $this->instance->mkdir('source'); + $this->instance->file_put_contents('source/test1.txt', 'foo'); + $sourceId = $this->instance->getCache()->getId('source'); + $this->assertNotEquals(-1, $sourceId); + + $this->instance->mkdir('target'); + $this->instance->file_put_contents('target/test1.txt', 'bar'); + $this->instance->file_put_contents('target/test2.txt', 'bar'); + + $this->instance->rename('source', 'target'); + + $this->assertFalse($this->instance->file_exists('source')); + $this->assertFalse($this->instance->file_exists('source/test1.txt')); + $this->assertFalse($this->instance->file_exists('target/test2.txt')); + $this->assertEquals('foo', $this->instance->file_get_contents('target/test1.txt')); + $targetId = $this->instance->getCache()->getId('target'); + $this->assertSame($sourceId, $targetId, 'fileid must be stable on move or shares will break'); + } + + public function testRenameOverWriteDirectoryOverFile() { + $this->instance->mkdir('source'); + $this->instance->file_put_contents('source/test1.txt', 'foo'); + $sourceId = $this->instance->getCache()->getId('source'); + $this->assertNotEquals(-1, $sourceId); + + $this->instance->file_put_contents('target', 'bar'); + + $this->instance->rename('source', 'target'); + + $this->assertFalse($this->instance->file_exists('source')); + $this->assertFalse($this->instance->file_exists('source/test1.txt')); + $this->assertEquals('foo', $this->instance->file_get_contents('target/test1.txt')); + $targetId = $this->instance->getCache()->getId('target'); + $this->assertSame($sourceId, $targetId, 'fileid must be stable on move or shares will break'); + } +} diff --git a/tests/lib/files/objectstore/noopscanner.php b/tests/lib/files/objectstore/noopscanner.php index f860c03cb18..fba6619d42b 100644 --- a/tests/lib/files/objectstore/noopscanner.php +++ b/tests/lib/files/objectstore/noopscanner.php @@ -9,7 +9,7 @@ * later. * See the COPYING-README file. */ -namespace Test\Files\Cache; +namespace Test\Files\Cache\ObjectStore; class NoopScanner extends \Test\TestCase { /** @var \OC\Files\Storage\Storage $storage */ diff --git a/tests/lib/files/objectstore/swift.php b/tests/lib/files/objectstore/swift.php deleted file mode 100644 index a63f5844145..00000000000 --- a/tests/lib/files/objectstore/swift.php +++ /dev/null @@ -1,198 +0,0 @@ - - * - * 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 . - * - */ - -namespace OCA\ObjectStore\Tests\Unit; - -use OC\Files\ObjectStore\ObjectStoreStorage; -use OC\Files\ObjectStore\Swift as ObjectStoreToTest; - -/** - * Class Swift - * - * @group DB - * - * @package OCA\ObjectStore\Tests\Unit - */ -class Swift extends \Test\Files\Storage\Storage { - - /** - * @var ObjectStoreToTest - */ - private $objectStorage; - - protected function setUp() { - parent::setUp(); - - if (!getenv('RUN_OBJECTSTORE_TESTS')) { - $this->markTestSkipped('objectstore tests are unreliable in some environments'); - } - - // reset backend - \OC_User::clearBackends(); - \OC_User::useBackend('database'); - - // create users - $users = array('test'); - foreach($users as $userName) { - $user = \OC::$server->getUserManager()->get($userName); - if ($user !== null) { $user->delete(); } - \OC::$server->getUserManager()->createUser($userName, $userName); - } - - // main test user - \OC_Util::tearDownFS(); - \OC_User::setUserId(''); - \OC\Files\Filesystem::tearDown(); - \OC_User::setUserId('test'); - - $config = \OC::$server->getConfig()->getSystemValue('objectstore'); - $this->objectStorage = new ObjectStoreToTest($config['arguments']); - $config['objectstore'] = $this->objectStorage; - $this->instance = new ObjectStoreStorage($config); - } - - protected function tearDown() { - if (is_null($this->instance)) { - return; - } - $this->objectStorage->deleteContainer(true); - $this->instance->getCache()->clear(); - - $users = array('test'); - foreach($users as $userName) { - $user = \OC::$server->getUserManager()->get($userName); - if ($user !== null) { $user->delete(); } - } - parent::tearDown(); - } - - public function testStat() { - - $textFile = \OC::$SERVERROOT . '/tests/data/lorem.txt'; - $ctimeStart = time(); - $this->instance->file_put_contents('/lorem.txt', file_get_contents($textFile)); - $this->assertTrue($this->instance->isReadable('/lorem.txt')); - $ctimeEnd = time(); - $mTime = $this->instance->filemtime('/lorem.txt'); - - // 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'); - //only size and mtime are required in the result - $this->assertEquals($stat['size'], $this->instance->filesize('/lorem.txt')); - $this->assertEquals($stat['mtime'], $mTime); - - if ($this->instance->touch('/lorem.txt', 100) !== false) { - $mTime = $this->instance->filemtime('/lorem.txt'); - $this->assertEquals($mTime, 100); - } - } - - public function testCheckUpdate() { - $this->markTestSkipped('Detecting external changes is not supported on object storages'); - } - - /** - * @dataProvider copyAndMoveProvider - */ - public function testMove($source, $target) { - $this->initSourceAndTarget($source); - $sourceId = $this->instance->getCache()->getId(ltrim('/',$source)); - $this->assertNotEquals(-1, $sourceId); - - $this->instance->rename($source, $target); - - $this->assertTrue($this->instance->file_exists($target), $target.' was not created'); - $this->assertFalse($this->instance->file_exists($source), $source.' still exists'); - $this->assertSameAsLorem($target); - - $targetId = $this->instance->getCache()->getId(ltrim('/',$target)); - $this->assertSame($sourceId, $targetId, 'fileid must be stable on move or shares will break'); - } - - public function testRenameDirectory() { - $this->instance->mkdir('source'); - $this->instance->file_put_contents('source/test1.txt', 'foo'); - $this->instance->file_put_contents('source/test2.txt', 'qwerty'); - $this->instance->mkdir('source/subfolder'); - $this->instance->file_put_contents('source/subfolder/test.txt', 'bar'); - $sourceId = $this->instance->getCache()->getId('source'); - $this->assertNotEquals(-1, $sourceId); - $this->instance->rename('source', 'target'); - - $this->assertFalse($this->instance->file_exists('source')); - $this->assertFalse($this->instance->file_exists('source/test1.txt')); - $this->assertFalse($this->instance->file_exists('source/test2.txt')); - $this->assertFalse($this->instance->file_exists('source/subfolder')); - $this->assertFalse($this->instance->file_exists('source/subfolder/test.txt')); - - $this->assertTrue($this->instance->file_exists('target')); - $this->assertTrue($this->instance->file_exists('target/test1.txt')); - $this->assertTrue($this->instance->file_exists('target/test2.txt')); - $this->assertTrue($this->instance->file_exists('target/subfolder')); - $this->assertTrue($this->instance->file_exists('target/subfolder/test.txt')); - - $this->assertEquals('foo', $this->instance->file_get_contents('target/test1.txt')); - $this->assertEquals('qwerty', $this->instance->file_get_contents('target/test2.txt')); - $this->assertEquals('bar', $this->instance->file_get_contents('target/subfolder/test.txt')); - $targetId = $this->instance->getCache()->getId('target'); - $this->assertSame($sourceId, $targetId, 'fileid must be stable on move or shares will break'); - } - - public function testRenameOverWriteDirectory() { - $this->instance->mkdir('source'); - $this->instance->file_put_contents('source/test1.txt', 'foo'); - $sourceId = $this->instance->getCache()->getId('source'); - $this->assertNotEquals(-1, $sourceId); - - $this->instance->mkdir('target'); - $this->instance->file_put_contents('target/test1.txt', 'bar'); - $this->instance->file_put_contents('target/test2.txt', 'bar'); - - $this->instance->rename('source', 'target'); - - $this->assertFalse($this->instance->file_exists('source')); - $this->assertFalse($this->instance->file_exists('source/test1.txt')); - $this->assertFalse($this->instance->file_exists('target/test2.txt')); - $this->assertEquals('foo', $this->instance->file_get_contents('target/test1.txt')); - $targetId = $this->instance->getCache()->getId('target'); - $this->assertSame($sourceId, $targetId, 'fileid must be stable on move or shares will break'); - } - - public function testRenameOverWriteDirectoryOverFile() { - $this->instance->mkdir('source'); - $this->instance->file_put_contents('source/test1.txt', 'foo'); - $sourceId = $this->instance->getCache()->getId('source'); - $this->assertNotEquals(-1, $sourceId); - - $this->instance->file_put_contents('target', 'bar'); - - $this->instance->rename('source', 'target'); - - $this->assertFalse($this->instance->file_exists('source')); - $this->assertFalse($this->instance->file_exists('source/test1.txt')); - $this->assertEquals('foo', $this->instance->file_get_contents('target/test1.txt')); - $targetId = $this->instance->getCache()->getId('target'); - $this->assertSame($sourceId, $targetId, 'fileid must be stable on move or shares will break'); - } -} diff --git a/tests/lib/files/pathverificationtest.php b/tests/lib/files/pathverificationtest.php index db393ce5e51..ea9859c862c 100644 --- a/tests/lib/files/pathverificationtest.php +++ b/tests/lib/files/pathverificationtest.php @@ -17,7 +17,7 @@ use OC\Files\View; * * @package Test\Files */ -class PathVerification extends \Test\TestCase { +class PathVerificationTest extends \Test\TestCase { /** * @var \OC\Files\View diff --git a/tests/lib/files/storage/wrapper/availability.php b/tests/lib/files/storage/wrapper/availability.php index 99d6f7dbe5c..311334a80a3 100644 --- a/tests/lib/files/storage/wrapper/availability.php +++ b/tests/lib/files/storage/wrapper/availability.php @@ -18,6 +18,7 @@ * along with this program. If not, see * */ + namespace Test\Files\Storage\Wrapper; class Availability extends \Test\TestCase { diff --git a/tests/lib/files/type/DetectionTest.php b/tests/lib/files/type/DetectionTest.php new file mode 100644 index 00000000000..5800f4eb8e3 --- /dev/null +++ b/tests/lib/files/type/DetectionTest.php @@ -0,0 +1,287 @@ + + * + * @copyright Copyright (c) 2015, ownCloud, Inc. + * @license AGPL-3.0 + * + * This code is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License, version 3, + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License, version 3, + * along with this program. If not, see + * + */ + +namespace Test\Files\Type; + +use \OC\Files\Type\Detection; + +class DetectionTest extends \Test\TestCase { + /** @var Detection */ + private $detection; + + public function setUp() { + parent::setUp(); + $this->detection = new Detection( + \OC::$server->getURLGenerator(), + \OC::$SERVERROOT . '/config/', + \OC::$SERVERROOT . '/resources/config/' + ); + } + + public function testDetect() { + $dir = \OC::$SERVERROOT.'/tests/data'; + + $result = $this->detection->detect($dir."/"); + $expected = 'httpd/unix-directory'; + $this->assertEquals($expected, $result); + + $result = $this->detection->detect($dir."/data.tar.gz"); + $expected = 'application/x-gzip'; + $this->assertEquals($expected, $result); + + $result = $this->detection->detect($dir."/data.zip"); + $expected = 'application/zip'; + $this->assertEquals($expected, $result); + + $result = $this->detection->detect($dir."/testimagelarge.svg"); + $expected = 'image/svg+xml'; + $this->assertEquals($expected, $result); + + $result = $this->detection->detect($dir."/testimage.png"); + $expected = 'image/png'; + $this->assertEquals($expected, $result); + } + + public function testGetSecureMimeType() { + $result = $this->detection->getSecureMimeType('image/svg+xml'); + $expected = 'text/plain'; + $this->assertEquals($expected, $result); + + $result = $this->detection->getSecureMimeType('image/png'); + $expected = 'image/png'; + $this->assertEquals($expected, $result); + } + + public function testDetectPath() { + $this->assertEquals('text/plain', $this->detection->detectPath('foo.txt')); + $this->assertEquals('image/png', $this->detection->detectPath('foo.png')); + $this->assertEquals('image/png', $this->detection->detectPath('foo.bar.png')); + $this->assertEquals('application/octet-stream', $this->detection->detectPath('.png')); + $this->assertEquals('application/octet-stream', $this->detection->detectPath('foo')); + $this->assertEquals('application/octet-stream', $this->detection->detectPath('')); + } + + public function testDetectString() { + if (\OC_Util::runningOnWindows()) { + $this->markTestSkipped('[Windows] Strings have mimetype application/octet-stream on Windows'); + } + + $result = $this->detection->detectString("/data/data.tar.gz"); + $expected = 'text/plain; charset=us-ascii'; + $this->assertEquals($expected, $result); + } + + public function testMimeTypeIcon() { + if (!class_exists('org\\bovigo\\vfs\\vfsStream')) { + $this->markTestSkipped('Package vfsStream not installed'); + } + $confDir = \org\bovigo\vfs\vfsStream::setup(); + $mimetypealiases_dist = \org\bovigo\vfs\vfsStream::newFile('mimetypealiases.dist.json')->at($confDir); + + //Empty alias file + $mimetypealiases_dist->setContent(json_encode([], JSON_FORCE_OBJECT)); + + + /* + * Test dir mimetype + */ + + //Mock UrlGenerator + $urlGenerator = $this->getMockBuilder('\OCP\IURLGenerator') + ->disableOriginalConstructor() + ->getMock(); + + //Only call the url generator once + $urlGenerator->expects($this->once()) + ->method('imagePath') + ->with($this->equalTo('core'), $this->equalTo('filetypes/folder.png')) + ->willReturn('folder.svg'); + + $detection = new Detection($urlGenerator, $confDir->url(), $confDir->url()); + $mimeType = $detection->mimeTypeIcon('dir'); + $this->assertEquals('folder.svg', $mimeType); + + + /* + * Test dir-shareed mimetype + */ + //Mock UrlGenerator + $urlGenerator = $this->getMockBuilder('\OCP\IURLGenerator') + ->disableOriginalConstructor() + ->getMock(); + + //Only call the url generator once + $urlGenerator->expects($this->once()) + ->method('imagePath') + ->with($this->equalTo('core'), $this->equalTo('filetypes/folder-shared.png')) + ->willReturn('folder-shared.svg'); + + $detection = new Detection($urlGenerator, $confDir->url(), $confDir->url()); + $mimeType = $detection->mimeTypeIcon('dir-shared'); + $this->assertEquals('folder-shared.svg', $mimeType); + + + /* + * Test dir external + */ + + //Mock UrlGenerator + $urlGenerator = $this->getMockBuilder('\OCP\IURLGenerator') + ->disableOriginalConstructor() + ->getMock(); + + //Only call the url generator once + $urlGenerator->expects($this->once()) + ->method('imagePath') + ->with($this->equalTo('core'), $this->equalTo('filetypes/folder-external.png')) + ->willReturn('folder-external.svg'); + + $detection = new Detection($urlGenerator, $confDir->url(), $confDir->url()); + $mimeType = $detection->mimeTypeIcon('dir-external'); + $this->assertEquals('folder-external.svg', $mimeType); + + + /* + * Test complete mimetype + */ + + //Mock UrlGenerator + $urlGenerator = $this->getMockBuilder('\OCP\IURLGenerator') + ->disableOriginalConstructor() + ->getMock(); + + //Only call the url generator once + $urlGenerator->expects($this->once()) + ->method('imagePath') + ->with($this->equalTo('core'), $this->equalTo('filetypes/my-type.png')) + ->willReturn('my-type.svg'); + + $detection = new Detection($urlGenerator, $confDir->url(), $confDir->url()); + $mimeType = $detection->mimeTypeIcon('my-type'); + $this->assertEquals('my-type.svg', $mimeType); + + + /* + * Test subtype + */ + + //Mock UrlGenerator + $urlGenerator = $this->getMockBuilder('\OCP\IURLGenerator') + ->disableOriginalConstructor() + ->getMock(); + + //Only call the url generator once + $urlGenerator->expects($this->exactly(2)) + ->method('imagePath') + ->withConsecutive( + [$this->equalTo('core'), $this->equalTo('filetypes/my-type.png')], + [$this->equalTo('core'), $this->equalTo('filetypes/my.png')] + ) + ->will($this->returnCallback( + function($appName, $file) { + if ($file === 'filetypes/my.png') { + return 'my.svg'; + } + throw new \RuntimeException(); + } + )); + + $detection = new Detection($urlGenerator, $confDir->url(), $confDir->url()); + $mimeType = $detection->mimeTypeIcon('my-type'); + $this->assertEquals('my.svg', $mimeType); + + + /* + * Test default mimetype + */ + + //Mock UrlGenerator + $urlGenerator = $this->getMockBuilder('\OCP\IURLGenerator') + ->disableOriginalConstructor() + ->getMock(); + + //Only call the url generator once + $urlGenerator->expects($this->exactly(3)) + ->method('imagePath') + ->withConsecutive( + [$this->equalTo('core'), $this->equalTo('filetypes/foo-bar.png')], + [$this->equalTo('core'), $this->equalTo('filetypes/foo.png')], + [$this->equalTo('core'), $this->equalTo('filetypes/file.png')] + ) + ->will($this->returnCallback( + function($appName, $file) { + if ($file === 'filetypes/file.png') { + return 'file.svg'; + } + throw new \RuntimeException(); + } + )); + + $detection = new Detection($urlGenerator, $confDir->url(), $confDir->url()); + $mimeType = $detection->mimeTypeIcon('foo-bar'); + $this->assertEquals('file.svg', $mimeType); + + /* + * Test chaching + */ + + //Mock UrlGenerator + $urlGenerator = $this->getMockBuilder('\OCP\IURLGenerator') + ->disableOriginalConstructor() + ->getMock(); + + //Only call the url generator once + $urlGenerator->expects($this->once()) + ->method('imagePath') + ->with($this->equalTo('core'), $this->equalTo('filetypes/foo-bar.png')) + ->willReturn('foo-bar.svg'); + + $detection = new Detection($urlGenerator, $confDir->url(), $confDir->url()); + $mimeType = $detection->mimeTypeIcon('foo-bar'); + $this->assertEquals('foo-bar.svg', $mimeType); + $mimeType = $detection->mimeTypeIcon('foo-bar'); + $this->assertEquals('foo-bar.svg', $mimeType); + + + + /* + * Test aliases + */ + + //Put alias + $mimetypealiases_dist->setContent(json_encode(['foo' => 'foobar/baz'], JSON_FORCE_OBJECT)); + + //Mock UrlGenerator + $urlGenerator = $this->getMockBuilder('\OCP\IURLGenerator') + ->disableOriginalConstructor() + ->getMock(); + + //Only call the url generator once + $urlGenerator->expects($this->once()) + ->method('imagePath') + ->with($this->equalTo('core'), $this->equalTo('filetypes/foobar-baz.png')) + ->willReturn('foobar-baz.svg'); + + $detection = new Detection($urlGenerator, $confDir->url(), $confDir->url()); + $mimeType = $detection->mimeTypeIcon('foo'); + $this->assertEquals('foobar-baz.svg', $mimeType); + } +} diff --git a/tests/lib/files/type/detection.php b/tests/lib/files/type/detection.php deleted file mode 100644 index 5800f4eb8e3..00000000000 --- a/tests/lib/files/type/detection.php +++ /dev/null @@ -1,287 +0,0 @@ - - * - * @copyright Copyright (c) 2015, ownCloud, Inc. - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see - * - */ - -namespace Test\Files\Type; - -use \OC\Files\Type\Detection; - -class DetectionTest extends \Test\TestCase { - /** @var Detection */ - private $detection; - - public function setUp() { - parent::setUp(); - $this->detection = new Detection( - \OC::$server->getURLGenerator(), - \OC::$SERVERROOT . '/config/', - \OC::$SERVERROOT . '/resources/config/' - ); - } - - public function testDetect() { - $dir = \OC::$SERVERROOT.'/tests/data'; - - $result = $this->detection->detect($dir."/"); - $expected = 'httpd/unix-directory'; - $this->assertEquals($expected, $result); - - $result = $this->detection->detect($dir."/data.tar.gz"); - $expected = 'application/x-gzip'; - $this->assertEquals($expected, $result); - - $result = $this->detection->detect($dir."/data.zip"); - $expected = 'application/zip'; - $this->assertEquals($expected, $result); - - $result = $this->detection->detect($dir."/testimagelarge.svg"); - $expected = 'image/svg+xml'; - $this->assertEquals($expected, $result); - - $result = $this->detection->detect($dir."/testimage.png"); - $expected = 'image/png'; - $this->assertEquals($expected, $result); - } - - public function testGetSecureMimeType() { - $result = $this->detection->getSecureMimeType('image/svg+xml'); - $expected = 'text/plain'; - $this->assertEquals($expected, $result); - - $result = $this->detection->getSecureMimeType('image/png'); - $expected = 'image/png'; - $this->assertEquals($expected, $result); - } - - public function testDetectPath() { - $this->assertEquals('text/plain', $this->detection->detectPath('foo.txt')); - $this->assertEquals('image/png', $this->detection->detectPath('foo.png')); - $this->assertEquals('image/png', $this->detection->detectPath('foo.bar.png')); - $this->assertEquals('application/octet-stream', $this->detection->detectPath('.png')); - $this->assertEquals('application/octet-stream', $this->detection->detectPath('foo')); - $this->assertEquals('application/octet-stream', $this->detection->detectPath('')); - } - - public function testDetectString() { - if (\OC_Util::runningOnWindows()) { - $this->markTestSkipped('[Windows] Strings have mimetype application/octet-stream on Windows'); - } - - $result = $this->detection->detectString("/data/data.tar.gz"); - $expected = 'text/plain; charset=us-ascii'; - $this->assertEquals($expected, $result); - } - - public function testMimeTypeIcon() { - if (!class_exists('org\\bovigo\\vfs\\vfsStream')) { - $this->markTestSkipped('Package vfsStream not installed'); - } - $confDir = \org\bovigo\vfs\vfsStream::setup(); - $mimetypealiases_dist = \org\bovigo\vfs\vfsStream::newFile('mimetypealiases.dist.json')->at($confDir); - - //Empty alias file - $mimetypealiases_dist->setContent(json_encode([], JSON_FORCE_OBJECT)); - - - /* - * Test dir mimetype - */ - - //Mock UrlGenerator - $urlGenerator = $this->getMockBuilder('\OCP\IURLGenerator') - ->disableOriginalConstructor() - ->getMock(); - - //Only call the url generator once - $urlGenerator->expects($this->once()) - ->method('imagePath') - ->with($this->equalTo('core'), $this->equalTo('filetypes/folder.png')) - ->willReturn('folder.svg'); - - $detection = new Detection($urlGenerator, $confDir->url(), $confDir->url()); - $mimeType = $detection->mimeTypeIcon('dir'); - $this->assertEquals('folder.svg', $mimeType); - - - /* - * Test dir-shareed mimetype - */ - //Mock UrlGenerator - $urlGenerator = $this->getMockBuilder('\OCP\IURLGenerator') - ->disableOriginalConstructor() - ->getMock(); - - //Only call the url generator once - $urlGenerator->expects($this->once()) - ->method('imagePath') - ->with($this->equalTo('core'), $this->equalTo('filetypes/folder-shared.png')) - ->willReturn('folder-shared.svg'); - - $detection = new Detection($urlGenerator, $confDir->url(), $confDir->url()); - $mimeType = $detection->mimeTypeIcon('dir-shared'); - $this->assertEquals('folder-shared.svg', $mimeType); - - - /* - * Test dir external - */ - - //Mock UrlGenerator - $urlGenerator = $this->getMockBuilder('\OCP\IURLGenerator') - ->disableOriginalConstructor() - ->getMock(); - - //Only call the url generator once - $urlGenerator->expects($this->once()) - ->method('imagePath') - ->with($this->equalTo('core'), $this->equalTo('filetypes/folder-external.png')) - ->willReturn('folder-external.svg'); - - $detection = new Detection($urlGenerator, $confDir->url(), $confDir->url()); - $mimeType = $detection->mimeTypeIcon('dir-external'); - $this->assertEquals('folder-external.svg', $mimeType); - - - /* - * Test complete mimetype - */ - - //Mock UrlGenerator - $urlGenerator = $this->getMockBuilder('\OCP\IURLGenerator') - ->disableOriginalConstructor() - ->getMock(); - - //Only call the url generator once - $urlGenerator->expects($this->once()) - ->method('imagePath') - ->with($this->equalTo('core'), $this->equalTo('filetypes/my-type.png')) - ->willReturn('my-type.svg'); - - $detection = new Detection($urlGenerator, $confDir->url(), $confDir->url()); - $mimeType = $detection->mimeTypeIcon('my-type'); - $this->assertEquals('my-type.svg', $mimeType); - - - /* - * Test subtype - */ - - //Mock UrlGenerator - $urlGenerator = $this->getMockBuilder('\OCP\IURLGenerator') - ->disableOriginalConstructor() - ->getMock(); - - //Only call the url generator once - $urlGenerator->expects($this->exactly(2)) - ->method('imagePath') - ->withConsecutive( - [$this->equalTo('core'), $this->equalTo('filetypes/my-type.png')], - [$this->equalTo('core'), $this->equalTo('filetypes/my.png')] - ) - ->will($this->returnCallback( - function($appName, $file) { - if ($file === 'filetypes/my.png') { - return 'my.svg'; - } - throw new \RuntimeException(); - } - )); - - $detection = new Detection($urlGenerator, $confDir->url(), $confDir->url()); - $mimeType = $detection->mimeTypeIcon('my-type'); - $this->assertEquals('my.svg', $mimeType); - - - /* - * Test default mimetype - */ - - //Mock UrlGenerator - $urlGenerator = $this->getMockBuilder('\OCP\IURLGenerator') - ->disableOriginalConstructor() - ->getMock(); - - //Only call the url generator once - $urlGenerator->expects($this->exactly(3)) - ->method('imagePath') - ->withConsecutive( - [$this->equalTo('core'), $this->equalTo('filetypes/foo-bar.png')], - [$this->equalTo('core'), $this->equalTo('filetypes/foo.png')], - [$this->equalTo('core'), $this->equalTo('filetypes/file.png')] - ) - ->will($this->returnCallback( - function($appName, $file) { - if ($file === 'filetypes/file.png') { - return 'file.svg'; - } - throw new \RuntimeException(); - } - )); - - $detection = new Detection($urlGenerator, $confDir->url(), $confDir->url()); - $mimeType = $detection->mimeTypeIcon('foo-bar'); - $this->assertEquals('file.svg', $mimeType); - - /* - * Test chaching - */ - - //Mock UrlGenerator - $urlGenerator = $this->getMockBuilder('\OCP\IURLGenerator') - ->disableOriginalConstructor() - ->getMock(); - - //Only call the url generator once - $urlGenerator->expects($this->once()) - ->method('imagePath') - ->with($this->equalTo('core'), $this->equalTo('filetypes/foo-bar.png')) - ->willReturn('foo-bar.svg'); - - $detection = new Detection($urlGenerator, $confDir->url(), $confDir->url()); - $mimeType = $detection->mimeTypeIcon('foo-bar'); - $this->assertEquals('foo-bar.svg', $mimeType); - $mimeType = $detection->mimeTypeIcon('foo-bar'); - $this->assertEquals('foo-bar.svg', $mimeType); - - - - /* - * Test aliases - */ - - //Put alias - $mimetypealiases_dist->setContent(json_encode(['foo' => 'foobar/baz'], JSON_FORCE_OBJECT)); - - //Mock UrlGenerator - $urlGenerator = $this->getMockBuilder('\OCP\IURLGenerator') - ->disableOriginalConstructor() - ->getMock(); - - //Only call the url generator once - $urlGenerator->expects($this->once()) - ->method('imagePath') - ->with($this->equalTo('core'), $this->equalTo('filetypes/foobar-baz.png')) - ->willReturn('foobar-baz.svg'); - - $detection = new Detection($urlGenerator, $confDir->url(), $confDir->url()); - $mimeType = $detection->mimeTypeIcon('foo'); - $this->assertEquals('foobar-baz.svg', $mimeType); - } -} diff --git a/tests/lib/files/type/loadertest.php b/tests/lib/files/type/loadertest.php index 7f87afd2f4d..a77d672f667 100644 --- a/tests/lib/files/type/loadertest.php +++ b/tests/lib/files/type/loadertest.php @@ -19,7 +19,7 @@ * */ -namespace OC\Files\Type; +namespace Test\Files\Type; use \OC\Files\Type\Loader; use \OCP\IDBConnection; -- cgit v1.2.3 From 995d4b7ecd27afb3a2388edf7cc2373104e4a66d Mon Sep 17 00:00:00 2001 From: Joas Schilling Date: Thu, 19 May 2016 08:44:41 +0200 Subject: Fix namespaces in tests/lib/groups/ --- tests/lib/group/backend.php | 4 +- tests/lib/group/database.php | 6 +- tests/lib/group/dummy.php | 6 +- tests/lib/group/metadata.php | 136 --------------------------------------- tests/lib/group/metadatatest.php | 136 +++++++++++++++++++++++++++++++++++++++ 5 files changed, 147 insertions(+), 141 deletions(-) delete mode 100644 tests/lib/group/metadata.php create mode 100644 tests/lib/group/metadatatest.php (limited to 'tests') diff --git a/tests/lib/group/backend.php b/tests/lib/group/backend.php index 3b06a3eb3a9..53a13e6c62f 100644 --- a/tests/lib/group/backend.php +++ b/tests/lib/group/backend.php @@ -24,12 +24,14 @@ * */ +namespace Test\Group; + /** * Class Test_Group_Backend * * @group DB */ -abstract class Test_Group_Backend extends \Test\TestCase { +abstract class Backend extends \Test\TestCase { /** * @var \OC\Group\Backend $backend */ diff --git a/tests/lib/group/database.php b/tests/lib/group/database.php index aae9f8bf1de..bf9d9c35b0b 100644 --- a/tests/lib/group/database.php +++ b/tests/lib/group/database.php @@ -23,12 +23,14 @@ * */ +namespace Test\Group; + /** - * Class Test_Group_Database + * Class Database * * @group DB */ -class Test_Group_Database extends Test_Group_Backend { +class Database extends Backend { private $groups = array(); /** diff --git a/tests/lib/group/dummy.php b/tests/lib/group/dummy.php index eaa299c39af..5504cd63a0a 100644 --- a/tests/lib/group/dummy.php +++ b/tests/lib/group/dummy.php @@ -20,12 +20,14 @@ * */ +namespace Test\Group; + /** - * Class Test_Group_Dummy + * Class Dummy * * @group DB */ -class Test_Group_Dummy extends Test_Group_Backend { +class Dummy extends Backend { protected function setUp() { parent::setUp(); $this->backend=new \Test\Util\Group\Dummy(); diff --git a/tests/lib/group/metadata.php b/tests/lib/group/metadata.php deleted file mode 100644 index 233463c71eb..00000000000 --- a/tests/lib/group/metadata.php +++ /dev/null @@ -1,136 +0,0 @@ - - * @author Lukas Reschke - * - * @copyright Copyright (c) 2015, ownCloud, Inc. - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see - * - */ - -namespace Test\Group; - -class Test_MetaData extends \Test\TestCase { - /** @var \OC\Group\Manager */ - private $groupManager; - /** @var \OCP\IUserSession */ - private $userSession; - /** @var \OC\Group\MetaData */ - private $groupMetadata; - /** @var bool */ - private $isAdmin = true; - - public function setUp() { - parent::setUp(); - $this->groupManager = $this->getMockBuilder('\OC\Group\Manager') - ->disableOriginalConstructor() - ->getMock(); - $this->userSession = $this->getMock('\OCP\IUserSession'); - $this->groupMetadata = new \OC\Group\MetaData( - 'foo', - $this->isAdmin, - $this->groupManager, - $this->userSession - ); - } - - private function getGroupMock($countCallCount = 0) { - $group = $this->getMockBuilder('\OC\Group\Group') - ->disableOriginalConstructor() - ->getMock(); - - $group->expects($this->exactly(9)) - ->method('getGID') - ->will($this->onConsecutiveCalls( - 'admin', 'admin', 'admin', - 'g2', 'g2', 'g2', - 'g3', 'g3', 'g3')); - - $group->expects($this->exactly($countCallCount)) - ->method('count') - ->with('') - ->will($this->onConsecutiveCalls(2, 3, 5)); - - return $group; - } - - - public function testGet() { - $group = $this->getGroupMock(); - $groups = array_fill(0, 3, $group); - - $this->groupManager->expects($this->once()) - ->method('search') - ->with('') - ->will($this->returnValue($groups)); - - list($adminGroups, $ordinaryGroups) = $this->groupMetadata->get(); - - $this->assertSame(1, count($adminGroups)); - $this->assertSame(2, count($ordinaryGroups)); - - $this->assertSame('g2', $ordinaryGroups[0]['name']); - // user count is not loaded - $this->assertSame(0, $ordinaryGroups[0]['usercount']); - } - - public function testGetWithSorting() { - $this->groupMetadata->setSorting(1); - $group = $this->getGroupMock(3); - $groups = array_fill(0, 3, $group); - - $this->groupManager->expects($this->once()) - ->method('search') - ->with('') - ->will($this->returnValue($groups)); - - list($adminGroups, $ordinaryGroups) = $this->groupMetadata->get(); - - $this->assertSame(1, count($adminGroups)); - $this->assertSame(2, count($ordinaryGroups)); - - $this->assertSame('g3', $ordinaryGroups[0]['name']); - $this->assertSame(5, $ordinaryGroups[0]['usercount']); - } - - public function testGetWithCache() { - $group = $this->getGroupMock(); - $groups = array_fill(0, 3, $group); - - $this->groupManager->expects($this->once()) - ->method('search') - ->with('') - ->will($this->returnValue($groups)); - - //two calls, if caching fails call counts for group and groupmanager - //are exceeded - $this->groupMetadata->get(); - $this->groupMetadata->get(); - } - - //get() does not need to be tested with search parameters, because they are - //solely and only passed to GroupManager and Group. - - public function testGetGroupsAsAdmin() { - $this->groupManager - ->expects($this->once()) - ->method('search') - ->with('Foo') - ->will($this->returnValue(['DummyValue'])); - - $expected = ['DummyValue']; - $this->assertSame($expected, $this->invokePrivate($this->groupMetadata, 'getGroups', ['Foo'])); - } -} diff --git a/tests/lib/group/metadatatest.php b/tests/lib/group/metadatatest.php new file mode 100644 index 00000000000..593bbcb48db --- /dev/null +++ b/tests/lib/group/metadatatest.php @@ -0,0 +1,136 @@ + + * @author Lukas Reschke + * + * @copyright Copyright (c) 2015, ownCloud, Inc. + * @license AGPL-3.0 + * + * This code is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License, version 3, + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License, version 3, + * along with this program. If not, see + * + */ + +namespace Test\Group; + +class MetaDataTest extends \Test\TestCase { + /** @var \OC\Group\Manager */ + private $groupManager; + /** @var \OCP\IUserSession */ + private $userSession; + /** @var \OC\Group\MetaData */ + private $groupMetadata; + /** @var bool */ + private $isAdmin = true; + + public function setUp() { + parent::setUp(); + $this->groupManager = $this->getMockBuilder('\OC\Group\Manager') + ->disableOriginalConstructor() + ->getMock(); + $this->userSession = $this->getMock('\OCP\IUserSession'); + $this->groupMetadata = new \OC\Group\MetaData( + 'foo', + $this->isAdmin, + $this->groupManager, + $this->userSession + ); + } + + private function getGroupMock($countCallCount = 0) { + $group = $this->getMockBuilder('\OC\Group\Group') + ->disableOriginalConstructor() + ->getMock(); + + $group->expects($this->exactly(9)) + ->method('getGID') + ->will($this->onConsecutiveCalls( + 'admin', 'admin', 'admin', + 'g2', 'g2', 'g2', + 'g3', 'g3', 'g3')); + + $group->expects($this->exactly($countCallCount)) + ->method('count') + ->with('') + ->will($this->onConsecutiveCalls(2, 3, 5)); + + return $group; + } + + + public function testGet() { + $group = $this->getGroupMock(); + $groups = array_fill(0, 3, $group); + + $this->groupManager->expects($this->once()) + ->method('search') + ->with('') + ->will($this->returnValue($groups)); + + list($adminGroups, $ordinaryGroups) = $this->groupMetadata->get(); + + $this->assertSame(1, count($adminGroups)); + $this->assertSame(2, count($ordinaryGroups)); + + $this->assertSame('g2', $ordinaryGroups[0]['name']); + // user count is not loaded + $this->assertSame(0, $ordinaryGroups[0]['usercount']); + } + + public function testGetWithSorting() { + $this->groupMetadata->setSorting(1); + $group = $this->getGroupMock(3); + $groups = array_fill(0, 3, $group); + + $this->groupManager->expects($this->once()) + ->method('search') + ->with('') + ->will($this->returnValue($groups)); + + list($adminGroups, $ordinaryGroups) = $this->groupMetadata->get(); + + $this->assertSame(1, count($adminGroups)); + $this->assertSame(2, count($ordinaryGroups)); + + $this->assertSame('g3', $ordinaryGroups[0]['name']); + $this->assertSame(5, $ordinaryGroups[0]['usercount']); + } + + public function testGetWithCache() { + $group = $this->getGroupMock(); + $groups = array_fill(0, 3, $group); + + $this->groupManager->expects($this->once()) + ->method('search') + ->with('') + ->will($this->returnValue($groups)); + + //two calls, if caching fails call counts for group and groupmanager + //are exceeded + $this->groupMetadata->get(); + $this->groupMetadata->get(); + } + + //get() does not need to be tested with search parameters, because they are + //solely and only passed to GroupManager and Group. + + public function testGetGroupsAsAdmin() { + $this->groupManager + ->expects($this->once()) + ->method('search') + ->with('Foo') + ->will($this->returnValue(['DummyValue'])); + + $expected = ['DummyValue']; + $this->assertSame($expected, $this->invokePrivate($this->groupMetadata, 'getGroups', ['Foo'])); + } +} -- cgit v1.2.3 From 51db410e67491048826c9441f2c9678a006f9898 Mon Sep 17 00:00:00 2001 From: Joas Schilling Date: Thu, 19 May 2016 08:46:58 +0200 Subject: Fix namespaces in tests/lib/http/ --- tests/lib/http/client/clientservicetest.php | 4 +++- tests/lib/http/client/clienttest.php | 3 ++- tests/lib/http/client/responsetest.php | 3 ++- 3 files changed, 7 insertions(+), 3 deletions(-) (limited to 'tests') diff --git a/tests/lib/http/client/clientservicetest.php b/tests/lib/http/client/clientservicetest.php index 6d7acea0be7..3c406f30111 100644 --- a/tests/lib/http/client/clientservicetest.php +++ b/tests/lib/http/client/clientservicetest.php @@ -6,9 +6,11 @@ * See the COPYING-README file. */ -namespace OC\Http\Client; +namespace Test\Http\Client; use GuzzleHttp\Client as GuzzleClient; +use OC\Http\Client\Client; +use OC\Http\Client\ClientService; /** * Class ClientServiceTest diff --git a/tests/lib/http/client/clienttest.php b/tests/lib/http/client/clienttest.php index c76fe0532a7..705e1eeddea 100644 --- a/tests/lib/http/client/clienttest.php +++ b/tests/lib/http/client/clienttest.php @@ -6,9 +6,10 @@ * See the COPYING-README file. */ -namespace OC\Http\Client; +namespace Test\Http\Client; use GuzzleHttp\Message\Response; +use OC\Http\Client\Client; use OCP\IConfig; /** diff --git a/tests/lib/http/client/responsetest.php b/tests/lib/http/client/responsetest.php index d9b181a8e28..685f34a0baf 100644 --- a/tests/lib/http/client/responsetest.php +++ b/tests/lib/http/client/responsetest.php @@ -6,10 +6,11 @@ * See the COPYING-README file. */ -namespace OC\Http\Client; +namespace Test\Http\Client; use Guzzle\Stream\Stream; use GuzzleHttp\Message\Response as GuzzleResponse; +use OC\Http\Client\Response; /** * Class ResponseTest -- cgit v1.2.3 From 0ab1120a33eb08e7deb27145199e61ca71f695d2 Mon Sep 17 00:00:00 2001 From: Joas Schilling Date: Thu, 19 May 2016 08:48:22 +0200 Subject: Fix namespaces in tests/lib/integritycheck --- tests/lib/integritycheck/checkertest.php | 1 - tests/lib/integritycheck/helpers/EnvironmentHelperTest.php | 2 +- 2 files changed, 1 insertion(+), 2 deletions(-) (limited to 'tests') diff --git a/tests/lib/integritycheck/checkertest.php b/tests/lib/integritycheck/checkertest.php index 0910c543a7a..6e6095668b0 100644 --- a/tests/lib/integritycheck/checkertest.php +++ b/tests/lib/integritycheck/checkertest.php @@ -23,7 +23,6 @@ namespace Test\IntegrityCheck; use OC\IntegrityCheck\Checker; use OC\Memcache\NullCache; -use OCP\ICache; use phpseclib\Crypt\RSA; use phpseclib\File\X509; use Test\TestCase; diff --git a/tests/lib/integritycheck/helpers/EnvironmentHelperTest.php b/tests/lib/integritycheck/helpers/EnvironmentHelperTest.php index a1d1f671b07..9dc9214a779 100644 --- a/tests/lib/integritycheck/helpers/EnvironmentHelperTest.php +++ b/tests/lib/integritycheck/helpers/EnvironmentHelperTest.php @@ -19,7 +19,7 @@ * */ -namespace Test\IntegrityCheck\Factories; +namespace Test\IntegrityCheck\Helpers; use OC\IntegrityCheck\Helpers\EnvironmentHelper; use Test\TestCase; -- cgit v1.2.3 From 71603fe34830c6b7e65cb59ef116611544a18d1a Mon Sep 17 00:00:00 2001 From: Joas Schilling Date: Thu, 19 May 2016 08:50:14 +0200 Subject: Fix namespace in log/ and mail/ --- tests/lib/log/OwncloudTest.php | 80 ++++++++++++++++++ tests/lib/log/owncloud.php | 80 ------------------ tests/lib/mail/MailerTest.php | 123 +++++++++++++++++++++++++++ tests/lib/mail/MessageTest.php | 183 +++++++++++++++++++++++++++++++++++++++++ tests/lib/mail/mailer.php | 121 --------------------------- tests/lib/mail/message.php | 182 ---------------------------------------- 6 files changed, 386 insertions(+), 383 deletions(-) create mode 100644 tests/lib/log/OwncloudTest.php delete mode 100644 tests/lib/log/owncloud.php create mode 100644 tests/lib/mail/MailerTest.php create mode 100644 tests/lib/mail/MessageTest.php delete mode 100644 tests/lib/mail/mailer.php delete mode 100644 tests/lib/mail/message.php (limited to 'tests') diff --git a/tests/lib/log/OwncloudTest.php b/tests/lib/log/OwncloudTest.php new file mode 100644 index 00000000000..e19063a83f5 --- /dev/null +++ b/tests/lib/log/OwncloudTest.php @@ -0,0 +1,80 @@ +. + */ + +namespace Test\Log; + +use OC\Log\Owncloud; +use Test\TestCase; + +/** + * Class OwncloudTest + * + * @group DB + */ +class OwncloudTest extends TestCase +{ + private $restore_logfile; + private $restore_logdateformat; + + protected function setUp() { + parent::setUp(); + $config = \OC::$server->getConfig(); + $this->restore_logfile = $config->getSystemValue("logfile"); + $this->restore_logdateformat = $config->getSystemValue('logdateformat'); + + $config->setSystemValue("logfile", $config->getSystemValue('datadirectory') . "/logtest"); + Owncloud::init(); + } + protected function tearDown() { + $config = \OC::$server->getConfig(); + if (isset($this->restore_logfile)) { + $config->getSystemValue("logfile", $this->restore_logfile); + } else { + $config->deleteSystemValue("logfile"); + } + if (isset($this->restore_logdateformat)) { + $config->getSystemValue("logdateformat", $this->restore_logdateformat); + } else { + $config->deleteSystemValue("restore_logdateformat"); + } + Owncloud::init(); + parent::tearDown(); + } + + public function testMicrosecondsLogTimestamp() { + $config = \OC::$server->getConfig(); + # delete old logfile + unlink($config->getSystemValue('logfile')); + + # set format & write log line + $config->setSystemValue('logdateformat', 'u'); + Owncloud::write('test', 'message', \OCP\Util::ERROR); + + # read log line + $handle = @fopen($config->getSystemValue('logfile'), 'r'); + $line = fread($handle, 1000); + fclose($handle); + + # check timestamp has microseconds part + $values = (array) json_decode($line); + $microseconds = $values['time']; + $this->assertNotEquals(0, $microseconds); + + } + + +} diff --git a/tests/lib/log/owncloud.php b/tests/lib/log/owncloud.php deleted file mode 100644 index e19063a83f5..00000000000 --- a/tests/lib/log/owncloud.php +++ /dev/null @@ -1,80 +0,0 @@ -. - */ - -namespace Test\Log; - -use OC\Log\Owncloud; -use Test\TestCase; - -/** - * Class OwncloudTest - * - * @group DB - */ -class OwncloudTest extends TestCase -{ - private $restore_logfile; - private $restore_logdateformat; - - protected function setUp() { - parent::setUp(); - $config = \OC::$server->getConfig(); - $this->restore_logfile = $config->getSystemValue("logfile"); - $this->restore_logdateformat = $config->getSystemValue('logdateformat'); - - $config->setSystemValue("logfile", $config->getSystemValue('datadirectory') . "/logtest"); - Owncloud::init(); - } - protected function tearDown() { - $config = \OC::$server->getConfig(); - if (isset($this->restore_logfile)) { - $config->getSystemValue("logfile", $this->restore_logfile); - } else { - $config->deleteSystemValue("logfile"); - } - if (isset($this->restore_logdateformat)) { - $config->getSystemValue("logdateformat", $this->restore_logdateformat); - } else { - $config->deleteSystemValue("restore_logdateformat"); - } - Owncloud::init(); - parent::tearDown(); - } - - public function testMicrosecondsLogTimestamp() { - $config = \OC::$server->getConfig(); - # delete old logfile - unlink($config->getSystemValue('logfile')); - - # set format & write log line - $config->setSystemValue('logdateformat', 'u'); - Owncloud::write('test', 'message', \OCP\Util::ERROR); - - # read log line - $handle = @fopen($config->getSystemValue('logfile'), 'r'); - $line = fread($handle, 1000); - fclose($handle); - - # check timestamp has microseconds part - $values = (array) json_decode($line); - $microseconds = $values['time']; - $this->assertNotEquals(0, $microseconds); - - } - - -} diff --git a/tests/lib/mail/MailerTest.php b/tests/lib/mail/MailerTest.php new file mode 100644 index 00000000000..c63ceb5982a --- /dev/null +++ b/tests/lib/mail/MailerTest.php @@ -0,0 +1,123 @@ + + * This file is licensed under the Affero General Public License version 3 or + * later. + * See the COPYING-README file. + */ + +namespace Test\Mail; + +use OC\Mail\Mailer; +use OCP\IConfig; +use OC_Defaults; +use OCP\ILogger; +use Test\TestCase; + +class MailerTest extends TestCase { + /** @var IConfig */ + private $config; + /** @var OC_Defaults */ + private $defaults; + /** @var ILogger */ + private $logger; + /** @var Mailer */ + private $mailer; + + function setUp() { + parent::setUp(); + + $this->config = $this->getMockBuilder('\OCP\IConfig') + ->disableOriginalConstructor()->getMock(); + $this->defaults = $this->getMockBuilder('\OC_Defaults') + ->disableOriginalConstructor()->getMock(); + $this->logger = $this->getMockBuilder('\OCP\ILogger') + ->disableOriginalConstructor()->getMock(); + $this->mailer = new Mailer($this->config, $this->logger, $this->defaults); + } + + public function testGetMailInstance() { + $this->assertEquals(\Swift_MailTransport::newInstance(), self::invokePrivate($this->mailer, 'getMailinstance')); + } + + public function testGetSendMailInstanceSendMail() { + $this->config + ->expects($this->once()) + ->method('getSystemValue') + ->with('mail_smtpmode', 'sendmail') + ->will($this->returnValue('sendmail')); + + $this->assertEquals(\Swift_SendmailTransport::newInstance('/usr/sbin/sendmail -bs'), self::invokePrivate($this->mailer, 'getSendMailInstance')); + } + + public function testGetSendMailInstanceSendMailQmail() { + $this->config + ->expects($this->once()) + ->method('getSystemValue') + ->with('mail_smtpmode', 'sendmail') + ->will($this->returnValue('qmail')); + + $this->assertEquals(\Swift_SendmailTransport::newInstance('/var/qmail/bin/sendmail -bs'), self::invokePrivate($this->mailer, 'getSendMailInstance')); + } + + public function testGetInstanceDefault() { + $this->assertInstanceOf('\Swift_MailTransport', self::invokePrivate($this->mailer, 'getInstance')); + } + + public function testGetInstancePhp() { + $this->config + ->expects($this->any()) + ->method('getSystemValue') + ->will($this->returnValue('php')); + + $this->assertInstanceOf('\Swift_MailTransport', self::invokePrivate($this->mailer, 'getInstance')); + } + + public function testGetInstanceSendmail() { + $this->config + ->expects($this->any()) + ->method('getSystemValue') + ->will($this->returnValue('sendmail')); + + $this->assertInstanceOf('\Swift_Mailer', self::invokePrivate($this->mailer, 'getInstance')); + } + + public function testCreateMessage() { + $this->assertInstanceOf('\OC\Mail\Message', $this->mailer->createMessage()); + } + + /** + * @expectedException \Exception + */ + public function testSendInvalidMailException() { + $message = $this->getMockBuilder('\OC\Mail\Message') + ->disableOriginalConstructor()->getMock(); + $message->expects($this->once()) + ->method('getSwiftMessage') + ->will($this->returnValue(new \Swift_Message())); + + $this->mailer->send($message); + } + + /** + * @return array + */ + public function mailAddressProvider() { + return [ + ['lukas@owncloud.com', true], + ['lukas@localhost', true], + ['lukas@192.168.1.1', true], + ['lukas@éxämplè.com', true], + ['asdf', false], + ['lukas@owncloud.org@owncloud.com', false], + ]; + } + + /** + * @dataProvider mailAddressProvider + */ + public function testValidateMailAddress($email, $expected) { + $this->assertSame($expected, $this->mailer->validateMailAddress($email)); + } + +} diff --git a/tests/lib/mail/MessageTest.php b/tests/lib/mail/MessageTest.php new file mode 100644 index 00000000000..691168ce24c --- /dev/null +++ b/tests/lib/mail/MessageTest.php @@ -0,0 +1,183 @@ + + * This file is licensed under the Affero General Public License version 3 or + * later. + * See the COPYING-README file. + */ + +namespace Test\Mail; + +use OC\Mail\Message; +use Swift_Message; +use Test\TestCase; + +class MessageTest extends TestCase { + /** @var Swift_Message */ + private $swiftMessage; + /** @var Message */ + private $message; + + /** + * @return array + */ + public function mailAddressProvider() { + return array( + array(array('lukas@owncloud.com' => 'Lukas Reschke'), array('lukas@owncloud.com' => 'Lukas Reschke')), + array(array('lukas@owncloud.com' => 'Lukas Reschke', 'lukas@öwnclöüd.com', 'lukäs@owncloud.örg' => 'Lükäs Réschke'), + array('lukas@owncloud.com' => 'Lukas Reschke', 'lukas@xn--wncld-iuae2c.com', 'lukäs@owncloud.xn--rg-eka' => 'Lükäs Réschke')), + array(array('lukas@öwnclöüd.com'), array('lukas@xn--wncld-iuae2c.com')) + ); + } + + function setUp() { + parent::setUp(); + + $this->swiftMessage = $this->getMockBuilder('\Swift_Message') + ->disableOriginalConstructor()->getMock(); + + $this->message = new Message($this->swiftMessage); + } + + /** + * @requires function idn_to_ascii + * @dataProvider mailAddressProvider + * + * @param string $unconverted + * @param string $expected + */ + public function testConvertAddresses($unconverted, $expected) { + $this->assertSame($expected, self::invokePrivate($this->message, 'convertAddresses', array($unconverted))); + } + + public function testSetFrom() { + $this->swiftMessage + ->expects($this->once()) + ->method('setFrom') + ->with(array('lukas@owncloud.com')); + $this->message->setFrom(array('lukas@owncloud.com')); + } + + public function testGetFrom() { + $this->swiftMessage + ->expects($this->once()) + ->method('getFrom') + ->will($this->returnValue(array('lukas@owncloud.com'))); + + $this->assertSame(array('lukas@owncloud.com'), $this->message->getFrom()); + } + + public function testSetReplyTo() { + $this->swiftMessage + ->expects($this->once()) + ->method('setReplyTo') + ->with(['lukas@owncloud.com']); + $this->message->setReplyTo(['lukas@owncloud.com']); + } + + public function testGetReplyTo() { + $this->swiftMessage + ->expects($this->once()) + ->method('getReplyTo') + ->will($this->returnValue(['lukas@owncloud.com'])); + + $this->assertSame(['lukas@owncloud.com'], $this->message->getReplyTo()); + } + + public function testSetTo() { + $this->swiftMessage + ->expects($this->once()) + ->method('setTo') + ->with(array('lukas@owncloud.com')); + $this->message->setTo(array('lukas@owncloud.com')); + } + + public function testGetTo() { + $this->swiftMessage + ->expects($this->once()) + ->method('getTo') + ->will($this->returnValue(array('lukas@owncloud.com'))); + + $this->assertSame(array('lukas@owncloud.com'), $this->message->getTo()); + } + + public function testSetCc() { + $this->swiftMessage + ->expects($this->once()) + ->method('setCc') + ->with(array('lukas@owncloud.com')); + $this->message->setCc(array('lukas@owncloud.com')); + } + + public function testGetCc() { + $this->swiftMessage + ->expects($this->once()) + ->method('getCc') + ->will($this->returnValue(array('lukas@owncloud.com'))); + + $this->assertSame(array('lukas@owncloud.com'), $this->message->getCc()); + } + + public function testSetBcc() { + $this->swiftMessage + ->expects($this->once()) + ->method('setBcc') + ->with(array('lukas@owncloud.com')); + $this->message->setBcc(array('lukas@owncloud.com')); + } + + public function testGetBcc() { + $this->swiftMessage + ->expects($this->once()) + ->method('getBcc') + ->will($this->returnValue(array('lukas@owncloud.com'))); + + $this->assertSame(array('lukas@owncloud.com'), $this->message->getBcc()); + } + + public function testSetSubject() { + $this->swiftMessage + ->expects($this->once()) + ->method('setSubject') + ->with('Fancy Subject'); + + $this->message->setSubject('Fancy Subject'); + } + + public function testGetSubject() { + $this->swiftMessage + ->expects($this->once()) + ->method('getSubject') + ->will($this->returnValue('Fancy Subject')); + + $this->assertSame('Fancy Subject', $this->message->getSubject()); + } + + public function testSetPlainBody() { + $this->swiftMessage + ->expects($this->once()) + ->method('setBody') + ->with('Fancy Body'); + + $this->message->setPlainBody('Fancy Body'); + } + + public function testGetPlainBody() { + $this->swiftMessage + ->expects($this->once()) + ->method('getBody') + ->will($this->returnValue('Fancy Body')); + + $this->assertSame('Fancy Body', $this->message->getPlainBody()); + } + + public function testSetHtmlBody() { + $this->swiftMessage + ->expects($this->once()) + ->method('addPart') + ->with('Fancy Body', 'text/html'); + + $this->message->setHtmlBody('Fancy Body'); + } + +} diff --git a/tests/lib/mail/mailer.php b/tests/lib/mail/mailer.php deleted file mode 100644 index 8023cda820e..00000000000 --- a/tests/lib/mail/mailer.php +++ /dev/null @@ -1,121 +0,0 @@ - - * This file is licensed under the Affero General Public License version 3 or - * later. - * See the COPYING-README file. - */ - -namespace Test; -use OC\Mail\Mailer; -use OCP\IConfig; -use OC_Defaults; -use OCP\ILogger; - -class MailerTest extends TestCase { - /** @var IConfig */ - private $config; - /** @var OC_Defaults */ - private $defaults; - /** @var ILogger */ - private $logger; - /** @var Mailer */ - private $mailer; - - function setUp() { - parent::setUp(); - - $this->config = $this->getMockBuilder('\OCP\IConfig') - ->disableOriginalConstructor()->getMock(); - $this->defaults = $this->getMockBuilder('\OC_Defaults') - ->disableOriginalConstructor()->getMock(); - $this->logger = $this->getMockBuilder('\OCP\ILogger') - ->disableOriginalConstructor()->getMock(); - $this->mailer = new Mailer($this->config, $this->logger, $this->defaults); - } - - public function testGetMailInstance() { - $this->assertEquals(\Swift_MailTransport::newInstance(), self::invokePrivate($this->mailer, 'getMailinstance')); - } - - public function testGetSendMailInstanceSendMail() { - $this->config - ->expects($this->once()) - ->method('getSystemValue') - ->with('mail_smtpmode', 'sendmail') - ->will($this->returnValue('sendmail')); - - $this->assertEquals(\Swift_SendmailTransport::newInstance('/usr/sbin/sendmail -bs'), self::invokePrivate($this->mailer, 'getSendMailInstance')); - } - - public function testGetSendMailInstanceSendMailQmail() { - $this->config - ->expects($this->once()) - ->method('getSystemValue') - ->with('mail_smtpmode', 'sendmail') - ->will($this->returnValue('qmail')); - - $this->assertEquals(\Swift_SendmailTransport::newInstance('/var/qmail/bin/sendmail -bs'), self::invokePrivate($this->mailer, 'getSendMailInstance')); - } - - public function testGetInstanceDefault() { - $this->assertInstanceOf('\Swift_MailTransport', self::invokePrivate($this->mailer, 'getInstance')); - } - - public function testGetInstancePhp() { - $this->config - ->expects($this->any()) - ->method('getSystemValue') - ->will($this->returnValue('php')); - - $this->assertInstanceOf('\Swift_MailTransport', self::invokePrivate($this->mailer, 'getInstance')); - } - - public function testGetInstanceSendmail() { - $this->config - ->expects($this->any()) - ->method('getSystemValue') - ->will($this->returnValue('sendmail')); - - $this->assertInstanceOf('\Swift_Mailer', self::invokePrivate($this->mailer, 'getInstance')); - } - - public function testCreateMessage() { - $this->assertInstanceOf('\OC\Mail\Message', $this->mailer->createMessage()); - } - - /** - * @expectedException \Exception - */ - public function testSendInvalidMailException() { - $message = $this->getMockBuilder('\OC\Mail\Message') - ->disableOriginalConstructor()->getMock(); - $message->expects($this->once()) - ->method('getSwiftMessage') - ->will($this->returnValue(new \Swift_Message())); - - $this->mailer->send($message); - } - - /** - * @return array - */ - public function mailAddressProvider() { - return [ - ['lukas@owncloud.com', true], - ['lukas@localhost', true], - ['lukas@192.168.1.1', true], - ['lukas@éxämplè.com', true], - ['asdf', false], - ['lukas@owncloud.org@owncloud.com', false], - ]; - } - - /** - * @dataProvider mailAddressProvider - */ - public function testValidateMailAddress($email, $expected) { - $this->assertSame($expected, $this->mailer->validateMailAddress($email)); - } - -} diff --git a/tests/lib/mail/message.php b/tests/lib/mail/message.php deleted file mode 100644 index 339677c0a7c..00000000000 --- a/tests/lib/mail/message.php +++ /dev/null @@ -1,182 +0,0 @@ - - * This file is licensed under the Affero General Public License version 3 or - * later. - * See the COPYING-README file. - */ - -namespace Test; - -use OC\Mail\Message; -use Swift_Message; - -class MessageTest extends TestCase { - /** @var Swift_Message */ - private $swiftMessage; - /** @var Message */ - private $message; - - /** - * @return array - */ - public function mailAddressProvider() { - return array( - array(array('lukas@owncloud.com' => 'Lukas Reschke'), array('lukas@owncloud.com' => 'Lukas Reschke')), - array(array('lukas@owncloud.com' => 'Lukas Reschke', 'lukas@öwnclöüd.com', 'lukäs@owncloud.örg' => 'Lükäs Réschke'), - array('lukas@owncloud.com' => 'Lukas Reschke', 'lukas@xn--wncld-iuae2c.com', 'lukäs@owncloud.xn--rg-eka' => 'Lükäs Réschke')), - array(array('lukas@öwnclöüd.com'), array('lukas@xn--wncld-iuae2c.com')) - ); - } - - function setUp() { - parent::setUp(); - - $this->swiftMessage = $this->getMockBuilder('\Swift_Message') - ->disableOriginalConstructor()->getMock(); - - $this->message = new Message($this->swiftMessage); - } - - /** - * @requires function idn_to_ascii - * @dataProvider mailAddressProvider - * - * @param string $unconverted - * @param string $expected - */ - public function testConvertAddresses($unconverted, $expected) { - $this->assertSame($expected, self::invokePrivate($this->message, 'convertAddresses', array($unconverted))); - } - - public function testSetFrom() { - $this->swiftMessage - ->expects($this->once()) - ->method('setFrom') - ->with(array('lukas@owncloud.com')); - $this->message->setFrom(array('lukas@owncloud.com')); - } - - public function testGetFrom() { - $this->swiftMessage - ->expects($this->once()) - ->method('getFrom') - ->will($this->returnValue(array('lukas@owncloud.com'))); - - $this->assertSame(array('lukas@owncloud.com'), $this->message->getFrom()); - } - - public function testSetReplyTo() { - $this->swiftMessage - ->expects($this->once()) - ->method('setReplyTo') - ->with(['lukas@owncloud.com']); - $this->message->setReplyTo(['lukas@owncloud.com']); - } - - public function testGetReplyTo() { - $this->swiftMessage - ->expects($this->once()) - ->method('getReplyTo') - ->will($this->returnValue(['lukas@owncloud.com'])); - - $this->assertSame(['lukas@owncloud.com'], $this->message->getReplyTo()); - } - - public function testSetTo() { - $this->swiftMessage - ->expects($this->once()) - ->method('setTo') - ->with(array('lukas@owncloud.com')); - $this->message->setTo(array('lukas@owncloud.com')); - } - - public function testGetTo() { - $this->swiftMessage - ->expects($this->once()) - ->method('getTo') - ->will($this->returnValue(array('lukas@owncloud.com'))); - - $this->assertSame(array('lukas@owncloud.com'), $this->message->getTo()); - } - - public function testSetCc() { - $this->swiftMessage - ->expects($this->once()) - ->method('setCc') - ->with(array('lukas@owncloud.com')); - $this->message->setCc(array('lukas@owncloud.com')); - } - - public function testGetCc() { - $this->swiftMessage - ->expects($this->once()) - ->method('getCc') - ->will($this->returnValue(array('lukas@owncloud.com'))); - - $this->assertSame(array('lukas@owncloud.com'), $this->message->getCc()); - } - - public function testSetBcc() { - $this->swiftMessage - ->expects($this->once()) - ->method('setBcc') - ->with(array('lukas@owncloud.com')); - $this->message->setBcc(array('lukas@owncloud.com')); - } - - public function testGetBcc() { - $this->swiftMessage - ->expects($this->once()) - ->method('getBcc') - ->will($this->returnValue(array('lukas@owncloud.com'))); - - $this->assertSame(array('lukas@owncloud.com'), $this->message->getBcc()); - } - - public function testSetSubject() { - $this->swiftMessage - ->expects($this->once()) - ->method('setSubject') - ->with('Fancy Subject'); - - $this->message->setSubject('Fancy Subject'); - } - - public function testGetSubject() { - $this->swiftMessage - ->expects($this->once()) - ->method('getSubject') - ->will($this->returnValue('Fancy Subject')); - - $this->assertSame('Fancy Subject', $this->message->getSubject()); - } - - public function testSetPlainBody() { - $this->swiftMessage - ->expects($this->once()) - ->method('setBody') - ->with('Fancy Body'); - - $this->message->setPlainBody('Fancy Body'); - } - - public function testGetPlainBody() { - $this->swiftMessage - ->expects($this->once()) - ->method('getBody') - ->will($this->returnValue('Fancy Body')); - - $this->assertSame('Fancy Body', $this->message->getPlainBody()); - } - - public function testSetHtmlBody() { - $this->swiftMessage - ->expects($this->once()) - ->method('addPart') - ->with('Fancy Body', 'text/html'); - - $this->message->setHtmlBody('Fancy Body'); - } - -} -- cgit v1.2.3 From 859d2bc0ffb0c0c8a473679c1e785366e83b267b Mon Sep 17 00:00:00 2001 From: Joas Schilling Date: Thu, 19 May 2016 08:53:06 +0200 Subject: Fix namespace of memcache/ and ocs/ --- tests/lib/memcache/FactoryTest.php | 132 ++++++++++++++++++++++++++++ tests/lib/memcache/factory.php | 132 ---------------------------- tests/lib/ocs/PrivatedataTest.php | 172 +++++++++++++++++++++++++++++++++++++ tests/lib/ocs/privatedata.php | 168 ------------------------------------ 4 files changed, 304 insertions(+), 300 deletions(-) create mode 100644 tests/lib/memcache/FactoryTest.php delete mode 100644 tests/lib/memcache/factory.php create mode 100644 tests/lib/ocs/PrivatedataTest.php delete mode 100644 tests/lib/ocs/privatedata.php (limited to 'tests') diff --git a/tests/lib/memcache/FactoryTest.php b/tests/lib/memcache/FactoryTest.php new file mode 100644 index 00000000000..8607ea7de9b --- /dev/null +++ b/tests/lib/memcache/FactoryTest.php @@ -0,0 +1,132 @@ + + * + * @copyright Copyright (c) 2015, ownCloud, Inc. + * @license AGPL-3.0 + * + * This code is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License, version 3, + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License, version 3, + * along with this program. If not, see + * + */ +namespace Test\Memcache; + +class Test_Factory_Available_Cache1 { + public function __construct($prefix = '') { + } + + public static function isAvailable() { + return true; + } +} + +class Test_Factory_Available_Cache2 { + public function __construct($prefix = '') { + } + + public static function isAvailable() { + return true; + } +} + +class Test_Factory_Unavailable_Cache1 { + public function __construct($prefix = '') { + } + + public static function isAvailable() { + return false; + } +} + +class Test_Factory_Unavailable_Cache2 { + public function __construct($prefix = '') { + } + + public static function isAvailable() { + return false; + } +} + +class FactoryTest extends \Test\TestCase { + const AVAILABLE1 = '\\Test\\Memcache\\Test_Factory_Available_Cache1'; + const AVAILABLE2 = '\\Test\\Memcache\\Test_Factory_Available_Cache2'; + const UNAVAILABLE1 = '\\Test\\Memcache\\Test_Factory_Unavailable_Cache1'; + const UNAVAILABLE2 = '\\Test\\Memcache\\Test_Factory_Unavailable_Cache2'; + + public function cacheAvailabilityProvider() { + return [ + [ + // local and distributed available + self::AVAILABLE1, self::AVAILABLE2, null, + self::AVAILABLE1, self::AVAILABLE2, \OC\Memcache\Factory::NULL_CACHE + ], + [ + // local and distributed null + null, null, null, + \OC\Memcache\Factory::NULL_CACHE, \OC\Memcache\Factory::NULL_CACHE, \OC\Memcache\Factory::NULL_CACHE + ], + [ + // local available, distributed null (most common scenario) + self::AVAILABLE1, null, null, + self::AVAILABLE1, self::AVAILABLE1, \OC\Memcache\Factory::NULL_CACHE + ], + [ + // locking cache available + null, null, self::AVAILABLE1, + \OC\Memcache\Factory::NULL_CACHE, \OC\Memcache\Factory::NULL_CACHE, self::AVAILABLE1 + ], + [ + // locking cache unavailable: no exception here in the factory + null, null, self::UNAVAILABLE1, + \OC\Memcache\Factory::NULL_CACHE, \OC\Memcache\Factory::NULL_CACHE, \OC\Memcache\Factory::NULL_CACHE + ] + ]; + } + + public function cacheUnavailableProvider() { + return [ + [ + // local available, distributed unavailable + self::AVAILABLE1, self::UNAVAILABLE1 + ], + [ + // local unavailable, distributed available + self::UNAVAILABLE1, self::AVAILABLE1 + ], + [ + // local and distributed unavailable + self::UNAVAILABLE1, self::UNAVAILABLE2 + ], + ]; + } + + /** + * @dataProvider cacheAvailabilityProvider + */ + public function testCacheAvailability($localCache, $distributedCache, $lockingCache, + $expectedLocalCache, $expectedDistributedCache, $expectedLockingCache) { + $logger = $this->getMockBuilder('\OCP\ILogger')->getMock(); + $factory = new \OC\Memcache\Factory('abc', $logger, $localCache, $distributedCache, $lockingCache); + $this->assertTrue(is_a($factory->createLocal(), $expectedLocalCache)); + $this->assertTrue(is_a($factory->createDistributed(), $expectedDistributedCache)); + $this->assertTrue(is_a($factory->createLocking(), $expectedLockingCache)); + } + + /** + * @dataProvider cacheUnavailableProvider + * @expectedException \OC\HintException + */ + public function testCacheNotAvailableException($localCache, $distributedCache) { + $logger = $this->getMockBuilder('\OCP\ILogger')->getMock(); + new \OC\Memcache\Factory('abc', $logger, $localCache, $distributedCache); + } +} diff --git a/tests/lib/memcache/factory.php b/tests/lib/memcache/factory.php deleted file mode 100644 index 33a27a42113..00000000000 --- a/tests/lib/memcache/factory.php +++ /dev/null @@ -1,132 +0,0 @@ - - * - * @copyright Copyright (c) 2015, ownCloud, Inc. - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see - * - */ -namespace Test\Memcache; - -class Test_Factory_Available_Cache1 { - public function __construct($prefix = '') { - } - - public static function isAvailable() { - return true; - } -} - -class Test_Factory_Available_Cache2 { - public function __construct($prefix = '') { - } - - public static function isAvailable() { - return true; - } -} - -class Test_Factory_Unavailable_Cache1 { - public function __construct($prefix = '') { - } - - public static function isAvailable() { - return false; - } -} - -class Test_Factory_Unavailable_Cache2 { - public function __construct($prefix = '') { - } - - public static function isAvailable() { - return false; - } -} - -class Test_Factory extends \Test\TestCase { - const AVAILABLE1 = '\\Test\\Memcache\\Test_Factory_Available_Cache1'; - const AVAILABLE2 = '\\Test\\Memcache\\Test_Factory_Available_Cache2'; - const UNAVAILABLE1 = '\\Test\\Memcache\\Test_Factory_Unavailable_Cache1'; - const UNAVAILABLE2 = '\\Test\\Memcache\\Test_Factory_Unavailable_Cache2'; - - public function cacheAvailabilityProvider() { - return [ - [ - // local and distributed available - self::AVAILABLE1, self::AVAILABLE2, null, - self::AVAILABLE1, self::AVAILABLE2, \OC\Memcache\Factory::NULL_CACHE - ], - [ - // local and distributed null - null, null, null, - \OC\Memcache\Factory::NULL_CACHE, \OC\Memcache\Factory::NULL_CACHE, \OC\Memcache\Factory::NULL_CACHE - ], - [ - // local available, distributed null (most common scenario) - self::AVAILABLE1, null, null, - self::AVAILABLE1, self::AVAILABLE1, \OC\Memcache\Factory::NULL_CACHE - ], - [ - // locking cache available - null, null, self::AVAILABLE1, - \OC\Memcache\Factory::NULL_CACHE, \OC\Memcache\Factory::NULL_CACHE, self::AVAILABLE1 - ], - [ - // locking cache unavailable: no exception here in the factory - null, null, self::UNAVAILABLE1, - \OC\Memcache\Factory::NULL_CACHE, \OC\Memcache\Factory::NULL_CACHE, \OC\Memcache\Factory::NULL_CACHE - ] - ]; - } - - public function cacheUnavailableProvider() { - return [ - [ - // local available, distributed unavailable - self::AVAILABLE1, self::UNAVAILABLE1 - ], - [ - // local unavailable, distributed available - self::UNAVAILABLE1, self::AVAILABLE1 - ], - [ - // local and distributed unavailable - self::UNAVAILABLE1, self::UNAVAILABLE2 - ], - ]; - } - - /** - * @dataProvider cacheAvailabilityProvider - */ - public function testCacheAvailability($localCache, $distributedCache, $lockingCache, - $expectedLocalCache, $expectedDistributedCache, $expectedLockingCache) { - $logger = $this->getMockBuilder('\OCP\ILogger')->getMock(); - $factory = new \OC\Memcache\Factory('abc', $logger, $localCache, $distributedCache, $lockingCache); - $this->assertTrue(is_a($factory->createLocal(), $expectedLocalCache)); - $this->assertTrue(is_a($factory->createDistributed(), $expectedDistributedCache)); - $this->assertTrue(is_a($factory->createLocking(), $expectedLockingCache)); - } - - /** - * @dataProvider cacheUnavailableProvider - * @expectedException \OC\HintException - */ - public function testCacheNotAvailableException($localCache, $distributedCache) { - $logger = $this->getMockBuilder('\OCP\ILogger')->getMock(); - new \OC\Memcache\Factory('abc', $logger, $localCache, $distributedCache); - } -} diff --git a/tests/lib/ocs/PrivatedataTest.php b/tests/lib/ocs/PrivatedataTest.php new file mode 100644 index 00000000000..0b3b23b8804 --- /dev/null +++ b/tests/lib/ocs/PrivatedataTest.php @@ -0,0 +1,172 @@ +. + * + */ + +namespace Test\OCS; + +use OC_OCS_Privatedata; + +/** + * Class PrivatedataTest + * + * @group DB + */ +class PrivatedataTest extends \Test\TestCase { + private $appKey; + + protected function setUp() { + parent::setUp(); + \OC::$server->getSession()->set('user_id', 'user1'); + $this->appKey = $this->getUniqueID('app'); + } + + 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 testSetSameValue() { + $_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']); + + // set the same value again + $_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']); + } + + 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 + * @param integer $expectedArraySize + */ + 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/ocs/privatedata.php b/tests/lib/ocs/privatedata.php deleted file mode 100644 index ce153bf07d6..00000000000 --- a/tests/lib/ocs/privatedata.php +++ /dev/null @@ -1,168 +0,0 @@ -. - * - */ - -/** - * Class Test_OC_OCS_Privatedata - * - * @group DB - */ -class Test_OC_OCS_Privatedata extends \Test\TestCase { - private $appKey; - - protected function setUp() { - parent::setUp(); - \OC::$server->getSession()->set('user_id', 'user1'); - $this->appKey = $this->getUniqueID('app'); - } - - 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 testSetSameValue() { - $_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']); - - // set the same value again - $_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']); - } - - 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 - * @param integer $expectedArraySize - */ - public function assertOcsResult($expectedArraySize, $result) { - $this->assertEquals(100, $result->getStatusCode()); - $data = $result->getData(); - $this->assertTrue(is_array($data)); - $this->assertEquals($expectedArraySize, sizeof($data)); - } -} -- cgit v1.2.3 From d19d6533dd8061f130e50fc55943cdcebc923fdd Mon Sep 17 00:00:00 2001 From: Joas Schilling Date: Thu, 19 May 2016 08:56:47 +0200 Subject: Fix public/ namespace in tests --- tests/lib/public/contacts.php | 118 --------------------------- tests/lib/public/ocpconfig.php | 36 --------- tests/lib/public/util.php | 47 ----------- tests/lib/publicnamespace/ContactsTest.php | 120 ++++++++++++++++++++++++++++ tests/lib/publicnamespace/OCPConfigTest.php | 38 +++++++++ tests/lib/publicnamespace/UtilTest.php | 50 ++++++++++++ 6 files changed, 208 insertions(+), 201 deletions(-) delete mode 100644 tests/lib/public/contacts.php delete mode 100644 tests/lib/public/ocpconfig.php delete mode 100644 tests/lib/public/util.php create mode 100644 tests/lib/publicnamespace/ContactsTest.php create mode 100644 tests/lib/publicnamespace/OCPConfigTest.php create mode 100644 tests/lib/publicnamespace/UtilTest.php (limited to 'tests') diff --git a/tests/lib/public/contacts.php b/tests/lib/public/contacts.php deleted file mode 100644 index 151e98d3905..00000000000 --- a/tests/lib/public/contacts.php +++ /dev/null @@ -1,118 +0,0 @@ -. - */ - -class Test_Contacts extends \Test\TestCase { - protected function setUp() { - parent::setUp(); - OCP\Contacts::clear(); - } - - public function testDisabledIfEmpty() { - // pretty simple - $this->assertFalse(OCP\Contacts::isEnabled()); - } - - public function testEnabledAfterRegister() { - // create mock for the addressbook - $stub = $this->getMockForAbstractClass("OCP\IAddressBook", array('getKey')); - - // we expect getKey to be called twice: - // first time on register - // second time on un-register - $stub->expects($this->exactly(2)) - ->method('getKey'); - - // not enabled before register - $this->assertFalse(OCP\Contacts::isEnabled()); - - // register the address book - OCP\Contacts::registerAddressBook($stub); - - // contacts api shall be enabled - $this->assertTrue(OCP\Contacts::isEnabled()); - - // unregister the address book - OCP\Contacts::unregisterAddressBook($stub); - - // not enabled after register - $this->assertFalse(OCP\Contacts::isEnabled()); - } - - public function testAddressBookEnumeration() { - // create mock for the addressbook - $stub = $this->getMockForAbstractClass("OCP\IAddressBook", array('getKey', 'getDisplayName')); - - // setup return for method calls - $stub->expects($this->any()) - ->method('getKey') - ->will($this->returnValue('SIMPLE_ADDRESS_BOOK')); - $stub->expects($this->any()) - ->method('getDisplayName') - ->will($this->returnValue('A very simple Addressbook')); - - // register the address book - OCP\Contacts::registerAddressBook($stub); - $all_books = OCP\Contacts::getAddressBooks(); - - $this->assertEquals(1, count($all_books)); - $this->assertEquals('A very simple Addressbook', $all_books['SIMPLE_ADDRESS_BOOK']); - } - - public function testSearchInAddressBook() { - // create mock for the addressbook - $stub1 = $this->getMockForAbstractClass("OCP\IAddressBook", array('getKey', 'getDisplayName', 'search')); - $stub2 = $this->getMockForAbstractClass("OCP\IAddressBook", array('getKey', 'getDisplayName', 'search')); - - $searchResult1 = array( - array('id' => 0, 'FN' => 'Frank Karlitschek', 'EMAIL' => 'a@b.c', 'GEO' => '37.386013;-122.082932'), - array('id' => 5, 'FN' => 'Klaas Freitag', 'EMAIL' => array('d@e.f', 'g@h.i')), - ); - $searchResult2 = array( - array('id' => 0, 'FN' => 'Thomas Müller', 'EMAIL' => 'a@b.c'), - array('id' => 5, 'FN' => 'Thomas Tanghus', 'EMAIL' => array('d@e.f', 'g@h.i')), - ); - - // setup return for method calls for $stub1 - $stub1->expects($this->any())->method('getKey')->will($this->returnValue('SIMPLE_ADDRESS_BOOK1')); - $stub1->expects($this->any())->method('getDisplayName')->will($this->returnValue('Address book ownCloud Inc')); - $stub1->expects($this->any())->method('search')->will($this->returnValue($searchResult1)); - - // setup return for method calls for $stub2 - $stub2->expects($this->any())->method('getKey')->will($this->returnValue('SIMPLE_ADDRESS_BOOK2')); - $stub2->expects($this->any())->method('getDisplayName')->will($this->returnValue('Address book ownCloud Community')); - $stub2->expects($this->any())->method('search')->will($this->returnValue($searchResult2)); - - // register the address books - OCP\Contacts::registerAddressBook($stub1); - OCP\Contacts::registerAddressBook($stub2); - $all_books = OCP\Contacts::getAddressBooks(); - - // assert the count - doesn't hurt - $this->assertEquals(2, count($all_books)); - - // perform the search - $result = OCP\Contacts::search('x', array()); - - // we expect 4 hits - $this->assertEquals(4, count($result)); - - } -} diff --git a/tests/lib/public/ocpconfig.php b/tests/lib/public/ocpconfig.php deleted file mode 100644 index 947d2b3c9ef..00000000000 --- a/tests/lib/public/ocpconfig.php +++ /dev/null @@ -1,36 +0,0 @@ -. - */ - -class Test_OCPConfig extends \Test\TestCase { - - public function testSetAppValueIfSetToNull() { - - $key = $this->getUniqueID('key-'); - - $result = \OCP\Config::setAppValue('unit-test', $key, null); - $this->assertTrue($result); - - $result = \OCP\Config::setAppValue('unit-test', $key, '12'); - $this->assertTrue($result); - - } - -} diff --git a/tests/lib/public/util.php b/tests/lib/public/util.php deleted file mode 100644 index ebc4f70079b..00000000000 --- a/tests/lib/public/util.php +++ /dev/null @@ -1,47 +0,0 @@ -. - */ - -class Test_Public_Util extends \Test\TestCase { - protected function setUp() { - parent::setUp(); - OCP\Contacts::clear(); - } - - /** - * @dataProvider channelProvider - * - * @param string $channel - */ - public function testOverrideChannel($channel) { - \OCP\Util::setChannel($channel); - $actual = \OCP\Util::getChannel($channel); - $this->assertEquals($channel, $actual); - } - - public function channelProvider() { - return [ - ['daily'], - ['beta'], - ['stable'], - ['production'] - ]; - } -} diff --git a/tests/lib/publicnamespace/ContactsTest.php b/tests/lib/publicnamespace/ContactsTest.php new file mode 100644 index 00000000000..8b07c4831b6 --- /dev/null +++ b/tests/lib/publicnamespace/ContactsTest.php @@ -0,0 +1,120 @@ +. + */ + +namespace Test\PublicNamespace; + +class ContactsTest extends \Test\TestCase { + protected function setUp() { + parent::setUp(); + \OCP\Contacts::clear(); + } + + public function testDisabledIfEmpty() { + // pretty simple + $this->assertFalse(\OCP\Contacts::isEnabled()); + } + + public function testEnabledAfterRegister() { + // create mock for the addressbook + $stub = $this->getMockForAbstractClass("OCP\IAddressBook", array('getKey')); + + // we expect getKey to be called twice: + // first time on register + // second time on un-register + $stub->expects($this->exactly(2)) + ->method('getKey'); + + // not enabled before register + $this->assertFalse(\OCP\Contacts::isEnabled()); + + // register the address book + \OCP\Contacts::registerAddressBook($stub); + + // contacts api shall be enabled + $this->assertTrue(\OCP\Contacts::isEnabled()); + + // unregister the address book + \OCP\Contacts::unregisterAddressBook($stub); + + // not enabled after register + $this->assertFalse(\OCP\Contacts::isEnabled()); + } + + public function testAddressBookEnumeration() { + // create mock for the addressbook + $stub = $this->getMockForAbstractClass("OCP\IAddressBook", array('getKey', 'getDisplayName')); + + // setup return for method calls + $stub->expects($this->any()) + ->method('getKey') + ->will($this->returnValue('SIMPLE_ADDRESS_BOOK')); + $stub->expects($this->any()) + ->method('getDisplayName') + ->will($this->returnValue('A very simple Addressbook')); + + // register the address book + \OCP\Contacts::registerAddressBook($stub); + $all_books = \OCP\Contacts::getAddressBooks(); + + $this->assertEquals(1, count($all_books)); + $this->assertEquals('A very simple Addressbook', $all_books['SIMPLE_ADDRESS_BOOK']); + } + + public function testSearchInAddressBook() { + // create mock for the addressbook + $stub1 = $this->getMockForAbstractClass("OCP\IAddressBook", array('getKey', 'getDisplayName', 'search')); + $stub2 = $this->getMockForAbstractClass("OCP\IAddressBook", array('getKey', 'getDisplayName', 'search')); + + $searchResult1 = array( + array('id' => 0, 'FN' => 'Frank Karlitschek', 'EMAIL' => 'a@b.c', 'GEO' => '37.386013;-122.082932'), + array('id' => 5, 'FN' => 'Klaas Freitag', 'EMAIL' => array('d@e.f', 'g@h.i')), + ); + $searchResult2 = array( + array('id' => 0, 'FN' => 'Thomas Müller', 'EMAIL' => 'a@b.c'), + array('id' => 5, 'FN' => 'Thomas Tanghus', 'EMAIL' => array('d@e.f', 'g@h.i')), + ); + + // setup return for method calls for $stub1 + $stub1->expects($this->any())->method('getKey')->will($this->returnValue('SIMPLE_ADDRESS_BOOK1')); + $stub1->expects($this->any())->method('getDisplayName')->will($this->returnValue('Address book ownCloud Inc')); + $stub1->expects($this->any())->method('search')->will($this->returnValue($searchResult1)); + + // setup return for method calls for $stub2 + $stub2->expects($this->any())->method('getKey')->will($this->returnValue('SIMPLE_ADDRESS_BOOK2')); + $stub2->expects($this->any())->method('getDisplayName')->will($this->returnValue('Address book ownCloud Community')); + $stub2->expects($this->any())->method('search')->will($this->returnValue($searchResult2)); + + // register the address books + \OCP\Contacts::registerAddressBook($stub1); + \OCP\Contacts::registerAddressBook($stub2); + $all_books = \OCP\Contacts::getAddressBooks(); + + // assert the count - doesn't hurt + $this->assertEquals(2, count($all_books)); + + // perform the search + $result = \OCP\Contacts::search('x', array()); + + // we expect 4 hits + $this->assertEquals(4, count($result)); + + } +} diff --git a/tests/lib/publicnamespace/OCPConfigTest.php b/tests/lib/publicnamespace/OCPConfigTest.php new file mode 100644 index 00000000000..44fd234735e --- /dev/null +++ b/tests/lib/publicnamespace/OCPConfigTest.php @@ -0,0 +1,38 @@ +. + */ + +namespace Test\PublicNamespace; + +class OCPConfigTest extends \Test\TestCase { + + public function testSetAppValueIfSetToNull() { + + $key = $this->getUniqueID('key-'); + + $result = \OCP\Config::setAppValue('unit-test', $key, null); + $this->assertTrue($result); + + $result = \OCP\Config::setAppValue('unit-test', $key, '12'); + $this->assertTrue($result); + + } + +} diff --git a/tests/lib/publicnamespace/UtilTest.php b/tests/lib/publicnamespace/UtilTest.php new file mode 100644 index 00000000000..31d1f9fb0ee --- /dev/null +++ b/tests/lib/publicnamespace/UtilTest.php @@ -0,0 +1,50 @@ +. + */ + +namespace Test\PublicNamespace; + + +class UtilTest extends \Test\TestCase { + protected function setUp() { + parent::setUp(); + \OCP\Contacts::clear(); + } + + /** + * @dataProvider channelProvider + * + * @param string $channel + */ + public function testOverrideChannel($channel) { + \OCP\Util::setChannel($channel); + $actual = \OCP\Util::getChannel($channel); + $this->assertEquals($channel, $actual); + } + + public function channelProvider() { + return [ + ['daily'], + ['beta'], + ['stable'], + ['production'] + ]; + } +} -- cgit v1.2.3 From a9f24a74a238536c787047b3f2950510738902da Mon Sep 17 00:00:00 2001 From: Joas Schilling Date: Thu, 19 May 2016 08:59:37 +0200 Subject: Fix namespace in repair/ --- tests/lib/repair/RepairCollationTest.php | 88 ++++++++++++++++++++++++++++++++ tests/lib/repair/repaircollation.php | 85 ------------------------------ 2 files changed, 88 insertions(+), 85 deletions(-) create mode 100644 tests/lib/repair/RepairCollationTest.php delete mode 100644 tests/lib/repair/repaircollation.php (limited to 'tests') diff --git a/tests/lib/repair/RepairCollationTest.php b/tests/lib/repair/RepairCollationTest.php new file mode 100644 index 00000000000..2e304a74abc --- /dev/null +++ b/tests/lib/repair/RepairCollationTest.php @@ -0,0 +1,88 @@ + + * This file is licensed under the Affero General Public License version 3 or + * later. + * See the COPYING-README file. + */ + +class TestCollationRepair extends \OC\Repair\Collation { + /** + * @param \Doctrine\DBAL\Connection $connection + * @return string[] + */ + public function getAllNonUTF8BinTables($connection) { + return parent::getAllNonUTF8BinTables($connection); + } +} + +/** + * Tests for the converting of MySQL tables to InnoDB engine + * + * @group DB + * + * @see \OC\Repair\RepairMimeTypes + */ +class RepairCollationTest extends \Test\TestCase { + + /** + * @var TestCollationRepair + */ + private $repair; + + /** + * @var \Doctrine\DBAL\Connection + */ + private $connection; + + /** + * @var string + */ + private $tableName; + + /** + * @var \OCP\IConfig + */ + private $config; + + protected function setUp() { + parent::setUp(); + + $this->connection = \OC::$server->getDatabaseConnection(); + $this->config = \OC::$server->getConfig(); + if (!$this->connection->getDatabasePlatform() instanceof \Doctrine\DBAL\Platforms\MySqlPlatform) { + $this->markTestSkipped("Test only relevant on MySql"); + } + + $dbPrefix = $this->config->getSystemValue("dbtableprefix"); + $this->tableName = $this->getUniqueID($dbPrefix . "_collation_test"); + $this->connection->exec("CREATE TABLE $this->tableName(text VARCHAR(16)) COLLATE utf8_unicode_ci"); + + $this->repair = new TestCollationRepair($this->config, $this->connection); + } + + protected function tearDown() { + $this->connection->getSchemaManager()->dropTable($this->tableName); + parent::tearDown(); + } + + public function testCollationConvert() { + $tables = $this->repair->getAllNonUTF8BinTables($this->connection); + $this->assertGreaterThanOrEqual(1, count($tables)); + + /** @var IOutput | \PHPUnit_Framework_MockObject_MockObject $outputMock */ + $outputMock = $this->getMockBuilder('\OCP\Migration\IOutput') + ->disableOriginalConstructor() + ->getMock(); + + $this->repair->run($outputMock); + + $tables = $this->repair->getAllNonUTF8BinTables($this->connection); + $this->assertCount(0, $tables); + } +} diff --git a/tests/lib/repair/repaircollation.php b/tests/lib/repair/repaircollation.php deleted file mode 100644 index 4efa8ccc552..00000000000 --- a/tests/lib/repair/repaircollation.php +++ /dev/null @@ -1,85 +0,0 @@ - - * This file is licensed under the Affero General Public License version 3 or - * later. - * See the COPYING-README file. - */ - -class TestCollationRepair extends \OC\Repair\Collation { - /** - * @param \Doctrine\DBAL\Connection $connection - * @return string[] - */ - public function getAllNonUTF8BinTables($connection) { - return parent::getAllNonUTF8BinTables($connection); - } -} - -/** - * Tests for the converting of MySQL tables to InnoDB engine - * - * @group DB - * - * @see \OC\Repair\RepairMimeTypes - */ -class TestRepairCollation extends \Test\TestCase { - - /** - * @var TestCollationRepair - */ - private $repair; - - /** - * @var \Doctrine\DBAL\Connection - */ - private $connection; - - /** - * @var string - */ - private $tableName; - - /** - * @var \OCP\IConfig - */ - private $config; - - protected function setUp() { - parent::setUp(); - - $this->connection = \OC::$server->getDatabaseConnection(); - $this->config = \OC::$server->getConfig(); - if (!$this->connection->getDatabasePlatform() instanceof \Doctrine\DBAL\Platforms\MySqlPlatform) { - $this->markTestSkipped("Test only relevant on MySql"); - } - - $dbPrefix = $this->config->getSystemValue("dbtableprefix"); - $this->tableName = $this->getUniqueID($dbPrefix . "_collation_test"); - $this->connection->exec("CREATE TABLE $this->tableName(text VARCHAR(16)) COLLATE utf8_unicode_ci"); - - $this->repair = new TestCollationRepair($this->config, $this->connection); - } - - protected function tearDown() { - $this->connection->getSchemaManager()->dropTable($this->tableName); - parent::tearDown(); - } - - public function testCollationConvert() { - $tables = $this->repair->getAllNonUTF8BinTables($this->connection); - $this->assertGreaterThanOrEqual(1, count($tables)); - - /** @var IOutput | \PHPUnit_Framework_MockObject_MockObject $outputMock */ - $outputMock = $this->getMockBuilder('\OCP\Migration\IOutput') - ->disableOriginalConstructor() - ->getMock(); - - $this->repair->run($outputMock); - - $tables = $this->repair->getAllNonUTF8BinTables($this->connection); - $this->assertCount(0, $tables); - } -} -- cgit v1.2.3 From 68481c10e61b9db04f6a3627d270aff7e712bd25 Mon Sep 17 00:00:00 2001 From: Joas Schilling Date: Thu, 19 May 2016 09:02:58 +0200 Subject: Fix namespaces in security/ --- tests/lib/security/CertificateManagerTest.php | 121 +++++++++++++++++++++ tests/lib/security/CertificateTest.php | 111 +++++++++++++++++++ tests/lib/security/CredentialsManagerTest.php | 104 ++++++++++++++++++ tests/lib/security/CryptoTest.php | 73 +++++++++++++ tests/lib/security/HasherTest.php | 118 ++++++++++++++++++++ tests/lib/security/SecureRandomTest.php | 78 +++++++++++++ tests/lib/security/TrustedDomainHelperTest.php | 82 ++++++++++++++ tests/lib/security/certificate.php | 109 ------------------- tests/lib/security/certificatemanager.php | 119 -------------------- tests/lib/security/credentialsmanager.php | 102 ----------------- tests/lib/security/crypto.php | 71 ------------ .../csp/ContentSecurityPolicyManagerTest.php | 3 + tests/lib/security/csrf/CsrfTokenGeneratorTest.php | 2 + tests/lib/security/csrf/CsrfTokenManagerTest.php | 2 + tests/lib/security/csrf/CsrfTokenTest.php | 2 + .../csrf/tokenstorage/SessionStorageTest.php | 2 + tests/lib/security/hasher.php | 116 -------------------- tests/lib/security/securerandom.php | 76 ------------- tests/lib/security/trusteddomainhelper.php | 80 -------------- 19 files changed, 698 insertions(+), 673 deletions(-) create mode 100644 tests/lib/security/CertificateManagerTest.php create mode 100644 tests/lib/security/CertificateTest.php create mode 100644 tests/lib/security/CredentialsManagerTest.php create mode 100644 tests/lib/security/CryptoTest.php create mode 100644 tests/lib/security/HasherTest.php create mode 100644 tests/lib/security/SecureRandomTest.php create mode 100644 tests/lib/security/TrustedDomainHelperTest.php delete mode 100644 tests/lib/security/certificate.php delete mode 100644 tests/lib/security/certificatemanager.php delete mode 100644 tests/lib/security/credentialsmanager.php delete mode 100644 tests/lib/security/crypto.php delete mode 100644 tests/lib/security/hasher.php delete mode 100644 tests/lib/security/securerandom.php delete mode 100644 tests/lib/security/trusteddomainhelper.php (limited to 'tests') diff --git a/tests/lib/security/CertificateManagerTest.php b/tests/lib/security/CertificateManagerTest.php new file mode 100644 index 00000000000..43206569cf4 --- /dev/null +++ b/tests/lib/security/CertificateManagerTest.php @@ -0,0 +1,121 @@ + + * This file is licensed under the Affero General Public License version 3 or + * later. + * See the COPYING-README file. + */ + +namespace Test\Security; + +use \OC\Security\CertificateManager; + +/** + * Class CertificateManagerTest + * + * @group DB + */ +class CertificateManagerTest extends \Test\TestCase { + use \Test\Traits\UserTrait; + use \Test\Traits\MountProviderTrait; + + /** @var CertificateManager */ + private $certificateManager; + /** @var String */ + private $username; + + protected function setUp() { + parent::setUp(); + + $this->username = $this->getUniqueID('', 20); + $this->createUser($this->username, ''); + + $storage = new \OC\Files\Storage\Temporary(); + $this->registerMount($this->username, $storage, '/' . $this->username . '/'); + + \OC_Util::tearDownFS(); + \OC_User::setUserId(''); + \OC\Files\Filesystem::tearDown(); + \OC_Util::setupFS($this->username); + + $config = $this->getMock('OCP\IConfig'); + $config->expects($this->any())->method('getSystemValue') + ->with('installed', false)->willReturn(true); + + $this->certificateManager = new CertificateManager($this->username, new \OC\Files\View(), $config); + } + + protected function tearDown() { + $user = \OC::$server->getUserManager()->get($this->username); + if ($user !== null) { + $user->delete(); + } + parent::tearDown(); + } + + protected function assertEqualsArrays($expected, $actual) { + sort($expected); + sort($actual); + + $this->assertEquals($expected, $actual); + } + + function testListCertificates() { + // Test empty certificate bundle + $this->assertSame(array(), $this->certificateManager->listCertificates()); + + // Add some certificates + $this->certificateManager->addCertificate(file_get_contents(__DIR__ . '/../../data/certificates/goodCertificate.crt'), 'GoodCertificate'); + $certificateStore = array(); + $certificateStore[] = new \OC\Security\Certificate(file_get_contents(__DIR__ . '/../../data/certificates/goodCertificate.crt'), 'GoodCertificate'); + $this->assertEqualsArrays($certificateStore, $this->certificateManager->listCertificates()); + + // Add another certificates + $this->certificateManager->addCertificate(file_get_contents(__DIR__ . '/../../data/certificates/expiredCertificate.crt'), 'ExpiredCertificate'); + $certificateStore[] = new \OC\Security\Certificate(file_get_contents(__DIR__ . '/../../data/certificates/expiredCertificate.crt'), 'ExpiredCertificate'); + $this->assertEqualsArrays($certificateStore, $this->certificateManager->listCertificates()); + } + + /** + * @expectedException \Exception + * @expectedExceptionMessage Certificate could not get parsed. + */ + function testAddInvalidCertificate() { + $this->certificateManager->addCertificate('InvalidCertificate', 'invalidCertificate'); + } + + /** + * @return array + */ + public function dangerousFileProvider() { + return [ + ['.htaccess'], + ['../../foo.txt'], + ['..\..\foo.txt'], + ]; + } + + /** + * @expectedException \Exception + * @expectedExceptionMessage Filename is not valid + * @dataProvider dangerousFileProvider + * @param string $filename + */ + function testAddDangerousFile($filename) { + $this->certificateManager->addCertificate(file_get_contents(__DIR__ . '/../../data/certificates/expiredCertificate.crt'), $filename); + } + + function testRemoveDangerousFile() { + $this->assertFalse($this->certificateManager->removeCertificate('../../foo.txt')); + } + + function testRemoveExistingFile() { + $this->certificateManager->addCertificate(file_get_contents(__DIR__ . '/../../data/certificates/goodCertificate.crt'), 'GoodCertificate'); + $this->assertTrue($this->certificateManager->removeCertificate('GoodCertificate')); + } + + function testGetCertificateBundle() { + $this->assertSame('/' . $this->username . '/files_external/rootcerts.crt', $this->certificateManager->getCertificateBundle()); + } + +} diff --git a/tests/lib/security/CertificateTest.php b/tests/lib/security/CertificateTest.php new file mode 100644 index 00000000000..888a4ba1f13 --- /dev/null +++ b/tests/lib/security/CertificateTest.php @@ -0,0 +1,111 @@ + + * + * @copyright Copyright (c) 2015, ownCloud, Inc. + * @license AGPL-3.0 + * + * This code is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License, version 3, + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License, version 3, + * along with this program. If not, see + * + */ + +namespace Test\Security; + +use \OC\Security\Certificate; + +class CertificateTest extends \Test\TestCase { + + /** @var Certificate That contains a valid certificate */ + protected $goodCertificate; + /** @var Certificate That contains an invalid certificate */ + protected $invalidCertificate; + /** @var Certificate That contains an expired certificate */ + protected $expiredCertificate; + + protected function setUp() { + parent::setUp(); + + $goodCertificate = file_get_contents(__DIR__ . '/../../data/certificates/goodCertificate.crt'); + $this->goodCertificate = new Certificate($goodCertificate, 'GoodCertificate'); + $badCertificate = file_get_contents(__DIR__ . '/../../data/certificates/badCertificate.crt'); + $this->invalidCertificate = new Certificate($badCertificate, 'BadCertificate'); + $expiredCertificate = file_get_contents(__DIR__ . '/../../data/certificates/expiredCertificate.crt'); + $this->expiredCertificate = new Certificate($expiredCertificate, 'ExpiredCertificate'); + } + + /** + * @expectedException \Exception + * @expectedExceptionMessage Certificate could not get parsed. + */ + public function testBogusData() { + $certificate = new Certificate('foo', 'bar'); + $certificate->getIssueDate(); + } + + /** + * @expectedException \Exception + * @expectedExceptionMessage Certificate could not get parsed. + */ + function testCertificateStartingWithFileReference() { + new Certificate('file://'.__DIR__ . '/../../data/certificates/goodCertificate.crt', 'bar'); + } + + public function testGetName() { + $this->assertSame('GoodCertificate', $this->goodCertificate->getName()); + $this->assertSame('BadCertificate', $this->invalidCertificate->getName()); + } + + public function testGetCommonName() { + $this->assertSame('security.owncloud.com', $this->goodCertificate->getCommonName()); + $this->assertSame(null, $this->invalidCertificate->getCommonName()); + } + + public function testGetOrganization() { + $this->assertSame('ownCloud Security', $this->goodCertificate->getOrganization()); + $this->assertSame('Internet Widgits Pty Ltd', $this->invalidCertificate->getOrganization()); + } + + public function testGetIssueDate() { + $expected = new DateTime('2015-08-27 20:03:42 GMT'); + $this->assertEquals($expected->getTimestamp(), $this->goodCertificate->getIssueDate()->getTimestamp()); + $expected = new DateTime('2015-08-27 20:19:13 GMT'); + $this->assertEquals($expected->getTimestamp(), $this->invalidCertificate->getIssueDate()->getTimestamp()); + } + + public function testGetExpireDate() { + $expected = new DateTime('2025-08-24 20:03:42 GMT'); + $this->assertEquals($expected->getTimestamp(), $this->goodCertificate->getExpireDate()->getTimestamp()); + $expected = new DateTime('2025-08-24 20:19:13 GMT'); + $this->assertEquals($expected->getTimestamp(), $this->invalidCertificate->getExpireDate()->getTimestamp()); + $expected = new DateTime('2014-08-28 09:12:43 GMT'); + $this->assertEquals($expected->getTimestamp(), $this->expiredCertificate->getExpireDate()->getTimestamp()); + } + + public function testIsExpired() { + $this->assertSame(false, $this->goodCertificate->isExpired()); + $this->assertSame(false, $this->invalidCertificate->isExpired()); + $this->assertSame(true, $this->expiredCertificate->isExpired()); + } + + public function testGetIssuerName() { + $this->assertSame('security.owncloud.com', $this->goodCertificate->getIssuerName()); + $this->assertSame(null, $this->invalidCertificate->getIssuerName()); + $this->assertSame(null, $this->expiredCertificate->getIssuerName()); + } + + public function testGetIssuerOrganization() { + $this->assertSame('ownCloud Security', $this->goodCertificate->getIssuerOrganization()); + $this->assertSame('Internet Widgits Pty Ltd', $this->invalidCertificate->getIssuerOrganization()); + $this->assertSame('Internet Widgits Pty Ltd', $this->expiredCertificate->getIssuerOrganization()); + } +} diff --git a/tests/lib/security/CredentialsManagerTest.php b/tests/lib/security/CredentialsManagerTest.php new file mode 100644 index 00000000000..7eb4e4d7b1a --- /dev/null +++ b/tests/lib/security/CredentialsManagerTest.php @@ -0,0 +1,104 @@ + + * + * @copyright Copyright (c) 2015, ownCloud, Inc. + * @license AGPL-3.0 + * + * This code is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License, version 3, + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License, version 3, + * along with this program. If not, see + * + */ + +namespace Test\Security; + +use \OCP\Security\ICrypto; +use \OCP\IDBConnection; +use \OC\Security\CredentialsManager; + +class CredentialsManagerTest extends \Test\TestCase { + + /** @var ICrypto */ + protected $crypto; + + /** @var IDBConnection */ + protected $dbConnection; + + /** @var CredentialsManager */ + protected $manager; + + protected function setUp() { + parent::setUp(); + $this->crypto = $this->getMock('\OCP\Security\ICrypto'); + $this->dbConnection = $this->getMockBuilder('\OC\DB\Connection') + ->disableOriginalConstructor() + ->getMock(); + $this->manager = new CredentialsManager($this->crypto, $this->dbConnection); + } + + private function getQeuryResult($row) { + $result = $this->getMockBuilder('\Doctrine\DBAL\Driver\Statement') + ->disableOriginalConstructor() + ->getMock(); + + $result->expects($this->any()) + ->method('fetch') + ->will($this->returnValue($row)); + + return $result; + } + + public function testStore() { + $userId = 'abc'; + $identifier = 'foo'; + $credentials = 'bar'; + + $this->crypto->expects($this->once()) + ->method('encrypt') + ->with(json_encode($credentials)) + ->willReturn('baz'); + + $this->dbConnection->expects($this->once()) + ->method('setValues') + ->with(CredentialsManager::DB_TABLE, + ['user' => $userId, 'identifier' => $identifier], + ['credentials' => 'baz'] + ); + + $this->manager->store($userId, $identifier, $credentials); + } + + public function testRetrieve() { + $userId = 'abc'; + $identifier = 'foo'; + + $this->crypto->expects($this->once()) + ->method('decrypt') + ->with('baz') + ->willReturn(json_encode('bar')); + + $qb = $this->getMockBuilder('\OC\DB\QueryBuilder\QueryBuilder') + ->setConstructorArgs([$this->dbConnection]) + ->setMethods(['execute']) + ->getMock(); + $qb->expects($this->once()) + ->method('execute') + ->willReturn($this->getQeuryResult(['credentials' => 'baz'])); + + $this->dbConnection->expects($this->once()) + ->method('getQueryBuilder') + ->willReturn($qb); + + $this->manager->retrieve($userId, $identifier); + } + +} diff --git a/tests/lib/security/CryptoTest.php b/tests/lib/security/CryptoTest.php new file mode 100644 index 00000000000..356d504f4b3 --- /dev/null +++ b/tests/lib/security/CryptoTest.php @@ -0,0 +1,73 @@ + + * This file is licensed under the Affero General Public License version 3 or + * later. + * See the COPYING-README file. + */ + +namespace Test\Security; + +use \OC\Security\Crypto; + +class CryptoTest extends \Test\TestCase { + + public function defaultEncryptionProvider() + { + return array( + array('Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt.'), + array(''), + array('我看这本书。 我看這本書') + ); + } + + /** @var Crypto */ + protected $crypto; + + protected function setUp() { + parent::setUp(); + $this->crypto = new Crypto(\OC::$server->getConfig(), \OC::$server->getSecureRandom()); + } + + /** + * @dataProvider defaultEncryptionProvider + */ + function testDefaultEncrypt($stringToEncrypt) { + $ciphertext = $this->crypto->encrypt($stringToEncrypt); + $this->assertEquals($stringToEncrypt, $this->crypto->decrypt($ciphertext)); + } + + /** + * @expectedException \Exception + * @expectedExceptionMessage HMAC does not match. + */ + function testWrongPassword() { + $stringToEncrypt = 'Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt.'; + $ciphertext = $this->crypto->encrypt($stringToEncrypt); + $this->crypto->decrypt($ciphertext, 'A wrong password!'); + } + + function testLaterDecryption() { + $stringToEncrypt = 'Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt.'; + $encryptedString = '44a35023cca2e7a6125e06c29fc4b2ad9d8a33d0873a8b45b0de4ef9284f260c6c46bf25dc62120644c59b8bafe4281ddc47a70c35ae6c29ef7a63d79eefacc297e60b13042ac582733598d0a6b4de37311556bb5c480fd2633de4e6ebafa868c2d1e2d80a5d24f9660360dba4d6e0c8|lhrFgK0zd9U160Wo|a75e57ab701f9124e1113543fd1dc596f21e20d456a0d1e813d5a8aaec9adcb11213788e96598b67fe9486a9f0b99642c18296d0175db44b1ae426e4e91080ee'; + $this->assertEquals($stringToEncrypt, $this->crypto->decrypt($encryptedString, 'ThisIsAVeryS3cur3P4ssw0rd')); + } + + /** + * @expectedException \Exception + * @expectedExceptionMessage HMAC does not match. + */ + function testWrongIV() { + $encryptedString = '560f5436ba864b9f12f7f7ca6d41c327554a6f2c0a160a03316b202af07c65163274993f3a46e7547c07ba89304f00594a2f3bd99f83859097c58049c39d0d4ade10e0de914ff0604961e7c849d0271ed6c0b23f984ba16e7d033e3305fb0910e7b6a2a65c988d17dbee71d8f953684d|d2kdFUspVjC0o0sr|1a5feacf87eaa6869a6abdfba9a296e7bbad45b6ad89f7dce67cdc98e2da5dc4379cc672cc655e52bbf19599bf59482fbea13a73937697fa656bf10f3fc4f1aa'; + $this->crypto->decrypt($encryptedString, 'ThisIsAVeryS3cur3P4ssw0rd'); + } + + /** + * @expectedException \Exception + * @expectedExceptionMessage Authenticated ciphertext could not be decoded. + */ + function testWrongParameters() { + $encryptedString = '1|2'; + $this->crypto->decrypt($encryptedString, 'ThisIsAVeryS3cur3P4ssw0rd'); + } +} diff --git a/tests/lib/security/HasherTest.php b/tests/lib/security/HasherTest.php new file mode 100644 index 00000000000..913f4d703e8 --- /dev/null +++ b/tests/lib/security/HasherTest.php @@ -0,0 +1,118 @@ + + * This file is licensed under the Affero General Public License version 3 or + * later. + * See the COPYING-README file. + */ + +namespace Test\Security; + +use OC\Security\Hasher; + +/** + * Class HasherTest + */ +class HasherTest extends \Test\TestCase { + + /** + * @return array + */ + public function versionHashProvider() + { + return array( + array('asf32äà$$a.|3', null), + array('asf32äà$$a.|3|5', null), + array('1|2|3|4', array('version' => 1, 'hash' => '2|3|4')), + array('1|我看|这本书。 我看這本書', array('version' => 1, 'hash' => '我看|这本书。 我看這本書')) + ); + } + + /** + * @return array + */ + public function allHashProviders() + { + return array( + // Bogus values + array(null, 'asf32äà$$a.|3', false), + array(null, false, false), + + // Valid SHA1 strings + array('password', '5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8', true), + array('owncloud.com', '27a4643e43046c3569e33b68c1a4b15d31306d29', true), + + // Invalid SHA1 strings + array('InvalidString', '5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8', false), + array('AnotherInvalidOne', '27a4643e43046c3569e33b68c1a4b15d31306d29', false), + + // Valid legacy password string with password salt "6Wow67q1wZQZpUUeI6G2LsWUu4XKx" + array('password', '$2a$08$emCpDEl.V.QwPWt5gPrqrOhdpH6ailBmkj2Hd2vD5U8qIy20HBe7.', true), + array('password', '$2a$08$yjaLO4ev70SaOsWZ9gRS3eRSEpHVsmSWTdTms1949mylxJ279hzo2', true), + array('password', '$2a$08$.jNRG/oB4r7gHJhAyb.mDupNUAqTnBIW/tWBqFobaYflKXiFeG0A6', true), + array('owncloud.com', '$2a$08$YbEsyASX/hXVNMv8hXQo7ezreN17T8Jl6PjecGZvpX.Ayz2aUyaZ2', true), + array('owncloud.com', '$2a$11$cHdDA2IkUP28oNGBwlL7jO/U3dpr8/0LIjTZmE8dMPA7OCUQsSTqS', true), + array('owncloud.com', '$2a$08$GH.UoIfJ1e.qeZ85KPqzQe6NR8XWRgJXWIUeE1o/j1xndvyTA1x96', true), + + // Invalid legacy passwords + array('password', '$2a$08$oKAQY5IhnZocP.61MwP7xu7TNeOb7Ostvk3j6UpacvaNMs.xRj7O2', false), + + // Valid passwords "6Wow67q1wZQZpUUeI6G2LsWUu4XKx" + array('password', '1|$2a$05$ezAE0dkwk57jlfo6z5Pql.gcIK3ReXT15W7ITNxVS0ksfhO/4E4Kq', true), + array('password', '1|$2a$05$4OQmloFW4yTVez2MEWGIleDO9Z5G9tWBXxn1vddogmKBQq/Mq93pe', true), + array('password', '1|$2a$11$yj0hlp6qR32G9exGEXktB.yW2rgt2maRBbPgi3EyxcDwKrD14x/WO', true), + array('owncloud.com', '1|$2a$10$Yiss2WVOqGakxuuqySv5UeOKpF8d8KmNjuAPcBMiRJGizJXjA2bKm', true), + array('owncloud.com', '1|$2a$10$v9mh8/.mF/Ut9jZ7pRnpkuac3bdFCnc4W/gSumheQUi02Sr.xMjPi', true), + array('owncloud.com', '1|$2a$05$ST5E.rplNRfDCzRpzq69leRzsTGtY7k88h9Vy2eWj0Ug/iA9w5kGK', true), + + // Invalid passwords + array('password', '0|$2a$08$oKAQY5IhnZocP.61MwP7xu7TNeOb7Ostvk3j6UpacvaNMs.xRj7O2', false), + array('password', '1|$2a$08$oKAQY5IhnZocP.61MwP7xu7TNeOb7Ostvk3j6UpacvaNMs.xRj7O2', false), + array('password', '2|$2a$08$oKAQY5IhnZocP.61MwP7xu7TNeOb7Ostvk3j6UpacvaNMs.xRj7O2', false), + ); + } + + /** @var Hasher */ + protected $hasher; + + /** @var \OCP\IConfig */ + protected $config; + + protected function setUp() { + parent::setUp(); + + $this->config = $this->getMockBuilder('\OCP\IConfig') + ->disableOriginalConstructor()->getMock(); + + $this->hasher = new Hasher($this->config); + } + + function testHash() { + $hash = $this->hasher->hash('String To Hash'); + $this->assertNotNull($hash); + } + + /** + * @dataProvider versionHashProvider + */ + function testSplitHash($hash, $expected) { + $relativePath = self::invokePrivate($this->hasher, 'splitHash', array($hash)); + $this->assertSame($expected, $relativePath); + } + + + /** + * @dataProvider allHashProviders + */ + function testVerify($password, $hash, $expected) { + $this->config + ->expects($this->any()) + ->method('getSystemValue') + ->with('passwordsalt', null) + ->will($this->returnValue('6Wow67q1wZQZpUUeI6G2LsWUu4XKx')); + + $result = $this->hasher->verify($password, $hash); + $this->assertSame($expected, $result); + } + +} diff --git a/tests/lib/security/SecureRandomTest.php b/tests/lib/security/SecureRandomTest.php new file mode 100644 index 00000000000..40431c89795 --- /dev/null +++ b/tests/lib/security/SecureRandomTest.php @@ -0,0 +1,78 @@ + + * This file is licensed under the Affero General Public License version 3 or + * later. + * See the COPYING-README file. + */ + +namespace Test\Security; + +use \OC\Security\SecureRandom; + +class SecureRandomTest extends \Test\TestCase { + + public function stringGenerationProvider() { + return array( + array(0, 0), + array(1, 1), + array(128, 128), + array(256, 256), + array(1024, 1024), + array(2048, 2048), + array(64000, 64000), + ); + } + + public static function charCombinations() { + return array( + array('CHAR_LOWER', '[a-z]'), + array('CHAR_UPPER', '[A-Z]'), + array('CHAR_DIGITS', '[0-9]'), + ); + } + + /** @var SecureRandom */ + protected $rng; + + protected function setUp() { + parent::setUp(); + $this->rng = new \OC\Security\SecureRandom(); + } + + /** + * @dataProvider stringGenerationProvider + */ + function testGetLowStrengthGeneratorLength($length, $expectedLength) { + $generator = $this->rng; + + $this->assertEquals($expectedLength, strlen($generator->generate($length))); + } + + /** + * @dataProvider stringGenerationProvider + */ + function testMediumLowStrengthGeneratorLength($length, $expectedLength) { + $generator = $this->rng; + + $this->assertEquals($expectedLength, strlen($generator->generate($length))); + } + + /** + * @dataProvider stringGenerationProvider + */ + function testUninitializedGenerate($length, $expectedLength) { + $this->assertEquals($expectedLength, strlen($this->rng->generate($length))); + } + + /** + * @dataProvider charCombinations + */ + public function testScheme($charName, $chars) { + $generator = $this->rng; + $scheme = constant('OCP\Security\ISecureRandom::' . $charName); + $randomString = $generator->generate(100, $scheme); + $matchesRegex = preg_match('/^'.$chars.'+$/', $randomString); + $this->assertSame(1, $matchesRegex); + } +} diff --git a/tests/lib/security/TrustedDomainHelperTest.php b/tests/lib/security/TrustedDomainHelperTest.php new file mode 100644 index 00000000000..dfd51167cca --- /dev/null +++ b/tests/lib/security/TrustedDomainHelperTest.php @@ -0,0 +1,82 @@ + + * This file is licensed under the Affero General Public License version 3 or + * later. + * See the COPYING-README file. + */ + +namespace Test\Security; + +use \OC\Security\TrustedDomainHelper; +use OCP\IConfig; + +/** + * Class TrustedDomainHelperTest + */ +class TrustedDomainHelperTest extends \Test\TestCase { + /** @var IConfig */ + protected $config; + + protected function setUp() { + parent::setUp(); + + $this->config = $this->getMockBuilder('\OCP\IConfig')->getMock(); + } + + /** + * @dataProvider trustedDomainDataProvider + * @param string $trustedDomains + * @param string $testDomain + * @param bool $result + */ + public function testIsTrustedDomain($trustedDomains, $testDomain, $result) { + $this->config->expects($this->once()) + ->method('getSystemValue') + ->with('trusted_domains') + ->will($this->returnValue($trustedDomains)); + + $trustedDomainHelper = new TrustedDomainHelper($this->config); + $this->assertEquals($result, $trustedDomainHelper->isTrustedDomain($testDomain)); + } + + /** + * @return array + */ + public function trustedDomainDataProvider() { + $trustedHostTestList = [ + 'host.one.test', + 'host.two.test', + '[1fff:0:a88:85a3::ac1f]', + 'host.three.test:443', + ]; + return [ + // empty defaults to false with 8.1 + [null, 'host.one.test:8080', false], + ['', 'host.one.test:8080', false], + [[], 'host.one.test:8080', false], + // trust list when defined + [$trustedHostTestList, 'host.two.test:8080', true], + [$trustedHostTestList, 'host.two.test:9999', true], + [$trustedHostTestList, 'host.three.test:8080', false], + [$trustedHostTestList, 'host.two.test:8080:aa:222', false], + [$trustedHostTestList, '[1fff:0:a88:85a3::ac1f]', true], + [$trustedHostTestList, '[1fff:0:a88:85a3::ac1f]:801', true], + [$trustedHostTestList, '[1fff:0:a88:85a3::ac1f]:801:34', false], + [$trustedHostTestList, 'host.three.test:443', true], + [$trustedHostTestList, 'host.three.test:80', false], + [$trustedHostTestList, 'host.three.test', false], + // trust localhost regardless of trust list + [$trustedHostTestList, 'localhost', true], + [$trustedHostTestList, 'localhost:8080', true], + [$trustedHostTestList, '127.0.0.1', true], + [$trustedHostTestList, '127.0.0.1:8080', true], + // do not trust invalid localhosts + [$trustedHostTestList, 'localhost:1:2', false], + [$trustedHostTestList, 'localhost: evil.host', false], + // do not trust casting + [[1], '1', false], + ]; + } + +} diff --git a/tests/lib/security/certificate.php b/tests/lib/security/certificate.php deleted file mode 100644 index 82e91c71733..00000000000 --- a/tests/lib/security/certificate.php +++ /dev/null @@ -1,109 +0,0 @@ - - * - * @copyright Copyright (c) 2015, ownCloud, Inc. - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see - * - */ - -use \OC\Security\Certificate; - -class CertificateTest extends \Test\TestCase { - - /** @var Certificate That contains a valid certificate */ - protected $goodCertificate; - /** @var Certificate That contains an invalid certificate */ - protected $invalidCertificate; - /** @var Certificate That contains an expired certificate */ - protected $expiredCertificate; - - protected function setUp() { - parent::setUp(); - - $goodCertificate = file_get_contents(__DIR__ . '/../../data/certificates/goodCertificate.crt'); - $this->goodCertificate = new Certificate($goodCertificate, 'GoodCertificate'); - $badCertificate = file_get_contents(__DIR__ . '/../../data/certificates/badCertificate.crt'); - $this->invalidCertificate = new Certificate($badCertificate, 'BadCertificate'); - $expiredCertificate = file_get_contents(__DIR__ . '/../../data/certificates/expiredCertificate.crt'); - $this->expiredCertificate = new Certificate($expiredCertificate, 'ExpiredCertificate'); - } - - /** - * @expectedException \Exception - * @expectedExceptionMessage Certificate could not get parsed. - */ - public function testBogusData() { - $certificate = new Certificate('foo', 'bar'); - $certificate->getIssueDate(); - } - - /** - * @expectedException \Exception - * @expectedExceptionMessage Certificate could not get parsed. - */ - function testCertificateStartingWithFileReference() { - new Certificate('file://'.__DIR__ . '/../../data/certificates/goodCertificate.crt', 'bar'); - } - - public function testGetName() { - $this->assertSame('GoodCertificate', $this->goodCertificate->getName()); - $this->assertSame('BadCertificate', $this->invalidCertificate->getName()); - } - - public function testGetCommonName() { - $this->assertSame('security.owncloud.com', $this->goodCertificate->getCommonName()); - $this->assertSame(null, $this->invalidCertificate->getCommonName()); - } - - public function testGetOrganization() { - $this->assertSame('ownCloud Security', $this->goodCertificate->getOrganization()); - $this->assertSame('Internet Widgits Pty Ltd', $this->invalidCertificate->getOrganization()); - } - - public function testGetIssueDate() { - $expected = new DateTime('2015-08-27 20:03:42 GMT'); - $this->assertEquals($expected->getTimestamp(), $this->goodCertificate->getIssueDate()->getTimestamp()); - $expected = new DateTime('2015-08-27 20:19:13 GMT'); - $this->assertEquals($expected->getTimestamp(), $this->invalidCertificate->getIssueDate()->getTimestamp()); - } - - public function testGetExpireDate() { - $expected = new DateTime('2025-08-24 20:03:42 GMT'); - $this->assertEquals($expected->getTimestamp(), $this->goodCertificate->getExpireDate()->getTimestamp()); - $expected = new DateTime('2025-08-24 20:19:13 GMT'); - $this->assertEquals($expected->getTimestamp(), $this->invalidCertificate->getExpireDate()->getTimestamp()); - $expected = new DateTime('2014-08-28 09:12:43 GMT'); - $this->assertEquals($expected->getTimestamp(), $this->expiredCertificate->getExpireDate()->getTimestamp()); - } - - public function testIsExpired() { - $this->assertSame(false, $this->goodCertificate->isExpired()); - $this->assertSame(false, $this->invalidCertificate->isExpired()); - $this->assertSame(true, $this->expiredCertificate->isExpired()); - } - - public function testGetIssuerName() { - $this->assertSame('security.owncloud.com', $this->goodCertificate->getIssuerName()); - $this->assertSame(null, $this->invalidCertificate->getIssuerName()); - $this->assertSame(null, $this->expiredCertificate->getIssuerName()); - } - - public function testGetIssuerOrganization() { - $this->assertSame('ownCloud Security', $this->goodCertificate->getIssuerOrganization()); - $this->assertSame('Internet Widgits Pty Ltd', $this->invalidCertificate->getIssuerOrganization()); - $this->assertSame('Internet Widgits Pty Ltd', $this->expiredCertificate->getIssuerOrganization()); - } -} diff --git a/tests/lib/security/certificatemanager.php b/tests/lib/security/certificatemanager.php deleted file mode 100644 index e9ccea39efe..00000000000 --- a/tests/lib/security/certificatemanager.php +++ /dev/null @@ -1,119 +0,0 @@ - - * This file is licensed under the Affero General Public License version 3 or - * later. - * See the COPYING-README file. - */ - -use \OC\Security\CertificateManager; - -/** - * Class CertificateManagerTest - * - * @group DB - */ -class CertificateManagerTest extends \Test\TestCase { - use \Test\Traits\UserTrait; - use \Test\Traits\MountProviderTrait; - - /** @var CertificateManager */ - private $certificateManager; - /** @var String */ - private $username; - - protected function setUp() { - parent::setUp(); - - $this->username = $this->getUniqueID('', 20); - $this->createUser($this->username, ''); - - $storage = new \OC\Files\Storage\Temporary(); - $this->registerMount($this->username, $storage, '/' . $this->username . '/'); - - \OC_Util::tearDownFS(); - \OC_User::setUserId(''); - \OC\Files\Filesystem::tearDown(); - \OC_Util::setupFS($this->username); - - $config = $this->getMock('OCP\IConfig'); - $config->expects($this->any())->method('getSystemValue') - ->with('installed', false)->willReturn(true); - - $this->certificateManager = new CertificateManager($this->username, new \OC\Files\View(), $config); - } - - protected function tearDown() { - $user = \OC::$server->getUserManager()->get($this->username); - if ($user !== null) { - $user->delete(); - } - parent::tearDown(); - } - - protected function assertEqualsArrays($expected, $actual) { - sort($expected); - sort($actual); - - $this->assertEquals($expected, $actual); - } - - function testListCertificates() { - // Test empty certificate bundle - $this->assertSame(array(), $this->certificateManager->listCertificates()); - - // Add some certificates - $this->certificateManager->addCertificate(file_get_contents(__DIR__ . '/../../data/certificates/goodCertificate.crt'), 'GoodCertificate'); - $certificateStore = array(); - $certificateStore[] = new \OC\Security\Certificate(file_get_contents(__DIR__ . '/../../data/certificates/goodCertificate.crt'), 'GoodCertificate'); - $this->assertEqualsArrays($certificateStore, $this->certificateManager->listCertificates()); - - // Add another certificates - $this->certificateManager->addCertificate(file_get_contents(__DIR__ . '/../../data/certificates/expiredCertificate.crt'), 'ExpiredCertificate'); - $certificateStore[] = new \OC\Security\Certificate(file_get_contents(__DIR__ . '/../../data/certificates/expiredCertificate.crt'), 'ExpiredCertificate'); - $this->assertEqualsArrays($certificateStore, $this->certificateManager->listCertificates()); - } - - /** - * @expectedException \Exception - * @expectedExceptionMessage Certificate could not get parsed. - */ - function testAddInvalidCertificate() { - $this->certificateManager->addCertificate('InvalidCertificate', 'invalidCertificate'); - } - - /** - * @return array - */ - public function dangerousFileProvider() { - return [ - ['.htaccess'], - ['../../foo.txt'], - ['..\..\foo.txt'], - ]; - } - - /** - * @expectedException \Exception - * @expectedExceptionMessage Filename is not valid - * @dataProvider dangerousFileProvider - * @param string $filename - */ - function testAddDangerousFile($filename) { - $this->certificateManager->addCertificate(file_get_contents(__DIR__ . '/../../data/certificates/expiredCertificate.crt'), $filename); - } - - function testRemoveDangerousFile() { - $this->assertFalse($this->certificateManager->removeCertificate('../../foo.txt')); - } - - function testRemoveExistingFile() { - $this->certificateManager->addCertificate(file_get_contents(__DIR__ . '/../../data/certificates/goodCertificate.crt'), 'GoodCertificate'); - $this->assertTrue($this->certificateManager->removeCertificate('GoodCertificate')); - } - - function testGetCertificateBundle() { - $this->assertSame('/' . $this->username . '/files_external/rootcerts.crt', $this->certificateManager->getCertificateBundle()); - } - -} diff --git a/tests/lib/security/credentialsmanager.php b/tests/lib/security/credentialsmanager.php deleted file mode 100644 index 72f061e05bb..00000000000 --- a/tests/lib/security/credentialsmanager.php +++ /dev/null @@ -1,102 +0,0 @@ - - * - * @copyright Copyright (c) 2015, ownCloud, Inc. - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see - * - */ - -use \OCP\Security\ICrypto; -use \OCP\IDBConnection; -use \OC\Security\CredentialsManager; - -class CredentialsManagerTest extends \Test\TestCase { - - /** @var ICrypto */ - protected $crypto; - - /** @var IDBConnection */ - protected $dbConnection; - - /** @var CredentialsManager */ - protected $manager; - - protected function setUp() { - parent::setUp(); - $this->crypto = $this->getMock('\OCP\Security\ICrypto'); - $this->dbConnection = $this->getMockBuilder('\OC\DB\Connection') - ->disableOriginalConstructor() - ->getMock(); - $this->manager = new CredentialsManager($this->crypto, $this->dbConnection); - } - - private function getQeuryResult($row) { - $result = $this->getMockBuilder('\Doctrine\DBAL\Driver\Statement') - ->disableOriginalConstructor() - ->getMock(); - - $result->expects($this->any()) - ->method('fetch') - ->will($this->returnValue($row)); - - return $result; - } - - public function testStore() { - $userId = 'abc'; - $identifier = 'foo'; - $credentials = 'bar'; - - $this->crypto->expects($this->once()) - ->method('encrypt') - ->with(json_encode($credentials)) - ->willReturn('baz'); - - $this->dbConnection->expects($this->once()) - ->method('setValues') - ->with(CredentialsManager::DB_TABLE, - ['user' => $userId, 'identifier' => $identifier], - ['credentials' => 'baz'] - ); - - $this->manager->store($userId, $identifier, $credentials); - } - - public function testRetrieve() { - $userId = 'abc'; - $identifier = 'foo'; - - $this->crypto->expects($this->once()) - ->method('decrypt') - ->with('baz') - ->willReturn(json_encode('bar')); - - $qb = $this->getMockBuilder('\OC\DB\QueryBuilder\QueryBuilder') - ->setConstructorArgs([$this->dbConnection]) - ->setMethods(['execute']) - ->getMock(); - $qb->expects($this->once()) - ->method('execute') - ->willReturn($this->getQeuryResult(['credentials' => 'baz'])); - - $this->dbConnection->expects($this->once()) - ->method('getQueryBuilder') - ->willReturn($qb); - - $this->manager->retrieve($userId, $identifier); - } - -} diff --git a/tests/lib/security/crypto.php b/tests/lib/security/crypto.php deleted file mode 100644 index 1571cf89248..00000000000 --- a/tests/lib/security/crypto.php +++ /dev/null @@ -1,71 +0,0 @@ - - * This file is licensed under the Affero General Public License version 3 or - * later. - * See the COPYING-README file. - */ - -use \OC\Security\Crypto; - -class CryptoTest extends \Test\TestCase { - - public function defaultEncryptionProvider() - { - return array( - array('Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt.'), - array(''), - array('我看这本书。 我看這本書') - ); - } - - /** @var Crypto */ - protected $crypto; - - protected function setUp() { - parent::setUp(); - $this->crypto = new Crypto(\OC::$server->getConfig(), \OC::$server->getSecureRandom()); - } - - /** - * @dataProvider defaultEncryptionProvider - */ - function testDefaultEncrypt($stringToEncrypt) { - $ciphertext = $this->crypto->encrypt($stringToEncrypt); - $this->assertEquals($stringToEncrypt, $this->crypto->decrypt($ciphertext)); - } - - /** - * @expectedException \Exception - * @expectedExceptionMessage HMAC does not match. - */ - function testWrongPassword() { - $stringToEncrypt = 'Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt.'; - $ciphertext = $this->crypto->encrypt($stringToEncrypt); - $this->crypto->decrypt($ciphertext, 'A wrong password!'); - } - - function testLaterDecryption() { - $stringToEncrypt = 'Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt.'; - $encryptedString = '44a35023cca2e7a6125e06c29fc4b2ad9d8a33d0873a8b45b0de4ef9284f260c6c46bf25dc62120644c59b8bafe4281ddc47a70c35ae6c29ef7a63d79eefacc297e60b13042ac582733598d0a6b4de37311556bb5c480fd2633de4e6ebafa868c2d1e2d80a5d24f9660360dba4d6e0c8|lhrFgK0zd9U160Wo|a75e57ab701f9124e1113543fd1dc596f21e20d456a0d1e813d5a8aaec9adcb11213788e96598b67fe9486a9f0b99642c18296d0175db44b1ae426e4e91080ee'; - $this->assertEquals($stringToEncrypt, $this->crypto->decrypt($encryptedString, 'ThisIsAVeryS3cur3P4ssw0rd')); - } - - /** - * @expectedException \Exception - * @expectedExceptionMessage HMAC does not match. - */ - function testWrongIV() { - $encryptedString = '560f5436ba864b9f12f7f7ca6d41c327554a6f2c0a160a03316b202af07c65163274993f3a46e7547c07ba89304f00594a2f3bd99f83859097c58049c39d0d4ade10e0de914ff0604961e7c849d0271ed6c0b23f984ba16e7d033e3305fb0910e7b6a2a65c988d17dbee71d8f953684d|d2kdFUspVjC0o0sr|1a5feacf87eaa6869a6abdfba9a296e7bbad45b6ad89f7dce67cdc98e2da5dc4379cc672cc655e52bbf19599bf59482fbea13a73937697fa656bf10f3fc4f1aa'; - $this->crypto->decrypt($encryptedString, 'ThisIsAVeryS3cur3P4ssw0rd'); - } - - /** - * @expectedException \Exception - * @expectedExceptionMessage Authenticated ciphertext could not be decoded. - */ - function testWrongParameters() { - $encryptedString = '1|2'; - $this->crypto->decrypt($encryptedString, 'ThisIsAVeryS3cur3P4ssw0rd'); - } -} diff --git a/tests/lib/security/csp/ContentSecurityPolicyManagerTest.php b/tests/lib/security/csp/ContentSecurityPolicyManagerTest.php index 975c35d3780..d463e7c648c 100644 --- a/tests/lib/security/csp/ContentSecurityPolicyManagerTest.php +++ b/tests/lib/security/csp/ContentSecurityPolicyManagerTest.php @@ -19,6 +19,9 @@ * */ +namespace Test\Security\CSP; + + use OC\Security\CSP\ContentSecurityPolicyManager; class ContentSecurityPolicyManagerTest extends \Test\TestCase { diff --git a/tests/lib/security/csrf/CsrfTokenGeneratorTest.php b/tests/lib/security/csrf/CsrfTokenGeneratorTest.php index be7434f514f..28b85c3951f 100644 --- a/tests/lib/security/csrf/CsrfTokenGeneratorTest.php +++ b/tests/lib/security/csrf/CsrfTokenGeneratorTest.php @@ -19,6 +19,8 @@ * */ +namespace Test\Security\CSRF; + class CsrfTokenGeneratorTest extends \Test\TestCase { /** @var \OCP\Security\ISecureRandom */ private $random; diff --git a/tests/lib/security/csrf/CsrfTokenManagerTest.php b/tests/lib/security/csrf/CsrfTokenManagerTest.php index 145fc03c51e..ab19a43e91e 100644 --- a/tests/lib/security/csrf/CsrfTokenManagerTest.php +++ b/tests/lib/security/csrf/CsrfTokenManagerTest.php @@ -19,6 +19,8 @@ * */ +namespace Test\Security\CSRF; + class CsrfTokenManagerTest extends \Test\TestCase { /** @var \OC\Security\CSRF\CsrfTokenManager */ private $csrfTokenManager; diff --git a/tests/lib/security/csrf/CsrfTokenTest.php b/tests/lib/security/csrf/CsrfTokenTest.php index 62e6ad112e7..da640ce5052 100644 --- a/tests/lib/security/csrf/CsrfTokenTest.php +++ b/tests/lib/security/csrf/CsrfTokenTest.php @@ -19,6 +19,8 @@ * */ +namespace Test\Security\CSRF; + class CsrfTokenTest extends \Test\TestCase { public function testGetEncryptedValue() { $csrfToken = new \OC\Security\CSRF\CsrfToken('MyCsrfToken'); diff --git a/tests/lib/security/csrf/tokenstorage/SessionStorageTest.php b/tests/lib/security/csrf/tokenstorage/SessionStorageTest.php index 3a83f6a8c00..550fa49e1b2 100644 --- a/tests/lib/security/csrf/tokenstorage/SessionStorageTest.php +++ b/tests/lib/security/csrf/tokenstorage/SessionStorageTest.php @@ -19,6 +19,8 @@ * */ +namespace Test\Security\CSRF\TokenStorage; + class SessionStorageTest extends \Test\TestCase { /** @var \OCP\ISession */ private $session; diff --git a/tests/lib/security/hasher.php b/tests/lib/security/hasher.php deleted file mode 100644 index a6f7df5b79f..00000000000 --- a/tests/lib/security/hasher.php +++ /dev/null @@ -1,116 +0,0 @@ - - * This file is licensed under the Affero General Public License version 3 or - * later. - * See the COPYING-README file. - */ - -use OC\Security\Hasher; - -/** - * Class HasherTest - */ -class HasherTest extends \Test\TestCase { - - /** - * @return array - */ - public function versionHashProvider() - { - return array( - array('asf32äà$$a.|3', null), - array('asf32äà$$a.|3|5', null), - array('1|2|3|4', array('version' => 1, 'hash' => '2|3|4')), - array('1|我看|这本书。 我看這本書', array('version' => 1, 'hash' => '我看|这本书。 我看這本書')) - ); - } - - /** - * @return array - */ - public function allHashProviders() - { - return array( - // Bogus values - array(null, 'asf32äà$$a.|3', false), - array(null, false, false), - - // Valid SHA1 strings - array('password', '5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8', true), - array('owncloud.com', '27a4643e43046c3569e33b68c1a4b15d31306d29', true), - - // Invalid SHA1 strings - array('InvalidString', '5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8', false), - array('AnotherInvalidOne', '27a4643e43046c3569e33b68c1a4b15d31306d29', false), - - // Valid legacy password string with password salt "6Wow67q1wZQZpUUeI6G2LsWUu4XKx" - array('password', '$2a$08$emCpDEl.V.QwPWt5gPrqrOhdpH6ailBmkj2Hd2vD5U8qIy20HBe7.', true), - array('password', '$2a$08$yjaLO4ev70SaOsWZ9gRS3eRSEpHVsmSWTdTms1949mylxJ279hzo2', true), - array('password', '$2a$08$.jNRG/oB4r7gHJhAyb.mDupNUAqTnBIW/tWBqFobaYflKXiFeG0A6', true), - array('owncloud.com', '$2a$08$YbEsyASX/hXVNMv8hXQo7ezreN17T8Jl6PjecGZvpX.Ayz2aUyaZ2', true), - array('owncloud.com', '$2a$11$cHdDA2IkUP28oNGBwlL7jO/U3dpr8/0LIjTZmE8dMPA7OCUQsSTqS', true), - array('owncloud.com', '$2a$08$GH.UoIfJ1e.qeZ85KPqzQe6NR8XWRgJXWIUeE1o/j1xndvyTA1x96', true), - - // Invalid legacy passwords - array('password', '$2a$08$oKAQY5IhnZocP.61MwP7xu7TNeOb7Ostvk3j6UpacvaNMs.xRj7O2', false), - - // Valid passwords "6Wow67q1wZQZpUUeI6G2LsWUu4XKx" - array('password', '1|$2a$05$ezAE0dkwk57jlfo6z5Pql.gcIK3ReXT15W7ITNxVS0ksfhO/4E4Kq', true), - array('password', '1|$2a$05$4OQmloFW4yTVez2MEWGIleDO9Z5G9tWBXxn1vddogmKBQq/Mq93pe', true), - array('password', '1|$2a$11$yj0hlp6qR32G9exGEXktB.yW2rgt2maRBbPgi3EyxcDwKrD14x/WO', true), - array('owncloud.com', '1|$2a$10$Yiss2WVOqGakxuuqySv5UeOKpF8d8KmNjuAPcBMiRJGizJXjA2bKm', true), - array('owncloud.com', '1|$2a$10$v9mh8/.mF/Ut9jZ7pRnpkuac3bdFCnc4W/gSumheQUi02Sr.xMjPi', true), - array('owncloud.com', '1|$2a$05$ST5E.rplNRfDCzRpzq69leRzsTGtY7k88h9Vy2eWj0Ug/iA9w5kGK', true), - - // Invalid passwords - array('password', '0|$2a$08$oKAQY5IhnZocP.61MwP7xu7TNeOb7Ostvk3j6UpacvaNMs.xRj7O2', false), - array('password', '1|$2a$08$oKAQY5IhnZocP.61MwP7xu7TNeOb7Ostvk3j6UpacvaNMs.xRj7O2', false), - array('password', '2|$2a$08$oKAQY5IhnZocP.61MwP7xu7TNeOb7Ostvk3j6UpacvaNMs.xRj7O2', false), - ); - } - - /** @var Hasher */ - protected $hasher; - - /** @var \OCP\IConfig */ - protected $config; - - protected function setUp() { - parent::setUp(); - - $this->config = $this->getMockBuilder('\OCP\IConfig') - ->disableOriginalConstructor()->getMock(); - - $this->hasher = new Hasher($this->config); - } - - function testHash() { - $hash = $this->hasher->hash('String To Hash'); - $this->assertNotNull($hash); - } - - /** - * @dataProvider versionHashProvider - */ - function testSplitHash($hash, $expected) { - $relativePath = self::invokePrivate($this->hasher, 'splitHash', array($hash)); - $this->assertSame($expected, $relativePath); - } - - - /** - * @dataProvider allHashProviders - */ - function testVerify($password, $hash, $expected) { - $this->config - ->expects($this->any()) - ->method('getSystemValue') - ->with('passwordsalt', null) - ->will($this->returnValue('6Wow67q1wZQZpUUeI6G2LsWUu4XKx')); - - $result = $this->hasher->verify($password, $hash); - $this->assertSame($expected, $result); - } - -} diff --git a/tests/lib/security/securerandom.php b/tests/lib/security/securerandom.php deleted file mode 100644 index 526066d92ee..00000000000 --- a/tests/lib/security/securerandom.php +++ /dev/null @@ -1,76 +0,0 @@ - - * This file is licensed under the Affero General Public License version 3 or - * later. - * See the COPYING-README file. - */ - -use \OC\Security\SecureRandom; - -class SecureRandomTest extends \Test\TestCase { - - public function stringGenerationProvider() { - return array( - array(0, 0), - array(1, 1), - array(128, 128), - array(256, 256), - array(1024, 1024), - array(2048, 2048), - array(64000, 64000), - ); - } - - public static function charCombinations() { - return array( - array('CHAR_LOWER', '[a-z]'), - array('CHAR_UPPER', '[A-Z]'), - array('CHAR_DIGITS', '[0-9]'), - ); - } - - /** @var SecureRandom */ - protected $rng; - - protected function setUp() { - parent::setUp(); - $this->rng = new \OC\Security\SecureRandom(); - } - - /** - * @dataProvider stringGenerationProvider - */ - function testGetLowStrengthGeneratorLength($length, $expectedLength) { - $generator = $this->rng; - - $this->assertEquals($expectedLength, strlen($generator->generate($length))); - } - - /** - * @dataProvider stringGenerationProvider - */ - function testMediumLowStrengthGeneratorLength($length, $expectedLength) { - $generator = $this->rng; - - $this->assertEquals($expectedLength, strlen($generator->generate($length))); - } - - /** - * @dataProvider stringGenerationProvider - */ - function testUninitializedGenerate($length, $expectedLength) { - $this->assertEquals($expectedLength, strlen($this->rng->generate($length))); - } - - /** - * @dataProvider charCombinations - */ - public function testScheme($charName, $chars) { - $generator = $this->rng; - $scheme = constant('OCP\Security\ISecureRandom::' . $charName); - $randomString = $generator->generate(100, $scheme); - $matchesRegex = preg_match('/^'.$chars.'+$/', $randomString); - $this->assertSame(1, $matchesRegex); - } -} diff --git a/tests/lib/security/trusteddomainhelper.php b/tests/lib/security/trusteddomainhelper.php deleted file mode 100644 index 3581211ce61..00000000000 --- a/tests/lib/security/trusteddomainhelper.php +++ /dev/null @@ -1,80 +0,0 @@ - - * This file is licensed under the Affero General Public License version 3 or - * later. - * See the COPYING-README file. - */ - -use \OC\Security\TrustedDomainHelper; -use OCP\IConfig; - -/** - * Class TrustedDomainHelperTest - */ -class TrustedDomainHelperTest extends \Test\TestCase { - /** @var IConfig */ - protected $config; - - protected function setUp() { - parent::setUp(); - - $this->config = $this->getMockBuilder('\OCP\IConfig')->getMock(); - } - - /** - * @dataProvider trustedDomainDataProvider - * @param string $trustedDomains - * @param string $testDomain - * @param bool $result - */ - public function testIsTrustedDomain($trustedDomains, $testDomain, $result) { - $this->config->expects($this->once()) - ->method('getSystemValue') - ->with('trusted_domains') - ->will($this->returnValue($trustedDomains)); - - $trustedDomainHelper = new TrustedDomainHelper($this->config); - $this->assertEquals($result, $trustedDomainHelper->isTrustedDomain($testDomain)); - } - - /** - * @return array - */ - public function trustedDomainDataProvider() { - $trustedHostTestList = [ - 'host.one.test', - 'host.two.test', - '[1fff:0:a88:85a3::ac1f]', - 'host.three.test:443', - ]; - return [ - // empty defaults to false with 8.1 - [null, 'host.one.test:8080', false], - ['', 'host.one.test:8080', false], - [[], 'host.one.test:8080', false], - // trust list when defined - [$trustedHostTestList, 'host.two.test:8080', true], - [$trustedHostTestList, 'host.two.test:9999', true], - [$trustedHostTestList, 'host.three.test:8080', false], - [$trustedHostTestList, 'host.two.test:8080:aa:222', false], - [$trustedHostTestList, '[1fff:0:a88:85a3::ac1f]', true], - [$trustedHostTestList, '[1fff:0:a88:85a3::ac1f]:801', true], - [$trustedHostTestList, '[1fff:0:a88:85a3::ac1f]:801:34', false], - [$trustedHostTestList, 'host.three.test:443', true], - [$trustedHostTestList, 'host.three.test:80', false], - [$trustedHostTestList, 'host.three.test', false], - // trust localhost regardless of trust list - [$trustedHostTestList, 'localhost', true], - [$trustedHostTestList, 'localhost:8080', true], - [$trustedHostTestList, '127.0.0.1', true], - [$trustedHostTestList, '127.0.0.1:8080', true], - // do not trust invalid localhosts - [$trustedHostTestList, 'localhost:1:2', false], - [$trustedHostTestList, 'localhost: evil.host', false], - // do not trust casting - [[1], '1', false], - ]; - } - -} -- cgit v1.2.3 From a107e7de7b59f197367a44bdadddb9b46c590697 Mon Sep 17 00:00:00 2001 From: Joas Schilling Date: Thu, 19 May 2016 09:15:10 +0200 Subject: Fix namespace in share/ --- tests/lib/share/MailNotificationsTest.php | 14 +- tests/lib/share/backend.php | 4 +- tests/lib/share/helper.php | 6 +- tests/lib/share/searchresultsorter.php | 4 +- tests/lib/share/share.php | 488 +++++++++++++++--------------- 5 files changed, 263 insertions(+), 253 deletions(-) (limited to 'tests') diff --git a/tests/lib/share/MailNotificationsTest.php b/tests/lib/share/MailNotificationsTest.php index f160fed57ae..0c951d11f88 100644 --- a/tests/lib/share/MailNotificationsTest.php +++ b/tests/lib/share/MailNotificationsTest.php @@ -19,6 +19,8 @@ * */ +namespace Test\Share; + use OC\Share\MailNotifications; use OCP\IL10N; use OCP\IUser; @@ -33,15 +35,15 @@ use OCP\IURLGenerator; class MailNotificationsTest extends \Test\TestCase { /** @var IL10N */ private $l10n; - /** @var IMailer | PHPUnit_Framework_MockObject_MockObject */ + /** @var IMailer | \PHPUnit_Framework_MockObject_MockObject */ private $mailer; /** @var ILogger */ private $logger; - /** @var Defaults | PHPUnit_Framework_MockObject_MockObject */ + /** @var Defaults | \PHPUnit_Framework_MockObject_MockObject */ private $defaults; - /** @var IUser | PHPUnit_Framework_MockObject_MockObject */ + /** @var IUser | \PHPUnit_Framework_MockObject_MockObject */ private $user; - /** @var IURLGenerator | PHPUnit_Framework_MockObject_MockObject */ + /** @var IURLGenerator | \PHPUnit_Framework_MockObject_MockObject */ private $urlGenerator; @@ -209,7 +211,7 @@ class MailNotificationsTest extends \Test\TestCase { public function testSendInternalShareMail() { $this->setupMailerMock('TestUser shared »welcome.txt« with you', ['recipient@owncloud.com' => 'Recipient'], false); - /** @var MailNotifications | PHPUnit_Framework_MockObject_MockObject $mailNotifications */ + /** @var MailNotifications | \PHPUnit_Framework_MockObject_MockObject $mailNotifications */ $mailNotifications = $this->getMock('OC\Share\MailNotifications',['getItemSharedWithUser'], [ $this->user, $this->l10n, @@ -286,7 +288,7 @@ class MailNotificationsTest extends \Test\TestCase { ->expects($this->once()) ->method('send') ->with($message) - ->will($this->throwException(new Exception('Some Exception Message'))); + ->will($this->throwException(new \Exception('Some Exception Message'))); } } } diff --git a/tests/lib/share/backend.php b/tests/lib/share/backend.php index 9c0d7fcb020..c5007d1583b 100644 --- a/tests/lib/share/backend.php +++ b/tests/lib/share/backend.php @@ -19,7 +19,9 @@ * License along with this library. If not, see . */ -class Test_Share_Backend implements OCP\Share_Backend { +namespace Test\Share; + +class Backend implements \OCP\Share_Backend { const FORMAT_SOURCE = 0; const FORMAT_TARGET = 1; diff --git a/tests/lib/share/helper.php b/tests/lib/share/helper.php index eaa29c8cb90..3fe6389c408 100644 --- a/tests/lib/share/helper.php +++ b/tests/lib/share/helper.php @@ -19,11 +19,13 @@ * License along with this library. If not, see . */ +namespace Test\Share; + /** * @group DB - * Class Test_Share_Helper + * Class Helper */ -class Test_Share_Helper extends \Test\TestCase { +class Helper extends \Test\TestCase { public function expireDateProvider() { return array( diff --git a/tests/lib/share/searchresultsorter.php b/tests/lib/share/searchresultsorter.php index d91110f7a9a..6bee5dfe7f0 100644 --- a/tests/lib/share/searchresultsorter.php +++ b/tests/lib/share/searchresultsorter.php @@ -19,7 +19,9 @@ * License along with this library. If not, see . */ -class Test_Share_Search extends \Test\TestCase { +namespace Test\Share; + +class SearchResultSorter extends \Test\TestCase { public function testSort() { $search = 'lin'; $sorter = new \OC\Share\SearchResultSorter($search, 'foobar'); diff --git a/tests/lib/share/share.php b/tests/lib/share/share.php index a07e90effc3..e8240fb6738 100644 --- a/tests/lib/share/share.php +++ b/tests/lib/share/share.php @@ -19,12 +19,14 @@ * License along with this library. If not, see . */ +namespace Test\Share; + /** * Class Test_Share * * @group DB */ -class Test_Share extends \Test\TestCase { +class Share extends \Test\TestCase { protected $itemType; protected $userBackend; @@ -45,8 +47,8 @@ class Test_Share extends \Test\TestCase { protected function setUp() { parent::setUp(); - OC_User::clearBackends(); - OC_User::useBackend('dummy'); + \OC_User::clearBackends(); + \OC_User::useBackend('dummy'); $this->user1 = $this->getUniqueID('user1_'); $this->user2 = $this->getUniqueID('user2_'); $this->user3 = $this->getUniqueID('user3_'); @@ -61,24 +63,24 @@ class Test_Share extends \Test\TestCase { \OC::$server->getUserManager()->createUser($this->user5, 'pass'); \OC::$server->getUserManager()->createUser($this->user6, 'pass'); // no group \OC::$server->getUserManager()->createUser($this->groupAndUser, 'pass'); - OC_User::setUserId($this->user1); - OC_Group::clearBackends(); - OC_Group::useBackend(new \Test\Util\Group\Dummy()); + \OC_User::setUserId($this->user1); + \OC_Group::clearBackends(); + \OC_Group::useBackend(new \Test\Util\Group\Dummy()); $this->group1 = $this->getUniqueID('group1_'); $this->group2 = $this->getUniqueID('group2_'); - OC_Group::createGroup($this->group1); - OC_Group::createGroup($this->group2); - OC_Group::createGroup($this->groupAndUser); - OC_Group::addToGroup($this->user1, $this->group1); - OC_Group::addToGroup($this->user2, $this->group1); - OC_Group::addToGroup($this->user3, $this->group1); - OC_Group::addToGroup($this->user2, $this->group2); - OC_Group::addToGroup($this->user4, $this->group2); - OC_Group::addToGroup($this->user2, $this->groupAndUser); - OC_Group::addToGroup($this->user3, $this->groupAndUser); - OCP\Share::registerBackend('test', 'Test_Share_Backend'); - OC_Hook::clear('OCP\\Share'); - OC::registerShareHooks(); + \OC_Group::createGroup($this->group1); + \OC_Group::createGroup($this->group2); + \OC_Group::createGroup($this->groupAndUser); + \OC_Group::addToGroup($this->user1, $this->group1); + \OC_Group::addToGroup($this->user2, $this->group1); + \OC_Group::addToGroup($this->user3, $this->group1); + \OC_Group::addToGroup($this->user2, $this->group2); + \OC_Group::addToGroup($this->user4, $this->group2); + \OC_Group::addToGroup($this->user2, $this->groupAndUser); + \OC_Group::addToGroup($this->user3, $this->groupAndUser); + \OCP\Share::registerBackend('test', 'Test_Share_Backend'); + \OC_Hook::clear('OCP\\Share'); + \OC::registerShareHooks(); $this->resharing = \OC::$server->getAppConfig()->getValue('core', 'shareapi_allow_resharing', 'yes'); \OC::$server->getAppConfig()->setValue('core', 'shareapi_allow_resharing', 'yes'); @@ -109,9 +111,9 @@ class Test_Share extends \Test\TestCase { $user = \OC::$server->getUserManager()->get($this->groupAndUser); if ($user !== null) { $user->delete(); } - OC_Group::deleteGroup($this->group1); - OC_Group::deleteGroup($this->group2); - OC_Group::deleteGroup($this->groupAndUser); + \OC_Group::deleteGroup($this->group1); + \OC_Group::deleteGroup($this->group2); + \OC_Group::deleteGroup($this->groupAndUser); $this->logout(); parent::tearDown(); @@ -126,8 +128,8 @@ class Test_Share extends \Test\TestCase { public function testShareInvalidShareType() { $message = 'Share type foobar is not valid for test.txt'; try { - OCP\Share::shareItem('test', 'test.txt', 'foobar', $this->user2, \OCP\Constants::PERMISSION_READ); - } catch (Exception $exception) { + \OCP\Share::shareItem('test', 'test.txt', 'foobar', $this->user2, \OCP\Constants::PERMISSION_READ); + } catch (\Exception $exception) { $this->assertEquals($message, $exception->getMessage()); } } @@ -135,72 +137,72 @@ class Test_Share extends \Test\TestCase { public function testInvalidItemType() { $message = 'Sharing backend for foobar not found'; try { - OCP\Share::shareItem('foobar', 'test.txt', OCP\Share::SHARE_TYPE_USER, $this->user2, \OCP\Constants::PERMISSION_READ); + \OCP\Share::shareItem('foobar', 'test.txt', \OCP\Share::SHARE_TYPE_USER, $this->user2, \OCP\Constants::PERMISSION_READ); $this->fail('Exception was expected: '.$message); - } catch (Exception $exception) { + } catch (\Exception $exception) { $this->assertEquals($message, $exception->getMessage()); } try { - OCP\Share::getItemsSharedWith('foobar'); + \OCP\Share::getItemsSharedWith('foobar'); $this->fail('Exception was expected: '.$message); - } catch (Exception $exception) { + } catch (\Exception $exception) { $this->assertEquals($message, $exception->getMessage()); } try { - OCP\Share::getItemSharedWith('foobar', 'test.txt'); + \OCP\Share::getItemSharedWith('foobar', 'test.txt'); $this->fail('Exception was expected: '.$message); - } catch (Exception $exception) { + } catch (\Exception $exception) { $this->assertEquals($message, $exception->getMessage()); } try { - OCP\Share::getItemSharedWithBySource('foobar', 'test.txt'); + \OCP\Share::getItemSharedWithBySource('foobar', 'test.txt'); $this->fail('Exception was expected: '.$message); - } catch (Exception $exception) { + } catch (\Exception $exception) { $this->assertEquals($message, $exception->getMessage()); } try { - OCP\Share::getItemShared('foobar', 'test.txt'); + \OCP\Share::getItemShared('foobar', 'test.txt'); $this->fail('Exception was expected: '.$message); - } catch (Exception $exception) { + } catch (\Exception $exception) { $this->assertEquals($message, $exception->getMessage()); } try { - OCP\Share::unshare('foobar', 'test.txt', OCP\Share::SHARE_TYPE_USER, $this->user2); + \OCP\Share::unshare('foobar', 'test.txt', \OCP\Share::SHARE_TYPE_USER, $this->user2); $this->fail('Exception was expected: '.$message); - } catch (Exception $exception) { + } catch (\Exception $exception) { $this->assertEquals($message, $exception->getMessage()); } try { - OCP\Share::setPermissions('foobar', 'test.txt', OCP\Share::SHARE_TYPE_USER, $this->user2, \OCP\Constants::PERMISSION_UPDATE); + \OCP\Share::setPermissions('foobar', 'test.txt', \OCP\Share::SHARE_TYPE_USER, $this->user2, \OCP\Constants::PERMISSION_UPDATE); $this->fail('Exception was expected: '.$message); - } catch (Exception $exception) { + } catch (\Exception $exception) { $this->assertEquals($message, $exception->getMessage()); } } protected function shareUserOneTestFileWithUserTwo() { - OC_User::setUserId($this->user1); + \OC_User::setUserId($this->user1); $this->assertTrue( - OCP\Share::shareItem('test', 'test.txt', OCP\Share::SHARE_TYPE_USER, $this->user2, \OCP\Constants::PERMISSION_READ), + \OCP\Share::shareItem('test', 'test.txt', \OCP\Share::SHARE_TYPE_USER, $this->user2, \OCP\Constants::PERMISSION_READ), 'Failed asserting that user 1 successfully shared text.txt with user 2.' ); $this->assertContains( 'test.txt', - OCP\Share::getItemShared('test', 'test.txt', Test_Share_Backend::FORMAT_SOURCE), + \OCP\Share::getItemShared('test', 'test.txt', Backend::FORMAT_SOURCE), 'Failed asserting that test.txt is a shared file of user 1.' ); - OC_User::setUserId($this->user2); + \OC_User::setUserId($this->user2); $this->assertContains( 'test.txt', - OCP\Share::getItemSharedWith('test', 'test.txt', Test_Share_Backend::FORMAT_SOURCE), + \OCP\Share::getItemSharedWith('test', 'test.txt', Backend::FORMAT_SOURCE), 'Failed asserting that user 2 has access to test.txt after initial sharing.' ); } protected function shareUserTestFileAsLink() { - OC_User::setUserId($this->user1); - $result = OCP\Share::shareItem('test', 'test.txt', OCP\Share::SHARE_TYPE_LINK, null, \OCP\Constants::PERMISSION_READ); + \OC_User::setUserId($this->user1); + $result = \OCP\Share::shareItem('test', 'test.txt', \OCP\Share::SHARE_TYPE_LINK, null, \OCP\Constants::PERMISSION_READ); $this->assertTrue(is_string($result)); } @@ -209,21 +211,21 @@ class Test_Share extends \Test\TestCase { * @param string $receiver */ protected function shareUserTestFileWithUser($sharer, $receiver) { - OC_User::setUserId($sharer); + \OC_User::setUserId($sharer); $this->assertTrue( - OCP\Share::shareItem('test', 'test.txt', OCP\Share::SHARE_TYPE_USER, $receiver, \OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_SHARE), + \OCP\Share::shareItem('test', 'test.txt', \OCP\Share::SHARE_TYPE_USER, $receiver, \OCP\Constants::PERMISSION_READ | \OCP\Constants::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), + \OCP\Share::getItemShared('test', 'test.txt', Backend::FORMAT_SOURCE), 'Failed asserting that test.txt is a shared file of ' . $sharer . '.' ); - OC_User::setUserId($receiver); + \OC_User::setUserId($receiver); $this->assertContains( 'test.txt', - OCP\Share::getItemSharedWith('test', 'test.txt', Test_Share_Backend::FORMAT_SOURCE), + \OCP\Share::getItemSharedWith('test', 'test.txt', Backend::FORMAT_SOURCE), 'Failed asserting that ' . $receiver . ' has access to test.txt after initial sharing.' ); } @@ -232,23 +234,23 @@ class Test_Share extends \Test\TestCase { // Invalid shares $message = 'Sharing test.txt failed, because you can not share with yourself'; try { - OCP\Share::shareItem('test', 'test.txt', OCP\Share::SHARE_TYPE_USER, $this->user1, \OCP\Constants::PERMISSION_READ); + \OCP\Share::shareItem('test', 'test.txt', \OCP\Share::SHARE_TYPE_USER, $this->user1, \OCP\Constants::PERMISSION_READ); $this->fail('Exception was expected: '.$message); - } catch (Exception $exception) { + } catch (\Exception $exception) { $this->assertEquals($message, $exception->getMessage()); } $message = 'Sharing test.txt failed, because the user foobar does not exist'; try { - OCP\Share::shareItem('test', 'test.txt', OCP\Share::SHARE_TYPE_USER, 'foobar', \OCP\Constants::PERMISSION_READ); + \OCP\Share::shareItem('test', 'test.txt', \OCP\Share::SHARE_TYPE_USER, 'foobar', \OCP\Constants::PERMISSION_READ); $this->fail('Exception was expected: '.$message); - } catch (Exception $exception) { + } catch (\Exception $exception) { $this->assertEquals($message, $exception->getMessage()); } $message = 'Sharing foobar failed, because the sharing backend for test could not find its source'; try { - OCP\Share::shareItem('test', 'foobar', OCP\Share::SHARE_TYPE_USER, $this->user2, \OCP\Constants::PERMISSION_READ); + \OCP\Share::shareItem('test', 'foobar', \OCP\Share::SHARE_TYPE_USER, $this->user2, \OCP\Constants::PERMISSION_READ); $this->fail('Exception was expected: '.$message); - } catch (Exception $exception) { + } catch (\Exception $exception) { $this->assertEquals($message, $exception->getMessage()); } @@ -256,140 +258,140 @@ class Test_Share extends \Test\TestCase { $this->shareUserOneTestFileWithUserTwo(); // Attempt to share again - OC_User::setUserId($this->user1); + \OC_User::setUserId($this->user1); $message = 'Sharing test.txt failed, because this item is already shared with '.$this->user2; try { - OCP\Share::shareItem('test', 'test.txt', OCP\Share::SHARE_TYPE_USER, $this->user2, \OCP\Constants::PERMISSION_READ); + \OCP\Share::shareItem('test', 'test.txt', \OCP\Share::SHARE_TYPE_USER, $this->user2, \OCP\Constants::PERMISSION_READ); $this->fail('Exception was expected: '.$message); - } catch (Exception $exception) { + } catch (\Exception $exception) { $this->assertEquals($message, $exception->getMessage()); } // Attempt to share back - OC_User::setUserId($this->user2); + \OC_User::setUserId($this->user2); $message = 'Sharing failed, because the user '.$this->user1.' is the original sharer'; try { - OCP\Share::shareItem('test', 'test.txt', OCP\Share::SHARE_TYPE_USER, $this->user1, \OCP\Constants::PERMISSION_READ); + \OCP\Share::shareItem('test', 'test.txt', \OCP\Share::SHARE_TYPE_USER, $this->user1, \OCP\Constants::PERMISSION_READ); $this->fail('Exception was expected: '.$message); - } catch (Exception $exception) { + } catch (\Exception $exception) { $this->assertEquals($message, $exception->getMessage()); } // Unshare - OC_User::setUserId($this->user1); - $this->assertTrue(OCP\Share::unshare('test', 'test.txt', OCP\Share::SHARE_TYPE_USER, $this->user2)); + \OC_User::setUserId($this->user1); + $this->assertTrue(\OCP\Share::unshare('test', 'test.txt', \OCP\Share::SHARE_TYPE_USER, $this->user2)); // Attempt reshare without share permission - $this->assertTrue(OCP\Share::shareItem('test', 'test.txt', OCP\Share::SHARE_TYPE_USER, $this->user2, \OCP\Constants::PERMISSION_READ)); - OC_User::setUserId($this->user2); + $this->assertTrue(\OCP\Share::shareItem('test', 'test.txt', \OCP\Share::SHARE_TYPE_USER, $this->user2, \OCP\Constants::PERMISSION_READ)); + \OC_User::setUserId($this->user2); $message = 'Sharing test.txt failed, because resharing is not allowed'; try { - OCP\Share::shareItem('test', 'test.txt', OCP\Share::SHARE_TYPE_USER, $this->user3, \OCP\Constants::PERMISSION_READ); + \OCP\Share::shareItem('test', 'test.txt', \OCP\Share::SHARE_TYPE_USER, $this->user3, \OCP\Constants::PERMISSION_READ); $this->fail('Exception was expected: '.$message); - } catch (Exception $exception) { + } catch (\Exception $exception) { $this->assertEquals($message, $exception->getMessage()); } // Owner grants share and update permission - OC_User::setUserId($this->user1); - $this->assertTrue(OCP\Share::setPermissions('test', 'test.txt', OCP\Share::SHARE_TYPE_USER, $this->user2, \OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_SHARE)); + \OC_User::setUserId($this->user1); + $this->assertTrue(\OCP\Share::setPermissions('test', 'test.txt', \OCP\Share::SHARE_TYPE_USER, $this->user2, \OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_SHARE)); // Attempt reshare with escalated permissions - OC_User::setUserId($this->user2); + \OC_User::setUserId($this->user2); $message = 'Sharing test.txt failed, because the permissions exceed permissions granted to '.$this->user2; try { - OCP\Share::shareItem('test', 'test.txt', OCP\Share::SHARE_TYPE_USER, $this->user3, \OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_DELETE); + \OCP\Share::shareItem('test', 'test.txt', \OCP\Share::SHARE_TYPE_USER, $this->user3, \OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_DELETE); $this->fail('Exception was expected: '.$message); - } catch (Exception $exception) { + } catch (\Exception $exception) { $this->assertEquals($message, $exception->getMessage()); } // Valid reshare - $this->assertTrue(OCP\Share::shareItem('test', 'test.txt', OCP\Share::SHARE_TYPE_USER, $this->user3, \OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_UPDATE)); - $this->assertEquals(array('test.txt'), OCP\Share::getItemShared('test', 'test.txt', Test_Share_Backend::FORMAT_SOURCE)); - OC_User::setUserId($this->user3); - $this->assertEquals(array('test.txt'), OCP\Share::getItemSharedWith('test', 'test.txt', Test_Share_Backend::FORMAT_SOURCE)); - $this->assertEquals(array(\OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_UPDATE), OCP\Share::getItemSharedWith('test', 'test.txt', Test_Share_Backend::FORMAT_PERMISSIONS)); + $this->assertTrue(\OCP\Share::shareItem('test', 'test.txt', \OCP\Share::SHARE_TYPE_USER, $this->user3, \OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_UPDATE)); + $this->assertEquals(array('test.txt'), \OCP\Share::getItemShared('test', 'test.txt', Backend::FORMAT_SOURCE)); + \OC_User::setUserId($this->user3); + $this->assertEquals(array('test.txt'), \OCP\Share::getItemSharedWith('test', 'test.txt', Backend::FORMAT_SOURCE)); + $this->assertEquals(array(\OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_UPDATE), \OCP\Share::getItemSharedWith('test', 'test.txt', Backend::FORMAT_PERMISSIONS)); // Attempt to escalate permissions - OC_User::setUserId($this->user2); + \OC_User::setUserId($this->user2); $message = 'Setting permissions for test.txt failed, because the permissions exceed permissions granted to '.$this->user2; try { - OCP\Share::setPermissions('test', 'test.txt', OCP\Share::SHARE_TYPE_USER, $this->user3, \OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_DELETE); + \OCP\Share::setPermissions('test', 'test.txt', \OCP\Share::SHARE_TYPE_USER, $this->user3, \OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_DELETE); $this->fail('Exception was expected: '.$message); - } catch (Exception $exception) { + } catch (\Exception $exception) { $this->assertEquals($message, $exception->getMessage()); } // Remove update permission - OC_User::setUserId($this->user1); - $this->assertTrue(OCP\Share::setPermissions('test', 'test.txt', OCP\Share::SHARE_TYPE_USER, $this->user2, \OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_SHARE)); - OC_User::setUserId($this->user2); - $this->assertEquals(array(\OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_SHARE), OCP\Share::getItemSharedWith('test', 'test.txt', Test_Share_Backend::FORMAT_PERMISSIONS)); - OC_User::setUserId($this->user3); - $this->assertEquals(array(\OCP\Constants::PERMISSION_READ), OCP\Share::getItemSharedWith('test', 'test.txt', Test_Share_Backend::FORMAT_PERMISSIONS)); + \OC_User::setUserId($this->user1); + $this->assertTrue(\OCP\Share::setPermissions('test', 'test.txt', \OCP\Share::SHARE_TYPE_USER, $this->user2, \OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_SHARE)); + \OC_User::setUserId($this->user2); + $this->assertEquals(array(\OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_SHARE), \OCP\Share::getItemSharedWith('test', 'test.txt', Backend::FORMAT_PERMISSIONS)); + \OC_User::setUserId($this->user3); + $this->assertEquals(array(\OCP\Constants::PERMISSION_READ), \OCP\Share::getItemSharedWith('test', 'test.txt', Backend::FORMAT_PERMISSIONS)); // Remove share permission - OC_User::setUserId($this->user1); - $this->assertTrue(OCP\Share::setPermissions('test', 'test.txt', OCP\Share::SHARE_TYPE_USER, $this->user2, \OCP\Constants::PERMISSION_READ)); - OC_User::setUserId($this->user2); - $this->assertEquals(array(\OCP\Constants::PERMISSION_READ), OCP\Share::getItemSharedWith('test', 'test.txt', Test_Share_Backend::FORMAT_PERMISSIONS)); - OC_User::setUserId($this->user3); - $this->assertSame(array(), OCP\Share::getItemSharedWith('test', 'test.txt')); + \OC_User::setUserId($this->user1); + $this->assertTrue(\OCP\Share::setPermissions('test', 'test.txt', \OCP\Share::SHARE_TYPE_USER, $this->user2, \OCP\Constants::PERMISSION_READ)); + \OC_User::setUserId($this->user2); + $this->assertEquals(array(\OCP\Constants::PERMISSION_READ), \OCP\Share::getItemSharedWith('test', 'test.txt', Backend::FORMAT_PERMISSIONS)); + \OC_User::setUserId($this->user3); + $this->assertSame(array(), \OCP\Share::getItemSharedWith('test', 'test.txt')); // Reshare again, and then have owner unshare - OC_User::setUserId($this->user1); - $this->assertTrue(OCP\Share::setPermissions('test', 'test.txt', OCP\Share::SHARE_TYPE_USER, $this->user2, \OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_SHARE)); - OC_User::setUserId($this->user2); - $this->assertTrue(OCP\Share::shareItem('test', 'test.txt', OCP\Share::SHARE_TYPE_USER, $this->user3, \OCP\Constants::PERMISSION_READ)); - OC_User::setUserId($this->user1); - $this->assertTrue(OCP\Share::unshare('test', 'test.txt', OCP\Share::SHARE_TYPE_USER, $this->user2)); - OC_User::setUserId($this->user2); - $this->assertSame(array(), OCP\Share::getItemSharedWith('test', 'test.txt')); - OC_User::setUserId($this->user3); - $this->assertSame(array(), OCP\Share::getItemSharedWith('test', 'test.txt')); + \OC_User::setUserId($this->user1); + $this->assertTrue(\OCP\Share::setPermissions('test', 'test.txt', \OCP\Share::SHARE_TYPE_USER, $this->user2, \OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_SHARE)); + \OC_User::setUserId($this->user2); + $this->assertTrue(\OCP\Share::shareItem('test', 'test.txt', \OCP\Share::SHARE_TYPE_USER, $this->user3, \OCP\Constants::PERMISSION_READ)); + \OC_User::setUserId($this->user1); + $this->assertTrue(\OCP\Share::unshare('test', 'test.txt', \OCP\Share::SHARE_TYPE_USER, $this->user2)); + \OC_User::setUserId($this->user2); + $this->assertSame(array(), \OCP\Share::getItemSharedWith('test', 'test.txt')); + \OC_User::setUserId($this->user3); + $this->assertSame(array(), \OCP\Share::getItemSharedWith('test', 'test.txt')); // Attempt target conflict - OC_User::setUserId($this->user1); - $this->assertTrue(OCP\Share::shareItem('test', 'test.txt', OCP\Share::SHARE_TYPE_USER, $this->user2, \OCP\Constants::PERMISSION_READ)); - OC_User::setUserId($this->user3); - $this->assertTrue(OCP\Share::shareItem('test', 'share.txt', OCP\Share::SHARE_TYPE_USER, $this->user2, \OCP\Constants::PERMISSION_READ)); + \OC_User::setUserId($this->user1); + $this->assertTrue(\OCP\Share::shareItem('test', 'test.txt', \OCP\Share::SHARE_TYPE_USER, $this->user2, \OCP\Constants::PERMISSION_READ)); + \OC_User::setUserId($this->user3); + $this->assertTrue(\OCP\Share::shareItem('test', 'share.txt', \OCP\Share::SHARE_TYPE_USER, $this->user2, \OCP\Constants::PERMISSION_READ)); - OC_User::setUserId($this->user2); - $to_test = OCP\Share::getItemsSharedWith('test', Test_Share_Backend::FORMAT_TARGET); + \OC_User::setUserId($this->user2); + $to_test = \OCP\Share::getItemsSharedWith('test', Backend::FORMAT_TARGET); $this->assertEquals(2, count($to_test)); $this->assertTrue(in_array('test.txt', $to_test)); $this->assertTrue(in_array('test1.txt', $to_test)); // Unshare from self - $this->assertTrue(OCP\Share::unshareFromSelf('test', 'test.txt')); - $this->assertEquals(array('test1.txt'), OCP\Share::getItemsSharedWith('test', Test_Share_Backend::FORMAT_TARGET)); + $this->assertTrue(\OCP\Share::unshareFromSelf('test', 'test.txt')); + $this->assertEquals(array('test1.txt'), \OCP\Share::getItemsSharedWith('test', Backend::FORMAT_TARGET)); // Unshare from self via source - $this->assertTrue(OCP\Share::unshareFromSelf('test', 'share.txt', true)); - $this->assertEquals(array(), OCP\Share::getItemsSharedWith('test', Test_Share_Backend::FORMAT_TARGET)); + $this->assertTrue(\OCP\Share::unshareFromSelf('test', 'share.txt', true)); + $this->assertEquals(array(), \OCP\Share::getItemsSharedWith('test', Backend::FORMAT_TARGET)); - OC_User::setUserId($this->user1); - $this->assertTrue(OCP\Share::shareItem('test', 'test.txt', OCP\Share::SHARE_TYPE_USER, $this->user2, \OCP\Constants::PERMISSION_READ)); - OC_User::setUserId($this->user3); - $this->assertTrue(OCP\Share::shareItem('test', 'share.txt', OCP\Share::SHARE_TYPE_USER, $this->user2, \OCP\Constants::PERMISSION_READ)); + \OC_User::setUserId($this->user1); + $this->assertTrue(\OCP\Share::shareItem('test', 'test.txt', \OCP\Share::SHARE_TYPE_USER, $this->user2, \OCP\Constants::PERMISSION_READ)); + \OC_User::setUserId($this->user3); + $this->assertTrue(\OCP\Share::shareItem('test', 'share.txt', \OCP\Share::SHARE_TYPE_USER, $this->user2, \OCP\Constants::PERMISSION_READ)); - OC_User::setUserId($this->user2); - $to_test = OCP\Share::getItemsSharedWith('test', Test_Share_Backend::FORMAT_TARGET); + \OC_User::setUserId($this->user2); + $to_test = \OCP\Share::getItemsSharedWith('test', Backend::FORMAT_TARGET); $this->assertEquals(2, count($to_test)); $this->assertTrue(in_array('test.txt', $to_test)); $this->assertTrue(in_array('test1.txt', $to_test)); // Remove user - OC_User::setUserId($this->user1); + \OC_User::setUserId($this->user1); $user = \OC::$server->getUserManager()->get($this->user1); if ($user !== null) { $user->delete(); } - OC_User::setUserId($this->user2); - $this->assertEquals(array('test1.txt'), OCP\Share::getItemsSharedWith('test', Test_Share_Backend::FORMAT_TARGET)); + \OC_User::setUserId($this->user2); + $this->assertEquals(array('test1.txt'), \OCP\Share::getItemsSharedWith('test', Backend::FORMAT_TARGET)); } public function testShareWithUserExpirationExpired() { - OC_User::setUserId($this->user1); + \OC_User::setUserId($this->user1); $this->shareUserOneTestFileWithUserTwo(); $this->shareUserTestFileAsLink(); @@ -402,14 +404,14 @@ class Test_Share extends \Test\TestCase { $query->bindValue(5, \OCP\Share::SHARE_TYPE_LINK); $query->execute(); - $shares = OCP\Share::getItemsShared('test'); + $shares = \OCP\Share::getItemsShared('test'); $this->assertSame(1, count($shares)); $share = reset($shares); $this->assertSame(\OCP\Share::SHARE_TYPE_USER, $share['share_type']); } public function testGetShareFromOutsideFilesFolder() { - OC_User::setUserId($this->user1); + \OC_User::setUserId($this->user1); $view = new \OC\Files\View('/' . $this->user1 . '/'); $view->mkdir('files/test'); $view->mkdir('files/test/sub'); @@ -422,41 +424,41 @@ class Test_Share extends \Test\TestCase { $fileId = $fileInfo->getId(); $this->assertTrue( - OCP\Share::shareItem('folder', $fileId, OCP\Share::SHARE_TYPE_USER, $this->user2, \OCP\Constants::PERMISSION_READ), + \OCP\Share::shareItem('folder', $fileId, \OCP\Share::SHARE_TYPE_USER, $this->user2, \OCP\Constants::PERMISSION_READ), 'Failed asserting that user 1 successfully shared "test/sub" with user 2.' ); - $result = OCP\Share::getItemShared('folder', $fileId, Test_Share_Backend::FORMAT_SOURCE); + $result = \OCP\Share::getItemShared('folder', $fileId, Backend::FORMAT_SOURCE); $this->assertNotEmpty($result); - $result = OCP\Share::getItemSharedWithUser('folder', $fileId, $this->user2); + $result = \OCP\Share::getItemSharedWithUser('folder', $fileId, $this->user2); $this->assertNotEmpty($result); - $result = OCP\Share::getItemsSharedWithUser('folder', $this->user2); + $result = \OCP\Share::getItemsSharedWithUser('folder', $this->user2); $this->assertNotEmpty($result); // move to trash (keeps file id) $view->rename('files/test', 'files_trashbin/files/test'); - $result = OCP\Share::getItemShared('folder', $fileId, Test_Share_Backend::FORMAT_SOURCE); + $result = \OCP\Share::getItemShared('folder', $fileId, Backend::FORMAT_SOURCE); $this->assertEmpty($result, 'Share must not be returned for files outside of "files"'); - $result = OCP\Share::getItemSharedWithUser('folder', $fileId, $this->user2); + $result = \OCP\Share::getItemSharedWithUser('folder', $fileId, $this->user2); $this->assertEmpty($result, 'Share must not be returned for files outside of "files"'); - $result = OCP\Share::getItemsSharedWithUser('folder', $this->user2); + $result = \OCP\Share::getItemsSharedWithUser('folder', $this->user2); $this->assertEmpty($result, 'Share must not be returned for files outside of "files"'); } public function testSetExpireDateInPast() { - OC_User::setUserId($this->user1); + \OC_User::setUserId($this->user1); $this->shareUserOneTestFileWithUserTwo(); $this->shareUserTestFileAsLink(); $setExpireDateFailed = false; try { $this->assertTrue( - OCP\Share::setExpirationDate('test', 'test.txt', $this->dateInPast, ''), + \OCP\Share::setExpirationDate('test', 'test.txt', $this->dateInPast, ''), 'Failed asserting that user 1 successfully set an expiration date for the test.txt share.' ); } catch (\Exception $e) { @@ -467,17 +469,17 @@ class Test_Share extends \Test\TestCase { } public function testShareWithUserExpirationValid() { - OC_User::setUserId($this->user1); + \OC_User::setUserId($this->user1); $this->shareUserOneTestFileWithUserTwo(); $this->shareUserTestFileAsLink(); $this->assertTrue( - OCP\Share::setExpirationDate('test', 'test.txt', $this->dateInFuture, ''), + \OCP\Share::setExpirationDate('test', 'test.txt', $this->dateInFuture, ''), 'Failed asserting that user 1 successfully set an expiration date for the test.txt share.' ); - $shares = OCP\Share::getItemsShared('test'); + $shares = \OCP\Share::getItemsShared('test'); $this->assertSame(2, count($shares)); } @@ -488,14 +490,14 @@ class Test_Share extends \Test\TestCase { */ public function testShareWithUserAndUserIsExcludedFromResharing() { - OC_User::setUserId($this->user1); + \OC_User::setUserId($this->user1); $this->assertTrue( - OCP\Share::shareItem('test', 'test.txt', OCP\Share::SHARE_TYPE_USER, $this->user4, \OCP\Constants::PERMISSION_ALL), + \OCP\Share::shareItem('test', 'test.txt', \OCP\Share::SHARE_TYPE_USER, $this->user4, \OCP\Constants::PERMISSION_ALL), 'Failed asserting that user 1 successfully shared text.txt with user 4.' ); $this->assertContains( 'test.txt', - OCP\Share::getItemShared('test', 'test.txt', Test_Share_Backend::FORMAT_SOURCE), + \OCP\Share::getItemShared('test', 'test.txt', Backend::FORMAT_SOURCE), 'Failed asserting that test.txt is a shared file of user 1.' ); @@ -503,9 +505,9 @@ class Test_Share extends \Test\TestCase { \OC::$server->getAppConfig()->setValue('core', 'shareapi_exclude_groups_list', $this->group2); \OC::$server->getAppConfig()->setValue('core', 'shareapi_exclude_groups', "yes"); - OC_User::setUserId($this->user4); + \OC_User::setUserId($this->user4); - $share = OCP\Share::getItemSharedWith('test', 'test.txt'); + $share = \OCP\Share::getItemSharedWith('test', 'test.txt'); $this->assertSame(\OCP\Constants::PERMISSION_ALL & ~\OCP\Constants::PERMISSION_SHARE, $share['permissions'], 'Failed asserting that user 4 is excluded from re-sharing'); @@ -516,7 +518,7 @@ class Test_Share extends \Test\TestCase { } public function testSharingAFolderThatIsSharedWithAGroupOfTheOwner() { - OC_User::setUserId($this->user1); + \OC_User::setUserId($this->user1); $view = new \OC\Files\View('/' . $this->user1 . '/'); $view->mkdir('files/test'); $view->mkdir('files/test/sub1'); @@ -527,11 +529,11 @@ class Test_Share extends \Test\TestCase { $fileId = $fileInfo->getId(); $this->assertTrue( - OCP\Share::shareItem('folder', $fileId, OCP\Share::SHARE_TYPE_GROUP, $this->group1, \OCP\Constants::PERMISSION_READ + \OCP\Constants::PERMISSION_CREATE), + \OCP\Share::shareItem('folder', $fileId, \OCP\Share::SHARE_TYPE_GROUP, $this->group1, \OCP\Constants::PERMISSION_READ + \OCP\Constants::PERMISSION_CREATE), 'Failed asserting that user 1 successfully shared "test/sub1" with group 1.' ); - $result = OCP\Share::getItemShared('folder', $fileId, Test_Share_Backend::FORMAT_SOURCE); + $result = \OCP\Share::getItemShared('folder', $fileId, Backend::FORMAT_SOURCE); $this->assertNotEmpty($result); $this->assertEquals(\OCP\Constants::PERMISSION_READ + \OCP\Constants::PERMISSION_CREATE, $result['permissions']); @@ -540,17 +542,17 @@ class Test_Share extends \Test\TestCase { $fileId = $fileInfo->getId(); $this->assertTrue( - OCP\Share::shareItem('folder', $fileId, OCP\Share::SHARE_TYPE_USER, $this->user4, \OCP\Constants::PERMISSION_READ), + \OCP\Share::shareItem('folder', $fileId, \OCP\Share::SHARE_TYPE_USER, $this->user4, \OCP\Constants::PERMISSION_READ), 'Failed asserting that user 1 successfully shared "test/sub1/sub2" with user 4.' ); - $result = OCP\Share::getItemShared('folder', $fileId, Test_Share_Backend::FORMAT_SOURCE); + $result = \OCP\Share::getItemShared('folder', $fileId, Backend::FORMAT_SOURCE); $this->assertNotEmpty($result); $this->assertEquals(\OCP\Constants::PERMISSION_READ, $result['permissions']); } public function testSharingAFileInsideAFolderThatIsAlreadyShared() { - OC_User::setUserId($this->user1); + \OC_User::setUserId($this->user1); $view = new \OC\Files\View('/' . $this->user1 . '/'); $view->mkdir('files/test'); $view->mkdir('files/test/sub1'); @@ -565,12 +567,12 @@ class Test_Share extends \Test\TestCase { $fileId = $fileInfo->getId(); $this->assertTrue( - OCP\Share::shareItem('folder', $folderId, OCP\Share::SHARE_TYPE_GROUP, $this->group2, \OCP\Constants::PERMISSION_READ + \OCP\Constants::PERMISSION_UPDATE), + \OCP\Share::shareItem('folder', $folderId, \OCP\Share::SHARE_TYPE_GROUP, $this->group2, \OCP\Constants::PERMISSION_READ + \OCP\Constants::PERMISSION_UPDATE), 'Failed asserting that user 1 successfully shared "test/sub1" with group 2.' ); $this->assertTrue( - OCP\Share::shareItem('file', $fileId, OCP\Share::SHARE_TYPE_USER, $this->user2, \OCP\Constants::PERMISSION_READ), + \OCP\Share::shareItem('file', $fileId, \OCP\Share::SHARE_TYPE_USER, $this->user2, \OCP\Constants::PERMISSION_READ), 'Failed asserting that user 1 successfully shared "test/sub1/file.txt" with user 2.' ); @@ -585,28 +587,28 @@ class Test_Share extends \Test\TestCase { } protected function shareUserOneTestFileWithGroupOne() { - OC_User::setUserId($this->user1); + \OC_User::setUserId($this->user1); $this->assertTrue( - OCP\Share::shareItem('test', 'test.txt', OCP\Share::SHARE_TYPE_GROUP, $this->group1, \OCP\Constants::PERMISSION_READ), + \OCP\Share::shareItem('test', 'test.txt', \OCP\Share::SHARE_TYPE_GROUP, $this->group1, \OCP\Constants::PERMISSION_READ), 'Failed asserting that user 1 successfully shared text.txt with group 1.' ); $this->assertContains( 'test.txt', - OCP\Share::getItemShared('test', 'test.txt', Test_Share_Backend::FORMAT_SOURCE), + \OCP\Share::getItemShared('test', 'test.txt', Backend::FORMAT_SOURCE), 'Failed asserting that test.txt is a shared file of user 1.' ); - OC_User::setUserId($this->user2); + \OC_User::setUserId($this->user2); $this->assertContains( 'test.txt', - OCP\Share::getItemSharedWith('test', 'test.txt', Test_Share_Backend::FORMAT_SOURCE), + \OCP\Share::getItemSharedWith('test', 'test.txt', Backend::FORMAT_SOURCE), 'Failed asserting that user 2 has access to test.txt after initial sharing.' ); - OC_User::setUserId($this->user3); + \OC_User::setUserId($this->user3); $this->assertContains( 'test.txt', - OCP\Share::getItemSharedWith('test', 'test.txt', Test_Share_Backend::FORMAT_SOURCE), + \OCP\Share::getItemSharedWith('test', 'test.txt', Backend::FORMAT_SOURCE), 'Failed asserting that user 3 has access to test.txt after initial sharing.' ); } @@ -616,11 +618,11 @@ class Test_Share extends \Test\TestCase { * child entries */ public function testShareWithGroupThenUnshare() { - OC_User::setUserId($this->user5); - OCP\Share::shareItem( + \OC_User::setUserId($this->user5); + \OCP\Share::shareItem( 'test', 'test.txt', - OCP\Share::SHARE_TYPE_GROUP, + \OCP\Share::SHARE_TYPE_GROUP, $this->group1, \OCP\Constants::PERMISSION_ALL ); @@ -628,30 +630,30 @@ class Test_Share extends \Test\TestCase { $targetUsers = array($this->user1, $this->user2, $this->user3); foreach($targetUsers as $targetUser) { - OC_User::setUserId($targetUser); - $items = OCP\Share::getItemsSharedWithUser( + \OC_User::setUserId($targetUser); + $items = \OCP\Share::getItemsSharedWithUser( 'test', $targetUser, - Test_Share_Backend::FORMAT_TARGET + Backend::FORMAT_TARGET ); $this->assertEquals(1, count($items)); } - OC_User::setUserId($this->user5); - OCP\Share::unshare( + \OC_User::setUserId($this->user5); + \OCP\Share::unshare( 'test', 'test.txt', - OCP\Share::SHARE_TYPE_GROUP, + \OCP\Share::SHARE_TYPE_GROUP, $this->group1 ); // verify that all were deleted foreach($targetUsers as $targetUser) { - OC_User::setUserId($targetUser); - $items = OCP\Share::getItemsSharedWithUser( + \OC_User::setUserId($targetUser); + $items = \OCP\Share::getItemsSharedWithUser( 'test', $targetUser, - Test_Share_Backend::FORMAT_TARGET + Backend::FORMAT_TARGET ); $this->assertEquals(0, count($items)); } @@ -661,33 +663,33 @@ class Test_Share extends \Test\TestCase { $this->shareUserTestFileWithUser($this->user1, $this->groupAndUser); - OC_User::setUserId($this->groupAndUser); + \OC_User::setUserId($this->groupAndUser); - $this->assertEquals(array('test.txt'), OCP\Share::getItemSharedWith('test', 'test.txt', Test_Share_Backend::FORMAT_SOURCE), + $this->assertEquals(array('test.txt'), \OCP\Share::getItemSharedWith('test', 'test.txt', Backend::FORMAT_SOURCE), '"groupAndUser"-User does not see the file but it was shared with him'); - OC_User::setUserId($this->user2); - $this->assertEquals(array(), OCP\Share::getItemSharedWith('test', 'test.txt', Test_Share_Backend::FORMAT_SOURCE), + \OC_User::setUserId($this->user2); + $this->assertEquals(array(), \OCP\Share::getItemSharedWith('test', 'test.txt', Backend::FORMAT_SOURCE), 'User2 sees test.txt but it was only shared with the user "groupAndUser" and not with group'); - OC_User::setUserId($this->user1); - $this->assertTrue(OCP\Share::unshareAll('test', 'test.txt')); + \OC_User::setUserId($this->user1); + $this->assertTrue(\OCP\Share::unshareAll('test', 'test.txt')); $this->assertTrue( - OCP\Share::shareItem('test', 'test.txt', OCP\Share::SHARE_TYPE_GROUP, $this->groupAndUser, \OCP\Constants::PERMISSION_READ), + \OCP\Share::shareItem('test', 'test.txt', \OCP\Share::SHARE_TYPE_GROUP, $this->groupAndUser, \OCP\Constants::PERMISSION_READ), 'Failed asserting that user 1 successfully shared text.txt with group 1.' ); - OC_User::setUserId($this->groupAndUser); - $this->assertEquals(array(), OCP\Share::getItemSharedWith('test', 'test.txt', Test_Share_Backend::FORMAT_SOURCE), + \OC_User::setUserId($this->groupAndUser); + $this->assertEquals(array(), \OCP\Share::getItemSharedWith('test', 'test.txt', Backend::FORMAT_SOURCE), '"groupAndUser"-User sees test.txt but it was only shared with the group "groupAndUser" and not with the user'); - OC_User::setUserId($this->user2); - $this->assertEquals(array('test.txt'), OCP\Share::getItemSharedWith('test', 'test.txt', Test_Share_Backend::FORMAT_SOURCE), + \OC_User::setUserId($this->user2); + $this->assertEquals(array('test.txt'), \OCP\Share::getItemSharedWith('test', 'test.txt', Backend::FORMAT_SOURCE), 'User2 does not see test.txt but it was shared with the group "groupAndUser"'); - OC_User::setUserId($this->user1); - $this->assertTrue(OCP\Share::unshareAll('test', 'test.txt')); + \OC_User::setUserId($this->user1); + $this->assertTrue(\OCP\Share::unshareAll('test', 'test.txt')); } @@ -696,7 +698,7 @@ class Test_Share extends \Test\TestCase { * @return array */ protected function getShareByValidToken($token) { - $row = OCP\Share::getShareByToken($token); + $row = \OCP\Share::getShareByToken($token); $this->assertInternalType( 'array', $row, @@ -706,21 +708,21 @@ class Test_Share extends \Test\TestCase { } public function testGetItemSharedWithUser() { - OC_User::setUserId($this->user1); + \OC_User::setUserId($this->user1); //add dummy values to the share table $query = \OC_DB::prepare('INSERT INTO `*PREFIX*share` (' .' `item_type`, `item_source`, `item_target`, `share_type`,' .' `share_with`, `uid_owner`) VALUES (?,?,?,?,?,?)'); - $args = array('test', 99, 'target1', OCP\Share::SHARE_TYPE_USER, $this->user2, $this->user1); + $args = array('test', 99, 'target1', \OCP\Share::SHARE_TYPE_USER, $this->user2, $this->user1); $query->execute($args); - $args = array('test', 99, 'target2', OCP\Share::SHARE_TYPE_USER, $this->user4, $this->user1); + $args = array('test', 99, 'target2', \OCP\Share::SHARE_TYPE_USER, $this->user4, $this->user1); $query->execute($args); - $args = array('test', 99, 'target3', OCP\Share::SHARE_TYPE_USER, $this->user3, $this->user2); + $args = array('test', 99, 'target3', \OCP\Share::SHARE_TYPE_USER, $this->user3, $this->user2); $query->execute($args); - $args = array('test', 99, 'target4', OCP\Share::SHARE_TYPE_USER, $this->user3, $this->user4); + $args = array('test', 99, 'target4', \OCP\Share::SHARE_TYPE_USER, $this->user3, $this->user4); $query->execute($args); - $args = array('test', 99, 'target4', OCP\Share::SHARE_TYPE_USER, $this->user6, $this->user4); + $args = array('test', 99, 'target4', \OCP\Share::SHARE_TYPE_USER, $this->user6, $this->user4); $query->execute($args); @@ -746,19 +748,19 @@ class Test_Share extends \Test\TestCase { } public function testGetItemSharedWithUserFromGroupShare() { - OC_User::setUserId($this->user1); + \OC_User::setUserId($this->user1); //add dummy values to the share table $query = \OC_DB::prepare('INSERT INTO `*PREFIX*share` (' .' `item_type`, `item_source`, `item_target`, `share_type`,' .' `share_with`, `uid_owner`) VALUES (?,?,?,?,?,?)'); - $args = array('test', 99, 'target1', OCP\Share::SHARE_TYPE_GROUP, $this->group1, $this->user1); + $args = array('test', 99, 'target1', \OCP\Share::SHARE_TYPE_GROUP, $this->group1, $this->user1); $query->execute($args); - $args = array('test', 99, 'target2', OCP\Share::SHARE_TYPE_GROUP, $this->group2, $this->user1); + $args = array('test', 99, 'target2', \OCP\Share::SHARE_TYPE_GROUP, $this->group2, $this->user1); $query->execute($args); - $args = array('test', 99, 'target3', OCP\Share::SHARE_TYPE_GROUP, $this->group1, $this->user2); + $args = array('test', 99, 'target3', \OCP\Share::SHARE_TYPE_GROUP, $this->group1, $this->user2); $query->execute($args); - $args = array('test', 99, 'target4', OCP\Share::SHARE_TYPE_GROUP, $this->group1, $this->user4); + $args = array('test', 99, 'target4', \OCP\Share::SHARE_TYPE_GROUP, $this->group1, $this->user4); $query->execute($args); // user2 is in group1 and group2 @@ -794,7 +796,7 @@ class Test_Share extends \Test\TestCase { } public function testGetShareSubItemsWhenUserNotInGroup() { - OCP\Share::shareItem('test', 'test.txt', OCP\Share::SHARE_TYPE_GROUP, $this->group1, \OCP\Constants::PERMISSION_READ); + \OCP\Share::shareItem('test', 'test.txt', \OCP\Share::SHARE_TYPE_GROUP, $this->group1, \OCP\Constants::PERMISSION_READ); $result = \OCP\Share::getItemsSharedWithUser('test', $this->user2); $this->assertCount(1, $result); @@ -831,8 +833,8 @@ class Test_Share extends \Test\TestCase { } public function testShareItemWithLink() { - OC_User::setUserId($this->user1); - $token = OCP\Share::shareItem('test', 'test.txt', OCP\Share::SHARE_TYPE_LINK, null, \OCP\Constants::PERMISSION_READ); + \OC_User::setUserId($this->user1); + $token = \OCP\Share::shareItem('test', 'test.txt', \OCP\Share::SHARE_TYPE_LINK, null, \OCP\Constants::PERMISSION_READ); $this->assertInternalType( 'string', $token, @@ -848,7 +850,7 @@ class Test_Share extends \Test\TestCase { // testGetShareByTokenExpirationValid $this->assertTrue( - OCP\Share::setExpirationDate('test', 'test.txt', $this->dateInFuture, ''), + \OCP\Share::setExpirationDate('test', 'test.txt', $this->dateInFuture, ''), 'Failed asserting that user 1 successfully set a future expiration date for the test.txt share.' ); $row = $this->getShareByValidToken($token); @@ -867,20 +869,20 @@ class Test_Share extends \Test\TestCase { $query->execute(); $this->assertFalse( - OCP\Share::getShareByToken($token), + \OCP\Share::getShareByToken($token), 'Failed asserting that an expired share could not be found.' ); } public function testShareItemWithLinkAndDefaultExpireDate() { - OC_User::setUserId($this->user1); + \OC_User::setUserId($this->user1); $config = \OC::$server->getConfig(); $config->setAppValue('core', 'shareapi_default_expire_date', 'yes'); $config->setAppValue('core', 'shareapi_expire_after_n_days', '2'); - $token = OCP\Share::shareItem('test', 'test.txt', OCP\Share::SHARE_TYPE_LINK, null, \OCP\Constants::PERMISSION_READ); + $token = \OCP\Share::shareItem('test', 'test.txt', \OCP\Share::SHARE_TYPE_LINK, null, \OCP\Constants::PERMISSION_READ); $this->assertInternalType( 'string', $token, @@ -925,8 +927,8 @@ class Test_Share extends \Test\TestCase { * @expectedException \OC\HintException */ public function testShareWithRemoteUserAndRemoteIsInvalid($remoteId) { - OC_User::setUserId($this->user1); - OCP\Share::shareItem('test', 'test.txt', OCP\Share::SHARE_TYPE_REMOTE, $remoteId, \OCP\Constants::PERMISSION_ALL); + \OC_User::setUserId($this->user1); + \OCP\Share::shareItem('test', 'test.txt', \OCP\Share::SHARE_TYPE_REMOTE, $remoteId, \OCP\Constants::PERMISSION_ALL); } public function testUnshareAll() { @@ -935,49 +937,49 @@ class Test_Share extends \Test\TestCase { $this->shareUserTestFileWithUser($this->user3, $this->user4); $this->shareUserOneTestFileWithGroupOne(); - OC_User::setUserId($this->user1); + \OC_User::setUserId($this->user1); $this->assertEquals( array('test.txt', 'test.txt'), - OCP\Share::getItemsShared('test', Test_Share_Backend::FORMAT_SOURCE), + \OCP\Share::getItemsShared('test', Backend::FORMAT_SOURCE), 'Failed asserting that the test.txt file is shared exactly two times by user1.' ); - OC_User::setUserId($this->user2); + \OC_User::setUserId($this->user2); $this->assertEquals( array('test.txt'), - OCP\Share::getItemsShared('test', Test_Share_Backend::FORMAT_SOURCE), + \OCP\Share::getItemsShared('test', Backend::FORMAT_SOURCE), 'Failed asserting that the test.txt file is shared exactly once by user2.' ); - OC_User::setUserId($this->user3); + \OC_User::setUserId($this->user3); $this->assertEquals( array('test.txt'), - OCP\Share::getItemsShared('test', Test_Share_Backend::FORMAT_SOURCE), + \OCP\Share::getItemsShared('test', Backend::FORMAT_SOURCE), 'Failed asserting that the test.txt file is shared exactly once by user3.' ); $this->assertTrue( - OCP\Share::unshareAll('test', 'test.txt'), + \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'), + \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); + \OC_User::setUserId($this->user1); $this->assertEquals( array(), - OCP\Share::getItemsShared('test'), + \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); + \OC_User::setUserId($this->user2); $this->assertEquals( array(), - OCP\Share::getItemsShared('test'), + \OCP\Share::getItemsShared('test'), 'Failed asserting that the share of the test.txt file by user 2 has been removed.' ); } @@ -1154,13 +1156,13 @@ class Test_Share extends \Test\TestCase { * is enforced by the settings. */ public function testClearExpireDateWhileEnforced() { - OC_User::setUserId($this->user1); + \OC_User::setUserId($this->user1); \OC::$server->getAppConfig()->setValue('core', 'shareapi_default_expire_date', 'yes'); \OC::$server->getAppConfig()->setValue('core', 'shareapi_expire_after_n_days', '2'); \OC::$server->getAppConfig()->setValue('core', 'shareapi_enforce_expire_date', 'yes'); - $token = OCP\Share::shareItem('test', 'test.txt', OCP\Share::SHARE_TYPE_LINK, null, \OCP\Constants::PERMISSION_READ); + $token = \OCP\Share::shareItem('test', 'test.txt', \OCP\Share::SHARE_TYPE_LINK, null, \OCP\Constants::PERMISSION_READ); $this->assertInternalType( 'string', $token, @@ -1170,7 +1172,7 @@ class Test_Share extends \Test\TestCase { $setExpireDateFailed = false; try { $this->assertTrue( - OCP\Share::setExpirationDate('test', 'test.txt', '', ''), + \OCP\Share::setExpirationDate('test', 'test.txt', '', ''), 'Failed asserting that user 1 successfully set an expiration date for the test.txt share.' ); } catch (\Exception $e) { @@ -1187,7 +1189,7 @@ class Test_Share extends \Test\TestCase { /** * Cannot set password is there is no user * - * @expectedException Exception + * @expectedException \Exception * @expectedExceptionMessage User not logged in */ public function testSetPasswordNoUser() { @@ -1305,7 +1307,7 @@ class Test_Share extends \Test\TestCase { } /** - * @expectedException Exception + * @expectedException \Exception * @expectedExceptionMessage Cannot remove password * * Test removing a password when password is enforced @@ -1358,7 +1360,7 @@ class Test_Share extends \Test\TestCase { } /** - * @expectedException Exception + * @expectedException \Exception * @expectedExceptionMessage Share not found * * Test modification of invaid share @@ -1411,7 +1413,7 @@ class Test_Share extends \Test\TestCase { } /** - * @expectedException Exception + * @expectedException \Exception * @expectedExceptionMessage Cannot update share of a different user * * Test modification of share of another user @@ -1509,7 +1511,7 @@ class Test_Share extends \Test\TestCase { // Expiration date $expireAt = time() + 2 * 24*60*60; - $date = new DateTime(); + $date = new \DateTime(); $date->setTimestamp($expireAt); $date->setTime(0, 0, 0); @@ -1517,20 +1519,20 @@ class Test_Share extends \Test\TestCase { $this->shareUserTestFileWithUser($this->user1, $this->user2); //User 2 shares as link - OC_User::setUserId($this->user2); - $result = OCP\Share::shareItem('test', 'test.txt', OCP\Share::SHARE_TYPE_LINK, null, \OCP\Constants::PERMISSION_READ); + \OC_User::setUserId($this->user2); + $result = \OCP\Share::shareItem('test', 'test.txt', \OCP\Share::SHARE_TYPE_LINK, null, \OCP\Constants::PERMISSION_READ); $this->assertTrue(is_string($result)); //Check if expire date is correct - $result = OCP\Share::getItemShared('test', 'test.txt'); + $result = \OCP\Share::getItemShared('test', 'test.txt'); $this->assertCount(1, $result); $result = reset($result); $this->assertNotEmpty($result['expiration']); - $expireDate = new DateTime($result['expiration']); + $expireDate = new \DateTime($result['expiration']); $this->assertEquals($date, $expireDate); //Unshare - $this->assertTrue(OCP\Share::unshareAll('test', 'test.txt')); + $this->assertTrue(\OCP\Share::unshareAll('test', 'test.txt')); //Reset config $config->deleteAppValue('core', 'shareapi_default_expire_date'); @@ -1541,7 +1543,7 @@ class Test_Share extends \Test\TestCase { * Test case for #17560 */ public function testAccesToSharedSubFolder() { - OC_User::setUserId($this->user1); + \OC_User::setUserId($this->user1); $view = new \OC\Files\View('/' . $this->user1 . '/'); $view->mkdir('files/folder1'); @@ -1550,11 +1552,11 @@ class Test_Share extends \Test\TestCase { $fileId = $fileInfo->getId(); $this->assertTrue( - OCP\Share::shareItem('folder', $fileId, OCP\Share::SHARE_TYPE_USER, $this->user2, \OCP\Constants::PERMISSION_ALL), + \OCP\Share::shareItem('folder', $fileId, \OCP\Share::SHARE_TYPE_USER, $this->user2, \OCP\Constants::PERMISSION_ALL), 'Failed asserting that user 1 successfully shared "test" with user 2.' ); $this->assertTrue( - OCP\Share::shareItem('folder', $fileId, OCP\Share::SHARE_TYPE_USER, $this->user3, \OCP\Constants::PERMISSION_ALL), + \OCP\Share::shareItem('folder', $fileId, \OCP\Share::SHARE_TYPE_USER, $this->user3, \OCP\Constants::PERMISSION_ALL), 'Failed asserting that user 1 successfully shared "test" with user 3.' ); @@ -1565,28 +1567,28 @@ class Test_Share extends \Test\TestCase { $fileId = $fileInfo->getId(); $this->assertTrue( - OCP\Share::shareItem('folder', $fileId, OCP\Share::SHARE_TYPE_USER, $this->user4, \OCP\Constants::PERMISSION_ALL), + \OCP\Share::shareItem('folder', $fileId, \OCP\Share::SHARE_TYPE_USER, $this->user4, \OCP\Constants::PERMISSION_ALL), 'Failed asserting that user 1 successfully shared "test" with user 4.' ); - $res = OCP\Share::getItemShared( + $res = \OCP\Share::getItemShared( 'folder', $fileId, - OCP\Share::FORMAT_NONE, + \OCP\Share::FORMAT_NONE, null, true ); $this->assertCount(3, $res); $this->assertTrue( - OCP\Share::shareItem('folder', $fileId, OCP\Share::SHARE_TYPE_USER, $this->user5, \OCP\Constants::PERMISSION_ALL), + \OCP\Share::shareItem('folder', $fileId, \OCP\Share::SHARE_TYPE_USER, $this->user5, \OCP\Constants::PERMISSION_ALL), 'Failed asserting that user 1 successfully shared "test" with user 5.' ); - $res = OCP\Share::getItemShared( + $res = \OCP\Share::getItemShared( 'folder', $fileId, - OCP\Share::FORMAT_NONE, + \OCP\Share::FORMAT_NONE, null, true ); @@ -1594,7 +1596,7 @@ class Test_Share extends \Test\TestCase { } public function testShareWithSelfError() { - OC_User::setUserId($this->user1); + \OC_User::setUserId($this->user1); $view = new \OC\Files\View('/' . $this->user1 . '/'); $view->mkdir('files/folder1'); @@ -1603,7 +1605,7 @@ class Test_Share extends \Test\TestCase { $fileId = $fileInfo->getId(); try { - OCP\Share::shareItem('folder', $fileId, OCP\Share::SHARE_TYPE_USER, $this->user1, \OCP\Constants::PERMISSION_ALL); + \OCP\Share::shareItem('folder', $fileId, \OCP\Share::SHARE_TYPE_USER, $this->user1, \OCP\Constants::PERMISSION_ALL); $this->fail(); } catch (\Exception $e) { $this->assertEquals('Sharing /folder1 failed, because you can not share with yourself', $e->getMessage()); @@ -1612,7 +1614,7 @@ class Test_Share extends \Test\TestCase { public function testShareWithOwnerError() { - OC_User::setUserId($this->user1); + \OC_User::setUserId($this->user1); $view = new \OC\Files\View('/' . $this->user1 . '/'); $view->mkdir('files/folder1'); @@ -1621,13 +1623,13 @@ class Test_Share extends \Test\TestCase { $fileId = $fileInfo->getId(); $this->assertTrue( - OCP\Share::shareItem('folder', $fileId, OCP\Share::SHARE_TYPE_USER, $this->user2, \OCP\Constants::PERMISSION_ALL), + \OCP\Share::shareItem('folder', $fileId, \OCP\Share::SHARE_TYPE_USER, $this->user2, \OCP\Constants::PERMISSION_ALL), 'Failed asserting that user 1 successfully shared "test" with user 2.' ); - OC_User::setUserId($this->user2); + \OC_User::setUserId($this->user2); try { - OCP\Share::shareItem('folder', $fileId, OCP\Share::SHARE_TYPE_USER, $this->user1, \OCP\Constants::PERMISSION_ALL); + \OCP\Share::shareItem('folder', $fileId, \OCP\Share::SHARE_TYPE_USER, $this->user1, \OCP\Constants::PERMISSION_ALL); $this->fail(); } catch (\Exception $e) { $this->assertEquals('Sharing failed, because the user ' . $this->user1 . ' is the original sharer', $e->getMessage()); -- cgit v1.2.3 From 7f3f16d1554bd2adbe3287fbf09a1124664f54af Mon Sep 17 00:00:00 2001 From: Joas Schilling Date: Thu, 19 May 2016 09:17:54 +0200 Subject: Fix namespace in user/ --- tests/lib/updater/VersionCheckTest.php | 261 +++++++++++++++++++++++++++++++++ tests/lib/updater/versioncheck.php | 261 --------------------------------- tests/lib/user/avataruserdummy.php | 6 +- tests/lib/user/backend.php | 4 +- tests/lib/user/database.php | 4 +- tests/lib/user/dummy.php | 4 +- 6 files changed, 274 insertions(+), 266 deletions(-) create mode 100644 tests/lib/updater/VersionCheckTest.php delete mode 100644 tests/lib/updater/versioncheck.php (limited to 'tests') diff --git a/tests/lib/updater/VersionCheckTest.php b/tests/lib/updater/VersionCheckTest.php new file mode 100644 index 00000000000..13851338eef --- /dev/null +++ b/tests/lib/updater/VersionCheckTest.php @@ -0,0 +1,261 @@ + + * @author Victor Dubiniuk + * + * @copyright Copyright (c) 2015, ownCloud, Inc. + * @license AGPL-3.0 + * + * This code is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License, version 3, + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License, version 3, + * along with this program. If not, see + * + */ + +namespace Test\Update; + +use OC\Updater\VersionCheck; +use OCP\IConfig; +use OCP\Util; + +class VersionCheckTest extends \Test\TestCase { + /** @var IConfig| \PHPUnit_Framework_MockObject_MockObject */ + private $config; + /** @var VersionCheck | \PHPUnit_Framework_MockObject_MockObject*/ + private $updater; + + public function setUp() { + parent::setUp(); + $this->config = $this->getMockBuilder('\OCP\IConfig') + ->disableOriginalConstructor() + ->getMock(); + $clientService = $this->getMockBuilder('\OCP\Http\Client\IClientService') + ->disableOriginalConstructor() + ->getMock(); + + $this->updater = $this->getMock('\OC\Updater\VersionCheck', + ['getUrlContent'], [$clientService, $this->config]); + } + + /** + * @param string $baseUrl + * @return string + */ + private function buildUpdateUrl($baseUrl) { + return $baseUrl . '?version='.implode('x', Util::getVersion()).'xinstalledatxlastupdatedatx'.\OC_Util::getChannel().'x'.\OC_Util::getEditionString().'x'; + } + + public function testCheckInCache() { + $expectedResult = [ + 'version' => '8.0.4.2', + 'versionstring' => 'ownCloud 8.0.4', + 'url' => 'https://download.owncloud.org/community/owncloud-8.0.4.zip', + 'web' => 'http://doc.owncloud.org/server/8.0/admin_manual/maintenance/upgrade.html', + ]; + + $this->config + ->expects($this->at(0)) + ->method('getAppValue') + ->with('core', 'lastupdatedat') + ->will($this->returnValue(time())); + $this->config + ->expects($this->at(1)) + ->method('getAppValue') + ->with('core', 'lastupdateResult') + ->will($this->returnValue(json_encode($expectedResult))); + + $this->assertSame($expectedResult, $this->updater->check()); + } + + public function testCheckWithoutUpdateUrl() { + $expectedResult = [ + 'version' => '8.0.4.2', + 'versionstring' => 'ownCloud 8.0.4', + 'url' => 'https://download.owncloud.org/community/owncloud-8.0.4.zip', + 'web' => 'http://doc.owncloud.org/server/8.0/admin_manual/maintenance/upgrade.html', + ]; + + $this->config + ->expects($this->at(0)) + ->method('getAppValue') + ->with('core', 'lastupdatedat') + ->will($this->returnValue(0)); + $this->config + ->expects($this->at(1)) + ->method('getSystemValue') + ->with('updater.server.url', 'https://updates.owncloud.com/server/') + ->willReturn('https://updates.owncloud.com/server/'); + $this->config + ->expects($this->at(2)) + ->method('setAppValue') + ->with('core', 'lastupdatedat', $this->isType('integer')); + $this->config + ->expects($this->at(4)) + ->method('getAppValue') + ->with('core', 'installedat') + ->will($this->returnValue('installedat')); + $this->config + ->expects($this->at(5)) + ->method('getAppValue') + ->with('core', 'lastupdatedat') + ->will($this->returnValue('lastupdatedat')); + $this->config + ->expects($this->at(6)) + ->method('setAppValue') + ->with('core', 'lastupdateResult', json_encode($expectedResult)); + + $updateXml = ' + + 8.0.4.2 + ownCloud 8.0.4 + https://download.owncloud.org/community/owncloud-8.0.4.zip + http://doc.owncloud.org/server/8.0/admin_manual/maintenance/upgrade.html +'; + $this->updater + ->expects($this->once()) + ->method('getUrlContent') + ->with($this->buildUpdateUrl('https://updates.owncloud.com/server/')) + ->will($this->returnValue($updateXml)); + + $this->assertSame($expectedResult, $this->updater->check()); + } + + public function testCheckWithInvalidXml() { + $this->config + ->expects($this->at(0)) + ->method('getAppValue') + ->with('core', 'lastupdatedat') + ->will($this->returnValue(0)); + $this->config + ->expects($this->at(1)) + ->method('getSystemValue') + ->with('updater.server.url', 'https://updates.owncloud.com/server/') + ->willReturn('https://updates.owncloud.com/server/'); + $this->config + ->expects($this->at(2)) + ->method('setAppValue') + ->with('core', 'lastupdatedat', $this->isType('integer')); + $this->config + ->expects($this->at(4)) + ->method('getAppValue') + ->with('core', 'installedat') + ->will($this->returnValue('installedat')); + $this->config + ->expects($this->at(5)) + ->method('getAppValue') + ->with('core', 'lastupdatedat') + ->will($this->returnValue('lastupdatedat')); + $this->config + ->expects($this->at(6)) + ->method('setAppValue') + ->with('core', 'lastupdateResult', 'false'); + + $updateXml = 'Invalid XML Response!'; + $this->updater + ->expects($this->once()) + ->method('getUrlContent') + ->with($this->buildUpdateUrl('https://updates.owncloud.com/server/')) + ->will($this->returnValue($updateXml)); + + $this->assertSame([], $this->updater->check()); + } + + public function testCheckWithEmptyValidXmlResponse() { + $expectedResult = [ + 'version' => '', + 'versionstring' => '', + 'url' => '', + 'web' => '', + ]; + + $this->config + ->expects($this->at(0)) + ->method('getAppValue') + ->with('core', 'lastupdatedat') + ->will($this->returnValue(0)); + $this->config + ->expects($this->at(1)) + ->method('getSystemValue') + ->with('updater.server.url', 'https://updates.owncloud.com/server/') + ->willReturn('https://updates.owncloud.com/server/'); + $this->config + ->expects($this->at(2)) + ->method('setAppValue') + ->with('core', 'lastupdatedat', $this->isType('integer')); + $this->config + ->expects($this->at(4)) + ->method('getAppValue') + ->with('core', 'installedat') + ->will($this->returnValue('installedat')); + $this->config + ->expects($this->at(5)) + ->method('getAppValue') + ->with('core', 'lastupdatedat') + ->will($this->returnValue('lastupdatedat')); + + $updateXml = ' + + + + + +'; + $this->updater + ->expects($this->once()) + ->method('getUrlContent') + ->with($this->buildUpdateUrl('https://updates.owncloud.com/server/')) + ->will($this->returnValue($updateXml)); + + $this->assertSame($expectedResult, $this->updater->check()); + } + + public function testCheckWithEmptyInvalidXmlResponse() { + $expectedResult = []; + + $this->config + ->expects($this->at(0)) + ->method('getAppValue') + ->with('core', 'lastupdatedat') + ->will($this->returnValue(0)); + $this->config + ->expects($this->at(1)) + ->method('getSystemValue') + ->with('updater.server.url', 'https://updates.owncloud.com/server/') + ->willReturn('https://updates.owncloud.com/server/'); + $this->config + ->expects($this->at(2)) + ->method('setAppValue') + ->with('core', 'lastupdatedat', $this->isType('integer')); + $this->config + ->expects($this->at(4)) + ->method('getAppValue') + ->with('core', 'installedat') + ->will($this->returnValue('installedat')); + $this->config + ->expects($this->at(5)) + ->method('getAppValue') + ->with('core', 'lastupdatedat') + ->will($this->returnValue('lastupdatedat')); + $this->config + ->expects($this->at(6)) + ->method('setAppValue') + ->with('core', 'lastupdateResult', json_encode($expectedResult)); + + $updateXml = ''; + $this->updater + ->expects($this->once()) + ->method('getUrlContent') + ->with($this->buildUpdateUrl('https://updates.owncloud.com/server/')) + ->will($this->returnValue($updateXml)); + + $this->assertSame($expectedResult, $this->updater->check()); + } +} diff --git a/tests/lib/updater/versioncheck.php b/tests/lib/updater/versioncheck.php deleted file mode 100644 index 2122ca28800..00000000000 --- a/tests/lib/updater/versioncheck.php +++ /dev/null @@ -1,261 +0,0 @@ - - * @author Victor Dubiniuk - * - * @copyright Copyright (c) 2015, ownCloud, Inc. - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see - * - */ - -namespace OC; - -use OC\Updater\VersionCheck; -use OCP\IConfig; -use OCP\Util; - -class VersionCheckTest extends \Test\TestCase { - /** @var IConfig| \PHPUnit_Framework_MockObject_MockObject */ - private $config; - /** @var VersionCheck | \PHPUnit_Framework_MockObject_MockObject*/ - private $updater; - - public function setUp() { - parent::setUp(); - $this->config = $this->getMockBuilder('\OCP\IConfig') - ->disableOriginalConstructor() - ->getMock(); - $clientService = $this->getMockBuilder('\OCP\Http\Client\IClientService') - ->disableOriginalConstructor() - ->getMock(); - - $this->updater = $this->getMock('\OC\Updater\VersionCheck', - ['getUrlContent'], [$clientService, $this->config]); - } - - /** - * @param string $baseUrl - * @return string - */ - private function buildUpdateUrl($baseUrl) { - return $baseUrl . '?version='.implode('x', Util::getVersion()).'xinstalledatxlastupdatedatx'.\OC_Util::getChannel().'x'.\OC_Util::getEditionString().'x'; - } - - public function testCheckInCache() { - $expectedResult = [ - 'version' => '8.0.4.2', - 'versionstring' => 'ownCloud 8.0.4', - 'url' => 'https://download.owncloud.org/community/owncloud-8.0.4.zip', - 'web' => 'http://doc.owncloud.org/server/8.0/admin_manual/maintenance/upgrade.html', - ]; - - $this->config - ->expects($this->at(0)) - ->method('getAppValue') - ->with('core', 'lastupdatedat') - ->will($this->returnValue(time())); - $this->config - ->expects($this->at(1)) - ->method('getAppValue') - ->with('core', 'lastupdateResult') - ->will($this->returnValue(json_encode($expectedResult))); - - $this->assertSame($expectedResult, $this->updater->check()); - } - - public function testCheckWithoutUpdateUrl() { - $expectedResult = [ - 'version' => '8.0.4.2', - 'versionstring' => 'ownCloud 8.0.4', - 'url' => 'https://download.owncloud.org/community/owncloud-8.0.4.zip', - 'web' => 'http://doc.owncloud.org/server/8.0/admin_manual/maintenance/upgrade.html', - ]; - - $this->config - ->expects($this->at(0)) - ->method('getAppValue') - ->with('core', 'lastupdatedat') - ->will($this->returnValue(0)); - $this->config - ->expects($this->at(1)) - ->method('getSystemValue') - ->with('updater.server.url', 'https://updates.owncloud.com/server/') - ->willReturn('https://updates.owncloud.com/server/'); - $this->config - ->expects($this->at(2)) - ->method('setAppValue') - ->with('core', 'lastupdatedat', $this->isType('integer')); - $this->config - ->expects($this->at(4)) - ->method('getAppValue') - ->with('core', 'installedat') - ->will($this->returnValue('installedat')); - $this->config - ->expects($this->at(5)) - ->method('getAppValue') - ->with('core', 'lastupdatedat') - ->will($this->returnValue('lastupdatedat')); - $this->config - ->expects($this->at(6)) - ->method('setAppValue') - ->with('core', 'lastupdateResult', json_encode($expectedResult)); - - $updateXml = ' - - 8.0.4.2 - ownCloud 8.0.4 - https://download.owncloud.org/community/owncloud-8.0.4.zip - http://doc.owncloud.org/server/8.0/admin_manual/maintenance/upgrade.html -'; - $this->updater - ->expects($this->once()) - ->method('getUrlContent') - ->with($this->buildUpdateUrl('https://updates.owncloud.com/server/')) - ->will($this->returnValue($updateXml)); - - $this->assertSame($expectedResult, $this->updater->check()); - } - - public function testCheckWithInvalidXml() { - $this->config - ->expects($this->at(0)) - ->method('getAppValue') - ->with('core', 'lastupdatedat') - ->will($this->returnValue(0)); - $this->config - ->expects($this->at(1)) - ->method('getSystemValue') - ->with('updater.server.url', 'https://updates.owncloud.com/server/') - ->willReturn('https://updates.owncloud.com/server/'); - $this->config - ->expects($this->at(2)) - ->method('setAppValue') - ->with('core', 'lastupdatedat', $this->isType('integer')); - $this->config - ->expects($this->at(4)) - ->method('getAppValue') - ->with('core', 'installedat') - ->will($this->returnValue('installedat')); - $this->config - ->expects($this->at(5)) - ->method('getAppValue') - ->with('core', 'lastupdatedat') - ->will($this->returnValue('lastupdatedat')); - $this->config - ->expects($this->at(6)) - ->method('setAppValue') - ->with('core', 'lastupdateResult', 'false'); - - $updateXml = 'Invalid XML Response!'; - $this->updater - ->expects($this->once()) - ->method('getUrlContent') - ->with($this->buildUpdateUrl('https://updates.owncloud.com/server/')) - ->will($this->returnValue($updateXml)); - - $this->assertSame([], $this->updater->check()); - } - - public function testCheckWithEmptyValidXmlResponse() { - $expectedResult = [ - 'version' => '', - 'versionstring' => '', - 'url' => '', - 'web' => '', - ]; - - $this->config - ->expects($this->at(0)) - ->method('getAppValue') - ->with('core', 'lastupdatedat') - ->will($this->returnValue(0)); - $this->config - ->expects($this->at(1)) - ->method('getSystemValue') - ->with('updater.server.url', 'https://updates.owncloud.com/server/') - ->willReturn('https://updates.owncloud.com/server/'); - $this->config - ->expects($this->at(2)) - ->method('setAppValue') - ->with('core', 'lastupdatedat', $this->isType('integer')); - $this->config - ->expects($this->at(4)) - ->method('getAppValue') - ->with('core', 'installedat') - ->will($this->returnValue('installedat')); - $this->config - ->expects($this->at(5)) - ->method('getAppValue') - ->with('core', 'lastupdatedat') - ->will($this->returnValue('lastupdatedat')); - - $updateXml = ' - - - - - -'; - $this->updater - ->expects($this->once()) - ->method('getUrlContent') - ->with($this->buildUpdateUrl('https://updates.owncloud.com/server/')) - ->will($this->returnValue($updateXml)); - - $this->assertSame($expectedResult, $this->updater->check()); - } - - public function testCheckWithEmptyInvalidXmlResponse() { - $expectedResult = []; - - $this->config - ->expects($this->at(0)) - ->method('getAppValue') - ->with('core', 'lastupdatedat') - ->will($this->returnValue(0)); - $this->config - ->expects($this->at(1)) - ->method('getSystemValue') - ->with('updater.server.url', 'https://updates.owncloud.com/server/') - ->willReturn('https://updates.owncloud.com/server/'); - $this->config - ->expects($this->at(2)) - ->method('setAppValue') - ->with('core', 'lastupdatedat', $this->isType('integer')); - $this->config - ->expects($this->at(4)) - ->method('getAppValue') - ->with('core', 'installedat') - ->will($this->returnValue('installedat')); - $this->config - ->expects($this->at(5)) - ->method('getAppValue') - ->with('core', 'lastupdatedat') - ->will($this->returnValue('lastupdatedat')); - $this->config - ->expects($this->at(6)) - ->method('setAppValue') - ->with('core', 'lastupdateResult', json_encode($expectedResult)); - - $updateXml = ''; - $this->updater - ->expects($this->once()) - ->method('getUrlContent') - ->with($this->buildUpdateUrl('https://updates.owncloud.com/server/')) - ->will($this->returnValue($updateXml)); - - $this->assertSame($expectedResult, $this->updater->check()); - } -} diff --git a/tests/lib/user/avataruserdummy.php b/tests/lib/user/avataruserdummy.php index 086adb6043f..123825de50f 100644 --- a/tests/lib/user/avataruserdummy.php +++ b/tests/lib/user/avataruserdummy.php @@ -20,8 +20,10 @@ * */ -class Avatar_User_Dummy extends \Test\Util\User\Dummy { +namespace Test\User; + +class AvatarUserDummy extends \Test\Util\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 d5bbbe9f406..85ccbac913c 100644 --- a/tests/lib/user/backend.php +++ b/tests/lib/user/backend.php @@ -20,6 +20,8 @@ * */ +namespace Test\User; + /** * Abstract class to provide the basis of backend-specific unit test classes. * @@ -30,7 +32,7 @@ * For an example see /tests/lib/user/dummy.php */ -abstract class Test_User_Backend extends \Test\TestCase { +abstract class Backend extends \Test\TestCase { /** * @var \OC\User\Backend $backend */ diff --git a/tests/lib/user/database.php b/tests/lib/user/database.php index 0dea037ad78..76d6226a7fd 100644 --- a/tests/lib/user/database.php +++ b/tests/lib/user/database.php @@ -20,12 +20,14 @@ * */ +namespace Test\User; + /** * Class Test_User_Database * * @group DB */ -class Test_User_Database extends Test_User_Backend { +class Database extends Backend { /** @var array */ private $users; diff --git a/tests/lib/user/dummy.php b/tests/lib/user/dummy.php index c6c79d7a860..50382aa8fe6 100644 --- a/tests/lib/user/dummy.php +++ b/tests/lib/user/dummy.php @@ -20,7 +20,9 @@ * */ -class Test_User_Dummy extends Test_User_Backend { +namespace Test\User; + +class Dummy extends Backend { protected function setUp() { parent::setUp(); $this->backend=new \Test\Util\User\Dummy(); -- cgit v1.2.3 From 55fc6536d33bd044a72437ac61d3c5ade09111cb Mon Sep 17 00:00:00 2001 From: Joas Schilling Date: Thu, 19 May 2016 09:27:21 +0200 Subject: FIx lib/ a-d --- tests/lib/APITest.php | 199 ++++++++++++ tests/lib/AllConfigTest.php | 419 ++++++++++++++++++++++++++ tests/lib/AppTest.php | 549 ++++++++++++++++++++++++++++++++++ tests/lib/CapabilitiesManagerTest.php | 162 ++++++++++ tests/lib/ConfigTest.php | 142 +++++++++ tests/lib/ContactsManagerTest.php | 210 +++++++++++++ tests/lib/ErrorHandlerTest.php | 68 +++++ tests/lib/allconfig.php | 419 -------------------------- tests/lib/api.php | 197 ------------ tests/lib/app.php | 546 --------------------------------- tests/lib/appconfig.php | 6 +- tests/lib/avatarmanagertest.php | 5 +- tests/lib/avatartest.php | 19 +- tests/lib/capabilitiesmanager.php | 164 ---------- tests/lib/configtests.php | 142 --------- tests/lib/contactsmanager.php | 209 ------------- tests/lib/db.php | 389 ------------------------ tests/lib/db/DBSchemaTest.php | 107 +++++++ tests/lib/db/LegacyDBTest.php | 393 ++++++++++++++++++++++++ tests/lib/dbschema.php | 105 ------- tests/lib/errorHandler.php | 66 ---- 21 files changed, 2265 insertions(+), 2251 deletions(-) create mode 100644 tests/lib/APITest.php create mode 100644 tests/lib/AllConfigTest.php create mode 100644 tests/lib/AppTest.php create mode 100644 tests/lib/CapabilitiesManagerTest.php create mode 100644 tests/lib/ConfigTest.php create mode 100644 tests/lib/ContactsManagerTest.php create mode 100644 tests/lib/ErrorHandlerTest.php delete mode 100644 tests/lib/allconfig.php delete mode 100644 tests/lib/api.php delete mode 100644 tests/lib/app.php delete mode 100644 tests/lib/capabilitiesmanager.php delete mode 100644 tests/lib/configtests.php delete mode 100644 tests/lib/contactsmanager.php delete mode 100644 tests/lib/db.php create mode 100644 tests/lib/db/DBSchemaTest.php create mode 100644 tests/lib/db/LegacyDBTest.php delete mode 100644 tests/lib/dbschema.php delete mode 100644 tests/lib/errorHandler.php (limited to 'tests') diff --git a/tests/lib/APITest.php b/tests/lib/APITest.php new file mode 100644 index 00000000000..d3ab6db9e4b --- /dev/null +++ b/tests/lib/APITest.php @@ -0,0 +1,199 @@ + + * This file is licensed under the Affero General Public License version 3 or + * later. + * See the COPYING-README file. + */ + +namespace Test; + +class APITest extends \Test\TestCase { + + // Helps build a response variable + + /** + * @param string $message + */ + function buildResponse($shipped, $data, $code, $message=null) { + $resp = new \OC_OCS_Result($data, $code, $message); + $resp->addHeader('KEY', 'VALUE'); + return [ + 'shipped' => $shipped, + 'response' => $resp, + 'app' => $this->getUniqueID('testapp_'), + ]; + } + + // Validate details of the result + + /** + * @param \OC_OCS_Result $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()); + } + + /** + * @return array + */ + public function versionDataScriptNameProvider() { + return [ + // Valid script name + [ + '/master/ocs/v2.php', + true, + ], + + // Invalid script names + [ + '/master/ocs/v2.php/someInvalidPathName', + false, + ], + [ + '/master/ocs/v1.php', + false, + ], + [ + '', + false, + ], + ]; + } + + /** + * @dataProvider versionDataScriptNameProvider + * @param string $scriptName + * @param bool $expected + */ + public function testIsV2($scriptName, $expected) { + $request = $this->getMockBuilder('\OCP\IRequest') + ->disableOriginalConstructor() + ->getMock(); + $request + ->expects($this->once()) + ->method('getScriptName') + ->will($this->returnValue($scriptName)); + + $this->assertEquals($expected, $this->invokePrivate(new \OC_API, 'isV2', [$request])); + } + + function dataProviderTestOneResult() { + return [ + [100, true], + [101, false], + [997, false], + ]; + } + + /** + * @dataProvider dataProviderTestOneResult + * + * @param $statusCode + * @param $succeeded + */ + public function testOneResult($statusCode, $succeeded) { + // Setup some data arrays + $data1 = [ + 'users' => [ + 'tom' => [ + 'key' => 'value', + ], + 'frank' => [ + 'key' => 'value', + ], + ]]; + + // Test merging one success result + $response = $this->buildResponse(true, $data1, $statusCode); + $result = \OC_API::mergeResponses([$response]); + $this->assertEquals($response['response'], $result); + $this->checkResult($result, $succeeded); + } + + function dataProviderTestMergeResponses() { + return [ + // Two shipped success results + [true, 100, true, 100, true], + // Two shipped results, one success and one failure + [true, 100, true, 998, false], + // Two shipped results, both failure + [true, 997, true, 998, false], + // Two third party success results + [false, 100, false, 100, true], + // Two third party results, one success and one failure + [false, 100, false, 998, false], + // Two third party results, both failure + [false, 997, false, 998, false], + // One of each, both success + [false, 100, true, 100, true], + [true, 100, false, 100, true], + // One of each, both failure + [false, 997, true, 998, false], + // One of each, shipped success + [false, 997, true, 100, true], + // One of each, third party success + [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(); + $resultHeaders = $result->getHeaders(); + $resultStatusCode = $result->getStatusCode(); + + $this->assertArrayHasKey('jan', $resultData['users']); + $this->assertArrayHasKey('KEY', $resultHeaders); + + // 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/AllConfigTest.php b/tests/lib/AllConfigTest.php new file mode 100644 index 00000000000..4f8b0658b80 --- /dev/null +++ b/tests/lib/AllConfigTest.php @@ -0,0 +1,419 @@ + + * This file is licensed under the Affero General Public License version 3 or + * later. + * See the COPYING-README file. + */ + +namespace Test; + +/** + * Class AllConfigTest + * + * @group DB + * + * @package Test + */ +class AllConfigTest extends \Test\TestCase { + + /** @var \OCP\IDBConnection */ + protected $connection; + + protected function getConfig($systemConfig = null, $connection = null) { + if($this->connection === null) { + $this->connection = \OC::$server->getDatabaseConnection(); + } + if($connection === null) { + $connection = $this->connection; + } + if($systemConfig === null) { + $systemConfig = $this->getMockBuilder('\OC\SystemConfig') + ->disableOriginalConstructor() + ->getMock(); + } + return new \OC\AllConfig($systemConfig, $connection); + } + + public function testDeleteUserValue() { + $config = $this->getConfig(); + + // preparation - add something to the database + $this->connection->executeUpdate( + 'INSERT INTO `*PREFIX*preferences` (`userid`, `appid`, ' . + '`configkey`, `configvalue`) VALUES (?, ?, ?, ?)', + array('userDelete', 'appDelete', 'keyDelete', 'valueDelete') + ); + + $config->deleteUserValue('userDelete', 'appDelete', 'keyDelete'); + + $result = $this->connection->executeQuery( + 'SELECT COUNT(*) AS `count` FROM `*PREFIX*preferences` WHERE `userid` = ?', + array('userDelete') + )->fetch(); + $actualCount = $result['count']; + + $this->assertEquals(0, $actualCount, 'There was one value in the database and after the tests there should be no entry left.'); + } + + public function testSetUserValue() { + $selectAllSQL = 'SELECT `userid`, `appid`, `configkey`, `configvalue` FROM `*PREFIX*preferences` WHERE `userid` = ?'; + $config = $this->getConfig(); + + $config->setUserValue('userSet', 'appSet', 'keySet', 'valueSet'); + + $result = $this->connection->executeQuery($selectAllSQL, array('userSet'))->fetchAll(); + + $this->assertEquals(1, count($result)); + $this->assertEquals(array( + 'userid' => 'userSet', + 'appid' => 'appSet', + 'configkey' => 'keySet', + 'configvalue' => 'valueSet' + ), $result[0]); + + // test if the method overwrites existing database entries + $config->setUserValue('userSet', 'appSet', 'keySet', 'valueSet2'); + + $result = $this->connection->executeQuery($selectAllSQL, array('userSet'))->fetchAll(); + + $this->assertEquals(1, count($result)); + $this->assertEquals(array( + 'userid' => 'userSet', + 'appid' => 'appSet', + 'configkey' => 'keySet', + 'configvalue' => 'valueSet2' + ), $result[0]); + + // cleanup - it therefore relies on the successful execution of the previous test + $config->deleteUserValue('userSet', 'appSet', 'keySet'); + } + + public function testSetUserValueWithPreCondition() { + $config = $this->getConfig(); + + $selectAllSQL = 'SELECT `userid`, `appid`, `configkey`, `configvalue` FROM `*PREFIX*preferences` WHERE `userid` = ?'; + + $config->setUserValue('userPreCond', 'appPreCond', 'keyPreCond', 'valuePreCond'); + + $result = $this->connection->executeQuery($selectAllSQL, array('userPreCond'))->fetchAll(); + + $this->assertEquals(1, count($result)); + $this->assertEquals(array( + 'userid' => 'userPreCond', + 'appid' => 'appPreCond', + 'configkey' => 'keyPreCond', + 'configvalue' => 'valuePreCond' + ), $result[0]); + + // test if the method overwrites existing database entries with valid precond + $config->setUserValue('userPreCond', 'appPreCond', 'keyPreCond', 'valuePreCond2', 'valuePreCond'); + + $result = $this->connection->executeQuery($selectAllSQL, array('userPreCond'))->fetchAll(); + + $this->assertEquals(1, count($result)); + $this->assertEquals(array( + 'userid' => 'userPreCond', + 'appid' => 'appPreCond', + 'configkey' => 'keyPreCond', + 'configvalue' => 'valuePreCond2' + ), $result[0]); + + // cleanup + $config->deleteUserValue('userPreCond', 'appPreCond', 'keyPreCond'); + } + + /** + * @expectedException \OCP\PreConditionNotMetException + */ + public function testSetUserValueWithPreConditionFailure() { + $config = $this->getConfig(); + + $selectAllSQL = 'SELECT `userid`, `appid`, `configkey`, `configvalue` FROM `*PREFIX*preferences` WHERE `userid` = ?'; + + $config->setUserValue('userPreCond1', 'appPreCond', 'keyPreCond', 'valuePreCond'); + + $result = $this->connection->executeQuery($selectAllSQL, array('userPreCond1'))->fetchAll(); + + $this->assertEquals(1, count($result)); + $this->assertEquals(array( + 'userid' => 'userPreCond1', + 'appid' => 'appPreCond', + 'configkey' => 'keyPreCond', + 'configvalue' => 'valuePreCond' + ), $result[0]); + + // test if the method overwrites existing database entries with valid precond + $config->setUserValue('userPreCond1', 'appPreCond', 'keyPreCond', 'valuePreCond2', 'valuePreCond3'); + + $result = $this->connection->executeQuery($selectAllSQL, array('userPreCond1'))->fetchAll(); + + $this->assertEquals(1, count($result)); + $this->assertEquals(array( + 'userid' => 'userPreCond1', + 'appid' => 'appPreCond', + 'configkey' => 'keyPreCond', + 'configvalue' => 'valuePreCond' + ), $result[0]); + + // cleanup + $config->deleteUserValue('userPreCond1', 'appPreCond', 'keyPreCond'); + } + + public function testSetUserValueUnchanged() { + // TODO - FIXME until the dependency injection is handled properly (in AllConfig) + $this->markTestSkipped('Skipped because this is just testable if database connection can be injected'); + + $resultMock = $this->getMockBuilder('\Doctrine\DBAL\Driver\Statement') + ->disableOriginalConstructor()->getMock(); + $resultMock->expects($this->once()) + ->method('fetchColumn') + ->will($this->returnValue('valueSetUnchanged')); + + $connectionMock = $this->getMock('\OCP\IDBConnection'); + $connectionMock->expects($this->once()) + ->method('executeQuery') + ->with($this->equalTo('SELECT `configvalue` FROM `*PREFIX*preferences` '. + 'WHERE `userid` = ? AND `appid` = ? AND `configkey` = ?'), + $this->equalTo(array('userSetUnchanged', 'appSetUnchanged', 'keySetUnchanged'))) + ->will($this->returnValue($resultMock)); + $connectionMock->expects($this->never()) + ->method('executeUpdate'); + + $config = $this->getConfig(null, $connectionMock); + + $config->setUserValue('userSetUnchanged', 'appSetUnchanged', 'keySetUnchanged', 'valueSetUnchanged'); + } + + public function testGetUserValue() { + $config = $this->getConfig(); + + // setup - it therefore relies on the successful execution of the previous test + $config->setUserValue('userGet', 'appGet', 'keyGet', 'valueGet'); + $value = $config->getUserValue('userGet', 'appGet', 'keyGet'); + + $this->assertEquals('valueGet', $value); + + $result = $this->connection->executeQuery( + 'SELECT `userid`, `appid`, `configkey`, `configvalue` FROM `*PREFIX*preferences` WHERE `userid` = ?', + array('userGet') + )->fetchAll(); + + $this->assertEquals(1, count($result)); + $this->assertEquals(array( + 'userid' => 'userGet', + 'appid' => 'appGet', + 'configkey' => 'keyGet', + 'configvalue' => 'valueGet' + ), $result[0]); + + // drop data from database - but the config option should be cached in the config object + $this->connection->executeUpdate('DELETE FROM `*PREFIX*preferences` WHERE `userid` = ?', array('userGet')); + + // testing the caching mechanism + $value = $config->getUserValue('userGet', 'appGet', 'keyGet'); + + $this->assertEquals('valueGet', $value); + + $result = $this->connection->executeQuery( + 'SELECT `userid`, `appid`, `configkey`, `configvalue` FROM `*PREFIX*preferences` WHERE `userid` = ?', + array('userGet') + )->fetchAll(); + + $this->assertEquals(0, count($result)); + } + + public function testGetUserKeys() { + $config = $this->getConfig(); + + // preparation - add something to the database + $data = array( + array('userFetch', 'appFetch1', 'keyFetch1', 'value1'), + array('userFetch', 'appFetch1', 'keyFetch2', 'value2'), + array('userFetch', 'appFetch2', 'keyFetch3', 'value3'), + array('userFetch', 'appFetch1', 'keyFetch4', 'value4'), + array('userFetch', 'appFetch4', 'keyFetch1', 'value5'), + array('userFetch', 'appFetch5', 'keyFetch1', 'value6'), + array('userFetch2', 'appFetch', 'keyFetch1', 'value7') + ); + foreach ($data as $entry) { + $this->connection->executeUpdate( + 'INSERT INTO `*PREFIX*preferences` (`userid`, `appid`, ' . + '`configkey`, `configvalue`) VALUES (?, ?, ?, ?)', + $entry + ); + } + + $value = $config->getUserKeys('userFetch', 'appFetch1'); + $this->assertEquals(array('keyFetch1', 'keyFetch2', 'keyFetch4'), $value); + + $value = $config->getUserKeys('userFetch2', 'appFetch'); + $this->assertEquals(array('keyFetch1'), $value); + + // cleanup + $this->connection->executeUpdate('DELETE FROM `*PREFIX*preferences`'); + } + + public function testGetUserValueDefault() { + $config = $this->getConfig(); + + $this->assertEquals('', $config->getUserValue('userGetUnset', 'appGetUnset', 'keyGetUnset')); + $this->assertEquals(null, $config->getUserValue('userGetUnset', 'appGetUnset', 'keyGetUnset', null)); + $this->assertEquals('foobar', $config->getUserValue('userGetUnset', 'appGetUnset', 'keyGetUnset', 'foobar')); + } + + public function testGetUserValueForUsers() { + $config = $this->getConfig(); + + // preparation - add something to the database + $data = array( + array('userFetch1', 'appFetch2', 'keyFetch1', 'value1'), + array('userFetch2', 'appFetch2', 'keyFetch1', 'value2'), + array('userFetch3', 'appFetch2', 'keyFetch1', 3), + array('userFetch4', 'appFetch2', 'keyFetch1', 'value4'), + array('userFetch5', 'appFetch2', 'keyFetch1', 'value5'), + array('userFetch6', 'appFetch2', 'keyFetch1', 'value6'), + array('userFetch7', 'appFetch2', 'keyFetch1', 'value7') + ); + foreach ($data as $entry) { + $this->connection->executeUpdate( + 'INSERT INTO `*PREFIX*preferences` (`userid`, `appid`, ' . + '`configkey`, `configvalue`) VALUES (?, ?, ?, ?)', + $entry + ); + } + + $value = $config->getUserValueForUsers('appFetch2', 'keyFetch1', + array('userFetch1', 'userFetch2', 'userFetch3', 'userFetch5')); + $this->assertEquals(array( + 'userFetch1' => 'value1', + 'userFetch2' => 'value2', + 'userFetch3' => 3, + 'userFetch5' => 'value5' + ), $value); + + $value = $config->getUserValueForUsers('appFetch2', 'keyFetch1', + array('userFetch1', 'userFetch4', 'userFetch9')); + $this->assertEquals(array( + 'userFetch1' => 'value1', + 'userFetch4' => 'value4' + ), $value, 'userFetch9 is an non-existent user and should not be shown.'); + + // cleanup + $this->connection->executeUpdate('DELETE FROM `*PREFIX*preferences`'); + } + + public function testDeleteAllUserValues() { + $config = $this->getConfig(); + + // preparation - add something to the database + $data = array( + array('userFetch3', 'appFetch1', 'keyFetch1', 'value1'), + array('userFetch3', 'appFetch1', 'keyFetch2', 'value2'), + array('userFetch3', 'appFetch2', 'keyFetch3', 'value3'), + array('userFetch3', 'appFetch1', 'keyFetch4', 'value4'), + array('userFetch3', 'appFetch4', 'keyFetch1', 'value5'), + array('userFetch3', 'appFetch5', 'keyFetch1', 'value6'), + array('userFetch4', 'appFetch2', 'keyFetch1', 'value7') + ); + foreach ($data as $entry) { + $this->connection->executeUpdate( + 'INSERT INTO `*PREFIX*preferences` (`userid`, `appid`, ' . + '`configkey`, `configvalue`) VALUES (?, ?, ?, ?)', + $entry + ); + } + + $config->deleteAllUserValues('userFetch3'); + + $result = $this->connection->executeQuery( + 'SELECT COUNT(*) AS `count` FROM `*PREFIX*preferences`' + )->fetch(); + $actualCount = $result['count']; + + $this->assertEquals(1, $actualCount, 'After removing `userFetch3` there should be exactly 1 entry left.'); + + // cleanup + $this->connection->executeUpdate('DELETE FROM `*PREFIX*preferences`'); + } + + public function testDeleteAppFromAllUsers() { + $config = $this->getConfig(); + + // preparation - add something to the database + $data = array( + array('userFetch5', 'appFetch1', 'keyFetch1', 'value1'), + array('userFetch5', 'appFetch1', 'keyFetch2', 'value2'), + array('userFetch5', 'appFetch2', 'keyFetch3', 'value3'), + array('userFetch5', 'appFetch1', 'keyFetch4', 'value4'), + array('userFetch5', 'appFetch4', 'keyFetch1', 'value5'), + array('userFetch5', 'appFetch5', 'keyFetch1', 'value6'), + array('userFetch6', 'appFetch2', 'keyFetch1', 'value7') + ); + foreach ($data as $entry) { + $this->connection->executeUpdate( + 'INSERT INTO `*PREFIX*preferences` (`userid`, `appid`, ' . + '`configkey`, `configvalue`) VALUES (?, ?, ?, ?)', + $entry + ); + } + + $config->deleteAppFromAllUsers('appFetch1'); + + $result = $this->connection->executeQuery( + 'SELECT COUNT(*) AS `count` FROM `*PREFIX*preferences`' + )->fetch(); + $actualCount = $result['count']; + + $this->assertEquals(4, $actualCount, 'After removing `appFetch1` there should be exactly 4 entries left.'); + + $config->deleteAppFromAllUsers('appFetch2'); + + $result = $this->connection->executeQuery( + 'SELECT COUNT(*) AS `count` FROM `*PREFIX*preferences`' + )->fetch(); + $actualCount = $result['count']; + + $this->assertEquals(2, $actualCount, 'After removing `appFetch2` there should be exactly 2 entries left.'); + + // cleanup + $this->connection->executeUpdate('DELETE FROM `*PREFIX*preferences`'); + } + + public function testGetUsersForUserValue() { + // mock the check for the database to run the correct SQL statements for each database type + $systemConfig = $this->getMockBuilder('\OC\SystemConfig') + ->disableOriginalConstructor() + ->getMock(); + $systemConfig->expects($this->once()) + ->method('getValue') + ->with($this->equalTo('dbtype'), + $this->equalTo('sqlite')) + ->will($this->returnValue(\OC::$server->getConfig()->getSystemValue('dbtype', 'sqlite'))); + $config = $this->getConfig($systemConfig); + + // preparation - add something to the database + $data = array( + array('user1', 'appFetch9', 'keyFetch9', 'value9'), + array('user2', 'appFetch9', 'keyFetch9', 'value9'), + array('user3', 'appFetch9', 'keyFetch9', 'value8'), + array('user4', 'appFetch9', 'keyFetch8', 'value9'), + array('user5', 'appFetch8', 'keyFetch9', 'value9'), + array('user6', 'appFetch9', 'keyFetch9', 'value9'), + ); + foreach ($data as $entry) { + $this->connection->executeUpdate( + 'INSERT INTO `*PREFIX*preferences` (`userid`, `appid`, ' . + '`configkey`, `configvalue`) VALUES (?, ?, ?, ?)', + $entry + ); + } + + $value = $config->getUsersForUserValue('appFetch9', 'keyFetch9', 'value9'); + $this->assertEquals(array('user1', 'user2', 'user6'), $value); + + // cleanup + $this->connection->executeUpdate('DELETE FROM `*PREFIX*preferences`'); + } + +} diff --git a/tests/lib/AppTest.php b/tests/lib/AppTest.php new file mode 100644 index 00000000000..2e5b6f74ab7 --- /dev/null +++ b/tests/lib/AppTest.php @@ -0,0 +1,549 @@ + + * Copyright (c) 2014 Vincent Petry + * This file is licensed under the Affero General Public License version 3 or + * later. + * See the COPYING-README file. + */ + +namespace Test; +use OCP\IAppConfig; + +/** + * Class AppTest + * + * @group DB + */ +class AppTest extends \Test\TestCase { + + const TEST_USER1 = 'user1'; + const TEST_USER2 = 'user2'; + const TEST_USER3 = 'user3'; + const TEST_GROUP1 = 'group1'; + const TEST_GROUP2 = 'group2'; + + function appVersionsProvider() { + return array( + // exact match + array( + '6.0.0.0', + array( + 'requiremin' => '6.0', + 'requiremax' => '6.0', + ), + true + ), + // in-between match + array( + '6.0.0.0', + array( + 'requiremin' => '5.0', + 'requiremax' => '7.0', + ), + true + ), + // app too old + array( + '6.0.0.0', + array( + 'requiremin' => '5.0', + 'requiremax' => '5.0', + ), + false + ), + // app too new + array( + '5.0.0.0', + array( + 'requiremin' => '6.0', + 'requiremax' => '6.0', + ), + false + ), + // only min specified + array( + '6.0.0.0', + array( + 'requiremin' => '6.0', + ), + true + ), + // only min specified fail + array( + '5.0.0.0', + array( + 'requiremin' => '6.0', + ), + false + ), + // only min specified legacy + array( + '6.0.0.0', + array( + 'require' => '6.0', + ), + true + ), + // only min specified legacy fail + array( + '4.0.0.0', + array( + 'require' => '6.0', + ), + false + ), + // only max specified + array( + '5.0.0.0', + array( + 'requiremax' => '6.0', + ), + true + ), + // only max specified fail + array( + '7.0.0.0', + array( + 'requiremax' => '6.0', + ), + false + ), + // variations of versions + // single OC number + array( + '4', + array( + 'require' => '4.0', + ), + true + ), + // multiple OC number + array( + '4.3.1', + array( + 'require' => '4.3', + ), + true + ), + // single app number + array( + '4', + array( + 'require' => '4', + ), + true + ), + // single app number fail + array( + '4.3', + array( + 'require' => '5', + ), + false + ), + // complex + array( + '5.0.0', + array( + 'require' => '4.5.1', + ), + true + ), + // complex fail + array( + '4.3.1', + array( + 'require' => '4.3.2', + ), + false + ), + // two numbers + array( + '4.3.1', + array( + 'require' => '4.4', + ), + false + ), + // one number fail + array( + '4.3.1', + array( + 'require' => '5', + ), + false + ), + // pre-alpha app + array( + '5.0.3', + array( + 'require' => '4.93', + ), + true + ), + // pre-alpha OC + array( + '6.90.0.2', + array( + 'require' => '6.90', + ), + true + ), + // pre-alpha OC max + array( + '6.90.0.2', + array( + 'requiremax' => '7', + ), + true + ), + // expect same major number match + array( + '5.0.3', + array( + 'require' => '5', + ), + true + ), + // expect same major number match + array( + '5.0.3', + array( + 'requiremax' => '5', + ), + true + ), + // dependencies versions before require* + array( + '6.0.0.0', + array( + 'requiremin' => '5.0', + 'requiremax' => '7.0', + 'dependencies' => array( + 'owncloud' => array( + '@attributes' => array( + 'min-version' => '7.0', + 'max-version' => '7.0', + ), + ), + ), + ), + false + ), + array( + '6.0.0.0', + array( + 'requiremin' => '5.0', + 'requiremax' => '7.0', + 'dependencies' => array( + 'owncloud' => array( + '@attributes' => array( + 'min-version' => '5.0', + 'max-version' => '5.0', + ), + ), + ), + ), + false + ), + array( + '6.0.0.0', + array( + 'requiremin' => '5.0', + 'requiremax' => '5.0', + 'dependencies' => array( + 'owncloud' => array( + '@attributes' => array( + 'min-version' => '5.0', + 'max-version' => '7.0', + ), + ), + ), + ), + true + ), + ); + } + + /** + * @dataProvider appVersionsProvider + */ + public function testIsAppCompatible($ocVersion, $appInfo, $expectedResult) { + $this->assertEquals($expectedResult, \OC_App::isAppCompatible($ocVersion, $appInfo)); + } + + /** + * Test that the isAppCompatible method also supports passing an array + * as $ocVersion + */ + public function testIsAppCompatibleWithArray() { + $ocVersion = array(6); + $appInfo = array( + 'requiremin' => '6', + 'requiremax' => '6', + ); + $this->assertTrue(\OC_App::isAppCompatible($ocVersion, $appInfo)); + } + + /** + * Tests that the app order is correct + */ + public function testGetEnabledAppsIsSorted() { + $apps = \OC_App::getEnabledApps(); + // 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); + } + + /** + * Providers for the app config values + */ + function appConfigValuesProvider() { + return array( + // logged in user1 + array( + self::TEST_USER1, + array( + 'files', + 'app1', + 'app3', + 'appforgroup1', + 'appforgroup12', + 'dav', + 'federatedfilesharing', + ), + false + ), + // logged in user2 + array( + self::TEST_USER2, + array( + 'files', + 'app1', + 'app3', + 'appforgroup12', + 'appforgroup2', + 'dav', + 'federatedfilesharing', + ), + false + ), + // logged in user3 + array( + self::TEST_USER3, + array( + 'files', + 'app1', + 'app3', + 'appforgroup1', + 'appforgroup12', + 'appforgroup2', + 'dav', + 'federatedfilesharing', + ), + false + ), + // no user, returns all apps + array( + null, + array( + 'files', + 'app1', + 'app3', + 'appforgroup1', + 'appforgroup12', + 'appforgroup2', + 'dav', + 'federatedfilesharing', + ), + false, + ), + // user given, but ask for all + array( + self::TEST_USER1, + array( + 'files', + 'app1', + 'app3', + 'appforgroup1', + 'appforgroup12', + 'appforgroup2', + 'dav', + 'federatedfilesharing', + ), + true, + ), + ); + } + + /** + * Test enabled apps + * + * @dataProvider appConfigValuesProvider + */ + public function testEnabledApps($user, $expectedApps, $forceAll) { + $userManager = \OC::$server->getUserManager(); + $groupManager = \OC::$server->getGroupManager(); + $user1 = $userManager->createUser(self::TEST_USER1, self::TEST_USER1); + $user2 = $userManager->createUser(self::TEST_USER2, self::TEST_USER2); + $user3 = $userManager->createUser(self::TEST_USER3, self::TEST_USER3); + + $group1 = $groupManager->createGroup(self::TEST_GROUP1); + $group1->addUser($user1); + $group1->addUser($user3); + $group2 = $groupManager->createGroup(self::TEST_GROUP2); + $group2->addUser($user2); + $group2->addUser($user3); + + \OC_User::setUserId($user); + + $this->setupAppConfigMock()->expects($this->once()) + ->method('getValues') + ->will($this->returnValue( + array( + 'app3' => 'yes', + 'app2' => 'no', + 'app1' => 'yes', + 'appforgroup1' => '["group1"]', + 'appforgroup2' => '["group2"]', + 'appforgroup12' => '["group2","group1"]', + ) + ) + ); + + $apps = \OC_App::getEnabledApps(false, $forceAll); + + $this->restoreAppConfig(); + \OC_User::setUserId(null); + + $user1->delete(); + $user2->delete(); + $user3->delete(); + + $group1->delete(); + $group2->delete(); + + $this->assertEquals($expectedApps, $apps); + } + + /** + * Test isEnabledApps() with cache, not re-reading the list of + * enabled apps more than once when a user is set. + */ + public function testEnabledAppsCache() { + $userManager = \OC::$server->getUserManager(); + $user1 = $userManager->createUser(self::TEST_USER1, self::TEST_USER1); + + \OC_User::setUserId(self::TEST_USER1); + + $this->setupAppConfigMock()->expects($this->once()) + ->method('getValues') + ->will($this->returnValue( + array( + 'app3' => 'yes', + 'app2' => 'no', + ) + ) + ); + + $apps = \OC_App::getEnabledApps(); + $this->assertEquals(array('files', 'app3', 'dav', 'federatedfilesharing',), $apps); + + // mock should not be called again here + $apps = \OC_App::getEnabledApps(); + $this->assertEquals(array('files', 'app3', 'dav', 'federatedfilesharing',), $apps); + + $this->restoreAppConfig(); + \OC_User::setUserId(null); + + $user1->delete(); + } + + + private function setupAppConfigMock() { + $appConfig = $this->getMock( + '\OC\AppConfig', + array('getValues'), + array(\OC::$server->getDatabaseConnection()), + '', + false + ); + + $this->registerAppConfig($appConfig); + return $appConfig; + } + + /** + * Register an app config mock for testing purposes. + * + * @param IAppConfig $appConfig app config mock + */ + private function registerAppConfig(IAppConfig $appConfig) { + \OC::$server->registerService('AppConfig', function ($c) use ($appConfig) { + return $appConfig; + }); + \OC::$server->registerService('AppManager', function (\OC\Server $c) use ($appConfig) { + return new \OC\App\AppManager($c->getUserSession(), $appConfig, $c->getGroupManager(), $c->getMemCacheFactory(), $c->getEventDispatcher()); + }); + } + + /** + * Restore the original app config service. + */ + private function restoreAppConfig() { + \OC::$server->registerService('AppConfig', function (\OC\Server $c) { + return new \OC\AppConfig($c->getDatabaseConnection()); + }); + \OC::$server->registerService('AppManager', function (\OC\Server $c) { + return new \OC\App\AppManager($c->getUserSession(), $c->getAppConfig(), $c->getGroupManager(), $c->getMemCacheFactory(), $c->getEventDispatcher()); + }); + + // Remove the cache of the mocked apps list with a forceRefresh + \OC_App::getEnabledApps(); + } + + /** + * Providers for the app data values + */ + function appDataProvider() { + return [ + [ + ['description' => " \t This is a multiline \n test with \n \t \n \n some new lines "], + ['description' => "This is a multiline test with\n\nsome new lines"] + ], + [ + ['description' => " \t This is a multiline \n test with \n \t some new lines "], + ['description' => "This is a multiline test with some new lines"] + ], + [ + ['description' => hex2bin('5065726d657420646520732761757468656e7469666965722064616e732070697769676f20646972656374656d656e74206176656320736573206964656e74696669616e7473206f776e636c6f75642073616e73206c65732072657461706572206574206d657420c3a0206a6f757273206365757820636920656e20636173206465206368616e67656d656e74206465206d6f742064652070617373652e0d0a0d')], + ['description' => "Permet de s'authentifier dans piwigo directement avec ses identifiants owncloud sans les retaper et met à jours ceux ci en cas de changement de mot de passe."] + ], + [ + ['not-a-description' => " \t This is a multiline \n test with \n \t some new lines "], + ['not-a-description' => " \t This is a multiline \n test with \n \t some new lines "] + ], + [ + ['description' => [100, 'bla']], + ['description' => ""] + ], + ]; + } + + /** + * Test app info parser + * + * @dataProvider appDataProvider + * @param array $data + * @param array $expected + */ + public function testParseAppInfo(array $data, array $expected) { + $this->assertSame($expected, \OC_App::parseAppInfo($data)); + } +} + diff --git a/tests/lib/CapabilitiesManagerTest.php b/tests/lib/CapabilitiesManagerTest.php new file mode 100644 index 00000000000..d4dd52d07f1 --- /dev/null +++ b/tests/lib/CapabilitiesManagerTest.php @@ -0,0 +1,162 @@ + + * + * @copyright Copyright (c) 2015, ownCloud, Inc. + * @license AGPL-3.0 + * + * This code is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License, version 3, + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License, version 3, + * along with this program. If not, see + * + */ + +namespace Test; + +class CapabilitiesManagerTest extends TestCase { + + /** + * Test no capabilities + */ + public function testNoCapabilities() { + $manager = new \OC\CapabilitiesManager(); + $res = $manager->getCapabilities(); + $this->assertEmpty($res); + } + + /** + * Test a valid capabilitie + */ + public function testValidCapability() { + $manager = new \OC\CapabilitiesManager(); + + $manager->registerCapability(function() { + return new SimpleCapability(); + }); + + $res = $manager->getCapabilities(); + $this->assertEquals(['foo' => 1], $res); + } + + /** + * Test that we need something that implents ICapability + * @expectedException \InvalidArgumentException + * @expectedExceptionMessage The given Capability (Test\NoCapability) does not implement the ICapability interface + */ + public function testNoICapability() { + $manager = new \OC\CapabilitiesManager(); + + $manager->registerCapability(function() { + return new NoCapability(); + }); + + $res = $manager->getCapabilities(); + $this->assertEquals([], $res); + } + + /** + * Test a bunch of merged Capabilities + */ + public function testMergedCapabilities() { + $manager = new \OC\CapabilitiesManager(); + + $manager->registerCapability(function() { + return new SimpleCapability(); + }); + $manager->registerCapability(function() { + return new SimpleCapability2(); + }); + $manager->registerCapability(function() { + return new SimpleCapability3(); + }); + + $res = $manager->getCapabilities(); + $expected = [ + 'foo' => 1, + 'bar' => [ + 'x' => 1, + 'y' => 2 + ] + ]; + + $this->assertEquals($expected, $res); + } + + /** + * Test deep identical capabilities + */ + public function testDeepIdenticalCapabilities() { + $manager = new \OC\CapabilitiesManager(); + + $manager->registerCapability(function() { + return new DeepCapability(); + }); + $manager->registerCapability(function() { + return new DeepCapability(); + }); + + $res = $manager->getCapabilities(); + $expected = [ + 'foo' => [ + 'bar' => [ + 'baz' => true + ] + ] + ]; + + $this->assertEquals($expected, $res); + } +} + +class SimpleCapability implements \OCP\Capabilities\ICapability { + public function getCapabilities() { + return [ + 'foo' => 1 + ]; + } +} + +class SimpleCapability2 implements \OCP\Capabilities\ICapability { + public function getCapabilities() { + return [ + 'bar' => ['x' => 1] + ]; + } +} + +class SimpleCapability3 implements \OCP\Capabilities\ICapability { + public function getCapabilities() { + return [ + 'bar' => ['y' => 2] + ]; + } +} + +class NoCapability { + public function getCapabilities() { + return [ + 'baz' => 'z' + ]; + } +} + +class DeepCapability implements \OCP\Capabilities\ICapability { + public function getCapabilities() { + return [ + 'foo' => [ + 'bar' => [ + 'baz' => true + ] + ] + ]; + } +} + diff --git a/tests/lib/ConfigTest.php b/tests/lib/ConfigTest.php new file mode 100644 index 00000000000..74dcdc192ce --- /dev/null +++ b/tests/lib/ConfigTest.php @@ -0,0 +1,142 @@ + + * This file is licensed under the Affero General Public License version 3 or + * later. + * See the COPYING-README file. + */ + +namespace Test; + +class ConfigTest extends TestCase { + const TESTCONTENT = '"bar", "beers" => array("Appenzeller", "Guinness", "Kölsch"), "alcohol_free" => false);'; + + /** @var array */ + private $initialConfig = array('foo' => 'bar', 'beers' => array('Appenzeller', 'Guinness', 'Kölsch'), 'alcohol_free' => false); + /** @var string */ + private $configFile; + /** @var \OC\Config */ + private $config; + /** @var string */ + private $randomTmpDir; + + protected function setUp() { + parent::setUp(); + + $this->randomTmpDir = \OC::$server->getTempManager()->getTemporaryFolder(); + $this->configFile = $this->randomTmpDir.'testconfig.php'; + file_put_contents($this->configFile, self::TESTCONTENT); + $this->config = new \OC\Config($this->randomTmpDir, 'testconfig.php'); + } + + protected function tearDown() { + unlink($this->configFile); + parent::tearDown(); + } + + public function testGetKeys() { + $expectedConfig = array('foo', 'beers', 'alcohol_free'); + $this->assertSame($expectedConfig, $this->config->getKeys()); + } + + public function testGetValue() { + $this->assertSame('bar', $this->config->getValue('foo')); + $this->assertSame(null, $this->config->getValue('bar')); + $this->assertSame('moo', $this->config->getValue('bar', 'moo')); + $this->assertSame(false, $this->config->getValue('alcohol_free', 'someBogusValue')); + $this->assertSame(array('Appenzeller', 'Guinness', 'Kölsch'), $this->config->getValue('beers', 'someBogusValue')); + $this->assertSame(array('Appenzeller', 'Guinness', 'Kölsch'), $this->config->getValue('beers')); + } + + public function testSetValue() { + $this->config->setValue('foo', 'moo'); + $expectedConfig = $this->initialConfig; + $expectedConfig['foo'] = 'moo'; + $this->assertAttributeEquals($expectedConfig, 'cache', $this->config); + + $content = file_get_contents($this->configFile); + $expected = " 'moo',\n 'beers' => \n array (\n 0 => 'Appenzeller',\n " . + " 1 => 'Guinness',\n 2 => 'Kölsch',\n ),\n 'alcohol_free' => false,\n);\n"; + $this->assertEquals($expected, $content); + + $this->config->setValue('bar', 'red'); + $this->config->setValue('apps', array('files', 'gallery')); + $expectedConfig['bar'] = 'red'; + $expectedConfig['apps'] = array('files', 'gallery'); + $this->assertAttributeEquals($expectedConfig, 'cache', $this->config); + + $content = file_get_contents($this->configFile); + + $expected = " 'moo',\n 'beers' => \n array (\n 0 => 'Appenzeller',\n " . + " 1 => 'Guinness',\n 2 => 'Kölsch',\n ),\n 'alcohol_free' => false,\n 'bar' => 'red',\n 'apps' => \n " . + " array (\n 0 => 'files',\n 1 => 'gallery',\n ),\n);\n"; + $this->assertEquals($expected, $content); + } + + public function testSetValues() { + $content = file_get_contents($this->configFile); + $this->assertEquals(self::TESTCONTENT, $content); + + // Changing configs to existing values and deleting non-existing once + // should not rewrite the config.php + $this->config->setValues([ + 'foo' => 'bar', + 'not_exists' => null, + ]); + + $this->assertAttributeEquals($this->initialConfig, 'cache', $this->config); + $content = file_get_contents($this->configFile); + $this->assertEquals(self::TESTCONTENT, $content); + + $this->config->setValues([ + 'foo' => 'moo', + 'alcohol_free' => null, + ]); + $expectedConfig = $this->initialConfig; + $expectedConfig['foo'] = 'moo'; + unset($expectedConfig['alcohol_free']); + $this->assertAttributeEquals($expectedConfig, 'cache', $this->config); + + $content = file_get_contents($this->configFile); + $expected = " 'moo',\n 'beers' => \n array (\n 0 => 'Appenzeller',\n " . + " 1 => 'Guinness',\n 2 => 'Kölsch',\n ),\n);\n"; + $this->assertEquals($expected, $content); + } + + public function testDeleteKey() { + $this->config->deleteKey('foo'); + $expectedConfig = $this->initialConfig; + unset($expectedConfig['foo']); + $this->assertAttributeEquals($expectedConfig, 'cache', $this->config); + $content = file_get_contents($this->configFile); + + $expected = " \n array (\n 0 => 'Appenzeller',\n " . + " 1 => 'Guinness',\n 2 => 'Kölsch',\n ),\n 'alcohol_free' => false,\n);\n"; + $this->assertEquals($expected, $content); + } + + public function testConfigMerge() { + // Create additional config + $additionalConfig = '"totallyOutdated");'; + $additionalConfigPath = $this->randomTmpDir.'additionalConfig.testconfig.php'; + file_put_contents($additionalConfigPath, $additionalConfig); + + // Reinstantiate the config to force a read-in of the additional configs + $this->config = new \OC\Config($this->randomTmpDir, 'testconfig.php'); + + // Ensure that the config value can be read and the config has not been modified + $this->assertSame('totallyOutdated', $this->config->getValue('php53', 'bogusValue')); + $this->assertEquals(self::TESTCONTENT, file_get_contents($this->configFile)); + + // Write a new value to the config + $this->config->setValue('CoolWebsites', array('demo.owncloud.org', 'owncloud.org', 'owncloud.com')); + $expected = " 'bar',\n 'beers' => \n array (\n 0 => 'Appenzeller',\n " . + " 1 => 'Guinness',\n 2 => 'Kölsch',\n ),\n 'alcohol_free' => false,\n 'php53' => 'totallyOutdated',\n 'CoolWebsites' => \n array (\n " . + " 0 => 'demo.owncloud.org',\n 1 => 'owncloud.org',\n 2 => 'owncloud.com',\n ),\n);\n"; + $this->assertEquals($expected, file_get_contents($this->configFile)); + + // Cleanup + unlink($additionalConfigPath); + } + +} diff --git a/tests/lib/ContactsManagerTest.php b/tests/lib/ContactsManagerTest.php new file mode 100644 index 00000000000..89a9cb95b97 --- /dev/null +++ b/tests/lib/ContactsManagerTest.php @@ -0,0 +1,210 @@ +cm = new \OC\ContactsManager(); + } + + public function searchProvider(){ + $search1 = array( + 0 => array( + 'N' => array(0 => '', 1 => 'Jan', 2 => 'Jansen', 3 => '', 4 => '',), + 'UID' => '04ada7f5-01f9-4309-9c82-6b555b2170ed', + 'FN' => 'Jan Jansen', + 'id' => '1', + 'addressbook-key' => 'simple:1', + ), + 0 => array( + 'N' => array(0 => '', 1 => 'Tom', 2 => 'Peeters', 3 => '', 4 => '',), + 'UID' => '04ada7f5-01f9-4309-9c82-2345-2345--6b555b2170ed', + 'FN' => 'Tom Peeters', + 'id' => '2', + 'addressbook-key' => 'simple:1', + ), + ); + + $search2 = array( + 0 => array( + 'N' => array(0 => '', 1 => 'fg', 2 => '', 3 => '', 4 => '',), + 'UID' => '04ada234h5jh357f5-01f9-4309-9c82-6b555b2170ed', + 'FN' => 'Jan Rompuy', + 'id' => '1', + 'addressbook-key' => 'simple:2', + ), + 0 => array( + 'N' => array(0 => '', 1 => 'fg', 2 => '', 3 => '', 4 => '',), + 'UID' => '04ada7f5-01f9-4309-345kj345j9c82-2345-2345--6b555b2170ed', + 'FN' => 'Tim Peeters', + 'id' => '2', + 'addressbook-key' => 'simple:2', + ), + ); + + $expectedResult = array_merge($search1, $search2); + return array( + array( + $search1, + $search2, + $expectedResult + ) + ); + } + + /** + * @dataProvider searchProvider + */ + public function testSearch($search1, $search2, $expectedResult ){ + $addressbook1 = $this->getMockBuilder('\OCP\IAddressBook') + ->disableOriginalConstructor() + ->getMock(); + + $addressbook1->expects($this->once()) + ->method('search') + ->willReturn($search1); + + $addressbook1->expects($this->any()) + ->method('getKey') + ->willReturn('simple:1'); + + $addressbook2 = $this->getMockBuilder('\OCP\IAddressBook') + ->disableOriginalConstructor() + ->getMock(); + + $addressbook2->expects($this->once()) + ->method('search') + ->willReturn($search2); + + $addressbook2->expects($this->any()) + ->method('getKey') + ->willReturn('simple:2'); + + + $this->cm->registerAddressBook($addressbook1); + $this->cm->registerAddressBook($addressbook2); + $result = $this->cm->search(''); + $this->assertEquals($expectedResult, $result); + } + + + public function testDeleteHavePermission(){ + $addressbook = $this->getMockBuilder('\OCP\IAddressBook') + ->disableOriginalConstructor() + ->getMock(); + + $addressbook->expects($this->any()) + ->method('getPermissions') + ->willReturn(\OCP\Constants::PERMISSION_ALL); + + $addressbook->expects($this->once()) + ->method('delete') + ->willReturn('returnMe'); + + + $this->cm->registerAddressBook($addressbook); + $result = $this->cm->delete(1, $addressbook->getKey()); + $this->assertEquals($result, 'returnMe'); + } + + public function testDeleteNoPermission(){ + $addressbook = $this->getMockBuilder('\OCP\IAddressBook') + ->disableOriginalConstructor() + ->getMock(); + + $addressbook->expects($this->any()) + ->method('getPermissions') + ->willReturn(\OCP\Constants::PERMISSION_READ); + + $addressbook->expects($this->never()) + ->method('delete'); + + $this->cm->registerAddressBook($addressbook); + $result = $this->cm->delete(1, $addressbook->getKey()); + $this->assertEquals($result, null); + } + + public function testDeleteNoAddressbook(){ + $addressbook = $this->getMockBuilder('\OCP\IAddressBook') + ->disableOriginalConstructor() + ->getMock(); + + $addressbook->expects($this->never()) + ->method('delete'); + + $this->cm->registerAddressBook($addressbook); + $result = $this->cm->delete(1, 'noaddressbook'); + $this->assertEquals($result, null); + + } + + public function testCreateOrUpdateHavePermission(){ + $addressbook = $this->getMockBuilder('\OCP\IAddressBook') + ->disableOriginalConstructor() + ->getMock(); + + $addressbook->expects($this->any()) + ->method('getPermissions') + ->willReturn(\OCP\Constants::PERMISSION_ALL); + + $addressbook->expects($this->once()) + ->method('createOrUpdate') + ->willReturn('returnMe'); + + $this->cm->registerAddressBook($addressbook); + $result = $this->cm->createOrUpdate(array(), $addressbook->getKey()); + $this->assertEquals($result, 'returnMe'); + } + + public function testCreateOrUpdateNoPermission(){ + $addressbook = $this->getMockBuilder('\OCP\IAddressBook') + ->disableOriginalConstructor() + ->getMock(); + + $addressbook->expects($this->any()) + ->method('getPermissions') + ->willReturn(\OCP\Constants::PERMISSION_READ); + + $addressbook->expects($this->never()) + ->method('createOrUpdate'); + + $this->cm->registerAddressBook($addressbook); + $result = $this->cm->createOrUpdate(array(), $addressbook->getKey()); + $this->assertEquals($result, null); + + } + + public function testCreateOrUpdateNOAdressbook(){ + $addressbook = $this->getMockBuilder('\OCP\IAddressBook') + ->disableOriginalConstructor() + ->getMock(); + + $addressbook->expects($this->never()) + ->method('createOrUpdate'); + + $this->cm->registerAddressBook($addressbook); + $result = $this->cm->createOrUpdate(array(), 'noaddressbook'); + $this->assertEquals($result, null); + } + + public function testIsEnabledIfNot(){ + $result = $this->cm->isEnabled(); + $this->assertFalse($result); + } + + public function testIsEnabledIfSo(){ + $addressbook = $this->getMockBuilder('\OCP\IAddressBook') + ->disableOriginalConstructor() + ->getMock(); + + $this->cm->registerAddressBook($addressbook); + $result = $this->cm->isEnabled(); + $this->assertTrue($result); + } + +} diff --git a/tests/lib/ErrorHandlerTest.php b/tests/lib/ErrorHandlerTest.php new file mode 100644 index 00000000000..aece7f146f6 --- /dev/null +++ b/tests/lib/ErrorHandlerTest.php @@ -0,0 +1,68 @@ + + * + * 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 . + * + */ + +namespace Test; + +class ErrorHandlerTest extends \Test\TestCase { + + /** + * 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); + } + +} + +/** + * dummy class to access protected methods of \OC\Log\ErrorHandler + */ +class TestableErrorHandler extends \OC\Log\ErrorHandler { + + /** + * @param string $msg + */ + public static function testRemovePassword($msg) { + return self::removePassword($msg); + } +} diff --git a/tests/lib/allconfig.php b/tests/lib/allconfig.php deleted file mode 100644 index 869bf9b8d66..00000000000 --- a/tests/lib/allconfig.php +++ /dev/null @@ -1,419 +0,0 @@ - - * This file is licensed under the Affero General Public License version 3 or - * later. - * See the COPYING-README file. - */ - -namespace Test; - -/** - * Class TestAllConfig - * - * @group DB - * - * @package Test - */ -class TestAllConfig extends \Test\TestCase { - - /** @var \OCP\IDBConnection */ - protected $connection; - - protected function getConfig($systemConfig = null, $connection = null) { - if($this->connection === null) { - $this->connection = \OC::$server->getDatabaseConnection(); - } - if($connection === null) { - $connection = $this->connection; - } - if($systemConfig === null) { - $systemConfig = $this->getMockBuilder('\OC\SystemConfig') - ->disableOriginalConstructor() - ->getMock(); - } - return new \OC\AllConfig($systemConfig, $connection); - } - - public function testDeleteUserValue() { - $config = $this->getConfig(); - - // preparation - add something to the database - $this->connection->executeUpdate( - 'INSERT INTO `*PREFIX*preferences` (`userid`, `appid`, ' . - '`configkey`, `configvalue`) VALUES (?, ?, ?, ?)', - array('userDelete', 'appDelete', 'keyDelete', 'valueDelete') - ); - - $config->deleteUserValue('userDelete', 'appDelete', 'keyDelete'); - - $result = $this->connection->executeQuery( - 'SELECT COUNT(*) AS `count` FROM `*PREFIX*preferences` WHERE `userid` = ?', - array('userDelete') - )->fetch(); - $actualCount = $result['count']; - - $this->assertEquals(0, $actualCount, 'There was one value in the database and after the tests there should be no entry left.'); - } - - public function testSetUserValue() { - $selectAllSQL = 'SELECT `userid`, `appid`, `configkey`, `configvalue` FROM `*PREFIX*preferences` WHERE `userid` = ?'; - $config = $this->getConfig(); - - $config->setUserValue('userSet', 'appSet', 'keySet', 'valueSet'); - - $result = $this->connection->executeQuery($selectAllSQL, array('userSet'))->fetchAll(); - - $this->assertEquals(1, count($result)); - $this->assertEquals(array( - 'userid' => 'userSet', - 'appid' => 'appSet', - 'configkey' => 'keySet', - 'configvalue' => 'valueSet' - ), $result[0]); - - // test if the method overwrites existing database entries - $config->setUserValue('userSet', 'appSet', 'keySet', 'valueSet2'); - - $result = $this->connection->executeQuery($selectAllSQL, array('userSet'))->fetchAll(); - - $this->assertEquals(1, count($result)); - $this->assertEquals(array( - 'userid' => 'userSet', - 'appid' => 'appSet', - 'configkey' => 'keySet', - 'configvalue' => 'valueSet2' - ), $result[0]); - - // cleanup - it therefore relies on the successful execution of the previous test - $config->deleteUserValue('userSet', 'appSet', 'keySet'); - } - - public function testSetUserValueWithPreCondition() { - $config = $this->getConfig(); - - $selectAllSQL = 'SELECT `userid`, `appid`, `configkey`, `configvalue` FROM `*PREFIX*preferences` WHERE `userid` = ?'; - - $config->setUserValue('userPreCond', 'appPreCond', 'keyPreCond', 'valuePreCond'); - - $result = $this->connection->executeQuery($selectAllSQL, array('userPreCond'))->fetchAll(); - - $this->assertEquals(1, count($result)); - $this->assertEquals(array( - 'userid' => 'userPreCond', - 'appid' => 'appPreCond', - 'configkey' => 'keyPreCond', - 'configvalue' => 'valuePreCond' - ), $result[0]); - - // test if the method overwrites existing database entries with valid precond - $config->setUserValue('userPreCond', 'appPreCond', 'keyPreCond', 'valuePreCond2', 'valuePreCond'); - - $result = $this->connection->executeQuery($selectAllSQL, array('userPreCond'))->fetchAll(); - - $this->assertEquals(1, count($result)); - $this->assertEquals(array( - 'userid' => 'userPreCond', - 'appid' => 'appPreCond', - 'configkey' => 'keyPreCond', - 'configvalue' => 'valuePreCond2' - ), $result[0]); - - // cleanup - $config->deleteUserValue('userPreCond', 'appPreCond', 'keyPreCond'); - } - - /** - * @expectedException \OCP\PreConditionNotMetException - */ - public function testSetUserValueWithPreConditionFailure() { - $config = $this->getConfig(); - - $selectAllSQL = 'SELECT `userid`, `appid`, `configkey`, `configvalue` FROM `*PREFIX*preferences` WHERE `userid` = ?'; - - $config->setUserValue('userPreCond1', 'appPreCond', 'keyPreCond', 'valuePreCond'); - - $result = $this->connection->executeQuery($selectAllSQL, array('userPreCond1'))->fetchAll(); - - $this->assertEquals(1, count($result)); - $this->assertEquals(array( - 'userid' => 'userPreCond1', - 'appid' => 'appPreCond', - 'configkey' => 'keyPreCond', - 'configvalue' => 'valuePreCond' - ), $result[0]); - - // test if the method overwrites existing database entries with valid precond - $config->setUserValue('userPreCond1', 'appPreCond', 'keyPreCond', 'valuePreCond2', 'valuePreCond3'); - - $result = $this->connection->executeQuery($selectAllSQL, array('userPreCond1'))->fetchAll(); - - $this->assertEquals(1, count($result)); - $this->assertEquals(array( - 'userid' => 'userPreCond1', - 'appid' => 'appPreCond', - 'configkey' => 'keyPreCond', - 'configvalue' => 'valuePreCond' - ), $result[0]); - - // cleanup - $config->deleteUserValue('userPreCond1', 'appPreCond', 'keyPreCond'); - } - - public function testSetUserValueUnchanged() { - // TODO - FIXME until the dependency injection is handled properly (in AllConfig) - $this->markTestSkipped('Skipped because this is just testable if database connection can be injected'); - - $resultMock = $this->getMockBuilder('\Doctrine\DBAL\Driver\Statement') - ->disableOriginalConstructor()->getMock(); - $resultMock->expects($this->once()) - ->method('fetchColumn') - ->will($this->returnValue('valueSetUnchanged')); - - $connectionMock = $this->getMock('\OCP\IDBConnection'); - $connectionMock->expects($this->once()) - ->method('executeQuery') - ->with($this->equalTo('SELECT `configvalue` FROM `*PREFIX*preferences` '. - 'WHERE `userid` = ? AND `appid` = ? AND `configkey` = ?'), - $this->equalTo(array('userSetUnchanged', 'appSetUnchanged', 'keySetUnchanged'))) - ->will($this->returnValue($resultMock)); - $connectionMock->expects($this->never()) - ->method('executeUpdate'); - - $config = $this->getConfig(null, $connectionMock); - - $config->setUserValue('userSetUnchanged', 'appSetUnchanged', 'keySetUnchanged', 'valueSetUnchanged'); - } - - public function testGetUserValue() { - $config = $this->getConfig(); - - // setup - it therefore relies on the successful execution of the previous test - $config->setUserValue('userGet', 'appGet', 'keyGet', 'valueGet'); - $value = $config->getUserValue('userGet', 'appGet', 'keyGet'); - - $this->assertEquals('valueGet', $value); - - $result = $this->connection->executeQuery( - 'SELECT `userid`, `appid`, `configkey`, `configvalue` FROM `*PREFIX*preferences` WHERE `userid` = ?', - array('userGet') - )->fetchAll(); - - $this->assertEquals(1, count($result)); - $this->assertEquals(array( - 'userid' => 'userGet', - 'appid' => 'appGet', - 'configkey' => 'keyGet', - 'configvalue' => 'valueGet' - ), $result[0]); - - // drop data from database - but the config option should be cached in the config object - $this->connection->executeUpdate('DELETE FROM `*PREFIX*preferences` WHERE `userid` = ?', array('userGet')); - - // testing the caching mechanism - $value = $config->getUserValue('userGet', 'appGet', 'keyGet'); - - $this->assertEquals('valueGet', $value); - - $result = $this->connection->executeQuery( - 'SELECT `userid`, `appid`, `configkey`, `configvalue` FROM `*PREFIX*preferences` WHERE `userid` = ?', - array('userGet') - )->fetchAll(); - - $this->assertEquals(0, count($result)); - } - - public function testGetUserKeys() { - $config = $this->getConfig(); - - // preparation - add something to the database - $data = array( - array('userFetch', 'appFetch1', 'keyFetch1', 'value1'), - array('userFetch', 'appFetch1', 'keyFetch2', 'value2'), - array('userFetch', 'appFetch2', 'keyFetch3', 'value3'), - array('userFetch', 'appFetch1', 'keyFetch4', 'value4'), - array('userFetch', 'appFetch4', 'keyFetch1', 'value5'), - array('userFetch', 'appFetch5', 'keyFetch1', 'value6'), - array('userFetch2', 'appFetch', 'keyFetch1', 'value7') - ); - foreach ($data as $entry) { - $this->connection->executeUpdate( - 'INSERT INTO `*PREFIX*preferences` (`userid`, `appid`, ' . - '`configkey`, `configvalue`) VALUES (?, ?, ?, ?)', - $entry - ); - } - - $value = $config->getUserKeys('userFetch', 'appFetch1'); - $this->assertEquals(array('keyFetch1', 'keyFetch2', 'keyFetch4'), $value); - - $value = $config->getUserKeys('userFetch2', 'appFetch'); - $this->assertEquals(array('keyFetch1'), $value); - - // cleanup - $this->connection->executeUpdate('DELETE FROM `*PREFIX*preferences`'); - } - - public function testGetUserValueDefault() { - $config = $this->getConfig(); - - $this->assertEquals('', $config->getUserValue('userGetUnset', 'appGetUnset', 'keyGetUnset')); - $this->assertEquals(null, $config->getUserValue('userGetUnset', 'appGetUnset', 'keyGetUnset', null)); - $this->assertEquals('foobar', $config->getUserValue('userGetUnset', 'appGetUnset', 'keyGetUnset', 'foobar')); - } - - public function testGetUserValueForUsers() { - $config = $this->getConfig(); - - // preparation - add something to the database - $data = array( - array('userFetch1', 'appFetch2', 'keyFetch1', 'value1'), - array('userFetch2', 'appFetch2', 'keyFetch1', 'value2'), - array('userFetch3', 'appFetch2', 'keyFetch1', 3), - array('userFetch4', 'appFetch2', 'keyFetch1', 'value4'), - array('userFetch5', 'appFetch2', 'keyFetch1', 'value5'), - array('userFetch6', 'appFetch2', 'keyFetch1', 'value6'), - array('userFetch7', 'appFetch2', 'keyFetch1', 'value7') - ); - foreach ($data as $entry) { - $this->connection->executeUpdate( - 'INSERT INTO `*PREFIX*preferences` (`userid`, `appid`, ' . - '`configkey`, `configvalue`) VALUES (?, ?, ?, ?)', - $entry - ); - } - - $value = $config->getUserValueForUsers('appFetch2', 'keyFetch1', - array('userFetch1', 'userFetch2', 'userFetch3', 'userFetch5')); - $this->assertEquals(array( - 'userFetch1' => 'value1', - 'userFetch2' => 'value2', - 'userFetch3' => 3, - 'userFetch5' => 'value5' - ), $value); - - $value = $config->getUserValueForUsers('appFetch2', 'keyFetch1', - array('userFetch1', 'userFetch4', 'userFetch9')); - $this->assertEquals(array( - 'userFetch1' => 'value1', - 'userFetch4' => 'value4' - ), $value, 'userFetch9 is an non-existent user and should not be shown.'); - - // cleanup - $this->connection->executeUpdate('DELETE FROM `*PREFIX*preferences`'); - } - - public function testDeleteAllUserValues() { - $config = $this->getConfig(); - - // preparation - add something to the database - $data = array( - array('userFetch3', 'appFetch1', 'keyFetch1', 'value1'), - array('userFetch3', 'appFetch1', 'keyFetch2', 'value2'), - array('userFetch3', 'appFetch2', 'keyFetch3', 'value3'), - array('userFetch3', 'appFetch1', 'keyFetch4', 'value4'), - array('userFetch3', 'appFetch4', 'keyFetch1', 'value5'), - array('userFetch3', 'appFetch5', 'keyFetch1', 'value6'), - array('userFetch4', 'appFetch2', 'keyFetch1', 'value7') - ); - foreach ($data as $entry) { - $this->connection->executeUpdate( - 'INSERT INTO `*PREFIX*preferences` (`userid`, `appid`, ' . - '`configkey`, `configvalue`) VALUES (?, ?, ?, ?)', - $entry - ); - } - - $config->deleteAllUserValues('userFetch3'); - - $result = $this->connection->executeQuery( - 'SELECT COUNT(*) AS `count` FROM `*PREFIX*preferences`' - )->fetch(); - $actualCount = $result['count']; - - $this->assertEquals(1, $actualCount, 'After removing `userFetch3` there should be exactly 1 entry left.'); - - // cleanup - $this->connection->executeUpdate('DELETE FROM `*PREFIX*preferences`'); - } - - public function testDeleteAppFromAllUsers() { - $config = $this->getConfig(); - - // preparation - add something to the database - $data = array( - array('userFetch5', 'appFetch1', 'keyFetch1', 'value1'), - array('userFetch5', 'appFetch1', 'keyFetch2', 'value2'), - array('userFetch5', 'appFetch2', 'keyFetch3', 'value3'), - array('userFetch5', 'appFetch1', 'keyFetch4', 'value4'), - array('userFetch5', 'appFetch4', 'keyFetch1', 'value5'), - array('userFetch5', 'appFetch5', 'keyFetch1', 'value6'), - array('userFetch6', 'appFetch2', 'keyFetch1', 'value7') - ); - foreach ($data as $entry) { - $this->connection->executeUpdate( - 'INSERT INTO `*PREFIX*preferences` (`userid`, `appid`, ' . - '`configkey`, `configvalue`) VALUES (?, ?, ?, ?)', - $entry - ); - } - - $config->deleteAppFromAllUsers('appFetch1'); - - $result = $this->connection->executeQuery( - 'SELECT COUNT(*) AS `count` FROM `*PREFIX*preferences`' - )->fetch(); - $actualCount = $result['count']; - - $this->assertEquals(4, $actualCount, 'After removing `appFetch1` there should be exactly 4 entries left.'); - - $config->deleteAppFromAllUsers('appFetch2'); - - $result = $this->connection->executeQuery( - 'SELECT COUNT(*) AS `count` FROM `*PREFIX*preferences`' - )->fetch(); - $actualCount = $result['count']; - - $this->assertEquals(2, $actualCount, 'After removing `appFetch2` there should be exactly 2 entries left.'); - - // cleanup - $this->connection->executeUpdate('DELETE FROM `*PREFIX*preferences`'); - } - - public function testGetUsersForUserValue() { - // mock the check for the database to run the correct SQL statements for each database type - $systemConfig = $this->getMockBuilder('\OC\SystemConfig') - ->disableOriginalConstructor() - ->getMock(); - $systemConfig->expects($this->once()) - ->method('getValue') - ->with($this->equalTo('dbtype'), - $this->equalTo('sqlite')) - ->will($this->returnValue(\OC::$server->getConfig()->getSystemValue('dbtype', 'sqlite'))); - $config = $this->getConfig($systemConfig); - - // preparation - add something to the database - $data = array( - array('user1', 'appFetch9', 'keyFetch9', 'value9'), - array('user2', 'appFetch9', 'keyFetch9', 'value9'), - array('user3', 'appFetch9', 'keyFetch9', 'value8'), - array('user4', 'appFetch9', 'keyFetch8', 'value9'), - array('user5', 'appFetch8', 'keyFetch9', 'value9'), - array('user6', 'appFetch9', 'keyFetch9', 'value9'), - ); - foreach ($data as $entry) { - $this->connection->executeUpdate( - 'INSERT INTO `*PREFIX*preferences` (`userid`, `appid`, ' . - '`configkey`, `configvalue`) VALUES (?, ?, ?, ?)', - $entry - ); - } - - $value = $config->getUsersForUserValue('appFetch9', 'keyFetch9', 'value9'); - $this->assertEquals(array('user1', 'user2', 'user6'), $value); - - // cleanup - $this->connection->executeUpdate('DELETE FROM `*PREFIX*preferences`'); - } - -} diff --git a/tests/lib/api.php b/tests/lib/api.php deleted file mode 100644 index 1d1f97c4942..00000000000 --- a/tests/lib/api.php +++ /dev/null @@ -1,197 +0,0 @@ - - * This file is licensed under the Affero General Public License version 3 or - * later. - * See the COPYING-README file. - */ - -class Test_API extends \Test\TestCase { - - // Helps build a response variable - - /** - * @param string $message - */ - function buildResponse($shipped, $data, $code, $message=null) { - $resp = new OC_OCS_Result($data, $code, $message); - $resp->addHeader('KEY', 'VALUE'); - return [ - 'shipped' => $shipped, - 'response' => $resp, - 'app' => $this->getUniqueID('testapp_'), - ]; - } - - // Validate details of the result - - /** - * @param OC_OCS_Result $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()); - } - - /** - * @return array - */ - public function versionDataScriptNameProvider() { - return [ - // Valid script name - [ - '/master/ocs/v2.php', - true, - ], - - // Invalid script names - [ - '/master/ocs/v2.php/someInvalidPathName', - false, - ], - [ - '/master/ocs/v1.php', - false, - ], - [ - '', - false, - ], - ]; - } - - /** - * @dataProvider versionDataScriptNameProvider - * @param string $scriptName - * @param bool $expected - */ - public function testIsV2($scriptName, $expected) { - $request = $this->getMockBuilder('\OCP\IRequest') - ->disableOriginalConstructor() - ->getMock(); - $request - ->expects($this->once()) - ->method('getScriptName') - ->will($this->returnValue($scriptName)); - - $this->assertEquals($expected, $this->invokePrivate(new \OC_API, 'isV2', [$request])); - } - - function dataProviderTestOneResult() { - return [ - [100, true], - [101, false], - [997, false], - ]; - } - - /** - * @dataProvider dataProviderTestOneResult - * - * @param $statusCode - * @param $succeeded - */ - public function testOneResult($statusCode, $succeeded) { - // Setup some data arrays - $data1 = [ - 'users' => [ - 'tom' => [ - 'key' => 'value', - ], - 'frank' => [ - 'key' => 'value', - ], - ]]; - - // Test merging one success result - $response = $this->buildResponse(true, $data1, $statusCode); - $result = OC_API::mergeResponses([$response]); - $this->assertEquals($response['response'], $result); - $this->checkResult($result, $succeeded); - } - - function dataProviderTestMergeResponses() { - return [ - // Two shipped success results - [true, 100, true, 100, true], - // Two shipped results, one success and one failure - [true, 100, true, 998, false], - // Two shipped results, both failure - [true, 997, true, 998, false], - // Two third party success results - [false, 100, false, 100, true], - // Two third party results, one success and one failure - [false, 100, false, 998, false], - // Two third party results, both failure - [false, 997, false, 998, false], - // One of each, both success - [false, 100, true, 100, true], - [true, 100, false, 100, true], - // One of each, both failure - [false, 997, true, 998, false], - // One of each, shipped success - [false, 997, true, 100, true], - // One of each, third party success - [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(); - $resultHeaders = $result->getHeaders(); - $resultStatusCode = $result->getStatusCode(); - - $this->assertArrayHasKey('jan', $resultData['users']); - $this->assertArrayHasKey('KEY', $resultHeaders); - - // 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 deleted file mode 100644 index e7255ad955a..00000000000 --- a/tests/lib/app.php +++ /dev/null @@ -1,546 +0,0 @@ - - * Copyright (c) 2014 Vincent Petry - * This file is licensed under the Affero General Public License version 3 or - * later. - * See the COPYING-README file. - */ - -/** - * Class Test_App - * - * @group DB - */ -class Test_App extends \Test\TestCase { - - const TEST_USER1 = 'user1'; - const TEST_USER2 = 'user2'; - const TEST_USER3 = 'user3'; - const TEST_GROUP1 = 'group1'; - const TEST_GROUP2 = 'group2'; - - function appVersionsProvider() { - return array( - // exact match - array( - '6.0.0.0', - array( - 'requiremin' => '6.0', - 'requiremax' => '6.0', - ), - true - ), - // in-between match - array( - '6.0.0.0', - array( - 'requiremin' => '5.0', - 'requiremax' => '7.0', - ), - true - ), - // app too old - array( - '6.0.0.0', - array( - 'requiremin' => '5.0', - 'requiremax' => '5.0', - ), - false - ), - // app too new - array( - '5.0.0.0', - array( - 'requiremin' => '6.0', - 'requiremax' => '6.0', - ), - false - ), - // only min specified - array( - '6.0.0.0', - array( - 'requiremin' => '6.0', - ), - true - ), - // only min specified fail - array( - '5.0.0.0', - array( - 'requiremin' => '6.0', - ), - false - ), - // only min specified legacy - array( - '6.0.0.0', - array( - 'require' => '6.0', - ), - true - ), - // only min specified legacy fail - array( - '4.0.0.0', - array( - 'require' => '6.0', - ), - false - ), - // only max specified - array( - '5.0.0.0', - array( - 'requiremax' => '6.0', - ), - true - ), - // only max specified fail - array( - '7.0.0.0', - array( - 'requiremax' => '6.0', - ), - false - ), - // variations of versions - // single OC number - array( - '4', - array( - 'require' => '4.0', - ), - true - ), - // multiple OC number - array( - '4.3.1', - array( - 'require' => '4.3', - ), - true - ), - // single app number - array( - '4', - array( - 'require' => '4', - ), - true - ), - // single app number fail - array( - '4.3', - array( - 'require' => '5', - ), - false - ), - // complex - array( - '5.0.0', - array( - 'require' => '4.5.1', - ), - true - ), - // complex fail - array( - '4.3.1', - array( - 'require' => '4.3.2', - ), - false - ), - // two numbers - array( - '4.3.1', - array( - 'require' => '4.4', - ), - false - ), - // one number fail - array( - '4.3.1', - array( - 'require' => '5', - ), - false - ), - // pre-alpha app - array( - '5.0.3', - array( - 'require' => '4.93', - ), - true - ), - // pre-alpha OC - array( - '6.90.0.2', - array( - 'require' => '6.90', - ), - true - ), - // pre-alpha OC max - array( - '6.90.0.2', - array( - 'requiremax' => '7', - ), - true - ), - // expect same major number match - array( - '5.0.3', - array( - 'require' => '5', - ), - true - ), - // expect same major number match - array( - '5.0.3', - array( - 'requiremax' => '5', - ), - true - ), - // dependencies versions before require* - array( - '6.0.0.0', - array( - 'requiremin' => '5.0', - 'requiremax' => '7.0', - 'dependencies' => array( - 'owncloud' => array( - '@attributes' => array( - 'min-version' => '7.0', - 'max-version' => '7.0', - ), - ), - ), - ), - false - ), - array( - '6.0.0.0', - array( - 'requiremin' => '5.0', - 'requiremax' => '7.0', - 'dependencies' => array( - 'owncloud' => array( - '@attributes' => array( - 'min-version' => '5.0', - 'max-version' => '5.0', - ), - ), - ), - ), - false - ), - array( - '6.0.0.0', - array( - 'requiremin' => '5.0', - 'requiremax' => '5.0', - 'dependencies' => array( - 'owncloud' => array( - '@attributes' => array( - 'min-version' => '5.0', - 'max-version' => '7.0', - ), - ), - ), - ), - true - ), - ); - } - - /** - * @dataProvider appVersionsProvider - */ - public function testIsAppCompatible($ocVersion, $appInfo, $expectedResult) { - $this->assertEquals($expectedResult, OC_App::isAppCompatible($ocVersion, $appInfo)); - } - - /** - * Test that the isAppCompatible method also supports passing an array - * as $ocVersion - */ - public function testIsAppCompatibleWithArray() { - $ocVersion = array(6); - $appInfo = array( - 'requiremin' => '6', - 'requiremax' => '6', - ); - $this->assertTrue(OC_App::isAppCompatible($ocVersion, $appInfo)); - } - - /** - * Tests that the app order is correct - */ - public function testGetEnabledAppsIsSorted() { - $apps = \OC_App::getEnabledApps(); - // 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); - } - - /** - * Providers for the app config values - */ - function appConfigValuesProvider() { - return array( - // logged in user1 - array( - self::TEST_USER1, - array( - 'files', - 'app1', - 'app3', - 'appforgroup1', - 'appforgroup12', - 'dav', - 'federatedfilesharing', - ), - false - ), - // logged in user2 - array( - self::TEST_USER2, - array( - 'files', - 'app1', - 'app3', - 'appforgroup12', - 'appforgroup2', - 'dav', - 'federatedfilesharing', - ), - false - ), - // logged in user3 - array( - self::TEST_USER3, - array( - 'files', - 'app1', - 'app3', - 'appforgroup1', - 'appforgroup12', - 'appforgroup2', - 'dav', - 'federatedfilesharing', - ), - false - ), - // no user, returns all apps - array( - null, - array( - 'files', - 'app1', - 'app3', - 'appforgroup1', - 'appforgroup12', - 'appforgroup2', - 'dav', - 'federatedfilesharing', - ), - false, - ), - // user given, but ask for all - array( - self::TEST_USER1, - array( - 'files', - 'app1', - 'app3', - 'appforgroup1', - 'appforgroup12', - 'appforgroup2', - 'dav', - 'federatedfilesharing', - ), - true, - ), - ); - } - - /** - * Test enabled apps - * - * @dataProvider appConfigValuesProvider - */ - public function testEnabledApps($user, $expectedApps, $forceAll) { - $userManager = \OC::$server->getUserManager(); - $groupManager = \OC::$server->getGroupManager(); - $user1 = $userManager->createUser(self::TEST_USER1, self::TEST_USER1); - $user2 = $userManager->createUser(self::TEST_USER2, self::TEST_USER2); - $user3 = $userManager->createUser(self::TEST_USER3, self::TEST_USER3); - - $group1 = $groupManager->createGroup(self::TEST_GROUP1); - $group1->addUser($user1); - $group1->addUser($user3); - $group2 = $groupManager->createGroup(self::TEST_GROUP2); - $group2->addUser($user2); - $group2->addUser($user3); - - \OC_User::setUserId($user); - - $this->setupAppConfigMock()->expects($this->once()) - ->method('getValues') - ->will($this->returnValue( - array( - 'app3' => 'yes', - 'app2' => 'no', - 'app1' => 'yes', - 'appforgroup1' => '["group1"]', - 'appforgroup2' => '["group2"]', - 'appforgroup12' => '["group2","group1"]', - ) - ) - ); - - $apps = \OC_App::getEnabledApps(false, $forceAll); - - $this->restoreAppConfig(); - \OC_User::setUserId(null); - - $user1->delete(); - $user2->delete(); - $user3->delete(); - - $group1->delete(); - $group2->delete(); - - $this->assertEquals($expectedApps, $apps); - } - - /** - * Test isEnabledApps() with cache, not re-reading the list of - * enabled apps more than once when a user is set. - */ - public function testEnabledAppsCache() { - $userManager = \OC::$server->getUserManager(); - $user1 = $userManager->createUser(self::TEST_USER1, self::TEST_USER1); - - \OC_User::setUserId(self::TEST_USER1); - - $this->setupAppConfigMock()->expects($this->once()) - ->method('getValues') - ->will($this->returnValue( - array( - 'app3' => 'yes', - 'app2' => 'no', - ) - ) - ); - - $apps = \OC_App::getEnabledApps(); - $this->assertEquals(array('files', 'app3', 'dav', 'federatedfilesharing',), $apps); - - // mock should not be called again here - $apps = \OC_App::getEnabledApps(); - $this->assertEquals(array('files', 'app3', 'dav', 'federatedfilesharing',), $apps); - - $this->restoreAppConfig(); - \OC_User::setUserId(null); - - $user1->delete(); - } - - - private function setupAppConfigMock() { - $appConfig = $this->getMock( - '\OC\AppConfig', - array('getValues'), - array(\OC::$server->getDatabaseConnection()), - '', - false - ); - - $this->registerAppConfig($appConfig); - return $appConfig; - } - - /** - * Register an app config mock for testing purposes. - * - * @param $appConfig app config mock - */ - private function registerAppConfig($appConfig) { - \OC::$server->registerService('AppConfig', function ($c) use ($appConfig) { - return $appConfig; - }); - \OC::$server->registerService('AppManager', function (\OC\Server $c) use ($appConfig) { - return new \OC\App\AppManager($c->getUserSession(), $appConfig, $c->getGroupManager(), $c->getMemCacheFactory(), $c->getEventDispatcher()); - }); - } - - /** - * Restore the original app config service. - */ - private function restoreAppConfig() { - \OC::$server->registerService('AppConfig', function (\OC\Server $c) { - return new \OC\AppConfig($c->getDatabaseConnection()); - }); - \OC::$server->registerService('AppManager', function (\OC\Server $c) { - return new \OC\App\AppManager($c->getUserSession(), $c->getAppConfig(), $c->getGroupManager(), $c->getMemCacheFactory(), $c->getEventDispatcher()); - }); - - // Remove the cache of the mocked apps list with a forceRefresh - \OC_App::getEnabledApps(); - } - - /** - * Providers for the app data values - */ - function appDataProvider() { - return [ - [ - ['description' => " \t This is a multiline \n test with \n \t \n \n some new lines "], - ['description' => "This is a multiline test with\n\nsome new lines"] - ], - [ - ['description' => " \t This is a multiline \n test with \n \t some new lines "], - ['description' => "This is a multiline test with some new lines"] - ], - [ - ['description' => hex2bin('5065726d657420646520732761757468656e7469666965722064616e732070697769676f20646972656374656d656e74206176656320736573206964656e74696669616e7473206f776e636c6f75642073616e73206c65732072657461706572206574206d657420c3a0206a6f757273206365757820636920656e20636173206465206368616e67656d656e74206465206d6f742064652070617373652e0d0a0d')], - ['description' => "Permet de s'authentifier dans piwigo directement avec ses identifiants owncloud sans les retaper et met à jours ceux ci en cas de changement de mot de passe."] - ], - [ - ['not-a-description' => " \t This is a multiline \n test with \n \t some new lines "], - ['not-a-description' => " \t This is a multiline \n test with \n \t some new lines "] - ], - [ - ['description' => [100, 'bla']], - ['description' => ""] - ], - ]; - } - - /** - * Test app info parser - * - * @dataProvider appDataProvider - * @param array $data - * @param array $expected - */ - public function testParseAppInfo(array $data, array $expected) { - $this->assertSame($expected, \OC_App::parseAppInfo($data)); - } -} - diff --git a/tests/lib/appconfig.php b/tests/lib/appconfig.php index 64f0f80e045..12d9728c868 100644 --- a/tests/lib/appconfig.php +++ b/tests/lib/appconfig.php @@ -7,16 +7,14 @@ * See the COPYING-README file. */ -namespace Test\Lib; - -use Test\TestCase; +namespace Test; /** * Class AppConfig * * @group DB * - * @package Test\Lib + * @package Test */ class AppConfig extends TestCase { /** @var \OCP\IAppConfig */ diff --git a/tests/lib/avatarmanagertest.php b/tests/lib/avatarmanagertest.php index f5cdd99176d..2dd6ff34923 100644 --- a/tests/lib/avatarmanagertest.php +++ b/tests/lib/avatarmanagertest.php @@ -18,6 +18,9 @@ * along with this program. If not, see * */ + +namespace Test; + use OC\AvatarManager; use Test\Traits\UserTrait; use Test\Traits\MountProviderTrait; @@ -48,7 +51,7 @@ class AvatarManagerTest extends \Test\TestCase { } /** - * @expectedException Exception + * @expectedException \Exception * @expectedExceptionMessage user does not exist */ public function testGetAvatarInvalidUser() { diff --git a/tests/lib/avatartest.php b/tests/lib/avatartest.php index b0ab4cb8b5c..0a00f5d5614 100644 --- a/tests/lib/avatartest.php +++ b/tests/lib/avatartest.php @@ -1,5 +1,4 @@ * This file is licensed under the Affero General Public License version 3 or @@ -7,23 +6,25 @@ * See the COPYING-README file. */ +namespace Test; + use OCP\Files\Folder; class AvatarTest extends \Test\TestCase { - /** @var Folder | PHPUnit_Framework_MockObject_MockObject */ + /** @var Folder | \PHPUnit_Framework_MockObject_MockObject */ private $folder; /** @var \OC\Avatar */ private $avatar; - /** @var \OC\User\User | PHPUnit_Framework_MockObject_MockObject $user */ + /** @var \OC\User\User | \PHPUnit_Framework_MockObject_MockObject $user */ private $user; public function setUp() { parent::setUp(); $this->folder = $this->getMock('\OCP\Files\Folder'); - /** @var \OCP\IL10N | PHPUnit_Framework_MockObject_MockObject $l */ + /** @var \OCP\IL10N | \PHPUnit_Framework_MockObject_MockObject $l */ $l = $this->getMock('\OCP\IL10N'); $l->method('t')->will($this->returnArgument(0)); $this->user = $this->getMockBuilder('\OC\User\User')->disableOriginalConstructor()->getMock(); @@ -41,7 +42,7 @@ class AvatarTest extends \Test\TestCase { ['avatar.128.jpg', true], ])); - $expected = new OC_Image(\OC::$SERVERROOT . '/tests/data/testavatar.png'); + $expected = new \OC_Image(\OC::$SERVERROOT . '/tests/data/testavatar.png'); $file = $this->getMock('\OCP\Files\File'); $file->method('getContent')->willReturn($expected->data()); @@ -56,7 +57,7 @@ class AvatarTest extends \Test\TestCase { ['avatar.jpg', true], ])); - $expected = new OC_Image(\OC::$SERVERROOT . '/tests/data/testavatar.png'); + $expected = new \OC_Image(\OC::$SERVERROOT . '/tests/data/testavatar.png'); $file = $this->getMock('\OCP\Files\File'); $file->method('getContent')->willReturn($expected->data()); @@ -72,8 +73,8 @@ class AvatarTest extends \Test\TestCase { ['avatar.32.png', false], ])); - $expected = new OC_Image(\OC::$SERVERROOT . '/tests/data/testavatar.png'); - $expected2 = new OC_Image(\OC::$SERVERROOT . '/tests/data/testavatar.png'); + $expected = new \OC_Image(\OC::$SERVERROOT . '/tests/data/testavatar.png'); + $expected2 = new \OC_Image(\OC::$SERVERROOT . '/tests/data/testavatar.png'); $expected2->resize(32); $file = $this->getMock('\OCP\Files\File'); @@ -157,7 +158,7 @@ class AvatarTest extends \Test\TestCase { ->with('avatar.png') ->willReturn($newFile); - $image = new OC_Image(\OC::$SERVERROOT . '/tests/data/testavatar.png'); + $image = new \OC_Image(\OC::$SERVERROOT . '/tests/data/testavatar.png'); $newFile->expects($this->once()) ->method('putContent') ->with($image->data()); diff --git a/tests/lib/capabilitiesmanager.php b/tests/lib/capabilitiesmanager.php deleted file mode 100644 index b5dac80ee51..00000000000 --- a/tests/lib/capabilitiesmanager.php +++ /dev/null @@ -1,164 +0,0 @@ - - * - * @copyright Copyright (c) 2015, ownCloud, Inc. - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see - * - */ - -namespace Test; - -use OC\CapabilitiesManager; - -class CapabilitiesManagerTest extends TestCase { - - /** - * Test no capabilities - */ - public function testNoCapabilities() { - $manager = new \OC\CapabilitiesManager(); - $res = $manager->getCapabilities(); - $this->assertEmpty($res); - } - - /** - * Test a valid capabilitie - */ - public function testValidCapability() { - $manager = new \OC\CapabilitiesManager(); - - $manager->registerCapability(function() { - return new SimpleCapability(); - }); - - $res = $manager->getCapabilities(); - $this->assertEquals(['foo' => 1], $res); - } - - /** - * Test that we need something that implents ICapability - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage The given Capability (Test\NoCapability) does not implement the ICapability interface - */ - public function testNoICapability() { - $manager = new \OC\CapabilitiesManager(); - - $manager->registerCapability(function() { - return new NoCapability(); - }); - - $res = $manager->getCapabilities(); - $this->assertEquals([], $res); - } - - /** - * Test a bunch of merged Capabilities - */ - public function testMergedCapabilities() { - $manager = new \OC\CapabilitiesManager(); - - $manager->registerCapability(function() { - return new SimpleCapability(); - }); - $manager->registerCapability(function() { - return new SimpleCapability2(); - }); - $manager->registerCapability(function() { - return new SimpleCapability3(); - }); - - $res = $manager->getCapabilities(); - $expected = [ - 'foo' => 1, - 'bar' => [ - 'x' => 1, - 'y' => 2 - ] - ]; - - $this->assertEquals($expected, $res); - } - - /** - * Test deep identical capabilities - */ - public function testDeepIdenticalCapabilities() { - $manager = new \OC\CapabilitiesManager(); - - $manager->registerCapability(function() { - return new DeepCapability(); - }); - $manager->registerCapability(function() { - return new DeepCapability(); - }); - - $res = $manager->getCapabilities(); - $expected = [ - 'foo' => [ - 'bar' => [ - 'baz' => true - ] - ] - ]; - - $this->assertEquals($expected, $res); - } -} - -class SimpleCapability implements \OCP\Capabilities\ICapability { - public function getCapabilities() { - return [ - 'foo' => 1 - ]; - } -} - -class SimpleCapability2 implements \OCP\Capabilities\ICapability { - public function getCapabilities() { - return [ - 'bar' => ['x' => 1] - ]; - } -} - -class SimpleCapability3 implements \OCP\Capabilities\ICapability { - public function getCapabilities() { - return [ - 'bar' => ['y' => 2] - ]; - } -} - -class NoCapability { - public function getCapabilities() { - return [ - 'baz' => 'z' - ]; - } -} - -class DeepCapability implements \OCP\Capabilities\ICapability { - public function getCapabilities() { - return [ - 'foo' => [ - 'bar' => [ - 'baz' => true - ] - ] - ]; - } -} - diff --git a/tests/lib/configtests.php b/tests/lib/configtests.php deleted file mode 100644 index c0251e693c6..00000000000 --- a/tests/lib/configtests.php +++ /dev/null @@ -1,142 +0,0 @@ - - * This file is licensed under the Affero General Public License version 3 or - * later. - * See the COPYING-README file. - */ - -namespace Test; - -class ConfigTests extends TestCase { - const TESTCONTENT = '"bar", "beers" => array("Appenzeller", "Guinness", "Kölsch"), "alcohol_free" => false);'; - - /** @var array */ - private $initialConfig = array('foo' => 'bar', 'beers' => array('Appenzeller', 'Guinness', 'Kölsch'), 'alcohol_free' => false); - /** @var string */ - private $configFile; - /** @var \OC\Config */ - private $config; - /** @var string */ - private $randomTmpDir; - - protected function setUp() { - parent::setUp(); - - $this->randomTmpDir = \OC::$server->getTempManager()->getTemporaryFolder(); - $this->configFile = $this->randomTmpDir.'testconfig.php'; - file_put_contents($this->configFile, self::TESTCONTENT); - $this->config = new \OC\Config($this->randomTmpDir, 'testconfig.php'); - } - - protected function tearDown() { - unlink($this->configFile); - parent::tearDown(); - } - - public function testGetKeys() { - $expectedConfig = array('foo', 'beers', 'alcohol_free'); - $this->assertSame($expectedConfig, $this->config->getKeys()); - } - - public function testGetValue() { - $this->assertSame('bar', $this->config->getValue('foo')); - $this->assertSame(null, $this->config->getValue('bar')); - $this->assertSame('moo', $this->config->getValue('bar', 'moo')); - $this->assertSame(false, $this->config->getValue('alcohol_free', 'someBogusValue')); - $this->assertSame(array('Appenzeller', 'Guinness', 'Kölsch'), $this->config->getValue('beers', 'someBogusValue')); - $this->assertSame(array('Appenzeller', 'Guinness', 'Kölsch'), $this->config->getValue('beers')); - } - - public function testSetValue() { - $this->config->setValue('foo', 'moo'); - $expectedConfig = $this->initialConfig; - $expectedConfig['foo'] = 'moo'; - $this->assertAttributeEquals($expectedConfig, 'cache', $this->config); - - $content = file_get_contents($this->configFile); - $expected = " 'moo',\n 'beers' => \n array (\n 0 => 'Appenzeller',\n " . - " 1 => 'Guinness',\n 2 => 'Kölsch',\n ),\n 'alcohol_free' => false,\n);\n"; - $this->assertEquals($expected, $content); - - $this->config->setValue('bar', 'red'); - $this->config->setValue('apps', array('files', 'gallery')); - $expectedConfig['bar'] = 'red'; - $expectedConfig['apps'] = array('files', 'gallery'); - $this->assertAttributeEquals($expectedConfig, 'cache', $this->config); - - $content = file_get_contents($this->configFile); - - $expected = " 'moo',\n 'beers' => \n array (\n 0 => 'Appenzeller',\n " . - " 1 => 'Guinness',\n 2 => 'Kölsch',\n ),\n 'alcohol_free' => false,\n 'bar' => 'red',\n 'apps' => \n " . - " array (\n 0 => 'files',\n 1 => 'gallery',\n ),\n);\n"; - $this->assertEquals($expected, $content); - } - - public function testSetValues() { - $content = file_get_contents($this->configFile); - $this->assertEquals(self::TESTCONTENT, $content); - - // Changing configs to existing values and deleting non-existing once - // should not rewrite the config.php - $this->config->setValues([ - 'foo' => 'bar', - 'not_exists' => null, - ]); - - $this->assertAttributeEquals($this->initialConfig, 'cache', $this->config); - $content = file_get_contents($this->configFile); - $this->assertEquals(self::TESTCONTENT, $content); - - $this->config->setValues([ - 'foo' => 'moo', - 'alcohol_free' => null, - ]); - $expectedConfig = $this->initialConfig; - $expectedConfig['foo'] = 'moo'; - unset($expectedConfig['alcohol_free']); - $this->assertAttributeEquals($expectedConfig, 'cache', $this->config); - - $content = file_get_contents($this->configFile); - $expected = " 'moo',\n 'beers' => \n array (\n 0 => 'Appenzeller',\n " . - " 1 => 'Guinness',\n 2 => 'Kölsch',\n ),\n);\n"; - $this->assertEquals($expected, $content); - } - - public function testDeleteKey() { - $this->config->deleteKey('foo'); - $expectedConfig = $this->initialConfig; - unset($expectedConfig['foo']); - $this->assertAttributeEquals($expectedConfig, 'cache', $this->config); - $content = file_get_contents($this->configFile); - - $expected = " \n array (\n 0 => 'Appenzeller',\n " . - " 1 => 'Guinness',\n 2 => 'Kölsch',\n ),\n 'alcohol_free' => false,\n);\n"; - $this->assertEquals($expected, $content); - } - - public function testConfigMerge() { - // Create additional config - $additionalConfig = '"totallyOutdated");'; - $additionalConfigPath = $this->randomTmpDir.'additionalConfig.testconfig.php'; - file_put_contents($additionalConfigPath, $additionalConfig); - - // Reinstantiate the config to force a read-in of the additional configs - $this->config = new \OC\Config($this->randomTmpDir, 'testconfig.php'); - - // Ensure that the config value can be read and the config has not been modified - $this->assertSame('totallyOutdated', $this->config->getValue('php53', 'bogusValue')); - $this->assertEquals(self::TESTCONTENT, file_get_contents($this->configFile)); - - // Write a new value to the config - $this->config->setValue('CoolWebsites', array('demo.owncloud.org', 'owncloud.org', 'owncloud.com')); - $expected = " 'bar',\n 'beers' => \n array (\n 0 => 'Appenzeller',\n " . - " 1 => 'Guinness',\n 2 => 'Kölsch',\n ),\n 'alcohol_free' => false,\n 'php53' => 'totallyOutdated',\n 'CoolWebsites' => \n array (\n " . - " 0 => 'demo.owncloud.org',\n 1 => 'owncloud.org',\n 2 => 'owncloud.com',\n ),\n);\n"; - $this->assertEquals($expected, file_get_contents($this->configFile)); - - // Cleanup - unlink($additionalConfigPath); - } - -} diff --git a/tests/lib/contactsmanager.php b/tests/lib/contactsmanager.php deleted file mode 100644 index 39e44cc6302..00000000000 --- a/tests/lib/contactsmanager.php +++ /dev/null @@ -1,209 +0,0 @@ -cm = new \OC\ContactsManager(); - } - - public function searchProvider(){ - $search1 = array( - 0 => array( - 'N' => array(0 => '', 1 => 'Jan', 2 => 'Jansen', 3 => '', 4 => '',), - 'UID' => '04ada7f5-01f9-4309-9c82-6b555b2170ed', - 'FN' => 'Jan Jansen', - 'id' => '1', - 'addressbook-key' => 'simple:1', - ), - 0 => array( - 'N' => array(0 => '', 1 => 'Tom', 2 => 'Peeters', 3 => '', 4 => '',), - 'UID' => '04ada7f5-01f9-4309-9c82-2345-2345--6b555b2170ed', - 'FN' => 'Tom Peeters', - 'id' => '2', - 'addressbook-key' => 'simple:1', - ), - ); - - $search2 = array( - 0 => array( - 'N' => array(0 => '', 1 => 'fg', 2 => '', 3 => '', 4 => '',), - 'UID' => '04ada234h5jh357f5-01f9-4309-9c82-6b555b2170ed', - 'FN' => 'Jan Rompuy', - 'id' => '1', - 'addressbook-key' => 'simple:2', - ), - 0 => array( - 'N' => array(0 => '', 1 => 'fg', 2 => '', 3 => '', 4 => '',), - 'UID' => '04ada7f5-01f9-4309-345kj345j9c82-2345-2345--6b555b2170ed', - 'FN' => 'Tim Peeters', - 'id' => '2', - 'addressbook-key' => 'simple:2', - ), - ); - - $expectedResult = array_merge($search1, $search2); - return array( - array( - $search1, - $search2, - $expectedResult - ) - ); - } - - /** - * @dataProvider searchProvider - */ - public function testSearch($search1, $search2, $expectedResult ){ - $addressbook1 = $this->getMockBuilder('\OCP\IAddressBook') - ->disableOriginalConstructor() - ->getMock(); - - $addressbook1->expects($this->once()) - ->method('search') - ->willReturn($search1); - - $addressbook1->expects($this->any()) - ->method('getKey') - ->willReturn('simple:1'); - - $addressbook2 = $this->getMockBuilder('\OCP\IAddressBook') - ->disableOriginalConstructor() - ->getMock(); - - $addressbook2->expects($this->once()) - ->method('search') - ->willReturn($search2); - - $addressbook2->expects($this->any()) - ->method('getKey') - ->willReturn('simple:2'); - - - $this->cm->registerAddressBook($addressbook1); - $this->cm->registerAddressBook($addressbook2); - $result = $this->cm->search(''); - $this->assertEquals($expectedResult, $result); - } - - - public function testDeleteHavePermission(){ - $addressbook = $this->getMockBuilder('\OCP\IAddressBook') - ->disableOriginalConstructor() - ->getMock(); - - $addressbook->expects($this->any()) - ->method('getPermissions') - ->willReturn(\OCP\Constants::PERMISSION_ALL); - - $addressbook->expects($this->once()) - ->method('delete') - ->willReturn('returnMe'); - - - $this->cm->registerAddressBook($addressbook); - $result = $this->cm->delete(1, $addressbook->getKey()); - $this->assertEquals($result, 'returnMe'); - } - - public function testDeleteNoPermission(){ - $addressbook = $this->getMockBuilder('\OCP\IAddressBook') - ->disableOriginalConstructor() - ->getMock(); - - $addressbook->expects($this->any()) - ->method('getPermissions') - ->willReturn(\OCP\Constants::PERMISSION_READ); - - $addressbook->expects($this->never()) - ->method('delete'); - - $this->cm->registerAddressBook($addressbook); - $result = $this->cm->delete(1, $addressbook->getKey()); - $this->assertEquals($result, null); - } - - public function testDeleteNoAddressbook(){ - $addressbook = $this->getMockBuilder('\OCP\IAddressBook') - ->disableOriginalConstructor() - ->getMock(); - - $addressbook->expects($this->never()) - ->method('delete'); - - $this->cm->registerAddressBook($addressbook); - $result = $this->cm->delete(1, 'noaddressbook'); - $this->assertEquals($result, null); - - } - - public function testCreateOrUpdateHavePermission(){ - $addressbook = $this->getMockBuilder('\OCP\IAddressBook') - ->disableOriginalConstructor() - ->getMock(); - - $addressbook->expects($this->any()) - ->method('getPermissions') - ->willReturn(\OCP\Constants::PERMISSION_ALL); - - $addressbook->expects($this->once()) - ->method('createOrUpdate') - ->willReturn('returnMe'); - - $this->cm->registerAddressBook($addressbook); - $result = $this->cm->createOrUpdate(array(), $addressbook->getKey()); - $this->assertEquals($result, 'returnMe'); - } - - public function testCreateOrUpdateNoPermission(){ - $addressbook = $this->getMockBuilder('\OCP\IAddressBook') - ->disableOriginalConstructor() - ->getMock(); - - $addressbook->expects($this->any()) - ->method('getPermissions') - ->willReturn(\OCP\Constants::PERMISSION_READ); - - $addressbook->expects($this->never()) - ->method('createOrUpdate'); - - $this->cm->registerAddressBook($addressbook); - $result = $this->cm->createOrUpdate(array(), $addressbook->getKey()); - $this->assertEquals($result, null); - - } - - public function testCreateOrUpdateNOAdressbook(){ - $addressbook = $this->getMockBuilder('\OCP\IAddressBook') - ->disableOriginalConstructor() - ->getMock(); - - $addressbook->expects($this->never()) - ->method('createOrUpdate'); - - $this->cm->registerAddressBook($addressbook); - $result = $this->cm->createOrUpdate(array(), 'noaddressbook'); - $this->assertEquals($result, null); - } - - public function testIsEnabledIfNot(){ - $result = $this->cm->isEnabled(); - $this->assertFalse($result); - } - - public function testIsEnabledIfSo(){ - $addressbook = $this->getMockBuilder('\OCP\IAddressBook') - ->disableOriginalConstructor() - ->getMock(); - - $this->cm->registerAddressBook($addressbook); - $result = $this->cm->isEnabled(); - $this->assertTrue($result); - } - -} \ No newline at end of file diff --git a/tests/lib/db.php b/tests/lib/db.php deleted file mode 100644 index 88c9ee75b3b..00000000000 --- a/tests/lib/db.php +++ /dev/null @@ -1,389 +0,0 @@ - - * This file is licensed under the Affero General Public License version 3 or - * later. - * See the COPYING-README file. - */ - -/** - * Class Test_DB - * - * @group DB - */ -class Test_DB extends \Test\TestCase { - protected $backupGlobals = FALSE; - - protected static $schema_file = 'static://test_db_scheme'; - protected $test_prefix; - - /** - * @var string - */ - private $table1; - - /** - * @var string - */ - private $table2; - - /** - * @var string - */ - private $table3; - - /** - * @var string - */ - private $table4; - - /** - * @var string - */ - private $table5; - - protected function setUp() { - parent::setUp(); - - $dbFile = OC::$SERVERROOT.'/tests/data/db_structure.xml'; - - $r = $this->getUniqueID('_', 4).'_'; - $content = file_get_contents( $dbFile ); - $content = str_replace( '*dbprefix*', '*dbprefix*'.$r, $content ); - file_put_contents( self::$schema_file, $content ); - OC_DB::createDbFromStructure(self::$schema_file); - - $this->test_prefix = $r; - $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'; - $this->table5 = $this->test_prefix.'uniconst'; - } - - protected function tearDown() { - OC_DB::removeDBStructure(self::$schema_file); - unlink(self::$schema_file); - - parent::tearDown(); - } - - public function testQuotes() { - $query = OC_DB::prepare('SELECT `fullname` FROM `*PREFIX*'.$this->table2.'` WHERE `uri` = ?'); - $result = $query->execute(array('uri_1')); - $this->assertTrue((bool)$result); - $row = $result->fetchRow(); - $this->assertFalse($row); - $query = OC_DB::prepare('INSERT INTO `*PREFIX*'.$this->table2.'` (`fullname`,`uri`) VALUES (?,?)'); - $result = $query->execute(array('fullname test', 'uri_1')); - $this->assertEquals(1, $result); - $query = OC_DB::prepare('SELECT `fullname`,`uri` FROM `*PREFIX*'.$this->table2.'` WHERE `uri` = ?'); - $result = $query->execute(array('uri_1')); - $this->assertTrue((bool)$result); - $row = $result->fetchRow(); - $this->assertArrayHasKey('fullname', $row); - $this->assertEquals($row['fullname'], 'fullname test'); - $row = $result->fetchRow(); - $this->assertFalse((bool)$row); //PDO returns false, MDB2 returns null - } - - /** - * @medium - */ - public function testNOW() { - $query = OC_DB::prepare('INSERT INTO `*PREFIX*'.$this->table2.'` (`fullname`,`uri`) VALUES (NOW(),?)'); - $result = $query->execute(array('uri_2')); - $this->assertEquals(1, $result); - $query = OC_DB::prepare('SELECT `fullname`,`uri` FROM `*PREFIX*'.$this->table2.'` WHERE `uri` = ?'); - $result = $query->execute(array('uri_2')); - $this->assertTrue((bool)$result); - } - - public function testUNIX_TIMESTAMP() { - $query = OC_DB::prepare('INSERT INTO `*PREFIX*'.$this->table2.'` (`fullname`,`uri`) VALUES (UNIX_TIMESTAMP(),?)'); - $result = $query->execute(array('uri_3')); - $this->assertEquals(1, $result); - $query = OC_DB::prepare('SELECT `fullname`,`uri` FROM `*PREFIX*'.$this->table2.'` WHERE `uri` = ?'); - $result = $query->execute(array('uri_3')); - $this->assertTrue((bool)$result); - } - - public function testLastInsertId() { - $query = OC_DB::prepare('INSERT INTO `*PREFIX*'.$this->table2.'` (`fullname`,`uri`) VALUES (?,?)'); - $result1 = OC_DB::executeAudited($query, array('insertid 1','uri_1')); - $id1 = \OC::$server->getDatabaseConnection()->lastInsertId('*PREFIX*'.$this->table2); - - // we don't know the id we should expect, so insert another row - $result2 = OC_DB::executeAudited($query, array('insertid 2','uri_2')); - $id2 = \OC::$server->getDatabaseConnection()->lastInsertId('*PREFIX*'.$this->table2); - // now we can check if the two ids are in correct order - $this->assertGreaterThan($id1, $id2); - } - - public function testinsertIfNotExist() { - $categoryEntries = array( - array('user' => 'test', 'type' => 'contact', 'category' => 'Family', 'expectedResult' => 1), - array('user' => 'test', 'type' => 'contact', 'category' => 'Friends', 'expectedResult' => 1), - array('user' => 'test', 'type' => 'contact', 'category' => 'Coworkers', 'expectedResult' => 1), - array('user' => 'test', 'type' => 'contact', 'category' => 'Coworkers', 'expectedResult' => 0), - array('user' => 'test', 'type' => 'contact', 'category' => 'School', 'expectedResult' => 1), - ); - - foreach($categoryEntries as $entry) { - $result = \OCP\DB::insertIfNotExist('*PREFIX*'.$this->table3, - array( - 'uid' => $entry['user'], - 'type' => $entry['type'], - 'category' => $entry['category'], - )); - $this->assertEquals($entry['expectedResult'], $result); - } - - $query = OC_DB::prepare('SELECT * FROM `*PREFIX*'.$this->table3.'`'); - $result = $query->execute(); - $this->assertTrue((bool)$result); - $this->assertEquals(4, count($result->fetchAll())); - } - - public function testInsertIfNotExistNull() { - $categoryEntries = array( - array('addressbookid' => 123, 'fullname' => null, 'expectedResult' => 1), - array('addressbookid' => 123, 'fullname' => null, 'expectedResult' => 0), - array('addressbookid' => 123, 'fullname' => 'test', 'expectedResult' => 1), - ); - - foreach($categoryEntries as $entry) { - $result = \OCP\DB::insertIfNotExist('*PREFIX*'.$this->table2, - array( - 'addressbookid' => $entry['addressbookid'], - 'fullname' => $entry['fullname'], - )); - $this->assertEquals($entry['expectedResult'], $result); - } - - $query = OC_DB::prepare('SELECT * FROM `*PREFIX*'.$this->table2.'`'); - $result = $query->execute(); - $this->assertTrue((bool)$result); - $this->assertEquals(2, count($result->fetchAll())); - } - - public function testInsertIfNotExistDonTOverwrite() { - $fullName = 'fullname test'; - $uri = 'uri_1'; - $carddata = 'This is a vCard'; - - // Normal test to have same known data inserted. - $query = OC_DB::prepare('INSERT INTO `*PREFIX*'.$this->table2.'` (`fullname`, `uri`, `carddata`) VALUES (?, ?, ?)'); - $result = $query->execute(array($fullName, $uri, $carddata)); - $this->assertEquals(1, $result); - $query = OC_DB::prepare('SELECT `fullname`, `uri`, `carddata` FROM `*PREFIX*'.$this->table2.'` WHERE `uri` = ?'); - $result = $query->execute(array($uri)); - $this->assertTrue((bool)$result); - $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 = \OCP\DB::insertIfNotExist('*PREFIX*'.$this->table2, - array( - 'fullname' => $fullName, - 'uri' => $uri, - )); - $this->assertEquals(0, $result); - - $query = OC_DB::prepare('SELECT `fullname`, `uri`, `carddata` FROM `*PREFIX*'.$this->table2.'` WHERE `uri` = ?'); - $result = $query->execute(array($uri)); - $this->assertTrue((bool)$result); - // Test that previously inserted data isn't overwritten - // And that a new row hasn't been inserted. - $rowset = $result->fetchAll(); - $this->assertEquals(1, count($rowset)); - $this->assertArrayHasKey('carddata', $rowset[0]); - $this->assertEquals($carddata, $rowset[0]['carddata']); - } - - public function testInsertIfNotExistsViolating() { - $result = \OCP\DB::insertIfNotExist('*PREFIX*'.$this->table5, - array( - 'storage' => 1, - 'path_hash' => md5('welcome.txt'), - 'etag' => $this->getUniqueID() - )); - $this->assertEquals(1, $result); - - $result = \OCP\DB::insertIfNotExist('*PREFIX*'.$this->table5, - array( - 'storage' => 1, - 'path_hash' => md5('welcome.txt'), - 'etag' => $this->getUniqueID() - ),['storage', 'path_hash']); - - $this->assertEquals(0, $result); - } - - public function insertIfNotExistsViolatingThrows() { - return [ - [null], - [['etag']], - ]; - } - - /** - * @dataProvider insertIfNotExistsViolatingThrows - * @expectedException \Doctrine\DBAL\Exception\UniqueConstraintViolationException - * - * @param array $compareKeys - */ - public function testInsertIfNotExistsViolatingThrows($compareKeys) { - $result = \OCP\DB::insertIfNotExist('*PREFIX*'.$this->table5, - array( - 'storage' => 1, - 'path_hash' => md5('welcome.txt'), - 'etag' => $this->getUniqueID() - )); - $this->assertEquals(1, $result); - - $result = \OCP\DB::insertIfNotExist('*PREFIX*'.$this->table5, - array( - 'storage' => 1, - 'path_hash' => md5('welcome.txt'), - 'etag' => $this->getUniqueID() - ), $compareKeys); - - $this->assertEquals(0, $result); - } - - 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 = OC_DB::prepare("SELECT `fullname` FROM `$table`")->execute()->fetchOne(); - $this->assertSame($expected, $actual); - } - - /** - * Insert, select and delete decimal(12,2) values - * @dataProvider decimalData - */ - public function testDecimal($insert, $expect) { - $table = "*PREFIX*" . $this->table4; - $rowname = 'decimaltest'; - - $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); - } - - public function decimalData() { - return [ - ['1337133713.37', '1337133713.37'], - ['1234567890', '1234567890.00'], - ]; - } - - public function testUpdateAffectedRowsNoMatch() { - $this->insertCardData('fullname1', 'uri1'); - // The WHERE clause does not match any rows - $this->assertSame(0, $this->updateCardData('fullname3', 'uri2')); - } - - public function testUpdateAffectedRowsDifferent() { - $this->insertCardData('fullname1', 'uri1'); - // The WHERE clause matches a single row and the value we are updating - // is different from the one already present. - $this->assertSame(1, $this->updateCardData('fullname1', 'uri2')); - } - - public function testUpdateAffectedRowsSame() { - $this->insertCardData('fullname1', 'uri1'); - // The WHERE clause matches a single row and the value we are updating - // to is the same as the one already present. MySQL reports 0 here when - // the PDO::MYSQL_ATTR_FOUND_ROWS flag is not specified. - $this->assertSame(1, $this->updateCardData('fullname1', 'uri1')); - } - - public function testUpdateAffectedRowsMultiple() { - $this->insertCardData('fullname1', 'uri1'); - $this->insertCardData('fullname2', 'uri2'); - // The WHERE clause matches two rows. One row contains a value that - // needs to be updated, the other one already contains the value we are - // updating to. MySQL reports 1 here when the PDO::MYSQL_ATTR_FOUND_ROWS - // flag is not specified. - $query = OC_DB::prepare("UPDATE `*PREFIX*{$this->table2}` SET `uri` = ?"); - $this->assertSame(2, $query->execute(array('uri1'))); - } - - protected function insertCardData($fullname, $uri) { - $query = OC_DB::prepare("INSERT INTO `*PREFIX*{$this->table2}` (`fullname`, `uri`, `carddata`) VALUES (?, ?, ?)"); - $this->assertSame(1, $query->execute(array($fullname, $uri, $this->getUniqueID()))); - } - - protected function updateCardData($fullname, $uri) { - $query = OC_DB::prepare("UPDATE `*PREFIX*{$this->table2}` SET `uri` = ? WHERE `fullname` = ?"); - return $query->execute(array($uri, $fullname)); - } - - public function testILIKE() { - $table = "*PREFIX*{$this->table2}"; - - $query = OC_DB::prepare("INSERT INTO `$table` (`fullname`, `uri`, `carddata`) VALUES (?, ?, ?)"); - $query->execute(array('fooBAR', 'foo', 'bar')); - - $query = OC_DB::prepare("SELECT * FROM `$table` WHERE `fullname` LIKE ?"); - $result = $query->execute(array('foobar')); - $this->assertCount(0, $result->fetchAll()); - - $query = OC_DB::prepare("SELECT * FROM `$table` WHERE `fullname` ILIKE ?"); - $result = $query->execute(array('foobar')); - $this->assertCount(1, $result->fetchAll()); - - $query = OC_DB::prepare("SELECT * FROM `$table` WHERE `fullname` ILIKE ?"); - $result = $query->execute(array('foo')); - $this->assertCount(0, $result->fetchAll()); - } - - public function testILIKEWildcard() { - $table = "*PREFIX*{$this->table2}"; - - $query = OC_DB::prepare("INSERT INTO `$table` (`fullname`, `uri`, `carddata`) VALUES (?, ?, ?)"); - $query->execute(array('FooBAR', 'foo', 'bar')); - - $query = OC_DB::prepare("SELECT * FROM `$table` WHERE `fullname` LIKE ?"); - $result = $query->execute(array('%bar')); - $this->assertCount(0, $result->fetchAll()); - - $query = OC_DB::prepare("SELECT * FROM `$table` WHERE `fullname` LIKE ?"); - $result = $query->execute(array('foo%')); - $this->assertCount(0, $result->fetchAll()); - - $query = OC_DB::prepare("SELECT * FROM `$table` WHERE `fullname` LIKE ?"); - $result = $query->execute(array('%ba%')); - $this->assertCount(0, $result->fetchAll()); - - $query = OC_DB::prepare("SELECT * FROM `$table` WHERE `fullname` ILIKE ?"); - $result = $query->execute(array('%bar')); - $this->assertCount(1, $result->fetchAll()); - - $query = OC_DB::prepare("SELECT * FROM `$table` WHERE `fullname` ILIKE ?"); - $result = $query->execute(array('foo%')); - $this->assertCount(1, $result->fetchAll()); - - $query = OC_DB::prepare("SELECT * FROM `$table` WHERE `fullname` ILIKE ?"); - $result = $query->execute(array('%ba%')); - $this->assertCount(1, $result->fetchAll()); - } -} diff --git a/tests/lib/db/DBSchemaTest.php b/tests/lib/db/DBSchemaTest.php new file mode 100644 index 00000000000..284fc532c2a --- /dev/null +++ b/tests/lib/db/DBSchemaTest.php @@ -0,0 +1,107 @@ + + * This file is licensed under the Affero General Public License version 3 or + * later. + * See the COPYING-README file. + */ + +namespace Test\DB; + +use OC_DB; +use OCP\Security\ISecureRandom; + +/** + * Class DBSchemaTest + * + * @group DB + */ +class DBSchemaTest extends \Test\TestCase { + protected $schema_file = 'static://test_db_scheme'; + protected $schema_file2 = 'static://test_db_scheme2'; + protected $table1; + protected $table2; + + protected function setUp() { + parent::setUp(); + + $dbfile = \OC::$SERVERROOT.'/tests/data/db_structure.xml'; + $dbfile2 = \OC::$SERVERROOT.'/tests/data/db_structure2.xml'; + + $r = '_' . \OC::$server->getSecureRandom()-> + generate(4, ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_DIGITS) . '_'; + $content = file_get_contents( $dbfile ); + $content = str_replace( '*dbprefix*', '*dbprefix*'.$r, $content ); + file_put_contents( $this->schema_file, $content ); + $content = file_get_contents( $dbfile2 ); + $content = str_replace( '*dbprefix*', '*dbprefix*'.$r, $content ); + file_put_contents( $this->schema_file2, $content ); + + $this->table1 = $r.'cntcts_addrsbks'; + $this->table2 = $r.'cntcts_cards'; + } + + protected function tearDown() { + unlink($this->schema_file); + unlink($this->schema_file2); + + parent::tearDown(); + } + + // everything in one test, they depend on each other + /** + * @medium + */ + public function testSchema() { + $platform = \OC::$server->getDatabaseConnection()->getDatabasePlatform(); + $this->doTestSchemaCreating(); + $this->doTestSchemaChanging(); + $this->doTestSchemaDumping(); + $this->doTestSchemaRemoving(); + } + + public function doTestSchemaCreating() { + OC_DB::createDbFromStructure($this->schema_file); + $this->assertTableExist($this->table1); + $this->assertTableExist($this->table2); + } + + public function doTestSchemaChanging() { + OC_DB::updateDbFromStructure($this->schema_file2); + $this->assertTableExist($this->table2); + } + + public function doTestSchemaDumping() { + $outfile = 'static://db_out.xml'; + OC_DB::getDbStructure($outfile); + $content = file_get_contents($outfile); + $this->assertContains($this->table1, $content); + $this->assertContains($this->table2, $content); + } + + public function doTestSchemaRemoving() { + OC_DB::removeDBStructure($this->schema_file); + $this->assertTableNotExist($this->table1); + $this->assertTableNotExist($this->table2); + } + + /** + * @param string $table + */ + public function assertTableExist($table) { + $this->assertTrue(OC_DB::tableExists($table), 'Table ' . $table . ' does not exist'); + } + + /** + * @param string $table + */ + public function assertTableNotExist($table) { + $platform = \OC::$server->getDatabaseConnection()->getDatabasePlatform(); + if ($platform instanceof \Doctrine\DBAL\Platforms\SqlitePlatform) { + // sqlite removes the tables after closing the DB + $this->assertTrue(true); + } else { + $this->assertFalse(OC_DB::tableExists($table), 'Table ' . $table . ' exists.'); + } + } +} diff --git a/tests/lib/db/LegacyDBTest.php b/tests/lib/db/LegacyDBTest.php new file mode 100644 index 00000000000..7aeeb3dd1f9 --- /dev/null +++ b/tests/lib/db/LegacyDBTest.php @@ -0,0 +1,393 @@ + + * This file is licensed under the Affero General Public License version 3 or + * later. + * See the COPYING-README file. + */ + +namespace Test\DB; + +use OC_DB; + +/** + * Class LegacyDBTest + * + * @group DB + */ +class LegacyDBTest extends \Test\TestCase { + protected $backupGlobals = FALSE; + + protected static $schema_file = 'static://test_db_scheme'; + protected $test_prefix; + + /** + * @var string + */ + private $table1; + + /** + * @var string + */ + private $table2; + + /** + * @var string + */ + private $table3; + + /** + * @var string + */ + private $table4; + + /** + * @var string + */ + private $table5; + + protected function setUp() { + parent::setUp(); + + $dbFile = \OC::$SERVERROOT.'/tests/data/db_structure.xml'; + + $r = $this->getUniqueID('_', 4).'_'; + $content = file_get_contents( $dbFile ); + $content = str_replace( '*dbprefix*', '*dbprefix*'.$r, $content ); + file_put_contents( self::$schema_file, $content ); + OC_DB::createDbFromStructure(self::$schema_file); + + $this->test_prefix = $r; + $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'; + $this->table5 = $this->test_prefix.'uniconst'; + } + + protected function tearDown() { + OC_DB::removeDBStructure(self::$schema_file); + unlink(self::$schema_file); + + parent::tearDown(); + } + + public function testQuotes() { + $query = OC_DB::prepare('SELECT `fullname` FROM `*PREFIX*'.$this->table2.'` WHERE `uri` = ?'); + $result = $query->execute(array('uri_1')); + $this->assertTrue((bool)$result); + $row = $result->fetchRow(); + $this->assertFalse($row); + $query = OC_DB::prepare('INSERT INTO `*PREFIX*'.$this->table2.'` (`fullname`,`uri`) VALUES (?,?)'); + $result = $query->execute(array('fullname test', 'uri_1')); + $this->assertEquals(1, $result); + $query = OC_DB::prepare('SELECT `fullname`,`uri` FROM `*PREFIX*'.$this->table2.'` WHERE `uri` = ?'); + $result = $query->execute(array('uri_1')); + $this->assertTrue((bool)$result); + $row = $result->fetchRow(); + $this->assertArrayHasKey('fullname', $row); + $this->assertEquals($row['fullname'], 'fullname test'); + $row = $result->fetchRow(); + $this->assertFalse((bool)$row); //PDO returns false, MDB2 returns null + } + + /** + * @medium + */ + public function testNOW() { + $query = OC_DB::prepare('INSERT INTO `*PREFIX*'.$this->table2.'` (`fullname`,`uri`) VALUES (NOW(),?)'); + $result = $query->execute(array('uri_2')); + $this->assertEquals(1, $result); + $query = OC_DB::prepare('SELECT `fullname`,`uri` FROM `*PREFIX*'.$this->table2.'` WHERE `uri` = ?'); + $result = $query->execute(array('uri_2')); + $this->assertTrue((bool)$result); + } + + public function testUNIX_TIMESTAMP() { + $query = OC_DB::prepare('INSERT INTO `*PREFIX*'.$this->table2.'` (`fullname`,`uri`) VALUES (UNIX_TIMESTAMP(),?)'); + $result = $query->execute(array('uri_3')); + $this->assertEquals(1, $result); + $query = OC_DB::prepare('SELECT `fullname`,`uri` FROM `*PREFIX*'.$this->table2.'` WHERE `uri` = ?'); + $result = $query->execute(array('uri_3')); + $this->assertTrue((bool)$result); + } + + public function testLastInsertId() { + $query = OC_DB::prepare('INSERT INTO `*PREFIX*'.$this->table2.'` (`fullname`,`uri`) VALUES (?,?)'); + $result1 = OC_DB::executeAudited($query, array('insertid 1','uri_1')); + $id1 = \OC::$server->getDatabaseConnection()->lastInsertId('*PREFIX*'.$this->table2); + + // we don't know the id we should expect, so insert another row + $result2 = OC_DB::executeAudited($query, array('insertid 2','uri_2')); + $id2 = \OC::$server->getDatabaseConnection()->lastInsertId('*PREFIX*'.$this->table2); + // now we can check if the two ids are in correct order + $this->assertGreaterThan($id1, $id2); + } + + public function testinsertIfNotExist() { + $categoryEntries = array( + array('user' => 'test', 'type' => 'contact', 'category' => 'Family', 'expectedResult' => 1), + array('user' => 'test', 'type' => 'contact', 'category' => 'Friends', 'expectedResult' => 1), + array('user' => 'test', 'type' => 'contact', 'category' => 'Coworkers', 'expectedResult' => 1), + array('user' => 'test', 'type' => 'contact', 'category' => 'Coworkers', 'expectedResult' => 0), + array('user' => 'test', 'type' => 'contact', 'category' => 'School', 'expectedResult' => 1), + ); + + foreach($categoryEntries as $entry) { + $result = \OCP\DB::insertIfNotExist('*PREFIX*'.$this->table3, + array( + 'uid' => $entry['user'], + 'type' => $entry['type'], + 'category' => $entry['category'], + )); + $this->assertEquals($entry['expectedResult'], $result); + } + + $query = OC_DB::prepare('SELECT * FROM `*PREFIX*'.$this->table3.'`'); + $result = $query->execute(); + $this->assertTrue((bool)$result); + $this->assertEquals(4, count($result->fetchAll())); + } + + public function testInsertIfNotExistNull() { + $categoryEntries = array( + array('addressbookid' => 123, 'fullname' => null, 'expectedResult' => 1), + array('addressbookid' => 123, 'fullname' => null, 'expectedResult' => 0), + array('addressbookid' => 123, 'fullname' => 'test', 'expectedResult' => 1), + ); + + foreach($categoryEntries as $entry) { + $result = \OCP\DB::insertIfNotExist('*PREFIX*'.$this->table2, + array( + 'addressbookid' => $entry['addressbookid'], + 'fullname' => $entry['fullname'], + )); + $this->assertEquals($entry['expectedResult'], $result); + } + + $query = OC_DB::prepare('SELECT * FROM `*PREFIX*'.$this->table2.'`'); + $result = $query->execute(); + $this->assertTrue((bool)$result); + $this->assertEquals(2, count($result->fetchAll())); + } + + public function testInsertIfNotExistDonTOverwrite() { + $fullName = 'fullname test'; + $uri = 'uri_1'; + $carddata = 'This is a vCard'; + + // Normal test to have same known data inserted. + $query = OC_DB::prepare('INSERT INTO `*PREFIX*'.$this->table2.'` (`fullname`, `uri`, `carddata`) VALUES (?, ?, ?)'); + $result = $query->execute(array($fullName, $uri, $carddata)); + $this->assertEquals(1, $result); + $query = OC_DB::prepare('SELECT `fullname`, `uri`, `carddata` FROM `*PREFIX*'.$this->table2.'` WHERE `uri` = ?'); + $result = $query->execute(array($uri)); + $this->assertTrue((bool)$result); + $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 = \OCP\DB::insertIfNotExist('*PREFIX*'.$this->table2, + array( + 'fullname' => $fullName, + 'uri' => $uri, + )); + $this->assertEquals(0, $result); + + $query = OC_DB::prepare('SELECT `fullname`, `uri`, `carddata` FROM `*PREFIX*'.$this->table2.'` WHERE `uri` = ?'); + $result = $query->execute(array($uri)); + $this->assertTrue((bool)$result); + // Test that previously inserted data isn't overwritten + // And that a new row hasn't been inserted. + $rowset = $result->fetchAll(); + $this->assertEquals(1, count($rowset)); + $this->assertArrayHasKey('carddata', $rowset[0]); + $this->assertEquals($carddata, $rowset[0]['carddata']); + } + + public function testInsertIfNotExistsViolating() { + $result = \OCP\DB::insertIfNotExist('*PREFIX*'.$this->table5, + array( + 'storage' => 1, + 'path_hash' => md5('welcome.txt'), + 'etag' => $this->getUniqueID() + )); + $this->assertEquals(1, $result); + + $result = \OCP\DB::insertIfNotExist('*PREFIX*'.$this->table5, + array( + 'storage' => 1, + 'path_hash' => md5('welcome.txt'), + 'etag' => $this->getUniqueID() + ),['storage', 'path_hash']); + + $this->assertEquals(0, $result); + } + + public function insertIfNotExistsViolatingThrows() { + return [ + [null], + [['etag']], + ]; + } + + /** + * @dataProvider insertIfNotExistsViolatingThrows + * @expectedException \Doctrine\DBAL\Exception\UniqueConstraintViolationException + * + * @param array $compareKeys + */ + public function testInsertIfNotExistsViolatingThrows($compareKeys) { + $result = \OCP\DB::insertIfNotExist('*PREFIX*'.$this->table5, + array( + 'storage' => 1, + 'path_hash' => md5('welcome.txt'), + 'etag' => $this->getUniqueID() + )); + $this->assertEquals(1, $result); + + $result = \OCP\DB::insertIfNotExist('*PREFIX*'.$this->table5, + array( + 'storage' => 1, + 'path_hash' => md5('welcome.txt'), + 'etag' => $this->getUniqueID() + ), $compareKeys); + + $this->assertEquals(0, $result); + } + + 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 = OC_DB::prepare("SELECT `fullname` FROM `$table`")->execute()->fetchOne(); + $this->assertSame($expected, $actual); + } + + /** + * Insert, select and delete decimal(12,2) values + * @dataProvider decimalData + */ + public function testDecimal($insert, $expect) { + $table = "*PREFIX*" . $this->table4; + $rowname = 'decimaltest'; + + $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); + } + + public function decimalData() { + return [ + ['1337133713.37', '1337133713.37'], + ['1234567890', '1234567890.00'], + ]; + } + + public function testUpdateAffectedRowsNoMatch() { + $this->insertCardData('fullname1', 'uri1'); + // The WHERE clause does not match any rows + $this->assertSame(0, $this->updateCardData('fullname3', 'uri2')); + } + + public function testUpdateAffectedRowsDifferent() { + $this->insertCardData('fullname1', 'uri1'); + // The WHERE clause matches a single row and the value we are updating + // is different from the one already present. + $this->assertSame(1, $this->updateCardData('fullname1', 'uri2')); + } + + public function testUpdateAffectedRowsSame() { + $this->insertCardData('fullname1', 'uri1'); + // The WHERE clause matches a single row and the value we are updating + // to is the same as the one already present. MySQL reports 0 here when + // the PDO::MYSQL_ATTR_FOUND_ROWS flag is not specified. + $this->assertSame(1, $this->updateCardData('fullname1', 'uri1')); + } + + public function testUpdateAffectedRowsMultiple() { + $this->insertCardData('fullname1', 'uri1'); + $this->insertCardData('fullname2', 'uri2'); + // The WHERE clause matches two rows. One row contains a value that + // needs to be updated, the other one already contains the value we are + // updating to. MySQL reports 1 here when the PDO::MYSQL_ATTR_FOUND_ROWS + // flag is not specified. + $query = OC_DB::prepare("UPDATE `*PREFIX*{$this->table2}` SET `uri` = ?"); + $this->assertSame(2, $query->execute(array('uri1'))); + } + + protected function insertCardData($fullname, $uri) { + $query = OC_DB::prepare("INSERT INTO `*PREFIX*{$this->table2}` (`fullname`, `uri`, `carddata`) VALUES (?, ?, ?)"); + $this->assertSame(1, $query->execute(array($fullname, $uri, $this->getUniqueID()))); + } + + protected function updateCardData($fullname, $uri) { + $query = OC_DB::prepare("UPDATE `*PREFIX*{$this->table2}` SET `uri` = ? WHERE `fullname` = ?"); + return $query->execute(array($uri, $fullname)); + } + + public function testILIKE() { + $table = "*PREFIX*{$this->table2}"; + + $query = OC_DB::prepare("INSERT INTO `$table` (`fullname`, `uri`, `carddata`) VALUES (?, ?, ?)"); + $query->execute(array('fooBAR', 'foo', 'bar')); + + $query = OC_DB::prepare("SELECT * FROM `$table` WHERE `fullname` LIKE ?"); + $result = $query->execute(array('foobar')); + $this->assertCount(0, $result->fetchAll()); + + $query = OC_DB::prepare("SELECT * FROM `$table` WHERE `fullname` ILIKE ?"); + $result = $query->execute(array('foobar')); + $this->assertCount(1, $result->fetchAll()); + + $query = OC_DB::prepare("SELECT * FROM `$table` WHERE `fullname` ILIKE ?"); + $result = $query->execute(array('foo')); + $this->assertCount(0, $result->fetchAll()); + } + + public function testILIKEWildcard() { + $table = "*PREFIX*{$this->table2}"; + + $query = OC_DB::prepare("INSERT INTO `$table` (`fullname`, `uri`, `carddata`) VALUES (?, ?, ?)"); + $query->execute(array('FooBAR', 'foo', 'bar')); + + $query = OC_DB::prepare("SELECT * FROM `$table` WHERE `fullname` LIKE ?"); + $result = $query->execute(array('%bar')); + $this->assertCount(0, $result->fetchAll()); + + $query = OC_DB::prepare("SELECT * FROM `$table` WHERE `fullname` LIKE ?"); + $result = $query->execute(array('foo%')); + $this->assertCount(0, $result->fetchAll()); + + $query = OC_DB::prepare("SELECT * FROM `$table` WHERE `fullname` LIKE ?"); + $result = $query->execute(array('%ba%')); + $this->assertCount(0, $result->fetchAll()); + + $query = OC_DB::prepare("SELECT * FROM `$table` WHERE `fullname` ILIKE ?"); + $result = $query->execute(array('%bar')); + $this->assertCount(1, $result->fetchAll()); + + $query = OC_DB::prepare("SELECT * FROM `$table` WHERE `fullname` ILIKE ?"); + $result = $query->execute(array('foo%')); + $this->assertCount(1, $result->fetchAll()); + + $query = OC_DB::prepare("SELECT * FROM `$table` WHERE `fullname` ILIKE ?"); + $result = $query->execute(array('%ba%')); + $this->assertCount(1, $result->fetchAll()); + } +} diff --git a/tests/lib/dbschema.php b/tests/lib/dbschema.php deleted file mode 100644 index 11eacbf397f..00000000000 --- a/tests/lib/dbschema.php +++ /dev/null @@ -1,105 +0,0 @@ - - * This file is licensed under the Affero General Public License version 3 or - * later. - * See the COPYING-README file. - */ - -use OCP\Security\ISecureRandom; - -/** - * Class Test_DBSchema - * - * @group DB - */ -class Test_DBSchema extends \Test\TestCase { - protected $schema_file = 'static://test_db_scheme'; - protected $schema_file2 = 'static://test_db_scheme2'; - protected $table1; - protected $table2; - - protected function setUp() { - parent::setUp(); - - $dbfile = OC::$SERVERROOT.'/tests/data/db_structure.xml'; - $dbfile2 = OC::$SERVERROOT.'/tests/data/db_structure2.xml'; - - $r = '_' . \OC::$server->getSecureRandom()-> - generate(4, ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_DIGITS) . '_'; - $content = file_get_contents( $dbfile ); - $content = str_replace( '*dbprefix*', '*dbprefix*'.$r, $content ); - file_put_contents( $this->schema_file, $content ); - $content = file_get_contents( $dbfile2 ); - $content = str_replace( '*dbprefix*', '*dbprefix*'.$r, $content ); - file_put_contents( $this->schema_file2, $content ); - - $this->table1 = $r.'cntcts_addrsbks'; - $this->table2 = $r.'cntcts_cards'; - } - - protected function tearDown() { - unlink($this->schema_file); - unlink($this->schema_file2); - - parent::tearDown(); - } - - // everything in one test, they depend on each other - /** - * @medium - */ - public function testSchema() { - $platform = \OC::$server->getDatabaseConnection()->getDatabasePlatform(); - $this->doTestSchemaCreating(); - $this->doTestSchemaChanging(); - $this->doTestSchemaDumping(); - $this->doTestSchemaRemoving(); - } - - public function doTestSchemaCreating() { - OC_DB::createDbFromStructure($this->schema_file); - $this->assertTableExist($this->table1); - $this->assertTableExist($this->table2); - } - - public function doTestSchemaChanging() { - OC_DB::updateDbFromStructure($this->schema_file2); - $this->assertTableExist($this->table2); - } - - public function doTestSchemaDumping() { - $outfile = 'static://db_out.xml'; - OC_DB::getDbStructure($outfile); - $content = file_get_contents($outfile); - $this->assertContains($this->table1, $content); - $this->assertContains($this->table2, $content); - } - - public function doTestSchemaRemoving() { - OC_DB::removeDBStructure($this->schema_file); - $this->assertTableNotExist($this->table1); - $this->assertTableNotExist($this->table2); - } - - /** - * @param string $table - */ - public function assertTableExist($table) { - $this->assertTrue(OC_DB::tableExists($table), 'Table ' . $table . ' does not exist'); - } - - /** - * @param string $table - */ - public function assertTableNotExist($table) { - $platform = \OC::$server->getDatabaseConnection()->getDatabasePlatform(); - if ($platform instanceof \Doctrine\DBAL\Platforms\SqlitePlatform) { - // sqlite removes the tables after closing the DB - $this->assertTrue(true); - } else { - $this->assertFalse(OC_DB::tableExists($table), 'Table ' . $table . ' exists.'); - } - } -} diff --git a/tests/lib/errorHandler.php b/tests/lib/errorHandler.php deleted file mode 100644 index 726529e83f4..00000000000 --- a/tests/lib/errorHandler.php +++ /dev/null @@ -1,66 +0,0 @@ - - * - * 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 . - * - */ - -class Test_ErrorHandler extends \Test\TestCase { - - /** - * 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); - } - -} - -/** - * dummy class to access protected methods of \OC\Log\ErrorHandler - */ -class TestableErrorHandler extends \OC\Log\ErrorHandler { - - /** - * @param string $msg - */ - public static function testRemovePassword($msg) { - return self::removePassword($msg); - } -} -- cgit v1.2.3 From 9a4253ef7c34f9dc71a6a9f7828a10df769f0c32 Mon Sep 17 00:00:00 2001 From: Joas Schilling Date: Thu, 19 May 2016 09:38:52 +0200 Subject: Fix lib/ --- tests/lib/HTTPHelperTest.php | 120 +++++++++ tests/lib/HelperStorageTest.php | 232 ++++++++++++++++ tests/lib/ImageTest.php | 341 ++++++++++++++++++++++++ tests/lib/LegacyHelperTest.php | 301 +++++++++++++++++++++ tests/lib/NaturalSortTest.php | 272 +++++++++++++++++++ tests/lib/RepairStepTest.php | 134 ++++++++++ tests/lib/RepairTest.php | 134 ---------- tests/lib/SetupTest.php | 135 ++++++++++ tests/lib/StreamWrappersTest.php | 116 ++++++++ tests/lib/TagsTest.php | 316 ++++++++++++++++++++++ tests/lib/TemplateFunctionsTest.php | 252 ++++++++++++++++++ tests/lib/UpdaterTest.php | 182 +++++++++++++ tests/lib/UrlGeneratorTest.php | 134 ++++++++++ tests/lib/UtilCheckServerTest.php | 172 ++++++++++++ tests/lib/UtilTest.php | 509 ++++++++++++++++++++++++++++++++++++ tests/lib/group.php | 197 -------------- tests/lib/group/LegacyGroupTest.php | 202 ++++++++++++++ tests/lib/helper.php | 297 --------------------- tests/lib/helperstorage.php | 230 ---------------- tests/lib/httphelper.php | 118 --------- tests/lib/image.php | 337 ------------------------ tests/lib/naturalsort.php | 270 ------------------- tests/lib/ocsclienttest.php | 2 + tests/lib/setup.php | 133 ---------- tests/lib/streamwrappers.php | 114 -------- tests/lib/tags.php | 314 ---------------------- tests/lib/template.php | 250 ------------------ tests/lib/updater.php | 181 ------------- tests/lib/urlGenerator.php | 132 ---------- tests/lib/util.php | 505 ----------------------------------- tests/lib/utilcheckserver.php | 170 ------------ 31 files changed, 3420 insertions(+), 3382 deletions(-) create mode 100644 tests/lib/HTTPHelperTest.php create mode 100644 tests/lib/HelperStorageTest.php create mode 100644 tests/lib/ImageTest.php create mode 100644 tests/lib/LegacyHelperTest.php create mode 100644 tests/lib/NaturalSortTest.php create mode 100644 tests/lib/RepairStepTest.php delete mode 100644 tests/lib/RepairTest.php create mode 100644 tests/lib/SetupTest.php create mode 100644 tests/lib/StreamWrappersTest.php create mode 100644 tests/lib/TagsTest.php create mode 100644 tests/lib/TemplateFunctionsTest.php create mode 100644 tests/lib/UpdaterTest.php create mode 100644 tests/lib/UrlGeneratorTest.php create mode 100644 tests/lib/UtilCheckServerTest.php create mode 100644 tests/lib/UtilTest.php delete mode 100644 tests/lib/group.php create mode 100644 tests/lib/group/LegacyGroupTest.php delete mode 100644 tests/lib/helper.php delete mode 100644 tests/lib/helperstorage.php delete mode 100644 tests/lib/httphelper.php delete mode 100644 tests/lib/image.php delete mode 100644 tests/lib/naturalsort.php delete mode 100644 tests/lib/setup.php delete mode 100644 tests/lib/streamwrappers.php delete mode 100644 tests/lib/tags.php delete mode 100644 tests/lib/template.php delete mode 100644 tests/lib/updater.php delete mode 100644 tests/lib/urlGenerator.php delete mode 100644 tests/lib/util.php delete mode 100644 tests/lib/utilcheckserver.php (limited to 'tests') diff --git a/tests/lib/HTTPHelperTest.php b/tests/lib/HTTPHelperTest.php new file mode 100644 index 00000000000..6d9c4788735 --- /dev/null +++ b/tests/lib/HTTPHelperTest.php @@ -0,0 +1,120 @@ + + * This file is licensed under the Affero General Public License version 3 or + * later. + * See the COPYING-README file. + */ + +namespace Test; + +class HTTPHelperTest extends \Test\TestCase { + + /** @var \OCP\IConfig*/ + private $config; + /** @var \OC\HTTPHelper */ + private $httpHelperMock; + /** @var \OCP\Http\Client\IClientService */ + private $clientService; + + protected function setUp() { + parent::setUp(); + + $this->config = $this->getMockBuilder('\OCP\IConfig') + ->disableOriginalConstructor()->getMock(); + $this->clientService = $this->getMock('\OCP\Http\Client\IClientService'); + $this->httpHelperMock = $this->getMockBuilder('\OC\HTTPHelper') + ->setConstructorArgs(array($this->config, $this->clientService)) + ->setMethods(array('getHeaders')) + ->getMock(); + } + + public function isHttpTestData() { + return array( + array('http://wwww.owncloud.org/enterprise/', true), + array('https://wwww.owncloud.org/enterprise/', true), + array('HTTPS://WWW.OWNCLOUD.ORG', true), + array('HTTP://WWW.OWNCLOUD.ORG', true), + array('FILE://WWW.OWNCLOUD.ORG', false), + array('file://www.owncloud.org', false), + array('FTP://WWW.OWNCLOUD.ORG', false), + array('ftp://www.owncloud.org', false), + ); + } + + /** + * @dataProvider isHttpTestData + */ + public function testIsHTTP($url, $expected) { + $this->assertSame($expected, $this->httpHelperMock->isHTTPURL($url)); + } + + public function testPostSuccess() { + $client = $this->getMockBuilder('\OCP\Http\Client\IClient') + ->disableOriginalConstructor()->getMock(); + $this->clientService + ->expects($this->once()) + ->method('newClient') + ->will($this->returnValue($client)); + $response = $this->getMockBuilder('\OCP\Http\Client\IResponse') + ->disableOriginalConstructor()->getMock(); + $client + ->expects($this->once()) + ->method('post') + ->with( + 'https://owncloud.org', + [ + 'body' => [ + 'Foo' => 'Bar', + ], + 'connect_timeout' => 10, + + ] + ) + ->will($this->returnValue($response)); + $response + ->expects($this->once()) + ->method('getBody') + ->will($this->returnValue('Body of the requested page')); + + + $response = $this->httpHelperMock->post('https://owncloud.org', ['Foo' => 'Bar']); + $expected = [ + 'success' => true, + 'result' => 'Body of the requested page' + ]; + $this->assertSame($expected, $response); + } + + public function testPostException() { + $client = $this->getMockBuilder('\OCP\Http\Client\IClient') + ->disableOriginalConstructor()->getMock(); + $this->clientService + ->expects($this->once()) + ->method('newClient') + ->will($this->returnValue($client)); + $client + ->expects($this->once()) + ->method('post') + ->with( + 'https://owncloud.org', + [ + 'body' => [ + 'Foo' => 'Bar', + ], + 'connect_timeout' => 10, + + ] + ) + ->will($this->throwException(new \Exception('Something failed'))); + + + $response = $this->httpHelperMock->post('https://owncloud.org', ['Foo' => 'Bar']); + $expected = [ + 'success' => false, + 'result' => 'Something failed' + ]; + $this->assertSame($expected, $response); + } + +} diff --git a/tests/lib/HelperStorageTest.php b/tests/lib/HelperStorageTest.php new file mode 100644 index 00000000000..e841dbfce18 --- /dev/null +++ b/tests/lib/HelperStorageTest.php @@ -0,0 +1,232 @@ + + * This file is licensed under the Affero General Public License version 3 or + * later. + * See the COPYING-README file. + */ + +namespace Test; + +/** + * Test the storage functions of OC_Helper + * + * @group DB + */ +class HelperStorageTest extends \Test\TestCase { + /** @var string */ + private $user; + /** @var \OC\Files\Storage\Storage */ + private $storageMock; + /** @var \OC\Files\Storage\Storage */ + private $storage; + + protected function setUp() { + parent::setUp(); + + $this->user = $this->getUniqueID('user_'); + \OC::$server->getUserManager()->createUser($this->user, $this->user); + + $this->storage = \OC\Files\Filesystem::getStorage('/'); + \OC\Files\Filesystem::tearDown(); + \OC_User::setUserId($this->user); + \OC\Files\Filesystem::init($this->user, '/' . $this->user . '/files'); + \OC\Files\Filesystem::clearMounts(); + + $this->storageMock = null; + } + + protected function tearDown() { + $this->user = null; + + if ($this->storageMock) { + $this->storageMock->getCache()->clear(); + $this->storageMock = null; + } + \OC\Files\Filesystem::tearDown(); + \OC\Files\Filesystem::mount($this->storage, array(), '/'); + + \OC_User::setUserId(''); + $user = \OC::$server->getUserManager()->get($this->user); + if ($user !== null) { $user->delete(); } + \OC::$server->getConfig()->deleteAllUserValues($this->user); + + parent::tearDown(); + } + + /** + * Returns a storage mock that returns the given value as + * free space + * + * @param int $freeSpace free space value + * @return \OC\Files\Storage\Storage + */ + private function getStorageMock($freeSpace = 12) { + $this->storageMock = $this->getMock( + '\OC\Files\Storage\Temporary', + array('free_space'), + array('') + ); + + + $this->storageMock->expects($this->once()) + ->method('free_space') + ->will($this->returnValue(12)); + return $this->storageMock; + } + + /** + * Test getting the storage info + */ + function testGetStorageInfo() { + $homeStorage = $this->getStorageMock(12); + \OC\Files\Filesystem::mount($homeStorage, array(), '/' . $this->user . '/files'); + $homeStorage->file_put_contents('test.txt', '01234'); + + $storageInfo = \OC_Helper::getStorageInfo(''); + $this->assertEquals(12, $storageInfo['free']); + $this->assertEquals(5, $storageInfo['used']); + $this->assertEquals(17, $storageInfo['total']); + } + + /** + * Test getting the storage info, ignoring extra mount points + */ + function testGetStorageInfoExcludingExtStorage() { + $homeStorage = $this->getStorageMock(12); + \OC\Files\Filesystem::mount($homeStorage, array(), '/' . $this->user . '/files'); + $homeStorage->file_put_contents('test.txt', '01234'); + + $extStorage = new \OC\Files\Storage\Temporary(array()); + $extStorage->file_put_contents('extfile.txt', 'abcdefghijklmnopq'); + $extStorage->getScanner()->scan(''); // update root size + + \OC\Files\Filesystem::mount($extStorage, array(), '/' . $this->user . '/files/ext'); + + $storageInfo = \OC_Helper::getStorageInfo(''); + $this->assertEquals(12, $storageInfo['free']); + $this->assertEquals(5, $storageInfo['used']); + $this->assertEquals(17, $storageInfo['total']); + } + + /** + * Test getting the storage info, including extra mount points + */ + function testGetStorageInfoIncludingExtStorage() { + $homeStorage = new \OC\Files\Storage\Temporary(array()); + \OC\Files\Filesystem::mount($homeStorage, array(), '/' . $this->user . '/files'); + $homeStorage->file_put_contents('test.txt', '01234'); + + $extStorage = new \OC\Files\Storage\Temporary(array()); + $extStorage->file_put_contents('extfile.txt', 'abcdefghijklmnopq'); + $extStorage->getScanner()->scan(''); // update root size + + \OC\Files\Filesystem::mount($extStorage, array(), '/' . $this->user . '/files/ext'); + + $config = \OC::$server->getConfig(); + $oldConfig = $config->getSystemValue('quota_include_external_storage', false); + $config->setSystemValue('quota_include_external_storage', 'true'); + + $config->setUserValue($this->user, 'files', 'quota', '25'); + + $storageInfo = \OC_Helper::getStorageInfo(''); + $this->assertEquals(3, $storageInfo['free']); + $this->assertEquals(22, $storageInfo['used']); + $this->assertEquals(25, $storageInfo['total']); + + $config->setSystemValue('quota_include_external_storage', $oldConfig); + $config->setUserValue($this->user, 'files', 'quota', 'default'); + } + + /** + * Test getting the storage info excluding extra mount points + * when user has no quota set, even when quota ext storage option + * was set + */ + function testGetStorageInfoIncludingExtStorageWithNoUserQuota() { + $homeStorage = $this->getStorageMock(12); + \OC\Files\Filesystem::mount($homeStorage, array(), '/' . $this->user . '/files'); + $homeStorage->file_put_contents('test.txt', '01234'); + + $extStorage = new \OC\Files\Storage\Temporary(array()); + $extStorage->file_put_contents('extfile.txt', 'abcdefghijklmnopq'); + $extStorage->getScanner()->scan(''); // update root size + + \OC\Files\Filesystem::mount($extStorage, array(), '/' . $this->user . '/files/ext'); + + $config = \OC::$server->getConfig(); + $oldConfig = $config->getSystemValue('quota_include_external_storage', false); + $config->setSystemValue('quota_include_external_storage', 'true'); + + $storageInfo = \OC_Helper::getStorageInfo(''); + $this->assertEquals(12, $storageInfo['free']); + $this->assertEquals(5, $storageInfo['used']); + $this->assertEquals(17, $storageInfo['total']); + + $config->setSystemValue('quota_include_external_storage', $oldConfig); + } + + + /** + * Test getting the storage info with quota enabled + */ + function testGetStorageInfoWithQuota() { + $homeStorage = $this->getStorageMock(12); + $homeStorage->file_put_contents('test.txt', '01234'); + $homeStorage = new \OC\Files\Storage\Wrapper\Quota( + array( + 'storage' => $homeStorage, + 'quota' => 7 + ) + ); + \OC\Files\Filesystem::mount($homeStorage, array(), '/' . $this->user . '/files'); + + $storageInfo = \OC_Helper::getStorageInfo(''); + $this->assertEquals(2, $storageInfo['free']); + $this->assertEquals(5, $storageInfo['used']); + $this->assertEquals(7, $storageInfo['total']); + } + + /** + * Test getting the storage info when data exceeds quota + */ + function testGetStorageInfoWhenSizeExceedsQuota() { + $homeStorage = $this->getStorageMock(12); + $homeStorage->file_put_contents('test.txt', '0123456789'); + $homeStorage = new \OC\Files\Storage\Wrapper\Quota( + array( + 'storage' => $homeStorage, + 'quota' => 7 + ) + ); + \OC\Files\Filesystem::mount($homeStorage, array(), '/' . $this->user . '/files'); + + $storageInfo = \OC_Helper::getStorageInfo(''); + $this->assertEquals(0, $storageInfo['free']); + $this->assertEquals(10, $storageInfo['used']); + // total = quota + $this->assertEquals(7, $storageInfo['total']); + } + + /** + * Test getting the storage info when the remaining + * free storage space is less than the quota + */ + function testGetStorageInfoWhenFreeSpaceLessThanQuota() { + $homeStorage = $this->getStorageMock(12); + $homeStorage->file_put_contents('test.txt', '01234'); + $homeStorage = new \OC\Files\Storage\Wrapper\Quota( + array( + 'storage' => $homeStorage, + 'quota' => 18 + ) + ); + \OC\Files\Filesystem::mount($homeStorage, array(), '/' . $this->user . '/files'); + + $storageInfo = \OC_Helper::getStorageInfo(''); + $this->assertEquals(12, $storageInfo['free']); + $this->assertEquals(5, $storageInfo['used']); + // total = free + used (because quota > total) + $this->assertEquals(17, $storageInfo['total']); + } +} diff --git a/tests/lib/ImageTest.php b/tests/lib/ImageTest.php new file mode 100644 index 00000000000..9dba7e3739b --- /dev/null +++ b/tests/lib/ImageTest.php @@ -0,0 +1,341 @@ + + * This file is licensed under the Affero General Public License version 3 or + * later. + * See the COPYING-README file. + */ + +namespace Test; + +use OC; + +class ImageTest extends \Test\TestCase { + public static function tearDownAfterClass() { + @unlink(OC::$SERVERROOT.'/tests/data/testimage2.png'); + @unlink(OC::$SERVERROOT.'/tests/data/testimage2.jpg'); + + parent::tearDownAfterClass(); + } + + public function testGetMimeTypeForFile() { + $mimetype = \OC_Image::getMimeTypeForFile(OC::$SERVERROOT.'/tests/data/testimage.png'); + $this->assertEquals('image/png', $mimetype); + + $mimetype = \OC_Image::getMimeTypeForFile(OC::$SERVERROOT.'/tests/data/testimage.jpg'); + $this->assertEquals('image/jpeg', $mimetype); + + $mimetype = \OC_Image::getMimeTypeForFile(OC::$SERVERROOT.'/tests/data/testimage.gif'); + $this->assertEquals('image/gif', $mimetype); + + $mimetype = \OC_Image::getMimeTypeForFile(null); + $this->assertEquals('', $mimetype); + } + + public function testConstructDestruct() { + $img = new \OC_Image(OC::$SERVERROOT.'/tests/data/testimage.png'); + $this->assertInstanceOf('\OC_Image', $img); + $this->assertInstanceOf('\OCP\IImage', $img); + unset($img); + + $imgcreate = imagecreatefromjpeg(OC::$SERVERROOT.'/tests/data/testimage.jpg'); + $img = new \OC_Image($imgcreate); + $this->assertInstanceOf('\OC_Image', $img); + $this->assertInstanceOf('\OCP\IImage', $img); + unset($img); + + $base64 = base64_encode(file_get_contents(OC::$SERVERROOT.'/tests/data/testimage.gif')); + $img = new \OC_Image($base64); + $this->assertInstanceOf('\OC_Image', $img); + $this->assertInstanceOf('\OCP\IImage', $img); + unset($img); + + $img = new \OC_Image(null); + $this->assertInstanceOf('\OC_Image', $img); + $this->assertInstanceOf('\OCP\IImage', $img); + unset($img); + } + + public function testValid() { + $img = new \OC_Image(OC::$SERVERROOT.'/tests/data/testimage.png'); + $this->assertTrue($img->valid()); + + $text = base64_encode("Lorem ipsum dolor sir amet …"); + $img = new \OC_Image($text); + $this->assertFalse($img->valid()); + + $img = new \OC_Image(null); + $this->assertFalse($img->valid()); + } + + public function testMimeType() { + $img = new \OC_Image(OC::$SERVERROOT.'/tests/data/testimage.png'); + $this->assertEquals('image/png', $img->mimeType()); + + $img = new \OC_Image(null); + $this->assertEquals('', $img->mimeType()); + + if (\OC_Util::runningOnWindows()) { + $this->markTestSkipped('[Windows] Images created with imagecreate() are pngs on windows'); + } + + $img = new \OC_Image(file_get_contents(OC::$SERVERROOT.'/tests/data/testimage.jpg')); + $this->assertEquals('image/jpeg', $img->mimeType()); + + $img = new \OC_Image(base64_encode(file_get_contents(OC::$SERVERROOT.'/tests/data/testimage.gif'))); + $this->assertEquals('image/gif', $img->mimeType()); + } + + public function testWidth() { + $img = new \OC_Image(OC::$SERVERROOT.'/tests/data/testimage.png'); + $this->assertEquals(128, $img->width()); + + $img = new \OC_Image(file_get_contents(OC::$SERVERROOT.'/tests/data/testimage.jpg')); + $this->assertEquals(1680, $img->width()); + + $img = new \OC_Image(base64_encode(file_get_contents(OC::$SERVERROOT.'/tests/data/testimage.gif'))); + $this->assertEquals(64, $img->width()); + + $img = new \OC_Image(null); + $this->assertEquals(-1, $img->width()); + } + + public function testHeight() { + $img = new \OC_Image(OC::$SERVERROOT.'/tests/data/testimage.png'); + $this->assertEquals(128, $img->height()); + + $img = new \OC_Image(file_get_contents(OC::$SERVERROOT.'/tests/data/testimage.jpg')); + $this->assertEquals(1050, $img->height()); + + $img = new \OC_Image(base64_encode(file_get_contents(OC::$SERVERROOT.'/tests/data/testimage.gif'))); + $this->assertEquals(64, $img->height()); + + $img = new \OC_Image(null); + $this->assertEquals(-1, $img->height()); + } + + public function testSave() { + $img = new \OC_Image(OC::$SERVERROOT.'/tests/data/testimage.png'); + $img->resize(16); + $img->save(OC::$SERVERROOT.'/tests/data/testimage2.png'); + $this->assertEquals(file_get_contents(OC::$SERVERROOT.'/tests/data/testimage2.png'), $img->data()); + + $img = new \OC_Image(OC::$SERVERROOT.'/tests/data/testimage.jpg'); + $img->resize(128); + $img->save(OC::$SERVERROOT.'/tests/data/testimage2.jpg'); + $this->assertEquals(file_get_contents(OC::$SERVERROOT.'/tests/data/testimage2.jpg'), $img->data()); + } + + public function testData() { + $img = new \OC_Image(OC::$SERVERROOT.'/tests/data/testimage.png'); + $raw = imagecreatefromstring(file_get_contents(OC::$SERVERROOT.'/tests/data/testimage.png')); + // Preserve transparency + imagealphablending($raw, true); + imagesavealpha($raw, true); + ob_start(); + imagepng($raw); + $expected = ob_get_clean(); + $this->assertEquals($expected, $img->data()); + + $img = new \OC_Image(OC::$SERVERROOT.'/tests/data/testimage.jpg'); + $raw = imagecreatefromstring(file_get_contents(OC::$SERVERROOT.'/tests/data/testimage.jpg')); + ob_start(); + imagejpeg($raw); + $expected = ob_get_clean(); + $this->assertEquals($expected, $img->data()); + + $img = new \OC_Image(OC::$SERVERROOT.'/tests/data/testimage.gif'); + $raw = imagecreatefromstring(file_get_contents(OC::$SERVERROOT.'/tests/data/testimage.gif')); + ob_start(); + imagegif($raw); + $expected = ob_get_clean(); + $this->assertEquals($expected, $img->data()); + } + + public function testDataNoResource() { + $img = new \OC_Image(); + $this->assertNull($img->data()); + } + + /** + * @depends testData + */ + public function testToString() { + $img = new \OC_Image(OC::$SERVERROOT.'/tests/data/testimage.png'); + $expected = base64_encode($img->data()); + $this->assertEquals($expected, (string)$img); + + $img = new \OC_Image(file_get_contents(OC::$SERVERROOT.'/tests/data/testimage.jpg')); + $expected = base64_encode($img->data()); + $this->assertEquals($expected, (string)$img); + + $img = new \OC_Image(OC::$SERVERROOT.'/tests/data/testimage.gif'); + $expected = base64_encode($img->data()); + $this->assertEquals($expected, (string)$img); + } + + public function testResize() { + $img = new \OC_Image(OC::$SERVERROOT.'/tests/data/testimage.png'); + $this->assertTrue($img->resize(32)); + $this->assertEquals(32, $img->width()); + $this->assertEquals(32, $img->height()); + + $img = new \OC_Image(file_get_contents(OC::$SERVERROOT.'/tests/data/testimage.jpg')); + $this->assertTrue($img->resize(840)); + $this->assertEquals(840, $img->width()); + $this->assertEquals(525, $img->height()); + + $img = new \OC_Image(base64_encode(file_get_contents(OC::$SERVERROOT.'/tests/data/testimage.gif'))); + $this->assertTrue($img->resize(100)); + $this->assertEquals(100, $img->width()); + $this->assertEquals(100, $img->height()); + } + + public function testPreciseResize() { + $img = new \OC_Image(OC::$SERVERROOT.'/tests/data/testimage.png'); + $this->assertTrue($img->preciseResize(128, 512)); + $this->assertEquals(128, $img->width()); + $this->assertEquals(512, $img->height()); + + $img = new \OC_Image(file_get_contents(OC::$SERVERROOT.'/tests/data/testimage.jpg')); + $this->assertTrue($img->preciseResize(64, 840)); + $this->assertEquals(64, $img->width()); + $this->assertEquals(840, $img->height()); + + $img = new \OC_Image(base64_encode(file_get_contents(OC::$SERVERROOT.'/tests/data/testimage.gif'))); + $this->assertTrue($img->preciseResize(1000, 1337)); + $this->assertEquals(1000, $img->width()); + $this->assertEquals(1337, $img->height()); + } + + public function testCenterCrop() { + $img = new \OC_Image(OC::$SERVERROOT.'/tests/data/testimage.png'); + $img->centerCrop(); + $this->assertEquals(128, $img->width()); + $this->assertEquals(128, $img->height()); + + $img = new \OC_Image(file_get_contents(OC::$SERVERROOT.'/tests/data/testimage.jpg')); + $img->centerCrop(); + $this->assertEquals(1050, $img->width()); + $this->assertEquals(1050, $img->height()); + + $img = new \OC_Image(base64_encode(file_get_contents(OC::$SERVERROOT.'/tests/data/testimage.gif'))); + $img->centerCrop(512); + $this->assertEquals(512, $img->width()); + $this->assertEquals(512, $img->height()); + } + + public function testCrop() { + $img = new \OC_Image(OC::$SERVERROOT.'/tests/data/testimage.png'); + $this->assertTrue($img->crop(0, 0, 50, 20)); + $this->assertEquals(50, $img->width()); + $this->assertEquals(20, $img->height()); + + $img = new \OC_Image(file_get_contents(OC::$SERVERROOT.'/tests/data/testimage.jpg')); + $this->assertTrue($img->crop(500, 700, 550, 300)); + $this->assertEquals(550, $img->width()); + $this->assertEquals(300, $img->height()); + + $img = new \OC_Image(base64_encode(file_get_contents(OC::$SERVERROOT.'/tests/data/testimage.gif'))); + $this->assertTrue($img->crop(10, 10, 15, 15)); + $this->assertEquals(15, $img->width()); + $this->assertEquals(15, $img->height()); + } + + public static function sampleProvider() { + return [ + ['testimage.png', [200, 100], [100, 100]], + ['testimage.jpg', [840, 840], [840, 525]], + ['testimage.gif', [200, 250], [200, 200]] + ]; + } + + /** + * @dataProvider sampleProvider + * + * @param string $filename + * @param int[] $asked + * @param int[] $expected + */ + public function testFitIn($filename, $asked, $expected) { + $img = new \OC_Image(OC::$SERVERROOT . '/tests/data/' . $filename); + $this->assertTrue($img->fitIn($asked[0], $asked[1])); + $this->assertEquals($expected[0], $img->width()); + $this->assertEquals($expected[1], $img->height()); + } + + public static function sampleFilenamesProvider() { + return [ + ['testimage.png'], + ['testimage.jpg'], + ['testimage.gif'] + ]; + } + + /** + * Image should not be resized if it's already smaller than what is required + * + * @dataProvider sampleFilenamesProvider + * + * @param string $filename + */ + public function testScaleDownToFitWhenSmallerAlready($filename) { + $img = new \OC_Image(OC::$SERVERROOT . '/tests/data/' . $filename); + $currentWidth = $img->width(); + $currentHeight = $img->height(); + // We pick something larger than the image we want to scale down + $this->assertFalse($img->scaleDownToFit(4000, 4000)); + // The dimensions of the image should not have changed since it's smaller already + $resizedWidth = $img->width(); + $resizedHeight = $img->height(); + $this->assertEquals( + $currentWidth, $img->width(), "currentWidth $currentWidth resizedWidth $resizedWidth \n" + ); + $this->assertEquals( + $currentHeight, $img->height(), + "currentHeight $currentHeight resizedHeight $resizedHeight \n" + ); + } + + public static function largeSampleProvider() { + return [ + ['testimage.png', [200, 100], [100, 100]], + ['testimage.jpg', [840, 840], [840, 525]], + ]; + } + + /** + * @dataProvider largeSampleProvider + * + * @param string $filename + * @param int[] $asked + * @param int[] $expected + */ + public function testScaleDownWhenBigger($filename, $asked, $expected) { + $img = new \OC_Image(OC::$SERVERROOT . '/tests/data/' . $filename); + //$this->assertTrue($img->scaleDownToFit($asked[0], $asked[1])); + $img->scaleDownToFit($asked[0], $asked[1]); + $this->assertEquals($expected[0], $img->width()); + $this->assertEquals($expected[1], $img->height()); + } + + function convertDataProvider() { + return array( + array( 'image/gif'), + array( 'image/jpeg'), + array( 'image/png'), + ); + } + + /** + * @dataProvider convertDataProvider + */ + public function testConvert($mimeType) { + $img = new \OC_Image(OC::$SERVERROOT.'/tests/data/testimage.png'); + $tempFile = tempnam(sys_get_temp_dir(), 'img-test'); + + $img->save($tempFile, $mimeType); + $actualMimeType = \OC_Image::getMimeTypeForFile($tempFile); + $this->assertEquals($mimeType, $actualMimeType); + } +} diff --git a/tests/lib/LegacyHelperTest.php b/tests/lib/LegacyHelperTest.php new file mode 100644 index 00000000000..d8b1a82c271 --- /dev/null +++ b/tests/lib/LegacyHelperTest.php @@ -0,0 +1,301 @@ + + * This file is licensed under the Affero General Public License version 3 or + * later. + * See the COPYING-README file. + */ + +namespace Test; + +use OC_Helper; + +class LegacyHelperTest extends \Test\TestCase { + + /** + * @dataProvider humanFileSizeProvider + */ + public function testHumanFileSize($expected, $input) + { + $result = OC_Helper::humanFileSize($input); + $this->assertEquals($expected, $result); + } + + public function humanFileSizeProvider() + { + return array( + array('0 B', 0), + array('1 KB', 1024), + array('9.5 MB', 10000000), + array('1.3 GB', 1395864371), + array('465.7 GB', 500000000000), + array('454.7 TB', 500000000000000), + array('444.1 PB', 500000000000000000), + ); + } + + /** + * @dataProvider phpFileSizeProvider + */ + public function testPhpFileSize($expected, $input) + { + $result = OC_Helper::phpFileSize($input); + $this->assertEquals($expected, $result); + } + + public function phpFileSizeProvider() + { + return array( + array('0B', 0), + array('1K', 1024), + array('9.5M', 10000000), + array('1.3G', 1395864371), + array('465.7G', 500000000000), + array('465661.3G', 500000000000000), + array('465661287.3G', 500000000000000000), + ); + } + + /** + * @dataProvider providesComputerFileSize + */ + function testComputerFileSize($expected, $input) { + $result = OC_Helper::computerFileSize($input); + $this->assertEquals($expected, $result); + } + + function providesComputerFileSize(){ + return [ + [0.0, "0 B"], + [1024.0, "1 KB"], + [1395864371.0, '1.3 GB'], + [9961472.0, "9.5 MB"], + [500041567437.0, "465.7 GB"], + [false, "12 GB etfrhzui"] + ]; + } + + function testIsSubDirectory() { + $result = OC_Helper::isSubDirectory("./data/", "/anotherDirectory/"); + $this->assertFalse($result); + + $result = OC_Helper::isSubDirectory("./data/", "./data/"); + $this->assertTrue($result); + + mkdir("data/TestSubdirectory", 0777); + $result = OC_Helper::isSubDirectory("data/TestSubdirectory/", "data"); + rmdir("data/TestSubdirectory"); + $this->assertTrue($result); + } + + function testMb_array_change_key_case() { + $arrayStart = array( + "Foo" => "bar", + "Bar" => "foo", + ); + $arrayResult = array( + "foo" => "bar", + "bar" => "foo", + ); + $result = OC_Helper::mb_array_change_key_case($arrayStart); + $expected = $arrayResult; + $this->assertEquals($result, $expected); + + $arrayStart = array( + "foo" => "bar", + "bar" => "foo", + ); + $arrayResult = array( + "FOO" => "bar", + "BAR" => "foo", + ); + $result = OC_Helper::mb_array_change_key_case($arrayStart, MB_CASE_UPPER); + $expected = $arrayResult; + $this->assertEquals($result, $expected); + } + + function testRecursiveArraySearch() { + $haystack = array( + "Foo" => "own", + "Bar" => "Cloud", + ); + + $result = OC_Helper::recursiveArraySearch($haystack, "own"); + $expected = "Foo"; + $this->assertEquals($result, $expected); + + $result = OC_Helper::recursiveArraySearch($haystack, "NotFound"); + $this->assertFalse($result); + } + + function testBuildNotExistingFileNameForView() { + $viewMock = $this->getMock('\OC\Files\View', array(), array(), '', false); + $this->assertEquals('/filename', OC_Helper::buildNotExistingFileNameForView('/', 'filename', $viewMock)); + $this->assertEquals('dir/filename.ext', OC_Helper::buildNotExistingFileNameForView('dir', 'filename.ext', $viewMock)); + + $viewMock->expects($this->at(0)) + ->method('file_exists') + ->will($this->returnValue(true)); // filename.ext exists + $this->assertEquals('dir/filename (2).ext', OC_Helper::buildNotExistingFileNameForView('dir', 'filename.ext', $viewMock)); + + $viewMock->expects($this->at(0)) + ->method('file_exists') + ->will($this->returnValue(true)); // filename.ext exists + $viewMock->expects($this->at(1)) + ->method('file_exists') + ->will($this->returnValue(true)); // filename (2).ext exists + $this->assertEquals('dir/filename (3).ext', OC_Helper::buildNotExistingFileNameForView('dir', 'filename.ext', $viewMock)); + + $viewMock->expects($this->at(0)) + ->method('file_exists') + ->will($this->returnValue(true)); // filename (1).ext exists + $this->assertEquals('dir/filename (2).ext', OC_Helper::buildNotExistingFileNameForView('dir', 'filename (1).ext', $viewMock)); + + $viewMock->expects($this->at(0)) + ->method('file_exists') + ->will($this->returnValue(true)); // filename (2).ext exists + $this->assertEquals('dir/filename (3).ext', OC_Helper::buildNotExistingFileNameForView('dir', 'filename (2).ext', $viewMock)); + + $viewMock->expects($this->at(0)) + ->method('file_exists') + ->will($this->returnValue(true)); // filename (2).ext exists + $viewMock->expects($this->at(1)) + ->method('file_exists') + ->will($this->returnValue(true)); // filename (3).ext exists + $this->assertEquals('dir/filename (4).ext', OC_Helper::buildNotExistingFileNameForView('dir', 'filename (2).ext', $viewMock)); + + $viewMock->expects($this->at(0)) + ->method('file_exists') + ->will($this->returnValue(true)); // filename(1).ext exists + $this->assertEquals('dir/filename(2).ext', OC_Helper::buildNotExistingFileNameForView('dir', 'filename(1).ext', $viewMock)); + + $viewMock->expects($this->at(0)) + ->method('file_exists') + ->will($this->returnValue(true)); // filename(1) (1).ext exists + $this->assertEquals('dir/filename(1) (2).ext', OC_Helper::buildNotExistingFileNameForView('dir', 'filename(1) (1).ext', $viewMock)); + + $viewMock->expects($this->at(0)) + ->method('file_exists') + ->will($this->returnValue(true)); // filename(1) (1).ext exists + $viewMock->expects($this->at(1)) + ->method('file_exists') + ->will($this->returnValue(true)); // filename(1) (2).ext exists + $this->assertEquals('dir/filename(1) (3).ext', OC_Helper::buildNotExistingFileNameForView('dir', 'filename(1) (1).ext', $viewMock)); + + $viewMock->expects($this->at(0)) + ->method('file_exists') + ->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'), + ); + } + + // Url generator methods + + /** + * @small + * test linkToPublic URL construction + */ + public function testLinkToPublic() { + \OC::$WEBROOT = ''; + $result = \OC_Helper::linkToPublic('files'); + $this->assertEquals('http://localhost/s', $result); + $result = \OC_Helper::linkToPublic('files', false); + $this->assertEquals('http://localhost/s', $result); + $result = \OC_Helper::linkToPublic('files', true); + $this->assertEquals('http://localhost/s/', $result); + + $result = \OC_Helper::linkToPublic('other'); + $this->assertEquals('http://localhost/public.php?service=other', $result); + $result = \OC_Helper::linkToPublic('other', false); + $this->assertEquals('http://localhost/public.php?service=other', $result); + $result = \OC_Helper::linkToPublic('other', true); + $this->assertEquals('http://localhost/public.php?service=other/', $result); + + \OC::$WEBROOT = '/owncloud'; + $result = \OC_Helper::linkToPublic('files'); + $this->assertEquals('http://localhost/owncloud/s', $result); + $result = \OC_Helper::linkToPublic('files', false); + $this->assertEquals('http://localhost/owncloud/s', $result); + $result = \OC_Helper::linkToPublic('files', true); + $this->assertEquals('http://localhost/owncloud/s/', $result); + + $result = \OC_Helper::linkToPublic('other'); + $this->assertEquals('http://localhost/owncloud/public.php?service=other', $result); + $result = \OC_Helper::linkToPublic('other', false); + $this->assertEquals('http://localhost/owncloud/public.php?service=other', $result); + $result = \OC_Helper::linkToPublic('other', true); + $this->assertEquals('http://localhost/owncloud/public.php?service=other/', $result); + } + + /** + * Tests recursive folder deletion with rmdirr() + */ + public function testRecursiveFolderDeletion() { + $baseDir = \OC::$server->getTempManager()->getTemporaryFolder() . '/'; + mkdir($baseDir . 'a/b/c/d/e', 0777, true); + mkdir($baseDir . 'a/b/c1/d/e', 0777, true); + mkdir($baseDir . 'a/b/c2/d/e', 0777, true); + mkdir($baseDir . 'a/b1/c1/d/e', 0777, true); + mkdir($baseDir . 'a/b2/c1/d/e', 0777, true); + mkdir($baseDir . 'a/b3/c1/d/e', 0777, true); + mkdir($baseDir . 'a1/b', 0777, true); + mkdir($baseDir . 'a1/c', 0777, true); + file_put_contents($baseDir . 'a/test.txt', 'Hello file!'); + file_put_contents($baseDir . 'a/b1/c1/test one.txt', 'Hello file one!'); + file_put_contents($baseDir . 'a1/b/test two.txt', 'Hello file two!'); + \OC_Helper::rmdirr($baseDir . 'a'); + + $this->assertFalse(file_exists($baseDir . 'a')); + $this->assertTrue(file_exists($baseDir . 'a1')); + + \OC_Helper::rmdirr($baseDir); + $this->assertFalse(file_exists($baseDir)); + } + + /** + * Allows us to test private methods/properties + * + * @param $object + * @param $methodName + * @param array $parameters + * @return mixed + * @deprecated Please extend \Test\TestCase and use self::invokePrivate() then + */ + public static function invokePrivate($object, $methodName, array $parameters = array()) { + return parent::invokePrivate($object, $methodName, $parameters); + } +} diff --git a/tests/lib/NaturalSortTest.php b/tests/lib/NaturalSortTest.php new file mode 100644 index 00000000000..50c2d0be9f0 --- /dev/null +++ b/tests/lib/NaturalSortTest.php @@ -0,0 +1,272 @@ + + * This file is licensed under the Affero General Public License version 3 or + * later. + * See the COPYING-README file. + */ + +namespace Test; + +class NaturalSortTest extends \Test\TestCase { + + /** + * @dataProvider naturalSortDataProvider + */ + public function testNaturalSortCompare($array, $sorted) + { + if(!class_exists('Collator')) { + $this->markTestSkipped('The intl module is not available, natural sorting might not work as expected.'); + return; + } + $comparator = \OC\NaturalSort::getInstance(); + usort($array, array($comparator, 'compare')); + $this->assertEquals($sorted, $array); + } + + /** + * @dataProvider defaultCollatorDataProvider + */ + public function testDefaultCollatorCompare($array, $sorted) + { + $comparator = new \OC\NaturalSort(new \OC\NaturalSort_DefaultCollator()); + usort($array, array($comparator, 'compare')); + $this->assertEquals($sorted, $array); + } + + /** + * Data provider for natural sorting with php5-intl's Collator. + * Must provide the same result as in core/js/tests/specs/coreSpec.js + * @return array test cases + */ + public function naturalSortDataProvider() + { + return array( + // different casing + array( + // unsorted + array( + 'aaa', + 'bbb', + 'BBB', + 'AAA' + ), + // sorted + array( + 'aaa', + 'AAA', + 'bbb', + 'BBB' + ) + ), + // numbers + array( + // unsorted + array( + '124.txt', + 'abc1', + '123.txt', + 'abc', + 'abc2', + 'def (2).txt', + 'ghi 10.txt', + 'abc12', + 'def.txt', + 'def (1).txt', + 'ghi 2.txt', + 'def (10).txt', + 'abc10', + 'def (12).txt', + 'z', + 'ghi.txt', + 'za', + 'ghi 1.txt', + 'ghi 12.txt', + 'zz', + '15.txt', + '15b.txt', + ), + // sorted + array( + '15.txt', + '15b.txt', + '123.txt', + '124.txt', + 'abc', + 'abc1', + 'abc2', + 'abc10', + 'abc12', + 'def.txt', + 'def (1).txt', + 'def (2).txt', + 'def (10).txt', + 'def (12).txt', + 'ghi.txt', + 'ghi 1.txt', + 'ghi 2.txt', + 'ghi 10.txt', + 'ghi 12.txt', + 'z', + 'za', + 'zz', + ) + ), + // chinese characters + array( + // unsorted + array( + '十.txt', + '一.txt', + '二.txt', + '十 2.txt', + '三.txt', + '四.txt', + 'abc.txt', + '五.txt', + '七.txt', + '八.txt', + '九.txt', + '六.txt', + '十一.txt', + '波.txt', + '破.txt', + '莫.txt', + '啊.txt', + '123.txt', + ), + // sorted + array( + '123.txt', + 'abc.txt', + '一.txt', + '七.txt', + '三.txt', + '九.txt', + '二.txt', + '五.txt', + '八.txt', + '六.txt', + '十.txt', + '十 2.txt', + '十一.txt', + '啊.txt', + '四.txt', + '波.txt', + '破.txt', + '莫.txt', + ) + ), + // with umlauts + array( + // unsorted + array( + 'öh.txt', + 'Äh.txt', + 'oh.txt', + 'Üh 2.txt', + 'Üh.txt', + 'ah.txt', + 'Öh.txt', + 'uh.txt', + 'üh.txt', + 'äh.txt', + ), + // sorted + array( + 'ah.txt', + 'äh.txt', + 'Äh.txt', + 'oh.txt', + 'öh.txt', + 'Öh.txt', + 'uh.txt', + 'üh.txt', + 'Üh.txt', + 'Üh 2.txt', + ) + ), + ); + } + + /** + * Data provider for natural sorting with \OC\NaturalSort_DefaultCollator. + * Must provide the same result as in core/js/tests/specs/coreSpec.js + * @return array test cases + */ + public function defaultCollatorDataProvider() + { + return array( + // different casing + array( + // unsorted + array( + 'aaa', + 'bbb', + 'BBB', + 'AAA' + ), + // sorted + array( + 'aaa', + 'AAA', + 'bbb', + 'BBB' + ) + ), + // numbers + array( + // unsorted + array( + '124.txt', + 'abc1', + '123.txt', + 'abc', + 'abc2', + 'def (2).txt', + 'ghi 10.txt', + 'abc12', + 'def.txt', + 'def (1).txt', + 'ghi 2.txt', + 'def (10).txt', + 'abc10', + 'def (12).txt', + 'z', + 'ghi.txt', + 'za', + 'ghi 1.txt', + 'ghi 12.txt', + 'zz', + '15.txt', + '15b.txt', + ), + // sorted + array( + '15.txt', + '15b.txt', + '123.txt', + '124.txt', + 'abc', + 'abc1', + 'abc2', + 'abc10', + 'abc12', + 'def.txt', + 'def (1).txt', + 'def (2).txt', + 'def (10).txt', + 'def (12).txt', + 'ghi.txt', + 'ghi 1.txt', + 'ghi 2.txt', + 'ghi 10.txt', + 'ghi 12.txt', + 'z', + 'za', + 'zz', + ) + ), + ); + } +} diff --git a/tests/lib/RepairStepTest.php b/tests/lib/RepairStepTest.php new file mode 100644 index 00000000000..3f7a0ce064b --- /dev/null +++ b/tests/lib/RepairStepTest.php @@ -0,0 +1,134 @@ + + * This file is licensed under the Affero General Public License version 3 or + * later. + * See the COPYING-README file. + */ + +namespace Test; + +use OCP\Migration\IRepairStep; +use Symfony\Component\EventDispatcher\EventDispatcher; + +class RepairStepTest implements IRepairStep { + private $warning; + + public function __construct($warning = false) { + $this->warning = $warning; + } + + public function getName() { + return 'Test Name'; + } + + public function run(\OCP\Migration\IOutput $out) { + if ($this->warning) { + $out->warning('Simulated warning'); + } + else { + $out->info('Simulated info'); + } + } +} + +class RepairTest extends TestCase { + /** @var \OC\Repair */ + private $repair; + + /** @var string[] */ + private $outputArray; + + public function setUp() { + parent::setUp(); + $dispatcher = new EventDispatcher(); + $this->repair = new \OC\Repair([], $dispatcher); + + $dispatcher->addListener('\OC\Repair::warning', function ($event) { + /** @var \Symfony\Component\EventDispatcher\GenericEvent $event */ + $this->outputArray[] = 'warning: ' . $event->getArgument(0); + }); + $dispatcher->addListener('\OC\Repair::info', function ($event) { + /** @var \Symfony\Component\EventDispatcher\GenericEvent $event */ + $this->outputArray[] = 'info: ' . $event->getArgument(0); + }); + $dispatcher->addListener('\OC\Repair::step', function ($event) { + /** @var \Symfony\Component\EventDispatcher\GenericEvent $event */ + $this->outputArray[] = 'step: ' . $event->getArgument(0); + }); + } + + public function testRunRepairStep() { + + $this->repair->addStep(new TestRepairStep(false)); + $this->repair->run(); + + $this->assertEquals( + array( + 'step: Test Name', + 'info: Simulated info', + ), + $this->outputArray + ); + } + + public function testRunRepairStepThatFail() { + + $this->repair->addStep(new TestRepairStep(true)); + $this->repair->run(); + + $this->assertEquals( + array( + 'step: Test Name', + 'warning: Simulated warning', + ), + $this->outputArray + ); + } + + public function testRunRepairStepsWithException() { + $mock = $this->getMock('\Test\TestRepairStep'); + $mock->expects($this->any()) + ->method('run') + ->will($this->throwException(new \Exception())); + $mock->expects($this->any()) + ->method('getName') + ->will($this->returnValue('Exception Test')); + + $this->repair->addStep($mock); + $this->repair->addStep(new TestRepairStep(false)); + + $thrown = false; + try { + $this->repair->run(); + } + catch (\Exception $e) { + $thrown = true; + } + + $this->assertTrue($thrown); + // jump out after exception + $this->assertEquals( + array( + 'step: Exception Test', + ), + $this->outputArray + ); + } + + public function testRunRepairStepsContinueAfterWarning() { + $this->repair->addStep(new TestRepairStep(true)); + $this->repair->addStep(new TestRepairStep(false)); + $this->repair->run(); + + $this->assertEquals( + array( + 'step: Test Name', + 'warning: Simulated warning', + 'step: Test Name', + 'info: Simulated info', + ), + $this->outputArray + ); + } +} diff --git a/tests/lib/RepairTest.php b/tests/lib/RepairTest.php deleted file mode 100644 index 9ae1318eb32..00000000000 --- a/tests/lib/RepairTest.php +++ /dev/null @@ -1,134 +0,0 @@ - - * This file is licensed under the Affero General Public License version 3 or - * later. - * See the COPYING-README file. - */ - -namespace Test; - -use OCP\Migration\IRepairStep; -use Symfony\Component\EventDispatcher\EventDispatcher; - -class TestRepairStep implements IRepairStep { - private $warning; - - public function __construct($warning = false) { - $this->warning = $warning; - } - - public function getName() { - return 'Test Name'; - } - - public function run(\OCP\Migration\IOutput $out) { - if ($this->warning) { - $out->warning('Simulated warning'); - } - else { - $out->info('Simulated info'); - } - } -} - -class RepairTest extends TestCase { - /** @var \OC\Repair */ - private $repair; - - /** @var string[] */ - private $outputArray; - - public function setUp() { - parent::setUp(); - $dispatcher = new EventDispatcher(); - $this->repair = new \OC\Repair([], $dispatcher); - - $dispatcher->addListener('\OC\Repair::warning', function ($event) { - /** @var \Symfony\Component\EventDispatcher\GenericEvent $event */ - $this->outputArray[] = 'warning: ' . $event->getArgument(0); - }); - $dispatcher->addListener('\OC\Repair::info', function ($event) { - /** @var \Symfony\Component\EventDispatcher\GenericEvent $event */ - $this->outputArray[] = 'info: ' . $event->getArgument(0); - }); - $dispatcher->addListener('\OC\Repair::step', function ($event) { - /** @var \Symfony\Component\EventDispatcher\GenericEvent $event */ - $this->outputArray[] = 'step: ' . $event->getArgument(0); - }); - } - - public function testRunRepairStep() { - - $this->repair->addStep(new TestRepairStep(false)); - $this->repair->run(); - - $this->assertEquals( - array( - 'step: Test Name', - 'info: Simulated info', - ), - $this->outputArray - ); - } - - public function testRunRepairStepThatFail() { - - $this->repair->addStep(new TestRepairStep(true)); - $this->repair->run(); - - $this->assertEquals( - array( - 'step: Test Name', - 'warning: Simulated warning', - ), - $this->outputArray - ); - } - - public function testRunRepairStepsWithException() { - $mock = $this->getMock('\Test\TestRepairStep'); - $mock->expects($this->any()) - ->method('run') - ->will($this->throwException(new \Exception())); - $mock->expects($this->any()) - ->method('getName') - ->will($this->returnValue('Exception Test')); - - $this->repair->addStep($mock); - $this->repair->addStep(new TestRepairStep(false)); - - $thrown = false; - try { - $this->repair->run(); - } - catch (\Exception $e) { - $thrown = true; - } - - $this->assertTrue($thrown); - // jump out after exception - $this->assertEquals( - array( - 'step: Exception Test', - ), - $this->outputArray - ); - } - - public function testRunRepairStepsContinueAfterWarning() { - $this->repair->addStep(new TestRepairStep(true)); - $this->repair->addStep(new TestRepairStep(false)); - $this->repair->run(); - - $this->assertEquals( - array( - 'step: Test Name', - 'warning: Simulated warning', - 'step: Test Name', - 'info: Simulated info', - ), - $this->outputArray - ); - } -} diff --git a/tests/lib/SetupTest.php b/tests/lib/SetupTest.php new file mode 100644 index 00000000000..e2723efd76a --- /dev/null +++ b/tests/lib/SetupTest.php @@ -0,0 +1,135 @@ + + * This file is licensed under the Affero General Public License version 3 or + * later. + * See the COPYING-README file. + */ + +namespace Test; + +use OCP\IConfig; + +class SetupTest extends \Test\TestCase { + + /** @var IConfig | \PHPUnit_Framework_MockObject_MockObject */ + protected $config; + /** @var \bantu\IniGetWrapper\IniGetWrapper | \PHPUnit_Framework_MockObject_MockObject */ + private $iniWrapper; + /** @var \OCP\IL10N | \PHPUnit_Framework_MockObject_MockObject */ + private $l10n; + /** @var \OC_Defaults | \PHPUnit_Framework_MockObject_MockObject */ + private $defaults; + /** @var \OC\Setup | \PHPUnit_Framework_MockObject_MockObject */ + protected $setupClass; + /** @var \OCP\ILogger | \PHPUnit_Framework_MockObject_MockObject */ + protected $logger; + /** @var \OCP\Security\ISecureRandom | \PHPUnit_Framework_MockObject_MockObject */ + protected $random; + + protected function setUp() { + parent::setUp(); + + $this->config = $this->getMock('\OCP\IConfig'); + $this->iniWrapper = $this->getMock('\bantu\IniGetWrapper\IniGetWrapper'); + $this->l10n = $this->getMock('\OCP\IL10N'); + $this->defaults = $this->getMock('\OC_Defaults'); + $this->logger = $this->getMock('\OCP\ILogger'); + $this->random = $this->getMock('\OCP\Security\ISecureRandom'); + $this->setupClass = $this->getMock('\OC\Setup', + ['class_exists', 'is_callable', 'getAvailableDbDriversForPdo'], + [$this->config, $this->iniWrapper, $this->l10n, $this->defaults, $this->logger, $this->random]); + } + + public function testGetSupportedDatabasesWithOneWorking() { + $this->config + ->expects($this->once()) + ->method('getSystemValue') + ->will($this->returnValue( + array('sqlite', 'mysql', 'oci') + )); + $this->setupClass + ->expects($this->once()) + ->method('class_exists') + ->will($this->returnValue(true)); + $this->setupClass + ->expects($this->once()) + ->method('is_callable') + ->will($this->returnValue(false)); + $this->setupClass + ->expects($this->once()) + ->method('getAvailableDbDriversForPdo') + ->will($this->returnValue([])); + $result = $this->setupClass->getSupportedDatabases(); + $expectedResult = array( + 'sqlite' => 'SQLite' + ); + + $this->assertSame($expectedResult, $result); + } + + public function testGetSupportedDatabasesWithNoWorking() { + $this->config + ->expects($this->once()) + ->method('getSystemValue') + ->will($this->returnValue( + array('sqlite', 'mysql', 'oci', 'pgsql') + )); + $this->setupClass + ->expects($this->once()) + ->method('class_exists') + ->will($this->returnValue(false)); + $this->setupClass + ->expects($this->exactly(2)) + ->method('is_callable') + ->will($this->returnValue(false)); + $this->setupClass + ->expects($this->once()) + ->method('getAvailableDbDriversForPdo') + ->will($this->returnValue([])); + $result = $this->setupClass->getSupportedDatabases(); + + $this->assertSame(array(), $result); + } + + public function testGetSupportedDatabasesWithAllWorking() { + $this->config + ->expects($this->once()) + ->method('getSystemValue') + ->will($this->returnValue( + array('sqlite', 'mysql', 'pgsql', 'oci') + )); + $this->setupClass + ->expects($this->once()) + ->method('class_exists') + ->will($this->returnValue(true)); + $this->setupClass + ->expects($this->exactly(2)) + ->method('is_callable') + ->will($this->returnValue(true)); + $this->setupClass + ->expects($this->once()) + ->method('getAvailableDbDriversForPdo') + ->will($this->returnValue(['mysql'])); + $result = $this->setupClass->getSupportedDatabases(); + $expectedResult = array( + 'sqlite' => 'SQLite', + 'mysql' => 'MySQL/MariaDB', + 'pgsql' => 'PostgreSQL', + 'oci' => 'Oracle' + ); + $this->assertSame($expectedResult, $result); + } + + /** + * @expectedException \Exception + * @expectedExceptionMessage Supported databases are not properly configured. + */ + public function testGetSupportedDatabaseException() { + $this->config + ->expects($this->once()) + ->method('getSystemValue') + ->will($this->returnValue('NotAnArray')); + $this->setupClass->getSupportedDatabases(); + } +} diff --git a/tests/lib/StreamWrappersTest.php b/tests/lib/StreamWrappersTest.php new file mode 100644 index 00000000000..14bcbb847d9 --- /dev/null +++ b/tests/lib/StreamWrappersTest.php @@ -0,0 +1,116 @@ +. + * + */ + +namespace Test; + +/** + * Class StreamWrappersTest + * + * @group DB + */ +class StreamWrappersTest extends \Test\TestCase { + + private static $trashBinStatus; + + public static function setUpBeforeClass() { + self::$trashBinStatus = \OC_App::isEnabled('files_trashbin'); + \OC_App::disable('files_trashbin'); + } + + public static function tearDownAfterClass() { + if (self::$trashBinStatus) { + \OC_App::enable('files_trashbin'); + } + } + + public function testFakeDir() { + $items = array('foo', 'bar'); + \OC\Files\Stream\Dir::register('test', $items); + $dh = opendir('fakedir://test'); + $result = array(); + while ($file = readdir($dh)) { + $result[] = $file; + $this->assertContains($file, $items); + } + $this->assertEquals(count($items), count($result)); + } + + public function testCloseStream() { + //ensure all basic stream stuff works + $sourceFile = OC::$SERVERROOT . '/tests/data/lorem.txt'; + $tmpFile = \OC::$server->getTempManager()->getTemporaryFile('.txt'); + $file = 'close://' . $tmpFile; + $this->assertTrue(file_exists($file)); + file_put_contents($file, file_get_contents($sourceFile)); + $this->assertEquals(file_get_contents($sourceFile), file_get_contents($file)); + unlink($file); + clearstatcache(); + $this->assertFalse(file_exists($file)); + + //test callback + $tmpFile = \OC::$server->getTempManager()->getTemporaryFile('.txt'); + $file = 'close://' . $tmpFile; + $actual = false; + $callback = function($path) use (&$actual) { $actual = $path; }; + \OC\Files\Stream\Close::registerCallback($tmpFile, $callback); + $fh = fopen($file, 'w'); + fwrite($fh, 'asd'); + fclose($fh); + $this->assertSame($tmpFile, $actual); + } + + public function testOC() { + // FIXME: use proper tearDown with $this->loginAsUser() and $this->logout() + // (would currently break the tests for some reason) + $originalStorage = \OC\Files\Filesystem::getStorage('/'); + \OC\Files\Filesystem::clearMounts(); + + $storage = new \OC\Files\Storage\Temporary(array()); + $storage->file_put_contents('foo.txt', 'asd'); + \OC\Files\Filesystem::mount($storage, array(), '/'); + + $this->assertTrue(file_exists('oc:///foo.txt')); + $this->assertEquals('asd', file_get_contents('oc:///foo.txt')); + $this->assertEquals(array('.', '..', 'foo.txt'), scandir('oc:///')); + + file_put_contents('oc:///bar.txt', 'qwerty'); + $this->assertEquals('qwerty', $storage->file_get_contents('bar.txt')); + $this->assertEquals(array('.', '..', 'bar.txt', 'foo.txt'), scandir('oc:///')); + $this->assertEquals('qwerty', file_get_contents('oc:///bar.txt')); + + $fh = fopen('oc:///bar.txt', 'rb'); + $this->assertSame(0, ftell($fh)); + $content = fread($fh, 4); + $this->assertSame(4, ftell($fh)); + $this->assertSame('qwer', $content); + $content = fread($fh, 1); + $this->assertSame(5, ftell($fh)); + $this->assertSame(0, fseek($fh, 0)); + $this->assertSame(0, ftell($fh)); + + unlink('oc:///foo.txt'); + $this->assertEquals(array('.', '..', 'bar.txt'), scandir('oc:///')); + + \OC\Files\Filesystem::clearMounts(); + \OC\Files\Filesystem::mount($originalStorage, array(), '/'); + } +} diff --git a/tests/lib/TagsTest.php b/tests/lib/TagsTest.php new file mode 100644 index 00000000000..88e0f87ad8f --- /dev/null +++ b/tests/lib/TagsTest.php @@ -0,0 +1,316 @@ +. +* +*/ + +namespace Test; + +/** + * Class TagsTest + * + * @group DB + */ +class TagsTest extends \Test\TestCase { + + protected $objectType; + /** @var \OCP\IUser */ + protected $user; + /** @var \OCP\IUserSession */ + protected $userSession; + protected $backupGlobals = FALSE; + /** @var \OC\Tagging\TagMapper */ + protected $tagMapper; + /** @var \OCP\ITagManager */ + protected $tagMgr; + + protected function setUp() { + parent::setUp(); + + \OC_User::clearBackends(); + \OC_User::useBackend('dummy'); + $userId = $this->getUniqueID('user_'); + \OC::$server->getUserManager()->createUser($userId, 'pass'); + \OC_User::setUserId($userId); + $this->user = new \OC\User\User($userId, null); + $this->userSession = $this->getMock('\OCP\IUserSession'); + $this->userSession + ->expects($this->any()) + ->method('getUser') + ->will($this->returnValue($this->user)); + + $this->objectType = $this->getUniqueID('type_'); + $this->tagMapper = new \OC\Tagging\TagMapper(\OC::$server->getDatabaseConnection()); + $this->tagMgr = new \OC\TagManager($this->tagMapper, $this->userSession); + + } + + protected function tearDown() { + $conn = \OC::$server->getDatabaseConnection(); + $conn->executeQuery('DELETE FROM `*PREFIX*vcategory_to_object`'); + $conn->executeQuery('DELETE FROM `*PREFIX*vcategory`'); + + parent::tearDown(); + } + + public function testTagManagerWithoutUserReturnsNull() { + $this->userSession = $this->getMock('\OCP\IUserSession'); + $this->userSession + ->expects($this->any()) + ->method('getUser') + ->will($this->returnValue(null)); + $this->tagMgr = new \OC\TagManager($this->tagMapper, $this->userSession); + $this->assertNull($this->tagMgr->load($this->objectType)); + } + + public function testInstantiateWithDefaults() { + $defaultTags = array('Friends', 'Family', 'Work', 'Other'); + + $tagger = $this->tagMgr->load($this->objectType, $defaultTags); + + $this->assertEquals(4, count($tagger->getTags())); + } + + public function testAddTags() { + $tags = array('Friends', 'Family', 'Work', 'Other'); + + $tagger = $this->tagMgr->load($this->objectType); + + foreach($tags as $tag) { + $result = $tagger->add($tag); + $this->assertGreaterThan(0, $result, 'add() returned an ID <= 0'); + $this->assertTrue((bool)$result); + } + + $this->assertFalse($tagger->add('Family')); + $this->assertFalse($tagger->add('fAMILY')); + + $this->assertCount(4, $tagger->getTags(), 'Wrong number of added tags'); + } + + public function testAddMultiple() { + $tags = array('Friends', 'Family', 'Work', 'Other'); + + $tagger = $this->tagMgr->load($this->objectType); + + foreach($tags as $tag) { + $this->assertFalse($tagger->hasTag($tag)); + } + + $result = $tagger->addMultiple($tags); + $this->assertTrue((bool)$result); + + foreach($tags as $tag) { + $this->assertTrue($tagger->hasTag($tag)); + } + + $tagMaps = $tagger->getTags(); + $this->assertCount(4, $tagMaps, 'Not all tags added'); + foreach($tagMaps as $tagMap) { + $this->assertEquals(null, $tagMap['id']); + } + + // As addMultiple has been called without $sync=true, the tags aren't + // saved to the database, so they're gone when we reload $tagger: + + $tagger = $this->tagMgr->load($this->objectType); + $this->assertEquals(0, count($tagger->getTags())); + + // Now, we call addMultiple() with $sync=true so the tags will be + // be saved to the database. + $result = $tagger->addMultiple($tags, true); + $this->assertTrue((bool)$result); + + $tagMaps = $tagger->getTags(); + foreach($tagMaps as $tagMap) { + $this->assertNotEquals(null, $tagMap['id']); + } + + // Reload the tagger. + $tagger = $this->tagMgr->load($this->objectType); + + foreach($tags as $tag) { + $this->assertTrue($tagger->hasTag($tag)); + } + + $this->assertCount(4, $tagger->getTags(), 'Not all previously saved tags found'); + } + + public function testIsEmpty() { + $tagger = $this->tagMgr->load($this->objectType); + + $this->assertEquals(0, count($tagger->getTags())); + $this->assertTrue($tagger->isEmpty()); + + $result = $tagger->add('Tag'); + $this->assertGreaterThan(0, $result, 'add() returned an ID <= 0'); + $this->assertNotEquals(false, $result, 'add() returned false'); + $this->assertFalse($tagger->isEmpty()); + } + + public function testGetTagsForObjects() { + $defaultTags = array('Friends', 'Family', 'Work', 'Other'); + $tagger = $this->tagMgr->load($this->objectType, $defaultTags); + + $tagger->tagAs(1, 'Friends'); + $tagger->tagAs(1, 'Other'); + $tagger->tagAs(2, 'Family'); + + $tags = $tagger->getTagsForObjects(array(1)); + $this->assertEquals(1, count($tags)); + $tags = current($tags); + sort($tags); + $this->assertSame(array('Friends', 'Other'), $tags); + + $tags = $tagger->getTagsForObjects(array(1, 2)); + $this->assertEquals(2, count($tags)); + $tags1 = $tags[1]; + sort($tags1); + $this->assertSame(array('Friends', 'Other'), $tags1); + $this->assertSame(array('Family'), $tags[2]); + $this->assertEquals( + array(), + $tagger->getTagsForObjects(array(4)) + ); + $this->assertEquals( + array(), + $tagger->getTagsForObjects(array(4, 5)) + ); + } + + public function testGetTagsForObjectsMassiveResults() { + $defaultTags = array('tag1'); + $tagger = $this->tagMgr->load($this->objectType, $defaultTags); + $tagData = $tagger->getTags(); + $tagId = $tagData[0]['id']; + $tagType = $tagData[0]['type']; + + $conn = \OC::$server->getDatabaseConnection(); + $statement = $conn->prepare( + 'INSERT INTO `*PREFIX*vcategory_to_object` ' . + '(`objid`, `categoryid`, `type`) VALUES ' . + '(?, ?, ?)' + ); + + // insert lots of entries + $idsArray = array(); + for($i = 1; $i <= 1500; $i++) { + $statement->execute(array($i, $tagId, $tagType)); + $idsArray[] = $i; + } + + $tags = $tagger->getTagsForObjects($idsArray); + $this->assertEquals(1500, count($tags)); + } + + public function testDeleteTags() { + $defaultTags = array('Friends', 'Family', 'Work', 'Other'); + $tagger = $this->tagMgr->load($this->objectType, $defaultTags); + + $this->assertEquals(4, count($tagger->getTags())); + + $tagger->delete('family'); + $this->assertEquals(3, count($tagger->getTags())); + + $tagger->delete(array('Friends', 'Work', 'Other')); + $this->assertEquals(0, count($tagger->getTags())); + } + + public function testRenameTag() { + $defaultTags = array('Friends', 'Family', 'Wrok', 'Other'); + $tagger = $this->tagMgr->load($this->objectType, $defaultTags); + + $this->assertTrue($tagger->rename('Wrok', 'Work')); + $this->assertTrue($tagger->hasTag('Work')); + $this->assertFalse($tagger->hasTag('Wrok')); + $this->assertFalse($tagger->rename('Wrok', 'Work')); // Rename non-existant tag. + $this->assertFalse($tagger->rename('Work', 'Family')); // Collide with existing tag. + } + + public function testTagAs() { + $objids = array(1, 2, 3, 4, 5, 6, 7, 8, 9); + + $tagger = $this->tagMgr->load($this->objectType); + + foreach($objids as $id) { + $this->assertTrue($tagger->tagAs($id, 'Family')); + } + + $this->assertEquals(1, count($tagger->getTags())); + $this->assertEquals(9, count($tagger->getIdsForTag('Family'))); + } + + /** + * @depends testTagAs + */ + public function testUnTag() { + $objIds = array(1, 2, 3, 4, 5, 6, 7, 8, 9); + + // Is this "legal"? + $this->testTagAs(); + $tagger = $this->tagMgr->load($this->objectType); + + foreach($objIds as $id) { + $this->assertTrue(in_array($id, $tagger->getIdsForTag('Family'))); + $tagger->unTag($id, 'Family'); + $this->assertFalse(in_array($id, $tagger->getIdsForTag('Family'))); + } + + $this->assertEquals(1, count($tagger->getTags())); + $this->assertEquals(0, count($tagger->getIdsForTag('Family'))); + } + + public function testFavorite() { + $tagger = $this->tagMgr->load($this->objectType); + $this->assertTrue($tagger->addToFavorites(1)); + $this->assertEquals(array(1), $tagger->getFavorites()); + $this->assertTrue($tagger->removeFromFavorites(1)); + $this->assertEquals(array(), $tagger->getFavorites()); + } + + public function testShareTags() { + $testTag = 'TestTag'; + \OCP\Share::registerBackend('test', 'Test_Share_Backend'); + + $tagger = $this->tagMgr->load('test'); + $tagger->tagAs(1, $testTag); + + $otherUserId = $this->getUniqueID('user2_'); + \OC::$server->getUserManager()->createUser($otherUserId, 'pass'); + \OC_User::setUserId($otherUserId); + $otherUserSession = $this->getMock('\OCP\IUserSession'); + $otherUserSession + ->expects($this->any()) + ->method('getUser') + ->will($this->returnValue(new \OC\User\User($otherUserId, null))); + + $otherTagMgr = new \OC\TagManager($this->tagMapper, $otherUserSession); + $otherTagger = $otherTagMgr->load('test'); + $this->assertFalse($otherTagger->hasTag($testTag)); + + \OC_User::setUserId($this->user->getUID()); + \OCP\Share::shareItem('test', 1, \OCP\Share::SHARE_TYPE_USER, $otherUserId, \OCP\Constants::PERMISSION_READ); + + \OC_User::setUserId($otherUserId); + $otherTagger = $otherTagMgr->load('test', array(), true); // Update tags, load shared ones. + $this->assertTrue($otherTagger->hasTag($testTag)); + $this->assertContains(1, $otherTagger->getIdsForTag($testTag)); + } + +} diff --git a/tests/lib/TemplateFunctionsTest.php b/tests/lib/TemplateFunctionsTest.php new file mode 100644 index 00000000000..aa3c73d4743 --- /dev/null +++ b/tests/lib/TemplateFunctionsTest.php @@ -0,0 +1,252 @@ + + * + * 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 . + * + */ + +namespace Test; + +class TemplateFunctionsTest extends \Test\TestCase { + + protected function setUp() { + parent::setUp(); + + $loader = new \OC\Autoloader([\OC::$SERVERROOT . '/lib']); + $loader->load('OC_Template'); + } + + public function testPJavaScript() { + $this->expectOutputString('<img onload="alert(1)" />'); + p(''); + } + + public function testPJavaScriptWithScriptTags() { + $this->expectOutputString('<script>alert('Hacked!');</script>'); + p(""); + } + + public function testPNormalString() { + $string = 'This is a good string without HTML.'; + $this->expectOutputString($string); + p($string); + } + + public function testPrintUnescaped() { + $htmlString = ""; + $this->expectOutputString($htmlString); + print_unescaped($htmlString); + } + + public function testPrintUnescapedNormalString() { + $string = 'This is a good string!'; + $this->expectOutputString($string); + print_unescaped($string); + } + + // --------------------------------------------------------------------------- + // 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 * 65; + $result = (string)relative_modified_date($elementTime, $currentTime, true); + + $this->assertEquals('2 months ago', $result); + + $elementTime = $currentTime - 86400 * 130; + $result = (string)relative_modified_date($elementTime, $currentTime, true); + + $this->assertEquals('4 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('2 years ago', $result); + + $elementTime = $currentTime - 86400 * 365.25 * 3; + $result = (string)relative_modified_date($elementTime, $currentTime, true); + + $this->assertEquals('3 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 * 65; + $result = (string)relative_modified_date($elementTime, $currentTime, false); + + $this->assertEquals('2 months ago', $result); + + $elementTime = $currentTime - 86400 * 130; + $result = (string)relative_modified_date($elementTime, $currentTime, false); + + $this->assertEquals('4 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('2 years ago', $result); + + $elementTime = $currentTime - 86400 * 365.25 * 3; + $result = (string)relative_modified_date($elementTime, $currentTime, false); + + $this->assertEquals('3 years ago', $result); + } +} diff --git a/tests/lib/UpdaterTest.php b/tests/lib/UpdaterTest.php new file mode 100644 index 00000000000..643a18cc714 --- /dev/null +++ b/tests/lib/UpdaterTest.php @@ -0,0 +1,182 @@ + + * @author Victor Dubiniuk + * + * @copyright Copyright (c) 2015, ownCloud, Inc. + * @license AGPL-3.0 + * + * This code is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License, version 3, + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License, version 3, + * along with this program. If not, see + * + */ + +namespace Test; + +use OC\Updater; +use OCP\IConfig; +use OCP\ILogger; +use OC\IntegrityCheck\Checker; + +class UpdaterTest extends \Test\TestCase { + /** @var IConfig|\PHPUnit_Framework_MockObject_MockObject */ + private $config; + /** @var ILogger */ + private $logger; + /** @var Updater */ + private $updater; + /** @var Checker */ + private $checker; + + public function setUp() { + parent::setUp(); + $this->config = $this->getMockBuilder('\\OCP\\IConfig') + ->disableOriginalConstructor() + ->getMock(); + $this->logger = $this->getMockBuilder('\\OCP\\ILogger') + ->disableOriginalConstructor() + ->getMock(); + $this->checker = $this->getMockBuilder('\OC\IntegrityCheck\Checker') + ->disableOriginalConstructor() + ->getMock(); + + $this->updater = new Updater( + $this->config, + $this->checker, + $this->logger + ); + } + + /** + * @param string $baseUrl + * @return string + */ + private function buildUpdateUrl($baseUrl) { + return $baseUrl . '?version='.implode('x', \OCP\Util::getVersion()).'xinstalledatxlastupdatedatx'.\OC_Util::getChannel().'x'.\OC_Util::getEditionString().'x'; + } + + /** + * @return array + */ + public function versionCompatibilityTestData() { + return [ + ['1', '2', '1', true], + ['2', '2', '2', true], + ['6.0.5.0', '6.0.6.0', '5.0', true], + ['5.0.6.0', '7.0.4.0', '6.0', false], + // allow upgrading within the same major release + ['8.0.0.0', '8.0.0.0', '8.0', true], + ['8.0.0.0', '8.0.0.4', '8.0', true], + ['8.0.0.0', '8.0.1.0', '8.0', true], + ['8.0.0.0', '8.0.2.0', '8.0', true], + // does not allow downgrading within the same major release + ['8.0.1.0', '8.0.0.0', '8.0', false], + ['8.0.2.0', '8.0.1.0', '8.0', false], + ['8.0.0.4', '8.0.0.0', '8.0', false], + // allows upgrading within the patch version + ['8.0.0.0', '8.0.0.1', '8.0', true], + ['8.0.0.0', '8.0.0.2', '8.0', true], + // does not allow downgrading within the same major release + ['8.0.0.1', '8.0.0.0', '8.0', false], + ['8.0.0.2', '8.0.0.0', '8.0', false], + // allow upgrading to the next major release + ['8.0.0.0', '8.1.0.0', '8.0', true], + ['8.0.0.0', '8.1.1.0', '8.0', true], + ['8.0.0.0', '8.1.1.5', '8.0', true], + ['8.0.0.2', '8.1.1.5', '8.0', true], + ['8.1.0.0', '8.2.0.0', '8.1', true], + ['8.1.0.2', '8.2.0.4', '8.1', true], + ['8.1.0.5', '8.2.0.1', '8.1', true], + ['8.1.0.0', '8.2.1.0', '8.1', true], + ['8.1.0.2', '8.2.1.5', '8.1', true], + ['8.1.0.5', '8.2.1.1', '8.1', true], + // does not allow downgrading to the previous major release + ['8.1.0.0', '8.0.0.0', '7.0', false], + ['8.1.1.0', '8.0.0.0', '7.0', false], + // does not allow skipping major releases + ['8.0.0.0', '8.2.0.0', '8.1', false], + ['8.0.0.0', '8.2.1.0', '8.1', false], + ['8.0.0.0', '9.0.1.0', '8.2', false], + ['8.0.0.0', '10.0.0.0', '9.3', false], + // allows updating to the next major release + ['8.2.0.0', '9.0.0.0', '8.2', true], + ['8.2.0.0', '9.0.0.0', '8.2', true], + ['8.2.0.0', '9.0.1.0', '8.2', true], + ['8.2.0.0', '9.0.1.1', '8.2', true], + ['8.2.0.2', '9.0.1.1', '8.2', true], + ['8.2.2.0', '9.0.1.0', '8.2', true], + ['8.2.2.2', '9.0.1.1', '8.2', true], + ['9.0.0.0', '9.1.0.0', '9.0', true], + ['9.0.0.0', '9.1.0.2', '9.0', true], + ['9.0.0.2', '9.1.0.1', '9.0', true], + ['9.1.0.0', '9.2.0.0', '9.1', true], + ['9.2.0.0', '9.3.0.0', '9.2', true], + ['9.3.0.0', '10.0.0.0', '9.3', true], + // does not allow updating to the next major release (first number) + ['9.0.0.0', '8.2.0.0', '8.1', false], + // other cases + ['8.0.0.0', '8.1.5.0', '8.0', true], + ['8.2.0.0', '9.0.0.0', '8.2', true], + ['8.2.0.0', '9.1.0.0', '9.0', false], + ['9.0.0.0', '8.1.0.0', '8.0', false], + ['9.0.0.0', '8.0.0.0', '7.0', false], + ['9.1.0.0', '8.0.0.0', '7.0', false], + ['8.2.0.0', '8.1.0.0', '8.0', false], + + // With debug enabled + ['8.0.0.0', '8.2.0.0', '8.1', false, true], + ['8.1.0.0', '8.2.0.0', '8.1', true, true], + ['8.2.0.1', '8.2.0.1', '8.1', true, true], + ['8.3.0.0', '8.2.0.0', '8.1', true, true], + ]; + } + + /** + * @dataProvider versionCompatibilityTestData + * + * @param string $oldVersion + * @param string $newVersion + * @param string $allowedVersion + * @param bool $result + * @param bool $debug + */ + public function testIsUpgradePossible($oldVersion, $newVersion, $allowedVersion, $result, $debug = false) { + $this->config->expects($this->any()) + ->method('getSystemValue') + ->with('debug', false) + ->willReturn($debug); + + $this->assertSame($result, $this->updater->isUpgradePossible($oldVersion, $newVersion, $allowedVersion)); + } + + public function testSetSimulateStepEnabled() { + $this->updater->setSimulateStepEnabled(true); + $this->assertSame(true, $this->invokePrivate($this->updater, 'simulateStepEnabled')); + $this->updater->setSimulateStepEnabled(false); + $this->assertSame(false, $this->invokePrivate($this->updater, 'simulateStepEnabled')); + } + + public function testSetUpdateStepEnabled() { + $this->updater->setUpdateStepEnabled(true); + $this->assertSame(true, $this->invokePrivate($this->updater, 'updateStepEnabled')); + $this->updater->setUpdateStepEnabled(false); + $this->assertSame(false, $this->invokePrivate($this->updater, 'updateStepEnabled')); + } + + public function testSetSkip3rdPartyAppsDisable() { + $this->updater->setSkip3rdPartyAppsDisable(true); + $this->assertSame(true, $this->invokePrivate($this->updater, 'skip3rdPartyAppsDisable')); + $this->updater->setSkip3rdPartyAppsDisable(false); + $this->assertSame(false, $this->invokePrivate($this->updater, 'skip3rdPartyAppsDisable')); + } + +} diff --git a/tests/lib/UrlGeneratorTest.php b/tests/lib/UrlGeneratorTest.php new file mode 100644 index 00000000000..7186c8fad80 --- /dev/null +++ b/tests/lib/UrlGeneratorTest.php @@ -0,0 +1,134 @@ + + * This file is licensed under the Affero General Public License version 3 or + * later. + * See the COPYING-README file. + */ + +namespace Test; + +/** + * Class UrlGeneratorTest + * + * @group DB + */ +class UrlGeneratorTest extends \Test\TestCase { + + /** + * @small + * test linkTo URL construction + * @dataProvider provideDocRootAppUrlParts + */ + public function testLinkToDocRoot($app, $file, $args, $expectedResult) { + \OC::$WEBROOT = ''; + $config = $this->getMock('\OCP\IConfig'); + $cacheFactory = $this->getMock('\OCP\ICacheFactory'); + $urlGenerator = new \OC\URLGenerator($config, $cacheFactory); + $result = $urlGenerator->linkTo($app, $file, $args); + + $this->assertEquals($expectedResult, $result); + } + + /** + * @small + * test linkTo URL construction in sub directory + * @dataProvider provideSubDirAppUrlParts + */ + public function testLinkToSubDir($app, $file, $args, $expectedResult) { + \OC::$WEBROOT = '/owncloud'; + $config = $this->getMock('\OCP\IConfig'); + $cacheFactory = $this->getMock('\OCP\ICacheFactory'); + $urlGenerator = new \OC\URLGenerator($config, $cacheFactory); + $result = $urlGenerator->linkTo($app, $file, $args); + + $this->assertEquals($expectedResult, $result); + } + + /** + * @dataProvider provideRoutes + */ + public function testLinkToRouteAbsolute($route, $expected) { + \OC::$WEBROOT = '/owncloud'; + $config = $this->getMock('\OCP\IConfig'); + $cacheFactory = $this->getMock('\OCP\ICacheFactory'); + $urlGenerator = new \OC\URLGenerator($config, $cacheFactory); + $result = $urlGenerator->linkToRouteAbsolute($route); + $this->assertEquals($expected, $result); + + } + + public function provideRoutes() { + return array( + array('files_ajax_list', 'http://localhost/owncloud/index.php/apps/files/ajax/list.php'), + array('core_ajax_preview', 'http://localhost/owncloud/index.php/core/preview.png'), + ); + } + + public function provideDocRootAppUrlParts() { + return array( + array('files', 'ajax/list.php', array(), '/index.php/apps/files/ajax/list.php'), + array('files', 'ajax/list.php', array('trut' => 'trat', 'dut' => 'dat'), '/index.php/apps/files/ajax/list.php?trut=trat&dut=dat'), + array('', 'index.php', array('trut' => 'trat', 'dut' => 'dat'), '/index.php?trut=trat&dut=dat'), + ); + } + + public function provideSubDirAppUrlParts() { + return array( + array('files', 'ajax/list.php', array(), '/owncloud/index.php/apps/files/ajax/list.php'), + array('files', 'ajax/list.php', array('trut' => 'trat', 'dut' => 'dat'), '/owncloud/index.php/apps/files/ajax/list.php?trut=trat&dut=dat'), + array('', 'index.php', array('trut' => 'trat', 'dut' => 'dat'), '/owncloud/index.php?trut=trat&dut=dat'), + ); + } + + /** + * @small + * test absolute URL construction + * @dataProvider provideDocRootURLs + */ + function testGetAbsoluteURLDocRoot($url, $expectedResult) { + + \OC::$WEBROOT = ''; + $config = $this->getMock('\OCP\IConfig'); + $cacheFactory = $this->getMock('\OCP\ICacheFactory'); + $urlGenerator = new \OC\URLGenerator($config, $cacheFactory); + $result = $urlGenerator->getAbsoluteURL($url); + + $this->assertEquals($expectedResult, $result); + } + + /** + * @small + * test absolute URL construction + * @dataProvider provideSubDirURLs + */ + function testGetAbsoluteURLSubDir($url, $expectedResult) { + + \OC::$WEBROOT = '/owncloud'; + $config = $this->getMock('\OCP\IConfig'); + $cacheFactory = $this->getMock('\OCP\ICacheFactory'); + $urlGenerator = new \OC\URLGenerator($config, $cacheFactory); + $result = $urlGenerator->getAbsoluteURL($url); + + $this->assertEquals($expectedResult, $result); + } + + public function provideDocRootURLs() { + return array( + array("index.php", "http://localhost/index.php"), + array("/index.php", "http://localhost/index.php"), + array("/apps/index.php", "http://localhost/apps/index.php"), + array("apps/index.php", "http://localhost/apps/index.php"), + ); + } + + public function provideSubDirURLs() { + return array( + array("index.php", "http://localhost/owncloud/index.php"), + array("/index.php", "http://localhost/owncloud/index.php"), + array("/apps/index.php", "http://localhost/owncloud/apps/index.php"), + array("apps/index.php", "http://localhost/owncloud/apps/index.php"), + ); + } +} + diff --git a/tests/lib/UtilCheckServerTest.php b/tests/lib/UtilCheckServerTest.php new file mode 100644 index 00000000000..b864af6888a --- /dev/null +++ b/tests/lib/UtilCheckServerTest.php @@ -0,0 +1,172 @@ + + * This file is licensed under the Affero General Public License version 3 or + * later. + * See the COPYING-README file. + */ + +namespace Test; + +/** + * Tests for server check functions + * + * @group DB + */ +class UtilCheckServerTest extends \Test\TestCase { + + private $datadir; + + /** + * @param array $systemOptions + * @return \OCP\IConfig | \PHPUnit_Framework_MockObject_MockObject + */ + protected function getConfig($systemOptions) { + $systemOptions['datadirectory'] = $this->datadir; + $systemOptions['appstoreenabled'] = false; //it's likely that there is no app folder we can write in + $config = $this->getMockBuilder('\OCP\IConfig') + ->disableOriginalConstructor() + ->getMock(); + + $config->expects($this->any()) + ->method('getSystemValue') + ->will($this->returnCallback(function ($key, $default) use ($systemOptions) { + return isset($systemOptions[$key]) ? $systemOptions[$key] : $default; + })); + return $config; + } + + protected function setUp() { + parent::setUp(); + + $this->datadir = \OC::$server->getTempManager()->getTemporaryFolder(); + + file_put_contents($this->datadir . '/.ocdata', ''); + \OC::$server->getSession()->set('checkServer_succeeded', false); + } + + protected function tearDown() { + // clean up + @unlink($this->datadir . '/.ocdata'); + parent::tearDown(); + } + + /** + * Test that checkServer() returns no errors in the regular case. + */ + public function testCheckServer() { + $result = \OC_Util::checkServer($this->getConfig(array( + 'installed' => true + ))); + $this->assertEmpty($result); + } + + /** + * Test that checkServer() does not check the data dir validity + * when the server is not installed yet (else the setup cannot + * be run...) + */ + public function testCheckServerSkipDataDirValidityOnSetup() { + // simulate old version that didn't have it + unlink($this->datadir . '/.ocdata'); + + // even though ".ocdata" is missing, the error isn't + // triggered to allow setup to run + $result = \OC_Util::checkServer($this->getConfig(array( + 'installed' => false + ))); + $this->assertEmpty($result); + } + + /** + * Test that checkServer() does not check the data dir validity + * when an upgrade is required (else the upgrade cannot be + * performed...) + */ + public function testCheckServerSkipDataDirValidityOnUpgrade() { + // simulate old version that didn't have it + unlink($this->datadir . '/.ocdata'); + + $session = \OC::$server->getSession(); + $oldCurrentVersion = $session->get('OC_Version'); + + // upgrade condition to simulate needUpgrade() === true + $session->set('OC_Version', array(6, 0, 0, 2)); + + // even though ".ocdata" is missing, the error isn't + // triggered to allow for upgrade + $result = \OC_Util::checkServer($this->getConfig(array( + 'installed' => true, + 'version' => '6.0.0.1' + ))); + $this->assertEmpty($result); + + // restore versions + $session->set('OC_Version', $oldCurrentVersion); + } + + /** + * Test that checkDataDirectoryValidity returns no error + * when ".ocdata" is present. + */ + public function testCheckDataDirValidity() { + $result = \OC_Util::checkDataDirectoryValidity($this->datadir); + $this->assertEmpty($result); + } + + /** + * Test that checkDataDirectoryValidity and checkServer + * both return an error when ".ocdata" is missing. + */ + public function testCheckDataDirValidityWhenFileMissing() { + unlink($this->datadir . '/.ocdata'); + $result = \OC_Util::checkDataDirectoryValidity($this->datadir); + $this->assertEquals(1, count($result)); + + $result = \OC_Util::checkServer($this->getConfig(array( + 'installed' => true, + 'version' => implode('.', \OCP\Util::getVersion()) + ))); + $this->assertCount(1, $result); + } + + /** + * Tests that no error is given when the datadir is writable + */ + public function testDataDirWritable() { + $result = \OC_Util::checkServer($this->getConfig(array( + 'installed' => true, + 'version' => implode('.', \OCP\Util::getVersion()) + ))); + $this->assertEmpty($result); + } + + /** + * Tests an error is given when the datadir is not writable + */ + public function testDataDirNotWritable() { + if (\OC_Util::runningOnWindows()) { + $this->markTestSkipped('[Windows] chmod() does not work as intended on Windows.'); + } + + chmod($this->datadir, 0300); + $result = \OC_Util::checkServer($this->getConfig(array( + 'installed' => true, + 'version' => implode('.', \OCP\Util::getVersion()) + ))); + $this->assertCount(1, $result); + } + + /** + * Tests no error is given when the datadir is not writable during setup + */ + public function testDataDirNotWritableSetup() { + chmod($this->datadir, 0300); + $result = \OC_Util::checkServer($this->getConfig(array( + 'installed' => false, + 'version' => implode('.', \OCP\Util::getVersion()) + ))); + chmod($this->datadir, 0700); //needed for cleanup + $this->assertEmpty($result); + } +} diff --git a/tests/lib/UtilTest.php b/tests/lib/UtilTest.php new file mode 100644 index 00000000000..7da7db0291c --- /dev/null +++ b/tests/lib/UtilTest.php @@ -0,0 +1,509 @@ + + * This file is licensed under the Affero General Public License version 3 or + * later. + * See the COPYING-README file. + */ + +namespace Test; + +use OC_Util; + +class UtilTest extends \Test\TestCase { + public function testGetVersion() { + $version = \OCP\Util::getVersion(); + $this->assertTrue(is_array($version)); + foreach ($version as $num) { + $this->assertTrue(is_int($num)); + } + } + + public function testGetVersionString() { + $version = \OC_Util::getVersionString(); + $this->assertTrue(is_string($version)); + } + + public function testGetEditionString() { + $edition = \OC_Util::getEditionString(); + $this->assertTrue(is_string($edition)); + } + + function testFormatDate() { + date_default_timezone_set("UTC"); + + $result = OC_Util::formatDate(1350129205); + $expected = 'October 13, 2012 at 11:53:25 AM GMT+0'; + $this->assertEquals($expected, $result); + + $result = OC_Util::formatDate(1102831200, true); + $expected = 'December 12, 2004'; + $this->assertEquals($expected, $result); + } + + function testFormatDateWithTZ() { + date_default_timezone_set("UTC"); + + $result = OC_Util::formatDate(1350129205, false, 'Europe/Berlin'); + $expected = 'October 13, 2012 at 1:53:25 PM GMT+2'; + $this->assertEquals($expected, $result); + } + + /** + * @expectedException \Exception + */ + function testFormatDateWithInvalidTZ() { + OC_Util::formatDate(1350129205, false, 'Mordor/Barad-dûr'); + } + + public function formatDateWithTZFromSessionData() { + return array( + array(3, 'October 13, 2012 at 2:53:25 PM GMT+3', 'Etc/GMT-3'), + array(15, 'October 13, 2012 at 11:53:25 AM GMT+0', 'UTC'), + array(-13, 'October 13, 2012 at 11:53:25 AM GMT+0', 'UTC'), + array(9.5, 'October 13, 2012 at 9:23:25 PM GMT+9:30', 'Australia/Darwin'), + array(-4.5, 'October 13, 2012 at 7:23:25 AM GMT-4:30', 'America/Caracas'), + array(15.5, 'October 13, 2012 at 11:53:25 AM GMT+0', 'UTC'), + ); + } + + /** + * @dataProvider formatDateWithTZFromSessionData + */ + function testFormatDateWithTZFromSession($offset, $expected, $expectedTimeZone) { + date_default_timezone_set("UTC"); + + $oldDateTimeFormatter = \OC::$server->query('DateTimeFormatter'); + \OC::$server->getSession()->set('timezone', $offset); + + $selectedTimeZone = \OC::$server->getDateTimeZone()->getTimeZone(1350129205); + $this->assertEquals($expectedTimeZone, $selectedTimeZone->getName()); + $newDateTimeFormatter = new \OC\DateTimeFormatter($selectedTimeZone, new \OC_L10N('lib', 'en')); + $this->setDateFormatter($newDateTimeFormatter); + + $result = OC_Util::formatDate(1350129205, false); + $this->assertEquals($expected, $result); + + $this->setDateFormatter($oldDateTimeFormatter); + } + + protected function setDateFormatter($formatter) { + \OC::$server->registerService('DateTimeFormatter', function ($c) use ($formatter) { + return $formatter; + }); + } + + function testSanitizeHTML() { + $badArray = [ + 'While it is unusual to pass an array', + 'this function actually supports it.', + 'And therefore there needs to be a for it!', + [ + 'And It Even May Nest', + ], + ]; + $goodArray = [ + 'While it is unusual to pass an array', + 'this function actually <blink>supports</blink> it.', + 'And therefore there needs to be a <script>alert("Unit"+'test')</script> for it!', + [ + 'And It Even May <strong>Nest</strong>' + ], + ]; + $result = OC_Util::sanitizeHTML($badArray); + $this->assertEquals($goodArray, $result); + + $badString = ''; + $result = OC_Util::sanitizeHTML($badString); + $this->assertEquals('<img onload="alert(1)" />', $result); + + $badString = ""; + $result = OC_Util::sanitizeHTML($badString); + $this->assertEquals('<script>alert('Hacked!');</script>', $result); + + $goodString = 'This is a good string without HTML.'; + $result = OC_Util::sanitizeHTML($goodString); + $this->assertEquals('This is a good string without HTML.', $result); + } + + function testEncodePath() { + $component = '/§#@test%&^ä/-child'; + $result = OC_Util::encodePath($component); + $this->assertEquals("/%C2%A7%23%40test%25%26%5E%C3%A4/-child", $result); + } + + public function testFileInfoLoaded() { + $expected = function_exists('finfo_open'); + $this->assertEquals($expected, \OC_Util::fileInfoLoaded()); + } + + function testGetDefaultEmailAddress() { + $email = \OCP\Util::getDefaultEmailAddress("no-reply"); + $this->assertEquals('no-reply@localhost', $email); + } + + function testGetDefaultEmailAddressFromConfig() { + $config = \OC::$server->getConfig(); + $config->setSystemValue('mail_domain', 'example.com'); + $email = \OCP\Util::getDefaultEmailAddress("no-reply"); + $this->assertEquals('no-reply@example.com', $email); + $config->deleteSystemValue('mail_domain'); + } + + function testGetConfiguredEmailAddressFromConfig() { + $config = \OC::$server->getConfig(); + $config->setSystemValue('mail_domain', 'example.com'); + $config->setSystemValue('mail_from_address', 'owncloud'); + $email = \OCP\Util::getDefaultEmailAddress("no-reply"); + $this->assertEquals('owncloud@example.com', $email); + $config->deleteSystemValue('mail_domain'); + $config->deleteSystemValue('mail_from_address'); + } + + function testGetInstanceIdGeneratesValidId() { + \OC::$server->getConfig()->deleteSystemValue('instanceid'); + $instanceId = OC_Util::getInstanceId(); + $this->assertStringStartsWith('oc', $instanceId); + $matchesRegex = preg_match('/^[a-z0-9]+$/', $instanceId); + $this->assertSame(1, $matchesRegex); + } + + /** + * @dataProvider baseNameProvider + */ + public function testBaseName($expected, $file) { + $base = \OC_Util::basename($file); + $this->assertEquals($expected, $base); + } + + public function baseNameProvider() { + return array( + array('public_html', '/home/user/public_html/'), + array('public_html', '/home/user/public_html'), + array('', '/'), + array('public_html', 'public_html'), + array('442aa682de2a64db1e010f50e60fd9c9', 'local::C:\Users\ADMINI~1\AppData\Local\Temp\2/442aa682de2a64db1e010f50e60fd9c9/') + ); + } + + /** + * @dataProvider filenameValidationProvider + */ + public function testFilenameValidation($file, $valid) { + // private API + $this->assertEquals($valid, \OC_Util::isValidFileName($file)); + // public API + $this->assertEquals($valid, \OCP\Util::isValidFileName($file)); + } + + public function filenameValidationProvider() { + return array( + // valid names + array('boringname', true), + array('something.with.extension', true), + array('now with spaces', true), + array('.a', true), + array('..a', true), + array('.dotfile', true), + array('single\'quote', true), + array(' spaces before', true), + array('spaces after ', true), + array('allowed chars including the crazy ones $%&_-^@!,()[]{}=;#', true), + array('汉字也能用', true), + array('und Ümläüte sind auch willkommen', true), + // disallowed names + array('', false), + array(' ', false), + array('.', false), + array('..', false), + array('back\\slash', false), + array('sl/ash', false), + array('ltgt', true), + array('col:on', true), + array('double"quote', true), + array('pi|pe', true), + array('dont?ask?questions?', true), + array('super*star', true), + array('new\nline', false), + // better disallow these to avoid unexpected trimming to have side effects + array(' ..', false), + array('.. ', false), + array('. ', false), + array(' .', false), + ); + } + + /** + * @dataProvider dataProviderForTestIsSharingDisabledForUser + * @param array $groups existing groups + * @param array $membership groups the user belong to + * @param array $excludedGroups groups which should be excluded from sharing + * @param bool $expected expected result + */ + function testIsSharingDisabledForUser($groups, $membership, $excludedGroups, $expected) { + $config = $this->getMockBuilder('OCP\IConfig')->disableOriginalConstructor()->getMock(); + $groupManager = $this->getMockBuilder('OCP\IGroupManager')->disableOriginalConstructor()->getMock(); + $user = $this->getMockBuilder('OCP\IUser')->disableOriginalConstructor()->getMock(); + + $config + ->expects($this->at(0)) + ->method('getAppValue') + ->with('core', 'shareapi_exclude_groups', 'no') + ->will($this->returnValue('yes')); + $config + ->expects($this->at(1)) + ->method('getAppValue') + ->with('core', 'shareapi_exclude_groups_list') + ->will($this->returnValue(json_encode($excludedGroups))); + + $groupManager + ->expects($this->at(0)) + ->method('getUserGroupIds') + ->with($user) + ->will($this->returnValue($membership)); + + $result = \OC_Util::isSharingDisabledForUser($config, $groupManager, $user); + + $this->assertSame($expected, $result); + } + + public function dataProviderForTestIsSharingDisabledForUser() { + return array( + // existing groups, groups the user belong to, groups excluded from sharing, expected result + array(array('g1', 'g2', 'g3'), array(), array('g1'), false), + array(array('g1', 'g2', 'g3'), array(), array(), false), + array(array('g1', 'g2', 'g3'), array('g2'), array('g1'), false), + array(array('g1', 'g2', 'g3'), array('g2'), array(), false), + array(array('g1', 'g2', 'g3'), array('g1', 'g2'), array('g1'), false), + array(array('g1', 'g2', 'g3'), array('g1', 'g2'), array('g1', 'g2'), true), + array(array('g1', 'g2', 'g3'), array('g1', 'g2'), array('g1', 'g2', 'g3'), true), + ); + } + + /** + * Test default apps + * + * @dataProvider defaultAppsProvider + */ + function testDefaultApps($defaultAppConfig, $expectedPath, $enabledApps) { + $oldDefaultApps = \OCP\Config::getSystemValue('defaultapp', ''); + // CLI is doing messy stuff with the webroot, so need to work it around + $oldWebRoot = \OC::$WEBROOT; + \OC::$WEBROOT = ''; + + $appManager = $this->getMock('\OCP\App\IAppManager'); + $appManager->expects($this->any()) + ->method('isEnabledForUser') + ->will($this->returnCallback(function($appId) use ($enabledApps){ + return in_array($appId, $enabledApps); + })); + Dummy_OC_Util::$appManager = $appManager; + + // need to set a user id to make sure enabled apps are read from cache + \OC_User::setUserId($this->getUniqueID()); + \OCP\Config::setSystemValue('defaultapp', $defaultAppConfig); + $this->assertEquals('http://localhost/' . $expectedPath, Dummy_OC_Util::getDefaultPageUrl()); + + // restore old state + \OC::$WEBROOT = $oldWebRoot; + \OCP\Config::setSystemValue('defaultapp', $oldDefaultApps); + \OC_User::setUserId(null); + } + + function defaultAppsProvider() { + return array( + // none specified, default to files + array( + '', + 'index.php/apps/files/', + array('files'), + ), + // unexisting or inaccessible app specified, default to files + array( + 'unexist', + 'index.php/apps/files/', + array('files'), + ), + // non-standard app + array( + 'calendar', + 'index.php/apps/calendar/', + array('files', 'calendar'), + ), + // non-standard app with fallback + array( + 'contacts,calendar', + 'index.php/apps/calendar/', + array('files', 'calendar'), + ), + ); + } + + public function testGetDefaultPageUrlWithRedirectUrlWithoutFrontController() { + putenv('front_controller_active=false'); + + $_REQUEST['redirect_url'] = 'myRedirectUrl.com'; + $this->assertSame('http://localhost'.\OC::$WEBROOT.'/myRedirectUrl.com', OC_Util::getDefaultPageUrl()); + } + + public function testGetDefaultPageUrlWithRedirectUrlRedirectBypassWithoutFrontController() { + putenv('front_controller_active=false'); + + $_REQUEST['redirect_url'] = 'myRedirectUrl.com@foo.com:a'; + $this->assertSame('http://localhost'.\OC::$WEBROOT.'/index.php/apps/files/', OC_Util::getDefaultPageUrl()); + } + + public function testGetDefaultPageUrlWithRedirectUrlRedirectBypassWithFrontController() { + putenv('front_controller_active=true'); + $_REQUEST['redirect_url'] = 'myRedirectUrl.com@foo.com:a'; + $this->assertSame('http://localhost'.\OC::$WEBROOT.'/apps/files/', OC_Util::getDefaultPageUrl()); + } + + /** + * Test needUpgrade() when the core version is increased + */ + public function testNeedUpgradeCore() { + $config = \OC::$server->getConfig(); + $oldConfigVersion = $config->getSystemValue('version', '0.0.0'); + $oldSessionVersion = \OC::$server->getSession()->get('OC_Version'); + + $this->assertFalse(\OCP\Util::needUpgrade()); + + $config->setSystemValue('version', '7.0.0.0'); + \OC::$server->getSession()->set('OC_Version', array(7, 0, 0, 1)); + self::invokePrivate(new \OCP\Util, 'needUpgradeCache', array(null)); + + $this->assertTrue(\OCP\Util::needUpgrade()); + + $config->setSystemValue('version', $oldConfigVersion); + \OC::$server->getSession()->set('OC_Version', $oldSessionVersion); + self::invokePrivate(new \OCP\Util, 'needUpgradeCache', array(null)); + + $this->assertFalse(\OCP\Util::needUpgrade()); + } + + public function testCheckDataDirectoryValidity() { + $dataDir = \OCP\Files::tmpFolder(); + touch($dataDir . '/.ocdata'); + $errors = \OC_Util::checkDataDirectoryValidity($dataDir); + $this->assertEmpty($errors); + \OCP\Files::rmdirr($dataDir); + + $dataDir = \OCP\Files::tmpFolder(); + // no touch + $errors = \OC_Util::checkDataDirectoryValidity($dataDir); + $this->assertNotEmpty($errors); + \OCP\Files::rmdirr($dataDir); + + if (!\OC_Util::runningOnWindows()) { + $errors = \OC_Util::checkDataDirectoryValidity('relative/path'); + $this->assertNotEmpty($errors); + } + } + + protected function setUp() { + parent::setUp(); + + \OC_Util::$scripts = []; + \OC_Util::$styles = []; + } + protected function tearDown() { + parent::tearDown(); + + \OC_Util::$scripts = []; + \OC_Util::$styles = []; + } + + public function testAddScript() { + \OC_Util::addScript('core', 'myFancyJSFile1'); + \OC_Util::addScript('myApp', 'myFancyJSFile2'); + \OC_Util::addScript('core', 'myFancyJSFile0', true); + \OC_Util::addScript('core', 'myFancyJSFile10', true); + // add duplicate + \OC_Util::addScript('core', 'myFancyJSFile1'); + + $this->assertEquals([ + 'core/js/myFancyJSFile10', + 'core/js/myFancyJSFile0', + 'core/js/myFancyJSFile1', + 'myApp/l10n/en', + 'myApp/js/myFancyJSFile2', + ], \OC_Util::$scripts); + $this->assertEquals([], \OC_Util::$styles); + } + + public function testAddVendorScript() { + \OC_Util::addVendorScript('core', 'myFancyJSFile1'); + \OC_Util::addVendorScript('myApp', 'myFancyJSFile2'); + \OC_Util::addVendorScript('core', 'myFancyJSFile0', true); + \OC_Util::addVendorScript('core', 'myFancyJSFile10', true); + // add duplicate + \OC_Util::addVendorScript('core', 'myFancyJSFile1'); + + $this->assertEquals([ + 'core/vendor/myFancyJSFile10', + 'core/vendor/myFancyJSFile0', + 'core/vendor/myFancyJSFile1', + 'myApp/vendor/myFancyJSFile2', + ], \OC_Util::$scripts); + $this->assertEquals([], \OC_Util::$styles); + } + + public function testAddTranslations() { + \OC_Util::addTranslations('appId', 'de'); + + $this->assertEquals([ + 'appId/l10n/de' + ], \OC_Util::$scripts); + $this->assertEquals([], \OC_Util::$styles); + } + + public function testAddStyle() { + \OC_Util::addStyle('core', 'myFancyCSSFile1'); + \OC_Util::addStyle('myApp', 'myFancyCSSFile2'); + \OC_Util::addStyle('core', 'myFancyCSSFile0', true); + \OC_Util::addStyle('core', 'myFancyCSSFile10', true); + // add duplicate + \OC_Util::addStyle('core', 'myFancyCSSFile1'); + + $this->assertEquals([], \OC_Util::$scripts); + $this->assertEquals([ + 'core/css/myFancyCSSFile10', + 'core/css/myFancyCSSFile0', + 'core/css/myFancyCSSFile1', + 'myApp/css/myFancyCSSFile2', + ], \OC_Util::$styles); + } + + public function testAddVendorStyle() { + \OC_Util::addVendorStyle('core', 'myFancyCSSFile1'); + \OC_Util::addVendorStyle('myApp', 'myFancyCSSFile2'); + \OC_Util::addVendorStyle('core', 'myFancyCSSFile0', true); + \OC_Util::addVendorStyle('core', 'myFancyCSSFile10', true); + // add duplicate + \OC_Util::addVendorStyle('core', 'myFancyCSSFile1'); + + $this->assertEquals([], \OC_Util::$scripts); + $this->assertEquals([ + 'core/vendor/myFancyCSSFile10', + 'core/vendor/myFancyCSSFile0', + 'core/vendor/myFancyCSSFile1', + 'myApp/vendor/myFancyCSSFile2', + ], \OC_Util::$styles); + } +} + +/** + * Dummy OC Util class to make it possible to override the app manager + */ +class Dummy_OC_Util extends OC_Util { + /** + * @var \OCP\App\IAppManager + */ + public static $appManager; + + protected static function getAppManager() { + return self::$appManager; + } +} diff --git a/tests/lib/group.php b/tests/lib/group.php deleted file mode 100644 index d3ac6d8d69e..00000000000 --- a/tests/lib/group.php +++ /dev/null @@ -1,197 +0,0 @@ - - * @copyright 2012 Bernhard Posselt - * - * 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 . - * - */ - -class Test_Group extends \Test\TestCase { - protected function setUp() { - parent::setUp(); - OC_Group::clearBackends(); - OC_User::clearBackends(); - } - - public function testSingleBackend() { - $userBackend = new \Test\Util\User\Dummy(); - \OC::$server->getUserManager()->registerBackend($userBackend); - OC_Group::useBackend(new \Test\Util\Group\Dummy()); - - $group1 = $this->getUniqueID(); - $group2 = $this->getUniqueID(); - OC_Group::createGroup($group1); - OC_Group::createGroup($group2); - - $user1 = $this->getUniqueID(); - $user2 = $this->getUniqueID(); - $userBackend->createUser($user1, ''); - $userBackend->createUser($user2, ''); - - $this->assertFalse(OC_Group::inGroup($user1, $group1), 'Asserting that user1 is not in group1'); - $this->assertFalse(OC_Group::inGroup($user2, $group1), 'Asserting that user2 is not in group1'); - $this->assertFalse(OC_Group::inGroup($user1, $group2), 'Asserting that user1 is not in group2'); - $this->assertFalse(OC_Group::inGroup($user2, $group2), 'Asserting that user2 is not in group2'); - - $this->assertTrue(OC_Group::addToGroup($user1, $group1)); - - $this->assertTrue(OC_Group::inGroup($user1, $group1), 'Asserting that user1 is in group1'); - $this->assertFalse(OC_Group::inGroup($user2, $group1), 'Asserting that user2 is not in group1'); - $this->assertFalse(OC_Group::inGroup($user1, $group2), 'Asserting that user1 is not in group2'); - $this->assertFalse(OC_Group::inGroup($user2, $group2), 'Asserting that user2 is not in group2'); - - $this->assertTrue(OC_Group::addToGroup($user1, $group1)); - - $this->assertEquals(array($user1), OC_Group::usersInGroup($group1)); - $this->assertEquals(array(), OC_Group::usersInGroup($group2)); - - $this->assertEquals(array($group1), OC_Group::getUserGroups($user1)); - $this->assertEquals(array(), OC_Group::getUserGroups($user2)); - - OC_Group::deleteGroup($group1); - $this->assertEquals(array(), OC_Group::getUserGroups($user1)); - $this->assertEquals(array(), OC_Group::usersInGroup($group1)); - $this->assertFalse(OC_Group::inGroup($user1, $group1)); - } - - - public function testNoEmptyGIDs() { - OC_Group::useBackend(new \Test\Util\Group\Dummy()); - $emptyGroup = null; - - $this->assertFalse(OC_Group::createGroup($emptyGroup)); - } - - - public function testNoGroupsTwice() { - OC_Group::useBackend(new \Test\Util\Group\Dummy()); - $group = $this->getUniqueID(); - OC_Group::createGroup($group); - - $groupCopy = $group; - - OC_Group::createGroup($groupCopy); - $this->assertEquals(array($group), OC_Group::getGroups()); - } - - - public function testDontDeleteAdminGroup() { - OC_Group::useBackend(new \Test\Util\Group\Dummy()); - $adminGroup = 'admin'; - OC_Group::createGroup($adminGroup); - - $this->assertFalse(OC_Group::deleteGroup($adminGroup)); - $this->assertEquals(array($adminGroup), OC_Group::getGroups()); - } - - - public function testDontAddUserToNonexistentGroup() { - OC_Group::useBackend(new \Test\Util\Group\Dummy()); - $groupNonExistent = 'notExistent'; - $user = $this->getUniqueID(); - - $this->assertEquals(false, OC_Group::addToGroup($user, $groupNonExistent)); - $this->assertEquals(array(), OC_Group::getGroups()); - } - - public function testUsersInGroup() { - OC_Group::useBackend(new \Test\Util\Group\Dummy()); - $userBackend = new \Test\Util\User\Dummy(); - \OC::$server->getUserManager()->registerBackend($userBackend); - - $group1 = $this->getUniqueID(); - $group2 = $this->getUniqueID(); - $group3 = $this->getUniqueID(); - $user1 = $this->getUniqueID(); - $user2 = $this->getUniqueID(); - $user3 = $this->getUniqueID(); - OC_Group::createGroup($group1); - OC_Group::createGroup($group2); - OC_Group::createGroup($group3); - - $userBackend->createUser($user1, ''); - $userBackend->createUser($user2, ''); - $userBackend->createUser($user3, ''); - - OC_Group::addToGroup($user1, $group1); - OC_Group::addToGroup($user2, $group1); - OC_Group::addToGroup($user3, $group1); - OC_Group::addToGroup($user3, $group2); - - $this->assertEquals(array($user1, $user2, $user3), - OC_Group::usersInGroups(array($group1, $group2, $group3))); - - // FIXME: needs more parameter variation - } - - public function testMultiBackend() { - $userBackend = new \Test\Util\User\Dummy(); - \OC::$server->getUserManager()->registerBackend($userBackend); - $backend1 = new \Test\Util\Group\Dummy(); - $backend2 = new \Test\Util\Group\Dummy(); - OC_Group::useBackend($backend1); - OC_Group::useBackend($backend2); - - $group1 = $this->getUniqueID(); - $group2 = $this->getUniqueID(); - OC_Group::createGroup($group1); - - //groups should be added to the first registered backend - $this->assertEquals(array($group1), $backend1->getGroups()); - $this->assertEquals(array(), $backend2->getGroups()); - - $this->assertEquals(array($group1), OC_Group::getGroups()); - $this->assertTrue(OC_Group::groupExists($group1)); - $this->assertFalse(OC_Group::groupExists($group2)); - - $backend1->createGroup($group2); - - $this->assertEquals(array($group1, $group2), OC_Group::getGroups()); - $this->assertTrue(OC_Group::groupExists($group1)); - $this->assertTrue(OC_Group::groupExists($group2)); - - $user1 = $this->getUniqueID(); - $user2 = $this->getUniqueID(); - - $userBackend->createUser($user1, ''); - $userBackend->createUser($user2, ''); - - $this->assertFalse(OC_Group::inGroup($user1, $group1)); - $this->assertFalse(OC_Group::inGroup($user2, $group1)); - - - $this->assertTrue(OC_Group::addToGroup($user1, $group1)); - - $this->assertTrue(OC_Group::inGroup($user1, $group1)); - $this->assertFalse(OC_Group::inGroup($user2, $group1)); - $this->assertFalse($backend2->inGroup($user1, $group1)); - - OC_Group::addToGroup($user1, $group1); - - $this->assertEquals(array($user1), OC_Group::usersInGroup($group1)); - - $this->assertEquals(array($group1), OC_Group::getUserGroups($user1)); - $this->assertEquals(array(), OC_Group::getUserGroups($user2)); - - OC_Group::deleteGroup($group1); - $this->assertEquals(array(), OC_Group::getUserGroups($user1)); - $this->assertEquals(array(), OC_Group::usersInGroup($group1)); - $this->assertFalse(OC_Group::inGroup($user1, $group1)); - } -} diff --git a/tests/lib/group/LegacyGroupTest.php b/tests/lib/group/LegacyGroupTest.php new file mode 100644 index 00000000000..12bcfdddf15 --- /dev/null +++ b/tests/lib/group/LegacyGroupTest.php @@ -0,0 +1,202 @@ + + * @copyright 2012 Bernhard Posselt + * + * 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 . + * + */ + +namespace Test\Group; + +use OC_Group; +use OC_User; + +class LegacyGroupTest extends \Test\TestCase { + protected function setUp() { + parent::setUp(); + OC_Group::clearBackends(); + OC_User::clearBackends(); + } + + public function testSingleBackend() { + $userBackend = new \Test\Util\User\Dummy(); + \OC::$server->getUserManager()->registerBackend($userBackend); + OC_Group::useBackend(new \Test\Util\Group\Dummy()); + + $group1 = $this->getUniqueID(); + $group2 = $this->getUniqueID(); + OC_Group::createGroup($group1); + OC_Group::createGroup($group2); + + $user1 = $this->getUniqueID(); + $user2 = $this->getUniqueID(); + $userBackend->createUser($user1, ''); + $userBackend->createUser($user2, ''); + + $this->assertFalse(OC_Group::inGroup($user1, $group1), 'Asserting that user1 is not in group1'); + $this->assertFalse(OC_Group::inGroup($user2, $group1), 'Asserting that user2 is not in group1'); + $this->assertFalse(OC_Group::inGroup($user1, $group2), 'Asserting that user1 is not in group2'); + $this->assertFalse(OC_Group::inGroup($user2, $group2), 'Asserting that user2 is not in group2'); + + $this->assertTrue(OC_Group::addToGroup($user1, $group1)); + + $this->assertTrue(OC_Group::inGroup($user1, $group1), 'Asserting that user1 is in group1'); + $this->assertFalse(OC_Group::inGroup($user2, $group1), 'Asserting that user2 is not in group1'); + $this->assertFalse(OC_Group::inGroup($user1, $group2), 'Asserting that user1 is not in group2'); + $this->assertFalse(OC_Group::inGroup($user2, $group2), 'Asserting that user2 is not in group2'); + + $this->assertTrue(OC_Group::addToGroup($user1, $group1)); + + $this->assertEquals(array($user1), OC_Group::usersInGroup($group1)); + $this->assertEquals(array(), OC_Group::usersInGroup($group2)); + + $this->assertEquals(array($group1), OC_Group::getUserGroups($user1)); + $this->assertEquals(array(), OC_Group::getUserGroups($user2)); + + OC_Group::deleteGroup($group1); + $this->assertEquals(array(), OC_Group::getUserGroups($user1)); + $this->assertEquals(array(), OC_Group::usersInGroup($group1)); + $this->assertFalse(OC_Group::inGroup($user1, $group1)); + } + + + public function testNoEmptyGIDs() { + OC_Group::useBackend(new \Test\Util\Group\Dummy()); + $emptyGroup = null; + + $this->assertFalse(OC_Group::createGroup($emptyGroup)); + } + + + public function testNoGroupsTwice() { + OC_Group::useBackend(new \Test\Util\Group\Dummy()); + $group = $this->getUniqueID(); + OC_Group::createGroup($group); + + $groupCopy = $group; + + OC_Group::createGroup($groupCopy); + $this->assertEquals(array($group), OC_Group::getGroups()); + } + + + public function testDontDeleteAdminGroup() { + OC_Group::useBackend(new \Test\Util\Group\Dummy()); + $adminGroup = 'admin'; + OC_Group::createGroup($adminGroup); + + $this->assertFalse(OC_Group::deleteGroup($adminGroup)); + $this->assertEquals(array($adminGroup), OC_Group::getGroups()); + } + + + public function testDontAddUserToNonexistentGroup() { + OC_Group::useBackend(new \Test\Util\Group\Dummy()); + $groupNonExistent = 'notExistent'; + $user = $this->getUniqueID(); + + $this->assertEquals(false, OC_Group::addToGroup($user, $groupNonExistent)); + $this->assertEquals(array(), OC_Group::getGroups()); + } + + public function testUsersInGroup() { + OC_Group::useBackend(new \Test\Util\Group\Dummy()); + $userBackend = new \Test\Util\User\Dummy(); + \OC::$server->getUserManager()->registerBackend($userBackend); + + $group1 = $this->getUniqueID(); + $group2 = $this->getUniqueID(); + $group3 = $this->getUniqueID(); + $user1 = $this->getUniqueID(); + $user2 = $this->getUniqueID(); + $user3 = $this->getUniqueID(); + OC_Group::createGroup($group1); + OC_Group::createGroup($group2); + OC_Group::createGroup($group3); + + $userBackend->createUser($user1, ''); + $userBackend->createUser($user2, ''); + $userBackend->createUser($user3, ''); + + OC_Group::addToGroup($user1, $group1); + OC_Group::addToGroup($user2, $group1); + OC_Group::addToGroup($user3, $group1); + OC_Group::addToGroup($user3, $group2); + + $this->assertEquals(array($user1, $user2, $user3), + OC_Group::usersInGroups(array($group1, $group2, $group3))); + + // FIXME: needs more parameter variation + } + + public function testMultiBackend() { + $userBackend = new \Test\Util\User\Dummy(); + \OC::$server->getUserManager()->registerBackend($userBackend); + $backend1 = new \Test\Util\Group\Dummy(); + $backend2 = new \Test\Util\Group\Dummy(); + OC_Group::useBackend($backend1); + OC_Group::useBackend($backend2); + + $group1 = $this->getUniqueID(); + $group2 = $this->getUniqueID(); + OC_Group::createGroup($group1); + + //groups should be added to the first registered backend + $this->assertEquals(array($group1), $backend1->getGroups()); + $this->assertEquals(array(), $backend2->getGroups()); + + $this->assertEquals(array($group1), OC_Group::getGroups()); + $this->assertTrue(OC_Group::groupExists($group1)); + $this->assertFalse(OC_Group::groupExists($group2)); + + $backend1->createGroup($group2); + + $this->assertEquals(array($group1, $group2), OC_Group::getGroups()); + $this->assertTrue(OC_Group::groupExists($group1)); + $this->assertTrue(OC_Group::groupExists($group2)); + + $user1 = $this->getUniqueID(); + $user2 = $this->getUniqueID(); + + $userBackend->createUser($user1, ''); + $userBackend->createUser($user2, ''); + + $this->assertFalse(OC_Group::inGroup($user1, $group1)); + $this->assertFalse(OC_Group::inGroup($user2, $group1)); + + + $this->assertTrue(OC_Group::addToGroup($user1, $group1)); + + $this->assertTrue(OC_Group::inGroup($user1, $group1)); + $this->assertFalse(OC_Group::inGroup($user2, $group1)); + $this->assertFalse($backend2->inGroup($user1, $group1)); + + OC_Group::addToGroup($user1, $group1); + + $this->assertEquals(array($user1), OC_Group::usersInGroup($group1)); + + $this->assertEquals(array($group1), OC_Group::getUserGroups($user1)); + $this->assertEquals(array(), OC_Group::getUserGroups($user2)); + + OC_Group::deleteGroup($group1); + $this->assertEquals(array(), OC_Group::getUserGroups($user1)); + $this->assertEquals(array(), OC_Group::usersInGroup($group1)); + $this->assertFalse(OC_Group::inGroup($user1, $group1)); + } +} diff --git a/tests/lib/helper.php b/tests/lib/helper.php deleted file mode 100644 index 89a981e6e23..00000000000 --- a/tests/lib/helper.php +++ /dev/null @@ -1,297 +0,0 @@ - - * This file is licensed under the Affero General Public License version 3 or - * later. - * See the COPYING-README file. - */ - -class Test_Helper extends \Test\TestCase { - - /** - * @dataProvider humanFileSizeProvider - */ - public function testHumanFileSize($expected, $input) - { - $result = OC_Helper::humanFileSize($input); - $this->assertEquals($expected, $result); - } - - public function humanFileSizeProvider() - { - return array( - array('0 B', 0), - array('1 KB', 1024), - array('9.5 MB', 10000000), - array('1.3 GB', 1395864371), - array('465.7 GB', 500000000000), - array('454.7 TB', 500000000000000), - array('444.1 PB', 500000000000000000), - ); - } - - /** - * @dataProvider phpFileSizeProvider - */ - public function testPhpFileSize($expected, $input) - { - $result = OC_Helper::phpFileSize($input); - $this->assertEquals($expected, $result); - } - - public function phpFileSizeProvider() - { - return array( - array('0B', 0), - array('1K', 1024), - array('9.5M', 10000000), - array('1.3G', 1395864371), - array('465.7G', 500000000000), - array('465661.3G', 500000000000000), - array('465661287.3G', 500000000000000000), - ); - } - - /** - * @dataProvider providesComputerFileSize - */ - function testComputerFileSize($expected, $input) { - $result = OC_Helper::computerFileSize($input); - $this->assertEquals($expected, $result); - } - - function providesComputerFileSize(){ - return [ - [0.0, "0 B"], - [1024.0, "1 KB"], - [1395864371.0, '1.3 GB'], - [9961472.0, "9.5 MB"], - [500041567437.0, "465.7 GB"], - [false, "12 GB etfrhzui"] - ]; - } - - function testIsSubDirectory() { - $result = OC_Helper::isSubDirectory("./data/", "/anotherDirectory/"); - $this->assertFalse($result); - - $result = OC_Helper::isSubDirectory("./data/", "./data/"); - $this->assertTrue($result); - - mkdir("data/TestSubdirectory", 0777); - $result = OC_Helper::isSubDirectory("data/TestSubdirectory/", "data"); - rmdir("data/TestSubdirectory"); - $this->assertTrue($result); - } - - function testMb_array_change_key_case() { - $arrayStart = array( - "Foo" => "bar", - "Bar" => "foo", - ); - $arrayResult = array( - "foo" => "bar", - "bar" => "foo", - ); - $result = OC_Helper::mb_array_change_key_case($arrayStart); - $expected = $arrayResult; - $this->assertEquals($result, $expected); - - $arrayStart = array( - "foo" => "bar", - "bar" => "foo", - ); - $arrayResult = array( - "FOO" => "bar", - "BAR" => "foo", - ); - $result = OC_Helper::mb_array_change_key_case($arrayStart, MB_CASE_UPPER); - $expected = $arrayResult; - $this->assertEquals($result, $expected); - } - - function testRecursiveArraySearch() { - $haystack = array( - "Foo" => "own", - "Bar" => "Cloud", - ); - - $result = OC_Helper::recursiveArraySearch($haystack, "own"); - $expected = "Foo"; - $this->assertEquals($result, $expected); - - $result = OC_Helper::recursiveArraySearch($haystack, "NotFound"); - $this->assertFalse($result); - } - - function testBuildNotExistingFileNameForView() { - $viewMock = $this->getMock('\OC\Files\View', array(), array(), '', false); - $this->assertEquals('/filename', OC_Helper::buildNotExistingFileNameForView('/', 'filename', $viewMock)); - $this->assertEquals('dir/filename.ext', OC_Helper::buildNotExistingFileNameForView('dir', 'filename.ext', $viewMock)); - - $viewMock->expects($this->at(0)) - ->method('file_exists') - ->will($this->returnValue(true)); // filename.ext exists - $this->assertEquals('dir/filename (2).ext', OC_Helper::buildNotExistingFileNameForView('dir', 'filename.ext', $viewMock)); - - $viewMock->expects($this->at(0)) - ->method('file_exists') - ->will($this->returnValue(true)); // filename.ext exists - $viewMock->expects($this->at(1)) - ->method('file_exists') - ->will($this->returnValue(true)); // filename (2).ext exists - $this->assertEquals('dir/filename (3).ext', OC_Helper::buildNotExistingFileNameForView('dir', 'filename.ext', $viewMock)); - - $viewMock->expects($this->at(0)) - ->method('file_exists') - ->will($this->returnValue(true)); // filename (1).ext exists - $this->assertEquals('dir/filename (2).ext', OC_Helper::buildNotExistingFileNameForView('dir', 'filename (1).ext', $viewMock)); - - $viewMock->expects($this->at(0)) - ->method('file_exists') - ->will($this->returnValue(true)); // filename (2).ext exists - $this->assertEquals('dir/filename (3).ext', OC_Helper::buildNotExistingFileNameForView('dir', 'filename (2).ext', $viewMock)); - - $viewMock->expects($this->at(0)) - ->method('file_exists') - ->will($this->returnValue(true)); // filename (2).ext exists - $viewMock->expects($this->at(1)) - ->method('file_exists') - ->will($this->returnValue(true)); // filename (3).ext exists - $this->assertEquals('dir/filename (4).ext', OC_Helper::buildNotExistingFileNameForView('dir', 'filename (2).ext', $viewMock)); - - $viewMock->expects($this->at(0)) - ->method('file_exists') - ->will($this->returnValue(true)); // filename(1).ext exists - $this->assertEquals('dir/filename(2).ext', OC_Helper::buildNotExistingFileNameForView('dir', 'filename(1).ext', $viewMock)); - - $viewMock->expects($this->at(0)) - ->method('file_exists') - ->will($this->returnValue(true)); // filename(1) (1).ext exists - $this->assertEquals('dir/filename(1) (2).ext', OC_Helper::buildNotExistingFileNameForView('dir', 'filename(1) (1).ext', $viewMock)); - - $viewMock->expects($this->at(0)) - ->method('file_exists') - ->will($this->returnValue(true)); // filename(1) (1).ext exists - $viewMock->expects($this->at(1)) - ->method('file_exists') - ->will($this->returnValue(true)); // filename(1) (2).ext exists - $this->assertEquals('dir/filename(1) (3).ext', OC_Helper::buildNotExistingFileNameForView('dir', 'filename(1) (1).ext', $viewMock)); - - $viewMock->expects($this->at(0)) - ->method('file_exists') - ->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'), - ); - } - - // Url generator methods - - /** - * @small - * test linkToPublic URL construction - */ - public function testLinkToPublic() { - \OC::$WEBROOT = ''; - $result = \OC_Helper::linkToPublic('files'); - $this->assertEquals('http://localhost/s', $result); - $result = \OC_Helper::linkToPublic('files', false); - $this->assertEquals('http://localhost/s', $result); - $result = \OC_Helper::linkToPublic('files', true); - $this->assertEquals('http://localhost/s/', $result); - - $result = \OC_Helper::linkToPublic('other'); - $this->assertEquals('http://localhost/public.php?service=other', $result); - $result = \OC_Helper::linkToPublic('other', false); - $this->assertEquals('http://localhost/public.php?service=other', $result); - $result = \OC_Helper::linkToPublic('other', true); - $this->assertEquals('http://localhost/public.php?service=other/', $result); - - \OC::$WEBROOT = '/owncloud'; - $result = \OC_Helper::linkToPublic('files'); - $this->assertEquals('http://localhost/owncloud/s', $result); - $result = \OC_Helper::linkToPublic('files', false); - $this->assertEquals('http://localhost/owncloud/s', $result); - $result = \OC_Helper::linkToPublic('files', true); - $this->assertEquals('http://localhost/owncloud/s/', $result); - - $result = \OC_Helper::linkToPublic('other'); - $this->assertEquals('http://localhost/owncloud/public.php?service=other', $result); - $result = \OC_Helper::linkToPublic('other', false); - $this->assertEquals('http://localhost/owncloud/public.php?service=other', $result); - $result = \OC_Helper::linkToPublic('other', true); - $this->assertEquals('http://localhost/owncloud/public.php?service=other/', $result); - } - - /** - * Tests recursive folder deletion with rmdirr() - */ - public function testRecursiveFolderDeletion() { - $baseDir = \OC::$server->getTempManager()->getTemporaryFolder() . '/'; - mkdir($baseDir . 'a/b/c/d/e', 0777, true); - mkdir($baseDir . 'a/b/c1/d/e', 0777, true); - mkdir($baseDir . 'a/b/c2/d/e', 0777, true); - mkdir($baseDir . 'a/b1/c1/d/e', 0777, true); - mkdir($baseDir . 'a/b2/c1/d/e', 0777, true); - mkdir($baseDir . 'a/b3/c1/d/e', 0777, true); - mkdir($baseDir . 'a1/b', 0777, true); - mkdir($baseDir . 'a1/c', 0777, true); - file_put_contents($baseDir . 'a/test.txt', 'Hello file!'); - file_put_contents($baseDir . 'a/b1/c1/test one.txt', 'Hello file one!'); - file_put_contents($baseDir . 'a1/b/test two.txt', 'Hello file two!'); - \OC_Helper::rmdirr($baseDir . 'a'); - - $this->assertFalse(file_exists($baseDir . 'a')); - $this->assertTrue(file_exists($baseDir . 'a1')); - - \OC_Helper::rmdirr($baseDir); - $this->assertFalse(file_exists($baseDir)); - } - - /** - * Allows us to test private methods/properties - * - * @param $object - * @param $methodName - * @param array $parameters - * @return mixed - * @deprecated Please extend \Test\TestCase and use self::invokePrivate() then - */ - public static function invokePrivate($object, $methodName, array $parameters = array()) { - return parent::invokePrivate($object, $methodName, $parameters); - } -} diff --git a/tests/lib/helperstorage.php b/tests/lib/helperstorage.php deleted file mode 100644 index 3109b509549..00000000000 --- a/tests/lib/helperstorage.php +++ /dev/null @@ -1,230 +0,0 @@ - - * This file is licensed under the Affero General Public License version 3 or - * later. - * See the COPYING-README file. - */ - -/** - * Test the storage functions of OC_Helper - * - * @group DB - */ -class Test_Helper_Storage extends \Test\TestCase { - /** @var string */ - private $user; - /** @var \OC\Files\Storage\Storage */ - private $storageMock; - /** @var \OC\Files\Storage\Storage */ - private $storage; - - protected function setUp() { - parent::setUp(); - - $this->user = $this->getUniqueID('user_'); - \OC::$server->getUserManager()->createUser($this->user, $this->user); - - $this->storage = \OC\Files\Filesystem::getStorage('/'); - \OC\Files\Filesystem::tearDown(); - \OC_User::setUserId($this->user); - \OC\Files\Filesystem::init($this->user, '/' . $this->user . '/files'); - \OC\Files\Filesystem::clearMounts(); - - $this->storageMock = null; - } - - protected function tearDown() { - $this->user = null; - - if ($this->storageMock) { - $this->storageMock->getCache()->clear(); - $this->storageMock = null; - } - \OC\Files\Filesystem::tearDown(); - \OC\Files\Filesystem::mount($this->storage, array(), '/'); - - \OC_User::setUserId(''); - $user = \OC::$server->getUserManager()->get($this->user); - if ($user !== null) { $user->delete(); } - \OC::$server->getConfig()->deleteAllUserValues($this->user); - - parent::tearDown(); - } - - /** - * Returns a storage mock that returns the given value as - * free space - * - * @param int $freeSpace free space value - * @return \OC\Files\Storage\Storage - */ - private function getStorageMock($freeSpace = 12) { - $this->storageMock = $this->getMock( - '\OC\Files\Storage\Temporary', - array('free_space'), - array('') - ); - - - $this->storageMock->expects($this->once()) - ->method('free_space') - ->will($this->returnValue(12)); - return $this->storageMock; - } - - /** - * Test getting the storage info - */ - function testGetStorageInfo() { - $homeStorage = $this->getStorageMock(12); - \OC\Files\Filesystem::mount($homeStorage, array(), '/' . $this->user . '/files'); - $homeStorage->file_put_contents('test.txt', '01234'); - - $storageInfo = \OC_Helper::getStorageInfo(''); - $this->assertEquals(12, $storageInfo['free']); - $this->assertEquals(5, $storageInfo['used']); - $this->assertEquals(17, $storageInfo['total']); - } - - /** - * Test getting the storage info, ignoring extra mount points - */ - function testGetStorageInfoExcludingExtStorage() { - $homeStorage = $this->getStorageMock(12); - \OC\Files\Filesystem::mount($homeStorage, array(), '/' . $this->user . '/files'); - $homeStorage->file_put_contents('test.txt', '01234'); - - $extStorage = new \OC\Files\Storage\Temporary(array()); - $extStorage->file_put_contents('extfile.txt', 'abcdefghijklmnopq'); - $extStorage->getScanner()->scan(''); // update root size - - \OC\Files\Filesystem::mount($extStorage, array(), '/' . $this->user . '/files/ext'); - - $storageInfo = \OC_Helper::getStorageInfo(''); - $this->assertEquals(12, $storageInfo['free']); - $this->assertEquals(5, $storageInfo['used']); - $this->assertEquals(17, $storageInfo['total']); - } - - /** - * Test getting the storage info, including extra mount points - */ - function testGetStorageInfoIncludingExtStorage() { - $homeStorage = new \OC\Files\Storage\Temporary(array()); - \OC\Files\Filesystem::mount($homeStorage, array(), '/' . $this->user . '/files'); - $homeStorage->file_put_contents('test.txt', '01234'); - - $extStorage = new \OC\Files\Storage\Temporary(array()); - $extStorage->file_put_contents('extfile.txt', 'abcdefghijklmnopq'); - $extStorage->getScanner()->scan(''); // update root size - - \OC\Files\Filesystem::mount($extStorage, array(), '/' . $this->user . '/files/ext'); - - $config = \OC::$server->getConfig(); - $oldConfig = $config->getSystemValue('quota_include_external_storage', false); - $config->setSystemValue('quota_include_external_storage', 'true'); - - $config->setUserValue($this->user, 'files', 'quota', '25'); - - $storageInfo = \OC_Helper::getStorageInfo(''); - $this->assertEquals(3, $storageInfo['free']); - $this->assertEquals(22, $storageInfo['used']); - $this->assertEquals(25, $storageInfo['total']); - - $config->setSystemValue('quota_include_external_storage', $oldConfig); - $config->setUserValue($this->user, 'files', 'quota', 'default'); - } - - /** - * Test getting the storage info excluding extra mount points - * when user has no quota set, even when quota ext storage option - * was set - */ - function testGetStorageInfoIncludingExtStorageWithNoUserQuota() { - $homeStorage = $this->getStorageMock(12); - \OC\Files\Filesystem::mount($homeStorage, array(), '/' . $this->user . '/files'); - $homeStorage->file_put_contents('test.txt', '01234'); - - $extStorage = new \OC\Files\Storage\Temporary(array()); - $extStorage->file_put_contents('extfile.txt', 'abcdefghijklmnopq'); - $extStorage->getScanner()->scan(''); // update root size - - \OC\Files\Filesystem::mount($extStorage, array(), '/' . $this->user . '/files/ext'); - - $config = \OC::$server->getConfig(); - $oldConfig = $config->getSystemValue('quota_include_external_storage', false); - $config->setSystemValue('quota_include_external_storage', 'true'); - - $storageInfo = \OC_Helper::getStorageInfo(''); - $this->assertEquals(12, $storageInfo['free']); - $this->assertEquals(5, $storageInfo['used']); - $this->assertEquals(17, $storageInfo['total']); - - $config->setSystemValue('quota_include_external_storage', $oldConfig); - } - - - /** - * Test getting the storage info with quota enabled - */ - function testGetStorageInfoWithQuota() { - $homeStorage = $this->getStorageMock(12); - $homeStorage->file_put_contents('test.txt', '01234'); - $homeStorage = new \OC\Files\Storage\Wrapper\Quota( - array( - 'storage' => $homeStorage, - 'quota' => 7 - ) - ); - \OC\Files\Filesystem::mount($homeStorage, array(), '/' . $this->user . '/files'); - - $storageInfo = \OC_Helper::getStorageInfo(''); - $this->assertEquals(2, $storageInfo['free']); - $this->assertEquals(5, $storageInfo['used']); - $this->assertEquals(7, $storageInfo['total']); - } - - /** - * Test getting the storage info when data exceeds quota - */ - function testGetStorageInfoWhenSizeExceedsQuota() { - $homeStorage = $this->getStorageMock(12); - $homeStorage->file_put_contents('test.txt', '0123456789'); - $homeStorage = new \OC\Files\Storage\Wrapper\Quota( - array( - 'storage' => $homeStorage, - 'quota' => 7 - ) - ); - \OC\Files\Filesystem::mount($homeStorage, array(), '/' . $this->user . '/files'); - - $storageInfo = \OC_Helper::getStorageInfo(''); - $this->assertEquals(0, $storageInfo['free']); - $this->assertEquals(10, $storageInfo['used']); - // total = quota - $this->assertEquals(7, $storageInfo['total']); - } - - /** - * Test getting the storage info when the remaining - * free storage space is less than the quota - */ - function testGetStorageInfoWhenFreeSpaceLessThanQuota() { - $homeStorage = $this->getStorageMock(12); - $homeStorage->file_put_contents('test.txt', '01234'); - $homeStorage = new \OC\Files\Storage\Wrapper\Quota( - array( - 'storage' => $homeStorage, - 'quota' => 18 - ) - ); - \OC\Files\Filesystem::mount($homeStorage, array(), '/' . $this->user . '/files'); - - $storageInfo = \OC_Helper::getStorageInfo(''); - $this->assertEquals(12, $storageInfo['free']); - $this->assertEquals(5, $storageInfo['used']); - // total = free + used (because quota > total) - $this->assertEquals(17, $storageInfo['total']); - } -} diff --git a/tests/lib/httphelper.php b/tests/lib/httphelper.php deleted file mode 100644 index 1d0981ba51b..00000000000 --- a/tests/lib/httphelper.php +++ /dev/null @@ -1,118 +0,0 @@ - - * This file is licensed under the Affero General Public License version 3 or - * later. - * See the COPYING-README file. - */ - -class TestHTTPHelper extends \Test\TestCase { - - /** @var \OCP\IConfig*/ - private $config; - /** @var \OC\HTTPHelper */ - private $httpHelperMock; - /** @var \OCP\Http\Client\IClientService */ - private $clientService; - - protected function setUp() { - parent::setUp(); - - $this->config = $this->getMockBuilder('\OCP\IConfig') - ->disableOriginalConstructor()->getMock(); - $this->clientService = $this->getMock('\OCP\Http\Client\IClientService'); - $this->httpHelperMock = $this->getMockBuilder('\OC\HTTPHelper') - ->setConstructorArgs(array($this->config, $this->clientService)) - ->setMethods(array('getHeaders')) - ->getMock(); - } - - public function isHttpTestData() { - return array( - array('http://wwww.owncloud.org/enterprise/', true), - array('https://wwww.owncloud.org/enterprise/', true), - array('HTTPS://WWW.OWNCLOUD.ORG', true), - array('HTTP://WWW.OWNCLOUD.ORG', true), - array('FILE://WWW.OWNCLOUD.ORG', false), - array('file://www.owncloud.org', false), - array('FTP://WWW.OWNCLOUD.ORG', false), - array('ftp://www.owncloud.org', false), - ); - } - - /** - * @dataProvider isHttpTestData - */ - public function testIsHTTP($url, $expected) { - $this->assertSame($expected, $this->httpHelperMock->isHTTPURL($url)); - } - - public function testPostSuccess() { - $client = $this->getMockBuilder('\OCP\Http\Client\IClient') - ->disableOriginalConstructor()->getMock(); - $this->clientService - ->expects($this->once()) - ->method('newClient') - ->will($this->returnValue($client)); - $response = $this->getMockBuilder('\OCP\Http\Client\IResponse') - ->disableOriginalConstructor()->getMock(); - $client - ->expects($this->once()) - ->method('post') - ->with( - 'https://owncloud.org', - [ - 'body' => [ - 'Foo' => 'Bar', - ], - 'connect_timeout' => 10, - - ] - ) - ->will($this->returnValue($response)); - $response - ->expects($this->once()) - ->method('getBody') - ->will($this->returnValue('Body of the requested page')); - - - $response = $this->httpHelperMock->post('https://owncloud.org', ['Foo' => 'Bar']); - $expected = [ - 'success' => true, - 'result' => 'Body of the requested page' - ]; - $this->assertSame($expected, $response); - } - - public function testPostException() { - $client = $this->getMockBuilder('\OCP\Http\Client\IClient') - ->disableOriginalConstructor()->getMock(); - $this->clientService - ->expects($this->once()) - ->method('newClient') - ->will($this->returnValue($client)); - $client - ->expects($this->once()) - ->method('post') - ->with( - 'https://owncloud.org', - [ - 'body' => [ - 'Foo' => 'Bar', - ], - 'connect_timeout' => 10, - - ] - ) - ->will($this->throwException(new \Exception('Something failed'))); - - - $response = $this->httpHelperMock->post('https://owncloud.org', ['Foo' => 'Bar']); - $expected = [ - 'success' => false, - 'result' => 'Something failed' - ]; - $this->assertSame($expected, $response); - } - -} diff --git a/tests/lib/image.php b/tests/lib/image.php deleted file mode 100644 index e74c75b48cf..00000000000 --- a/tests/lib/image.php +++ /dev/null @@ -1,337 +0,0 @@ - - * This file is licensed under the Affero General Public License version 3 or - * later. - * See the COPYING-README file. - */ - -class Test_Image extends \Test\TestCase { - public static function tearDownAfterClass() { - @unlink(OC::$SERVERROOT.'/tests/data/testimage2.png'); - @unlink(OC::$SERVERROOT.'/tests/data/testimage2.jpg'); - - parent::tearDownAfterClass(); - } - - public function testGetMimeTypeForFile() { - $mimetype = \OC_Image::getMimeTypeForFile(OC::$SERVERROOT.'/tests/data/testimage.png'); - $this->assertEquals('image/png', $mimetype); - - $mimetype = \OC_Image::getMimeTypeForFile(OC::$SERVERROOT.'/tests/data/testimage.jpg'); - $this->assertEquals('image/jpeg', $mimetype); - - $mimetype = \OC_Image::getMimeTypeForFile(OC::$SERVERROOT.'/tests/data/testimage.gif'); - $this->assertEquals('image/gif', $mimetype); - - $mimetype = \OC_Image::getMimeTypeForFile(null); - $this->assertEquals('', $mimetype); - } - - public function testConstructDestruct() { - $img = new \OC_Image(OC::$SERVERROOT.'/tests/data/testimage.png'); - $this->assertInstanceOf('\OC_Image', $img); - $this->assertInstanceOf('\OCP\IImage', $img); - unset($img); - - $imgcreate = imagecreatefromjpeg(OC::$SERVERROOT.'/tests/data/testimage.jpg'); - $img = new \OC_Image($imgcreate); - $this->assertInstanceOf('\OC_Image', $img); - $this->assertInstanceOf('\OCP\IImage', $img); - unset($img); - - $base64 = base64_encode(file_get_contents(OC::$SERVERROOT.'/tests/data/testimage.gif')); - $img = new \OC_Image($base64); - $this->assertInstanceOf('\OC_Image', $img); - $this->assertInstanceOf('\OCP\IImage', $img); - unset($img); - - $img = new \OC_Image(null); - $this->assertInstanceOf('\OC_Image', $img); - $this->assertInstanceOf('\OCP\IImage', $img); - unset($img); - } - - public function testValid() { - $img = new \OC_Image(OC::$SERVERROOT.'/tests/data/testimage.png'); - $this->assertTrue($img->valid()); - - $text = base64_encode("Lorem ipsum dolor sir amet …"); - $img = new \OC_Image($text); - $this->assertFalse($img->valid()); - - $img = new \OC_Image(null); - $this->assertFalse($img->valid()); - } - - public function testMimeType() { - $img = new \OC_Image(OC::$SERVERROOT.'/tests/data/testimage.png'); - $this->assertEquals('image/png', $img->mimeType()); - - $img = new \OC_Image(null); - $this->assertEquals('', $img->mimeType()); - - if (\OC_Util::runningOnWindows()) { - $this->markTestSkipped('[Windows] Images created with imagecreate() are pngs on windows'); - } - - $img = new \OC_Image(file_get_contents(OC::$SERVERROOT.'/tests/data/testimage.jpg')); - $this->assertEquals('image/jpeg', $img->mimeType()); - - $img = new \OC_Image(base64_encode(file_get_contents(OC::$SERVERROOT.'/tests/data/testimage.gif'))); - $this->assertEquals('image/gif', $img->mimeType()); - } - - public function testWidth() { - $img = new \OC_Image(OC::$SERVERROOT.'/tests/data/testimage.png'); - $this->assertEquals(128, $img->width()); - - $img = new \OC_Image(file_get_contents(OC::$SERVERROOT.'/tests/data/testimage.jpg')); - $this->assertEquals(1680, $img->width()); - - $img = new \OC_Image(base64_encode(file_get_contents(OC::$SERVERROOT.'/tests/data/testimage.gif'))); - $this->assertEquals(64, $img->width()); - - $img = new \OC_Image(null); - $this->assertEquals(-1, $img->width()); - } - - public function testHeight() { - $img = new \OC_Image(OC::$SERVERROOT.'/tests/data/testimage.png'); - $this->assertEquals(128, $img->height()); - - $img = new \OC_Image(file_get_contents(OC::$SERVERROOT.'/tests/data/testimage.jpg')); - $this->assertEquals(1050, $img->height()); - - $img = new \OC_Image(base64_encode(file_get_contents(OC::$SERVERROOT.'/tests/data/testimage.gif'))); - $this->assertEquals(64, $img->height()); - - $img = new \OC_Image(null); - $this->assertEquals(-1, $img->height()); - } - - public function testSave() { - $img = new \OC_Image(OC::$SERVERROOT.'/tests/data/testimage.png'); - $img->resize(16); - $img->save(OC::$SERVERROOT.'/tests/data/testimage2.png'); - $this->assertEquals(file_get_contents(OC::$SERVERROOT.'/tests/data/testimage2.png'), $img->data()); - - $img = new \OC_Image(OC::$SERVERROOT.'/tests/data/testimage.jpg'); - $img->resize(128); - $img->save(OC::$SERVERROOT.'/tests/data/testimage2.jpg'); - $this->assertEquals(file_get_contents(OC::$SERVERROOT.'/tests/data/testimage2.jpg'), $img->data()); - } - - public function testData() { - $img = new \OC_Image(OC::$SERVERROOT.'/tests/data/testimage.png'); - $raw = imagecreatefromstring(file_get_contents(OC::$SERVERROOT.'/tests/data/testimage.png')); - // Preserve transparency - imagealphablending($raw, true); - imagesavealpha($raw, true); - ob_start(); - imagepng($raw); - $expected = ob_get_clean(); - $this->assertEquals($expected, $img->data()); - - $img = new \OC_Image(OC::$SERVERROOT.'/tests/data/testimage.jpg'); - $raw = imagecreatefromstring(file_get_contents(OC::$SERVERROOT.'/tests/data/testimage.jpg')); - ob_start(); - imagejpeg($raw); - $expected = ob_get_clean(); - $this->assertEquals($expected, $img->data()); - - $img = new \OC_Image(OC::$SERVERROOT.'/tests/data/testimage.gif'); - $raw = imagecreatefromstring(file_get_contents(OC::$SERVERROOT.'/tests/data/testimage.gif')); - ob_start(); - imagegif($raw); - $expected = ob_get_clean(); - $this->assertEquals($expected, $img->data()); - } - - public function testDataNoResource() { - $img = new \OC_Image(); - $this->assertNull($img->data()); - } - - /** - * @depends testData - */ - public function testToString() { - $img = new \OC_Image(OC::$SERVERROOT.'/tests/data/testimage.png'); - $expected = base64_encode($img->data()); - $this->assertEquals($expected, (string)$img); - - $img = new \OC_Image(file_get_contents(OC::$SERVERROOT.'/tests/data/testimage.jpg')); - $expected = base64_encode($img->data()); - $this->assertEquals($expected, (string)$img); - - $img = new \OC_Image(OC::$SERVERROOT.'/tests/data/testimage.gif'); - $expected = base64_encode($img->data()); - $this->assertEquals($expected, (string)$img); - } - - public function testResize() { - $img = new \OC_Image(OC::$SERVERROOT.'/tests/data/testimage.png'); - $this->assertTrue($img->resize(32)); - $this->assertEquals(32, $img->width()); - $this->assertEquals(32, $img->height()); - - $img = new \OC_Image(file_get_contents(OC::$SERVERROOT.'/tests/data/testimage.jpg')); - $this->assertTrue($img->resize(840)); - $this->assertEquals(840, $img->width()); - $this->assertEquals(525, $img->height()); - - $img = new \OC_Image(base64_encode(file_get_contents(OC::$SERVERROOT.'/tests/data/testimage.gif'))); - $this->assertTrue($img->resize(100)); - $this->assertEquals(100, $img->width()); - $this->assertEquals(100, $img->height()); - } - - public function testPreciseResize() { - $img = new \OC_Image(OC::$SERVERROOT.'/tests/data/testimage.png'); - $this->assertTrue($img->preciseResize(128, 512)); - $this->assertEquals(128, $img->width()); - $this->assertEquals(512, $img->height()); - - $img = new \OC_Image(file_get_contents(OC::$SERVERROOT.'/tests/data/testimage.jpg')); - $this->assertTrue($img->preciseResize(64, 840)); - $this->assertEquals(64, $img->width()); - $this->assertEquals(840, $img->height()); - - $img = new \OC_Image(base64_encode(file_get_contents(OC::$SERVERROOT.'/tests/data/testimage.gif'))); - $this->assertTrue($img->preciseResize(1000, 1337)); - $this->assertEquals(1000, $img->width()); - $this->assertEquals(1337, $img->height()); - } - - public function testCenterCrop() { - $img = new \OC_Image(OC::$SERVERROOT.'/tests/data/testimage.png'); - $img->centerCrop(); - $this->assertEquals(128, $img->width()); - $this->assertEquals(128, $img->height()); - - $img = new \OC_Image(file_get_contents(OC::$SERVERROOT.'/tests/data/testimage.jpg')); - $img->centerCrop(); - $this->assertEquals(1050, $img->width()); - $this->assertEquals(1050, $img->height()); - - $img = new \OC_Image(base64_encode(file_get_contents(OC::$SERVERROOT.'/tests/data/testimage.gif'))); - $img->centerCrop(512); - $this->assertEquals(512, $img->width()); - $this->assertEquals(512, $img->height()); - } - - public function testCrop() { - $img = new \OC_Image(OC::$SERVERROOT.'/tests/data/testimage.png'); - $this->assertTrue($img->crop(0, 0, 50, 20)); - $this->assertEquals(50, $img->width()); - $this->assertEquals(20, $img->height()); - - $img = new \OC_Image(file_get_contents(OC::$SERVERROOT.'/tests/data/testimage.jpg')); - $this->assertTrue($img->crop(500, 700, 550, 300)); - $this->assertEquals(550, $img->width()); - $this->assertEquals(300, $img->height()); - - $img = new \OC_Image(base64_encode(file_get_contents(OC::$SERVERROOT.'/tests/data/testimage.gif'))); - $this->assertTrue($img->crop(10, 10, 15, 15)); - $this->assertEquals(15, $img->width()); - $this->assertEquals(15, $img->height()); - } - - public static function sampleProvider() { - return [ - ['testimage.png', [200, 100], [100, 100]], - ['testimage.jpg', [840, 840], [840, 525]], - ['testimage.gif', [200, 250], [200, 200]] - ]; - } - - /** - * @dataProvider sampleProvider - * - * @param string $filename - * @param int[] $asked - * @param int[] $expected - */ - public function testFitIn($filename, $asked, $expected) { - $img = new \OC_Image(OC::$SERVERROOT . '/tests/data/' . $filename); - $this->assertTrue($img->fitIn($asked[0], $asked[1])); - $this->assertEquals($expected[0], $img->width()); - $this->assertEquals($expected[1], $img->height()); - } - - public static function sampleFilenamesProvider() { - return [ - ['testimage.png'], - ['testimage.jpg'], - ['testimage.gif'] - ]; - } - - /** - * Image should not be resized if it's already smaller than what is required - * - * @dataProvider sampleFilenamesProvider - * - * @param string $filename - */ - public function testScaleDownToFitWhenSmallerAlready($filename) { - $img = new \OC_Image(OC::$SERVERROOT . '/tests/data/' . $filename); - $currentWidth = $img->width(); - $currentHeight = $img->height(); - // We pick something larger than the image we want to scale down - $this->assertFalse($img->scaleDownToFit(4000, 4000)); - // The dimensions of the image should not have changed since it's smaller already - $resizedWidth = $img->width(); - $resizedHeight = $img->height(); - $this->assertEquals( - $currentWidth, $img->width(), "currentWidth $currentWidth resizedWidth $resizedWidth \n" - ); - $this->assertEquals( - $currentHeight, $img->height(), - "currentHeight $currentHeight resizedHeight $resizedHeight \n" - ); - } - - public static function largeSampleProvider() { - return [ - ['testimage.png', [200, 100], [100, 100]], - ['testimage.jpg', [840, 840], [840, 525]], - ]; - } - - /** - * @dataProvider largeSampleProvider - * - * @param string $filename - * @param int[] $asked - * @param int[] $expected - */ - public function testScaleDownWhenBigger($filename, $asked, $expected) { - $img = new \OC_Image(OC::$SERVERROOT . '/tests/data/' . $filename); - //$this->assertTrue($img->scaleDownToFit($asked[0], $asked[1])); - $img->scaleDownToFit($asked[0], $asked[1]); - $this->assertEquals($expected[0], $img->width()); - $this->assertEquals($expected[1], $img->height()); - } - - function convertDataProvider() { - return array( - array( 'image/gif'), - array( 'image/jpeg'), - array( 'image/png'), - ); - } - - /** - * @dataProvider convertDataProvider - */ - public function testConvert($mimeType) { - $img = new \OC_Image(OC::$SERVERROOT.'/tests/data/testimage.png'); - $tempFile = tempnam(sys_get_temp_dir(), 'img-test'); - - $img->save($tempFile, $mimeType); - $actualMimeType = \OC_Image::getMimeTypeForFile($tempFile); - $this->assertEquals($mimeType, $actualMimeType); - } -} diff --git a/tests/lib/naturalsort.php b/tests/lib/naturalsort.php deleted file mode 100644 index 8fcbc6f5fd3..00000000000 --- a/tests/lib/naturalsort.php +++ /dev/null @@ -1,270 +0,0 @@ - - * This file is licensed under the Affero General Public License version 3 or - * later. - * See the COPYING-README file. - */ - -class Test_NaturalSort extends \Test\TestCase { - - /** - * @dataProvider naturalSortDataProvider - */ - public function testNaturalSortCompare($array, $sorted) - { - if(!class_exists('Collator')) { - $this->markTestSkipped('The intl module is not available, natural sorting might not work as expected.'); - return; - } - $comparator = \OC\NaturalSort::getInstance(); - usort($array, array($comparator, 'compare')); - $this->assertEquals($sorted, $array); - } - - /** - * @dataProvider defaultCollatorDataProvider - */ - public function testDefaultCollatorCompare($array, $sorted) - { - $comparator = new \OC\NaturalSort(new \OC\NaturalSort_DefaultCollator()); - usort($array, array($comparator, 'compare')); - $this->assertEquals($sorted, $array); - } - - /** - * Data provider for natural sorting with php5-intl's Collator. - * Must provide the same result as in core/js/tests/specs/coreSpec.js - * @return array test cases - */ - public function naturalSortDataProvider() - { - return array( - // different casing - array( - // unsorted - array( - 'aaa', - 'bbb', - 'BBB', - 'AAA' - ), - // sorted - array( - 'aaa', - 'AAA', - 'bbb', - 'BBB' - ) - ), - // numbers - array( - // unsorted - array( - '124.txt', - 'abc1', - '123.txt', - 'abc', - 'abc2', - 'def (2).txt', - 'ghi 10.txt', - 'abc12', - 'def.txt', - 'def (1).txt', - 'ghi 2.txt', - 'def (10).txt', - 'abc10', - 'def (12).txt', - 'z', - 'ghi.txt', - 'za', - 'ghi 1.txt', - 'ghi 12.txt', - 'zz', - '15.txt', - '15b.txt', - ), - // sorted - array( - '15.txt', - '15b.txt', - '123.txt', - '124.txt', - 'abc', - 'abc1', - 'abc2', - 'abc10', - 'abc12', - 'def.txt', - 'def (1).txt', - 'def (2).txt', - 'def (10).txt', - 'def (12).txt', - 'ghi.txt', - 'ghi 1.txt', - 'ghi 2.txt', - 'ghi 10.txt', - 'ghi 12.txt', - 'z', - 'za', - 'zz', - ) - ), - // chinese characters - array( - // unsorted - array( - '十.txt', - '一.txt', - '二.txt', - '十 2.txt', - '三.txt', - '四.txt', - 'abc.txt', - '五.txt', - '七.txt', - '八.txt', - '九.txt', - '六.txt', - '十一.txt', - '波.txt', - '破.txt', - '莫.txt', - '啊.txt', - '123.txt', - ), - // sorted - array( - '123.txt', - 'abc.txt', - '一.txt', - '七.txt', - '三.txt', - '九.txt', - '二.txt', - '五.txt', - '八.txt', - '六.txt', - '十.txt', - '十 2.txt', - '十一.txt', - '啊.txt', - '四.txt', - '波.txt', - '破.txt', - '莫.txt', - ) - ), - // with umlauts - array( - // unsorted - array( - 'öh.txt', - 'Äh.txt', - 'oh.txt', - 'Üh 2.txt', - 'Üh.txt', - 'ah.txt', - 'Öh.txt', - 'uh.txt', - 'üh.txt', - 'äh.txt', - ), - // sorted - array( - 'ah.txt', - 'äh.txt', - 'Äh.txt', - 'oh.txt', - 'öh.txt', - 'Öh.txt', - 'uh.txt', - 'üh.txt', - 'Üh.txt', - 'Üh 2.txt', - ) - ), - ); - } - - /** - * Data provider for natural sorting with \OC\NaturalSort_DefaultCollator. - * Must provide the same result as in core/js/tests/specs/coreSpec.js - * @return array test cases - */ - public function defaultCollatorDataProvider() - { - return array( - // different casing - array( - // unsorted - array( - 'aaa', - 'bbb', - 'BBB', - 'AAA' - ), - // sorted - array( - 'aaa', - 'AAA', - 'bbb', - 'BBB' - ) - ), - // numbers - array( - // unsorted - array( - '124.txt', - 'abc1', - '123.txt', - 'abc', - 'abc2', - 'def (2).txt', - 'ghi 10.txt', - 'abc12', - 'def.txt', - 'def (1).txt', - 'ghi 2.txt', - 'def (10).txt', - 'abc10', - 'def (12).txt', - 'z', - 'ghi.txt', - 'za', - 'ghi 1.txt', - 'ghi 12.txt', - 'zz', - '15.txt', - '15b.txt', - ), - // sorted - array( - '15.txt', - '15b.txt', - '123.txt', - '124.txt', - 'abc', - 'abc1', - 'abc2', - 'abc10', - 'abc12', - 'def.txt', - 'def (1).txt', - 'def (2).txt', - 'def (10).txt', - 'def (12).txt', - 'ghi.txt', - 'ghi 1.txt', - 'ghi 2.txt', - 'ghi 10.txt', - 'ghi 12.txt', - 'z', - 'za', - 'zz', - ) - ), - ); - } -} diff --git a/tests/lib/ocsclienttest.php b/tests/lib/ocsclienttest.php index 7555562d124..4ae6fb62e0e 100644 --- a/tests/lib/ocsclienttest.php +++ b/tests/lib/ocsclienttest.php @@ -19,6 +19,8 @@ * */ +namespace Test; + use OC\OCSClient; use OCP\Http\Client\IClientService; use OCP\IConfig; diff --git a/tests/lib/setup.php b/tests/lib/setup.php deleted file mode 100644 index bc78c14008f..00000000000 --- a/tests/lib/setup.php +++ /dev/null @@ -1,133 +0,0 @@ - - * This file is licensed under the Affero General Public License version 3 or - * later. - * See the COPYING-README file. - */ - -use OCP\IConfig; - -class Test_OC_Setup extends \Test\TestCase { - - /** @var IConfig | PHPUnit_Framework_MockObject_MockObject */ - protected $config; - /** @var \bantu\IniGetWrapper\IniGetWrapper | PHPUnit_Framework_MockObject_MockObject */ - private $iniWrapper; - /** @var \OCP\IL10N | PHPUnit_Framework_MockObject_MockObject */ - private $l10n; - /** @var \OC_Defaults | PHPUnit_Framework_MockObject_MockObject */ - private $defaults; - /** @var \OC\Setup | PHPUnit_Framework_MockObject_MockObject */ - protected $setupClass; - /** @var \OCP\ILogger | PHPUnit_Framework_MockObject_MockObject */ - protected $logger; - /** @var \OCP\Security\ISecureRandom | PHPUnit_Framework_MockObject_MockObject */ - protected $random; - - protected function setUp() { - parent::setUp(); - - $this->config = $this->getMock('\OCP\IConfig'); - $this->iniWrapper = $this->getMock('\bantu\IniGetWrapper\IniGetWrapper'); - $this->l10n = $this->getMock('\OCP\IL10N'); - $this->defaults = $this->getMock('\OC_Defaults'); - $this->logger = $this->getMock('\OCP\ILogger'); - $this->random = $this->getMock('\OCP\Security\ISecureRandom'); - $this->setupClass = $this->getMock('\OC\Setup', - ['class_exists', 'is_callable', 'getAvailableDbDriversForPdo'], - [$this->config, $this->iniWrapper, $this->l10n, $this->defaults, $this->logger, $this->random]); - } - - public function testGetSupportedDatabasesWithOneWorking() { - $this->config - ->expects($this->once()) - ->method('getSystemValue') - ->will($this->returnValue( - array('sqlite', 'mysql', 'oci') - )); - $this->setupClass - ->expects($this->once()) - ->method('class_exists') - ->will($this->returnValue(true)); - $this->setupClass - ->expects($this->once()) - ->method('is_callable') - ->will($this->returnValue(false)); - $this->setupClass - ->expects($this->once()) - ->method('getAvailableDbDriversForPdo') - ->will($this->returnValue([])); - $result = $this->setupClass->getSupportedDatabases(); - $expectedResult = array( - 'sqlite' => 'SQLite' - ); - - $this->assertSame($expectedResult, $result); - } - - public function testGetSupportedDatabasesWithNoWorking() { - $this->config - ->expects($this->once()) - ->method('getSystemValue') - ->will($this->returnValue( - array('sqlite', 'mysql', 'oci', 'pgsql') - )); - $this->setupClass - ->expects($this->once()) - ->method('class_exists') - ->will($this->returnValue(false)); - $this->setupClass - ->expects($this->exactly(2)) - ->method('is_callable') - ->will($this->returnValue(false)); - $this->setupClass - ->expects($this->once()) - ->method('getAvailableDbDriversForPdo') - ->will($this->returnValue([])); - $result = $this->setupClass->getSupportedDatabases(); - - $this->assertSame(array(), $result); - } - - public function testGetSupportedDatabasesWithAllWorking() { - $this->config - ->expects($this->once()) - ->method('getSystemValue') - ->will($this->returnValue( - array('sqlite', 'mysql', 'pgsql', 'oci') - )); - $this->setupClass - ->expects($this->once()) - ->method('class_exists') - ->will($this->returnValue(true)); - $this->setupClass - ->expects($this->exactly(2)) - ->method('is_callable') - ->will($this->returnValue(true)); - $this->setupClass - ->expects($this->once()) - ->method('getAvailableDbDriversForPdo') - ->will($this->returnValue(['mysql'])); - $result = $this->setupClass->getSupportedDatabases(); - $expectedResult = array( - 'sqlite' => 'SQLite', - 'mysql' => 'MySQL/MariaDB', - 'pgsql' => 'PostgreSQL', - 'oci' => 'Oracle' - ); - $this->assertSame($expectedResult, $result); - } - - /** - * @expectedException \Exception - * @expectedExceptionMessage Supported databases are not properly configured. - */ - public function testGetSupportedDatabaseException() { - $this->config - ->expects($this->once()) - ->method('getSystemValue') - ->will($this->returnValue('NotAnArray')); - $this->setupClass->getSupportedDatabases(); - } -} diff --git a/tests/lib/streamwrappers.php b/tests/lib/streamwrappers.php deleted file mode 100644 index 7175683a60b..00000000000 --- a/tests/lib/streamwrappers.php +++ /dev/null @@ -1,114 +0,0 @@ -. - * - */ - -/** - * Class Test_StreamWrappers - * - * @group DB - */ -class Test_StreamWrappers extends \Test\TestCase { - - private static $trashBinStatus; - - public static function setUpBeforeClass() { - self::$trashBinStatus = \OC_App::isEnabled('files_trashbin'); - \OC_App::disable('files_trashbin'); - } - - public static function tearDownAfterClass() { - if (self::$trashBinStatus) { - \OC_App::enable('files_trashbin'); - } - } - - public function testFakeDir() { - $items = array('foo', 'bar'); - \OC\Files\Stream\Dir::register('test', $items); - $dh = opendir('fakedir://test'); - $result = array(); - while ($file = readdir($dh)) { - $result[] = $file; - $this->assertContains($file, $items); - } - $this->assertEquals(count($items), count($result)); - } - - public function testCloseStream() { - //ensure all basic stream stuff works - $sourceFile = OC::$SERVERROOT . '/tests/data/lorem.txt'; - $tmpFile = \OC::$server->getTempManager()->getTemporaryFile('.txt'); - $file = 'close://' . $tmpFile; - $this->assertTrue(file_exists($file)); - file_put_contents($file, file_get_contents($sourceFile)); - $this->assertEquals(file_get_contents($sourceFile), file_get_contents($file)); - unlink($file); - clearstatcache(); - $this->assertFalse(file_exists($file)); - - //test callback - $tmpFile = \OC::$server->getTempManager()->getTemporaryFile('.txt'); - $file = 'close://' . $tmpFile; - $actual = false; - $callback = function($path) use (&$actual) { $actual = $path; }; - \OC\Files\Stream\Close::registerCallback($tmpFile, $callback); - $fh = fopen($file, 'w'); - fwrite($fh, 'asd'); - fclose($fh); - $this->assertSame($tmpFile, $actual); - } - - public function testOC() { - // FIXME: use proper tearDown with $this->loginAsUser() and $this->logout() - // (would currently break the tests for some reason) - $originalStorage = \OC\Files\Filesystem::getStorage('/'); - \OC\Files\Filesystem::clearMounts(); - - $storage = new \OC\Files\Storage\Temporary(array()); - $storage->file_put_contents('foo.txt', 'asd'); - \OC\Files\Filesystem::mount($storage, array(), '/'); - - $this->assertTrue(file_exists('oc:///foo.txt')); - $this->assertEquals('asd', file_get_contents('oc:///foo.txt')); - $this->assertEquals(array('.', '..', 'foo.txt'), scandir('oc:///')); - - file_put_contents('oc:///bar.txt', 'qwerty'); - $this->assertEquals('qwerty', $storage->file_get_contents('bar.txt')); - $this->assertEquals(array('.', '..', 'bar.txt', 'foo.txt'), scandir('oc:///')); - $this->assertEquals('qwerty', file_get_contents('oc:///bar.txt')); - - $fh = fopen('oc:///bar.txt', 'rb'); - $this->assertSame(0, ftell($fh)); - $content = fread($fh, 4); - $this->assertSame(4, ftell($fh)); - $this->assertSame('qwer', $content); - $content = fread($fh, 1); - $this->assertSame(5, ftell($fh)); - $this->assertSame(0, fseek($fh, 0)); - $this->assertSame(0, ftell($fh)); - - unlink('oc:///foo.txt'); - $this->assertEquals(array('.', '..', 'bar.txt'), scandir('oc:///')); - - \OC\Files\Filesystem::clearMounts(); - \OC\Files\Filesystem::mount($originalStorage, array(), '/'); - } -} diff --git a/tests/lib/tags.php b/tests/lib/tags.php deleted file mode 100644 index 91472d5ceb8..00000000000 --- a/tests/lib/tags.php +++ /dev/null @@ -1,314 +0,0 @@ -. -* -*/ - -/** - * Class Test_Tags - * - * @group DB - */ -class Test_Tags extends \Test\TestCase { - - protected $objectType; - /** @var \OCP\IUser */ - protected $user; - /** @var \OCP\IUserSession */ - protected $userSession; - protected $backupGlobals = FALSE; - /** @var \OC\Tagging\TagMapper */ - protected $tagMapper; - /** @var \OCP\ITagManager */ - protected $tagMgr; - - protected function setUp() { - parent::setUp(); - - OC_User::clearBackends(); - OC_User::useBackend('dummy'); - $userId = $this->getUniqueID('user_'); - \OC::$server->getUserManager()->createUser($userId, 'pass'); - OC_User::setUserId($userId); - $this->user = new OC\User\User($userId, null); - $this->userSession = $this->getMock('\OCP\IUserSession'); - $this->userSession - ->expects($this->any()) - ->method('getUser') - ->will($this->returnValue($this->user)); - - $this->objectType = $this->getUniqueID('type_'); - $this->tagMapper = new OC\Tagging\TagMapper(\OC::$server->getDatabaseConnection()); - $this->tagMgr = new OC\TagManager($this->tagMapper, $this->userSession); - - } - - protected function tearDown() { - $conn = \OC::$server->getDatabaseConnection(); - $conn->executeQuery('DELETE FROM `*PREFIX*vcategory_to_object`'); - $conn->executeQuery('DELETE FROM `*PREFIX*vcategory`'); - - parent::tearDown(); - } - - public function testTagManagerWithoutUserReturnsNull() { - $this->userSession = $this->getMock('\OCP\IUserSession'); - $this->userSession - ->expects($this->any()) - ->method('getUser') - ->will($this->returnValue(null)); - $this->tagMgr = new OC\TagManager($this->tagMapper, $this->userSession); - $this->assertNull($this->tagMgr->load($this->objectType)); - } - - public function testInstantiateWithDefaults() { - $defaultTags = array('Friends', 'Family', 'Work', 'Other'); - - $tagger = $this->tagMgr->load($this->objectType, $defaultTags); - - $this->assertEquals(4, count($tagger->getTags())); - } - - public function testAddTags() { - $tags = array('Friends', 'Family', 'Work', 'Other'); - - $tagger = $this->tagMgr->load($this->objectType); - - foreach($tags as $tag) { - $result = $tagger->add($tag); - $this->assertGreaterThan(0, $result, 'add() returned an ID <= 0'); - $this->assertTrue((bool)$result); - } - - $this->assertFalse($tagger->add('Family')); - $this->assertFalse($tagger->add('fAMILY')); - - $this->assertCount(4, $tagger->getTags(), 'Wrong number of added tags'); - } - - public function testAddMultiple() { - $tags = array('Friends', 'Family', 'Work', 'Other'); - - $tagger = $this->tagMgr->load($this->objectType); - - foreach($tags as $tag) { - $this->assertFalse($tagger->hasTag($tag)); - } - - $result = $tagger->addMultiple($tags); - $this->assertTrue((bool)$result); - - foreach($tags as $tag) { - $this->assertTrue($tagger->hasTag($tag)); - } - - $tagMaps = $tagger->getTags(); - $this->assertCount(4, $tagMaps, 'Not all tags added'); - foreach($tagMaps as $tagMap) { - $this->assertEquals(null, $tagMap['id']); - } - - // As addMultiple has been called without $sync=true, the tags aren't - // saved to the database, so they're gone when we reload $tagger: - - $tagger = $this->tagMgr->load($this->objectType); - $this->assertEquals(0, count($tagger->getTags())); - - // Now, we call addMultiple() with $sync=true so the tags will be - // be saved to the database. - $result = $tagger->addMultiple($tags, true); - $this->assertTrue((bool)$result); - - $tagMaps = $tagger->getTags(); - foreach($tagMaps as $tagMap) { - $this->assertNotEquals(null, $tagMap['id']); - } - - // Reload the tagger. - $tagger = $this->tagMgr->load($this->objectType); - - foreach($tags as $tag) { - $this->assertTrue($tagger->hasTag($tag)); - } - - $this->assertCount(4, $tagger->getTags(), 'Not all previously saved tags found'); - } - - public function testIsEmpty() { - $tagger = $this->tagMgr->load($this->objectType); - - $this->assertEquals(0, count($tagger->getTags())); - $this->assertTrue($tagger->isEmpty()); - - $result = $tagger->add('Tag'); - $this->assertGreaterThan(0, $result, 'add() returned an ID <= 0'); - $this->assertNotEquals(false, $result, 'add() returned false'); - $this->assertFalse($tagger->isEmpty()); - } - - public function testGetTagsForObjects() { - $defaultTags = array('Friends', 'Family', 'Work', 'Other'); - $tagger = $this->tagMgr->load($this->objectType, $defaultTags); - - $tagger->tagAs(1, 'Friends'); - $tagger->tagAs(1, 'Other'); - $tagger->tagAs(2, 'Family'); - - $tags = $tagger->getTagsForObjects(array(1)); - $this->assertEquals(1, count($tags)); - $tags = current($tags); - sort($tags); - $this->assertSame(array('Friends', 'Other'), $tags); - - $tags = $tagger->getTagsForObjects(array(1, 2)); - $this->assertEquals(2, count($tags)); - $tags1 = $tags[1]; - sort($tags1); - $this->assertSame(array('Friends', 'Other'), $tags1); - $this->assertSame(array('Family'), $tags[2]); - $this->assertEquals( - array(), - $tagger->getTagsForObjects(array(4)) - ); - $this->assertEquals( - array(), - $tagger->getTagsForObjects(array(4, 5)) - ); - } - - public function testGetTagsForObjectsMassiveResults() { - $defaultTags = array('tag1'); - $tagger = $this->tagMgr->load($this->objectType, $defaultTags); - $tagData = $tagger->getTags(); - $tagId = $tagData[0]['id']; - $tagType = $tagData[0]['type']; - - $conn = \OC::$server->getDatabaseConnection(); - $statement = $conn->prepare( - 'INSERT INTO `*PREFIX*vcategory_to_object` ' . - '(`objid`, `categoryid`, `type`) VALUES ' . - '(?, ?, ?)' - ); - - // insert lots of entries - $idsArray = array(); - for($i = 1; $i <= 1500; $i++) { - $statement->execute(array($i, $tagId, $tagType)); - $idsArray[] = $i; - } - - $tags = $tagger->getTagsForObjects($idsArray); - $this->assertEquals(1500, count($tags)); - } - - public function testDeleteTags() { - $defaultTags = array('Friends', 'Family', 'Work', 'Other'); - $tagger = $this->tagMgr->load($this->objectType, $defaultTags); - - $this->assertEquals(4, count($tagger->getTags())); - - $tagger->delete('family'); - $this->assertEquals(3, count($tagger->getTags())); - - $tagger->delete(array('Friends', 'Work', 'Other')); - $this->assertEquals(0, count($tagger->getTags())); - } - - public function testRenameTag() { - $defaultTags = array('Friends', 'Family', 'Wrok', 'Other'); - $tagger = $this->tagMgr->load($this->objectType, $defaultTags); - - $this->assertTrue($tagger->rename('Wrok', 'Work')); - $this->assertTrue($tagger->hasTag('Work')); - $this->assertFalse($tagger->hastag('Wrok')); - $this->assertFalse($tagger->rename('Wrok', 'Work')); // Rename non-existant tag. - $this->assertFalse($tagger->rename('Work', 'Family')); // Collide with existing tag. - } - - public function testTagAs() { - $objids = array(1, 2, 3, 4, 5, 6, 7, 8, 9); - - $tagger = $this->tagMgr->load($this->objectType); - - foreach($objids as $id) { - $this->assertTrue($tagger->tagAs($id, 'Family')); - } - - $this->assertEquals(1, count($tagger->getTags())); - $this->assertEquals(9, count($tagger->getIdsForTag('Family'))); - } - - /** - * @depends testTagAs - */ - public function testUnTag() { - $objIds = array(1, 2, 3, 4, 5, 6, 7, 8, 9); - - // Is this "legal"? - $this->testTagAs(); - $tagger = $this->tagMgr->load($this->objectType); - - foreach($objIds as $id) { - $this->assertTrue(in_array($id, $tagger->getIdsForTag('Family'))); - $tagger->unTag($id, 'Family'); - $this->assertFalse(in_array($id, $tagger->getIdsForTag('Family'))); - } - - $this->assertEquals(1, count($tagger->getTags())); - $this->assertEquals(0, count($tagger->getIdsForTag('Family'))); - } - - public function testFavorite() { - $tagger = $this->tagMgr->load($this->objectType); - $this->assertTrue($tagger->addToFavorites(1)); - $this->assertEquals(array(1), $tagger->getFavorites()); - $this->assertTrue($tagger->removeFromFavorites(1)); - $this->assertEquals(array(), $tagger->getFavorites()); - } - - public function testShareTags() { - $testTag = 'TestTag'; - OCP\Share::registerBackend('test', 'Test_Share_Backend'); - - $tagger = $this->tagMgr->load('test'); - $tagger->tagAs(1, $testTag); - - $otherUserId = $this->getUniqueID('user2_'); - \OC::$server->getUserManager()->createUser($otherUserId, 'pass'); - OC_User::setUserId($otherUserId); - $otherUserSession = $this->getMock('\OCP\IUserSession'); - $otherUserSession - ->expects($this->any()) - ->method('getUser') - ->will($this->returnValue(new OC\User\User($otherUserId, null))); - - $otherTagMgr = new OC\TagManager($this->tagMapper, $otherUserSession); - $otherTagger = $otherTagMgr->load('test'); - $this->assertFalse($otherTagger->hasTag($testTag)); - - OC_User::setUserId($this->user->getUID()); - OCP\Share::shareItem('test', 1, OCP\Share::SHARE_TYPE_USER, $otherUserId, \OCP\Constants::PERMISSION_READ); - - OC_User::setUserId($otherUserId); - $otherTagger = $otherTagMgr->load('test', array(), true); // Update tags, load shared ones. - $this->assertTrue($otherTagger->hasTag($testTag)); - $this->assertContains(1, $otherTagger->getIdsForTag($testTag)); - } - -} diff --git a/tests/lib/template.php b/tests/lib/template.php deleted file mode 100644 index 6e62d3955f1..00000000000 --- a/tests/lib/template.php +++ /dev/null @@ -1,250 +0,0 @@ - - * - * 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 . - * - */ -class Test_TemplateFunctions extends \Test\TestCase { - - protected function setUp() { - parent::setUp(); - - $loader = new \OC\Autoloader([OC::$SERVERROOT . '/lib']); - $loader->load('OC_Template'); - } - - public function testPJavaScript() { - $this->expectOutputString('<img onload="alert(1)" />'); - p(''); - } - - public function testPJavaScriptWithScriptTags() { - $this->expectOutputString('<script>alert('Hacked!');</script>'); - p(""); - } - - public function testPNormalString() { - $string = 'This is a good string without HTML.'; - $this->expectOutputString($string); - p($string); - } - - public function testPrintUnescaped() { - $htmlString = ""; - $this->expectOutputString($htmlString); - print_unescaped($htmlString); - } - - public function testPrintUnescapedNormalString() { - $string = 'This is a good string!'; - $this->expectOutputString($string); - print_unescaped($string); - } - - // --------------------------------------------------------------------------- - // 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 * 65; - $result = (string)relative_modified_date($elementTime, $currentTime, true); - - $this->assertEquals('2 months ago', $result); - - $elementTime = $currentTime - 86400 * 130; - $result = (string)relative_modified_date($elementTime, $currentTime, true); - - $this->assertEquals('4 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('2 years ago', $result); - - $elementTime = $currentTime - 86400 * 365.25 * 3; - $result = (string)relative_modified_date($elementTime, $currentTime, true); - - $this->assertEquals('3 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 * 65; - $result = (string)relative_modified_date($elementTime, $currentTime, false); - - $this->assertEquals('2 months ago', $result); - - $elementTime = $currentTime - 86400 * 130; - $result = (string)relative_modified_date($elementTime, $currentTime, false); - - $this->assertEquals('4 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('2 years ago', $result); - - $elementTime = $currentTime - 86400 * 365.25 * 3; - $result = (string)relative_modified_date($elementTime, $currentTime, false); - - $this->assertEquals('3 years ago', $result); - } -} diff --git a/tests/lib/updater.php b/tests/lib/updater.php deleted file mode 100644 index f97eb3ac139..00000000000 --- a/tests/lib/updater.php +++ /dev/null @@ -1,181 +0,0 @@ - - * @author Victor Dubiniuk - * - * @copyright Copyright (c) 2015, ownCloud, Inc. - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see - * - */ - -namespace OC; - -use OCP\IConfig; -use OCP\ILogger; -use OC\IntegrityCheck\Checker; - -class UpdaterTest extends \Test\TestCase { - /** @var IConfig|\PHPUnit_Framework_MockObject_MockObject */ - private $config; - /** @var ILogger */ - private $logger; - /** @var Updater */ - private $updater; - /** @var Checker */ - private $checker; - - public function setUp() { - parent::setUp(); - $this->config = $this->getMockBuilder('\\OCP\\IConfig') - ->disableOriginalConstructor() - ->getMock(); - $this->logger = $this->getMockBuilder('\\OCP\\ILogger') - ->disableOriginalConstructor() - ->getMock(); - $this->checker = $this->getMockBuilder('\OC\IntegrityCheck\Checker') - ->disableOriginalConstructor() - ->getMock(); - - $this->updater = new Updater( - $this->config, - $this->checker, - $this->logger - ); - } - - /** - * @param string $baseUrl - * @return string - */ - private function buildUpdateUrl($baseUrl) { - return $baseUrl . '?version='.implode('x', \OCP\Util::getVersion()).'xinstalledatxlastupdatedatx'.\OC_Util::getChannel().'x'.\OC_Util::getEditionString().'x'; - } - - /** - * @return array - */ - public function versionCompatibilityTestData() { - return [ - ['1', '2', '1', true], - ['2', '2', '2', true], - ['6.0.5.0', '6.0.6.0', '5.0', true], - ['5.0.6.0', '7.0.4.0', '6.0', false], - // allow upgrading within the same major release - ['8.0.0.0', '8.0.0.0', '8.0', true], - ['8.0.0.0', '8.0.0.4', '8.0', true], - ['8.0.0.0', '8.0.1.0', '8.0', true], - ['8.0.0.0', '8.0.2.0', '8.0', true], - // does not allow downgrading within the same major release - ['8.0.1.0', '8.0.0.0', '8.0', false], - ['8.0.2.0', '8.0.1.0', '8.0', false], - ['8.0.0.4', '8.0.0.0', '8.0', false], - // allows upgrading within the patch version - ['8.0.0.0', '8.0.0.1', '8.0', true], - ['8.0.0.0', '8.0.0.2', '8.0', true], - // does not allow downgrading within the same major release - ['8.0.0.1', '8.0.0.0', '8.0', false], - ['8.0.0.2', '8.0.0.0', '8.0', false], - // allow upgrading to the next major release - ['8.0.0.0', '8.1.0.0', '8.0', true], - ['8.0.0.0', '8.1.1.0', '8.0', true], - ['8.0.0.0', '8.1.1.5', '8.0', true], - ['8.0.0.2', '8.1.1.5', '8.0', true], - ['8.1.0.0', '8.2.0.0', '8.1', true], - ['8.1.0.2', '8.2.0.4', '8.1', true], - ['8.1.0.5', '8.2.0.1', '8.1', true], - ['8.1.0.0', '8.2.1.0', '8.1', true], - ['8.1.0.2', '8.2.1.5', '8.1', true], - ['8.1.0.5', '8.2.1.1', '8.1', true], - // does not allow downgrading to the previous major release - ['8.1.0.0', '8.0.0.0', '7.0', false], - ['8.1.1.0', '8.0.0.0', '7.0', false], - // does not allow skipping major releases - ['8.0.0.0', '8.2.0.0', '8.1', false], - ['8.0.0.0', '8.2.1.0', '8.1', false], - ['8.0.0.0', '9.0.1.0', '8.2', false], - ['8.0.0.0', '10.0.0.0', '9.3', false], - // allows updating to the next major release - ['8.2.0.0', '9.0.0.0', '8.2', true], - ['8.2.0.0', '9.0.0.0', '8.2', true], - ['8.2.0.0', '9.0.1.0', '8.2', true], - ['8.2.0.0', '9.0.1.1', '8.2', true], - ['8.2.0.2', '9.0.1.1', '8.2', true], - ['8.2.2.0', '9.0.1.0', '8.2', true], - ['8.2.2.2', '9.0.1.1', '8.2', true], - ['9.0.0.0', '9.1.0.0', '9.0', true], - ['9.0.0.0', '9.1.0.2', '9.0', true], - ['9.0.0.2', '9.1.0.1', '9.0', true], - ['9.1.0.0', '9.2.0.0', '9.1', true], - ['9.2.0.0', '9.3.0.0', '9.2', true], - ['9.3.0.0', '10.0.0.0', '9.3', true], - // does not allow updating to the next major release (first number) - ['9.0.0.0', '8.2.0.0', '8.1', false], - // other cases - ['8.0.0.0', '8.1.5.0', '8.0', true], - ['8.2.0.0', '9.0.0.0', '8.2', true], - ['8.2.0.0', '9.1.0.0', '9.0', false], - ['9.0.0.0', '8.1.0.0', '8.0', false], - ['9.0.0.0', '8.0.0.0', '7.0', false], - ['9.1.0.0', '8.0.0.0', '7.0', false], - ['8.2.0.0', '8.1.0.0', '8.0', false], - - // With debug enabled - ['8.0.0.0', '8.2.0.0', '8.1', false, true], - ['8.1.0.0', '8.2.0.0', '8.1', true, true], - ['8.2.0.1', '8.2.0.1', '8.1', true, true], - ['8.3.0.0', '8.2.0.0', '8.1', true, true], - ]; - } - - /** - * @dataProvider versionCompatibilityTestData - * - * @param string $oldVersion - * @param string $newVersion - * @param string $allowedVersion - * @param bool $result - * @param bool $debug - */ - public function testIsUpgradePossible($oldVersion, $newVersion, $allowedVersion, $result, $debug = false) { - $this->config->expects($this->any()) - ->method('getSystemValue') - ->with('debug', false) - ->willReturn($debug); - - $this->assertSame($result, $this->updater->isUpgradePossible($oldVersion, $newVersion, $allowedVersion)); - } - - public function testSetSimulateStepEnabled() { - $this->updater->setSimulateStepEnabled(true); - $this->assertSame(true, $this->invokePrivate($this->updater, 'simulateStepEnabled')); - $this->updater->setSimulateStepEnabled(false); - $this->assertSame(false, $this->invokePrivate($this->updater, 'simulateStepEnabled')); - } - - public function testSetUpdateStepEnabled() { - $this->updater->setUpdateStepEnabled(true); - $this->assertSame(true, $this->invokePrivate($this->updater, 'updateStepEnabled')); - $this->updater->setUpdateStepEnabled(false); - $this->assertSame(false, $this->invokePrivate($this->updater, 'updateStepEnabled')); - } - - public function testSetSkip3rdPartyAppsDisable() { - $this->updater->setSkip3rdPartyAppsDisable(true); - $this->assertSame(true, $this->invokePrivate($this->updater, 'skip3rdPartyAppsDisable')); - $this->updater->setSkip3rdPartyAppsDisable(false); - $this->assertSame(false, $this->invokePrivate($this->updater, 'skip3rdPartyAppsDisable')); - } - -} diff --git a/tests/lib/urlGenerator.php b/tests/lib/urlGenerator.php deleted file mode 100644 index 07103225baa..00000000000 --- a/tests/lib/urlGenerator.php +++ /dev/null @@ -1,132 +0,0 @@ - - * This file is licensed under the Affero General Public License version 3 or - * later. - * See the COPYING-README file. - */ - -/** - * Class Test_UrlGenerator - * - * @group DB - */ -class Test_UrlGenerator extends \Test\TestCase { - - /** - * @small - * test linkTo URL construction - * @dataProvider provideDocRootAppUrlParts - */ - public function testLinkToDocRoot($app, $file, $args, $expectedResult) { - \OC::$WEBROOT = ''; - $config = $this->getMock('\OCP\IConfig'); - $cacheFactory = $this->getMock('\OCP\ICacheFactory'); - $urlGenerator = new \OC\URLGenerator($config, $cacheFactory); - $result = $urlGenerator->linkTo($app, $file, $args); - - $this->assertEquals($expectedResult, $result); - } - - /** - * @small - * test linkTo URL construction in sub directory - * @dataProvider provideSubDirAppUrlParts - */ - public function testLinkToSubDir($app, $file, $args, $expectedResult) { - \OC::$WEBROOT = '/owncloud'; - $config = $this->getMock('\OCP\IConfig'); - $cacheFactory = $this->getMock('\OCP\ICacheFactory'); - $urlGenerator = new \OC\URLGenerator($config, $cacheFactory); - $result = $urlGenerator->linkTo($app, $file, $args); - - $this->assertEquals($expectedResult, $result); - } - - /** - * @dataProvider provideRoutes - */ - public function testLinkToRouteAbsolute($route, $expected) { - \OC::$WEBROOT = '/owncloud'; - $config = $this->getMock('\OCP\IConfig'); - $cacheFactory = $this->getMock('\OCP\ICacheFactory'); - $urlGenerator = new \OC\URLGenerator($config, $cacheFactory); - $result = $urlGenerator->linkToRouteAbsolute($route); - $this->assertEquals($expected, $result); - - } - - public function provideRoutes() { - return array( - array('files_ajax_list', 'http://localhost/owncloud/index.php/apps/files/ajax/list.php'), - array('core_ajax_preview', 'http://localhost/owncloud/index.php/core/preview.png'), - ); - } - - public function provideDocRootAppUrlParts() { - return array( - array('files', 'ajax/list.php', array(), '/index.php/apps/files/ajax/list.php'), - array('files', 'ajax/list.php', array('trut' => 'trat', 'dut' => 'dat'), '/index.php/apps/files/ajax/list.php?trut=trat&dut=dat'), - array('', 'index.php', array('trut' => 'trat', 'dut' => 'dat'), '/index.php?trut=trat&dut=dat'), - ); - } - - public function provideSubDirAppUrlParts() { - return array( - array('files', 'ajax/list.php', array(), '/owncloud/index.php/apps/files/ajax/list.php'), - array('files', 'ajax/list.php', array('trut' => 'trat', 'dut' => 'dat'), '/owncloud/index.php/apps/files/ajax/list.php?trut=trat&dut=dat'), - array('', 'index.php', array('trut' => 'trat', 'dut' => 'dat'), '/owncloud/index.php?trut=trat&dut=dat'), - ); - } - - /** - * @small - * test absolute URL construction - * @dataProvider provideDocRootURLs - */ - function testGetAbsoluteURLDocRoot($url, $expectedResult) { - - \OC::$WEBROOT = ''; - $config = $this->getMock('\OCP\IConfig'); - $cacheFactory = $this->getMock('\OCP\ICacheFactory'); - $urlGenerator = new \OC\URLGenerator($config, $cacheFactory); - $result = $urlGenerator->getAbsoluteURL($url); - - $this->assertEquals($expectedResult, $result); - } - - /** - * @small - * test absolute URL construction - * @dataProvider provideSubDirURLs - */ - function testGetAbsoluteURLSubDir($url, $expectedResult) { - - \OC::$WEBROOT = '/owncloud'; - $config = $this->getMock('\OCP\IConfig'); - $cacheFactory = $this->getMock('\OCP\ICacheFactory'); - $urlGenerator = new \OC\URLGenerator($config, $cacheFactory); - $result = $urlGenerator->getAbsoluteURL($url); - - $this->assertEquals($expectedResult, $result); - } - - public function provideDocRootURLs() { - return array( - array("index.php", "http://localhost/index.php"), - array("/index.php", "http://localhost/index.php"), - array("/apps/index.php", "http://localhost/apps/index.php"), - array("apps/index.php", "http://localhost/apps/index.php"), - ); - } - - public function provideSubDirURLs() { - return array( - array("index.php", "http://localhost/owncloud/index.php"), - array("/index.php", "http://localhost/owncloud/index.php"), - array("/apps/index.php", "http://localhost/owncloud/apps/index.php"), - array("apps/index.php", "http://localhost/owncloud/apps/index.php"), - ); - } -} - diff --git a/tests/lib/util.php b/tests/lib/util.php deleted file mode 100644 index 4d788353881..00000000000 --- a/tests/lib/util.php +++ /dev/null @@ -1,505 +0,0 @@ - - * This file is licensed under the Affero General Public License version 3 or - * later. - * See the COPYING-README file. - */ -class Test_Util extends \Test\TestCase { - public function testGetVersion() { - $version = \OCP\Util::getVersion(); - $this->assertTrue(is_array($version)); - foreach ($version as $num) { - $this->assertTrue(is_int($num)); - } - } - - public function testGetVersionString() { - $version = \OC_Util::getVersionString(); - $this->assertTrue(is_string($version)); - } - - public function testGetEditionString() { - $edition = \OC_Util::getEditionString(); - $this->assertTrue(is_string($edition)); - } - - function testFormatDate() { - date_default_timezone_set("UTC"); - - $result = OC_Util::formatDate(1350129205); - $expected = 'October 13, 2012 at 11:53:25 AM GMT+0'; - $this->assertEquals($expected, $result); - - $result = OC_Util::formatDate(1102831200, true); - $expected = 'December 12, 2004'; - $this->assertEquals($expected, $result); - } - - function testFormatDateWithTZ() { - date_default_timezone_set("UTC"); - - $result = OC_Util::formatDate(1350129205, false, 'Europe/Berlin'); - $expected = 'October 13, 2012 at 1:53:25 PM GMT+2'; - $this->assertEquals($expected, $result); - } - - /** - * @expectedException Exception - */ - function testFormatDateWithInvalidTZ() { - OC_Util::formatDate(1350129205, false, 'Mordor/Barad-dûr'); - } - - public function formatDateWithTZFromSessionData() { - return array( - array(3, 'October 13, 2012 at 2:53:25 PM GMT+3', 'Etc/GMT-3'), - array(15, 'October 13, 2012 at 11:53:25 AM GMT+0', 'UTC'), - array(-13, 'October 13, 2012 at 11:53:25 AM GMT+0', 'UTC'), - array(9.5, 'October 13, 2012 at 9:23:25 PM GMT+9:30', 'Australia/Darwin'), - array(-4.5, 'October 13, 2012 at 7:23:25 AM GMT-4:30', 'America/Caracas'), - array(15.5, 'October 13, 2012 at 11:53:25 AM GMT+0', 'UTC'), - ); - } - - /** - * @dataProvider formatDateWithTZFromSessionData - */ - function testFormatDateWithTZFromSession($offset, $expected, $expectedTimeZone) { - date_default_timezone_set("UTC"); - - $oldDateTimeFormatter = \OC::$server->query('DateTimeFormatter'); - \OC::$server->getSession()->set('timezone', $offset); - - $selectedTimeZone = \OC::$server->getDateTimeZone()->getTimeZone(1350129205); - $this->assertEquals($expectedTimeZone, $selectedTimeZone->getName()); - $newDateTimeFormatter = new \OC\DateTimeFormatter($selectedTimeZone, new \OC_L10N('lib', 'en')); - $this->setDateFormatter($newDateTimeFormatter); - - $result = OC_Util::formatDate(1350129205, false); - $this->assertEquals($expected, $result); - - $this->setDateFormatter($oldDateTimeFormatter); - } - - protected function setDateFormatter($formatter) { - \OC::$server->registerService('DateTimeFormatter', function ($c) use ($formatter) { - return $formatter; - }); - } - - function testSanitizeHTML() { - $badArray = [ - 'While it is unusual to pass an array', - 'this function actually supports it.', - 'And therefore there needs to be a for it!', - [ - 'And It Even May Nest', - ], - ]; - $goodArray = [ - 'While it is unusual to pass an array', - 'this function actually <blink>supports</blink> it.', - 'And therefore there needs to be a <script>alert("Unit"+'test')</script> for it!', - [ - 'And It Even May <strong>Nest</strong>' - ], - ]; - $result = OC_Util::sanitizeHTML($badArray); - $this->assertEquals($goodArray, $result); - - $badString = ''; - $result = OC_Util::sanitizeHTML($badString); - $this->assertEquals('<img onload="alert(1)" />', $result); - - $badString = ""; - $result = OC_Util::sanitizeHTML($badString); - $this->assertEquals('<script>alert('Hacked!');</script>', $result); - - $goodString = 'This is a good string without HTML.'; - $result = OC_Util::sanitizeHTML($goodString); - $this->assertEquals('This is a good string without HTML.', $result); - } - - function testEncodePath() { - $component = '/§#@test%&^ä/-child'; - $result = OC_Util::encodePath($component); - $this->assertEquals("/%C2%A7%23%40test%25%26%5E%C3%A4/-child", $result); - } - - public function testFileInfoLoaded() { - $expected = function_exists('finfo_open'); - $this->assertEquals($expected, \OC_Util::fileInfoLoaded()); - } - - function testGetDefaultEmailAddress() { - $email = \OCP\Util::getDefaultEmailAddress("no-reply"); - $this->assertEquals('no-reply@localhost', $email); - } - - function testGetDefaultEmailAddressFromConfig() { - $config = \OC::$server->getConfig(); - $config->setSystemValue('mail_domain', 'example.com'); - $email = \OCP\Util::getDefaultEmailAddress("no-reply"); - $this->assertEquals('no-reply@example.com', $email); - $config->deleteSystemValue('mail_domain'); - } - - function testGetConfiguredEmailAddressFromConfig() { - $config = \OC::$server->getConfig(); - $config->setSystemValue('mail_domain', 'example.com'); - $config->setSystemValue('mail_from_address', 'owncloud'); - $email = \OCP\Util::getDefaultEmailAddress("no-reply"); - $this->assertEquals('owncloud@example.com', $email); - $config->deleteSystemValue('mail_domain'); - $config->deleteSystemValue('mail_from_address'); - } - - function testGetInstanceIdGeneratesValidId() { - \OC::$server->getConfig()->deleteSystemValue('instanceid'); - $instanceId = OC_Util::getInstanceId(); - $this->assertStringStartsWith('oc', $instanceId); - $matchesRegex = preg_match('/^[a-z0-9]+$/', $instanceId); - $this->assertSame(1, $matchesRegex); - } - - /** - * @dataProvider baseNameProvider - */ - public function testBaseName($expected, $file) { - $base = \OC_Util::basename($file); - $this->assertEquals($expected, $base); - } - - public function baseNameProvider() { - return array( - array('public_html', '/home/user/public_html/'), - array('public_html', '/home/user/public_html'), - array('', '/'), - array('public_html', 'public_html'), - array('442aa682de2a64db1e010f50e60fd9c9', 'local::C:\Users\ADMINI~1\AppData\Local\Temp\2/442aa682de2a64db1e010f50e60fd9c9/') - ); - } - - /** - * @dataProvider filenameValidationProvider - */ - public function testFilenameValidation($file, $valid) { - // private API - $this->assertEquals($valid, \OC_Util::isValidFileName($file)); - // public API - $this->assertEquals($valid, \OCP\Util::isValidFileName($file)); - } - - public function filenameValidationProvider() { - return array( - // valid names - array('boringname', true), - array('something.with.extension', true), - array('now with spaces', true), - array('.a', true), - array('..a', true), - array('.dotfile', true), - array('single\'quote', true), - array(' spaces before', true), - array('spaces after ', true), - array('allowed chars including the crazy ones $%&_-^@!,()[]{}=;#', true), - array('汉字也能用', true), - array('und Ümläüte sind auch willkommen', true), - // disallowed names - array('', false), - array(' ', false), - array('.', false), - array('..', false), - array('back\\slash', false), - array('sl/ash', false), - array('ltgt', true), - array('col:on', true), - array('double"quote', true), - array('pi|pe', true), - array('dont?ask?questions?', true), - array('super*star', true), - array('new\nline', false), - // better disallow these to avoid unexpected trimming to have side effects - array(' ..', false), - array('.. ', false), - array('. ', false), - array(' .', false), - ); - } - - /** - * @dataProvider dataProviderForTestIsSharingDisabledForUser - * @param array $groups existing groups - * @param array $membership groups the user belong to - * @param array $excludedGroups groups which should be excluded from sharing - * @param bool $expected expected result - */ - function testIsSharingDisabledForUser($groups, $membership, $excludedGroups, $expected) { - $config = $this->getMockBuilder('OCP\IConfig')->disableOriginalConstructor()->getMock(); - $groupManager = $this->getMockBuilder('OCP\IGroupManager')->disableOriginalConstructor()->getMock(); - $user = $this->getMockBuilder('OCP\IUser')->disableOriginalConstructor()->getMock(); - - $config - ->expects($this->at(0)) - ->method('getAppValue') - ->with('core', 'shareapi_exclude_groups', 'no') - ->will($this->returnValue('yes')); - $config - ->expects($this->at(1)) - ->method('getAppValue') - ->with('core', 'shareapi_exclude_groups_list') - ->will($this->returnValue(json_encode($excludedGroups))); - - $groupManager - ->expects($this->at(0)) - ->method('getUserGroupIds') - ->with($user) - ->will($this->returnValue($membership)); - - $result = \OC_Util::isSharingDisabledForUser($config, $groupManager, $user); - - $this->assertSame($expected, $result); - } - - public function dataProviderForTestIsSharingDisabledForUser() { - return array( - // existing groups, groups the user belong to, groups excluded from sharing, expected result - array(array('g1', 'g2', 'g3'), array(), array('g1'), false), - array(array('g1', 'g2', 'g3'), array(), array(), false), - array(array('g1', 'g2', 'g3'), array('g2'), array('g1'), false), - array(array('g1', 'g2', 'g3'), array('g2'), array(), false), - array(array('g1', 'g2', 'g3'), array('g1', 'g2'), array('g1'), false), - array(array('g1', 'g2', 'g3'), array('g1', 'g2'), array('g1', 'g2'), true), - array(array('g1', 'g2', 'g3'), array('g1', 'g2'), array('g1', 'g2', 'g3'), true), - ); - } - - /** - * Test default apps - * - * @dataProvider defaultAppsProvider - */ - function testDefaultApps($defaultAppConfig, $expectedPath, $enabledApps) { - $oldDefaultApps = \OCP\Config::getSystemValue('core', 'defaultapp', ''); - // CLI is doing messy stuff with the webroot, so need to work it around - $oldWebRoot = \OC::$WEBROOT; - \OC::$WEBROOT = ''; - - $appManager = $this->getMock('\OCP\App\IAppManager'); - $appManager->expects($this->any()) - ->method('isEnabledForUser') - ->will($this->returnCallback(function($appId) use ($enabledApps){ - return in_array($appId, $enabledApps); - })); - Dummy_OC_Util::$appManager = $appManager; - - // need to set a user id to make sure enabled apps are read from cache - \OC_User::setUserId($this->getUniqueID()); - \OCP\Config::setSystemValue('defaultapp', $defaultAppConfig); - $this->assertEquals('http://localhost/' . $expectedPath, Dummy_OC_Util::getDefaultPageUrl()); - - // restore old state - \OC::$WEBROOT = $oldWebRoot; - \OCP\Config::setSystemValue('defaultapp', $oldDefaultApps); - \OC_User::setUserId(null); - } - - function defaultAppsProvider() { - return array( - // none specified, default to files - array( - '', - 'index.php/apps/files/', - array('files'), - ), - // unexisting or inaccessible app specified, default to files - array( - 'unexist', - 'index.php/apps/files/', - array('files'), - ), - // non-standard app - array( - 'calendar', - 'index.php/apps/calendar/', - array('files', 'calendar'), - ), - // non-standard app with fallback - array( - 'contacts,calendar', - 'index.php/apps/calendar/', - array('files', 'calendar'), - ), - ); - } - - public function testGetDefaultPageUrlWithRedirectUrlWithoutFrontController() { - putenv('front_controller_active=false'); - - $_REQUEST['redirect_url'] = 'myRedirectUrl.com'; - $this->assertSame('http://localhost'.\OC::$WEBROOT.'/myRedirectUrl.com', OC_Util::getDefaultPageUrl()); - } - - public function testGetDefaultPageUrlWithRedirectUrlRedirectBypassWithoutFrontController() { - putenv('front_controller_active=false'); - - $_REQUEST['redirect_url'] = 'myRedirectUrl.com@foo.com:a'; - $this->assertSame('http://localhost'.\OC::$WEBROOT.'/index.php/apps/files/', OC_Util::getDefaultPageUrl()); - } - - public function testGetDefaultPageUrlWithRedirectUrlRedirectBypassWithFrontController() { - putenv('front_controller_active=true'); - $_REQUEST['redirect_url'] = 'myRedirectUrl.com@foo.com:a'; - $this->assertSame('http://localhost'.\OC::$WEBROOT.'/apps/files/', OC_Util::getDefaultPageUrl()); - } - - /** - * Test needUpgrade() when the core version is increased - */ - public function testNeedUpgradeCore() { - $config = \OC::$server->getConfig(); - $oldConfigVersion = $config->getSystemValue('version', '0.0.0'); - $oldSessionVersion = \OC::$server->getSession()->get('OC_Version'); - - $this->assertFalse(\OCP\Util::needUpgrade()); - - $config->setSystemValue('version', '7.0.0.0'); - \OC::$server->getSession()->set('OC_Version', array(7, 0, 0, 1)); - self::invokePrivate(new \OCP\Util, 'needUpgradeCache', array(null)); - - $this->assertTrue(\OCP\Util::needUpgrade()); - - $config->setSystemValue('version', $oldConfigVersion); - \OC::$server->getSession()->set('OC_Version', $oldSessionVersion); - self::invokePrivate(new \OCP\Util, 'needUpgradeCache', array(null)); - - $this->assertFalse(\OCP\Util::needUpgrade()); - } - - public function testCheckDataDirectoryValidity() { - $dataDir = \OCP\Files::tmpFolder(); - touch($dataDir . '/.ocdata'); - $errors = \OC_Util::checkDataDirectoryValidity($dataDir); - $this->assertEmpty($errors); - \OCP\Files::rmdirr($dataDir); - - $dataDir = \OCP\Files::tmpFolder(); - // no touch - $errors = \OC_Util::checkDataDirectoryValidity($dataDir); - $this->assertNotEmpty($errors); - \OCP\Files::rmdirr($dataDir); - - if (!\OC_Util::runningOnWindows()) { - $errors = \OC_Util::checkDataDirectoryValidity('relative/path'); - $this->assertNotEmpty($errors); - } - } - - protected function setUp() { - parent::setUp(); - - \OC_Util::$scripts = []; - \OC_Util::$styles = []; - } - protected function tearDown() { - parent::tearDown(); - - \OC_Util::$scripts = []; - \OC_Util::$styles = []; - } - - public function testAddScript() { - \OC_Util::addScript('core', 'myFancyJSFile1'); - \OC_Util::addScript('myApp', 'myFancyJSFile2'); - \OC_Util::addScript('core', 'myFancyJSFile0', true); - \OC_Util::addScript('core', 'myFancyJSFile10', true); - // add duplicate - \OC_Util::addScript('core', 'myFancyJSFile1'); - - $this->assertEquals([ - 'core/js/myFancyJSFile10', - 'core/js/myFancyJSFile0', - 'core/js/myFancyJSFile1', - 'myApp/l10n/en', - 'myApp/js/myFancyJSFile2', - ], \OC_Util::$scripts); - $this->assertEquals([], \OC_Util::$styles); - } - - public function testAddVendorScript() { - \OC_Util::addVendorScript('core', 'myFancyJSFile1'); - \OC_Util::addVendorScript('myApp', 'myFancyJSFile2'); - \OC_Util::addVendorScript('core', 'myFancyJSFile0', true); - \OC_Util::addVendorScript('core', 'myFancyJSFile10', true); - // add duplicate - \OC_Util::addVendorScript('core', 'myFancyJSFile1'); - - $this->assertEquals([ - 'core/vendor/myFancyJSFile10', - 'core/vendor/myFancyJSFile0', - 'core/vendor/myFancyJSFile1', - 'myApp/vendor/myFancyJSFile2', - ], \OC_Util::$scripts); - $this->assertEquals([], \OC_Util::$styles); - } - - public function testAddTranslations() { - \OC_Util::addTranslations('appId', 'de'); - - $this->assertEquals([ - 'appId/l10n/de' - ], \OC_Util::$scripts); - $this->assertEquals([], \OC_Util::$styles); - } - - public function testAddStyle() { - \OC_Util::addStyle('core', 'myFancyCSSFile1'); - \OC_Util::addStyle('myApp', 'myFancyCSSFile2'); - \OC_Util::addStyle('core', 'myFancyCSSFile0', true); - \OC_Util::addStyle('core', 'myFancyCSSFile10', true); - // add duplicate - \OC_Util::addStyle('core', 'myFancyCSSFile1'); - - $this->assertEquals([], \OC_Util::$scripts); - $this->assertEquals([ - 'core/css/myFancyCSSFile10', - 'core/css/myFancyCSSFile0', - 'core/css/myFancyCSSFile1', - 'myApp/css/myFancyCSSFile2', - ], \OC_Util::$styles); - } - - public function testAddVendorStyle() { - \OC_Util::addVendorStyle('core', 'myFancyCSSFile1'); - \OC_Util::addVendorStyle('myApp', 'myFancyCSSFile2'); - \OC_Util::addVendorStyle('core', 'myFancyCSSFile0', true); - \OC_Util::addVendorStyle('core', 'myFancyCSSFile10', true); - // add duplicate - \OC_Util::addVendorStyle('core', 'myFancyCSSFile1'); - - $this->assertEquals([], \OC_Util::$scripts); - $this->assertEquals([ - 'core/vendor/myFancyCSSFile10', - 'core/vendor/myFancyCSSFile0', - 'core/vendor/myFancyCSSFile1', - 'myApp/vendor/myFancyCSSFile2', - ], \OC_Util::$styles); - } -} - -/** - * Dummy OC Util class to make it possible to override the app manager - */ -class Dummy_OC_Util extends OC_Util { - /** - * @var \OCP\App\IAppManager - */ - public static $appManager; - - protected static function getAppManager() { - return self::$appManager; - } -} diff --git a/tests/lib/utilcheckserver.php b/tests/lib/utilcheckserver.php deleted file mode 100644 index 94e7fd2f779..00000000000 --- a/tests/lib/utilcheckserver.php +++ /dev/null @@ -1,170 +0,0 @@ - - * This file is licensed under the Affero General Public License version 3 or - * later. - * See the COPYING-README file. - */ - -/** - * Tests for server check functions - * - * @group DB - */ -class Test_Util_CheckServer extends \Test\TestCase { - - private $datadir; - - /** - * @param array $systemOptions - * @return \OCP\IConfig | PHPUnit_Framework_MockObject_MockObject - */ - protected function getConfig($systemOptions) { - $systemOptions['datadirectory'] = $this->datadir; - $systemOptions['appstoreenabled'] = false; //it's likely that there is no app folder we can write in - $config = $this->getMockBuilder('\OCP\IConfig') - ->disableOriginalConstructor() - ->getMock(); - - $config->expects($this->any()) - ->method('getSystemValue') - ->will($this->returnCallback(function ($key, $default) use ($systemOptions) { - return isset($systemOptions[$key]) ? $systemOptions[$key] : $default; - })); - return $config; - } - - protected function setUp() { - parent::setUp(); - - $this->datadir = \OC::$server->getTempManager()->getTemporaryFolder(); - - file_put_contents($this->datadir . '/.ocdata', ''); - \OC::$server->getSession()->set('checkServer_succeeded', false); - } - - protected function tearDown() { - // clean up - @unlink($this->datadir . '/.ocdata'); - parent::tearDown(); - } - - /** - * Test that checkServer() returns no errors in the regular case. - */ - public function testCheckServer() { - $result = \OC_Util::checkServer($this->getConfig(array( - 'installed' => true - ))); - $this->assertEmpty($result); - } - - /** - * Test that checkServer() does not check the data dir validity - * when the server is not installed yet (else the setup cannot - * be run...) - */ - public function testCheckServerSkipDataDirValidityOnSetup() { - // simulate old version that didn't have it - unlink($this->datadir . '/.ocdata'); - - // even though ".ocdata" is missing, the error isn't - // triggered to allow setup to run - $result = \OC_Util::checkServer($this->getConfig(array( - 'installed' => false - ))); - $this->assertEmpty($result); - } - - /** - * Test that checkServer() does not check the data dir validity - * when an upgrade is required (else the upgrade cannot be - * performed...) - */ - public function testCheckServerSkipDataDirValidityOnUpgrade() { - // simulate old version that didn't have it - unlink($this->datadir . '/.ocdata'); - - $session = \OC::$server->getSession(); - $oldCurrentVersion = $session->get('OC_Version'); - - // upgrade condition to simulate needUpgrade() === true - $session->set('OC_Version', array(6, 0, 0, 2)); - - // even though ".ocdata" is missing, the error isn't - // triggered to allow for upgrade - $result = \OC_Util::checkServer($this->getConfig(array( - 'installed' => true, - 'version' => '6.0.0.1' - ))); - $this->assertEmpty($result); - - // restore versions - $session->set('OC_Version', $oldCurrentVersion); - } - - /** - * Test that checkDataDirectoryValidity returns no error - * when ".ocdata" is present. - */ - public function testCheckDataDirValidity() { - $result = \OC_Util::checkDataDirectoryValidity($this->datadir); - $this->assertEmpty($result); - } - - /** - * Test that checkDataDirectoryValidity and checkServer - * both return an error when ".ocdata" is missing. - */ - public function testCheckDataDirValidityWhenFileMissing() { - unlink($this->datadir . '/.ocdata'); - $result = \OC_Util::checkDataDirectoryValidity($this->datadir); - $this->assertEquals(1, count($result)); - - $result = \OC_Util::checkServer($this->getConfig(array( - 'installed' => true, - 'version' => implode('.', \OCP\Util::getVersion()) - ))); - $this->assertCount(1, $result); - } - - /** - * Tests that no error is given when the datadir is writable - */ - public function testDataDirWritable() { - $result = \OC_Util::checkServer($this->getConfig(array( - 'installed' => true, - 'version' => implode('.', \OCP\Util::getVersion()) - ))); - $this->assertEmpty($result); - } - - /** - * Tests an error is given when the datadir is not writable - */ - public function testDataDirNotWritable() { - if (\OC_Util::runningOnWindows()) { - $this->markTestSkipped('[Windows] chmod() does not work as intended on Windows.'); - } - - chmod($this->datadir, 0300); - $result = \OC_Util::checkServer($this->getConfig(array( - 'installed' => true, - 'version' => implode('.', \OCP\Util::getVersion()) - ))); - $this->assertCount(1, $result); - } - - /** - * Tests no error is given when the datadir is not writable during setup - */ - public function testDataDirNotWritableSetup() { - chmod($this->datadir, 0300); - $result = \OC_Util::checkServer($this->getConfig(array( - 'installed' => false, - 'version' => implode('.', \OCP\Util::getVersion()) - ))); - chmod($this->datadir, 0700); //needed for cleanup - $this->assertEmpty($result); - } -} -- cgit v1.2.3 From e823d5004457e4bf9fcf343e352169c7fa6a8151 Mon Sep 17 00:00:00 2001 From: Joas Schilling Date: Thu, 19 May 2016 09:40:34 +0200 Subject: Fix "Class 'Test\Security\DateTime' not found" --- tests/lib/security/CertificateTest.php | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) (limited to 'tests') diff --git a/tests/lib/security/CertificateTest.php b/tests/lib/security/CertificateTest.php index 888a4ba1f13..6f7d7d4a37f 100644 --- a/tests/lib/security/CertificateTest.php +++ b/tests/lib/security/CertificateTest.php @@ -76,18 +76,18 @@ class CertificateTest extends \Test\TestCase { } public function testGetIssueDate() { - $expected = new DateTime('2015-08-27 20:03:42 GMT'); + $expected = new \DateTime('2015-08-27 20:03:42 GMT'); $this->assertEquals($expected->getTimestamp(), $this->goodCertificate->getIssueDate()->getTimestamp()); - $expected = new DateTime('2015-08-27 20:19:13 GMT'); + $expected = new \DateTime('2015-08-27 20:19:13 GMT'); $this->assertEquals($expected->getTimestamp(), $this->invalidCertificate->getIssueDate()->getTimestamp()); } public function testGetExpireDate() { - $expected = new DateTime('2025-08-24 20:03:42 GMT'); + $expected = new \DateTime('2025-08-24 20:03:42 GMT'); $this->assertEquals($expected->getTimestamp(), $this->goodCertificate->getExpireDate()->getTimestamp()); - $expected = new DateTime('2025-08-24 20:19:13 GMT'); + $expected = new \DateTime('2025-08-24 20:19:13 GMT'); $this->assertEquals($expected->getTimestamp(), $this->invalidCertificate->getExpireDate()->getTimestamp()); - $expected = new DateTime('2014-08-28 09:12:43 GMT'); + $expected = new \DateTime('2014-08-28 09:12:43 GMT'); $this->assertEquals($expected->getTimestamp(), $this->expiredCertificate->getExpireDate()->getTimestamp()); } -- cgit v1.2.3 From e88a9b2fed7e395bb80c87d837fc688b74dc667e Mon Sep 17 00:00:00 2001 From: Joas Schilling Date: Thu, 19 May 2016 09:41:45 +0200 Subject: Fix missing backtick before OC --- tests/lib/StreamWrappersTest.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'tests') diff --git a/tests/lib/StreamWrappersTest.php b/tests/lib/StreamWrappersTest.php index 14bcbb847d9..a378f975fde 100644 --- a/tests/lib/StreamWrappersTest.php +++ b/tests/lib/StreamWrappersTest.php @@ -56,7 +56,7 @@ class StreamWrappersTest extends \Test\TestCase { public function testCloseStream() { //ensure all basic stream stuff works - $sourceFile = OC::$SERVERROOT . '/tests/data/lorem.txt'; + $sourceFile = \OC::$SERVERROOT . '/tests/data/lorem.txt'; $tmpFile = \OC::$server->getTempManager()->getTemporaryFile('.txt'); $file = 'close://' . $tmpFile; $this->assertTrue(file_exists($file)); -- cgit v1.2.3 From f24179a327c102d6ed7687d0445ac042ff2b373e Mon Sep 17 00:00:00 2001 From: Joas Schilling Date: Thu, 19 May 2016 09:44:53 +0200 Subject: Fix deprecated private method --- tests/lib/files/view.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'tests') diff --git a/tests/lib/files/view.php b/tests/lib/files/view.php index 86413c61aa1..d33c9f31503 100644 --- a/tests/lib/files/view.php +++ b/tests/lib/files/view.php @@ -1508,7 +1508,7 @@ class View extends \Test\TestCase { $defaultView = new \OC\Files\View('/foo/files'); $defaultRootValue->setValue($defaultView); $view = new \OC\Files\View($root); - $result = \Test_Helper::invokePrivate($view, 'shouldEmitHooks', [$path]); + $result = $this->invokePrivate($view, 'shouldEmitHooks', [$path]); $defaultRootValue->setValue($oldRoot); $this->assertEquals($shouldEmit, $result); } @@ -1872,7 +1872,7 @@ class View extends \Test\TestCase { $this->assertEquals(ILockingProvider::LOCK_SHARED, $lockTypePre, 'File locked properly during pre-hook'); $this->assertEquals(ILockingProvider::LOCK_EXCLUSIVE, $lockTypeDuring, 'File locked properly during operation'); - $this->assertNull(null, $lockTypePost, 'No post hook, no lock check possible'); + $this->assertNull($lockTypePost, 'No post hook, no lock check possible'); $this->assertEquals(ILockingProvider::LOCK_EXCLUSIVE, $lockTypeDuring, 'File still locked after fopen'); -- cgit v1.2.3 From 320b1c3abf28b7770661d0dd8dbbdda356022b4b Mon Sep 17 00:00:00 2001 From: Joas Schilling Date: Thu, 19 May 2016 10:11:42 +0200 Subject: Fix more failures --- apps/files_sharing/tests/deleteorphanedsharesjobtest.php | 2 +- apps/files_sharing/tests/server2server.php | 2 +- tests/lib/TagsTest.php | 2 +- tests/lib/share/share.php | 4 ++-- 4 files changed, 5 insertions(+), 5 deletions(-) (limited to 'tests') diff --git a/apps/files_sharing/tests/deleteorphanedsharesjobtest.php b/apps/files_sharing/tests/deleteorphanedsharesjobtest.php index 353520bd604..c9aea60d255 100644 --- a/apps/files_sharing/tests/deleteorphanedsharesjobtest.php +++ b/apps/files_sharing/tests/deleteorphanedsharesjobtest.php @@ -154,7 +154,7 @@ class DeleteOrphanedSharesJobTest extends \Test\TestCase { public function testKeepNonFileShares() { $this->loginAsUser($this->user1); - \OCP\Share::registerBackend('test', 'Test_Share_Backend'); + \OCP\Share::registerBackend('test', 'Test\Share\Backend'); $this->assertTrue( \OCP\Share::shareItem('test', 'test.txt', \OCP\Share::SHARE_TYPE_USER, $this->user2, \OCP\Constants::PERMISSION_READ), diff --git a/apps/files_sharing/tests/server2server.php b/apps/files_sharing/tests/server2server.php index 1d047916ca9..1c8b5ed7a17 100644 --- a/apps/files_sharing/tests/server2server.php +++ b/apps/files_sharing/tests/server2server.php @@ -51,7 +51,7 @@ class Test_Files_Sharing_S2S_OCS_API extends TestCase { parent::setUp(); self::loginHelper(self::TEST_FILES_SHARING_API_USER1); - \OCP\Share::registerBackend('test', 'Test_Share_Backend'); + \OCP\Share::registerBackend('test', 'Test\Share\Backend'); $config = $this->getMockBuilder('\OCP\IConfig') ->disableOriginalConstructor()->getMock(); diff --git a/tests/lib/TagsTest.php b/tests/lib/TagsTest.php index 88e0f87ad8f..2662c209d2c 100644 --- a/tests/lib/TagsTest.php +++ b/tests/lib/TagsTest.php @@ -286,7 +286,7 @@ class TagsTest extends \Test\TestCase { public function testShareTags() { $testTag = 'TestTag'; - \OCP\Share::registerBackend('test', 'Test_Share_Backend'); + \OCP\Share::registerBackend('test', 'Test\Share\Backend'); $tagger = $this->tagMgr->load('test'); $tagger->tagAs(1, $testTag); diff --git a/tests/lib/share/share.php b/tests/lib/share/share.php index e8240fb6738..355005bb586 100644 --- a/tests/lib/share/share.php +++ b/tests/lib/share/share.php @@ -78,7 +78,7 @@ class Share extends \Test\TestCase { \OC_Group::addToGroup($this->user4, $this->group2); \OC_Group::addToGroup($this->user2, $this->groupAndUser); \OC_Group::addToGroup($this->user3, $this->groupAndUser); - \OCP\Share::registerBackend('test', 'Test_Share_Backend'); + \OCP\Share::registerBackend('test', 'Test\Share\Backend'); \OC_Hook::clear('OCP\\Share'); \OC::registerShareHooks(); $this->resharing = \OC::$server->getAppConfig()->getValue('core', 'shareapi_allow_resharing', 'yes'); @@ -92,7 +92,7 @@ class Share extends \Test\TestCase { } protected function tearDown() { - $query = OC_DB::prepare('DELETE FROM `*PREFIX*share` WHERE `item_type` = ?'); + $query = \OC_DB::prepare('DELETE FROM `*PREFIX*share` WHERE `item_type` = ?'); $query->execute(array('test')); \OC::$server->getAppConfig()->setValue('core', 'shareapi_allow_resharing', $this->resharing); -- cgit v1.2.3 From bae4118b4fe08c22cf3a12236705d09423a37b8b Mon Sep 17 00:00:00 2001 From: Joas Schilling Date: Thu, 19 May 2016 10:33:12 +0200 Subject: Fix renamed class --- tests/lib/user/user.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'tests') diff --git a/tests/lib/user/user.php b/tests/lib/user/user.php index 0a972f7bdaa..71be3691003 100644 --- a/tests/lib/user/user.php +++ b/tests/lib/user/user.php @@ -121,7 +121,7 @@ class User extends \Test\TestCase { * @var \OC\User\Backend | \PHPUnit_Framework_MockObject_MockObject $backend */ require_once 'avataruserdummy.php'; - $backend = $this->getMock('Avatar_User_Dummy'); + $backend = $this->getMock('Test\User\AvatarUserDummy'); $backend->expects($this->once()) ->method('canChangeAvatar') ->with($this->equalTo('foo')) @@ -146,7 +146,7 @@ class User extends \Test\TestCase { * @var \OC\User\Backend | \PHPUnit_Framework_MockObject_MockObject $backend */ require_once 'avataruserdummy.php'; - $backend = $this->getMock('Avatar_User_Dummy'); + $backend = $this->getMock('Test\User\AvatarUserDummy'); $backend->expects($this->once()) ->method('canChangeAvatar') ->with($this->equalTo('foo')) @@ -171,7 +171,7 @@ class User extends \Test\TestCase { * @var \OC\User\Backend | \PHPUnit_Framework_MockObject_MockObject $backend */ require_once 'avataruserdummy.php'; - $backend = $this->getMock('Avatar_User_Dummy'); + $backend = $this->getMock('Test\User\AvatarUserDummy'); $backend->expects($this->never()) ->method('canChangeAvatar'); -- cgit v1.2.3