From bc49c6be04d78740d9b7cb100debcb6641559d39 Mon Sep 17 00:00:00 2001 From: Robin Appelman Date: Wed, 26 Feb 2014 14:29:13 +0100 Subject: Manually triger the filecache update hooks before any other hook --- tests/lib/files/cache/updater.php | 5 ----- 1 file changed, 5 deletions(-) (limited to 'tests') diff --git a/tests/lib/files/cache/updater.php b/tests/lib/files/cache/updater.php index 48986149a73..1c4c965af0b 100644 --- a/tests/lib/files/cache/updater.php +++ b/tests/lib/files/cache/updater.php @@ -65,11 +65,6 @@ class Updater extends \PHPUnit_Framework_TestCase { Filesystem::mount($this->storage, array(), '/' . self::$user . '/files'); \OC_Hook::clear('OC_Filesystem'); - - \OC_Hook::connect('OC_Filesystem', 'post_write', '\OC\Files\Cache\Updater', 'writeHook'); - \OC_Hook::connect('OC_Filesystem', 'post_delete', '\OC\Files\Cache\Updater', 'deleteHook'); - \OC_Hook::connect('OC_Filesystem', 'post_rename', '\OC\Files\Cache\Updater', 'renameHook'); - \OC_Hook::connect('OC_Filesystem', 'post_touch', '\OC\Files\Cache\Updater', 'touchHook'); } public function tearDown() { -- cgit v1.2.3 From 459b5086d56d97b2ccf42b1fd50a7924883b6c7a Mon Sep 17 00:00:00 2001 From: Thomas Müller Date: Wed, 26 Feb 2014 20:42:45 +0100 Subject: adding test for migrations on columns using keywords --- tests/data/db_structure.xml | 15 +++++++++++++++ tests/data/db_structure2.xml | 15 +++++++++++++++ 2 files changed, 30 insertions(+) (limited to 'tests') diff --git a/tests/data/db_structure.xml b/tests/data/db_structure.xml index d98066c4b7e..5fffd5475f9 100644 --- a/tests/data/db_structure.xml +++ b/tests/data/db_structure.xml @@ -223,4 +223,19 @@ + + *dbprefix*migratekeyword + + + + + key + text + + true + 255 + + +
+ diff --git a/tests/data/db_structure2.xml b/tests/data/db_structure2.xml index ae5f22e9573..aa6e94a2a84 100644 --- a/tests/data/db_structure2.xml +++ b/tests/data/db_structure2.xml @@ -119,4 +119,19 @@ + + *dbprefix*migratekeyword + + + + + key + text + + false + 255 + + +
+ -- cgit v1.2.3 From 230e5e3788f8289447602b70e2445c134e532e0d Mon Sep 17 00:00:00 2001 From: Thomas Müller Date: Wed, 26 Feb 2014 20:47:07 +0100 Subject: let's name the column 'select' because this is a keyword on all platforms --- tests/data/db_structure.xml | 2 +- tests/data/db_structure2.xml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) (limited to 'tests') diff --git a/tests/data/db_structure.xml b/tests/data/db_structure.xml index 5fffd5475f9..858c9ab1002 100644 --- a/tests/data/db_structure.xml +++ b/tests/data/db_structure.xml @@ -229,7 +229,7 @@ - key + select text true diff --git a/tests/data/db_structure2.xml b/tests/data/db_structure2.xml index aa6e94a2a84..568d90ab0a9 100644 --- a/tests/data/db_structure2.xml +++ b/tests/data/db_structure2.xml @@ -125,7 +125,7 @@ - key + select text false -- cgit v1.2.3 From 39f2f564a99ebe719748f349aafe92ed9910bc0b Mon Sep 17 00:00:00 2001 From: Jörn Friedrich Dreyer Date: Thu, 27 Feb 2014 09:39:34 +0100 Subject: use assertSame and assertNotSame for etag checks --- apps/files_encryption/tests/util.php | 4 ++-- tests/lib/appframework/http/ResponseTest.php | 2 +- tests/lib/files/cache/scanner.php | 26 ++++++++++++++++++-------- tests/lib/files/etagtest.php | 6 +++++- tests/lib/files/view.php | 2 +- 5 files changed, 27 insertions(+), 13 deletions(-) (limited to 'tests') diff --git a/apps/files_encryption/tests/util.php b/apps/files_encryption/tests/util.php index f70e30c4d73..203ba55dbfd 100755 --- a/apps/files_encryption/tests/util.php +++ b/apps/files_encryption/tests/util.php @@ -344,7 +344,7 @@ class Test_Encryption_Util extends \PHPUnit_Framework_TestCase { // check if mtime and etags unchanged $this->assertEquals($fileInfoEncrypted['mtime'], $fileInfoUnencrypted['mtime']); - $this->assertEquals($fileInfoEncrypted['etag'], $fileInfoUnencrypted['etag']); + $this->assertSame($fileInfoEncrypted['etag'], $fileInfoUnencrypted['etag']); $this->view->unlink($this->userId . '/files/' . $filename); } @@ -373,7 +373,7 @@ class Test_Encryption_Util extends \PHPUnit_Framework_TestCase { // check if mtime and etags unchanged $this->assertEquals($fileInfoEncrypted['mtime'], $fileInfoUnencrypted['mtime']); - $this->assertEquals($fileInfoEncrypted['etag'], $fileInfoUnencrypted['etag']); + $this->assertSame($fileInfoEncrypted['etag'], $fileInfoUnencrypted['etag']); // file should no longer be encrypted $this->assertEquals(0, $fileInfoUnencrypted['encrypted']); diff --git a/tests/lib/appframework/http/ResponseTest.php b/tests/lib/appframework/http/ResponseTest.php index 4f21d77a170..063ab8b5d33 100644 --- a/tests/lib/appframework/http/ResponseTest.php +++ b/tests/lib/appframework/http/ResponseTest.php @@ -78,7 +78,7 @@ class ResponseTest extends \PHPUnit_Framework_TestCase { public function testGetEtag() { $this->childResponse->setEtag('hi'); - $this->assertEquals('hi', $this->childResponse->getEtag()); + $this->assertSame('hi', $this->childResponse->getEtag()); } diff --git a/tests/lib/files/cache/scanner.php b/tests/lib/files/cache/scanner.php index 3f5604b4d45..9df98c36fa8 100644 --- a/tests/lib/files/cache/scanner.php +++ b/tests/lib/files/cache/scanner.php @@ -150,13 +150,15 @@ class Scanner extends \PHPUnit_Framework_TestCase { $this->cache->put('folder', array('mtime' => $this->storage->filemtime('folder'), 'storage_mtime' => $this->storage->filemtime('folder'))); $this->scanner->scan('', \OC\Files\Cache\Scanner::SCAN_SHALLOW, \OC\Files\Cache\Scanner::REUSE_SIZE); $newData = $this->cache->get(''); - $this->assertNotEquals($oldData['etag'], $newData['etag']); + $this->assertTrue(is_string($oldData['etag']), 'Expected a string'); + $this->assertTrue(is_string($newData['etag']), 'Expected a string'); + $this->assertNotSame($oldData['etag'], $newData['etag']); $this->assertEquals($oldData['size'], $newData['size']); $oldData = $newData; $this->scanner->scan('', \OC\Files\Cache\Scanner::SCAN_SHALLOW, \OC\Files\Cache\Scanner::REUSE_ETAG); $newData = $this->cache->get(''); - $this->assertEquals($oldData['etag'], $newData['etag']); + $this->assertSame($oldData['etag'], $newData['etag']); $this->assertEquals(-1, $newData['size']); $this->scanner->scan('', \OC\Files\Cache\Scanner::SCAN_RECURSIVE); @@ -164,17 +166,17 @@ class Scanner extends \PHPUnit_Framework_TestCase { $this->assertNotEquals(-1, $oldData['size']); $this->scanner->scanFile('', \OC\Files\Cache\Scanner::REUSE_ETAG + \OC\Files\Cache\Scanner::REUSE_SIZE); $newData = $this->cache->get(''); - $this->assertEquals($oldData['etag'], $newData['etag']); + $this->assertSame($oldData['etag'], $newData['etag']); $this->assertEquals($oldData['size'], $newData['size']); $this->scanner->scan('', \OC\Files\Cache\Scanner::SCAN_RECURSIVE, \OC\Files\Cache\Scanner::REUSE_ETAG + \OC\Files\Cache\Scanner::REUSE_SIZE); $newData = $this->cache->get(''); - $this->assertEquals($oldData['etag'], $newData['etag']); + $this->assertSame($oldData['etag'], $newData['etag']); $this->assertEquals($oldData['size'], $newData['size']); $this->scanner->scan('', \OC\Files\Cache\Scanner::SCAN_SHALLOW, \OC\Files\Cache\Scanner::REUSE_ETAG + \OC\Files\Cache\Scanner::REUSE_SIZE); $newData = $this->cache->get(''); - $this->assertEquals($oldData['etag'], $newData['etag']); + $this->assertSame($oldData['etag'], $newData['etag']); $this->assertEquals($oldData['size'], $newData['size']); } @@ -217,8 +219,11 @@ class Scanner extends \PHPUnit_Framework_TestCase { // manipulate etag to simulate an empty etag $this->scanner->scan('', \OC\Files\Cache\Scanner::SCAN_SHALLOW, \OC\Files\Cache\Scanner::REUSE_ETAG); $data0 = $this->cache->get('folder/bar.txt'); + $this->assertTrue(is_string($data0['etag']), 'Expected a string'); $data1 = $this->cache->get('folder'); + $this->assertTrue(is_string($data1['etag']), 'Expected a string'); $data2 = $this->cache->get(''); + $this->assertTrue(is_string($data2['etag']), 'Expected a string'); $data0['etag'] = ''; $this->cache->put('folder/bar.txt', $data0); @@ -227,10 +232,15 @@ class Scanner extends \PHPUnit_Framework_TestCase { // verify cache content $newData0 = $this->cache->get('folder/bar.txt'); + $this->assertTrue(is_string($newData0['etag']), 'Expected a string'); + $this->assertNotEmpty($newData0['etag']); + $newData1 = $this->cache->get('folder'); + $this->assertTrue(is_string($newData1['etag']), 'Expected a string'); + $this->assertNotSame($data1['etag'], $newData1['etag']); + $newData2 = $this->cache->get(''); - $this->assertNotEmpty($newData0['etag']); - $this->assertNotEquals($data1['etag'], $newData1['etag']); - $this->assertNotEquals($data2['etag'], $newData2['etag']); + $this->assertTrue(is_string($newData2['etag']), 'Expected a string'); + $this->assertNotSame($data2['etag'], $newData2['etag']); } } diff --git a/tests/lib/files/etagtest.php b/tests/lib/files/etagtest.php index ce05adb188a..af9f66835f0 100644 --- a/tests/lib/files/etagtest.php +++ b/tests/lib/files/etagtest.php @@ -65,7 +65,11 @@ class EtagTest extends \PHPUnit_Framework_TestCase { $scanner = new \OC\Files\Utils\Scanner($user1); $scanner->backgroundScan('/'); - $this->assertEquals($originalEtags, $this->getEtags($files)); + $newEtags = $this->getEtags($files); + // loop over array and use assertSame over assertEquals to prevent false positives + foreach ($originalEtags as $file => $originalEtag) { + $this->assertSame($originalEtag, $newEtags[$file]); + } } /** diff --git a/tests/lib/files/view.php b/tests/lib/files/view.php index 371d1ed1798..c85f1128dbe 100644 --- a/tests/lib/files/view.php +++ b/tests/lib/files/view.php @@ -563,6 +563,6 @@ class View extends \PHPUnit_Framework_TestCase { $scanner->scanFile('test', \OC\Files\Cache\Scanner::REUSE_ETAG); $info2 = $view->getFileInfo('/test/test'); - $this->assertEquals($info['etag'], $info2['etag']); + $this->assertSame($info['etag'], $info2['etag']); } } -- cgit v1.2.3 From 131c12ad8d51c4a0acad03299bd617907c9f1d66 Mon Sep 17 00:00:00 2001 From: Jörn Friedrich Dreyer Date: Thu, 27 Feb 2014 09:51:26 +0100 Subject: use assertInternalType for typechecking --- tests/lib/files/cache/scanner.php | 16 ++++---- tests/lib/files/cache/updater.php | 84 +++++++++++++++++++++++++++++---------- 2 files changed, 71 insertions(+), 29 deletions(-) (limited to 'tests') diff --git a/tests/lib/files/cache/scanner.php b/tests/lib/files/cache/scanner.php index 9df98c36fa8..5182fac8b10 100644 --- a/tests/lib/files/cache/scanner.php +++ b/tests/lib/files/cache/scanner.php @@ -150,8 +150,8 @@ class Scanner extends \PHPUnit_Framework_TestCase { $this->cache->put('folder', array('mtime' => $this->storage->filemtime('folder'), 'storage_mtime' => $this->storage->filemtime('folder'))); $this->scanner->scan('', \OC\Files\Cache\Scanner::SCAN_SHALLOW, \OC\Files\Cache\Scanner::REUSE_SIZE); $newData = $this->cache->get(''); - $this->assertTrue(is_string($oldData['etag']), 'Expected a string'); - $this->assertTrue(is_string($newData['etag']), 'Expected a string'); + $this->assertInternalType('string', $oldData['etag']); + $this->assertInternalType('string', $newData['etag']); $this->assertNotSame($oldData['etag'], $newData['etag']); $this->assertEquals($oldData['size'], $newData['size']); @@ -219,11 +219,11 @@ class Scanner extends \PHPUnit_Framework_TestCase { // manipulate etag to simulate an empty etag $this->scanner->scan('', \OC\Files\Cache\Scanner::SCAN_SHALLOW, \OC\Files\Cache\Scanner::REUSE_ETAG); $data0 = $this->cache->get('folder/bar.txt'); - $this->assertTrue(is_string($data0['etag']), 'Expected a string'); + $this->assertInternalType('string', $data0['etag']); $data1 = $this->cache->get('folder'); - $this->assertTrue(is_string($data1['etag']), 'Expected a string'); + $this->assertInternalType('string', $data1['etag']); $data2 = $this->cache->get(''); - $this->assertTrue(is_string($data2['etag']), 'Expected a string'); + $this->assertInternalType('string', $data2['etag']); $data0['etag'] = ''; $this->cache->put('folder/bar.txt', $data0); @@ -232,15 +232,15 @@ class Scanner extends \PHPUnit_Framework_TestCase { // verify cache content $newData0 = $this->cache->get('folder/bar.txt'); - $this->assertTrue(is_string($newData0['etag']), 'Expected a string'); + $this->assertInternalType('string', $newData0['etag']); $this->assertNotEmpty($newData0['etag']); $newData1 = $this->cache->get('folder'); - $this->assertTrue(is_string($newData1['etag']), 'Expected a string'); + $this->assertInternalType('string', $newData1['etag']); $this->assertNotSame($data1['etag'], $newData1['etag']); $newData2 = $this->cache->get(''); - $this->assertTrue(is_string($newData2['etag']), 'Expected a string'); + $this->assertInternalType('string', $newData2['etag']); $this->assertNotSame($data2['etag'], $newData2['etag']); } } diff --git a/tests/lib/files/cache/updater.php b/tests/lib/files/cache/updater.php index 48986149a73..57c799e608b 100644 --- a/tests/lib/files/cache/updater.php +++ b/tests/lib/files/cache/updater.php @@ -96,10 +96,14 @@ class Updater extends \PHPUnit_Framework_TestCase { Filesystem::file_put_contents('foo.txt', 'asd'); $cachedData = $this->cache->get('foo.txt'); $this->assertEquals(3, $cachedData['size']); - $this->assertNotEquals($fooCachedData['etag'], $cachedData['etag']); + $this->assertInternalType('string', $fooCachedData['etag']); + $this->assertInternalType('string', $cachedData['etag']); + $this->assertNotSame($fooCachedData['etag'], $cachedData['etag']); $cachedData = $this->cache->get(''); $this->assertEquals(2 * $textSize + $imageSize + 3, $cachedData['size']); - $this->assertNotEquals($rootCachedData['etag'], $cachedData['etag']); + $this->assertInternalType('string', $rootCachedData['etag']); + $this->assertInternalType('string', $cachedData['etag']); + $this->assertNotSame($rootCachedData['etag'], $cachedData['etag']); $rootCachedData = $cachedData; $this->assertFalse($this->cache->inCache('bar.txt')); @@ -110,7 +114,9 @@ class Updater extends \PHPUnit_Framework_TestCase { $mtime = $cachedData['mtime']; $cachedData = $this->cache->get(''); $this->assertEquals(2 * $textSize + $imageSize + 2 * 3, $cachedData['size']); - $this->assertNotEquals($rootCachedData['etag'], $cachedData['etag']); + $this->assertInternalType('string', $rootCachedData['etag']); + $this->assertInternalType('string', $cachedData['etag']); + $this->assertNotSame($rootCachedData['etag'], $cachedData['etag']); $this->assertGreaterThanOrEqual($rootCachedData['mtime'], $mtime); } @@ -127,11 +133,15 @@ class Updater extends \PHPUnit_Framework_TestCase { $mtime = $cachedData['mtime']; $cachedData = $cache2->get(''); - $this->assertNotEquals($substorageCachedData['etag'], $cachedData['etag']); + $this->assertInternalType('string', $substorageCachedData['etag']); + $this->assertInternalType('string', $cachedData['etag']); + $this->assertNotSame($substorageCachedData['etag'], $cachedData['etag']); $this->assertEquals($mtime, $cachedData['mtime']); $cachedData = $this->cache->get('folder'); - $this->assertNotEquals($folderCachedData['etag'], $cachedData['etag']); + $this->assertInternalType('string', $folderCachedData['etag']); + $this->assertInternalType('string', $cachedData['etag']); + $this->assertNotSame($folderCachedData['etag'], $cachedData['etag']); $this->assertEquals($mtime, $cachedData['mtime']); } @@ -146,19 +156,25 @@ class Updater extends \PHPUnit_Framework_TestCase { $this->assertFalse($this->cache->inCache('foo.txt')); $cachedData = $this->cache->get(''); $this->assertEquals(2 * $textSize + $imageSize, $cachedData['size']); - $this->assertNotEquals($rootCachedData['etag'], $cachedData['etag']); + $this->assertInternalType('string', $rootCachedData['etag']); + $this->assertInternalType('string', $cachedData['etag']); + $this->assertNotSame($rootCachedData['etag'], $cachedData['etag']); $this->assertGreaterThanOrEqual($rootCachedData['mtime'], $cachedData['mtime']); $rootCachedData = $cachedData; Filesystem::mkdir('bar_folder'); $this->assertTrue($this->cache->inCache('bar_folder')); $cachedData = $this->cache->get(''); - $this->assertNotEquals($rootCachedData['etag'], $cachedData['etag']); + $this->assertInternalType('string', $rootCachedData['etag']); + $this->assertInternalType('string', $cachedData['etag']); + $this->assertNotSame($rootCachedData['etag'], $cachedData['etag']); $rootCachedData = $cachedData; Filesystem::rmdir('bar_folder'); $this->assertFalse($this->cache->inCache('bar_folder')); $cachedData = $this->cache->get(''); - $this->assertNotEquals($rootCachedData['etag'], $cachedData['etag']); + $this->assertInternalType('string', $rootCachedData['etag']); + $this->assertInternalType('string', $cachedData['etag']); + $this->assertNotSame($rootCachedData['etag'], $cachedData['etag']); $this->assertGreaterThanOrEqual($rootCachedData['mtime'], $cachedData['mtime']); } @@ -174,11 +190,15 @@ class Updater extends \PHPUnit_Framework_TestCase { $this->assertFalse($cache2->inCache('foo.txt')); $cachedData = $cache2->get(''); - $this->assertNotEquals($substorageCachedData['etag'], $cachedData['etag']); + $this->assertInternalType('string', $substorageCachedData['etag']); + $this->assertInternalType('string', $cachedData['etag']); + $this->assertNotSame($substorageCachedData['etag'], $cachedData['etag']); $this->assertGreaterThanOrEqual($substorageCachedData['mtime'], $cachedData['mtime']); $cachedData = $this->cache->get('folder'); - $this->assertNotEquals($folderCachedData['etag'], $cachedData['etag']); + $this->assertInternalType('string', $folderCachedData['etag']); + $this->assertInternalType('string', $cachedData['etag']); + $this->assertNotSame($folderCachedData['etag'], $cachedData['etag']); $this->assertGreaterThanOrEqual($folderCachedData['mtime'], $cachedData['mtime']); } @@ -199,7 +219,9 @@ class Updater extends \PHPUnit_Framework_TestCase { $mtime = $cachedData['mtime']; $cachedData = $this->cache->get(''); $this->assertEquals(3 * $textSize + $imageSize, $cachedData['size']); - $this->assertNotEquals($rootCachedData['etag'], $cachedData['etag']); + $this->assertInternalType('string', $rootCachedData['etag']); + $this->assertInternalType('string', $cachedData['etag']); + $this->assertNotSame($rootCachedData['etag'], $cachedData['etag']); } public function testRenameExtension() { @@ -227,12 +249,16 @@ class Updater extends \PHPUnit_Framework_TestCase { $mtime = $cachedData['mtime']; $cachedData = $cache2->get(''); - $this->assertNotEquals($substorageCachedData['etag'], $cachedData['etag']); + $this->assertInternalType('string', $substorageCachedData['etag']); + $this->assertInternalType('string', $cachedData['etag']); + $this->assertNotSame($substorageCachedData['etag'], $cachedData['etag']); // rename can cause mtime change - invalid assert // $this->assertEquals($mtime, $cachedData['mtime']); $cachedData = $this->cache->get('folder'); - $this->assertNotEquals($folderCachedData['etag'], $cachedData['etag']); + $this->assertInternalType('string', $folderCachedData['etag']); + $this->assertInternalType('string', $cachedData['etag']); + $this->assertNotSame($folderCachedData['etag'], $cachedData['etag']); // rename can cause mtime change - invalid assert // $this->assertEquals($mtime, $cachedData['mtime']); } @@ -242,11 +268,15 @@ class Updater extends \PHPUnit_Framework_TestCase { $fooCachedData = $this->cache->get('foo.txt'); Filesystem::touch('foo.txt'); $cachedData = $this->cache->get('foo.txt'); - $this->assertNotEquals($fooCachedData['etag'], $cachedData['etag']); + $this->assertInternalType('string', $fooCachedData['etag']); + $this->assertInternalType('string', $cachedData['etag']); + $this->assertNotSame($fooCachedData['etag'], $cachedData['etag']); $this->assertGreaterThanOrEqual($fooCachedData['mtime'], $cachedData['mtime']); $cachedData = $this->cache->get(''); - $this->assertNotEquals($rootCachedData['etag'], $cachedData['etag']); + $this->assertInternalType('string', $rootCachedData['etag']); + $this->assertInternalType('string', $cachedData['etag']); + $this->assertNotSame($rootCachedData['etag'], $cachedData['etag']); $this->assertGreaterThanOrEqual($rootCachedData['mtime'], $cachedData['mtime']); $rootCachedData = $cachedData; @@ -255,14 +285,20 @@ class Updater extends \PHPUnit_Framework_TestCase { $folderCachedData = $this->cache->get('folder'); Filesystem::touch('folder/bar.txt', $time); $cachedData = $this->cache->get('folder/bar.txt'); - $this->assertNotEquals($barCachedData['etag'], $cachedData['etag']); + $this->assertInternalType('string', $barCachedData['etag']); + $this->assertInternalType('string', $cachedData['etag']); + $this->assertNotSame($barCachedData['etag'], $cachedData['etag']); $this->assertEquals($time, $cachedData['mtime']); $cachedData = $this->cache->get('folder'); - $this->assertNotEquals($folderCachedData['etag'], $cachedData['etag']); + $this->assertInternalType('string', $folderCachedData['etag']); + $this->assertInternalType('string', $cachedData['etag']); + $this->assertNotSame($folderCachedData['etag'], $cachedData['etag']); $cachedData = $this->cache->get(''); - $this->assertNotEquals($rootCachedData['etag'], $cachedData['etag']); + $this->assertInternalType('string', $rootCachedData['etag']); + $this->assertInternalType('string', $cachedData['etag']); + $this->assertNotSame($rootCachedData['etag'], $cachedData['etag']); $this->assertEquals($time, $cachedData['mtime']); } @@ -279,14 +315,20 @@ class Updater extends \PHPUnit_Framework_TestCase { $time = 1371006070; Filesystem::touch('folder/substorage/foo.txt', $time); $cachedData = $cache2->get('foo.txt'); - $this->assertNotEquals($fooCachedData['etag'], $cachedData['etag']); + $this->assertInternalType('string', $fooCachedData['etag']); + $this->assertInternalType('string', $cachedData['etag']); + $this->assertNotSame($fooCachedData['etag'], $cachedData['etag']); $this->assertEquals($time, $cachedData['mtime']); $cachedData = $cache2->get(''); - $this->assertNotEquals($substorageCachedData['etag'], $cachedData['etag']); + $this->assertInternalType('string', $substorageCachedData['etag']); + $this->assertInternalType('string', $cachedData['etag']); + $this->assertNotSame($substorageCachedData['etag'], $cachedData['etag']); $cachedData = $this->cache->get('folder'); - $this->assertNotEquals($folderCachedData['etag'], $cachedData['etag']); + $this->assertInternalType('string', $folderCachedData['etag']); + $this->assertInternalType('string', $cachedData['etag']); + $this->assertNotSame($folderCachedData['etag'], $cachedData['etag']); $this->assertEquals($time, $cachedData['mtime']); } -- cgit v1.2.3 From 2ba6cd4e2b779d43424fd2a037319923749666d2 Mon Sep 17 00:00:00 2001 From: Jörn Friedrich Dreyer Date: Thu, 27 Feb 2014 12:42:53 +0100 Subject: initialize etags of temporary storage --- tests/lib/files/cache/updater.php | 1 + 1 file changed, 1 insertion(+) (limited to 'tests') diff --git a/tests/lib/files/cache/updater.php b/tests/lib/files/cache/updater.php index 57c799e608b..a6ee8c46661 100644 --- a/tests/lib/files/cache/updater.php +++ b/tests/lib/files/cache/updater.php @@ -122,6 +122,7 @@ class Updater extends \PHPUnit_Framework_TestCase { public function testWriteWithMountPoints() { $storage2 = new \OC\Files\Storage\Temporary(array()); + $storage2->getScanner()->scan(''); //initialize etags $cache2 = $storage2->getCache(); Filesystem::mount($storage2, array(), '/' . self::$user . '/files/folder/substorage'); $folderCachedData = $this->cache->get('folder'); -- cgit v1.2.3 From 35a8dfb2fa7970098e6677f7b93b7d782d5df7f0 Mon Sep 17 00:00:00 2001 From: Bart Visscher Date: Fri, 28 Feb 2014 13:53:41 +0100 Subject: More PHPDoc fixes, using scrutinizer patches as hints --- lib/private/appconfig.php | 4 ++-- lib/private/cache.php | 2 +- lib/private/contactsmanager.php | 4 ++-- lib/private/db.php | 5 ++--- lib/private/image.php | 2 +- lib/private/legacy/appconfig.php | 2 -- lib/private/request.php | 2 +- lib/private/share/mailnotifications.php | 3 +-- lib/public/contacts/imanager.php | 4 ++-- lib/public/iappconfig.php | 5 ++--- tests/lib/appframework/routing/RoutingTest.php | 6 +++--- tests/lib/dbschema.php | 3 +++ 12 files changed, 20 insertions(+), 22 deletions(-) (limited to 'tests') diff --git a/lib/private/appconfig.php b/lib/private/appconfig.php index cdaaebb87e5..cfb84309c67 100644 --- a/lib/private/appconfig.php +++ b/lib/private/appconfig.php @@ -218,8 +218,8 @@ class AppConfig implements \OCP\IAppConfig { /** * get multiply values, either the app or key can be used as wildcard by setting it to false * - * @param boolean $app - * @param string $key + * @param string|false $app + * @param string|false $key * @return array */ public function getValues($app, $key) { diff --git a/lib/private/cache.php b/lib/private/cache.php index a311f10a00f..961270c334c 100644 --- a/lib/private/cache.php +++ b/lib/private/cache.php @@ -97,7 +97,7 @@ class Cache { /** * creates cache key based on the files given - * @param $files + * @param string[] $files * @return string */ static public function generateCacheKeyFromFiles($files) { diff --git a/lib/private/contactsmanager.php b/lib/private/contactsmanager.php index fc6745b4505..1cb3da7098f 100644 --- a/lib/private/contactsmanager.php +++ b/lib/private/contactsmanager.php @@ -47,7 +47,7 @@ namespace OC { * This function can be used to delete the contact identified by the given id * * @param object $id the unique identifier to a contact - * @param $address_book_key + * @param string $address_book_key identifier of the address book in which the contact shall be deleted * @return bool successful or not */ public function delete($id, $address_book_key) { @@ -66,7 +66,7 @@ namespace OC { * Otherwise the contact will be updated by replacing the entire data set. * * @param array $properties this array if key-value-pairs defines a contact - * @param $address_book_key string to identify the address book in which the contact shall be created or updated + * @param string $address_book_key identifier of the address book in which the contact shall be created or updated * @return array representing the contact just created or updated */ public function createOrUpdate($properties, $address_book_key) { diff --git a/lib/private/db.php b/lib/private/db.php index cfdac766bff..322a13642ae 100644 --- a/lib/private/db.php +++ b/lib/private/db.php @@ -313,9 +313,8 @@ class OC_DB { /** * @brief Insert a row if a matching row doesn't exists. - * @param string $table. The table to insert into in the form '*PREFIX*tableName' - * @param array $input. An array of fieldname/value pairs - * @param string $table + * @param string $table The table to insert into in the form '*PREFIX*tableName' + * @param array $input An array of fieldname/value pairs * @return boolean number of updated rows */ public static function insertIfNotExist($table, $input) { diff --git a/lib/private/image.php b/lib/private/image.php index 17caaa012f5..e0397ec8a00 100644 --- a/lib/private/image.php +++ b/lib/private/image.php @@ -34,7 +34,7 @@ class OC_Image { /** * @brief Get mime type for an image file. - * @param string|null $filepath The path to a local image file. + * @param string|null $filePath The path to a local image file. * @returns string The mime type if the it could be determined, otherwise an empty string. */ static public function getMimeTypeForFile($filePath) { diff --git a/lib/private/legacy/appconfig.php b/lib/private/legacy/appconfig.php index b6c3542a673..cb5cef7e350 100644 --- a/lib/private/legacy/appconfig.php +++ b/lib/private/legacy/appconfig.php @@ -116,8 +116,6 @@ class OC_Appconfig { /** * get multiply values, either the app or key can be used as wildcard by setting it to false * - * @param app - * @param key * @param string|false $app * @param string|false $key * @return array diff --git a/lib/private/request.php b/lib/private/request.php index afd3fda4f2d..59a9e395e85 100755 --- a/lib/private/request.php +++ b/lib/private/request.php @@ -26,7 +26,7 @@ class OC_Request { /** * @brief Checks whether a domain is considered as trusted. This is used to prevent Host Header Poisoning. - * @param string $host + * @param string $domain * @return bool */ public static function isTrustedDomain($domain) { diff --git a/lib/private/share/mailnotifications.php b/lib/private/share/mailnotifications.php index 360376294cc..afbf35aa397 100644 --- a/lib/private/share/mailnotifications.php +++ b/lib/private/share/mailnotifications.php @@ -30,7 +30,6 @@ class MailNotifications { /** * - * @param string $recipient user id * @param string $sender user id (if nothing is set we use the currently logged-in user) */ public function __construct($sender = null) { @@ -113,7 +112,7 @@ class MailNotifications { * @param string $filename the shared file * @param string $link the public link * @param int $expiration expiration date (timestamp) - * @return mixed $result true or error message + * @return string|boolean $result true or error message */ public function sendLinkShareMail($recipient, $filename, $link, $expiration) { $subject = (string)$this->l->t('%s shared »%s« with you', array($this->senderDisplayName, $filename)); diff --git a/lib/public/contacts/imanager.php b/lib/public/contacts/imanager.php index 5b9d64ecc41..005b71f298b 100644 --- a/lib/public/contacts/imanager.php +++ b/lib/public/contacts/imanager.php @@ -96,7 +96,7 @@ namespace OCP\Contacts { * This function can be used to delete the contact identified by the given id * * @param object $id the unique identifier to a contact - * @param $address_book_key + * @param string $address_book_key identifier of the address book in which the contact shall be deleted * @return bool successful or not */ function delete($id, $address_book_key); @@ -106,7 +106,7 @@ namespace OCP\Contacts { * Otherwise the contact will be updated by replacing the entire data set. * * @param array $properties this array if key-value-pairs defines a contact - * @param $address_book_key string to identify the address book in which the contact shall be created or updated + * @param string $address_book_key identifier of the address book in which the contact shall be created or updated * @return array representing the contact just created or updated */ function createOrUpdate($properties, $address_book_key); diff --git a/lib/public/iappconfig.php b/lib/public/iappconfig.php index 1f31898bf2c..2b014df2e42 100644 --- a/lib/public/iappconfig.php +++ b/lib/public/iappconfig.php @@ -55,9 +55,8 @@ interface IAppConfig { /** * get multiply values, either the app or key can be used as wildcard by setting it to false * - * @param app - * @param key - * @param string $key + * @param string|false $key + * @param string|false $app * @return array */ public function getValues($app, $key); diff --git a/tests/lib/appframework/routing/RoutingTest.php b/tests/lib/appframework/routing/RoutingTest.php index d0244cf2511..56e625fd168 100644 --- a/tests/lib/appframework/routing/RoutingTest.php +++ b/tests/lib/appframework/routing/RoutingTest.php @@ -166,9 +166,9 @@ class RouteConfigTest extends \PHPUnit_Framework_TestCase } /** - * @param $verb - * @param $controllerName - * @param $actionName + * @param string $verb + * @param string $controllerName + * @param string $actionName * @return \PHPUnit_Framework_MockObject_MockObject */ private function mockRoute($verb, $controllerName, $actionName) diff --git a/tests/lib/dbschema.php b/tests/lib/dbschema.php index 11e9fcdf4fa..cfa2d6fd9aa 100644 --- a/tests/lib/dbschema.php +++ b/tests/lib/dbschema.php @@ -71,6 +71,9 @@ class Test_DBSchema extends PHPUnit_Framework_TestCase { $this->assertTableNotExist($this->table2); } + /** + * @param string $table + */ public function tableExist($table) { switch (OC_Config::getValue( 'dbtype', 'sqlite' )) { -- cgit v1.2.3 From 331fc55e2d876123580986264f47318afcf9352b Mon Sep 17 00:00:00 2001 From: Robin Appelman Date: Mon, 3 Mar 2014 14:27:24 +0100 Subject: Update unit tests to use the new injection --- .../sabre/aborteduploaddetectionplugin.php | 27 ++++---- tests/lib/connector/sabre/directory.php | 22 ++++-- tests/lib/connector/sabre/file.php | 81 ++++++++++++++++++---- tests/lib/connector/sabre/objecttree.php | 14 +++- tests/lib/connector/sabre/quotaplugin.php | 23 +++--- 5 files changed, 120 insertions(+), 47 deletions(-) (limited to 'tests') diff --git a/tests/lib/connector/sabre/aborteduploaddetectionplugin.php b/tests/lib/connector/sabre/aborteduploaddetectionplugin.php index 201f1263867..60d141e72bc 100644 --- a/tests/lib/connector/sabre/aborteduploaddetectionplugin.php +++ b/tests/lib/connector/sabre/aborteduploaddetectionplugin.php @@ -1,11 +1,11 @@ * This file is licensed under the Affero General Public License version 3 or * later. * See the COPYING-README file. */ - class Test_OC_Connector_Sabre_AbortedUploadDetectionPlugin extends PHPUnit_Framework_TestCase { /** @@ -18,17 +18,18 @@ class Test_OC_Connector_Sabre_AbortedUploadDetectionPlugin extends PHPUnit_Frame */ private $plugin; - public function setUp() { + private function init($view) { $this->server = new Sabre_DAV_Server(); - $this->plugin = new OC_Connector_Sabre_AbortedUploadDetectionPlugin(); + $this->plugin = new OC_Connector_Sabre_AbortedUploadDetectionPlugin($view); $this->plugin->initialize($this->server); } /** * @dataProvider lengthProvider */ - public function testLength($expected, $headers) - { + public function testLength($expected, $headers) { + $this->init(null); + $this->server->httpRequest = new Sabre_HTTP_Request($headers); $length = $this->plugin->getLength(); $this->assertEquals($expected, $length); @@ -37,9 +38,8 @@ class Test_OC_Connector_Sabre_AbortedUploadDetectionPlugin extends PHPUnit_Frame /** * @dataProvider verifyContentLengthProvider */ - public function testVerifyContentLength($method, $fileSize, $headers) - { - $this->plugin->fileView = $this->buildFileViewMock($fileSize); + public function testVerifyContentLength($method, $fileSize, $headers) { + $this->init($this->buildFileViewMock($fileSize)); $headers['REQUEST_METHOD'] = $method; $this->server->httpRequest = new Sabre_HTTP_Request($headers); @@ -51,12 +51,11 @@ class Test_OC_Connector_Sabre_AbortedUploadDetectionPlugin extends PHPUnit_Frame * @dataProvider verifyContentLengthFailedProvider * @expectedException Sabre_DAV_Exception_BadRequest */ - public function testVerifyContentLengthFailed($method, $fileSize, $headers) - { - $this->plugin->fileView = $this->buildFileViewMock($fileSize); - + public function testVerifyContentLengthFailed($method, $fileSize, $headers) { + $view = $this->buildFileViewMock($fileSize); + $this->init($view); // we expect unlink to be called - $this->plugin->fileView->expects($this->once())->method('unlink'); + $view->expects($this->once())->method('unlink'); $headers['REQUEST_METHOD'] = $method; $this->server->httpRequest = new Sabre_HTTP_Request($headers); @@ -92,7 +91,7 @@ class Test_OC_Connector_Sabre_AbortedUploadDetectionPlugin extends PHPUnit_Frame private function buildFileViewMock($fileSize) { // mock filesystem - $view = $this->getMock('\OC\Files\View', array('filesize', 'unlink'), array(), '', FALSE); + $view = $this->getMock('\OC\Files\View', array('filesize', 'unlink'), array(), '', false); $view->expects($this->any())->method('filesize')->withAnyParameters()->will($this->returnValue($fileSize)); return $view; diff --git a/tests/lib/connector/sabre/directory.php b/tests/lib/connector/sabre/directory.php index c501521b601..b2bf0d4a6d2 100644 --- a/tests/lib/connector/sabre/directory.php +++ b/tests/lib/connector/sabre/directory.php @@ -1,18 +1,32 @@ * This file is licensed under the Affero General Public License version 3 or * later. * See the COPYING-README file. */ - class Test_OC_Connector_Sabre_Directory extends PHPUnit_Framework_TestCase { + private function getRootDir() { + $view = $this->getMock('OC\Files\View', array(), array(), '', false); + $view->expects($this->once()) + ->method('getRelativePath') + ->will($this->returnValue('')); + + $info = $this->getMock('OC\Files\FileInfo', array(), array(), '', false); + $info->expects($this->once()) + ->method('getPath') + ->will($this->returnValue('')); + + return new OC_Connector_Sabre_Directory($view, $info); + } + /** * @expectedException Sabre_DAV_Exception_Forbidden */ public function testCreateSharedFileFails() { - $dir = new OC_Connector_Sabre_Directory(''); + $dir = $this->getRootDir(); $dir->createFile('Shared'); } @@ -20,7 +34,7 @@ class Test_OC_Connector_Sabre_Directory extends PHPUnit_Framework_TestCase { * @expectedException Sabre_DAV_Exception_Forbidden */ public function testCreateSharedFolderFails() { - $dir = new OC_Connector_Sabre_Directory(''); + $dir = $this->getRootDir(); $dir->createDirectory('Shared'); } @@ -28,7 +42,7 @@ class Test_OC_Connector_Sabre_Directory extends PHPUnit_Framework_TestCase { * @expectedException Sabre_DAV_Exception_Forbidden */ public function testDeleteSharedFolderFails() { - $dir = new OC_Connector_Sabre_Directory('Shared'); + $dir = $this->getRootDir(); $dir->delete(); } } diff --git a/tests/lib/connector/sabre/file.php b/tests/lib/connector/sabre/file.php index c2f0ffa12d4..011f8ffb6e3 100644 --- a/tests/lib/connector/sabre/file.php +++ b/tests/lib/connector/sabre/file.php @@ -13,9 +13,20 @@ class Test_OC_Connector_Sabre_File extends PHPUnit_Framework_TestCase { */ public function testSimplePutFails() { // setup - $file = new OC_Connector_Sabre_File('/test.txt'); - $file->fileView = $this->getMock('\OC\Files\View', array('file_put_contents'), array(), '', FALSE); - $file->fileView->expects($this->any())->method('file_put_contents')->withAnyParameters()->will($this->returnValue(false)); + $view = $this->getMock('\OC\Files\View', array('file_put_contents', 'getRelativePath'), array(), '', false); + $view->expects($this->any()) + ->method('file_put_contents') + ->will($this->returnValue(false)); + + $view->expects($this->any()) + ->method('getRelativePath') + ->will($this->returnValue('/test.txt')); + + $info = new \OC\Files\FileInfo('/test.txt', null, null, array( + 'permissions'=>\OCP\PERMISSION_ALL + )); + + $file = new OC_Connector_Sabre_File($view, $info); // action $etag = $file->put('test data'); @@ -26,10 +37,25 @@ class Test_OC_Connector_Sabre_File extends PHPUnit_Framework_TestCase { */ public function testSimplePutFailsOnRename() { // setup - $file = new OC_Connector_Sabre_File('/test.txt'); - $file->fileView = $this->getMock('\OC\Files\View', array('file_put_contents', 'rename'), array(), '', FALSE); - $file->fileView->expects($this->any())->method('file_put_contents')->withAnyParameters()->will($this->returnValue(true)); - $file->fileView->expects($this->any())->method('rename')->withAnyParameters()->will($this->returnValue(false)); + $view = $this->getMock('\OC\Files\View', array('file_put_contents', 'rename', 'getRelativePath'), array(), '', false); + $view->expects($this->any()) + ->method('file_put_contents') + ->withAnyParameters() + ->will($this->returnValue(true)); + $view->expects($this->any()) + ->method('rename') + ->withAnyParameters() + ->will($this->returnValue(false)); + + $view->expects($this->any()) + ->method('getRelativePath') + ->will($this->returnValue('/test.txt')); + + $info = new \OC\Files\FileInfo('/test.txt', null, null, array( + 'permissions' => \OCP\PERMISSION_ALL + )); + + $file = new OC_Connector_Sabre_File($view, $info); // action $etag = $file->put('test data'); @@ -40,9 +66,19 @@ class Test_OC_Connector_Sabre_File extends PHPUnit_Framework_TestCase { */ public function testSimplePutInvalidChars() { // setup - $file = new OC_Connector_Sabre_File('/super*star.txt'); - $file->fileView = $this->getMock('\OC\Files\View', array('file_put_contents'), array(), '', FALSE); - $file->fileView->expects($this->any())->method('file_put_contents')->withAnyParameters()->will($this->returnValue(false)); + $view = $this->getMock('\OC\Files\View', array('file_put_contents', 'getRelativePath'), array(), '', false); + $view->expects($this->any()) + ->method('file_put_contents') + ->will($this->returnValue(false)); + + $view->expects($this->any()) + ->method('getRelativePath') + ->will($this->returnValue('/super*star.txt')); + + $info = new \OC\Files\FileInfo('/super*star.txt', null, null, array( + 'permissions' => \OCP\PERMISSION_ALL + )); + $file = new OC_Connector_Sabre_File($view, $info); // action $etag = $file->put('test data'); @@ -54,9 +90,16 @@ class Test_OC_Connector_Sabre_File extends PHPUnit_Framework_TestCase { */ public function testSetNameInvalidChars() { // setup - $file = new OC_Connector_Sabre_File('/test.txt'); - $file->fileView = $this->getMock('\OC\Files\View', array('isUpdatable'), array(), '', FALSE); - $file->fileView->expects($this->any())->method('isUpdatable')->withAnyParameters()->will($this->returnValue(true)); + $view = $this->getMock('\OC\Files\View', array('getRelativePath'), array(), '', false); + + $view->expects($this->any()) + ->method('getRelativePath') + ->will($this->returnValue('/super*star.txt')); + + $info = new \OC\Files\FileInfo('/super*star.txt', null, null, array( + 'permissions' => \OCP\PERMISSION_ALL + )); + $file = new OC_Connector_Sabre_File($view, $info); $file->setName('/super*star.txt'); } @@ -64,7 +107,17 @@ class Test_OC_Connector_Sabre_File extends PHPUnit_Framework_TestCase { * @expectedException Sabre_DAV_Exception_Forbidden */ public function testDeleteSharedFails() { - $file = new OC_Connector_Sabre_File('Shared'); + $view = $this->getMock('\OC\Files\View', array('getRelativePath'), array(), '', false); + + $view->expects($this->any()) + ->method('getRelativePath') + ->will($this->returnValue('Shared')); + + $info = new \OC\Files\FileInfo('/Shared', null, null, array( + 'permissions' => \OCP\PERMISSION_ALL + )); + + $file = new OC_Connector_Sabre_File($view, $info); $file->delete(); } } diff --git a/tests/lib/connector/sabre/objecttree.php b/tests/lib/connector/sabre/objecttree.php index fb50c736edd..876334cf68f 100644 --- a/tests/lib/connector/sabre/objecttree.php +++ b/tests/lib/connector/sabre/objecttree.php @@ -9,6 +9,7 @@ namespace Test\OC\Connector\Sabre; +use OC\Files\FileInfo; use OC_Connector_Sabre_Directory; use PHPUnit_Framework_TestCase; use Sabre_DAV_Exception_Forbidden; @@ -32,6 +33,10 @@ class TestDoubleFileView extends \OC\Files\View{ public function rename($path1, $path2) { return $this->canRename; } + + public function getRelativePath($path){ + return $path; + } } class ObjectTree extends PHPUnit_Framework_TestCase { @@ -91,10 +96,14 @@ class ObjectTree extends PHPUnit_Framework_TestCase { * @param $updatables */ private function moveTest($source, $dest, $updatables, $deletables) { - $rootDir = new OC_Connector_Sabre_Directory(''); + $view = new TestDoubleFileView($updatables, $deletables); + + $info = new FileInfo('', null, null, array()); + + $rootDir = new OC_Connector_Sabre_Directory($view, $info); $objectTree = $this->getMock('\OC\Connector\Sabre\ObjectTree', array('nodeExists', 'getNodeForPath'), - array($rootDir)); + array($rootDir, $view)); $objectTree->expects($this->once()) ->method('getNodeForPath') @@ -102,7 +111,6 @@ class ObjectTree extends PHPUnit_Framework_TestCase { ->will($this->returnValue(false)); /** @var $objectTree \OC\Connector\Sabre\ObjectTree */ - $objectTree->fileView = new TestDoubleFileView($updatables, $deletables); $objectTree->move($source, $dest); } diff --git a/tests/lib/connector/sabre/quotaplugin.php b/tests/lib/connector/sabre/quotaplugin.php index 1186de28742..6781b970a4f 100644 --- a/tests/lib/connector/sabre/quotaplugin.php +++ b/tests/lib/connector/sabre/quotaplugin.php @@ -1,11 +1,11 @@ * This file is licensed under the Affero General Public License version 3 or * later. * See the COPYING-README file. */ - class Test_OC_Connector_Sabre_QuotaPlugin extends PHPUnit_Framework_TestCase { /** @@ -18,17 +18,18 @@ class Test_OC_Connector_Sabre_QuotaPlugin extends PHPUnit_Framework_TestCase { */ private $plugin; - public function setUp() { + private function init($quota) { + $view = $this->buildFileViewMock($quota); $this->server = new Sabre_DAV_Server(); - $this->plugin = new OC_Connector_Sabre_QuotaPlugin(); + $this->plugin = new OC_Connector_Sabre_QuotaPlugin($view); $this->plugin->initialize($this->server); } /** * @dataProvider lengthProvider */ - public function testLength($expected, $headers) - { + public function testLength($expected, $headers) { + $this->init(0); $this->server->httpRequest = new Sabre_HTTP_Request($headers); $length = $this->plugin->getLength(); $this->assertEquals($expected, $length); @@ -37,9 +38,8 @@ class Test_OC_Connector_Sabre_QuotaPlugin extends PHPUnit_Framework_TestCase { /** * @dataProvider quotaOkayProvider */ - public function testCheckQuota($quota, $headers) - { - $this->plugin->fileView = $this->buildFileViewMock($quota); + public function testCheckQuota($quota, $headers) { + $this->init($quota); $this->server->httpRequest = new Sabre_HTTP_Request($headers); $result = $this->plugin->checkQuota(''); @@ -50,9 +50,8 @@ class Test_OC_Connector_Sabre_QuotaPlugin extends PHPUnit_Framework_TestCase { * @expectedException Sabre_DAV_Exception_InsufficientStorage * @dataProvider quotaExceededProvider */ - public function testCheckExceededQuota($quota, $headers) - { - $this->plugin->fileView = $this->buildFileViewMock($quota); + public function testCheckExceededQuota($quota, $headers) { + $this->init($quota); $this->server->httpRequest = new Sabre_HTTP_Request($headers); $this->plugin->checkQuota(''); @@ -92,7 +91,7 @@ class Test_OC_Connector_Sabre_QuotaPlugin extends PHPUnit_Framework_TestCase { private function buildFileViewMock($quota) { // mock filesysten - $view = $this->getMock('\OC\Files\View', array('free_space'), array(), '', FALSE); + $view = $this->getMock('\OC\Files\View', array('free_space'), array(), '', false); $view->expects($this->any())->method('free_space')->withAnyParameters()->will($this->returnValue($quota)); return $view; -- cgit v1.2.3 From bb8a7a2230ce1b13ab97e1558a56f54009064066 Mon Sep 17 00:00:00 2001 From: Robin Appelman Date: Mon, 3 Mar 2014 16:48:06 +0100 Subject: Remove assert since the root size of the home storage is no longer calculated --- tests/lib/files/cache/homecache.php | 1 - 1 file changed, 1 deletion(-) (limited to 'tests') diff --git a/tests/lib/files/cache/homecache.php b/tests/lib/files/cache/homecache.php index dbcf6e9caa0..80dc54c9d19 100644 --- a/tests/lib/files/cache/homecache.php +++ b/tests/lib/files/cache/homecache.php @@ -90,7 +90,6 @@ class HomeCache extends \PHPUnit_Framework_TestCase { // check that files and root size ignored the unknown sizes $this->assertEquals(1000, $this->cache->calculateFolderSize('files')); - $this->assertEquals(1000, $this->cache->calculateFolderSize('')); // clean up $this->cache->remove(''); -- cgit v1.2.3 From 52115662057408d095249a237a78c2207ab1b821 Mon Sep 17 00:00:00 2001 From: Robin Appelman Date: Tue, 4 Mar 2014 16:36:03 +0100 Subject: update test case --- tests/lib/connector/sabre/objecttree.php | 1 + 1 file changed, 1 insertion(+) (limited to 'tests') diff --git a/tests/lib/connector/sabre/objecttree.php b/tests/lib/connector/sabre/objecttree.php index 876334cf68f..bc8ec98faee 100644 --- a/tests/lib/connector/sabre/objecttree.php +++ b/tests/lib/connector/sabre/objecttree.php @@ -111,6 +111,7 @@ class ObjectTree extends PHPUnit_Framework_TestCase { ->will($this->returnValue(false)); /** @var $objectTree \OC\Connector\Sabre\ObjectTree */ + $objectTree->init($rootDir, $view); $objectTree->move($source, $dest); } -- cgit v1.2.3 From c7e204bd3674b616faddbb0b88187f94638e5b01 Mon Sep 17 00:00:00 2001 From: Vincent Petry Date: Wed, 5 Mar 2014 17:04:15 +0100 Subject: Added unit tests for serverHost and other related functions --- tests/lib/request.php | 137 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 137 insertions(+) (limited to 'tests') diff --git a/tests/lib/request.php b/tests/lib/request.php index 1d77acc70ae..bff84e1b03f 100644 --- a/tests/lib/request.php +++ b/tests/lib/request.php @@ -135,4 +135,141 @@ class Test_Request extends PHPUnit_Framework_TestCase { ), ); } + + public function testInsecureServerHost() { + unset($_SERVER['HTTP_X_FORWARDED_HOST']); + unset($_SERVER['HTTP_HOST']); + unset($_SERVER['SERVER_NAME']); + $_SERVER['SERVER_NAME'] = 'from.server.name:8080'; + $host = OC_Request::insecureServerHost(); + $this->assertEquals('from.server.name:8080', $host); + + $_SERVER['HTTP_HOST'] = 'from.host.header:8080'; + $host = OC_Request::insecureServerHost(); + $this->assertEquals('from.host.header:8080', $host); + + $_SERVER['HTTP_X_FORWARDED_HOST'] = 'from.forwarded.host:8080'; + $host = OC_Request::insecureServerHost(); + $this->assertEquals('from.forwarded.host:8080', $host); + + $_SERVER['HTTP_X_FORWARDED_HOST'] = 'from.forwarded.host2:8080,another.one:9000'; + $host = OC_Request::insecureServerHost(); + $this->assertEquals('from.forwarded.host2:8080', $host); + + // clean up + unset($_SERVER['HTTP_X_FORWARDED_HOST']); + unset($_SERVER['HTTP_HOST']); + unset($_SERVER['SERVER_NAME']); + } + + public function testGetOverwriteHost() { + unset($_SERVER['REMOTE_ADDR']); + OC_Config::deleteKey('overwritecondaddr'); + OC_Config::deleteKey('overwritehost'); + $host = OC_Request::getOverwriteHost(); + $this->assertNull($host); + + OC_Config::setValue('overwritehost', ''); + $host = OC_Request::getOverwriteHost(); + $this->assertNull($host); + + OC_Config::setValue('overwritehost', 'host.one.test:8080'); + $host = OC_Request::getOverwriteHost(); + $this->assertEquals('host.one.test:8080', $host); + + $_SERVER['REMOTE_ADDR'] = 'somehost.test:8080'; + OC_Config::setValue('overwritecondaddr', '^somehost\..*$'); + $host = OC_Request::getOverwriteHost(); + $this->assertEquals('host.one.test:8080', $host); + + OC_Config::setValue('overwritecondaddr', '^somethingelse.*$'); + $host = OC_Request::getOverwriteHost(); + $this->assertNull($host); + + // clean up + unset($_SERVER['REMOTE_ADDR']); + OC_Config::deleteKey('overwritecondaddr'); + OC_Config::deleteKey('overwritehost'); + } + + /** + * @dataProvider trustedDomainDataProvider + */ + public function testIsTrustedDomain($trustedDomains, $testDomain, $result) { + OC_Config::deleteKey('trusted_domains'); + if ($trustedDomains !== null) { + OC_Config::setValue('trusted_domains', $trustedDomains); + } + + $this->assertEquals($result, OC_Request::isTrustedDomain($testDomain)); + + // clean up + OC_Config::deleteKey('trusted_domains'); + } + + public function trustedDomainDataProvider() { + $trustedHostTestList = array('host.one.test:8080', 'host.two.test:8080'); + return array( + // empty defaults to true + array(null, 'host.one.test:8080', true), + array('', 'host.one.test:8080', true), + array(array(), 'host.one.test:8080', true), + + // trust list when defined + array($trustedHostTestList, 'host.two.test:8080', true), + array($trustedHostTestList, 'host.two.test:9999', false), + array($trustedHostTestList, 'host.three.test:8080', false), + + // trust localhost regardless of trust list + array($trustedHostTestList, 'localhost', true), + array($trustedHostTestList, 'localhost:8080', true), + array($trustedHostTestList, '127.0.0.1', true), + array($trustedHostTestList, '127.0.0.1:8080', true), + + // do not trust invalid localhosts + array($trustedHostTestList, 'localhost:1:2', false), + array($trustedHostTestList, 'localhost: evil.host', false), + ); + } + + public function testServerHost() { + OC_Config::deleteKey('overwritecondaddr'); + OC_Config::setValue('overwritehost', 'overwritten.host:8080'); + OC_Config::setValue( + 'trusted_domains', + array( + 'trusted.host:8080', + 'second.trusted.host:8080' + ) + ); + $_SERVER['HTTP_HOST'] = 'trusted.host:8080'; + + // CLI always gives localhost + $oldCLI = OC::$CLI; + OC::$CLI = true; + $host = OC_Request::serverHost(); + $this->assertEquals('localhost', $host); + OC::$CLI = false; + + // overwritehost overrides trusted domain + $host = OC_Request::serverHost(); + $this->assertEquals('overwritten.host:8080', $host); + + // trusted domain returned when used + OC_Config::deleteKey('overwritehost'); + $host = OC_Request::serverHost(); + $this->assertEquals('trusted.host:8080', $host); + + // trusted domain returned when untrusted one in header + $_SERVER['HTTP_HOST'] = 'untrusted.host:8080'; + OC_Config::deleteKey('overwritehost'); + $host = OC_Request::serverHost(); + $this->assertEquals('trusted.host:8080', $host); + + // clean up + OC_Config::deleteKey('overwritecondaddr'); + OC_Config::deleteKey('overwritehost'); + unset($_SERVER['HTTP_HOST']); + OC::$CLI = $oldCLI; + } } -- cgit v1.2.3 From ada8d4e0c91a885ca21db6b2bf4ca5d5c932e51b Mon Sep 17 00:00:00 2001 From: Thomas Tanghus Date: Fri, 7 Mar 2014 02:44:34 +0100 Subject: Fix unit tests --- tests/lib/urlgenerator.php | 30 +++++++++++++++++++++++++++--- 1 file changed, 27 insertions(+), 3 deletions(-) (limited to 'tests') diff --git a/tests/lib/urlgenerator.php b/tests/lib/urlgenerator.php index 875a7f06580..8e605d88f32 100644 --- a/tests/lib/urlgenerator.php +++ b/tests/lib/urlgenerator.php @@ -12,17 +12,32 @@ class Test_Urlgenerator extends PHPUnit_Framework_TestCase { /** * @small * @brief test absolute URL construction - * @dataProvider provideURLs + * @dataProvider provideDocRootURLs */ - function testGetAbsoluteURL($url, $expectedResult) { + function testGetAbsoluteURLDocRoot($url, $expectedResult) { + \OC::$WEBROOT = ''; $urlGenerator = new \OC\URLGenerator(null); $result = $urlGenerator->getAbsoluteURL($url); $this->assertEquals($expectedResult, $result); } - public function provideURLs() { + /** + * @small + * @brief test absolute URL construction + * @dataProvider provideSubDirURLs + */ + function testGetAbsoluteURLSubDir($url, $expectedResult) { + + \OC::$WEBROOT = '/owncloud'; + $urlGenerator = new \OC\URLGenerator(null); + $result = $urlGenerator->getAbsoluteURL($url); + + $this->assertEquals($expectedResult, $result); + } + + public function provideDocRootURLs() { return array( array("index.php", "http://localhost/index.php"), array("/index.php", "http://localhost/index.php"), @@ -30,5 +45,14 @@ class Test_Urlgenerator extends PHPUnit_Framework_TestCase { array("apps/index.php", "http://localhost/apps/index.php"), ); } + + public function provideSubDirURLs() { + return array( + array("index.php", "http://localhost/owncloud/index.php"), + array("/index.php", "http://localhost/owncloud/index.php"), + array("/apps/index.php", "http://localhost/owncloud/apps/index.php"), + array("apps/index.php", "http://localhost/owncloud/apps/index.php"), + ); + } } -- cgit v1.2.3 From 48d63a6278078d164774fd182f03ebba5e3c77ad Mon Sep 17 00:00:00 2001 From: Vincent Petry Date: Fri, 7 Mar 2014 11:25:29 +0100 Subject: Return unencrypted_size of folder when queried This fixes the "used space" to be based on the unencrypted size, not encrypted size, to be consistent with how quota/space is handled when encryption is enabled --- apps/files_encryption/lib/proxy.php | 7 +++++++ apps/files_encryption/tests/proxy.php | 20 ++++++++++++++++++++ lib/private/files/storage/wrapper/quota.php | 5 +++++ tests/lib/files/storage/wrapper/quota.php | 16 ++++++++++++++++ 4 files changed, 48 insertions(+) (limited to 'tests') diff --git a/apps/files_encryption/lib/proxy.php b/apps/files_encryption/lib/proxy.php index a2d42c22c13..b7e1599c1fe 100644 --- a/apps/files_encryption/lib/proxy.php +++ b/apps/files_encryption/lib/proxy.php @@ -340,6 +340,13 @@ class Proxy extends \OC_FileProxy { // if path is a folder do nothing if ($view->is_dir($path)) { + $proxyState = \OC_FileProxy::$enabled; + \OC_FileProxy::$enabled = false; + $fileInfo = $view->getFileInfo($path); + \OC_FileProxy::$enabled = $proxyState; + if ($fileInfo['unencrypted_size'] > 0) { + return $fileInfo['unencrypted_size']; + } return $size; } diff --git a/apps/files_encryption/tests/proxy.php b/apps/files_encryption/tests/proxy.php index 51cc0b795e3..647ee955eb1 100644 --- a/apps/files_encryption/tests/proxy.php +++ b/apps/files_encryption/tests/proxy.php @@ -112,4 +112,24 @@ class Test_Encryption_Proxy extends \PHPUnit_Framework_TestCase { } + function testPostFileSizeWithDirectory() { + + $this->view->file_put_contents($this->filename, $this->data); + + \OC_FileProxy::$enabled = false; + + // get root size, must match the file's unencrypted size + $unencryptedSize = $this->view->filesize(''); + + \OC_FileProxy::$enabled = true; + + $encryptedSize = $this->view->filesize(''); + + $this->assertTrue($encryptedSize !== $unencryptedSize); + + // cleanup + $this->view->unlink($this->filename); + + } + } diff --git a/lib/private/files/storage/wrapper/quota.php b/lib/private/files/storage/wrapper/quota.php index 26c952e694a..ea612735477 100644 --- a/lib/private/files/storage/wrapper/quota.php +++ b/lib/private/files/storage/wrapper/quota.php @@ -36,6 +36,11 @@ class Quota extends Wrapper { $cache = $this->getCache(); $data = $cache->get($path); if (is_array($data) and isset($data['size'])) { + if (isset($data['unencrypted_size']) + && $data['unencrypted_size'] > 0 + ) { + return $data['unencrypted_size']; + } return $data['size']; } else { return \OC\Files\SPACE_NOT_COMPUTED; diff --git a/tests/lib/files/storage/wrapper/quota.php b/tests/lib/files/storage/wrapper/quota.php index 43eae78415d..bd2c69a7396 100644 --- a/tests/lib/files/storage/wrapper/quota.php +++ b/tests/lib/files/storage/wrapper/quota.php @@ -53,6 +53,22 @@ class Quota extends \Test\Files\Storage\Storage { $this->assertEquals(9, $instance->free_space('')); } + public function testFreeSpaceWithUsedSpace() { + $instance = $this->getLimitedStorage(9); + $instance->getCache()->put( + '', array('size' => 3, 'unencrypted_size' => 0) + ); + $this->assertEquals(6, $instance->free_space('')); + } + + public function testFreeSpaceWithUsedSpaceAndEncryption() { + $instance = $this->getLimitedStorage(9); + $instance->getCache()->put( + '', array('size' => 7, 'unencrypted_size' => 3) + ); + $this->assertEquals(6, $instance->free_space('')); + } + public function testFWriteNotEnoughSpace() { $instance = $this->getLimitedStorage(9); $stream = $instance->fopen('foo', 'w+'); -- cgit v1.2.3 From 8f6ea900f2f75bfdfadb7f484ec64ac7ea78623c Mon Sep 17 00:00:00 2001 From: Thomas Tanghus Date: Sun, 9 Mar 2014 23:01:16 +0100 Subject: Chainable Response in AppFramework --- lib/public/appframework/http/jsonresponse.php | 2 ++ lib/public/appframework/http/response.php | 9 +++++++++ lib/public/appframework/http/templateresponse.php | 4 ++++ tests/lib/appframework/http/JSONResponseTest.php | 10 ++++++++++ tests/lib/appframework/http/ResponseTest.php | 20 ++++++++++++++++++++ tests/lib/appframework/http/TemplateResponseTest.php | 10 ++++++++++ 6 files changed, 55 insertions(+) (limited to 'tests') diff --git a/lib/public/appframework/http/jsonresponse.php b/lib/public/appframework/http/jsonresponse.php index b54b23a34e6..bcfe469ef1b 100644 --- a/lib/public/appframework/http/jsonresponse.php +++ b/lib/public/appframework/http/jsonresponse.php @@ -69,6 +69,8 @@ class JSONResponse extends Response { */ public function setData($data){ $this->data = $data; + + return $this; } diff --git a/lib/public/appframework/http/response.php b/lib/public/appframework/http/response.php index d223621d4fd..e704acca7f0 100644 --- a/lib/public/appframework/http/response.php +++ b/lib/public/appframework/http/response.php @@ -80,6 +80,7 @@ class Response { $this->addHeader('Cache-Control', 'no-cache, must-revalidate'); } + return $this; } @@ -95,6 +96,8 @@ class Response { } else { $this->headers[$name] = $value; } + + return $this; } @@ -133,6 +136,8 @@ class Response { */ public function setStatus($status) { $this->status = $status; + + return $this; } @@ -168,6 +173,8 @@ class Response { */ public function setETag($ETag) { $this->ETag = $ETag; + + return $this; } @@ -177,6 +184,8 @@ class Response { */ public function setLastModified($lastModified) { $this->lastModified = $lastModified; + + return $this; } diff --git a/lib/public/appframework/http/templateresponse.php b/lib/public/appframework/http/templateresponse.php index 2200a38beca..1ae22dde7ff 100644 --- a/lib/public/appframework/http/templateresponse.php +++ b/lib/public/appframework/http/templateresponse.php @@ -77,6 +77,8 @@ class TemplateResponse extends Response { */ public function setParams(array $params){ $this->params = $params; + + return $this; } @@ -107,6 +109,8 @@ class TemplateResponse extends Response { */ public function renderAs($renderAs){ $this->renderAs = $renderAs; + + return $this; } diff --git a/tests/lib/appframework/http/JSONResponseTest.php b/tests/lib/appframework/http/JSONResponseTest.php index 534c54cbcee..b9b7c7d6382 100644 --- a/tests/lib/appframework/http/JSONResponseTest.php +++ b/tests/lib/appframework/http/JSONResponseTest.php @@ -28,6 +28,7 @@ namespace OC\AppFramework\Http; use OCP\AppFramework\Http\JSONResponse; +use OCP\AppFramework\Http; //require_once(__DIR__ . "/../classloader.php"); @@ -95,4 +96,13 @@ class JSONResponseTest extends \PHPUnit_Framework_TestCase { $this->assertEquals($code, $response->getStatus()); } + public function testChainability() { + $params = array('hi', 'yo'); + $this->json->setData($params) + ->setStatus(Http::STATUS_NOT_FOUND); + + $this->assertEquals(Http::STATUS_NOT_FOUND, $this->json->getStatus()); + $this->assertEquals(array('hi', 'yo'), $this->json->getData()); + } + } diff --git a/tests/lib/appframework/http/ResponseTest.php b/tests/lib/appframework/http/ResponseTest.php index 063ab8b5d33..27350725d79 100644 --- a/tests/lib/appframework/http/ResponseTest.php +++ b/tests/lib/appframework/http/ResponseTest.php @@ -117,5 +117,25 @@ class ResponseTest extends \PHPUnit_Framework_TestCase { $this->assertEquals('Thu, 01 Jan 1970 00:00:01 +0000', $headers['Last-Modified']); } + public function testChainability() { + $lastModified = new \DateTime(null, new \DateTimeZone('GMT')); + $lastModified->setTimestamp(1); + + $this->childResponse->setEtag('hi') + ->setStatus(Http::STATUS_NOT_FOUND) + ->setLastModified($lastModified) + ->cacheFor(33) + ->addHeader('hello', 'world'); + + $headers = $this->childResponse->getHeaders(); + + $this->assertEquals('world', $headers['hello']); + $this->assertEquals(Http::STATUS_NOT_FOUND, $this->childResponse->getStatus()); + $this->assertEquals('hi', $this->childResponse->getEtag()); + $this->assertEquals('Thu, 01 Jan 1970 00:00:01 +0000', $headers['Last-Modified']); + $this->assertEquals('max-age=33, must-revalidate', + $headers['Cache-Control']); + + } } diff --git a/tests/lib/appframework/http/TemplateResponseTest.php b/tests/lib/appframework/http/TemplateResponseTest.php index a583d9da14f..0b158edff6f 100644 --- a/tests/lib/appframework/http/TemplateResponseTest.php +++ b/tests/lib/appframework/http/TemplateResponseTest.php @@ -25,6 +25,7 @@ namespace OC\AppFramework\Http; use OCP\AppFramework\Http\TemplateResponse; +use OCP\AppFramework\Http; class TemplateResponseTest extends \PHPUnit_Framework_TestCase { @@ -98,4 +99,13 @@ class TemplateResponseTest extends \PHPUnit_Framework_TestCase { $this->assertEquals($render, $this->tpl->getRenderAs()); } + public function testChainability() { + $params = array('hi' => 'yo'); + $this->tpl->setParams($params) + ->setStatus(Http::STATUS_NOT_FOUND); + + $this->assertEquals(Http::STATUS_NOT_FOUND, $this->tpl->getStatus()); + $this->assertEquals(array('hi' => 'yo'), $this->tpl->getParams()); + } + } -- cgit v1.2.3 From 8ab7d18a6a2b023527d2eef63099e2834c46ec97 Mon Sep 17 00:00:00 2001 From: Robin Appelman Date: Mon, 10 Mar 2014 14:04:58 +0100 Subject: Move the router classes to a namespace and expose it with a public interface --- apps/files_sharing/appinfo/routes.php | 2 +- lib/base.php | 14 +- lib/private/appframework/routing/routeconfig.php | 7 +- lib/private/route.php | 124 -------------- lib/private/route/route.php | 132 +++++++++++++++ lib/private/route/router.php | 202 +++++++++++++++++++++++ lib/private/router.php | 161 ------------------ lib/private/server.php | 15 ++ lib/public/appframework/app.php | 2 +- lib/public/iservercontainer.php | 6 + lib/public/route/iroute.php | 79 +++++++++ lib/public/route/irouter.php | 71 ++++++++ tests/lib/appframework/routing/RoutingTest.php | 8 +- 13 files changed, 517 insertions(+), 306 deletions(-) delete mode 100644 lib/private/route.php create mode 100644 lib/private/route/route.php create mode 100644 lib/private/route/router.php delete mode 100644 lib/private/router.php create mode 100644 lib/public/route/iroute.php create mode 100644 lib/public/route/irouter.php (limited to 'tests') diff --git a/apps/files_sharing/appinfo/routes.php b/apps/files_sharing/appinfo/routes.php index 9417a6eeb89..06e454b7d77 100644 --- a/apps/files_sharing/appinfo/routes.php +++ b/apps/files_sharing/appinfo/routes.php @@ -1,5 +1,5 @@ create('core_ajax_public_preview', '/publicpreview.png')->action( function() { require_once __DIR__ . '/../ajax/publicpreview.php'; diff --git a/lib/base.php b/lib/base.php index 86ee5349828..d49dd958310 100644 --- a/lib/base.php +++ b/lib/base.php @@ -73,11 +73,6 @@ class OC { */ public static $CLI = false; - /** - * @var OC_Router - */ - protected static $router = null; - /** * @var \OC\Session\Session */ @@ -388,15 +383,10 @@ class OC { } /** - * @return OC_Router + * @return \OCP\Route\IRouter */ public static function getRouter() { - if (!isset(OC::$router)) { - OC::$router = new OC_Router(); - OC::$router->loadRoutes(); - } - - return OC::$router; + return self::$server->getRouter(); } diff --git a/lib/private/appframework/routing/routeconfig.php b/lib/private/appframework/routing/routeconfig.php index 716358444a2..35bee75cc4d 100644 --- a/lib/private/appframework/routing/routeconfig.php +++ b/lib/private/appframework/routing/routeconfig.php @@ -23,6 +23,7 @@ namespace OC\AppFramework\routing; use OC\AppFramework\DependencyInjection\DIContainer; +use OCP\Route\IRouter; /** * Class RouteConfig @@ -36,10 +37,10 @@ class RouteConfig { /** * @param \OC\AppFramework\DependencyInjection\DIContainer $container - * @param \OC_Router $router + * @param \OCP\Route\IRouter $router * @internal param $appName */ - public function __construct(DIContainer $container, \OC_Router $router, $routes) { + public function __construct(DIContainer $container, IRouter $router, $routes) { $this->routes = $routes; $this->container = $container; $this->router = $router; @@ -47,7 +48,7 @@ class RouteConfig { } /** - * The routes and resource will be registered to the \OC_Router + * The routes and resource will be registered to the \OCP\Route\IRouter */ public function register() { diff --git a/lib/private/route.php b/lib/private/route.php deleted file mode 100644 index fb7da456b62..00000000000 --- a/lib/private/route.php +++ /dev/null @@ -1,124 +0,0 @@ - - * This file is licensed under the Affero General Public License version 3 or - * later. - * See the COPYING-README file. - */ - -use Symfony\Component\Routing\Route; - -class OC_Route extends Route { - /** - * Specify the method when this route is to be used - * - * @param string $method HTTP method (uppercase) - */ - public function method($method) { - $this->setRequirement('_method', strtoupper($method)); - return $this; - } - - /** - * Specify POST as the method to use with this route - */ - public function post() { - $this->method('POST'); - return $this; - } - - /** - * Specify GET as the method to use with this route - */ - public function get() { - $this->method('GET'); - return $this; - } - - /** - * Specify PUT as the method to use with this route - */ - public function put() { - $this->method('PUT'); - return $this; - } - - /** - * Specify DELETE as the method to use with this route - */ - public function delete() { - $this->method('DELETE'); - return $this; - } - - /** - * Specify PATCH as the method to use with this route - */ - public function patch() { - $this->method('PATCH'); - return $this; - } - - /** - * Defaults to use for this route - * - * @param array $defaults The defaults - */ - public function defaults($defaults) { - $action = $this->getDefault('action'); - $this->setDefaults($defaults); - if (isset($defaults['action'])) { - $action = $defaults['action']; - } - $this->action($action); - return $this; - } - - /** - * Requirements for this route - * - * @param array $requirements The requirements - */ - public function requirements($requirements) { - $method = $this->getRequirement('_method'); - $this->setRequirements($requirements); - if (isset($requirements['_method'])) { - $method = $requirements['_method']; - } - if ($method) { - $this->method($method); - } - return $this; - } - - /** - * The action to execute when this route matches - * @param string|callable $class the class or a callable - * @param string $function the function to use with the class - * - * This function is called with $class set to a callable or - * to the class with $function - */ - public function action($class, $function = null) { - $action = array($class, $function); - if (is_null($function)) { - $action = $class; - } - $this->setDefault('action', $action); - return $this; - } - - /** - * The action to execute when this route matches, includes a file like - * it is called directly - * @param $file - */ - public function actionInclude($file) { - $function = create_function('$param', - 'unset($param["_route"]);' - .'$_GET=array_merge($_GET, $param);' - .'unset($param);' - .'require_once "'.$file.'";'); - $this->action($function); - } -} diff --git a/lib/private/route/route.php b/lib/private/route/route.php new file mode 100644 index 00000000000..6ade9ec15f6 --- /dev/null +++ b/lib/private/route/route.php @@ -0,0 +1,132 @@ + + * This file is licensed under the Affero General Public License version 3 or + * later. + * See the COPYING-README file. + */ + +namespace OC\Route; + +use OCP\Route\IRoute; +use Symfony\Component\Routing\Route as SymfonyRoute; + +class Route extends SymfonyRoute implements IRoute { + /** + * Specify the method when this route is to be used + * + * @param string $method HTTP method (uppercase) + * @return \OC\Route\Route + */ + public function method($method) { + $this->setRequirement('_method', strtoupper($method)); + return $this; + } + + /** + * Specify POST as the method to use with this route + */ + public function post() { + $this->method('POST'); + return $this; + } + + /** + * Specify GET as the method to use with this route + */ + public function get() { + $this->method('GET'); + return $this; + } + + /** + * Specify PUT as the method to use with this route + */ + public function put() { + $this->method('PUT'); + return $this; + } + + /** + * Specify DELETE as the method to use with this route + */ + public function delete() { + $this->method('DELETE'); + return $this; + } + + /** + * Specify PATCH as the method to use with this route + */ + public function patch() { + $this->method('PATCH'); + return $this; + } + + /** + * Defaults to use for this route + * + * @param array $defaults The defaults + * @return \OC\Route\Route + */ + public function defaults($defaults) { + $action = $this->getDefault('action'); + $this->setDefaults($defaults); + if (isset($defaults['action'])) { + $action = $defaults['action']; + } + $this->action($action); + return $this; + } + + /** + * Requirements for this route + * + * @param array $requirements The requirements + * @return \OC\Route\Route + */ + public function requirements($requirements) { + $method = $this->getRequirement('_method'); + $this->setRequirements($requirements); + if (isset($requirements['_method'])) { + $method = $requirements['_method']; + } + if ($method) { + $this->method($method); + } + return $this; + } + + /** + * The action to execute when this route matches + * + * @param string|callable $class the class or a callable + * @param string $function the function to use with the class + * @return \OC\Route\Route + * + * This function is called with $class set to a callable or + * to the class with $function + */ + public function action($class, $function = null) { + $action = array($class, $function); + if (is_null($function)) { + $action = $class; + } + $this->setDefault('action', $action); + return $this; + } + + /** + * The action to execute when this route matches, includes a file like + * it is called directly + * @param $file + */ + public function actionInclude($file) { + $function = create_function('$param', + 'unset($param["_route"]);' + .'$_GET=array_merge($_GET, $param);' + .'unset($param);' + .'require_once "'.$file.'";'); + $this->action($function); + } +} diff --git a/lib/private/route/router.php b/lib/private/route/router.php new file mode 100644 index 00000000000..60ba5878401 --- /dev/null +++ b/lib/private/route/router.php @@ -0,0 +1,202 @@ + + * This file is licensed under the Affero General Public License version 3 or + * later. + * See the COPYING-README file. + */ + +namespace OC\Route; + +use OCP\Route\IRouter; +use Symfony\Component\Routing\Matcher\UrlMatcher; +use Symfony\Component\Routing\Generator\UrlGenerator; +use Symfony\Component\Routing\RequestContext; +use Symfony\Component\Routing\RouteCollection; + +class Router implements IRouter { + /** + * @var \Symfony\Component\Routing\RouteCollection[] + */ + protected $collections = array(); + + /** + * @var \Symfony\Component\Routing\RouteCollection + */ + protected $collection = null; + + /** + * @var \Symfony\Component\Routing\RouteCollection + */ + protected $root = null; + + /** + * @var \Symfony\Component\Routing\Generator\UrlGenerator + */ + protected $generator = null; + + /** + * @var string[] + */ + protected $routingFiles; + + /** + * @var string + */ + protected $cacheKey; + + protected $loaded = false; + + public function __construct() { + $baseUrl = \OC_Helper::linkTo('', 'index.php'); + if (!\OC::$CLI) { + $method = $_SERVER['REQUEST_METHOD']; + } else { + $method = 'GET'; + } + $host = \OC_Request::serverHost(); + $schema = \OC_Request::serverProtocol(); + $this->context = new RequestContext($baseUrl, $method, $host, $schema); + // TODO cache + $this->root = $this->getCollection('root'); + } + + /** + * Get the files to load the routes from + * + * @return string[] + */ + public function getRoutingFiles() { + if (!isset($this->routingFiles)) { + $this->routingFiles = array(); + foreach (\OC_APP::getEnabledApps() as $app) { + $file = \OC_App::getAppPath($app) . '/appinfo/routes.php'; + if (file_exists($file)) { + $this->routingFiles[$app] = $file; + } + } + } + return $this->routingFiles; + } + + public function getCacheKey() { + if (!isset($this->cacheKey)) { + $files = $this->getRoutingFiles(); + $files[] = 'settings/routes.php'; + $files[] = 'core/routes.php'; + $files[] = 'ocs/routes.php'; + $this->cacheKey = \OC_Cache::generateCacheKeyFromFiles($files); + } + return $this->cacheKey; + } + + /** + * loads the api routes + */ + public function loadRoutes() { + if ($this->loaded) { + return; + } + $this->loaded = true; + foreach ($this->getRoutingFiles() as $app => $file) { + $this->useCollection($app); + require_once $file; + $collection = $this->getCollection($app); + $collection->addPrefix('/apps/' . $app); + $this->root->addCollection($collection); + } + $this->useCollection('root'); + require_once 'settings/routes.php'; + require_once 'core/routes.php'; + + // include ocs routes + require_once 'ocs/routes.php'; + $collection = $this->getCollection('ocs'); + $collection->addPrefix('/ocs'); + $this->root->addCollection($collection); + } + + /** + * @param string $name + * @return \Symfony\Component\Routing\RouteCollection + */ + protected function getCollection($name) { + if (!isset($this->collections[$name])) { + $this->collections[$name] = new RouteCollection(); + } + return $this->collections[$name]; + } + + /** + * Sets the collection to use for adding routes + * + * @param string $name Name of the collection to use. + */ + public function useCollection($name) { + $this->collection = $this->getCollection($name); + } + + /** + * Create a \OC\Route\Route. + * + * @param string $name Name of the route to create. + * @param string $pattern The pattern to match + * @param array $defaults An array of default parameter values + * @param array $requirements An array of requirements for parameters (regexes) + * @return \OC\Route\Route + */ + public function create($name, $pattern, array $defaults = array(), array $requirements = array()) { + $route = new Route($pattern, $defaults, $requirements); + $this->collection->add($name, $route); + return $route; + } + + /** + * Find the route matching $url. + * + * @param string $url The url to find + * @throws \Exception + */ + public function match($url) { + $matcher = new UrlMatcher($this->root, $this->context); + $parameters = $matcher->match($url); + if (isset($parameters['action'])) { + $action = $parameters['action']; + if (!is_callable($action)) { + var_dump($action); + throw new \Exception('not a callable action'); + } + unset($parameters['action']); + call_user_func($action, $parameters); + } elseif (isset($parameters['file'])) { + include $parameters['file']; + } else { + throw new \Exception('no action available'); + } + } + + /** + * Get the url generator + * + */ + public function getGenerator() { + if (null !== $this->generator) { + return $this->generator; + } + + return $this->generator = new UrlGenerator($this->root, $this->context); + } + + /** + * Generate url based on $name and $parameters + * + * @param string $name Name of the route to use. + * @param array $parameters Parameters for the route + * @param bool $absolute + * @return string + */ + public function generate($name, $parameters = array(), $absolute = false) { + return $this->getGenerator()->generate($name, $parameters, $absolute); + } + +} diff --git a/lib/private/router.php b/lib/private/router.php deleted file mode 100644 index 918e3b13206..00000000000 --- a/lib/private/router.php +++ /dev/null @@ -1,161 +0,0 @@ - - * This file is licensed under the Affero General Public License version 3 or - * later. - * See the COPYING-README file. - */ - -use Symfony\Component\Routing\Matcher\UrlMatcher; -use Symfony\Component\Routing\Generator\UrlGenerator; -use Symfony\Component\Routing\RequestContext; -use Symfony\Component\Routing\RouteCollection; -//use Symfony\Component\Routing\Route; - -class OC_Router { - protected $collections = array(); - protected $collection = null; - protected $root = null; - - protected $generator = null; - protected $routing_files; - protected $cache_key; - - public function __construct() { - $baseUrl = OC_Helper::linkTo('', 'index.php'); - if ( !OC::$CLI) { - $method = $_SERVER['REQUEST_METHOD']; - }else{ - $method = 'GET'; - } - $host = OC_Request::serverHost(); - $schema = OC_Request::serverProtocol(); - $this->context = new RequestContext($baseUrl, $method, $host, $schema); - // TODO cache - $this->root = $this->getCollection('root'); - } - - public function getRoutingFiles() { - if (!isset($this->routing_files)) { - $this->routing_files = array(); - foreach(OC_APP::getEnabledApps() as $app) { - $file = OC_App::getAppPath($app).'/appinfo/routes.php'; - if(file_exists($file)) { - $this->routing_files[$app] = $file; - } - } - } - return $this->routing_files; - } - - public function getCacheKey() { - if (!isset($this->cache_key)) { - $files = $this->getRoutingFiles(); - $files[] = 'settings/routes.php'; - $files[] = 'core/routes.php'; - $files[] = 'ocs/routes.php'; - $this->cache_key = OC_Cache::generateCacheKeyFromFiles($files); - } - return $this->cache_key; - } - - /** - * loads the api routes - */ - public function loadRoutes() { - foreach($this->getRoutingFiles() as $app => $file) { - $this->useCollection($app); - require_once $file; - $collection = $this->getCollection($app); - $collection->addPrefix('/apps/'.$app); - $this->root->addCollection($collection); - } - $this->useCollection('root'); - require_once 'settings/routes.php'; - require_once 'core/routes.php'; - - // include ocs routes - require_once 'ocs/routes.php'; - $collection = $this->getCollection('ocs'); - $collection->addPrefix('/ocs'); - $this->root->addCollection($collection); - } - - protected function getCollection($name) { - if (!isset($this->collections[$name])) { - $this->collections[$name] = new RouteCollection(); - } - return $this->collections[$name]; - } - - /** - * Sets the collection to use for adding routes - * - * @param string $name Name of the colletion to use. - */ - public function useCollection($name) { - $this->collection = $this->getCollection($name); - } - - /** - * Create a OC_Route. - * - * @param string $name Name of the route to create. - * @param string $pattern The pattern to match - * @param array $defaults An array of default parameter values - * @param array $requirements An array of requirements for parameters (regexes) - */ - public function create($name, $pattern, array $defaults = array(), array $requirements = array()) { - $route = new OC_Route($pattern, $defaults, $requirements); - $this->collection->add($name, $route); - return $route; - } - - /** - * Find the route matching $url. - * - * @param string $url The url to find - */ - public function match($url) { - $matcher = new UrlMatcher($this->root, $this->context); - $parameters = $matcher->match($url); - if (isset($parameters['action'])) { - $action = $parameters['action']; - if (!is_callable($action)) { - var_dump($action); - throw new Exception('not a callable action'); - } - unset($parameters['action']); - call_user_func($action, $parameters); - } elseif (isset($parameters['file'])) { - include $parameters['file']; - } else { - throw new Exception('no action available'); - } - } - - /** - * Get the url generator - * - */ - public function getGenerator() - { - if (null !== $this->generator) { - return $this->generator; - } - - return $this->generator = new UrlGenerator($this->root, $this->context); - } - - /** - * Generate url based on $name and $parameters - * - * @param string $name Name of the route to use. - * @param array $parameters Parameters for the route - */ - public function generate($name, $parameters = array(), $absolute = false) - { - return $this->getGenerator()->generate($name, $parameters, $absolute); - } - -} diff --git a/lib/private/server.php b/lib/private/server.php index 7696fc207fd..8c9ea39c562 100644 --- a/lib/private/server.php +++ b/lib/private/server.php @@ -158,6 +158,10 @@ class Server extends SimpleContainer implements IServerContainer { $config = $c->getConfig(); return new \OC\BackgroundJob\JobList($c->getDatabaseConnection(), $config); }); + $this->registerService('Router', function ($c){ + $router = new \OC\Route\Router(); + return $router; + }); } /** @@ -364,4 +368,15 @@ class Server extends SimpleContainer implements IServerContainer { function getJobList(){ return $this->query('JobList'); } + + /** + * Returns a router for generating and matching urls + * + * @return \OCP\Route\IRouter + */ + function getRouter(){ + $router = $this->query('Router'); + $router->loadRoutes(); + return $router; + } } diff --git a/lib/public/appframework/app.php b/lib/public/appframework/app.php index 90150245c41..21612327879 100644 --- a/lib/public/appframework/app.php +++ b/lib/public/appframework/app.php @@ -67,7 +67,7 @@ class App { * $a = new TasksApp(); * $a->registerRoutes($this, $routes); * - * @param \OC_Router $router + * @param \OCP\Route\IRouter $router * @param array $routes */ public function registerRoutes($router, $routes) { diff --git a/lib/public/iservercontainer.php b/lib/public/iservercontainer.php index 5fb51f9ecd5..dc3aff663d4 100644 --- a/lib/public/iservercontainer.php +++ b/lib/public/iservercontainer.php @@ -190,4 +190,10 @@ interface IServerContainer { */ function getJobList(); + /** + * Returns a router for generating and matching urls + * + * @return \OCP\Route\IRouter + */ + function getRouter(); } diff --git a/lib/public/route/iroute.php b/lib/public/route/iroute.php new file mode 100644 index 00000000000..66fdb841821 --- /dev/null +++ b/lib/public/route/iroute.php @@ -0,0 +1,79 @@ + + * This file is licensed under the Affero General Public License version 3 or + * later. + * See the COPYING-README file. + */ +namespace OCP\Route; + +interface IRoute { + /** + * Specify PATCH as the method to use with this route + */ + public function patch(); + + /** + * Specify the method when this route is to be used + * + * @param string $method HTTP method (uppercase) + * @return \OCP\Route\IRoute + */ + public function method($method); + + /** + * The action to execute when this route matches, includes a file like + * it is called directly + * + * @param $file + */ + public function actionInclude($file); + + /** + * Specify GET as the method to use with this route + */ + public function get(); + + /** + * Specify POST as the method to use with this route + */ + public function post(); + + /** + * Specify DELETE as the method to use with this route + */ + public function delete(); + + /** + * The action to execute when this route matches + * + * @param string|callable $class the class or a callable + * @param string $function the function to use with the class + * @return \OCP\Route\IRoute + * + * This function is called with $class set to a callable or + * to the class with $function + */ + public function action($class, $function = null); + + /** + * Defaults to use for this route + * + * @param array $defaults The defaults + * @return \OCP\Route\IRoute + */ + public function defaults($defaults); + + /** + * Requirements for this route + * + * @param array $requirements The requirements + * @return \OCP\Route\IRoute + */ + public function requirements($requirements); + + /** + * Specify PUT as the method to use with this route + */ + public function put(); +} diff --git a/lib/public/route/irouter.php b/lib/public/route/irouter.php new file mode 100644 index 00000000000..deb01bca9b9 --- /dev/null +++ b/lib/public/route/irouter.php @@ -0,0 +1,71 @@ + + * This file is licensed under the Affero General Public License version 3 or + * later. + * See the COPYING-README file. + */ + +namespace OCP\Route; + +interface IRouter { + + public function __construct(); + + /** + * Get the files to load the routes from + * + * @return string[] + */ + public function getRoutingFiles(); + + public function getCacheKey(); + + /** + * loads the api routes + */ + public function loadRoutes(); + + /** + * Sets the collection to use for adding routes + * + * @param string $name Name of the collection to use. + */ + public function useCollection($name); + + /** + * Create a \OCP\Route\IRoute. + * + * @param string $name Name of the route to create. + * @param string $pattern The pattern to match + * @param array $defaults An array of default parameter values + * @param array $requirements An array of requirements for parameters (regexes) + * @return \OCP\Route\IRoute + */ + public function create($name, $pattern, array $defaults = array(), array $requirements = array()); + + /** + * Find the route matching $url. + * + * @param string $url The url to find + * @throws \Exception + */ + public function match($url); + + /** + * Get the url generator + * + */ + public function getGenerator(); + + /** + * Generate url based on $name and $parameters + * + * @param string $name Name of the route to use. + * @param array $parameters Parameters for the route + * @param bool $absolute + * @return string + */ + public function generate($name, $parameters = array(), $absolute = false); + +} diff --git a/tests/lib/appframework/routing/RoutingTest.php b/tests/lib/appframework/routing/RoutingTest.php index d0244cf2511..9f2675bf0b4 100644 --- a/tests/lib/appframework/routing/RoutingTest.php +++ b/tests/lib/appframework/routing/RoutingTest.php @@ -46,7 +46,7 @@ class RouteConfigTest extends \PHPUnit_Framework_TestCase )); // router mock - $router = $this->getMock("\OC_Router", array('create')); + $router = $this->getMock("\OC\Route\Router", array('create')); // load route configuration $container = new DIContainer('app1'); @@ -91,7 +91,7 @@ class RouteConfigTest extends \PHPUnit_Framework_TestCase $route = $this->mockRoute($verb, $controllerName, $actionName); // router mock - $router = $this->getMock("\OC_Router", array('create')); + $router = $this->getMock("\OC\Route\Router", array('create')); // we expect create to be called once: $router @@ -116,7 +116,7 @@ class RouteConfigTest extends \PHPUnit_Framework_TestCase private function assertResource($yaml, $resourceName, $url, $controllerName, $paramName) { // router mock - $router = $this->getMock("\OC_Router", array('create')); + $router = $this->getMock("\OC\Route\Router", array('create')); // route mocks $indexRoute = $this->mockRoute('GET', $controllerName, 'index'); @@ -174,7 +174,7 @@ class RouteConfigTest extends \PHPUnit_Framework_TestCase private function mockRoute($verb, $controllerName, $actionName) { $container = new DIContainer('app1'); - $route = $this->getMock("\OC_Route", array('method', 'action'), array(), '', false); + $route = $this->getMock("\OC\Route\Route", array('method', 'action'), array(), '', false); $route ->expects($this->exactly(1)) ->method('method') -- cgit v1.2.3 From 010eef95c0c5cebd03b03645d29847638e064bd5 Mon Sep 17 00:00:00 2001 From: Vincent Petry Date: Mon, 10 Mar 2014 15:19:18 +0100 Subject: Fixed total space display when data size exceeds quota The total space display in the personal page now shows the quota value instead of used space when used space exceeds the quota (soft quota). --- lib/private/files/storage/wrapper/quota.php | 7 ++ lib/private/helper.php | 11 ++- tests/lib/helperstorage.php | 113 ++++++++++++++++++++++++++++ 3 files changed, 130 insertions(+), 1 deletion(-) create mode 100644 tests/lib/helperstorage.php (limited to 'tests') diff --git a/lib/private/files/storage/wrapper/quota.php b/lib/private/files/storage/wrapper/quota.php index 26c952e694a..0e0d5b13104 100644 --- a/lib/private/files/storage/wrapper/quota.php +++ b/lib/private/files/storage/wrapper/quota.php @@ -29,6 +29,13 @@ class Quota extends Wrapper { $this->sizeRoot = isset($parameters['root']) ? $parameters['root'] : ''; } + /** + * @return quota value + */ + public function getQuota() { + return $this->quota; + } + /** * @param string $path */ diff --git a/lib/private/helper.php b/lib/private/helper.php index b9956d5ec1c..0b1a26bbecd 100644 --- a/lib/private/helper.php +++ b/lib/private/helper.php @@ -914,13 +914,22 @@ class OC_Helper { if ($used < 0) { $used = 0; } - $free = \OC\Files\Filesystem::free_space($path); + $quota = 0; + // TODO: need a better way to get total space from storage + $storage = $rootInfo->getStorage(); + if ($storage instanceof \OC\Files\Storage\Wrapper\Quota) { + $quota = $storage->getQuota(); + } + $free = $storage->free_space(''); if ($free >= 0) { $total = $free + $used; } else { $total = $free; //either unknown or unlimited } if ($total > 0) { + if ($quota > 0 && $total > $quota) { + $total = $quota; + } // prevent division by zero or error codes (negative values) $relative = round(($used / $total) * 10000) / 100; } else { diff --git a/tests/lib/helperstorage.php b/tests/lib/helperstorage.php new file mode 100644 index 00000000000..010a54e3bb0 --- /dev/null +++ b/tests/lib/helperstorage.php @@ -0,0 +1,113 @@ + + * This file is licensed under the Affero General Public License version 3 or + * later. + * See the COPYING-README file. + */ + +/** + * Test the storage functions of OC_Helper + */ +class Test_Helper_Storage extends PHPUnit_Framework_TestCase { + private $user; + private $storageMock; + + public function setUp() { + $this->user = 'user_' . uniqid(); + \OC\Files\Filesystem::tearDown(); + \OC\Files\Filesystem::init($this->user, '/' . $this->user . '/files'); + + $this->storageMock = $this->getMock( + '\OC\Files\Storage\Temporary', + array('free_space'), + array('') + ); + + \OC\Files\Filesystem::clearMounts(); + + $this->storageMock->expects($this->once()) + ->method('free_space') + ->will($this->returnValue(12)); + } + + public function tearDown() { + $this->user = null; + + $this->storageMock->getCache()->clear(); + \OC\Files\Filesystem::tearDown(); + } + + /** + * Test getting the storage info + */ + function testGetStorageInfo() { + \OC\Files\Filesystem::mount($this->storageMock, array(), '/' . $this->user . '/files'); + $this->storageMock->file_put_contents('test.txt', '01234'); + + $storageInfo = \OC_Helper::getStorageInfo(''); + $this->assertEquals(12, $storageInfo['free']); + $this->assertEquals(5, $storageInfo['used']); + $this->assertEquals(17, $storageInfo['total']); + } + + /** + * Test getting the storage info with quota enabled + */ + function testGetStorageInfoWithQuota() { + $this->storageMock->file_put_contents('test.txt', '01234'); + $this->storageMock = new \OC\Files\Storage\Wrapper\Quota( + array( + 'storage' => $this->storageMock, + 'quota' => 7 + ) + ); + \OC\Files\Filesystem::mount($this->storageMock, array(), '/' . $this->user . '/files'); + + $storageInfo = \OC_Helper::getStorageInfo(''); + $this->assertEquals(2, $storageInfo['free']); + $this->assertEquals(5, $storageInfo['used']); + $this->assertEquals(7, $storageInfo['total']); + } + + /** + * Test getting the storage info when data exceeds quota + */ + function testGetStorageInfoWhenSizeExceedsQuota() { + $this->storageMock->file_put_contents('test.txt', '0123456789'); + $this->storageMock = new \OC\Files\Storage\Wrapper\Quota( + array( + 'storage' => $this->storageMock, + 'quota' => 7 + ) + ); + \OC\Files\Filesystem::mount($this->storageMock, array(), '/' . $this->user . '/files'); + + $storageInfo = \OC_Helper::getStorageInfo(''); + $this->assertEquals(0, $storageInfo['free']); + $this->assertEquals(10, $storageInfo['used']); + // total = quota + $this->assertEquals(7, $storageInfo['total']); + } + + /** + * Test getting the storage info when the remaining + * free storage space is less than the quota + */ + function testGetStorageInfoWhenFreeSpaceLessThanQuota() { + $this->storageMock->file_put_contents('test.txt', '01234'); + $this->storageMock = new \OC\Files\Storage\Wrapper\Quota( + array( + 'storage' => $this->storageMock, + 'quota' => 18 + ) + ); + \OC\Files\Filesystem::mount($this->storageMock, array(), '/' . $this->user . '/files'); + + $storageInfo = \OC_Helper::getStorageInfo(''); + $this->assertEquals(12, $storageInfo['free']); + $this->assertEquals(5, $storageInfo['used']); + // total = free + used (because quota > total) + $this->assertEquals(17, $storageInfo['total']); + } +} -- cgit v1.2.3 From d798169037e666ab9b4165666193019d4dd18aaf Mon Sep 17 00:00:00 2001 From: Bart Visscher Date: Tue, 11 Mar 2014 21:01:16 +0100 Subject: Cleanup the fileproxy proxies on test bootstrap --- tests/bootstrap.php | 1 + 1 file changed, 1 insertion(+) (limited to 'tests') diff --git a/tests/bootstrap.php b/tests/bootstrap.php index 581cfcff9f3..88f5de4b584 100644 --- a/tests/bootstrap.php +++ b/tests/bootstrap.php @@ -11,3 +11,4 @@ if(!class_exists('PHPUnit_Framework_TestCase')) { OC_Hook::clear(); OC_Log::$enabled = false; +OC_FileProxy::clearProxies(); -- cgit v1.2.3 From a8eb7a5092fad987b96f9dac947dc9bf4a2b0eaf Mon Sep 17 00:00:00 2001 From: Robin Appelman Date: Thu, 13 Mar 2014 13:33:09 +0100 Subject: Allow setting the config dir to use as enviroment variable for phpunit --- lib/base.php | 4 +++- tests/bootstrap.php | 9 +++++++-- 2 files changed, 10 insertions(+), 3 deletions(-) (limited to 'tests') diff --git a/lib/base.php b/lib/base.php index 86ee5349828..2d4a9f92764 100644 --- a/lib/base.php +++ b/lib/base.php @@ -103,7 +103,9 @@ class OC { get_include_path() ); - if(defined('PHPUNIT_RUN') and PHPUNIT_RUN and is_dir(OC::$SERVERROOT . '/tests/config/')) { + if(defined('PHPUNIT_CONFIG_DIR')) { + self::$configDir = OC::$SERVERROOT . '/' . PHPUNIT_CONFIG_DIR . '/'; + } elseif(defined('PHPUNIT_RUN') and PHPUNIT_RUN and is_dir(OC::$SERVERROOT . '/tests/config/')) { self::$configDir = OC::$SERVERROOT . '/tests/config/'; } else { self::$configDir = OC::$SERVERROOT . '/config/'; diff --git a/tests/bootstrap.php b/tests/bootstrap.php index 581cfcff9f3..70de7cd1c44 100644 --- a/tests/bootstrap.php +++ b/tests/bootstrap.php @@ -3,9 +3,14 @@ define('PHPUNIT_RUN', 1); -require_once __DIR__.'/../lib/base.php'; +$configDir = getenv('CONFIG_DIR'); +if ($configDir) { + define('PHPUNIT_CONFIG_DIR', $configDir); +} + +require_once __DIR__ . '/../lib/base.php'; -if(!class_exists('PHPUnit_Framework_TestCase')) { +if (!class_exists('PHPUnit_Framework_TestCase')) { require_once('PHPUnit/Autoload.php'); } -- cgit v1.2.3 From fc697c729811e5644e2c7bc884bd54d3ff092ac8 Mon Sep 17 00:00:00 2001 From: Thomas Müller Date: Thu, 13 Mar 2014 16:19:17 +0100 Subject: adding StartSessionListener which initializes the session before each test case execution --- tests/phpunit-autotest.xml | 1 + tests/phpunit.xml.dist | 3 +++ tests/startsessionlistener.php | 45 ++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 49 insertions(+) create mode 100644 tests/startsessionlistener.php (limited to 'tests') diff --git a/tests/phpunit-autotest.xml b/tests/phpunit-autotest.xml index 1a2ab35491b..872ff2c2596 100644 --- a/tests/phpunit-autotest.xml +++ b/tests/phpunit-autotest.xml @@ -36,6 +36,7 @@ + detail diff --git a/tests/phpunit.xml.dist b/tests/phpunit.xml.dist index 71a4ff2762c..21c63ea0469 100644 --- a/tests/phpunit.xml.dist +++ b/tests/phpunit.xml.dist @@ -29,4 +29,7 @@ + + + diff --git a/tests/startsessionlistener.php b/tests/startsessionlistener.php new file mode 100644 index 00000000000..fb7fa83e090 --- /dev/null +++ b/tests/startsessionlistener.php @@ -0,0 +1,45 @@ + + * This file is licensed under the Affero General Public License version 3 or + * later. + * See the COPYING-README file. + */ + +/** + * Starts a new session before each test execution + */ +class StartSessionListener implements PHPUnit_Framework_TestListener { + + public function addError(PHPUnit_Framework_Test $test, Exception $e, $time) { + } + + public function addFailure(PHPUnit_Framework_Test $test, PHPUnit_Framework_AssertionFailedError $e, $time) { + } + + public function addIncompleteTest(PHPUnit_Framework_Test $test, Exception $e, $time) { + } + + public function addSkippedTest(PHPUnit_Framework_Test $test, Exception $e, $time) { + } + + public function startTest(PHPUnit_Framework_Test $test) { + + // new session + \OC::$session = new \OC\Session\Memory(''); + + // load the version + OC_Util::getVersion(); + + } + + public function endTest(PHPUnit_Framework_Test $test, $time) { + } + + public function startTestSuite(PHPUnit_Framework_TestSuite $suite) { + } + + public function endTestSuite(PHPUnit_Framework_TestSuite $suite) { + } + +} -- cgit v1.2.3 From 3c46dcd7ddde403cdc89abdaabd3879fc71d39b9 Mon Sep 17 00:00:00 2001 From: Vincent Petry Date: Fri, 14 Mar 2014 13:03:18 +0100 Subject: Added .ocdata file to check for data folder validity In environments where the data folder is mount from another partition, it is important to check that the data folder we see is actually the real one. If the mount failed for some reasons, this fix will make ownCloud temporarily unavailable instead of causing unpredictable behavior. --- lib/private/setup.php | 4 ++ lib/private/updater.php | 5 ++ lib/private/util.php | 32 +++++++++++-- tests/lib/utilcheckserver.php | 108 ++++++++++++++++++++++++++++++++++++++++++ tests/testcleanuplistener.php | 1 + 5 files changed, 146 insertions(+), 4 deletions(-) create mode 100644 tests/lib/utilcheckserver.php (limited to 'tests') diff --git a/lib/private/setup.php b/lib/private/setup.php index 0d5bf424b33..b1061b3a25b 100644 --- a/lib/private/setup.php +++ b/lib/private/setup.php @@ -106,6 +106,10 @@ class OC_Setup { //guess what this does OC_Installer::installShippedApps(); + // create empty file in data dir, so we can later find + // out that this is indeed an ownCloud data directory + file_put_contents(OC_Config::getValue('datadirectory', OC::$SERVERROOT.'/data').'/.ocdata', ''); + //create htaccess files for apache hosts if (isset($_SERVER['SERVER_SOFTWARE']) && strstr($_SERVER['SERVER_SOFTWARE'], 'Apache')) { self::createHtaccess(); diff --git a/lib/private/updater.php b/lib/private/updater.php index fd2d46a1fac..2ca705193cc 100644 --- a/lib/private/updater.php +++ b/lib/private/updater.php @@ -105,6 +105,11 @@ class Updater extends BasicEmitter { } $this->emit('\OC\Updater', 'maintenanceStart'); + // create empty file in data dir, so we can later find + // out that this is indeed an ownCloud data directory + // (in case it didn't exist before) + file_put_contents(\OC_Config::getValue('datadirectory', \OC::$SERVERROOT.'/data').'/.ocdata', ''); + /* * START CONFIG CHANGES FOR OLDER VERSIONS */ diff --git a/lib/private/util.php b/lib/private/util.php index 920161949ae..75e1711b0de 100755 --- a/lib/private/util.php +++ b/lib/private/util.php @@ -290,13 +290,19 @@ class OC_Util { * @return array arrays with error messages and hints */ public static function checkServer() { + $errors = array(); + $CONFIG_DATADIRECTORY = OC_Config::getValue('datadirectory', OC::$SERVERROOT . '/data'); + + if (!\OC::needUpgrade() && OC_Config::getValue('installed', false)) { + // this check needs to be done every time + $errors = self::checkDataDirectoryValidity($CONFIG_DATADIRECTORY); + } + // Assume that if checkServer() succeeded before in this session, then all is fine. if(\OC::$session->exists('checkServer_suceeded') && \OC::$session->get('checkServer_suceeded')) { - return array(); + return $errors; } - $errors = array(); - $defaults = new \OC_Defaults(); $webServerRestart = false; @@ -341,7 +347,6 @@ class OC_Util { ); } } - $CONFIG_DATADIRECTORY = OC_Config::getValue( "datadirectory", OC::$SERVERROOT."/data" ); // Create root dir. if(!is_dir($CONFIG_DATADIRECTORY)) { $success=@mkdir($CONFIG_DATADIRECTORY); @@ -540,6 +545,25 @@ class OC_Util { return $errors; } + /** + * Check that the data directory exists and is valid by + * checking the existence of the ".ocdata" file. + * + * @param string $dataDirectory data directory path + * @return bool true if the data directory is valid, false otherwise + */ + public static function checkDataDirectoryValidity($dataDirectory) { + $errors = array(); + if (!file_exists($dataDirectory.'/.ocdata')) { + $errors[] = array( + 'error' => 'Data directory (' . $dataDirectory . ') is invalid', + 'hint' => 'Please check that the data directory contains a file' . + ' ".ocdata" in its root.' + ); + } + return $errors; + } + /** * @return void */ diff --git a/tests/lib/utilcheckserver.php b/tests/lib/utilcheckserver.php new file mode 100644 index 00000000000..155d617c4ad --- /dev/null +++ b/tests/lib/utilcheckserver.php @@ -0,0 +1,108 @@ + + * This file is licensed under the Affero General Public License version 3 or + * later. + * See the COPYING-README file. + */ + +/** + * Tests for server check functions + */ +class Test_Util_CheckServer extends PHPUnit_Framework_TestCase { + + private $datadir; + + public function setUp() { + $this->datadir = \OC_Config::getValue('datadirectory', \OC::$SERVERROOT . '/data'); + + file_put_contents($this->datadir . '/.ocdata', ''); + } + + public function tearDown() { + // clean up + @unlink($this->datadir . '/.ocdata'); + } + + /** + * Test that checkServer() returns no errors in the regular case. + */ + public function testCheckServer() { + $result = \OC_Util::checkServer(); + $this->assertEmpty($result); + } + + /** + * Test that checkServer() does not check the data dir validity + * when the server is not installed yet (else the setup cannot + * be run...) + */ + public function testCheckServerSkipDataDirValidityOnSetup() { + // simulate old version that didn't have it + unlink($this->datadir . '/.ocdata'); + + $session = \OC::$server->getSession(); + $oldInstalled = \OC_Config::getValue('installed', false); + + // simulate that the server isn't setup yet + \OC_Config::setValue('installed', false); + + // even though ".ocdata" is missing, the error isn't + // triggered to allow setup to run + $result = \OC_Util::checkServer(); + $this->assertEmpty($result); + + // restore config + \OC_Config::setValue('installed', $oldInstalled); + } + + /** + * Test that checkServer() does not check the data dir validity + * when an upgrade is required (else the upgrade cannot be + * performed...) + */ + public function testCheckServerSkipDataDirValidityOnUpgrade() { + // simulate old version that didn't have it + unlink($this->datadir . '/.ocdata'); + + $session = \OC::$server->getSession(); + $oldCurrentVersion = $session->get('OC_Version'); + $oldInstallVersion = \OC_Config::getValue('version', '0.0.0'); + + // upgrade condition to simulate needUpgrade() === true + $session->set('OC_Version', array(6, 0, 0, 2)); + \OC_Config::setValue('version', '6.0.0.1'); + + // even though ".ocdata" is missing, the error isn't + // triggered to allow for upgrade + $result = \OC_Util::checkServer(); + $this->assertEmpty($result); + + // restore versions + $session->set('OC_Version', $oldCurrentVersion); + \OC_Config::setValue('version', $oldInstallVersion); + } + + /** + * Test that checkDataDirectoryValidity returns no error + * when ".ocdata" is present. + */ + public function testCheckDataDirValidity() { + $result = \OC_Util::checkDataDirectoryValidity($this->datadir); + $this->assertEmpty($result); + } + + /** + * Test that checkDataDirectoryValidity and checkServer + * both return an error when ".ocdata" is missing. + */ + public function testCheckDataDirValidityWhenFileMissing() { + unlink($this->datadir . '/.ocdata'); + $result = \OC_Util::checkDataDirectoryValidity($this->datadir); + $this->assertEquals(1, count($result)); + + $result = \OC_Util::checkServer(); + $this->assertEquals(1, count($result)); + } + +} diff --git a/tests/testcleanuplistener.php b/tests/testcleanuplistener.php index 299a589ef4e..2083ffce67c 100644 --- a/tests/testcleanuplistener.php +++ b/tests/testcleanuplistener.php @@ -83,6 +83,7 @@ class TestCleanupListener implements PHPUnit_Framework_TestListener { $knownEntries = array( 'owncloud.log' => true, 'owncloud.db' => true, + '.ocdata' => true, '..' => true, '.' => true ); -- cgit v1.2.3 From fe05c0c81bba1e2203f6ec5c8fbe1007281e1d45 Mon Sep 17 00:00:00 2001 From: Thomas Müller Date: Fri, 14 Mar 2014 18:16:20 +0100 Subject: move session reset to endTest() - necessary because we need a valid session in the next unit tests setUp() call --- tests/startsessionlistener.php | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) (limited to 'tests') diff --git a/tests/startsessionlistener.php b/tests/startsessionlistener.php index fb7fa83e090..7559b8cff65 100644 --- a/tests/startsessionlistener.php +++ b/tests/startsessionlistener.php @@ -24,16 +24,14 @@ class StartSessionListener implements PHPUnit_Framework_TestListener { } public function startTest(PHPUnit_Framework_Test $test) { + } + public function endTest(PHPUnit_Framework_Test $test, $time) { // new session \OC::$session = new \OC\Session\Memory(''); // load the version OC_Util::getVersion(); - - } - - public function endTest(PHPUnit_Framework_Test $test, $time) { } public function startTestSuite(PHPUnit_Framework_TestSuite $suite) { -- cgit v1.2.3 From cd038604d396b7611353041cb8ed033f23fe305b Mon Sep 17 00:00:00 2001 From: Thomas Müller Date: Mon, 17 Mar 2014 08:40:59 +0100 Subject: unit tests for specific image type output added --- lib/private/image.php | 7 ++++++- tests/lib/image.php | 24 ++++++++++++++++++++++-- 2 files changed, 28 insertions(+), 3 deletions(-) (limited to 'tests') diff --git a/lib/private/image.php b/lib/private/image.php index dd041442ed6..c987ce92c3c 100644 --- a/lib/private/image.php +++ b/lib/private/image.php @@ -239,7 +239,12 @@ class OC_Image { $retVal = imagepng($this->resource, $filePath); break; case IMAGETYPE_XBM: - $retVal = imagexbm($this->resource, $filePath); + if (function_exists('imagexbm')) { + $retVal = imagexbm($this->resource, $filePath); + } else { + throw new Exception('\OC_Image::_output(): imagexbm() is not supported.'); + } + break; case IMAGETYPE_WBMP: $retVal = imagewbmp($this->resource, $filePath); diff --git a/tests/lib/image.php b/tests/lib/image.php index 4aba1b0bc61..131a9d86f3e 100644 --- a/tests/lib/image.php +++ b/tests/lib/image.php @@ -8,8 +8,8 @@ class Test_Image extends PHPUnit_Framework_TestCase { public static function tearDownAfterClass() { - unlink(OC::$SERVERROOT.'/tests/data/testimage2.png'); - unlink(OC::$SERVERROOT.'/tests/data/testimage2.jpg'); + @unlink(OC::$SERVERROOT.'/tests/data/testimage2.png'); + @unlink(OC::$SERVERROOT.'/tests/data/testimage2.jpg'); } public function testGetMimeTypeForFile() { @@ -236,4 +236,24 @@ class Test_Image extends PHPUnit_Framework_TestCase { $this->assertEquals(200, $img->width()); $this->assertEquals(200, $img->height()); } + + function convertDataProvider() { + return array( + array( 'image/gif'), + array( 'image/jpeg'), + array( 'image/png'), + ); + } + + /** + * @dataProvider convertDataProvider + */ + public function testConvert($mimeType) { + $img = new \OC_Image(OC::$SERVERROOT.'/tests/data/testimage.png'); + $tempFile = tempnam(sys_get_temp_dir(), 'img-test'); + + $img->save($tempFile, $mimeType); + $actualMimeType = \OC_Image::getMimeTypeForFile($tempFile); + $this->assertEquals($mimeType, $actualMimeType); + } } -- cgit v1.2.3 From 145db370d1e83978d0e575a60d7d61fbe1039cc4 Mon Sep 17 00:00:00 2001 From: Vincent Petry Date: Mon, 17 Mar 2014 12:15:12 +0100 Subject: Correctly round bytes when converted from human readable format Instead of leave two decimal places which is confusing, round the byte values correctly to the closest byte. --- lib/private/helper.php | 4 ++-- tests/lib/helper.php | 4 +++- 2 files changed, 5 insertions(+), 3 deletions(-) (limited to 'tests') diff --git a/lib/private/helper.php b/lib/private/helper.php index 0b1a26bbecd..807fa849637 100644 --- a/lib/private/helper.php +++ b/lib/private/helper.php @@ -308,7 +308,7 @@ class OC_Helper { /** * @brief Make a computer file size - * @param string $str file size in a fancy format + * @param string $str file size in human readable format * @return int a file size in bytes * * Makes 2kB to 2048. @@ -338,7 +338,7 @@ class OC_Helper { $bytes *= $bytes_array[$matches[1]]; } - $bytes = round($bytes, 2); + $bytes = round($bytes); return $bytes; } diff --git a/tests/lib/helper.php b/tests/lib/helper.php index 4311215795c..0943e6bc1b9 100644 --- a/tests/lib/helper.php +++ b/tests/lib/helper.php @@ -23,6 +23,7 @@ class Test_Helper extends PHPUnit_Framework_TestCase { array('0 B', 0), array('1 kB', 1024), array('9.5 MB', 10000000), + array('1.3 GB', 1395864371), array('465.7 GB', 500000000000), array('454.7 TB', 500000000000000), array('444.1 PB', 500000000000000000), @@ -41,8 +42,9 @@ class Test_Helper extends PHPUnit_Framework_TestCase { return array( array(0.0, "0 B"), array(1024.0, "1 kB"), + array(1395864371.0, '1.3 GB'), array(9961472.0, "9.5 MB"), - array(500041567436.8, "465.7 GB"), + array(500041567437.0, "465.7 GB"), ); } -- cgit v1.2.3 From 6bbbf8536f6d5d21eed906c42da1e12118e4112e Mon Sep 17 00:00:00 2001 From: Thomas Müller Date: Mon, 17 Mar 2014 21:57:10 +0100 Subject: introduce reopen() method to be used for unit test execution only - right after a unit test has been executed the session will be reopened --- lib/private/session/memory.php | 7 +++++++ tests/startsessionlistener.php | 11 ++++++----- 2 files changed, 13 insertions(+), 5 deletions(-) (limited to 'tests') diff --git a/lib/private/session/memory.php b/lib/private/session/memory.php index 8434b6000e5..1497c0f8928 100644 --- a/lib/private/session/memory.php +++ b/lib/private/session/memory.php @@ -63,6 +63,13 @@ class Memory extends Session { $this->data = array(); } + /** + * Helper function for PHPUnit execution - don't use in non-test code + */ + public function reopen() { + $this->sessionClosed = false; + } + /** * In case the session has already been locked an exception will be thrown * diff --git a/tests/startsessionlistener.php b/tests/startsessionlistener.php index 7559b8cff65..808a2a2226f 100644 --- a/tests/startsessionlistener.php +++ b/tests/startsessionlistener.php @@ -27,11 +27,12 @@ class StartSessionListener implements PHPUnit_Framework_TestListener { } public function endTest(PHPUnit_Framework_Test $test, $time) { - // new session - \OC::$session = new \OC\Session\Memory(''); - - // load the version - OC_Util::getVersion(); + // reopen the session - only allowed for memory session + if (\OC::$session instanceof \OC\Session\Memory) { + /** @var $session \OC\Session\Memory */ + $session = \OC::$session; + $session->reopen(); + } } public function startTestSuite(PHPUnit_Framework_TestSuite $suite) { -- cgit v1.2.3 From 66bc0f0848846bce3680b79da4209d42620f1b8d Mon Sep 17 00:00:00 2001 From: Vincent Petry Date: Wed, 19 Mar 2014 19:07:11 +0100 Subject: Still return quota value when free space is unknown Fixed the quota storage wrapper to correctly return the quota value when the free space is not known (which usually happens when the disk_free_space function is disabled) --- lib/private/files/storage/wrapper/quota.php | 9 ++++++++- tests/lib/files/storage/wrapper/quota.php | 18 ++++++++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) (limited to 'tests') diff --git a/lib/private/files/storage/wrapper/quota.php b/lib/private/files/storage/wrapper/quota.php index 32ceba8b196..a878b2c5cf6 100644 --- a/lib/private/files/storage/wrapper/quota.php +++ b/lib/private/files/storage/wrapper/quota.php @@ -69,7 +69,14 @@ class Quota extends Wrapper { return \OC\Files\SPACE_NOT_COMPUTED; } else { $free = $this->storage->free_space($path); - return min($free, (max($this->quota - $used, 0))); + $quotaFree = max($this->quota - $used, 0); + // if free space is known + if ($free >= 0) { + $free = min($free, $quotaFree); + } else { + $free = $quotaFree; + } + return $free; } } } diff --git a/tests/lib/files/storage/wrapper/quota.php b/tests/lib/files/storage/wrapper/quota.php index bd2c69a7396..777529fd85e 100644 --- a/tests/lib/files/storage/wrapper/quota.php +++ b/tests/lib/files/storage/wrapper/quota.php @@ -61,6 +61,24 @@ class Quota extends \Test\Files\Storage\Storage { $this->assertEquals(6, $instance->free_space('')); } + public function testFreeSpaceWithUnknownDiskSpace() { + $storage = $this->getMock( + '\OC\Files\Storage\Local', + array('free_space'), + array(array('datadir' => $this->tmpDir)) + ); + $storage->expects($this->any()) + ->method('free_space') + ->will($this->returnValue(-2)); + $storage->getScanner()->scan(''); + + $instance = new \OC\Files\Storage\Wrapper\Quota(array('storage' => $storage, 'quota' => 9)); + $instance->getCache()->put( + '', array('size' => 3, 'unencrypted_size' => 0) + ); + $this->assertEquals(6, $instance->free_space('')); + } + public function testFreeSpaceWithUsedSpaceAndEncryption() { $instance = $this->getLimitedStorage(9); $instance->getCache()->put( -- cgit v1.2.3 From fffe330bbccee617cac6d84d1f4097133de82e44 Mon Sep 17 00:00:00 2001 From: Robin Appelman Date: Thu, 20 Mar 2014 15:32:12 +0100 Subject: Fix parameter order for Storage\Local::hash --- lib/private/files/storage/local.php | 2 +- lib/private/files/storage/mappedlocal.php | 2 +- tests/lib/files/storage/storage.php | 47 +++++++++++++++++++++---------- 3 files changed, 34 insertions(+), 17 deletions(-) (limited to 'tests') diff --git a/lib/private/files/storage/local.php b/lib/private/files/storage/local.php index a62230bdba5..071b12ffbd5 100644 --- a/lib/private/files/storage/local.php +++ b/lib/private/files/storage/local.php @@ -256,7 +256,7 @@ if (\OC_Util::runningOnWindows()) { return 0; } - public function hash($path, $type, $raw = false) { + public function hash($type, $path, $raw = false) { return hash_file($type, $this->datadir . $path, $raw); } diff --git a/lib/private/files/storage/mappedlocal.php b/lib/private/files/storage/mappedlocal.php index 1bab3489a28..cb5ab6902e6 100644 --- a/lib/private/files/storage/mappedlocal.php +++ b/lib/private/files/storage/mappedlocal.php @@ -276,7 +276,7 @@ class MappedLocal extends \OC\Files\Storage\Common{ return 0; } - public function hash($path, $type, $raw=false) { + public function hash($type, $path, $raw=false) { return hash_file($type, $this->buildPath($path), $raw); } diff --git a/tests/lib/files/storage/storage.php b/tests/lib/files/storage/storage.php index f9291758606..f3bfba3feb8 100644 --- a/tests/lib/files/storage/storage.php +++ b/tests/lib/files/storage/storage.php @@ -64,17 +64,17 @@ abstract class Storage extends \PHPUnit_Framework_TestCase { * @dataProvider directoryProvider */ public function testDirectories($directory) { - $this->assertFalse($this->instance->file_exists('/'.$directory)); + $this->assertFalse($this->instance->file_exists('/' . $directory)); - $this->assertTrue($this->instance->mkdir('/'.$directory)); + $this->assertTrue($this->instance->mkdir('/' . $directory)); - $this->assertTrue($this->instance->file_exists('/'.$directory)); - $this->assertTrue($this->instance->is_dir('/'.$directory)); - $this->assertFalse($this->instance->is_file('/'.$directory)); - $this->assertEquals('dir', $this->instance->filetype('/'.$directory)); - $this->assertEquals(0, $this->instance->filesize('/'.$directory)); - $this->assertTrue($this->instance->isReadable('/'.$directory)); - $this->assertTrue($this->instance->isUpdatable('/'.$directory)); + $this->assertTrue($this->instance->file_exists('/' . $directory)); + $this->assertTrue($this->instance->is_dir('/' . $directory)); + $this->assertFalse($this->instance->is_file('/' . $directory)); + $this->assertEquals('dir', $this->instance->filetype('/' . $directory)); + $this->assertEquals(0, $this->instance->filesize('/' . $directory)); + $this->assertTrue($this->instance->isReadable('/' . $directory)); + $this->assertTrue($this->instance->isUpdatable('/' . $directory)); $dh = $this->instance->opendir('/'); $content = array(); @@ -85,13 +85,13 @@ abstract class Storage extends \PHPUnit_Framework_TestCase { } $this->assertEquals(array($directory), $content); - $this->assertFalse($this->instance->mkdir('/'.$directory)); //cant create existing folders - $this->assertTrue($this->instance->rmdir('/'.$directory)); + $this->assertFalse($this->instance->mkdir('/' . $directory)); //cant create existing folders + $this->assertTrue($this->instance->rmdir('/' . $directory)); $this->wait(); - $this->assertFalse($this->instance->file_exists('/'.$directory)); + $this->assertFalse($this->instance->file_exists('/' . $directory)); - $this->assertFalse($this->instance->rmdir('/'.$directory)); //cant remove non existing folders + $this->assertFalse($this->instance->rmdir('/' . $directory)); //cant remove non existing folders $dh = $this->instance->opendir('/'); $content = array(); @@ -103,8 +103,7 @@ abstract class Storage extends \PHPUnit_Framework_TestCase { $this->assertEquals(array(), $content); } - public function directoryProvider() - { + public function directoryProvider() { return array( array('folder'), array(' folder'), @@ -113,6 +112,7 @@ abstract class Storage extends \PHPUnit_Framework_TestCase { array('spéciäl földer'), ); } + /** * test the various uses of file_get_contents and file_put_contents */ @@ -298,4 +298,21 @@ abstract class Storage extends \PHPUnit_Framework_TestCase { $this->assertFalse($this->instance->file_exists('folder/bar')); $this->assertFalse($this->instance->file_exists('folder')); } + + public function hashProvider(){ + return array( + array('Foobar', 'md5'), + array('Foobar', 'sha1'), + array('Foobar', 'sha256'), + ); + } + + /** + * @dataProvider hashProvider + */ + public function testHash($data, $type) { + $this->instance->file_put_contents('hash.txt', $data); + $this->assertEquals(hash($type, $data), $this->instance->hash($type, 'hash.txt')); + $this->assertEquals(hash($type, $data, true), $this->instance->hash($type, 'hash.txt', true)); + } } -- cgit v1.2.3 From fb7f3008d33cb123f8b6931f6edf8697913b355a Mon Sep 17 00:00:00 2001 From: Thomas Müller Date: Mon, 24 Mar 2014 13:46:31 +0100 Subject: idn have to be converted before being used --- lib/private/mail.php | 17 +++++++++++++++++ tests/lib/mail.php | 30 ++++++++++++++++++++++++++++++ 2 files changed, 47 insertions(+) create mode 100644 tests/lib/mail.php (limited to 'tests') diff --git a/lib/private/mail.php b/lib/private/mail.php index 9605290fe57..f691fda979d 100644 --- a/lib/private/mail.php +++ b/lib/private/mail.php @@ -73,6 +73,7 @@ class OC_Mail { $mailo->FromName = $fromname;; $mailo->Sender = $fromaddress; try { + $toaddress = self::buildAsciiEmail($toaddress); $mailo->AddAddress($toaddress, $toname); if($ccaddress<>'') $mailo->AddCC($ccaddress, $ccname); @@ -125,6 +126,22 @@ class OC_Mail { * @return bool */ public static function ValidateAddress($emailAddress) { + $emailAddress = self::buildAsciiEmail($emailAddress); return PHPMailer::ValidateAddress($emailAddress); } + + /** + * IDN domains will be properly converted to ascii domains. + * + * @param string $emailAddress + * @return string + */ + public static function buildAsciiEmail($emailAddress) { + + list($name, $domain) = explode('@', $emailAddress, 2); + $domain = idn_to_ascii($domain); + + return "$name@$domain"; + } + } diff --git a/tests/lib/mail.php b/tests/lib/mail.php new file mode 100644 index 00000000000..a88a9d797ae --- /dev/null +++ b/tests/lib/mail.php @@ -0,0 +1,30 @@ + + * This file is licensed under the Affero General Public License version 3 or + * later. + * See the COPYING-README file. + */ + +class Test_Mail extends PHPUnit_Framework_TestCase { + + /** + * @dataProvider buildAsciiEmailProvider + * @param $expected + * @param $address + */ + public function testBuildAsciiEmail($expected, $address) { + $actual = \OC_Mail::buildAsciiEmail($address); + $this->assertEquals($expected, $actual); + } + + function buildAsciiEmailProvider() { + return array( + array('info@example.com', 'info@example.com'), + array('info@xn--cjr6vy5ejyai80u.com', 'info@國際化域名.com'), + array('info@xn--mller-kva.de', 'info@müller.de'), + array('info@xn--mller-kva.xn--mller-kva.de', 'info@müller.müller.de'), + ); + } + +} -- cgit v1.2.3 From 1e39719926ea4b204a3b0a3e8aeba6a9a9ad5a96 Mon Sep 17 00:00:00 2001 From: Vincent Petry Date: Mon, 24 Mar 2014 14:32:04 +0100 Subject: Added unit tests for external cache folder --- tests/lib/files/filesystem.php | 51 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) (limited to 'tests') diff --git a/tests/lib/files/filesystem.php b/tests/lib/files/filesystem.php index 90f1dfe581b..53f528af793 100644 --- a/tests/lib/files/filesystem.php +++ b/tests/lib/files/filesystem.php @@ -226,4 +226,55 @@ class Filesystem extends \PHPUnit_Framework_TestCase { $path = $arguments['path']; $this->assertEquals($path, \OC\Files\Filesystem::normalizePath($path)); //the path passed to the hook should already be normalized } + + /** + * Test that the default cache dir is part of the user's home + */ + public function testMountDefaultCacheDir() { + $userId = uniqid('user_'); + $oldCachePath = \OC_Config::getValue('cache_path', ''); + // no cache path configured + \OC_Config::setValue('cache_path', ''); + + \OC_User::createUser($userId, $userId); + \OC\Files\Filesystem::initMountPoints($userId); + + $this->assertEquals( + '/' . $userId . '/', + \OC\Files\Filesystem::getMountPoint('/' . $userId . '/cache') + ); + list($storage, $internalPath) = \OC\Files\Filesystem::resolvePath('/' . $userId . '/cache'); + $this->assertInstanceOf('\OC\Files\Storage\Home', $storage); + $this->assertEquals('cache', $internalPath); + \OC_User::deleteUser($userId); + + \OC_Config::setValue('cache_path', $oldCachePath); + } + + /** + * Test that an external cache is mounted into + * the user's home + */ + public function testMountExternalCacheDir() { + $userId = uniqid('user_'); + + $oldCachePath = \OC_Config::getValue('cache_path', ''); + // set cache path to temp dir + $cachePath = \OC_Helper::tmpFolder() . '/extcache'; + \OC_Config::setValue('cache_path', $cachePath); + + \OC_User::createUser($userId, $userId); + \OC\Files\Filesystem::initMountPoints($userId); + + $this->assertEquals( + '/' . $userId . '/cache/', + \OC\Files\Filesystem::getMountPoint('/' . $userId . '/cache') + ); + list($storage, $internalPath) = \OC\Files\Filesystem::resolvePath('/' . $userId . '/cache'); + $this->assertInstanceOf('\OC\Files\Storage\Local', $storage); + $this->assertEquals('', $internalPath); + \OC_User::deleteUser($userId); + + \OC_Config::setValue('cache_path', $oldCachePath); + } } -- cgit v1.2.3 From bc0292c16d5fa8e99727306ef703da1e018defa2 Mon Sep 17 00:00:00 2001 From: Bjoern Schiessle Date: Thu, 6 Mar 2014 14:00:12 +0100 Subject: always return an array --- lib/private/share/share.php | 15 ++++----------- tests/lib/share/share.php | 12 ++++++------ 2 files changed, 10 insertions(+), 17 deletions(-) (limited to 'tests') diff --git a/lib/private/share/share.php b/lib/private/share/share.php index f6f2ac8ccf8..b69f620646f 100644 --- a/lib/private/share/share.php +++ b/lib/private/share/share.php @@ -889,7 +889,7 @@ class Share extends \OC\Share\Constants { * @param bool Include collection item types (optional) * @param bool TODO (optional) * @prams bool check expire date - * @return mixed + * @return array * * See public functions getItem(s)... for parameter usage * @@ -898,11 +898,7 @@ class Share extends \OC\Share\Constants { $uidOwner = null, $format = self::FORMAT_NONE, $parameters = null, $limit = -1, $includeCollections = false, $itemShareWithBySource = false, $checkExpireDate = true) { if (!self::isEnabled()) { - if ($limit == 1 || (isset($uidOwner) && isset($item))) { - return false; - } else { - return array(); - } + return array(); } $backend = self::getBackend($itemType); $collectionTypes = false; @@ -1214,13 +1210,10 @@ class Share extends \OC\Share\Constants { if (!empty($collectionItems)) { $items = array_merge($items, $collectionItems); } - if (empty($items) && $limit == 1) { - return false; - } + return self::formatResult($items, $column, $backend, $format, $parameters); - } else if ($limit == 1 || (isset($uidOwner) && isset($item))) { - return false; } + return array(); } diff --git a/tests/lib/share/share.php b/tests/lib/share/share.php index b5cba9430aa..aae91fa1087 100644 --- a/tests/lib/share/share.php +++ b/tests/lib/share/share.php @@ -282,7 +282,7 @@ class Test_Share extends PHPUnit_Framework_TestCase { OC_User::setUserId($this->user2); $this->assertEquals(array(OCP\PERMISSION_READ), OCP\Share::getItemSharedWith('test', 'test.txt', Test_Share_Backend::FORMAT_PERMISSIONS)); OC_User::setUserId($this->user3); - $this->assertFalse(OCP\Share::getItemSharedWith('test', 'test.txt')); + $this->assertSame(array(), OCP\Share::getItemSharedWith('test', 'test.txt')); // Reshare again, and then have owner unshare OC_User::setUserId($this->user1); @@ -292,9 +292,9 @@ class Test_Share extends PHPUnit_Framework_TestCase { OC_User::setUserId($this->user1); $this->assertTrue(OCP\Share::unshare('test', 'test.txt', OCP\Share::SHARE_TYPE_USER, $this->user2)); OC_User::setUserId($this->user2); - $this->assertFalse(OCP\Share::getItemSharedWith('test', 'test.txt')); + $this->assertSame(array(), OCP\Share::getItemSharedWith('test', 'test.txt')); OC_User::setUserId($this->user3); - $this->assertFalse(OCP\Share::getItemSharedWith('test', 'test.txt')); + $this->assertSame(array(), OCP\Share::getItemSharedWith('test', 'test.txt')); // Attempt target conflict OC_User::setUserId($this->user1); @@ -325,7 +325,7 @@ class Test_Share extends PHPUnit_Framework_TestCase { ); OC_User::setUserId($this->user2); - $this->assertFalse( + $this->assertSame(array(), OCP\Share::getItemSharedWith('test', 'test.txt', Test_Share_Backend::FORMAT_SOURCE), 'Failed asserting that user 2 no longer has access to test.txt after expiration.' ); @@ -526,13 +526,13 @@ class Test_Share extends PHPUnit_Framework_TestCase { ); OC_User::setUserId($this->user2); - $this->assertFalse( + $this->assertSame(array(), OCP\Share::getItemSharedWith('test', 'test.txt', Test_Share_Backend::FORMAT_SOURCE), 'Failed asserting that user 2 no longer has access to test.txt after expiration.' ); OC_User::setUserId($this->user3); - $this->assertFalse( + $this->assertSame(array(), OCP\Share::getItemSharedWith('test', 'test.txt', Test_Share_Backend::FORMAT_SOURCE), 'Failed asserting that user 3 no longer has access to test.txt after expiration.' ); -- cgit v1.2.3 From 83b4bcfdbf832f1ebc78c9cf6f6aba5490b65cb3 Mon Sep 17 00:00:00 2001 From: Thomas Müller Date: Wed, 26 Mar 2014 11:17:23 +0100 Subject: idn_to_ascii is only used if available --- lib/private/mail.php | 3 +++ tests/lib/mail.php | 9 +++++++++ 2 files changed, 12 insertions(+) (limited to 'tests') diff --git a/lib/private/mail.php b/lib/private/mail.php index 79f51609631..f9083cc4e64 100644 --- a/lib/private/mail.php +++ b/lib/private/mail.php @@ -137,6 +137,9 @@ class OC_Mail { * @return string */ public static function buildAsciiEmail($emailAddress) { + if (!function_exists('idn_to_ascii')) { + return $emailAddress; + } list($name, $domain) = explode('@', $emailAddress, 2); $domain = idn_to_ascii($domain); diff --git a/tests/lib/mail.php b/tests/lib/mail.php index a88a9d797ae..3cc9868e25e 100644 --- a/tests/lib/mail.php +++ b/tests/lib/mail.php @@ -8,6 +8,15 @@ class Test_Mail extends PHPUnit_Framework_TestCase { + protected function setUp() + { + if (!function_exists('idn_to_ascii')) { + $this->markTestSkipped( + 'The intl extension is not available.' + ); + } + } + /** * @dataProvider buildAsciiEmailProvider * @param $expected -- cgit v1.2.3 From 76c63a576089edcd553244f02d8c3f6c28038fd2 Mon Sep 17 00:00:00 2001 From: Robin Appelman Date: Mon, 31 Mar 2014 17:00:32 +0200 Subject: Fix uploading files containing a # in the path for webdav --- apps/files_external/lib/webdav.php | 2 +- tests/lib/files/storage/storage.php | 21 ++++++++++++++++++++- 2 files changed, 21 insertions(+), 2 deletions(-) (limited to 'tests') diff --git a/apps/files_external/lib/webdav.php b/apps/files_external/lib/webdav.php index 279ae716935..f5010f92208 100644 --- a/apps/files_external/lib/webdav.php +++ b/apps/files_external/lib/webdav.php @@ -267,7 +267,7 @@ class DAV extends \OC\Files\Storage\Common { $curl = curl_init(); curl_setopt($curl, CURLOPT_USERPWD, $this->user . ':' . $this->password); - curl_setopt($curl, CURLOPT_URL, $this->createBaseUri() . str_replace(' ', '%20', $target)); + curl_setopt($curl, CURLOPT_URL, $this->createBaseUri() . $this->encodePath($target)); curl_setopt($curl, CURLOPT_BINARYTRANSFER, true); curl_setopt($curl, CURLOPT_INFILE, $source); // file pointer curl_setopt($curl, CURLOPT_INFILESIZE, filesize($path)); diff --git a/tests/lib/files/storage/storage.php b/tests/lib/files/storage/storage.php index f3bfba3feb8..e4d9e93ca97 100644 --- a/tests/lib/files/storage/storage.php +++ b/tests/lib/files/storage/storage.php @@ -299,7 +299,7 @@ abstract class Storage extends \PHPUnit_Framework_TestCase { $this->assertFalse($this->instance->file_exists('folder')); } - public function hashProvider(){ + public function hashProvider() { return array( array('Foobar', 'md5'), array('Foobar', 'sha1'), @@ -315,4 +315,23 @@ abstract class Storage extends \PHPUnit_Framework_TestCase { $this->assertEquals(hash($type, $data), $this->instance->hash($type, 'hash.txt')); $this->assertEquals(hash($type, $data, true), $this->instance->hash($type, 'hash.txt', true)); } + + public function testHashInFileName() { + $this->instance->file_put_contents('#test.txt', 'data'); + $this->assertEquals('data', $this->instance->file_get_contents('#test.txt')); + + $this->instance->mkdir('#foo'); + $this->instance->file_put_contents('#foo/test.txt', 'data'); + $this->assertEquals('data', $this->instance->file_get_contents('#foo/test.txt')); + + $dh = $this->instance->opendir('#foo'); + $content = array(); + while ($file = readdir($dh)) { + if ($file != '.' and $file != '..') { + $content[] = $file; + } + } + + $this->assertEquals(array('test.txt'), $content); + } } -- cgit v1.2.3 From d6ce45fe61c05c0779cfaa3207a538a7a5b9a04c Mon Sep 17 00:00:00 2001 From: Vincent Petry Date: Mon, 31 Mar 2014 18:36:52 +0200 Subject: Correctly read the full stream in file_get_contents When using user-defined stream wrappers, PHP will return a maximum of 8192 bytes even if more was requested. This fix uses stream_get_contents to make sure the full stream is read and not only the first 8 KB. Added unit test with a bigger test file to cover this case. --- lib/private/files/storage/common.php | 7 ++----- tests/data/lorem-big.txt | 29 +++++++++++++++++++++++++++++ tests/lib/files/storage/storage.php | 15 +++++++++++++-- 3 files changed, 44 insertions(+), 7 deletions(-) create mode 100644 tests/data/lorem-big.txt (limited to 'tests') diff --git a/lib/private/files/storage/common.php b/lib/private/files/storage/common.php index 2b697141515..480cf6b5c77 100644 --- a/lib/private/files/storage/common.php +++ b/lib/private/files/storage/common.php @@ -118,11 +118,8 @@ abstract class Common implements \OC\Files\Storage\Storage { if (!$handle) { return false; } - $size = $this->filesize($path); - if ($size == 0) { - return ''; - } - return fread($handle, $size); + $data = stream_get_contents($handle); + return $data; } public function file_put_contents($path, $data) { diff --git a/tests/data/lorem-big.txt b/tests/data/lorem-big.txt new file mode 100644 index 00000000000..3712b9d30f0 --- /dev/null +++ b/tests/data/lorem-big.txt @@ -0,0 +1,29 @@ +Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse id hendrerit felis. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Sed dictum dolor nec lobortis sagittis. Aliquam blandit lobortis ullamcorper. Donec malesuada ante ante, vel cursus purus suscipit ut. Sed a eros vitae lorem tristique hendrerit a a odio. Cras interdum mi lectus, sed molestie mauris tempus sit amet. Praesent auctor neque venenatis diam tincidunt sodales. Maecenas tincidunt ligula et ipsum dignissim, et molestie dui hendrerit. Nunc lobortis mauris vel tempor tristique. Sed consectetur bibendum nunc. Pellentesque augue velit, interdum ac posuere eu, eleifend et massa. Vestibulum ac mi eu mi viverra iaculis. Sed consequat leo adipiscing dui varius, sagittis vestibulum massa vehicula. + +Praesent imperdiet erat vitae dui placerat, sit amet vulputate tortor viverra. In laoreet elit lorem, at luctus est tempor ac. Nam elementum scelerisque nisl vitae accumsan. Curabitur cursus rutrum est, ut adipiscing ante elementum ut. Ut lectus sem, luctus ut massa non, dignissim vestibulum ipsum. Suspendisse non convallis enim, aliquam adipiscing velit. Donec pharetra non turpis hendrerit porttitor. Aliquam erat volutpat. + +Cras eget arcu eu dolor faucibus accumsan non eget orci. Integer quis quam tincidunt, faucibus neque in, imperdiet lacus. Aenean dui turpis, lacinia quis ligula non, semper adipiscing tellus. Curabitur vitae dui quis nisl malesuada commodo. Nunc eleifend metus enim, eu aliquet dui semper sit amet. Sed a odio sapien. Suspendisse vitae ante id sapien semper accumsan. Sed vestibulum erat quis laoreet pellentesque. Nullam placerat ligula eu odio faucibus, eget dictum orci tristique. Quisque sit amet pulvinar velit, lacinia dictum sem. + +Phasellus id sagittis lacus. Vivamus facilisis convallis metus, sit amet ultricies purus gravida quis. Vivamus eget egestas arcu, a euismod risus. Fusce metus arcu, molestie ut lacinia at, commodo eu nibh. In leo tortor, feugiat aliquet semper in, malesuada ac nulla. Fusce tempor ultricies blandit. Pellentesque et lorem quam. Suspendisse eros eros, mattis ut porttitor vitae, fermentum eget augue. Aliquam vitae justo sed est dictum lobortis. Cras lacinia commodo ligula sed ornare. Donec ut eros semper, sodales tellus quis, cursus quam. Quisque elementum ullamcorper pellentesque. Integer in rutrum ante, vel condimentum metus. Aliquam erat volutpat. + +Quisque convallis tempus eros, sit amet mattis ipsum eleifend in. Mauris volutpat, urna ut commodo tempus, est quam scelerisque erat, eget consequat nulla arcu id eros. Nam elementum nibh quis tincidunt adipiscing. Fusce tristique pretium mollis. Nulla quis ornare felis, vel lacinia diam. In et dui et mauris vestibulum commodo. In hac habitasse platea dictumst. Vestibulum viverra pellentesque tortor, tempor vehicula orci. Praesent rutrum turpis ipsum, ac commodo nisi vehicula ac. + +Nulla gravida ultrices mauris. Ut congue purus nec dolor euismod, vitae auctor elit condimentum. Nullam elementum velit lectus, fringilla pharetra sem hendrerit sit amet. Cras quis lobortis nisi, id interdum massa. Proin eget porttitor sapien. Vivamus quam odio, consectetur at rhoncus vel, posuere in nisi. Donec hendrerit urna ac massa tristique, pellentesque consequat orci dapibus. Mauris mi erat, aliquet id adipiscing ultricies, ultrices nec lacus. Proin imperdiet elit magna, ut suscipit metus faucibus eget. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas at leo lorem. Donec mi nibh, blandit ut mi quis, dictum adipiscing ante. Curabitur sodales blandit odio id viverra. Fusce sagittis rutrum nibh. Mauris risus lacus, placerat at dictum in, varius volutpat quam. + +Ut accumsan tincidunt dui, non semper lorem sodales nec. Curabitur pellentesque velit nec erat ultrices, in convallis diam suscipit. Curabitur pellentesque convallis mi. Phasellus iaculis orci quis nisi semper auctor. Vestibulum eleifend tortor quis odio feugiat, pulvinar congue turpis blandit. Sed viverra diam risus, vel mattis orci dignissim ut. Cras pellentesque dapibus dolor. Morbi tempor eleifend magna. Ut sodales ut sapien sed elementum. In hac habitasse platea dictumst. + +Nullam eget sagittis tellus. Donec a tellus id ligula viverra pellentesque. Pellentesque nulla turpis, pretium vel sem vel, placerat ultricies diam. Donec felis nibh, rhoncus id ornare at, lobortis vel massa. Nullam eu luctus ipsum. Mauris consequat dictum aliquam. Suspendisse ullamcorper aliquam mauris, viverra tincidunt augue suscipit at. Sed luctus scelerisque justo ut semper. Phasellus massa mauris, molestie at nulla eget, dictum ultricies nisi. Aliquam rhoncus nisl sed urna egestas, vel luctus lectus euismod. Mauris sagittis dapibus leo. Donec vitae dignissim risus, ac ultricies augue. Ut vulputate tortor sed dui consectetur placerat. Nullam viverra non diam vel dignissim. + +Suspendisse potenti. Integer facilisis neque vitae euismod adipiscing. Aenean dictum leo commodo dui sodales, sit amet volutpat mauris gravida. Proin tempus convallis eros at consectetur. Proin nisl purus, dictum vel euismod ut, imperdiet quis est. Etiam sollicitudin lobortis neque eget pulvinar. Etiam venenatis vel sem ut posuere. Aliquam consectetur rhoncus facilisis. Morbi a viverra orci. + +Praesent ut vehicula orci, vel convallis risus. Suspendisse consectetur varius interdum. Interdum et malesuada fames ac ante ipsum primis in faucibus. Proin vel sodales enim. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Curabitur suscipit tristique justo vel dapibus. Sed tincidunt mattis massa a auctor. Donec in tincidunt elit. Curabitur interdum neque at ante fringilla tempus. In hac habitasse platea dictumst. Vivamus luctus ligula ut nisl fermentum egestas. Praesent pulvinar accumsan neque. Sed nec leo sit amet arcu vehicula vehicula non ac diam. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; + +Morbi vel arcu quis neque dictum ullamcorper. Pellentesque condimentum consequat lacinia. Vestibulum eleifend placerat erat, eu hendrerit dui pulvinar eget. Vestibulum accumsan, lectus id vehicula fringilla, erat eros dictum massa, ut tristique libero mi eu ante. In at ante nunc. Praesent sodales ullamcorper porta. Curabitur egestas odio elit. Praesent et libero malesuada, venenatis lorem vitae, eleifend nisl. Donec dapibus euismod turpis, nec porttitor turpis dapibus ac. Fusce iaculis lacus eget dictum aliquam. Sed dictum eu enim ac posuere. Ut accumsan, ipsum et laoreet consectetur, ipsum quam dapibus diam, ac molestie ligula dui id massa. Nulla aliquam mauris congue nibh vestibulum imperdiet. + +Aenean ultricies, orci vel consectetur suscipit, ante nisi eleifend est, vitae suscipit risus erat dictum dui. Ut nisi diam, tristique sed nisl nec, aliquam gravida orci. Vestibulum in molestie sem. Ut eu molestie mi. Suspendisse potenti. Nunc sagittis lorem ut est vehicula, vitae imperdiet leo rutrum. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Donec pharetra urna pretium, faucibus orci cursus, sodales purus. Duis iaculis dignissim augue, non aliquet ligula elementum quis. Sed tempus a nisi et faucibus. Donec mattis ligula ac sem aliquam, sed sodales est ullamcorper. Cras vel orci est. Integer eget ultricies nisi. + +Quisque rhoncus, nisl vel auctor consectetur, sapien augue iaculis urna, quis suscipit arcu dolor ac est. Fusce sit amet quam lacinia, malesuada lorem vitae, dapibus justo. Mauris eget massa nec dolor volutpat tempor ut eu ante. Donec risus mi, aliquam at euismod vulputate, ullamcorper non leo. Etiam ac elit velit. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Vivamus sollicitudin enim sed felis pharetra, a convallis mi venenatis. Donec convallis non velit venenatis suscipit. Sed massa risus, dictum quis aliquam ut, placerat quis arcu. Donec at nisi neque. Nullam porta et mi vel ultricies. Donec vel aliquam sem. Mauris varius, ipsum interdum mattis rhoncus, nunc nisl vehicula tortor, quis condimentum nibh nisl vel ante. Sed vel pretium dui. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce pulvinar molestie neque, quis luctus ante. + +Interdum et malesuada fames ac ante ipsum primis in faucibus. Donec ac ipsum egestas, luctus urna aliquet, fringilla tortor. Cras eleifend sed tellus tempor congue. Integer venenatis magna dignissim pharetra cursus. Nulla volutpat, sem sit amet malesuada laoreet, odio libero consectetur orci, sit amet pellentesque neque ligula quis libero. Morbi nec interdum metus, in imperdiet justo. Fusce euismod egestas nulla et elementum. Etiam aliquam lectus quis eros semper, sed dapibus velit ultrices. Lorem ipsum dolor sit amet, consectetur adipiscing elit. + +Proin sed elit vel massa placerat mattis et vel mauris. Aliquam accumsan ante ligula, at accumsan enim pellentesque sit amet. Sed eget quam vel nunc molestie iaculis vitae nec massa. Vivamus sed accumsan libero. Duis pretium quam at blandit sollicitudin. Nullam sodales sit amet elit ac adipiscing. Ut ullamcorper dignissim sapien. Nulla facilisi. Fusce sed consequat lectus, et tempus ipsum. Aliquam vestibulum lectus vitae quam mollis, et adipiscing nisl lobortis diff --git a/tests/lib/files/storage/storage.php b/tests/lib/files/storage/storage.php index f3bfba3feb8..6ec35dfbc92 100644 --- a/tests/lib/files/storage/storage.php +++ b/tests/lib/files/storage/storage.php @@ -113,11 +113,22 @@ abstract class Storage extends \PHPUnit_Framework_TestCase { ); } + function loremFileProvider() { + $root = \OC::$SERVERROOT . '/tests/data/'; + return array( + // small file + array($root . 'lorem.txt'), + // bigger file (> 8 KB which is the standard PHP block size) + array($root . 'lorem-big.txt') + ); + } + /** * test the various uses of file_get_contents and file_put_contents + * + * @dataProvider loremFileProvider */ - public function testGetPutContents() { - $sourceFile = \OC::$SERVERROOT . '/tests/data/lorem.txt'; + public function testGetPutContents($sourceFile) { $sourceText = file_get_contents($sourceFile); //fill a file with string data -- cgit v1.2.3 From b00592ade50f48b73002682494341c429a6a12eb Mon Sep 17 00:00:00 2001 From: tomneedham Date: Thu, 3 Apr 2014 14:47:55 +0000 Subject: Fix test case for api response code --- tests/lib/api.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'tests') diff --git a/tests/lib/api.php b/tests/lib/api.php index 233beebd68a..0f7d08543ea 100644 --- a/tests/lib/api.php +++ b/tests/lib/api.php @@ -37,7 +37,7 @@ class Test_API extends PHPUnit_Framework_TestCase { function dataProviderTestOneResult() { return array( array(100, true), - array(101, true), + array(101, false), array(997, false), ); } -- cgit v1.2.3 From f029312e5b20a540aa94f2ead4581a8b653b1c5c Mon Sep 17 00:00:00 2001 From: Thomas Müller Date: Fri, 4 Apr 2014 11:37:47 +0200 Subject: fixing typos/spellings --- lib/private/preview.php | 15 +++++++++++---- tests/lib/preview.php | 32 ++++++++++++++++---------------- 2 files changed, 27 insertions(+), 20 deletions(-) (limited to 'tests') diff --git a/lib/private/preview.php b/lib/private/preview.php index 71c16687fb9..0fecb25341b 100755 --- a/lib/private/preview.php +++ b/lib/private/preview.php @@ -13,6 +13,8 @@ */ namespace OC; +use OC\Preview\Provider; + require_once 'preview/image.php'; require_once 'preview/movies.php'; require_once 'preview/mp3.php'; @@ -46,8 +48,9 @@ class Preview { // index is path, value is fileinfo static public $deleteFileMapper = array(); - //preview images object /** + * preview images object + * * @var \OC_Image */ private $preview; @@ -198,7 +201,7 @@ class Preview { } /** - * @brief set mimetype explicitely + * @brief set mimetype explicitly * @param string $mimetype */ public function setMimetype($mimetype) { @@ -361,6 +364,7 @@ class Preview { return false; } + /** * @brief get possible bigger thumbnails of the given image * @param int $fileId fileId of the original image @@ -396,6 +400,7 @@ class Preview { return $possibleThumbnails; } + private function getDimensionsFromFilename($name) { $size = explode('-', $name); $x = (int) $size[0]; @@ -403,6 +408,7 @@ class Preview { $aspectRatio = (float) ($x / $y); return array('x' => $x,'y' => $y,'aspectRatio' => $aspectRatio); } + private function unscalable($x, $y) { $maxX = $this->getMaxX(); @@ -422,6 +428,7 @@ class Preview { } return false; } + /** * @brief return a preview of a file * @return \OC_Image @@ -464,6 +471,7 @@ class Preview { \OC_Log::write('core', 'Generating preview for "' . $file . '" with "' . get_class($provider) . '"', \OC_Log::DEBUG); + /** @var $provider Provider */ $preview = $provider->getThumbnail($file, $maxX, $maxY, $scalingUp, $this->fileView); if (!($preview instanceof \OC_Image)) { @@ -507,7 +515,6 @@ class Preview { $this->getPreview(); } $this->preview->show('image/png'); - return; } /** @@ -516,7 +523,6 @@ class Preview { */ public function show() { $this->showPreview(); - return; } /** @@ -653,6 +659,7 @@ class Preview { $class = $provider['class']; $options = $provider['options']; + /** @var $object Provider */ $object = new $class($options); self::$providers[$object->getMimeType()] = $object; diff --git a/tests/lib/preview.php b/tests/lib/preview.php index 353b66fd6d6..fb1c959b45a 100644 --- a/tests/lib/preview.php +++ b/tests/lib/preview.php @@ -17,9 +17,9 @@ class Preview extends \PHPUnit_Framework_TestCase { $rootView->mkdir('/'.$user); $rootView->mkdir('/'.$user.'/files'); - $samplefile = '/'.$user.'/files/test.txt'; + $sampleFile = '/'.$user.'/files/test.txt'; - $rootView->file_put_contents($samplefile, 'dummy file data'); + $rootView->file_put_contents($sampleFile, 'dummy file data'); $x = 50; $y = 50; @@ -27,16 +27,16 @@ class Preview extends \PHPUnit_Framework_TestCase { $preview = new \OC\Preview($user, 'files/', 'test.txt', $x, $y); $preview->getPreview(); - $fileinfo = $rootView->getFileInfo($samplefile); - $fileid = $fileinfo['fileid']; + $fileInfo = $rootView->getFileInfo($sampleFile); + $fileId = $fileInfo['fileid']; - $thumbcachefile = '/' . $user . '/' . \OC\Preview::THUMBNAILS_FOLDER . '/' . $fileid . '/' . $x . '-' . $y . '.png'; + $thumbCacheFile = '/' . $user . '/' . \OC\Preview::THUMBNAILS_FOLDER . '/' . $fileId . '/' . $x . '-' . $y . '.png'; - $this->assertEquals($rootView->file_exists($thumbcachefile), true); + $this->assertEquals($rootView->file_exists($thumbCacheFile), true); $preview->deletePreview(); - $this->assertEquals($rootView->file_exists($thumbcachefile), false); + $this->assertEquals($rootView->file_exists($thumbCacheFile), false); } public function testAreAllPreviewsDeleted() { @@ -46,9 +46,9 @@ class Preview extends \PHPUnit_Framework_TestCase { $rootView->mkdir('/'.$user); $rootView->mkdir('/'.$user.'/files'); - $samplefile = '/'.$user.'/files/test.txt'; + $sampleFile = '/'.$user.'/files/test.txt'; - $rootView->file_put_contents($samplefile, 'dummy file data'); + $rootView->file_put_contents($sampleFile, 'dummy file data'); $x = 50; $y = 50; @@ -56,16 +56,16 @@ class Preview extends \PHPUnit_Framework_TestCase { $preview = new \OC\Preview($user, 'files/', 'test.txt', $x, $y); $preview->getPreview(); - $fileinfo = $rootView->getFileInfo($samplefile); - $fileid = $fileinfo['fileid']; + $fileInfo = $rootView->getFileInfo($sampleFile); + $fileId = $fileInfo['fileid']; - $thumbcachefolder = '/' . $user . '/' . \OC\Preview::THUMBNAILS_FOLDER . '/' . $fileid . '/'; + $thumbCacheFolder = '/' . $user . '/' . \OC\Preview::THUMBNAILS_FOLDER . '/' . $fileId . '/'; - $this->assertEquals($rootView->is_dir($thumbcachefolder), true); + $this->assertEquals($rootView->is_dir($thumbCacheFolder), true); $preview->deleteAllPreviews(); - $this->assertEquals($rootView->is_dir($thumbcachefolder), false); + $this->assertEquals($rootView->is_dir($thumbCacheFolder), false); } public function testIsMaxSizeWorking() { @@ -81,9 +81,9 @@ class Preview extends \PHPUnit_Framework_TestCase { $rootView->mkdir('/'.$user); $rootView->mkdir('/'.$user.'/files'); - $samplefile = '/'.$user.'/files/test.txt'; + $sampleFile = '/'.$user.'/files/test.txt'; - $rootView->file_put_contents($samplefile, 'dummy file data'); + $rootView->file_put_contents($sampleFile, 'dummy file data'); $preview = new \OC\Preview($user, 'files/', 'test.txt', 1000, 1000); $image = $preview->getPreview(); -- cgit v1.2.3 From ccf1287fbf8baa083c7c043b0ed0df054ecaf9c1 Mon Sep 17 00:00:00 2001 From: Thomas Müller Date: Fri, 4 Apr 2014 16:21:50 +0200 Subject: adding unit test for cache mechanism --- lib/private/preview.php | 98 +++++++++++++++++----------------- tests/lib/preview.php | 136 ++++++++++++++++++++++++++++++++++-------------- 2 files changed, 145 insertions(+), 89 deletions(-) (limited to 'tests') diff --git a/lib/private/preview.php b/lib/private/preview.php index 0fecb25341b..995cfc3f6dc 100755 --- a/lib/private/preview.php +++ b/lib/private/preview.php @@ -41,8 +41,8 @@ class Preview { private $file; private $maxX; private $maxY; - private $scalingup; - private $mimetype; + private $scalingUp; + private $mimeType; //filemapper used for deleting previews // index is path, value is fileinfo @@ -137,7 +137,7 @@ class Preview { * @return bool */ public function getScalingUp() { - return $this->scalingup; + return $this->scalingUp; } /** @@ -194,18 +194,18 @@ class Preview { if ($file !== '') { $this->getFileInfo(); if($this->info !== null && $this->info !== false) { - $this->mimetype = $this->info->getMimetype(); + $this->mimeType = $this->info->getMimetype(); } } return $this; } /** - * @brief set mimetype explicitly - * @param string $mimetype + * @brief set mime type explicitly + * @param string $mimeType */ - public function setMimetype($mimetype) { - $this->mimetype = $mimetype; + public function setMimetype($mimeType) { + $this->mimeType = $mimeType; } /** @@ -257,7 +257,7 @@ class Preview { if ($this->getMaxScaleFactor() === 1) { $scalingUp = false; } - $this->scalingup = $scalingUp; + $this->scalingUp = $scalingUp; return $this; } @@ -320,7 +320,7 @@ class Preview { * @param int $fileId fileId of the original image * @return string|false path to thumbnail if it exists or false */ - private function isCached($fileId) { + public function isCached($fileId) { if (is_null($fileId)) { return false; } @@ -406,7 +406,7 @@ class Preview { $x = (int) $size[0]; $y = (int) $size[1]; $aspectRatio = (float) ($x / $y); - return array('x' => $x,'y' => $y,'aspectRatio' => $aspectRatio); + return array($x, $y, $aspectRatio); } private function unscalable($x, $y) { @@ -464,8 +464,8 @@ class Preview { if (is_null($this->preview)) { $preview = null; - foreach (self::$providers as $supportedMimetype => $provider) { - if (!preg_match($supportedMimetype, $this->mimetype)) { + foreach (self::$providers as $supportedMimeType => $provider) { + if (!preg_match($supportedMimeType, $this->mimeType)) { continue; } @@ -534,7 +534,7 @@ class Preview { $x = $this->getMaxX(); $y = $this->getMaxY(); $scalingUp = $this->getScalingUp(); - $maxscalefactor = $this->getMaxScaleFactor(); + $maxScaleFactor = $this->getMaxScaleFactor(); if (!($image instanceof \OC_Image)) { \OC_Log::write('core', '$this->preview is not an instance of OC_Image', \OC_Log::DEBUG); @@ -543,16 +543,16 @@ class Preview { $image->fixOrientation(); - $realx = (int)$image->width(); - $realy = (int)$image->height(); + $realX = (int)$image->width(); + $realY = (int)$image->height(); - if ($x === $realx && $y === $realy) { + if ($x === $realX && $y === $realY) { $this->preview = $image; return; } - $factorX = $x / $realx; - $factorY = $y / $realy; + $factorX = $x / $realX; + $factorY = $y / $realY; if ($factorX >= $factorY) { $factor = $factorX; @@ -566,25 +566,25 @@ class Preview { } } - if (!is_null($maxscalefactor)) { - if ($factor > $maxscalefactor) { - \OC_Log::write('core', 'scalefactor reduced from ' . $factor . ' to ' . $maxscalefactor, \OC_Log::DEBUG); - $factor = $maxscalefactor; + if (!is_null($maxScaleFactor)) { + if ($factor > $maxScaleFactor) { + \OC_Log::write('core', 'scale factor reduced from ' . $factor . ' to ' . $maxScaleFactor, \OC_Log::DEBUG); + $factor = $maxScaleFactor; } } - $newXsize = (int)($realx * $factor); - $newYsize = (int)($realy * $factor); + $newXSize = (int)($realX * $factor); + $newYSize = (int)($realY * $factor); - $image->preciseResize($newXsize, $newYsize); + $image->preciseResize($newXSize, $newYSize); - if ($newXsize === $x && $newYsize === $y) { + if ($newXSize === $x && $newYSize === $y) { $this->preview = $image; return; } - if ($newXsize >= $x && $newYsize >= $y) { - $cropX = floor(abs($x - $newXsize) * 0.5); + if ($newXSize >= $x && $newYSize >= $y) { + $cropX = floor(abs($x - $newXSize) * 0.5); //don't crop previews on the Y axis, this sucks if it's a document. //$cropY = floor(abs($y - $newYsize) * 0.5); $cropY = 0; @@ -595,36 +595,36 @@ class Preview { return; } - if ($newXsize < $x || $newYsize < $y) { - if ($newXsize > $x) { - $cropX = floor(($newXsize - $x) * 0.5); - $image->crop($cropX, 0, $x, $newYsize); + if ($newXSize < $x || $newYSize < $y) { + if ($newXSize > $x) { + $cropX = floor(($newXSize - $x) * 0.5); + $image->crop($cropX, 0, $x, $newYSize); } - if ($newYsize > $y) { - $cropY = floor(($newYsize - $y) * 0.5); - $image->crop(0, $cropY, $newXsize, $y); + if ($newYSize > $y) { + $cropY = floor(($newYSize - $y) * 0.5); + $image->crop(0, $cropY, $newXSize, $y); } - $newXsize = (int)$image->width(); - $newYsize = (int)$image->height(); + $newXSize = (int)$image->width(); + $newYSize = (int)$image->height(); //create transparent background layer - $backgroundlayer = imagecreatetruecolor($x, $y); - $white = imagecolorallocate($backgroundlayer, 255, 255, 255); - imagefill($backgroundlayer, 0, 0, $white); + $backgroundLayer = imagecreatetruecolor($x, $y); + $white = imagecolorallocate($backgroundLayer, 255, 255, 255); + imagefill($backgroundLayer, 0, 0, $white); $image = $image->resource(); - $mergeX = floor(abs($x - $newXsize) * 0.5); - $mergeY = floor(abs($y - $newYsize) * 0.5); + $mergeX = floor(abs($x - $newXSize) * 0.5); + $mergeY = floor(abs($y - $newYSize) * 0.5); - imagecopy($backgroundlayer, $image, $mergeX, $mergeY, 0, 0, $newXsize, $newYsize); + imagecopy($backgroundLayer, $image, $mergeX, $mergeY, 0, 0, $newXSize, $newYSize); //$black = imagecolorallocate(0,0,0); //imagecolortransparent($transparentlayer, $black); - $image = new \OC_Image($backgroundlayer); + $image = new \OC_Image($backgroundLayer); $this->preview = $image; return; @@ -706,9 +706,9 @@ class Preview { } /** - * @param string $mimetype + * @param string $mimeType */ - public static function isMimeSupported($mimetype) { + public static function isMimeSupported($mimeType) { if (!\OC_Config::getValue('enable_previews', true)) { return false; } @@ -720,8 +720,8 @@ class Preview { //remove last element because it has the mimetype * $providers = array_slice(self::$providers, 0, -1); - foreach ($providers as $supportedMimetype => $provider) { - if (preg_match($supportedMimetype, $mimetype)) { + foreach ($providers as $supportedMimeType => $provider) { + if (preg_match($supportedMimeType, $mimeType)) { return true; } } diff --git a/tests/lib/preview.php b/tests/lib/preview.php index fb1c959b45a..4ef61fb8257 100644 --- a/tests/lib/preview.php +++ b/tests/lib/preview.php @@ -10,66 +10,73 @@ namespace Test; class Preview extends \PHPUnit_Framework_TestCase { - public function testIsPreviewDeleted() { - $user = $this->initFS(); + /** + * @var string + */ + private $user; - $rootView = new \OC\Files\View(''); - $rootView->mkdir('/'.$user); - $rootView->mkdir('/'.$user.'/files'); + /** + * @var \OC\Files\View + */ + private $rootView; - $sampleFile = '/'.$user.'/files/test.txt'; + public function setUp() { + $this->user = $this->initFS(); - $rootView->file_put_contents($sampleFile, 'dummy file data'); + $this->rootView = new \OC\Files\View(''); + $this->rootView->mkdir('/'.$this->user); + $this->rootView->mkdir('/'.$this->user.'/files'); + } + + public function testIsPreviewDeleted() { + + $sampleFile = '/'.$this->user.'/files/test.txt'; + + $this->rootView->file_put_contents($sampleFile, 'dummy file data'); $x = 50; $y = 50; - $preview = new \OC\Preview($user, 'files/', 'test.txt', $x, $y); + $preview = new \OC\Preview($this->user, 'files/', 'test.txt', $x, $y); $preview->getPreview(); - $fileInfo = $rootView->getFileInfo($sampleFile); + $fileInfo = $this->rootView->getFileInfo($sampleFile); $fileId = $fileInfo['fileid']; - $thumbCacheFile = '/' . $user . '/' . \OC\Preview::THUMBNAILS_FOLDER . '/' . $fileId . '/' . $x . '-' . $y . '.png'; + $thumbCacheFile = '/' . $this->user . '/' . \OC\Preview::THUMBNAILS_FOLDER . '/' . $fileId . '/' . $x . '-' . $y . '.png'; - $this->assertEquals($rootView->file_exists($thumbCacheFile), true); + $this->assertEquals($this->rootView->file_exists($thumbCacheFile), true); $preview->deletePreview(); - $this->assertEquals($rootView->file_exists($thumbCacheFile), false); + $this->assertEquals($this->rootView->file_exists($thumbCacheFile), false); } public function testAreAllPreviewsDeleted() { - $user = $this->initFS(); - - $rootView = new \OC\Files\View(''); - $rootView->mkdir('/'.$user); - $rootView->mkdir('/'.$user.'/files'); - $sampleFile = '/'.$user.'/files/test.txt'; + $sampleFile = '/'.$this->user.'/files/test.txt'; - $rootView->file_put_contents($sampleFile, 'dummy file data'); + $this->rootView->file_put_contents($sampleFile, 'dummy file data'); $x = 50; $y = 50; - $preview = new \OC\Preview($user, 'files/', 'test.txt', $x, $y); + $preview = new \OC\Preview($this->user, 'files/', 'test.txt', $x, $y); $preview->getPreview(); - $fileInfo = $rootView->getFileInfo($sampleFile); + $fileInfo = $this->rootView->getFileInfo($sampleFile); $fileId = $fileInfo['fileid']; - $thumbCacheFolder = '/' . $user . '/' . \OC\Preview::THUMBNAILS_FOLDER . '/' . $fileId . '/'; + $thumbCacheFolder = '/' . $this->user . '/' . \OC\Preview::THUMBNAILS_FOLDER . '/' . $fileId . '/'; - $this->assertEquals($rootView->is_dir($thumbCacheFolder), true); + $this->assertEquals($this->rootView->is_dir($thumbCacheFolder), true); $preview->deleteAllPreviews(); - $this->assertEquals($rootView->is_dir($thumbCacheFolder), false); + $this->assertEquals($this->rootView->is_dir($thumbCacheFolder), false); } public function testIsMaxSizeWorking() { - $user = $this->initFS(); $maxX = 250; $maxY = 250; @@ -77,15 +84,11 @@ class Preview extends \PHPUnit_Framework_TestCase { \OC_Config::setValue('preview_max_x', $maxX); \OC_Config::setValue('preview_max_y', $maxY); - $rootView = new \OC\Files\View(''); - $rootView->mkdir('/'.$user); - $rootView->mkdir('/'.$user.'/files'); + $sampleFile = '/'.$this->user.'/files/test.txt'; - $sampleFile = '/'.$user.'/files/test.txt'; + $this->rootView->file_put_contents($sampleFile, 'dummy file data'); - $rootView->file_put_contents($sampleFile, 'dummy file data'); - - $preview = new \OC\Preview($user, 'files/', 'test.txt', 1000, 1000); + $preview = new \OC\Preview($this->user, 'files/', 'test.txt', 1000, 1000); $image = $preview->getPreview(); $this->assertEquals($image->width(), $maxX); @@ -108,18 +111,13 @@ class Preview extends \PHPUnit_Framework_TestCase { * @dataProvider txtBlacklist */ public function testIsTransparent($extension, $data, $expectedResult) { - $user = $this->initFS(); - - $rootView = new \OC\Files\View(''); - $rootView->mkdir('/'.$user); - $rootView->mkdir('/'.$user.'/files'); $x = 32; $y = 32; - $sample = '/'.$user.'/files/test.'.$extension; - $rootView->file_put_contents($sample, $data); - $preview = new \OC\Preview($user, 'files/', 'test.'.$extension, $x, $y); + $sample = '/'.$this->user.'/files/test.'.$extension; + $this->rootView->file_put_contents($sample, $data); + $preview = new \OC\Preview($this->user, 'files/', 'test.'.$extension, $x, $y); $image = $preview->getPreview(); $resource = $image->resource(); @@ -133,6 +131,64 @@ class Preview extends \PHPUnit_Framework_TestCase { ); } + public function testCreationFromCached() { + + $sampleFile = '/'.$this->user.'/files/test.txt'; + + $this->rootView->file_put_contents($sampleFile, 'dummy file data'); + + // create base preview + $x = 150; + $y = 150; + + $preview = new \OC\Preview($this->user, 'files/', 'test.txt', $x, $y); + $preview->getPreview(); + + $fileInfo = $this->rootView->getFileInfo($sampleFile); + $fileId = $fileInfo['fileid']; + + $thumbCacheFile = '/' . $this->user . '/' . \OC\Preview::THUMBNAILS_FOLDER . '/' . $fileId . '/' . $x . '-' . $y . '.png'; + + $this->assertEquals($this->rootView->file_exists($thumbCacheFile), true); + + + // create smaller previews + $preview = new \OC\Preview($this->user, 'files/', 'test.txt', 50, 50); + $isCached = $preview->isCached($fileId); + + $this->assertEquals($this->user . '/' . \OC\Preview::THUMBNAILS_FOLDER . '/' . $fileId . '/150-150.png', $isCached); + } + + /* + public function testScalingUp() { + + $sampleFile = '/'.$this->user.'/files/test.txt'; + + $this->rootView->file_put_contents($sampleFile, 'dummy file data'); + + // create base preview + $x = 150; + $y = 150; + + $preview = new \OC\Preview($this->user, 'files/', 'test.txt', $x, $y); + $preview->getPreview(); + + $fileInfo = $this->rootView->getFileInfo($sampleFile); + $fileId = $fileInfo['fileid']; + + $thumbCacheFile = '/' . $this->user . '/' . \OC\Preview::THUMBNAILS_FOLDER . '/' . $fileId . '/' . $x . '-' . $y . '.png'; + + $this->assertEquals($this->rootView->file_exists($thumbCacheFile), true); + + + // create bigger previews - with scale up + $preview = new \OC\Preview($this->user, 'files/', 'test.txt', 250, 250); + $isCached = $preview->isCached($fileId); + + $this->assertEquals($this->user . '/' . \OC\Preview::THUMBNAILS_FOLDER . '/' . $fileId . '/150-150.png', $isCached); + } + */ + private function initFS() { // create a new user with his own filesystem view // this gets called by each test in this test class -- cgit v1.2.3 From 1245ff8f318fafd66eed1ba8f9f2b3755aa537ca Mon Sep 17 00:00:00 2001 From: Fabian Henze Date: Mon, 7 Apr 2014 15:31:34 +0200 Subject: Add unit tests for OC_Helper::phpFileSize function --- tests/lib/helper.php | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) (limited to 'tests') diff --git a/tests/lib/helper.php b/tests/lib/helper.php index 0943e6bc1b9..7177570d67f 100644 --- a/tests/lib/helper.php +++ b/tests/lib/helper.php @@ -30,6 +30,28 @@ class Test_Helper extends PHPUnit_Framework_TestCase { ); } + /** + * @dataProvider phpFileSizeProvider + */ + public function testPhpFileSize($expected, $input) + { + $result = OC_Helper::phpFileSize($input); + $this->assertEquals($expected, $result); + } + + public function phpFileSizeProvider() + { + return array( + array('0B', 0), + array('1K', 1024), + array('9.5M', 10000000), + array('1.3G', 1395864371), + array('465.7G', 500000000000), + array('465661.3G', 500000000000000), + array('465661287.3G', 500000000000000000), + ); + } + /** * @dataProvider computerFileSizeProvider */ -- cgit v1.2.3 From 240d1ae6b9aa506de4c21e93258a17b23052ac5e Mon Sep 17 00:00:00 2001 From: Thomas Müller Date: Mon, 7 Apr 2014 20:56:43 +0200 Subject: unit test testSetAppValueIfSetToNull() added --- tests/lib/public/config.php | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 tests/lib/public/config.php (limited to 'tests') diff --git a/tests/lib/public/config.php b/tests/lib/public/config.php new file mode 100644 index 00000000000..68367034e9a --- /dev/null +++ b/tests/lib/public/config.php @@ -0,0 +1,37 @@ +. + */ + +class Test_Config extends PHPUnit_Framework_TestCase +{ + + public function testSetAppValueIfSetToNull() { + + $key = uniqid("key-"); + + $result = \OCP\Config::setAppValue('unit-test', $key, null); + $this->assertTrue($result); + + $result = \OCP\Config::setAppValue('unit-test', $key, '12'); + $this->assertTrue($result); + + } + +} -- cgit v1.2.3 From 9597f4190460c54066586c0eb42ed9a8532ad90a Mon Sep 17 00:00:00 2001 From: Arthur Schiwon Date: Tue, 8 Apr 2014 12:32:30 +0200 Subject: add group tests --- tests/lib/group/group.php | 62 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) (limited to 'tests') diff --git a/tests/lib/group/group.php b/tests/lib/group/group.php index 3982c00e45f..147532f9947 100644 --- a/tests/lib/group/group.php +++ b/tests/lib/group/group.php @@ -299,6 +299,68 @@ class Group extends \PHPUnit_Framework_TestCase { $this->assertEquals('user1', $user1->getUID()); } + public function testCountUsers() { + $backend1 = $this->getMock('OC_Group_Database'); + $userManager = $this->getUserManager(); + $group = new \OC\Group\Group('group1', array($backend1), $userManager); + + $backend1->expects($this->once()) + ->method('countUsersInGroup') + ->with('group1', '2') + ->will($this->returnValue(3)); + + $backend1->expects($this->any()) + ->method('implementsActions') + ->will($this->returnValue(true)); + + $users = $group->count('2'); + + $this->assertSame(3, $users); + } + + public function testCountUsersMultipleBackends() { + $backend1 = $this->getMock('OC_Group_Database'); + $backend2 = $this->getMock('OC_Group_Database'); + $userManager = $this->getUserManager(); + $group = new \OC\Group\Group('group1', array($backend1, $backend2), $userManager); + + $backend1->expects($this->once()) + ->method('countUsersInGroup') + ->with('group1', '2') + ->will($this->returnValue(3)); + $backend1->expects($this->any()) + ->method('implementsActions') + ->will($this->returnValue(true)); + + $backend2->expects($this->once()) + ->method('countUsersInGroup') + ->with('group1', '2') + ->will($this->returnValue(4)); + $backend2->expects($this->any()) + ->method('implementsActions') + ->will($this->returnValue(true)); + + $users = $group->count('2'); + + $this->assertSame(7, $users); + } + + public function testCountUsersNoMethod() { + $backend1 = $this->getMock('OC_Group_Database'); + $userManager = $this->getUserManager(); + $group = new \OC\Group\Group('group1', array($backend1), $userManager); + + $backend1->expects($this->never()) + ->method('countUsersInGroup'); + $backend1->expects($this->any()) + ->method('implementsActions') + ->will($this->returnValue(false)); + + $users = $group->count('2'); + + $this->assertSame(false, $users); + } + public function testDelete() { $backend = $this->getMock('OC_Group_Database'); $userManager = $this->getUserManager(); -- cgit v1.2.3 From a4fc92b05bb5131ae7b9fe0d6be5b7f68f470de0 Mon Sep 17 00:00:00 2001 From: Thomas Müller Date: Tue, 8 Apr 2014 14:15:33 +0200 Subject: class Test_Config is already declared --- tests/lib/public/config.php | 37 ------------------------------------- tests/lib/public/ocpconfig.php | 37 +++++++++++++++++++++++++++++++++++++ 2 files changed, 37 insertions(+), 37 deletions(-) delete mode 100644 tests/lib/public/config.php create mode 100644 tests/lib/public/ocpconfig.php (limited to 'tests') diff --git a/tests/lib/public/config.php b/tests/lib/public/config.php deleted file mode 100644 index 68367034e9a..00000000000 --- a/tests/lib/public/config.php +++ /dev/null @@ -1,37 +0,0 @@ -. - */ - -class Test_Config extends PHPUnit_Framework_TestCase -{ - - public function testSetAppValueIfSetToNull() { - - $key = uniqid("key-"); - - $result = \OCP\Config::setAppValue('unit-test', $key, null); - $this->assertTrue($result); - - $result = \OCP\Config::setAppValue('unit-test', $key, '12'); - $this->assertTrue($result); - - } - -} diff --git a/tests/lib/public/ocpconfig.php b/tests/lib/public/ocpconfig.php new file mode 100644 index 00000000000..43a9ca625ee --- /dev/null +++ b/tests/lib/public/ocpconfig.php @@ -0,0 +1,37 @@ +. + */ + +class Test_OCPConfig extends PHPUnit_Framework_TestCase +{ + + public function testSetAppValueIfSetToNull() { + + $key = uniqid("key-"); + + $result = \OCP\Config::setAppValue('unit-test', $key, null); + $this->assertTrue($result); + + $result = \OCP\Config::setAppValue('unit-test', $key, '12'); + $this->assertTrue($result); + + } + +} -- cgit v1.2.3 From bfb1e0867f82a61a2e19e900d3e62d2bafa0b514 Mon Sep 17 00:00:00 2001 From: Vincent Petry Date: Tue, 8 Apr 2014 17:21:11 +0200 Subject: Enable autowatch for karma This way unit tests can be run in multiple browsers with the command line and tests will re-run automatically when files are changed. --- tests/karma.config.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'tests') diff --git a/tests/karma.config.js b/tests/karma.config.js index 529bd31338f..ed9836ed4c3 100644 --- a/tests/karma.config.js +++ b/tests/karma.config.js @@ -167,7 +167,7 @@ module.exports = function(config) { logLevel: config.LOG_INFO, // enable / disable watching file and executing tests whenever any file changes - autoWatch: false, + autoWatch: true, // Start these browsers, currently available: // - Chrome -- cgit v1.2.3 From 70c88027db5c5d586d689d310572f8f34d10b285 Mon Sep 17 00:00:00 2001 From: Bernhard Posselt Date: Wed, 9 Apr 2014 21:57:32 +0200 Subject: add requirements to routing --- lib/private/appframework/routing/routeconfig.php | 10 ++++++++- tests/lib/appframework/routing/RoutingTest.php | 26 ++++++++++++++++++++---- 2 files changed, 31 insertions(+), 5 deletions(-) (limited to 'tests') diff --git a/lib/private/appframework/routing/routeconfig.php b/lib/private/appframework/routing/routeconfig.php index 35bee75cc4d..a3bbde6af53 100644 --- a/lib/private/appframework/routing/routeconfig.php +++ b/lib/private/appframework/routing/routeconfig.php @@ -84,7 +84,15 @@ class RouteConfig { // register the route $handler = new RouteActionHandler($this->container, $controllerName, $actionName); - $this->router->create($this->appName.'.'.$controller.'.'.$action, $url)->method($verb)->action($handler); + $router = $this->router->create($this->appName.'.'.$controller.'.'.$action, $url) + ->method($verb) + ->action($handler); + + // optionally register requirements for route. This is used to + // tell the route parser how url parameters should be matched + if(array_key_exists('requirements', $simpleRoute)) { + $router->requirements($simpleRoute['requirements']); + } } } diff --git a/tests/lib/appframework/routing/RoutingTest.php b/tests/lib/appframework/routing/RoutingTest.php index 735dd7cef41..261ab0b26af 100644 --- a/tests/lib/appframework/routing/RoutingTest.php +++ b/tests/lib/appframework/routing/RoutingTest.php @@ -36,6 +36,16 @@ class RouteConfigTest extends \PHPUnit_Framework_TestCase $this->assertSimpleRoute($routes, 'folders.open', 'DELETE', '/folders/{folderId}/open', 'FoldersController', 'open'); } + public function testSimpleRouteWithRequirements() + { + $routes = array('routes' => array( + array('name' => 'folders#open', 'url' => '/folders/{folderId}/open', 'verb' => 'delete', 'requirements' => array('something')) + )); + + $this->assertSimpleRoute($routes, 'folders.open', 'DELETE', '/folders/{folderId}/open', 'FoldersController', 'open', array('something')); + } + + /** * @expectedException \UnexpectedValueException */ @@ -85,10 +95,10 @@ class RouteConfigTest extends \PHPUnit_Framework_TestCase * @param string $controllerName * @param string $actionName */ - private function assertSimpleRoute($routes, $name, $verb, $url, $controllerName, $actionName) + private function assertSimpleRoute($routes, $name, $verb, $url, $controllerName, $actionName, array $requirements=array()) { // route mocks - $route = $this->mockRoute($verb, $controllerName, $actionName); + $route = $this->mockRoute($verb, $controllerName, $actionName, $requirements); // router mock $router = $this->getMock("\OC\Route\Router", array('create')); @@ -171,10 +181,10 @@ class RouteConfigTest extends \PHPUnit_Framework_TestCase * @param string $actionName * @return \PHPUnit_Framework_MockObject_MockObject */ - private function mockRoute($verb, $controllerName, $actionName) + private function mockRoute($verb, $controllerName, $actionName, array $requirements=array()) { $container = new DIContainer('app1'); - $route = $this->getMock("\OC\Route\Route", array('method', 'action'), array(), '', false); + $route = $this->getMock("\OC\Route\Route", array('method', 'action', 'requirements'), array(), '', false); $route ->expects($this->exactly(1)) ->method('method') @@ -186,6 +196,14 @@ class RouteConfigTest extends \PHPUnit_Framework_TestCase ->method('action') ->with($this->equalTo(new RouteActionHandler($container, $controllerName, $actionName))) ->will($this->returnValue($route)); + + if(count($requirements) > 0) { + $route + ->expects($this->exactly(1)) + ->method('requirements') + ->with($this->equalTo($requirements)) + ->will($this->returnValue($route)); + } return $route; } -- cgit v1.2.3 From e92fe47d2af67f844584da2d9e802f77815d6aa4 Mon Sep 17 00:00:00 2001 From: Vincent Petry Date: Fri, 11 Apr 2014 15:25:40 +0200 Subject: Remove annoying karma 404 warnings for images Karma now serves images from core to avoid polluting the logs with a lot of 404 warnings. This also makes it easier to read the test errors during development. --- tests/karma.config.js | 8 ++++++++ 1 file changed, 8 insertions(+) (limited to 'tests') diff --git a/tests/karma.config.js b/tests/karma.config.js index ed9836ed4c3..338e3f868e9 100644 --- a/tests/karma.config.js +++ b/tests/karma.config.js @@ -121,6 +121,9 @@ module.exports = function(config) { files.push('apps/' + appsToTest[i] + '/tests/js/*.js'); } + // serve images to avoid warnings + files.push({pattern: 'core/img/**/*', watched: false, included: false, served: true}); + config.set({ // base path, that will be used to resolve files and exclude @@ -137,6 +140,11 @@ module.exports = function(config) { ], + proxies: { + // prevent warnings for images + '/context.html//core/img/': 'http://localhost:9876/base/core/img/' + }, + // test results reporter to use // possible values: 'dots', 'progress', 'junit', 'growl', 'coverage' reporters: ['dots', 'junit', 'coverage'], -- cgit v1.2.3 From 62cce982bbd66c11ddb7867b516bc13f95eaf9a5 Mon Sep 17 00:00:00 2001 From: Bernhard Posselt Date: Sat, 12 Apr 2014 16:17:49 +0200 Subject: default to GET request when no method is set to fix unittests, also set parsed json parameters on the post attribute --- lib/private/appframework/http/request.php | 7 ++++++ .../dependencyinjection/DIContainerTest.php | 2 +- tests/lib/appframework/http/RequestTest.php | 28 ++++++++++++---------- .../middleware/MiddlewareDispatcherTest.php | 2 +- 4 files changed, 25 insertions(+), 14 deletions(-) (limited to 'tests') diff --git a/lib/private/appframework/http/request.php b/lib/private/appframework/http/request.php index 43631697d3a..643fa685adc 100644 --- a/lib/private/appframework/http/request.php +++ b/lib/private/appframework/http/request.php @@ -65,6 +65,10 @@ class Request implements \ArrayAccess, \Countable, IRequest { $this->inputStream = $stream; $this->items['params'] = array(); + if(!array_key_exists('method', $vars)) { + $vars['method'] = 'GET'; + } + foreach($this->allowedKeys as $name) { $this->items[$name] = isset($vars[$name]) ? $vars[$name] @@ -76,6 +80,9 @@ class Request implements \ArrayAccess, \Countable, IRequest { $params = json_decode(file_get_contents($this->inputStream), true); if(count($params) > 0) { $this->items['params'] = $params; + if($vars['method'] === 'POST') { + $this->items['post'] = $params; + } } // Handle application/x-www-form-urlencoded for methods other than GET // or post correctly diff --git a/tests/lib/appframework/dependencyinjection/DIContainerTest.php b/tests/lib/appframework/dependencyinjection/DIContainerTest.php index f3ebff0207f..d1bc900fb28 100644 --- a/tests/lib/appframework/dependencyinjection/DIContainerTest.php +++ b/tests/lib/appframework/dependencyinjection/DIContainerTest.php @@ -70,7 +70,7 @@ class DIContainerTest extends \PHPUnit_Framework_TestCase { public function testMiddlewareDispatcherIncludesSecurityMiddleware(){ - $this->container['Request'] = new Request(); + $this->container['Request'] = new Request(array('method' => 'GET')); $security = $this->container['SecurityMiddleware']; $dispatcher = $this->container['MiddlewareDispatcher']; diff --git a/tests/lib/appframework/http/RequestTest.php b/tests/lib/appframework/http/RequestTest.php index 00473a8c44f..58828d17bb2 100644 --- a/tests/lib/appframework/http/RequestTest.php +++ b/tests/lib/appframework/http/RequestTest.php @@ -18,6 +18,7 @@ class RequestTest extends \PHPUnit_Framework_TestCase { stream_wrapper_unregister('fakeinput'); } stream_wrapper_register('fakeinput', 'RequestStream'); + $this->stream = 'fakeinput://data'; } public function tearDown() { @@ -30,7 +31,7 @@ class RequestTest extends \PHPUnit_Framework_TestCase { 'method' => 'GET', ); - $request = new Request($vars); + $request = new Request($vars, $this->stream); // Countable $this->assertEquals(2, count($request)); @@ -54,9 +55,10 @@ class RequestTest extends \PHPUnit_Framework_TestCase { 'get' => array('name' => 'John Q. Public', 'nickname' => 'Joey'), 'post' => array('name' => 'Jane Doe', 'nickname' => 'Janey'), 'urlParams' => array('user' => 'jw', 'name' => 'Johnny Weissmüller'), + 'method' => 'GET' ); - $request = new Request($vars); + $request = new Request($vars, $this->stream); $this->assertEquals(3, count($request)); $this->assertEquals('Janey', $request->{'nickname'}); @@ -70,9 +72,10 @@ class RequestTest extends \PHPUnit_Framework_TestCase { public function testImmutableArrayAccess() { $vars = array( 'get' => array('name' => 'John Q. Public', 'nickname' => 'Joey'), + 'method' => 'GET' ); - $request = new Request($vars); + $request = new Request($vars, $this->stream); $request['nickname'] = 'Janey'; } @@ -82,9 +85,10 @@ class RequestTest extends \PHPUnit_Framework_TestCase { public function testImmutableMagicAccess() { $vars = array( 'get' => array('name' => 'John Q. Public', 'nickname' => 'Joey'), + 'method' => 'GET' ); - $request = new Request($vars); + $request = new Request($vars, $this->stream); $request->{'nickname'} = 'Janey'; } @@ -97,7 +101,7 @@ class RequestTest extends \PHPUnit_Framework_TestCase { 'method' => 'GET', ); - $request = new Request($vars); + $request = new Request($vars, $this->stream); $result = $request->post; } @@ -107,7 +111,7 @@ class RequestTest extends \PHPUnit_Framework_TestCase { 'method' => 'GET', ); - $request = new Request($vars); + $request = new Request($vars, $this->stream); $this->assertEquals('GET', $request->method); $result = $request->get; $this->assertEquals('John Q. Public', $result['name']); @@ -119,10 +123,10 @@ class RequestTest extends \PHPUnit_Framework_TestCase { $data = '{"name": "John Q. Public", "nickname": "Joey"}'; $vars = array( 'method' => 'POST', - 'server' => array('CONTENT_TYPE' => 'application/json; utf-8'), + 'server' => array('CONTENT_TYPE' => 'application/json; utf-8') ); - $request = new Request($vars); + $request = new Request($vars, $this->stream); $this->assertEquals('POST', $request->method); $result = $request->post; $this->assertEquals('John Q. Public', $result['name']); @@ -140,7 +144,7 @@ class RequestTest extends \PHPUnit_Framework_TestCase { 'server' => array('CONTENT_TYPE' => 'application/x-www-form-urlencoded'), ); - $request = new Request($vars); + $request = new Request($vars, $this->stream); $this->assertEquals('PATCH', $request->method); $result = $request->patch; @@ -159,7 +163,7 @@ class RequestTest extends \PHPUnit_Framework_TestCase { 'server' => array('CONTENT_TYPE' => 'application/json; utf-8'), ); - $request = new Request($vars); + $request = new Request($vars, $this->stream); $this->assertEquals('PUT', $request->method); $result = $request->put; @@ -174,7 +178,7 @@ class RequestTest extends \PHPUnit_Framework_TestCase { 'server' => array('CONTENT_TYPE' => 'application/json; utf-8'), ); - $request = new Request($vars); + $request = new Request($vars, $this->stream); $this->assertEquals('PATCH', $request->method); $result = $request->patch; @@ -193,7 +197,7 @@ class RequestTest extends \PHPUnit_Framework_TestCase { 'server' => array('CONTENT_TYPE' => 'image/png'), ); - $request = new Request($vars); + $request = new Request($vars, $this->stream); $this->assertEquals('PUT', $request->method); $resource = $request->put; $contents = stream_get_contents($resource); diff --git a/tests/lib/appframework/middleware/MiddlewareDispatcherTest.php b/tests/lib/appframework/middleware/MiddlewareDispatcherTest.php index f16b14150c3..935f97d2a6f 100644 --- a/tests/lib/appframework/middleware/MiddlewareDispatcherTest.php +++ b/tests/lib/appframework/middleware/MiddlewareDispatcherTest.php @@ -132,7 +132,7 @@ class MiddlewareDispatcherTest extends \PHPUnit_Framework_TestCase { private function getControllerMock(){ return $this->getMock('OCP\AppFramework\Controller', array('method'), - array($this->getAPIMock(), new Request())); + array($this->getAPIMock(), new Request(array('method' => 'GET')))); } -- cgit v1.2.3 From b04d95b1160673dbaa80ce214f22e931e8c93178 Mon Sep 17 00:00:00 2001 From: Lukas Reschke Date: Sun, 13 Apr 2014 12:48:16 +0200 Subject: Remove uneeded usages of nosniff --- lib/private/json.php | 2 -- lib/public/appframework/http/jsonresponse.php | 1 - tests/lib/appframework/http/JSONResponseTest.php | 7 ------- 3 files changed, 10 deletions(-) (limited to 'tests') diff --git a/lib/private/json.php b/lib/private/json.php index 4ccdb490a6c..34f81c3b8cf 100644 --- a/lib/private/json.php +++ b/lib/private/json.php @@ -119,8 +119,6 @@ class OC_JSON{ * Encode and print $data in json format */ public static function encodedPrint($data, $setContentType=true) { - // Disable mimesniffing, don't move this to setContentTypeHeader! - header( 'X-Content-Type-Options: nosniff' ); if($setContentType) { self::setContentTypeHeader(); } diff --git a/lib/public/appframework/http/jsonresponse.php b/lib/public/appframework/http/jsonresponse.php index 6628c4514d9..6d029b7464a 100644 --- a/lib/public/appframework/http/jsonresponse.php +++ b/lib/public/appframework/http/jsonresponse.php @@ -49,7 +49,6 @@ class JSONResponse extends Response { public function __construct($data=array(), $statusCode=Http::STATUS_OK) { $this->data = $data; $this->setStatus($statusCode); - $this->addHeader('X-Content-Type-Options', 'nosniff'); $this->addHeader('Content-type', 'application/json; charset=utf-8'); } diff --git a/tests/lib/appframework/http/JSONResponseTest.php b/tests/lib/appframework/http/JSONResponseTest.php index b9b7c7d6382..fbaae1b9227 100644 --- a/tests/lib/appframework/http/JSONResponseTest.php +++ b/tests/lib/appframework/http/JSONResponseTest.php @@ -79,13 +79,6 @@ class JSONResponseTest extends \PHPUnit_Framework_TestCase { $this->assertEquals($expected, $this->json->render()); } - - public function testShouldHaveXContentHeaderByDefault() { - $headers = $this->json->getHeaders(); - $this->assertEquals('nosniff', $headers['X-Content-Type-Options']); - } - - public function testConstructorAllowsToSetData() { $data = array('hi'); $code = 300; -- cgit v1.2.3 From 51e47319ef2ab37d458dc96ba33a26bb851102be Mon Sep 17 00:00:00 2001 From: Thomas Tanghus Date: Mon, 14 Apr 2014 17:17:50 +0200 Subject: White-list known secure mime types. Refs. #8184 --- lib/private/connector/sabre/file.php | 6 +- lib/private/files/type/detection.php | 40 ++++++- lib/private/helper.php | 10 ++ lib/private/mimetypes.list.php | 210 +++++++++++++++++------------------ tests/lib/helper.php | 12 ++ 5 files changed, 166 insertions(+), 112 deletions(-) (limited to 'tests') diff --git a/lib/private/connector/sabre/file.php b/lib/private/connector/sabre/file.php index ef6caaf22a7..750d646a8f5 100644 --- a/lib/private/connector/sabre/file.php +++ b/lib/private/connector/sabre/file.php @@ -205,10 +205,12 @@ class OC_Connector_Sabre_File extends OC_Connector_Sabre_Node implements Sabre_D */ public function getContentType() { if (isset($this->fileinfo_cache['mimetype'])) { - return $this->fileinfo_cache['mimetype']; + $mimeType = $this->fileinfo_cache['mimetype']; + } else { + $mimeType = \OC\Files\Filesystem::getMimeType($this->path); } - return \OC\Files\Filesystem::getMimeType($this->path); + return \OC_Helper::getSecureMimeType($mimeType); } diff --git a/lib/private/files/type/detection.php b/lib/private/files/type/detection.php index 11e439032ce..8ee53917814 100644 --- a/lib/private/files/type/detection.php +++ b/lib/private/files/type/detection.php @@ -17,24 +17,40 @@ namespace OC\Files\Type; */ class Detection { protected $mimetypes = array(); + protected $secureMimeTypes = array(); /** - * add an extension -> mimetype mapping + * Add an extension -> mimetype mapping + * + * $mimetype is the assumed correct mime type + * The optional $secureMimeType is an alternative to send to send + * to avoid potential XSS. * * @param string $extension * @param string $mimetype + * @param string|null $secureMimeType */ - public function registerType($extension, $mimetype) { - $this->mimetypes[$extension] = $mimetype; + public function registerType($extension, $mimetype, $secureMimeType = null) { + $this->mimetypes[$extension] = array($mimetype, $secureMimeType); + $this->secureMimeTypes[$mimetype] = $secureMimeType ?: $mimetype; } /** - * add an array of extension -> mimetype mappings + * Add an array of extension -> mimetype mappings + * + * The mimetype value is in itself an array where the first index is + * the assumed correct mimetype and the second is either a secure alternative + * or null if the correct is considered secure. * * @param array $types */ public function registerTypeArray($types) { $this->mimetypes = array_merge($this->mimetypes, $types); + + // Update the alternative mimetypes to avoid having to look them up each time. + foreach ($this->mimetypes as $mimeType) { + $this->secureMimeTypes[$mimeType[0]] = $mimeType[1] ?: $mimeType[0]; + } } /** @@ -48,7 +64,9 @@ class Detection { //try to guess the type by the file extension $extension = strtolower(strrchr(basename($path), ".")); $extension = substr($extension, 1); //remove leading . - return (isset($this->mimetypes[$extension])) ? $this->mimetypes[$extension] : 'application/octet-stream'; + return (isset($this->mimetypes[$extension]) && isset($this->mimetypes[$extension][0])) + ? $this->mimetypes[$extension][0] + : 'application/octet-stream'; } else { return 'application/octet-stream'; } @@ -123,4 +141,16 @@ class Detection { return $mime; } } + + /** + * Get a secure mimetype that won't expose potential XSS. + * + * @param string $mimeType + * @return string + */ + public function getSecureMimeType($mimeType) { + return isset($this->secureMimeTypes[$mimeType]) + ? $this->secureMimeTypes[$mimeType] + : 'application/octet-stream'; + } } diff --git a/lib/private/helper.php b/lib/private/helper.php index da3d3cd1c6e..d5214823de9 100644 --- a/lib/private/helper.php +++ b/lib/private/helper.php @@ -430,6 +430,16 @@ class OC_Helper { return self::getMimetypeDetector()->detect($path); } + /** + * Get a secure mimetype that won't expose potential XSS. + * + * @param string $mimeType + * @return string + */ + static function getSecureMimeType($mimeType) { + return self::getMimetypeDetector()->getSecureMimeType($mimeType); + } + /** * get the mimetype form a data string * diff --git a/lib/private/mimetypes.list.php b/lib/private/mimetypes.list.php index 91bcf584267..cdfd2ec0fdd 100644 --- a/lib/private/mimetypes.list.php +++ b/lib/private/mimetypes.list.php @@ -24,109 +24,109 @@ * Array mapping file extensions to mimetypes (in alphabetical order). */ return array( - '7z' => 'application/x-7z-compressed', - 'accdb' => 'application/msaccess', - 'ai' => 'application/illustrator', - 'avi' => 'video/x-msvideo', - 'bash' => 'text/x-shellscript', - 'blend' => 'application/x-blender', - 'bin' => 'application/x-bin', - 'bmp' => 'image/bmp', - 'cb7' => 'application/x-cbr', - 'cba' => 'application/x-cbr', - 'cbr' => 'application/x-cbr', - 'cbt' => 'application/x-cbr', - 'cbtc' => 'application/x-cbr', - 'cbz' => 'application/x-cbr', - 'cc' => 'text/x-c', - 'cdr' => 'application/coreldraw', - 'cpp' => 'text/x-c++src', - 'css' => 'text/css', - 'csv' => 'text/csv', - 'cvbdl' => 'application/x-cbr', - 'c' => 'text/x-c', - 'c++' => 'text/x-c++src', - 'deb' => 'application/x-deb', - 'doc' => 'application/msword', - 'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', - 'dot' => 'application/msword', - 'dotx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.template', - 'dv' => 'video/dv', - 'eot' => 'application/vnd.ms-fontobject', - 'epub' => 'application/epub+zip', - 'exe' => 'application/x-ms-dos-executable', - 'flac' => 'audio/flac', - 'gif' => 'image/gif', - 'gz' => 'application/x-gzip', - 'gzip' => 'application/x-gzip', - 'html' => 'text/html', - 'htm' => 'text/html', - 'ical' => 'text/calendar', - 'ics' => 'text/calendar', - 'impress' => 'text/impress', - 'jpeg' => 'image/jpeg', - 'jpg' => 'image/jpeg', - 'js' => 'application/javascript', - 'json' => 'application/json', - 'keynote' => 'application/x-iwork-keynote-sffkey', - 'kra' => 'application/x-krita', - 'm2t' => 'video/mp2t', - 'm4v' => 'video/mp4', - 'markdown' => 'text/markdown', - 'mdown' => 'text/markdown', - 'md' => 'text/markdown', - 'mdb' => 'application/msaccess', - 'mdwn' => 'text/markdown', - 'mkv' => 'video/x-matroska', - 'mobi' => 'application/x-mobipocket-ebook', - 'mov' => 'video/quicktime', - 'mp3' => 'audio/mpeg', - 'mp4' => 'video/mp4', - 'mpeg' => 'video/mpeg', - 'mpg' => 'video/mpeg', - 'msi' => 'application/x-msi', - 'numbers' => 'application/x-iwork-numbers-sffnumbers', - 'odg' => 'application/vnd.oasis.opendocument.graphics', - 'odp' => 'application/vnd.oasis.opendocument.presentation', - 'ods' => 'application/vnd.oasis.opendocument.spreadsheet', - 'odt' => 'application/vnd.oasis.opendocument.text', - 'oga' => 'audio/ogg', - 'ogg' => 'audio/ogg', - 'ogv' => 'video/ogg', - 'otf' => 'font/opentype', - 'pages' => 'application/x-iwork-pages-sffpages', - 'pdf' => 'application/pdf', - 'php' => 'application/x-php', - 'pl' => 'application/x-perl', - 'png' => 'image/png', - 'ppt' => 'application/mspowerpoint', - 'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation', - 'psd' => 'application/x-photoshop', - 'py' => 'text/x-python', - 'rar' => 'application/x-rar-compressed', - 'reveal' => 'text/reveal', - 'sgf' => 'application/sgf', - 'sh-lib' => 'text/x-shellscript', - 'sh' => 'text/x-shellscript', - 'svg' => 'image/svg+xml', - 'swf' => 'application/x-shockwave-flash', - 'tar' => 'application/x-tar', - 'tar.gz' => 'application/x-compressed', - 'tex' => 'application/x-tex', - 'tgz' => 'application/x-compressed', - 'tiff' => 'image/tiff', - 'tif' => 'image/tiff', - 'ttf' => 'application/x-font-ttf', - 'txt' => 'text/plain', - 'vcard' => 'text/vcard', - 'vcf' => 'text/vcard', - 'wav' => 'audio/wav', - 'webm' => 'video/webm', - 'woff' => 'application/font-woff', - 'wmv' => 'video/x-ms-asf', - 'xcf' => 'application/x-gimp', - 'xls' => 'application/msexcel', - 'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', - 'xml' => 'application/xml', - 'zip' => 'application/zip', + '7z' => array('application/x-7z-compressed', null), + 'accdb' => array('application/msaccess', null), + 'ai' => array('application/illustrator', null), + 'avi' => array('video/x-msvideo', null), + 'bash' => array('text/x-shellscript', null), + 'blend' => array('application/x-blender', null), + 'bin' => array('application/x-bin', null), + 'bmp' => array('image/bmp', null), + 'cb7' => array('application/x-cbr', null), + 'cba' => array('application/x-cbr', null), + 'cbr' => array('application/x-cbr', null), + 'cbt' => array('application/x-cbr', null), + 'cbtc' => array('application/x-cbr', null), + 'cbz' => array('application/x-cbr', null), + 'cc' => array('text/x-c', null), + 'cdr' => array('application/coreldraw', null), + 'cpp' => array('text/x-c++src', null), + 'css' => array('text/css', null), + 'csv' => array('text/csv', null), + 'cvbdl' => array('application/x-cbr', null), + 'c' => array('text/x-c', null), + 'c++' => array('text/x-c++src', null), + 'deb' => array('application/x-deb', null), + 'doc' => array('application/msword', null), + 'docx' => array('application/vnd.openxmlformats-officedocument.wordprocessingml.document', null), + 'dot' => array('application/msword', null), + 'dotx' => array('application/vnd.openxmlformats-officedocument.wordprocessingml.template', null), + 'dv' => array('video/dv', null), + 'eot' => array('application/vnd.ms-fontobject', null), + 'epub' => array('application/epub+zip', null), + 'exe' => array('application/x-ms-dos-executable', null), + 'flac' => array('audio/flac', null), + 'gif' => array('image/gif', null), + 'gz' => array('application/x-gzip', null), + 'gzip' => array('application/x-gzip', null), + 'html' => array('text/html', 'text/plain'), + 'htm' => array('text/html', 'text/plain'), + 'ical' => array('text/calendar', null), + 'ics' => array('text/calendar', null), + 'impress' => array('text/impress', null), + 'jpeg' => array('image/jpeg', null), + 'jpg' => array('image/jpeg', null), + 'js' => array('application/javascript', 'text/plain'), + 'json' => array('application/json', 'text/plain'), + 'keynote' => array('application/x-iwork-keynote-sffkey', null), + 'kra' => array('application/x-krita', null), + 'm2t' => array('video/mp2t', null), + 'm4v' => array('video/mp4', null), + 'markdown' => array('text/markdown', null), + 'mdown' => array('text/markdown', null), + 'md' => array('text/markdown', null), + 'mdb' => array('application/msaccess', null), + 'mdwn' => array('text/markdown', null), + 'mkv' => array('video/x-matroska', null), + 'mobi' => array('application/x-mobipocket-ebook', null), + 'mov' => array('video/quicktime', null), + 'mp3' => array('audio/mpeg', null), + 'mp4' => array('video/mp4', null), + 'mpeg' => array('video/mpeg', null), + 'mpg' => array('video/mpeg', null), + 'msi' => array('application/x-msi', null), + 'numbers' => array('application/x-iwork-numbers-sffnumbers', null), + 'odg' => array('application/vnd.oasis.opendocument.graphics', null), + 'odp' => array('application/vnd.oasis.opendocument.presentation', null), + 'ods' => array('application/vnd.oasis.opendocument.spreadsheet', null), + 'odt' => array('application/vnd.oasis.opendocument.text', null), + 'oga' => array('audio/ogg', null), + 'ogg' => array('audio/ogg', null), + 'ogv' => array('video/ogg', null), + 'otf' => array('font/opentype', null), + 'pages' => array('application/x-iwork-pages-sffpages', null), + 'pdf' => array('application/pdf', null), + 'php' => array('application/x-php', null), + 'pl' => array('application/x-perl', null), + 'png' => array('image/png', null), + 'ppt' => array('application/mspowerpoint', null), + 'pptx' => array('application/vnd.openxmlformats-officedocument.presentationml.presentation', null), + 'psd' => array('application/x-photoshop', null), + 'py' => array('text/x-python', null), + 'rar' => array('application/x-rar-compressed', null), + 'reveal' => array('text/reveal', null), + 'sgf' => array('application/sgf', null), + 'sh-lib' => array('text/x-shellscript', null), + 'sh' => array('text/x-shellscript', null), + 'svg' => array('image/svg+xml', 'text/plain'), + 'swf' => array('application/x-shockwave-flash', 'application/octet-stream'), + 'tar' => array('application/x-tar', null), + 'tar.gz' => array('application/x-compressed', null), + 'tex' => array('application/x-tex', null), + 'tgz' => array('application/x-compressed', null), + 'tiff' => array('image/tiff', null), + 'tif' => array('image/tiff', null), + 'ttf' => array('application/x-font-ttf', null), + 'txt' => array('text/plain', null), + 'vcard' => array('text/vcard', null), + 'vcf' => array('text/vcard', null), + 'wav' => array('audio/wav', null), + 'webm' => array('video/webm', null), + 'woff' => array('application/font-woff', null), + 'wmv' => array('video/x-ms-asf', null), + 'xcf' => array('application/x-gimp', null), + 'xls' => array('application/msexcel', null), + 'xlsx' => array('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', null), + 'xml' => array('application/xml', 'text/plain'), + 'zip' => array('application/zip', null), ); diff --git a/tests/lib/helper.php b/tests/lib/helper.php index 0943e6bc1b9..5d319e40f02 100644 --- a/tests/lib/helper.php +++ b/tests/lib/helper.php @@ -71,6 +71,18 @@ class Test_Helper extends PHPUnit_Framework_TestCase { $this->assertEquals($result, $expected); } + function testGetSecureMimeType() { + $dir=OC::$SERVERROOT.'/tests/data'; + + $result = OC_Helper::getSecureMimeType('image/svg+xml'); + $expected = 'text/plain'; + $this->assertEquals($result, $expected); + + $result = OC_Helper::getSecureMimeType('image/png'); + $expected = 'image/png'; + $this->assertEquals($result, $expected); + } + function testGetFileNameMimeType() { $this->assertEquals('text/plain', OC_Helper::getFileNameMimeType('foo.txt')); $this->assertEquals('image/png', OC_Helper::getFileNameMimeType('foo.png')); -- cgit v1.2.3 From 450de0091abe137110d57005280ff56fa2914b92 Mon Sep 17 00:00:00 2001 From: Arthur Schiwon Date: Tue, 15 Apr 2014 17:53:57 +0200 Subject: adjust tests accordingly --- tests/lib/group/group.php | 2 +- tests/lib/group/manager.php | 2 +- tests/lib/user/manager.php | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) (limited to 'tests') diff --git a/tests/lib/group/group.php b/tests/lib/group/group.php index 147532f9947..990f8ecc1d5 100644 --- a/tests/lib/group/group.php +++ b/tests/lib/group/group.php @@ -287,7 +287,7 @@ class Group extends \PHPUnit_Framework_TestCase { ->will($this->returnValue(array('user2'))); $backend2->expects($this->once()) ->method('usersInGroup') - ->with('group1', 'user', 1, 0) + ->with('group1', 'user', 2, 1) ->will($this->returnValue(array('user1'))); $users = $group->searchUsers('user', 2, 1); diff --git a/tests/lib/group/manager.php b/tests/lib/group/manager.php index 90f0e1b35e2..a03997c58eb 100644 --- a/tests/lib/group/manager.php +++ b/tests/lib/group/manager.php @@ -254,7 +254,7 @@ class Manager extends \PHPUnit_Framework_TestCase { $backend2 = $this->getMock('\OC_Group_Database'); $backend2->expects($this->once()) ->method('getGroups') - ->with('1', 1, 0) + ->with('1', 2, 1) ->will($this->returnValue(array('group12'))); $backend2->expects($this->any()) ->method('groupExists') diff --git a/tests/lib/user/manager.php b/tests/lib/user/manager.php index ad1ac9e12f2..8ca0f94c6fa 100644 --- a/tests/lib/user/manager.php +++ b/tests/lib/user/manager.php @@ -210,7 +210,7 @@ class Manager extends \PHPUnit_Framework_TestCase { $backend2 = $this->getMock('\OC_User_Dummy'); $backend2->expects($this->once()) ->method('getUsers') - ->with($this->equalTo('fo'), $this->equalTo(1), $this->equalTo(0)) + ->with($this->equalTo('fo'), $this->equalTo(3), $this->equalTo(1)) ->will($this->returnValue(array('foo3'))); $manager = new \OC\User\Manager(); -- cgit v1.2.3 From dd36d4b8941fe2bcd74b146cda26be620cbe7a5e Mon Sep 17 00:00:00 2001 From: Thomas Tanghus Date: Wed, 16 Apr 2014 14:32:08 +0200 Subject: Add tests for linkTo, linkToPublic, linkToRemote, linkToRemoteBase --- tests/lib/helper.php | 175 +++++++++++++++++++++++++++++++++++++++++++++ tests/lib/urlgenerator.php | 48 +++++++++++++ 2 files changed, 223 insertions(+) (limited to 'tests') diff --git a/tests/lib/helper.php b/tests/lib/helper.php index 0943e6bc1b9..70371583bda 100644 --- a/tests/lib/helper.php +++ b/tests/lib/helper.php @@ -245,4 +245,179 @@ class Test_Helper extends PHPUnit_Framework_TestCase { array(3670, true, \OC::$SERVERROOT . '/tests/data/testimage.png', \OC::$SERVERROOT . '/tests/data/testimage-copy.png'), ); } + + // Url generator methods + + /** + * @small + * @brief test absolute URL construction + * @dataProvider provideDocRootURLs + */ + function testMakeAbsoluteURLDocRoot($url, $expectedResult) { + \OC::$WEBROOT = ''; + $result = \OC_Helper::makeURLAbsolute($url); + + $this->assertEquals($expectedResult, $result); + } + + /** + * @small + * @brief test absolute URL construction + * @dataProvider provideSubDirURLs + */ + function testMakeAbsoluteURLSubDir($url, $expectedResult) { + \OC::$WEBROOT = '/owncloud'; + $result = \OC_Helper::makeURLAbsolute($url); + + $this->assertEquals($expectedResult, $result); + } + + public function provideDocRootURLs() { + return array( + array('index.php', 'http://localhost/index.php'), + array('/index.php', 'http://localhost/index.php'), + array('/apps/index.php', 'http://localhost/apps/index.php'), + array('apps/index.php', 'http://localhost/apps/index.php'), + ); + } + + public function provideSubDirURLs() { + return array( + array('index.php', 'http://localhost/owncloud/index.php'), + array('/index.php', 'http://localhost/owncloud/index.php'), + array('/apps/index.php', 'http://localhost/owncloud/apps/index.php'), + array('apps/index.php', 'http://localhost/owncloud/apps/index.php'), + ); + } + + /** + * @small + * @brief test linkTo URL construction + * @dataProvider provideDocRootAppUrlParts + */ + public function testLinkToDocRoot($app, $file, $args, $expectedResult) { + \OC::$WEBROOT = ''; + $result = \OC_Helper::linkTo($app, $file, $args); + + $this->assertEquals($expectedResult, $result); + } + + /** + * @small + * @brief test linkTo URL construction in sub directory + * @dataProvider provideSubDirAppUrlParts + */ + public function testLinkToSubDir($app, $file, $args, $expectedResult) { + \OC::$WEBROOT = '/owncloud'; + $result = \OC_Helper::linkTo($app, $file, $args); + + $this->assertEquals($expectedResult, $result); + } + + public function provideDocRootAppUrlParts() { + return array( + array('files', 'index.php', array(), '/index.php/apps/files'), + array('files', 'index.php', array('trut' => 'trat', 'dut' => 'dat'), '/index.php/apps/files?trut=trat&dut=dat'), + array('', 'index.php', array('trut' => 'trat', 'dut' => 'dat'), '/index.php?trut=trat&dut=dat'), + ); + } + + public function provideSubDirAppUrlParts() { + return array( + array('files', 'index.php', array(), '/owncloud/index.php/apps/files'), + array('files', 'index.php', array('trut' => 'trat', 'dut' => 'dat'), '/owncloud/index.php/apps/files?trut=trat&dut=dat'), + array('', 'index.php', array('trut' => 'trat', 'dut' => 'dat'), '/owncloud/index.php?trut=trat&dut=dat'), + ); + } + + /** + * @small + * @brief test linkToAbsolute URL construction + * @dataProvider provideDocRootAppAbsoluteUrlParts + */ + public function testLinkToAbsoluteDocRoot($app, $file, $args, $expectedResult) { + \OC::$WEBROOT = ''; + $result = \OC_Helper::linkToAbsolute($app, $file, $args); + + $this->assertEquals($expectedResult, $result); + } + + /** + * @small + * @brief test linkToAbsolute URL construction in sub directory + * @dataProvider provideSubDirAppAbsoluteUrlParts + */ + public function testLinkToAbsoluteSubDir($app, $file, $args, $expectedResult) { + \OC::$WEBROOT = '/owncloud'; + $result = \OC_Helper::linkToAbsolute($app, $file, $args); + + $this->assertEquals($expectedResult, $result); + } + + public function provideDocRootAppAbsoluteUrlParts() { + return array( + array('files', 'index.php', array(), 'http://localhost/index.php/apps/files'), + array('files', 'index.php', array('trut' => 'trat', 'dut' => 'dat'), 'http://localhost/index.php/apps/files?trut=trat&dut=dat'), + array('', 'index.php', array('trut' => 'trat', 'dut' => 'dat'), 'http://localhost/index.php?trut=trat&dut=dat'), + ); + } + + public function provideSubDirAppAbsoluteUrlParts() { + return array( + array('files', 'index.php', array(), 'http://localhost/owncloud/index.php/apps/files'), + array('files', 'index.php', array('trut' => 'trat', 'dut' => 'dat'), 'http://localhost/owncloud/index.php/apps/files?trut=trat&dut=dat'), + array('', 'index.php', array('trut' => 'trat', 'dut' => 'dat'), 'http://localhost/owncloud/index.php?trut=trat&dut=dat'), + ); + } + + /** + * @small + * @brief test linkToRemoteBase URL construction + */ + public function testLinkToRemoteBase() { + \OC::$WEBROOT = ''; + $result = \OC_Helper::linkToRemoteBase('webdav'); + $this->assertEquals('/remote.php/webdav', $result); + + \OC::$WEBROOT = '/owncloud'; + $result = \OC_Helper::linkToRemoteBase('webdav'); + $this->assertEquals('/owncloud/remote.php/webdav', $result); + } + + /** + * @small + * @brief test linkToRemote URL construction + */ + public function testLinkToRemote() { + \OC::$WEBROOT = ''; + $result = \OC_Helper::linkToRemote('webdav'); + $this->assertEquals('http://localhost/remote.php/webdav/', $result); + $result = \OC_Helper::linkToRemote('webdav', false); + $this->assertEquals('http://localhost/remote.php/webdav', $result); + + \OC::$WEBROOT = '/owncloud'; + $result = \OC_Helper::linkToRemote('webdav'); + $this->assertEquals('http://localhost/owncloud/remote.php/webdav/', $result); + $result = \OC_Helper::linkToRemote('webdav', false); + $this->assertEquals('http://localhost/owncloud/remote.php/webdav', $result); + } + + /** + * @small + * @brief test linkToPublic URL construction + */ + public function testLinkToPublic() { + \OC::$WEBROOT = ''; + $result = \OC_Helper::linkToPublic('files'); + $this->assertEquals('http://localhost/public.php?service=files', $result); + $result = \OC_Helper::linkToPublic('files', false); + $this->assertEquals('http://localhost/public.php?service=files', $result); + + \OC::$WEBROOT = '/owncloud'; + $result = \OC_Helper::linkToPublic('files'); + $this->assertEquals('http://localhost/owncloud/public.php?service=files', $result); + $result = \OC_Helper::linkToPublic('files', false); + $this->assertEquals('http://localhost/owncloud/public.php?service=files', $result); + } + } diff --git a/tests/lib/urlgenerator.php b/tests/lib/urlgenerator.php index 8e605d88f32..12d7ae0bf52 100644 --- a/tests/lib/urlgenerator.php +++ b/tests/lib/urlgenerator.php @@ -8,6 +8,54 @@ class Test_Urlgenerator extends PHPUnit_Framework_TestCase { + /** + * @var \OCP\IConfig | \PHPUnit_Framework_MockObject_MockObject $config + */ + protected $config; + + /** + * @small + * @brief test linkTo URL construction + * @dataProvider provideDocRootAppUrlParts + */ + public function testLinkToDocRoot($app, $file, $args, $expectedResult) { + \OC::$WEBROOT = ''; + $config = $this->getMock('\OCP\IConfig'); + $urlGenerator = new \OC\URLGenerator($config); + $result = $urlGenerator->linkTo($app, $file, $args); + + $this->assertEquals($expectedResult, $result); + } + + /** + * @small + * @brief test linkTo URL construction in sub directory + * @dataProvider provideSubDirAppUrlParts + */ + public function testLinkToSubDir($app, $file, $args, $expectedResult) { + \OC::$WEBROOT = '/owncloud'; + $config = $this->getMock('\OCP\IConfig'); + $urlGenerator = new \OC\URLGenerator($config); + $result = $urlGenerator->linkTo($app, $file, $args); + + $this->assertEquals($expectedResult, $result); + } + + public function provideDocRootAppUrlParts() { + return array( + array('files', 'index.php', array(), '/index.php/apps/files'), + array('files', 'index.php', array('trut' => 'trat', 'dut' => 'dat'), '/index.php/apps/files?trut=trat&dut=dat'), + array('', 'index.php', array('trut' => 'trat', 'dut' => 'dat'), '/index.php?trut=trat&dut=dat'), + ); + } + + public function provideSubDirAppUrlParts() { + return array( + array('files', 'index.php', array(), '/owncloud/index.php/apps/files'), + array('files', 'index.php', array('trut' => 'trat', 'dut' => 'dat'), '/owncloud/index.php/apps/files?trut=trat&dut=dat'), + array('', 'index.php', array('trut' => 'trat', 'dut' => 'dat'), '/owncloud/index.php?trut=trat&dut=dat'), + ); + } /** * @small -- cgit v1.2.3 From df9d9ac958da9e61e069bd7c1be5350551bdb36b Mon Sep 17 00:00:00 2001 From: Thomas Tanghus Date: Wed, 16 Apr 2014 14:34:13 +0200 Subject: Remove unused var --- tests/lib/urlgenerator.php | 5 ----- 1 file changed, 5 deletions(-) (limited to 'tests') diff --git a/tests/lib/urlgenerator.php b/tests/lib/urlgenerator.php index 12d7ae0bf52..65c7fb56943 100644 --- a/tests/lib/urlgenerator.php +++ b/tests/lib/urlgenerator.php @@ -8,11 +8,6 @@ class Test_Urlgenerator extends PHPUnit_Framework_TestCase { - /** - * @var \OCP\IConfig | \PHPUnit_Framework_MockObject_MockObject $config - */ - protected $config; - /** * @small * @brief test linkTo URL construction -- cgit v1.2.3 From 7e447f4f42de8dc0cf9a1f92c61a71dfda8f8dcd Mon Sep 17 00:00:00 2001 From: Bernhard Posselt Date: Sun, 20 Apr 2014 16:12:46 +0200 Subject: make download and redirectresponse public --- lib/private/appframework/http/downloadresponse.php | 50 ------------------- lib/private/appframework/http/redirectresponse.php | 57 ---------------------- .../middleware/security/securitymiddleware.php | 2 +- lib/public/appframework/http/downloadresponse.php | 50 +++++++++++++++++++ lib/public/appframework/http/redirectresponse.php | 57 ++++++++++++++++++++++ .../lib/appframework/http/DownloadResponseTest.php | 2 +- .../lib/appframework/http/RedirectResponseTest.php | 2 +- .../middleware/security/SecurityMiddlewareTest.php | 2 +- 8 files changed, 111 insertions(+), 111 deletions(-) delete mode 100644 lib/private/appframework/http/downloadresponse.php delete mode 100644 lib/private/appframework/http/redirectresponse.php create mode 100644 lib/public/appframework/http/downloadresponse.php create mode 100644 lib/public/appframework/http/redirectresponse.php (limited to 'tests') diff --git a/lib/private/appframework/http/downloadresponse.php b/lib/private/appframework/http/downloadresponse.php deleted file mode 100644 index 67b9542dba6..00000000000 --- a/lib/private/appframework/http/downloadresponse.php +++ /dev/null @@ -1,50 +0,0 @@ -. - * - */ - - -namespace OC\AppFramework\Http; - - -/** - * Prompts the user to download the a file - */ -class DownloadResponse extends \OCP\AppFramework\Http\Response { - - private $filename; - private $contentType; - - /** - * Creates a response that prompts the user to download the file - * @param string $filename the name that the downloaded file should have - * @param string $contentType the mimetype that the downloaded file should have - */ - public function __construct($filename, $contentType) { - $this->filename = $filename; - $this->contentType = $contentType; - - $this->addHeader('Content-Disposition', 'attachment; filename="' . $filename . '"'); - $this->addHeader('Content-Type', $contentType); - } - - -} diff --git a/lib/private/appframework/http/redirectresponse.php b/lib/private/appframework/http/redirectresponse.php deleted file mode 100644 index 05353349065..00000000000 --- a/lib/private/appframework/http/redirectresponse.php +++ /dev/null @@ -1,57 +0,0 @@ -. - * - */ - - -namespace OC\AppFramework\Http; - -use OCP\AppFramework\Http\Response; -use OCP\AppFramework\Http; - - -/** - * Redirects to a different URL - */ -class RedirectResponse extends Response { - - private $redirectURL; - - /** - * Creates a response that redirects to a url - * @param string $redirectURL the url to redirect to - */ - public function __construct($redirectURL) { - $this->redirectURL = $redirectURL; - $this->setStatus(Http::STATUS_TEMPORARY_REDIRECT); - $this->addHeader('Location', $redirectURL); - } - - - /** - * @return string the url to redirect - */ - public function getRedirectURL() { - return $this->redirectURL; - } - - -} diff --git a/lib/private/appframework/middleware/security/securitymiddleware.php b/lib/private/appframework/middleware/security/securitymiddleware.php index bb02d565fa4..0f160d224ad 100644 --- a/lib/private/appframework/middleware/security/securitymiddleware.php +++ b/lib/private/appframework/middleware/security/securitymiddleware.php @@ -25,8 +25,8 @@ namespace OC\AppFramework\Middleware\Security; use OC\AppFramework\Http; -use OC\AppFramework\Http\RedirectResponse; use OC\AppFramework\Utility\MethodAnnotationReader; +use OCP\AppFramework\Http\RedirectResponse; use OCP\AppFramework\Middleware; use OCP\AppFramework\Http\Response; use OCP\AppFramework\Http\JSONResponse; diff --git a/lib/public/appframework/http/downloadresponse.php b/lib/public/appframework/http/downloadresponse.php new file mode 100644 index 00000000000..d3c2818e828 --- /dev/null +++ b/lib/public/appframework/http/downloadresponse.php @@ -0,0 +1,50 @@ +. + * + */ + + +namespace OCP\AppFramework\Http; + + +/** + * Prompts the user to download the a file + */ +class DownloadResponse extends \OCP\AppFramework\Http\Response { + + private $filename; + private $contentType; + + /** + * Creates a response that prompts the user to download the file + * @param string $filename the name that the downloaded file should have + * @param string $contentType the mimetype that the downloaded file should have + */ + public function __construct($filename, $contentType) { + $this->filename = $filename; + $this->contentType = $contentType; + + $this->addHeader('Content-Disposition', 'attachment; filename="' . $filename . '"'); + $this->addHeader('Content-Type', $contentType); + } + + +} diff --git a/lib/public/appframework/http/redirectresponse.php b/lib/public/appframework/http/redirectresponse.php new file mode 100644 index 00000000000..416e1533635 --- /dev/null +++ b/lib/public/appframework/http/redirectresponse.php @@ -0,0 +1,57 @@ +. + * + */ + + +namespace OCP\AppFramework\Http; + +use OCP\AppFramework\Http\Response; +use OCP\AppFramework\Http; + + +/** + * Redirects to a different URL + */ +class RedirectResponse extends Response { + + private $redirectURL; + + /** + * Creates a response that redirects to a url + * @param string $redirectURL the url to redirect to + */ + public function __construct($redirectURL) { + $this->redirectURL = $redirectURL; + $this->setStatus(Http::STATUS_TEMPORARY_REDIRECT); + $this->addHeader('Location', $redirectURL); + } + + + /** + * @return string the url to redirect + */ + public function getRedirectURL() { + return $this->redirectURL; + } + + +} diff --git a/tests/lib/appframework/http/DownloadResponseTest.php b/tests/lib/appframework/http/DownloadResponseTest.php index 64fe7992b6a..b305c63ad4d 100644 --- a/tests/lib/appframework/http/DownloadResponseTest.php +++ b/tests/lib/appframework/http/DownloadResponseTest.php @@ -22,7 +22,7 @@ */ -namespace OC\AppFramework\Http; +namespace OCP\AppFramework\Http; //require_once(__DIR__ . "/../classloader.php"); diff --git a/tests/lib/appframework/http/RedirectResponseTest.php b/tests/lib/appframework/http/RedirectResponseTest.php index f82d0c3a675..f62b420f4ee 100644 --- a/tests/lib/appframework/http/RedirectResponseTest.php +++ b/tests/lib/appframework/http/RedirectResponseTest.php @@ -22,7 +22,7 @@ */ -namespace OC\AppFramework\Http; +namespace OCP\AppFramework\Http; use OCP\AppFramework\Http; diff --git a/tests/lib/appframework/middleware/security/SecurityMiddlewareTest.php b/tests/lib/appframework/middleware/security/SecurityMiddlewareTest.php index 63c48a62829..19e8a68c388 100644 --- a/tests/lib/appframework/middleware/security/SecurityMiddlewareTest.php +++ b/tests/lib/appframework/middleware/security/SecurityMiddlewareTest.php @@ -26,7 +26,7 @@ namespace OC\AppFramework\Middleware\Security; use OC\AppFramework\Http; use OC\AppFramework\Http\Request; -use OC\AppFramework\Http\RedirectResponse; +use OCP\AppFramework\Http\RedirectResponse; use OCP\AppFramework\Http\JSONResponse; -- cgit v1.2.3 From f07180639c5af149447bc573db58ee130575369e Mon Sep 17 00:00:00 2001 From: Lukas Reschke Date: Tue, 22 Apr 2014 20:09:55 +0200 Subject: Add unit tests for arrays and " OC_Util::sanitizeHTML() also supports array but we actually had no unit test for it. Additionally this commit introduces a test for escaping " into " --- tests/lib/template.php | 18 ++++++++++++++---- tests/lib/util.php | 28 +++++++++++++++++++++++----- 2 files changed, 37 insertions(+), 9 deletions(-) (limited to 'tests') diff --git a/tests/lib/template.php b/tests/lib/template.php index b4f1a4c4053..b3d0975b793 100644 --- a/tests/lib/template.php +++ b/tests/lib/template.php @@ -28,13 +28,23 @@ class Test_TemplateFunctions extends PHPUnit_Framework_TestCase { } public function testP() { - // FIXME: do we need more testcases? - $htmlString = ""; + $badString = ''; + ob_start(); + p($badString); + $result = ob_get_clean(); + $this->assertEquals('<img onload="alert(1)" />', $result); + + $badString = ""; ob_start(); - p($htmlString); + p($badString); $result = ob_get_clean(); + $this->assertEquals('<script>alert('Hacked!');</script>', $result); - $this->assertEquals("<script>alert('xss');</script>", $result); + $goodString = 'This is a good string without HTML.'; + ob_start(); + p($goodString); + $result = ob_get_clean(); + $this->assertEquals('This is a good string without HTML.', $result); } public function testPNormalString() { diff --git a/tests/lib/util.php b/tests/lib/util.php index ee336aa1118..20f2f7bbeab 100644 --- a/tests/lib/util.php +++ b/tests/lib/util.php @@ -43,15 +43,33 @@ class Test_Util extends PHPUnit_Framework_TestCase { } function testSanitizeHTML() { + $badArray = array( + 'While it is unusual to pass an array', + 'this function actually supports it.', + 'And therefore there needs to be a for it!' + ); + $goodArray = array( + 'While it is unusual to pass an array', + 'this function actually <blink>supports</blink> it.', + 'And therefore there needs to be a <script>alert("Unit"+'test')</script> for it!' + ); + $result = OC_Util::sanitizeHTML($badArray); + $this->assertEquals($goodArray, $result); + + $badString = ''; + $result = OC_Util::sanitizeHTML($badString); + $this->assertEquals('<img onload="alert(1)" />', $result); + $badString = ""; $result = OC_Util::sanitizeHTML($badString); - $this->assertEquals("<script>alert('Hacked!');</script>", $result); + $this->assertEquals('<script>alert('Hacked!');</script>', $result); - $goodString = "This is an harmless string."; + $goodString = 'This is a good string without HTML.'; $result = OC_Util::sanitizeHTML($goodString); - $this->assertEquals("This is an harmless string.", $result); - } - + $this->assertEquals('This is a good string without HTML.', $result); +} + + function testEncodePath(){ $component = '/§#@test%&^ä/-child'; $result = OC_Util::encodePath($component); -- cgit v1.2.3 From 589c74e1761f7450d7aabb0f5cf8391f89c3847d Mon Sep 17 00:00:00 2001 From: Lukas Reschke Date: Tue, 22 Apr 2014 20:10:46 +0200 Subject: Fix indentation --- tests/lib/util.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'tests') diff --git a/tests/lib/util.php b/tests/lib/util.php index 20f2f7bbeab..4c0ed920388 100644 --- a/tests/lib/util.php +++ b/tests/lib/util.php @@ -67,7 +67,7 @@ class Test_Util extends PHPUnit_Framework_TestCase { $goodString = 'This is a good string without HTML.'; $result = OC_Util::sanitizeHTML($goodString); $this->assertEquals('This is a good string without HTML.', $result); -} + } function testEncodePath(){ -- cgit v1.2.3 From 9d3b639ce68b1b60845b7bf605f16292fd0a6019 Mon Sep 17 00:00:00 2001 From: Lukas Reschke Date: Tue, 22 Apr 2014 20:11:34 +0200 Subject: Remove uneeded newline --- tests/lib/util.php | 1 - 1 file changed, 1 deletion(-) (limited to 'tests') diff --git a/tests/lib/util.php b/tests/lib/util.php index 4c0ed920388..c4780cc5f48 100644 --- a/tests/lib/util.php +++ b/tests/lib/util.php @@ -69,7 +69,6 @@ class Test_Util extends PHPUnit_Framework_TestCase { $this->assertEquals('This is a good string without HTML.', $result); } - function testEncodePath(){ $component = '/§#@test%&^ä/-child'; $result = OC_Util::encodePath($component); -- cgit v1.2.3 From 6650be99136bbeecc39a28cbe9c22de0c5cf08ac Mon Sep 17 00:00:00 2001 From: Bjoern Schiessle Date: Wed, 23 Apr 2014 12:50:24 +0200 Subject: add setting to set default expire date --- lib/private/share/helper.php | 49 ++++++++++++++++++++++++++++++++++++++++ lib/private/share/share.php | 15 ++++++++++-- settings/admin.php | 4 ++++ settings/css/settings.css | 1 + settings/templates/admin.php | 19 +++++++++++++++- tests/lib/share/helper.php | 54 ++++++++++++++++++++++++++++++++++++++++++++ 6 files changed, 139 insertions(+), 3 deletions(-) create mode 100644 tests/lib/share/helper.php (limited to 'tests') diff --git a/lib/private/share/helper.php b/lib/private/share/helper.php index fde55667281..515ec85909a 100644 --- a/lib/private/share/helper.php +++ b/lib/private/share/helper.php @@ -199,4 +199,53 @@ class Helper extends \OC\Share\Constants { $query->execute(); } } + + /** + * @brief get default expire settings defined by the admin + * @return array contains 'defaultExpireDateSet', 'enforceExpireDate', 'expireAfterDays' + */ + public static function getDefaultExpireSetting() { + + $defaultExpireSettings = array('defaultExpireDateSet' => false); + + // get default expire settings + $defaultExpireDate = \OC_Appconfig::getValue('core', 'shareapi_default_expire_date', 'no'); + if ($defaultExpireDate === 'yes') { + $enforceExpireDate = \OC_Appconfig::getValue('core', 'shareapi_enforce_expire_date', 'no'); + $defaultExpireSettings['defaultExpireDateSet'] = true; + $defaultExpireSettings['expireAfterDays'] = (int)\OC_Appconfig::getValue('core', 'shareapi_expire_after_n_days', '7'); + $defaultExpireSettings['enforceExpireDate'] = $enforceExpireDate === 'yes' ? true : false; + } + + return $defaultExpireSettings; + } + + /** + * @brief calculate expire date + * @param array $defaultExpireSettings contains 'defaultExpireDateSet', 'enforceExpireDate', 'expireAfterDays' + * @param int $creationTime timestamp when the share was created + * @param int $userExpireDate expire timestamp set by the user + * @return mixed integer timestamp or False + */ + public static function calculateExpireDate($defaultExpireSettings, $creationTime, $userExpireDate = null) { + + $expires = false; + + if (isset($defaultExpireSettings['defaultExpireDateSet']) && $defaultExpireSettings['defaultExpireDateSet']) { + $expires = $creationTime + $defaultExpireSettings['expireAfterDays'] * 86400; + } + + + if (isset($userExpireDate)) { + // if the admin decided to enforce the default expire date then we only take + // the user defined expire date of it is before the default expire date + if ($expires && isset($defaultExpireSettings['enforceExpireDate']) && $defaultExpireSettings['enforceExpireDate']) { + $expires = ($userExpireDate < $expires) ? $userExpireDate : $expires; + } else { + $expires = $userExpireDate; + } + } + + return $expires; + } } diff --git a/lib/private/share/share.php b/lib/private/share/share.php index fe756b5ae7f..a18c54af8a3 100644 --- a/lib/private/share/share.php +++ b/lib/private/share/share.php @@ -844,9 +844,20 @@ class Share extends \OC\Share\Constants { * @return bool True if item was expired, false otherwise. */ protected static function expireItem(array $item) { + + // get default expire settings + $defaultSettings = Helper::getDefaultExpireSetting(); + // calculate expire date if (!empty($item['expiration'])) { - $now = new \DateTime(); - $expires = new \DateTime($item['expiration']); + $userDefinedExpire = new \DateTime($item['expiration']); + $userDefinedExpireTimestamp = $userDefinedExpire->getTimestamp(); + } else { + $userDefinedExpireTimestamp = null; + } + $expires = Helper::calculateExpireDate($defaultSettings, $item['stime'], $userDefinedExpireTimestamp); + + if (is_int($expires)) { + $now = time(); if ($now > $expires) { self::unshareItem($item); return true; diff --git a/settings/admin.php b/settings/admin.php index bce18b7cf6a..49dde59ce2a 100755 --- a/settings/admin.php +++ b/settings/admin.php @@ -45,6 +45,10 @@ $tmpl->assign('backgroundjobs_mode', OC_Appconfig::getValue('core', 'backgroundj $tmpl->assign('cron_log', OC_Config::getValue('cron_log', true)); $tmpl->assign('lastcron', OC_Appconfig::getValue('core', 'lastcron', false)); $tmpl->assign('shareAPIEnabled', OC_Appconfig::getValue('core', 'shareapi_enabled', 'yes')); +$tmpl->assign('shareDefaultExpireDateSet', OC_Appconfig::getValue('core', 'shareapi_default_expire_date', 'no')); +$tmpl->assign('shareExpireAfterNDays', OC_Appconfig::getValue('core', 'shareapi_expire_after_n_days', '7')); +$tmpl->assign('shareEnforceExpireDate', OC_Appconfig::getValue('core', 'shareapi_enforce_expire_date', 'no')); + // Check if connected using HTTPS if (OC_Request::serverProtocol() === 'https') { diff --git a/settings/css/settings.css b/settings/css/settings.css index a7680aad948..5d8f9a7541c 100644 --- a/settings/css/settings.css +++ b/settings/css/settings.css @@ -132,6 +132,7 @@ table.grid td.date{ span.securitywarning {color:#C33; font-weight:bold; } span.connectionwarning {color:#933; font-weight:bold; } table.shareAPI td { padding-bottom: 0.8em; } +table.shareAPI input#shareapi_expire_after_n_days {width: 25px;} #mail_settings p label:first-child { display: inline-block; diff --git a/settings/templates/admin.php b/settings/templates/admin.php index 07b5ee7860e..8eb1beb9566 100644 --- a/settings/templates/admin.php +++ b/settings/templates/admin.php @@ -254,6 +254,23 @@ if (!$_['internetconnectionworking']) { t('Allow users to send mail notification for shared files')); ?> + + + > + /> +
+ t( 'Expire after ' )); ?> + ' /> + t( 'days' )); ?> + /> +
+ t('Expire shares by default after N days')); ?> + + + @@ -296,7 +313,7 @@ if (!$_['internetconnectionworking']) {

t('This is used for sending out notifications.')); ?>

- +