summaryrefslogtreecommitdiffstats
path: root/tests
diff options
context:
space:
mode:
Diffstat (limited to 'tests')
-rw-r--r--tests/lib/activitymanager.php103
-rw-r--r--tests/lib/encryption/keys/storage.php16
-rw-r--r--tests/lib/files/cache/updater.php82
-rw-r--r--tests/lib/files/cache/updaterlegacy.php10
-rw-r--r--tests/lib/files/cache/watcher.php10
-rw-r--r--tests/lib/files/etagtest.php17
-rw-r--r--tests/lib/files/filesystem.php34
-rw-r--r--tests/lib/files/mount/mountpoint.php4
-rw-r--r--tests/lib/files/node/integration.php19
-rw-r--r--tests/lib/files/storage/wrapper/encryption.php15
-rw-r--r--tests/lib/files/stream/encryption.php5
-rw-r--r--tests/lib/files/utils/scanner.php8
-rw-r--r--tests/lib/files/view.php100
-rw-r--r--tests/lib/group/manager.php22
-rw-r--r--tests/lib/mail/message.php17
-rw-r--r--tests/lib/ocsclienttest.php979
-rw-r--r--tests/lib/preview.php56
-rw-r--r--tests/lib/repair/repairlegacystorage.php74
-rw-r--r--tests/lib/share/MailNotificationsTest.php237
-rw-r--r--tests/lib/share/share.php241
-rw-r--r--tests/lib/streamwrappers.php2
-rw-r--r--tests/lib/testcase.php4
-rw-r--r--tests/settings/controller/AppSettingsControllerTest.php231
23 files changed, 2138 insertions, 148 deletions
diff --git a/tests/lib/activitymanager.php b/tests/lib/activitymanager.php
index d227c05d827..d3263fa2ede 100644
--- a/tests/lib/activitymanager.php
+++ b/tests/lib/activitymanager.php
@@ -13,10 +13,34 @@ class Test_ActivityManager extends \Test\TestCase {
/** @var \OC\ActivityManager */
private $activityManager;
+ /** @var \PHPUnit_Framework_MockObject_MockObject */
+ protected $request;
+
+ /** @var \PHPUnit_Framework_MockObject_MockObject */
+ protected $session;
+
+ /** @var \PHPUnit_Framework_MockObject_MockObject */
+ protected $config;
+
protected function setUp() {
parent::setUp();
- $this->activityManager = new \OC\ActivityManager();
+ $this->request = $this->getMockBuilder('OCP\IRequest')
+ ->disableOriginalConstructor()
+ ->getMock();
+ $this->session = $this->getMockBuilder('OCP\IUserSession')
+ ->disableOriginalConstructor()
+ ->getMock();
+ $this->config = $this->getMockBuilder('OCP\IConfig')
+ ->disableOriginalConstructor()
+ ->getMock();
+
+ $this->activityManager = new \OC\ActivityManager(
+ $this->request,
+ $this->session,
+ $this->config
+ );
+
$this->activityManager->registerExtension(function() {
return new NoOpExtension();
});
@@ -111,6 +135,83 @@ class Test_ActivityManager extends \Test\TestCase {
$result = $this->activityManager->getQueryForFilter('InvalidFilter');
$this->assertEquals(array(null, null), $result);
}
+
+ public function getUserFromTokenThrowInvalidTokenData() {
+ return [
+ [null, []],
+ ['', []],
+ ['12345678901234567890123456789', []],
+ ['1234567890123456789012345678901', []],
+ ['123456789012345678901234567890', []],
+ ['123456789012345678901234567890', ['user1', 'user2']],
+ ];
+ }
+
+ /**
+ * @expectedException \UnexpectedValueException
+ * @dataProvider getUserFromTokenThrowInvalidTokenData
+ *
+ * @param string $token
+ * @param array $users
+ */
+ public function testGetUserFromTokenThrowInvalidToken($token, $users) {
+ $this->mockRSSToken($token, $token, $users);
+ \Test_Helper::invokePrivate($this->activityManager, 'getUserFromToken');
+ }
+
+ public function getUserFromTokenData() {
+ return [
+ [null, '123456789012345678901234567890', 'user1'],
+ ['user2', null, 'user2'],
+ ['user2', '123456789012345678901234567890', 'user2'],
+ ];
+ }
+
+ /**
+ * @dataProvider getUserFromTokenData
+ *
+ * @param string $userLoggedIn
+ * @param string $token
+ * @param string $expected
+ */
+ public function testGetUserFromToken($userLoggedIn, $token, $expected) {
+ if ($userLoggedIn !== null) {
+ $this->mockUserSession($userLoggedIn);
+ }
+ $this->mockRSSToken($token, '123456789012345678901234567890', ['user1']);
+
+ $this->assertEquals($expected, $this->activityManager->getCurrentUserId());
+ }
+
+ protected function mockRSSToken($requestToken, $userToken, $users) {
+ if ($requestToken !== null) {
+ $this->request->expects($this->any())
+ ->method('getParam')
+ ->with('token', '')
+ ->willReturn($requestToken);
+ }
+
+ $this->config->expects($this->any())
+ ->method('getUsersForUserValue')
+ ->with('activity', 'rsstoken', $userToken)
+ ->willReturn($users);
+ }
+
+ protected function mockUserSession($user) {
+ $mockUser = $this->getMockBuilder('\OCP\IUser')
+ ->disableOriginalConstructor()
+ ->getMock();
+ $mockUser->expects($this->any())
+ ->method('getUID')
+ ->willReturn($user);
+
+ $this->session->expects($this->any())
+ ->method('isLoggedIn')
+ ->willReturn(true);
+ $this->session->expects($this->any())
+ ->method('getUser')
+ ->willReturn($mockUser);
+ }
}
class SimpleExtension implements \OCP\Activity\IExtension {
diff --git a/tests/lib/encryption/keys/storage.php b/tests/lib/encryption/keys/storage.php
index 8ab46987f8c..bcf1c0f7624 100644
--- a/tests/lib/encryption/keys/storage.php
+++ b/tests/lib/encryption/keys/storage.php
@@ -198,6 +198,10 @@ class StorageTest extends TestCase {
public function testDeleteUserKey() {
$this->view->expects($this->once())
+ ->method('file_exists')
+ ->with($this->equalTo('/user1/files_encryption/encModule/user1.publicKey'))
+ ->willReturn(true);
+ $this->view->expects($this->once())
->method('unlink')
->with($this->equalTo('/user1/files_encryption/encModule/user1.publicKey'))
->willReturn(true);
@@ -209,6 +213,10 @@ class StorageTest extends TestCase {
public function testDeleteSystemUserKey() {
$this->view->expects($this->once())
+ ->method('file_exists')
+ ->with($this->equalTo('/files_encryption/encModule/shareKey_56884'))
+ ->willReturn(true);
+ $this->view->expects($this->once())
->method('unlink')
->with($this->equalTo('/files_encryption/encModule/shareKey_56884'))
->willReturn(true);
@@ -229,6 +237,10 @@ class StorageTest extends TestCase {
->method('isSystemWideMountPoint')
->willReturn(true);
$this->view->expects($this->once())
+ ->method('file_exists')
+ ->with($this->equalTo('/files_encryption/keys/files/foo.txt/encModule/fileKey'))
+ ->willReturn(true);
+ $this->view->expects($this->once())
->method('unlink')
->with($this->equalTo('/files_encryption/keys/files/foo.txt/encModule/fileKey'))
->willReturn(true);
@@ -249,6 +261,10 @@ class StorageTest extends TestCase {
->method('isSystemWideMountPoint')
->willReturn(false);
$this->view->expects($this->once())
+ ->method('file_exists')
+ ->with($this->equalTo('/user1/files_encryption/keys/files/foo.txt/encModule/fileKey'))
+ ->willReturn(true);
+ $this->view->expects($this->once())
->method('unlink')
->with($this->equalTo('/user1/files_encryption/keys/files/foo.txt/encModule/fileKey'))
->willReturn(true);
diff --git a/tests/lib/files/cache/updater.php b/tests/lib/files/cache/updater.php
index 970af2e68df..726ee360479 100644
--- a/tests/lib/files/cache/updater.php
+++ b/tests/lib/files/cache/updater.php
@@ -33,16 +33,12 @@ class Updater extends \Test\TestCase {
*/
protected $updater;
- /** @var \OC\Files\Storage\Storage */
- private $originalStorage;
-
protected function setUp() {
parent::setUp();
- $this->originalStorage = Filesystem::getStorage('/');
+ $this->loginAsUser();
$this->storage = new Temporary(array());
- Filesystem::clearMounts();
Filesystem::mount($this->storage, array(), '/');
$this->view = new View('');
$this->updater = new \OC\Files\Cache\Updater($this->view);
@@ -51,8 +47,8 @@ class Updater extends \Test\TestCase {
protected function tearDown() {
Filesystem::clearMounts();
- Filesystem::mount($this->originalStorage, array(), '/');
+ $this->logout();
parent::tearDown();
}
@@ -176,4 +172,78 @@ class Updater extends \Test\TestCase {
$this->assertTrue($this->cache->inCache('foo.txt'));
$this->assertFalse($this->cache->inCache('bar.txt'));
}
+
+ public function testMoveCrossStorage() {
+ $storage2 = new Temporary(array());
+ $cache2 = $storage2->getCache();
+ Filesystem::mount($storage2, array(), '/bar');
+ $this->storage->file_put_contents('foo.txt', 'qwerty');
+
+ $this->updater->update('foo.txt');
+
+ $this->assertTrue($this->cache->inCache('foo.txt'));
+ $this->assertFalse($cache2->inCache('bar.txt'));
+ $cached = $this->cache->get('foo.txt');
+
+ // "rename"
+ $storage2->file_put_contents('bar.txt', 'qwerty');
+ $this->storage->unlink('foo.txt');
+
+ $this->assertTrue($this->cache->inCache('foo.txt'));
+ $this->assertFalse($cache2->inCache('bar.txt'));
+
+ $this->updater->rename('foo.txt', 'bar/bar.txt');
+
+ $this->assertFalse($this->cache->inCache('foo.txt'));
+ $this->assertTrue($cache2->inCache('bar.txt'));
+
+ $cachedTarget = $cache2->get('bar.txt');
+ $this->assertEquals($cached['mtime'], $cachedTarget['mtime']);
+ $this->assertEquals($cached['size'], $cachedTarget['size']);
+ $this->assertEquals($cached['etag'], $cachedTarget['etag']);
+ $this->assertEquals($cached['fileid'], $cachedTarget['fileid']);
+ }
+
+ public function testMoveFolderCrossStorage() {
+ $storage2 = new Temporary(array());
+ $cache2 = $storage2->getCache();
+ Filesystem::mount($storage2, array(), '/bar');
+ $this->storage->mkdir('foo');
+ $this->storage->mkdir('foo/bar');
+ $this->storage->file_put_contents('foo/foo.txt', 'qwerty');
+ $this->storage->file_put_contents('foo/bar.txt', 'foo');
+ $this->storage->file_put_contents('foo/bar/bar.txt', 'qwertyuiop');
+
+ $this->storage->getScanner()->scan('');
+
+ $this->assertTrue($this->cache->inCache('foo/foo.txt'));
+ $this->assertTrue($this->cache->inCache('foo/bar.txt'));
+ $this->assertTrue($this->cache->inCache('foo/bar/bar.txt'));
+ $cached = [];
+ $cached[] = $this->cache->get('foo/foo.txt');
+ $cached[] = $this->cache->get('foo/bar.txt');
+ $cached[] = $this->cache->get('foo/bar/bar.txt');
+
+ $this->view->rename('/foo', '/bar/foo');
+
+ $this->assertFalse($this->cache->inCache('foo/foo.txt'));
+ $this->assertFalse($this->cache->inCache('foo/bar.txt'));
+ $this->assertFalse($this->cache->inCache('foo/bar/bar.txt'));
+ $this->assertTrue($cache2->inCache('foo/foo.txt'));
+ $this->assertTrue($cache2->inCache('foo/bar.txt'));
+ $this->assertTrue($cache2->inCache('foo/bar/bar.txt'));
+
+ $cachedTarget = [];
+ $cachedTarget[] = $cache2->get('foo/foo.txt');
+ $cachedTarget[] = $cache2->get('foo/bar.txt');
+ $cachedTarget[] = $cache2->get('foo/bar/bar.txt');
+
+ foreach ($cached as $i => $old) {
+ $new = $cachedTarget[$i];
+ $this->assertEquals($old['mtime'], $new['mtime']);
+ $this->assertEquals($old['size'], $new['size']);
+ $this->assertEquals($old['etag'], $new['etag']);
+ $this->assertEquals($old['fileid'], $new['fileid']);
+ }
+ }
}
diff --git a/tests/lib/files/cache/updaterlegacy.php b/tests/lib/files/cache/updaterlegacy.php
index 6bdacbe34fe..f4d52e9a390 100644
--- a/tests/lib/files/cache/updaterlegacy.php
+++ b/tests/lib/files/cache/updaterlegacy.php
@@ -27,9 +27,6 @@ class UpdaterLegacy extends \Test\TestCase {
*/
private $cache;
- /** @var \OC\Files\Storage\Storage */
- private $originalStorage;
-
private static $user;
protected function setUp() {
@@ -48,14 +45,12 @@ class UpdaterLegacy extends \Test\TestCase {
$this->scanner->scan('');
$this->cache = $this->storage->getCache();
- $this->originalStorage = Filesystem::getStorage('/');
- Filesystem::tearDown();
if (!self::$user) {
self::$user = $this->getUniqueID();
}
\OC_User::createUser(self::$user, 'password');
- \OC_User::setUserId(self::$user);
+ $this->loginAsUser(self::$user);
Filesystem::init(self::$user, '/' . self::$user . '/files');
@@ -71,9 +66,8 @@ class UpdaterLegacy extends \Test\TestCase {
}
$result = \OC_User::deleteUser(self::$user);
$this->assertTrue($result);
- Filesystem::tearDown();
- Filesystem::mount($this->originalStorage, array(), '/');
+ $this->logout();
parent::tearDown();
}
diff --git a/tests/lib/files/cache/watcher.php b/tests/lib/files/cache/watcher.php
index ee605c64e01..e6947e36a17 100644
--- a/tests/lib/files/cache/watcher.php
+++ b/tests/lib/files/cache/watcher.php
@@ -15,14 +15,10 @@ class Watcher extends \Test\TestCase {
*/
private $storages = array();
- /** @var \OC\Files\Storage\Storage */
- private $originalStorage;
-
protected function setUp() {
parent::setUp();
- $this->originalStorage = \OC\Files\Filesystem::getStorage('/');
- \OC\Files\Filesystem::clearMounts();
+ $this->loginAsUser();
}
protected function tearDown() {
@@ -32,9 +28,7 @@ class Watcher extends \Test\TestCase {
$cache->clear();
}
- \OC\Files\Filesystem::clearMounts();
- \OC\Files\Filesystem::mount($this->originalStorage, array(), '/');
-
+ $this->logout();
parent::tearDown();
}
diff --git a/tests/lib/files/etagtest.php b/tests/lib/files/etagtest.php
index eec24d9f4c6..055927652bc 100644
--- a/tests/lib/files/etagtest.php
+++ b/tests/lib/files/etagtest.php
@@ -16,16 +16,11 @@ class EtagTest extends \Test\TestCase {
private $tmpDir;
- private $uid;
-
/**
* @var \OC_User_Dummy $userBackend
*/
private $userBackend;
- /** @var \OC\Files\Storage\Storage */
- private $originalStorage;
-
protected function setUp() {
parent::setUp();
@@ -37,21 +32,15 @@ class EtagTest extends \Test\TestCase {
$this->datadir = \OC_Config::getValue('datadirectory');
$this->tmpDir = \OC_Helper::tmpFolder();
\OC_Config::setValue('datadirectory', $this->tmpDir);
- $this->uid = \OC_User::getUser();
- \OC_User::setUserId(null);
$this->userBackend = new \OC_User_Dummy();
\OC_User::useBackend($this->userBackend);
- $this->originalStorage = \OC\Files\Filesystem::getStorage('/');
- \OC_Util::tearDownFS();
}
protected function tearDown() {
\OC_Config::setValue('datadirectory', $this->datadir);
- \OC_User::setUserId($this->uid);
- \OC_Util::setupFS($this->uid);
- \OC\Files\Filesystem::mount($this->originalStorage, array(), '/');
+ $this->logout();
parent::tearDown();
}
@@ -59,9 +48,7 @@ class EtagTest extends \Test\TestCase {
$user1 = $this->getUniqueID('user_');
$this->userBackend->createUser($user1, '');
- \OC_Util::tearDownFS();
- \OC_User::setUserId($user1);
- \OC_Util::setupFS($user1);
+ $this->loginAsUser($user1);
Filesystem::mkdir('/folder');
Filesystem::mkdir('/folder/subfolder');
Filesystem::file_put_contents('/foo.txt', 'asd');
diff --git a/tests/lib/files/filesystem.php b/tests/lib/files/filesystem.php
index 7bf59315d77..082d22781fa 100644
--- a/tests/lib/files/filesystem.php
+++ b/tests/lib/files/filesystem.php
@@ -22,15 +22,17 @@
namespace Test\Files;
+use OC\User\NoUserException;
+
class Filesystem extends \Test\TestCase {
+
+ const TEST_FILESYSTEM_USER1 = "test-filesystem-user1";
+
/**
* @var array tmpDirs
*/
private $tmpDirs = array();
- /** @var \OC\Files\Storage\Storage */
- private $originalStorage;
-
/**
* @return array
*/
@@ -42,20 +44,15 @@ class Filesystem extends \Test\TestCase {
protected function setUp() {
parent::setUp();
-
- $this->originalStorage = \OC\Files\Filesystem::getStorage('/');
- \OC_User::setUserId('');
- \OC\Files\Filesystem::clearMounts();
+ $this->loginAsUser();
}
protected function tearDown() {
foreach ($this->tmpDirs as $dir) {
\OC_Helper::rmdirr($dir);
}
- \OC\Files\Filesystem::clearMounts();
- \OC\Files\Filesystem::mount($this->originalStorage, array(), '/');
- \OC_User::setUserId('');
+ $this->logout();
parent::tearDown();
}
@@ -244,8 +241,14 @@ class Filesystem extends \Test\TestCase {
if (\OC\Files\Filesystem::getView()) {
$user = \OC_User::getUser();
} else {
- $user = $this->getUniqueID();
+ $user = self::TEST_FILESYSTEM_USER1;
+ $backend = new \OC_User_Dummy();
+ \OC_User::useBackend($backend);
+ $backend->createUser($user, $user);
+ $userObj = \OC::$server->getUserManager()->get($user);
+ \OC::$server->getUserSession()->setUser($userObj);
\OC\Files\Filesystem::init($user, '/' . $user . '/files');
+
}
\OC_Hook::clear('OC_Filesystem');
\OC_Hook::connect('OC_Filesystem', 'post_write', $this, 'dummyHook');
@@ -267,19 +270,14 @@ class Filesystem extends \Test\TestCase {
}
/**
- * Tests that a local storage mount is used when passed user
- * does not exist.
+ * Tests that an exception is thrown when passed user does not exist.
+ * @expectedException \OC\User\NoUserException
*/
public function testLocalMountWhenUserDoesNotExist() {
$datadir = \OC_Config::getValue("datadirectory", \OC::$SERVERROOT . "/data");
$userId = $this->getUniqueID('user_');
\OC\Files\Filesystem::initMountPoints($userId);
-
- $homeMount = \OC\Files\Filesystem::getStorage('/' . $userId . '/');
-
- $this->assertTrue($homeMount->instanceOfStorage('\OC\Files\Storage\Local'));
- $this->assertEquals('local::' . $datadir . '/' . $userId . '/', $homeMount->getId());
}
/**
diff --git a/tests/lib/files/mount/mountpoint.php b/tests/lib/files/mount/mountpoint.php
index 5a9c6de3e0a..29610e6058d 100644
--- a/tests/lib/files/mount/mountpoint.php
+++ b/tests/lib/files/mount/mountpoint.php
@@ -31,6 +31,10 @@ class MountPoint extends \Test\TestCase {
$this->assertEquals($storage, $mountPoint->getStorage());
$this->assertEquals(123, $mountPoint->getStorageId());
+ $this->assertEquals('/mountpoint/', $mountPoint->getMountPoint());
+
+ $mountPoint->setMountPoint('another');
+ $this->assertEquals('/another/', $mountPoint->getMountPoint());
}
public function testInvalidStorage() {
diff --git a/tests/lib/files/node/integration.php b/tests/lib/files/node/integration.php
index 456a4a0e287..545793be54a 100644
--- a/tests/lib/files/node/integration.php
+++ b/tests/lib/files/node/integration.php
@@ -20,9 +20,6 @@ class IntegrationTests extends \Test\TestCase {
*/
private $root;
- /** @var \OC\Files\Storage\Storage */
- private $originalStorage;
-
/**
* @var \OC\Files\Storage\Storage[]
*/
@@ -36,20 +33,13 @@ class IntegrationTests extends \Test\TestCase {
protected function setUp() {
parent::setUp();
- $this->originalStorage = \OC\Files\Filesystem::getStorage('/');
- \OC\Files\Filesystem::init('', '');
- \OC\Files\Filesystem::clearMounts();
$manager = \OC\Files\Filesystem::getMountManager();
\OC_Hook::clear('OC_Filesystem');
- \OC_Hook::connect('OC_Filesystem', 'post_write', '\OC\Files\Cache\Updater', 'writeHook');
- \OC_Hook::connect('OC_Filesystem', 'post_delete', '\OC\Files\Cache\Updater', 'deleteHook');
- \OC_Hook::connect('OC_Filesystem', 'post_rename', '\OC\Files\Cache\Updater', 'renameHook');
- \OC_Hook::connect('OC_Filesystem', 'post_touch', '\OC\Files\Cache\Updater', 'touchHook');
-
$user = new User($this->getUniqueID('user'), new \OC_User_Dummy);
- \OC_User::setUserId($user->getUID());
+ $this->loginAsUser($user->getUID());
+
$this->view = new View();
$this->root = new Root($manager, $this->view, $user);
$storage = new Temporary(array());
@@ -64,9 +54,8 @@ class IntegrationTests extends \Test\TestCase {
foreach ($this->storages as $storage) {
$storage->getCache()->clear();
}
- \OC\Files\Filesystem::clearMounts();
- \OC\Files\Filesystem::mount($this->originalStorage, array(), '/');
+ $this->logout();
parent::tearDown();
}
@@ -89,7 +78,7 @@ class IntegrationTests extends \Test\TestCase {
$this->assertEquals('bar.txt', $file->getInternalPath());
$file->move('/substorage/bar.txt');
- $this->assertNotEquals($id, $file->getId());
+ $this->assertEquals($id, $file->getId());
$this->assertEquals('qwerty', $file->getContent());
}
diff --git a/tests/lib/files/storage/wrapper/encryption.php b/tests/lib/files/storage/wrapper/encryption.php
index bf4464f0eb9..ec3770260aa 100644
--- a/tests/lib/files/storage/wrapper/encryption.php
+++ b/tests/lib/files/storage/wrapper/encryption.php
@@ -44,7 +44,9 @@ class Encryption extends \Test\Files\Storage\Storage {
$file = $this->getMockBuilder('\OC\Encryption\File')
->disableOriginalConstructor()
+ ->setMethods(['getAccessList'])
->getMock();
+ $file->expects($this->any())->method('getAccessList')->willReturn([]);
$logger = $this->getMock('\OC\Log');
@@ -72,7 +74,7 @@ class Encryption extends \Test\Files\Storage\Storage {
protected function buildMockModule() {
$encryptionModule = $this->getMockBuilder('\OCP\Encryption\IEncryptionModule')
->disableOriginalConstructor()
- ->setMethods(['getId', 'getDisplayName', 'begin', 'end', 'encrypt', 'decrypt', 'update', 'shouldEncrypt', 'calculateUnencryptedSize', 'getUnencryptedBlockSize'])
+ ->setMethods(['getId', 'getDisplayName', 'begin', 'end', 'encrypt', 'decrypt', 'update', 'shouldEncrypt', 'getUnencryptedBlockSize'])
->getMock();
$encryptionModule->expects($this->any())->method('getId')->willReturn('UNIT_TEST_MODULE');
@@ -83,20 +85,9 @@ class Encryption extends \Test\Files\Storage\Storage {
$encryptionModule->expects($this->any())->method('decrypt')->willReturnArgument(0);
$encryptionModule->expects($this->any())->method('update')->willReturn(true);
$encryptionModule->expects($this->any())->method('shouldEncrypt')->willReturn(true);
- $encryptionModule->expects($this->any())->method('calculateUnencryptedSize')->willReturn(42);
$encryptionModule->expects($this->any())->method('getUnencryptedBlockSize')->willReturn(8192);
return $encryptionModule;
}
-
-// public function testMkDirRooted() {
-// $this->instance->mkdir('bar');
-// $this->assertTrue($this->sourceStorage->is_dir('foo/bar'));
-// }
-//
-// public function testFilePutContentsRooted() {
-// $this->instance->file_put_contents('bar', 'asd');
-// $this->assertEquals('asd', $this->sourceStorage->file_get_contents('foo/bar'));
-// }
}
//
diff --git a/tests/lib/files/stream/encryption.php b/tests/lib/files/stream/encryption.php
index 84156337ad7..6964d203f18 100644
--- a/tests/lib/files/stream/encryption.php
+++ b/tests/lib/files/stream/encryption.php
@@ -29,7 +29,9 @@ class Encryption extends \Test\TestCase {
->getMock();
$file = $this->getMockBuilder('\OC\Encryption\File')
->disableOriginalConstructor()
+ ->setMethods(['getAccessList'])
->getMock();
+ $file->expects($this->any())->method('getAccessList')->willReturn([]);
$util = $this->getMock('\OC\Encryption\Util', ['getUidAndFilename'], [new View(), new \OC\User\Manager(), $config]);
$util->expects($this->any())
->method('getUidAndFilename')
@@ -86,7 +88,7 @@ class Encryption extends \Test\TestCase {
protected function buildMockModule() {
$encryptionModule = $this->getMockBuilder('\OCP\Encryption\IEncryptionModule')
->disableOriginalConstructor()
- ->setMethods(['getId', 'getDisplayName', 'begin', 'end', 'encrypt', 'decrypt', 'update', 'shouldEncrypt', 'calculateUnencryptedSize', 'getUnencryptedBlockSize'])
+ ->setMethods(['getId', 'getDisplayName', 'begin', 'end', 'encrypt', 'decrypt', 'update', 'shouldEncrypt', 'getUnencryptedBlockSize'])
->getMock();
$encryptionModule->expects($this->any())->method('getId')->willReturn('UNIT_TEST_MODULE');
@@ -97,7 +99,6 @@ class Encryption extends \Test\TestCase {
$encryptionModule->expects($this->any())->method('decrypt')->willReturnArgument(0);
$encryptionModule->expects($this->any())->method('update')->willReturn(true);
$encryptionModule->expects($this->any())->method('shouldEncrypt')->willReturn(true);
- $encryptionModule->expects($this->any())->method('calculateUnencryptedSize')->willReturn(42);
$encryptionModule->expects($this->any())->method('getUnencryptedBlockSize')->willReturn(8192);
return $encryptionModule;
}
diff --git a/tests/lib/files/utils/scanner.php b/tests/lib/files/utils/scanner.php
index 65ddfe47514..dfc683c1bcf 100644
--- a/tests/lib/files/utils/scanner.php
+++ b/tests/lib/files/utils/scanner.php
@@ -39,18 +39,14 @@ class TestScanner extends \OC\Files\Utils\Scanner {
}
class Scanner extends \Test\TestCase {
- /** @var \OC\Files\Storage\Storage */
- private $originalStorage;
-
protected function setUp() {
parent::setUp();
- $this->originalStorage = \OC\Files\Filesystem::getStorage('/');
+ $this->loginAsUser();
}
protected function tearDown() {
- \OC\Files\Filesystem::mount($this->originalStorage, array(), '/');
-
+ $this->logout();
parent::tearDown();
}
diff --git a/tests/lib/files/view.php b/tests/lib/files/view.php
index cd9f2d4afd1..269b8b23e7d 100644
--- a/tests/lib/files/view.php
+++ b/tests/lib/files/view.php
@@ -8,6 +8,7 @@
namespace Test\Files;
use OC\Files\Cache\Watcher;
+use OC\Files\Storage\Common;
use OC\Files\Mount\MountPoint;
use OC\Files\Storage\Temporary;
@@ -17,6 +18,26 @@ class TemporaryNoTouch extends \OC\Files\Storage\Temporary {
}
}
+class TemporaryNoCross extends \OC\Files\Storage\Temporary {
+ public function copyFromStorage(\OCP\Files\Storage $sourceStorage, $sourceInternalPath, $targetInternalPath) {
+ return Common::copyFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
+ }
+
+ public function moveFromStorage(\OCP\Files\Storage $sourceStorage, $sourceInternalPath, $targetInternalPath) {
+ return Common::moveFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
+ }
+}
+
+class TemporaryNoLocal extends \OC\Files\Storage\Temporary {
+ public function instanceOfStorage($className) {
+ if($className === '\OC\Files\Storage\Local') {
+ return false;
+ } else {
+ return parent::instanceOfStorage($className);
+ }
+ }
+}
+
class View extends \Test\TestCase {
/**
* @var \OC\Files\Storage\Storage[] $storages
@@ -27,9 +48,6 @@ class View extends \Test\TestCase {
/** @var \OC\Files\Storage\Storage */
private $tempStorage;
- /** @var \OC\Files\Storage\Storage */
- private $originalStorage;
-
protected function setUp() {
parent::setUp();
@@ -39,9 +57,10 @@ class View extends \Test\TestCase {
//login
\OC_User::createUser('test', 'test');
$this->user = \OC_User::getUser();
- \OC_User::setUserId('test');
- $this->originalStorage = \OC\Files\Filesystem::getStorage('/');
+ $this->loginAsUser('test');
+ // clear mounts but somehow keep the root storage
+ // that was initialized above...
\OC\Files\Filesystem::clearMounts();
$this->tempStorage = null;
@@ -59,9 +78,7 @@ class View extends \Test\TestCase {
system('rm -rf ' . escapeshellarg($this->tempStorage->getDataDir()));
}
- \OC\Files\Filesystem::clearMounts();
- \OC\Files\Filesystem::mount($this->originalStorage, array(), '/');
-
+ $this->logout();
parent::tearDown();
}
@@ -295,9 +312,31 @@ class View extends \Test\TestCase {
/**
* @medium
*/
- function testCopyBetweenStorages() {
+ function testCopyBetweenStorageNoCross() {
+ $storage1 = $this->getTestStorage(true, '\Test\Files\TemporaryNoCross');
+ $storage2 = $this->getTestStorage(true, '\Test\Files\TemporaryNoCross');
+ $this->copyBetweenStorages($storage1, $storage2);
+ }
+
+ /**
+ * @medium
+ */
+ function testCopyBetweenStorageCross() {
$storage1 = $this->getTestStorage();
$storage2 = $this->getTestStorage();
+ $this->copyBetweenStorages($storage1, $storage2);
+ }
+
+ /**
+ * @medium
+ */
+ function testCopyBetweenStorageCrossNonLocal() {
+ $storage1 = $this->getTestStorage(true, '\Test\Files\TemporaryNoLocal');
+ $storage2 = $this->getTestStorage(true, '\Test\Files\TemporaryNoLocal');
+ $this->copyBetweenStorages($storage1, $storage2);
+ }
+
+ function copyBetweenStorages($storage1, $storage2) {
\OC\Files\Filesystem::mount($storage1, array(), '/');
\OC\Files\Filesystem::mount($storage2, array(), '/substorage');
@@ -319,9 +358,31 @@ class View extends \Test\TestCase {
/**
* @medium
*/
- function testMoveBetweenStorages() {
+ function testMoveBetweenStorageNoCross() {
+ $storage1 = $this->getTestStorage(true, '\Test\Files\TemporaryNoCross');
+ $storage2 = $this->getTestStorage(true, '\Test\Files\TemporaryNoCross');
+ $this->moveBetweenStorages($storage1, $storage2);
+ }
+
+ /**
+ * @medium
+ */
+ function testMoveBetweenStorageCross() {
$storage1 = $this->getTestStorage();
$storage2 = $this->getTestStorage();
+ $this->moveBetweenStorages($storage1, $storage2);
+ }
+
+ /**
+ * @medium
+ */
+ function testMoveBetweenStorageCrossNonLocal() {
+ $storage1 = $this->getTestStorage(true, '\Test\Files\TemporaryNoLocal');
+ $storage2 = $this->getTestStorage(true, '\Test\Files\TemporaryNoLocal');
+ $this->moveBetweenStorages($storage1, $storage2);
+ }
+
+ function moveBetweenStorages($storage1, $storage2) {
\OC\Files\Filesystem::mount($storage1, array(), '/');
\OC\Files\Filesystem::mount($storage2, array(), '/substorage');
@@ -883,8 +944,19 @@ class View extends \Test\TestCase {
private function doTestCopyRenameFail($operation) {
$storage1 = new Temporary(array());
- $storage2 = new Temporary(array());
- $storage2 = new \OC\Files\Storage\Wrapper\Quota(array('storage' => $storage2, 'quota' => 9));
+ /** @var \PHPUnit_Framework_MockObject_MockObject | \OC\Files\Storage\Temporary $storage2 */
+ $storage2 = $this->getMockBuilder('\Test\Files\TemporaryNoCross')
+ ->setConstructorArgs([[]])
+ ->setMethods(['fopen'])
+ ->getMock();
+
+ $storage2->expects($this->any())
+ ->method('fopen')
+ ->will($this->returnCallback(function($path, $mode) use($storage2) {
+ $source = fopen($storage2->getSourcePath($path), $mode);
+ return \OC\Files\Stream\Quota::wrap($source, 9);
+ }));
+
$storage1->mkdir('sub');
$storage1->file_put_contents('foo.txt', '0123456789ABCDEFGH');
$storage1->mkdir('dirtomove');
@@ -915,10 +987,8 @@ class View extends \Test\TestCase {
$this->assertFalse($view->$operation('/test/dirtomove/', '/test/sub/storage/dirtomove/'));
// since the move failed, the full source tree is kept
$this->assertTrue($storage1->file_exists('dirtomove/indir1.txt'));
- // but the target file stays
- $this->assertTrue($storage2->file_exists('dirtomove/indir1.txt'));
- // second file not moved/copied
$this->assertTrue($storage1->file_exists('dirtomove/indir2.txt'));
+ // second file not moved/copied
$this->assertFalse($storage2->file_exists('dirtomove/indir2.txt'));
$this->assertFalse($storage2->getCache()->get('dirtomove/indir2.txt'));
diff --git a/tests/lib/group/manager.php b/tests/lib/group/manager.php
index 76996a2b9bb..e3e2a96e46d 100644
--- a/tests/lib/group/manager.php
+++ b/tests/lib/group/manager.php
@@ -846,4 +846,26 @@ class Manager extends \Test\TestCase {
$groups = $manager->getUserGroups($user1);
$this->assertEquals(array(), $groups);
}
+
+ public function testGetUserIdGroups() {
+ /**
+ * @var \PHPUnit_Framework_MockObject_MockObject | \OC_Group_Backend $backend
+ */
+ $backend = $this->getMock('\OC_Group_Database');
+ $backend->expects($this->any())
+ ->method('getUserGroups')
+ ->with('user1')
+ ->will($this->returnValue(null));
+
+ /**
+ * @var \OC\User\Manager $userManager
+ */
+ $userManager = $this->getMock('\OC\User\Manager');
+ $manager = new \OC\Group\Manager($userManager);
+ $manager->addBackend($backend);
+
+ $groups = $manager->getUserIdGroups('user1');
+ $this->assertEquals([], $groups);
+ }
+
}
diff --git a/tests/lib/mail/message.php b/tests/lib/mail/message.php
index 0db2017d81e..c75cc18b650 100644
--- a/tests/lib/mail/message.php
+++ b/tests/lib/mail/message.php
@@ -62,6 +62,23 @@ class MessageTest extends TestCase {
$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())
diff --git a/tests/lib/ocsclienttest.php b/tests/lib/ocsclienttest.php
new file mode 100644
index 00000000000..f4bf1536291
--- /dev/null
+++ b/tests/lib/ocsclienttest.php
@@ -0,0 +1,979 @@
+<?php
+/**
+ * @author Lukas Reschke <lukas@owncloud.com>
+ *
+ * @copyright Copyright (c) 2015, ownCloud, Inc.
+ * @license AGPL-3.0
+ *
+ * This code is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License, version 3,
+ * as published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License, version 3,
+ * along with this program. If not, see <http://www.gnu.org/licenses/>
+ *
+ */
+
+use OC\OCSClient;
+use OCP\Http\Client\IClientService;
+use OCP\IConfig;
+use OCP\ILogger;
+
+/**
+ * Class OCSClientTest
+ */
+class OCSClientTest extends \Test\TestCase {
+ /** @var OCSClient */
+ private $ocsClient;
+ /** @var IConfig */
+ private $config;
+ /** @var IClientService */
+ private $clientService;
+ /** @var ILogger */
+ private $logger;
+
+ public function setUp() {
+ parent::setUp();
+
+ $this->config = $this->getMockBuilder('\OCP\IConfig')
+ ->disableOriginalConstructor()->getMock();
+ $this->clientService = $this->getMock('\OCP\Http\Client\IClientService');
+ $this->logger = $this->getMock('\OCP\ILogger');
+
+ $this->ocsClient = new OCSClient(
+ $this->clientService,
+ $this->config,
+ $this->logger
+ );
+ }
+
+ public function testIsAppStoreEnabledSuccess() {
+ $this->config
+ ->expects($this->once())
+ ->method('getSystemValue')
+ ->with('appstoreenabled', true)
+ ->will($this->returnValue(true));
+ $this->assertTrue($this->ocsClient->isAppStoreEnabled());
+ }
+
+ public function testIsAppStoreEnabledFail() {
+ $this->config
+ ->expects($this->once())
+ ->method('getSystemValue')
+ ->with('appstoreenabled', true)
+ ->will($this->returnValue(false));
+ $this->assertFalse($this->ocsClient->isAppStoreEnabled());
+ }
+
+ public function testGetAppStoreUrl() {
+ $this->config
+ ->expects($this->once())
+ ->method('getSystemValue')
+ ->with('appstoreurl', 'https://api.owncloud.com/v1')
+ ->will($this->returnValue('https://api.owncloud.com/v1'));
+ $this->assertSame('https://api.owncloud.com/v1', Test_Helper::invokePrivate($this->ocsClient, 'getAppStoreUrl'));
+ }
+
+ public function testGetCategoriesDisabledAppStore() {
+ $this->config
+ ->expects($this->once())
+ ->method('getSystemValue')
+ ->with('appstoreenabled', true)
+ ->will($this->returnValue(false));
+ $this->assertNull($this->ocsClient->getCategories());
+ }
+
+ public function testGetCategoriesExceptionClient() {
+ $this->config
+ ->expects($this->at(0))
+ ->method('getSystemValue')
+ ->with('appstoreenabled', true)
+ ->will($this->returnValue(true));
+ $this->config
+ ->expects($this->at(1))
+ ->method('getSystemValue')
+ ->with('appstoreurl', 'https://api.owncloud.com/v1')
+ ->will($this->returnValue('https://api.owncloud.com/v1'));
+
+ $client = $this->getMock('\OCP\Http\Client\IClient');
+ $client
+ ->expects($this->once())
+ ->method('get')
+ ->with(
+ 'https://api.owncloud.com/v1/content/categories',
+ [
+ 'timeout' => 5,
+ ]
+ )
+ ->will($this->throwException(new \Exception('TheErrorMessage')));
+
+ $this->clientService
+ ->expects($this->once())
+ ->method('newClient')
+ ->will($this->returnValue($client));
+
+ $this->logger
+ ->expects($this->once())
+ ->method('error')
+ ->with(
+ 'Could not get categories: TheErrorMessage',
+ [
+ 'app' => 'core',
+ ]
+ );
+
+ $this->assertNull($this->ocsClient->getCategories());
+ }
+
+ public function testGetCategoriesParseError() {
+ $this->config
+ ->expects($this->at(0))
+ ->method('getSystemValue')
+ ->with('appstoreenabled', true)
+ ->will($this->returnValue(true));
+ $this->config
+ ->expects($this->at(1))
+ ->method('getSystemValue')
+ ->with('appstoreurl', 'https://api.owncloud.com/v1')
+ ->will($this->returnValue('https://api.owncloud.com/v1'));
+
+ $response = $this->getMock('\OCP\Http\Client\IResponse');
+ $response
+ ->expects($this->once())
+ ->method('getBody')
+ ->will($this->returnValue('MyInvalidXml'));
+
+ $client = $this->getMock('\OCP\Http\Client\IClient');
+ $client
+ ->expects($this->once())
+ ->method('get')
+ ->with(
+ 'https://api.owncloud.com/v1/content/categories',
+ [
+ 'timeout' => 5,
+ ]
+ )
+ ->will($this->returnValue($response));
+
+ $this->clientService
+ ->expects($this->once())
+ ->method('newClient')
+ ->will($this->returnValue($client));
+
+ $this->logger
+ ->expects($this->once())
+ ->method('error')
+ ->with(
+ 'Could not get categories, content was no valid XML',
+ [
+ 'app' => 'core',
+ ]
+ );
+
+ $this->assertNull($this->ocsClient->getCategories());
+ }
+
+ public function testGetCategoriesSuccessful() {
+ $this->config
+ ->expects($this->at(0))
+ ->method('getSystemValue')
+ ->with('appstoreenabled', true)
+ ->will($this->returnValue(true));
+ $this->config
+ ->expects($this->at(1))
+ ->method('getSystemValue')
+ ->with('appstoreurl', 'https://api.owncloud.com/v1')
+ ->will($this->returnValue('https://api.owncloud.com/v1'));
+
+ $response = $this->getMock('\OCP\Http\Client\IResponse');
+ $response
+ ->expects($this->once())
+ ->method('getBody')
+ ->will($this->returnValue('<?xml version="1.0"?>
+ <ocs>
+ <meta>
+ <status>ok</status>
+ <statuscode>100</statuscode>
+ <message></message>
+ <totalitems>6</totalitems>
+ </meta>
+ <data>
+ <category>
+ <id>920</id>
+ <name>ownCloud Multimedia</name>
+ </category>
+ <category>
+ <id>921</id>
+ <name>ownCloud PIM</name>
+ </category>
+ <category>
+ <id>922</id>
+ <name>ownCloud Productivity</name>
+ </category>
+ <category>
+ <id>923</id>
+ <name>ownCloud Game</name>
+ </category>
+ <category>
+ <id>924</id>
+ <name>ownCloud Tool</name>
+ </category>
+ <category>
+ <id>925</id>
+ <name>ownCloud other</name>
+ </category>
+ </data>
+ </ocs>
+ '));
+
+ $client = $this->getMock('\OCP\Http\Client\IClient');
+ $client
+ ->expects($this->once())
+ ->method('get')
+ ->with(
+ 'https://api.owncloud.com/v1/content/categories',
+ [
+ 'timeout' => 5,
+ ]
+ )
+ ->will($this->returnValue($response));
+
+ $this->clientService
+ ->expects($this->once())
+ ->method('newClient')
+ ->will($this->returnValue($client));
+
+ $expected = [
+ 920 => 'ownCloud Multimedia',
+ 921 => 'ownCloud PIM',
+ 922 => 'ownCloud Productivity',
+ 923 => 'ownCloud Game',
+ 924 => 'ownCloud Tool',
+ 925 => 'ownCloud other',
+ ];
+ $this->assertSame($expected, $this->ocsClient->getCategories());
+ }
+
+ public function testGetApplicationsDisabledAppStore() {
+ $this->config
+ ->expects($this->once())
+ ->method('getSystemValue')
+ ->with('appstoreenabled', true)
+ ->will($this->returnValue(false));
+ $this->assertSame([], $this->ocsClient->getApplications([], 1, 'approved'));
+ }
+
+ public function testGetApplicationsExceptionClient() {
+ $this->config
+ ->expects($this->at(0))
+ ->method('getSystemValue')
+ ->with('appstoreenabled', true)
+ ->will($this->returnValue(true));
+ $this->config
+ ->expects($this->at(1))
+ ->method('getSystemValue')
+ ->with('appstoreurl', 'https://api.owncloud.com/v1')
+ ->will($this->returnValue('https://api.owncloud.com/v1'));
+
+ $client = $this->getMock('\OCP\Http\Client\IClient');
+ $client
+ ->expects($this->once())
+ ->method('get')
+ ->with(
+ 'https://api.owncloud.com/v1/content/data',
+ [
+ 'timeout' => 5,
+ 'query' => [
+ 'version' => implode('x', \OC_Util::getVersion()),
+ 'filter' => 'approved',
+ 'categories' => '815x1337',
+ 'sortmode' => 'new',
+ 'page' => 1,
+ 'pagesize' => 100,
+ 'approved' => 'approved',
+ ],
+ ]
+ )
+ ->will($this->throwException(new \Exception('TheErrorMessage')));
+
+ $this->clientService
+ ->expects($this->once())
+ ->method('newClient')
+ ->will($this->returnValue($client));
+
+ $this->logger
+ ->expects($this->once())
+ ->method('error')
+ ->with(
+ 'Could not get applications: TheErrorMessage',
+ [
+ 'app' => 'core',
+ ]
+ );
+
+ $this->assertSame([], $this->ocsClient->getApplications([815, 1337], 1, 'approved'));
+ }
+
+ public function testGetApplicationsParseError() {
+ $this->config
+ ->expects($this->at(0))
+ ->method('getSystemValue')
+ ->with('appstoreenabled', true)
+ ->will($this->returnValue(true));
+ $this->config
+ ->expects($this->at(1))
+ ->method('getSystemValue')
+ ->with('appstoreurl', 'https://api.owncloud.com/v1')
+ ->will($this->returnValue('https://api.owncloud.com/v1'));
+
+ $response = $this->getMock('\OCP\Http\Client\IResponse');
+ $response
+ ->expects($this->once())
+ ->method('getBody')
+ ->will($this->returnValue('MyInvalidXml'));
+
+ $client = $this->getMock('\OCP\Http\Client\IClient');
+ $client
+ ->expects($this->once())
+ ->method('get')
+ ->with(
+ 'https://api.owncloud.com/v1/content/data',
+ [
+ 'timeout' => 5,
+ 'query' => [
+ 'version' => implode('x', \OC_Util::getVersion()),
+ 'filter' => 'approved',
+ 'categories' => '815x1337',
+ 'sortmode' => 'new',
+ 'page' => 1,
+ 'pagesize' => 100,
+ 'approved' => 'approved',
+ ],
+ ]
+ )
+ ->will($this->returnValue($response));
+
+ $this->clientService
+ ->expects($this->once())
+ ->method('newClient')
+ ->will($this->returnValue($client));
+
+ $this->logger
+ ->expects($this->once())
+ ->method('error')
+ ->with(
+ 'Could not get applications, content was no valid XML',
+ [
+ 'app' => 'core',
+ ]
+ );
+
+ $this->assertSame([], $this->ocsClient->getApplications([815, 1337], 1, 'approved'));
+ }
+
+ public function testGetApplicationsSuccessful() {
+ $this->config
+ ->expects($this->at(0))
+ ->method('getSystemValue')
+ ->with('appstoreenabled', true)
+ ->will($this->returnValue(true));
+ $this->config
+ ->expects($this->at(1))
+ ->method('getSystemValue')
+ ->with('appstoreurl', 'https://api.owncloud.com/v1')
+ ->will($this->returnValue('https://api.owncloud.com/v1'));
+
+ $response = $this->getMock('\OCP\Http\Client\IResponse');
+ $response
+ ->expects($this->once())
+ ->method('getBody')
+ ->will($this->returnValue('<?xml version="1.0"?>
+ <ocs>
+ <meta>
+ <status>ok</status>
+ <statuscode>100</statuscode>
+ <message></message>
+ <totalitems>2</totalitems>
+ <itemsperpage>100</itemsperpage>
+ </meta>
+ <data>
+ <content details="summary">
+ <id>168707</id>
+ <name>Calendar 8.0</name>
+ <version>0.6.4</version>
+ <label>recommended</label>
+ <changed>2015-02-09T15:23:56+01:00</changed>
+ <created>2015-01-26T04:35:19+01:00</created>
+ <typeid>921</typeid>
+ <typename>ownCloud PIM</typename>
+ <language></language>
+ <personid>owncloud</personid>
+ <profilepage>http://opendesktop.org/usermanager/search.php?username=owncloud</profilepage>
+ <downloads>5393</downloads>
+ <score>60</score>
+ <description>Calendar App for ownCloud</description>
+ <comments>7</comments>
+ <fans>10</fans>
+ <licensetype>16</licensetype>
+ <approved>0</approved>
+ <category>1</category>
+ <license>AGPL</license>
+ <preview1></preview1>
+ <detailpage>https://apps.owncloud.com/content/show.php?content=168707</detailpage>
+ <downloadtype1></downloadtype1>
+ <downloadway1>0</downloadway1>
+ <downloadprice1>0</downloadprice1>
+ <downloadlink1>http://apps.owncloud.com/content/download.php?content=168707&amp;id=1</downloadlink1>
+ <downloadgpgsignature1></downloadgpgsignature1>
+ <downloadgpgfingerprint1></downloadgpgfingerprint1>
+ <downloadpackagename1></downloadpackagename1>
+ <downloadrepository1></downloadrepository1>
+ <downloadname1></downloadname1>
+ <downloadsize1>885</downloadsize1>
+ </content>
+ <content details="summary">
+ <id>168708</id>
+ <name>Contacts 8.0</name>
+ <version>0.3.0.18</version>
+ <label>recommended</label>
+ <changed>2015-02-09T15:18:58+01:00</changed>
+ <created>2015-01-26T04:45:17+01:00</created>
+ <typeid>921</typeid>
+ <typename>ownCloud PIM</typename>
+ <language></language>
+ <personid>owncloud</personid>
+ <profilepage>http://opendesktop.org/usermanager/search.php?username=owncloud</profilepage>
+ <downloads>4237</downloads>
+ <score>58</score>
+ <description></description>
+ <comments>3</comments>
+ <fans>6</fans>
+ <licensetype>16</licensetype>
+ <approved>200</approved>
+ <category>1</category>
+ <license>AGPL</license>
+ <preview1></preview1>
+ <detailpage>https://apps.owncloud.com/content/show.php?content=168708</detailpage>
+ <downloadtype1></downloadtype1>
+ <downloadway1>0</downloadway1>
+ <downloadprice1>0</downloadprice1>
+ <downloadlink1>http://apps.owncloud.com/content/download.php?content=168708&amp;id=1</downloadlink1>
+ <downloadgpgsignature1></downloadgpgsignature1>
+ <downloadgpgfingerprint1></downloadgpgfingerprint1>
+ <downloadpackagename1></downloadpackagename1>
+ <downloadrepository1></downloadrepository1>
+ <downloadname1></downloadname1>
+ <downloadsize1>1409</downloadsize1>
+ </content>
+ </data>
+ </ocs> '));
+
+ $client = $this->getMock('\OCP\Http\Client\IClient');
+ $client
+ ->expects($this->once())
+ ->method('get')
+ ->with(
+ 'https://api.owncloud.com/v1/content/data',
+ [
+ 'timeout' => 5,
+ 'query' => [
+ 'version' => implode('x', \OC_Util::getVersion()),
+ 'filter' => 'approved',
+ 'categories' => '815x1337',
+ 'sortmode' => 'new',
+ 'page' => 1,
+ 'pagesize' => 100,
+ 'approved' => 'approved',
+ ],
+ ]
+ )
+ ->will($this->returnValue($response));
+
+ $this->clientService
+ ->expects($this->once())
+ ->method('newClient')
+ ->will($this->returnValue($client));
+
+ $expected = [
+ [
+ 'id' => '168707',
+ 'name' => 'Calendar 8.0',
+ 'label' => 'recommended',
+ 'version' => '0.6.4',
+ 'type' => '921',
+ 'typename' => 'ownCloud PIM',
+ 'personid' => 'owncloud',
+ 'license' => 'AGPL',
+ 'detailpage' => 'https://apps.owncloud.com/content/show.php?content=168707',
+ 'preview' => '',
+ 'preview-full' => '',
+ 'changed' => 1423491836,
+ 'description' => 'Calendar App for ownCloud',
+ 'score' => '60',
+ 'downloads' => 5393,
+ 'level' => 0,
+ 'profilepage' => 'http://opendesktop.org/usermanager/search.php?username=owncloud',
+ ],
+ [
+ 'id' => '168708',
+ 'name' => 'Contacts 8.0',
+ 'label' => 'recommended',
+ 'version' => '0.3.0.18',
+ 'type' => '921',
+ 'typename' => 'ownCloud PIM',
+ 'personid' => 'owncloud',
+ 'license' => 'AGPL',
+ 'detailpage' => 'https://apps.owncloud.com/content/show.php?content=168708',
+ 'preview' => '',
+ 'preview-full' => '',
+ 'changed' => 1423491538,
+ 'description' => '',
+ 'score' => '58',
+ 'downloads' => 4237,
+ 'level' => 200,
+ 'profilepage' => 'http://opendesktop.org/usermanager/search.php?username=owncloud',
+ ],
+ ];
+ $this->assertEquals($expected, $this->ocsClient->getApplications([815, 1337], 1, 'approved'));
+ }
+
+ public function tesGetApplicationDisabledAppStore() {
+ $this->config
+ ->expects($this->once())
+ ->method('getSystemValue')
+ ->with('appstoreenabled', true)
+ ->will($this->returnValue(false));
+ $this->assertNull($this->ocsClient->getApplication('MyId'));
+ }
+
+ public function testGetApplicationExceptionClient() {
+ $this->config
+ ->expects($this->at(0))
+ ->method('getSystemValue')
+ ->with('appstoreenabled', true)
+ ->will($this->returnValue(true));
+ $this->config
+ ->expects($this->at(1))
+ ->method('getSystemValue')
+ ->with('appstoreurl', 'https://api.owncloud.com/v1')
+ ->will($this->returnValue('https://api.owncloud.com/v1'));
+
+ $client = $this->getMock('\OCP\Http\Client\IClient');
+ $client
+ ->expects($this->once())
+ ->method('get')
+ ->with(
+ 'https://api.owncloud.com/v1/content/data/MyId',
+ [
+ 'timeout' => 5,
+ ]
+ )
+ ->will($this->throwException(new \Exception('TheErrorMessage')));
+
+ $this->clientService
+ ->expects($this->once())
+ ->method('newClient')
+ ->will($this->returnValue($client));
+
+ $this->logger
+ ->expects($this->once())
+ ->method('error')
+ ->with(
+ 'Could not get application: TheErrorMessage',
+ [
+ 'app' => 'core',
+ ]
+ );
+
+ $this->assertNull($this->ocsClient->getApplication('MyId'));
+ }
+
+ public function testGetApplicationParseError() {
+ $this->config
+ ->expects($this->at(0))
+ ->method('getSystemValue')
+ ->with('appstoreenabled', true)
+ ->will($this->returnValue(true));
+ $this->config
+ ->expects($this->at(1))
+ ->method('getSystemValue')
+ ->with('appstoreurl', 'https://api.owncloud.com/v1')
+ ->will($this->returnValue('https://api.owncloud.com/v1'));
+
+ $response = $this->getMock('\OCP\Http\Client\IResponse');
+ $response
+ ->expects($this->once())
+ ->method('getBody')
+ ->will($this->returnValue('MyInvalidXml'));
+
+ $client = $this->getMock('\OCP\Http\Client\IClient');
+ $client
+ ->expects($this->once())
+ ->method('get')
+ ->with(
+ 'https://api.owncloud.com/v1/content/data/MyId',
+ [
+ 'timeout' => 5,
+ ]
+ )
+ ->will($this->returnValue($response));
+
+ $this->clientService
+ ->expects($this->once())
+ ->method('newClient')
+ ->will($this->returnValue($client));
+
+ $this->logger
+ ->expects($this->once())
+ ->method('error')
+ ->with(
+ 'Could not get application, content was no valid XML',
+ [
+ 'app' => 'core',
+ ]
+ );
+
+ $this->assertNull($this->ocsClient->getApplication('MyId'));
+ }
+
+ public function testGetApplicationSuccessful() {
+ $this->config
+ ->expects($this->at(0))
+ ->method('getSystemValue')
+ ->with('appstoreenabled', true)
+ ->will($this->returnValue(true));
+ $this->config
+ ->expects($this->at(1))
+ ->method('getSystemValue')
+ ->with('appstoreurl', 'https://api.owncloud.com/v1')
+ ->will($this->returnValue('https://api.owncloud.com/v1'));
+
+ $response = $this->getMock('\OCP\Http\Client\IResponse');
+ $response
+ ->expects($this->once())
+ ->method('getBody')
+ ->will($this->returnValue('<?xml version="1.0"?>
+ <ocs>
+ <meta>
+ <status>ok</status>
+ <statuscode>100</statuscode>
+ <message></message>
+ </meta>
+ <data>
+ <content details="full">
+ <id>166053</id>
+ <name>Versioning</name>
+ <version>0.0.1</version>
+ <label>recommended</label>
+ <typeid>925</typeid>
+ <typename>ownCloud other</typename>
+ <language></language>
+ <personid>owncloud</personid>
+ <profilepage>http://opendesktop.org/usermanager/search.php?username=owncloud</profilepage>
+ <created>2014-07-07T16:34:40+02:00</created>
+ <changed>2014-07-07T16:34:40+02:00</changed>
+ <downloads>140</downloads>
+ <score>50</score>
+ <description>Placeholder for future updates</description>
+ <summary></summary>
+ <feedbackurl></feedbackurl>
+ <changelog></changelog>
+ <homepage></homepage>
+ <homepagetype></homepagetype>
+ <homepage2></homepage2>
+ <homepagetype2></homepagetype2>
+ <homepage3></homepage3>
+ <homepagetype3></homepagetype3>
+ <homepage4></homepage4>
+ <homepagetype4></homepagetype4>
+ <homepage5></homepage5>
+ <homepagetype5></homepagetype5>
+ <homepage6></homepage6>
+ <homepagetype6></homepagetype6>
+ <homepage7></homepage7>
+ <homepagetype7></homepagetype7>
+ <homepage8></homepage8>
+ <homepagetype8></homepagetype8>
+ <homepage9></homepage9>
+ <homepagetype9></homepagetype9>
+ <homepage10></homepage10>
+ <homepagetype10></homepagetype10>
+ <licensetype>16</licensetype>
+ <license>AGPL</license>
+ <donationpage></donationpage>
+ <comments>0</comments>
+ <commentspage>http://apps.owncloud.com/content/show.php?content=166053</commentspage>
+ <fans>0</fans>
+ <fanspage>http://apps.owncloud.com/content/show.php?action=fan&amp;content=166053</fanspage>
+ <knowledgebaseentries>0</knowledgebaseentries>
+ <knowledgebasepage>http://apps.owncloud.com/content/show.php?action=knowledgebase&amp;content=166053</knowledgebasepage>
+ <depend>ownCloud 7</depend>
+ <preview1></preview1>
+ <preview2></preview2>
+ <preview3></preview3>
+ <previewpic1></previewpic1>
+ <previewpic2></previewpic2>
+ <previewpic3></previewpic3>
+ <picsmall1></picsmall1>
+ <picsmall2></picsmall2>
+ <picsmall3></picsmall3>
+ <detailpage>https://apps.owncloud.com/content/show.php?content=166053</detailpage>
+ <downloadtype1></downloadtype1>
+ <downloadprice1>0</downloadprice1>
+ <downloadlink1>http://apps.owncloud.com/content/download.php?content=166053&amp;id=1</downloadlink1>
+ <downloadname1></downloadname1>
+ <downloadgpgfingerprint1></downloadgpgfingerprint1>
+ <downloadgpgsignature1></downloadgpgsignature1>
+ <downloadpackagename1></downloadpackagename1>
+ <downloadrepository1></downloadrepository1>
+ <downloadsize1>1</downloadsize1>
+ </content>
+ </data>
+ </ocs>
+ '));
+
+ $client = $this->getMock('\OCP\Http\Client\IClient');
+ $client
+ ->expects($this->once())
+ ->method('get')
+ ->with(
+ 'https://api.owncloud.com/v1/content/data/MyId',
+ [
+ 'timeout' => 5,
+ ]
+ )
+ ->will($this->returnValue($response));
+
+ $this->clientService
+ ->expects($this->once())
+ ->method('newClient')
+ ->will($this->returnValue($client));
+
+ $expected = [
+ 'id' => 166053,
+ 'name' => 'Versioning',
+ 'version' => '0.0.1',
+ 'type' => '925',
+ 'label' => 'recommended',
+ 'typename' => 'ownCloud other',
+ 'personid' => 'owncloud',
+ 'profilepage' => 'http://opendesktop.org/usermanager/search.php?username=owncloud',
+ 'detailpage' => 'https://apps.owncloud.com/content/show.php?content=166053',
+ 'preview1' => '',
+ 'preview2' => '',
+ 'preview3' => '',
+ 'changed' => 1404743680,
+ 'description' => 'Placeholder for future updates',
+ 'score' => 50,
+ ];
+ $this->assertSame($expected, $this->ocsClient->getApplication('MyId'));
+ }
+ public function testGetApplicationEmptyXml() {
+ $this->config
+ ->expects($this->at(0))
+ ->method('getSystemValue')
+ ->with('appstoreenabled', true)
+ ->will($this->returnValue(true));
+ $this->config
+ ->expects($this->at(1))
+ ->method('getSystemValue')
+ ->with('appstoreurl', 'https://api.owncloud.com/v1')
+ ->will($this->returnValue('https://api.owncloud.com/v1'));
+
+ $response = $this->getMock('\OCP\Http\Client\IResponse');
+ $response
+ ->expects($this->once())
+ ->method('getBody')
+ ->will($this->returnValue('<?xml version="1.0"?>
+ <ocs>
+ <meta>
+ <status>ok</status>
+ <statuscode>100</statuscode>
+ <message></message>
+ </meta>
+ </ocs>
+ '));
+
+ $client = $this->getMock('\OCP\Http\Client\IClient');
+ $client
+ ->expects($this->once())
+ ->method('get')
+ ->with(
+ 'https://api.owncloud.com/v1/content/data/MyId',
+ [
+ 'timeout' => 5,
+ ]
+ )
+ ->will($this->returnValue($response));
+
+ $this->clientService
+ ->expects($this->once())
+ ->method('newClient')
+ ->will($this->returnValue($client));
+
+ $this->assertSame(null, $this->ocsClient->getApplication('MyId'));
+ }
+
+ public function testGetApplicationDownloadDisabledAppStore() {
+ $this->config
+ ->expects($this->once())
+ ->method('getSystemValue')
+ ->with('appstoreenabled', true)
+ ->will($this->returnValue(false));
+ $this->assertNull($this->ocsClient->getApplicationDownload('MyId'));
+ }
+
+ public function testGetApplicationDownloadExceptionClient() {
+ $this->config
+ ->expects($this->at(0))
+ ->method('getSystemValue')
+ ->with('appstoreenabled', true)
+ ->will($this->returnValue(true));
+ $this->config
+ ->expects($this->at(1))
+ ->method('getSystemValue')
+ ->with('appstoreurl', 'https://api.owncloud.com/v1')
+ ->will($this->returnValue('https://api.owncloud.com/v1'));
+
+ $client = $this->getMock('\OCP\Http\Client\IClient');
+ $client
+ ->expects($this->once())
+ ->method('get')
+ ->with(
+ 'https://api.owncloud.com/v1/content/download/MyId/1',
+ [
+ 'timeout' => 5,
+ ]
+ )
+ ->will($this->throwException(new \Exception('TheErrorMessage')));
+
+ $this->clientService
+ ->expects($this->once())
+ ->method('newClient')
+ ->will($this->returnValue($client));
+
+ $this->logger
+ ->expects($this->once())
+ ->method('error')
+ ->with(
+ 'Could not get application download URL: TheErrorMessage',
+ [
+ 'app' => 'core',
+ ]
+ );
+
+ $this->assertNull($this->ocsClient->getApplicationDownload('MyId'));
+ }
+
+ public function testGetApplicationDownloadParseError() {
+ $this->config
+ ->expects($this->at(0))
+ ->method('getSystemValue')
+ ->with('appstoreenabled', true)
+ ->will($this->returnValue(true));
+ $this->config
+ ->expects($this->at(1))
+ ->method('getSystemValue')
+ ->with('appstoreurl', 'https://api.owncloud.com/v1')
+ ->will($this->returnValue('https://api.owncloud.com/v1'));
+
+ $response = $this->getMock('\OCP\Http\Client\IResponse');
+ $response
+ ->expects($this->once())
+ ->method('getBody')
+ ->will($this->returnValue('MyInvalidXml'));
+
+ $client = $this->getMock('\OCP\Http\Client\IClient');
+ $client
+ ->expects($this->once())
+ ->method('get')
+ ->with(
+ 'https://api.owncloud.com/v1/content/download/MyId/1',
+ [
+ 'timeout' => 5,
+ ]
+ )
+ ->will($this->returnValue($response));
+
+ $this->clientService
+ ->expects($this->once())
+ ->method('newClient')
+ ->will($this->returnValue($client));
+
+ $this->logger
+ ->expects($this->once())
+ ->method('error')
+ ->with(
+ 'Could not get application download URL, content was no valid XML',
+ [
+ 'app' => 'core',
+ ]
+ );
+
+ $this->assertNull($this->ocsClient->getApplicationDownload('MyId'));
+ }
+
+ public function testGetApplicationDownloadUrlSuccessful() {
+ $this->config
+ ->expects($this->at(0))
+ ->method('getSystemValue')
+ ->with('appstoreenabled', true)
+ ->will($this->returnValue(true));
+ $this->config
+ ->expects($this->at(1))
+ ->method('getSystemValue')
+ ->with('appstoreurl', 'https://api.owncloud.com/v1')
+ ->will($this->returnValue('https://api.owncloud.com/v1'));
+
+ $response = $this->getMock('\OCP\Http\Client\IResponse');
+ $response
+ ->expects($this->once())
+ ->method('getBody')
+ ->will($this->returnValue('<?xml version="1.0"?>
+ <ocs>
+ <meta>
+ <status>ok</status>
+ <statuscode>100</statuscode>
+ <message></message>
+ </meta>
+ <data>
+ <content details="download">
+ <downloadlink>https://apps.owncloud.com/CONTENT/content-files/166052-files_trashbin.zip</downloadlink>
+ <mimetype>application/zip</mimetype>
+ <gpgfingerprint></gpgfingerprint>
+ <gpgsignature></gpgsignature>
+ <packagename></packagename>
+ <repository></repository>
+ </content>
+ </data>
+ </ocs>
+ '));
+
+ $client = $this->getMock('\OCP\Http\Client\IClient');
+ $client
+ ->expects($this->once())
+ ->method('get')
+ ->with(
+ 'https://api.owncloud.com/v1/content/download/MyId/1',
+ [
+ 'timeout' => 5,
+ ]
+ )
+ ->will($this->returnValue($response));
+
+ $this->clientService
+ ->expects($this->once())
+ ->method('newClient')
+ ->will($this->returnValue($client));
+
+ $expected = [
+ 'downloadlink' => 'https://apps.owncloud.com/CONTENT/content-files/166052-files_trashbin.zip',
+ ];
+ $this->assertSame($expected, $this->ocsClient->getApplicationDownload('MyId'));
+ }
+}
diff --git a/tests/lib/preview.php b/tests/lib/preview.php
index 003ecedb65a..20e4209dedf 100644
--- a/tests/lib/preview.php
+++ b/tests/lib/preview.php
@@ -10,10 +10,7 @@ namespace Test;
class Preview extends TestCase {
- /**
- * @var string
- */
- private $user;
+ const TEST_PREVIEW_USER1 = "test-preview-user1";
/**
* @var \OC\Files\View
@@ -26,19 +23,24 @@ class Preview extends TestCase {
protected function setUp() {
parent::setUp();
+ // FIXME: use proper tearDown with $this->loginAsUser() and $this->logout()
+ // (would currently break the tests for some reason)
$this->originalStorage = \OC\Files\Filesystem::getStorage('/');
// create a new user with his own filesystem view
// this gets called by each test in this test class
- $this->user = $this->getUniqueID();
- \OC_User::setUserId($this->user);
- \OC\Files\Filesystem::init($this->user, '/' . $this->user . '/files');
+ $backend = new \OC_User_Dummy();
+ \OC_User::useBackend($backend);
+ $backend->createUser(self::TEST_PREVIEW_USER1, self::TEST_PREVIEW_USER1);
+ $user = \OC::$server->getUserManager()->get(self::TEST_PREVIEW_USER1);
+ \OC::$server->getUserSession()->setUser($user);
+ \OC\Files\Filesystem::init(self::TEST_PREVIEW_USER1, '/' . self::TEST_PREVIEW_USER1 . '/files');
\OC\Files\Filesystem::mount('OC\Files\Storage\Temporary', array(), '/');
$this->rootView = new \OC\Files\View('');
- $this->rootView->mkdir('/'.$this->user);
- $this->rootView->mkdir('/'.$this->user.'/files');
+ $this->rootView->mkdir('/'.self::TEST_PREVIEW_USER1);
+ $this->rootView->mkdir('/'.self::TEST_PREVIEW_USER1.'/files');
}
protected function tearDown() {
@@ -57,14 +59,14 @@ class Preview extends TestCase {
\OC::$server->getConfig()->setSystemValue('preview_max_y', $maxY);
// Sample is 1680x1050 JPEG
- $sampleFile = '/' . $this->user . '/files/testimage.jpg';
+ $sampleFile = '/' . self::TEST_PREVIEW_USER1 . '/files/testimage.jpg';
$this->rootView->file_put_contents($sampleFile, file_get_contents(\OC::$SERVERROOT.'/tests/data/testimage.jpg'));
$fileInfo = $this->rootView->getFileInfo($sampleFile);
$fileId = $fileInfo['fileid'];
$largeX = 1920;
$largeY = 1080;
- $preview = new \OC\Preview($this->user, 'files/', 'testimage.jpg', $largeX, $largeY);
+ $preview = new \OC\Preview(self::TEST_PREVIEW_USER1, 'files/', 'testimage.jpg', $largeX, $largeY);
$this->assertEquals($preview->isFileValid(), true);
@@ -82,7 +84,7 @@ class Preview extends TestCase {
$this->assertEquals($image->height(), $maxY);
// The max thumbnail should be created
- $maxThumbCacheFile = '/' . $this->user . '/' . \OC\Preview::THUMBNAILS_FOLDER . '/' . $fileId . '/' . $maxX . '-' . $maxY . '-max.png';
+ $maxThumbCacheFile = '/' . self::TEST_PREVIEW_USER1 . '/' . \OC\Preview::THUMBNAILS_FOLDER . '/' . $fileId . '/' . $maxX . '-' . $maxY . '-max.png';
$this->assertEquals($this->rootView->file_exists($maxThumbCacheFile), true);
@@ -98,7 +100,7 @@ class Preview extends TestCase {
// Smaller previews should be based on the cached max preview
$smallX = 50;
$smallY = 50;
- $preview = new \OC\Preview($this->user, 'files/', 'testimage.jpg', $smallX, $smallY);
+ $preview = new \OC\Preview(self::TEST_PREVIEW_USER1, 'files/', 'testimage.jpg', $smallX, $smallY);
$isCached = $preview->isCached($fileId);
$this->assertEquals(\OC\Preview::THUMBNAILS_FOLDER . '/' . $fileId . '/' . $maxX . '-' . $maxY . '.png', $isCached);
@@ -109,7 +111,7 @@ class Preview extends TestCase {
$this->assertEquals($image->height(), $smallY);
// The cache should contain the small preview
- $thumbCacheFile = '/' . $this->user . '/' . \OC\Preview::THUMBNAILS_FOLDER . '/' . $fileId . '/' . $smallX . '-' . $smallY . '.png';
+ $thumbCacheFile = '/' . self::TEST_PREVIEW_USER1 . '/' . \OC\Preview::THUMBNAILS_FOLDER . '/' . $fileId . '/' . $smallX . '-' . $smallY . '.png';
$this->assertEquals($this->rootView->file_exists($thumbCacheFile), true);
@@ -121,20 +123,20 @@ class Preview extends TestCase {
public function testIsPreviewDeleted() {
- $sampleFile = '/'.$this->user.'/files/test.txt';
+ $sampleFile = '/'.self::TEST_PREVIEW_USER1.'/files/test.txt';
$this->rootView->file_put_contents($sampleFile, 'dummy file data');
$x = 50;
$y = 50;
- $preview = new \OC\Preview($this->user, 'files/', 'test.txt', $x, $y);
+ $preview = new \OC\Preview(self::TEST_PREVIEW_USER1, 'files/', 'test.txt', $x, $y);
$preview->getPreview();
$fileInfo = $this->rootView->getFileInfo($sampleFile);
$fileId = $fileInfo['fileid'];
- $thumbCacheFile = '/' . $this->user . '/' . \OC\Preview::THUMBNAILS_FOLDER . '/' . $fileId . '/' . $x . '-' . $y . '.png';
+ $thumbCacheFile = '/' . self::TEST_PREVIEW_USER1 . '/' . \OC\Preview::THUMBNAILS_FOLDER . '/' . $fileId . '/' . $x . '-' . $y . '.png';
$this->assertEquals($this->rootView->file_exists($thumbCacheFile), true);
@@ -145,20 +147,20 @@ class Preview extends TestCase {
public function testAreAllPreviewsDeleted() {
- $sampleFile = '/'.$this->user.'/files/test.txt';
+ $sampleFile = '/'.self::TEST_PREVIEW_USER1.'/files/test.txt';
$this->rootView->file_put_contents($sampleFile, 'dummy file data');
$x = 50;
$y = 50;
- $preview = new \OC\Preview($this->user, 'files/', 'test.txt', $x, $y);
+ $preview = new \OC\Preview(self::TEST_PREVIEW_USER1, 'files/', 'test.txt', $x, $y);
$preview->getPreview();
$fileInfo = $this->rootView->getFileInfo($sampleFile);
$fileId = $fileInfo['fileid'];
- $thumbCacheFolder = '/' . $this->user . '/' . \OC\Preview::THUMBNAILS_FOLDER . '/' . $fileId . '/';
+ $thumbCacheFolder = '/' . self::TEST_PREVIEW_USER1 . '/' . \OC\Preview::THUMBNAILS_FOLDER . '/' . $fileId . '/';
$this->assertEquals($this->rootView->is_dir($thumbCacheFolder), true);
@@ -183,9 +185,9 @@ class Preview extends TestCase {
$x = 32;
$y = 32;
- $sample = '/'.$this->user.'/files/test.'.$extension;
+ $sample = '/'.self::TEST_PREVIEW_USER1.'/files/test.'.$extension;
$this->rootView->file_put_contents($sample, $data);
- $preview = new \OC\Preview($this->user, 'files/', 'test.'.$extension, $x, $y);
+ $preview = new \OC\Preview(self::TEST_PREVIEW_USER1, 'files/', 'test.'.$extension, $x, $y);
$image = $preview->getPreview();
$resource = $image->resource();
@@ -201,7 +203,7 @@ class Preview extends TestCase {
public function testCreationFromCached() {
- $sampleFile = '/'.$this->user.'/files/test.txt';
+ $sampleFile = '/'.self::TEST_PREVIEW_USER1.'/files/test.txt';
$this->rootView->file_put_contents($sampleFile, 'dummy file data');
@@ -209,22 +211,22 @@ class Preview extends TestCase {
$x = 150;
$y = 150;
- $preview = new \OC\Preview($this->user, 'files/', 'test.txt', $x, $y);
+ $preview = new \OC\Preview(self::TEST_PREVIEW_USER1, 'files/', 'test.txt', $x, $y);
$preview->getPreview();
$fileInfo = $this->rootView->getFileInfo($sampleFile);
$fileId = $fileInfo['fileid'];
- $thumbCacheFile = '/' . $this->user . '/' . \OC\Preview::THUMBNAILS_FOLDER . '/' . $fileId . '/' . $x . '-' . $y . '.png';
+ $thumbCacheFile = '/' . self::TEST_PREVIEW_USER1 . '/' . \OC\Preview::THUMBNAILS_FOLDER . '/' . $fileId . '/' . $x . '-' . $y . '.png';
$this->assertEquals($this->rootView->file_exists($thumbCacheFile), true);
// create smaller previews
- $preview = new \OC\Preview($this->user, 'files/', 'test.txt', 50, 50);
+ $preview = new \OC\Preview(self::TEST_PREVIEW_USER1, 'files/', 'test.txt', 50, 50);
$isCached = $preview->isCached($fileId);
- $this->assertEquals($this->user . '/' . \OC\Preview::THUMBNAILS_FOLDER . '/' . $fileId . '/150-150.png', $isCached);
+ $this->assertEquals(self::TEST_PREVIEW_USER1 . '/' . \OC\Preview::THUMBNAILS_FOLDER . '/' . $fileId . '/150-150.png', $isCached);
}
/*
diff --git a/tests/lib/repair/repairlegacystorage.php b/tests/lib/repair/repairlegacystorage.php
index 2df0f6b94b4..e1edf704424 100644
--- a/tests/lib/repair/repairlegacystorage.php
+++ b/tests/lib/repair/repairlegacystorage.php
@@ -5,18 +5,25 @@
* later.
* See the COPYING-README file.
*/
+
namespace Test\Repair;
+use OC\Files\Cache\Cache;
+use OC\Files\Cache\Storage;
+use Test\TestCase;
+
/**
* Tests for the converting of legacy storages to home storages.
*
* @see \OC\Repair\RepairLegacyStorages
*/
-class RepairLegacyStorages extends \Test\TestCase {
-
+class RepairLegacyStorages extends TestCase {
+ /** @var \OCP\IDBConnection */
private $connection;
+ /** @var \OCP\IConfig */
private $config;
private $user;
+ /** @var \OC\Repair\RepairLegacyStorages */
private $repair;
private $dataDir;
@@ -31,7 +38,7 @@ class RepairLegacyStorages extends \Test\TestCase {
parent::setUp();
$this->config = \OC::$server->getConfig();
- $this->connection = \OC_DB::getConnection();
+ $this->connection = \OC::$server->getDatabaseConnection();
$this->oldDataDir = $this->config->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data/');
$this->repair = new \OC\Repair\RepairLegacyStorages($this->config, $this->connection);
@@ -44,40 +51,49 @@ class RepairLegacyStorages extends \Test\TestCase {
}
protected function tearDown() {
- \OC_User::deleteUser($this->user);
+ $user = \OC::$server->getUserManager()->get($this->user);
+ if ($user) {
+ $user->delete();
+ }
$sql = 'DELETE FROM `*PREFIX*storages`';
$this->connection->executeQuery($sql);
$sql = 'DELETE FROM `*PREFIX*filecache`';
$this->connection->executeQuery($sql);
- \OCP\Config::setSystemValue('datadirectory', $this->oldDataDir);
+ $this->config->setSystemValue('datadirectory', $this->oldDataDir);
$this->config->setAppValue('core', 'repairlegacystoragesdone', 'no');
parent::tearDown();
}
+ /**
+ * @param string $dataDir
+ * @param string $userId
+ * @throws \Exception
+ */
function prepareSettings($dataDir, $userId) {
// hard-coded string as we want a predictable fixed length
// no data will be written there
$this->dataDir = $dataDir;
- \OCP\Config::setSystemValue('datadirectory', $this->dataDir);
+ $this->config->setSystemValue('datadirectory', $this->dataDir);
$this->user = $userId;
$this->legacyStorageId = 'local::' . $this->dataDir . $this->user . '/';
$this->newStorageId = 'home::' . $this->user;
- \OC_User::createUser($this->user, $this->user);
+ \OC::$server->getUserManager()->createUser($this->user, $this->user);
}
/**
* Create a storage entry
*
* @param string $storageId
+ * @return int
*/
private function createStorage($storageId) {
$sql = 'INSERT INTO `*PREFIX*storages` (`id`)'
. ' VALUES (?)';
- $storageId = \OC\Files\Cache\Storage::adjustStorageId($storageId);
+ $storageId = Storage::adjustStorageId($storageId);
$numRows = $this->connection->executeUpdate($sql, array($storageId));
$this->assertEquals(1, $numRows);
@@ -87,11 +103,11 @@ class RepairLegacyStorages extends \Test\TestCase {
/**
* Returns the storage id based on the numeric id
*
- * @param int $numericId numeric id of the storage
+ * @param int $storageId numeric id of the storage
* @return string storage id or null if not found
*/
private function getStorageId($storageId) {
- $numericId = \OC\Files\Cache\Storage::getNumericStorageId($storageId);
+ $numericId = Storage::getNumericStorageId($storageId);
if (!is_null($numericId)) {
return (int)$numericId;
}
@@ -104,7 +120,7 @@ class RepairLegacyStorages extends \Test\TestCase {
* @param string $storageId storage id
*/
private function createData($storageId) {
- $cache = new \OC\Files\Cache\Cache($storageId);
+ $cache = new Cache($storageId);
$cache->put(
'dummyfile.txt',
array('size' => 5, 'mtime' => 12, 'mimetype' => 'text/plain')
@@ -113,7 +129,11 @@ class RepairLegacyStorages extends \Test\TestCase {
/**
* Test that existing home storages are left alone when valid.
+ *
* @dataProvider settingsProvider
+ *
+ * @param string $dataDir
+ * @param string $userId
*/
public function testNoopWithExistingHomeStorage($dataDir, $userId) {
$this->prepareSettings($dataDir, $userId);
@@ -128,7 +148,11 @@ class RepairLegacyStorages extends \Test\TestCase {
/**
* Test that legacy storages are converted to home storages when
* the latter does not exist.
+ *
* @dataProvider settingsProvider
+ *
+ * @param string $dataDir
+ * @param string $userId
*/
public function testConvertLegacyToHomeStorage($dataDir, $userId) {
$this->prepareSettings($dataDir, $userId);
@@ -143,12 +167,16 @@ class RepairLegacyStorages extends \Test\TestCase {
/**
* Test that legacy storages are converted to home storages
* when home storage already exists but has no data.
+ *
* @dataProvider settingsProvider
+ *
+ * @param string $dataDir
+ * @param string $userId
*/
public function testConvertLegacyToExistingEmptyHomeStorage($dataDir, $userId) {
$this->prepareSettings($dataDir, $userId);
$legacyStorageNumId = $this->createStorage($this->legacyStorageId);
- $newStorageNumId = $this->createStorage($this->newStorageId);
+ $this->createStorage($this->newStorageId);
$this->createData($this->legacyStorageId);
@@ -162,11 +190,15 @@ class RepairLegacyStorages extends \Test\TestCase {
* Test that legacy storages are converted to home storages
* when home storage already exists and the legacy storage
* has no data.
+ *
* @dataProvider settingsProvider
+ *
+ * @param string $dataDir
+ * @param string $userId
*/
public function testConvertEmptyLegacyToHomeStorage($dataDir, $userId) {
$this->prepareSettings($dataDir, $userId);
- $legacyStorageNumId = $this->createStorage($this->legacyStorageId);
+ $this->createStorage($this->legacyStorageId);
$newStorageNumId = $this->createStorage($this->newStorageId);
$this->createData($this->newStorageId);
@@ -180,7 +212,11 @@ class RepairLegacyStorages extends \Test\TestCase {
/**
* Test that nothing is done when both conflicting legacy
* and home storage have data.
+ *
* @dataProvider settingsProvider
+ *
+ * @param string $dataDir
+ * @param string $userId
*/
public function testConflictNoop($dataDir, $userId) {
$this->prepareSettings($dataDir, $userId);
@@ -205,7 +241,11 @@ class RepairLegacyStorages extends \Test\TestCase {
/**
* Test that the data dir local entry is left alone
+ *
* @dataProvider settingsProvider
+ *
+ * @param string $dataDir
+ * @param string $userId
*/
public function testDataDirEntryNoop($dataDir, $userId) {
$this->prepareSettings($dataDir, $userId);
@@ -219,7 +259,11 @@ class RepairLegacyStorages extends \Test\TestCase {
/**
* Test that external local storages are left alone
+ *
* @dataProvider settingsProvider
+ *
+ * @param string $dataDir
+ * @param string $userId
*/
public function testLocalExtStorageNoop($dataDir, $userId) {
$this->prepareSettings($dataDir, $userId);
@@ -233,7 +277,11 @@ class RepairLegacyStorages extends \Test\TestCase {
/**
* Test that other external storages are left alone
+ *
* @dataProvider settingsProvider
+ *
+ * @param string $dataDir
+ * @param string $userId
*/
public function testExtStorageNoop($dataDir, $userId) {
$this->prepareSettings($dataDir, $userId);
diff --git a/tests/lib/share/MailNotificationsTest.php b/tests/lib/share/MailNotificationsTest.php
new file mode 100644
index 00000000000..c74fe406db1
--- /dev/null
+++ b/tests/lib/share/MailNotificationsTest.php
@@ -0,0 +1,237 @@
+<?php
+/**
+ * @author Lukas Reschke <lukas@owncloud.com>
+ *
+ * @copyright Copyright (c) 2015, ownCloud, Inc.
+ * @license AGPL-3.0
+ *
+ * This code is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License, version 3,
+ * as published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License, version 3,
+ * along with this program. If not, see <http://www.gnu.org/licenses/>
+ *
+ */
+
+use OC\Share\MailNotifications;
+use OCP\IConfig;
+use OCP\IL10N;
+use OCP\Mail\IMailer;
+use OCP\ILogger;
+use OCP\Defaults;
+
+/**
+ * Class MailNotificationsTest
+ */
+class MailNotificationsTest extends \Test\TestCase {
+ /** @var IConfig */
+ private $config;
+ /** @var IL10N */
+ private $l10n;
+ /** @var IMailer */
+ private $mailer;
+ /** @var ILogger */
+ private $logger;
+ /** @var Defaults */
+ private $defaults;
+
+
+ public function setUp() {
+ parent::setUp();
+
+ $this->config = $this->getMockBuilder('\OCP\IConfig')
+ ->disableOriginalConstructor()->getMock();
+ $this->l10n = $this->getMockBuilder('\OCP\IL10N')
+ ->disableOriginalConstructor()->getMock();
+ $this->mailer = $this->getMockBuilder('\OCP\Mail\IMailer')
+ ->disableOriginalConstructor()->getMock();
+ $this->logger = $this->getMockBuilder('\OCP\ILogger')
+ ->disableOriginalConstructor()->getMock();
+ $this->defaults = $this->getMockBuilder('\OCP\Defaults')
+ ->disableOriginalConstructor()->getMock();
+
+ $this->l10n->expects($this->any())
+ ->method('t')
+ ->will($this->returnCallback(function($text, $parameters = array()) {
+ return vsprintf($text, $parameters);
+ }));
+ }
+
+ public function testSendLinkShareMailWithoutReplyTo() {
+ $message = $this->getMockBuilder('\OC\Mail\Message')
+ ->disableOriginalConstructor()->getMock();
+
+ $message
+ ->expects($this->once())
+ ->method('setSubject')
+ ->with('TestUser shared »MyFile« with you');
+ $message
+ ->expects($this->once())
+ ->method('setTo')
+ ->with(['lukas@owncloud.com']);
+ $message
+ ->expects($this->once())
+ ->method('setHtmlBody');
+ $message
+ ->expects($this->once())
+ ->method('setPlainBody');
+ $message
+ ->expects($this->once())
+ ->method('setFrom')
+ ->with([\OCP\Util::getDefaultEmailAddress('sharing-noreply') => 'TestUser via UnitTestCloud']);
+
+ $this->mailer
+ ->expects($this->once())
+ ->method('createMessage')
+ ->will($this->returnValue($message));
+ $this->mailer
+ ->expects($this->once())
+ ->method('send')
+ ->with($message)
+ ->will($this->returnValue([]));
+
+ $this->defaults
+ ->expects($this->once())
+ ->method('getName')
+ ->will($this->returnValue('UnitTestCloud'));
+
+ $this->config
+ ->expects($this->at(0))
+ ->method('getUserValue')
+ ->with('TestUser', 'settings', 'email', null)
+ ->will($this->returnValue('sharer@owncloud.com'));
+
+ $mailNotifications = new MailNotifications(
+ 'TestUser',
+ $this->config,
+ $this->l10n,
+ $this->mailer,
+ $this->logger,
+ $this->defaults
+ );
+
+ $this->assertSame([], $mailNotifications->sendLinkShareMail('lukas@owncloud.com', 'MyFile', 'https://owncloud.com/file/?foo=bar', 3600));
+ }
+
+ public function testSendLinkShareMailWithReplyTo() {
+ $message = $this->getMockBuilder('\OC\Mail\Message')
+ ->disableOriginalConstructor()->getMock();
+
+ $message
+ ->expects($this->once())
+ ->method('setSubject')
+ ->with('TestUser shared »MyFile« with you');
+ $message
+ ->expects($this->once())
+ ->method('setTo')
+ ->with(['lukas@owncloud.com']);
+ $message
+ ->expects($this->once())
+ ->method('setHtmlBody');
+ $message
+ ->expects($this->once())
+ ->method('setPlainBody');
+ $message
+ ->expects($this->once())
+ ->method('setFrom')
+ ->with([\OCP\Util::getDefaultEmailAddress('sharing-noreply') => 'TestUser via UnitTestCloud']);
+ $message
+ ->expects($this->once())
+ ->method('setReplyTo')
+ ->with(['sharer@owncloud.com']);
+
+ $this->mailer
+ ->expects($this->once())
+ ->method('createMessage')
+ ->will($this->returnValue($message));
+ $this->mailer
+ ->expects($this->once())
+ ->method('send')
+ ->with($message)
+ ->will($this->returnValue([]));
+
+ $this->defaults
+ ->expects($this->once())
+ ->method('getName')
+ ->will($this->returnValue('UnitTestCloud'));
+
+ $this->config
+ ->expects($this->at(0))
+ ->method('getUserValue')
+ ->with('TestUser', 'settings', 'email', null)
+ ->will($this->returnValue('sharer@owncloud.com'));
+
+ $mailNotifications = new MailNotifications(
+ 'TestUser',
+ $this->config,
+ $this->l10n,
+ $this->mailer,
+ $this->logger,
+ $this->defaults
+ );
+ $this->assertSame([], $mailNotifications->sendLinkShareMail('lukas@owncloud.com', 'MyFile', 'https://owncloud.com/file/?foo=bar', 3600));
+ }
+
+ public function testSendLinkShareMailException() {
+ $message = $this->getMockBuilder('\OC\Mail\Message')
+ ->disableOriginalConstructor()->getMock();
+
+ $message
+ ->expects($this->once())
+ ->method('setSubject')
+ ->with('TestUser shared »MyFile« with you');
+ $message
+ ->expects($this->once())
+ ->method('setTo')
+ ->with(['lukas@owncloud.com']);
+ $message
+ ->expects($this->once())
+ ->method('setHtmlBody');
+ $message
+ ->expects($this->once())
+ ->method('setPlainBody');
+ $message
+ ->expects($this->once())
+ ->method('setFrom')
+ ->with([\OCP\Util::getDefaultEmailAddress('sharing-noreply') => 'TestUser via UnitTestCloud']);
+
+ $this->mailer
+ ->expects($this->once())
+ ->method('createMessage')
+ ->will($this->returnValue($message));
+ $this->mailer
+ ->expects($this->once())
+ ->method('send')
+ ->with($message)
+ ->will($this->throwException(new Exception('Some Exception Message')));
+
+ $this->defaults
+ ->expects($this->once())
+ ->method('getName')
+ ->will($this->returnValue('UnitTestCloud'));
+
+ $this->config
+ ->expects($this->at(0))
+ ->method('getUserValue')
+ ->with('TestUser', 'settings', 'email', null)
+ ->will($this->returnValue('sharer@owncloud.com'));
+
+ $mailNotifications = new MailNotifications(
+ 'TestUser',
+ $this->config,
+ $this->l10n,
+ $this->mailer,
+ $this->logger,
+ $this->defaults
+ );
+
+ $this->assertSame(['lukas@owncloud.com'], $mailNotifications->sendLinkShareMail('lukas@owncloud.com', 'MyFile', 'https://owncloud.com/file/?foo=bar', 3600));
+ }
+
+}
diff --git a/tests/lib/share/share.php b/tests/lib/share/share.php
index f35a0fa8e43..124ad450e2e 100644
--- a/tests/lib/share/share.php
+++ b/tests/lib/share/share.php
@@ -545,6 +545,13 @@ class Test_Share extends \Test\TestCase {
// Valid share
$this->shareUserOneTestFileWithGroupOne();
+ // check if only the group share was created and not a single db-entry for each user
+ $statement = \OCP\DB::prepare('select `id` from `*PREFIX*share`');
+ $query = $statement->execute();
+ $result = $query->fetchAll();
+ $this->assertSame(1, count($result));
+
+
// Attempt to share again
OC_User::setUserId($this->user1);
$message = 'Sharing test.txt failed, because this item is already shared with '.$this->group1;
@@ -1128,6 +1135,240 @@ class Test_Share extends \Test\TestCase {
\OC_Appconfig::deleteKey('core', 'shareapi_expire_after_n_days');
\OC_Appconfig::deleteKey('core', 'shareapi_enforce_expire_date');
}
+
+ /**
+ * Cannot set password is there is no user
+ *
+ * @expectedException Exception
+ * @expectedExceptionMessage User not logged in
+ */
+ public function testSetPasswordNoUser() {
+ $userSession = $this->getMockBuilder('\OCP\IUserSession')
+ ->disableOriginalConstructor()
+ ->getMock();
+
+ $connection = $this->getMockBuilder('\OC\DB\Connection')
+ ->disableOriginalConstructor()
+ ->getMock();
+
+ $config = $this->getMockBuilder('\OCP\IConfig')
+ ->disableOriginalConstructor()
+ ->getMock();
+
+ \OC\Share\Share::setPassword($userSession, $connection, $config, 1, 'pass');
+ }
+
+ /**
+ * Test setting a password when everything is fine
+ */
+ public function testSetPassword() {
+ $user = $this->getMockBuilder('\OCP\IUser')
+ ->disableOriginalConstructor()
+ ->getMock();
+ $user->method('getUID')->willReturn('user');
+
+ $userSession = $this->getMockBuilder('\OCP\IUserSession')
+ ->disableOriginalConstructor()
+ ->getMock();
+ $userSession->method('getUser')->willReturn($user);
+
+
+ $ex = $this->getMockBuilder('\Doctrine\DBAL\Query\Expression\ExpressionBuilder')
+ ->disableOriginalConstructor()
+ ->getMock();
+ $qb = $this->getMockBuilder('\Doctrine\DBAL\Query\QueryBuilder')
+ ->disableOriginalConstructor()
+ ->getMock();
+ $qb->method('update')->will($this->returnSelf());
+ $qb->method('set')->will($this->returnSelf());
+ $qb->method('where')->will($this->returnSelf());
+ $qb->method('andWhere')->will($this->returnSelf());
+ $qb->method('select')->will($this->returnSelf());
+ $qb->method('from')->will($this->returnSelf());
+ $qb->method('setParameter')->will($this->returnSelf());
+ $qb->method('expr')->willReturn($ex);
+
+ $ret = $this->getMockBuilder('\Doctrine\DBAL\Driver\ResultStatement')
+ ->disableOriginalConstructor()
+ ->getMock();
+ $ret->method('fetch')->willReturn(['uid_owner' => 'user']);
+ $qb->method('execute')->willReturn($ret);
+
+
+ $connection = $this->getMockBuilder('\OC\DB\Connection')
+ ->disableOriginalConstructor()
+ ->getMock();
+ $connection->method('createQueryBuilder')->willReturn($qb);
+
+ $config = $this->getMockBuilder('\OCP\IConfig')
+ ->disableOriginalConstructor()
+ ->getMock();
+
+
+ $res = \OC\Share\Share::setPassword($userSession, $connection, $config, 1, 'pass');
+
+ $this->assertTrue($res);
+ }
+
+ /**
+ * @expectedException Exception
+ * @expectedExceptionMessage Cannot remove password
+ *
+ * Test removing a password when password is enforced
+ */
+ public function testSetPasswordRemove() {
+ $user = $this->getMockBuilder('\OCP\IUser')
+ ->disableOriginalConstructor()
+ ->getMock();
+ $user->method('getUID')->willReturn('user');
+
+ $userSession = $this->getMockBuilder('\OCP\IUserSession')
+ ->disableOriginalConstructor()
+ ->getMock();
+ $userSession->method('getUser')->willReturn($user);
+
+
+ $ex = $this->getMockBuilder('\Doctrine\DBAL\Query\Expression\ExpressionBuilder')
+ ->disableOriginalConstructor()
+ ->getMock();
+ $qb = $this->getMockBuilder('\Doctrine\DBAL\Query\QueryBuilder')
+ ->disableOriginalConstructor()
+ ->getMock();
+ $qb->method('update')->will($this->returnSelf());
+ $qb->method('select')->will($this->returnSelf());
+ $qb->method('from')->will($this->returnSelf());
+ $qb->method('set')->will($this->returnSelf());
+ $qb->method('where')->will($this->returnSelf());
+ $qb->method('andWhere')->will($this->returnSelf());
+ $qb->method('setParameter')->will($this->returnSelf());
+ $qb->method('expr')->willReturn($ex);
+
+ $ret = $this->getMockBuilder('\Doctrine\DBAL\Driver\ResultStatement')
+ ->disableOriginalConstructor()
+ ->getMock();
+ $ret->method('fetch')->willReturn(['uid_owner' => 'user']);
+ $qb->method('execute')->willReturn($ret);
+
+
+ $connection = $this->getMockBuilder('\OC\DB\Connection')
+ ->disableOriginalConstructor()
+ ->getMock();
+ $connection->method('createQueryBuilder')->willReturn($qb);
+
+ $config = $this->getMockBuilder('\OCP\IConfig')
+ ->disableOriginalConstructor()
+ ->getMock();
+ $config->method('getAppValue')->willReturn('yes');
+
+ \OC\Share\Share::setPassword($userSession, $connection, $config, 1, '');
+ }
+
+ /**
+ * @expectedException Exception
+ * @expectedExceptionMessage Share not found
+ *
+ * Test modification of invaid share
+ */
+ public function testSetPasswordInvalidShare() {
+ $user = $this->getMockBuilder('\OCP\IUser')
+ ->disableOriginalConstructor()
+ ->getMock();
+ $user->method('getUID')->willReturn('user');
+
+ $userSession = $this->getMockBuilder('\OCP\IUserSession')
+ ->disableOriginalConstructor()
+ ->getMock();
+ $userSession->method('getUser')->willReturn($user);
+
+
+ $ex = $this->getMockBuilder('\Doctrine\DBAL\Query\Expression\ExpressionBuilder')
+ ->disableOriginalConstructor()
+ ->getMock();
+ $qb = $this->getMockBuilder('\Doctrine\DBAL\Query\QueryBuilder')
+ ->disableOriginalConstructor()
+ ->getMock();
+ $qb->method('update')->will($this->returnSelf());
+ $qb->method('set')->will($this->returnSelf());
+ $qb->method('where')->will($this->returnSelf());
+ $qb->method('andWhere')->will($this->returnSelf());
+ $qb->method('select')->will($this->returnSelf());
+ $qb->method('from')->will($this->returnSelf());
+ $qb->method('setParameter')->will($this->returnSelf());
+ $qb->method('expr')->willReturn($ex);
+
+ $ret = $this->getMockBuilder('\Doctrine\DBAL\Driver\ResultStatement')
+ ->disableOriginalConstructor()
+ ->getMock();
+ $ret->method('fetch')->willReturn([]);
+ $qb->method('execute')->willReturn($ret);
+
+
+ $connection = $this->getMockBuilder('\OC\DB\Connection')
+ ->disableOriginalConstructor()
+ ->getMock();
+ $connection->method('createQueryBuilder')->willReturn($qb);
+
+ $config = $this->getMockBuilder('\OCP\IConfig')
+ ->disableOriginalConstructor()
+ ->getMock();
+
+
+ \OC\Share\Share::setPassword($userSession, $connection, $config, 1, 'pass');
+ }
+
+ /**
+ * @expectedException Exception
+ * @expectedExceptionMessage Cannot update share of a different user
+ *
+ * Test modification of share of another user
+ */
+ public function testSetPasswordShareOtherUser() {
+ $user = $this->getMockBuilder('\OCP\IUser')
+ ->disableOriginalConstructor()
+ ->getMock();
+ $user->method('getUID')->willReturn('user');
+
+ $userSession = $this->getMockBuilder('\OCP\IUserSession')
+ ->disableOriginalConstructor()
+ ->getMock();
+ $userSession->method('getUser')->willReturn($user);
+
+
+ $ex = $this->getMockBuilder('\Doctrine\DBAL\Query\Expression\ExpressionBuilder')
+ ->disableOriginalConstructor()
+ ->getMock();
+ $qb = $this->getMockBuilder('\Doctrine\DBAL\Query\QueryBuilder')
+ ->disableOriginalConstructor()
+ ->getMock();
+ $qb->method('update')->will($this->returnSelf());
+ $qb->method('set')->will($this->returnSelf());
+ $qb->method('where')->will($this->returnSelf());
+ $qb->method('andWhere')->will($this->returnSelf());
+ $qb->method('select')->will($this->returnSelf());
+ $qb->method('from')->will($this->returnSelf());
+ $qb->method('setParameter')->will($this->returnSelf());
+ $qb->method('expr')->willReturn($ex);
+
+ $ret = $this->getMockBuilder('\Doctrine\DBAL\Driver\ResultStatement')
+ ->disableOriginalConstructor()
+ ->getMock();
+ $ret->method('fetch')->willReturn(['uid_owner' => 'user2']);
+ $qb->method('execute')->willReturn($ret);
+
+
+ $connection = $this->getMockBuilder('\OC\DB\Connection')
+ ->disableOriginalConstructor()
+ ->getMock();
+ $connection->method('createQueryBuilder')->willReturn($qb);
+
+ $config = $this->getMockBuilder('\OCP\IConfig')
+ ->disableOriginalConstructor()
+ ->getMock();
+
+
+ \OC\Share\Share::setPassword($userSession, $connection, $config, 1, 'pass');
+ }
+
}
class DummyShareClass extends \OC\Share\Share {
diff --git a/tests/lib/streamwrappers.php b/tests/lib/streamwrappers.php
index fc3d02acae7..6216c5a4be8 100644
--- a/tests/lib/streamwrappers.php
+++ b/tests/lib/streamwrappers.php
@@ -72,6 +72,8 @@ class Test_StreamWrappers extends \Test\TestCase {
}
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();
diff --git a/tests/lib/testcase.php b/tests/lib/testcase.php
index a83be713194..e66dfb13353 100644
--- a/tests/lib/testcase.php
+++ b/tests/lib/testcase.php
@@ -167,9 +167,9 @@ abstract class TestCase extends \PHPUnit_Framework_TestCase {
* Login and setup FS as a given user,
* sets the given user as the current user.
*
- * @param string $user user id
+ * @param string $user user id or empty for a generic FS
*/
- static protected function loginAsUser($user) {
+ static protected function loginAsUser($user = '') {
self::logout();
\OC\Files\Filesystem::tearDown();
\OC_User::setUserId($user);
diff --git a/tests/settings/controller/AppSettingsControllerTest.php b/tests/settings/controller/AppSettingsControllerTest.php
new file mode 100644
index 00000000000..d6379deb9c8
--- /dev/null
+++ b/tests/settings/controller/AppSettingsControllerTest.php
@@ -0,0 +1,231 @@
+<?php
+/**
+ * @author Lukas Reschke <lukas@owncloud.com>
+ *
+ * @copyright Copyright (c) 2015, ownCloud, Inc.
+ * @license AGPL-3.0
+ *
+ * This code is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License, version 3,
+ * as published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License, version 3,
+ * along with this program. If not, see <http://www.gnu.org/licenses/>
+ *
+ */
+
+namespace OC\Settings\Controller;
+
+use OCP\AppFramework\Http\ContentSecurityPolicy;
+use OCP\AppFramework\Http\DataResponse;
+use OCP\AppFramework\Http\TemplateResponse;
+use Test\TestCase;
+use OCP\IRequest;
+use OCP\IL10N;
+use OCP\IConfig;
+use OCP\ICache;
+use OCP\INavigationManager;
+use OCP\App\IAppManager;
+use OC\OCSClient;
+
+/**
+ * Class AppSettingsControllerTest
+ *
+ * @package OC\Settings\Controller
+ */
+class AppSettingsControllerTest extends TestCase {
+ /** @var AppSettingsController */
+ private $appSettingsController;
+ /** @var IRequest */
+ private $request;
+ /** @var IL10N */
+ private $l10n;
+ /** @var IConfig */
+ private $config;
+ /** @var ICache */
+ private $cache;
+ /** @var INavigationManager */
+ private $navigationManager;
+ /** @var IAppManager */
+ private $appManager;
+ /** @var OCSClient */
+ private $ocsClient;
+
+ public function setUp() {
+ parent::setUp();
+
+ $this->request = $this->getMockBuilder('\OCP\IRequest')
+ ->disableOriginalConstructor()->getMock();
+ $this->l10n = $this->getMockBuilder('\OCP\IL10N')
+ ->disableOriginalConstructor()->getMock();
+ $this->l10n->expects($this->any())
+ ->method('t')
+ ->will($this->returnArgument(0));
+ $this->config = $this->getMockBuilder('\OCP\IConfig')
+ ->disableOriginalConstructor()->getMock();
+ $cacheFactory = $this->getMockBuilder('\OCP\ICacheFactory')
+ ->disableOriginalConstructor()->getMock();
+ $this->cache = $this->getMockBuilder('\OCP\ICache')
+ ->disableOriginalConstructor()->getMock();
+ $cacheFactory
+ ->expects($this->once())
+ ->method('create')
+ ->with('settings')
+ ->will($this->returnValue($this->cache));
+
+ $this->navigationManager = $this->getMockBuilder('\OCP\INavigationManager')
+ ->disableOriginalConstructor()->getMock();
+ $this->appManager = $this->getMockBuilder('\OCP\App\IAppManager')
+ ->disableOriginalConstructor()->getMock();
+ $this->ocsClient = $this->getMockBuilder('\OC\OCSClient')
+ ->disableOriginalConstructor()->getMock();
+
+ $this->appSettingsController = new AppSettingsController(
+ 'settings',
+ $this->request,
+ $this->l10n,
+ $this->config,
+ $cacheFactory,
+ $this->navigationManager,
+ $this->appManager,
+ $this->ocsClient
+ );
+ }
+
+ public function testChangeExperimentalConfigStateTrue() {
+ $this->config
+ ->expects($this->once())
+ ->method('setSystemValue')
+ ->with('appstore.experimental.enabled', true);
+ $this->appManager
+ ->expects($this->once())
+ ->method('clearAppsCache');
+ $this->assertEquals(new DataResponse(), $this->appSettingsController->changeExperimentalConfigState(true));
+ }
+
+ public function testChangeExperimentalConfigStateFalse() {
+ $this->config
+ ->expects($this->once())
+ ->method('setSystemValue')
+ ->with('appstore.experimental.enabled', false);
+ $this->appManager
+ ->expects($this->once())
+ ->method('clearAppsCache');
+ $this->assertEquals(new DataResponse(), $this->appSettingsController->changeExperimentalConfigState(false));
+ }
+
+ public function testListCategoriesCached() {
+ $this->cache
+ ->expects($this->exactly(2))
+ ->method('get')
+ ->with('listCategories')
+ ->will($this->returnValue(['CachedArray']));
+ $this->assertSame(['CachedArray'], $this->appSettingsController->listCategories());
+ }
+
+ public function testListCategoriesNotCachedWithoutAppStore() {
+ $expected = [
+ [
+ 'id' => 0,
+ 'displayName' => 'Enabled',
+ ],
+ [
+ 'id' => 1,
+ 'displayName' => 'Not enabled',
+ ],
+ ];
+ $this->cache
+ ->expects($this->once())
+ ->method('get')
+ ->with('listCategories')
+ ->will($this->returnValue(null));
+ $this->cache
+ ->expects($this->once())
+ ->method('set')
+ ->with('listCategories', $expected, 3600);
+
+
+ $this->assertSame($expected, $this->appSettingsController->listCategories());
+ }
+
+ public function testListCategoriesNotCachedWithAppStore() {
+ $expected = [
+ [
+ 'id' => 0,
+ 'displayName' => 'Enabled',
+ ],
+ [
+ 'id' => 1,
+ 'displayName' => 'Not enabled',
+ ],
+ [
+ 'id' => 0,
+ 'displayName' => 'Tools',
+ ],
+ [
+ 'id' => 1,
+ 'displayName' => 'Awesome Games',
+ ],
+ [
+ 'id' => 2,
+ 'displayName' => 'PIM',
+ ],
+ [
+ 'id' => 3,
+ 'displayName' => 'Papershop',
+ ],
+ ];
+
+ $this->cache
+ ->expects($this->once())
+ ->method('get')
+ ->with('listCategories')
+ ->will($this->returnValue(null));
+ $this->cache
+ ->expects($this->once())
+ ->method('set')
+ ->with('listCategories', $expected, 3600);
+
+ $this->ocsClient
+ ->expects($this->once())
+ ->method('isAppStoreEnabled')
+ ->will($this->returnValue(true));
+ $this->ocsClient
+ ->expects($this->once())
+ ->method('getCategories')
+ ->will($this->returnValue(
+ [
+ 'ownCloud Tools',
+ 'Awesome Games',
+ 'ownCloud PIM',
+ 'Papershop',
+ ]
+ ));
+
+ $this->assertSame($expected, $this->appSettingsController->listCategories());
+ }
+
+ public function testViewApps() {
+ $this->config
+ ->expects($this->once())
+ ->method('getSystemValue')
+ ->with('appstore.experimental.enabled', false);
+ $this->navigationManager
+ ->expects($this->once())
+ ->method('setActiveEntry')
+ ->with('core_apps');
+
+ $policy = new ContentSecurityPolicy();
+ $policy->addAllowedImageDomain('https://apps.owncloud.com');
+
+ $expected = new TemplateResponse('settings', 'apps', ['experimentalEnabled' => false], 'user');
+ $expected->setContentSecurityPolicy($policy);
+
+ $this->assertEquals($expected, $this->appSettingsController->viewApps());
+ }
+}